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
server.py
import socket from PIL import Image import io import os def string_to_byte(hex_input): return bytearray.fromhex(hex_input) def
(): host = "" port = 5001 my_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) my_socket.bind((host, port)) my_socket.listen(1) conn, address = my_socket.accept() decoded_data_buffer = "" decoded_data = "" print("Connection from: " + str(address)) # Keep on reading untill the program finishes while True: img = None # Read until a colon is found. This signals the image size segment while not ":" in decoded_data: data = conn.recv(1) decoded_data = data.decode() decoded_data_buffer += decoded_data print("Config received: ") print(decoded_data_buffer) expected_size_str = decoded_data_buffer.replace("config", "").replace(",", "").replace(":", "") expected_size = int(expected_size_str) print("Expected hex bytes: ", expected_size) decoded_data_buffer = "" hexBytesCount = 0 # Read the amount of hex chars indicated before while True: missing_bytes = expected_size - hexBytesCount data = conn.recv(missing_bytes if missing_bytes < 1024 else 1024) if not data: break print("Read ", hexBytesCount, " out of ", expected_size) last_read_size = len(data) hexBytesCount += last_read_size decoded_data = data.decode() decoded_data_buffer += decoded_data if hexBytesCount >= expected_size: break # We are done! print("Read hex bytes: ", len(decoded_data_buffer)) image_bytes = string_to_byte(decoded_data_buffer) print("Read bytes: ", len(image_bytes)) img = Image.open(io.BytesIO(bytes(image_bytes))) imageName = "test" + ".jpg" img.save(imageName) print("Saved image: ", imageName) decoded_data_buffer = "" decoded_data = "" steering, throttle = (0,0) # TODO: Plug your designed algorithm here. os.remove('test.jpg') reply = '{ "steering" : "%f", "throttle" : "%f" }' % (steering, throttle) reply = reply + '\n' print(reply) reply = reply.encode() conn.send(reply ) conn.close() if __name__ == '__main__': print("Server Start") serve()
serve
identifier_name
back-live-detail.component.ts
import { Component, OnInit } from '@angular/core'; import { ActivatedRoute, Router, ActivatedRouteSnapshot, RouterState, RouterStateSnapshot } from '@angular/router'; import { BackLiveDetailService } from "./service/back-live-detail.service"; import { ProfileService } from "../../../service/profile.service"; declare var $: any; declare var prismplayer: any; declare var layer: any; declare var prismplayer: any; declare var QRCode: any; declare var Clipboard: any; @Component({ selector: 'app-back-live-detail', templateUrl: './back-live-detail.component.html', styleUrls: ['./back-live-detail.component.scss'], providers: [ BackLiveDetailService, ProfileService ] }) export class BackLiveDetailComponent implements OnInit { public player; public cover; public source; public anchorDetail; public isFollow: boolean; public profile; public shareUrl;// 分享地址 public shareCode;// 分享二维码插件实例化 constructor( public router: Router, public activatedRoute: ActivatedRoute, public backLiveDetailService: BackLiveDetailService, public profileService: ProfileService, ) { } ngOnInit() { this.profile = JSON.parse(window.localStorage.getItem("profile")); this.activatedRoute.params .subscribe( data => { // console.log(data); this.backLiveDetailService.getBackLiveDetail(data.id) .subscribe( datas => { console.log(datas); this.anchorDetail = datas.d; this.cover = this.anchorDetail.avatar; this.source = this.anchorDetail.live; this.media(this.source, this.cover); this.anchorDetail.followed ? this.isFollow = true : this.isFollow = false; }, errors => console.log(errors) ) }, error => console.log(error) ) this.shareUrl = 'http://api.clive.1booker.com/share/MTAwODVfMTAwNDg='; } media(source, cover) { // console.log(source, cover); this.player = new prismplayer({ id: "J_prismPlayer", // 容器id source: source, autoplay: true, //自动播放:否 width: "100%", // 播放器宽度 height: "inherit", // 播放器高度 preload: true, cover: cover }); this.player.on("pause", function () { console.log("播放器暂停啦!"); }); } doFollow(status, id) { console.log(status, id); if (status == false) { this.backLiveD
; this.shareCode = new QRCode(e.target.parentNode.querySelector('.sharedPanel .qrcode .code'), { text: this.shareUrl, width: 140, height: 140, }); } hideShare(e) { e.target.parentNode.querySelector('.sharedPanel').style.display = 'none'; e.target.parentNode.querySelector('.sharedPanel .qrcode .code').innerHTML = ''; this.shareCode.clear(); } clipboradShare(e) {// 复制分享地址 let clipboard = new Clipboard('.copy'); clipboard.on('success', (e) => { layer.msg('復製成功'); }); clipboard.on('error', (e) => { layer.msg('複製失敗'); }); } shareToQQ(url, pics, event) {//手动分享到qq let source = event.target.ownerDocument.querySelector("head meta[name='site']").getAttribute('content'); let title = event.target.ownerDocument.querySelector("head title").innerHTML; let desc = event.target.ownerDocument.querySelector("head meta[name='description']").getAttribute('content'); pics = this.cover; window.location.href = "http://connect.qq.com/widget/shareqq/index.html?url=" + url + "&title=" + title + "&source=" + source + "&desc=" + desc + "&pics=" + pics; } shareToXinlang(url, pics, event) {//手动分享到微博 let source = event.target.ownerDocument.querySelector("head meta[name='site']").getAttribute('content'); let title = event.target.ownerDocument.querySelector("head title").innerHTML; let desc = event.target.ownerDocument.querySelector("head meta[name='description']").getAttribute('content'); pics = this.cover; window.location.href = "http://service.weibo.com/share/share.php?url=" + url + "&title=" + title + "&pic=" + pics + "&appkey=" + ''; } }
etailService.addFollow(id) .subscribe( data => { console.log(data) layer.msg("關注成功"); this.isFollow = true; }, error => console.log(error) ) } else { this.backLiveDetailService.cancelFollow(id) .subscribe( data => { console.log(data); layer.msg("已取消關注"); this.isFollow = false; }, error => console.log(error) ) } } showShare(e) { e.target.parentNode.querySelector('.sharedPanel').style.display = 'block'
identifier_body
back-live-detail.component.ts
import { Component, OnInit } from '@angular/core'; import { ActivatedRoute, Router, ActivatedRouteSnapshot, RouterState, RouterStateSnapshot } from '@angular/router'; import { BackLiveDetailService } from "./service/back-live-detail.service"; import { ProfileService } from "../../../service/profile.service"; declare var $: any; declare var prismplayer: any; declare var layer: any; declare var prismplayer: any; declare var QRCode: any; declare var Clipboard: any; @Component({ selector: 'app-back-live-detail', templateUrl: './back-live-detail.component.html', styleUrls: ['./back-live-detail.component.scss'], providers: [ BackLiveDetailService, ProfileService ] }) export class BackLiveDetailComponent implements OnInit { public player; public cover; public source; public anchorDetail; public isFollow: boolean; public profile; public shareUrl;// 分享地址 public shareCode;// 分享二维码插件实例化 constructor( public router: Router, public activatedRoute: ActivatedRoute, public backLiveDetailService: BackLiveDetailService, public profileService: ProfileService, ) { } ngOnInit() { this.profile = JSON.parse(window.localStorage.getItem("profile")); this.activatedRoute.params .subscribe( data => { // console.log(data); this.backLiveDetailService.getBackLiveDetail(data.id) .subscribe( datas => { console.log(datas); this.anchorDetail = datas.d; this.cover = this.anchorDetail.avatar; this.source = this.anchorDetail.live; this.media(this.source, this.cover); this.anchorDetail.followed ? this.isFollow = true : this.isFollow = false; }, errors => console.log(errors) ) }, error => console.log(error) ) this.shareUrl = 'http://api.clive.1booker.com/share/MTAwODVfMTAwNDg='; } media(source, cover) { // console.log(source, cover); this.player = new prismplayer({ id: "J_prismPlayer", // 容器id source: source, autoplay: true, //自动播放:否 width: "100%", // 播放器宽度 height: "inherit", // 播放器高度 preload: true, cover: cover }); this.player.on("pause", function () { console.log("播放器暂停啦!"); }); } doFollow(status, id) { console.log(status, id); if (status == false) { this.backLiveDetailService.addFollow(id) .subscribe( d
data => { console.log(data); layer.msg("已取消關注"); this.isFollow = false; }, error => console.log(error) ) } } showShare(e) { e.target.parentNode.querySelector('.sharedPanel').style.display = 'block'; this.shareCode = new QRCode(e.target.parentNode.querySelector('.sharedPanel .qrcode .code'), { text: this.shareUrl, width: 140, height: 140, }); } hideShare(e) { e.target.parentNode.querySelector('.sharedPanel').style.display = 'none'; e.target.parentNode.querySelector('.sharedPanel .qrcode .code').innerHTML = ''; this.shareCode.clear(); } clipboradShare(e) {// 复制分享地址 let clipboard = new Clipboard('.copy'); clipboard.on('success', (e) => { layer.msg('復製成功'); }); clipboard.on('error', (e) => { layer.msg('複製失敗'); }); } shareToQQ(url, pics, event) {//手动分享到qq let source = event.target.ownerDocument.querySelector("head meta[name='site']").getAttribute('content'); let title = event.target.ownerDocument.querySelector("head title").innerHTML; let desc = event.target.ownerDocument.querySelector("head meta[name='description']").getAttribute('content'); pics = this.cover; window.location.href = "http://connect.qq.com/widget/shareqq/index.html?url=" + url + "&title=" + title + "&source=" + source + "&desc=" + desc + "&pics=" + pics; } shareToXinlang(url, pics, event) {//手动分享到微博 let source = event.target.ownerDocument.querySelector("head meta[name='site']").getAttribute('content'); let title = event.target.ownerDocument.querySelector("head title").innerHTML; let desc = event.target.ownerDocument.querySelector("head meta[name='description']").getAttribute('content'); pics = this.cover; window.location.href = "http://service.weibo.com/share/share.php?url=" + url + "&title=" + title + "&pic=" + pics + "&appkey=" + ''; } }
ata => { console.log(data) layer.msg("關注成功"); this.isFollow = true; }, error => console.log(error) ) } else { this.backLiveDetailService.cancelFollow(id) .subscribe(
conditional_block
back-live-detail.component.ts
import { Component, OnInit } from '@angular/core'; import { ActivatedRoute, Router, ActivatedRouteSnapshot, RouterState, RouterStateSnapshot } from '@angular/router'; import { BackLiveDetailService } from "./service/back-live-detail.service"; import { ProfileService } from "../../../service/profile.service"; declare var $: any; declare var prismplayer: any; declare var layer: any; declare var prismplayer: any; declare var QRCode: any; declare var Clipboard: any; @Component({ selector: 'app-back-live-detail', templateUrl: './back-live-detail.component.html', styleUrls: ['./back-live-detail.component.scss'], providers: [ BackLiveDetailService, ProfileService ] }) export class BackLiveDetailComponent implements OnInit { public player; public cover; public source; public anchorDetail; public isFollow: boolean; public profile; public shareUrl;// 分享地址 public shareCode;// 分享二维码插件实例化 constructor( public router: Router, public activatedRoute: ActivatedRoute, public backLiveDetailService: BackLiveDetailService, public profileService: ProfileService, ) { } ngOnInit() { this.profile = JSON.parse(window.localStorage.getItem("profile")); this.activatedRoute.params .subscribe( data => { // console.log(data); this.backLiveDetailService.getBackLiveDetail(data.id) .subscribe( datas => { console.log(datas); this.anchorDetail = datas.d; this.cover = this.anchorDetail.avatar; this.source = this.anchorDetail.live; this.media(this.source, this.cover); this.anchorDetail.followed ? this.isFollow = true : this.isFollow = false; }, errors => console.log(errors) ) }, error => console.log(error) ) this.shareUrl = 'http://api.clive.1booker.com/share/MTAwODVfMTAwNDg='; } media(source, cover) { // console.log(source, cover); this.player = new prismplayer({ id: "J_prismPlayer", // 容器id source: source, autoplay: true, //自动播放:否 width: "100%", // 播放器宽度 height: "inherit", // 播放器高度 preload: true, cover: cover }); this.player.on("pause", function () { console.log("播放器暂停啦!"); }); } doFollow(status, id) { console.log(status, id); if (status == false) { this.backLiveDetailService.addFollow(id) .subscribe( data => { console.log(data) layer.msg("關注成功"); this.isFollow = true; }, error => console.log(error) ) } else { this.backLiveDetailService.cancelFollow(id) .subscribe( data => { console.log(data); layer.msg("已取消關注"); this.isFollow = false; }, error => console.log(error) ) } } showShare(e) { e.target.parentNode.querySelector('.sharedPanel').style.display = 'block'; this.shareCode = new QRCode(e.target.parentNode.querySelector('.sharedPanel .qrcode .code'), { text: this.shareUrl, width: 140, height: 140, }); }
} clipboradShare(e) {// 复制分享地址 let clipboard = new Clipboard('.copy'); clipboard.on('success', (e) => { layer.msg('復製成功'); }); clipboard.on('error', (e) => { layer.msg('複製失敗'); }); } shareToQQ(url, pics, event) {//手动分享到qq let source = event.target.ownerDocument.querySelector("head meta[name='site']").getAttribute('content'); let title = event.target.ownerDocument.querySelector("head title").innerHTML; let desc = event.target.ownerDocument.querySelector("head meta[name='description']").getAttribute('content'); pics = this.cover; window.location.href = "http://connect.qq.com/widget/shareqq/index.html?url=" + url + "&title=" + title + "&source=" + source + "&desc=" + desc + "&pics=" + pics; } shareToXinlang(url, pics, event) {//手动分享到微博 let source = event.target.ownerDocument.querySelector("head meta[name='site']").getAttribute('content'); let title = event.target.ownerDocument.querySelector("head title").innerHTML; let desc = event.target.ownerDocument.querySelector("head meta[name='description']").getAttribute('content'); pics = this.cover; window.location.href = "http://service.weibo.com/share/share.php?url=" + url + "&title=" + title + "&pic=" + pics + "&appkey=" + ''; } }
hideShare(e) { e.target.parentNode.querySelector('.sharedPanel').style.display = 'none'; e.target.parentNode.querySelector('.sharedPanel .qrcode .code').innerHTML = ''; this.shareCode.clear();
random_line_split
back-live-detail.component.ts
import { Component, OnInit } from '@angular/core'; import { ActivatedRoute, Router, ActivatedRouteSnapshot, RouterState, RouterStateSnapshot } from '@angular/router'; import { BackLiveDetailService } from "./service/back-live-detail.service"; import { ProfileService } from "../../../service/profile.service"; declare var $: any; declare var prismplayer: any; declare var layer: any; declare var prismplayer: any; declare var QRCode: any; declare var Clipboard: any; @Component({ selector: 'app-back-live-detail', templateUrl: './back-live-detail.component.html', styleUrls: ['./back-live-detail.component.scss'], providers: [ BackLiveDetailService, ProfileService ] }) export class BackLiveDetailComponent implements OnInit { public player; public cover; public source; public anchorDetail; public isFollow: boolean; public profile; public shareUrl;// 分享地址 public shareCode;// 分享二维码插件实例化 constructor( public router: Router, public activatedRoute: ActivatedRoute, public backLiveDetailService: BackLiveDetailService, public profileService: ProfileService, ) { } ngOnInit() { this.profile = JSON.parse(window.localStorage.getItem("profile")); this.activatedRoute.params .subscribe( data => { // console.log(data); this.backLiveDetailService.getBackLiveDetail(data.id) .subscribe( datas => { console.log(datas); this.anchorDetail = datas.d; this.cover = this.anchorDetail.avatar; this.source = this.anchorDetail.live; this.media(this.source, this.cover); this.anchorDetail.followed ? this.isFollow = true : this.isFollow = false; }, errors => console.log(errors) ) }, error => console.log(error) ) this.shareUrl = 'http://api.clive.1booker.com/share/MTAwODVfMTAwNDg='; } media(source, cover) { /
sole.log(source, cover); this.player = new prismplayer({ id: "J_prismPlayer", // 容器id source: source, autoplay: true, //自动播放:否 width: "100%", // 播放器宽度 height: "inherit", // 播放器高度 preload: true, cover: cover }); this.player.on("pause", function () { console.log("播放器暂停啦!"); }); } doFollow(status, id) { console.log(status, id); if (status == false) { this.backLiveDetailService.addFollow(id) .subscribe( data => { console.log(data) layer.msg("關注成功"); this.isFollow = true; }, error => console.log(error) ) } else { this.backLiveDetailService.cancelFollow(id) .subscribe( data => { console.log(data); layer.msg("已取消關注"); this.isFollow = false; }, error => console.log(error) ) } } showShare(e) { e.target.parentNode.querySelector('.sharedPanel').style.display = 'block'; this.shareCode = new QRCode(e.target.parentNode.querySelector('.sharedPanel .qrcode .code'), { text: this.shareUrl, width: 140, height: 140, }); } hideShare(e) { e.target.parentNode.querySelector('.sharedPanel').style.display = 'none'; e.target.parentNode.querySelector('.sharedPanel .qrcode .code').innerHTML = ''; this.shareCode.clear(); } clipboradShare(e) {// 复制分享地址 let clipboard = new Clipboard('.copy'); clipboard.on('success', (e) => { layer.msg('復製成功'); }); clipboard.on('error', (e) => { layer.msg('複製失敗'); }); } shareToQQ(url, pics, event) {//手动分享到qq let source = event.target.ownerDocument.querySelector("head meta[name='site']").getAttribute('content'); let title = event.target.ownerDocument.querySelector("head title").innerHTML; let desc = event.target.ownerDocument.querySelector("head meta[name='description']").getAttribute('content'); pics = this.cover; window.location.href = "http://connect.qq.com/widget/shareqq/index.html?url=" + url + "&title=" + title + "&source=" + source + "&desc=" + desc + "&pics=" + pics; } shareToXinlang(url, pics, event) {//手动分享到微博 let source = event.target.ownerDocument.querySelector("head meta[name='site']").getAttribute('content'); let title = event.target.ownerDocument.querySelector("head title").innerHTML; let desc = event.target.ownerDocument.querySelector("head meta[name='description']").getAttribute('content'); pics = this.cover; window.location.href = "http://service.weibo.com/share/share.php?url=" + url + "&title=" + title + "&pic=" + pics + "&appkey=" + ''; } }
/ con
identifier_name
zsi_init.js
//initialize Settings. zsi.init({ baseURL : base_url ,errorUpdateURL : base_url + "common/errors_update" ,sqlConsoleName : "runsql" ,excludeAjaxWatch : ["checkDataExist","employe_search_json"] }); //check cookie and load user menus. var userInfo = readCookie("userinfo"); if(userInfo){ if(isLocalStorageSupport()) { userInfo = JSON.parse(localStorage.getItem("userinfo")); var menuInfo = localStorage.getItem("menuInfo"); if(menuInfo){ displayMenu( JSON.parse(menuInfo)); } }else{ loadMenu(); loadUserInfo(); } }else{ loadMenu(); loadUserInfo(); } function isLocalStorageSupport(){ if(typeof(Storage) !== "undefined") return true; else return false; } function loadMenu(){ $.getJSON(base_url + "menu_types/getdata_json",function(data){ if(isLocalStorageSupport()) { localStorage.setItem("menuInfo", JSON.stringify(data)); } displayMenu(data); }); } function loadUserInfo()
function displayMenu(data){ var nav = $("#navbar-main"); var m = '<ul class="nav navbar-nav">'; $.each(data,function(){ var mlength= this.subMenus.length; m += '<li class="dropdown">'; m += '<a data-toggle="dropdown" class="dropdown-toggle" href="#">' + this.name + ( mlength >0 ? '<span class="caret"></span>':'') + '</a>'; if(mlength>0){ m +='<ul class="dropdown-menu">'; $.each(this.subMenus,function(){ m +='<li><a href="' + base_url + this.url + '">' + this.name + '</a></li>'; }); m +='</ul>'; } m += '</>'; }); m +='<url>'; nav.append(m); }
{ $.getJSON(base_url + "users/getuserinfo",function(data){ createCookie("userinfo", "*",1); localStorage.setItem("userinfo", JSON.stringify(data)); userInfo = data; }); }
identifier_body
zsi_init.js
//initialize Settings. zsi.init({ baseURL : base_url ,errorUpdateURL : base_url + "common/errors_update" ,sqlConsoleName : "runsql" ,excludeAjaxWatch : ["checkDataExist","employe_search_json"] }); //check cookie and load user menus. var userInfo = readCookie("userinfo"); if(userInfo){ if(isLocalStorageSupport()) { userInfo = JSON.parse(localStorage.getItem("userinfo")); var menuInfo = localStorage.getItem("menuInfo"); if(menuInfo){ displayMenu( JSON.parse(menuInfo)); } }else{ loadMenu(); loadUserInfo(); } }else{ loadMenu(); loadUserInfo(); } function
(){ if(typeof(Storage) !== "undefined") return true; else return false; } function loadMenu(){ $.getJSON(base_url + "menu_types/getdata_json",function(data){ if(isLocalStorageSupport()) { localStorage.setItem("menuInfo", JSON.stringify(data)); } displayMenu(data); }); } function loadUserInfo(){ $.getJSON(base_url + "users/getuserinfo",function(data){ createCookie("userinfo", "*",1); localStorage.setItem("userinfo", JSON.stringify(data)); userInfo = data; }); } function displayMenu(data){ var nav = $("#navbar-main"); var m = '<ul class="nav navbar-nav">'; $.each(data,function(){ var mlength= this.subMenus.length; m += '<li class="dropdown">'; m += '<a data-toggle="dropdown" class="dropdown-toggle" href="#">' + this.name + ( mlength >0 ? '<span class="caret"></span>':'') + '</a>'; if(mlength>0){ m +='<ul class="dropdown-menu">'; $.each(this.subMenus,function(){ m +='<li><a href="' + base_url + this.url + '">' + this.name + '</a></li>'; }); m +='</ul>'; } m += '</>'; }); m +='<url>'; nav.append(m); }
isLocalStorageSupport
identifier_name
zsi_init.js
//initialize Settings. zsi.init({ baseURL : base_url ,errorUpdateURL : base_url + "common/errors_update" ,sqlConsoleName : "runsql" ,excludeAjaxWatch : ["checkDataExist","employe_search_json"] }); //check cookie and load user menus. var userInfo = readCookie("userinfo");
if(menuInfo){ displayMenu( JSON.parse(menuInfo)); } }else{ loadMenu(); loadUserInfo(); } }else{ loadMenu(); loadUserInfo(); } function isLocalStorageSupport(){ if(typeof(Storage) !== "undefined") return true; else return false; } function loadMenu(){ $.getJSON(base_url + "menu_types/getdata_json",function(data){ if(isLocalStorageSupport()) { localStorage.setItem("menuInfo", JSON.stringify(data)); } displayMenu(data); }); } function loadUserInfo(){ $.getJSON(base_url + "users/getuserinfo",function(data){ createCookie("userinfo", "*",1); localStorage.setItem("userinfo", JSON.stringify(data)); userInfo = data; }); } function displayMenu(data){ var nav = $("#navbar-main"); var m = '<ul class="nav navbar-nav">'; $.each(data,function(){ var mlength= this.subMenus.length; m += '<li class="dropdown">'; m += '<a data-toggle="dropdown" class="dropdown-toggle" href="#">' + this.name + ( mlength >0 ? '<span class="caret"></span>':'') + '</a>'; if(mlength>0){ m +='<ul class="dropdown-menu">'; $.each(this.subMenus,function(){ m +='<li><a href="' + base_url + this.url + '">' + this.name + '</a></li>'; }); m +='</ul>'; } m += '</>'; }); m +='<url>'; nav.append(m); }
if(userInfo){ if(isLocalStorageSupport()) { userInfo = JSON.parse(localStorage.getItem("userinfo")); var menuInfo = localStorage.getItem("menuInfo");
random_line_split
zsi_init.js
//initialize Settings. zsi.init({ baseURL : base_url ,errorUpdateURL : base_url + "common/errors_update" ,sqlConsoleName : "runsql" ,excludeAjaxWatch : ["checkDataExist","employe_search_json"] }); //check cookie and load user menus. var userInfo = readCookie("userinfo"); if(userInfo)
else{ loadMenu(); loadUserInfo(); } function isLocalStorageSupport(){ if(typeof(Storage) !== "undefined") return true; else return false; } function loadMenu(){ $.getJSON(base_url + "menu_types/getdata_json",function(data){ if(isLocalStorageSupport()) { localStorage.setItem("menuInfo", JSON.stringify(data)); } displayMenu(data); }); } function loadUserInfo(){ $.getJSON(base_url + "users/getuserinfo",function(data){ createCookie("userinfo", "*",1); localStorage.setItem("userinfo", JSON.stringify(data)); userInfo = data; }); } function displayMenu(data){ var nav = $("#navbar-main"); var m = '<ul class="nav navbar-nav">'; $.each(data,function(){ var mlength= this.subMenus.length; m += '<li class="dropdown">'; m += '<a data-toggle="dropdown" class="dropdown-toggle" href="#">' + this.name + ( mlength >0 ? '<span class="caret"></span>':'') + '</a>'; if(mlength>0){ m +='<ul class="dropdown-menu">'; $.each(this.subMenus,function(){ m +='<li><a href="' + base_url + this.url + '">' + this.name + '</a></li>'; }); m +='</ul>'; } m += '</>'; }); m +='<url>'; nav.append(m); }
{ if(isLocalStorageSupport()) { userInfo = JSON.parse(localStorage.getItem("userinfo")); var menuInfo = localStorage.getItem("menuInfo"); if(menuInfo){ displayMenu( JSON.parse(menuInfo)); } }else{ loadMenu(); loadUserInfo(); } }
conditional_block
collect_2.py
import threading import urllib2 import time, json import requests import os.path #"284330,150810,09,1109,52,071040,17,28432,7406" countrylist = ["brazil","canada","china","france","japan","india","mexico","russia","uk","us"] yrs = ["2011","2012","2013","2014","2015"] dataTable ={"284330":"gold","150810":"crude","09":"coffee","1109":"wheat","52":"cotton","071040":"corn","17":"sugar","28432":"silver","7406":"copper","271111":"natural gas"}; file_list = [] start = time.time() urls = ["http://comtrade.un.org/api/get?max=50000&type=C&freq=A&px=HS&ps=2015,2014,2013,2012,2011&r=76&p=all&rg=2&cc=284330,150810,09,1109,52,071040,17,28432,7406,271111&fmt=json", "http://comtrade.un.org/api/get?max=50000&type=C&freq=A&px=HS&ps=2015,2014,2013,2012,2011&r=124&p=all&rg=2&cc=284330,150810,09,1109,52,071040,17,28432,7406,271111&fmt=json", "http://comtrade.un.org/api/get?max=50000&type=C&freq=A&px=HS&ps=2015,2014,2013,2012,2011&r=156&p=all&rg=2&cc=284330,150810,09,1109,52,071040,17,28432,7406,271111&fmt=json", "http://comtrade.un.org/api/get?max=50000&type=C&freq=A&px=HS&ps=2015,2014,2013,2012,2011&r=251&p=all&rg=2&cc=284330,150810,09,1109,52,071040,17,28432,7406,271111&fmt=json", "http://comtrade.un.org/api/get?max=50000&type=C&freq=A&px=HS&ps=2015,2014,2013,2012,2011&r=392&p=all&rg=2&cc=284330,150810,09,1109,52,071040,17,28432,7406,271111&fmt=json", "http://comtrade.un.org/api/get?max=50000&type=C&freq=A&px=HS&ps=2015,2014,2013,2012,2011&r=699&p=all&rg=2&cc=284330,150810,09,1109,52,071040,17,28432,7406,271111&fmt=json", "http://comtrade.un.org/api/get?max=50000&type=C&freq=A&px=HS&ps=2015,2014,2013,2012,2011&r=484&p=all&rg=2&cc=284330,150810,09,1109,52,071040,17,28432,7406,271111&fmt=json", "http://comtrade.un.org/api/get?max=50000&type=C&freq=A&px=HS&ps=2015,2014,2013,2012,2011&r=643&p=all&rg=2&cc=284330,150810,09,1109,52,071040,17,28432,7406,271111&fmt=json", "http://comtrade.un.org/api/get?max=50000&type=C&freq=A&px=HS&ps=2015,2014,2013,2012,2011&r=826&p=all&rg=2&cc=284330,150810,09,1109,52,071040,17,28432,7406,271111&fmt=json", "http://comtrade.un.org/api/get?max=50000&type=C&freq=A&px=HS&ps=2015,2014,2013,2012,2011&r=834&p=all&rg=2&cc=284330,150810,09,1109,52,071040,17,28432,7406,271111&fmt=json"] def fetch_url(url, i): file_name = "file_"+countrylist[i]+".json" file_list.append(file_name) response = requests.get(url, verify=False) data = response.json() if not os.path.isfile("./"+file_name): with open(file_name, 'w') as outfile: json.dump(data["dataset"], outfile) print "'%s\' fetched in %ss" % (url, (time.time() - start)) # threads = [threading.Thread(target=fetch_url, args=(urls[i],i,)) for i in range(0,len(urls)) ] for thread in threads: thread.start() time.sleep(12) for thread in threads: thread.join() #final data identifier res_data = {} for k in range(0,len(countrylist)):
if data_json[j]['yr'] == 2011: a = (countrylist[k],"2011") elif data_json[j]['yr'] == 2012: a = (countrylist[k],"2012") elif data_json[j]['yr'] == 2013: a = (countrylist[k],"2013") elif data_json[j]['yr'] == 2014: a = (countrylist[k],"2014") elif data_json[j]['yr'] == 2015: a = (countrylist[k],"2015") # insrt the key a = "".join(a) if a not in res_data.keys(): res_data[a] = [] if data_json[j]["ptTitle"].lower() not in countrylist: continue b = {} b["country"] = data_json[j]["ptTitle"].lower() b["commodity"] = dataTable[str(data_json[j]["cmdCode"])] b["val"] = data_json[j]["TradeValue"] res_data[a].append(b) final_file_name = "exportData.json" if not os.path.isfile("./"+final_file_name): with open(final_file_name, 'w') as outfile: json.dump(res_data, outfile) #for i in range(0,len(file_list)): print "Elapsed Time: %s" % (time.time() - start)
with open(file_list[k],"r") as json_data: data_json = json.load(json_data) for j in range(0,len(data_json)):
random_line_split
collect_2.py
import threading import urllib2 import time, json import requests import os.path #"284330,150810,09,1109,52,071040,17,28432,7406" countrylist = ["brazil","canada","china","france","japan","india","mexico","russia","uk","us"] yrs = ["2011","2012","2013","2014","2015"] dataTable ={"284330":"gold","150810":"crude","09":"coffee","1109":"wheat","52":"cotton","071040":"corn","17":"sugar","28432":"silver","7406":"copper","271111":"natural gas"}; file_list = [] start = time.time() urls = ["http://comtrade.un.org/api/get?max=50000&type=C&freq=A&px=HS&ps=2015,2014,2013,2012,2011&r=76&p=all&rg=2&cc=284330,150810,09,1109,52,071040,17,28432,7406,271111&fmt=json", "http://comtrade.un.org/api/get?max=50000&type=C&freq=A&px=HS&ps=2015,2014,2013,2012,2011&r=124&p=all&rg=2&cc=284330,150810,09,1109,52,071040,17,28432,7406,271111&fmt=json", "http://comtrade.un.org/api/get?max=50000&type=C&freq=A&px=HS&ps=2015,2014,2013,2012,2011&r=156&p=all&rg=2&cc=284330,150810,09,1109,52,071040,17,28432,7406,271111&fmt=json", "http://comtrade.un.org/api/get?max=50000&type=C&freq=A&px=HS&ps=2015,2014,2013,2012,2011&r=251&p=all&rg=2&cc=284330,150810,09,1109,52,071040,17,28432,7406,271111&fmt=json", "http://comtrade.un.org/api/get?max=50000&type=C&freq=A&px=HS&ps=2015,2014,2013,2012,2011&r=392&p=all&rg=2&cc=284330,150810,09,1109,52,071040,17,28432,7406,271111&fmt=json", "http://comtrade.un.org/api/get?max=50000&type=C&freq=A&px=HS&ps=2015,2014,2013,2012,2011&r=699&p=all&rg=2&cc=284330,150810,09,1109,52,071040,17,28432,7406,271111&fmt=json", "http://comtrade.un.org/api/get?max=50000&type=C&freq=A&px=HS&ps=2015,2014,2013,2012,2011&r=484&p=all&rg=2&cc=284330,150810,09,1109,52,071040,17,28432,7406,271111&fmt=json", "http://comtrade.un.org/api/get?max=50000&type=C&freq=A&px=HS&ps=2015,2014,2013,2012,2011&r=643&p=all&rg=2&cc=284330,150810,09,1109,52,071040,17,28432,7406,271111&fmt=json", "http://comtrade.un.org/api/get?max=50000&type=C&freq=A&px=HS&ps=2015,2014,2013,2012,2011&r=826&p=all&rg=2&cc=284330,150810,09,1109,52,071040,17,28432,7406,271111&fmt=json", "http://comtrade.un.org/api/get?max=50000&type=C&freq=A&px=HS&ps=2015,2014,2013,2012,2011&r=834&p=all&rg=2&cc=284330,150810,09,1109,52,071040,17,28432,7406,271111&fmt=json"] def fetch_url(url, i):
# threads = [threading.Thread(target=fetch_url, args=(urls[i],i,)) for i in range(0,len(urls)) ] for thread in threads: thread.start() time.sleep(12) for thread in threads: thread.join() #final data identifier res_data = {} for k in range(0,len(countrylist)): with open(file_list[k],"r") as json_data: data_json = json.load(json_data) for j in range(0,len(data_json)): if data_json[j]['yr'] == 2011: a = (countrylist[k],"2011") elif data_json[j]['yr'] == 2012: a = (countrylist[k],"2012") elif data_json[j]['yr'] == 2013: a = (countrylist[k],"2013") elif data_json[j]['yr'] == 2014: a = (countrylist[k],"2014") elif data_json[j]['yr'] == 2015: a = (countrylist[k],"2015") # insrt the key a = "".join(a) if a not in res_data.keys(): res_data[a] = [] if data_json[j]["ptTitle"].lower() not in countrylist: continue b = {} b["country"] = data_json[j]["ptTitle"].lower() b["commodity"] = dataTable[str(data_json[j]["cmdCode"])] b["val"] = data_json[j]["TradeValue"] res_data[a].append(b) final_file_name = "exportData.json" if not os.path.isfile("./"+final_file_name): with open(final_file_name, 'w') as outfile: json.dump(res_data, outfile) #for i in range(0,len(file_list)): print "Elapsed Time: %s" % (time.time() - start)
file_name = "file_"+countrylist[i]+".json" file_list.append(file_name) response = requests.get(url, verify=False) data = response.json() if not os.path.isfile("./"+file_name): with open(file_name, 'w') as outfile: json.dump(data["dataset"], outfile) print "'%s\' fetched in %ss" % (url, (time.time() - start))
identifier_body
collect_2.py
import threading import urllib2 import time, json import requests import os.path #"284330,150810,09,1109,52,071040,17,28432,7406" countrylist = ["brazil","canada","china","france","japan","india","mexico","russia","uk","us"] yrs = ["2011","2012","2013","2014","2015"] dataTable ={"284330":"gold","150810":"crude","09":"coffee","1109":"wheat","52":"cotton","071040":"corn","17":"sugar","28432":"silver","7406":"copper","271111":"natural gas"}; file_list = [] start = time.time() urls = ["http://comtrade.un.org/api/get?max=50000&type=C&freq=A&px=HS&ps=2015,2014,2013,2012,2011&r=76&p=all&rg=2&cc=284330,150810,09,1109,52,071040,17,28432,7406,271111&fmt=json", "http://comtrade.un.org/api/get?max=50000&type=C&freq=A&px=HS&ps=2015,2014,2013,2012,2011&r=124&p=all&rg=2&cc=284330,150810,09,1109,52,071040,17,28432,7406,271111&fmt=json", "http://comtrade.un.org/api/get?max=50000&type=C&freq=A&px=HS&ps=2015,2014,2013,2012,2011&r=156&p=all&rg=2&cc=284330,150810,09,1109,52,071040,17,28432,7406,271111&fmt=json", "http://comtrade.un.org/api/get?max=50000&type=C&freq=A&px=HS&ps=2015,2014,2013,2012,2011&r=251&p=all&rg=2&cc=284330,150810,09,1109,52,071040,17,28432,7406,271111&fmt=json", "http://comtrade.un.org/api/get?max=50000&type=C&freq=A&px=HS&ps=2015,2014,2013,2012,2011&r=392&p=all&rg=2&cc=284330,150810,09,1109,52,071040,17,28432,7406,271111&fmt=json", "http://comtrade.un.org/api/get?max=50000&type=C&freq=A&px=HS&ps=2015,2014,2013,2012,2011&r=699&p=all&rg=2&cc=284330,150810,09,1109,52,071040,17,28432,7406,271111&fmt=json", "http://comtrade.un.org/api/get?max=50000&type=C&freq=A&px=HS&ps=2015,2014,2013,2012,2011&r=484&p=all&rg=2&cc=284330,150810,09,1109,52,071040,17,28432,7406,271111&fmt=json", "http://comtrade.un.org/api/get?max=50000&type=C&freq=A&px=HS&ps=2015,2014,2013,2012,2011&r=643&p=all&rg=2&cc=284330,150810,09,1109,52,071040,17,28432,7406,271111&fmt=json", "http://comtrade.un.org/api/get?max=50000&type=C&freq=A&px=HS&ps=2015,2014,2013,2012,2011&r=826&p=all&rg=2&cc=284330,150810,09,1109,52,071040,17,28432,7406,271111&fmt=json", "http://comtrade.un.org/api/get?max=50000&type=C&freq=A&px=HS&ps=2015,2014,2013,2012,2011&r=834&p=all&rg=2&cc=284330,150810,09,1109,52,071040,17,28432,7406,271111&fmt=json"] def
(url, i): file_name = "file_"+countrylist[i]+".json" file_list.append(file_name) response = requests.get(url, verify=False) data = response.json() if not os.path.isfile("./"+file_name): with open(file_name, 'w') as outfile: json.dump(data["dataset"], outfile) print "'%s\' fetched in %ss" % (url, (time.time() - start)) # threads = [threading.Thread(target=fetch_url, args=(urls[i],i,)) for i in range(0,len(urls)) ] for thread in threads: thread.start() time.sleep(12) for thread in threads: thread.join() #final data identifier res_data = {} for k in range(0,len(countrylist)): with open(file_list[k],"r") as json_data: data_json = json.load(json_data) for j in range(0,len(data_json)): if data_json[j]['yr'] == 2011: a = (countrylist[k],"2011") elif data_json[j]['yr'] == 2012: a = (countrylist[k],"2012") elif data_json[j]['yr'] == 2013: a = (countrylist[k],"2013") elif data_json[j]['yr'] == 2014: a = (countrylist[k],"2014") elif data_json[j]['yr'] == 2015: a = (countrylist[k],"2015") # insrt the key a = "".join(a) if a not in res_data.keys(): res_data[a] = [] if data_json[j]["ptTitle"].lower() not in countrylist: continue b = {} b["country"] = data_json[j]["ptTitle"].lower() b["commodity"] = dataTable[str(data_json[j]["cmdCode"])] b["val"] = data_json[j]["TradeValue"] res_data[a].append(b) final_file_name = "exportData.json" if not os.path.isfile("./"+final_file_name): with open(final_file_name, 'w') as outfile: json.dump(res_data, outfile) #for i in range(0,len(file_list)): print "Elapsed Time: %s" % (time.time() - start)
fetch_url
identifier_name
collect_2.py
import threading import urllib2 import time, json import requests import os.path #"284330,150810,09,1109,52,071040,17,28432,7406" countrylist = ["brazil","canada","china","france","japan","india","mexico","russia","uk","us"] yrs = ["2011","2012","2013","2014","2015"] dataTable ={"284330":"gold","150810":"crude","09":"coffee","1109":"wheat","52":"cotton","071040":"corn","17":"sugar","28432":"silver","7406":"copper","271111":"natural gas"}; file_list = [] start = time.time() urls = ["http://comtrade.un.org/api/get?max=50000&type=C&freq=A&px=HS&ps=2015,2014,2013,2012,2011&r=76&p=all&rg=2&cc=284330,150810,09,1109,52,071040,17,28432,7406,271111&fmt=json", "http://comtrade.un.org/api/get?max=50000&type=C&freq=A&px=HS&ps=2015,2014,2013,2012,2011&r=124&p=all&rg=2&cc=284330,150810,09,1109,52,071040,17,28432,7406,271111&fmt=json", "http://comtrade.un.org/api/get?max=50000&type=C&freq=A&px=HS&ps=2015,2014,2013,2012,2011&r=156&p=all&rg=2&cc=284330,150810,09,1109,52,071040,17,28432,7406,271111&fmt=json", "http://comtrade.un.org/api/get?max=50000&type=C&freq=A&px=HS&ps=2015,2014,2013,2012,2011&r=251&p=all&rg=2&cc=284330,150810,09,1109,52,071040,17,28432,7406,271111&fmt=json", "http://comtrade.un.org/api/get?max=50000&type=C&freq=A&px=HS&ps=2015,2014,2013,2012,2011&r=392&p=all&rg=2&cc=284330,150810,09,1109,52,071040,17,28432,7406,271111&fmt=json", "http://comtrade.un.org/api/get?max=50000&type=C&freq=A&px=HS&ps=2015,2014,2013,2012,2011&r=699&p=all&rg=2&cc=284330,150810,09,1109,52,071040,17,28432,7406,271111&fmt=json", "http://comtrade.un.org/api/get?max=50000&type=C&freq=A&px=HS&ps=2015,2014,2013,2012,2011&r=484&p=all&rg=2&cc=284330,150810,09,1109,52,071040,17,28432,7406,271111&fmt=json", "http://comtrade.un.org/api/get?max=50000&type=C&freq=A&px=HS&ps=2015,2014,2013,2012,2011&r=643&p=all&rg=2&cc=284330,150810,09,1109,52,071040,17,28432,7406,271111&fmt=json", "http://comtrade.un.org/api/get?max=50000&type=C&freq=A&px=HS&ps=2015,2014,2013,2012,2011&r=826&p=all&rg=2&cc=284330,150810,09,1109,52,071040,17,28432,7406,271111&fmt=json", "http://comtrade.un.org/api/get?max=50000&type=C&freq=A&px=HS&ps=2015,2014,2013,2012,2011&r=834&p=all&rg=2&cc=284330,150810,09,1109,52,071040,17,28432,7406,271111&fmt=json"] def fetch_url(url, i): file_name = "file_"+countrylist[i]+".json" file_list.append(file_name) response = requests.get(url, verify=False) data = response.json() if not os.path.isfile("./"+file_name): with open(file_name, 'w') as outfile: json.dump(data["dataset"], outfile) print "'%s\' fetched in %ss" % (url, (time.time() - start)) # threads = [threading.Thread(target=fetch_url, args=(urls[i],i,)) for i in range(0,len(urls)) ] for thread in threads: thread.start() time.sleep(12) for thread in threads: thread.join() #final data identifier res_data = {} for k in range(0,len(countrylist)): with open(file_list[k],"r") as json_data: data_json = json.load(json_data) for j in range(0,len(data_json)): if data_json[j]['yr'] == 2011:
elif data_json[j]['yr'] == 2012: a = (countrylist[k],"2012") elif data_json[j]['yr'] == 2013: a = (countrylist[k],"2013") elif data_json[j]['yr'] == 2014: a = (countrylist[k],"2014") elif data_json[j]['yr'] == 2015: a = (countrylist[k],"2015") # insrt the key a = "".join(a) if a not in res_data.keys(): res_data[a] = [] if data_json[j]["ptTitle"].lower() not in countrylist: continue b = {} b["country"] = data_json[j]["ptTitle"].lower() b["commodity"] = dataTable[str(data_json[j]["cmdCode"])] b["val"] = data_json[j]["TradeValue"] res_data[a].append(b) final_file_name = "exportData.json" if not os.path.isfile("./"+final_file_name): with open(final_file_name, 'w') as outfile: json.dump(res_data, outfile) #for i in range(0,len(file_list)): print "Elapsed Time: %s" % (time.time() - start)
a = (countrylist[k],"2011")
conditional_block
psd.py
#!/usr/bin/env python3 import math, logging, threading, concurrent.futures import numpy import simplespectral from soapypower import threadpool logger = logging.getLogger(__name__) class PSD: """Compute averaged power spectral density using Welch's method""" def __init__(self, bins, sample_rate, fft_window='hann', fft_overlap=0.5, crop_factor=0, log_scale=True, remove_dc=False, detrend=None, lnb_lo=0, max_threads=0, max_queue_size=0): self._bins = bins self._sample_rate = sample_rate self._fft_window = fft_window self._fft_overlap = fft_overlap self._fft_overlap_bins = math.floor(self._bins * self._fft_overlap) self._crop_factor = crop_factor self._log_scale = log_scale self._remove_dc = remove_dc self._detrend = detrend self._lnb_lo = lnb_lo self._executor = threadpool.ThreadPoolExecutor( max_workers=max_threads, max_queue_size=max_queue_size, thread_name_prefix='PSD_thread' ) self._base_freq_array = numpy.fft.fftfreq(self._bins, 1 / self._sample_rate) def set_center_freq(self, center_freq): """Set center frequency and clear averaged PSD data""" psd_state = { 'repeats': 0, 'freq_array': self._base_freq_array + self._lnb_lo + center_freq, 'pwr_array': None, 'update_lock': threading.Lock(), 'futures': [], } return psd_state def result(self, psd_state): """Return freqs and averaged PSD for given center frequency""" freq_array = numpy.fft.fftshift(psd_state['freq_array']) pwr_array = numpy.fft.fftshift(psd_state['pwr_array']) if self._crop_factor: crop_bins_half = round((self._crop_factor * self._bins) / 2) freq_array = freq_array[crop_bins_half:-crop_bins_half] pwr_array = pwr_array[crop_bins_half:-crop_bins_half] if psd_state['repeats'] > 1: pwr_array = pwr_array / psd_state['repeats'] if self._log_scale: pwr_array = 10 * numpy.log10(pwr_array) return (freq_array, pwr_array) def wait_for_result(self, psd_state): """Wait for all PSD threads to finish and return result""" if len(psd_state['futures']) > 1: concurrent.futures.wait(psd_state['futures']) elif psd_state['futures']: psd_state['futures'][0].result() return self.result(psd_state) def result_async(self, psd_state): """Return freqs and averaged PSD for given center frequency (asynchronously in another thread)""" return self._executor.submit(self.wait_for_result, psd_state) def _release_future_memory(self, future):
def update(self, psd_state, samples_array): """Compute PSD from samples and update average for given center frequency""" freq_array, pwr_array = simplespectral.welch(samples_array, self._sample_rate, nperseg=self._bins, window=self._fft_window, noverlap=self._fft_overlap_bins, detrend=self._detrend) if self._remove_dc: pwr_array[0] = (pwr_array[1] + pwr_array[-1]) / 2 with psd_state['update_lock']: psd_state['repeats'] += 1 if psd_state['pwr_array'] is None: psd_state['pwr_array'] = pwr_array else: psd_state['pwr_array'] += pwr_array def update_async(self, psd_state, samples_array): """Compute PSD from samples and update average for given center frequency (asynchronously in another thread)""" future = self._executor.submit(self.update, psd_state, samples_array) future.add_done_callback(self._release_future_memory) psd_state['futures'].append(future) return future
"""Remove result from future to release memory""" future._result = None
identifier_body
psd.py
#!/usr/bin/env python3 import math, logging, threading, concurrent.futures import numpy import simplespectral from soapypower import threadpool logger = logging.getLogger(__name__) class PSD: """Compute averaged power spectral density using Welch's method""" def __init__(self, bins, sample_rate, fft_window='hann', fft_overlap=0.5, crop_factor=0, log_scale=True, remove_dc=False, detrend=None, lnb_lo=0, max_threads=0, max_queue_size=0): self._bins = bins self._sample_rate = sample_rate self._fft_window = fft_window self._fft_overlap = fft_overlap self._fft_overlap_bins = math.floor(self._bins * self._fft_overlap) self._crop_factor = crop_factor self._log_scale = log_scale self._remove_dc = remove_dc self._detrend = detrend self._lnb_lo = lnb_lo self._executor = threadpool.ThreadPoolExecutor( max_workers=max_threads, max_queue_size=max_queue_size, thread_name_prefix='PSD_thread' ) self._base_freq_array = numpy.fft.fftfreq(self._bins, 1 / self._sample_rate) def set_center_freq(self, center_freq): """Set center frequency and clear averaged PSD data""" psd_state = { 'repeats': 0, 'freq_array': self._base_freq_array + self._lnb_lo + center_freq, 'pwr_array': None, 'update_lock': threading.Lock(), 'futures': [], } return psd_state def result(self, psd_state): """Return freqs and averaged PSD for given center frequency""" freq_array = numpy.fft.fftshift(psd_state['freq_array']) pwr_array = numpy.fft.fftshift(psd_state['pwr_array']) if self._crop_factor: crop_bins_half = round((self._crop_factor * self._bins) / 2) freq_array = freq_array[crop_bins_half:-crop_bins_half] pwr_array = pwr_array[crop_bins_half:-crop_bins_half] if psd_state['repeats'] > 1: pwr_array = pwr_array / psd_state['repeats'] if self._log_scale: pwr_array = 10 * numpy.log10(pwr_array) return (freq_array, pwr_array) def
(self, psd_state): """Wait for all PSD threads to finish and return result""" if len(psd_state['futures']) > 1: concurrent.futures.wait(psd_state['futures']) elif psd_state['futures']: psd_state['futures'][0].result() return self.result(psd_state) def result_async(self, psd_state): """Return freqs and averaged PSD for given center frequency (asynchronously in another thread)""" return self._executor.submit(self.wait_for_result, psd_state) def _release_future_memory(self, future): """Remove result from future to release memory""" future._result = None def update(self, psd_state, samples_array): """Compute PSD from samples and update average for given center frequency""" freq_array, pwr_array = simplespectral.welch(samples_array, self._sample_rate, nperseg=self._bins, window=self._fft_window, noverlap=self._fft_overlap_bins, detrend=self._detrend) if self._remove_dc: pwr_array[0] = (pwr_array[1] + pwr_array[-1]) / 2 with psd_state['update_lock']: psd_state['repeats'] += 1 if psd_state['pwr_array'] is None: psd_state['pwr_array'] = pwr_array else: psd_state['pwr_array'] += pwr_array def update_async(self, psd_state, samples_array): """Compute PSD from samples and update average for given center frequency (asynchronously in another thread)""" future = self._executor.submit(self.update, psd_state, samples_array) future.add_done_callback(self._release_future_memory) psd_state['futures'].append(future) return future
wait_for_result
identifier_name
psd.py
#!/usr/bin/env python3 import math, logging, threading, concurrent.futures import numpy import simplespectral from soapypower import threadpool logger = logging.getLogger(__name__) class PSD: """Compute averaged power spectral density using Welch's method""" def __init__(self, bins, sample_rate, fft_window='hann', fft_overlap=0.5, crop_factor=0, log_scale=True, remove_dc=False, detrend=None, lnb_lo=0, max_threads=0, max_queue_size=0): self._bins = bins self._sample_rate = sample_rate self._fft_window = fft_window self._fft_overlap = fft_overlap self._fft_overlap_bins = math.floor(self._bins * self._fft_overlap) self._crop_factor = crop_factor self._log_scale = log_scale self._remove_dc = remove_dc self._detrend = detrend self._lnb_lo = lnb_lo self._executor = threadpool.ThreadPoolExecutor( max_workers=max_threads, max_queue_size=max_queue_size, thread_name_prefix='PSD_thread' ) self._base_freq_array = numpy.fft.fftfreq(self._bins, 1 / self._sample_rate) def set_center_freq(self, center_freq): """Set center frequency and clear averaged PSD data""" psd_state = { 'repeats': 0, 'freq_array': self._base_freq_array + self._lnb_lo + center_freq, 'pwr_array': None, 'update_lock': threading.Lock(), 'futures': [], } return psd_state def result(self, psd_state): """Return freqs and averaged PSD for given center frequency""" freq_array = numpy.fft.fftshift(psd_state['freq_array']) pwr_array = numpy.fft.fftshift(psd_state['pwr_array']) if self._crop_factor:
if psd_state['repeats'] > 1: pwr_array = pwr_array / psd_state['repeats'] if self._log_scale: pwr_array = 10 * numpy.log10(pwr_array) return (freq_array, pwr_array) def wait_for_result(self, psd_state): """Wait for all PSD threads to finish and return result""" if len(psd_state['futures']) > 1: concurrent.futures.wait(psd_state['futures']) elif psd_state['futures']: psd_state['futures'][0].result() return self.result(psd_state) def result_async(self, psd_state): """Return freqs and averaged PSD for given center frequency (asynchronously in another thread)""" return self._executor.submit(self.wait_for_result, psd_state) def _release_future_memory(self, future): """Remove result from future to release memory""" future._result = None def update(self, psd_state, samples_array): """Compute PSD from samples and update average for given center frequency""" freq_array, pwr_array = simplespectral.welch(samples_array, self._sample_rate, nperseg=self._bins, window=self._fft_window, noverlap=self._fft_overlap_bins, detrend=self._detrend) if self._remove_dc: pwr_array[0] = (pwr_array[1] + pwr_array[-1]) / 2 with psd_state['update_lock']: psd_state['repeats'] += 1 if psd_state['pwr_array'] is None: psd_state['pwr_array'] = pwr_array else: psd_state['pwr_array'] += pwr_array def update_async(self, psd_state, samples_array): """Compute PSD from samples and update average for given center frequency (asynchronously in another thread)""" future = self._executor.submit(self.update, psd_state, samples_array) future.add_done_callback(self._release_future_memory) psd_state['futures'].append(future) return future
crop_bins_half = round((self._crop_factor * self._bins) / 2) freq_array = freq_array[crop_bins_half:-crop_bins_half] pwr_array = pwr_array[crop_bins_half:-crop_bins_half]
conditional_block
psd.py
#!/usr/bin/env python3 import math, logging, threading, concurrent.futures import numpy import simplespectral from soapypower import threadpool logger = logging.getLogger(__name__) class PSD: """Compute averaged power spectral density using Welch's method""" def __init__(self, bins, sample_rate, fft_window='hann', fft_overlap=0.5,
self._sample_rate = sample_rate self._fft_window = fft_window self._fft_overlap = fft_overlap self._fft_overlap_bins = math.floor(self._bins * self._fft_overlap) self._crop_factor = crop_factor self._log_scale = log_scale self._remove_dc = remove_dc self._detrend = detrend self._lnb_lo = lnb_lo self._executor = threadpool.ThreadPoolExecutor( max_workers=max_threads, max_queue_size=max_queue_size, thread_name_prefix='PSD_thread' ) self._base_freq_array = numpy.fft.fftfreq(self._bins, 1 / self._sample_rate) def set_center_freq(self, center_freq): """Set center frequency and clear averaged PSD data""" psd_state = { 'repeats': 0, 'freq_array': self._base_freq_array + self._lnb_lo + center_freq, 'pwr_array': None, 'update_lock': threading.Lock(), 'futures': [], } return psd_state def result(self, psd_state): """Return freqs and averaged PSD for given center frequency""" freq_array = numpy.fft.fftshift(psd_state['freq_array']) pwr_array = numpy.fft.fftshift(psd_state['pwr_array']) if self._crop_factor: crop_bins_half = round((self._crop_factor * self._bins) / 2) freq_array = freq_array[crop_bins_half:-crop_bins_half] pwr_array = pwr_array[crop_bins_half:-crop_bins_half] if psd_state['repeats'] > 1: pwr_array = pwr_array / psd_state['repeats'] if self._log_scale: pwr_array = 10 * numpy.log10(pwr_array) return (freq_array, pwr_array) def wait_for_result(self, psd_state): """Wait for all PSD threads to finish and return result""" if len(psd_state['futures']) > 1: concurrent.futures.wait(psd_state['futures']) elif psd_state['futures']: psd_state['futures'][0].result() return self.result(psd_state) def result_async(self, psd_state): """Return freqs and averaged PSD for given center frequency (asynchronously in another thread)""" return self._executor.submit(self.wait_for_result, psd_state) def _release_future_memory(self, future): """Remove result from future to release memory""" future._result = None def update(self, psd_state, samples_array): """Compute PSD from samples and update average for given center frequency""" freq_array, pwr_array = simplespectral.welch(samples_array, self._sample_rate, nperseg=self._bins, window=self._fft_window, noverlap=self._fft_overlap_bins, detrend=self._detrend) if self._remove_dc: pwr_array[0] = (pwr_array[1] + pwr_array[-1]) / 2 with psd_state['update_lock']: psd_state['repeats'] += 1 if psd_state['pwr_array'] is None: psd_state['pwr_array'] = pwr_array else: psd_state['pwr_array'] += pwr_array def update_async(self, psd_state, samples_array): """Compute PSD from samples and update average for given center frequency (asynchronously in another thread)""" future = self._executor.submit(self.update, psd_state, samples_array) future.add_done_callback(self._release_future_memory) psd_state['futures'].append(future) return future
crop_factor=0, log_scale=True, remove_dc=False, detrend=None, lnb_lo=0, max_threads=0, max_queue_size=0): self._bins = bins
random_line_split
dom.js
/** * Created by Administrator on 2015/12/26. * 一些变量 $.fn.extend({ // 通过一定的条件,删选自身
find 查找子节点, 调用的是jQuery.find == Sizzle, jQuery.unique == Sizzle.unique ; has 指子元素有没有,返回自身的。。 not filter 指自身有没有,返回自身的。。 is 返回true or false closest 找满足条件的最近父节点(包括自身) index 返回元素在兄弟节点中的索引值 add addBack }); function sibling(){} jQuery.each({ parent // parentNode parents // parentNode 循环 parentsUntil // next // nextSibling prev // previousSibling nextAll // 循环 prevAll // nextUntil prevUntil // 下面的兄弟节点,直到一个 siblings // 所有兄弟节点 children // 只有元素节点 contents // 包括文本节点,elem.childNodes, iframe }); jQuery.extend({ filter dir sibling }); function winnow(){} 一些变量 jQuery.fn.extend({ text // 返回文本节点的文本形式 append // body.append(tr)在ie67中有问题,tbody.append(tr) prepend // before after remove // 返回自身,但是自身上绑定的事件都没有,调用jQuery.cleanData(); empty // elem.textContent, 678不支持 clone // clone(true)=clone(true,true) ,clone(false)=clone(false,false)=clone(), clone(true,false):父元素事件不清除,子元素清除 // 原生添加(addEventListener)的事件不会被克隆 html //"<script></scrip>" 与原生 innerHTML 插入不同 replaceWith detach // 与remove差不多,但是原先绑定的data或是event都存在 domManip }); jQuery.each({ appendTo: "append", prependTo: "prepend", insertBefore: "before", insertAfter: "after", replaceAll: "replaceWith" }); jQuery.extend({ clone buildFragment cleanData _evalUrl }); function manipulationTarget(){} function disableScript(){} function restoreScript(){} function setGlobalEval(){} function cloneCopyEvent(){} function getAll(){} function fixInput(){} jQuery.fn.extend({ wrapAll //选择到的元素包装 wrapInner //包装每个元素的子节点 wrap //对每个元素进行包装 unwrap //删去每个元素的父级,除了body }); */
random_line_split
DataProviderService.ts
import {Injectable} from 'angular2/core'; import {GEDCOMX_SCHEMA} from './GedcomXDummy'; import {GEDCOMX_DATA} from './demoData/GedcomX.data'; import {GEDCOMX_DATA2} from './demoData/GedcomX.data2'; import {GEDCOMX_DATA3} from './demoData/GedcomX.data3'; import {GEDCOMX_DATA4} from './demoData/GedcomX.data4'; declare var JsonRefs; @Injectable() export class DataProviderService { private _callbacks:SchemaResolvedCallback[]=[]; private _dataSchema:any=GEDCOMX_SCHEMA; private _resolved:boolean=false; //private _dataSchemaPromise:Promise=new Promise(function(resolve, reject) {}) private _refs:any; constructor() { JsonRefs.resolveRefs(this._dataSchema) .then(res =>{ // Do something with the response // res.refs: JSON Reference locations and details // res.resolved: The document with the appropriate JSON References resolved this._dataSchema=res.resolved; this._refs=res.refs; this._resolved=true; this._callbacks.forEach(callback=>{callback.call}); }, err => {console.log(err.stack);} ); } getSchema(){ return new Promise( (resolve, reject)=> { if(this._resolved) resolve(this._dataSchema); else this._callbacks.push(()=>{resolve(this._dataSchema)}); }); } getRefs(){ return new Promise( (resolve, reject)=> { if(this._resolved) resolve(this._refs); else this._callbacks.push(()=>{resolve(this._refs)}); }); } private get data():any{return GEDCOMX_DATA3;} private createNewObject(idPrefix:string):any{ return {id:idPrefix+"_"+Math.round(Math.random()*100)}; } private setArrayValue(arrayName:string, value:any){ if(this.data[arrayName]==undefined){ this.data[arrayName]=[]; } this.data[arrayName].push(value); } getRoot(){ return Promise.resolve(this.data); } getPersons() { return Promise.resolve(this.data.persons); } getPerson(id:string){ return Promise.resolve(this.data.persons).then(persons => persons.filter(p => p.id === id)[0]); } createPerson(){ let newPerson=this.createNewObject("person"); this.setArrayValue("persons",newPerson); return newPerson.id; } getPlaces(){ return Promise.resolve(this.data.places); } getPlace(id:string){ return Promise.resolve(this.data.places).then(places => places.filter(p => p.id === id)[0]); } createPlace(){ let newPlace=this.createNewObject("place"); this.setArrayValue("places",newPlace); return newPlace.id; } getSources(){ return Promise.resolve(this.data.sourceDescriptions); } getSource(id:string){ return Promise.resolve(this.data.sourceDescriptions).then(sourceDescriptions => sourceDescriptions.filter(s => s.id === id)[0]); } createSource(){ let newSource=this.createNewObject("source"); this.setArrayValue("sourceDescriptions",newSource); return newSource.id; } getRelationships(){ return Promise.resolve(this.data.relationships); } getRelationship(id:string){ return Promise.resolve(this.data.relationships).then(relationships => relationships.filter(r => r.id === id)[0]); } createRelationship(){ let newRelationship=this.createNewObject("relationship"); this.setArrayValue("relationships",newRelationship); return newRelationship.id; }
(){ return Promise.resolve(this.data.agents); } getAgent(id:string){ return Promise.resolve(this.data.agents).then(agents => agents.filter(a => a.id === id)[0]); } createAgent(){ let newAgent=this.createNewObject("agent"); this.setArrayValue("agents",newAgent); return newAgent.id; } getEvents(){ return Promise.resolve(this.data.events); } getEvent(id:string){ return Promise.resolve(this.data.events).then(events => events.filter(e => e.id === id)[0]); } createEvent(){ let newEvent=this.createNewObject("event"); this.setArrayValue("events",newEvent); return newEvent.id; } getDocuments(){ return Promise.resolve(this.data.documents); } getDocument(id:string){ return Promise.resolve(this.data.documents).then(documents => documents.filter(d => d.id === id)[0]); } createDocument(){ let newDocument=this.createNewObject("document"); this.setArrayValue("documents",newDocument); return newDocument.id; } } interface SchemaResolvedCallback {():void;}
getAgents
identifier_name
DataProviderService.ts
import {Injectable} from 'angular2/core'; import {GEDCOMX_SCHEMA} from './GedcomXDummy'; import {GEDCOMX_DATA} from './demoData/GedcomX.data'; import {GEDCOMX_DATA2} from './demoData/GedcomX.data2'; import {GEDCOMX_DATA3} from './demoData/GedcomX.data3'; import {GEDCOMX_DATA4} from './demoData/GedcomX.data4'; declare var JsonRefs; @Injectable() export class DataProviderService { private _callbacks:SchemaResolvedCallback[]=[]; private _dataSchema:any=GEDCOMX_SCHEMA; private _resolved:boolean=false; //private _dataSchemaPromise:Promise=new Promise(function(resolve, reject) {}) private _refs:any; constructor()
getSchema(){ return new Promise( (resolve, reject)=> { if(this._resolved) resolve(this._dataSchema); else this._callbacks.push(()=>{resolve(this._dataSchema)}); }); } getRefs(){ return new Promise( (resolve, reject)=> { if(this._resolved) resolve(this._refs); else this._callbacks.push(()=>{resolve(this._refs)}); }); } private get data():any{return GEDCOMX_DATA3;} private createNewObject(idPrefix:string):any{ return {id:idPrefix+"_"+Math.round(Math.random()*100)}; } private setArrayValue(arrayName:string, value:any){ if(this.data[arrayName]==undefined){ this.data[arrayName]=[]; } this.data[arrayName].push(value); } getRoot(){ return Promise.resolve(this.data); } getPersons() { return Promise.resolve(this.data.persons); } getPerson(id:string){ return Promise.resolve(this.data.persons).then(persons => persons.filter(p => p.id === id)[0]); } createPerson(){ let newPerson=this.createNewObject("person"); this.setArrayValue("persons",newPerson); return newPerson.id; } getPlaces(){ return Promise.resolve(this.data.places); } getPlace(id:string){ return Promise.resolve(this.data.places).then(places => places.filter(p => p.id === id)[0]); } createPlace(){ let newPlace=this.createNewObject("place"); this.setArrayValue("places",newPlace); return newPlace.id; } getSources(){ return Promise.resolve(this.data.sourceDescriptions); } getSource(id:string){ return Promise.resolve(this.data.sourceDescriptions).then(sourceDescriptions => sourceDescriptions.filter(s => s.id === id)[0]); } createSource(){ let newSource=this.createNewObject("source"); this.setArrayValue("sourceDescriptions",newSource); return newSource.id; } getRelationships(){ return Promise.resolve(this.data.relationships); } getRelationship(id:string){ return Promise.resolve(this.data.relationships).then(relationships => relationships.filter(r => r.id === id)[0]); } createRelationship(){ let newRelationship=this.createNewObject("relationship"); this.setArrayValue("relationships",newRelationship); return newRelationship.id; } getAgents(){ return Promise.resolve(this.data.agents); } getAgent(id:string){ return Promise.resolve(this.data.agents).then(agents => agents.filter(a => a.id === id)[0]); } createAgent(){ let newAgent=this.createNewObject("agent"); this.setArrayValue("agents",newAgent); return newAgent.id; } getEvents(){ return Promise.resolve(this.data.events); } getEvent(id:string){ return Promise.resolve(this.data.events).then(events => events.filter(e => e.id === id)[0]); } createEvent(){ let newEvent=this.createNewObject("event"); this.setArrayValue("events",newEvent); return newEvent.id; } getDocuments(){ return Promise.resolve(this.data.documents); } getDocument(id:string){ return Promise.resolve(this.data.documents).then(documents => documents.filter(d => d.id === id)[0]); } createDocument(){ let newDocument=this.createNewObject("document"); this.setArrayValue("documents",newDocument); return newDocument.id; } } interface SchemaResolvedCallback {():void;}
{ JsonRefs.resolveRefs(this._dataSchema) .then(res =>{ // Do something with the response // res.refs: JSON Reference locations and details // res.resolved: The document with the appropriate JSON References resolved this._dataSchema=res.resolved; this._refs=res.refs; this._resolved=true; this._callbacks.forEach(callback=>{callback.call}); }, err => {console.log(err.stack);} ); }
identifier_body
DataProviderService.ts
import {Injectable} from 'angular2/core'; import {GEDCOMX_SCHEMA} from './GedcomXDummy'; import {GEDCOMX_DATA} from './demoData/GedcomX.data'; import {GEDCOMX_DATA2} from './demoData/GedcomX.data2'; import {GEDCOMX_DATA3} from './demoData/GedcomX.data3'; import {GEDCOMX_DATA4} from './demoData/GedcomX.data4'; declare var JsonRefs; @Injectable() export class DataProviderService { private _callbacks:SchemaResolvedCallback[]=[]; private _dataSchema:any=GEDCOMX_SCHEMA; private _resolved:boolean=false; //private _dataSchemaPromise:Promise=new Promise(function(resolve, reject) {}) private _refs:any; constructor() { JsonRefs.resolveRefs(this._dataSchema)
this._refs=res.refs; this._resolved=true; this._callbacks.forEach(callback=>{callback.call}); }, err => {console.log(err.stack);} ); } getSchema(){ return new Promise( (resolve, reject)=> { if(this._resolved) resolve(this._dataSchema); else this._callbacks.push(()=>{resolve(this._dataSchema)}); }); } getRefs(){ return new Promise( (resolve, reject)=> { if(this._resolved) resolve(this._refs); else this._callbacks.push(()=>{resolve(this._refs)}); }); } private get data():any{return GEDCOMX_DATA3;} private createNewObject(idPrefix:string):any{ return {id:idPrefix+"_"+Math.round(Math.random()*100)}; } private setArrayValue(arrayName:string, value:any){ if(this.data[arrayName]==undefined){ this.data[arrayName]=[]; } this.data[arrayName].push(value); } getRoot(){ return Promise.resolve(this.data); } getPersons() { return Promise.resolve(this.data.persons); } getPerson(id:string){ return Promise.resolve(this.data.persons).then(persons => persons.filter(p => p.id === id)[0]); } createPerson(){ let newPerson=this.createNewObject("person"); this.setArrayValue("persons",newPerson); return newPerson.id; } getPlaces(){ return Promise.resolve(this.data.places); } getPlace(id:string){ return Promise.resolve(this.data.places).then(places => places.filter(p => p.id === id)[0]); } createPlace(){ let newPlace=this.createNewObject("place"); this.setArrayValue("places",newPlace); return newPlace.id; } getSources(){ return Promise.resolve(this.data.sourceDescriptions); } getSource(id:string){ return Promise.resolve(this.data.sourceDescriptions).then(sourceDescriptions => sourceDescriptions.filter(s => s.id === id)[0]); } createSource(){ let newSource=this.createNewObject("source"); this.setArrayValue("sourceDescriptions",newSource); return newSource.id; } getRelationships(){ return Promise.resolve(this.data.relationships); } getRelationship(id:string){ return Promise.resolve(this.data.relationships).then(relationships => relationships.filter(r => r.id === id)[0]); } createRelationship(){ let newRelationship=this.createNewObject("relationship"); this.setArrayValue("relationships",newRelationship); return newRelationship.id; } getAgents(){ return Promise.resolve(this.data.agents); } getAgent(id:string){ return Promise.resolve(this.data.agents).then(agents => agents.filter(a => a.id === id)[0]); } createAgent(){ let newAgent=this.createNewObject("agent"); this.setArrayValue("agents",newAgent); return newAgent.id; } getEvents(){ return Promise.resolve(this.data.events); } getEvent(id:string){ return Promise.resolve(this.data.events).then(events => events.filter(e => e.id === id)[0]); } createEvent(){ let newEvent=this.createNewObject("event"); this.setArrayValue("events",newEvent); return newEvent.id; } getDocuments(){ return Promise.resolve(this.data.documents); } getDocument(id:string){ return Promise.resolve(this.data.documents).then(documents => documents.filter(d => d.id === id)[0]); } createDocument(){ let newDocument=this.createNewObject("document"); this.setArrayValue("documents",newDocument); return newDocument.id; } } interface SchemaResolvedCallback {():void;}
.then(res =>{ // Do something with the response // res.refs: JSON Reference locations and details // res.resolved: The document with the appropriate JSON References resolved this._dataSchema=res.resolved;
random_line_split
main.rs
use std::thread; use std::thread::JoinHandle; mod factorial; use factorial::util::t_log; use factorial::find_factors; fn get_chunk(index: u64, chunk_size: u64, max: u64) -> Option<(u64, u64)> { let mut result = None; let low = chunk_size * (index - 1); let high = chunk_size * index; if high <= max { result = Some((low, high)) } else if low >= max { // no-op } else { result = Some((low, max)) } result } fn main() { const MAX: u64 = 300; const CHUNK: u64 = 50; let mut done = false; let mut index: u64 = 1; let mut handles: Vec<JoinHandle<_>> = vec![]; while ! done { let chunk = get_chunk(index, CHUNK, MAX); if let Some((low, high)) = chunk { let handle = thread::spawn(move || { t_log(&format!("TRACER {} {}", low, high)); find_factors(low, high); }); handles.push(handle); index += 1; } else
} t_log("waiting in main..."); for handle in handles.into_iter() { handle.join().unwrap(); } t_log("Ready."); } #[allow(unused_imports)] mod tests { use super::*; #[test] fn test_get_chunk_low_boundary() { let index: u64 = 1; let chunk: u64 = 10; let max: u64 = 25; // test let (low, high) = get_chunk(index, chunk, max).unwrap(); assert_eq!(low, 0); assert_eq!(high, 10); } #[test] fn test_get_chunk_basic() { let index: u64 = 2; let chunk: u64 = 10; let max: u64 = 25; // test let (low, high) = get_chunk(index, chunk, max).unwrap(); assert_eq!(low, 10); assert_eq!(high, 20); } #[test] fn test_get_chunk_high_boundary() { let index: u64 = 3; let chunk: u64 = 10; let max: u64 = 25; // test let (low, high) = get_chunk(index, chunk, max).unwrap(); assert_eq!(low, 20); assert_eq!(high, 25); } #[test] fn test_get_chunk_out_of_range() { let index: u64 = 4; let chunk: u64 = 10; let max: u64 = 25; // test let result = get_chunk(index, chunk, max); assert_eq!(result.is_none(), true); } }
{ done = true; }
conditional_block
main.rs
use std::thread; use std::thread::JoinHandle; mod factorial; use factorial::util::t_log; use factorial::find_factors; fn get_chunk(index: u64, chunk_size: u64, max: u64) -> Option<(u64, u64)> { let mut result = None; let low = chunk_size * (index - 1); let high = chunk_size * index; if high <= max { result = Some((low, high)) } else if low >= max { // no-op } else { result = Some((low, max)) } result } fn main() { const MAX: u64 = 300; const CHUNK: u64 = 50; let mut done = false; let mut index: u64 = 1; let mut handles: Vec<JoinHandle<_>> = vec![]; while ! done { let chunk = get_chunk(index, CHUNK, MAX); if let Some((low, high)) = chunk { let handle = thread::spawn(move || { t_log(&format!("TRACER {} {}", low, high)); find_factors(low, high); }); handles.push(handle); index += 1; } else { done = true; } } t_log("waiting in main..."); for handle in handles.into_iter() { handle.join().unwrap(); } t_log("Ready."); } #[allow(unused_imports)] mod tests { use super::*; #[test] fn
() { let index: u64 = 1; let chunk: u64 = 10; let max: u64 = 25; // test let (low, high) = get_chunk(index, chunk, max).unwrap(); assert_eq!(low, 0); assert_eq!(high, 10); } #[test] fn test_get_chunk_basic() { let index: u64 = 2; let chunk: u64 = 10; let max: u64 = 25; // test let (low, high) = get_chunk(index, chunk, max).unwrap(); assert_eq!(low, 10); assert_eq!(high, 20); } #[test] fn test_get_chunk_high_boundary() { let index: u64 = 3; let chunk: u64 = 10; let max: u64 = 25; // test let (low, high) = get_chunk(index, chunk, max).unwrap(); assert_eq!(low, 20); assert_eq!(high, 25); } #[test] fn test_get_chunk_out_of_range() { let index: u64 = 4; let chunk: u64 = 10; let max: u64 = 25; // test let result = get_chunk(index, chunk, max); assert_eq!(result.is_none(), true); } }
test_get_chunk_low_boundary
identifier_name
main.rs
use std::thread; use std::thread::JoinHandle; mod factorial; use factorial::util::t_log; use factorial::find_factors; fn get_chunk(index: u64, chunk_size: u64, max: u64) -> Option<(u64, u64)> { let mut result = None; let low = chunk_size * (index - 1); let high = chunk_size * index; if high <= max { result = Some((low, high)) } else if low >= max { // no-op } else { result = Some((low, max)) } result } fn main() { const MAX: u64 = 300; const CHUNK: u64 = 50; let mut done = false; let mut index: u64 = 1; let mut handles: Vec<JoinHandle<_>> = vec![]; while ! done { let chunk = get_chunk(index, CHUNK, MAX); if let Some((low, high)) = chunk { let handle = thread::spawn(move || { t_log(&format!("TRACER {} {}", low, high)); find_factors(low, high); }); handles.push(handle); index += 1; } else { done = true; } } t_log("waiting in main..."); for handle in handles.into_iter() { handle.join().unwrap(); } t_log("Ready."); } #[allow(unused_imports)] mod tests { use super::*; #[test] fn test_get_chunk_low_boundary() { let index: u64 = 1; let chunk: u64 = 10; let max: u64 = 25; // test let (low, high) = get_chunk(index, chunk, max).unwrap(); assert_eq!(low, 0); assert_eq!(high, 10); } #[test] fn test_get_chunk_basic() { let index: u64 = 2; let chunk: u64 = 10; let max: u64 = 25; // test let (low, high) = get_chunk(index, chunk, max).unwrap(); assert_eq!(low, 10); assert_eq!(high, 20); } #[test] fn test_get_chunk_high_boundary() { let index: u64 = 3; let chunk: u64 = 10; let max: u64 = 25; // test let (low, high) = get_chunk(index, chunk, max).unwrap(); assert_eq!(low, 20); assert_eq!(high, 25); } #[test] fn test_get_chunk_out_of_range() { let index: u64 = 4; let chunk: u64 = 10; let max: u64 = 25; // test
assert_eq!(result.is_none(), true); } }
let result = get_chunk(index, chunk, max);
random_line_split
main.rs
use std::thread; use std::thread::JoinHandle; mod factorial; use factorial::util::t_log; use factorial::find_factors; fn get_chunk(index: u64, chunk_size: u64, max: u64) -> Option<(u64, u64)> { let mut result = None; let low = chunk_size * (index - 1); let high = chunk_size * index; if high <= max { result = Some((low, high)) } else if low >= max { // no-op } else { result = Some((low, max)) } result } fn main() { const MAX: u64 = 300; const CHUNK: u64 = 50; let mut done = false; let mut index: u64 = 1; let mut handles: Vec<JoinHandle<_>> = vec![]; while ! done { let chunk = get_chunk(index, CHUNK, MAX); if let Some((low, high)) = chunk { let handle = thread::spawn(move || { t_log(&format!("TRACER {} {}", low, high)); find_factors(low, high); }); handles.push(handle); index += 1; } else { done = true; } } t_log("waiting in main..."); for handle in handles.into_iter() { handle.join().unwrap(); } t_log("Ready."); } #[allow(unused_imports)] mod tests { use super::*; #[test] fn test_get_chunk_low_boundary() { let index: u64 = 1; let chunk: u64 = 10; let max: u64 = 25; // test let (low, high) = get_chunk(index, chunk, max).unwrap(); assert_eq!(low, 0); assert_eq!(high, 10); } #[test] fn test_get_chunk_basic() { let index: u64 = 2; let chunk: u64 = 10; let max: u64 = 25; // test let (low, high) = get_chunk(index, chunk, max).unwrap(); assert_eq!(low, 10); assert_eq!(high, 20); } #[test] fn test_get_chunk_high_boundary() { let index: u64 = 3; let chunk: u64 = 10; let max: u64 = 25; // test let (low, high) = get_chunk(index, chunk, max).unwrap(); assert_eq!(low, 20); assert_eq!(high, 25); } #[test] fn test_get_chunk_out_of_range()
}
{ let index: u64 = 4; let chunk: u64 = 10; let max: u64 = 25; // test let result = get_chunk(index, chunk, max); assert_eq!(result.is_none(), true); }
identifier_body
mod.rs
pub use self::os::{FNM_NOMATCH}; pub use self::os::{FNM_PATHNAME}; pub use self::os::{FNM_PERIOD}; pub use self::os::{FNM_NOESCAPE}; use {NTStr, int_t, char_t}; #[cfg(target_os = "linux")] #[path = "linux/mod.rs"] mod os; pub fn fnmatch<T: NTStr, U: NTStr>(pattern: &T, string: &U, flags: int_t) -> int_t { extern { fn fnmatch(pattern: *const char_t, name: *const char_t, flags: int_t) -> int_t; } unsafe { fnmatch(pattern.as_ptr(), string.as_ptr(), flags) } } #[cfg(test)] mod tests { use {ToNTStr}; #[test] fn test()
}
{ let pat = "abc*123".to_nt_str(); let stn = "abcTE/ST123".to_nt_str(); let pat2 = "*123".to_nt_str(); let stn2 = ".123".to_nt_str(); assert_eq!(super::fnmatch(&pat, &stn, 0), 0); assert_eq!(super::fnmatch(&pat, &stn, super::FNM_PATHNAME), super::FNM_NOMATCH); assert_eq!(super::fnmatch(&pat2, &stn2, super::FNM_PATHNAME), 0); assert_eq!(super::fnmatch(&pat, &stn, super::FNM_PERIOD), 0); assert_eq!(super::fnmatch(&pat2, &stn2, super::FNM_PERIOD), super::FNM_NOMATCH); }
identifier_body
mod.rs
pub use self::os::{FNM_NOMATCH}; pub use self::os::{FNM_PATHNAME}; pub use self::os::{FNM_PERIOD}; pub use self::os::{FNM_NOESCAPE}; use {NTStr, int_t, char_t}; #[cfg(target_os = "linux")] #[path = "linux/mod.rs"] mod os; pub fn fnmatch<T: NTStr, U: NTStr>(pattern: &T, string: &U, flags: int_t) -> int_t { extern { fn fnmatch(pattern: *const char_t, name: *const char_t, flags: int_t) -> int_t; }
unsafe { fnmatch(pattern.as_ptr(), string.as_ptr(), flags) } } #[cfg(test)] mod tests { use {ToNTStr}; #[test] fn test() { let pat = "abc*123".to_nt_str(); let stn = "abcTE/ST123".to_nt_str(); let pat2 = "*123".to_nt_str(); let stn2 = ".123".to_nt_str(); assert_eq!(super::fnmatch(&pat, &stn, 0), 0); assert_eq!(super::fnmatch(&pat, &stn, super::FNM_PATHNAME), super::FNM_NOMATCH); assert_eq!(super::fnmatch(&pat2, &stn2, super::FNM_PATHNAME), 0); assert_eq!(super::fnmatch(&pat, &stn, super::FNM_PERIOD), 0); assert_eq!(super::fnmatch(&pat2, &stn2, super::FNM_PERIOD), super::FNM_NOMATCH); } }
random_line_split
mod.rs
pub use self::os::{FNM_NOMATCH}; pub use self::os::{FNM_PATHNAME}; pub use self::os::{FNM_PERIOD}; pub use self::os::{FNM_NOESCAPE}; use {NTStr, int_t, char_t}; #[cfg(target_os = "linux")] #[path = "linux/mod.rs"] mod os; pub fn
<T: NTStr, U: NTStr>(pattern: &T, string: &U, flags: int_t) -> int_t { extern { fn fnmatch(pattern: *const char_t, name: *const char_t, flags: int_t) -> int_t; } unsafe { fnmatch(pattern.as_ptr(), string.as_ptr(), flags) } } #[cfg(test)] mod tests { use {ToNTStr}; #[test] fn test() { let pat = "abc*123".to_nt_str(); let stn = "abcTE/ST123".to_nt_str(); let pat2 = "*123".to_nt_str(); let stn2 = ".123".to_nt_str(); assert_eq!(super::fnmatch(&pat, &stn, 0), 0); assert_eq!(super::fnmatch(&pat, &stn, super::FNM_PATHNAME), super::FNM_NOMATCH); assert_eq!(super::fnmatch(&pat2, &stn2, super::FNM_PATHNAME), 0); assert_eq!(super::fnmatch(&pat, &stn, super::FNM_PERIOD), 0); assert_eq!(super::fnmatch(&pat2, &stn2, super::FNM_PERIOD), super::FNM_NOMATCH); } }
fnmatch
identifier_name
guide-items.ts
import { Injectable } from '@angular/core'; export interface GuideItem { id: string; name: string; document: string; url: string; } const GUIDES: GuideItem[] = [ { id: 'getting-started', document: 'assets/docs/guides/getting-started.html', url: 'doc/guides/getting-started', name: 'Getting Started' }, { id: 'generate-api-key', document: 'assets/docs/guides/generate-api-key.html', url: 'doc/guides/generate-api-key', name: 'Generating an API Key' }, { id: 'troubleshooting', document: 'assets/docs/guides/troubleshooting.html', url: 'doc/guides/troubleshooting', name: 'Troubleshooting' } ]; @Injectable() export class
{ getAllItems(): GuideItem[] { return this.getGuideItems(); } getGuideItems(): GuideItem[] { return GUIDES; } getGuideItemById(id: string): GuideItem { return GUIDES.find(i => i.id === id); } }
GuideItemsService
identifier_name
guide-items.ts
import { Injectable } from '@angular/core'; export interface GuideItem { id: string; name: string; document: string; url: string; } const GUIDES: GuideItem[] = [ { id: 'getting-started', document: 'assets/docs/guides/getting-started.html', url: 'doc/guides/getting-started', name: 'Getting Started' }, { id: 'generate-api-key', document: 'assets/docs/guides/generate-api-key.html', url: 'doc/guides/generate-api-key', name: 'Generating an API Key' }, { id: 'troubleshooting', document: 'assets/docs/guides/troubleshooting.html', url: 'doc/guides/troubleshooting', name: 'Troubleshooting' } ]; @Injectable() export class GuideItemsService { getAllItems(): GuideItem[] { return this.getGuideItems(); } getGuideItems(): GuideItem[] {
} getGuideItemById(id: string): GuideItem { return GUIDES.find(i => i.id === id); } }
return GUIDES;
random_line_split
__openerp__.py
# -*- encoding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2010 Savoir-faire Linux (<http://www.savoirfairelinux.com>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero 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 Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>.
"name": "Hazard Risk", "version": "8.0.1.1.0", "author": "Savoir-faire Linux, Odoo Community Association (OCA)", "website": "http://www.savoirfairelinux.com", "license": "AGPL-3", "category": "Management System", "depends": [ 'mgmtsystem_hazard', 'hr' ], "data": [ 'security/ir.model.access.csv', 'data/mgmtsystem_hazard_risk_computation.xml', 'data/mgmtsystem_hazard_risk_type.xml', 'views/res_company.xml', 'views/mgmtsystem_hazard.xml', 'views/mgmtsystem_hazard_risk_type.xml', 'views/mgmtsystem_hazard_risk_computation.xml', 'views/mgmtsystem_hazard_residual_risk.xml', ], "installable": True, }
# ############################################################################## {
random_line_split
defaults.py
#!/usr/bin/env python # vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:fdm=marker:ai from __future__ import (unicode_literals, division, absolute_import, print_function) __license__ = 'GPL v3' __copyright__ = '2012, Kovid Goyal <kovid at kovidgoyal.net>' __docformat__ = 'restructuredtext en' import traceback, re from calibre.constants import iswindows class
(object): def __init__(self): self.rules = ( # Amazon devices ({'vendor':0x1949}, { 'format_map': ['azw3', 'mobi', 'azw', 'azw1', 'azw4', 'pdf'], 'send_to': ['documents', 'books', 'kindle'], } ), ) def __call__(self, device, driver): if iswindows: vid = pid = 0xffff m = re.search(r'(?i)vid_([0-9a-fA-F]+)&pid_([0-9a-fA-F]+)', device) if m is not None: try: vid, pid = int(m.group(1), 16), int(m.group(2), 16) except: traceback.print_exc() else: vid, pid = device.vendor_id, device.product_id for rule in self.rules: tests = rule[0] matches = True for k, v in tests.iteritems(): if k == 'vendor' and v != vid: matches = False break if k == 'product' and v != pid: matches = False break if matches: return rule[1] return {}
DeviceDefaults
identifier_name
defaults.py
#!/usr/bin/env python # vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:fdm=marker:ai from __future__ import (unicode_literals, division, absolute_import, print_function) __license__ = 'GPL v3' __copyright__ = '2012, Kovid Goyal <kovid at kovidgoyal.net>' __docformat__ = 'restructuredtext en' import traceback, re from calibre.constants import iswindows class DeviceDefaults(object): def __init__(self): self.rules = ( # Amazon devices ({'vendor':0x1949}, { 'format_map': ['azw3', 'mobi', 'azw', 'azw1', 'azw4', 'pdf'], 'send_to': ['documents', 'books', 'kindle'], } ), ) def __call__(self, device, driver): if iswindows: vid = pid = 0xffff m = re.search(r'(?i)vid_([0-9a-fA-F]+)&pid_([0-9a-fA-F]+)', device) if m is not None: try:
for rule in self.rules: tests = rule[0] matches = True for k, v in tests.iteritems(): if k == 'vendor' and v != vid: matches = False break if k == 'product' and v != pid: matches = False break if matches: return rule[1] return {}
vid, pid = int(m.group(1), 16), int(m.group(2), 16) except: traceback.print_exc() else: vid, pid = device.vendor_id, device.product_id
random_line_split
defaults.py
#!/usr/bin/env python # vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:fdm=marker:ai from __future__ import (unicode_literals, division, absolute_import, print_function) __license__ = 'GPL v3' __copyright__ = '2012, Kovid Goyal <kovid at kovidgoyal.net>' __docformat__ = 'restructuredtext en' import traceback, re from calibre.constants import iswindows class DeviceDefaults(object): def __init__(self): self.rules = ( # Amazon devices ({'vendor':0x1949}, { 'format_map': ['azw3', 'mobi', 'azw', 'azw1', 'azw4', 'pdf'], 'send_to': ['documents', 'books', 'kindle'], } ), ) def __call__(self, device, driver): if iswindows: vid = pid = 0xffff m = re.search(r'(?i)vid_([0-9a-fA-F]+)&pid_([0-9a-fA-F]+)', device) if m is not None: try: vid, pid = int(m.group(1), 16), int(m.group(2), 16) except: traceback.print_exc() else: vid, pid = device.vendor_id, device.product_id for rule in self.rules:
return {}
tests = rule[0] matches = True for k, v in tests.iteritems(): if k == 'vendor' and v != vid: matches = False break if k == 'product' and v != pid: matches = False break if matches: return rule[1]
conditional_block
defaults.py
#!/usr/bin/env python # vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:fdm=marker:ai from __future__ import (unicode_literals, division, absolute_import, print_function) __license__ = 'GPL v3' __copyright__ = '2012, Kovid Goyal <kovid at kovidgoyal.net>' __docformat__ = 'restructuredtext en' import traceback, re from calibre.constants import iswindows class DeviceDefaults(object): def __init__(self):
def __call__(self, device, driver): if iswindows: vid = pid = 0xffff m = re.search(r'(?i)vid_([0-9a-fA-F]+)&pid_([0-9a-fA-F]+)', device) if m is not None: try: vid, pid = int(m.group(1), 16), int(m.group(2), 16) except: traceback.print_exc() else: vid, pid = device.vendor_id, device.product_id for rule in self.rules: tests = rule[0] matches = True for k, v in tests.iteritems(): if k == 'vendor' and v != vid: matches = False break if k == 'product' and v != pid: matches = False break if matches: return rule[1] return {}
self.rules = ( # Amazon devices ({'vendor':0x1949}, { 'format_map': ['azw3', 'mobi', 'azw', 'azw1', 'azw4', 'pdf'], 'send_to': ['documents', 'books', 'kindle'], } ), )
identifier_body
elf.py
#!/usr/bin/env python # -*- coding: utf-8 -*-
from elftools.elf.segments import NoteSegment class ReadELF(object): def __init__(self, file): self.elffile = ELFFile(file) def get_build(self): for segment in self.elffile.iter_segments(): if isinstance(segment, NoteSegment): for note in segment.iter_notes(): print note def main(): if(len(sys.argv) < 2): print "Missing argument" sys.exit(1) with open(sys.argv[1], 'rb') as file: try: readelf = ReadELF(file) readelf.get_build() except ELFError as err: sys.stderr.write('ELF error: %s\n' % err) sys.exit(1) if __name__ == '__main__': main()
import sys from elftools.elf.elffile import ELFFile from elftools.common.exceptions import ELFError
random_line_split
elf.py
#!/usr/bin/env python # -*- coding: utf-8 -*- import sys from elftools.elf.elffile import ELFFile from elftools.common.exceptions import ELFError from elftools.elf.segments import NoteSegment class ReadELF(object): def __init__(self, file):
def get_build(self): for segment in self.elffile.iter_segments(): if isinstance(segment, NoteSegment): for note in segment.iter_notes(): print note def main(): if(len(sys.argv) < 2): print "Missing argument" sys.exit(1) with open(sys.argv[1], 'rb') as file: try: readelf = ReadELF(file) readelf.get_build() except ELFError as err: sys.stderr.write('ELF error: %s\n' % err) sys.exit(1) if __name__ == '__main__': main()
self.elffile = ELFFile(file)
identifier_body
elf.py
#!/usr/bin/env python # -*- coding: utf-8 -*- import sys from elftools.elf.elffile import ELFFile from elftools.common.exceptions import ELFError from elftools.elf.segments import NoteSegment class ReadELF(object): def __init__(self, file): self.elffile = ELFFile(file) def
(self): for segment in self.elffile.iter_segments(): if isinstance(segment, NoteSegment): for note in segment.iter_notes(): print note def main(): if(len(sys.argv) < 2): print "Missing argument" sys.exit(1) with open(sys.argv[1], 'rb') as file: try: readelf = ReadELF(file) readelf.get_build() except ELFError as err: sys.stderr.write('ELF error: %s\n' % err) sys.exit(1) if __name__ == '__main__': main()
get_build
identifier_name
elf.py
#!/usr/bin/env python # -*- coding: utf-8 -*- import sys from elftools.elf.elffile import ELFFile from elftools.common.exceptions import ELFError from elftools.elf.segments import NoteSegment class ReadELF(object): def __init__(self, file): self.elffile = ELFFile(file) def get_build(self): for segment in self.elffile.iter_segments(): if isinstance(segment, NoteSegment): for note in segment.iter_notes():
def main(): if(len(sys.argv) < 2): print "Missing argument" sys.exit(1) with open(sys.argv[1], 'rb') as file: try: readelf = ReadELF(file) readelf.get_build() except ELFError as err: sys.stderr.write('ELF error: %s\n' % err) sys.exit(1) if __name__ == '__main__': main()
print note
conditional_block
main.py
# encoding: utf8 from __future__ import print_function import argparse import os import sys import pokedex.cli.search import pokedex.db import pokedex.db.load import pokedex.db.tables import pokedex.lookup from pokedex import defaults def main(junk, *argv): if len(argv) <= 0: command_help() return parser = create_parser() args = parser.parse_args(argv) args.func(parser, args) def setuptools_entry(): main(*sys.argv) def create_parser(): """Build and return an ArgumentParser. """ # Slightly clumsy workaround to make both `setup -v` and `-v setup` work common_parser = argparse.ArgumentParser(add_help=False) common_parser.add_argument( '-e', '--engine', dest='engine_uri', default=None, help=u'By default, all commands try to use a SQLite database ' u'in the pokedex install directory. Use this option (or ' u'a POKEDEX_DB_ENGINE environment variable) to specify an ' u'alternate database.', ) common_parser.add_argument( '-i', '--index', dest='index_dir', default=None, help=u'By default, all commands try to put the lookup index in ' u'the pokedex install directory. Use this option (or a ' u'POKEDEX_INDEX_DIR environment variable) to specify an ' u'alternate loction.', ) common_parser.add_argument( '-q', '--quiet', dest='verbose', action='store_false', help=u'Don\'t print system output. This is the default for ' 'non-system commands and setup.', ) common_parser.add_argument( '-v', '--verbose', dest='verbose', default=False, action='store_true', help=u'Print system output. This is the default for system ' u'commands, except setup.', ) parser = argparse.ArgumentParser( prog='pokedex', description=u'A command-line Pokédex interface', parents=[common_parser], ) cmds = parser.add_subparsers(title='Commands') cmd_help = cmds.add_parser( 'help', help=u'Display this message', parents=[common_parser]) cmd_help.set_defaults(func=command_help) cmd_lookup = cmds.add_parser( 'lookup', help=u'Look up something in the Pokédex', parents=[common_parser]) cmd_lookup.set_defaults(func=command_lookup) cmd_lookup.add_argument('criteria', nargs='+') cmd_search = cmds.add_parser( 'search', help=u'Find things by various criteria', parents=[common_parser]) pokedex.cli.search.configure_parser(cmd_search) cmd_load = cmds.add_parser( 'load', help=u'Load Pokédex data into a database from CSV files', parents=[common_parser]) cmd_load.set_defaults(func=command_load, verbose=True) # TODO get the actual default here cmd_load.add_argument( '-d', '--directory', dest='directory', default=None, help="directory containing the CSV files to load") cmd_load.add_argument( '-D', '--drop-tables', dest='drop_tables', default=False, action='store_true', help="drop all tables before loading data") cmd_load.add_argument( '-r', '--recursive', dest='recursive', default=False, action='store_true', help="load and drop all dependent tables (default is to use exactly the given list)") cmd_load.add_argument( '-S', '--safe', dest='safe', default=False, action='store_true', help="disable database-specific optimizations, such as Postgres's COPY FROM") # TODO need a custom handler for splittin' all of these cmd_load.add_argument( '-l', '--langs', dest='langs', default=None, help="comma-separated list of language codes to load, or 'none' (default: all)") cmd_load.add_argument( 'tables', nargs='*', help="list of database tables to load (default: all)") cmd_dump = cmds.add_parser( 'dump', help=u'Dump Pokédex data from a database into CSV files', parents=[common_parser]) cmd_dump.set_defaults(func=command_dump, verbose=True) cmd_dump.add_argument( '-d', '--directory', dest='directory', default=None, help="directory to place the dumped CSV files") cmd_dump.add_argument( '-l', '--langs', dest='langs', default=None, help="comma-separated list of language codes to load, 'none', or 'all' (default: en)") cmd_dump.add_argument( 'tables', nargs='*', help="list of database tables to load (default: all)") cmd_reindex = cmds.add_parser( 'reindex', help=u'Rebuild the lookup index from the database', parents=[common_parser]) cmd_reindex.set_defaults(func=command_reindex, verbose=True) cmd_setup = cmds.add_parser( 'setup', help=u'Combine load and reindex', parents=[common_parser]) cmd_setup.set_defaults(func=command_setup, verbose=False) cmd_status = cmds.add_parser( 'status', help=u'Print which engine, index, and csv directory would be used for other commands', parents=[common_parser]) cmd_status.set_defaults(func=command_status, verbose=True) return parser def get_session(args): """Given a parsed options object, connects to the database and returns a session. """ engine_uri = args.engine_uri got_from = 'command line' if engine_uri is None: engine_uri, got_from = defaults.get_default_db_uri_with_origin() session = pokedex.db.connect(engine_uri) if args.verbose: print("Connected to database %(engine)s (from %(got_from)s)" % dict(engine=session.bind.url, got_from=got_from)) return session def get_lookup(args, session=None, recreate=False): """Given a parsed options object, opens the whoosh index and returns a PokedexLookup object. """ if recreate and not session: raise ValueError("get_lookup() needs an explicit session to regen the index") index_dir = args.index_dir got_from = 'command line' if index_dir is None: index_dir, got_from = defaults.get_default_index_dir_with_origin() if args.verbose: print("Opened lookup index %(index_dir)s (from %(got_from)s)" % dict(index_dir=index_dir, got_from=got_from)) lookup = pokedex.lookup.PokedexLookup(index_dir, session=session) if recreate: lookup.rebuild_index() return lookup def get_csv_directory(args): """Prints and returns the csv directory we're about to use.""" if not args.verbose: return csvdir = args.directory got_from = 'command line' if csvdir is None: csvdir, got_from = defaults.get_default_csv_dir_with_origin() print("Using CSV directory %(csvdir)s (from %(got_from)s)" % dict(csvdir=csvdir, got_from=got_from)) return csvdir ### Plumbing commands def command_dump(parser, args): session = get_session(args) get_csv_directory(args) if args.langs is not None: langs = [l.strip() for l in args.langs.split(',')] else: langs = None pokedex.db.load.dump( session, directory=args.directory, tables=args.tables, verbose=args.verbose, langs=langs, ) def command_load(parser, args): if not args.engine_uri: print("WARNING: You're reloading the default database, but not the lookup index. They") print(" might get out of sync, and pokedex commands may not work correctly!") print("To fix this, run `pokedex reindex` when this command finishes. Or, just use") print("`pokedex setup` to do both at once.") print() if args.langs == 'none': langs = [] elif args.langs is None: langs = None else: langs = [l.strip() for l in args.langs.split(',')] session = get_session(args) get_csv_directory(args) pokedex.db.load.load( session, directory=args.directory, drop_tables=args.drop_tables, tables=args.tables, verbose=args.verbose, safe=args.safe, recursive=args.recursive, langs=langs, ) def command_reindex(parser, args): session = get_session(args) get_lookup(args, session=session, recreate=True) print("Recreated lookup index.") def command_setup(parser, args): args.directory = None session = get_session(args) get_csv_directory(args) pokedex.db.load.load( session, directory=None, drop_tables=True, verbose=args.verbose, safe=False) get_lookup(args, session=session, recreate=True) print("Recreated lookup index.") def command_status(parser, args): args.directory = None # Database, and a lame check for whether it's been inited at least once session = get_session(args) print(" - OK! Connected successfully.") if pokedex.db.tables.Pokemon.__table__.exists(session.bind): print(" - OK! Database seems to contain some data.") else: print(" - WARNING: Database appears to be empty.") # CSV; simple checks that the dir exists csvdir = get_csv_directory(args) if not os.path.exists(csvdir): print(" - ERROR: No such directory!") elif not os.path.isdir(csvdir): print(" - ERROR: Not a directory!") else: print(" - OK! Directory exists.") if os.access(csvdir, os.R_OK): print(" - OK! Can read from directory.") else: print(" - ERROR: Can't read from directory!") if os.access(csvdir, os.W_OK): print(" - OK! Can write to directory.") else: print(" - WARNING: Can't write to directory! " "`dump` will not work. You may need to sudo.") # Index; the PokedexLookup constructor covers most tests and will # cheerfully bomb if they fail get_lookup(args, recreate=False) print(" - OK! Opened successfully.") ### User-facing commands def command_lookup(parser, args): name
ef command_help(parser, args): parser.print_help() if __name__ == '__main__': main(*sys.argv)
= u' '.join(args.criteria) session = get_session(args) lookup = get_lookup(args, session=session, recreate=False) results = lookup.lookup(name) if not results: print("No matches.") elif results[0].exact: print("Matched:") else: print("Fuzzy-matched:") for result in results: if hasattr(result.object, 'full_name'): name = result.object.full_name else: name = result.object.name print("%s: %s" % (result.object.__tablename__, name), end='') if result.language: print("(%s in %s)" % (result.name, result.language)) else: print() d
identifier_body
main.py
# encoding: utf8 from __future__ import print_function import argparse import os import sys import pokedex.cli.search import pokedex.db import pokedex.db.load import pokedex.db.tables import pokedex.lookup from pokedex import defaults def main(junk, *argv): if len(argv) <= 0: command_help() return parser = create_parser() args = parser.parse_args(argv) args.func(parser, args) def setuptools_entry(): main(*sys.argv) def create_parser(): """Build and return an ArgumentParser. """ # Slightly clumsy workaround to make both `setup -v` and `-v setup` work common_parser = argparse.ArgumentParser(add_help=False) common_parser.add_argument( '-e', '--engine', dest='engine_uri', default=None, help=u'By default, all commands try to use a SQLite database ' u'in the pokedex install directory. Use this option (or ' u'a POKEDEX_DB_ENGINE environment variable) to specify an ' u'alternate database.', ) common_parser.add_argument( '-i', '--index', dest='index_dir', default=None, help=u'By default, all commands try to put the lookup index in ' u'the pokedex install directory. Use this option (or a ' u'POKEDEX_INDEX_DIR environment variable) to specify an ' u'alternate loction.', ) common_parser.add_argument( '-q', '--quiet', dest='verbose', action='store_false', help=u'Don\'t print system output. This is the default for ' 'non-system commands and setup.', ) common_parser.add_argument( '-v', '--verbose', dest='verbose', default=False, action='store_true', help=u'Print system output. This is the default for system ' u'commands, except setup.', ) parser = argparse.ArgumentParser( prog='pokedex', description=u'A command-line Pokédex interface', parents=[common_parser], ) cmds = parser.add_subparsers(title='Commands') cmd_help = cmds.add_parser(
cmd_help.set_defaults(func=command_help) cmd_lookup = cmds.add_parser( 'lookup', help=u'Look up something in the Pokédex', parents=[common_parser]) cmd_lookup.set_defaults(func=command_lookup) cmd_lookup.add_argument('criteria', nargs='+') cmd_search = cmds.add_parser( 'search', help=u'Find things by various criteria', parents=[common_parser]) pokedex.cli.search.configure_parser(cmd_search) cmd_load = cmds.add_parser( 'load', help=u'Load Pokédex data into a database from CSV files', parents=[common_parser]) cmd_load.set_defaults(func=command_load, verbose=True) # TODO get the actual default here cmd_load.add_argument( '-d', '--directory', dest='directory', default=None, help="directory containing the CSV files to load") cmd_load.add_argument( '-D', '--drop-tables', dest='drop_tables', default=False, action='store_true', help="drop all tables before loading data") cmd_load.add_argument( '-r', '--recursive', dest='recursive', default=False, action='store_true', help="load and drop all dependent tables (default is to use exactly the given list)") cmd_load.add_argument( '-S', '--safe', dest='safe', default=False, action='store_true', help="disable database-specific optimizations, such as Postgres's COPY FROM") # TODO need a custom handler for splittin' all of these cmd_load.add_argument( '-l', '--langs', dest='langs', default=None, help="comma-separated list of language codes to load, or 'none' (default: all)") cmd_load.add_argument( 'tables', nargs='*', help="list of database tables to load (default: all)") cmd_dump = cmds.add_parser( 'dump', help=u'Dump Pokédex data from a database into CSV files', parents=[common_parser]) cmd_dump.set_defaults(func=command_dump, verbose=True) cmd_dump.add_argument( '-d', '--directory', dest='directory', default=None, help="directory to place the dumped CSV files") cmd_dump.add_argument( '-l', '--langs', dest='langs', default=None, help="comma-separated list of language codes to load, 'none', or 'all' (default: en)") cmd_dump.add_argument( 'tables', nargs='*', help="list of database tables to load (default: all)") cmd_reindex = cmds.add_parser( 'reindex', help=u'Rebuild the lookup index from the database', parents=[common_parser]) cmd_reindex.set_defaults(func=command_reindex, verbose=True) cmd_setup = cmds.add_parser( 'setup', help=u'Combine load and reindex', parents=[common_parser]) cmd_setup.set_defaults(func=command_setup, verbose=False) cmd_status = cmds.add_parser( 'status', help=u'Print which engine, index, and csv directory would be used for other commands', parents=[common_parser]) cmd_status.set_defaults(func=command_status, verbose=True) return parser def get_session(args): """Given a parsed options object, connects to the database and returns a session. """ engine_uri = args.engine_uri got_from = 'command line' if engine_uri is None: engine_uri, got_from = defaults.get_default_db_uri_with_origin() session = pokedex.db.connect(engine_uri) if args.verbose: print("Connected to database %(engine)s (from %(got_from)s)" % dict(engine=session.bind.url, got_from=got_from)) return session def get_lookup(args, session=None, recreate=False): """Given a parsed options object, opens the whoosh index and returns a PokedexLookup object. """ if recreate and not session: raise ValueError("get_lookup() needs an explicit session to regen the index") index_dir = args.index_dir got_from = 'command line' if index_dir is None: index_dir, got_from = defaults.get_default_index_dir_with_origin() if args.verbose: print("Opened lookup index %(index_dir)s (from %(got_from)s)" % dict(index_dir=index_dir, got_from=got_from)) lookup = pokedex.lookup.PokedexLookup(index_dir, session=session) if recreate: lookup.rebuild_index() return lookup def get_csv_directory(args): """Prints and returns the csv directory we're about to use.""" if not args.verbose: return csvdir = args.directory got_from = 'command line' if csvdir is None: csvdir, got_from = defaults.get_default_csv_dir_with_origin() print("Using CSV directory %(csvdir)s (from %(got_from)s)" % dict(csvdir=csvdir, got_from=got_from)) return csvdir ### Plumbing commands def command_dump(parser, args): session = get_session(args) get_csv_directory(args) if args.langs is not None: langs = [l.strip() for l in args.langs.split(',')] else: langs = None pokedex.db.load.dump( session, directory=args.directory, tables=args.tables, verbose=args.verbose, langs=langs, ) def command_load(parser, args): if not args.engine_uri: print("WARNING: You're reloading the default database, but not the lookup index. They") print(" might get out of sync, and pokedex commands may not work correctly!") print("To fix this, run `pokedex reindex` when this command finishes. Or, just use") print("`pokedex setup` to do both at once.") print() if args.langs == 'none': langs = [] elif args.langs is None: langs = None else: langs = [l.strip() for l in args.langs.split(',')] session = get_session(args) get_csv_directory(args) pokedex.db.load.load( session, directory=args.directory, drop_tables=args.drop_tables, tables=args.tables, verbose=args.verbose, safe=args.safe, recursive=args.recursive, langs=langs, ) def command_reindex(parser, args): session = get_session(args) get_lookup(args, session=session, recreate=True) print("Recreated lookup index.") def command_setup(parser, args): args.directory = None session = get_session(args) get_csv_directory(args) pokedex.db.load.load( session, directory=None, drop_tables=True, verbose=args.verbose, safe=False) get_lookup(args, session=session, recreate=True) print("Recreated lookup index.") def command_status(parser, args): args.directory = None # Database, and a lame check for whether it's been inited at least once session = get_session(args) print(" - OK! Connected successfully.") if pokedex.db.tables.Pokemon.__table__.exists(session.bind): print(" - OK! Database seems to contain some data.") else: print(" - WARNING: Database appears to be empty.") # CSV; simple checks that the dir exists csvdir = get_csv_directory(args) if not os.path.exists(csvdir): print(" - ERROR: No such directory!") elif not os.path.isdir(csvdir): print(" - ERROR: Not a directory!") else: print(" - OK! Directory exists.") if os.access(csvdir, os.R_OK): print(" - OK! Can read from directory.") else: print(" - ERROR: Can't read from directory!") if os.access(csvdir, os.W_OK): print(" - OK! Can write to directory.") else: print(" - WARNING: Can't write to directory! " "`dump` will not work. You may need to sudo.") # Index; the PokedexLookup constructor covers most tests and will # cheerfully bomb if they fail get_lookup(args, recreate=False) print(" - OK! Opened successfully.") ### User-facing commands def command_lookup(parser, args): name = u' '.join(args.criteria) session = get_session(args) lookup = get_lookup(args, session=session, recreate=False) results = lookup.lookup(name) if not results: print("No matches.") elif results[0].exact: print("Matched:") else: print("Fuzzy-matched:") for result in results: if hasattr(result.object, 'full_name'): name = result.object.full_name else: name = result.object.name print("%s: %s" % (result.object.__tablename__, name), end='') if result.language: print("(%s in %s)" % (result.name, result.language)) else: print() def command_help(parser, args): parser.print_help() if __name__ == '__main__': main(*sys.argv)
'help', help=u'Display this message', parents=[common_parser])
random_line_split
main.py
# encoding: utf8 from __future__ import print_function import argparse import os import sys import pokedex.cli.search import pokedex.db import pokedex.db.load import pokedex.db.tables import pokedex.lookup from pokedex import defaults def main(junk, *argv): if len(argv) <= 0: command_help() return parser = create_parser() args = parser.parse_args(argv) args.func(parser, args) def setuptools_entry(): main(*sys.argv) def create_parser(): """Build and return an ArgumentParser. """ # Slightly clumsy workaround to make both `setup -v` and `-v setup` work common_parser = argparse.ArgumentParser(add_help=False) common_parser.add_argument( '-e', '--engine', dest='engine_uri', default=None, help=u'By default, all commands try to use a SQLite database ' u'in the pokedex install directory. Use this option (or ' u'a POKEDEX_DB_ENGINE environment variable) to specify an ' u'alternate database.', ) common_parser.add_argument( '-i', '--index', dest='index_dir', default=None, help=u'By default, all commands try to put the lookup index in ' u'the pokedex install directory. Use this option (or a ' u'POKEDEX_INDEX_DIR environment variable) to specify an ' u'alternate loction.', ) common_parser.add_argument( '-q', '--quiet', dest='verbose', action='store_false', help=u'Don\'t print system output. This is the default for ' 'non-system commands and setup.', ) common_parser.add_argument( '-v', '--verbose', dest='verbose', default=False, action='store_true', help=u'Print system output. This is the default for system ' u'commands, except setup.', ) parser = argparse.ArgumentParser( prog='pokedex', description=u'A command-line Pokédex interface', parents=[common_parser], ) cmds = parser.add_subparsers(title='Commands') cmd_help = cmds.add_parser( 'help', help=u'Display this message', parents=[common_parser]) cmd_help.set_defaults(func=command_help) cmd_lookup = cmds.add_parser( 'lookup', help=u'Look up something in the Pokédex', parents=[common_parser]) cmd_lookup.set_defaults(func=command_lookup) cmd_lookup.add_argument('criteria', nargs='+') cmd_search = cmds.add_parser( 'search', help=u'Find things by various criteria', parents=[common_parser]) pokedex.cli.search.configure_parser(cmd_search) cmd_load = cmds.add_parser( 'load', help=u'Load Pokédex data into a database from CSV files', parents=[common_parser]) cmd_load.set_defaults(func=command_load, verbose=True) # TODO get the actual default here cmd_load.add_argument( '-d', '--directory', dest='directory', default=None, help="directory containing the CSV files to load") cmd_load.add_argument( '-D', '--drop-tables', dest='drop_tables', default=False, action='store_true', help="drop all tables before loading data") cmd_load.add_argument( '-r', '--recursive', dest='recursive', default=False, action='store_true', help="load and drop all dependent tables (default is to use exactly the given list)") cmd_load.add_argument( '-S', '--safe', dest='safe', default=False, action='store_true', help="disable database-specific optimizations, such as Postgres's COPY FROM") # TODO need a custom handler for splittin' all of these cmd_load.add_argument( '-l', '--langs', dest='langs', default=None, help="comma-separated list of language codes to load, or 'none' (default: all)") cmd_load.add_argument( 'tables', nargs='*', help="list of database tables to load (default: all)") cmd_dump = cmds.add_parser( 'dump', help=u'Dump Pokédex data from a database into CSV files', parents=[common_parser]) cmd_dump.set_defaults(func=command_dump, verbose=True) cmd_dump.add_argument( '-d', '--directory', dest='directory', default=None, help="directory to place the dumped CSV files") cmd_dump.add_argument( '-l', '--langs', dest='langs', default=None, help="comma-separated list of language codes to load, 'none', or 'all' (default: en)") cmd_dump.add_argument( 'tables', nargs='*', help="list of database tables to load (default: all)") cmd_reindex = cmds.add_parser( 'reindex', help=u'Rebuild the lookup index from the database', parents=[common_parser]) cmd_reindex.set_defaults(func=command_reindex, verbose=True) cmd_setup = cmds.add_parser( 'setup', help=u'Combine load and reindex', parents=[common_parser]) cmd_setup.set_defaults(func=command_setup, verbose=False) cmd_status = cmds.add_parser( 'status', help=u'Print which engine, index, and csv directory would be used for other commands', parents=[common_parser]) cmd_status.set_defaults(func=command_status, verbose=True) return parser def get_session(args): """Given a parsed options object, connects to the database and returns a session. """ engine_uri = args.engine_uri got_from = 'command line' if engine_uri is None: engine_uri, got_from = defaults.get_default_db_uri_with_origin() session = pokedex.db.connect(engine_uri) if args.verbose: print("Connected to database %(engine)s (from %(got_from)s)" % dict(engine=session.bind.url, got_from=got_from)) return session def get_lookup(args, session=None, recreate=False): """Given a parsed options object, opens the whoosh index and returns a PokedexLookup object. """ if recreate and not session: raise ValueError("get_lookup() needs an explicit session to regen the index") index_dir = args.index_dir got_from = 'command line' if index_dir is None: index_dir, got_from = defaults.get_default_index_dir_with_origin() if args.verbose: print("Opened lookup index %(index_dir)s (from %(got_from)s)" % dict(index_dir=index_dir, got_from=got_from)) lookup = pokedex.lookup.PokedexLookup(index_dir, session=session) if recreate: lookup.rebuild_index() return lookup def get_csv_directory(args): """Prints and returns the csv directory we're about to use.""" if not args.verbose: return csvdir = args.directory got_from = 'command line' if csvdir is None: csvdir, got_from = defaults.get_default_csv_dir_with_origin() print("Using CSV directory %(csvdir)s (from %(got_from)s)" % dict(csvdir=csvdir, got_from=got_from)) return csvdir ### Plumbing commands def command_dump(parser, args): session = get_session(args) get_csv_directory(args) if args.langs is not None: langs = [l.strip() for l in args.langs.split(',')] else: langs = None pokedex.db.load.dump( session, directory=args.directory, tables=args.tables, verbose=args.verbose, langs=langs, ) def command_load(parser, args): if not args.engine_uri: print("WARNING: You're reloading the default database, but not the lookup index. They") print(" might get out of sync, and pokedex commands may not work correctly!") print("To fix this, run `pokedex reindex` when this command finishes. Or, just use") print("`pokedex setup` to do both at once.") print() if args.langs == 'none': langs = [] elif args.langs is None: langs = None else: langs = [l.strip() for l in args.langs.split(',')] session = get_session(args) get_csv_directory(args) pokedex.db.load.load( session, directory=args.directory, drop_tables=args.drop_tables, tables=args.tables, verbose=args.verbose, safe=args.safe, recursive=args.recursive, langs=langs, ) def command_reindex(parser, args): session = get_session(args) get_lookup(args, session=session, recreate=True) print("Recreated lookup index.") def command_setup(parser, args): args.directory = None session = get_session(args) get_csv_directory(args) pokedex.db.load.load( session, directory=None, drop_tables=True, verbose=args.verbose, safe=False) get_lookup(args, session=session, recreate=True) print("Recreated lookup index.") def comm
ser, args): args.directory = None # Database, and a lame check for whether it's been inited at least once session = get_session(args) print(" - OK! Connected successfully.") if pokedex.db.tables.Pokemon.__table__.exists(session.bind): print(" - OK! Database seems to contain some data.") else: print(" - WARNING: Database appears to be empty.") # CSV; simple checks that the dir exists csvdir = get_csv_directory(args) if not os.path.exists(csvdir): print(" - ERROR: No such directory!") elif not os.path.isdir(csvdir): print(" - ERROR: Not a directory!") else: print(" - OK! Directory exists.") if os.access(csvdir, os.R_OK): print(" - OK! Can read from directory.") else: print(" - ERROR: Can't read from directory!") if os.access(csvdir, os.W_OK): print(" - OK! Can write to directory.") else: print(" - WARNING: Can't write to directory! " "`dump` will not work. You may need to sudo.") # Index; the PokedexLookup constructor covers most tests and will # cheerfully bomb if they fail get_lookup(args, recreate=False) print(" - OK! Opened successfully.") ### User-facing commands def command_lookup(parser, args): name = u' '.join(args.criteria) session = get_session(args) lookup = get_lookup(args, session=session, recreate=False) results = lookup.lookup(name) if not results: print("No matches.") elif results[0].exact: print("Matched:") else: print("Fuzzy-matched:") for result in results: if hasattr(result.object, 'full_name'): name = result.object.full_name else: name = result.object.name print("%s: %s" % (result.object.__tablename__, name), end='') if result.language: print("(%s in %s)" % (result.name, result.language)) else: print() def command_help(parser, args): parser.print_help() if __name__ == '__main__': main(*sys.argv)
and_status(par
identifier_name
main.py
# encoding: utf8 from __future__ import print_function import argparse import os import sys import pokedex.cli.search import pokedex.db import pokedex.db.load import pokedex.db.tables import pokedex.lookup from pokedex import defaults def main(junk, *argv): if len(argv) <= 0: command_help() return parser = create_parser() args = parser.parse_args(argv) args.func(parser, args) def setuptools_entry(): main(*sys.argv) def create_parser(): """Build and return an ArgumentParser. """ # Slightly clumsy workaround to make both `setup -v` and `-v setup` work common_parser = argparse.ArgumentParser(add_help=False) common_parser.add_argument( '-e', '--engine', dest='engine_uri', default=None, help=u'By default, all commands try to use a SQLite database ' u'in the pokedex install directory. Use this option (or ' u'a POKEDEX_DB_ENGINE environment variable) to specify an ' u'alternate database.', ) common_parser.add_argument( '-i', '--index', dest='index_dir', default=None, help=u'By default, all commands try to put the lookup index in ' u'the pokedex install directory. Use this option (or a ' u'POKEDEX_INDEX_DIR environment variable) to specify an ' u'alternate loction.', ) common_parser.add_argument( '-q', '--quiet', dest='verbose', action='store_false', help=u'Don\'t print system output. This is the default for ' 'non-system commands and setup.', ) common_parser.add_argument( '-v', '--verbose', dest='verbose', default=False, action='store_true', help=u'Print system output. This is the default for system ' u'commands, except setup.', ) parser = argparse.ArgumentParser( prog='pokedex', description=u'A command-line Pokédex interface', parents=[common_parser], ) cmds = parser.add_subparsers(title='Commands') cmd_help = cmds.add_parser( 'help', help=u'Display this message', parents=[common_parser]) cmd_help.set_defaults(func=command_help) cmd_lookup = cmds.add_parser( 'lookup', help=u'Look up something in the Pokédex', parents=[common_parser]) cmd_lookup.set_defaults(func=command_lookup) cmd_lookup.add_argument('criteria', nargs='+') cmd_search = cmds.add_parser( 'search', help=u'Find things by various criteria', parents=[common_parser]) pokedex.cli.search.configure_parser(cmd_search) cmd_load = cmds.add_parser( 'load', help=u'Load Pokédex data into a database from CSV files', parents=[common_parser]) cmd_load.set_defaults(func=command_load, verbose=True) # TODO get the actual default here cmd_load.add_argument( '-d', '--directory', dest='directory', default=None, help="directory containing the CSV files to load") cmd_load.add_argument( '-D', '--drop-tables', dest='drop_tables', default=False, action='store_true', help="drop all tables before loading data") cmd_load.add_argument( '-r', '--recursive', dest='recursive', default=False, action='store_true', help="load and drop all dependent tables (default is to use exactly the given list)") cmd_load.add_argument( '-S', '--safe', dest='safe', default=False, action='store_true', help="disable database-specific optimizations, such as Postgres's COPY FROM") # TODO need a custom handler for splittin' all of these cmd_load.add_argument( '-l', '--langs', dest='langs', default=None, help="comma-separated list of language codes to load, or 'none' (default: all)") cmd_load.add_argument( 'tables', nargs='*', help="list of database tables to load (default: all)") cmd_dump = cmds.add_parser( 'dump', help=u'Dump Pokédex data from a database into CSV files', parents=[common_parser]) cmd_dump.set_defaults(func=command_dump, verbose=True) cmd_dump.add_argument( '-d', '--directory', dest='directory', default=None, help="directory to place the dumped CSV files") cmd_dump.add_argument( '-l', '--langs', dest='langs', default=None, help="comma-separated list of language codes to load, 'none', or 'all' (default: en)") cmd_dump.add_argument( 'tables', nargs='*', help="list of database tables to load (default: all)") cmd_reindex = cmds.add_parser( 'reindex', help=u'Rebuild the lookup index from the database', parents=[common_parser]) cmd_reindex.set_defaults(func=command_reindex, verbose=True) cmd_setup = cmds.add_parser( 'setup', help=u'Combine load and reindex', parents=[common_parser]) cmd_setup.set_defaults(func=command_setup, verbose=False) cmd_status = cmds.add_parser( 'status', help=u'Print which engine, index, and csv directory would be used for other commands', parents=[common_parser]) cmd_status.set_defaults(func=command_status, verbose=True) return parser def get_session(args): """Given a parsed options object, connects to the database and returns a session. """ engine_uri = args.engine_uri got_from = 'command line' if engine_uri is None: engine_uri, got_from = defaults.get_default_db_uri_with_origin() session = pokedex.db.connect(engine_uri) if args.verbose: print("Connected to database %(engine)s (from %(got_from)s)" % dict(engine=session.bind.url, got_from=got_from)) return session def get_lookup(args, session=None, recreate=False): """Given a parsed options object, opens the whoosh index and returns a PokedexLookup object. """ if recreate and not session: raise ValueError("get_lookup() needs an explicit session to regen the index") index_dir = args.index_dir got_from = 'command line' if index_dir is None: index_dir, got_from = defaults.get_default_index_dir_with_origin() if args.verbose: print("Opened lookup index %(index_dir)s (from %(got_from)s)" % dict(index_dir=index_dir, got_from=got_from)) lookup = pokedex.lookup.PokedexLookup(index_dir, session=session) if recreate: lookup.rebuild_index() return lookup def get_csv_directory(args): """Prints and returns the csv directory we're about to use.""" if not args.verbose: return csvdir = args.directory got_from = 'command line' if csvdir is None: csvdir, got_from = defaults.get_default_csv_dir_with_origin() print("Using CSV directory %(csvdir)s (from %(got_from)s)" % dict(csvdir=csvdir, got_from=got_from)) return csvdir ### Plumbing commands def command_dump(parser, args): session = get_session(args) get_csv_directory(args) if args.langs is not None: langs = [l.strip() for l in args.langs.split(',')] else: langs = None pokedex.db.load.dump( session, directory=args.directory, tables=args.tables, verbose=args.verbose, langs=langs, ) def command_load(parser, args): if not args.engine_uri: prin
if args.langs == 'none': langs = [] elif args.langs is None: langs = None else: langs = [l.strip() for l in args.langs.split(',')] session = get_session(args) get_csv_directory(args) pokedex.db.load.load( session, directory=args.directory, drop_tables=args.drop_tables, tables=args.tables, verbose=args.verbose, safe=args.safe, recursive=args.recursive, langs=langs, ) def command_reindex(parser, args): session = get_session(args) get_lookup(args, session=session, recreate=True) print("Recreated lookup index.") def command_setup(parser, args): args.directory = None session = get_session(args) get_csv_directory(args) pokedex.db.load.load( session, directory=None, drop_tables=True, verbose=args.verbose, safe=False) get_lookup(args, session=session, recreate=True) print("Recreated lookup index.") def command_status(parser, args): args.directory = None # Database, and a lame check for whether it's been inited at least once session = get_session(args) print(" - OK! Connected successfully.") if pokedex.db.tables.Pokemon.__table__.exists(session.bind): print(" - OK! Database seems to contain some data.") else: print(" - WARNING: Database appears to be empty.") # CSV; simple checks that the dir exists csvdir = get_csv_directory(args) if not os.path.exists(csvdir): print(" - ERROR: No such directory!") elif not os.path.isdir(csvdir): print(" - ERROR: Not a directory!") else: print(" - OK! Directory exists.") if os.access(csvdir, os.R_OK): print(" - OK! Can read from directory.") else: print(" - ERROR: Can't read from directory!") if os.access(csvdir, os.W_OK): print(" - OK! Can write to directory.") else: print(" - WARNING: Can't write to directory! " "`dump` will not work. You may need to sudo.") # Index; the PokedexLookup constructor covers most tests and will # cheerfully bomb if they fail get_lookup(args, recreate=False) print(" - OK! Opened successfully.") ### User-facing commands def command_lookup(parser, args): name = u' '.join(args.criteria) session = get_session(args) lookup = get_lookup(args, session=session, recreate=False) results = lookup.lookup(name) if not results: print("No matches.") elif results[0].exact: print("Matched:") else: print("Fuzzy-matched:") for result in results: if hasattr(result.object, 'full_name'): name = result.object.full_name else: name = result.object.name print("%s: %s" % (result.object.__tablename__, name), end='') if result.language: print("(%s in %s)" % (result.name, result.language)) else: print() def command_help(parser, args): parser.print_help() if __name__ == '__main__': main(*sys.argv)
t("WARNING: You're reloading the default database, but not the lookup index. They") print(" might get out of sync, and pokedex commands may not work correctly!") print("To fix this, run `pokedex reindex` when this command finishes. Or, just use") print("`pokedex setup` to do both at once.") print()
conditional_block
flatxml2po.py
# -*- coding: utf-8 -*- # # Copyright 2018 BhaaL # # This file is part of translate. # # translate 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. # # translate 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 this program; if not, see <http://www.gnu.org/licenses/>. """Convert flat XML files to Gettext PO localization files. See: http://docs.translatehouse.org/projects/translate-toolkit/en/latest/commands/flatxml2po.html for examples and usage instructions. """ from translate.convert import convert from translate.storage import flatxml, po class flatxml2po:
def run_converter(inputfile, outputfile, templatefile=None, root="root", value="str", key="key", ns=None): """Wrapper around the converter.""" return flatxml2po(inputfile, outputfile, templatefile, root, value, key, ns).run() formats = { "xml": ("po", run_converter), } def main(argv=None): parser = convert.ConvertOptionParser(formats, description=__doc__) parser.add_option("-r", "--root", action="store", dest="root", default="root", help='name of the XML root element (default: "root")') parser.add_option("-v", "--value", action="store", dest="value", default="str", help='name of the XML value element (default: "str")') parser.add_option("-k", "--key", action="store", dest="key", default="key", help='name of the XML key attribute (default: "key")') parser.add_option("-n", "--namespace", action="store", dest="ns", default=None, help="XML namespace uri (default: None)") parser.passthrough.append("root") parser.passthrough.append("value") parser.passthrough.append("key") parser.passthrough.append("ns") parser.run(argv) if __name__ == "__main__": main()
"""Convert a single XML file to a single PO file.""" SourceStoreClass = flatxml.FlatXMLFile TargetStoreClass = po.pofile TargetUnitClass = po.pounit def __init__(self, inputfile, outputfile, templatefile=None, root="root", value="str", key="key", ns=None): """Initialize the converter.""" self.inputfile = inputfile self.outputfile = outputfile self.source_store = self.SourceStoreClass(inputfile, root_name=root, value_name=value, key_name=key, namespace=ns) self.target_store = self.TargetStoreClass() def convert_unit(self, unit): """Convert a source format unit to a target format unit.""" target_unit = self.TargetUnitClass.buildfromunit(unit) return target_unit def convert_store(self): """Convert a single source file to a target format file.""" for source_unit in self.source_store.units: self.target_store.addunit(self.convert_unit(source_unit)) def run(self): """Run the converter.""" self.convert_store() if self.target_store.isempty(): return 0 self.target_store.serialize(self.outputfile) return 1
identifier_body
flatxml2po.py
# -*- coding: utf-8 -*- # # Copyright 2018 BhaaL # # This file is part of translate. # # translate 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. # # translate 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 this program; if not, see <http://www.gnu.org/licenses/>. """Convert flat XML files to Gettext PO localization files. See: http://docs.translatehouse.org/projects/translate-toolkit/en/latest/commands/flatxml2po.html for examples and usage instructions. """ from translate.convert import convert from translate.storage import flatxml, po class
: """Convert a single XML file to a single PO file.""" SourceStoreClass = flatxml.FlatXMLFile TargetStoreClass = po.pofile TargetUnitClass = po.pounit def __init__(self, inputfile, outputfile, templatefile=None, root="root", value="str", key="key", ns=None): """Initialize the converter.""" self.inputfile = inputfile self.outputfile = outputfile self.source_store = self.SourceStoreClass(inputfile, root_name=root, value_name=value, key_name=key, namespace=ns) self.target_store = self.TargetStoreClass() def convert_unit(self, unit): """Convert a source format unit to a target format unit.""" target_unit = self.TargetUnitClass.buildfromunit(unit) return target_unit def convert_store(self): """Convert a single source file to a target format file.""" for source_unit in self.source_store.units: self.target_store.addunit(self.convert_unit(source_unit)) def run(self): """Run the converter.""" self.convert_store() if self.target_store.isempty(): return 0 self.target_store.serialize(self.outputfile) return 1 def run_converter(inputfile, outputfile, templatefile=None, root="root", value="str", key="key", ns=None): """Wrapper around the converter.""" return flatxml2po(inputfile, outputfile, templatefile, root, value, key, ns).run() formats = { "xml": ("po", run_converter), } def main(argv=None): parser = convert.ConvertOptionParser(formats, description=__doc__) parser.add_option("-r", "--root", action="store", dest="root", default="root", help='name of the XML root element (default: "root")') parser.add_option("-v", "--value", action="store", dest="value", default="str", help='name of the XML value element (default: "str")') parser.add_option("-k", "--key", action="store", dest="key", default="key", help='name of the XML key attribute (default: "key")') parser.add_option("-n", "--namespace", action="store", dest="ns", default=None, help="XML namespace uri (default: None)") parser.passthrough.append("root") parser.passthrough.append("value") parser.passthrough.append("key") parser.passthrough.append("ns") parser.run(argv) if __name__ == "__main__": main()
flatxml2po
identifier_name
flatxml2po.py
# -*- coding: utf-8 -*- # # Copyright 2018 BhaaL # # This file is part of translate. # # translate 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. # # translate 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 this program; if not, see <http://www.gnu.org/licenses/>. """Convert flat XML files to Gettext PO localization files. See: http://docs.translatehouse.org/projects/translate-toolkit/en/latest/commands/flatxml2po.html for examples and usage instructions. """ from translate.convert import convert from translate.storage import flatxml, po class flatxml2po: """Convert a single XML file to a single PO file.""" SourceStoreClass = flatxml.FlatXMLFile TargetStoreClass = po.pofile TargetUnitClass = po.pounit def __init__(self, inputfile, outputfile, templatefile=None, root="root", value="str", key="key", ns=None): """Initialize the converter.""" self.inputfile = inputfile self.outputfile = outputfile self.source_store = self.SourceStoreClass(inputfile, root_name=root, value_name=value, key_name=key, namespace=ns) self.target_store = self.TargetStoreClass() def convert_unit(self, unit): """Convert a source format unit to a target format unit.""" target_unit = self.TargetUnitClass.buildfromunit(unit) return target_unit def convert_store(self): """Convert a single source file to a target format file.""" for source_unit in self.source_store.units: self.target_store.addunit(self.convert_unit(source_unit)) def run(self): """Run the converter.""" self.convert_store() if self.target_store.isempty(): return 0 self.target_store.serialize(self.outputfile) return 1 def run_converter(inputfile, outputfile, templatefile=None, root="root", value="str", key="key", ns=None): """Wrapper around the converter.""" return flatxml2po(inputfile, outputfile, templatefile, root, value, key, ns).run() formats = { "xml": ("po", run_converter), } def main(argv=None): parser = convert.ConvertOptionParser(formats, description=__doc__) parser.add_option("-r", "--root", action="store", dest="root", default="root",
default="key", help='name of the XML key attribute (default: "key")') parser.add_option("-n", "--namespace", action="store", dest="ns", default=None, help="XML namespace uri (default: None)") parser.passthrough.append("root") parser.passthrough.append("value") parser.passthrough.append("key") parser.passthrough.append("ns") parser.run(argv) if __name__ == "__main__": main()
help='name of the XML root element (default: "root")') parser.add_option("-v", "--value", action="store", dest="value", default="str", help='name of the XML value element (default: "str")') parser.add_option("-k", "--key", action="store", dest="key",
random_line_split
flatxml2po.py
# -*- coding: utf-8 -*- # # Copyright 2018 BhaaL # # This file is part of translate. # # translate 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. # # translate 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 this program; if not, see <http://www.gnu.org/licenses/>. """Convert flat XML files to Gettext PO localization files. See: http://docs.translatehouse.org/projects/translate-toolkit/en/latest/commands/flatxml2po.html for examples and usage instructions. """ from translate.convert import convert from translate.storage import flatxml, po class flatxml2po: """Convert a single XML file to a single PO file.""" SourceStoreClass = flatxml.FlatXMLFile TargetStoreClass = po.pofile TargetUnitClass = po.pounit def __init__(self, inputfile, outputfile, templatefile=None, root="root", value="str", key="key", ns=None): """Initialize the converter.""" self.inputfile = inputfile self.outputfile = outputfile self.source_store = self.SourceStoreClass(inputfile, root_name=root, value_name=value, key_name=key, namespace=ns) self.target_store = self.TargetStoreClass() def convert_unit(self, unit): """Convert a source format unit to a target format unit.""" target_unit = self.TargetUnitClass.buildfromunit(unit) return target_unit def convert_store(self): """Convert a single source file to a target format file.""" for source_unit in self.source_store.units:
def run(self): """Run the converter.""" self.convert_store() if self.target_store.isempty(): return 0 self.target_store.serialize(self.outputfile) return 1 def run_converter(inputfile, outputfile, templatefile=None, root="root", value="str", key="key", ns=None): """Wrapper around the converter.""" return flatxml2po(inputfile, outputfile, templatefile, root, value, key, ns).run() formats = { "xml": ("po", run_converter), } def main(argv=None): parser = convert.ConvertOptionParser(formats, description=__doc__) parser.add_option("-r", "--root", action="store", dest="root", default="root", help='name of the XML root element (default: "root")') parser.add_option("-v", "--value", action="store", dest="value", default="str", help='name of the XML value element (default: "str")') parser.add_option("-k", "--key", action="store", dest="key", default="key", help='name of the XML key attribute (default: "key")') parser.add_option("-n", "--namespace", action="store", dest="ns", default=None, help="XML namespace uri (default: None)") parser.passthrough.append("root") parser.passthrough.append("value") parser.passthrough.append("key") parser.passthrough.append("ns") parser.run(argv) if __name__ == "__main__": main()
self.target_store.addunit(self.convert_unit(source_unit))
conditional_block
InfiniteScrollNewsArticle.tsx
import { data as sd } from "sharify" import { getENV } from "v2/Utils/getENV" import moment from "moment" import styled from "styled-components" import React, { Component, Fragment } from "react" import { flatten, throttle } from "lodash" import Waypoint from "react-waypoint" import { positronql } from "desktop/lib/positronql" import { newsArticlesQuery } from "desktop/apps/article/queries/articles" import { ArticleData, RelatedArticleCanvasData, } from "@artsy/reaction/dist/Components/Publishing/Typings" import { NewsNav } from "@artsy/reaction/dist/Components/Publishing/Nav/NewsNav" import { LoadingSpinner } from "./InfiniteScrollArticle" import { NewsArticle } from "./NewsArticle" import { NewsDateDivider } from "@artsy/reaction/dist/Components/Publishing/News/NewsDateDivider" const Cookies = require("desktop/components/cookies/index.coffee") import { shouldAdRender } from "desktop/apps/article/helpers" import { handleScrollingAuthModal } from "desktop/lib/openAuthModal" import { ContextModule, Intent } from "@artsy/cohesion" export interface Props { article?: ArticleData articles: ArticleData[] isMobile?: boolean isEigen?: boolean shouldAdRender?: boolean } interface State { activeArticle: string articles: ArticleData[] date: string error: boolean isEnabled: boolean isLoading: boolean offset: number omit: string relatedArticles: RelatedArticleCanvasData[] } export class InfiniteScrollNewsArticle extends Component<Props, State> { private throttledDateChange
(props) { super(props) const article = props.articles[0] || {} const date = this.getDateField(article) const omit = props.article ? props.article.id : null const offset = props.article ? 0 : 6 this.throttledDateChange = throttle(this.onDateChange, 50) this.state = { activeArticle: "", articles: props.articles, date, error: false, isEnabled: true, isLoading: false, offset, omit, relatedArticles: [], } } componentDidMount() { const editorialAuthDismissedCookie = Cookies.get( "editorial-signup-dismissed" ) if ( !sd.CURRENT_USER && !editorialAuthDismissedCookie && !this.props.isMobile ) { this.showAuthModal() } } dismissAuthModal() { Cookies.set("editorial-signup-dismissed", 1, { expires: 864000 }) } fetchNextArticles = async () => { const { articles, offset, omit, relatedArticles } = this.state this.setState({ isLoading: true, }) try { const data = await positronql({ query: newsArticlesQuery({ offset, limit: 6, omit, }), }) const newArticles = data.articles const newRelatedArticles = [data.relatedArticlesCanvas] if (newArticles.length) { this.setState({ articles: articles.concat(newArticles), relatedArticles: relatedArticles.concat(newRelatedArticles), isLoading: false, offset: offset + 6, }) } else { this.setState({ isEnabled: false, isLoading: false, }) } } catch (error) { console.error( "(apps/article/InfiniteScrollNewsArticle) Error fetching next article set: ", error ) this.setState({ isEnabled: false, isLoading: false, error: true, }) } } renderWaypoint = () => { const { isLoading, error } = this.state const isGooglebot = getENV("IS_GOOGLEBOT") const isEnabled = !isGooglebot && this.state.isEnabled if (isEnabled) { if (!isLoading) { return ( <Waypoint data-test="news" onEnter={this.fetchNextArticles} bottomOffset="-50%" /> ) } else if (!error) { return ( <LoadingSpinner> <div className="loading-spinner" /> </LoadingSpinner> ) } } } onDateChange = date => { const hasNewDate = !moment(date).isSame(this.state.date, "day") if (hasNewDate) { // Commenting this out as we're noticing that when a user is scrolling // and the top date is updated, it leads to a reset of the current scroll // position, preventing the user from scrolling down the page. // FIXME: Reenable once newsfeed scrolling bug tracked down. this.setState({ date }) } } onActiveArticleChange = id => { this.setState({ activeArticle: id }) } hasNewDate = (article, i) => { const { articles } = this.state const beforeArticle = articles[i - 1] || {} const beforeDate = this.getDateField(beforeArticle).substring(0, 10) const currentDate = this.getDateField(article).substring(0, 10) return beforeDate !== currentDate } getDateField = article => { const { published_at, scheduled_publish_at } = article return published_at || scheduled_publish_at || moment().toISOString() } renderContent = () => { const { activeArticle, articles, relatedArticles } = this.state const { isMobile } = this.props let counter = 0 return flatten( articles.map((article, i) => { const hasMetaContent = i % 6 === 0 && i !== 0 const related = relatedArticles[counter] if (hasMetaContent) { counter++ } const isTruncated = !this.props.article || i !== 0 const hasDateDivider = i !== 0 && this.hasNewDate(article, i) const relatedArticlesCanvas = hasMetaContent && related const { isEigen } = this.props // render ads on News Landing the 3rd and then every 6 news articles thereafter const adPosition = { index: i + 1, // article index + 1 startIndex: 3, // render first ad after 3rd article frequency: 6, // render subsequent ads after 6th article } const renderAd = shouldAdRender( adPosition.index, adPosition.startIndex, adPosition.frequency, null, isEigen ) return ( <Fragment key={`article-${i}`}> {hasDateDivider && <NewsDateDivider date={article.published_at} />} <NewsArticle isMobile={isMobile || false} isEigen={isEigen} article={article} isTruncated={isTruncated} onDateChange={this.throttledDateChange} nextArticle={articles[i + 1] as any} onActiveArticleChange={id => this.onActiveArticleChange(id)} isActive={activeArticle === article.id} relatedArticlesForCanvas={relatedArticlesCanvas as any} shouldAdRender={renderAd} articleSerial={adPosition.index} /> </Fragment> ) }) ) } showAuthModal() { handleScrollingAuthModal({ intent: Intent.viewEditorial, copy: "Sign up for the best stories in art and visual culture", destination: location.href, afterSignUpAction: { action: "editorialSignup", }, contextModule: ContextModule.popUpModal, }) } render() { const { isEigen, isMobile } = this.props const { date } = this.state return ( <NewsContainer isEigen={isEigen || false} isMobile={isMobile || false} id="article-root" > {!isEigen && <NewsNav date={date} positionTop={56} />} {this.renderContent()} {this.renderWaypoint()} </NewsContainer> ) } } const NewsContainer = styled.div<{ isMobile: boolean; isEigen: boolean }>` margin-top: ${props => props.isEigen ? "0" : props.isMobile ? "100" : "200"}px; `
constructor
identifier_name
InfiniteScrollNewsArticle.tsx
import { data as sd } from "sharify" import { getENV } from "v2/Utils/getENV" import moment from "moment" import styled from "styled-components" import React, { Component, Fragment } from "react" import { flatten, throttle } from "lodash" import Waypoint from "react-waypoint" import { positronql } from "desktop/lib/positronql" import { newsArticlesQuery } from "desktop/apps/article/queries/articles" import { ArticleData, RelatedArticleCanvasData, } from "@artsy/reaction/dist/Components/Publishing/Typings" import { NewsNav } from "@artsy/reaction/dist/Components/Publishing/Nav/NewsNav" import { LoadingSpinner } from "./InfiniteScrollArticle" import { NewsArticle } from "./NewsArticle" import { NewsDateDivider } from "@artsy/reaction/dist/Components/Publishing/News/NewsDateDivider" const Cookies = require("desktop/components/cookies/index.coffee") import { shouldAdRender } from "desktop/apps/article/helpers" import { handleScrollingAuthModal } from "desktop/lib/openAuthModal" import { ContextModule, Intent } from "@artsy/cohesion" export interface Props { article?: ArticleData articles: ArticleData[] isMobile?: boolean isEigen?: boolean shouldAdRender?: boolean } interface State { activeArticle: string articles: ArticleData[] date: string error: boolean isEnabled: boolean isLoading: boolean offset: number omit: string relatedArticles: RelatedArticleCanvasData[] } export class InfiniteScrollNewsArticle extends Component<Props, State> { private throttledDateChange constructor(props) { super(props) const article = props.articles[0] || {} const date = this.getDateField(article) const omit = props.article ? props.article.id : null const offset = props.article ? 0 : 6 this.throttledDateChange = throttle(this.onDateChange, 50) this.state = { activeArticle: "", articles: props.articles, date, error: false, isEnabled: true, isLoading: false, offset, omit, relatedArticles: [], } } componentDidMount() { const editorialAuthDismissedCookie = Cookies.get( "editorial-signup-dismissed" ) if ( !sd.CURRENT_USER && !editorialAuthDismissedCookie && !this.props.isMobile ) { this.showAuthModal() } } dismissAuthModal() { Cookies.set("editorial-signup-dismissed", 1, { expires: 864000 }) } fetchNextArticles = async () => { const { articles, offset, omit, relatedArticles } = this.state this.setState({ isLoading: true, }) try { const data = await positronql({ query: newsArticlesQuery({ offset, limit: 6, omit, }), }) const newArticles = data.articles const newRelatedArticles = [data.relatedArticlesCanvas] if (newArticles.length) { this.setState({ articles: articles.concat(newArticles), relatedArticles: relatedArticles.concat(newRelatedArticles), isLoading: false, offset: offset + 6, }) } else { this.setState({ isEnabled: false, isLoading: false, }) } } catch (error) { console.error( "(apps/article/InfiniteScrollNewsArticle) Error fetching next article set: ", error ) this.setState({ isEnabled: false, isLoading: false, error: true, }) } } renderWaypoint = () => { const { isLoading, error } = this.state const isGooglebot = getENV("IS_GOOGLEBOT") const isEnabled = !isGooglebot && this.state.isEnabled if (isEnabled) { if (!isLoading) { return ( <Waypoint data-test="news" onEnter={this.fetchNextArticles} bottomOffset="-50%" /> ) } else if (!error) { return ( <LoadingSpinner> <div className="loading-spinner" /> </LoadingSpinner> ) } } } onDateChange = date => { const hasNewDate = !moment(date).isSame(this.state.date, "day") if (hasNewDate) { // Commenting this out as we're noticing that when a user is scrolling // and the top date is updated, it leads to a reset of the current scroll // position, preventing the user from scrolling down the page. // FIXME: Reenable once newsfeed scrolling bug tracked down. this.setState({ date }) } } onActiveArticleChange = id => { this.setState({ activeArticle: id }) } hasNewDate = (article, i) => { const { articles } = this.state const beforeArticle = articles[i - 1] || {} const beforeDate = this.getDateField(beforeArticle).substring(0, 10)
const currentDate = this.getDateField(article).substring(0, 10) return beforeDate !== currentDate } getDateField = article => { const { published_at, scheduled_publish_at } = article return published_at || scheduled_publish_at || moment().toISOString() } renderContent = () => { const { activeArticle, articles, relatedArticles } = this.state const { isMobile } = this.props let counter = 0 return flatten( articles.map((article, i) => { const hasMetaContent = i % 6 === 0 && i !== 0 const related = relatedArticles[counter] if (hasMetaContent) { counter++ } const isTruncated = !this.props.article || i !== 0 const hasDateDivider = i !== 0 && this.hasNewDate(article, i) const relatedArticlesCanvas = hasMetaContent && related const { isEigen } = this.props // render ads on News Landing the 3rd and then every 6 news articles thereafter const adPosition = { index: i + 1, // article index + 1 startIndex: 3, // render first ad after 3rd article frequency: 6, // render subsequent ads after 6th article } const renderAd = shouldAdRender( adPosition.index, adPosition.startIndex, adPosition.frequency, null, isEigen ) return ( <Fragment key={`article-${i}`}> {hasDateDivider && <NewsDateDivider date={article.published_at} />} <NewsArticle isMobile={isMobile || false} isEigen={isEigen} article={article} isTruncated={isTruncated} onDateChange={this.throttledDateChange} nextArticle={articles[i + 1] as any} onActiveArticleChange={id => this.onActiveArticleChange(id)} isActive={activeArticle === article.id} relatedArticlesForCanvas={relatedArticlesCanvas as any} shouldAdRender={renderAd} articleSerial={adPosition.index} /> </Fragment> ) }) ) } showAuthModal() { handleScrollingAuthModal({ intent: Intent.viewEditorial, copy: "Sign up for the best stories in art and visual culture", destination: location.href, afterSignUpAction: { action: "editorialSignup", }, contextModule: ContextModule.popUpModal, }) } render() { const { isEigen, isMobile } = this.props const { date } = this.state return ( <NewsContainer isEigen={isEigen || false} isMobile={isMobile || false} id="article-root" > {!isEigen && <NewsNav date={date} positionTop={56} />} {this.renderContent()} {this.renderWaypoint()} </NewsContainer> ) } } const NewsContainer = styled.div<{ isMobile: boolean; isEigen: boolean }>` margin-top: ${props => props.isEigen ? "0" : props.isMobile ? "100" : "200"}px; `
random_line_split
InfiniteScrollNewsArticle.tsx
import { data as sd } from "sharify" import { getENV } from "v2/Utils/getENV" import moment from "moment" import styled from "styled-components" import React, { Component, Fragment } from "react" import { flatten, throttle } from "lodash" import Waypoint from "react-waypoint" import { positronql } from "desktop/lib/positronql" import { newsArticlesQuery } from "desktop/apps/article/queries/articles" import { ArticleData, RelatedArticleCanvasData, } from "@artsy/reaction/dist/Components/Publishing/Typings" import { NewsNav } from "@artsy/reaction/dist/Components/Publishing/Nav/NewsNav" import { LoadingSpinner } from "./InfiniteScrollArticle" import { NewsArticle } from "./NewsArticle" import { NewsDateDivider } from "@artsy/reaction/dist/Components/Publishing/News/NewsDateDivider" const Cookies = require("desktop/components/cookies/index.coffee") import { shouldAdRender } from "desktop/apps/article/helpers" import { handleScrollingAuthModal } from "desktop/lib/openAuthModal" import { ContextModule, Intent } from "@artsy/cohesion" export interface Props { article?: ArticleData articles: ArticleData[] isMobile?: boolean isEigen?: boolean shouldAdRender?: boolean } interface State { activeArticle: string articles: ArticleData[] date: string error: boolean isEnabled: boolean isLoading: boolean offset: number omit: string relatedArticles: RelatedArticleCanvasData[] } export class InfiniteScrollNewsArticle extends Component<Props, State> { private throttledDateChange constructor(props) { super(props) const article = props.articles[0] || {} const date = this.getDateField(article) const omit = props.article ? props.article.id : null const offset = props.article ? 0 : 6 this.throttledDateChange = throttle(this.onDateChange, 50) this.state = { activeArticle: "", articles: props.articles, date, error: false, isEnabled: true, isLoading: false, offset, omit, relatedArticles: [], } } componentDidMount()
dismissAuthModal() { Cookies.set("editorial-signup-dismissed", 1, { expires: 864000 }) } fetchNextArticles = async () => { const { articles, offset, omit, relatedArticles } = this.state this.setState({ isLoading: true, }) try { const data = await positronql({ query: newsArticlesQuery({ offset, limit: 6, omit, }), }) const newArticles = data.articles const newRelatedArticles = [data.relatedArticlesCanvas] if (newArticles.length) { this.setState({ articles: articles.concat(newArticles), relatedArticles: relatedArticles.concat(newRelatedArticles), isLoading: false, offset: offset + 6, }) } else { this.setState({ isEnabled: false, isLoading: false, }) } } catch (error) { console.error( "(apps/article/InfiniteScrollNewsArticle) Error fetching next article set: ", error ) this.setState({ isEnabled: false, isLoading: false, error: true, }) } } renderWaypoint = () => { const { isLoading, error } = this.state const isGooglebot = getENV("IS_GOOGLEBOT") const isEnabled = !isGooglebot && this.state.isEnabled if (isEnabled) { if (!isLoading) { return ( <Waypoint data-test="news" onEnter={this.fetchNextArticles} bottomOffset="-50%" /> ) } else if (!error) { return ( <LoadingSpinner> <div className="loading-spinner" /> </LoadingSpinner> ) } } } onDateChange = date => { const hasNewDate = !moment(date).isSame(this.state.date, "day") if (hasNewDate) { // Commenting this out as we're noticing that when a user is scrolling // and the top date is updated, it leads to a reset of the current scroll // position, preventing the user from scrolling down the page. // FIXME: Reenable once newsfeed scrolling bug tracked down. this.setState({ date }) } } onActiveArticleChange = id => { this.setState({ activeArticle: id }) } hasNewDate = (article, i) => { const { articles } = this.state const beforeArticle = articles[i - 1] || {} const beforeDate = this.getDateField(beforeArticle).substring(0, 10) const currentDate = this.getDateField(article).substring(0, 10) return beforeDate !== currentDate } getDateField = article => { const { published_at, scheduled_publish_at } = article return published_at || scheduled_publish_at || moment().toISOString() } renderContent = () => { const { activeArticle, articles, relatedArticles } = this.state const { isMobile } = this.props let counter = 0 return flatten( articles.map((article, i) => { const hasMetaContent = i % 6 === 0 && i !== 0 const related = relatedArticles[counter] if (hasMetaContent) { counter++ } const isTruncated = !this.props.article || i !== 0 const hasDateDivider = i !== 0 && this.hasNewDate(article, i) const relatedArticlesCanvas = hasMetaContent && related const { isEigen } = this.props // render ads on News Landing the 3rd and then every 6 news articles thereafter const adPosition = { index: i + 1, // article index + 1 startIndex: 3, // render first ad after 3rd article frequency: 6, // render subsequent ads after 6th article } const renderAd = shouldAdRender( adPosition.index, adPosition.startIndex, adPosition.frequency, null, isEigen ) return ( <Fragment key={`article-${i}`}> {hasDateDivider && <NewsDateDivider date={article.published_at} />} <NewsArticle isMobile={isMobile || false} isEigen={isEigen} article={article} isTruncated={isTruncated} onDateChange={this.throttledDateChange} nextArticle={articles[i + 1] as any} onActiveArticleChange={id => this.onActiveArticleChange(id)} isActive={activeArticle === article.id} relatedArticlesForCanvas={relatedArticlesCanvas as any} shouldAdRender={renderAd} articleSerial={adPosition.index} /> </Fragment> ) }) ) } showAuthModal() { handleScrollingAuthModal({ intent: Intent.viewEditorial, copy: "Sign up for the best stories in art and visual culture", destination: location.href, afterSignUpAction: { action: "editorialSignup", }, contextModule: ContextModule.popUpModal, }) } render() { const { isEigen, isMobile } = this.props const { date } = this.state return ( <NewsContainer isEigen={isEigen || false} isMobile={isMobile || false} id="article-root" > {!isEigen && <NewsNav date={date} positionTop={56} />} {this.renderContent()} {this.renderWaypoint()} </NewsContainer> ) } } const NewsContainer = styled.div<{ isMobile: boolean; isEigen: boolean }>` margin-top: ${props => props.isEigen ? "0" : props.isMobile ? "100" : "200"}px; `
{ const editorialAuthDismissedCookie = Cookies.get( "editorial-signup-dismissed" ) if ( !sd.CURRENT_USER && !editorialAuthDismissedCookie && !this.props.isMobile ) { this.showAuthModal() } }
identifier_body
InfiniteScrollNewsArticle.tsx
import { data as sd } from "sharify" import { getENV } from "v2/Utils/getENV" import moment from "moment" import styled from "styled-components" import React, { Component, Fragment } from "react" import { flatten, throttle } from "lodash" import Waypoint from "react-waypoint" import { positronql } from "desktop/lib/positronql" import { newsArticlesQuery } from "desktop/apps/article/queries/articles" import { ArticleData, RelatedArticleCanvasData, } from "@artsy/reaction/dist/Components/Publishing/Typings" import { NewsNav } from "@artsy/reaction/dist/Components/Publishing/Nav/NewsNav" import { LoadingSpinner } from "./InfiniteScrollArticle" import { NewsArticle } from "./NewsArticle" import { NewsDateDivider } from "@artsy/reaction/dist/Components/Publishing/News/NewsDateDivider" const Cookies = require("desktop/components/cookies/index.coffee") import { shouldAdRender } from "desktop/apps/article/helpers" import { handleScrollingAuthModal } from "desktop/lib/openAuthModal" import { ContextModule, Intent } from "@artsy/cohesion" export interface Props { article?: ArticleData articles: ArticleData[] isMobile?: boolean isEigen?: boolean shouldAdRender?: boolean } interface State { activeArticle: string articles: ArticleData[] date: string error: boolean isEnabled: boolean isLoading: boolean offset: number omit: string relatedArticles: RelatedArticleCanvasData[] } export class InfiniteScrollNewsArticle extends Component<Props, State> { private throttledDateChange constructor(props) { super(props) const article = props.articles[0] || {} const date = this.getDateField(article) const omit = props.article ? props.article.id : null const offset = props.article ? 0 : 6 this.throttledDateChange = throttle(this.onDateChange, 50) this.state = { activeArticle: "", articles: props.articles, date, error: false, isEnabled: true, isLoading: false, offset, omit, relatedArticles: [], } } componentDidMount() { const editorialAuthDismissedCookie = Cookies.get( "editorial-signup-dismissed" ) if ( !sd.CURRENT_USER && !editorialAuthDismissedCookie && !this.props.isMobile ) { this.showAuthModal() } } dismissAuthModal() { Cookies.set("editorial-signup-dismissed", 1, { expires: 864000 }) } fetchNextArticles = async () => { const { articles, offset, omit, relatedArticles } = this.state this.setState({ isLoading: true, }) try { const data = await positronql({ query: newsArticlesQuery({ offset, limit: 6, omit, }), }) const newArticles = data.articles const newRelatedArticles = [data.relatedArticlesCanvas] if (newArticles.length) { this.setState({ articles: articles.concat(newArticles), relatedArticles: relatedArticles.concat(newRelatedArticles), isLoading: false, offset: offset + 6, }) } else { this.setState({ isEnabled: false, isLoading: false, }) } } catch (error) { console.error( "(apps/article/InfiniteScrollNewsArticle) Error fetching next article set: ", error ) this.setState({ isEnabled: false, isLoading: false, error: true, }) } } renderWaypoint = () => { const { isLoading, error } = this.state const isGooglebot = getENV("IS_GOOGLEBOT") const isEnabled = !isGooglebot && this.state.isEnabled if (isEnabled) { if (!isLoading) { return ( <Waypoint data-test="news" onEnter={this.fetchNextArticles} bottomOffset="-50%" /> ) } else if (!error) { return ( <LoadingSpinner> <div className="loading-spinner" /> </LoadingSpinner> ) } } } onDateChange = date => { const hasNewDate = !moment(date).isSame(this.state.date, "day") if (hasNewDate)
} onActiveArticleChange = id => { this.setState({ activeArticle: id }) } hasNewDate = (article, i) => { const { articles } = this.state const beforeArticle = articles[i - 1] || {} const beforeDate = this.getDateField(beforeArticle).substring(0, 10) const currentDate = this.getDateField(article).substring(0, 10) return beforeDate !== currentDate } getDateField = article => { const { published_at, scheduled_publish_at } = article return published_at || scheduled_publish_at || moment().toISOString() } renderContent = () => { const { activeArticle, articles, relatedArticles } = this.state const { isMobile } = this.props let counter = 0 return flatten( articles.map((article, i) => { const hasMetaContent = i % 6 === 0 && i !== 0 const related = relatedArticles[counter] if (hasMetaContent) { counter++ } const isTruncated = !this.props.article || i !== 0 const hasDateDivider = i !== 0 && this.hasNewDate(article, i) const relatedArticlesCanvas = hasMetaContent && related const { isEigen } = this.props // render ads on News Landing the 3rd and then every 6 news articles thereafter const adPosition = { index: i + 1, // article index + 1 startIndex: 3, // render first ad after 3rd article frequency: 6, // render subsequent ads after 6th article } const renderAd = shouldAdRender( adPosition.index, adPosition.startIndex, adPosition.frequency, null, isEigen ) return ( <Fragment key={`article-${i}`}> {hasDateDivider && <NewsDateDivider date={article.published_at} />} <NewsArticle isMobile={isMobile || false} isEigen={isEigen} article={article} isTruncated={isTruncated} onDateChange={this.throttledDateChange} nextArticle={articles[i + 1] as any} onActiveArticleChange={id => this.onActiveArticleChange(id)} isActive={activeArticle === article.id} relatedArticlesForCanvas={relatedArticlesCanvas as any} shouldAdRender={renderAd} articleSerial={adPosition.index} /> </Fragment> ) }) ) } showAuthModal() { handleScrollingAuthModal({ intent: Intent.viewEditorial, copy: "Sign up for the best stories in art and visual culture", destination: location.href, afterSignUpAction: { action: "editorialSignup", }, contextModule: ContextModule.popUpModal, }) } render() { const { isEigen, isMobile } = this.props const { date } = this.state return ( <NewsContainer isEigen={isEigen || false} isMobile={isMobile || false} id="article-root" > {!isEigen && <NewsNav date={date} positionTop={56} />} {this.renderContent()} {this.renderWaypoint()} </NewsContainer> ) } } const NewsContainer = styled.div<{ isMobile: boolean; isEigen: boolean }>` margin-top: ${props => props.isEigen ? "0" : props.isMobile ? "100" : "200"}px; `
{ // Commenting this out as we're noticing that when a user is scrolling // and the top date is updated, it leads to a reset of the current scroll // position, preventing the user from scrolling down the page. // FIXME: Reenable once newsfeed scrolling bug tracked down. this.setState({ date }) }
conditional_block
calls.rs
use crate::types::{Error, Params, Value}; use crate::BoxFuture; use std::fmt; use std::future::Future; use std::sync::Arc; /// Metadata trait pub trait Metadata: Clone + Send + 'static {} impl Metadata for () {} impl<T: Metadata> Metadata for Option<T> {} impl<T: Metadata> Metadata for Box<T> {} impl<T: Sync + Send + 'static> Metadata for Arc<T> {} /// A future-conversion trait. pub trait WrapFuture<T, E> { /// Convert itself into a boxed future. fn into_future(self) -> BoxFuture<Result<T, E>>; } impl<T: Send + 'static, E: Send + 'static> WrapFuture<T, E> for Result<T, E> { fn into_future(self) -> BoxFuture<Result<T, E>> { Box::pin(async { self }) } } impl<T, E> WrapFuture<T, E> for BoxFuture<Result<T, E>> { fn
(self) -> BoxFuture<Result<T, E>> { self } } /// A synchronous or asynchronous method. pub trait RpcMethodSync: Send + Sync + 'static { /// Call method fn call(&self, params: Params) -> BoxFuture<crate::Result<Value>>; } /// Asynchronous Method pub trait RpcMethodSimple: Send + Sync + 'static { /// Output future type Out: Future<Output = Result<Value, Error>> + Send; /// Call method fn call(&self, params: Params) -> Self::Out; } /// Asynchronous Method with Metadata pub trait RpcMethod<T: Metadata>: Send + Sync + 'static { /// Call method fn call(&self, params: Params, meta: T) -> BoxFuture<crate::Result<Value>>; } /// Notification pub trait RpcNotificationSimple: Send + Sync + 'static { /// Execute notification fn execute(&self, params: Params); } /// Notification with Metadata pub trait RpcNotification<T: Metadata>: Send + Sync + 'static { /// Execute notification fn execute(&self, params: Params, meta: T); } /// Possible Remote Procedures with Metadata #[derive(Clone)] pub enum RemoteProcedure<T: Metadata> { /// A method call Method(Arc<dyn RpcMethod<T>>), /// A notification Notification(Arc<dyn RpcNotification<T>>), /// An alias to other method, Alias(String), } impl<T: Metadata> fmt::Debug for RemoteProcedure<T> { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { use self::RemoteProcedure::*; match *self { Method(..) => write!(fmt, "<method>"), Notification(..) => write!(fmt, "<notification>"), Alias(ref alias) => write!(fmt, "alias => {:?}", alias), } } } impl<F: Send + Sync + 'static, X: Send + 'static> RpcMethodSimple for F where F: Fn(Params) -> X, X: Future<Output = Result<Value, Error>>, { type Out = X; fn call(&self, params: Params) -> Self::Out { self(params) } } impl<F: Send + Sync + 'static, X: Send + 'static> RpcMethodSync for F where F: Fn(Params) -> X, X: WrapFuture<Value, Error>, { fn call(&self, params: Params) -> BoxFuture<crate::Result<Value>> { self(params).into_future() } } impl<F: Send + Sync + 'static> RpcNotificationSimple for F where F: Fn(Params), { fn execute(&self, params: Params) { self(params) } } impl<F: Send + Sync + 'static, X: Send + 'static, T> RpcMethod<T> for F where T: Metadata, F: Fn(Params, T) -> X, X: Future<Output = Result<Value, Error>>, { fn call(&self, params: Params, meta: T) -> BoxFuture<crate::Result<Value>> { Box::pin(self(params, meta)) } } impl<F: Send + Sync + 'static, T> RpcNotification<T> for F where T: Metadata, F: Fn(Params, T), { fn execute(&self, params: Params, meta: T) { self(params, meta) } }
into_future
identifier_name
calls.rs
use crate::types::{Error, Params, Value}; use crate::BoxFuture; use std::fmt; use std::future::Future; use std::sync::Arc; /// Metadata trait pub trait Metadata: Clone + Send + 'static {} impl Metadata for () {}
/// A future-conversion trait. pub trait WrapFuture<T, E> { /// Convert itself into a boxed future. fn into_future(self) -> BoxFuture<Result<T, E>>; } impl<T: Send + 'static, E: Send + 'static> WrapFuture<T, E> for Result<T, E> { fn into_future(self) -> BoxFuture<Result<T, E>> { Box::pin(async { self }) } } impl<T, E> WrapFuture<T, E> for BoxFuture<Result<T, E>> { fn into_future(self) -> BoxFuture<Result<T, E>> { self } } /// A synchronous or asynchronous method. pub trait RpcMethodSync: Send + Sync + 'static { /// Call method fn call(&self, params: Params) -> BoxFuture<crate::Result<Value>>; } /// Asynchronous Method pub trait RpcMethodSimple: Send + Sync + 'static { /// Output future type Out: Future<Output = Result<Value, Error>> + Send; /// Call method fn call(&self, params: Params) -> Self::Out; } /// Asynchronous Method with Metadata pub trait RpcMethod<T: Metadata>: Send + Sync + 'static { /// Call method fn call(&self, params: Params, meta: T) -> BoxFuture<crate::Result<Value>>; } /// Notification pub trait RpcNotificationSimple: Send + Sync + 'static { /// Execute notification fn execute(&self, params: Params); } /// Notification with Metadata pub trait RpcNotification<T: Metadata>: Send + Sync + 'static { /// Execute notification fn execute(&self, params: Params, meta: T); } /// Possible Remote Procedures with Metadata #[derive(Clone)] pub enum RemoteProcedure<T: Metadata> { /// A method call Method(Arc<dyn RpcMethod<T>>), /// A notification Notification(Arc<dyn RpcNotification<T>>), /// An alias to other method, Alias(String), } impl<T: Metadata> fmt::Debug for RemoteProcedure<T> { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { use self::RemoteProcedure::*; match *self { Method(..) => write!(fmt, "<method>"), Notification(..) => write!(fmt, "<notification>"), Alias(ref alias) => write!(fmt, "alias => {:?}", alias), } } } impl<F: Send + Sync + 'static, X: Send + 'static> RpcMethodSimple for F where F: Fn(Params) -> X, X: Future<Output = Result<Value, Error>>, { type Out = X; fn call(&self, params: Params) -> Self::Out { self(params) } } impl<F: Send + Sync + 'static, X: Send + 'static> RpcMethodSync for F where F: Fn(Params) -> X, X: WrapFuture<Value, Error>, { fn call(&self, params: Params) -> BoxFuture<crate::Result<Value>> { self(params).into_future() } } impl<F: Send + Sync + 'static> RpcNotificationSimple for F where F: Fn(Params), { fn execute(&self, params: Params) { self(params) } } impl<F: Send + Sync + 'static, X: Send + 'static, T> RpcMethod<T> for F where T: Metadata, F: Fn(Params, T) -> X, X: Future<Output = Result<Value, Error>>, { fn call(&self, params: Params, meta: T) -> BoxFuture<crate::Result<Value>> { Box::pin(self(params, meta)) } } impl<F: Send + Sync + 'static, T> RpcNotification<T> for F where T: Metadata, F: Fn(Params, T), { fn execute(&self, params: Params, meta: T) { self(params, meta) } }
impl<T: Metadata> Metadata for Option<T> {} impl<T: Metadata> Metadata for Box<T> {} impl<T: Sync + Send + 'static> Metadata for Arc<T> {}
random_line_split
calls.rs
use crate::types::{Error, Params, Value}; use crate::BoxFuture; use std::fmt; use std::future::Future; use std::sync::Arc; /// Metadata trait pub trait Metadata: Clone + Send + 'static {} impl Metadata for () {} impl<T: Metadata> Metadata for Option<T> {} impl<T: Metadata> Metadata for Box<T> {} impl<T: Sync + Send + 'static> Metadata for Arc<T> {} /// A future-conversion trait. pub trait WrapFuture<T, E> { /// Convert itself into a boxed future. fn into_future(self) -> BoxFuture<Result<T, E>>; } impl<T: Send + 'static, E: Send + 'static> WrapFuture<T, E> for Result<T, E> { fn into_future(self) -> BoxFuture<Result<T, E>> { Box::pin(async { self }) } } impl<T, E> WrapFuture<T, E> for BoxFuture<Result<T, E>> { fn into_future(self) -> BoxFuture<Result<T, E>> { self } } /// A synchronous or asynchronous method. pub trait RpcMethodSync: Send + Sync + 'static { /// Call method fn call(&self, params: Params) -> BoxFuture<crate::Result<Value>>; } /// Asynchronous Method pub trait RpcMethodSimple: Send + Sync + 'static { /// Output future type Out: Future<Output = Result<Value, Error>> + Send; /// Call method fn call(&self, params: Params) -> Self::Out; } /// Asynchronous Method with Metadata pub trait RpcMethod<T: Metadata>: Send + Sync + 'static { /// Call method fn call(&self, params: Params, meta: T) -> BoxFuture<crate::Result<Value>>; } /// Notification pub trait RpcNotificationSimple: Send + Sync + 'static { /// Execute notification fn execute(&self, params: Params); } /// Notification with Metadata pub trait RpcNotification<T: Metadata>: Send + Sync + 'static { /// Execute notification fn execute(&self, params: Params, meta: T); } /// Possible Remote Procedures with Metadata #[derive(Clone)] pub enum RemoteProcedure<T: Metadata> { /// A method call Method(Arc<dyn RpcMethod<T>>), /// A notification Notification(Arc<dyn RpcNotification<T>>), /// An alias to other method, Alias(String), } impl<T: Metadata> fmt::Debug for RemoteProcedure<T> { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { use self::RemoteProcedure::*; match *self { Method(..) => write!(fmt, "<method>"), Notification(..) => write!(fmt, "<notification>"), Alias(ref alias) => write!(fmt, "alias => {:?}", alias), } } } impl<F: Send + Sync + 'static, X: Send + 'static> RpcMethodSimple for F where F: Fn(Params) -> X, X: Future<Output = Result<Value, Error>>, { type Out = X; fn call(&self, params: Params) -> Self::Out { self(params) } } impl<F: Send + Sync + 'static, X: Send + 'static> RpcMethodSync for F where F: Fn(Params) -> X, X: WrapFuture<Value, Error>, { fn call(&self, params: Params) -> BoxFuture<crate::Result<Value>> { self(params).into_future() } } impl<F: Send + Sync + 'static> RpcNotificationSimple for F where F: Fn(Params), { fn execute(&self, params: Params) { self(params) } } impl<F: Send + Sync + 'static, X: Send + 'static, T> RpcMethod<T> for F where T: Metadata, F: Fn(Params, T) -> X, X: Future<Output = Result<Value, Error>>, { fn call(&self, params: Params, meta: T) -> BoxFuture<crate::Result<Value>>
} impl<F: Send + Sync + 'static, T> RpcNotification<T> for F where T: Metadata, F: Fn(Params, T), { fn execute(&self, params: Params, meta: T) { self(params, meta) } }
{ Box::pin(self(params, meta)) }
identifier_body
mutex.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. use prelude::v1::*; use cell::UnsafeCell; #[cfg(feature = "thread")] use sys::sync as ffi; use sys_common::mutex; #[cfg(feature = "thread")] pub struct Mutex { inner: UnsafeCell<ffi::pthread_mutex_t> } #[inline] #[cfg(feature = "thread")] pub unsafe fn raw(m: &Mutex) -> *mut ffi::pthread_mutex_t { m.inner.get() } #[cfg(feature = "thread")] pub const MUTEX_INIT: Mutex = Mutex { inner: UnsafeCell { value: ffi::PTHREAD_MUTEX_INITIALIZER }, }; unsafe impl Send for Mutex {} unsafe impl Sync for Mutex {} #[cfg(feature = "thread")] impl Mutex { #[inline] pub unsafe fn new() -> Mutex { // Might be moved and address is changing it is better to avoid // initialization of potentially opaque OS data before it landed MUTEX_INIT } #[inline] pub unsafe fn lock(&self) { let r = ffi::pthread_mutex_lock(self.inner.get()); debug_assert_eq!(r, 0); } #[inline] pub unsafe fn unlock(&self) { let r = ffi::pthread_mutex_unlock(self.inner.get()); debug_assert_eq!(r, 0); } #[inline] pub unsafe fn try_lock(&self) -> bool { ffi::pthread_mutex_trylock(self.inner.get()) == 0 } #[inline] #[cfg(not(target_os = "dragonfly"))]
} #[inline] #[cfg(target_os = "dragonfly")] pub unsafe fn destroy(&self) { use libc; let r = ffi::pthread_mutex_destroy(self.inner.get()); // On DragonFly pthread_mutex_destroy() returns EINVAL if called on a // mutex that was just initialized with ffi::PTHREAD_MUTEX_INITIALIZER. // Once it is used (locked/unlocked) or pthread_mutex_init() is called, // this behaviour no longer occurs. debug_assert!(r == 0 || r == libc::EINVAL); } } #[cfg(not(feature = "thread"))] pub struct Mutex; #[cfg(not(feature = "thread"))] impl Mutex { #[inline] pub unsafe fn new() -> Mutex { Mutex } #[inline] pub unsafe fn lock(&self) { } #[inline] pub unsafe fn unlock(&self) { } #[inline] pub unsafe fn try_lock(&self) -> bool { true } #[inline] pub unsafe fn destroy(&self) { } } #[cfg(not(feature = "thread"))] pub const MUTEX_INIT: Mutex = Mutex;
pub unsafe fn destroy(&self) { let r = ffi::pthread_mutex_destroy(self.inner.get()); debug_assert_eq!(r, 0);
random_line_split
mutex.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. use prelude::v1::*; use cell::UnsafeCell; #[cfg(feature = "thread")] use sys::sync as ffi; use sys_common::mutex; #[cfg(feature = "thread")] pub struct Mutex { inner: UnsafeCell<ffi::pthread_mutex_t> } #[inline] #[cfg(feature = "thread")] pub unsafe fn raw(m: &Mutex) -> *mut ffi::pthread_mutex_t { m.inner.get() } #[cfg(feature = "thread")] pub const MUTEX_INIT: Mutex = Mutex { inner: UnsafeCell { value: ffi::PTHREAD_MUTEX_INITIALIZER }, }; unsafe impl Send for Mutex {} unsafe impl Sync for Mutex {} #[cfg(feature = "thread")] impl Mutex { #[inline] pub unsafe fn new() -> Mutex { // Might be moved and address is changing it is better to avoid // initialization of potentially opaque OS data before it landed MUTEX_INIT } #[inline] pub unsafe fn lock(&self) { let r = ffi::pthread_mutex_lock(self.inner.get()); debug_assert_eq!(r, 0); } #[inline] pub unsafe fn unlock(&self) { let r = ffi::pthread_mutex_unlock(self.inner.get()); debug_assert_eq!(r, 0); } #[inline] pub unsafe fn try_lock(&self) -> bool { ffi::pthread_mutex_trylock(self.inner.get()) == 0 } #[inline] #[cfg(not(target_os = "dragonfly"))] pub unsafe fn destroy(&self) { let r = ffi::pthread_mutex_destroy(self.inner.get()); debug_assert_eq!(r, 0); } #[inline] #[cfg(target_os = "dragonfly")] pub unsafe fn destroy(&self) { use libc; let r = ffi::pthread_mutex_destroy(self.inner.get()); // On DragonFly pthread_mutex_destroy() returns EINVAL if called on a // mutex that was just initialized with ffi::PTHREAD_MUTEX_INITIALIZER. // Once it is used (locked/unlocked) or pthread_mutex_init() is called, // this behaviour no longer occurs. debug_assert!(r == 0 || r == libc::EINVAL); } } #[cfg(not(feature = "thread"))] pub struct Mutex; #[cfg(not(feature = "thread"))] impl Mutex { #[inline] pub unsafe fn new() -> Mutex { Mutex } #[inline] pub unsafe fn lock(&self) { } #[inline] pub unsafe fn unlock(&self) { } #[inline] pub unsafe fn try_lock(&self) -> bool { true } #[inline] pub unsafe fn
(&self) { } } #[cfg(not(feature = "thread"))] pub const MUTEX_INIT: Mutex = Mutex;
destroy
identifier_name
event-recipe.js
/** * Created by ko on 2016-07-15. */ $(document).ready(function () { var pageNo= 1; // webtoon $("#recipe").on("click", function () { $("#travel_content").html(""); $("#youtube_content").html(""); $("#honbap_content").html(""); $("#game_content").html("");
$("#resultArea").html(""); $("#prodInfo_content").css("display", "none"); pageNo=1; $("#cvs_content").css("display", "none"); common_module.moveYoutubeMenu(); recipe_module.recipeTitle(); recipe_module.showRecipe(1); $(window).unbind('scroll'); $(window).scroll(function(){ if (Math.ceil($(window).scrollTop()) == $(document).height() - $(window).height()) { pageNo +=1; recipe_module.showRecipe(pageNo); $(".loadingArea").html('<img src = "https://cdn.rawgit.com/kokk9239/singleLife_web/master/src/img/preloader.gif" style="width: 60px; height: 60px">'); } }); $("#webtoon_content").css("display", "none"); }); });
$("#parcelArea").css("display","none");
random_line_split
event-recipe.js
/** * Created by ko on 2016-07-15. */ $(document).ready(function () { var pageNo= 1; // webtoon $("#recipe").on("click", function () { $("#travel_content").html(""); $("#youtube_content").html(""); $("#honbap_content").html(""); $("#game_content").html(""); $("#parcelArea").css("display","none"); $("#resultArea").html(""); $("#prodInfo_content").css("display", "none"); pageNo=1; $("#cvs_content").css("display", "none"); common_module.moveYoutubeMenu(); recipe_module.recipeTitle(); recipe_module.showRecipe(1); $(window).unbind('scroll'); $(window).scroll(function(){ if (Math.ceil($(window).scrollTop()) == $(document).height() - $(window).height())
}); $("#webtoon_content").css("display", "none"); }); });
{ pageNo +=1; recipe_module.showRecipe(pageNo); $(".loadingArea").html('<img src = "https://cdn.rawgit.com/kokk9239/singleLife_web/master/src/img/preloader.gif" style="width: 60px; height: 60px">'); }
conditional_block
mod.rs
// Copyright 2021 TiKV Project Authors. Licensed under Apache-2.0. mod engine; mod engine_factory; mod mvcc; mod storage; mod txn; use std::fmt;
use self::engine::bench_engine; use self::engine_factory::{BTreeEngineFactory, EngineFactory, RocksEngineFactory}; use self::mvcc::bench_mvcc; use self::storage::bench_storage; use self::txn::bench_txn; use criterion::Criterion; use tikv::storage::Engine; const DEFAULT_ITERATIONS: usize = 10; const DEFAULT_KEY_LENGTHS: [usize; 1] = [64]; const DEFAULT_VALUE_LENGTHS: [usize; 2] = [64, 65]; const DEFAULT_KV_GENERATOR_SEED: u64 = 0; #[derive(Clone)] pub struct BenchConfig<F> { pub key_length: usize, pub value_length: usize, pub engine_factory: F, } impl<F: fmt::Debug> fmt::Debug for BenchConfig<F> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!( f, "{:?}_KL{:?}_VL{:?}", self.engine_factory, self.key_length, self.value_length ) } } pub fn load_configs<E: Engine, F: EngineFactory<E>>(engine_factory: F) -> Vec<BenchConfig<F>> { let key_lengths = DEFAULT_KEY_LENGTHS; let value_lengths = DEFAULT_VALUE_LENGTHS; let mut configs = vec![]; for &kl in &key_lengths { for &vl in &value_lengths { configs.push(BenchConfig { key_length: kl, value_length: vl, engine_factory, }) } } configs } fn main() { let mut c = Criterion::default().configure_from_args(); let btree_engine_configs = load_configs(BTreeEngineFactory {}); let rocks_engine_configs = load_configs(RocksEngineFactory {}); bench_engine(&mut c, &btree_engine_configs); bench_engine(&mut c, &rocks_engine_configs); bench_mvcc(&mut c, &btree_engine_configs); bench_mvcc(&mut c, &rocks_engine_configs); bench_txn(&mut c, &btree_engine_configs); bench_txn(&mut c, &rocks_engine_configs); bench_storage(&mut c, &btree_engine_configs); bench_storage(&mut c, &rocks_engine_configs); c.final_summary(); }
random_line_split
mod.rs
// Copyright 2021 TiKV Project Authors. Licensed under Apache-2.0. mod engine; mod engine_factory; mod mvcc; mod storage; mod txn; use std::fmt; use self::engine::bench_engine; use self::engine_factory::{BTreeEngineFactory, EngineFactory, RocksEngineFactory}; use self::mvcc::bench_mvcc; use self::storage::bench_storage; use self::txn::bench_txn; use criterion::Criterion; use tikv::storage::Engine; const DEFAULT_ITERATIONS: usize = 10; const DEFAULT_KEY_LENGTHS: [usize; 1] = [64]; const DEFAULT_VALUE_LENGTHS: [usize; 2] = [64, 65]; const DEFAULT_KV_GENERATOR_SEED: u64 = 0; #[derive(Clone)] pub struct
<F> { pub key_length: usize, pub value_length: usize, pub engine_factory: F, } impl<F: fmt::Debug> fmt::Debug for BenchConfig<F> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!( f, "{:?}_KL{:?}_VL{:?}", self.engine_factory, self.key_length, self.value_length ) } } pub fn load_configs<E: Engine, F: EngineFactory<E>>(engine_factory: F) -> Vec<BenchConfig<F>> { let key_lengths = DEFAULT_KEY_LENGTHS; let value_lengths = DEFAULT_VALUE_LENGTHS; let mut configs = vec![]; for &kl in &key_lengths { for &vl in &value_lengths { configs.push(BenchConfig { key_length: kl, value_length: vl, engine_factory, }) } } configs } fn main() { let mut c = Criterion::default().configure_from_args(); let btree_engine_configs = load_configs(BTreeEngineFactory {}); let rocks_engine_configs = load_configs(RocksEngineFactory {}); bench_engine(&mut c, &btree_engine_configs); bench_engine(&mut c, &rocks_engine_configs); bench_mvcc(&mut c, &btree_engine_configs); bench_mvcc(&mut c, &rocks_engine_configs); bench_txn(&mut c, &btree_engine_configs); bench_txn(&mut c, &rocks_engine_configs); bench_storage(&mut c, &btree_engine_configs); bench_storage(&mut c, &rocks_engine_configs); c.final_summary(); }
BenchConfig
identifier_name
mod.rs
// Copyright 2021 TiKV Project Authors. Licensed under Apache-2.0. mod engine; mod engine_factory; mod mvcc; mod storage; mod txn; use std::fmt; use self::engine::bench_engine; use self::engine_factory::{BTreeEngineFactory, EngineFactory, RocksEngineFactory}; use self::mvcc::bench_mvcc; use self::storage::bench_storage; use self::txn::bench_txn; use criterion::Criterion; use tikv::storage::Engine; const DEFAULT_ITERATIONS: usize = 10; const DEFAULT_KEY_LENGTHS: [usize; 1] = [64]; const DEFAULT_VALUE_LENGTHS: [usize; 2] = [64, 65]; const DEFAULT_KV_GENERATOR_SEED: u64 = 0; #[derive(Clone)] pub struct BenchConfig<F> { pub key_length: usize, pub value_length: usize, pub engine_factory: F, } impl<F: fmt::Debug> fmt::Debug for BenchConfig<F> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!( f, "{:?}_KL{:?}_VL{:?}", self.engine_factory, self.key_length, self.value_length ) } } pub fn load_configs<E: Engine, F: EngineFactory<E>>(engine_factory: F) -> Vec<BenchConfig<F>>
fn main() { let mut c = Criterion::default().configure_from_args(); let btree_engine_configs = load_configs(BTreeEngineFactory {}); let rocks_engine_configs = load_configs(RocksEngineFactory {}); bench_engine(&mut c, &btree_engine_configs); bench_engine(&mut c, &rocks_engine_configs); bench_mvcc(&mut c, &btree_engine_configs); bench_mvcc(&mut c, &rocks_engine_configs); bench_txn(&mut c, &btree_engine_configs); bench_txn(&mut c, &rocks_engine_configs); bench_storage(&mut c, &btree_engine_configs); bench_storage(&mut c, &rocks_engine_configs); c.final_summary(); }
{ let key_lengths = DEFAULT_KEY_LENGTHS; let value_lengths = DEFAULT_VALUE_LENGTHS; let mut configs = vec![]; for &kl in &key_lengths { for &vl in &value_lengths { configs.push(BenchConfig { key_length: kl, value_length: vl, engine_factory, }) } } configs }
identifier_body
CreateStrategy.tsx
import { useHistory } from 'react-router-dom'; import useUiConfig from '../../../hooks/api/getters/useUiConfig/useUiConfig'; import useToast from '../../../hooks/useToast'; import FormTemplate from '../../common/FormTemplate/FormTemplate'; import { useStrategyForm } from '../hooks/useStrategyForm'; import { StrategyForm } from '../StrategyForm/StrategyForm'; import PermissionButton from '../../common/PermissionButton/PermissionButton'; import { CREATE_STRATEGY } from '../../providers/AccessProvider/permissions'; import useStrategiesApi from '../../../hooks/api/actions/useStrategiesApi/useStrategiesApi'; import { useStrategies } from '../../../hooks/api/getters/useStrategies/useStrategies'; import { formatUnknownError } from 'utils/format-unknown-error'; export const CreateStrategy = () => { const { setToastData, setToastApiError } = useToast(); const { uiConfig } = useUiConfig(); const history = useHistory(); const { strategyName, strategyDesc, params, setParams, setStrategyName, setStrategyDesc, getStrategyPayload, validateStrategyName, validateParams, clearErrors, setErrors, errors, } = useStrategyForm(); const { createStrategy, loading } = useStrategiesApi(); const { refetchStrategies } = useStrategies(); const handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => { clearErrors(); e.preventDefault(); const validName = validateStrategyName(); if (validName && validateParams()) { const payload = getStrategyPayload(); try { await createStrategy(payload); refetchStrategies(); history.push(`/strategies/${strategyName}`); setToastData({ title: 'Strategy created', text: 'Successfully created strategy', confetti: true, type: 'success', }); } catch (e: unknown) { setToastApiError(formatUnknownError(e)); } } };
--header 'Content-Type: application/json' \\ --data-raw '${JSON.stringify(getStrategyPayload(), undefined, 2)}'`; }; const handleCancel = () => { history.goBack(); }; return ( <FormTemplate loading={loading} title="Create strategy type" description="The strategy type and the parameters will be selectable when adding an activation strategy to a toggle in the environments. The parameter defines the type of activation strategy. E.g. you can create a type 'Teams' and add a parameter 'List'. Then it's easy to add team names to the activation strategy" documentationLink="https://docs.getunleash.io/advanced/custom_activation_strategy" formatApiCode={formatApiCode} > <StrategyForm errors={errors} handleSubmit={handleSubmit} handleCancel={handleCancel} strategyName={strategyName} setStrategyName={setStrategyName} strategyDesc={strategyDesc} setStrategyDesc={setStrategyDesc} params={params} setParams={setParams} mode="Create" setErrors={setErrors} clearErrors={clearErrors} > <PermissionButton permission={CREATE_STRATEGY} type="submit"> Create strategy </PermissionButton> </StrategyForm> </FormTemplate> ); };
const formatApiCode = () => { return `curl --location --request POST '${ uiConfig.unleashUrl }/api/admin/strategies' \\ --header 'Authorization: INSERT_API_KEY' \\
random_line_split
CreateStrategy.tsx
import { useHistory } from 'react-router-dom'; import useUiConfig from '../../../hooks/api/getters/useUiConfig/useUiConfig'; import useToast from '../../../hooks/useToast'; import FormTemplate from '../../common/FormTemplate/FormTemplate'; import { useStrategyForm } from '../hooks/useStrategyForm'; import { StrategyForm } from '../StrategyForm/StrategyForm'; import PermissionButton from '../../common/PermissionButton/PermissionButton'; import { CREATE_STRATEGY } from '../../providers/AccessProvider/permissions'; import useStrategiesApi from '../../../hooks/api/actions/useStrategiesApi/useStrategiesApi'; import { useStrategies } from '../../../hooks/api/getters/useStrategies/useStrategies'; import { formatUnknownError } from 'utils/format-unknown-error'; export const CreateStrategy = () => { const { setToastData, setToastApiError } = useToast(); const { uiConfig } = useUiConfig(); const history = useHistory(); const { strategyName, strategyDesc, params, setParams, setStrategyName, setStrategyDesc, getStrategyPayload, validateStrategyName, validateParams, clearErrors, setErrors, errors, } = useStrategyForm(); const { createStrategy, loading } = useStrategiesApi(); const { refetchStrategies } = useStrategies(); const handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => { clearErrors(); e.preventDefault(); const validName = validateStrategyName(); if (validName && validateParams())
}; const formatApiCode = () => { return `curl --location --request POST '${ uiConfig.unleashUrl }/api/admin/strategies' \\ --header 'Authorization: INSERT_API_KEY' \\ --header 'Content-Type: application/json' \\ --data-raw '${JSON.stringify(getStrategyPayload(), undefined, 2)}'`; }; const handleCancel = () => { history.goBack(); }; return ( <FormTemplate loading={loading} title="Create strategy type" description="The strategy type and the parameters will be selectable when adding an activation strategy to a toggle in the environments. The parameter defines the type of activation strategy. E.g. you can create a type 'Teams' and add a parameter 'List'. Then it's easy to add team names to the activation strategy" documentationLink="https://docs.getunleash.io/advanced/custom_activation_strategy" formatApiCode={formatApiCode} > <StrategyForm errors={errors} handleSubmit={handleSubmit} handleCancel={handleCancel} strategyName={strategyName} setStrategyName={setStrategyName} strategyDesc={strategyDesc} setStrategyDesc={setStrategyDesc} params={params} setParams={setParams} mode="Create" setErrors={setErrors} clearErrors={clearErrors} > <PermissionButton permission={CREATE_STRATEGY} type="submit"> Create strategy </PermissionButton> </StrategyForm> </FormTemplate> ); };
{ const payload = getStrategyPayload(); try { await createStrategy(payload); refetchStrategies(); history.push(`/strategies/${strategyName}`); setToastData({ title: 'Strategy created', text: 'Successfully created strategy', confetti: true, type: 'success', }); } catch (e: unknown) { setToastApiError(formatUnknownError(e)); } }
conditional_block
admin.module.ts
import { NgModule } from "@angular/core"; import { AdminComponent } from "./admin.component"; import { FormBuilder, FormsModule, ReactiveFormsModule } from "@angular/forms"; import { TranslateService, TranslateModule } from "ng2-translate"; import { RouterModule } from "@angular/router"; import { AdminViewComponent } from "./admin-view/admin-view.component"; import { AdminSpamFilterComponent } from "./spamFilter/admin-spam-filter.component"; import { AdminDashboardComponent } from "./dashboard/admin-dashboard.component"; import { AdminSettingsComponent } from "./settings/admin-settings.component"; import { BreadcrumbModule } from "../breadcrumb/breadcrumb.component"; import { UsersComponent } from "./users/admin-users.component"; import { ChartModule } from "primeng/components/chart/chart"; import { CommonModule } from "@angular/common"; import { DashboardModule } from "../common/component/dashboard/dashboard.module"; import { NavbarModule } from "../common/component/navbar/navbar.component"; const ADMIN_DECLARATION = [ AdminComponent, AdminViewComponent, UsersComponent, AdminDashboardComponent, AdminSettingsComponent, AdminSpamFilterComponent, ]; @NgModule({
CommonModule, TranslateModule, RouterModule, FormsModule, ReactiveFormsModule, BreadcrumbModule, ChartModule, NavbarModule, DashboardModule ], declarations: [ADMIN_DECLARATION], exports: [ADMIN_DECLARATION], providers: [ TranslateService, FormBuilder ] }) export class AdminModule { }
imports: [
random_line_split
admin.module.ts
import { NgModule } from "@angular/core"; import { AdminComponent } from "./admin.component"; import { FormBuilder, FormsModule, ReactiveFormsModule } from "@angular/forms"; import { TranslateService, TranslateModule } from "ng2-translate"; import { RouterModule } from "@angular/router"; import { AdminViewComponent } from "./admin-view/admin-view.component"; import { AdminSpamFilterComponent } from "./spamFilter/admin-spam-filter.component"; import { AdminDashboardComponent } from "./dashboard/admin-dashboard.component"; import { AdminSettingsComponent } from "./settings/admin-settings.component"; import { BreadcrumbModule } from "../breadcrumb/breadcrumb.component"; import { UsersComponent } from "./users/admin-users.component"; import { ChartModule } from "primeng/components/chart/chart"; import { CommonModule } from "@angular/common"; import { DashboardModule } from "../common/component/dashboard/dashboard.module"; import { NavbarModule } from "../common/component/navbar/navbar.component"; const ADMIN_DECLARATION = [ AdminComponent, AdminViewComponent, UsersComponent, AdminDashboardComponent, AdminSettingsComponent, AdminSpamFilterComponent, ]; @NgModule({ imports: [ CommonModule, TranslateModule, RouterModule, FormsModule, ReactiveFormsModule, BreadcrumbModule, ChartModule, NavbarModule, DashboardModule ], declarations: [ADMIN_DECLARATION], exports: [ADMIN_DECLARATION], providers: [ TranslateService, FormBuilder ] }) export class
{ }
AdminModule
identifier_name
modals.js
Element.prototype.remove = function() { this.parentElement.removeChild(this); }
const addIcon = (icon) => `<i class="fa fa-${icon}"></i>` const headerTxt = (type) => { switch (type) { case 'error': return `${addIcon('ban')} Error` case 'warning': return `${addIcon('exclamation')} Warning` case 'success': return `${addIcon('check')} Success` default: return `${addIcon('ban')} Error` } } const createModal = (texto, type) => { let modal = document.createElement('div') modal.classList = 'modal-background' let headertxt = 'Error' let content = ` <div class="modal-frame"> <header class="modal-${type} modal-header"> <h4> ${headerTxt(type)} </h4> <span id="closeModal">&times;</span> </header> <div class="modal-mssg"> ${texto} </div> <button id="btnAcceptModal" class="btn modal-btn modal-${type}">Aceptar</button> </div> ` modal.innerHTML = content document.body.appendChild(modal) document.getElementById('btnAcceptModal').addEventListener('click', () => modal.remove()) document.getElementById('closeModal').addEventListener('click', () => modal.remove()) } export const errorModal = (message) => createModal(message, 'error') export const successModal = (message) => createModal(message, 'success') export const warningModal = (message) => createModal(message, 'warning')
random_line_split
__init__.py
# coding=utf-8 from __future__ import unicode_literals from random import randint from .. import Provider as AddressProvider class Provider(AddressProvider): address_formats = ['{{street_address}}, {{city}}, {{postcode}}'] building_number_formats = ['#', '##', '###'] city_formats = ['{{city_prefix}} {{first_name}}'] street_address_formats = ['{{street_name}}, {{building_number}}'] street_name_formats = ['{{street_prefix}} {{last_name}}', '{{last_name}} {{street_suffix}}'] city_prefixes = ['місто', 'село', 'селище', 'хутір'] countries = [ 'Австралія', 'Австрія', 'Азербайджан', 'Албанія', 'Алжир', 'Ангола', 'Андорра', 'Антигуа і Барбуда', 'Аргентина', 'Афганістан', 'Багамські Острови', 'Бангладеш', 'Барбадос', 'Бахрейн', 'Беліз', 'Бельгія', 'Бенін', 'Білорусь', 'Болгарія', 'Болівія', 'Боснія і Герцеговина', 'Ботсвана', 'Бразилія', 'Бруней', 'Буркіна-Фасо', 'Бурунді', 'Бутан', 'Вануату', 'Ватикан', 'Велика Британія', 'Венесуела', 'В\'єтнам', 'Вірменія', 'Габон', 'Гаїті', 'Гаяна', 'Гамбія', 'Гана', 'Гватемала', 'Гвінея', 'Гвінея-Бісау', 'Гондурас', 'Гренада', 'Греція', 'Грузія', 'Данія', 'Джибуті', 'Домініка', 'Домініканська Республіка', 'Еквадор', 'Екваторіальна Гвінея', 'Еритрея', 'Естонія', 'Ефіопія', 'Єгипет', 'Ємен', 'Замбія', 'Західна Сахара', 'Зімбабве', 'Ізраїль', 'Індія', 'Індонезія', 'Ірак', 'Іран', 'Ірландія', 'Ісландія', 'Іспанія', 'Італія', 'Йорданія', 'Кабо-Верде', 'Казахстан', 'Камбоджа', 'Камерун', 'Канада', 'Катар', 'Кенія', 'Киргизстан', 'КНР', 'Кіпр', 'Кірибаті', 'Колумбія', 'Коморські Острови', 'Конго', 'ДР Конго', 'Південна Корея', 'Північна Корея', 'Косово', 'Коста-Рика', 'Кот-д\'Івуар', 'Куба', 'Кувейт', 'Лаос', 'Латвія', 'Лесото', 'Литва', 'Ліберія', 'Ліван', 'Лівія', 'Ліхтенштейн', 'Люксембург', 'Маврикій', 'Мавританія', 'Мадагаскар', 'Республіка Македонія', 'Малаві', 'Малайзія', 'Малі', 'Мальдіви', 'Мальта', 'Марокко', 'Маршаллові Острови', 'Мексика', 'Федеративні Штати Мікронезії', 'Мозамбік', 'Молдова', 'Монако', 'Монголія', 'М\'янма', 'Намібія', 'Науру', 'Непал', 'Нігер', 'Нігерія', 'Нідерланди', 'Нікарагуа', 'Німеччина', 'Нова Зеландія', 'Норвегія', 'ОАЕ', 'Оман', 'Пакистан', 'Палау', 'Палестинська держава', 'Панама', 'Папуа Нова Гвінея', 'ПАР', 'Парагвай', 'Перу', 'Південний Судан', 'Польща', 'Португалія', 'Росія', 'Руанда', 'Румунія', 'Сальвадор', 'Самоа', 'Сан-Марино', 'Сан-Томе і Принсіпі', 'Саудівська Аравія', 'Свазіленд', 'Сейшельські Острови', 'Сенегал', 'Сент-Вінсент і Гренадини', 'Сент-Кіттс і Невіс', 'Сент-Люсія', 'Сербія', 'Сінгапур', 'Сирія', 'Словаччина', 'Словенія', 'Соломонові Острови', 'Сомалі', 'Судан', 'Суринам', 'Східний Тимор', 'США', 'Сьєрра-Леоне', 'Таджикистан', 'Таїланд', 'Тайвань', 'Танзанія', 'Того', 'Тонга', 'Тринідад і Тобаго', 'Тувалу', 'Туніс', 'Туреччина', 'Туркменістан', 'Уганда', 'Угорщина', 'Узбекистан', 'Україна', 'Уругвай', 'Фіджі', 'Філіппіни', 'Фінляндія', 'Франція', 'Хорватія', 'Центральноафриканська Республіка', 'Чад', 'Чехія', 'Чилі', 'Чорногорія', 'Швейцарія', 'Швеція', 'Шрі-Ланка', 'Ямайка', 'Японія' ] street_prefixes = [ 'вулиця', 'проспект', 'майдан', 'набережна', 'бульвар', 'провулок' ] street_suffixes = ['узвіз'] @classmethod def city_prefix(cls): return cls.random_element(cls.city_prefixes) @classmethod def postcode(cls): """The code consists of five digits (01000-99999)""" return '{}{}'.format(randint(0, 10), randint(1000, 10000)) @classmethod def street_prefix(cls): return cls.random_element(cls.street_prefixes)
identifier_body
__init__.py
# coding=utf-8 from __future__ import unicode_literals from random import randint from .. import Provider as AddressProvider class Provider(AddressProvider): address_formats = ['{{street_address}}, {{city}}, {{postcode}}'] building_number_formats = ['#', '##', '###'] city_formats = ['{{city_prefix}} {{first_name}}'] street_address_formats = ['{{street_name}}, {{building_number}}'] street_name_formats = ['{{street_prefix}} {{last_name}}', '{{last_name}} {{street_suffix}}'] city_prefixes = ['місто', 'село', 'селище', 'хутір'] countries = [ 'Австралія', 'Австрія', 'Азербайджан', 'Албанія', 'Алжир', 'Ангола', 'Андорра', 'Антигуа і Барбуда', 'Аргентина', 'Афганістан', 'Багамські Острови', 'Бангладеш', 'Барбадос', 'Бахрейн', 'Беліз', 'Бельгія', 'Бенін', 'Білорусь', 'Болгарія', 'Болівія', 'Боснія і Герцеговина', 'Ботсвана', 'Бразилія', 'Бруней', 'Буркіна-Фасо', 'Бурунді', 'Бутан', 'Вануату', 'Ватикан', 'Велика Британія', 'Венесуела', 'В\'єтнам', 'Вірменія', 'Габон', 'Гаїті', 'Гаяна', 'Гамбія', 'Гана', 'Гватемала', 'Гвінея', 'Гвінея-Бісау', 'Гондурас', 'Гренада', 'Греція', 'Грузія', 'Данія', 'Джибуті', 'Домініка', 'Домініканська Республіка', 'Еквадор', 'Екваторіальна Гвінея', 'Еритрея', 'Естонія', 'Ефіопія', 'Єгипет', 'Ємен', 'Замбія', 'Західна Сахара', 'Зімбабве', 'Ізраїль', 'Індія', 'Індонезія', 'Ірак', 'Іран', 'Ірландія', 'Ісландія', 'Іспанія', 'Італія', 'Йорданія', 'Кабо-Верде', 'Казахстан', 'Камбоджа', 'Камерун', 'Канада', 'Катар', 'Кенія', 'Киргизстан', 'КНР', 'Кіпр', 'Кірибаті', 'Колумбія', 'Коморські Острови', 'Конго', 'ДР Конго', 'Південна Корея', 'Північна Корея', 'Косово', 'Коста-Рика', 'Кот-д\'Івуар', 'Куба', 'Кувейт', 'Лаос', 'Латвія', 'Лесото', 'Литва', 'Ліберія', 'Ліван', 'Лівія', 'Ліхтенштейн', 'Люксембург', 'Маврикій', 'Мавританія', 'Мадагаскар', 'Республіка Македонія', 'Малаві', 'Малайзія', 'Малі', 'Мальдіви', 'Мальта', 'Марокко', 'Маршаллові Острови', 'Мексика', 'Федеративні Штати Мікронезії', 'Мозамбік', 'Молдова', 'Монако', 'Монголія', 'М\'янма', 'Намібія', 'Науру', 'Непал', 'Нігер', 'Нігерія',
'Самоа', 'Сан-Марино', 'Сан-Томе і Принсіпі', 'Саудівська Аравія', 'Свазіленд', 'Сейшельські Острови', 'Сенегал', 'Сент-Вінсент і Гренадини', 'Сент-Кіттс і Невіс', 'Сент-Люсія', 'Сербія', 'Сінгапур', 'Сирія', 'Словаччина', 'Словенія', 'Соломонові Острови', 'Сомалі', 'Судан', 'Суринам', 'Східний Тимор', 'США', 'Сьєрра-Леоне', 'Таджикистан', 'Таїланд', 'Тайвань', 'Танзанія', 'Того', 'Тонга', 'Тринідад і Тобаго', 'Тувалу', 'Туніс', 'Туреччина', 'Туркменістан', 'Уганда', 'Угорщина', 'Узбекистан', 'Україна', 'Уругвай', 'Фіджі', 'Філіппіни', 'Фінляндія', 'Франція', 'Хорватія', 'Центральноафриканська Республіка', 'Чад', 'Чехія', 'Чилі', 'Чорногорія', 'Швейцарія', 'Швеція', 'Шрі-Ланка', 'Ямайка', 'Японія' ] street_prefixes = [ 'вулиця', 'проспект', 'майдан', 'набережна', 'бульвар', 'провулок' ] street_suffixes = ['узвіз'] @classmethod def city_prefix(cls): return cls.random_element(cls.city_prefixes) @classmethod def postcode(cls): """The code consists of five digits (01000-99999)""" return '{}{}'.format(randint(0, 10), randint(1000, 10000)) @classmethod def street_prefix(cls): return cls.random_element(cls.street_prefixes)
'Нідерланди', 'Нікарагуа', 'Німеччина', 'Нова Зеландія', 'Норвегія', 'ОАЕ', 'Оман', 'Пакистан', 'Палау', 'Палестинська держава', 'Панама', 'Папуа Нова Гвінея', 'ПАР', 'Парагвай', 'Перу', 'Південний Судан', 'Польща', 'Португалія', 'Росія', 'Руанда', 'Румунія', 'Сальвадор',
random_line_split
__init__.py
# coding=utf-8 from __future__ import unicode_literals from random import randint from .. import Provider as AddressProvider class Provider(AddressProvider): address_formats = ['{{street_address}}, {{city}}, {{postcode}}'] building_number_formats = ['#', '##', '###'] city_formats = ['{{city_prefix}} {{first_name}}'] street_address_formats = ['{{street_name}}, {{building_number}}'] street_name_formats = ['{{street_prefix}} {{last_name}}', '{{last_name}} {{street_suffix}}'] city_prefixes = ['місто', 'село', 'селище', 'хутір'] countries = [ 'Австралія', 'Австрія', 'Азербайджан', 'Албанія', 'Алжир', 'Ангола', 'Андорра', 'Антигуа і Барбуда', 'Аргентина', 'Афганістан', 'Багамські Острови', 'Бангладеш', 'Барбадос', 'Бахрейн', 'Беліз', 'Бельгія', 'Бенін', 'Білорусь', 'Болгарія', 'Болівія', 'Боснія і Герцеговина', 'Ботсвана', 'Бразилія', 'Бруней', 'Буркіна-Фасо', 'Бурунді', 'Бутан', 'Вануату', 'Ватикан', 'Велика Британія', 'Венесуела', 'В\'єтнам', 'Вірменія', 'Габон', 'Гаїті', 'Гаяна', 'Гамбія', 'Гана', 'Гватемала', 'Гвінея', 'Гвінея-Бісау', 'Гондурас', 'Гренада', 'Греція', 'Грузія', 'Данія', 'Джибуті', 'Домініка', 'Домініканська Республіка', 'Еквадор', 'Екваторіальна Гвінея', 'Еритрея', 'Естонія', 'Ефіопія', 'Єгипет', 'Ємен', 'Замбія', 'Західна Сахара', 'Зімбабве', 'Ізраїль', 'Індія', 'Індонезія', 'Ірак', 'Іран', 'Ірландія', 'Ісландія', 'Іспанія', 'Італія', 'Йорданія', 'Кабо-Верде', 'Казахстан', 'Камбоджа', 'Камерун', 'Канада', 'Катар', 'Кенія', 'Киргизстан', 'КНР', 'Кіпр', 'Кірибаті', 'Колумбія', 'Коморські Острови', 'Конго', 'ДР Конго', 'Південна Корея', 'Північна Корея', 'Косово', 'Коста-Рика', 'Кот-д\'Івуар', 'Куба', 'Кувейт', 'Лаос', 'Латвія', 'Лесото', 'Литва', 'Ліберія', 'Ліван', 'Лівія', 'Ліхтенштейн', 'Люксембург', 'Маврикій', 'Мавританія', 'Мадагаскар', 'Республіка Македонія', 'Малаві', 'Малайзія', 'Малі', 'Мальдіви', 'Мальта', 'Марокко', 'Маршаллові Острови', 'Мексика', 'Федеративні Штати Мікронезії', 'Мозамбік', 'Молдова', 'Монако', 'Монголія', 'М\'янма', 'Намібія', 'Науру', 'Непал', 'Нігер', 'Нігерія', 'Нідерланди', 'Нікарагуа', 'Німеччина', 'Нова Зеландія', 'Норвегія', 'ОАЕ', 'Оман', 'Пакистан', 'Палау', 'Палестинська держава', 'Панама', 'Папуа Нова Гвінея', 'ПАР', 'Парагвай', 'Перу', 'Південний Судан', 'Польща', 'Португалія', 'Росія', 'Руанда', 'Румунія', 'Сальвадор', 'Самоа', 'Сан-Марино', 'Сан-Томе і Принсіпі', 'Саудівська Аравія', 'Свазіленд', 'Сейшельські Острови', 'Сенегал', 'Сент-Вінсент і Гренадини', 'Сент-Кіттс і Невіс', 'Сент-Люсія', 'Сербія', 'Сінгапур', 'Сирія', 'Словаччина', 'Словенія', 'Соломонові Острови', 'Сомалі', 'Судан', 'Суринам', 'Східний Тимор', 'США', 'Сьєрра-Леоне', 'Таджикистан', 'Таїланд', 'Тайвань', 'Танзанія', 'Того', 'Тонга', 'Тринідад і Тобаго', 'Тувалу', 'Туніс', 'Туреччина', 'Туркменістан', 'Уганда', 'Угорщина', 'Узбекистан', 'Україна', 'Уругвай', 'Фіджі', 'Філіппіни', 'Фінляндія', 'Франція', 'Хорватія', 'Центральноафриканська Республіка', 'Чад', 'Чехія', 'Чилі', 'Чорногорія', 'Швейцарія', 'Швеція', 'Шрі-Ланка', 'Ямайка', 'Японія' ] street_prefixes = [ 'вулиця', 'проспект', 'майдан', 'набережна', 'бульвар', 'провулок' ] street_suffixes = ['узвіз'] @classmethod def city_prefix(cls): return cls.random_element(cls.city_prefixes) @classmethod def postcode(cls): """The code consists of five digits (01000-99999)""" return '{}{}'.format(randint(0, 10), randint(1000, 10000)) @classmethod def street_prefix(cls): return cls.random_element(cls.street_prefixes)
identifier_name
array.rs
//! Helper Module to treat Vec and fixed sized arrays as generic in some contexts use crate::linear_algebra::Vector; /// This trait is used to make up for the lack of generics over array lengths pub trait Array { /// Element type of the array type Element; /// Corresponding Vector type with same dimension type Vector: Vector; /// Number of elements within the array fn length(&self) -> usize; /// Access element by immutable reference fn at_ref(&self, index: usize) -> &Self::Element; /// Access element by mutable reference fn at_mut(&mut self, index: usize) -> &mut Self::Element; } macro_rules! array_impl_for { ($v:expr) => { impl<T> Array for [T; $v] { type Element = T; type Vector = [f64; $v];
} fn at_ref(&self, index: usize) -> &T { &self[index] } fn at_mut(&mut self, index: usize) -> &mut T { &mut self[index] } } }; } array_impl_for! { 1 } array_impl_for! { 2 } array_impl_for! { 3 } array_impl_for! { 4 } array_impl_for! { 5 } array_impl_for! { 6 } array_impl_for! { 7 } array_impl_for! { 8 } array_impl_for! { 9 } array_impl_for! { 10 } array_impl_for! { 11 } array_impl_for! { 12 } array_impl_for! { 13 } array_impl_for! { 14 } array_impl_for! { 15 } array_impl_for! { 16 } array_impl_for! { 17 } array_impl_for! { 18 } array_impl_for! { 19 } array_impl_for! { 20 } array_impl_for! { 21 } array_impl_for! { 22 } array_impl_for! { 23 } array_impl_for! { 24 } array_impl_for! { 25 } array_impl_for! { 26 } array_impl_for! { 27 } array_impl_for! { 28 } array_impl_for! { 29 } array_impl_for! { 30 } array_impl_for! { 31 } array_impl_for! { 32 }
fn length(&self) -> usize { $v
random_line_split
lib.rs
use wasm_bindgen::prelude::*; #[rustfmt::skip] #[wasm_bindgen] pub fn
( r: f64, g: f64, b: f64, a: f64, ref_x: f64, ref_y: f64, ref_z: f64, ) -> Vec<f64> { let mut r = r / 255.0; let mut g = g / 255.0; let mut b = b / 255.0; // Need lto = true in Cargo.toml to link pow r = if r > 0.04045 { ((r + 0.055) / 1.055).powf(2.4) } else { r / 12.92 }; g = if g > 0.04045 { ((g + 0.055) / 1.055).powf(2.4) } else { g / 12.92 }; b = if b > 0.04045 { ((b + 0.055) / 1.055).powf(2.4) } else { b / 12.92 }; r *= 100.0; g *= 100.0; b *= 100.0; // Observer= 2° (Only use CIE 1931!) let mut x = r * 0.4124 + g * 0.3576 + b * 0.1805; let mut y = r * 0.2126 + g * 0.7152 + b * 0.0722; let mut z = r * 0.0193 + g * 0.1192 + b * 0.9505; x /= ref_x; y /= ref_y; z /= ref_z; x = if x > 0.008856 { x.powf(1.0 / 3.0) } else { x * 7.787 + 16.0 / 116.0 }; y = if y > 0.008856 { y.powf(1.0 / 3.0) } else { y * 7.787 + 16.0 / 116.0 }; z = if z > 0.008856 { z.powf(1.0 / 3.0) } else { z * 7.787 + 16.0 / 116.0 }; let out_l = 116.0 * y - 16.0; let out_a = 500.0 * (x - y); let out_b = 200.0 * (y - z); vec![out_l, out_a, out_b, a] } #[wasm_bindgen] pub fn rgba_laba_distance( r1: f64, g1: f64, b1: f64, a1: f64, r2: f64, g2: f64, b2: f64, a2: f64, ref_x: f64, ref_y: f64, ref_z: f64, ) -> f64 { let left = rgba2laba(r1, g1, b1, a1, ref_x, ref_y, ref_z); let right = rgba2laba(r2, g2, b2, a2, ref_x, ref_y, ref_z); let dist = ((right[0] - left[0]).powf(2.0) + (right[1] - left[1]).powf(2.0) + (right[2] - left[2]).powf(2.0)).sqrt(); dist }
rgba2laba
identifier_name
lib.rs
use wasm_bindgen::prelude::*; #[rustfmt::skip] #[wasm_bindgen] pub fn rgba2laba( r: f64, g: f64, b: f64, a: f64, ref_x: f64, ref_y: f64, ref_z: f64, ) -> Vec<f64>
#[wasm_bindgen] pub fn rgba_laba_distance( r1: f64, g1: f64, b1: f64, a1: f64, r2: f64, g2: f64, b2: f64, a2: f64, ref_x: f64, ref_y: f64, ref_z: f64, ) -> f64 { let left = rgba2laba(r1, g1, b1, a1, ref_x, ref_y, ref_z); let right = rgba2laba(r2, g2, b2, a2, ref_x, ref_y, ref_z); let dist = ((right[0] - left[0]).powf(2.0) + (right[1] - left[1]).powf(2.0) + (right[2] - left[2]).powf(2.0)).sqrt(); dist }
{ let mut r = r / 255.0; let mut g = g / 255.0; let mut b = b / 255.0; // Need lto = true in Cargo.toml to link pow r = if r > 0.04045 { ((r + 0.055) / 1.055).powf(2.4) } else { r / 12.92 }; g = if g > 0.04045 { ((g + 0.055) / 1.055).powf(2.4) } else { g / 12.92 }; b = if b > 0.04045 { ((b + 0.055) / 1.055).powf(2.4) } else { b / 12.92 }; r *= 100.0; g *= 100.0; b *= 100.0; // Observer= 2° (Only use CIE 1931!) let mut x = r * 0.4124 + g * 0.3576 + b * 0.1805; let mut y = r * 0.2126 + g * 0.7152 + b * 0.0722; let mut z = r * 0.0193 + g * 0.1192 + b * 0.9505; x /= ref_x; y /= ref_y; z /= ref_z; x = if x > 0.008856 { x.powf(1.0 / 3.0) } else { x * 7.787 + 16.0 / 116.0 }; y = if y > 0.008856 { y.powf(1.0 / 3.0) } else { y * 7.787 + 16.0 / 116.0 }; z = if z > 0.008856 { z.powf(1.0 / 3.0) } else { z * 7.787 + 16.0 / 116.0 }; let out_l = 116.0 * y - 16.0; let out_a = 500.0 * (x - y); let out_b = 200.0 * (y - z); vec![out_l, out_a, out_b, a] }
identifier_body
lib.rs
use wasm_bindgen::prelude::*; #[rustfmt::skip] #[wasm_bindgen] pub fn rgba2laba( r: f64, g: f64, b: f64, a: f64, ref_x: f64, ref_y: f64, ref_z: f64, ) -> Vec<f64> { let mut r = r / 255.0; let mut g = g / 255.0; let mut b = b / 255.0; // Need lto = true in Cargo.toml to link pow r = if r > 0.04045 { ((r + 0.055) / 1.055).powf(2.4) } else { r / 12.92 }; g = if g > 0.04045 { ((g + 0.055) / 1.055).powf(2.4) } else { g / 12.92 }; b = if b > 0.04045 { ((b + 0.055) / 1.055).powf(2.4) } else { b / 12.92 }; r *= 100.0; g *= 100.0; b *= 100.0; // Observer= 2° (Only use CIE 1931!) let mut x = r * 0.4124 + g * 0.3576 + b * 0.1805; let mut y = r * 0.2126 + g * 0.7152 + b * 0.0722; let mut z = r * 0.0193 + g * 0.1192 + b * 0.9505; x /= ref_x; y /= ref_y; z /= ref_z; x = if x > 0.008856 { x.powf(1.0 / 3.0) } else { x * 7.787 + 16.0 / 116.0 }; y = if y > 0.008856 { y.powf(1.0 / 3.0) } else { y * 7.787 + 16.0 / 116.0 }; z = if z > 0.008856 { z.powf(1.0 / 3.0) } else { z * 7.787 + 16.0 / 116.0 }; let out_l = 116.0 * y - 16.0; let out_a = 500.0 * (x - y); let out_b = 200.0 * (y - z); vec![out_l, out_a, out_b, a] } #[wasm_bindgen] pub fn rgba_laba_distance( r1: f64, g1: f64,
g2: f64, b2: f64, a2: f64, ref_x: f64, ref_y: f64, ref_z: f64, ) -> f64 { let left = rgba2laba(r1, g1, b1, a1, ref_x, ref_y, ref_z); let right = rgba2laba(r2, g2, b2, a2, ref_x, ref_y, ref_z); let dist = ((right[0] - left[0]).powf(2.0) + (right[1] - left[1]).powf(2.0) + (right[2] - left[2]).powf(2.0)).sqrt(); dist }
b1: f64, a1: f64, r2: f64,
random_line_split
lib.rs
use wasm_bindgen::prelude::*; #[rustfmt::skip] #[wasm_bindgen] pub fn rgba2laba( r: f64, g: f64, b: f64, a: f64, ref_x: f64, ref_y: f64, ref_z: f64, ) -> Vec<f64> { let mut r = r / 255.0; let mut g = g / 255.0; let mut b = b / 255.0; // Need lto = true in Cargo.toml to link pow r = if r > 0.04045 { ((r + 0.055) / 1.055).powf(2.4) } else { r / 12.92 }; g = if g > 0.04045 { ((g + 0.055) / 1.055).powf(2.4) } else
; b = if b > 0.04045 { ((b + 0.055) / 1.055).powf(2.4) } else { b / 12.92 }; r *= 100.0; g *= 100.0; b *= 100.0; // Observer= 2° (Only use CIE 1931!) let mut x = r * 0.4124 + g * 0.3576 + b * 0.1805; let mut y = r * 0.2126 + g * 0.7152 + b * 0.0722; let mut z = r * 0.0193 + g * 0.1192 + b * 0.9505; x /= ref_x; y /= ref_y; z /= ref_z; x = if x > 0.008856 { x.powf(1.0 / 3.0) } else { x * 7.787 + 16.0 / 116.0 }; y = if y > 0.008856 { y.powf(1.0 / 3.0) } else { y * 7.787 + 16.0 / 116.0 }; z = if z > 0.008856 { z.powf(1.0 / 3.0) } else { z * 7.787 + 16.0 / 116.0 }; let out_l = 116.0 * y - 16.0; let out_a = 500.0 * (x - y); let out_b = 200.0 * (y - z); vec![out_l, out_a, out_b, a] } #[wasm_bindgen] pub fn rgba_laba_distance( r1: f64, g1: f64, b1: f64, a1: f64, r2: f64, g2: f64, b2: f64, a2: f64, ref_x: f64, ref_y: f64, ref_z: f64, ) -> f64 { let left = rgba2laba(r1, g1, b1, a1, ref_x, ref_y, ref_z); let right = rgba2laba(r2, g2, b2, a2, ref_x, ref_y, ref_z); let dist = ((right[0] - left[0]).powf(2.0) + (right[1] - left[1]).powf(2.0) + (right[2] - left[2]).powf(2.0)).sqrt(); dist }
{ g / 12.92 }
conditional_block
settings.py
import os from django.contrib.messages import constants BASE_DIR = os.path.dirname(os.path.dirname(__file__)) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.7/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = "s%u&15u2zkg&$c)md$(6a63gg0fc85@ec=f4gnc#thfs%(w4-9" # SECURITY WARNING: don"t run with debug turned on in production! DEBUG = True TEMPLATES = [ {
], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ # Insert your TEMPLATE_CONTEXT_PROCESSORS here or use this # list if you haven't customized them: 'django.contrib.auth.context_processors.auth', 'django.template.context_processors.debug', 'django.template.context_processors.i18n', 'django.template.context_processors.media', 'django.template.context_processors.static', 'django.template.context_processors.tz', 'django.contrib.messages.context_processors.messages', ], 'debug': True }, }, ] ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = ( "django.contrib.admin", "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.sessions", "django.contrib.messages", "django.contrib.staticfiles", "django.contrib.admindocs", "converter", "authorization", ) MIDDLEWARE_CLASSES = ( "django.contrib.sessions.middleware.SessionMiddleware", "django.middleware.common.CommonMiddleware", "django.middleware.csrf.CsrfViewMiddleware", "django.contrib.auth.middleware.AuthenticationMiddleware", "django.contrib.auth.middleware.SessionAuthenticationMiddleware", "django.contrib.messages.middleware.MessageMiddleware", "django.middleware.clickjacking.XFrameOptionsMiddleware", ) ROOT_URLCONF = "portal.urls" WSGI_APPLICATION = "portal.wsgi.application" # Database # https://docs.djangoproject.com/en/1.7/ref/settings/#databases DATABASES = { "default": { "ENGINE": "django.db.backends.sqlite3", "NAME": os.path.join(BASE_DIR, "db.sqlite3"), } # 'default': { # 'ENGINE': "django.db.backends.postgresql_psycopg2", # 'NAME': 'djangodb', # 'USER': 'postgres', # 'PASSWORD': 'postgres', # 'HOST': '127.0.0.1', # 'PORT': '5432', # } } # Internationalization # https://docs.djangoproject.com/en/1.7/topics/i18n/ LANGUAGE_CODE = "en-us" TIME_ZONE = "UTC" USE_I18N = True USE_L10N = True USE_TZ = True # AUTOCOMMIT = False # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/1.7/howto/static-files/ STATICFILES_DIRS = ( os.path.join(BASE_DIR, "common-static"), ) MEDIA_ROOT = os.path.join(BASE_DIR, 'media') # print("BASE_DIR" + BASE_DIR) MEDIA_URL = '/media/' STATIC_URL = "/static/" ADMIN_MEDIA_PREFIX = "/static/admin/" MESSAGE_LEVEL = constants.DEBUG LOGGING = { "version": 1, "disable_existing_loggers": False, "formatters": { "verbose": { "format": "[%(asctime)s] %(levelname)s [%(name)s:%(lineno)s] %(message)s", "datefmt": "%d/%b/%Y %H:%M:%S" }, }, "handlers": { "file_django": { "level": "DEBUG", "class": "logging.FileHandler", "filename": "logs/django.log", "formatter": "verbose" }, "file_converter": { "level": "DEBUG", "class": "logging.FileHandler", "filename": "logs/converter.log", "formatter": "verbose" }, }, "loggers": { "django": { "handlers": ["file_django"], "propagate": True, "level": "DEBUG", }, "converter": { "handlers": ["file_converter"], "propagate": True, "level": "DEBUG", }, } }
'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ # insert your TEMPLATE_DIRS here
random_line_split
settings.py
# Django settings for example project. import os DEBUG = True TEMPLATE_DEBUG = DEBUG ADMINS = ( ('Tester', 'test@example.com'), ) MANAGERS = ADMINS DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'. 'NAME': '%s/db.sqlite' % os.path.dirname(__file__), # Or path to database file if using sqlite3. 'USER': '', # Not used with sqlite3. 'PASSWORD': '', # Not used with sqlite3. 'HOST': '', # Set to empty string for localhost. Not used with sqlite3. 'PORT': '', # Set to empty string for default. Not used with sqlite3. } } SITE_ID = 1 # Absolute filesystem path to the directory that will hold user-uploaded files. # Example: "/home/media/media.lawrence.com/media/" MEDIA_ROOT = '' # URL that handles the media served from MEDIA_ROOT. Make sure to use a # trailing slash. # Examples: "http://media.lawrence.com/media/", "http://example.com/media/" MEDIA_URL = '' # Absolute path to the directory static files should be collected to. # Don't put anything in this directory yourself; store your static files # in apps' "static/" subdirectories and in STATICFILES_DIRS. # Example: "/home/media/media.lawrence.com/static/" STATIC_ROOT = '' # URL prefix for static files. # Example: "http://media.lawrence.com/static/" STATIC_URL = '/static/' # Make this unique, and don't share it with anybody. SECRET_KEY = 'secret'
'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.admin', 'provider', 'provider.oauth2', )
ROOT_URLCONF = 'tests.urls' INSTALLED_APPS = ( 'django.contrib.auth',
random_line_split
main.rs
extern crate clap; extern crate pwhash; extern crate termios; extern crate users; use clap::{App, Arg}; use std::error; use std::fmt; use std::fs::File; use std::io::{self, BufRead, BufReader, Write}; use std::path::Path; use termios::{tcsetattr, Termios}; #[derive(Debug)]
impl From<io::Error> for Error { fn from(err: io::Error) -> Error { Error::Io(err) } } impl From<pwhash::error::Error> for Error { fn from(err: pwhash::error::Error) -> Error { Error::PwHash(err) } } impl From<String> for Error { fn from(err: String) -> Error { Error::Str(err) } } impl From<&str> for Error { fn from(err: &str) -> Error { Error::Str(err.to_owned()) } } impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { Error::Io(ref err) => write!(f, "IO error: {}", err), Error::PwHash(ref err) => write!(f, "PwHash error: {}", err), Error::Str(ref err) => f.write_str(err), } } } impl error::Error for Error { fn cause(&self) -> Option<&dyn error::Error> { match *self { Error::Io(ref err) => Some(err), Error::PwHash(ref err) => Some(err), Error::Str(_) => None, } } } /// Prompt the password of a user fn prompt_password() -> Result<String, Error> { // Disable ECHO but echo the new line character let initial_term = Termios::from_fd(0)?; let mut term = initial_term; term.c_lflag &= !termios::ECHO; term.c_lflag |= termios::ECHONL; tcsetattr(0, termios::TCSANOW, &term)?; let mut password_line = String::new(); eprint!("Password: "); let result = io::stderr() .flush() .and_then(|_| io::stdin().read_line(&mut password_line)); // Reset the initial terminal before returning a failure tcsetattr(0, termios::TCSANOW, &initial_term)?; result?; Ok(password_line .trim_end_matches(|c| c == '\r' || c == '\n') .to_string()) } /// Check a password using a `/etc/shadow` file fn check_password_in_shadow<P: AsRef<Path>>( shadow_path: P, user: &str, password_opt: Option<&str>, ) -> Result<(), Error> { let mut is_found = false; let mut prompted_password = None; let file = File::open(shadow_path)?; let file_buffer = BufReader::new(&file); for line_result in file_buffer.lines() { let line = line_result?; let fields: Vec<&str> = line.split(':').collect(); if fields.len() >= 2 && fields[0] == user { is_found = true; let password_hash = fields[1]; if password_hash == "" || password_hash == "x" || password_hash.starts_with("!") { println!("Ignoring hash {:?} for {}", password_hash, user); continue; } println!("Found hash for {}: {:?}", user, password_hash); // Prompt the user for a password if there was none provided let password = match password_opt { Some(p) => p, None => { if prompted_password.is_none() { prompted_password = Some(prompt_password()?); } prompted_password.as_ref().unwrap() } }; // TODO: use a secure hash comparison function, which is constant-time if pwhash::unix::crypt(password, password_hash)? == password_hash { println!("The password is correct :)"); return Ok(()); } } } if !is_found { return Err(Error::Str("user not found in shadow file".to_owned())); } else { return Err(Error::Str("incorrect password".to_owned())); } } /// Check a password using `unix_chkpwd` helper /// /// The source code of the helper is /// [on GitHub](https://github.com/linux-pam/linux-pam/blob/v1.3.1/modules/pam_unix/unix_chkpwd.c) fn check_password_with_helper(user: &str, password_opt: Option<&str>) -> Result<(), Error> { // Find unix_chkpwd let mut unix_chkpwd_path_opt = None; for path_dir in &["/bin", "/sbin", "/usr/bin", "/usr/sbin"] { let path = path_dir.to_string() + "/unix_chkpwd"; if std::fs::metadata(&path).is_ok() { unix_chkpwd_path_opt = Some(path); break; } } let unix_chkpwd_path = unix_chkpwd_path_opt.ok_or("unable to find unix_chkpwd helper")?; println!("Using helper {}", unix_chkpwd_path); let prompted_password; let password = match password_opt { Some(p) => p, None => { prompted_password = prompt_password()?; prompted_password.as_ref() } }; let mut child = std::process::Command::new(unix_chkpwd_path) .args(&[user, "nullok"]) .current_dir("/") .stdin(std::process::Stdio::piped()) .spawn()?; { let stdin = child.stdin.as_mut().unwrap(); stdin.write_all(password.as_bytes())?; stdin.write_all(&[0])?; } let exit_status = child.wait()?; if !exit_status.success() { if exit_status.code() == Some(7) { return Err(Error::Str("incorrect password".to_owned())); } else { return Err(Error::Str(format!("unknown exit status ({})", exit_status))); } } println!("The password is correct :)"); Ok(()) } fn main_with_result() -> Result<(), Error> { let matches = App::new("CheckLinuxPass") .version("0.1.0") .author("Nicolas Iooss") .about("Check a password on a Linux system") .arg( Arg::with_name("user") .takes_value(true) .help("name of the user to check the password"), ) .arg( Arg::with_name("password") .short("p") .long("password") .takes_value(true) .help("password to test"), ) .arg( Arg::with_name("shadow_file") .short("s") .long("shadow") .takes_value(true) .help("use a shadow file to test the password"), ) .get_matches(); let current_username; let username: &str = match matches.value_of("user") { Some(u) => u, None => { current_username = users::get_current_username().ok_or("unable to get the current user name")?; current_username .to_str() .ok_or("unable to convert the current user name to str")? } }; let password_opt = matches.value_of("password"); if let Some(shadow_path) = matches.value_of("shadow_file") { // Parse /etc/shadow in search for the user check_password_in_shadow(shadow_path, &username, password_opt)?; } else { check_password_with_helper(&username, password_opt)?; } Ok(()) } fn main() { if let Err(err) = main_with_result() { eprintln!("Error: {}", err); std::process::exit(1); } }
enum Error { Io(io::Error), PwHash(pwhash::error::Error), Str(String), }
random_line_split
main.rs
extern crate clap; extern crate pwhash; extern crate termios; extern crate users; use clap::{App, Arg}; use std::error; use std::fmt; use std::fs::File; use std::io::{self, BufRead, BufReader, Write}; use std::path::Path; use termios::{tcsetattr, Termios}; #[derive(Debug)] enum Error { Io(io::Error), PwHash(pwhash::error::Error), Str(String), } impl From<io::Error> for Error { fn from(err: io::Error) -> Error { Error::Io(err) } } impl From<pwhash::error::Error> for Error { fn from(err: pwhash::error::Error) -> Error { Error::PwHash(err) } } impl From<String> for Error { fn from(err: String) -> Error { Error::Str(err) } } impl From<&str> for Error { fn from(err: &str) -> Error { Error::Str(err.to_owned()) } } impl fmt::Display for Error { fn
(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { Error::Io(ref err) => write!(f, "IO error: {}", err), Error::PwHash(ref err) => write!(f, "PwHash error: {}", err), Error::Str(ref err) => f.write_str(err), } } } impl error::Error for Error { fn cause(&self) -> Option<&dyn error::Error> { match *self { Error::Io(ref err) => Some(err), Error::PwHash(ref err) => Some(err), Error::Str(_) => None, } } } /// Prompt the password of a user fn prompt_password() -> Result<String, Error> { // Disable ECHO but echo the new line character let initial_term = Termios::from_fd(0)?; let mut term = initial_term; term.c_lflag &= !termios::ECHO; term.c_lflag |= termios::ECHONL; tcsetattr(0, termios::TCSANOW, &term)?; let mut password_line = String::new(); eprint!("Password: "); let result = io::stderr() .flush() .and_then(|_| io::stdin().read_line(&mut password_line)); // Reset the initial terminal before returning a failure tcsetattr(0, termios::TCSANOW, &initial_term)?; result?; Ok(password_line .trim_end_matches(|c| c == '\r' || c == '\n') .to_string()) } /// Check a password using a `/etc/shadow` file fn check_password_in_shadow<P: AsRef<Path>>( shadow_path: P, user: &str, password_opt: Option<&str>, ) -> Result<(), Error> { let mut is_found = false; let mut prompted_password = None; let file = File::open(shadow_path)?; let file_buffer = BufReader::new(&file); for line_result in file_buffer.lines() { let line = line_result?; let fields: Vec<&str> = line.split(':').collect(); if fields.len() >= 2 && fields[0] == user { is_found = true; let password_hash = fields[1]; if password_hash == "" || password_hash == "x" || password_hash.starts_with("!") { println!("Ignoring hash {:?} for {}", password_hash, user); continue; } println!("Found hash for {}: {:?}", user, password_hash); // Prompt the user for a password if there was none provided let password = match password_opt { Some(p) => p, None => { if prompted_password.is_none() { prompted_password = Some(prompt_password()?); } prompted_password.as_ref().unwrap() } }; // TODO: use a secure hash comparison function, which is constant-time if pwhash::unix::crypt(password, password_hash)? == password_hash { println!("The password is correct :)"); return Ok(()); } } } if !is_found { return Err(Error::Str("user not found in shadow file".to_owned())); } else { return Err(Error::Str("incorrect password".to_owned())); } } /// Check a password using `unix_chkpwd` helper /// /// The source code of the helper is /// [on GitHub](https://github.com/linux-pam/linux-pam/blob/v1.3.1/modules/pam_unix/unix_chkpwd.c) fn check_password_with_helper(user: &str, password_opt: Option<&str>) -> Result<(), Error> { // Find unix_chkpwd let mut unix_chkpwd_path_opt = None; for path_dir in &["/bin", "/sbin", "/usr/bin", "/usr/sbin"] { let path = path_dir.to_string() + "/unix_chkpwd"; if std::fs::metadata(&path).is_ok() { unix_chkpwd_path_opt = Some(path); break; } } let unix_chkpwd_path = unix_chkpwd_path_opt.ok_or("unable to find unix_chkpwd helper")?; println!("Using helper {}", unix_chkpwd_path); let prompted_password; let password = match password_opt { Some(p) => p, None => { prompted_password = prompt_password()?; prompted_password.as_ref() } }; let mut child = std::process::Command::new(unix_chkpwd_path) .args(&[user, "nullok"]) .current_dir("/") .stdin(std::process::Stdio::piped()) .spawn()?; { let stdin = child.stdin.as_mut().unwrap(); stdin.write_all(password.as_bytes())?; stdin.write_all(&[0])?; } let exit_status = child.wait()?; if !exit_status.success() { if exit_status.code() == Some(7) { return Err(Error::Str("incorrect password".to_owned())); } else { return Err(Error::Str(format!("unknown exit status ({})", exit_status))); } } println!("The password is correct :)"); Ok(()) } fn main_with_result() -> Result<(), Error> { let matches = App::new("CheckLinuxPass") .version("0.1.0") .author("Nicolas Iooss") .about("Check a password on a Linux system") .arg( Arg::with_name("user") .takes_value(true) .help("name of the user to check the password"), ) .arg( Arg::with_name("password") .short("p") .long("password") .takes_value(true) .help("password to test"), ) .arg( Arg::with_name("shadow_file") .short("s") .long("shadow") .takes_value(true) .help("use a shadow file to test the password"), ) .get_matches(); let current_username; let username: &str = match matches.value_of("user") { Some(u) => u, None => { current_username = users::get_current_username().ok_or("unable to get the current user name")?; current_username .to_str() .ok_or("unable to convert the current user name to str")? } }; let password_opt = matches.value_of("password"); if let Some(shadow_path) = matches.value_of("shadow_file") { // Parse /etc/shadow in search for the user check_password_in_shadow(shadow_path, &username, password_opt)?; } else { check_password_with_helper(&username, password_opt)?; } Ok(()) } fn main() { if let Err(err) = main_with_result() { eprintln!("Error: {}", err); std::process::exit(1); } }
fmt
identifier_name
compare-flags.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """
""" import sys import subprocess from typing import Set from pathlib import Path # A list of known-undocumented flags. This should be considered to be a to-do # list of flags that need to be documented. EXPECTED_UNDOCUMENTED_PATH = \ Path(__file__).parent / 'expected-undocumented-flags.txt' EXPECTED_UNDOCUMENTED = \ {line for line in open(EXPECTED_UNDOCUMENTED_PATH).read().split()} def expected_undocumented(flag: str) -> bool: if flag in EXPECTED_UNDOCUMENTED: return True if flag.startswith('-Werror'): return True if flag.startswith('-Wno-') \ or flag.startswith('-dno') \ or flag.startswith('-fno') \ or flag.startswith('-XNo'): return True if flag.startswith('-Wwarn=') \ or flag.startswith('-Wno-warn='): return True return False def read_documented_flags(doc_flags) -> Set[str]: # Map characters that mark the end of a flag # to whitespace. trans = str.maketrans({ '=': ' ', '[': ' ', '⟨': ' ', }) return {line.translate(trans).split()[0] for line in doc_flags.read().split('\n') if line != ''} def read_ghc_flags(ghc_path: str) -> Set[str]: ghc_output = subprocess.check_output([ghc_path, '--show-options'], encoding='UTF-8') return {flag for flag in ghc_output.split('\n') if not expected_undocumented(flag) if flag != ''} def main() -> None: import argparse parser = argparse.ArgumentParser() parser.add_argument('--ghc', type=argparse.FileType('r'), help='path of GHC executable') parser.add_argument('--doc-flags', type=argparse.FileType('r'), help='path of ghc-flags.txt output from Sphinx') args = parser.parse_args() doc_flags = read_documented_flags(args.doc_flags) ghc_flags = read_ghc_flags(args.ghc.name) failed = False undocumented = ghc_flags - doc_flags if len(undocumented) > 0: print(f'Found {len(undocumented)} flags not documented in the users guide:') print('\n'.join(f' {flag}' for flag in sorted(undocumented))) print() failed = True now_documented = EXPECTED_UNDOCUMENTED.intersection(doc_flags) if len(now_documented) > 0: print(f'Found flags that are documented yet listed in {EXPECTED_UNDOCUMENTED_PATH}:') print('\n'.join(f' {flag}' for flag in sorted(now_documented))) print() failed = True if failed: sys.exit(1) if __name__ == '__main__': main()
Linter to verify that all flags reported by GHC's --show-options mode are documented in the user's guide.
random_line_split
compare-flags.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Linter to verify that all flags reported by GHC's --show-options mode are documented in the user's guide. """ import sys import subprocess from typing import Set from pathlib import Path # A list of known-undocumented flags. This should be considered to be a to-do # list of flags that need to be documented. EXPECTED_UNDOCUMENTED_PATH = \ Path(__file__).parent / 'expected-undocumented-flags.txt' EXPECTED_UNDOCUMENTED = \ {line for line in open(EXPECTED_UNDOCUMENTED_PATH).read().split()} def expected_undocumented(flag: str) -> bool: if flag in EXPECTED_UNDOCUMENTED: return True if flag.startswith('-Werror'): return True if flag.startswith('-Wno-') \ or flag.startswith('-dno') \ or flag.startswith('-fno') \ or flag.startswith('-XNo'): return True if flag.startswith('-Wwarn=') \ or flag.startswith('-Wno-warn='): return True return False def read_documented_flags(doc_flags) -> Set[str]: # Map characters that mark the end of a flag # to whitespace. trans = str.maketrans({ '=': ' ', '[': ' ', '⟨': ' ', }) return {line.translate(trans).split()[0] for line in doc_flags.read().split('\n') if line != ''} def read_ghc_flags(ghc_path: str) -> Set[str]: ghc_output = subprocess.check_output([ghc_path, '--show-options'], encoding='UTF-8') return {flag for flag in ghc_output.split('\n') if not expected_undocumented(flag) if flag != ''} def main() -> None: import argparse parser = argparse.ArgumentParser() parser.add_argument('--ghc', type=argparse.FileType('r'), help='path of GHC executable') parser.add_argument('--doc-flags', type=argparse.FileType('r'), help='path of ghc-flags.txt output from Sphinx') args = parser.parse_args() doc_flags = read_documented_flags(args.doc_flags) ghc_flags = read_ghc_flags(args.ghc.name) failed = False undocumented = ghc_flags - doc_flags if len(undocumented) > 0: print(f'Found {len(undocumented)} flags not documented in the users guide:') print('\n'.join(f' {flag}' for flag in sorted(undocumented))) print() failed = True now_documented = EXPECTED_UNDOCUMENTED.intersection(doc_flags) if len(now_documented) > 0: print(f'Found flags that are documented yet listed in {EXPECTED_UNDOCUMENTED_PATH}:') print('\n'.join(f' {flag}' for flag in sorted(now_documented))) print() failed = True if failed: sys.exit(1) if __name__ == '__main__': ma
in()
conditional_block
compare-flags.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Linter to verify that all flags reported by GHC's --show-options mode are documented in the user's guide. """ import sys import subprocess from typing import Set from pathlib import Path # A list of known-undocumented flags. This should be considered to be a to-do # list of flags that need to be documented. EXPECTED_UNDOCUMENTED_PATH = \ Path(__file__).parent / 'expected-undocumented-flags.txt' EXPECTED_UNDOCUMENTED = \ {line for line in open(EXPECTED_UNDOCUMENTED_PATH).read().split()} def expected_undocumented(flag: str) -> bool: if flag in EXPECTED_UNDOCUMENTED: return True if flag.startswith('-Werror'): return True if flag.startswith('-Wno-') \ or flag.startswith('-dno') \ or flag.startswith('-fno') \ or flag.startswith('-XNo'): return True if flag.startswith('-Wwarn=') \ or flag.startswith('-Wno-warn='): return True return False def read_documented_flags(doc_flags) -> Set[str]: # Map characters that mark the end of a flag # to whitespace. trans = str.maketrans({ '=': ' ', '[': ' ', '⟨': ' ', }) return {line.translate(trans).split()[0] for line in doc_flags.read().split('\n') if line != ''} def read_ghc_flags(ghc_path: str) -> Set[str]: ghc_output = subprocess.check_output([ghc_path, '--show-options'], encoding='UTF-8') return {flag for flag in ghc_output.split('\n') if not expected_undocumented(flag) if flag != ''} def main() -> None: im
if __name__ == '__main__': main()
port argparse parser = argparse.ArgumentParser() parser.add_argument('--ghc', type=argparse.FileType('r'), help='path of GHC executable') parser.add_argument('--doc-flags', type=argparse.FileType('r'), help='path of ghc-flags.txt output from Sphinx') args = parser.parse_args() doc_flags = read_documented_flags(args.doc_flags) ghc_flags = read_ghc_flags(args.ghc.name) failed = False undocumented = ghc_flags - doc_flags if len(undocumented) > 0: print(f'Found {len(undocumented)} flags not documented in the users guide:') print('\n'.join(f' {flag}' for flag in sorted(undocumented))) print() failed = True now_documented = EXPECTED_UNDOCUMENTED.intersection(doc_flags) if len(now_documented) > 0: print(f'Found flags that are documented yet listed in {EXPECTED_UNDOCUMENTED_PATH}:') print('\n'.join(f' {flag}' for flag in sorted(now_documented))) print() failed = True if failed: sys.exit(1)
identifier_body
compare-flags.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Linter to verify that all flags reported by GHC's --show-options mode are documented in the user's guide. """ import sys import subprocess from typing import Set from pathlib import Path # A list of known-undocumented flags. This should be considered to be a to-do # list of flags that need to be documented. EXPECTED_UNDOCUMENTED_PATH = \ Path(__file__).parent / 'expected-undocumented-flags.txt' EXPECTED_UNDOCUMENTED = \ {line for line in open(EXPECTED_UNDOCUMENTED_PATH).read().split()} def expected_undocumented(flag: str) -> bool: if flag in EXPECTED_UNDOCUMENTED: return True if flag.startswith('-Werror'): return True if flag.startswith('-Wno-') \ or flag.startswith('-dno') \ or flag.startswith('-fno') \ or flag.startswith('-XNo'): return True if flag.startswith('-Wwarn=') \ or flag.startswith('-Wno-warn='): return True return False def read_documented_flags(doc_flags) -> Set[str]: # Map characters that mark the end of a flag # to whitespace. trans = str.maketrans({ '=': ' ', '[': ' ', '⟨': ' ', }) return {line.translate(trans).split()[0] for line in doc_flags.read().split('\n') if line != ''} def read_ghc_flags(ghc_path: str) -> Set[str]: ghc_output = subprocess.check_output([ghc_path, '--show-options'], encoding='UTF-8') return {flag for flag in ghc_output.split('\n') if not expected_undocumented(flag) if flag != ''} def ma
-> None: import argparse parser = argparse.ArgumentParser() parser.add_argument('--ghc', type=argparse.FileType('r'), help='path of GHC executable') parser.add_argument('--doc-flags', type=argparse.FileType('r'), help='path of ghc-flags.txt output from Sphinx') args = parser.parse_args() doc_flags = read_documented_flags(args.doc_flags) ghc_flags = read_ghc_flags(args.ghc.name) failed = False undocumented = ghc_flags - doc_flags if len(undocumented) > 0: print(f'Found {len(undocumented)} flags not documented in the users guide:') print('\n'.join(f' {flag}' for flag in sorted(undocumented))) print() failed = True now_documented = EXPECTED_UNDOCUMENTED.intersection(doc_flags) if len(now_documented) > 0: print(f'Found flags that are documented yet listed in {EXPECTED_UNDOCUMENTED_PATH}:') print('\n'.join(f' {flag}' for flag in sorted(now_documented))) print() failed = True if failed: sys.exit(1) if __name__ == '__main__': main()
in()
identifier_name
xhrio.js
// Copyright 2006 The Closure Library Authors. All Rights Reserved. // // 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. /** * @fileoverview Wrapper class for handling XmlHttpRequests. * * One off requests can be sent through goog.net.XhrIo.send() or an * instance can be created to send multiple requests. Each request uses its * own XmlHttpRequest object and handles clearing of the event callback to * ensure no leaks. * * XhrIo is event based, it dispatches events when a request finishes, fails or * succeeds or when the ready-state changes. The ready-state or timeout event * fires first, followed by a generic completed event. Then the abort, error, * or success event is fired as appropriate. Lastly, the ready event will fire * to indicate that the object may be used to make another request. * * The error event may also be called before completed and * ready-state-change if the XmlHttpRequest.open() or .send() methods throw. * * This class does not support multiple requests, queuing, or prioritization. * * Tested = IE6, FF1.5, Safari, Opera 8.5 * * TODO(user): Error cases aren't playing nicely in Safari. * * */ goog.provide('goog.net.XhrIo'); goog.require('goog.Timer'); goog.require('goog.debug.Logger'); goog.require('goog.debug.entryPointRegistry'); goog.require('goog.debug.errorHandlerWeakDep'); goog.require('goog.events.EventTarget'); goog.require('goog.json'); goog.require('goog.net.ErrorCode'); goog.require('goog.net.EventType'); goog.require('goog.net.XmlHttp'); goog.require('goog.net.xhrMonitor'); goog.require('goog.structs'); goog.require('goog.structs.Map'); /** * Basic class for handling XMLHttpRequests. * @param {goog.net.XmlHttpFactory=} opt_xmlHttpFactory Factory to use when * creating XMLHttpRequest objects. * @constructor * @extends {goog.events.EventTarget} */ goog.net.XhrIo = function(opt_xmlHttpFactory) { goog.events.EventTarget.call(this); /** * Map of default headers to add to every request, use: * XhrIo.headers.set(name, value) * @type {goog.structs.Map} */ this.headers = new goog.structs.Map(); /** * Optional XmlHttpFactory * @type {goog.net.XmlHttpFactory} * @private */ this.xmlHttpFactory_ = opt_xmlHttpFactory || null; }; goog.inherits(goog.net.XhrIo, goog.events.EventTarget); /** * A reference to the XhrIo logger * @type {goog.debug.Logger} * @private */ goog.net.XhrIo.prototype.logger_ = goog.debug.Logger.getLogger('goog.net.XhrIo'); /** * The Content-Type HTTP header name * @type {string} */ goog.net.XhrIo.CONTENT_TYPE_HEADER = 'Content-Type'; /** * The Content-Type HTTP header value for a url-encoded form * @type {string} */ goog.net.XhrIo.FORM_CONTENT_TYPE = 'application/x-www-form-urlencoded;charset=utf-8'; /** * All non-disposed instances of goog.net.XhrIo created * by {@link goog.net.XhrIo.send} are in this Array. * @see goog.net.XhrIo.cleanupAllPendingStaticSends * @type {Array.<goog.net.XhrIo>} * @private */ goog.net.XhrIo.sendInstances_ = []; /** * Static send that creates a short lived instance of XhrIo to send the * request. * @see goog.net.XhrIo.cleanupAllPendingStaticSends * @param {string|goog.Uri} url Uri to make request to. * @param {Function=} opt_callback Callback function for when request is * complete. * @param {string=} opt_method Send method, default: GET. * @param {string|GearsBlob=} opt_content Post data. This can be a Gears blob * if the underlying HTTP request object is a Gears HTTP request. * @param {Object|goog.structs.Map=} opt_headers Map of headers to add to the * request. * @param {number=} opt_timeoutInterval Number of milliseconds after which an * incomplete request will be aborted; 0 means no timeout is set. */ goog.net.XhrIo.send = function(url, opt_callback, opt_method, opt_content, opt_headers, opt_timeoutInterval) { var x = new goog.net.XhrIo(); goog.net.XhrIo.sendInstances_.push(x); if (opt_callback) { goog.events.listen(x, goog.net.EventType.COMPLETE, opt_callback); } goog.events.listen(x, goog.net.EventType.READY, goog.partial(goog.net.XhrIo.cleanupSend_, x)); if (opt_timeoutInterval) { x.setTimeoutInterval(opt_timeoutInterval); } x.send(url, opt_method, opt_content, opt_headers); }; /** * Disposes all non-disposed instances of goog.net.XhrIo created by * {@link goog.net.XhrIo.send}. * {@link goog.net.XhrIo.send} cleans up the goog.net.XhrIo instance * it creates when the request completes or fails. However, if * the request never completes, then the goog.net.XhrIo is not disposed. * This can occur if the window is unloaded before the request completes. * We could have {@link goog.net.XhrIo.send} return the goog.net.XhrIo * it creates and make the client of {@link goog.net.XhrIo.send} be * responsible for disposing it in this case. However, this makes things * significantly more complicated for the client, and the whole point * of {@link goog.net.XhrIo.send} is that it's simple and easy to use. * Clients of {@link goog.net.XhrIo.send} should call * {@link goog.net.XhrIo.cleanupAllPendingStaticSends} when doing final * cleanup on window unload. */ goog.net.XhrIo.cleanup = function() { var instances = goog.net.XhrIo.sendInstances_; while (instances.length) { instances.pop().dispose(); } }; /** * Installs exception protection for all entry point introduced by * goog.net.XhrIo instances which are not protected by * {@link goog.debug.ErrorHandler#protectWindowSetTimeout}, * {@link goog.debug.ErrorHandler#protectWindowSetInterval}, or * {@link goog.events.protectBrowserEventEntryPoint}. * * @param {goog.debug.ErrorHandler} errorHandler Error handler with which to * protect the entry point(s). */ goog.net.XhrIo.protectEntryPoints = function(errorHandler) { goog.net.XhrIo.prototype.onReadyStateChangeEntryPoint_ = errorHandler.protectEntryPoint( goog.net.XhrIo.prototype.onReadyStateChangeEntryPoint_); }; /** * Disposes of the specified goog.net.XhrIo created by * {@link goog.net.XhrIo.send} and removes it from * {@link goog.net.XhrIo.pendingStaticSendInstances_}. * @param {goog.net.XhrIo} XhrIo An XhrIo created by * {@link goog.net.XhrIo.send}. * @private */ goog.net.XhrIo.cleanupSend_ = function(XhrIo) { XhrIo.dispose(); goog.array.remove(goog.net.XhrIo.sendInstances_, XhrIo); }; /** * Whether XMLHttpRequest is active. A request is active from the time send() * is called until onReadyStateChange() is complete, or error() or abort() * is called. * @type {boolean} * @private */ goog.net.XhrIo.prototype.active_ = false; /** * Reference to an XMLHttpRequest object that is being used for the transfer. * @type {XMLHttpRequest|GearsHttpRequest} * @private */ goog.net.XhrIo.prototype.xhr_ = null; /** * The options to use with the current XMLHttpRequest object. * @type {Object} * @private */ goog.net.XhrIo.prototype.xhrOptions_ = null; /** * Last URL that was requested. * @type {string|goog.Uri} * @private */ goog.net.XhrIo.prototype.lastUri_ = ''; /** * Method for the last request. * @type {string} * @private */ goog.net.XhrIo.prototype.lastMethod_ = ''; /** * Last error code. * @type {goog.net.ErrorCode} * @private */ goog.net.XhrIo.prototype.lastErrorCode_ = goog.net.ErrorCode.NO_ERROR; /** * Last error message. * @type {Error|string} * @private */ goog.net.XhrIo.prototype.lastError_ = ''; /** * This is used to ensure that we don't dispatch an multiple ERROR events. This * can happen in IE when it does a synchronous load and one error is handled in * the ready statte change and one is handled due to send() throwing an * exception. * @type {boolean} * @private */ goog.net.XhrIo.prototype.errorDispatched_ = false; /** * Used to make sure we don't fire the complete event from inside a send call. * @type {boolean} * @private */ goog.net.XhrIo.prototype.inSend_ = false; /** * Used in determining if a call to {@link #onReadyStateChange_} is from within * a call to this.xhr_.open. * @type {boolean} * @private */ goog.net.XhrIo.prototype.inOpen_ = false; /** * Used in determining if a call to {@link #onReadyStateChange_} is from within * a call to this.xhr_.abort. * @type {boolean} * @private */ goog.net.XhrIo.prototype.inAbort_ = false; /** * Number of milliseconds after which an incomplete request will be aborted and * a {@link goog.net.EventType.TIMEOUT} event raised; 0 means no timeout is set. * @type {number} * @private */ goog.net.XhrIo.prototype.timeoutInterval_ = 0; /** * Window timeout ID used to cancel the timeout event handler if the request * completes successfully. * @type {Object} * @private */ goog.net.XhrIo.prototype.timeoutId_ = null; /** * Returns the number of milliseconds after which an incomplete request will be * aborted, or 0 if no timeout is set. * @return {number} Timeout interval in milliseconds. */ goog.net.XhrIo.prototype.getTimeoutInterval = function() { return this.timeoutInterval_; }; /** * Sets the number of milliseconds after which an incomplete request will be * aborted and a {@link goog.net.EventType.TIMEOUT} event raised; 0 means no * timeout is set. * @param {number} ms Timeout interval in milliseconds; 0 means none. */ goog.net.XhrIo.prototype.setTimeoutInterval = function(ms) { this.timeoutInterval_ = Math.max(0, ms); }; /** * Instance send that actually uses XMLHttpRequest to make a server call. * @param {string|goog.Uri} url Uri to make request to. * @param {string=} opt_method Send method, default: GET. * @param {string|GearsBlob=} opt_content Post data. This can be a Gears blob * if the underlying HTTP request object is a Gears HTTP request. * @param {Object|goog.structs.Map=} opt_headers Map of headers to add to the * request. */ goog.net.XhrIo.prototype.send = function(url, opt_method, opt_content, opt_headers) { if (this.xhr_) { throw Error('[goog.net.XhrIo] Object is active with another request'); } var method = opt_method || 'GET'; this.lastUri_ = url; this.lastError_ = ''; this.lastErrorCode_ = goog.net.ErrorCode.NO_ERROR; this.lastMethod_ = method; this.errorDispatched_ = false; this.active_ = true; // Use the factory to create the XHR object and options this.xhr_ = this.createXhr(); this.xhrOptions_ = this.xmlHttpFactory_ ? this.xmlHttpFactory_.getOptions() : goog.net.XmlHttp.getOptions(); // We tell the Xhr Monitor that we are opening an XMLHttpRequest. This stops // IframeIo from destroying iframes that may have been the source of the // execution context, which can result in an error in FF. See xhrmonitor.js // for more details. goog.net.xhrMonitor.markXhrOpen(this.xhr_); // Set up the onreadystatechange callback this.xhr_.onreadystatechange = goog.bind(this.onReadyStateChange_, this); /** * Try to open the XMLHttpRequest (always async), if an error occurs here it * is generally permission denied * @preserveTry */ try { this.logger_.fine(this.formatMsg_('Opening Xhr')); this.inOpen_ = true; this.xhr_.open(method, url, true); // Always async! this.inOpen_ = false; } catch (err) { this.logger_.fine(this.formatMsg_('Error opening Xhr: ' + err.message)); this.error_(goog.net.ErrorCode.EXCEPTION, err); return; } // We can't use null since this won't allow POSTs to have a content length // specified which will cause some proxies to return a 411 error. var content = opt_content || ''; var headers = this.headers.clone(); // Add headers specific to this request if (opt_headers) { goog.structs.forEach(opt_headers, function(value, key) { headers.set(key, value); }); } if (method == 'POST' && !headers.containsKey(goog.net.XhrIo.CONTENT_TYPE_HEADER)) { // For POST requests, default to the url-encoded form content type. headers.set(goog.net.XhrIo.CONTENT_TYPE_HEADER, goog.net.XhrIo.FORM_CONTENT_TYPE); } // Add the headers to the Xhr object goog.structs.forEach(headers, function(value, key) { this.xhr_.setRequestHeader(key, value); }, this); /** * Try to send the request, or other wise report an error (404 not found). * @preserveTry */ try { if (this.timeoutId_) { // This should never happen, since the if (this.active_) above shouldn't // let execution reach this point if there is a request in progress... goog.Timer.defaultTimerObject.clearTimeout(this.timeoutId_); this.timeoutId_ = null; } if (this.timeoutInterval_ > 0) { this.logger_.fine(this.formatMsg_('Will abort after ' + this.timeoutInterval_ + 'ms if incomplete')); this.timeoutId_ = goog.Timer.defaultTimerObject.setTimeout( goog.bind(this.timeout_, this), this.timeoutInterval_); } this.logger_.fine(this.formatMsg_('Sending request')); this.inSend_ = true; this.xhr_.send(content); this.inSend_ = false; } catch (err) { this.logger_.fine(this.formatMsg_('Send error: ' + err.message)); this.error_(goog.net.ErrorCode.EXCEPTION, err); } }; /** * Creates a new XHR object. * @return {XMLHttpRequest|GearsHttpRequest} The newly created XHR object. * @protected */ goog.net.XhrIo.prototype.createXhr = function() { return this.xmlHttpFactory_ ? this.xmlHttpFactory_.createInstance() : new goog.net.XmlHttp(); }; /** * Override of dispatchEvent. We need to keep track if an XMLHttpRequest is * being sent from the context of another requests' repsonse. If it is then, we * make the XHR send async. * @param {goog.events.Event|string} e Event to dispatch. * @return {boolean} Whether the dispatch completed without a handler calling * preventDefault. */ goog.net.XhrIo.prototype.dispatchEvent = function(e) { if (this.xhr_) { goog.net.xhrMonitor.pushContext(this.xhr_); try { return goog.net.XhrIo.superClass_.dispatchEvent.call(this, e); } finally { goog.net.xhrMonitor.popContext(); } } else { return goog.net.XhrIo.superClass_.dispatchEvent.call(this, e); } }; /** * The request didn't complete after {@link goog.net.XhrIo#timeoutInterval_} * milliseconds; raises a {@link goog.net.EventType.TIMEOUT} event and aborts * the request. * @private */ goog.net.XhrIo.prototype.timeout_ = function() { if (typeof goog == 'undefined') { // If goog is undefined then the callback has occurred as the application // is unloading and will error. Thus we let it silently fail. } else if (this.xhr_) { this.lastError_ = 'Timed out after ' + this.timeoutInterval_ + 'ms, aborting'; this.lastErrorCode_ = goog.net.ErrorCode.TIMEOUT; this.logger_.fine(this.formatMsg_(this.lastError_)); this.dispatchEvent(goog.net.EventType.TIMEOUT); this.abort(goog.net.ErrorCode.TIMEOUT); } }; /** * Something errorred, so inactivate, fire error callback and clean up * @param {goog.net.ErrorCode} errorCode The error code. * @param {Error} err The error object. * @private */ goog.net.XhrIo.prototype.error_ = function(errorCode, err) { this.active_ = false; if (this.xhr_) { this.inAbort_ = true; this.xhr_.abort(); // Ensures XHR isn't hung (FF) this.inAbort_ = false; } this.lastError_ = err; this.lastErrorCode_ = errorCode; this.dispatchErrors_(); this.cleanUpXhr_(); }; /** * Dispatches COMPLETE and ERROR in case of an error. This ensures that we do * not dispatch multiple error events. * @private */ goog.net.XhrIo.prototype.dispatchErrors_ = function() { if (!this.errorDispatched_) { this.errorDispatched_ = true; this.dispatchEvent(goog.net.EventType.COMPLETE); this.dispatchEvent(goog.net.EventType.ERROR); } }; /** * Abort the current XMLHttpRequest * @param {goog.net.ErrorCode=} opt_failureCode Optional error code to use - * defaults to ABORT. */ goog.net.XhrIo.prototype.abort = function(opt_failureCode) { if (this.xhr_ && this.active_) { this.logger_.fine(this.formatMsg_('Aborting')); this.active_ = false; this.inAbort_ = true; this.xhr_.abort(); this.inAbort_ = false; this.lastErrorCode_ = opt_failureCode || goog.net.ErrorCode.ABORT; this.dispatchEvent(goog.net.EventType.COMPLETE); this.dispatchEvent(goog.net.EventType.ABORT); this.cleanUpXhr_(); } }; /** * Nullifies all callbacks to reduce risks of leaks. */ goog.net.XhrIo.prototype.disposeInternal = function() { if (this.xhr_) { // We explicitly do not call xhr_.abort() unless active_ is still true. // This is to avoid unnecessarily aborting a successful request when // disposeInternal() is called in a callback triggered by a complete // response, but in which browser cleanup has not yet finished. // (See http://b/issue?id=1684217.) if (this.active_) { this.active_ = false; this.inAbort_ = true; this.xhr_.abort(); this.inAbort_ = false; } this.cleanUpXhr_(true); } goog.net.XhrIo.superClass_.disposeInternal.call(this); }; /** * Internal handler for the XHR object's readystatechange event. This method * checks the status and the readystate and fires the correct callbacks. * If the request has ended, the handlers are cleaned up and the XHR object is * nullified. * @private */ goog.net.XhrIo.prototype.onReadyStateChange_ = function() { if (!this.inOpen_ && !this.inSend_ && !this.inAbort_) { // Were not being called from within a call to this.xhr_.send // this.xhr_.abort, or this.xhr_.open, so this is an entry point this.onReadyStateChangeEntryPoint_(); } else { this.onReadyStateChangeHelper_(); } }; /** * Used to protect the onreadystatechange handler entry point. Necessary * as {#onReadyStateChange_} maybe called from within send or abort, this * method is only called when {#onReadyStateChange_} is called as an * entry point. * {@see #protectEntryPoints} * @private */ goog.net.XhrIo.prototype.onReadyStateChangeEntryPoint_ = function() { this.onReadyStateChangeHelper_(); }; /** * Helper for {@link #onReadyStateChange_}. This is used so that * entry point calls to {@link #onReadyStateChange_} can be routed through * {@link #onReadyStateChangeEntryPoint_}. * @private */ goog.net.XhrIo.prototype.onReadyStateChangeHelper_ = function() { if (!this.active_) { // can get called inside abort call return; } if (typeof goog == 'undefined') { // NOTE(user): If goog is undefined then the callback has occurred as the // application is unloading and will error. Thus we let it silently fail. } else if ( this.xhrOptions_[goog.net.XmlHttp.OptionType.LOCAL_REQUEST_ERROR] && this.getReadyState() == goog.net.XmlHttp.ReadyState.COMPLETE && this.getStatus() == 2) { // NOTE(user): In IE if send() errors on a *local* request the readystate // is still changed to COMPLETE. We need to ignore it and allow the // try/catch around send() to pick up the error. this.logger_.fine(this.formatMsg_( 'Local request error detected and ignored')); } else { // In IE when the response has been cached we sometimes get the callback // from inside the send call and this usually breaks code that assumes that // XhrIo is asynchronous. If that is the case we delay the callback // using a timer. if (this.inSend_ && this.getReadyState() == goog.net.XmlHttp.ReadyState.COMPLETE) { goog.Timer.defaultTimerObject.setTimeout( goog.bind(this.onReadyStateChange_, this), 0); return; } this.dispatchEvent(goog.net.EventType.READY_STATE_CHANGE); // readyState indicates the transfer has finished if (this.isComplete()) { this.logger_.fine(this.formatMsg_('Request complete')); this.active_ = false; // Call the specific callbacks for success or failure. Only call the // success if the status is 200 (HTTP_OK) or 304 (HTTP_CACHED) if (this.isSuccess()) { this.dispatchEvent(goog.net.EventType.COMPLETE); this.dispatchEvent(goog.net.EventType.SUCCESS); } else { this.lastErrorCode_ = goog.net.ErrorCode.HTTP_ERROR; this.lastError_ = this.getStatusText() + ' [' + this.getStatus() + ']'; this.dispatchErrors_(); } this.cleanUpXhr_(); } } }; /** * Remove the listener to protect against leaks, and nullify the XMLHttpRequest * object. * @param {boolean=} opt_fromDispose If this is from the dispose (don't want to * fire any events). * @private */ goog.net.XhrIo.prototype.cleanUpXhr_ = function(opt_fromDispose) { if (this.xhr_) { // Save reference so we can mark it as closed after the READY event. The // READY event may trigger another request, thus we must nullify this.xhr_ var xhr = this.xhr_; var clearedOnReadyStateChange = this.xhrOptions_[goog.net.XmlHttp.OptionType.USE_NULL_FUNCTION] ? goog.nullFunction : null; this.xhr_ = null; this.xhrOptions_ = null; if (this.timeoutId_) { // Cancel any pending timeout event handler. goog.Timer.defaultTimerObject.clearTimeout(this.timeoutId_); this.timeoutId_ = null; } if (!opt_fromDispose) { goog.net.xhrMonitor.pushContext(xhr); this.dispatchEvent(goog.net.EventType.READY); goog.net.xhrMonitor.popContext(); } // Mark the request as having completed. goog.net.xhrMonitor.markXhrClosed(xhr); try { // NOTE(user): Not nullifying in FireFox can still leak if the callbacks // are defined in the same scope as the instance of XhrIo. But, IE doesn't // allow you to set the onreadystatechange to NULL so nullFunction is // used. xhr.onreadystatechange = clearedOnReadyStateChange; } catch (e) { // This seems to occur with a Gears HTTP request. Delayed the setting of // this onreadystatechange until after READY is sent out and catching the // error to see if we can track down the problem. this.logger_.severe('Problem encountered resetting onreadystatechange: ' + e.message); } } }; /** * @return {boolean} Whether there is an active request. */ goog.net.XhrIo.prototype.isActive = function() { return !!this.xhr_; }; /** * @return {boolean} Whether the request has completed. */ goog.net.XhrIo.prototype.isComplete = function() { return this.getReadyState() == goog.net.XmlHttp.ReadyState.COMPLETE; }; /** * @return {boolean} Whether the request completed with a success. */ goog.net.XhrIo.prototype.isSuccess = function() { switch (this.getStatus()) { case 0: // Used for local XHR requests case 200: // Http Success case 204: // Http Success - no content case 304: // Http Cache return true; default: return false; } }; /** * Get the readystate from the Xhr object * Will only return correct result when called from the context of a callback * @return {goog.net.XmlHttp.ReadyState} goog.net.XmlHttp.ReadyState.*. */ goog.net.XhrIo.prototype.getReadyState = function() { return this.xhr_ ? /** @type {goog.net.XmlHttp.ReadyState} */ (this.xhr_.readyState) : goog.net.XmlHttp.ReadyState.UNINITIALIZED; }; /** * Get the status from the Xhr object * Will only return correct result when called from the context of a callback * @return {number} Http status. */ goog.net.XhrIo.prototype.getStatus = function() { /** * IE doesn't like you checking status until the readystate is greater than 2 * (i.e. it is recieving or complete). The try/catch is used for when the * page is unloading and an ERROR_NOT_AVAILABLE may occur when accessing xhr_. * @preserveTry */ try { return this.getReadyState() > goog.net.XmlHttp.ReadyState.LOADED ? this.xhr_.status : -1; } catch (e) { this.logger_.warning('Can not get status: ' + e.message); return -1; } }; /** * Get the status text from the Xhr object * Will only return correct result when called from the context of a callback * @return {string} Status text. */ goog.net.XhrIo.prototype.getStatusText = function() { /** * IE doesn't like you checking status until the readystate is greater than 2 * (i.e. it is recieving or complete). The try/catch is used for when the * page is unloading and an ERROR_NOT_AVAILABLE may occur when accessing xhr_. * @preserveTry */ try { return this.getReadyState() > goog.net.XmlHttp.ReadyState.LOADED ? this.xhr_.statusText : ''; } catch (e) { this.logger_.fine('Can not get status: ' + e.message); return ''; } }; /** * Get the last Uri that was requested * @return {string} Last Uri. */ goog.net.XhrIo.prototype.getLastUri = function() { return String(this.lastUri_); }; /** * Get the response text from the Xhr object * Will only return correct result when called from the context of a callback. * @return {string} Result from the server, or '' if no result available. */ goog.net.XhrIo.prototype.getResponseText = function() { /** @preserveTry */ try { return this.xhr_ ? this.xhr_.responseText : ''; } catch (e) { // http://www.w3.org/TR/XMLHttpRequest/#the-responsetext-attribute // states that responseText should return '' (and responseXML null) // when the state is not LOADING or DONE. Instead, IE and Gears can // throw unexpected exceptions, eg, when a request is aborted or no // data is available yet. this.logger_.fine('Can not get responseText: ' + e.message); return ''; } }; /** * Get the response XML from the Xhr object * Will only return correct result when called from the context of a callback. * @return {Document} The DOM Document representing the XML file, or null * if no result available. */ goog.net.XhrIo.prototype.getResponseXml = function() { /** @preserveTry */ try { return this.xhr_ ? this.xhr_.responseXML : null; } catch (e) { this.logger_.fine('Can not get responseXML: ' + e.message); return null; } }; /** * Get the response and evaluates it as JSON from the Xhr object * Will only return correct result when called from the context of a callback
goog.net.XhrIo.prototype.getResponseJson = function(opt_xssiPrefix) { if (!this.xhr_) { return undefined; } var responseText = this.xhr_.responseText; if (opt_xssiPrefix && responseText.indexOf(opt_xssiPrefix) == 0) { responseText = responseText.substring(opt_xssiPrefix.length); } return goog.json.parse(responseText); }; /** * Get the value of the response-header with the given name from the Xhr object * Will only return correct result when called from the context of a callback * and the request has completed * @param {string} key The name of the response-header to retrieve. * @return {string|undefined} The value of the response-header named key. */ goog.net.XhrIo.prototype.getResponseHeader = function(key) { return this.xhr_ && this.isComplete() ? this.xhr_.getResponseHeader(key) : undefined; }; /** * Gets the text of all the headers in the response. * Will only return correct result when called from the context of a callback * and the request has completed. * @return {string} The value of the response headers or empty string. */ goog.net.XhrIo.prototype.getAllResponseHeaders = function() { return this.xhr_ && this.isComplete() ? this.xhr_.getAllResponseHeaders() : ''; }; /** * Get the last error message * @return {goog.net.ErrorCode} Last error code. */ goog.net.XhrIo.prototype.getLastErrorCode = function() { return this.lastErrorCode_; }; /** * Get the last error message * @return {string} Last error message. */ goog.net.XhrIo.prototype.getLastError = function() { return goog.isString(this.lastError_) ? this.lastError_ : String(this.lastError_); }; /** * Adds the last method, status and URI to the message. This is used to add * this information to the logging calls. * @param {string} msg The message text that we want to add the extra text to. * @return {string} The message with the extra text appended. * @private */ goog.net.XhrIo.prototype.formatMsg_ = function(msg) { return msg + ' [' + this.lastMethod_ + ' ' + this.lastUri_ + ' ' + this.getStatus() + ']'; }; // Register the xhr handler as an entry point, so that // it can be monitored for exception handling, etc. goog.debug.entryPointRegistry.register( /** * @param {function(!Function): !Function} transformer The transforming * function. */ function(transformer) { goog.net.XhrIo.prototype.onReadyStateChangeEntryPoint_ = transformer(goog.net.XhrIo.prototype.onReadyStateChangeEntryPoint_); });
* @param {string=} opt_xssiPrefix Optional XSSI prefix string to use for * stripping of the response before parsing. This needs to be set only if * your backend server prepends the same prefix string to the JSON response. * @return {Object|undefined} JavaScript object. */
random_line_split
xhrio.js
// Copyright 2006 The Closure Library Authors. All Rights Reserved. // // 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. /** * @fileoverview Wrapper class for handling XmlHttpRequests. * * One off requests can be sent through goog.net.XhrIo.send() or an * instance can be created to send multiple requests. Each request uses its * own XmlHttpRequest object and handles clearing of the event callback to * ensure no leaks. * * XhrIo is event based, it dispatches events when a request finishes, fails or * succeeds or when the ready-state changes. The ready-state or timeout event * fires first, followed by a generic completed event. Then the abort, error, * or success event is fired as appropriate. Lastly, the ready event will fire * to indicate that the object may be used to make another request. * * The error event may also be called before completed and * ready-state-change if the XmlHttpRequest.open() or .send() methods throw. * * This class does not support multiple requests, queuing, or prioritization. * * Tested = IE6, FF1.5, Safari, Opera 8.5 * * TODO(user): Error cases aren't playing nicely in Safari. * * */ goog.provide('goog.net.XhrIo'); goog.require('goog.Timer'); goog.require('goog.debug.Logger'); goog.require('goog.debug.entryPointRegistry'); goog.require('goog.debug.errorHandlerWeakDep'); goog.require('goog.events.EventTarget'); goog.require('goog.json'); goog.require('goog.net.ErrorCode'); goog.require('goog.net.EventType'); goog.require('goog.net.XmlHttp'); goog.require('goog.net.xhrMonitor'); goog.require('goog.structs'); goog.require('goog.structs.Map'); /** * Basic class for handling XMLHttpRequests. * @param {goog.net.XmlHttpFactory=} opt_xmlHttpFactory Factory to use when * creating XMLHttpRequest objects. * @constructor * @extends {goog.events.EventTarget} */ goog.net.XhrIo = function(opt_xmlHttpFactory) { goog.events.EventTarget.call(this); /** * Map of default headers to add to every request, use: * XhrIo.headers.set(name, value) * @type {goog.structs.Map} */ this.headers = new goog.structs.Map(); /** * Optional XmlHttpFactory * @type {goog.net.XmlHttpFactory} * @private */ this.xmlHttpFactory_ = opt_xmlHttpFactory || null; }; goog.inherits(goog.net.XhrIo, goog.events.EventTarget); /** * A reference to the XhrIo logger * @type {goog.debug.Logger} * @private */ goog.net.XhrIo.prototype.logger_ = goog.debug.Logger.getLogger('goog.net.XhrIo'); /** * The Content-Type HTTP header name * @type {string} */ goog.net.XhrIo.CONTENT_TYPE_HEADER = 'Content-Type'; /** * The Content-Type HTTP header value for a url-encoded form * @type {string} */ goog.net.XhrIo.FORM_CONTENT_TYPE = 'application/x-www-form-urlencoded;charset=utf-8'; /** * All non-disposed instances of goog.net.XhrIo created * by {@link goog.net.XhrIo.send} are in this Array. * @see goog.net.XhrIo.cleanupAllPendingStaticSends * @type {Array.<goog.net.XhrIo>} * @private */ goog.net.XhrIo.sendInstances_ = []; /** * Static send that creates a short lived instance of XhrIo to send the * request. * @see goog.net.XhrIo.cleanupAllPendingStaticSends * @param {string|goog.Uri} url Uri to make request to. * @param {Function=} opt_callback Callback function for when request is * complete. * @param {string=} opt_method Send method, default: GET. * @param {string|GearsBlob=} opt_content Post data. This can be a Gears blob * if the underlying HTTP request object is a Gears HTTP request. * @param {Object|goog.structs.Map=} opt_headers Map of headers to add to the * request. * @param {number=} opt_timeoutInterval Number of milliseconds after which an * incomplete request will be aborted; 0 means no timeout is set. */ goog.net.XhrIo.send = function(url, opt_callback, opt_method, opt_content, opt_headers, opt_timeoutInterval) { var x = new goog.net.XhrIo(); goog.net.XhrIo.sendInstances_.push(x); if (opt_callback) { goog.events.listen(x, goog.net.EventType.COMPLETE, opt_callback); } goog.events.listen(x, goog.net.EventType.READY, goog.partial(goog.net.XhrIo.cleanupSend_, x)); if (opt_timeoutInterval) { x.setTimeoutInterval(opt_timeoutInterval); } x.send(url, opt_method, opt_content, opt_headers); }; /** * Disposes all non-disposed instances of goog.net.XhrIo created by * {@link goog.net.XhrIo.send}. * {@link goog.net.XhrIo.send} cleans up the goog.net.XhrIo instance * it creates when the request completes or fails. However, if * the request never completes, then the goog.net.XhrIo is not disposed. * This can occur if the window is unloaded before the request completes. * We could have {@link goog.net.XhrIo.send} return the goog.net.XhrIo * it creates and make the client of {@link goog.net.XhrIo.send} be * responsible for disposing it in this case. However, this makes things * significantly more complicated for the client, and the whole point * of {@link goog.net.XhrIo.send} is that it's simple and easy to use. * Clients of {@link goog.net.XhrIo.send} should call * {@link goog.net.XhrIo.cleanupAllPendingStaticSends} when doing final * cleanup on window unload. */ goog.net.XhrIo.cleanup = function() { var instances = goog.net.XhrIo.sendInstances_; while (instances.length) { instances.pop().dispose(); } }; /** * Installs exception protection for all entry point introduced by * goog.net.XhrIo instances which are not protected by * {@link goog.debug.ErrorHandler#protectWindowSetTimeout}, * {@link goog.debug.ErrorHandler#protectWindowSetInterval}, or * {@link goog.events.protectBrowserEventEntryPoint}. * * @param {goog.debug.ErrorHandler} errorHandler Error handler with which to * protect the entry point(s). */ goog.net.XhrIo.protectEntryPoints = function(errorHandler) { goog.net.XhrIo.prototype.onReadyStateChangeEntryPoint_ = errorHandler.protectEntryPoint( goog.net.XhrIo.prototype.onReadyStateChangeEntryPoint_); }; /** * Disposes of the specified goog.net.XhrIo created by * {@link goog.net.XhrIo.send} and removes it from * {@link goog.net.XhrIo.pendingStaticSendInstances_}. * @param {goog.net.XhrIo} XhrIo An XhrIo created by * {@link goog.net.XhrIo.send}. * @private */ goog.net.XhrIo.cleanupSend_ = function(XhrIo) { XhrIo.dispose(); goog.array.remove(goog.net.XhrIo.sendInstances_, XhrIo); }; /** * Whether XMLHttpRequest is active. A request is active from the time send() * is called until onReadyStateChange() is complete, or error() or abort() * is called. * @type {boolean} * @private */ goog.net.XhrIo.prototype.active_ = false; /** * Reference to an XMLHttpRequest object that is being used for the transfer. * @type {XMLHttpRequest|GearsHttpRequest} * @private */ goog.net.XhrIo.prototype.xhr_ = null; /** * The options to use with the current XMLHttpRequest object. * @type {Object} * @private */ goog.net.XhrIo.prototype.xhrOptions_ = null; /** * Last URL that was requested. * @type {string|goog.Uri} * @private */ goog.net.XhrIo.prototype.lastUri_ = ''; /** * Method for the last request. * @type {string} * @private */ goog.net.XhrIo.prototype.lastMethod_ = ''; /** * Last error code. * @type {goog.net.ErrorCode} * @private */ goog.net.XhrIo.prototype.lastErrorCode_ = goog.net.ErrorCode.NO_ERROR; /** * Last error message. * @type {Error|string} * @private */ goog.net.XhrIo.prototype.lastError_ = ''; /** * This is used to ensure that we don't dispatch an multiple ERROR events. This * can happen in IE when it does a synchronous load and one error is handled in * the ready statte change and one is handled due to send() throwing an * exception. * @type {boolean} * @private */ goog.net.XhrIo.prototype.errorDispatched_ = false; /** * Used to make sure we don't fire the complete event from inside a send call. * @type {boolean} * @private */ goog.net.XhrIo.prototype.inSend_ = false; /** * Used in determining if a call to {@link #onReadyStateChange_} is from within * a call to this.xhr_.open. * @type {boolean} * @private */ goog.net.XhrIo.prototype.inOpen_ = false; /** * Used in determining if a call to {@link #onReadyStateChange_} is from within * a call to this.xhr_.abort. * @type {boolean} * @private */ goog.net.XhrIo.prototype.inAbort_ = false; /** * Number of milliseconds after which an incomplete request will be aborted and * a {@link goog.net.EventType.TIMEOUT} event raised; 0 means no timeout is set. * @type {number} * @private */ goog.net.XhrIo.prototype.timeoutInterval_ = 0; /** * Window timeout ID used to cancel the timeout event handler if the request * completes successfully. * @type {Object} * @private */ goog.net.XhrIo.prototype.timeoutId_ = null; /** * Returns the number of milliseconds after which an incomplete request will be * aborted, or 0 if no timeout is set. * @return {number} Timeout interval in milliseconds. */ goog.net.XhrIo.prototype.getTimeoutInterval = function() { return this.timeoutInterval_; }; /** * Sets the number of milliseconds after which an incomplete request will be * aborted and a {@link goog.net.EventType.TIMEOUT} event raised; 0 means no * timeout is set. * @param {number} ms Timeout interval in milliseconds; 0 means none. */ goog.net.XhrIo.prototype.setTimeoutInterval = function(ms) { this.timeoutInterval_ = Math.max(0, ms); }; /** * Instance send that actually uses XMLHttpRequest to make a server call. * @param {string|goog.Uri} url Uri to make request to. * @param {string=} opt_method Send method, default: GET. * @param {string|GearsBlob=} opt_content Post data. This can be a Gears blob * if the underlying HTTP request object is a Gears HTTP request. * @param {Object|goog.structs.Map=} opt_headers Map of headers to add to the * request. */ goog.net.XhrIo.prototype.send = function(url, opt_method, opt_content, opt_headers) { if (this.xhr_) { throw Error('[goog.net.XhrIo] Object is active with another request'); } var method = opt_method || 'GET'; this.lastUri_ = url; this.lastError_ = ''; this.lastErrorCode_ = goog.net.ErrorCode.NO_ERROR; this.lastMethod_ = method; this.errorDispatched_ = false; this.active_ = true; // Use the factory to create the XHR object and options this.xhr_ = this.createXhr(); this.xhrOptions_ = this.xmlHttpFactory_ ? this.xmlHttpFactory_.getOptions() : goog.net.XmlHttp.getOptions(); // We tell the Xhr Monitor that we are opening an XMLHttpRequest. This stops // IframeIo from destroying iframes that may have been the source of the // execution context, which can result in an error in FF. See xhrmonitor.js // for more details. goog.net.xhrMonitor.markXhrOpen(this.xhr_); // Set up the onreadystatechange callback this.xhr_.onreadystatechange = goog.bind(this.onReadyStateChange_, this); /** * Try to open the XMLHttpRequest (always async), if an error occurs here it * is generally permission denied * @preserveTry */ try { this.logger_.fine(this.formatMsg_('Opening Xhr')); this.inOpen_ = true; this.xhr_.open(method, url, true); // Always async! this.inOpen_ = false; } catch (err) { this.logger_.fine(this.formatMsg_('Error opening Xhr: ' + err.message)); this.error_(goog.net.ErrorCode.EXCEPTION, err); return; } // We can't use null since this won't allow POSTs to have a content length // specified which will cause some proxies to return a 411 error. var content = opt_content || ''; var headers = this.headers.clone(); // Add headers specific to this request if (opt_headers) { goog.structs.forEach(opt_headers, function(value, key) { headers.set(key, value); }); } if (method == 'POST' && !headers.containsKey(goog.net.XhrIo.CONTENT_TYPE_HEADER)) { // For POST requests, default to the url-encoded form content type. headers.set(goog.net.XhrIo.CONTENT_TYPE_HEADER, goog.net.XhrIo.FORM_CONTENT_TYPE); } // Add the headers to the Xhr object goog.structs.forEach(headers, function(value, key) { this.xhr_.setRequestHeader(key, value); }, this); /** * Try to send the request, or other wise report an error (404 not found). * @preserveTry */ try { if (this.timeoutId_) { // This should never happen, since the if (this.active_) above shouldn't // let execution reach this point if there is a request in progress... goog.Timer.defaultTimerObject.clearTimeout(this.timeoutId_); this.timeoutId_ = null; } if (this.timeoutInterval_ > 0) { this.logger_.fine(this.formatMsg_('Will abort after ' + this.timeoutInterval_ + 'ms if incomplete')); this.timeoutId_ = goog.Timer.defaultTimerObject.setTimeout( goog.bind(this.timeout_, this), this.timeoutInterval_); } this.logger_.fine(this.formatMsg_('Sending request')); this.inSend_ = true; this.xhr_.send(content); this.inSend_ = false; } catch (err) { this.logger_.fine(this.formatMsg_('Send error: ' + err.message)); this.error_(goog.net.ErrorCode.EXCEPTION, err); } }; /** * Creates a new XHR object. * @return {XMLHttpRequest|GearsHttpRequest} The newly created XHR object. * @protected */ goog.net.XhrIo.prototype.createXhr = function() { return this.xmlHttpFactory_ ? this.xmlHttpFactory_.createInstance() : new goog.net.XmlHttp(); }; /** * Override of dispatchEvent. We need to keep track if an XMLHttpRequest is * being sent from the context of another requests' repsonse. If it is then, we * make the XHR send async. * @param {goog.events.Event|string} e Event to dispatch. * @return {boolean} Whether the dispatch completed without a handler calling * preventDefault. */ goog.net.XhrIo.prototype.dispatchEvent = function(e) { if (this.xhr_) { goog.net.xhrMonitor.pushContext(this.xhr_); try { return goog.net.XhrIo.superClass_.dispatchEvent.call(this, e); } finally { goog.net.xhrMonitor.popContext(); } } else { return goog.net.XhrIo.superClass_.dispatchEvent.call(this, e); } }; /** * The request didn't complete after {@link goog.net.XhrIo#timeoutInterval_} * milliseconds; raises a {@link goog.net.EventType.TIMEOUT} event and aborts * the request. * @private */ goog.net.XhrIo.prototype.timeout_ = function() { if (typeof goog == 'undefined') { // If goog is undefined then the callback has occurred as the application // is unloading and will error. Thus we let it silently fail. } else if (this.xhr_) { this.lastError_ = 'Timed out after ' + this.timeoutInterval_ + 'ms, aborting'; this.lastErrorCode_ = goog.net.ErrorCode.TIMEOUT; this.logger_.fine(this.formatMsg_(this.lastError_)); this.dispatchEvent(goog.net.EventType.TIMEOUT); this.abort(goog.net.ErrorCode.TIMEOUT); } }; /** * Something errorred, so inactivate, fire error callback and clean up * @param {goog.net.ErrorCode} errorCode The error code. * @param {Error} err The error object. * @private */ goog.net.XhrIo.prototype.error_ = function(errorCode, err) { this.active_ = false; if (this.xhr_) { this.inAbort_ = true; this.xhr_.abort(); // Ensures XHR isn't hung (FF) this.inAbort_ = false; } this.lastError_ = err; this.lastErrorCode_ = errorCode; this.dispatchErrors_(); this.cleanUpXhr_(); }; /** * Dispatches COMPLETE and ERROR in case of an error. This ensures that we do * not dispatch multiple error events. * @private */ goog.net.XhrIo.prototype.dispatchErrors_ = function() { if (!this.errorDispatched_) { this.errorDispatched_ = true; this.dispatchEvent(goog.net.EventType.COMPLETE); this.dispatchEvent(goog.net.EventType.ERROR); } }; /** * Abort the current XMLHttpRequest * @param {goog.net.ErrorCode=} opt_failureCode Optional error code to use - * defaults to ABORT. */ goog.net.XhrIo.prototype.abort = function(opt_failureCode) { if (this.xhr_ && this.active_) { this.logger_.fine(this.formatMsg_('Aborting')); this.active_ = false; this.inAbort_ = true; this.xhr_.abort(); this.inAbort_ = false; this.lastErrorCode_ = opt_failureCode || goog.net.ErrorCode.ABORT; this.dispatchEvent(goog.net.EventType.COMPLETE); this.dispatchEvent(goog.net.EventType.ABORT); this.cleanUpXhr_(); } }; /** * Nullifies all callbacks to reduce risks of leaks. */ goog.net.XhrIo.prototype.disposeInternal = function() { if (this.xhr_) { // We explicitly do not call xhr_.abort() unless active_ is still true. // This is to avoid unnecessarily aborting a successful request when // disposeInternal() is called in a callback triggered by a complete // response, but in which browser cleanup has not yet finished. // (See http://b/issue?id=1684217.) if (this.active_) { this.active_ = false; this.inAbort_ = true; this.xhr_.abort(); this.inAbort_ = false; } this.cleanUpXhr_(true); } goog.net.XhrIo.superClass_.disposeInternal.call(this); }; /** * Internal handler for the XHR object's readystatechange event. This method * checks the status and the readystate and fires the correct callbacks. * If the request has ended, the handlers are cleaned up and the XHR object is * nullified. * @private */ goog.net.XhrIo.prototype.onReadyStateChange_ = function() { if (!this.inOpen_ && !this.inSend_ && !this.inAbort_)
else { this.onReadyStateChangeHelper_(); } }; /** * Used to protect the onreadystatechange handler entry point. Necessary * as {#onReadyStateChange_} maybe called from within send or abort, this * method is only called when {#onReadyStateChange_} is called as an * entry point. * {@see #protectEntryPoints} * @private */ goog.net.XhrIo.prototype.onReadyStateChangeEntryPoint_ = function() { this.onReadyStateChangeHelper_(); }; /** * Helper for {@link #onReadyStateChange_}. This is used so that * entry point calls to {@link #onReadyStateChange_} can be routed through * {@link #onReadyStateChangeEntryPoint_}. * @private */ goog.net.XhrIo.prototype.onReadyStateChangeHelper_ = function() { if (!this.active_) { // can get called inside abort call return; } if (typeof goog == 'undefined') { // NOTE(user): If goog is undefined then the callback has occurred as the // application is unloading and will error. Thus we let it silently fail. } else if ( this.xhrOptions_[goog.net.XmlHttp.OptionType.LOCAL_REQUEST_ERROR] && this.getReadyState() == goog.net.XmlHttp.ReadyState.COMPLETE && this.getStatus() == 2) { // NOTE(user): In IE if send() errors on a *local* request the readystate // is still changed to COMPLETE. We need to ignore it and allow the // try/catch around send() to pick up the error. this.logger_.fine(this.formatMsg_( 'Local request error detected and ignored')); } else { // In IE when the response has been cached we sometimes get the callback // from inside the send call and this usually breaks code that assumes that // XhrIo is asynchronous. If that is the case we delay the callback // using a timer. if (this.inSend_ && this.getReadyState() == goog.net.XmlHttp.ReadyState.COMPLETE) { goog.Timer.defaultTimerObject.setTimeout( goog.bind(this.onReadyStateChange_, this), 0); return; } this.dispatchEvent(goog.net.EventType.READY_STATE_CHANGE); // readyState indicates the transfer has finished if (this.isComplete()) { this.logger_.fine(this.formatMsg_('Request complete')); this.active_ = false; // Call the specific callbacks for success or failure. Only call the // success if the status is 200 (HTTP_OK) or 304 (HTTP_CACHED) if (this.isSuccess()) { this.dispatchEvent(goog.net.EventType.COMPLETE); this.dispatchEvent(goog.net.EventType.SUCCESS); } else { this.lastErrorCode_ = goog.net.ErrorCode.HTTP_ERROR; this.lastError_ = this.getStatusText() + ' [' + this.getStatus() + ']'; this.dispatchErrors_(); } this.cleanUpXhr_(); } } }; /** * Remove the listener to protect against leaks, and nullify the XMLHttpRequest * object. * @param {boolean=} opt_fromDispose If this is from the dispose (don't want to * fire any events). * @private */ goog.net.XhrIo.prototype.cleanUpXhr_ = function(opt_fromDispose) { if (this.xhr_) { // Save reference so we can mark it as closed after the READY event. The // READY event may trigger another request, thus we must nullify this.xhr_ var xhr = this.xhr_; var clearedOnReadyStateChange = this.xhrOptions_[goog.net.XmlHttp.OptionType.USE_NULL_FUNCTION] ? goog.nullFunction : null; this.xhr_ = null; this.xhrOptions_ = null; if (this.timeoutId_) { // Cancel any pending timeout event handler. goog.Timer.defaultTimerObject.clearTimeout(this.timeoutId_); this.timeoutId_ = null; } if (!opt_fromDispose) { goog.net.xhrMonitor.pushContext(xhr); this.dispatchEvent(goog.net.EventType.READY); goog.net.xhrMonitor.popContext(); } // Mark the request as having completed. goog.net.xhrMonitor.markXhrClosed(xhr); try { // NOTE(user): Not nullifying in FireFox can still leak if the callbacks // are defined in the same scope as the instance of XhrIo. But, IE doesn't // allow you to set the onreadystatechange to NULL so nullFunction is // used. xhr.onreadystatechange = clearedOnReadyStateChange; } catch (e) { // This seems to occur with a Gears HTTP request. Delayed the setting of // this onreadystatechange until after READY is sent out and catching the // error to see if we can track down the problem. this.logger_.severe('Problem encountered resetting onreadystatechange: ' + e.message); } } }; /** * @return {boolean} Whether there is an active request. */ goog.net.XhrIo.prototype.isActive = function() { return !!this.xhr_; }; /** * @return {boolean} Whether the request has completed. */ goog.net.XhrIo.prototype.isComplete = function() { return this.getReadyState() == goog.net.XmlHttp.ReadyState.COMPLETE; }; /** * @return {boolean} Whether the request completed with a success. */ goog.net.XhrIo.prototype.isSuccess = function() { switch (this.getStatus()) { case 0: // Used for local XHR requests case 200: // Http Success case 204: // Http Success - no content case 304: // Http Cache return true; default: return false; } }; /** * Get the readystate from the Xhr object * Will only return correct result when called from the context of a callback * @return {goog.net.XmlHttp.ReadyState} goog.net.XmlHttp.ReadyState.*. */ goog.net.XhrIo.prototype.getReadyState = function() { return this.xhr_ ? /** @type {goog.net.XmlHttp.ReadyState} */ (this.xhr_.readyState) : goog.net.XmlHttp.ReadyState.UNINITIALIZED; }; /** * Get the status from the Xhr object * Will only return correct result when called from the context of a callback * @return {number} Http status. */ goog.net.XhrIo.prototype.getStatus = function() { /** * IE doesn't like you checking status until the readystate is greater than 2 * (i.e. it is recieving or complete). The try/catch is used for when the * page is unloading and an ERROR_NOT_AVAILABLE may occur when accessing xhr_. * @preserveTry */ try { return this.getReadyState() > goog.net.XmlHttp.ReadyState.LOADED ? this.xhr_.status : -1; } catch (e) { this.logger_.warning('Can not get status: ' + e.message); return -1; } }; /** * Get the status text from the Xhr object * Will only return correct result when called from the context of a callback * @return {string} Status text. */ goog.net.XhrIo.prototype.getStatusText = function() { /** * IE doesn't like you checking status until the readystate is greater than 2 * (i.e. it is recieving or complete). The try/catch is used for when the * page is unloading and an ERROR_NOT_AVAILABLE may occur when accessing xhr_. * @preserveTry */ try { return this.getReadyState() > goog.net.XmlHttp.ReadyState.LOADED ? this.xhr_.statusText : ''; } catch (e) { this.logger_.fine('Can not get status: ' + e.message); return ''; } }; /** * Get the last Uri that was requested * @return {string} Last Uri. */ goog.net.XhrIo.prototype.getLastUri = function() { return String(this.lastUri_); }; /** * Get the response text from the Xhr object * Will only return correct result when called from the context of a callback. * @return {string} Result from the server, or '' if no result available. */ goog.net.XhrIo.prototype.getResponseText = function() { /** @preserveTry */ try { return this.xhr_ ? this.xhr_.responseText : ''; } catch (e) { // http://www.w3.org/TR/XMLHttpRequest/#the-responsetext-attribute // states that responseText should return '' (and responseXML null) // when the state is not LOADING or DONE. Instead, IE and Gears can // throw unexpected exceptions, eg, when a request is aborted or no // data is available yet. this.logger_.fine('Can not get responseText: ' + e.message); return ''; } }; /** * Get the response XML from the Xhr object * Will only return correct result when called from the context of a callback. * @return {Document} The DOM Document representing the XML file, or null * if no result available. */ goog.net.XhrIo.prototype.getResponseXml = function() { /** @preserveTry */ try { return this.xhr_ ? this.xhr_.responseXML : null; } catch (e) { this.logger_.fine('Can not get responseXML: ' + e.message); return null; } }; /** * Get the response and evaluates it as JSON from the Xhr object * Will only return correct result when called from the context of a callback * @param {string=} opt_xssiPrefix Optional XSSI prefix string to use for * stripping of the response before parsing. This needs to be set only if * your backend server prepends the same prefix string to the JSON response. * @return {Object|undefined} JavaScript object. */ goog.net.XhrIo.prototype.getResponseJson = function(opt_xssiPrefix) { if (!this.xhr_) { return undefined; } var responseText = this.xhr_.responseText; if (opt_xssiPrefix && responseText.indexOf(opt_xssiPrefix) == 0) { responseText = responseText.substring(opt_xssiPrefix.length); } return goog.json.parse(responseText); }; /** * Get the value of the response-header with the given name from the Xhr object * Will only return correct result when called from the context of a callback * and the request has completed * @param {string} key The name of the response-header to retrieve. * @return {string|undefined} The value of the response-header named key. */ goog.net.XhrIo.prototype.getResponseHeader = function(key) { return this.xhr_ && this.isComplete() ? this.xhr_.getResponseHeader(key) : undefined; }; /** * Gets the text of all the headers in the response. * Will only return correct result when called from the context of a callback * and the request has completed. * @return {string} The value of the response headers or empty string. */ goog.net.XhrIo.prototype.getAllResponseHeaders = function() { return this.xhr_ && this.isComplete() ? this.xhr_.getAllResponseHeaders() : ''; }; /** * Get the last error message * @return {goog.net.ErrorCode} Last error code. */ goog.net.XhrIo.prototype.getLastErrorCode = function() { return this.lastErrorCode_; }; /** * Get the last error message * @return {string} Last error message. */ goog.net.XhrIo.prototype.getLastError = function() { return goog.isString(this.lastError_) ? this.lastError_ : String(this.lastError_); }; /** * Adds the last method, status and URI to the message. This is used to add * this information to the logging calls. * @param {string} msg The message text that we want to add the extra text to. * @return {string} The message with the extra text appended. * @private */ goog.net.XhrIo.prototype.formatMsg_ = function(msg) { return msg + ' [' + this.lastMethod_ + ' ' + this.lastUri_ + ' ' + this.getStatus() + ']'; }; // Register the xhr handler as an entry point, so that // it can be monitored for exception handling, etc. goog.debug.entryPointRegistry.register( /** * @param {function(!Function): !Function} transformer The transforming * function. */ function(transformer) { goog.net.XhrIo.prototype.onReadyStateChangeEntryPoint_ = transformer(goog.net.XhrIo.prototype.onReadyStateChangeEntryPoint_); });
{ // Were not being called from within a call to this.xhr_.send // this.xhr_.abort, or this.xhr_.open, so this is an entry point this.onReadyStateChangeEntryPoint_(); }
conditional_block
tap.py
# Copyright 2013 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import os from telemetry.page.actions import page_action class TapAction(page_action.PageAction): def __init__(self, selector=None, text=None, element_function=None, left_position_percentage=0.5, top_position_percentage=0.5, duration_ms=50): super(TapAction, self).__init__() self.selector = selector self.text = text self.element_function = element_function self.left_position_percentage = left_position_percentage self.top_position_percentage = top_position_percentage self.duration_ms = duration_ms def WillRunAction(self, tab): for js_file in ['gesture_common.js', 'tap.js']: with open(os.path.join(os.path.dirname(__file__), js_file)) as f: js = f.read() tab.ExecuteJavaScript(js) # Fail if browser doesn't support synthetic tap gestures. if not tab.EvaluateJavaScript('window.__TapAction_SupportedByBrowser()'): raise page_action.PageActionNotSupported( 'Synthetic tap not supported for this browser') done_callback = 'function() { window.__tapActionDone = true; }' tab.ExecuteJavaScript(""" window.__tapActionDone = false; window.__tapAction = new __TapAction(%s);""" % (done_callback)) def HasElementSelector(self): return (self.element_function is not None or self.selector is not None or self.text is not None) def RunAction(self, tab): if not self.HasElementSelector():
gesture_source_type = page_action.GetGestureSourceTypeFromOptions(tab) tap_cmd = (''' window.__tapAction.start({ element: element, left_position_percentage: %s, top_position_percentage: %s, duration_ms: %s, gesture_source_type: %s });''' % (self.left_position_percentage, self.top_position_percentage, self.duration_ms, gesture_source_type)) code = ''' function(element, errorMsg) { if (!element) { throw Error('Cannot find element: ' + errorMsg); } %s; }''' % tap_cmd page_action.EvaluateCallbackWithElement( tab, code, selector=self.selector, text=self.text, element_function=self.element_function) tab.WaitForJavaScriptExpression('window.__tapActionDone', 60)
self.element_function = 'document.body'
conditional_block
tap.py
# Copyright 2013 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import os from telemetry.page.actions import page_action class TapAction(page_action.PageAction): def __init__(self, selector=None, text=None, element_function=None, left_position_percentage=0.5, top_position_percentage=0.5, duration_ms=50): super(TapAction, self).__init__() self.selector = selector self.text = text self.element_function = element_function self.left_position_percentage = left_position_percentage self.top_position_percentage = top_position_percentage self.duration_ms = duration_ms def WillRunAction(self, tab): for js_file in ['gesture_common.js', 'tap.js']: with open(os.path.join(os.path.dirname(__file__), js_file)) as f: js = f.read() tab.ExecuteJavaScript(js) # Fail if browser doesn't support synthetic tap gestures. if not tab.EvaluateJavaScript('window.__TapAction_SupportedByBrowser()'): raise page_action.PageActionNotSupported( 'Synthetic tap not supported for this browser') done_callback = 'function() { window.__tapActionDone = true; }' tab.ExecuteJavaScript(""" window.__tapActionDone = false; window.__tapAction = new __TapAction(%s);""" % (done_callback)) def HasElementSelector(self):
def RunAction(self, tab): if not self.HasElementSelector(): self.element_function = 'document.body' gesture_source_type = page_action.GetGestureSourceTypeFromOptions(tab) tap_cmd = (''' window.__tapAction.start({ element: element, left_position_percentage: %s, top_position_percentage: %s, duration_ms: %s, gesture_source_type: %s });''' % (self.left_position_percentage, self.top_position_percentage, self.duration_ms, gesture_source_type)) code = ''' function(element, errorMsg) { if (!element) { throw Error('Cannot find element: ' + errorMsg); } %s; }''' % tap_cmd page_action.EvaluateCallbackWithElement( tab, code, selector=self.selector, text=self.text, element_function=self.element_function) tab.WaitForJavaScriptExpression('window.__tapActionDone', 60)
return (self.element_function is not None or self.selector is not None or self.text is not None)
identifier_body
tap.py
# Copyright 2013 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import os from telemetry.page.actions import page_action class TapAction(page_action.PageAction): def __init__(self, selector=None, text=None, element_function=None, left_position_percentage=0.5, top_position_percentage=0.5, duration_ms=50): super(TapAction, self).__init__() self.selector = selector self.text = text self.element_function = element_function self.left_position_percentage = left_position_percentage self.top_position_percentage = top_position_percentage self.duration_ms = duration_ms def WillRunAction(self, tab): for js_file in ['gesture_common.js', 'tap.js']: with open(os.path.join(os.path.dirname(__file__), js_file)) as f: js = f.read() tab.ExecuteJavaScript(js) # Fail if browser doesn't support synthetic tap gestures. if not tab.EvaluateJavaScript('window.__TapAction_SupportedByBrowser()'): raise page_action.PageActionNotSupported( 'Synthetic tap not supported for this browser') done_callback = 'function() { window.__tapActionDone = true; }' tab.ExecuteJavaScript(""" window.__tapActionDone = false; window.__tapAction = new __TapAction(%s);""" % (done_callback)) def HasElementSelector(self): return (self.element_function is not None or self.selector is not None or self.text is not None)
if not self.HasElementSelector(): self.element_function = 'document.body' gesture_source_type = page_action.GetGestureSourceTypeFromOptions(tab) tap_cmd = (''' window.__tapAction.start({ element: element, left_position_percentage: %s, top_position_percentage: %s, duration_ms: %s, gesture_source_type: %s });''' % (self.left_position_percentage, self.top_position_percentage, self.duration_ms, gesture_source_type)) code = ''' function(element, errorMsg) { if (!element) { throw Error('Cannot find element: ' + errorMsg); } %s; }''' % tap_cmd page_action.EvaluateCallbackWithElement( tab, code, selector=self.selector, text=self.text, element_function=self.element_function) tab.WaitForJavaScriptExpression('window.__tapActionDone', 60)
def RunAction(self, tab):
random_line_split
tap.py
# Copyright 2013 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import os from telemetry.page.actions import page_action class TapAction(page_action.PageAction): def __init__(self, selector=None, text=None, element_function=None, left_position_percentage=0.5, top_position_percentage=0.5, duration_ms=50): super(TapAction, self).__init__() self.selector = selector self.text = text self.element_function = element_function self.left_position_percentage = left_position_percentage self.top_position_percentage = top_position_percentage self.duration_ms = duration_ms def
(self, tab): for js_file in ['gesture_common.js', 'tap.js']: with open(os.path.join(os.path.dirname(__file__), js_file)) as f: js = f.read() tab.ExecuteJavaScript(js) # Fail if browser doesn't support synthetic tap gestures. if not tab.EvaluateJavaScript('window.__TapAction_SupportedByBrowser()'): raise page_action.PageActionNotSupported( 'Synthetic tap not supported for this browser') done_callback = 'function() { window.__tapActionDone = true; }' tab.ExecuteJavaScript(""" window.__tapActionDone = false; window.__tapAction = new __TapAction(%s);""" % (done_callback)) def HasElementSelector(self): return (self.element_function is not None or self.selector is not None or self.text is not None) def RunAction(self, tab): if not self.HasElementSelector(): self.element_function = 'document.body' gesture_source_type = page_action.GetGestureSourceTypeFromOptions(tab) tap_cmd = (''' window.__tapAction.start({ element: element, left_position_percentage: %s, top_position_percentage: %s, duration_ms: %s, gesture_source_type: %s });''' % (self.left_position_percentage, self.top_position_percentage, self.duration_ms, gesture_source_type)) code = ''' function(element, errorMsg) { if (!element) { throw Error('Cannot find element: ' + errorMsg); } %s; }''' % tap_cmd page_action.EvaluateCallbackWithElement( tab, code, selector=self.selector, text=self.text, element_function=self.element_function) tab.WaitForJavaScriptExpression('window.__tapActionDone', 60)
WillRunAction
identifier_name
utils.py
# 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. class DummyKeyResponse(object): def __init__(self, gen=1): self.generation = gen self.name = "" def request(self, path, method, **kwargs): self.name = path.split('/')[-1] return self def json(self): return {"generation": self.generation, "name": self.name} class DummyTicketResponse(object): def __init__(self, signature, metadata, ticket): self.signature = signature self.metadata = metadata self.ticket = ticket def request(self, path, method, **kwargs): return self def json(self): return {"signature": self.signature, "metadata": self.metadata, "ticket": self.ticket} class DummyGroupResponse(object): def __init__(self, name): self.name = name def request(self, path, method, **kwargs): return self def json(self):
class DummyGroupKeyResponse(object): def __init__(self, signature, metadata, group_key): self.signature = signature self.metadata = metadata self.group_key = group_key def request(self, path, method, **kwargs): return self def json(self): return {"signature": self.signature, "metadata": self.metadata, "group_key": self.group_key}
return {"name": self.name}
identifier_body
utils.py
# 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. class DummyKeyResponse(object):
def request(self, path, method, **kwargs): self.name = path.split('/')[-1] return self def json(self): return {"generation": self.generation, "name": self.name} class DummyTicketResponse(object): def __init__(self, signature, metadata, ticket): self.signature = signature self.metadata = metadata self.ticket = ticket def request(self, path, method, **kwargs): return self def json(self): return {"signature": self.signature, "metadata": self.metadata, "ticket": self.ticket} class DummyGroupResponse(object): def __init__(self, name): self.name = name def request(self, path, method, **kwargs): return self def json(self): return {"name": self.name} class DummyGroupKeyResponse(object): def __init__(self, signature, metadata, group_key): self.signature = signature self.metadata = metadata self.group_key = group_key def request(self, path, method, **kwargs): return self def json(self): return {"signature": self.signature, "metadata": self.metadata, "group_key": self.group_key}
def __init__(self, gen=1): self.generation = gen self.name = ""
random_line_split
utils.py
# 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. class
(object): def __init__(self, gen=1): self.generation = gen self.name = "" def request(self, path, method, **kwargs): self.name = path.split('/')[-1] return self def json(self): return {"generation": self.generation, "name": self.name} class DummyTicketResponse(object): def __init__(self, signature, metadata, ticket): self.signature = signature self.metadata = metadata self.ticket = ticket def request(self, path, method, **kwargs): return self def json(self): return {"signature": self.signature, "metadata": self.metadata, "ticket": self.ticket} class DummyGroupResponse(object): def __init__(self, name): self.name = name def request(self, path, method, **kwargs): return self def json(self): return {"name": self.name} class DummyGroupKeyResponse(object): def __init__(self, signature, metadata, group_key): self.signature = signature self.metadata = metadata self.group_key = group_key def request(self, path, method, **kwargs): return self def json(self): return {"signature": self.signature, "metadata": self.metadata, "group_key": self.group_key}
DummyKeyResponse
identifier_name
metadata_resolver.d.ts
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import { StaticSymbol, StaticSymbolCache } from './aot/static_symbol'; import * as cpl from './compile_metadata'; import { CompileReflector } from './compile_reflector'; import { CompilerConfig } from './config'; import { Directive, Type } from './core'; import { DirectiveNormalizer } from './directive_normalizer'; import { DirectiveResolver } from './directive_resolver'; import { HtmlParser } from './ml_parser/html_parser'; import { NgModuleResolver } from './ng_module_resolver'; import { PipeResolver } from './pipe_resolver'; import { ElementSchemaRegistry } from './schema/element_schema_registry'; import { SummaryResolver } from './summary_resolver'; import { Console, SyncAsync } from './util'; export declare type ErrorCollector = (error: any, type?: any) => void; export declare const ERROR_COMPONENT_TYPE = "ngComponentType"; export declare class
{ private _config; private _htmlParser; private _ngModuleResolver; private _directiveResolver; private _pipeResolver; private _summaryResolver; private _schemaRegistry; private _directiveNormalizer; private _console; private _staticSymbolCache; private _reflector; private _errorCollector; private _nonNormalizedDirectiveCache; private _directiveCache; private _summaryCache; private _pipeCache; private _ngModuleCache; private _ngModuleOfTypes; constructor(_config: CompilerConfig, _htmlParser: HtmlParser, _ngModuleResolver: NgModuleResolver, _directiveResolver: DirectiveResolver, _pipeResolver: PipeResolver, _summaryResolver: SummaryResolver<any>, _schemaRegistry: ElementSchemaRegistry, _directiveNormalizer: DirectiveNormalizer, _console: Console, _staticSymbolCache: StaticSymbolCache, _reflector: CompileReflector, _errorCollector?: ErrorCollector | undefined); getReflector(): CompileReflector; clearCacheFor(type: Type): void; clearCache(): void; private _createProxyClass(baseType, name); private getGeneratedClass(dirType, name); private getComponentViewClass(dirType); getHostComponentViewClass(dirType: any): StaticSymbol | cpl.ProxyClass; getHostComponentType(dirType: any): StaticSymbol | Type; private getRendererType(dirType); private getComponentFactory(selector, dirType, inputs, outputs); private initComponentFactory(factory, ngContentSelectors); private _loadSummary(type, kind); getHostComponentMetadata(compMeta: cpl.CompileDirectiveMetadata, hostViewType?: StaticSymbol | cpl.ProxyClass): cpl.CompileDirectiveMetadata; loadDirectiveMetadata(ngModuleType: any, directiveType: any, isSync: boolean): SyncAsync<null>; getNonNormalizedDirectiveMetadata(directiveType: any): { annotation: Directive; metadata: cpl.CompileDirectiveMetadata; } | null; /** * Gets the metadata for the given directive. * This assumes `loadNgModuleDirectiveAndPipeMetadata` has been called first. */ getDirectiveMetadata(directiveType: any): cpl.CompileDirectiveMetadata; getDirectiveSummary(dirType: any): cpl.CompileDirectiveSummary; isDirective(type: any): boolean; isPipe(type: any): boolean; isNgModule(type: any): boolean; getNgModuleSummary(moduleType: any, alreadyCollecting?: Set<any> | null): cpl.CompileNgModuleSummary | null; /** * Loads the declared directives and pipes of an NgModule. */ loadNgModuleDirectiveAndPipeMetadata(moduleType: any, isSync: boolean, throwIfNotFound?: boolean): Promise<any>; getNgModuleMetadata(moduleType: any, throwIfNotFound?: boolean, alreadyCollecting?: Set<any> | null): cpl.CompileNgModuleMetadata | null; private _checkSelfImport(moduleType, importedModuleType); private _getTypeDescriptor(type); private _addTypeToModule(type, moduleType); private _getTransitiveNgModuleMetadata(importedModules, exportedModules); private _getIdentifierMetadata(type); isInjectable(type: any): boolean; getInjectableSummary(type: any): cpl.CompileTypeSummary; private _getInjectableMetadata(type, dependencies?); private _getTypeMetadata(type, dependencies?, throwOnUnknownDeps?); private _getFactoryMetadata(factory, dependencies?); /** * Gets the metadata for the given pipe. * This assumes `loadNgModuleDirectiveAndPipeMetadata` has been called first. */ getPipeMetadata(pipeType: any): cpl.CompilePipeMetadata | null; getPipeSummary(pipeType: any): cpl.CompilePipeSummary; getOrLoadPipeMetadata(pipeType: any): cpl.CompilePipeMetadata; private _loadPipeMetadata(pipeType); private _getDependenciesMetadata(typeOrFunc, dependencies, throwOnUnknownDeps?); private _getTokenMetadata(token); private _getProvidersMetadata(providers, targetEntryComponents, debugInfo?, compileProviders?, type?); private _validateProvider(provider); private _getEntryComponentsFromProvider(provider, type?); private _getEntryComponentMetadata(dirType, throwIfNotFound?); getProviderMetadata(provider: cpl.ProviderMeta): cpl.CompileProviderMetadata; private _getQueriesMetadata(queries, isViewQuery, directiveType); private _queryVarBindings(selector); private _getQueryMetadata(q, propertyName, typeOrFunc); private _reportError(error, type?, otherType?); }
CompileMetadataResolver
identifier_name
metadata_resolver.d.ts
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import { StaticSymbol, StaticSymbolCache } from './aot/static_symbol'; import * as cpl from './compile_metadata'; import { CompileReflector } from './compile_reflector'; import { CompilerConfig } from './config'; import { Directive, Type } from './core'; import { DirectiveNormalizer } from './directive_normalizer'; import { DirectiveResolver } from './directive_resolver'; import { HtmlParser } from './ml_parser/html_parser'; import { NgModuleResolver } from './ng_module_resolver'; import { PipeResolver } from './pipe_resolver'; import { ElementSchemaRegistry } from './schema/element_schema_registry'; import { SummaryResolver } from './summary_resolver'; import { Console, SyncAsync } from './util'; export declare type ErrorCollector = (error: any, type?: any) => void; export declare const ERROR_COMPONENT_TYPE = "ngComponentType"; export declare class CompileMetadataResolver { private _config; private _htmlParser; private _ngModuleResolver; private _directiveResolver; private _pipeResolver; private _summaryResolver; private _schemaRegistry; private _directiveNormalizer; private _console; private _staticSymbolCache; private _reflector; private _errorCollector; private _nonNormalizedDirectiveCache; private _directiveCache; private _summaryCache;
private _ngModuleCache; private _ngModuleOfTypes; constructor(_config: CompilerConfig, _htmlParser: HtmlParser, _ngModuleResolver: NgModuleResolver, _directiveResolver: DirectiveResolver, _pipeResolver: PipeResolver, _summaryResolver: SummaryResolver<any>, _schemaRegistry: ElementSchemaRegistry, _directiveNormalizer: DirectiveNormalizer, _console: Console, _staticSymbolCache: StaticSymbolCache, _reflector: CompileReflector, _errorCollector?: ErrorCollector | undefined); getReflector(): CompileReflector; clearCacheFor(type: Type): void; clearCache(): void; private _createProxyClass(baseType, name); private getGeneratedClass(dirType, name); private getComponentViewClass(dirType); getHostComponentViewClass(dirType: any): StaticSymbol | cpl.ProxyClass; getHostComponentType(dirType: any): StaticSymbol | Type; private getRendererType(dirType); private getComponentFactory(selector, dirType, inputs, outputs); private initComponentFactory(factory, ngContentSelectors); private _loadSummary(type, kind); getHostComponentMetadata(compMeta: cpl.CompileDirectiveMetadata, hostViewType?: StaticSymbol | cpl.ProxyClass): cpl.CompileDirectiveMetadata; loadDirectiveMetadata(ngModuleType: any, directiveType: any, isSync: boolean): SyncAsync<null>; getNonNormalizedDirectiveMetadata(directiveType: any): { annotation: Directive; metadata: cpl.CompileDirectiveMetadata; } | null; /** * Gets the metadata for the given directive. * This assumes `loadNgModuleDirectiveAndPipeMetadata` has been called first. */ getDirectiveMetadata(directiveType: any): cpl.CompileDirectiveMetadata; getDirectiveSummary(dirType: any): cpl.CompileDirectiveSummary; isDirective(type: any): boolean; isPipe(type: any): boolean; isNgModule(type: any): boolean; getNgModuleSummary(moduleType: any, alreadyCollecting?: Set<any> | null): cpl.CompileNgModuleSummary | null; /** * Loads the declared directives and pipes of an NgModule. */ loadNgModuleDirectiveAndPipeMetadata(moduleType: any, isSync: boolean, throwIfNotFound?: boolean): Promise<any>; getNgModuleMetadata(moduleType: any, throwIfNotFound?: boolean, alreadyCollecting?: Set<any> | null): cpl.CompileNgModuleMetadata | null; private _checkSelfImport(moduleType, importedModuleType); private _getTypeDescriptor(type); private _addTypeToModule(type, moduleType); private _getTransitiveNgModuleMetadata(importedModules, exportedModules); private _getIdentifierMetadata(type); isInjectable(type: any): boolean; getInjectableSummary(type: any): cpl.CompileTypeSummary; private _getInjectableMetadata(type, dependencies?); private _getTypeMetadata(type, dependencies?, throwOnUnknownDeps?); private _getFactoryMetadata(factory, dependencies?); /** * Gets the metadata for the given pipe. * This assumes `loadNgModuleDirectiveAndPipeMetadata` has been called first. */ getPipeMetadata(pipeType: any): cpl.CompilePipeMetadata | null; getPipeSummary(pipeType: any): cpl.CompilePipeSummary; getOrLoadPipeMetadata(pipeType: any): cpl.CompilePipeMetadata; private _loadPipeMetadata(pipeType); private _getDependenciesMetadata(typeOrFunc, dependencies, throwOnUnknownDeps?); private _getTokenMetadata(token); private _getProvidersMetadata(providers, targetEntryComponents, debugInfo?, compileProviders?, type?); private _validateProvider(provider); private _getEntryComponentsFromProvider(provider, type?); private _getEntryComponentMetadata(dirType, throwIfNotFound?); getProviderMetadata(provider: cpl.ProviderMeta): cpl.CompileProviderMetadata; private _getQueriesMetadata(queries, isViewQuery, directiveType); private _queryVarBindings(selector); private _getQueryMetadata(q, propertyName, typeOrFunc); private _reportError(error, type?, otherType?); }
private _pipeCache;
random_line_split
boxplot.py
import numpy as np import pandas as pd from bokeh.plotting import * # Generate some synthetic time series for six different categories cats = list("abcdef") y = np.random.randn(2000) g = np.random.choice(cats, 2000) for i, l in enumerate(cats): y[g == l] += i // 2 df = pd.DataFrame(dict(score=y, group=g)) # Find the quartiles, IQR, and outliers for each category groups = df.groupby('group') q1 = groups.quantile(q=0.25) q2 = groups.quantile(q=0.5) q3 = groups.quantile(q=0.75) iqr = q3 - q1 upper = q2 + 1.5*iqr lower = q2 - 1.5*iqr def outliers(group): cat = group.name return group[(group.score > upper.loc[cat][0]) | (group.score < lower.loc[cat][0])]['score'] out = groups.apply(outliers).dropna() # Prepare outlier data for plotting, we need and x (categorical) and y (numeric) # coordinate for every outlier. outx = [] outy = [] for cat in cats: for value in out[cat]: outx.append(cat) outy.append(value) # EXERCISE: output static HTML file # EXERCISE: turn on plot hold # Draw the upper segment extending from the box plot using `segment` which # takes x0, x1 and y0, y1 as data segment(cats, upper.score, cats, q3.score, x_range=cats, line_width=2,
tools="", background_fill="#EFE8E2", line_color="black", title="") # EXERCISE: draw the lower segment # Draw the upper box of the box plot using `rect` rect(cats, (q3.score+q2.score)/2, 0.7, q3.score-q2.score, fill_color="#E08E79", line_width=2, line_color="black") # EXERCISE: use `rect` to draw the bottom box with a different color # OK here we use `rect` to draw the whiskers. It's slightly cheating, but it's # easier than using segments or lines, since we can specify widths simply with # categorical percentage units rect(cats, lower.score, 0.2, 0, line_color="black") rect(cats, upper.score, 0.2, 0, line_color="black") # EXERCISE: use `circle` to draw the outliers # EXERCISE: use grid(), axis(), etc. to style the plot. Some suggestions: # - remove the X grid lines, change the Y grid line color # - make the tick labels bigger xgrid().grid_line_color = None ygrid().grid_line_color = "white" ygrid().grid_line_width = 2 xaxis().major_label_text_font_size="12pt" show()
random_line_split
boxplot.py
import numpy as np import pandas as pd from bokeh.plotting import * # Generate some synthetic time series for six different categories cats = list("abcdef") y = np.random.randn(2000) g = np.random.choice(cats, 2000) for i, l in enumerate(cats): y[g == l] += i // 2 df = pd.DataFrame(dict(score=y, group=g)) # Find the quartiles, IQR, and outliers for each category groups = df.groupby('group') q1 = groups.quantile(q=0.25) q2 = groups.quantile(q=0.5) q3 = groups.quantile(q=0.75) iqr = q3 - q1 upper = q2 + 1.5*iqr lower = q2 - 1.5*iqr def outliers(group):
out = groups.apply(outliers).dropna() # Prepare outlier data for plotting, we need and x (categorical) and y (numeric) # coordinate for every outlier. outx = [] outy = [] for cat in cats: for value in out[cat]: outx.append(cat) outy.append(value) # EXERCISE: output static HTML file # EXERCISE: turn on plot hold # Draw the upper segment extending from the box plot using `segment` which # takes x0, x1 and y0, y1 as data segment(cats, upper.score, cats, q3.score, x_range=cats, line_width=2, tools="", background_fill="#EFE8E2", line_color="black", title="") # EXERCISE: draw the lower segment # Draw the upper box of the box plot using `rect` rect(cats, (q3.score+q2.score)/2, 0.7, q3.score-q2.score, fill_color="#E08E79", line_width=2, line_color="black") # EXERCISE: use `rect` to draw the bottom box with a different color # OK here we use `rect` to draw the whiskers. It's slightly cheating, but it's # easier than using segments or lines, since we can specify widths simply with # categorical percentage units rect(cats, lower.score, 0.2, 0, line_color="black") rect(cats, upper.score, 0.2, 0, line_color="black") # EXERCISE: use `circle` to draw the outliers # EXERCISE: use grid(), axis(), etc. to style the plot. Some suggestions: # - remove the X grid lines, change the Y grid line color # - make the tick labels bigger xgrid().grid_line_color = None ygrid().grid_line_color = "white" ygrid().grid_line_width = 2 xaxis().major_label_text_font_size="12pt" show()
cat = group.name return group[(group.score > upper.loc[cat][0]) | (group.score < lower.loc[cat][0])]['score']
identifier_body
boxplot.py
import numpy as np import pandas as pd from bokeh.plotting import * # Generate some synthetic time series for six different categories cats = list("abcdef") y = np.random.randn(2000) g = np.random.choice(cats, 2000) for i, l in enumerate(cats): y[g == l] += i // 2 df = pd.DataFrame(dict(score=y, group=g)) # Find the quartiles, IQR, and outliers for each category groups = df.groupby('group') q1 = groups.quantile(q=0.25) q2 = groups.quantile(q=0.5) q3 = groups.quantile(q=0.75) iqr = q3 - q1 upper = q2 + 1.5*iqr lower = q2 - 1.5*iqr def
(group): cat = group.name return group[(group.score > upper.loc[cat][0]) | (group.score < lower.loc[cat][0])]['score'] out = groups.apply(outliers).dropna() # Prepare outlier data for plotting, we need and x (categorical) and y (numeric) # coordinate for every outlier. outx = [] outy = [] for cat in cats: for value in out[cat]: outx.append(cat) outy.append(value) # EXERCISE: output static HTML file # EXERCISE: turn on plot hold # Draw the upper segment extending from the box plot using `segment` which # takes x0, x1 and y0, y1 as data segment(cats, upper.score, cats, q3.score, x_range=cats, line_width=2, tools="", background_fill="#EFE8E2", line_color="black", title="") # EXERCISE: draw the lower segment # Draw the upper box of the box plot using `rect` rect(cats, (q3.score+q2.score)/2, 0.7, q3.score-q2.score, fill_color="#E08E79", line_width=2, line_color="black") # EXERCISE: use `rect` to draw the bottom box with a different color # OK here we use `rect` to draw the whiskers. It's slightly cheating, but it's # easier than using segments or lines, since we can specify widths simply with # categorical percentage units rect(cats, lower.score, 0.2, 0, line_color="black") rect(cats, upper.score, 0.2, 0, line_color="black") # EXERCISE: use `circle` to draw the outliers # EXERCISE: use grid(), axis(), etc. to style the plot. Some suggestions: # - remove the X grid lines, change the Y grid line color # - make the tick labels bigger xgrid().grid_line_color = None ygrid().grid_line_color = "white" ygrid().grid_line_width = 2 xaxis().major_label_text_font_size="12pt" show()
outliers
identifier_name
boxplot.py
import numpy as np import pandas as pd from bokeh.plotting import * # Generate some synthetic time series for six different categories cats = list("abcdef") y = np.random.randn(2000) g = np.random.choice(cats, 2000) for i, l in enumerate(cats):
df = pd.DataFrame(dict(score=y, group=g)) # Find the quartiles, IQR, and outliers for each category groups = df.groupby('group') q1 = groups.quantile(q=0.25) q2 = groups.quantile(q=0.5) q3 = groups.quantile(q=0.75) iqr = q3 - q1 upper = q2 + 1.5*iqr lower = q2 - 1.5*iqr def outliers(group): cat = group.name return group[(group.score > upper.loc[cat][0]) | (group.score < lower.loc[cat][0])]['score'] out = groups.apply(outliers).dropna() # Prepare outlier data for plotting, we need and x (categorical) and y (numeric) # coordinate for every outlier. outx = [] outy = [] for cat in cats: for value in out[cat]: outx.append(cat) outy.append(value) # EXERCISE: output static HTML file # EXERCISE: turn on plot hold # Draw the upper segment extending from the box plot using `segment` which # takes x0, x1 and y0, y1 as data segment(cats, upper.score, cats, q3.score, x_range=cats, line_width=2, tools="", background_fill="#EFE8E2", line_color="black", title="") # EXERCISE: draw the lower segment # Draw the upper box of the box plot using `rect` rect(cats, (q3.score+q2.score)/2, 0.7, q3.score-q2.score, fill_color="#E08E79", line_width=2, line_color="black") # EXERCISE: use `rect` to draw the bottom box with a different color # OK here we use `rect` to draw the whiskers. It's slightly cheating, but it's # easier than using segments or lines, since we can specify widths simply with # categorical percentage units rect(cats, lower.score, 0.2, 0, line_color="black") rect(cats, upper.score, 0.2, 0, line_color="black") # EXERCISE: use `circle` to draw the outliers # EXERCISE: use grid(), axis(), etc. to style the plot. Some suggestions: # - remove the X grid lines, change the Y grid line color # - make the tick labels bigger xgrid().grid_line_color = None ygrid().grid_line_color = "white" ygrid().grid_line_width = 2 xaxis().major_label_text_font_size="12pt" show()
y[g == l] += i // 2
conditional_block
filter.js
/** * Filtering sensitive information */ const _ = require('lodash'); /** * reset option * @param {string|object|array} opt filter option * @param {array} filterKeys filter keys * @param {string|function} replaceChat replace chat or function * @param {boolean} recursion whether recursive , true of false */ const setOption = (option) => { let filterKeys = ['password', 'token', 'authorization']; let replaceChat = '*'; let recursion = false; if (option !== undefined) { if (typeof option === 'string') { filterKeys = [option]; } else if (option instanceof Array && option.length > 0) { filterKeys = option.filter(item => typeof item === 'string'); } else if (_.isPlainObject(option)) { const { filterKeys: fks, recursion: rcs, replaceChat: rpc } = option; recursion = !!rcs; if (fks instanceof Array && fks.length > 0) { filterKeys = fks.filter(item => typeof item === 'string'); } if (typeof rpc === 'string') { replaceChat = rpc; } else { replaceChat = '*'; } } else { console.error(new Error(`option.filter do not support ${typeof option} type !`)); } } return { filterKeys, recursion, replaceChat }; }; /** * replace by replaceChat * @param {string} param content to replace * @param {string|function} replaceChat replace chat or function */ const replace = (param, replaceChat) => { if (typeof replaceChat === 'function') { return replaceChat(param); } return param.replace(/\S/g, '*'); }; /** * filter log message by option * @param {*} message logger message * @param {object} opt filter option * @param {boolean} hit hit the fileterkeys , default false */ const filter = (message, opt, hit = false) => { const result = message; const { filterKeys, replaceChat } = opt; if (_.isPlainObject(result)) { Object.keys(result).forEach((key) => { const dHit = hit || filterKeys.indexOf(key) > -1; result[key] = filter(result[key], opt, dHit); // if (recursion) { // result[key] = filter(param, opt, true); // } else { // result[key] = replaceChat; // // replace the value of hit key // // eslint-disable-next-line no-return-assign // Object.keys(param).forEach(pk => (filterKeys.indexOf(pk) !== -1 ? result[key] = replaceChat : '')); // } }); return result; } else if (typeof result === 'number') { return replace(result.toString(), replaceChat); } else if (result instanceof Array && result.length > 0) { return result.map(param => filter(param, opt, hit)); } return replace(result, replaceChat); }; /** * filter log message by option do not recursion * @param {*} message logger message * @param {object} opt filter option * @param {array} opt.filterKeys filter keys * @param {string} opt.replaceChat replace chat or function */ const filterNoRecursion = (message, opt) => { const result = message; const { filterKeys, replaceChat } = opt; if (_.isPlainObject(result)) { Object.keys(result).forEach((key) => { if (filterKeys.indexOf(key) === -1) { result[key] = filterNoRecursion(result[key], opt); } else
}); return result; } else if (typeof result === 'number') { return result; } else if (result instanceof Array && result.length > 0) { return result; } return result; }; /** * filter sensitive information * @param {object} message log message * @param {*} option filter option */ const filteringSensitiveInfo = (message, option = false) => { if (!option) { return message; } if (typeof option === 'function') { return option(message); } return filterNoRecursion(message, setOption(option)); }; module.exports = { filteringSensitiveInfo, setOption, };
{ result[key] = replaceChat; }
conditional_block
filter.js
/** * Filtering sensitive information */ const _ = require('lodash'); /** * reset option * @param {string|object|array} opt filter option * @param {array} filterKeys filter keys * @param {string|function} replaceChat replace chat or function * @param {boolean} recursion whether recursive , true of false */ const setOption = (option) => { let filterKeys = ['password', 'token', 'authorization']; let replaceChat = '*'; let recursion = false; if (option !== undefined) { if (typeof option === 'string') { filterKeys = [option]; } else if (option instanceof Array && option.length > 0) { filterKeys = option.filter(item => typeof item === 'string'); } else if (_.isPlainObject(option)) { const { filterKeys: fks, recursion: rcs, replaceChat: rpc } = option; recursion = !!rcs; if (fks instanceof Array && fks.length > 0) { filterKeys = fks.filter(item => typeof item === 'string'); } if (typeof rpc === 'string') { replaceChat = rpc; } else { replaceChat = '*'; } } else { console.error(new Error(`option.filter do not support ${typeof option} type !`)); } } return { filterKeys, recursion, replaceChat }; }; /** * replace by replaceChat * @param {string} param content to replace * @param {string|function} replaceChat replace chat or function */ const replace = (param, replaceChat) => { if (typeof replaceChat === 'function') { return replaceChat(param); } return param.replace(/\S/g, '*'); }; /** * filter log message by option * @param {*} message logger message * @param {object} opt filter option * @param {boolean} hit hit the fileterkeys , default false */ const filter = (message, opt, hit = false) => { const result = message; const { filterKeys, replaceChat } = opt; if (_.isPlainObject(result)) { Object.keys(result).forEach((key) => { const dHit = hit || filterKeys.indexOf(key) > -1; result[key] = filter(result[key], opt, dHit); // if (recursion) { // result[key] = filter(param, opt, true); // } else { // result[key] = replaceChat; // // replace the value of hit key // // eslint-disable-next-line no-return-assign // Object.keys(param).forEach(pk => (filterKeys.indexOf(pk) !== -1 ? result[key] = replaceChat : '')); // } }); return result; } else if (typeof result === 'number') { return replace(result.toString(), replaceChat); } else if (result instanceof Array && result.length > 0) { return result.map(param => filter(param, opt, hit)); } return replace(result, replaceChat); }; /** * filter log message by option do not recursion * @param {*} message logger message * @param {object} opt filter option * @param {array} opt.filterKeys filter keys * @param {string} opt.replaceChat replace chat or function */ const filterNoRecursion = (message, opt) => { const result = message; const { filterKeys, replaceChat } = opt; if (_.isPlainObject(result)) { Object.keys(result).forEach((key) => { if (filterKeys.indexOf(key) === -1) { result[key] = filterNoRecursion(result[key], opt); } else { result[key] = replaceChat; } }); return result; } else if (typeof result === 'number') { return result; } else if (result instanceof Array && result.length > 0) { return result; } return result; }; /**
* filter sensitive information * @param {object} message log message * @param {*} option filter option */ const filteringSensitiveInfo = (message, option = false) => { if (!option) { return message; } if (typeof option === 'function') { return option(message); } return filterNoRecursion(message, setOption(option)); }; module.exports = { filteringSensitiveInfo, setOption, };
random_line_split
urls.py
from django.conf.urls.defaults import patterns, include, url from file_uploader import settings # Uncomment the next two lines to enable the admin: # from django.contrib import admin # admin.autodiscover()
# Uncomment the admin/doc line below to enable admin documentation: # url(r'^admin/doc/', include('django.contrib.admindocs.urls')), # Uncomment the next line to enable the admin: # url(r'^admin/', include(admin.site.urls)), url(r'^media/(?P<path>.*)$', "django.views.static.serve",{'document_root': settings.MEDIA_ROOT,'show_indexes': True}), # on debugging only url(r'^$', 'file_uploader.view.index'), url(r'^upload/$', 'file_uploader.view.upload'), )
urlpatterns = patterns('', # Examples: # url(r'^$', 'file_uploader.views.home', name='home'), # url(r'^file_uploader/', include('file_uploader.foo.urls')),
random_line_split