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 |
|---|---|---|---|---|
path-button.ts | import {PathKey} from "./path-key";
export class PathButton {
public key: PathKey;
public name: string;
public color: string;
public icon: string;
public url: string;
public type: string;
public active = true;
public tooltip: string;
public width: number;
public details: string[... |
public setPage(page: string) {
this.page = page;
}
public clone(): PathButton {
const copy = new PathButton();
copy.name = this.name;
copy.color = this.color;
copy.icon = this.icon;
copy.url = this.url;
copy.type = this.type;
copy.active = t... | {
const object = new Form();
object.form = form;
this.form = object;
} | identifier_body |
path-button.ts | import {PathKey} from "./path-key";
export class PathButton {
public key: PathKey;
public name: string;
public color: string;
public icon: string;
public url: string;
public type: string;
public active = true;
public tooltip: string;
public width: number;
public details: string[... | }
class Form {
public form: string;
} | random_line_split | |
patrol.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Patrols the edges of the map going clockwise. Just drives around in circles,
taking pains not to hit a wall.
When we see a wall, turn right a little.
"""
from courier import RoboLink
robot = RoboLink.connect(name="Patroller", scanner=2, engine=5)
# ... | robot.throttle = 100
if robot.scan_wall() is not None:
# If we see a wall, turn right ten degrees.
robot.turn(10) | conditional_block | |
patrol.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Patrols the edges of the map going clockwise. Just drives around in circles,
taking pains not to hit a wall.
When we see a wall, turn right a little.
"""
from courier import RoboLink
robot = RoboLink.connect(name="Patroller", scanner=2, engine=5)
# ... | if robot.scan_wall() is not None:
# If we see a wall, turn right ten degrees.
robot.turn(10) | # Full speed ahead! Doing this every tic just in case we hit a wall or stop
# or something. Setting the throttle doesn't take very long.
robot.throttle = 100
| random_line_split |
history_cost_chart.js | var data_cost = []; //Kosten
function createHistoryCostChart(){
var margin = {top: 60, right: 20, bottom: 120, left: 200},
width = 1160 - margin.right,
height = 500 - margin.top - margin.bottom;
var x,y,z,xAxis,yAxis,area_pos,area_neg,chart;
// chart Kosten
x = d3.scaleTime().r... |
function requestCostData(building, start_time, end_time, x, y, z, xAxis, yAxis, area_pos, area_neg, chart) {
$.getJSON(rest_url+"/rest/getdata/"+building+"/"+start_time+"/"+end_time, function(result) {
data_cost = [];
for (var i = 0; i < result.length; i++) {
var dataJSON = JSON.parse... | {
return a.x - b.x;
} | identifier_body |
history_cost_chart.js | var data_cost = []; //Kosten
function createHistoryCostChart(){
var margin = {top: 60, right: 20, bottom: 120, left: 200},
width = 1160 - margin.right,
height = 500 - margin.top - margin.bottom;
var x,y,z,xAxis,yAxis,area_pos,area_neg,chart;
// chart Kosten
x = d3.scaleTime().r... |
data_pos.forEach(function(currentValue, index) {
if (currentValue.y < 0) {
data_pos[index].y = 0;
}
});
data_neg.forEach(function(currentValue, index) {
if (currentValue.y > 0) {
data_neg[index].y = 0;
}
}... | {
data_pos[j] = {};
data_neg[j] = {};
for (var prop in data_cost[j]) {
if (!data_cost[j].hasOwnProperty(prop)) continue;
data_pos[j][prop] = data_cost[j][prop];
data_neg[j][prop] = data_cost[j][prop];
}
} | conditional_block |
history_cost_chart.js | var data_cost = []; //Kosten
function createHistoryCostChart(){
var margin = {top: 60, right: 20, bottom: 120, left: 200},
width = 1160 - margin.right,
height = 500 - margin.top - margin.bottom;
var x,y,z,xAxis,yAxis,area_pos,area_neg,chart;
// chart Kosten
x = d3.scaleTime().r... | (building, start_time, end_time, x, y, z, xAxis, yAxis, area_pos, area_neg, chart) {
$.getJSON(rest_url+"/rest/getdata/"+building+"/"+start_time+"/"+end_time, function(result) {
data_cost = [];
for (var i = 0; i < result.length; i++) {
var dataJSON = JSON.parse(result[i]);
v... | requestCostData | identifier_name |
history_cost_chart.js | var data_cost = []; //Kosten
function createHistoryCostChart(){
var margin = {top: 60, right: 20, bottom: 120, left: 200},
width = 1160 - margin.right,
height = 500 - margin.top - margin.bottom;
var x,y,z,xAxis,yAxis,area_pos,area_neg,chart;
// chart Kosten
x = d3.scaleTime().r... |
var mean_cost = d3.format(".2f")(d3.sum(data_cost, function (d) { return d.y; })/100);
var text_color = mean_cost >= 0 ? 'green' : 'red';
mean.append('text')
.style("text-anchor", "middle")
.text("Gesamtkosten:");
mean.append('text')
.attr('y', 30)
... | });
var mean = svg.append('g')
.attr('class', 'mean')
.attr('transform', 'translate(' + (1160/2 + 150) + ',450)'); | random_line_split |
ProcessingStage.ts | import * as continua from "../generated";
var log = require('winston');
log.level = 'info';
const serviceBrokerUrl = process.env.serviceBrokerUrl || "http://localhost:8090";
const resourcePath = process.env.resourcePath = "/continuum";
const stageId = "ProcessingStage";
const port = process.env.port || 8083;
// --... | // Allow tests to verify function ran.
this.thingWasProcessed = true;
log.error("thingWasProcessed:", this.thingWasProcessed);
}
}
// ----------------------------------------------------------------------------
// Start stage.
// ------------------------------------------------------------... | random_line_split | |
ProcessingStage.ts | import * as continua from "../generated";
var log = require('winston');
log.level = 'info';
const serviceBrokerUrl = process.env.serviceBrokerUrl || "http://localhost:8090";
const resourcePath = process.env.resourcePath = "/continuum";
const stageId = "ProcessingStage";
const port = process.env.port || 8083;
// --... | (v: string) {
log.info("ProcessingStage: processing data '" + v + "'");
// Allow tests to verify function ran.
this.thingWasProcessed = true;
log.error("thingWasProcessed:", this.thingWasProcessed);
}
}
// ---------------------------------------------------------------------------... | doThing | identifier_name |
ProcessingStage.ts | import * as continua from "../generated";
var log = require('winston');
log.level = 'info';
const serviceBrokerUrl = process.env.serviceBrokerUrl || "http://localhost:8090";
const resourcePath = process.env.resourcePath = "/continuum";
const stageId = "ProcessingStage";
const port = process.env.port || 8083;
// --... |
}
// ----------------------------------------------------------------------------
// Start stage.
// ----------------------------------------------------------------------------
export var processingStage;
if (require.main === module) {
processingStage = new ProcessingStage(continua.fabric, serviceBrokerUrl,
... | {
log.info("ProcessingStage: processing data '" + v + "'");
// Allow tests to verify function ran.
this.thingWasProcessed = true;
log.error("thingWasProcessed:", this.thingWasProcessed);
} | identifier_body |
ProcessingStage.ts | import * as continua from "../generated";
var log = require('winston');
log.level = 'info';
const serviceBrokerUrl = process.env.serviceBrokerUrl || "http://localhost:8090";
const resourcePath = process.env.resourcePath = "/continuum";
const stageId = "ProcessingStage";
const port = process.env.port || 8083;
// --... |
// export var ready = true;
| {
processingStage = new ProcessingStage(continua.fabric, serviceBrokerUrl,
resourcePath, stageId);
processingStage.listen(port);
} | conditional_block |
fastslim.py | #!/usr/bin/python
# This program processes an address trace generated by the Valgrind lackey tool
# to create a reduced trace according to the Fastslim-Demand algorithm
# described in "FastSlim: prefetch-safe trace reduction for I/O cache
# simulation" by Wei Jin, Xiaobai Sun, and Jeffrey S. Chase in ACM Transaction... | (self, other):
return self.pg == other.pg
def __repr__(self):
return self.reftype + " " + format(self.pg*4096,'x')
def __hash__(self):
return hash(self.pg)
ts = 0 # "timestamp" (entry number in original trace)
tracebuffer = set() # The set of entries in the buffer
toprint = [... | __eq__ | identifier_name |
fastslim.py | #!/usr/bin/python
# This program processes an address trace generated by the Valgrind lackey tool
# to create a reduced trace according to the Fastslim-Demand algorithm
# described in "FastSlim: prefetch-safe trace reduction for I/O cache
# simulation" by Wei Jin, Xiaobai Sun, and Jeffrey S. Chase in ACM Transaction... |
class TraceItem(object):
def __init__(self, reftype, pg, tstamp):
self.reftype = reftype
self.pg = pg
self.tstamp = tstamp
self.marked = False
def __eq__(self, other):
return self.pg == other.pg
def __repr__(self):
return self.reftype + " " + format(self.pg*4096,'x')
def... | import sys
import argparse
from operator import attrgetter | random_line_split |
fastslim.py | #!/usr/bin/python
# This program processes an address trace generated by the Valgrind lackey tool
# to create a reduced trace according to the Fastslim-Demand algorithm
# described in "FastSlim: prefetch-safe trace reduction for I/O cache
# simulation" by Wei Jin, Xiaobai Sun, and Jeffrey S. Chase in ACM Transaction... |
def __hash__(self):
return hash(self.pg)
ts = 0 # "timestamp" (entry number in original trace)
tracebuffer = set() # The set of entries in the buffer
toprint = [] # The list of entries waiting to be printed in order
# Emit in timestamp order may have to hold onto items until the trace b... | return self.reftype + " " + format(self.pg*4096,'x') | identifier_body |
fastslim.py | #!/usr/bin/python
# This program processes an address trace generated by the Valgrind lackey tool
# to create a reduced trace according to the Fastslim-Demand algorithm
# described in "FastSlim: prefetch-safe trace reduction for I/O cache
# simulation" by Wei Jin, Xiaobai Sun, and Jeffrey S. Chase in ACM Transaction... |
toprint.append(ti)
tracebuffer.add(ti)
ts = ts + 1
| emit_marked_in_ts_order() | conditional_block |
historybuffer.py | from __future__ import annotations
import os
import shutil
import time
import gc
import threading
from typing import Optional
from utils.utilfuncs import safeprint
def DummyAsyncFileWrite(fn, writestr, access='a'):
safeprint('Called HB file write before init {} {} {}'.format(fn, writestr, access))
AsyncFileWrite ... |
# noinspection PyBroadException
try:
os.rename('.HistoryBuffer', '.HistoryBuffer.1')
except:
pass
os.mkdir('.HistoryBuffer')
HBdir = dirnm + '/.HistoryBuffer/'
if WatchGC:
gc.callbacks.append(NoteGCs)
GCBuf = HistoryBuffer(50, 'GC')
def NoteGCs(phase, info):
if GCBuf is not None:
GCBuf.Entry('GC Cal... | os.rename('.HistoryBuffer.' + str(i), ".HistoryBuffer." + str(i + 1)) | conditional_block |
historybuffer.py | from __future__ import annotations
import os
import shutil
import time
import gc
import threading
from typing import Optional
from utils.utilfuncs import safeprint
def DummyAsyncFileWrite(fn, writestr, access='a'):
safeprint('Called HB file write before init {} {} {}'.format(fn, writestr, access))
AsyncFileWrite ... |
def DumpAll(idline, entrytime):
global bufdumpseq
if HBdir == '': # logs not yet set up
safeprint(time.strftime('%m-%d-%y %H:%M:%S') + ' Suppressing History Buffer Dump for {}'.format(idline))
return
fn = HBdir + str(bufdumpseq) + '-' + entrytime
try:
#topper.mvtops(str(bufdumpseq) + '-' + entrytime)
bu... | if GCBuf is not None:
GCBuf.Entry('GC Call' + phase + repr(info)) | identifier_body |
historybuffer.py | from __future__ import annotations
import os
import shutil
import time
import gc
import threading
from typing import Optional
from utils.utilfuncs import safeprint
def DummyAsyncFileWrite(fn, writestr, access='a'):
safeprint('Called HB file write before init {} {} {}'.format(fn, writestr, access))
AsyncFileWrite ... | if curfirst == {} or curtime == {}:
more = False
prevtime = 0
AsyncFileWrite(fn, '{} ({}): '.format(entrytime, now) + idline + '\n', 'w')
while more:
nextup = min(curtime, key=curtime.get)
if curtime[nextup] > prevtime:
prevtime = curtime[nextup]
else:
AsyncFileWrite(fn, 'seq error:' + str(... | if nm in curtime: del curtime[nm]
initial[nm] = '*' | random_line_split |
historybuffer.py | from __future__ import annotations
import os
import shutil
import time
import gc
import threading
from typing import Optional
from utils.utilfuncs import safeprint
def DummyAsyncFileWrite(fn, writestr, access='a'):
safeprint('Called HB file write before init {} {} {}'.format(fn, writestr, access))
AsyncFileWrite ... | (self, size, name):
self.buf = []
for i in range(size):
self.buf.append(EntryItem())
self.current = 0
self.size = size
self.name = name
Buffers[name] = self
def Entry(self, entry):
self.buf[self.current].entry = entry
self.buf[self.current].timeofentry = time.time()
self.buf[self.current].thread ... | __init__ | identifier_name |
organization_integration_repos.py | from __future__ import absolute_import
from django.http import Http404
from sentry.constants import ObjectStatus
from sentry.api.bases.organization import (
OrganizationEndpoint, OrganizationIntegrationsPermission
)
from sentry.integrations.exceptions import IntegrationError
from sentry.integrations.repositories ... | (self, request, organization, integration_id):
try:
integration = Integration.objects.get(id=integration_id, organizations=organization)
except Integration.DoesNotExist:
raise Http404
if integration.status == ObjectStatus.DISABLED:
context = {'repos': []}
... | get | identifier_name |
organization_integration_repos.py | from __future__ import absolute_import
from django.http import Http404
from sentry.constants import ObjectStatus
from sentry.api.bases.organization import (
OrganizationEndpoint, OrganizationIntegrationsPermission
)
from sentry.integrations.exceptions import IntegrationError
from sentry.integrations.repositories ... |
return self.respond({'detail': 'Repositories not supported'}, status=400)
| try:
repositories = install.get_repositories(request.GET.get('search'))
except IntegrationError as e:
return self.respond({'detail': e.message}, status=400)
context = {'repos': repositories, 'searchable': install.repo_search}
return self.respond(conte... | conditional_block |
organization_integration_repos.py | from __future__ import absolute_import
from django.http import Http404
from sentry.constants import ObjectStatus
from sentry.api.bases.organization import (
OrganizationEndpoint, OrganizationIntegrationsPermission
)
from sentry.integrations.exceptions import IntegrationError
from sentry.integrations.repositories ... |
if integration.status == ObjectStatus.DISABLED:
context = {'repos': []}
return self.respond(context)
install = integration.get_installation(organization.id)
if isinstance(install, RepositoryMixin):
try:
repositories = install.get_repositorie... | random_line_split | |
organization_integration_repos.py | from __future__ import absolute_import
from django.http import Http404
from sentry.constants import ObjectStatus
from sentry.api.bases.organization import (
OrganizationEndpoint, OrganizationIntegrationsPermission
)
from sentry.integrations.exceptions import IntegrationError
from sentry.integrations.repositories ... |
context = {'repos': repositories, 'searchable': install.repo_search}
return self.respond(context)
return self.respond({'detail': 'Repositories not supported'}, status=400)
| permission_classes = (OrganizationIntegrationsPermission, )
def get(self, request, organization, integration_id):
try:
integration = Integration.objects.get(id=integration_id, organizations=organization)
except Integration.DoesNotExist:
raise Http404
if integration... | identifier_body |
VoltmeterNode.ts | ETER_NUMBER_SAMPLE_POINTS = 10; // Number of points along the edge of the voltmeter tip to detect voltages
// unsigned measurements for the circles on the voltmeter body image, for where the probe wires connect
const PROBE_CONNECTION_POINT_DY = -18;
const PROBE_CONNECTION_POINT_DX = 8;
const SCALE = 0.5; // overall s... | extends Node {
private readonly circuitLayerNode: CircuitLayerNode | null;
readonly voltmeter: Voltmeter;
private readonly redProbeNode: Rectangle;
private readonly blackProbeNode: Rectangle;
private readonly dragHandler: DragListener | null;
static PROBE_ANGLE: number;
/**
* @param {Voltmeter} voltm... | VoltmeterNode | identifier_name |
VoltmeterNode.ts | outProperty, providedOptions.showResultsProperty, voltageString, tandem.createTandem( 'probeTextNode' ), {
centerX: voltmeterBody_png[ 0 ].width / 2,
centerY: voltmeterBody_png[ 0 ].height / 2
} );
const bodyNode = new Image( voltmeterBody_png, {
scale: SCALE,
cursor: 'pointer',
... | const updateVoltmeter = () => { | random_line_split | |
VoltmeterNode.ts | voltage: number | null ) =>
voltage === null ? MathSymbols.NO_VALUE : CCKCUtils.createVoltageReadout( voltage )
);
const probeTextNode = new ProbeTextNode(
voltageReadoutProperty, providedOptions.showResultsProperty, voltageString, tandem.createTandem( 'probeTextNode' ), {
centerX: voltmet... | {
return voltageConnection;
} | conditional_block | |
duration_pb2.py | # Generated by the protocol buffer compiler. DO NOT EDIT!
# source: google/protobuf/duration.proto
import sys
_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import ref... |
DESCRIPTOR = _descriptor.FileDescriptor(
name='google/protobuf/duration.proto',
package='google.protobuf',
syntax='proto3',
serialized_pb=_b('\n\x1egoogle/protobuf/duration.proto\x12\x0fgoogle.protobuf\"*\n\x08\x44uration\x12\x0f\n\x07seconds\x18\x01 \x01(\x03\x12\r\n\x05nanos\x18\x02 \x01(\x05\x42|\n\x13\x63... | # @@protoc_insertion_point(imports)
_sym_db = _symbol_database.Default()
| random_line_split |
ui.ts | import { IApiErrorResponse, ModelApi } from "@chiubaka/core";
import { LOCATION_CHANGE, LocationChangeAction } from "react-router-redux";
import { Action } from "redux";
import { Intent, Toaster } from "@blueprintjs/core";
import { ActionTypes, IFilterByEnergy, IFilterByTimeEstimate, IToggleTagFilter } from "../action... | activeTaskFilters: {
dueDate: false,
},
};
case ActionTypes.TOGGLE_DUE_DATE_FILTER:
return {
...state,
activeTaskFilters: {
...state.activeTaskFilters,
dueDate: !state.activeTaskFilters.dueDate,
},
};
case ActionTypes.TOGGLE... | };
case ActionTypes.CLEAR_FILTERS:
return {
...state, | random_line_split |
ui.ts | import { IApiErrorResponse, ModelApi } from "@chiubaka/core";
import { LOCATION_CHANGE, LocationChangeAction } from "react-router-redux";
import { Action } from "redux";
import { Intent, Toaster } from "@blueprintjs/core";
import { ActionTypes, IFilterByEnergy, IFilterByTimeEstimate, IToggleTagFilter } from "../action... | (pathname: string): Partial<ITask> {
switch (pathname) {
case Constants.INBOX_PATH:
return {
state: TaskState.Inbox,
};
case Constants.NEXT_PATH:
return {
state: TaskState.Next,
};
case Constants.WAITING_PATH:
return {
state: TaskState.Waiting,
}... | defaultTaskDataForPathname | identifier_name |
ui.ts | import { IApiErrorResponse, ModelApi } from "@chiubaka/core";
import { LOCATION_CHANGE, LocationChangeAction } from "react-router-redux";
import { Action } from "redux";
import { Intent, Toaster } from "@blueprintjs/core";
import { ActionTypes, IFilterByEnergy, IFilterByTimeEstimate, IToggleTagFilter } from "../action... | dueDate: false,
},
};
case ActionTypes.TOGGLE_DUE_DATE_FILTER:
return {
...state,
activeTaskFilters: {
...state.activeTaskFilters,
dueDate: !state.activeTaskFilters.dueDate,
},
};
case ActionTypes.TOGGLE_TAG_FILTER:
const tags... | {
switch (action.type) {
case ActionTypes.START_CREATING_TASK:
return {...state, creatingTask: true};
case ActionTypes.FINISH_CREATING_TASK:
return {...state, creatingTask: false};
case LOCATION_CHANGE:
const pathname = (action as LocationChangeAction).payload.pathname;
return {
... | identifier_body |
bug.js | var mongoose = require('mongoose');
var statuses = ['open', 'closed', 'as_expected'];
var priorities = ['major','regular','minor','enhancement'];
var Comment = new mongoose.Schema(
{
comment: String,
username: String,
name: String,
dca: {type: Date, default: Dat... |
now = new Date();
this.dua = now;
next();
});
module.exports = mongoose.model('Bug', Bug);
| {
this.id = (new Date()).getTime().toString();
} | conditional_block |
bug.js | var mongoose = require('mongoose');
var statuses = ['open', 'closed', 'as_expected'];
var priorities = ['major','regular','minor','enhancement'];
var Comment = new mongoose.Schema(
{
comment: String,
username: String,
name: String, |
var Bug = new mongoose.Schema(
{
id: {type: String},
name: {type: String, required: true},
desc: String,
status: {type: String, default: 'open'},
priority: {type: String, default: 'regular'},
username: { type: String, required: true},
... | dca: {type: Date, default: Date.now}
}
); | random_line_split |
LangModule.js | "fnCookieCallback": function (sNameFile, oData, sExpires, sPath) {
// append mod.php to cookiePath to avoid sending cookie-data to images etc. without reason
return sNameFile + "=" + encodeURIComponent($.fn.dataTableExt.oApi._fnJsonString(oData)) + "; expires=" + sExpires +"; path=" + sPath + "mod.php";
}
},
... | } else {
jQuery('.updateItem').off().addClass(className);
jQuery('.cancelItem').on('click', languageModule.cancelProcess).fadeIn(fadeSpeed);
jQuery('.selectionList input:checkbox').off();
jQuery('.selectionList input, .selectionList label').on('click', function(event) {
event.preventDefault();
}).p... | jQuery('.languageStateNone').on('click', function() {
languageModule.updateSingleTranslation(this);
}); | random_line_split |
LangModule.js | fnCookieCallback": function (sNameFile, oData, sExpires, sPath) {
// append mod.php to cookiePath to avoid sending cookie-data to images etc. without reason
return sNameFile + "=" + encodeURIComponent($.fn.dataTableExt.oApi._fnJsonString(oData)) + "; expires=" + sExpires +"; path=" + sPath + "mod.php";
}
},
... |
TYPO3.Flashmessage.display(
TYPO3.Severity.information,
TYPO3.l10n.localize('flashmessage.information'),
TYPO3.l10n.localize(label),
3
);
},
/**
* Display success flash message
*
* @param string label The label to show
* @return void
*/
displaySuccess: function(label) {
if (typeof label... | {
return;
} | conditional_block |
CloudClusterPrinterConfigurationMaterial.py | from typing import Optional
from UM.Logger import Logger
from cura.CuraApplication import CuraApplication
from cura.PrinterOutput.Models.MaterialOutputModel import MaterialOutputModel
from .BaseCloudModel import BaseCloudModel
## Class representing a cloud cluster printer configuration
# Spec: https://api-staging.... |
if material_group:
container = material_group.root_material_node.getContainer()
color = container.getMetaDataEntry("color_code")
brand = container.getMetaDataEntry("brand")
material_type = container.getMetaDataEntry("material")
name = container.getNa... | non_read_only_material_group_list = sorted(non_read_only_material_group_list, key = lambda x: x.name)
material_group = non_read_only_material_group_list[0] | conditional_block |
CloudClusterPrinterConfigurationMaterial.py | from typing import Optional
from UM.Logger import Logger
from cura.CuraApplication import CuraApplication
from cura.PrinterOutput.Models.MaterialOutputModel import MaterialOutputModel
from .BaseCloudModel import BaseCloudModel
## Class representing a cloud cluster printer configuration
# Spec: https://api-staging.... | (self) -> MaterialOutputModel:
material_manager = CuraApplication.getInstance().getMaterialManager()
material_group_list = material_manager.getMaterialGroupListByGUID(self.guid) or []
# Sort the material groups by "is_read_only = True" first, and then the name alphabetically.
read_only_... | createOutputModel | identifier_name |
CloudClusterPrinterConfigurationMaterial.py | from typing import Optional
from UM.Logger import Logger
from cura.CuraApplication import CuraApplication
from cura.PrinterOutput.Models.MaterialOutputModel import MaterialOutputModel
from .BaseCloudModel import BaseCloudModel
## Class representing a cloud cluster printer configuration
# Spec: https://api-staging.... | elif non_read_only_material_group_list:
non_read_only_material_group_list = sorted(non_read_only_material_group_list, key = lambda x: x.name)
material_group = non_read_only_material_group_list[0]
if material_group:
container = material_group.root_material_node.getCon... | def __init__(self, brand: Optional[str] = None, color: Optional[str] = None, guid: Optional[str] = None,
material: Optional[str] = None, **kwargs) -> None:
self.guid = guid
self.brand = brand
self.color = color
self.material = material
super().__init__(**kwargs)
... | identifier_body |
CloudClusterPrinterConfigurationMaterial.py | from typing import Optional
from UM.Logger import Logger
from cura.CuraApplication import CuraApplication
from cura.PrinterOutput.Models.MaterialOutputModel import MaterialOutputModel
from .BaseCloudModel import BaseCloudModel
## Class representing a cloud cluster printer configuration
# Spec: https://api-staging.... | name = container.getName()
else:
Logger.log("w", "Unable to find material with guid {guid}. Using data as provided by cluster"
.format(guid = self.guid))
color = self.color
brand = self.brand
material_type = self.material
... | container = material_group.root_material_node.getContainer()
color = container.getMetaDataEntry("color_code")
brand = container.getMetaDataEntry("brand")
material_type = container.getMetaDataEntry("material") | random_line_split |
linkify-element.js | 'use strict';
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol ? "symbol" : typeof obj; };
;(function (window, linkify) {
var linkifyElement = function ... |
// Build the link
var link = doc.createElement(tagName);
link.setAttribute('href', formattedHref);
link.setAttribute('class', linkClass);
if (target) {
link.setAttribute('target', target);
}
// Build up additional attributes
if (attributesHash) {
for (var attr in at... | events = options.resolve(opts.events, href, token.type); | random_line_split |
linkify-element.js | 'use strict';
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol ? "symbol" : typeof obj; };
;(function (window, linkify) {
var linkifyElement = function ... | link.setAttribute('href', formattedHref);
link.setAttribute('class', linkClass);
if (target) {
link.setAttribute('target', target);
}
// Build up additional attributes
if (attributesHash) {
for (var attr in attributesHash) {
link.setAttribute(attr, attributesHash[attr])... | {
var result = [];
for (var i = 0; i < tokens.length; i++) {
var token = tokens[i];
var validated = token.isLink && options.resolve(opts.validate, token.toString(), token.type);
if (token.isLink && validated) {
var href = token.toHref(opts.defaultProtocol),
formatted = options.resolve... | identifier_body |
linkify-element.js | 'use strict';
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol ? "symbol" : typeof obj; };
;(function (window, linkify) {
var linkifyElement = function ... |
}
/**
Given an array of MultiTokens, return an array of Nodes that are either
(a) Plain Text nodes (node type 3)
(b) Anchor tag nodes (usually, unless tag name is overridden in the options)
Takes the same options as linkifyElement and an optional doc element
(this should be passed in by linkifyEle... | {
parent.insertBefore(newChildren[i], lastNewChild);
lastNewChild = newChildren[i];
} | conditional_block |
linkify-element.js | 'use strict';
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol ? "symbol" : typeof obj; };
;(function (window, linkify) {
var linkifyElement = function ... | (tokens, opts, doc) {
var result = [];
for (var i = 0; i < tokens.length; i++) {
var token = tokens[i];
var validated = token.isLink && options.resolve(opts.validate, token.toString(), token.type);
if (token.isLink && validated) {
var href = token.toHref(opts.defaultProtocol),
formatt... | tokensToNodes | identifier_name |
swritercomp.py | # -*- tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
#
# This file is part of the LibreOffice project.
#
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
#
# ... | (XMain,unohelper.Base):
def __init__( self, ctx ):
self.ctx = ctx
# implementation for XMain.run( [in] sequence< any > )
def run( self,args ):
ctx = self.ctx
smgr = ctx.ServiceManager
desktop = smgr.createInstanceWithContext( "com.sun.star.frame.Desktop",ctx)
# open... | SWriterComp | identifier_name |
swritercomp.py | # -*- tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
#
# This file is part of the LibreOffice project.
#
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
#
# ... |
# the UNO component
# implementing the interface com.sun.star.lang.XMain
# unohelper.Base implements the XTypeProvider interface
class SWriterComp(XMain,unohelper.Base):
def __init__( self, ctx ):
self.ctx = ctx
# implementation for XMain.run( [in] sequence< any > )
def run( self,args ):
... | tableText = table.getCellByName( cellName )
cursor = tableText.createTextCursor()
cursor.setPropertyValue( "CharColor", color )
tableText.setString( text ) | identifier_body |
swritercomp.py | # -*- tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
#
# This file is part of the LibreOffice project.
#
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
#
# ... | # unohelper.Base implements the XTypeProvider interface
class SWriterComp(XMain,unohelper.Base):
def __init__( self, ctx ):
self.ctx = ctx
# implementation for XMain.run( [in] sequence< any > )
def run( self,args ):
ctx = self.ctx
smgr = ctx.ServiceManager
desktop = smgr.cre... | tableText.setString( text )
# the UNO component
# implementing the interface com.sun.star.lang.XMain | random_line_split |
lilylib.py | by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# LilyPond 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 Pub... |
return abs (retval)
system = subprocess_system
if sys.platform == 'mingw32':
## subprocess x-compile doesn't work.
system = ossystem_system
def strip_extension (f, ext):
(p, e) = os.path.splitext (f)
if e == ext:
e = ''
return p + e
def search_exe_path (name):
p = os.environ[... | print >>sys.stderr, 'command failed:', cmd
if retval < 0:
print >>sys.stderr, "Child was terminated by signal", -retval
elif retval > 0:
print >>sys.stderr, "Child returned", retval
if ignore_error:
print >>sys.stderr, "Error ignored"
else:
... | conditional_block |
lilylib.py | by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# LilyPond 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 Pub... |
def error (s):
print_logmessage ("ERROR", _ ("error: %s") % s);
def warning (s):
print_logmessage ("WARN", _ ("warning: %s") % s);
def basic_progress (s):
print_logmessage ("BASIC", s);
def progress (s, fullmessage = False, newline = True):
print_logmessage ("PROGRESS", s, fullmessage, newline);
d... | if (is_loglevel (level)):
if fullmessage:
stderr_write (program_name + ": " + s + '\n')
elif newline:
stderr_write (s + '\n')
else:
stderr_write (s) | identifier_body |
lilylib.py | by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# LilyPond 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 Pub... | ():
for (k,v) in os.environ.items ():
sys.stderr.write ("%s=\"%s\"\n" % (k, v))
class NonDentedHeadingFormatter (optparse.IndentedHelpFormatter):
def format_heading(self, heading):
if heading:
return heading[0].upper() + heading[1:] + ':\n'
return ''
def format_option_s... | print_environment | identifier_name |
lilylib.py | by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# LilyPond 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 Pub... |
show_progress= progress_p
name = command_name (cmd)
error_log_file = ''
if redirect_output:
progress (_ ("Processing %s.ly") % log_file)
else:
if be_verbose:
show_progress = 1
progress (_ ("Invoking `%s\'") % cmd)
else:
progress ( _("Runn... | random_line_split | |
test_api_base.py | from unittest.mock import patch
import pytest
import responses
from pythonanywhere.api.base import AuthenticationError, call_api, get_api_endpoint
class TestGetAPIEndpoint:
def test_defaults_to_pythonanywhere_dot_com_if_no_environment_variables(self):
assert get_api_endpoint() == "https://www.pythonany... |
def test_verify_is_true_if_env_not_set(self, api_token):
with patch("pythonanywhere.api.base.requests") as mock_requests:
call_api("url", "post", foo="bar")
args, kwargs = mock_requests.request.call_args
assert kwargs["verify"] is True
| monkeypatch.setenv("PYTHONANYWHERE_INSECURE_API", "true")
with patch("pythonanywhere.api.base.requests") as mock_requests:
call_api("url", "post", foo="bar")
args, kwargs = mock_requests.request.call_args
assert kwargs["verify"] is False | identifier_body |
test_api_base.py | from unittest.mock import patch
import pytest
import responses
from pythonanywhere.api.base import AuthenticationError, call_api, get_api_endpoint
class TestGetAPIEndpoint:
def test_defaults_to_pythonanywhere_dot_com_if_no_environment_variables(self):
assert get_api_endpoint() == "https://www.pythonany... | (self, api_token):
with patch("pythonanywhere.api.base.requests") as mock_requests:
call_api("url", "post", foo="bar")
args, kwargs = mock_requests.request.call_args
assert kwargs["verify"] is True
| test_verify_is_true_if_env_not_set | identifier_name |
test_api_base.py | from unittest.mock import patch
import pytest
import responses
from pythonanywhere.api.base import AuthenticationError, call_api, get_api_endpoint
class TestGetAPIEndpoint:
def test_defaults_to_pythonanywhere_dot_com_if_no_environment_variables(self):
assert get_api_endpoint() == "https://www.pythonany... |
class TestCallAPI:
def test_raises_on_401(self, api_token, api_responses):
url = "https://foo.com/"
api_responses.add(responses.POST, url, status=401, body="nope")
with pytest.raises(AuthenticationError) as e:
call_api(url, "post")
assert str(e.value) == "Authentication... | monkeypatch.setenv("PYTHONANYWHERE_DOMAIN", "foo.com")
assert get_api_endpoint() == "https://www.foo.com/api/v0/user/{username}/{flavor}/" | random_line_split |
trip_queries.py | import logging
import pymongo
import emission.net.usercache.abstract_usercache as enua
import emission.core.get_database as edb
import emission.core.wrapper.trip as ecwt
import emission.core.wrapper.section as ecws
import emission.core.wrapper.stop as ecwst
import emission.storage.decorations.timeline as esdt
def c... | curr_query.update({"start_loc" : {"$geoWithin" : {"$box": box}}})
curr_query.update({"end_loc" : {"$geoWithin" : {"$box": box}}})
trip_doc_cursor = edb.get_trip_new_db().find(curr_query).sort(time_query.timeType, pymongo.ASCENDING)
return [ecwt.Trip(doc) for doc in trip_doc_cursor]
def get_tri... | if box: | random_line_split |
trip_queries.py | import logging
import pymongo
import emission.net.usercache.abstract_usercache as enua
import emission.core.get_database as edb
import emission.core.wrapper.trip as ecwt
import emission.core.wrapper.section as ecws
import emission.core.wrapper.stop as ecwst
import emission.storage.decorations.timeline as esdt
def c... |
def get_trip(trip_id):
"""
Returns the trip for specified trip id.
:rtype : emission.core.wrapper.Trip
"""
return ecwt.Trip(edb.get_trip_new_db().find_one({"_id": trip_id}))
def get_time_query_for_trip(trip_id):
trip = get_trip(trip_id)
return enua.UserCache.TimeQuery("write_ts", trip.s... | curr_query = _get_ts_query(time_query)
if box:
curr_query.update({"start_loc" : {"$geoWithin" : {"$box": box}}})
curr_query.update({"end_loc" : {"$geoWithin" : {"$box": box}}})
trip_doc_cursor = edb.get_trip_new_db().find(curr_query).sort(time_query.timeType, pymongo.ASCENDING)
return [ecwt.... | identifier_body |
trip_queries.py | import logging
import pymongo
import emission.net.usercache.abstract_usercache as enua
import emission.core.get_database as edb
import emission.core.wrapper.trip as ecwt
import emission.core.wrapper.section as ecws
import emission.core.wrapper.stop as ecwst
import emission.storage.decorations.timeline as esdt
def c... |
return ret_query
def get_trips(user_id, time_query):
curr_query = _get_ts_query(time_query)
curr_query.update({"user_id": user_id})
trip_doc_cursor = edb.get_trip_new_db().find(curr_query).sort(time_query.timeType, pymongo.ASCENDING)
# TODO: Fix "TripIterator" and return it instead of this list
... | ret_query[time_key].update({"$gte": tq.startTs}) | conditional_block |
trip_queries.py | import logging
import pymongo
import emission.net.usercache.abstract_usercache as enua
import emission.core.get_database as edb
import emission.core.wrapper.trip as ecwt
import emission.core.wrapper.section as ecws
import emission.core.wrapper.stop as ecwst
import emission.storage.decorations.timeline as esdt
def c... | (trip_id):
trip = get_trip(trip_id)
return enua.UserCache.TimeQuery("write_ts", trip.start_ts, trip.end_ts)
def get_sections_for_trip(user_id, trip_id):
"""
Get the set of sections that are children of this trip.
"""
section_doc_cursor = edb.get_section_new_db().find({"user_id": user_id, "trip... | get_time_query_for_trip | identifier_name |
views.py | # views are handlers that respond to requests from web browsers or other clients
# Each view function maps to one or more request URLs
from flask import render_template, flash, redirect
from app import app
from .forms import Deck
#./run.py
@app.route('/submit', methods=('GET', 'POST'))
def submit():
form = Deck()
i... | 'title': 'GRE Words',
'cards': [
{
'word': 'combust',
'definition': 'to catch on fire'
},
{
'word': 'phaze',
'definition': 'to be affected'
}
]
},
{
'title': 'Food words',
'cards': [
{
'word': 'amuse bouche',
'definition': 'little serving'
},
{
'word': 'kimch... | random_line_split | |
views.py | # views are handlers that respond to requests from web browsers or other clients
# Each view function maps to one or more request URLs
from flask import render_template, flash, redirect
from app import app
from .forms import Deck
#./run.py
@app.route('/submit', methods=('GET', 'POST'))
def submit():
form = Deck()
i... | 'definition': 'little serving'
},
{
'word': 'kimchii',
'definition': 'femented cabbage'
}
]
}
]
return render_template('index.html',
title ='Home',
user=user,
posts=decks)
| user = {'nickname': 'Enrique Iglesias'} #fake user
decks = [
{
'title': 'GRE Words',
'cards': [
{
'word': 'combust',
'definition': 'to catch on fire'
},
{
'word': 'phaze',
'definition': 'to be affected'
}
]
},
{
'title': 'Food words',
'cards': [
{
'word': 'amuse bouche'... | identifier_body |
views.py | # views are handlers that respond to requests from web browsers or other clients
# Each view function maps to one or more request URLs
from flask import render_template, flash, redirect
from app import app
from .forms import Deck
#./run.py
@app.route('/submit', methods=('GET', 'POST'))
def submit():
form = Deck()
i... |
return render_template('submit.html',
title='Create Card',
form=form)
@app.route('/')
@app.route('/index')
def index():
# This is displayed on client's web browser
user = {'nickname': 'Enrique Iglesias'} #fake user
decks = [
{
'title': 'GRE Words',
'cards': [
{
'word': 'combust',
'd... | return redirect('/index') | conditional_block |
views.py | # views are handlers that respond to requests from web browsers or other clients
# Each view function maps to one or more request URLs
from flask import render_template, flash, redirect
from app import app
from .forms import Deck
#./run.py
@app.route('/submit', methods=('GET', 'POST'))
def submit():
form = Deck()
i... | ():
# This is displayed on client's web browser
user = {'nickname': 'Enrique Iglesias'} #fake user
decks = [
{
'title': 'GRE Words',
'cards': [
{
'word': 'combust',
'definition': 'to catch on fire'
},
{
'word': 'phaze',
'definition': 'to be affected'
}
]
},
{
'title': 'Food wo... | index | identifier_name |
elixir.js | module.exports = function(hljs) {
var ELIXIR_IDENT_RE = '[a-zA-Z_][a-zA-Z0-9_.]*(\\!|\\?)?';
var ELIXIR_METHOD_RE = '[a-zA-Z_]\\w*[!?=]?|[-+~]\\@|<<|>>|=~|===?|<=>|[<>]=?|\\*\\*|[-/+%^&*~`|]|\\[\\]=?';
var ELIXIR_KEYWORDS =
'and false then defined module in return redo retry end for true self when ' +
'ne... | contains: ELIXIR_DEFAULT_CONTAINS
};
}; | random_line_split | |
module.js | // Copyright 2015 Peter Beverloo. All rights reserved.
// Use of this source code is governed by the MIT license, a copy of which can
// be found in the LICENSE file.
// Base class for a module. Stores the environment and handles magic such as route annotations.
export class Module {
constructor(env) {
this.env_... | return (target, handler) => {
if (!target.hasOwnProperty('decoratedRoutes_'))
target.decoratedRoutes_ = [];
target.decoratedRoutes_.push({ method, route_path, handler });
};
} |
// Annotation that can be used on modules to indicate that the annotated method is the request
// handler for a |method| (GET, POST) request for |route_path|.
export function route(method, route_path) { | random_line_split |
module.js | // Copyright 2015 Peter Beverloo. All rights reserved.
// Use of this source code is governed by the MIT license, a copy of which can
// be found in the LICENSE file.
// Base class for a module. Stores the environment and handles magic such as route annotations.
export class Module {
| (env) {
this.env_ = env;
let decoratedRoutes = Object.getPrototypeOf(this).decoratedRoutes_;
if (!decoratedRoutes)
return;
decoratedRoutes.forEach(route => {
env.dispatcher.addRoute(route.method, route.route_path, ::this[route.handler]);
});
}
};
// Annotation that can be used on mo... | constructor | identifier_name |
_urllib2.py | # urllib2 work-alike interface
# ...from urllib2...
from urllib2 import \
URLError, \
HTTPError, \
BaseHandler, \
UnknownHandler, \
FTPHandler, \
CacheFTPHandler
# ...and from mechanize
from _auth import \
HTTPPasswordMgr, \
HTTPPasswordMgrWithDefaultRealm, \
AbstractBasicAu... | del httplib
from _opener import OpenerDirector, \
SeekableResponseOpener, \
build_opener, install_opener, urlopen
from _request import \
Request
from _seek import \
SeekableProcessor
from _upgrade import \
HTTPRequestUpgradeProcessor, \
ResponseUpgradeProcessor | RobotExclusionError
import httplib
if hasattr(httplib, 'HTTPS'):
from _http import HTTPSHandler | random_line_split |
_urllib2.py | # urllib2 work-alike interface
# ...from urllib2...
from urllib2 import \
URLError, \
HTTPError, \
BaseHandler, \
UnknownHandler, \
FTPHandler, \
CacheFTPHandler
# ...and from mechanize
from _auth import \
HTTPPasswordMgr, \
HTTPPasswordMgrWithDefaultRealm, \
AbstractBasicAu... |
del httplib
from _opener import OpenerDirector, \
SeekableResponseOpener, \
build_opener, install_opener, urlopen
from _request import \
Request
from _seek import \
SeekableProcessor
from _upgrade import \
HTTPRequestUpgradeProcessor, \
ResponseUpgradeProcessor
| from _http import HTTPSHandler | conditional_block |
makevcf.py | #!/usr/bin/env python
import sys,os
import textwrap
def | ():
print textwrap.dedent("""\
##fileformat=VCFv4.1
##phasing=none
##INDIVIDUAL=TRUTH
##SAMPLE=<ID=TRUTH,Individual="TRUTH",Description="bamsurgeon spike-in">
##INFO=<ID=CIPOS,Number=2,Type=Integer,Description="Confidence interval around POS for imprecise variants">
##INFO=<ID=IMPRECISE,Numb... | print_header | identifier_name |
makevcf.py | #!/usr/bin/env python
import sys,os
import textwrap
def print_header():
print textwrap.dedent("""\
##fileformat=VCFv4.1
##phasing=none
##INDIVIDUAL=TRUTH
##SAMPLE=<ID=TRUTH,Individual="TRUTH",Description="bamsurgeon spike-in">
##INFO=<ID=CIPOS,Number=2,Type=Integer,Description="Confidence inte... | ##INFO=<ID=DPR,Number=1,Type=Float,Description="Avg Depth in Region (+/- 1bp)">
##INFO=<ID=MATEID,Number=1,Type=String,Description="Breakend mate">
##ALT=<ID=INV,Description="Inversion">
##ALT=<ID=DUP,Description="Duplication">
##ALT=<ID=DEL,Description="Deletion">
##ALT=<ID=INS,Description="Ins... | ##INFO=<ID=IMPRECISE,Number=0,Type=Flag,Description="Imprecise structural variation">
##INFO=<ID=SVTYPE,Number=1,Type=String,Description="Type of structural variant">
##INFO=<ID=SVLEN,Number=.,Type=Integer,Description="Difference in length between REF and ALT alleles">
##INFO=<ID=SOMATIC,Number=0,Type=F... | random_line_split |
makevcf.py | #!/usr/bin/env python
import sys,os
import textwrap
def print_header():
|
if len(sys.argv) == 2:
print_header()
logdir_files = os.listdir(sys.argv[1])
for filename in logdir_files:
if filename.endswith('.log'):
with open(sys.argv[1] + '/' + filename, 'r') as infile:
for line in infile:
if line.startswith('snv'):
... | print textwrap.dedent("""\
##fileformat=VCFv4.1
##phasing=none
##INDIVIDUAL=TRUTH
##SAMPLE=<ID=TRUTH,Individual="TRUTH",Description="bamsurgeon spike-in">
##INFO=<ID=CIPOS,Number=2,Type=Integer,Description="Confidence interval around POS for imprecise variants">
##INFO=<ID=IMPRECISE,Number=0,Typ... | identifier_body |
makevcf.py | #!/usr/bin/env python
import sys,os
import textwrap
def print_header():
print textwrap.dedent("""\
##fileformat=VCFv4.1
##phasing=none
##INDIVIDUAL=TRUTH
##SAMPLE=<ID=TRUTH,Individual="TRUTH",Description="bamsurgeon spike-in">
##INFO=<ID=CIPOS,Number=2,Type=Integer,Description="Confidence inte... |
else:
print "usage:", sys.argv[0], "<log directory>"
| with open(sys.argv[1] + '/' + filename, 'r') as infile:
for line in infile:
if line.startswith('snv'):
#chrom, pos, mut = line.strip().split()
c = line.strip().split()
chrom = c[1].split(':')[0]
... | conditional_block |
sshsimpleserver.py | #!/usr/bin/env python
from twisted.cred import portal, checkers
from twisted.conch import error, avatar
from twisted.conch.checkers import SSHPublicKeyDatabase
from twisted.conch.ssh import factory, userauth, connection, keys, session
from twisted.internet import reactor, protocol, defer
from twisted.python import log
... |
portal = portal.Portal(ExampleRealm())
passwdDB = checkers.InMemoryUsernamePasswordDatabaseDontUse()
passwdDB.addUser('user', 'password')
portal.registerChecker(passwdDB)
portal.registerChecker(InMemoryPublicKeyChecker())
ExampleFactory.portal = portal
if __name__ == '__main__':
from twisted.conch.ssh imp... | t = mySSHServerTransport()
t.supportedPublicKeys = self.privateKeys.keys()
if not self.primes:
ske = t.supportedKeyExchanges[:]
ske.remove('diffie-hellman-group-exchange-sha1')
t.supportedKeyExchanges = ske
t.factory = self
return t | identifier_body |
sshsimpleserver.py | #!/usr/bin/env python
from twisted.cred import portal, checkers
from twisted.conch import error, avatar
from twisted.conch.checkers import SSHPublicKeyDatabase
from twisted.conch.ssh import factory, userauth, connection, keys, session
from twisted.internet import reactor, protocol, defer
from twisted.python import log
... |
t.factory = self
return t
portal = portal.Portal(ExampleRealm())
passwdDB = checkers.InMemoryUsernamePasswordDatabaseDontUse()
passwdDB.addUser('user', 'password')
portal.registerChecker(passwdDB)
portal.registerChecker(InMemoryPublicKeyChecker())
ExampleFactory.portal = portal
if __name__ == '... | ske = t.supportedKeyExchanges[:]
ske.remove('diffie-hellman-group-exchange-sha1')
t.supportedKeyExchanges = ske | conditional_block |
sshsimpleserver.py | #!/usr/bin/env python
from twisted.cred import portal, checkers
from twisted.conch import error, avatar
from twisted.conch.checkers import SSHPublicKeyDatabase
from twisted.conch.ssh import factory, userauth, connection, keys, session
from twisted.internet import reactor, protocol, defer
from twisted.python import log
... | (protocol.Protocol):
"""this is our example protocol that we will run over SSH
"""
def dataReceived(self, data):
if data == '\r':
data = '\r\n'
elif data == '\x03': #^C
self.transport.loseConnection()
return
self.transport.write(data)
publicKey = ... | EchoProtocol | identifier_name |
sshsimpleserver.py | #!/usr/bin/env python
from twisted.cred import portal, checkers
from twisted.conch import error, avatar
from twisted.conch.checkers import SSHPublicKeyDatabase
from twisted.conch.ssh import factory, userauth, connection, keys, session
from twisted.internet import reactor, protocol, defer
from twisted.python import log
... | protocol = factory.buildProtocol('a');
stdio.StandardIO(protocol);
reactor.run()
# reactor.listenTCP(5022, ExampleFactory())
# from twisted.internet import stdio;
# factory = ExampleFactory();
# stdio.StandardIO(factory);
# runWithProtocol(ExampleFactory().buildProtocol());
# factor... | from twisted.conch.ssh import transport;
from twisted.internet import stdio;
factory = ExampleFactory();
setattr(factory, 'primes', ''); | random_line_split |
profile_analysis.py |
if not(re.match('((.|\n)*[a-zA-Z]+(.|\n)*)+', s)):
continue
except IOError:
pass
finally:
fh.close()
... | print "Exiting Index...\n\n"
break | conditional_block | |
profile_analysis.py | (L):
return max(groupby(sorted(L)), key=lambda(x, v):(len(list(v)),-L.index(x)))[0]
#folder with txt, pdf & html files - must be located in the same dir with the script
path = os.getcwd()
tkn_path = path + "\\tokenize\\"
tag_path = path + "\\tagged\\"
types = ['*.txt', '*.html', '*.htm']
while(1):
x = raw_input... | most_common_func | identifier_name | |
profile_analysis.py |
#folder with txt, pdf & html files - must be located in the same dir with the script
path = os.getcwd()
tkn_path = path + "\\tokenize\\"
tag_path = path + "\\tagged\\"
types = ['*.txt', '*.html', '*.htm']
while(1):
x = raw_input("Press:\n1. Run profile analysis \
\n2. Enter index mode\n3. Exit Program\nY... | return max(groupby(sorted(L)), key=lambda(x, v):(len(list(v)),-L.index(x)))[0] | identifier_body | |
profile_analysis.py | _input("Invalid input!!! Press:\n1. Run profile analysis \
\n2. Enter index mode\n3. Exit Program\nYour option: ")
#----------------------------------- READ BOOKMARK FILE -------------------------------------#
if(x is '1'):
if not(os.path.exists(path+"\profile")):
print "\nThere is no pro... | with open(tkn_path+tkn,'w') as fh:
for each_token in tokens_list:
if not(re.search('&',each_token)) and not(each_token.isspace()):
fh.write(each_token.encode('utf-8'))
fh.write("\n") ... |
tkn = "tokenized_text_%04d.txt"%i | random_line_split |
createColumnMenuItems.ts | /*
* Copyright 2017 TWO SIGMA OPEN SOURCE, LLC
*
* 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 appl... | else {
column.move(frozenColumnsCount);
}
}
},
{
title: 'Reset formatting',
separator: true,
action: (column) => column.resetState()
}
];
}
| {
column.move(visibleColumnsLength - 1);
} | conditional_block |
createColumnMenuItems.ts | /*
* Copyright 2017 TWO SIGMA OPEN SOURCE, LLC
*
* 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 appl... | (column: DataGridColumn): MenuItem[] {
return [
{
title: 'Hide column',
action: (column) => column.hide()
},
{
title: 'Filter by Expression',
icon: 'fa fa-filter',
tooltip: 'filter with an expression with a variable defined for each column and $ means the current column. eg ... | createColumnMenuItems | identifier_name |
createColumnMenuItems.ts | /*
* Copyright 2017 TWO SIGMA OPEN SOURCE, LLC
*
* 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 appl... | action: (column) => column.resetState()
}
];
} | {
title: 'Reset formatting',
separator: true, | random_line_split |
createColumnMenuItems.ts | /*
* Copyright 2017 TWO SIGMA OPEN SOURCE, LLC
*
* 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 appl... | action: undefined,
items: createFormatMenuItems(column)
},
{
title: 'Sort Ascending',
separator: true,
isChecked: (column) => column.getSortOrder() === SORT_ORDER.ASC,
action: (column) => column.sort(SORT_ORDER.ASC)
},
{
title: 'Sort Descending',
isChecked... | {
return [
{
title: 'Hide column',
action: (column) => column.hide()
},
{
title: 'Filter by Expression',
icon: 'fa fa-filter',
tooltip: 'filter with an expression with a variable defined for each column and $ means the current column. eg "$ > 5"',
action: (column) => c... | identifier_body |
po_file.py | # coding=utf-8
from __future__ import absolute_import
from __future__ import print_function
from __future__ import unicode_literals
import re
from io import StringIO
from .strings import escape
EMBEDDED_NEWLINE_MATCHER = re.compile(r'[^\n]\n+[^\n]')
class PoFile(object):
def __init__(self):
self.header... | needs_blank_line = True
nplurals = self.get_nplurals()
for entry in sorted(self.entries.values(), key=get_entry_sort_key):
if needs_blank_line:
print('', file=fp)
needs_blank_line = entry.dump(
fp, nplurals, include_locations=include_lo... | print(r'"{}: {}\n"'.format(field, value), file=fp) | random_line_split |
po_file.py | # coding=utf-8
from __future__ import absolute_import
from __future__ import print_function
from __future__ import unicode_literals
import re
from io import StringIO
from .strings import escape
EMBEDDED_NEWLINE_MATCHER = re.compile(r'[^\n]\n+[^\n]')
class PoFile(object):
def __init__(self):
self.header... |
nplurals = self.get_nplurals()
for entry in sorted(self.entries.values(), key=get_entry_sort_key):
if needs_blank_line:
print('', file=fp)
needs_blank_line = entry.dump(
fp, nplurals, include_locations=include_locations, prune_obsolete=prune_obsol... | print('msgid ""', file=fp)
print('msgstr ""', file=fp)
for field, value in self.header_fields:
print(r'"{}: {}\n"'.format(field, value), file=fp)
needs_blank_line = True | conditional_block |
po_file.py | # coding=utf-8
from __future__ import absolute_import
from __future__ import print_function
from __future__ import unicode_literals
import re
from io import StringIO
from .strings import escape
EMBEDDED_NEWLINE_MATCHER = re.compile(r'[^\n]\n+[^\n]')
class PoFile(object):
def __init__(self):
self.header... |
def dump(self, fp, include_locations=True, prune_obsoletes=False):
needs_blank_line = False
if len(self.header_fields):
print('msgid ""', file=fp)
print('msgstr ""', file=fp)
for field, value in self.header_fields:
print(r'"{}: {}\n"'.format(fiel... | msgid = get_msgid(message, context)
if msgid in self.entries:
entry = self.entries[msgid]
# Allow merging a non-plural entry with a plural entry
# If more than one plural entry only keep the first
if entry.plural is None:
entry.plural = plural
... | identifier_body |
po_file.py | # coding=utf-8
from __future__ import absolute_import
from __future__ import print_function
from __future__ import unicode_literals
import re
from io import StringIO
from .strings import escape
EMBEDDED_NEWLINE_MATCHER = re.compile(r'[^\n]\n+[^\n]')
class PoFile(object):
def __init__(self):
self.header... | (self, fp, include_locations=True, prune_obsoletes=False):
needs_blank_line = False
if len(self.header_fields):
print('msgid ""', file=fp)
print('msgstr ""', file=fp)
for field, value in self.header_fields:
print(r'"{}: {}\n"'.format(field, value), fil... | dump | identifier_name |
index.js | import React, { PropTypes } from 'react';
import colorByCharacter from '~/constants/colorByCharacter';
function | (props) {
const { word, isClues } = props;
let cardClasses = `flex flex--jc--c align-items--center card--container `;
if (isClues) {
cardClasses += ' flip ';
cardClasses += word.isRevealed ? ' opacity--4-10 ' : ' cursor--pointer ';
} else {
cardClasses += word.isRevealed && ' flip ';
}
functio... | WordCard | identifier_name |
index.js | import React, { PropTypes } from 'react';
import colorByCharacter from '~/constants/colorByCharacter';
function WordCard(props) {
const { word, isClues } = props;
let cardClasses = `flex flex--jc--c align-items--center card--container `;
if (isClues) {
cardClasses += ' flip ';
cardClasses += word.isRev... |
function toggleIsRevealed(word) {
props.toggleIsRevealed && props.toggleIsRevealed(word);
}
return (
<div
className={`grid__item col-1-5 height--80 mv-`}
>
<div
onClick={() => word.isRevealed ? null : toggleIsRevealed(word)}
className={cardClasses}
>
<div c... | {
cardClasses += word.isRevealed && ' flip ';
} | conditional_block |
index.js | import React, { PropTypes } from 'react';
import colorByCharacter from '~/constants/colorByCharacter';
function WordCard(props) | onClick={() => word.isRevealed ? null : toggleIsRevealed(word)}
className={cardClasses}
>
<div className="grid grid--full col-1-1 card">
<div className="grid__item col-1-1 flex align-items--center flex--jc--c text--center font--lg front">
{word.text.toLowerCase()}
... | {
const { word, isClues } = props;
let cardClasses = `flex flex--jc--c align-items--center card--container `;
if (isClues) {
cardClasses += ' flip ';
cardClasses += word.isRevealed ? ' opacity--4-10 ' : ' cursor--pointer ';
} else {
cardClasses += word.isRevealed && ' flip ';
}
function toggle... | identifier_body |
index.js | import React, { PropTypes } from 'react';
import colorByCharacter from '~/constants/colorByCharacter';
function WordCard(props) {
const { word, isClues } = props;
let cardClasses = `flex flex--jc--c align-items--center card--container `;
if (isClues) {
cardClasses += ' flip ';
cardClasses += word.isRev... | export default WordCard; | random_line_split | |
default.py | from src.settings import Colors
def league_color(league: str) -> Colors:
if league in [
]:
return Colors.GREEN
if league in [
'1 CFL (Montenegro)',
'A Lyga (Lithuania)', | 'J-League (Japan)',
'J-League 2 (Japan)',
'K-League (South Korea)',
'Landspokal (Denmark)',
'League Cup (Scotland)',
'Meistriliiga (Estonia)',
'OFB Cup (Austria)',
'Pohar CMFS (Czech Republic)',
'Premier League (Wales)',
'Primera Division (... | 'Bikar (Iceland)',
'Coupe de la Ligue (France)',
'EURO Qualifiers (Europe)',
'FA Cup (England)', | random_line_split |
default.py | from src.settings import Colors
def league_color(league: str) -> Colors:
| 'Primera Division (Chile)',
'Proximus League (Belgium)',
'Serie A (Italy)',
'S-League (Singapore)',
'Slovensky Pohar (Slovakia)',
'Svenska Cupen (Sweden)',
'Swiss Cup (Switzerland)',
'Virsliga (Latvia)',
'Vyscha Liga (Ukraine)',
'Úrvalsdeil... | if league in [
]:
return Colors.GREEN
if league in [
'1 CFL (Montenegro)',
'A Lyga (Lithuania)',
'Bikar (Iceland)',
'Coupe de la Ligue (France)',
'EURO Qualifiers (Europe)',
'FA Cup (England)',
'J-League (Japan)',
'J-League 2 (Japan)',
... | identifier_body |
default.py | from src.settings import Colors
def | (league: str) -> Colors:
if league in [
]:
return Colors.GREEN
if league in [
'1 CFL (Montenegro)',
'A Lyga (Lithuania)',
'Bikar (Iceland)',
'Coupe de la Ligue (France)',
'EURO Qualifiers (Europe)',
'FA Cup (England)',
'J-League (Japan)',
... | league_color | identifier_name |
default.py | from src.settings import Colors
def league_color(league: str) -> Colors:
if league in [
]:
return Colors.GREEN
if league in [
'1 CFL (Montenegro)',
'A Lyga (Lithuania)',
'Bikar (Iceland)',
'Coupe de la Ligue (France)',
'EURO Qualifiers (Europe)',
'F... | if league in [
]:
return Colors.YELLOW
return Colors.EMPTY
| eturn Colors.RED
| conditional_block |
fixed.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>
//! A container which allows you to position widgets at fixed coordinates
use libc::c_int;
... | // FIXME: search a new name
pub fn move_<T: ::WidgetTrait>(&self,
widget: &T,
x: i32,
y: i32) -> () {
unsafe {
ffi::gtk_fixed_move(GTK_FIXED(self.pointer), widget.unwrap_widget(), x as c_int, y as c_int... | unsafe {
ffi::gtk_fixed_put(GTK_FIXED(self.pointer), widget.unwrap_widget(), x as c_int, y as c_int);
}
}
| identifier_body |
fixed.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>
//! A container which allows you to position widgets at fixed coordinates
use libc::c_int;
... | : ::WidgetTrait>(&self,
widget: &T,
x: i32,
y: i32) -> () {
unsafe {
ffi::gtk_fixed_move(GTK_FIXED(self.pointer), widget.unwrap_widget(), x as c_int, y as c_int);
}
}
}
impl_drop!(Fixed);
impl_Trai... | ve_<T | identifier_name |
fixed.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>
//! A container which allows you to position widgets at fixed coordinates
use libc::c_int;
... | ffi::gtk_fixed_move(GTK_FIXED(self.pointer), widget.unwrap_widget(), x as c_int, y as c_int);
}
}
}
impl_drop!(Fixed);
impl_TraitWidget!(Fixed);
impl ::ContainerTrait for Fixed {} | y: i32) -> () {
unsafe { | random_line_split |
observe.js | /**
* Librerías Javascript
*
* @package Roraima
* @author $Author$ <desarrollo@cidesa.com.ve>
* @version SVN: $Id$
*
* @copyright Copyright 2007, Cide S.A.
* @license http://opensource.org/licenses/gpl-2.0.php GPLv2
*/
//FUNCIONES JAVASCRIPT
var form = null;
var arreglo = null;
var inicio... | var i = 0;
arreglo.each(function(e,index){
if(!e.disabled && !e.readOnly)
{
e.tabindex = index;
i++;
}
});
if(arreglo & inicio) {
try{arreglo.first().focus();}catch(e){}
inicio=false;
}
}
}
////////////////////////////... | if(form) arreglo = $$('input[type=text]', 'select','textarea'); // -> only text inputs
| random_line_split |
observe.js | /**
* Librerías Javascript
*
* @package Roraima
* @author $Author$ <desarrollo@cidesa.com.ve>
* @version SVN: $Id$
*
* @copyright Copyright 2007, Cide S.A.
* @license http://opensource.org/licenses/gpl-2.0.php GPLv2
*/
//FUNCIONES JAVASCRIPT
var form = null;
var arreglo = null;
var inicio... | }
}
}
///////////////////////////////////////////////////
// Observar si se cargado la p�gina por completo //
///////////////////////////////////////////////////
Event.observe(window, 'load',
function() {
ActualizarInputs();
}
);
///////////////////////////////////////... |
if(!noActualizarInputs){
form = $('sf_admin_edit_form');
arreglo = Array();
if(form) arreglo = $$('input[type=text]', 'select','textarea'); // -> only text inputs
var i = 0;
arreglo.each(function(e,index){
if(!e.disabled && !e.readOnly)
{
e.tabindex = index... | identifier_body |
observe.js | /**
* Librerías Javascript
*
* @package Roraima
* @author $Author$ <desarrollo@cidesa.com.ve>
* @version SVN: $Id$
*
* @copyright Copyright 2007, Cide S.A.
* @license http://opensource.org/licenses/gpl-2.0.php GPLv2
*/
//FUNCIONES JAVASCRIPT
var form = null;
var arreglo = null;
var inicio... | e {
i++;
}
}catch(e){
if(arreglo[indice])
if(!arreglo[indice].disabled && !arreglo[indice].readOnly)
{
arreglo[indice].blur();
arreglo[indice].focus();
//try{arreglo[indice].select();}catch(e){}
... | arreglo[indice+i].focus();
try{arreglo[indice+i].select();}catch(e){}
salir=true;
}els | conditional_block |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.