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 |
|---|---|---|---|---|
garden_real.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
import pythymio
import random
from gardenworld import *
init('info2_1')
with pythymio.thymio(["acc"],[]) as Thym:
state = dict([])
state["time"] = 0
state["delay"] = 10
def dispatch(evtid, evt_name, evt_args): | if 7 < evt_args[1] < 14:
if evt_args[0] > 10:
state["delay"] = 20
tg()
elif evt_args[0] < -10:
state["delay"] = 20
td()
elif evt_args[1] > 20 and abs(e... | # https://www.thymio.org/en:thymioapi prox freq is 16Hz
if evt_name == "fwd.acc": # every 0.0625 sec
state["time"] += 0.0625
state["delay"] -= 1
if state["delay"] < 0: | random_line_split |
SelectionManager.js |
//BUG: unselect needs to be triggered when events are dragged+dropped
function SelectionManager() {
var t = this;
// exports
t.select = select;
t.unselect = unselect;
t.reportSelection = reportSelection;
t.daySelectionMousedown = daySelectionMousedown;
// imports
var opt = t.opt;
var trigger = t.trig... |
});
}
}
}
| {
if (+dates[0] == +dates[1]) {
reportDayClick(dates[0], true, ev);
}
reportSelection(dates[0], dates[1], true, ev);
} | conditional_block |
SelectionManager.js |
//BUG: unselect needs to be triggered when events are dragged+dropped
function SelectionManager() | var selected = false;
// unselectAuto
if (opt('selectable') && opt('unselectAuto')) {
$(document).mousedown(function(ev) {
var ignore = opt('unselectCancel');
if (ignore) {
if ($(ev.target).parents(ignore).length) { // could be optimized to stop after first match
return;
}
}
unselect(ev... | {
var t = this;
// exports
t.select = select;
t.unselect = unselect;
t.reportSelection = reportSelection;
t.daySelectionMousedown = daySelectionMousedown;
// imports
var opt = t.opt;
var trigger = t.trigger;
var defaultSelectionEnd = t.defaultSelectionEnd;
var renderSelection = t.renderSelection;
va... | identifier_body |
SelectionManager.js | //BUG: unselect needs to be triggered when events are dragged+dropped
function SelectionManager() {
var t = this;
// exports
t.select = select;
t.unselect = unselect;
t.reportSelection = reportSelection;
t.daySelectionMousedown = daySelectionMousedown;
// imports
var opt = t.opt;
var trigger = t.trigg... |
// locals
var selected = false;
// unselectAuto
if (opt('selectable') && opt('unselectAuto')) {
$(document).mousedown(function(ev) {
var ignore = opt('unselectCancel');
if (ignore) {
if ($(ev.target).parents(ignore).length) { // could be optimized to stop after first match
return;
}
}
... | random_line_split | |
SelectionManager.js |
//BUG: unselect needs to be triggered when events are dragged+dropped
function SelectionManager() {
var t = this;
// exports
t.select = select;
t.unselect = unselect;
t.reportSelection = reportSelection;
t.daySelectionMousedown = daySelectionMousedown;
// imports
var opt = t.opt;
var trigger = t.trig... | (ev) {
if (selected) {
selected = false;
clearSelection();
trigger('unselect', null, ev);
}
}
function reportSelection(startDate, endDate, allDay, ev, resource) {
selected = true;
trigger('select', null, startDate, endDate, allDay, ev, resource);
}
function daySelectionMousedown(ev) { // no... | unselect | identifier_name |
__init__.py | #!/usr/bin/python3
# -*- coding: latin-1 -*-
import os
import sys
import psycopg2
import json
from bson import json_util
from pymongo import MongoClient
from flask import Flask, request, session, g, redirect, url_for, abort, \
render_template, flash
def create_app():
app = Flask(__name__)
return app
app... |
if __name__ == "__main__":
app.run()
| return render_template('example.html') | identifier_body |
__init__.py | #!/usr/bin/python3
# -*- coding: latin-1 -*-
import os
import sys
import psycopg2
import json
from bson import json_util
from pymongo import MongoClient
from flask import Flask, request, session, g, redirect, url_for, abort, \
render_template, flash
def create_app():
app = Flask(__name__)
return app
app... | ():
if request.method == "GET":
with open(QUERIES_FILENAME, 'r', encoding='utf-8') as queries_file:
json_file = json.load(queries_file)
pairs = [(x["name"],
x["database"],
x["description"],
x["query"]) for x in json_fi... | home | identifier_name |
__init__.py | #!/usr/bin/python3
# -*- coding: latin-1 -*-
import os
import sys
import psycopg2
import json
from bson import json_util
from pymongo import MongoClient
from flask import Flask, request, session, g, redirect, url_for, abort, \
render_template, flash
def create_app():
app = Flask(__name__)
return app
app... |
ano = str(ano)
param = "{}-{}-{}".format(ano, mes, dia)
pairs.append((x["name"],
x["database"],
x["description"],
param.join(x["query"].split("PARAMETER1"))))
... | dia = "0" + dia | conditional_block |
__init__.py | #!/usr/bin/python3
# -*- coding: latin-1 -*-
import os
import sys
import psycopg2
import json
from bson import json_util
from pymongo import MongoClient
from flask import Flask, request, session, g, redirect, url_for, abort, \
render_template, flash
def create_app():
app = Flask(__name__)
return app
app... | return "ok"
@app.route("/postgres")
def postgres():
query = request.args.get("query")
cursor = postgresdb.cursor()
cursor.execute(query)
results = [[a for a in result] for result in cursor]
print(results)
return render_template('postgres.html', results=results)
@app.route("/example")... | return render_template('mongo.html', results=results)
else: | random_line_split |
ptr_as_ptr.rs | // run-rustfix
#![warn(clippy::ptr_as_ptr)]
#![feature(custom_inner_attributes)]
fn main() {
let ptr: *const u32 = &42_u32;
let mut_ptr: *mut u32 = &mut 42_u32;
let _ = ptr as *const i32;
let _ = mut_ptr as *mut i32;
// Make sure the lint can handle the difference in their operator precedences.
... | () {
#![clippy::msrv = "1.38"]
let ptr: *const u32 = &42_u32;
let mut_ptr: *mut u32 = &mut 42_u32;
let _ = ptr as *const i32;
let _ = mut_ptr as *mut i32;
}
| _msrv_1_38 | identifier_name |
ptr_as_ptr.rs | // run-rustfix
#![warn(clippy::ptr_as_ptr)]
#![feature(custom_inner_attributes)]
fn main() {
let ptr: *const u32 = &42_u32;
let mut_ptr: *mut u32 = &mut 42_u32;
let _ = ptr as *const i32;
let _ = mut_ptr as *mut i32;
// Make sure the lint can handle the difference in their operator precedences.
... | let _ = ptr as *const i32;
let _ = mut_ptr as *mut i32;
} | random_line_split | |
ptr_as_ptr.rs | // run-rustfix
#![warn(clippy::ptr_as_ptr)]
#![feature(custom_inner_attributes)]
fn main() {
let ptr: *const u32 = &42_u32;
let mut_ptr: *mut u32 = &mut 42_u32;
let _ = ptr as *const i32;
let _ = mut_ptr as *mut i32;
// Make sure the lint can handle the difference in their operator precedences.
... |
fn _msrv_1_38() {
#![clippy::msrv = "1.38"]
let ptr: *const u32 = &42_u32;
let mut_ptr: *mut u32 = &mut 42_u32;
let _ = ptr as *const i32;
let _ = mut_ptr as *mut i32;
}
| {
#![clippy::msrv = "1.37"]
let ptr: *const u32 = &42_u32;
let mut_ptr: *mut u32 = &mut 42_u32;
// `pointer::cast` was stabilized in 1.38. Do not lint this
let _ = ptr as *const i32;
let _ = mut_ptr as *mut i32;
} | identifier_body |
list.js | import Ember from 'ember';
const { Controller } = Ember;
export default Controller.extend({
columns: [
{
propertyName : 'name',
template : 'components/ui-table/cell/cell-event',
title : 'Name'
},
{
propertyName : 'starts-at',
template : 'components/ui-table/c... | (id, name) {
this.set('isEventDeleteModalOpen', true);
this.set('confirmName', '');
this.set('eventName', name);
this.set('eventId', id);
},
deleteEvent() {
this.set('isLoading', true);
this.store.findRecord('event', this.get('eventId'), { backgroundReload: false }).then(func... | openDeleteEventModal | identifier_name |
list.js | import Ember from 'ember';
const { Controller } = Ember;
export default Controller.extend({
columns: [
{
propertyName : 'name',
template : 'components/ui-table/cell/cell-event',
title : 'Name'
},
{
propertyName : 'starts-at',
template : 'components/ui-table/c... | title : 'Tickets',
disableSorting : true,
disableFiltering : true
},
{
propertyName : 'url',
template : 'components/ui-table/cell/cell-link',
title : 'Public URL',
disableSorting : true,
disableFiltering : true
},
{
... | },
{
propertyName : 'tickets',
template : 'components/ui-table/cell/cell-tickets', | random_line_split |
list.js | import Ember from 'ember';
const { Controller } = Ember;
export default Controller.extend({
columns: [
{
propertyName : 'name',
template : 'components/ui-table/cell/cell-event',
title : 'Name'
},
{
propertyName : 'starts-at',
template : 'components/ui-table/c... |
}
});
| {
this.set('isLoading', true);
this.store.findRecord('event', this.get('eventId'), { backgroundReload: false }).then(function(event) {
event.destroyRecord();
})
.then(() => {
this.notify.success(this.l10n.t('Event has been deleted successfully.'));
})
.catch((... | identifier_body |
gdt.rs | use core::mem::size_of;
use core::ptr;
use core::sync::atomic::{AtomicU8, Ordering};
use x86_64::structures::gdt::SegmentSelector;
use x86_64::structures::tss::TaskStateSegment;
use x86_64::{PrivilegeLevel, VirtAddr};
pub use x86_64::structures::gdt::Descriptor;
use crate::memory::constants::GDT_ADDR;
pub const DOUB... | ,
};
}
SegmentSelector::new(index as u16, PrivilegeLevel::Ring0)
}
pub unsafe fn load(self) {
use core::mem::size_of;
use x86_64::instructions::tables::{lgdt, DescriptorTablePointer};
let ptr = DescriptorTablePointer {
base: self.addr,
... | {
assert!(index + 2 < GDT_MAX_SIZE, "GDT full");
ptr::write(base.add(self.next_entry), value_low);
ptr::write(base.add(self.next_entry + 1), value_high);
self.next_entry += 2;
} | conditional_block |
gdt.rs | use core::mem::size_of;
use core::ptr;
use core::sync::atomic::{AtomicU8, Ordering};
use x86_64::structures::gdt::SegmentSelector;
use x86_64::structures::tss::TaskStateSegment;
use x86_64::{PrivilegeLevel, VirtAddr};
pub use x86_64::structures::gdt::Descriptor;
use crate::memory::constants::GDT_ADDR;
pub const DOUB... | (addr: VirtAddr) -> Self {
Self {
addr,
next_entry: 1, // first entry is the null descriptor, so it is not free
}
}
pub fn add_entry(&mut self, entry: Descriptor) -> SegmentSelector {
let base: *mut u64 = self.addr.as_mut_ptr();
let index = self.next_entr... | new | identifier_name |
gdt.rs | use core::mem::size_of;
use core::ptr;
use core::sync::atomic::{AtomicU8, Ordering};
use x86_64::structures::gdt::SegmentSelector;
use x86_64::structures::tss::TaskStateSegment;
use x86_64::{PrivilegeLevel, VirtAddr};
pub use x86_64::structures::gdt::Descriptor;
use crate::memory::constants::GDT_ADDR;
pub const DOUB... |
pub fn add_entry(&mut self, entry: Descriptor) -> SegmentSelector {
let base: *mut u64 = self.addr.as_mut_ptr();
let index = self.next_entry;
unsafe {
match entry {
Descriptor::UserSegment(value) => {
assert!(index + 1 < GDT_MAX_SIZE, "GDT fu... | {
Self {
addr,
next_entry: 1, // first entry is the null descriptor, so it is not free
}
} | identifier_body |
gdt.rs | use core::mem::size_of;
use core::ptr; | use core::sync::atomic::{AtomicU8, Ordering};
use x86_64::structures::gdt::SegmentSelector;
use x86_64::structures::tss::TaskStateSegment;
use x86_64::{PrivilegeLevel, VirtAddr};
pub use x86_64::structures::gdt::Descriptor;
use crate::memory::constants::GDT_ADDR;
pub const DOUBLE_FAULT_IST_INDEX: usize = 0;
/// Max... | random_line_split | |
EjpSecurityConfigImpl.ts | // DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
//
// Copyright 2016-2018 Pascal ECHEMANN.
//
// 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.apac... | () {}
////////////////////////////////////////////////////////////////////////////
// Public properties
////////////////////////////////////////////////////////////////////////////
/**
* @inheritDoc
*/
public constraints:EjpConstraintConfig[] = null;
/**
* @inheritDoc
*/
public roles:EjpR... | constructor | identifier_name |
EjpSecurityConfigImpl.ts | // DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
//
// Copyright 2016-2018 Pascal ECHEMANN.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at | //
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific la... | random_line_split | |
from_into.rs | // The From trait is used for value-to-value conversions.
// If From is implemented correctly for a type, the Into trait should work conversely.
// You can read more about it at https://doc.rust-lang.org/std/convert/trait.From.html
#[derive(Debug)]
struct Person {
name: String,
age: usize,
}
// We implement th... |
#[test]
fn test_missing_age() {
let p: Person = Person::from("Mark,");
assert_eq!(p.name, "John");
assert_eq!(p.age, 30);
}
#[test]
fn test_missing_name() {
let p: Person = Person::from(",1");
assert_eq!(p.name, "John");
assert_eq!(p.age, 30);
}... | {
let p: Person = Person::from("Mark");
assert_eq!(p.name, "John");
assert_eq!(p.age, 30);
} | identifier_body |
from_into.rs | // The From trait is used for value-to-value conversions.
// If From is implemented correctly for a type, the Into trait should work conversely.
// You can read more about it at https://doc.rust-lang.org/std/convert/trait.From.html
#[derive(Debug)]
struct Person {
name: String,
age: usize,
}
// We implement th... | let p: Person = Person::from(",1");
assert_eq!(p.name, "John");
assert_eq!(p.age, 30);
}
#[test]
fn test_missing_name_and_age() {
let p: Person = Person::from(",");
assert_eq!(p.name, "John");
assert_eq!(p.age, 30);
}
#[test]
fn test_missing_name... | }
#[test]
fn test_missing_name() { | random_line_split |
from_into.rs | // The From trait is used for value-to-value conversions.
// If From is implemented correctly for a type, the Into trait should work conversely.
// You can read more about it at https://doc.rust-lang.org/std/convert/trait.From.html
#[derive(Debug)]
struct Person {
name: String,
age: usize,
}
// We implement th... | () {
let p: Person = Person::from(",1");
assert_eq!(p.name, "John");
assert_eq!(p.age, 30);
}
#[test]
fn test_missing_name_and_age() {
let p: Person = Person::from(",");
assert_eq!(p.name, "John");
assert_eq!(p.age, 30);
}
#[test]
fn test_missing... | test_missing_name | identifier_name |
FileInput.tsx | import { forwardRef, InputHTMLAttributes, ReactNode } from "react";
import cn from "classnames";
import { buttonThemeClassNames, ButtonThemeProps } from "@react-md/button";
import { TextIconSpacing, useIcon } from "@react-md/icon";
import { useInteractionStates } from "@react-md/states";
import { SrOnly } from "@react-... |
const { ripples, className, handlers } = useInteractionStates({
handlers: {
onKeyDown,
onKeyUp,
onMouseDown,
onMouseUp,
onMouseLeave,
onClick,
onTouchStart,
onTouchMove,
onTouchEnd,
},
className: buttonThemeClassNames({
... | {
children = <SrOnly>Upload</SrOnly>;
} | conditional_block |
FileInput.tsx | import { forwardRef, InputHTMLAttributes, ReactNode } from "react";
import cn from "classnames";
import { buttonThemeClassNames, ButtonThemeProps } from "@react-md/button";
import { TextIconSpacing, useIcon } from "@react-md/icon";
import { useInteractionStates } from "@react-md/states";
import { SrOnly } from "@react-... | } else if (children) {
content = (
<TextIconSpacing icon={icon} iconAfter={iconAfter}>
{children}
</TextIconSpacing>
);
}
return (
<>
<input
{...props}
{...handlers}
ref={ref}
onChange={onChange}
value={di... | ); | random_line_split |
mysqldg.py | #!/usr/bin/env python
import os
import random
import types
import uuid
import msgpack
import MySQLdb
#from MySQLdb.cursors import DictCursor
#from MySQLdb.cursors import Cursor
from warnings import filterwarnings
from cocaine.worker import Worker
from cocaine.logging import Logger
#Suppressing warnings
filterwarnin... |
def putData(self, data, tablename):
try:
tablename = tablename.replace('.', '_').replace('-', '_').replace('+', '_')
line = None
fname = '/dev/shm/%s-%i' % ('COMBAINE', random.randint(0, 65535))
with open(fname, 'w') as table_file:
for line i... | self.logger = Logger()
self.place = None
self.tablename = ''
try:
# port = config.get('local_db_port', 3306)
unix_socket = config.get('MysqlSocket',
"/var/run/mysqld/mysqld.sock")
self.dbname = config.get('local_db_name', '... | identifier_body |
mysqldg.py | #!/usr/bin/env python
import os
import random
import types
import uuid
import msgpack
import MySQLdb
#from MySQLdb.cursors import DictCursor
#from MySQLdb.cursors import Cursor
from warnings import filterwarnings
from cocaine.worker import Worker
from cocaine.logging import Logger
#Suppressing warnings
filterwarnin... |
def _preparePlace(self, example):
ftypes = {types.IntType: "INT",
types.UnicodeType: "VARCHAR(200)",
types.StringType: "VARCHAR(200)",
types.FloatType: "FLOAT"}
try:
self.place = '( %s )' % ','.join([" %s %s" % (field_name,
... | self.tablename = tablename
return True | conditional_block |
mysqldg.py | #!/usr/bin/env python
import os
import random
import types
import uuid
import msgpack
import MySQLdb
#from MySQLdb.cursors import DictCursor
#from MySQLdb.cursors import Cursor
from warnings import filterwarnings
from cocaine.worker import Worker
from cocaine.logging import Logger
#Suppressing warnings
filterwarnin... | 'struct': self.place}
self.cursor.execute(query)
self.db.commit()
query = "LOAD DATA INFILE '%(filename)s' INTO TABLE %(tablename)s FIELDS TERMINATED BY ... | random_line_split | |
mysqldg.py | #!/usr/bin/env python
import os
import random
import types
import uuid
import msgpack
import MySQLdb
#from MySQLdb.cursors import DictCursor
#from MySQLdb.cursors import Cursor
from warnings import filterwarnings
from cocaine.worker import Worker
from cocaine.logging import Logger
#Suppressing warnings
filterwarnin... | (request, response):
raw = yield request.read()
config, tablename = msgpack.unpackb(raw)
try:
m = MySqlDG(**config)
drop_query = "DROP TABLE IF EXISTS %s" % tablename
log.info(drop_query)
m.perfomCustomQuery(drop_query)
except Exception as err:
response.error(-100... | drop | identifier_name |
variables.rs | use std::convert::TryFrom;
use vm::types::Value;
use vm::contexts::{LocalContext, Environment};
use vm::errors::{RuntimeErrorType, InterpreterResult as Result};
define_named_enum!(NativeVariables {
ContractCaller("contract-caller"), TxSender("tx-sender"), BlockHeight("block-height"), | NativeTrue("true"), NativeFalse("false"),
});
pub fn is_reserved_name(name: &str) -> bool {
NativeVariables::lookup_by_name(name).is_some()
}
pub fn lookup_reserved_variable(name: &str, _context: &LocalContext, env: &mut Environment) -> Result<Option<Value>> {
if let Some(variable) = NativeVariables::look... | BurnBlockHeight("burn-block-height"), NativeNone("none"), | random_line_split |
variables.rs | use std::convert::TryFrom;
use vm::types::Value;
use vm::contexts::{LocalContext, Environment};
use vm::errors::{RuntimeErrorType, InterpreterResult as Result};
define_named_enum!(NativeVariables {
ContractCaller("contract-caller"), TxSender("tx-sender"), BlockHeight("block-height"),
BurnBlockHeight("burn-bloc... | (name: &str, _context: &LocalContext, env: &mut Environment) -> Result<Option<Value>> {
if let Some(variable) = NativeVariables::lookup_by_name(name) {
match variable {
NativeVariables::TxSender => {
let sender = env.sender.clone()
.ok_or(RuntimeErrorType::NoS... | lookup_reserved_variable | identifier_name |
variables.rs | use std::convert::TryFrom;
use vm::types::Value;
use vm::contexts::{LocalContext, Environment};
use vm::errors::{RuntimeErrorType, InterpreterResult as Result};
define_named_enum!(NativeVariables {
ContractCaller("contract-caller"), TxSender("tx-sender"), BlockHeight("block-height"),
BurnBlockHeight("burn-bloc... | NativeVariables::NativeNone => {
Ok(Some(Value::none()))
},
NativeVariables::NativeTrue => {
Ok(Some(Value::Bool(true)))
},
NativeVariables::NativeFalse => {
Ok(Some(Value::Bool(false)))
},
}
... | {
if let Some(variable) = NativeVariables::lookup_by_name(name) {
match variable {
NativeVariables::TxSender => {
let sender = env.sender.clone()
.ok_or(RuntimeErrorType::NoSenderInContext)?;
Ok(Some(sender))
},
NativeVa... | identifier_body |
variables.rs | use std::convert::TryFrom;
use vm::types::Value;
use vm::contexts::{LocalContext, Environment};
use vm::errors::{RuntimeErrorType, InterpreterResult as Result};
define_named_enum!(NativeVariables {
ContractCaller("contract-caller"), TxSender("tx-sender"), BlockHeight("block-height"),
BurnBlockHeight("burn-bloc... | ,
NativeVariables::BurnBlockHeight => {
Err(RuntimeErrorType::NotImplemented.into())
},
NativeVariables::NativeNone => {
Ok(Some(Value::none()))
},
NativeVariables::NativeTrue => {
Ok(Some(Value::Bool(true)))
... | {
let block_height = env.global_context.database.get_current_block_height();
Ok(Some(Value::UInt(block_height as u128)))
} | conditional_block |
status.py | from kubeflow.kubeflow.crud_backend import api, status
def pvc_status(pvc):
"""
Set the status of the pvc
"""
if pvc.metadata.deletion_timestamp is not None:
return status.create_status(status.STATUS_PHASE.TERMINATING,
"Deleting Volume...")
if pvc.statu... | elif evs[0].reason == "Provisioning":
phase = status.STATUS_PHASE.WAITING
elif evs[0].reason == "FailedBinding":
phase = status.STATUS_PHASE.WARNING
elif evs[0].type == "Warning":
phase = status.STATUS_PHASE.WARNING
elif evs[0].type == "Normal":
phase = status.STATUS_PHAS... | " is created. E.g., when you first browse its contents, or"
" attach it to a notebook server"
) | random_line_split |
status.py | from kubeflow.kubeflow.crud_backend import api, status
def pvc_status(pvc):
"""
Set the status of the pvc
"""
if pvc.metadata.deletion_timestamp is not None:
return status.create_status(status.STATUS_PHASE.TERMINATING,
"Deleting Volume...")
if pvc.statu... | (viewer):
"""
Return a string representing the status of that viewer. If a deletion
timestamp is set we want to return a `Terminating` state.
"""
try:
ready = viewer["status"]["ready"]
except KeyError:
return status.STATUS_PHASE.UNINITIALIZED
if "deletionTimestamp" in viewer... | viewer_status | identifier_name |
status.py | from kubeflow.kubeflow.crud_backend import api, status
def pvc_status(pvc):
"""
Set the status of the pvc
"""
if pvc.metadata.deletion_timestamp is not None:
return status.create_status(status.STATUS_PHASE.TERMINATING,
"Deleting Volume...")
if pvc.statu... |
elif evs[0].reason == "FailedBinding":
phase = status.STATUS_PHASE.WARNING
elif evs[0].type == "Warning":
phase = status.STATUS_PHASE.WARNING
elif evs[0].type == "Normal":
phase = status.STATUS_PHASE.READY
return status.create_status(phase, msg, state)
def viewer_status(viewe... | phase = status.STATUS_PHASE.WAITING | conditional_block |
status.py | from kubeflow.kubeflow.crud_backend import api, status
def pvc_status(pvc):
"""
Set the status of the pvc
"""
if pvc.metadata.deletion_timestamp is not None:
return status.create_status(status.STATUS_PHASE.TERMINATING,
"Deleting Volume...")
if pvc.statu... | """
Return a string representing the status of that viewer. If a deletion
timestamp is set we want to return a `Terminating` state.
"""
try:
ready = viewer["status"]["ready"]
except KeyError:
return status.STATUS_PHASE.UNINITIALIZED
if "deletionTimestamp" in viewer["metadata"]:
... | identifier_body | |
Utils.spec.ts | import {hmsm} from '../src/hmsm';
import {expect} from 'chai';
import 'mocha';
import {clamp, getValue, inRange, makeValueGetter, merge} from "../src/Utils";
describe('Utils', () => {
| it('should return func result', () => {
let a = 1
expect(getValue(() => a++)).to.equal(a - 1)
expect(a).to.equal(2)
expect(getValue(() => a++)).to.equal(a - 1)
expect(a).to.equal(3)
});
it('if primitive it should return its value', () => {
expect(getValue("1")).to.equal(... | describe('getValue', () => { | random_line_split |
lib.rs | #[macro_use]
extern crate serde_derive;
extern crate chrono;
extern crate hyper;
extern crate hyper_native_tls;
extern crate serde_json;
pub mod types;
pub use types::*;
use std::io::Read;
use hyper::Client;
use hyper::client::RequestBuilder;
use hyper::net::HttpsConnector;
use hyper::header::{Authorization, Link, ... |
/// Extract link={rel_type} values from the header collection
///
/// Returns GetLinkErr if there's no link header or no link header whose rel={rel_type}
fn get_link_value<'a>(
headers: &hyper::header::Headers,
rel_type: RelationType,
) -> Result<LinkValue, GetLinkErr> {
let link = match headers.get::<Lin... | {
let client = get_client();
let mut res = get_request(&client, &ctx.token, &url, Method::Get)
.send()
.unwrap();
let mut content = String::new();
res.read_to_string(&mut content).unwrap();
let link_value = get_link_value(&res.headers, RelationType::Next);
let data: Vec<Branch... | identifier_body |
lib.rs | #[macro_use]
extern crate serde_derive;
extern crate chrono;
extern crate hyper;
extern crate hyper_native_tls;
extern crate serde_json;
pub mod types;
pub use types::*;
use std::io::Read;
use hyper::Client;
use hyper::client::RequestBuilder;
use hyper::net::HttpsConnector;
use hyper::header::{Authorization, Link, ... |
fn get_branches_and_next(url: String, ctx: &Context) -> (Option<String>, Vec<Branch>) {
let client = get_client();
let mut res = get_request(&client, &ctx.token, &url, Method::Get)
.send()
.unwrap();
let mut content = String::new();
res.read_to_string(&mut content).unwrap();
let l... |
all_branches
} | random_line_split |
lib.rs | #[macro_use]
extern crate serde_derive;
extern crate chrono;
extern crate hyper;
extern crate hyper_native_tls;
extern crate serde_json;
pub mod types;
pub use types::*;
use std::io::Read;
use hyper::Client;
use hyper::client::RequestBuilder;
use hyper::net::HttpsConnector;
use hyper::header::{Authorization, Link, ... | () -> Client {
let ssl = NativeTlsClient::new().unwrap();
let connector = HttpsConnector::new(ssl);
Client::with_connector(connector)
}
pub fn get_repository(ctx: &mut Context) {
let url = format!("https://api.github.com/repos/{}/{}", ctx.owner, ctx.repo);
let client = get_client();
let mut r... | get_client | identifier_name |
app_with_file_descriptor.rs | /*
Copyright 2017 Jinjing Wang
This file is part of mtcp.
mtcp 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 later version.
mtcp is distributed in the... | {
debug!("start_app_with_file..");
let (tun_in_sender, tun_out_receiver) =
app::start_app(server);
init_file_descriptor(tun_in_sender, tun_out_receiver, tun_file);
} | identifier_body | |
app_with_file_descriptor.rs | /*
Copyright 2017 Jinjing Wang
This file is part of mtcp.
mtcp 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 later version.
mtcp is distributed in the... |
(
tun_file: File,
server: Server,
)
{
debug!("start_app_with_file..");
let (tun_in_sender, tun_out_receiver) =
app::start_app(server);
init_file_descriptor(tun_in_sender, tun_out_receiver, tun_file);
}
| start_app | identifier_name |
app_with_file_descriptor.rs | /*
Copyright 2017 Jinjing Wang | mtcp 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 later version.
mtcp is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; witho... |
This file is part of mtcp.
| random_line_split |
foreach-external-iterators-hashmap-break-restart.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | }
assert_eq!(x, 6);
assert_eq!(y, 60);
}
| {
let mut h = HashMap::new();
let kvs = [(1, 10), (2, 20), (3, 30)];
for &(k,v) in kvs.iter() {
h.insert(k,v);
}
let mut x = 0;
let mut y = 0;
let mut i = h.iter();
for (&k,&v) in i {
x += k;
y += v;
break;
}
for (&k,&v) in i {
x += k;
... | identifier_body |
foreach-external-iterators-hashmap-break-restart.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | () {
let mut h = HashMap::new();
let kvs = [(1, 10), (2, 20), (3, 30)];
for &(k,v) in kvs.iter() {
h.insert(k,v);
}
let mut x = 0;
let mut y = 0;
let mut i = h.iter();
for (&k,&v) in i {
x += k;
y += v;
break;
}
for (&k,&v) in i {
x += k... | main | identifier_name |
foreach-external-iterators-hashmap-break-restart.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at | //
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
extern crate col... | // http://rust-lang.org/COPYRIGHT. | random_line_split |
html.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/. */
#![allow(unrooted_must_root)]
use crate::dom::bindings::codegen::Bindings::HTMLTemplateElementBinding::HTMLTempl... | (*mut JSTracer);
let tracer = Tracer(trc);
impl HtmlTracer for Tracer {
type Handle = Dom<Node>;
#[allow(unrooted_must_root)]
fn trace_handle(&self, node: &Dom<Node>) {
unsafe {
node.trace(self.0);
}
}
... | Tracer | identifier_name |
html.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/. */
#![allow(unrooted_must_root)]
use crate::dom::bindings::codegen::Bindings::HTMLTemplateElementBinding::HTMLTempl... | else {
ret.push_node(node);
}
ret
}
fn push_node(&mut self, n: &Node) {
match n.downcast::<Element>() {
Some(e) => self
.stack
.push(SerializationCommand::OpenElement(DomRoot::from_ref(e))),
None => self.stack.push(Ser... | {
for c in rev_children_iter(node) {
ret.push_node(&*c);
}
} | conditional_block |
html.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/. */
#![allow(unrooted_must_root)]
use crate::dom::bindings::codegen::Bindings::HTMLTemplateElementBinding::HTMLTempl... | },
}
}
Ok(())
}
} | NodeTypeId::Document(_) => panic!("Can't serialize Document node itself"),
NodeTypeId::Element(_) => panic!("Element shouldn't appear here"), | random_line_split |
project.config.ts | import { join } from 'path';
import { SeedConfig } from './seed.config';
/**
* This class extends the basic seed configuration, allowing for project specific overrides. A few examples can be found
* below.
*/
export class | extends SeedConfig {
PROJECT_TASKS_DIR = join(process.cwd(), this.TOOLS_DIR, 'tasks', 'project');
FONTS_DEST = `${this.APP_DEST}/fonts`;
FONTS_SRC = [
'node_modules/bootstrap/dist/fonts/**',
'node_modules/font-awesome/fonts/**'
];
constructor() {
super();
// this.APP_TITLE = 'Put name ... | ProjectConfig | identifier_name |
project.config.ts | import { join } from 'path';
| import { SeedConfig } from './seed.config';
/**
* This class extends the basic seed configuration, allowing for project specific overrides. A few examples can be found
* below.
*/
export class ProjectConfig extends SeedConfig {
PROJECT_TASKS_DIR = join(process.cwd(), this.TOOLS_DIR, 'tasks', 'project');
FONTS... | random_line_split | |
project.config.ts | import { join } from 'path';
import { SeedConfig } from './seed.config';
/**
* This class extends the basic seed configuration, allowing for project specific overrides. A few examples can be found
* below.
*/
export class ProjectConfig extends SeedConfig {
PROJECT_TASKS_DIR = join(process.cwd(), this.TOOLS_DIR,... | // {src: `${this.CSS_SRC}/path-to-lib/test-lib.css`, inject: true, vendor: false},
];
/* Add to or override NPM module configurations: */
// this.mergeObject(this.PLUGIN_CONFIGS['browser-sync'], { ghostMode: false });
}
}
| {
super();
// this.APP_TITLE = 'Put name of your app here';
/* Enable typeless compiler runs (faster) between typed compiler runs. */
// this.TYPED_COMPILE_INTERVAL = 5;
// Add `NPM` third-party libraries to be injected/bundled.
this.NPM_DEPENDENCIES = [
...this.NPM_DEPENDENCIES,
{... | identifier_body |
typescript.ts | import * as path from 'path';
import { stripIndent } from 'common-tags';
import {
AotPlugin,
AotPluginOptions,
AngularCompilerPlugin,
AngularCompilerPluginOptions,
PLATFORM
} from '@ngtools/webpack';
import { WebpackConfigOptions } from '../webpack-config';
const SilentError = require('silent-error');
cons... | options: { sourceMap: buildOptions.sourcemaps }
}];
}
const test = AngularCompilerPlugin.isSupported()
? /(?:\.ngfactory\.js|\.ngstyle\.js|\.ts)$/
: /\.ts$/;
return {
module: { rules: [{ test, use: [...boLoader, webpackLoader] }] },
plugins: [ _createAotPlugin(wco, pluginOptions) ]
}... | loader: '@angular-devkit/build-optimizer/webpack-loader', | random_line_split |
typescript.ts | import * as path from 'path';
import { stripIndent } from 'common-tags';
import {
AotPlugin,
AotPluginOptions,
AngularCompilerPlugin,
AngularCompilerPluginOptions,
PLATFORM
} from '@ngtools/webpack';
import { WebpackConfigOptions } from '../webpack-config';
const SilentError = require('silent-error');
cons... | "prod": "environments/environment.prod.ts"
}
`;
}
throw new SilentError(
`Environment configuration does not contain "environmentSource" entry.${migrationMessage}`
);
}
if (!(buildOptions.environment in appConfig.environments)) {
throw new SilentEr... | {
migrationMessage = '\n\n' + stripIndent`
A new environmentSource entry replaces the previous source entry inside environments.
To migrate angular-cli.json follow the example below:
Before:
"environments": {
"source": "environments/environment.ts",
... | conditional_block |
typescript.ts | import * as path from 'path';
import { stripIndent } from 'common-tags';
import {
AotPlugin,
AotPluginOptions,
AngularCompilerPlugin,
AngularCompilerPluginOptions,
PLATFORM
} from '@ngtools/webpack';
import { WebpackConfigOptions } from '../webpack-config';
const SilentError = require('silent-error');
cons... | (wco: WebpackConfigOptions) {
const { projectRoot, buildOptions, appConfig } = wco;
const tsConfigPath = path.resolve(projectRoot, appConfig.root, appConfig.tsconfig);
const testTsConfigPath = path.resolve(projectRoot, appConfig.root, appConfig.testTsconfig);
let pluginOptions: any = { tsConfigPath };
// Fa... | getAotConfig | identifier_name |
typescript.ts | import * as path from 'path';
import { stripIndent } from 'common-tags';
import {
AotPlugin,
AotPluginOptions,
AngularCompilerPlugin,
AngularCompilerPluginOptions,
PLATFORM
} from '@ngtools/webpack';
import { WebpackConfigOptions } from '../webpack-config';
const SilentError = require('silent-error');
cons... | return {
module: { rules: [{ test: /\.ts$/, loader: webpackLoader }] },
plugins: [ _createAotPlugin(wco, pluginOptions) ]
};
}
| {
const { projectRoot, appConfig } = wco;
const tsConfigPath = path.resolve(projectRoot, appConfig.root, appConfig.testTsconfig);
const appTsConfigPath = path.resolve(projectRoot, appConfig.root, appConfig.tsconfig);
// Force include main and polyfills.
// This is needed for AngularCompilerPlugin compatibili... | identifier_body |
measurematrix.py | #!/usr/bin/env python
# -*- coding: UTF-8 -*-
"""
.. module:: measurematrix.py
.. moduleauthor:: Jozsef Attila Janko, Bence Takacs, Zoltan Siki (code optimalization)
Sample application of Ulyxes PyAPI to measure within a rectangular area
:param argv[1] (int): number of horizontal intervals (between measurements), ... |
# set instrument
stationtype = '1100'
if len(sys.argv) > 3:
stationtype = sys.argv[3]
if re.search('120[0-9]$', stationtype):
mu = LeicaTPS1200()
elif re.search('110[0-9]$', stationtype):
mu = LeicaTCRA1100()
elif re.search('550[0-9]$', stationtype):
mu = Trimble... | try:
dv_nr = int(sys.argv[2])
except ValueError:
print("invalid numeric value " + sys.argv[2])
#sys.exit(1) | conditional_block |
measurematrix.py | #!/usr/bin/env python
# -*- coding: UTF-8 -*-
"""
.. module:: measurematrix.py
.. moduleauthor:: Jozsef Attila Janko, Bence Takacs, Zoltan Siki (code optimalization)
Sample application of Ulyxes PyAPI to measure within a rectangular area
:param argv[1] (int): number of horizontal intervals (between measurements), ... | else:
print("unsupported instrument type")
sys.exit(1)
# set port
port = '/dev/ttyUSB0'
if len(sys.argv) > 4:
port = sys.argv[4]
iface = SerialIface("test", port)
# set output file name
fn = None
if len(sys.argv) > 5:
fn = sys.argv[5]
# write out measu... | mu = LeicaTCRA1100()
elif re.search('550[0-9]$', stationtype):
mu = Trimble5500() | random_line_split |
__init__.py |
from django.template.loader import render_to_string
from django.utils.importlib import import_module
from pressgang.actions.options import Option, Options
from pressgang.utils.registry import create_registry
SiteOptionRegistry = create_registry('id')
class SiteOption(Option):
"""Base class for a single site option... |
return render_to_string(template, {
'option': self.provide_wp_id(blog) or self.wp_id,
'name': self.name,
'value': self.provide_wp_value(value) or value
})
def provide_wp_id(self, blog):
"""Allows an option to provide a dynamic value for the WordPress database ID.
If an option overrides this functi... | template = 'pressgang/options/site_option.php' | conditional_block |
__init__.py | from django.template.loader import render_to_string | from pressgang.actions.options import Option, Options
from pressgang.utils.registry import create_registry
SiteOptionRegistry = create_registry('id')
class SiteOption(Option):
"""Base class for a single site option."""
__metaclass__ = SiteOptionRegistry
# The databse ID used by WordPress for the site option
wp_... | from django.utils.importlib import import_module
| random_line_split |
__init__.py |
from django.template.loader import render_to_string
from django.utils.importlib import import_module
from pressgang.actions.options import Option, Options
from pressgang.utils.registry import create_registry
SiteOptionRegistry = create_registry('id')
class SiteOption(Option):
"""Base class for a single site option... |
class SiteOptions(Options):
"""Options for the site."""
def get_option_obj(self, option):
# Import the module containing the options, so that the registry is
# able to add each option to its list
import_module('pressgang.actions.options.site.options')
# Attempt to return the requested option
try:
re... | """Allows an option to provide a dynamic value for the WordPress database ID.
If an option overrides this function to return a value, that value will
be given preference over the value of the option's `wp_id`.
Arguments:
blog -- an instance of a Blog object
Returns: a string of the database ID of the optio... | identifier_body |
__init__.py |
from django.template.loader import render_to_string
from django.utils.importlib import import_module
from pressgang.actions.options import Option, Options
from pressgang.utils.registry import create_registry
SiteOptionRegistry = create_registry('id')
class | (Option):
"""Base class for a single site option."""
__metaclass__ = SiteOptionRegistry
# The databse ID used by WordPress for the site option
wp_id = None
# A custom template to use to set the option, relative to the site-options
# template directory
template = None
# Whether the option is only available o... | SiteOption | identifier_name |
dimensions.py | , dim, parent, jx):
dim = wrap(dim)
self.name = dim.name
self.parent = coalesce(parent)
self.full_name = join_field(split_field(self.parent.full_name)+[self.name])
self.edges = None # FOR NOW
dot.set_default(self, dim)
self.where = dim.where
self.type = ... |
self.partitions = wrap([
{
"name": str(d.partitions[i].name), # CONVERT TO STRING
"value": d.getEnd(d.partitions[i]),
"where": {"term": {edges[0].value: d.partitions[i].value}},
"count": SUM(subcube),
... | return tuple(values) | conditional_block |
dimensions.py | "allowNulls": False} for k, v in self.fields.items()])
else:
self.fields = listwrap(fields)
edges = wrap([{"name": f, "value": f, "index": i, "allowNulls": False} for i, f in enumerate(self.fields)])
if dim.partitions:
return # ALREADY HAVE PARTS
if self.ty... | if self.fields:
if len(self.fields) == 1:
return Data(
name=self.full_name,
value=self.fields[0],
aggregate="none"
)
else:
return Data(
name=self.full_name,
... | identifier_body | |
dimensions.py | e in listwrap(dim.edges):
new_e = Dimension(e, self, jx)
self.edges[new_e.full_name] = new_e
self.partitions = wrap(coalesce(dim.partitions, []))
parse_partition(self)
fields = coalesce(dim.field, dim.fields)
if not fields:
return # NO FIELDS TO SE... | getSelect | identifier_name | |
dimensions.py | self, dim, parent, jx):
dim = wrap(dim)
self.name = dim.name
self.parent = coalesce(parent)
self.full_name = join_field(split_field(self.parent.full_name)+[self.name])
self.edges = None # FOR NOW
dot.set_default(self, dim)
self.where = dim.where
self.typ... | "select": {"name": "count", "aggregate": "count"},
"edges": edges,
"where": self.where,
"limit": self.limit
})
Log.note("{{name}} has {{num}} parts", name= self.name, num= len(parts))
d = parts.edges[0].domain
if... |
jx.get_columns()
with Timer("Get parts of {{name}}", {"name": self.name}):
parts = jx.query({
"from": self.index, | random_line_split |
default.py | # Evonic plugin written by Mentality
# -*- coding: utf-8 -*-
import re,os,urllib,urllib2
import xbmcplugin,xbmcgui
import xbmcaddon
import evonic as enter
from BeautifulSoup import BeautifulSoup as BS
__settings__ = xbmcaddon.Addon(id="plugin.video.Evonic")
status = __settings__.getSetting("status")
def ge... | (name,url,iconimage):
ok=True
liz=xbmcgui.ListItem(name, iconImage="DefaultVideo.png", thumbnailImage=iconimage)
liz.setInfo( type="Video", infoLabels={ "Title": name } )
ok=xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=url,listitem=liz)
return ok
def addDir(name,url,m... | addLink | identifier_name |
default.py | # Evonic plugin written by Mentality
# -*- coding: utf-8 -*-
import re,os,urllib,urllib2
import xbmcplugin,xbmcgui
import xbmcaddon
import evonic as enter
from BeautifulSoup import BeautifulSoup as BS
__settings__ = xbmcaddon.Addon(id="plugin.video.Evonic")
status = __settings__.getSetting("status")
def ge... |
elif mode==3:
enter.play_premium_video(url,name,str(iconimage),imdb,mpaa)
elif mode==4:
enter.INDEX_GENRE(url)
elif mode==5:
enter.INDEX(url,name)
elif mode==6:
enter.VIDEOLINKS(url,name,iconimage,imdb,trailer)
elif mode==7:
ent... | enter.SEARCH(url) | conditional_block |
default.py | # Evonic plugin written by Mentality
# -*- coding: utf-8 -*-
import re,os,urllib,urllib2
import xbmcplugin,xbmcgui
import xbmcaddon
import evonic as enter
from BeautifulSoup import BeautifulSoup as BS
__settings__ = xbmcaddon.Addon(id="plugin.video.Evonic")
status = __settings__.getSetting("status")
def ge... | u=sys.argv[0]+"?url="+urllib.quote_plus(url)+"&mode="+str(mode)+"&name="+urllib.quote_plus(name)+"&iconimage="+urllib.quote_plus(iconimage)
ok=True
liz=xbmcgui.ListItem(name, iconImage="DefaultFolder.png", thumbnailImage=iconimage)
liz.setInfo( type="Video", infoLabels={ "Title": name } ... | random_line_split | |
default.py | # Evonic plugin written by Mentality
# -*- coding: utf-8 -*-
import re,os,urllib,urllib2
import xbmcplugin,xbmcgui
import xbmcaddon
import evonic as enter
from BeautifulSoup import BeautifulSoup as BS
__settings__ = xbmcaddon.Addon(id="plugin.video.Evonic")
status = __settings__.getSetting("status")
def ge... |
params=get_params()
url=None
url0=None
name=None
mode=None
iconimage=None
imdb=None
plot=None
mpaa=None
trailer=None
try:
url=urllib.unquote_plus(params['url'])
except:
pass
try:
url0=urllib.unquote_plus(params['url0'])
except:
pass
try:
name=urllib.unquote_plus(params["name"]... | u=sys.argv[0]+"?url="+urllib.quote_plus(url)+"&mode="+str(mode)+"&name="+urllib.quote_plus(name)+"&iconimage="+urllib.quote_plus(iconimage)
ok=True
liz=xbmcgui.ListItem(name, iconImage="DefaultFolder.png", thumbnailImage=iconimage)
liz.setInfo( type="Video", infoLabels={ "Title": name } )
... | identifier_body |
variable_handlers.py | """
This module provides methods that parse variables into
one of the three base level variable types. We map the
variable type names to methods that can handle them. Each
method consumes a Request object 'rq' as the first positional
argument, and does its work by calling one of the variable-setting
methods on rq.
"""
... |
else:
this_frame = frame + '\n\n'
this_data = value['value'].encode('ascii')
args = (boundary, name)
output += this_frame.format(*args).encode('ascii') + this_data
output += '\n--{}--'.format(boundary).encode('ascii')
rq.set_data(output)
content_type_head... | fname = value.get('filename', getattr(value['value'], 'name', uuid4().hex))
this_frame = frame + '; filename="{}"\nContent-Type: {}\n\n'
this_data = encode(value['value'], value['mimetype'])
args = (boundary, name, fname, value['mimetype']) | conditional_block |
variable_handlers.py | """
This module provides methods that parse variables into
one of the three base level variable types. We map the
variable type names to methods that can handle them. Each
method consumes a Request object 'rq' as the first positional
argument, and does its work by calling one of the variable-setting
methods on rq.
"""
... | (rq, **values):
frame = '\n--{}\nContent-Disposition: form-data; name="{}"'
boundary = uuid4().hex
files = [name for name, data in values.items() if 'mimetype' in data]
output = bytes()
for name, value in values.items():
if name in files:
fname = value.get('filename', getattr(val... | multipart | identifier_name |
variable_handlers.py | """
This module provides methods that parse variables into
one of the three base level variable types. We map the
variable type names to methods that can handle them. Each
method consumes a Request object 'rq' as the first positional
argument, and does its work by calling one of the variable-setting
methods on rq.
"""
... |
@VariableHandler('http_basic_auth')
def basic_auth(rq, **values):
username = values.get('username', {}).get('value', '')
password = values.get('password', {}).get('value', '')
authinfo = b64encode("{}:{}".format(username, password).encode('utf-8'))
authinfo = 'Basic {}'.format(authinfo.decode('utf-8'))... | random_line_split | |
variable_handlers.py | """
This module provides methods that parse variables into
one of the three base level variable types. We map the
variable type names to methods that can handle them. Each
method consumes a Request object 'rq' as the first positional
argument, and does its work by calling one of the variable-setting
methods on rq.
"""
... | if var_type in VariableHandler.registry:
variables = {val.pop('name', name): val for name, val in values.items()}
VariableHandler.registry[var_type](rq, **variables)
else:
raise CannotHandleVariableTypes(var_type) | identifier_body | |
ratekeeper_monkey_patch.py | # (c) Copyright 2015 Hewlett Packard Enterprise Development LP
#
# 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 appli... |
return wrapped_func
| if fn.func_name == '_populate_neutron_extension_values':
LOG.debug("RK: wrapping function call: %s" % fn.func_name)
foo, context, instance, pci_request_id, port_req_body = args
flavor = instance.get_flavor()
extra_specs = flavor.get('extra_specs', {})
min_rate... | identifier_body |
ratekeeper_monkey_patch.py | # (c) Copyright 2015 Hewlett Packard Enterprise Development LP
# | # not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CON... | # Licensed under the Apache License, Version 2.0 (the "License"); you may | random_line_split |
ratekeeper_monkey_patch.py | # (c) Copyright 2015 Hewlett Packard Enterprise Development LP
#
# 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 appli... |
return fn(*args, **kwarg)
return wrapped_func
| LOG.debug("RK: wrapping function call: %s" % fn.func_name)
foo, context, instance, pci_request_id, port_req_body = args
flavor = instance.get_flavor()
extra_specs = flavor.get('extra_specs', {})
min_rate = int(extra_specs.get(rk_const.RK_MIN_RATE, 0))
max_rate... | conditional_block |
ratekeeper_monkey_patch.py | # (c) Copyright 2015 Hewlett Packard Enterprise Development LP
#
# 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 appli... | (*args, **kwarg):
if fn.func_name == '_populate_neutron_extension_values':
LOG.debug("RK: wrapping function call: %s" % fn.func_name)
foo, context, instance, pci_request_id, port_req_body = args
flavor = instance.get_flavor()
extra_specs = flavor.get('extra_specs... | wrapped_func | identifier_name |
secret_configs_json.ts | /*
* Copyright 2022 ThoughtWorks, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agr... | }
export interface SecretConfigsWithSuggestionsJSON extends SecretConfigsJSON {
auto_completion: AutoSuggestionJSON[];
} | plugin_id: string;
properties: PropertyJSON[];
rules: RuleJSON[];
errors?: ErrorsJSON; | random_line_split |
__init__.py | import os
from fabric.decorators import task
from fabric.api import local, run, cd, env, prefix, hide
from fabric.colors import cyan, red, green, yellow
import app
import git
import virtualenv
@task
def init():
"""Execute init tasks for all components (virtualenv, pip)."""
print(yellow("# Setting up developme... | @task
def dev():
"""Setting up Development mode."""
print(yellow("# Setting up development environment...\n", True))
virtualenv.init()
virtualenv.update()
print(green("\n# DONE.", True))
print(green("Type ") + green("activate", True) + green(" to enable your dev virtual environment."))
@task
d... | virtualenv.update()
| random_line_split |
__init__.py | import os
from fabric.decorators import task
from fabric.api import local, run, cd, env, prefix, hide
from fabric.colors import cyan, red, green, yellow
import app
import git
import virtualenv
@task
def init():
"""Execute init tasks for all components (virtualenv, pip)."""
print(yellow("# Setting up developme... |
@task
def dev():
"""Setting up Development mode."""
print(yellow("# Setting up development environment...\n", True))
virtualenv.init()
virtualenv.update()
print(green("\n# DONE.", True))
print(green("Type ") + green("activate", True) + green(" to enable your dev virtual environment."))
@t... | """Update virtual env with requirements packages."""
virtualenv.update() | identifier_body |
__init__.py | import os
from fabric.decorators import task
from fabric.api import local, run, cd, env, prefix, hide
from fabric.colors import cyan, red, green, yellow
import app
import git
import virtualenv
@task
def init():
"""Execute init tasks for all components (virtualenv, pip)."""
print(yellow("# Setting up developme... | ():
"""Clean .pyc files"""
app.clean()
| clean | identifier_name |
blockhash.rs | // Implementation adapted from Python version:
// https://github.com/commonsmachinery/blockhash-python/blob/e8b009d/blockhash.py
// Main site: http://blockhash.io
use image::{GenericImageView, Pixel};
use {BitSet, Image, HashBytes};
use std::cmp::Ordering;
use std::ops::AddAssign;
use std::mem;
const FLOAT_EQ_MARGIN... | <T: PartialOrd>(data: &mut [T], k: usize) -> &mut T {
let len = data.len();
assert!(k < len, "Called qselect_inplace with k = {} and data length: {}", k, len);
if len < SORT_THRESH {
data.sort_by(|left, right| left.partial_cmp(right).unwrap_or(Ordering::Less));
return &mut data[k];
}
... | qselect_inplace | identifier_name |
blockhash.rs | // Implementation adapted from Python version:
// https://github.com/commonsmachinery/blockhash-python/blob/e8b009d/blockhash.py
// Main site: http://blockhash.io
use image::{GenericImageView, Pixel};
use {BitSet, Image, HashBytes};
use std::cmp::Ordering;
use std::ops::AddAssign;
use std::mem;
const FLOAT_EQ_MARGIN... |
BitSet::from_bools(
$blocks.chunks(group_len).zip(medians)
.flat_map(|(blocks, median)|
blocks.iter().map(move |&block|
block > median ||
($eq_fn(block, median) && median > cmp_factor)
)
)
... | / (2u32 as $valty);
let medians: Vec<$valty> = $blocks.chunks(group_len).map(get_median).collect(); | random_line_split |
blockhash.rs | // Implementation adapted from Python version:
// https://github.com/commonsmachinery/blockhash-python/blob/e8b009d/blockhash.py
// Main site: http://blockhash.io
use image::{GenericImageView, Pixel};
use {BitSet, Image, HashBytes};
use std::cmp::Ordering;
use std::ops::AddAssign;
use std::mem;
const FLOAT_EQ_MARGIN... |
}
fn partition<T: PartialOrd>(data: &mut [T]) -> usize {
let len = data.len();
let pivot_idx = {
let first = (&data[0], 0);
let mid = (&data[len / 2], len / 2);
let last = (&data[len - 1], len - 1);
median_of_3(&first, &mid, &last).1
};
data.swap(pivot_idx, len - 1);... | {
qselect_inplace(&mut data[pivot_idx + 1..], k - pivot_idx - 1)
} | conditional_block |
blockhash.rs | // Implementation adapted from Python version:
// https://github.com/commonsmachinery/blockhash-python/blob/e8b009d/blockhash.py
// Main site: http://blockhash.io
use image::{GenericImageView, Pixel};
use {BitSet, Image, HashBytes};
use std::cmp::Ordering;
use std::ops::AddAssign;
use std::mem;
const FLOAT_EQ_MARGIN... |
fn blockhash_slow<I: Image, B: HashBytes>(img: &I, hwidth: u32, hheight: u32) -> B {
let mut blocks = vec![0f32; (hwidth * hheight) as usize];
let (iwidth, iheight) = img.dimensions();
// Block dimensions, in pixels
let (block_width, block_height) = (iwidth as f32 / hwidth as f32, iheight as f32... | {
move |x, y, add| (blocks[(y as usize) * (width as usize) + (x as usize)] += add)
} | identifier_body |
builder.py | # -*- coding: utf-8 -*-
from sphinx.builders.html import JSONHTMLBuilder
from sphinx.util import jsonimpl
class DeconstJSONImpl:
"""
Enhance the default JSON encoder by adding additional keys.
"""
def dump(self, obj, fp, *args, **kwargs):
self._enhance(obj)
return jsonimpl.dump(obj, ... | JSONHTMLBuilder.init(self) | identifier_body | |
builder.py | # -*- coding: utf-8 -*-
from sphinx.builders.html import JSONHTMLBuilder
from sphinx.util import jsonimpl
class DeconstJSONImpl:
"""
Enhance the default JSON encoder by adding additional keys.
"""
def dump(self, obj, fp, *args, **kwargs):
self._enhance(obj)
return jsonimpl.dump(obj, ... | out_suffix = '.json'
def init(self):
JSONHTMLBuilder.init(self) | random_line_split | |
builder.py | # -*- coding: utf-8 -*-
from sphinx.builders.html import JSONHTMLBuilder
from sphinx.util import jsonimpl
class DeconstJSONImpl:
"""
Enhance the default JSON encoder by adding additional keys.
"""
def dump(self, obj, fp, *args, **kwargs):
self._enhance(obj)
return jsonimpl.dump(obj, ... | (self, *args, **kwargs):
return jsonimpl.loads(*args, **kwargs)
def _enhance(self, obj):
"""
Add additional properties to "obj" to get them into the JSON.
"""
obj["hello"] = "Sup"
class DeconstJSONBuilder(JSONHTMLBuilder):
"""
Custom Sphinx builder that generates ... | loads | identifier_name |
SQL.py | #!/usr/bin/env python3
# Copyright 2009-2017 BHG http://bw.org/
import sqlite3
def main():
print('connect')
db = sqlite3.connect('db-api.db')
cur = db.cursor()
| CREATE TABLE test (
id INTEGER PRIMARY KEY, string TEXT, number INTEGER
)
""")
print('insert row')
cur.execute("""
INSERT INTO test (string, number) VALUES ('one', 1)
""")
print('insert row')
cur.execute("""
INSERT INTO test (string, ... | print('create')
cur.execute("DROP TABLE IF EXISTS test")
cur.execute("""
| random_line_split |
SQL.py | #!/usr/bin/env python3
# Copyright 2009-2017 BHG http://bw.org/
import sqlite3
def main():
| INSERT INTO test (string, number) VALUES ('three', 3)
""")
print('commit')
db.commit()
print('count')
cur.execute("SELECT COUNT(*) FROM test")
count = cur.fetchone()[0]
print(f'there are {count} rows in the table.')
print('read')
for row in cur.execute("SELECT * ... | print('connect')
db = sqlite3.connect('db-api.db')
cur = db.cursor()
print('create')
cur.execute("DROP TABLE IF EXISTS test")
cur.execute("""
CREATE TABLE test (
id INTEGER PRIMARY KEY, string TEXT, number INTEGER
)
""")
print('insert row')
cur.... | identifier_body |
SQL.py | #!/usr/bin/env python3
# Copyright 2009-2017 BHG http://bw.org/
import sqlite3
def main():
print('connect')
db = sqlite3.connect('db-api.db')
cur = db.cursor()
print('create')
cur.execute("DROP TABLE IF EXISTS test")
cur.execute("""
CREATE TABLE test (
id INTEG... |
print('drop')
cur.execute("DROP TABLE test")
print('close')
db.close()
if __name__ == '__main__': main()
| print(row) | conditional_block |
SQL.py | #!/usr/bin/env python3
# Copyright 2009-2017 BHG http://bw.org/
import sqlite3
def | ():
print('connect')
db = sqlite3.connect('db-api.db')
cur = db.cursor()
print('create')
cur.execute("DROP TABLE IF EXISTS test")
cur.execute("""
CREATE TABLE test (
id INTEGER PRIMARY KEY, string TEXT, number INTEGER
)
""")
print('insert row')
... | main | identifier_name |
models.py | import datetime
import os
from django.conf import settings
from django.core.files.storage import FileSystemStorage
from django.core.urlresolvers import reverse
from django.db import models
from django.utils import timezone
from comics.core.managers import ComicManager
class Comic(models.Model):
LANGUAGES = (
... | db_table = 'comics_image'
def __unicode__(self):
return u'Image %s/%s...' % (self.comic.slug, self.checksum[:8]) | width = models.IntegerField()
class Meta: | random_line_split |
models.py | import datetime
import os
from django.conf import settings
from django.core.files.storage import FileSystemStorage
from django.core.urlresolvers import reverse
from django.db import models
from django.utils import timezone
from comics.core.managers import ComicManager
class Comic(models.Model):
LANGUAGES = (
... | comic = models.ForeignKey(Comic)
file = models.ImageField(
storage=image_storage, upload_to=image_file_path,
height_field='height', width_field='width')
checksum = models.CharField(max_length=64, db_index=True)
# Optional fields
title = models.CharField(max_length=255, blank=True)
t... | identifier_body | |
models.py | import datetime
import os
from django.conf import settings
from django.core.files.storage import FileSystemStorage
from django.core.urlresolvers import reverse
from django.db import models
from django.utils import timezone
from comics.core.managers import ComicManager
class Comic(models.Model):
LANGUAGES = (
... | (models.Model):
# Required fields
comic = models.ForeignKey(Comic)
file = models.ImageField(
storage=image_storage, upload_to=image_file_path,
height_field='height', width_field='width')
checksum = models.CharField(max_length=64, db_index=True)
# Optional fields
title = models.C... | Image | identifier_name |
models.py | import datetime
import os
from django.conf import settings
from django.core.files.storage import FileSystemStorage
from django.core.urlresolvers import reverse
from django.db import models
from django.utils import timezone
from comics.core.managers import ComicManager
class Comic(models.Model):
LANGUAGES = (
... |
return self._ordered_images
# Let all created dirs and files be writable by the group
os.umask(0002)
image_storage = FileSystemStorage(
location=settings.MEDIA_ROOT, base_url=settings.MEDIA_URL)
def image_file_path(instance, filename):
return u'%s/%s/%s' % (instance.comic.slug, filename[0], filena... | self._ordered_images = list(self.images.order_by('id')) | conditional_block |
borrowck-loan-rcvr-overloaded-op.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | {
x: isize,
y: isize,
}
impl Add<isize> for Point {
type Output = isize;
fn add(self, z: isize) -> isize {
self.x + self.y + z
}
}
impl Point {
pub fn times(&self, z: isize) -> isize {
self.x * self.y * z
}
}
fn a() {
let mut p = Point {x: 3, y: 4};
// ok (we ca... | Point | identifier_name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.