file_name large_stringlengths 4 140 | prefix large_stringlengths 0 12.1k | suffix large_stringlengths 0 12k | middle large_stringlengths 0 7.51k | fim_type large_stringclasses 4
values |
|---|---|---|---|---|
clip.component.ts | import { Component, Input, ElementRef, Inject, OnDestroy, OnChanges, SimpleChanges, OnInit, ViewChild } from '@angular/core'
import { Feature } from 'geojson'
import { Map, GeoJSON, PathOptions, Layer, FixedWidthMarker, control, TileLayer, WMSOptions, Circle, LatLng } from 'leaflet'
import { LocalStorageService, MapSer... | (): void {
if (this.layer) {
this.map.removeLayer(this.layer)
}
if (!this.feature || !this.feature.geometry) {
const mapPosition = this.localStorageService.getMapPosition()
this.map.setView(mapPosition.center, 1)
return
}
this.layer = new GeoJSON(this.feature, {
point... | addFeature | identifier_name |
clip.component.ts | import { Component, Input, ElementRef, Inject, OnDestroy, OnChanges, SimpleChanges, OnInit, ViewChild } from '@angular/core'
import { Feature } from 'geojson'
import { Map, GeoJSON, PathOptions, Layer, FixedWidthMarker, control, TileLayer, WMSOptions, Circle, LatLng } from 'leaflet'
import { LocalStorageService, MapSer... |
if (!this.feature || !this.feature.geometry) {
const mapPosition = this.localStorageService.getMapPosition()
this.map.setView(mapPosition.center, 1)
return
}
this.layer = new GeoJSON(this.feature, {
pointToLayer: function (feature: FeatureWithStyle, latlng): Layer {
return... | {
this.map.removeLayer(this.layer)
} | conditional_block |
clip.component.ts | import { Component, Input, ElementRef, Inject, OnDestroy, OnChanges, SimpleChanges, OnInit, ViewChild } from '@angular/core'
import { Feature } from 'geojson'
import { Map, GeoJSON, PathOptions, Layer, FixedWidthMarker, control, TileLayer, WMSOptions, Circle, LatLng } from 'leaflet'
import { LocalStorageService, MapSer... | ngOnDestroy(): void {
this.mapService.removeListener(this.mapListener)
}
onBaseLayerSelected(baseLayer): void {
let layer = this.layers[baseLayer.name]
if (layer) this.map.removeLayer(layer.layer)
layer = this.createRasterLayer(baseLayer)
this.layers[baseLayer.name] = { type: 'tile', layer: ... | this.addFeature();
}
| random_line_split |
clip.component.ts | import { Component, Input, ElementRef, Inject, OnDestroy, OnChanges, SimpleChanges, OnInit, ViewChild } from '@angular/core'
import { Feature } from 'geojson'
import { Map, GeoJSON, PathOptions, Layer, FixedWidthMarker, control, TileLayer, WMSOptions, Circle, LatLng } from 'leaflet'
import { LocalStorageService, MapSer... |
this.mapService.addListener(this.mapListener)
this.addFeature()
}
ngOnChanges(changes: SimpleChanges): void {
if (!this.map) return;
this.addFeature();
}
ngOnDestroy(): void {
this.mapService.removeListener(this.mapListener)
}
onBaseLayerSelected(baseLayer): void {
let layer =... | {
const mapPosition = this.localStorageService.getMapPosition();
this.map = new Map(this.mapElement.nativeElement, {
center: mapPosition.center,
zoom: 15,
minZoom: 0,
maxZoom: 18,
zoomControl: false,
trackResize: true,
scrollWheelZoom: false,
attributionControl: ... | identifier_body |
serial.rs | : Deserializer<'d>>(
d: D,
) -> Result<T, D::Error> {
use serde_json::Value;
let v = Value::deserialize(d)?;
Ok(T::deserialize(v).ok().unwrap_or_default())
}
/// Deserialize a maybe-string ID into a u64.
pub fn deserialize_id<'d, D: Deserializer<'d>>(d: D) -> Result<u64, D::Error> {
struct IdVisitor;
impl<'d> V... | <'d, D: Deserializer<'d>>(d: D) -> Result<Option<u16>, D::Error> {
macro_rules! check {
($self:ident, $v:ident, $wrong:expr) => {
if $v >= 0 && $v <= 9999 {
Ok(Some($v as u16))
} else {
Err(E::invalid_value($wrong, &$self))
}
};
}
struct DiscrimVisitor;
impl<'d> Visitor<'d> for DiscrimVisitor... | deserialize_discrim_opt | identifier_name |
serial.rs | : Deserializer<'d>>(
d: D,
) -> Result<T, D::Error> {
use serde_json::Value;
let v = Value::deserialize(d)?;
Ok(T::deserialize(v).ok().unwrap_or_default())
}
/// Deserialize a maybe-string ID into a u64.
pub fn deserialize_id<'d, D: Deserializer<'d>>(d: D) -> Result<u64, D::Error> {
struct IdVisitor;
impl<'d> V... |
pub fn deserialize<'d, T: NamedEnum, D: Deserializer<'d>>(d: D) -> Result<T, D::Error> {
struct NameVisitor<T>(PhantomData<T>);
impl<'d, T: NamedEnum> Visitor<'d> for NameVisitor<T> {
type Value = T;
fn expecting(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
write!(fmt, "a valid {} name", T::typen... | {
v.name().serialize(s)
} | identifier_body |
serial.rs | D: Deserializer<'d>>(
d: D,
) -> Result<T, D::Error> {
use serde_json::Value;
let v = Value::deserialize(d)?;
Ok(T::deserialize(v).ok().unwrap_or_default())
}
/// Deserialize a maybe-string ID into a u64.
pub fn deserialize_id<'d, D: Deserializer<'d>>(d: D) -> Result<u64, D::Error> {
struct IdVisitor;
impl<'d>... | fn from_name(name: &str) -> Option<Self> {
Self::from_name(name)
}
fn typename() -> &'static str {
stringify!($typ)
}
}
}
}
/// Support for numeric enums.
pub mod numeric {
use super::*;
pub trait NumericEnum: Sized {
fn num(&self) -> u64;
fn from_num(num: u64) -> Option<Self>;
fn type... | random_line_split | |
docfix.js | (function (w) {
var $ = w.$,
d = document,
e = d.documentElement,
g = d.getElementsByTagName('body')[0],
my = w.ilm,
contid = 0;
function fixCharts(width, fn) {
$(fn).css("width", width);
$(d).ready(function () {
var inner = $(fn).width();
setTimeout(function () {
$.each(w.ilm.charts... |
w.ilm.popup="";
w.ilm.Options = function(state){
var t = this, f = $("#lingid"), g = $("#sl");
g.html("Seaded (klikk varjamiseks)");
my.settingTemplate(f);
return false;
};
w.ilm.Lingid = function (state) {
var t = this, f = $("#lingid"), g = $("#sl");
g.html("Lingid (klikk varjamiseks)");
f.htm... | {
console.log(w.ilm.getWidth());
var inner = ((w.ilm.getWidth() < 1024) ? "100" : "50") + "%";
$('.float').each(function () {
fixCharts(inner, this);
});
} | identifier_body |
docfix.js | (function (w) {
var $ = w.$,
d = document,
e = d.documentElement,
g = d.getElementsByTagName('body')[0],
my = w.ilm,
contid = 0;
function fixCharts(width, fn) {
$(fn).css("width", width);
$(d).ready(function () {
var inner = $(fn).width();
setTimeout(function () {
$.each(w.ilm.charts... | });
$("#datepicker").datepicker({
dateFormat: 'yy-mm-dd',
timezone: "+0"+(((my.addDst)?1:0)+2)+"00",
onSelect: function(dateText, inst) {
w.ilm.setDate(dateText);
//w.ilm.reload();
}
});
$("#curtime").on("click",function(){
$("#datepicker").datepicker('show');
});
$("#curplace").on("... | w.ilm.setEstPlace(w.ilm.nextPlace());
//w.ilm.reloadest();
return false; | random_line_split |
docfix.js | (function (w) {
var $ = w.$,
d = document,
e = d.documentElement,
g = d.getElementsByTagName('body')[0],
my = w.ilm,
contid = 0;
function fixCharts(width, fn) {
$(fn).css("width", width);
$(d).ready(function () {
var inner = $(fn).width();
setTimeout(function () {
$.each(w.ilm.charts... | () {
console.log(w.ilm.getWidth());
var inner = ((w.ilm.getWidth() < 1024) ? "100" : "50") + "%";
$('.float').each(function () {
fixCharts(inner, this);
});
}
w.ilm.popup="";
w.ilm.Options = function(state){
var t = this, f = $("#lingid"), g = $("#sl");
g.html("Seaded (klikk varjamiseks)");
my.s... | setWidth | identifier_name |
generateres.ts |
/// <reference path="../lib/types.d.ts" />
import utils = require('../lib/utils');
import FileUtil = require('../lib/FileUtil');
class GenerateResource {
execute(): number {
FileUtil.getExtension
var resources = FileUtil.searchByFunction(egret.args.srcDir, isResource);
var config = {
... | export = GenerateResource; |
}
| random_line_split |
generateres.ts |
/// <reference path="../lib/types.d.ts" />
import utils = require('../lib/utils');
import FileUtil = require('../lib/FileUtil');
class Ge |
execute(): number {
FileUtil.getExtension
var resources = FileUtil.searchByFunction(egret.args.srcDir, isResource);
var config = {
resources: []
};
config.resources = resources.map(f=> {
var ext = FileUtil.getExtension(f);
f = FileUtil.ge... | nerateResource { | identifier_name |
generateres.ts |
/// <reference path="../lib/types.d.ts" />
import utils = require('../lib/utils');
import FileUtil = require('../lib/FileUtil');
class GenerateResource {
execute(): number {
|
}
var resourceExtensions = {
png: true,
jpg: true,
gif: true,
mp3: true,
wav: true,
json: true,
fnt: true,
webp: true,
mp4: true
}
var extToType = {
png: "image",
jpg: "image",
gif: "image",
mp3: "sound",
wav: "sound",
json: "json",
fnt: "font",
txt:... | FileUtil.getExtension
var resources = FileUtil.searchByFunction(egret.args.srcDir, isResource);
var config = {
resources: []
};
config.resources = resources.map(f=> {
var ext = FileUtil.getExtension(f);
f = FileUtil.getRelativePath(egret.args.... | identifier_body |
month-view.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 {
AfterContentInit,
ChangeDetectionStrategy,
Component,
EventEmitter,
Inject,
Input,
Optional,
... |
this.userSelection.emit();
}
/** Initializes this month view. */
private _init() {
this._selectedDate = this._getDateInCurrentMonth(this.selected);
this._todayDate = this._getDateInCurrentMonth(this._dateAdapter.today());
this._monthLabel =
this._dateAdapter.getMonthNames('short')[this.... | {
const selectedYear = this._dateAdapter.getYear(this.activeDate);
const selectedMonth = this._dateAdapter.getMonth(this.activeDate);
const selectedDate = this._dateAdapter.createDate(selectedYear, selectedMonth, date);
this.selectedChange.emit(selectedDate);
} | conditional_block |
month-view.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 {
AfterContentInit,
ChangeDetectionStrategy,
Component,
EventEmitter,
Inject,
Input,
Optional,
... |
/** Handles when a new date is selected. */
_dateSelected(date: number) {
if (this._selectedDate != date) {
const selectedYear = this._dateAdapter.getYear(this.activeDate);
const selectedMonth = this._dateAdapter.getMonth(this.activeDate);
const selectedDate = this._dateAdapter.createDate(se... | {
this._init();
} | identifier_body |
month-view.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 {
AfterContentInit,
ChangeDetectionStrategy,
Component,
EventEmitter,
Inject,
Input,
Optional,
... | (value: D) {
this._selected = value;
this._selectedDate = this._getDateInCurrentMonth(this.selected);
}
private _selected: D;
/** A function used to filter which dates are selectable. */
@Input() dateFilter: (date: D) => boolean;
/** Emits when a new date is selected. */
@Output() selectedChange =... | selected | identifier_name |
month-view.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 {
AfterContentInit,
ChangeDetectionStrategy,
Component,
EventEmitter,
Inject,
Input,
Optional,
... | private _createWeekCells() {
let daysInMonth = this._dateAdapter.getNumDaysInMonth(this.activeDate);
let dateNames = this._dateAdapter.getDateNames();
this._weeks = [[]];
for (let i = 0, cell = this._firstWeekOffset; i < daysInMonth; i++, cell++) {
if (cell == DAYS_PER_WEEK) {
this._week... |
/** Creates MdCalendarCells for the dates in this month. */ | random_line_split |
views.py | # -*- coding: UTF-8 -*-
from django.conf import settings as dsettings
from django.contrib.auth import models as authModels
from django.core.paginator import Paginator, InvalidPage, EmptyPage
from django.http import HttpResponse, Http404
from django.shortcuts import render, render_to_response, get_object_or_404
from dja... |
else:
result = j(result)
status = 200
return HttpResponse(content=result, content_type=ct, status=status)
return decorator(wrapper, f)
def post_list(request):
return render(request, 'microblog/post_list.html', {})
def category(request, category):
catego... | return result | conditional_block |
views.py | # -*- coding: UTF-8 -*-
from django.conf import settings as dsettings
from django.contrib.auth import models as authModels
from django.core.paginator import Paginator, InvalidPage, EmptyPage
from django.http import HttpResponse, Http404
from django.shortcuts import render, render_to_response, get_object_or_404
from dja... | (request, year, month=None):
return render_to_response(
'microblog/list_by_year.html',
{
'year': year,
'month': month,
},
context_instance=RequestContext(request)
)
def tag(request, tag):
tag = get_object_or_404(Tag, name=tag)
return render_to_res... | post_list_by_year | identifier_name |
views.py | # -*- coding: UTF-8 -*-
from django.conf import settings as dsettings
from django.contrib.auth import models as authModels
from django.core.paginator import Paginator, InvalidPage, EmptyPage
from django.http import HttpResponse, Http404
from django.shortcuts import render, render_to_response, get_object_or_404
from dja... | return -1
page = json.loads(page)
if not page['succeeded']:
return -1
elif page['message'] is None:
return 0
else:
return page['message']['num_comments']
def _post404(f):
def wrapper(*args, **kw):
try:
return f(*arg... | url = settings.MICROBLOG_COMMENT_DISQUS_API_URL + 'get_thread_by_url?%s' % args
resp, page = h.request(url)
if resp.status != 200: | random_line_split |
views.py | # -*- coding: UTF-8 -*-
from django.conf import settings as dsettings
from django.contrib.auth import models as authModels
from django.core.paginator import Paginator, InvalidPage, EmptyPage
from django.http import HttpResponse, Http404
from django.shortcuts import render, render_to_response, get_object_or_404
from dja... | url = settings.MICROBLOG_COMMENT_DISQUS_API_URL + 'get_thread_by_url?%s' % args
resp, page = h.request(url)
if resp.status != 200:
return -1
page = json.loads(page)
if not page['succeeded']:
return -1
elif page['message'] is None:
retu... | post = content.post
if settings.MICROBLOG_COMMENT == 'comment':
import django_comments as comments
from django.contrib.contenttypes.models import ContentType
model = comments.get_model()
q = model.objects.filter(
content_type=ContentType.objects.get_for_model(post),
... | identifier_body |
ComponentsView.js | var Backbone = require('backbone');
module.exports = Backbone.View.extend({
initialize(o) {
this.opts = o || {};
this.config = o.config || {};
this.listenTo( this.collection, 'add', this.addTo );
this.listenTo( this.collection, 'reset', this.render );
},
/**
* Add to collection
* @param ... |
}
//viewObject = dt[type] ? dt[type].view : dt.default.view;
var view = new viewObject({
model,
config: this.config,
componentTypes: dt,
});
var rendered = view.render().el;
if(view.model.get('type') == 'textnode')
rendered = document.createTextNode(view.model.get('co... | {
viewObject = dt[it].view;
break;
} | conditional_block |
ComponentsView.js | var Backbone = require('backbone');
module.exports = Backbone.View.extend({
initialize(o) {
this.opts = o || {};
this.config = o.config || {};
this.listenTo( this.collection, 'add', this.addTo );
this.listenTo( this.collection, 'reset', this.render );
},
/**
* Add to collection
* @param ... | // need to change the logic of append
if(pc && p.children().length == index){
index--;
method = 'after';
}
// In case the added is new in the collection index will be -1
if(index < 0) {
p.append(rendered);
}else {
if(pc) {
... | var p = this.$parent;
var pc = p.children;
if(typeof index != 'undefined'){
var method = 'before';
// If the added model is the last of collection | random_line_split |
ComponentsView.js | var Backbone = require('backbone');
module.exports = Backbone.View.extend({
| (o) {
this.opts = o || {};
this.config = o.config || {};
this.listenTo( this.collection, 'add', this.addTo );
this.listenTo( this.collection, 'reset', this.render );
},
/**
* Add to collection
* @param {Object} Model
*
* @return void
* @private
* */
addTo(model) {
var i =... | initialize | identifier_name |
ComponentsView.js | var Backbone = require('backbone');
module.exports = Backbone.View.extend({
initialize(o) {
this.opts = o || {};
this.config = o.config || {};
this.listenTo( this.collection, 'add', this.addTo );
this.listenTo( this.collection, 'reset', this.render );
},
/**
* Add to collection
* @param ... |
});
| {
var fragment = document.createDocumentFragment();
this.$parent = $p || this.$el;
this.$el.empty();
this.collection.each(function(model){
this.addToCollection(model, fragment);
},this);
this.$el.append(fragment);
return this;
} | identifier_body |
wbBoard.js | }
}
},
p.drawing= function (x,y){
if (this._objectInit!=false){
return;
}
console.log("..drawing nwo");
if (this.shapeNOW!=undefined){
if (this.shapeNOW != this.resizer.formTarget){
var lc= this.shapeNOW.bg.globalToLocal(x,y);
this.shapeNOW.drawTemp(lc.x,lc.y);
}
}
... | p.updateShape = function(shape,action/*int*/,tab){
//does tab exists?
var found=false;
console.log("~~~~!-updateShape-!~~~~"+tab);
if (shape==undefined){
window.WBdraw.trace("<<<<<<< [1] ??????????? >>>>>>>>>"+shape);
window.WBdraw.trace("<<<<<<<<<< >>>>>>>>>>");
window.WBdraw.trace("<<<<<<<<<... | random_line_split | |
wbBoard.js | (id, color ) {
this.Container_constructor();
this.id=this.name=id;
this.color = color;
this.layers= new Object();
this.controller =null;
this.currentTab=0;
this.allTabs={};
//this.config=new WBdraw.ConfigWB(platform, width, height);
this._currentdeckIndex=null;
this.shapeNOW=null; //shape cu... | WBoard | identifier_name | |
wbBoard.js | ,action/*int*/,tab){
//does tab exists?
var found=false;
console.log("~~~~!-updateShape-!~~~~"+tab);
if (shape==undefined){
window.WBdraw.trace("<<<<<<< [1] ??????????? >>>>>>>>>"+shape);
window.WBdraw.trace("<<<<<<<<<< >>>>>>>>>>");
window.WBdraw.trace("<<<<<<<<<< >>>>>>>>>>");
window.... | {
window.WBdraw.trace("=========onRelease-========"+this.currentTab);
var shape = event.param;
if (this._tempModel.type=="links"){
console.log("ola links just happened");
return;
}
mainStage.removeEventListener("stagemousemove", shape.moveSTART);
mainStage.removeEventListener("stagemous... | identifier_body | |
wbBoard.js | }
}
},
p.drawing= function (x,y){
if (this._objectInit!=false){
return;
}
console.log("..drawing nwo");
if (this.shapeNOW!=undefined){
if (this.shapeNOW != this.resizer.formTarget){
var lc= this.shapeNOW.bg.globalToLocal(x,y);
this.shapeNOW.drawTemp(lc.x,lc.y);
}
}
... | else if (action==window.WBdraw.FormProxy.DELETE){
console.log("see if event already exists in undo/redo with SAME timeStamp");
//console.log(shape);
//console.log(this.allTabs[tab]);
}
}
/**
** any links connected to SAME objects?
**/
p.uniqueLink = function (linkShape,tab){
| {
this.allTabs[tab].push(flat);
} | conditional_block |
snack-bar-ref.ts | /**
* @license
* Copyright Google LLC 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 {OverlayRef} from '@angular/cdk/overlay';
import {Observable, Subject} from 'rxjs';
import {_SnackBarContainer... |
/**
* Marks the snackbar action clicked.
* @deprecated Use `dismissWithAction` instead.
* @breaking-change 8.0.0
*/
closeWithAction(): void {
this.dismissWithAction();
}
/** Dismisses the snack bar after some duration */
_dismissAfter(duration: number): void {
// Note that we need to c... | {
if (!this._onAction.closed) {
this._dismissedByAction = true;
this._onAction.next();
this._onAction.complete();
}
clearTimeout(this._durationTimeoutId);
} | identifier_body |
snack-bar-ref.ts | /**
* @license
* Copyright Google LLC 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 {OverlayRef} from '@angular/cdk/overlay';
import {Observable, Subject} from 'rxjs';
import {_SnackBarContainer... | (containerInstance: _SnackBarContainer,
private _overlayRef: OverlayRef) {
this.containerInstance = containerInstance;
// Dismiss snackbar on action.
this.onAction().subscribe(() => this.dismiss());
containerInstance._onExit.subscribe(() => this._finishDismiss());
}
/** Dismisses the ... | constructor | identifier_name |
snack-bar-ref.ts | /**
* @license
* Copyright Google LLC 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 {OverlayRef} from '@angular/cdk/overlay';
import {Observable, Subject} from 'rxjs';
import {_SnackBarContainer... |
}
/** Cleans up the DOM after closing. */
private _finishDismiss(): void {
this._overlayRef.dispose();
if (!this._onAction.closed) {
this._onAction.complete();
}
this._afterDismissed.next({dismissedByAction: this._dismissedByAction});
this._afterDismissed.complete();
this._dismis... | {
this._afterOpened.next();
this._afterOpened.complete();
} | conditional_block |
snack-bar-ref.ts | /**
* @license
* Copyright Google LLC 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 {OverlayRef} from '@angular/cdk/overlay';
import {Observable, Subject} from 'rxjs';
import {_SnackBarContainer... | afterOpened(): Observable<void> {
return this.containerInstance._onEnter;
}
/** Gets an observable that is notified when the snack bar action is called. */
onAction(): Observable<void> {
return this._onAction;
}
} |
/** Gets an observable that is notified when the snack bar has opened and appeared. */ | random_line_split |
__openerp__.py | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2012 - INECO PARTNERSHIP LIMITED (<http://www.ineco.co.th>).
#
# This program is free software: you can redistribute it and/or modify
# it under... | 'category': 'Extended',
'description': """
""",
'author': 'Mr.Tititab Srisookco',
'website': 'http://www.ineco.co.th',
'depends': ['base','purchase','stock'],
'data': [],
'demo': [],
'test':[],
'update_xml': [
'stock_view.xml',
],
'installable': True,
'images'... |
{
'name': 'Ineco Purchase Sequence',
'version': '0.1', | random_line_split |
handleapi.rs | // Licensed under the Apache License, Version 2.0
// <LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
// All files in the project carrying such notice may not be copied, modified, or distributed
// except according ... | pub fn GetHandleInformation(
hObject: HANDLE,
lpdwFlags: LPDWORD,
) -> BOOL;
pub fn SetHandleInformation(
hObject: HANDLE,
dwMask: DWORD,
dwFlags: DWORD,
) -> BOOL;
} | random_line_split | |
overlap_numsam.py | #Copyright (C) 2013 by Ngan Nguyen
#
#Released under the MIT license, see LICENSE.txt
'''
1/ split the clones by number of samples that share them
2/ randomly select n clones for each number of samples
3/ print summary results: numsam2clonecount
Input: the clone2sample2size directory
minimum number of samples
... | if numsam not in numsam2clones:
numsam2clones[numsam] = [c]
else:
numsam2clones[numsam].append(c)
return numsam2clones
class SplitClonesByNumsam(Target):
def __init__(self, infile, outdir, minsam, maxsam):
Target.__init__(self)
self.in... | continue | random_line_split |
overlap_numsam.py | #Copyright (C) 2013 by Ngan Nguyen
#
#Released under the MIT license, see LICENSE.txt
'''
1/ split the clones by number of samples that share them
2/ randomly select n clones for each number of samples
3/ print summary results: numsam2clonecount
Input: the clone2sample2size directory
minimum number of samples
... |
if __name__ == '__main__':
from aimseqtk.src.overlap.overlap_numsam import *
main()
| usage = ("%prog <indir> <minimum_sample> <outdir>")
parser = lcommon.init_options(usage)
parser.add_option('-m', '--maxsam', dest='maxsam', type='int',
default=None, help=('max number of samples'))
parser.add_option('--db', dest='db', action='store_true', default=False,
... | identifier_body |
overlap_numsam.py | #Copyright (C) 2013 by Ngan Nguyen
#
#Released under the MIT license, see LICENSE.txt
'''
1/ split the clones by number of samples that share them
2/ randomly select n clones for each number of samples
3/ print summary results: numsam2clonecount
Input: the clone2sample2size directory
minimum number of samples
... |
for sc in subclones:
f2.write("%s\t%s\n" % (sc, num))
f.close()
if f2:
f2.close()
sumfile = os.path.join(self.outdir, "numsam2clonecount.txt")
f3 = open(sumfile, 'w')
f3.write("#Numsam\tClonecount\n")
nums = sorted([int(n) ... | subclones = random.sample(clones, self.sampling) | conditional_block |
overlap_numsam.py | #Copyright (C) 2013 by Ngan Nguyen
#
#Released under the MIT license, see LICENSE.txt
'''
1/ split the clones by number of samples that share them
2/ randomly select n clones for each number of samples
3/ print summary results: numsam2clonecount
Input: the clone2sample2size directory
minimum number of samples
... | (self):
c2sdir = self.indir
if self.db:
c2sdir = os.path.join(self.outdir, "clone2sam2size_db")
system("mkdir -p %s" % c2sdir)
sizetype = 'freq'
self.addChildTarget(scommon.GetClone2Samples(self.indir, c2sdir,
... | run | identifier_name |
color_chooser_dialog.rs | // Copyright 2013-2015, The Gtk-rs Project Developers.
// See the COPYRIGHT file at the top-level directory of this distribution.
// Licensed under the MIT license, see the LICENSE file or <http://opensource.org/licenses/MIT>
use ffi;
use FFIWidget;
use cast::{GTK_WINDOW};
use glib::translate::ToGlibPtr;
struct_Widge... | None => ::std::ptr::null_mut()
}
)
};
if tmp_pointer.is_null() {
None
} else {
Some(::FFIWidget::wrap_widget(tmp_pointer))
}
}
}
impl_drop!(ColorChooserDialog);
impl_TraitWidget!(ColorChooserDialog);
impl ::Co... | pub fn new(title: &str, parent: Option<&::Window>) -> Option<ColorChooserDialog> {
let tmp_pointer = unsafe {
ffi::gtk_color_chooser_dialog_new(title.to_glib_none().0,
match parent {
Some(ref p) => GTK_WINDOW(p.unwrap_widget()), | random_line_split |
color_chooser_dialog.rs | // Copyright 2013-2015, The Gtk-rs Project Developers.
// See the COPYRIGHT file at the top-level directory of this distribution.
// Licensed under the MIT license, see the LICENSE file or <http://opensource.org/licenses/MIT>
use ffi;
use FFIWidget;
use cast::{GTK_WINDOW};
use glib::translate::ToGlibPtr;
struct_Widge... |
}
impl_drop!(ColorChooserDialog);
impl_TraitWidget!(ColorChooserDialog);
impl ::ContainerTrait for ColorChooserDialog {}
impl ::BinTrait for ColorChooserDialog {}
impl ::WindowTrait for ColorChooserDialog {}
impl ::DialogTrait for ColorChooserDialog {}
impl ::ColorChooserTrait for ColorChooserDialog {}
| {
let tmp_pointer = unsafe {
ffi::gtk_color_chooser_dialog_new(title.to_glib_none().0,
match parent {
Some(ref p) => GTK_WINDOW(p.unwrap_widget()),
None => ::std::ptr::null_mut()
}
)
};
if tmp_pointe... | identifier_body |
color_chooser_dialog.rs | // Copyright 2013-2015, The Gtk-rs Project Developers.
// See the COPYRIGHT file at the top-level directory of this distribution.
// Licensed under the MIT license, see the LICENSE file or <http://opensource.org/licenses/MIT>
use ffi;
use FFIWidget;
use cast::{GTK_WINDOW};
use glib::translate::ToGlibPtr;
struct_Widge... | else {
Some(::FFIWidget::wrap_widget(tmp_pointer))
}
}
}
impl_drop!(ColorChooserDialog);
impl_TraitWidget!(ColorChooserDialog);
impl ::ContainerTrait for ColorChooserDialog {}
impl ::BinTrait for ColorChooserDialog {}
impl ::WindowTrait for ColorChooserDialog {}
impl ::DialogTrait for ColorCh... | {
None
} | conditional_block |
color_chooser_dialog.rs | // Copyright 2013-2015, The Gtk-rs Project Developers.
// See the COPYRIGHT file at the top-level directory of this distribution.
// Licensed under the MIT license, see the LICENSE file or <http://opensource.org/licenses/MIT>
use ffi;
use FFIWidget;
use cast::{GTK_WINDOW};
use glib::translate::ToGlibPtr;
struct_Widge... | (title: &str, parent: Option<&::Window>) -> Option<ColorChooserDialog> {
let tmp_pointer = unsafe {
ffi::gtk_color_chooser_dialog_new(title.to_glib_none().0,
match parent {
Some(ref p) => GTK_WINDOW(p.unwrap_widget()),
None => ::std::ptr::null_... | new | identifier_name |
CHANGELOG.tsx | import { change, date } from 'common/changelog';
import SPELLS from 'common/SPELLS';
import { Adoraci, Sharrq, Sref, Zea, Karahtar } from 'CONTRIBUTORS';
import { SpellLink } from 'interface';
export default [
change(date(2021, 11, 13), 'Bumped Frost Mage to supported for 9.1.5.', Sharrq),
change(date(2021, 10, 29... | change(date(2021, 1, 15), <>Fixed an issue that was not adding the proper amount of additional CDR from <SpellLink id={SPELLS.DISCIPLINE_OF_THE_GROVE.id} />.</>, Sharrq),
change(date(2020, 12, 28), <>Updated conduit statistic boxes to use the new layout.</>, Sharrq),
change(date(2020, 12, 24), <>Fixed an error in... | change(date(2021, 4, 3), 'Verified changes and bumped support to 9.0.5', Adoraci),
change(date(2021, 3, 11), 'Reverting support back to Patch 9.0.2 as Frost Mage has not been fully tested/updated for 9.0.5.', Sharrq),
change(date(2021, 3, 11), 'Removed myself as a contributor/maintainer for Frost Mage. Marked Fro... | random_line_split |
paths.ts | (path: string): string {
const idx = ~path.lastIndexOf('/') || ~path.lastIndexOf('\\');
if (idx === 0) {
return '.';
} else if (~idx === 0) {
return path[0];
} else if (~idx === path.length - 1) {
return dirname(path.substring(0, path.length - 1));
} else {
let res = path.substring(0, ~idx);
if (isWindow... | dirname | identifier_name | |
paths.ts | else if (~idx === path.length - 1) {
return dirname(path.substring(0, path.length - 1));
} else {
let res = path.substring(0, ~idx);
if (isWindows && res[res.length - 1] === ':') {
res += nativeSep; // make sure drive letters end with backslash
}
return res;
}
}
/**
* @returns the base name of a path.... | {
return path[0];
} | conditional_block | |
paths.ts | ':') {
res += nativeSep; // make sure drive letters end with backslash
}
return res;
}
}
/**
* @returns the base name of a path.
*/
export function basename(path: string): string {
const idx = ~path.lastIndexOf('/') || ~path.lastIndexOf('\\');
if (idx === 0) {
return path;
} else if (~idx === path.leng... | }
res += part;
}
start = end + 1;
skip = false;
}
}
return root + res;
}
function streql(value: string, start: number, end: number, other: string): boolean {
return start + other.length === end && value.indexOf(other, start) === start;
}
/**
* Computes the _root_ this path, like `getRoot('c:\f... | let part = path.slice(start, end);
if (res !== '' && res[res.length - 1] !== sep) {
res += sep; | random_line_split |
paths.ts | returns `.far` from `boo.far` or the empty string.
*/
export function extname(path: string): string {
path = basename(path);
const idx = ~path.lastIndexOf('.');
return idx ? path.substring(~idx) : '';
}
const _posixBadPath = /(\/\.\.?\/)|(\/\.\.?)$|^(\.\.?\/)|(\/\/+)|(\\)/;
const _winBadPath = /(\\\.\.?\\)|(\\\.\.... | {
const identityEquals = (pathA === pathB);
if (!ignoreCase || identityEquals) {
return identityEquals;
}
if (!pathA || !pathB) {
return false;
}
return equalsIgnoreCase(pathA, pathB);
} | identifier_body | |
journal.py | from django.contrib import admin
from django.contrib.admin.widgets import AdminIntegerFieldWidget
from django.core.validators import MaxValueValidator, MinValueValidator
from modeltranslation.admin import TranslationAdmin
from django.urls import reverse
from django.utils import timezone as tz
from django.utils.html imp... | "id",
"localidentifier",
)
list_filter = (
"is_published",
"journal__collection",
"journal__name",
)
actions = [
"make_published",
"make_unpublished",
"force_free_access_to_true",
"force_free_access_to_false",
]
def force_f... | "is_published",
"view_issue_on_site",
)
search_fields = ( | random_line_split |
journal.py | from django.contrib import admin
from django.contrib.admin.widgets import AdminIntegerFieldWidget
from django.core.validators import MaxValueValidator, MinValueValidator
from modeltranslation.admin import TranslationAdmin
from django.urls import reverse
from django.utils import timezone as tz
from django.utils.html imp... |
return super().get_field_queryset(db, db_field, request)
class JournalForm(forms.ModelForm):
fields = "all"
model = Journal
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
# Limit `year_of_addition` field values to the current year and the next two years.
... | if request._obj:
return db_field.remote_field.model._default_manager.using(db).filter(
type__code=request._obj.type.code
)
# If there is no parent journal (during journal creation), return an empty queryset.
else:
return db_fiel... | conditional_block |
journal.py | from django.contrib import admin
from django.contrib.admin.widgets import AdminIntegerFieldWidget
from django.core.validators import MaxValueValidator, MinValueValidator
from modeltranslation.admin import TranslationAdmin
from django.urls import reverse
from django.utils import timezone as tz
from django.utils.html imp... | odelForm):
class Meta:
model = JournalInformation
fields = "__all__"
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
# Exclude French & English from other_languages field. These languages are set in the
# main_languages field.
self.fields["... | nformationAdminForm(forms.M | identifier_name |
journal.py | from django.contrib import admin
from django.contrib.admin.widgets import AdminIntegerFieldWidget
from django.core.validators import MaxValueValidator, MinValueValidator
from modeltranslation.admin import TranslationAdmin
from django.urls import reverse
from django.utils import timezone as tz
from django.utils.html imp... | force_free_access_to_false.short_description = _(
"Ne pas contraindre ces numéros au libre accès"
)
def view_issue_on_site(self, obj):
""" Display the link leading to the issue on website """
url = reverse(
"public:journal:issue_detail",
kwargs={
... | rk a set of issues as not open access"""
queryset.update(force_free_access=False)
| identifier_body |
test_mongodb.py | """Tests for mongodb backend
Authors:
* Min RK
"""
#-------------------------------------------------------------------------
# Copyright (C) 2011 The IPython Development Team
#
# Distributed under the terms of the BSD License. The full license is in
# the file COPYING, distributed as part of this software.
#--... |
try:
c = Connection(**conn_kwargs)
except Exception:
c = None
class TestMongoBackend(test_db.TaskDBTest, TestCase):
"""MongoDB backend tests"""
def create_db(self):
try:
return MongoDB(database='iptestdb', _connection=c)
except Exception:
raise SkipTest("Cou... | conn_kwargs['port'] = int(os.environ['DB_PORT']) | conditional_block |
test_mongodb.py | """Tests for mongodb backend
Authors:
* Min RK
"""
#-------------------------------------------------------------------------
# Copyright (C) 2011 The IPython Development Team
#
# Distributed under the terms of the BSD License. The full license is in
# the file COPYING, distributed as part of this software.
#--... | try:
c = Connection(**conn_kwargs)
except Exception:
c = None
class TestMongoBackend(test_db.TaskDBTest, TestCase):
"""MongoDB backend tests"""
def create_db(self):
try:
return MongoDB(database='iptestdb', _connection=c)
except Exception:
raise SkipTest("Could... | conn_kwargs['host'] = os.environ['DBA_MONGODB_ADMIN_URI']
if 'DB_PORT' in os.environ:
conn_kwargs['port'] = int(os.environ['DB_PORT'])
| random_line_split |
test_mongodb.py | """Tests for mongodb backend
Authors:
* Min RK
"""
#-------------------------------------------------------------------------
# Copyright (C) 2011 The IPython Development Team
#
# Distributed under the terms of the BSD License. The full license is in
# the file COPYING, distributed as part of this software.
#--... | (self):
try:
return MongoDB(database='iptestdb', _connection=c)
except Exception:
raise SkipTest("Couldn't connect to mongodb")
def teardown(self):
if c is not None:
c.drop_database('iptestdb')
| create_db | identifier_name |
test_mongodb.py | """Tests for mongodb backend
Authors:
* Min RK
"""
#-------------------------------------------------------------------------
# Copyright (C) 2011 The IPython Development Team
#
# Distributed under the terms of the BSD License. The full license is in
# the file COPYING, distributed as part of this software.
#--... |
def teardown(self):
if c is not None:
c.drop_database('iptestdb')
| """MongoDB backend tests"""
def create_db(self):
try:
return MongoDB(database='iptestdb', _connection=c)
except Exception:
raise SkipTest("Couldn't connect to mongodb") | identifier_body |
router.js | const express = require('express')
const multer = require('multer')
const upload = multer({ dest: '.uploads/' })
const router = new express.Router()
// Routes handlers
const books = require('./books.js')
const authors = require('./authors.js')
const collections = require('./collections.js')
const illustrators = requir... |
module.exports = router |
// Error middleware to catch unexpected errors
router.use(require('../middleware/error.js').errorHandler) | random_line_split |
Sum_impl.ts | /**
* @license
* Copyright 2020 Google LLC. 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 a... |
let outShape = sumOutShape;
if (keepDims) {
// rather than reshape at the end, set the target shape here.
outShape = backend_util.expandShapeToKeepDim(sumOutShape, origAxes);
}
const inSize = util.sizeFromShape(reduceShape);
const xSize = util.sizeFromShape(x.shape);
const batchSize = xSize / inSi... | {
const reductionIndices = axis;
const xRank = x.shape.length;
const origAxes = util.parseAxisParam(reductionIndices, x.shape);
let axes = origAxes;
const permutedAxes = backend_util.getAxesPermutation(axes, xRank);
const sumInputIsTransposed = permutedAxes != null;
let sumInput = x;
if (sumInputIsTr... | identifier_body |
Sum_impl.ts | /**
* @license
* Copyright 2020 Google LLC. 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 a... | backend: MathBackendWebGL): TensorInfo {
const reductionIndices = axis;
const xRank = x.shape.length;
const origAxes = util.parseAxisParam(reductionIndices, x.shape);
let axes = origAxes;
const permutedAxes = backend_util.getAxesPermutation(axes, xRank);
const sumInputIsTransposed = permutedAxes != nu... | import {transposeImpl} from './Transpose_impl';
export function sumImpl(
x: TensorInfo, axis: number|number[], keepDims: boolean, | random_line_split |
Sum_impl.ts | /**
* @license
* Copyright 2020 Google LLC. 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 a... |
return out;
}
| {
backend.disposeIntermediateTensorInfo(sumInput);
} | conditional_block |
Sum_impl.ts | /**
* @license
* Copyright 2020 Google LLC. 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 a... | (
x: TensorInfo, axis: number|number[], keepDims: boolean,
backend: MathBackendWebGL): TensorInfo {
const reductionIndices = axis;
const xRank = x.shape.length;
const origAxes = util.parseAxisParam(reductionIndices, x.shape);
let axes = origAxes;
const permutedAxes = backend_util.getAxesPermutation(... | sumImpl | identifier_name |
stitching.ts | import { GraphQLSchema } from "graphql"
export const consignmentStitchingEnvironment = (
localSchema: GraphQLSchema,
convectionSchema: GraphQLSchema & { transforms: any }
) => ({
// The SDL used to declare how to stitch an object
extensionSchema: `
extend type ConsignmentSubmission {
artist: Artist
... | ConsignmentSubmission: {
artist: {
fragment: `fragment SubmissionArtist on ConsignmentSubmission { artist_id }`,
resolve: (parent, _args, context, info) => {
const id = parent.artist_id
return info.mergeInfo.delegateToSchema({
schema: localSchema,
op... | random_line_split | |
urls.py | """
Copyright 2016 Jacob C. Wimberley.
This file is part of Weathredds.
Weathredds is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any... | url(r'logout/$', auth_views.logout_then_login, name='logout'),
#url(r'^discussions/(\d{8}_\d{4})/(\d{8}_\d{4})/$', views.discussionRange),
#url(r'^discussions/$', views.allDiscussions),
url(r'extendThread/(\d+)$', views.extendThread, name='extendThread'),
url(r'newEvent/$', views.newEvent, name='newEvent'),... | url(r'login/$', auth_views.login, {'template_name': 'registration/login.html'}, name='login'), | random_line_split |
GCodeGzReader.py | # Copyright (c) 2020 Ultimaker B.V.
# Cura is released under the terms of the LGPLv3 or higher.
import gzip
from UM.Mesh.MeshReader import MeshReader #The class we're extending/implementing.
from UM.MimeTypeDatabase import MimeTypeDatabase, MimeType #To add the .gcode.gz files to the MIME type database.
from UM.Plugi... | PluginRegistry.getInstance().getPluginObject("GCodeReader").preReadFromStream(uncompressed_gcode)
result = PluginRegistry.getInstance().getPluginObject("GCodeReader").readFromStream(uncompressed_gcode, file_name)
return result
| """A file reader that reads gzipped g-code.
If you're zipping g-code, you might as well use gzip!
"""
def __init__(self) -> None:
super().__init__()
MimeTypeDatabase.addMimeType(
MimeType(
name = "application/x-cura-compressed-gcode-file",
commen... | identifier_body |
GCodeGzReader.py | # Copyright (c) 2020 Ultimaker B.V.
# Cura is released under the terms of the LGPLv3 or higher.
import gzip
| from UM.MimeTypeDatabase import MimeTypeDatabase, MimeType #To add the .gcode.gz files to the MIME type database.
from UM.PluginRegistry import PluginRegistry
class GCodeGzReader(MeshReader):
"""A file reader that reads gzipped g-code.
If you're zipping g-code, you might as well use gzip!
"""
def __... | from UM.Mesh.MeshReader import MeshReader #The class we're extending/implementing. | random_line_split |
GCodeGzReader.py | # Copyright (c) 2020 Ultimaker B.V.
# Cura is released under the terms of the LGPLv3 or higher.
import gzip
from UM.Mesh.MeshReader import MeshReader #The class we're extending/implementing.
from UM.MimeTypeDatabase import MimeTypeDatabase, MimeType #To add the .gcode.gz files to the MIME type database.
from UM.Plugi... | (self, file_name):
with open(file_name, "rb") as file:
file_data = file.read()
uncompressed_gcode = gzip.decompress(file_data).decode("utf-8")
PluginRegistry.getInstance().getPluginObject("GCodeReader").preReadFromStream(uncompressed_gcode)
result = PluginRegistry.getInstance... | _read | identifier_name |
javax.crypto.EncryptedPrivateKeyInfo.d.ts | declare namespace javax {
namespace crypto {
class | {
public constructor(arg0: number[] | java.lang.Byte[])
public constructor(arg0: java.lang.String | string, arg1: number[] | java.lang.Byte[])
public constructor(arg0: java.security.AlgorithmParameters, arg1: number[] | java.lang.Byte[])
public getAlgName(): java.lang.String
public getAlg... | EncryptedPrivateKeyInfo | identifier_name |
javax.crypto.EncryptedPrivateKeyInfo.d.ts | declare namespace javax {
namespace crypto {
class EncryptedPrivateKeyInfo {
public constructor(arg0: number[] | java.lang.Byte[]) | public constructor(arg0: java.security.AlgorithmParameters, arg1: number[] | java.lang.Byte[])
public getAlgName(): java.lang.String
public getAlgParameters(): java.security.AlgorithmParameters
public getEncryptedData(): number[]
public getKeySpec(arg0: javax.crypto.Cipher): java.security.... | public constructor(arg0: java.lang.String | string, arg1: number[] | java.lang.Byte[]) | random_line_split |
ychenik_search.js | (function ($) {
Drupal.ychenikSearch = {};
/**
* jQuery plugin. |
this.each(function () {
$(this).addClass('ychenik-search').find('label').each(function () {
var context = this.form;
var $label = $(this);
if (!$label.attr('for')) {
return;
}
var $field = $('#' + $label.attr('for'), context);
if (!$field.length || !$field.is('input:te... | */
$.fn.ychenikSearch = function (stars) {
stars = stars || 0; | random_line_split |
Makefile.py |
return
def uncompress( fp, member, encoding = 'U8' ):
name = member.rsplit( '/', 1 )[-1]
print( 'Extracting %s ...' % name )
fp.extract( member )
shutil.move( member, name )
if '/' in member:
shutil.rmtree( member.split( '/', 1 )[0] )
return open( name, 'rb', encoding, 'ignore' )
... | print( 'Downloading from [%s] ...' % url )
urllib_request.urlretrieve( url, dest )
print( 'Download complete.\n' ) | conditional_block | |
Makefile.py | member, encoding = 'U8': \
uncompress( tf.open( path, 'r:gz' ), member, encoding )
def parserCore( fp, pos, beginmark = None, endmark = None ):
if beginmark and endmark:
start = False
else: start = True
mlist = set()
for line in fp:
if beginmark and line.startswith( beginmark )... | ret[elems[0]] = elems[1:]
return ret
def toManyRules( src_table ):
tomany = set()
for ( f, t ) in src_table.iteritems():
for i in range( 1, len( t ) ):
tomany.add( t[i] )
return tomany
def removeRules( path, table ):
fp = open( path, 'rb', 'U8' )
texc = ... | random_line_split | |
Makefile.py | member, encoding = 'U8': \
uncompress( tf.open( path, 'r:gz' ), member, encoding )
def parserCore( fp, pos, beginmark = None, endmark = None ):
if beginmark and endmark:
start = False
else: start = True
mlist = set()
for line in fp:
if beginmark and line.startswith( beginmark )... |
def removeRules( path, table ):
fp = open( path, 'rb', 'U8' )
texc = list()
for line in fp:
elems = line.split( '=>' )
f = t = elems[0].strip()
if len( elems ) == 2:
t = elems[1].strip()
f = f.strip('"').strip("'")
t = t.strip('"').strip("'")
if ... | tomany = set()
for ( f, t ) in src_table.iteritems():
for i in range( 1, len( t ) ):
tomany.add( t[i] )
return tomany | identifier_body |
Makefile.py | member, encoding = 'U8': \
uncompress( tf.open( path, 'r:gz' ), member, encoding )
def parserCore( fp, pos, beginmark = None, endmark = None ):
if beginmark and endmark:
start = False
else: start = True
mlist = set()
for line in fp:
if beginmark and line.startswith( beginmark )... | ( path ):
""" Read tsi.src and parse it. """
src = 'libtabe/tsi-src/tsi.src'
dst = 'tsi.src'
fp = untargz( path, src, 'big5hkscs' )
return parserCore( fp, 0 )
def unihanParser( path ):
""" Read Unihan_Variants.txt and parse it. """
fp = unzip( path, 'Unihan_Variants.txt', 'U8' )
t2s = d... | tsiParser | identifier_name |
TranslatedInstanceStatus.tsx | import * as React from 'react'
import { Link, RouteComponentProps } from 'react-router-dom'
import { Dic, classes } from '@framework/Globals'
import { JavascriptMessage } from '@framework/Signum.Entities'
import { API, TranslatedTypeSummary } from '../TranslatedInstanceClient'
import { TranslationMessage } from '.... |
return (
<div>
<div className="btn-toolbar">
<input key={fileVer} type="file" onChange={handleInputChange} style={{ display: "inline", float: "left", width: "inherit" }} />
</div>
<small>Select a .xlsx file with the translations</small>
</div>
);
}
... | {
let f = (e.currentTarget as HTMLInputElement).files![0];
let fileReader = new FileReader();
fileReader.onerror = e => { setTimeout(() => { throw (e as any).error; }, 0); };
fileReader.onload = e => {
let content = ((e.target as any).result as string).after("base64,");
let... | identifier_body |
TranslatedInstanceStatus.tsx | import * as React from 'react'
import { Link, RouteComponentProps } from 'react-router-dom'
import { Dic, classes } from '@framework/Globals'
import { JavascriptMessage } from '@framework/Signum.Entities'
import { API, TranslatedTypeSummary } from '../TranslatedInstanceClient'
import { TranslationMessage } from '.... | (e: React.FormEvent<any>) {
let f = (e.currentTarget as HTMLInputElement).files![0];
let fileReader = new FileReader();
fileReader.onerror = e => { setTimeout(() => { throw (e as any).error; }, 0); };
fileReader.onload = e => {
let content = ((e.target as any).result as string).afte... | handleInputChange | identifier_name |
TranslatedInstanceStatus.tsx | import * as React from 'react'
import { Link, RouteComponentProps } from 'react-router-dom'
import { Dic, classes } from '@framework/Globals'
import { JavascriptMessage } from '@framework/Signum.Entities'
import { API, TranslatedTypeSummary } from '../TranslatedInstanceClient'
import { TranslationMessage } from '.... | <a href="#" className={classes("status-" + tree[type][culture].state, "ml-2")} onClick={e => { e.preventDefault(); API.downloadSync(type, culture); }}><FontAwesomeIcon icon="download" /></a>
</td>
)
)}
</tr>
)}
</tbody>
</tab... | <td key={culture}>
<Link to={`~/translatedInstance/view/${type}/${culture}`}>{TranslationMessage.View.niceToString()}</Link>
<a href="#" className="ml-2" onClick={e => { e.preventDefault(); API.downloadView(type, culture); }}><FontAwesomeIcon icon="download" /></a>
... | random_line_split |
attention_graphs.py | import gzip
import os
import pickle
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
matplotlib.use('TKagg')
def | ():
# Load attentions
print('Loading attentions to pickle file')
with gzip.open(
os.path.join('training_results', 'torch_train', 'attentions.pkl.gz'),
'r') as att_file:
attentions = pickle.load(att_file)
# Set up figure with colorbar
fig = plt.figure()
ax = fig.add_subplot(111)
cax = ax.m... | show_attention | identifier_name |
attention_graphs.py | import gzip
import os
import pickle
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
matplotlib.use('TKagg')
def show_attention():
# Load attentions
|
plt.show()
show_attention()
| print('Loading attentions to pickle file')
with gzip.open(
os.path.join('training_results', 'torch_train', 'attentions.pkl.gz'),
'r') as att_file:
attentions = pickle.load(att_file)
# Set up figure with colorbar
fig = plt.figure()
ax = fig.add_subplot(111)
cax = ax.matshow(np.mean(np.array(at... | identifier_body |
attention_graphs.py | import gzip
import os
import pickle
import matplotlib
import matplotlib.pyplot as plt |
matplotlib.use('TKagg')
def show_attention():
# Load attentions
print('Loading attentions to pickle file')
with gzip.open(
os.path.join('training_results', 'torch_train', 'attentions.pkl.gz'),
'r') as att_file:
attentions = pickle.load(att_file)
# Set up figure with colorbar
fig = plt.figu... | import numpy as np | random_line_split |
audio.rs | use super::error::Error;
use ao;
use earwax::{Earwax, Timestamp, LogLevel};
use std::sync::{Once, ONCE_INIT};
static START: Once = ONCE_INIT;
/// Type for audio streaming audio that hides the details of earwax and ao-rs handling.
pub struct Audio {
earwax: Earwax,
driver: ao::Driver,
format: ao::Format, | device: ao::Device,
}
impl Audio {
/// Tries to initialize a new stream for the given URL.
pub fn new(url: &str) -> Result<Self, Error> {
// #[cfg(not(debug_assertions))]
START.call_once(|| { Earwax::set_log_level(LogLevel::Error); });
let earwax = try!(Earwax::new(url));
l... | random_line_split | |
audio.rs | use super::error::Error;
use ao;
use earwax::{Earwax, Timestamp, LogLevel};
use std::sync::{Once, ONCE_INIT};
static START: Once = ONCE_INIT;
/// Type for audio streaming audio that hides the details of earwax and ao-rs handling.
pub struct Audio {
earwax: Earwax,
driver: ao::Driver,
format: ao::Format,
... |
/// Plays the next chunk of the stream to the default audio device.
/// # Returns
/// If playback was successful (at getting next stream chunk), the value returned
/// is a tuple where the first element is the current timestamp, and the second
/// element is the total timestamp.
pub fn play(&m... | {
// #[cfg(not(debug_assertions))]
START.call_once(|| { Earwax::set_log_level(LogLevel::Error); });
let earwax = try!(Earwax::new(url));
let driver = try!(ao::Driver::new());
let format = ao::Format::new();
let device = try!(ao::Device::new(&driver, &format, None));
... | identifier_body |
audio.rs | use super::error::Error;
use ao;
use earwax::{Earwax, Timestamp, LogLevel};
use std::sync::{Once, ONCE_INIT};
static START: Once = ONCE_INIT;
/// Type for audio streaming audio that hides the details of earwax and ao-rs handling.
pub struct Audio {
earwax: Earwax,
driver: ao::Driver,
format: ao::Format,
... | else {
Err(())
}
}
/// Plays all the chunks remaining in the stream to the default audio the device.
pub fn play_all(&mut self) {
while let Some(chunk) = self.earwax.spit() {
self.device.play(chunk.data);
}
}
}
| {
self.device.play(chunk.data);
Ok((chunk.time, duration))
} | conditional_block |
audio.rs | use super::error::Error;
use ao;
use earwax::{Earwax, Timestamp, LogLevel};
use std::sync::{Once, ONCE_INIT};
static START: Once = ONCE_INIT;
/// Type for audio streaming audio that hides the details of earwax and ao-rs handling.
pub struct Audio {
earwax: Earwax,
driver: ao::Driver,
format: ao::Format,
... | (url: &str) -> Result<Self, Error> {
// #[cfg(not(debug_assertions))]
START.call_once(|| { Earwax::set_log_level(LogLevel::Error); });
let earwax = try!(Earwax::new(url));
let driver = try!(ao::Driver::new());
let format = ao::Format::new();
let device = try!(ao::Device:... | new | identifier_name |
cssstylesheet.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
use crate::dom::bindings::codegen::Bindings::CSSStyleSheetBinding;
use crate::dom::bindings::codegen::Bindings::C... |
Ok(self.rulelist())
}
// https://drafts.csswg.org/cssom/#dom-cssstylesheet-insertrule
fn InsertRule(&self, rule: DOMString, index: u32) -> Fallible<u32> {
if !self.origin_clean.get() {
return Err(Error::Security);
}
self.rulelist()
.insert_rule(&rule... | {
return Err(Error::Security);
} | conditional_block |
cssstylesheet.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
| use crate::dom::bindings::root::{Dom, DomRoot, MutNullableDom};
use crate::dom::bindings::str::DOMString;
use crate::dom::cssrulelist::{CSSRuleList, RulesSource};
use crate::dom::element::Element;
use crate::dom::stylesheet::StyleSheet;
use crate::dom::window::Window;
use dom_struct::dom_struct;
use servo_arc::Arc;
use... | use crate::dom::bindings::codegen::Bindings::CSSStyleSheetBinding;
use crate::dom::bindings::codegen::Bindings::CSSStyleSheetBinding::CSSStyleSheetMethods;
use crate::dom::bindings::codegen::Bindings::WindowBinding::WindowBinding::WindowMethods;
use crate::dom::bindings::error::{Error, ErrorResult, Fallible};
use crate... | random_line_split |
cssstylesheet.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
use crate::dom::bindings::codegen::Bindings::CSSStyleSheetBinding;
use crate::dom::bindings::codegen::Bindings::C... | (&self) -> Fallible<DomRoot<CSSRuleList>> {
if !self.origin_clean.get() {
return Err(Error::Security);
}
Ok(self.rulelist())
}
// https://drafts.csswg.org/cssom/#dom-cssstylesheet-insertrule
fn InsertRule(&self, rule: DOMString, index: u32) -> Fallible<u32> {
if ... | GetCssRules | identifier_name |
cssstylesheet.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
use crate::dom::bindings::codegen::Bindings::CSSStyleSheetBinding;
use crate::dom::bindings::codegen::Bindings::C... |
}
| {
if !self.origin_clean.get() {
return Err(Error::Security);
}
self.rulelist().remove_rule(index)
} | identifier_body |
core.py | # -*- coding: utf-8 -*-
"""
Core Application - manage multiplexer connected with Analog Discovery 2
| receive voltage from sensors to estimate distance
API : wavefroms API
Author: Thatchakon Jom-ud
"""
from ctypes import *
from dwfconstants import *
import sys
import time
class Core():
hdwf = c_i... |
time.sleep(0.1)
self.dwf.FDwfAnalogInStatusData(self.hdwf, c_int(0), self.volt, 1)
return self.volt[0], self.distance(self.volt[0])
def disconnect_ad2(self):
self.enable_power_supplies(False)
self.dwf.FDwfDeviceCloseAll()
self.hdwf = c_int()
self.gui.st... | break | conditional_block |
core.py | # -*- coding: utf-8 -*-
"""
Core Application - manage multiplexer connected with Analog Discovery 2
| receive voltage from sensors to estimate distance
API : wavefroms API
Author: Thatchakon Jom-ud
"""
from ctypes import *
from dwfconstants import *
import sys
import time
class Core():
hdwf = c_i... |
def enable_power_supplies(self, enable):
# set up analog IO channel nodes
# enable positive supply
self.dwf.FDwfAnalogIOChannelNodeSet(self.hdwf, c_int(0), c_int(0), c_double(True))
# set voltage to 5 V
self.dwf.FDwfAnalogIOChannelNodeSet(self.hdwf, c_int(0), c_int(1), c_do... | return "Connected" if (self.hdwf.value != hdwfNone.value) else "Not Connect" | identifier_body |
core.py | # -*- coding: utf-8 -*-
"""
Core Application - manage multiplexer connected with Analog Discovery 2
| receive voltage from sensors to estimate distance
API : wavefroms API
Author: Thatchakon Jom-ud
"""
from ctypes import *
from dwfconstants import *
import sys
import time
class Core():
hdwf = c_i... |
self.dwf.FDwfAnalogInFrequencySet(self.hdwf, c_double(20000000.0))
self.dwf.FDwfAnalogInBufferSizeSet(self.hdwf, c_int(4000))
self.dwf.FDwfAnalogInChannelEnableSet(self.hdwf, c_int(0), c_bool(True))
self.dwf.FDwfAnalogInConfigure(self.hdwf, c_bool(False), c_bool(True))
while Tr... |
def get_volt_and_distance(self):
sts = c_byte() | random_line_split |
core.py | # -*- coding: utf-8 -*-
"""
Core Application - manage multiplexer connected with Analog Discovery 2
| receive voltage from sensors to estimate distance
API : wavefroms API
Author: Thatchakon Jom-ud
"""
from ctypes import *
from dwfconstants import *
import sys
import time
class Core():
hdwf = c_i... | (self, enable):
# set up analog IO channel nodes
# enable positive supply
self.dwf.FDwfAnalogIOChannelNodeSet(self.hdwf, c_int(0), c_int(0), c_double(True))
# set voltage to 5 V
self.dwf.FDwfAnalogIOChannelNodeSet(self.hdwf, c_int(0), c_int(1), c_double(5))
# enable negat... | enable_power_supplies | identifier_name |
log.py | import time
import logging
def time_zone(t):
if t.tm_isdst == 1 and time.daylight == 1:
tz_sec = time.altzone
tz_name = time.tzname[1]
else:
tz_sec = time.timezone
tz_name = time.tzname[0]
if tz_sec > 0:
tz_sign = '-'
else:
|
tz_offset = '%s%02d%02d' % (tz_sign, abs(tz_sec)//3600, abs(tz_sec//60)%60)
return (tz_offset, tz_name)
class JsubFormatter(logging.Formatter):
# Add this method in order to display time zone offset correctly under python 2.x
def formatTime(self, record, datefmt=None):
ct = time.localtime(re... | tz_sign = '+' | conditional_block |
log.py | import time
import logging
def time_zone(t):
if t.tm_isdst == 1 and time.daylight == 1:
tz_sec = time.altzone
tz_name = time.tzname[1]
else:
tz_sec = time.timezone
tz_name = time.tzname[0]
if tz_sec > 0:
tz_sign = '-'
else:
tz_sign = '+'
tz_offset =... | (self, record, datefmt=None):
ct = time.localtime(record.created)
if datefmt:
s = time.strftime(datefmt, ct)
else:
t = time.strftime('%Y-%m-%d %H:%M:%S', ct)
ms = '%03d' % record.msecs
tz_offset, tz_name = time_zone(ct)
s = '%s.%03d %... | formatTime | identifier_name |
log.py | import time
import logging
def time_zone(t):
if t.tm_isdst == 1 and time.daylight == 1:
tz_sec = time.altzone
tz_name = time.tzname[1]
else:
tz_sec = time.timezone
tz_name = time.tzname[0]
if tz_sec > 0:
tz_sign = '-'
else:
tz_sign = '+'
tz_offset =... |
_FORMATTER = JsubFormatter('[%(asctime)s][%(name)s|%(levelname)s]: %(message)s')
#_FORMATTER = logging.Formatter('[%(asctime)s](%(name)s:%(levelname)s) %(message)s', '%Y-%m-%d %H:%M:%S')
def add_stream_logger(level):
logger = logging.getLogger('JSUB')
logger.setLevel(level)
ch = logging.StreamHandler(... | ct = time.localtime(record.created)
if datefmt:
s = time.strftime(datefmt, ct)
else:
t = time.strftime('%Y-%m-%d %H:%M:%S', ct)
ms = '%03d' % record.msecs
tz_offset, tz_name = time_zone(ct)
s = '%s.%03d %s %s' % (t, record.msecs, tz_offset, t... | identifier_body |
log.py | import time
import logging
def time_zone(t):
if t.tm_isdst == 1 and time.daylight == 1:
tz_sec = time.altzone
tz_name = time.tzname[1]
else:
tz_sec = time.timezone
tz_name = time.tzname[0]
if tz_sec > 0:
tz_sign = '-'
else:
tz_sign = '+'
tz_offset =... | s = time.strftime(datefmt, ct)
else:
t = time.strftime('%Y-%m-%d %H:%M:%S', ct)
ms = '%03d' % record.msecs
tz_offset, tz_name = time_zone(ct)
s = '%s.%03d %s %s' % (t, record.msecs, tz_offset, tz_name)
return s
_FORMATTER = JsubFormatter('[... | if datefmt: | random_line_split |
pt-BR.js | export default {
region: 'Região',
calling: 'Chamadas',
logout: 'Logout',
version: 'Versão',
settings: 'Configurações',
clickToDial: 'Clique para discar',
autoCreateLog: 'Criar log de chamadas automaticamente',
autoCreateSMSLog: 'Criar log de SMS automaticamente',
autoLogCalls: 'Registrar chamadas aut... | };
// @key: @#@"region"@#@ @source: @#@"Region"@#@
// @key: @#@"calling"@#@ @source: @#@"Calling"@#@
// @key: @#@"logout"@#@ @source: @#@"Logout"@#@
// @key: @#@"version"@#@ @source: @#@"Version"@#@
// @key: @#@"settings"@#@ @source: @#@"Settings"@#@
// @key: @#@"clickToDial"@#@ @source: @#@"Click to Dial"@#@
// @key... | userGuide: 'Novidades', | random_line_split |
test_generation_xflow_to_es5.rs | extern crate env_logger;
extern crate ratel;
use ratel::parser;
|
mod common;
use crate::common::load_doc;
// partof: TST-artifact-generation-xflow
//
#[test]
fn test_load_basic_page_document() {
let _ = env_logger::try_init();
let xflow =
load_doc::<XFlowDocument>("resource/docs/xflow/flows/branch_boolean_condition.json");
let s_es5 = xflow_to_es5::output_es5(... | extern crate gears;
use gears::structure::xflow::*;
use gears::generation::xflow_to_es5; | random_line_split |
test_generation_xflow_to_es5.rs | extern crate env_logger;
extern crate ratel;
use ratel::parser;
extern crate gears;
use gears::structure::xflow::*;
use gears::generation::xflow_to_es5;
mod common;
use crate::common::load_doc;
// partof: TST-artifact-generation-xflow
//
#[test]
fn | () {
let _ = env_logger::try_init();
let xflow =
load_doc::<XFlowDocument>("resource/docs/xflow/flows/branch_boolean_condition.json");
let s_es5 = xflow_to_es5::output_es5(&xflow);
let s_es = xflow_to_es5::output(&xflow);
let _ = parser::parse(s_es5.to_string()).expect("Must compile");
... | test_load_basic_page_document | identifier_name |
test_generation_xflow_to_es5.rs | extern crate env_logger;
extern crate ratel;
use ratel::parser;
extern crate gears;
use gears::structure::xflow::*;
use gears::generation::xflow_to_es5;
mod common;
use crate::common::load_doc;
// partof: TST-artifact-generation-xflow
//
#[test]
fn test_load_basic_page_document() | {
let _ = env_logger::try_init();
let xflow =
load_doc::<XFlowDocument>("resource/docs/xflow/flows/branch_boolean_condition.json");
let s_es5 = xflow_to_es5::output_es5(&xflow);
let s_es = xflow_to_es5::output(&xflow);
let _ = parser::parse(s_es5.to_string()).expect("Must compile");
le... | identifier_body | |
util.py | """
This module contains several handy functions primarily meant for internal use.
"""
from datetime import date, datetime, timedelta
from time import mktime
import re
import sys
from types import MethodType
__all__ = ('asint', 'asbool', 'convert_to_datetime', 'timedelta_seconds',
'time_difference', 'datet... |
elif isinstance(input, date):
return datetime.fromordinal(input.toordinal())
elif isinstance(input, str):
m = _DATE_REGEX.match(input)
if not m:
raise ValueError('Invalid date string')
values = [(k, int(v or 0)) for k, v in m.groupdict().items()]
values = dic... | return input | conditional_block |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.