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 |
|---|---|---|---|---|
SiteActivationNotification.py | ##
##
#
# SOFTWARE HISTORY
#
# Date Ticket# Engineer Description
# ------------ ---------- ----------- --------------------------
# 09/10/14 #3623 randerso Manually created, do not regenerate
#
##
class SiteActivationNotification(object):
def __ini... | return self.pluginName.upper() + ":" \
+ self.status + ":" \
+ self.type + " " \
+ self.modifiedSite.upper() + " on " \
+ self.serverName + ":" \
+ self.runMode | identifier_body | |
SiteActivationNotification.py | ##
##
#
# SOFTWARE HISTORY
#
# Date Ticket# Engineer Description
# ------------ ---------- ----------- --------------------------
# 09/10/14 #3623 randerso Manually created, do not regenerate
#
##
class SiteActivationNotification(object):
def __ini... | (self, serverName):
self.serverName = serverName
def getPluginName(self):
return self.pluginName
def setPluginName(self, pluginName):
self.pluginName = pluginName
def __str__(self):
return self.pluginName.upper() + ":" \
+ self.status + ":" \
+ se... | setServerName | identifier_name |
SiteActivationNotification.py | ##
##
#
# SOFTWARE HISTORY
#
# Date Ticket# Engineer Description
# ------------ ---------- ----------- --------------------------
# 09/10/14 #3623 randerso Manually created, do not regenerate
#
##
class SiteActivationNotification(object):
def __ini... | + self.runMode | + self.type + " " \
+ self.modifiedSite.upper() + " on " \
+ self.serverName + ":" \ | random_line_split |
math.py | # Copyright 2014 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or ... | from xml.etree import cElementTree
import appengine_config
from common import schema_fields
from common import tags
from controllers import sites
from models import custom_modules
from models import services
from modules.math import messages
MATH_MODULE_URI = '/modules/math'
RESOURCES_URI = MATH_MODULE_URI + '/resour... | import os | random_line_split |
math.py | # Copyright 2014 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or ... | (cls):
return 'Mathematical Formula'
@classmethod
def vendor(cls):
return 'gcb'
def render(self, node, context):
math_script = cElementTree.XML('<script/>')
# The formula is "text" type in the schema and so is presented in the
# tag's body.
math_script.text... | name | identifier_name |
math.py | # Copyright 2014 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or ... | , global_routes, namespaced_routes,
notify_module_disabled=on_module_disable,
notify_module_enabled=on_module_enable)
return custom_module
| """Registers this module for use."""
def on_module_disable():
tags.Registry.remove_tag_binding(MathTag.binding_name)
def on_module_enable():
tags.Registry.add_tag_binding(MathTag.binding_name, MathTag)
global_routes = [
(RESOURCES_URI + '/.*', tags.ResourcesHandler),
(MATH... | identifier_body |
math.py | # Copyright 2014 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or ... |
else:
math_script.set('type', 'math/tex')
return math_script
def rollup_header_footer(self, context):
"""Include MathJax library only when a math tag is present."""
header = tags.html_string_to_element_tree("""
<script src="%s/MathJax.js?config=TeX-AMS-MML_HTMLorMML">... | math_script.set('type', 'math/mml') | conditional_block |
MediaInfoResponse.py | from InstagramAPI.src.http.Response.Objects.Comment import Comment
from .Objects.User import User
from .Response import Response
class MediaInfoResponse(Response):
def __init__(self, response):
self.taken_at = None
self.image_url = None
self.like_count = None
self.likers = None
... |
def getLikeCount(self):
return self.like_count
def getLikers(self):
return self.likers
def getComments(self):
return self.comments |
def getImageUrl(self):
return self.image_url | random_line_split |
MediaInfoResponse.py | from InstagramAPI.src.http.Response.Objects.Comment import Comment
from .Objects.User import User
from .Response import Response
class MediaInfoResponse(Response):
def __init__(self, response):
self.taken_at = None
self.image_url = None
self.like_count = None
self.likers = None
... |
self.setStatus(response['status'])
self.setFullResponse(response)
def getTakenTime(self):
return self.taken_at
def getImageUrl(self):
return self.image_url
def getLikeCount(self):
return self.like_count
def getLikers(self):
return self.likers
de... | self.setMessage(response['message']) | conditional_block |
MediaInfoResponse.py | from InstagramAPI.src.http.Response.Objects.Comment import Comment
from .Objects.User import User
from .Response import Response
class | (Response):
def __init__(self, response):
self.taken_at = None
self.image_url = None
self.like_count = None
self.likers = None
self.comments = None
if self.STATUS_OK == response['status']:
self.taken_at = response['items'][0]['taken_at']
sel... | MediaInfoResponse | identifier_name |
MediaInfoResponse.py | from InstagramAPI.src.http.Response.Objects.Comment import Comment
from .Objects.User import User
from .Response import Response
class MediaInfoResponse(Response):
def __init__(self, response):
self.taken_at = None
self.image_url = None
self.like_count = None
self.likers = None
... |
def getLikeCount(self):
return self.like_count
def getLikers(self):
return self.likers
def getComments(self):
return self.comments
| return self.image_url | identifier_body |
utils.js | import fs from "node:fs";
import readline from "node:readline";
import chalk from "chalk";
import { execa } from "execa";
import stringWidth from "string-width";
import fetch from "node-fetch";
import outdent from "outdent";
import getFormattedDate from "./get-formatted-date.js";
readline.emitKeypressEvents(process.st... | input += chalk.dim(".").repeat(WIDTH - input.length - 1);
}
return input;
}
async function logPromise(name, promiseOrAsyncFunction) {
const promise =
typeof promiseOrAsyncFunction === "function"
? promiseOrAsyncFunction()
: promiseOrAsyncFunction;
process.stdout.write(fitTerminal(name));
... | function fitTerminal(input) {
const columns = Math.min(process.stdout.columns, 80);
const WIDTH = columns - stringWidth(OK) + 1;
if (input.length < WIDTH) { | random_line_split |
utils.js | import fs from "node:fs";
import readline from "node:readline";
import chalk from "chalk";
import { execa } from "execa";
import stringWidth from "string-width";
import fetch from "node-fetch";
import outdent from "outdent";
import getFormattedDate from "./get-formatted-date.js";
readline.emitKeypressEvents(process.st... | (args, options) {
args = Array.isArray(args) ? args : [args];
return execa("git", args, options);
}
function waitForEnter() {
process.stdin.setRawMode(true);
return new Promise((resolve, reject) => {
process.stdin.on("keypress", listener);
process.stdin.resume();
function listener(ch, key) {
... | runGit | identifier_name |
utils.js | import fs from "node:fs";
import readline from "node:readline";
import chalk from "chalk";
import { execa } from "execa";
import stringWidth from "string-width";
import fetch from "node-fetch";
import outdent from "outdent";
import getFormattedDate from "./get-formatted-date.js";
readline.emitKeypressEvents(process.st... |
async function fetchText(url) {
const response = await fetch(url);
return response.text();
}
function getBlogPostInfo(version) {
const { year, month, day } = getFormattedDate();
return {
file: `website/blog/${year}-${month}-${day}-${version}.md`,
path: `blog/${year}/${month}/${day}/${version}.html`,... | {
const content = fs.readFileSync(filename, "utf-8");
fs.writeFileSync(filename, fn(content));
} | identifier_body |
debugging.js | /*
* Flocking Debugging Unit Generators
* http://github.com/colinbdclark/flocking
*
* Copyright 2011-2014, Colin Clark
* Dual licensed under the MIT and GPL Version 2 licenses.
*/
/*global require*/
/*jshint white: false, newcap: true, regexp: true, browser: true,
forin: false, nomen: true, bitwise: false, m... |
m.value = m.unscaledValue = val;
};
that.init = function () {
var o = that.options;
that.model.label = o.label ? o.label + ": " : "";
that.onInputChanged();
};
that.init();
return that;
};
flock.ugenDefaults("flock.ugen... | {
if (m.counter >= m.sampInterval) {
fluid.log(fluid.logLevel.IMPORTANT, label + source[j]);
m.counter = 0;
}
m.counter++;
out[i] = val = source[i];
} | conditional_block |
debugging.js | /*
* Flocking Debugging Unit Generators
* http://github.com/colinbdclark/flocking
*
* Copyright 2011-2014, Colin Clark
* Dual licensed under the MIT and GPL Version 2 licenses.
*/
/*global require*/
/*jshint white: false, newcap: true, regexp: true, browser: true,
forin: false, nomen: true, bitwise: false, m... | }
if (m.freq !== freq) {
m.sampInterval = Math.round(m.sampleRate / freq);
m.freq = freq;
m.counter = m.sampInterval;
}
for (i = 0, j = 0 ; i < numSamps; i++, j += m.strides.source) {
if (m.counter >= m.sam... | val;
if (trig > 0.0 && m.prevTrig <= 0.0) {
fluid.log(fluid.logLevel.IMPORTANT, label + source); | random_line_split |
tabs-demo.ts | import {Component, ViewEncapsulation} from '@angular/core';
import {Router} from '@angular/router';
import {Observable} from 'rxjs/Observable';
@Component({
moduleId: module.id,
selector: 'tabs-demo',
templateUrl: 'tabs-demo.html',
styleUrls: ['tabs-demo.css'],
encapsulation: ViewEncapsulation.None,
})
expor... | {
// Nav bar demo
tabLinks = [
{label: 'Sun', link: 'sunny-tab'},
{label: 'Rain', link: 'rainy-tab'},
{label: 'Fog', link: 'foggy-tab'},
];
activeLinkIndex = 0;
// Standard tabs demo
tabs = [
{
label: 'Tab 1',
content: 'This is the body of the first tab'
}, {
label: '... | TabsDemo | identifier_name |
tabs-demo.ts | import {Component, ViewEncapsulation} from '@angular/core';
import {Router} from '@angular/router';
import {Observable} from 'rxjs/Observable';
@Component({
moduleId: module.id,
selector: 'tabs-demo',
templateUrl: 'tabs-demo.html',
styleUrls: ['tabs-demo.css'],
encapsulation: ViewEncapsulation.None,
})
expor... |
}
deleteTab(tab: any) {
this.dynamicTabs.splice(this.dynamicTabs.indexOf(tab), 1);
}
}
@Component({
moduleId: module.id,
selector: 'sunny-routed-content',
template: 'This is the routed body of the sunny tab.',
})
export class SunnyTabContent {}
@Component({
moduleId: module.id,
selector: 'rain... | {
this.activeTabIndex = this.addTabPosition;
} | conditional_block |
tabs-demo.ts | import {Component, ViewEncapsulation} from '@angular/core';
import {Router} from '@angular/router';
import {Observable} from 'rxjs/Observable';
@Component({
moduleId: module.id,
selector: 'tabs-demo',
templateUrl: 'tabs-demo.html',
styleUrls: ['tabs-demo.css'],
encapsulation: ViewEncapsulation.None,
})
expor... | moduleId: module.id,
selector: 'rainy-routed-content',
template: 'This is the routed body of the rainy tab.',
})
export class RainyTabContent {}
@Component({
moduleId: module.id,
selector: 'foggy-routed-content',
template: 'This is the routed body of the foggy tab.',
})
export class FoggyTabContent {} | export class SunnyTabContent {}
@Component({ | random_line_split |
tabs-demo.ts | import {Component, ViewEncapsulation} from '@angular/core';
import {Router} from '@angular/router';
import {Observable} from 'rxjs/Observable';
@Component({
moduleId: module.id,
selector: 'tabs-demo',
templateUrl: 'tabs-demo.html',
styleUrls: ['tabs-demo.css'],
encapsulation: ViewEncapsulation.None,
})
expor... |
}
@Component({
moduleId: module.id,
selector: 'sunny-routed-content',
template: 'This is the routed body of the sunny tab.',
})
export class SunnyTabContent {}
@Component({
moduleId: module.id,
selector: 'rainy-routed-content',
template: 'This is the routed body of the rainy tab.',
})
export class Rain... | {
this.dynamicTabs.splice(this.dynamicTabs.indexOf(tab), 1);
} | identifier_body |
PrintViewerCore.view.tsx | import React, { useEffect, useLayoutEffect, useRef, useState } from 'react'
import { useAsync, useAsyncCallback } from 'react-async-hook';
import initSlicerRender, { start } from 'slicer-render';
import Typography from '@mui/material/Typography'
import Button from '@mui/material/Button'
import Slider from '@mui/materi... |
if (printFile == null) {
return true
}
let res
try {
res = await fetch(printFile.url)
} catch (e) {
console.warn('Unable to load user input file. Most likely a page reload, rendering nothing.');
return true
}
renderer.send('reset');
if (printFile.isMesh) {
... | {
return
} | conditional_block |
PrintViewerCore.view.tsx | import React, { useEffect, useLayoutEffect, useRef, useState } from 'react'
import { useAsync, useAsyncCallback } from 'react-async-hook';
import initSlicerRender, { start } from 'slicer-render';
import Typography from '@mui/material/Typography'
import Button from '@mui/material/Button'
import Slider from '@mui/materi... | ({
renderer,
setData,
data,
viewMode,
})}
{/* Loading Spinner */}
{ loading && (
<Box sx={{
display: 'grid',
overflow: 'hidden',
gridArea: 'main',
justifyItems: 'center',
... | renderOverlay | identifier_name |
PrintViewerCore.view.tsx | import React, { useEffect, useLayoutEffect, useRef, useState } from 'react'
import { useAsync, useAsyncCallback } from 'react-async-hook';
import initSlicerRender, { start } from 'slicer-render';
import Typography from '@mui/material/Typography'
import Button from '@mui/material/Button'
import Slider from '@mui/materi... |
{ loading && (
<Box sx={{
display: 'grid',
overflow: 'hidden',
gridArea: 'main',
justifyItems: 'center',
alignItems: 'center',
marginBottom: '100px',
}}>
<CircularProgress disableShrink /... | {/* Loading Spinner */} | identifier_body |
PrintViewerCore.view.tsx | import React, { useEffect, useLayoutEffect, useRef, useState } from 'react'
import { useAsync, useAsyncCallback } from 'react-async-hook';
import initSlicerRender, { start } from 'slicer-render';
import Typography from '@mui/material/Typography'
import Button from '@mui/material/Button'
import Slider from '@mui/materi... | md: `${(80+53) / 2 - 16}px`,
xs: -2,
},
zIndex: 1,
marginBottom: -500,
}}
/>
</Box>
</Box>
</Box>
</Box>
)
}
export default PrintViewerCore | margin: -2,
marginLeft: { md: `${-drawerWidth / 2 - 16}px` },
// Offset for top navigation
marginTop: { | random_line_split |
quicktags.js | /******************************************************************************
* *
* This file is part of RPB Chessboard, a WordPress plugin. *
* Copyright (C) 2013-2016 Yoann Le Montagner <yo35 -at- melix.net> *
... |
// Register the edit-FEN button.
QTags.addButton(
'rpbchessboard-editFENButton',
RPBChessboard.i18n.EDITOR_BUTTON_LABEL,
editFENButtonCallback,
null, null,
RPBChessboard.i18n.EDIT_CHESS_DIAGRAM_DIALOG_TITLE
);
})( /* global RPBChessboard */ RPBChessboard );
| {
var info = RPBChessboard.identifyFENShortcodeContent(canvas.value, canvas.selectionStart, canvas.selectionEnd);
if(info === null) {
RPBChessboard.showEditFENDialog(editFENDialogCallback);
}
else {
canvas.selectionStart = info.beginShortcode;
canvas.selectionEnd = info.endShortcode;
RPBChessboard... | identifier_body |
quicktags.js | /******************************************************************************
* *
* This file is part of RPB Chessboard, a WordPress plugin. *
* Copyright (C) 2013-2016 Yoann Le Montagner <yo35 -at- melix.net> *
... | if(/* global QTags */ typeof QTags === 'undefined') {
return;
}
/**
* Callback for the edit-FEN dialog.
*/
function editFENDialogCallback(fen, options) {
QTags.insertContent(RPBChessboard.serializeFENShortcodeContent(fen, options));
}
/**
* Callback for the edit-FEN button.
*/
function editFENBut... | random_line_split | |
quicktags.js | /******************************************************************************
* *
* This file is part of RPB Chessboard, a WordPress plugin. *
* Copyright (C) 2013-2016 Yoann Le Montagner <yo35 -at- melix.net> *
... |
}
// Register the edit-FEN button.
QTags.addButton(
'rpbchessboard-editFENButton',
RPBChessboard.i18n.EDITOR_BUTTON_LABEL,
editFENButtonCallback,
null, null,
RPBChessboard.i18n.EDIT_CHESS_DIAGRAM_DIALOG_TITLE
);
})( /* global RPBChessboard */ RPBChessboard );
| {
canvas.selectionStart = info.beginShortcode;
canvas.selectionEnd = info.endShortcode;
RPBChessboard.showEditFENDialog({
fen : info.fen,
options : info.options,
callback: editFENDialogCallback
});
} | conditional_block |
quicktags.js | /******************************************************************************
* *
* This file is part of RPB Chessboard, a WordPress plugin. *
* Copyright (C) 2013-2016 Yoann Le Montagner <yo35 -at- melix.net> *
... | (fen, options) {
QTags.insertContent(RPBChessboard.serializeFENShortcodeContent(fen, options));
}
/**
* Callback for the edit-FEN button.
*/
function editFENButtonCallback(button, canvas)
{
var info = RPBChessboard.identifyFENShortcodeContent(canvas.value, canvas.selectionStart, canvas.selectionEnd);
if... | editFENDialogCallback | identifier_name |
ipv4.rs | use common::get_slice::GetSlice;
use collections::slice;
use collections::vec::Vec;
use core::mem;
use network::common::*;
#[derive(Copy, Clone)]
#[repr(packed)]
pub struct Ipv4Header {
pub ver_hlen: u8,
pub services: u8,
pub len: n16,
pub id: n16,
pub flags_fragment: n16,
pub ttl: u8,
p... | impl FromBytes for Ipv4 {
fn from_bytes(bytes: Vec<u8>) -> Option<Self> {
if bytes.len() >= mem::size_of::<Ipv4Header>() {
unsafe {
let header = *(bytes.as_ptr() as *const Ipv4Header);
let header_len = ((header.ver_hlen & 0xF) << 2) as usize;
retu... | }
| random_line_split |
ipv4.rs | use common::get_slice::GetSlice;
use collections::slice;
use collections::vec::Vec;
use core::mem;
use network::common::*;
#[derive(Copy, Clone)]
#[repr(packed)]
pub struct Ipv4Header {
pub ver_hlen: u8,
pub services: u8,
pub len: n16,
pub id: n16,
pub flags_fragment: n16,
pub ttl: u8,
p... |
None
}
}
impl ToBytes for Ipv4 {
fn to_bytes(&self) -> Vec<u8> {
unsafe {
let header_ptr: *const Ipv4Header = &self.header;
let mut ret = Vec::<u8>::from(slice::from_raw_parts(header_ptr as *const u8,
mem::... | {
unsafe {
let header = *(bytes.as_ptr() as *const Ipv4Header);
let header_len = ((header.ver_hlen & 0xF) << 2) as usize;
return Some(Ipv4 {
header: header,
options: bytes.get_slice(Some(mem::size_of::<Ipv4Header>()), S... | conditional_block |
ipv4.rs | use common::get_slice::GetSlice;
use collections::slice;
use collections::vec::Vec;
use core::mem;
use network::common::*;
#[derive(Copy, Clone)]
#[repr(packed)]
pub struct | {
pub ver_hlen: u8,
pub services: u8,
pub len: n16,
pub id: n16,
pub flags_fragment: n16,
pub ttl: u8,
pub proto: u8,
pub checksum: Checksum,
pub src: Ipv4Addr,
pub dst: Ipv4Addr,
}
pub struct Ipv4 {
pub header: Ipv4Header,
pub options: Vec<u8>,
pub data: Vec<u8>,
}... | Ipv4Header | identifier_name |
ipv4.rs | use common::get_slice::GetSlice;
use collections::slice;
use collections::vec::Vec;
use core::mem;
use network::common::*;
#[derive(Copy, Clone)]
#[repr(packed)]
pub struct Ipv4Header {
pub ver_hlen: u8,
pub services: u8,
pub len: n16,
pub id: n16,
pub flags_fragment: n16,
pub ttl: u8,
p... |
}
impl ToBytes for Ipv4 {
fn to_bytes(&self) -> Vec<u8> {
unsafe {
let header_ptr: *const Ipv4Header = &self.header;
let mut ret = Vec::<u8>::from(slice::from_raw_parts(header_ptr as *const u8,
mem::size_of::<Ipv4Heade... | {
if bytes.len() >= mem::size_of::<Ipv4Header>() {
unsafe {
let header = *(bytes.as_ptr() as *const Ipv4Header);
let header_len = ((header.ver_hlen & 0xF) << 2) as usize;
return Some(Ipv4 {
header: header,
optio... | identifier_body |
MedianUI.py | ##########################################################################
#
# Copyright (c) 2017, Image Engine Design Inc. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistrib... | ##########################################################################
import Gaffer
import GafferImage
# Command suitable for use with `NodeMenu.append()`.
def nodeMenuCreateCommand( menu ) :
median = GafferImage.Median()
median["radius"].gang()
return median
Gaffer.Metadata.registerNode(
GafferImage.Medi... | # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
# | random_line_split |
MedianUI.py | ##########################################################################
#
# Copyright (c) 2017, Image Engine Design Inc. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistrib... |
Gaffer.Metadata.registerNode(
GafferImage.Median,
"description",
"""
Applies a median filter to the image. This can be useful for
removing noise.
""",
)
| median = GafferImage.Median()
median["radius"].gang()
return median | identifier_body |
MedianUI.py | ##########################################################################
#
# Copyright (c) 2017, Image Engine Design Inc. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistrib... | ( menu ) :
median = GafferImage.Median()
median["radius"].gang()
return median
Gaffer.Metadata.registerNode(
GafferImage.Median,
"description",
"""
Applies a median filter to the image. This can be useful for
removing noise.
""",
)
| nodeMenuCreateCommand | identifier_name |
theme.service.ts | /* Copyright (c) 2014-2021 Jason Ish
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of condi... | (): string {
let theme = this.settings.get(SETTING_THEME);
if (!theme) {
theme = "default";
}
return theme;
}
setTheme(theme: string): void {
switch (theme) {
case "dark":
document.getElementsByTagName("html")[0].setAttribute("clas... | currentTheme | identifier_name |
theme.service.ts | /* Copyright (c) 2014-2021 Jason Ish
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of condi... |
setTheme(theme: string): void {
switch (theme) {
case "dark":
document.getElementsByTagName("html")[0].setAttribute("class", "dark dark-mode");
//Chart.defaults.global.defaultFontColor = "#fff";
Chart.defaults.color = "#fff";
brea... | {
let theme = this.settings.get(SETTING_THEME);
if (!theme) {
theme = "default";
}
return theme;
} | identifier_body |
theme.service.ts | /* Copyright (c) 2014-2021 Jason Ish
* All rights reserved. | *
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other m... | *
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met: | random_line_split |
theme.service.ts | /* Copyright (c) 2014-2021 Jason Ish
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of condi... |
return theme;
}
setTheme(theme: string): void {
switch (theme) {
case "dark":
document.getElementsByTagName("html")[0].setAttribute("class", "dark dark-mode");
//Chart.defaults.global.defaultFontColor = "#fff";
Chart.defaults.color = ... | {
theme = "default";
} | conditional_block |
text.rs | // The MIT License (MIT)
//
// Copyright (c) 2014 Jeremy Letang (letang.jeremy@gmail.com)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitati... | {
pub x: i32,
pub y: i32,
pub text: String,
pub attribs: HashMap<String, String>,
pub transform: Option<Transform>
}
impl SVGEntity for Text {
fn gen_output(&self) -> String {
let mut o = String::new();
o.push_str(format!("<text x=\"{}\" y=\"{}\"",
se... | Text | identifier_name |
text.rs | // The MIT License (MIT)
//
// Copyright (c) 2014 Jeremy Letang (letang.jeremy@gmail.com)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitati... | } | o
} | random_line_split |
extract.py | .lib.base import BaseController, render
import json
import ijson
import collections, sys
import math
from urllib2 import urlopen,HTTPError
import lr.lib.helpers as h
log = logging.getLogger(__name__)
import couchdb
class ExtractController(BaseController):
"""REST Controller styled on the Atom Publishing Protocol"""... | (self,view='_all_docs',keys=[], includeDocs=True,startKey=None,endKey=None):
args = {'include_docs':includeDocs}
if len(keys) > 0:
args['keys'] = keys
args['reduce'] = False
args['stale'] = appConfig['couchdb.stale.flag']
if startKey is not None:
args['sta... | _getView | identifier_name |
extract.py | lr.lib.base import BaseController, render
import json
import ijson
import collections, sys
import math
from urllib2 import urlopen,HTTPError
import lr.lib.helpers as h
log = logging.getLogger(__name__)
import couchdb
class ExtractController(BaseController):
"""REST Controller styled on the Atom Publishing Protocol... |
def populateTs(startKey, endKey, pos, isLast):
if 'from' in params:
startKey.append(self._convertDateTime(params['from']))
elif pos == 1:
startKey.append(self._convertDateTime(datetime.min.isoformat() + "Z"))
if 'until' in params:
... | if funcName == 'ts' and ('from' in params or 'until' in params):
return True
elif funcName == 'discriminator' and ('discriminator' in params or 'discriminator-starts-with' in params):
return True
elif funcName == 'resource' and ('resource' in params or 'resource-s... | identifier_body |
extract.py | .lib.base import BaseController, render
import json
import ijson
import collections, sys
import math
from urllib2 import urlopen,HTTPError
import lr.lib.helpers as h
log = logging.getLogger(__name__)
import couchdb
class ExtractController(BaseController):
"""REST Controller styled on the Atom Publishing Protocol"""... |
# if this is a complex key, then get the last element and recurse
elif isinstance(newkey, list):
newkey[-1] = makeStartsWithEndKey(newkey[-1])
# if the last element in an object, it becomes a bit tricky, because you must modify the last key, which implies
... | newkey=newkey+u'\ud7af' | conditional_block |
extract.py | lr.lib.base import BaseController, render
import json
import ijson
import collections, sys
import math
from urllib2 import urlopen,HTTPError
import lr.lib.helpers as h
log = logging.getLogger(__name__)
import couchdb
class ExtractController(BaseController):
"""REST Controller styled on the Atom Publishing Protocol... | startKey=[]
endKey=[]
includeDocs = True
if "ids_only" in params:
includeDocs = not params
funcs = {
"discriminator":populateDiscriminator,
'resource':populateResource,
'ts':populateTs
}
queryOrderParts = view... | # startKey.append('')
# endKey.append(u'\ud7af') | random_line_split |
du.rs |
use std::fs::{read_dir, symlink_metadata};
use std::path::{PathBuf, Path};
use std::io;
use std::env;
use std::os::unix::fs::MetadataExt;
#[derive(Debug)]
pub enum | {
File { size: u64 },
Directory { size: u64, children: Vec<Entry> },
OtherFs,
Error(io::Error),
Other,
}
#[derive(Debug)]
pub struct Entry(pub PathBuf, pub EntryData);
impl Entry {
pub fn size(&self) -> u64 {
let Entry(_, ref data) = *self;
match data {
&EntryData... | EntryData | identifier_name |
du.rs |
use std::fs::{read_dir, symlink_metadata};
use std::path::{PathBuf, Path};
use std::io;
use std::env;
use std::os::unix::fs::MetadataExt;
#[derive(Debug)]
pub enum EntryData {
File { size: u64 },
Directory { size: u64, children: Vec<Entry> },
OtherFs,
Error(io::Error),
Other,
}
#[derive(Debug)]
p... | if m.is_file() {
return Entry(name, EntryData::File { size: m.len() });
} else if m.is_dir() {
let cwd = env::current_dir().unwrap();
if let Err(err) = env::set_current_dir(&name) {
return Entry(name, EntryData::Error(err));
}
let dir_list = read_dir(".");
... | {
let m = symlink_metadata(name);
let name = PathBuf::from(name);
if let Err(err) = m {
return Entry(name, EntryData::Error(err));
}
let m = m.unwrap();
let mdev = m.dev();
let dev = dev.unwrap_or(if xfs { mdev } else { 0 });
if xfs && mdev != dev {
return Entry(na... | identifier_body |
du.rs | use std::fs::{read_dir, symlink_metadata};
use std::path::{PathBuf, Path};
use std::io;
use std::env;
use std::os::unix::fs::MetadataExt;
#[derive(Debug)]
pub enum EntryData {
File { size: u64 },
Directory { size: u64, children: Vec<Entry> },
OtherFs,
Error(io::Error),
Other,
}
#[derive(Debug)]
pu... | match data {
&EntryData::File{size} => size,
&EntryData::Directory{size, ..} => size,
_ => 0
}
}
}
pub fn process_entry(name: &Path, xfs: bool, dev: Option<u64>) -> Entry {
let m = symlink_metadata(name);
let name = PathBuf::from(name);
if let Err... | impl Entry {
pub fn size(&self) -> u64 {
let Entry(_, ref data) = *self;
| random_line_split |
du.rs |
use std::fs::{read_dir, symlink_metadata};
use std::path::{PathBuf, Path};
use std::io;
use std::env;
use std::os::unix::fs::MetadataExt;
#[derive(Debug)]
pub enum EntryData {
File { size: u64 },
Directory { size: u64, children: Vec<Entry> },
OtherFs,
Error(io::Error),
Other,
}
#[derive(Debug)]
p... |
}
| {
return Entry(name, EntryData::Other);
} | conditional_block |
lib.rs | #![allow(unknown_lints)] // Allow clippy lints.
extern crate alga;
extern crate arrayvec;
extern crate decorum;
#[macro_use]
extern crate failure;
#[macro_use]
extern crate gfx;
extern crate gfx_device_gl;
extern crate gfx_window_glutin;
extern crate glutin;
extern crate image;
#[macro_use]
extern crate lazy_static;
e... | <F>(mut self, f: F) -> Self
where
F: Fn(&T) -> bool,
{
match self.take() {
Some(value) => if f(&value) {
Some(value)
}
else {
None
},
_ => None,
}
}
}
| and_if | identifier_name |
lib.rs | #![allow(unknown_lints)] // Allow clippy lints.
extern crate alga;
extern crate arrayvec;
extern crate decorum;
#[macro_use]
extern crate failure;
#[macro_use]
extern crate gfx;
extern crate gfx_device_gl;
extern crate gfx_window_glutin;
extern crate glutin;
extern crate image;
#[macro_use]
extern crate lazy_static;
e... | Some(value) => if f(&value) {
Some(value)
}
else {
None
},
_ => None,
}
}
} | fn and_if<F>(mut self, f: F) -> Self
where
F: Fn(&T) -> bool,
{
match self.take() { | random_line_split |
lib.rs | #![allow(unknown_lints)] // Allow clippy lints.
extern crate alga;
extern crate arrayvec;
extern crate decorum;
#[macro_use]
extern crate failure;
#[macro_use]
extern crate gfx;
extern crate gfx_device_gl;
extern crate gfx_window_glutin;
extern crate glutin;
extern crate image;
#[macro_use]
extern crate lazy_static;
e... |
}
pub trait OptionExt<T> {
fn and_if<F>(self, f: F) -> Self
where
F: Fn(&T) -> bool;
}
impl<T> OptionExt<T> for Option<T> {
fn and_if<F>(mut self, f: F) -> Self
where
F: Fn(&T) -> bool,
{
match self.take() {
Some(value) => if f(&value) {
Some(va... | {
if self {
Some(some)
}
else {
None
}
} | identifier_body |
EditCounterNoBots.py | #!/usr/bin/python
# Abbas (Ar:User:Elph), 2012 | import wikipedia,urllib,gzip,codecs,re
import MySQLdb as mysqldb
import config
pagetop=u"'''تاریخ آخری تجدید:''''': ~~~~~ '''بذریعہ:''' [[user:{{subst:Currentuser}}|{{subst:Currentuser}}]]''\n\n"
pagetop+=u'\nفہرست 100 بلند پایہ صارفین بلحاظ شراکت بدون روبہ جات۔\n'
pagetop+=u'\nمزید دیکھیں: [[ویکیپیڈیا:رودادہائے ڈیٹابی... | # -*- coding: utf-8 -*-
import catlib ,pagegenerators | random_line_split |
EditCounterNoBots.py | #!/usr/bin/python
# Abbas (Ar:User:Elph), 2012
# -*- coding: utf-8 -*-
import catlib ,pagegenerators
import wikipedia,urllib,gzip,codecs,re
import MySQLdb as mysqldb
import config
pagetop=u"'''تاریخ آخری تجدید:''''': ~~~~~ '''بذریعہ:''' [[user:{{subst:Currentuser}}|{{subst:Currentuser}}]]''\n\n"
pagetop+=u'\nفہرست 10... | text=rowfa.strip()
text=pagetop+text+pagedown
page = wikipedia.Page(site,adress)
page.put(text,message)
| conditional_block | |
reentrant.rs | //! Module to handle reentrant/recursion limits while deserializing.
use std::cell::Cell;
use std::rc::Rc; | /// not do any synchronization -- it is intended purely for single-threaded use.
pub struct ReentrantLimit(Rc<Cell<usize>>);
impl ReentrantLimit {
/// Create a new reentrant limit.
pub fn new(limit: usize) -> Self {
ReentrantLimit(Rc::new(Cell::new(limit)))
}
/// Try to decrease the limit by 1... |
use crate::errors::*;
/// Sets a limit on the amount of recursion during deserialization. This does | random_line_split |
reentrant.rs | //! Module to handle reentrant/recursion limits while deserializing.
use std::cell::Cell;
use std::rc::Rc;
use crate::errors::*;
/// Sets a limit on the amount of recursion during deserialization. This does
/// not do any synchronization -- it is intended purely for single-threaded use.
pub struct ReentrantLimit(Rc<... | (limit: usize) -> Self {
ReentrantLimit(Rc::new(Cell::new(limit)))
}
/// Try to decrease the limit by 1. Return an RAII guard that when freed
/// will increase the limit by 1.
pub fn acquire<S: Into<String>>(&mut self, kind: S) -> Result<ReentrantGuard> {
if self.0.get() == 0 {
... | new | identifier_name |
reentrant.rs | //! Module to handle reentrant/recursion limits while deserializing.
use std::cell::Cell;
use std::rc::Rc;
use crate::errors::*;
/// Sets a limit on the amount of recursion during deserialization. This does
/// not do any synchronization -- it is intended purely for single-threaded use.
pub struct ReentrantLimit(Rc<... |
self.0.set(self.0.get() - 1);
Ok(ReentrantGuard(self.0.clone()))
}
}
/// RAII guard for reentrant limits.
pub struct ReentrantGuard(Rc<Cell<usize>>);
impl Drop for ReentrantGuard {
fn drop(&mut self) {
self.0.set(self.0.get() + 1);
}
}
| {
bail!(ErrorKind::DeRecursionLimitExceeded(kind.into()));
} | conditional_block |
ack.py | # Copyright 2015 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or ag... | (base.Command):
"""Acknowledges one or more messages on the specified subscription.
Acknowledges one or more messages as having been successfully received.
If a delivered message is not acknowledged, Cloud Pub/Sub will attempt to
deliver it again.
"""
@staticmethod
def Args(parser):
"""Register flag... | Ack | identifier_name |
ack.py | # Copyright 2015 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or ag... | return util.SUBSCRIPTIONS_ACK_COLLECTION
def Run(self, args):
"""This is what gets called when the user runs this command.
Args:
args: an argparse namespace. All the arguments that were provided to this
command invocation.
Returns:
Ack display dictionary with information about t... | def Collection(self): | random_line_split |
ack.py | # Copyright 2015 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or ag... |
def Collection(self):
return util.SUBSCRIPTIONS_ACK_COLLECTION
def Run(self, args):
"""This is what gets called when the user runs this command.
Args:
args: an argparse namespace. All the arguments that were provided to this
command invocation.
Returns:
Ack display dictionar... | """Register flags for this command."""
parser.add_argument('subscription',
help='Subscription name to ACK messages on.')
parser.add_argument('ackid', nargs='+',
help='One or more AckId to acknowledge.') | identifier_body |
ApiViewport.js | Ext.ns('Docs');
Docs.ApiViewport = Ext.extend(Ext.Viewport, {
constructor : function(cfg) {
cfg = Ext.apply(cfg ||{}, {
layout:'border',
items : this.buildItems()
});
this.constructor.superclass.constructor.call(this,cfg);
},
buildItems : function() {
... |
this.doLayout();
},
onApiTreePanelClick : function(node, evtObj) {
if(node.isLeaf()){
evtObj.stopEvent();
this.getApiTabPanel().loadClass(node.attributes.href, node.id);
}
},
onApiTabPanelTabChange : function(tp, tab){
this.getApiTreePanel().selectC... | {
var ps = Ext.urlDecode(page),
cls = ps['class'];
this.getApiTabPanel().loadClass('output/' + cls + '.html', cls, ps.member);
} | conditional_block |
ApiViewport.js | Ext.ns('Docs');
Docs.ApiViewport = Ext.extend(Ext.Viewport, {
constructor : function(cfg) {
cfg = Ext.apply(cfg ||{}, {
layout:'border',
items : this.buildItems()
});
this.constructor.superclass.constructor.call(this,cfg);
},
buildItems : function() {
... | margins:'0 0 5 5',
cmargins:'0 0 0 0',
collapsible: true,
collapseMode:'mini',
listeners : {
scope : this,
click : this.onApiTreePanelClick,
afterrender : function(treePanel) {
... | region:'west',
split:true,
width: 280,
minSize: 175,
maxSize: 500, | random_line_split |
JsonpErrorHandlerPlugin.js | ` with jsonp error handling logic.
*/
JsonpErrorHandlerPlugin.prototype.patchJsonpMainTemplatePlugin = function() {
JsonpMainTemplatePlugin.prototype.apply = this._apply;
JsonpErrorHandlerPlugin.prototype.patched = true;
};
/**
* Adds the error handling logic by tapping into the main template plugin hooks.
* This... | {
var head = document.getElementsByTagName('head')[0];
var script = document.createElement('script');
script.type = 'text/javascript';
script.charset = 'utf-8';
script.src = $require$.p + $hotChunkFilename$;
head.appendChild(script);
} | identifier_body | |
JsonpErrorHandlerPlugin.js | pMainTemplatePlugin();
}
};
/**
* Patches the `JsonpMainTemplatePlugin` with jsonp error handling logic.
*/
JsonpErrorHandlerPlugin.prototype.patchJsonpMainTemplatePlugin = function() {
JsonpMainTemplatePlugin.prototype.apply = this._apply;
JsonpErrorHandlerPlugin.prototype.patched = true;
};
/**
* Adds the err... | (chunkId) {
var head = document.getElementsByTagName('head')[0];
var script = document.createElement('script');
script.type = 'text/javascript';
script.charset = 'utf-8';
script.src = | hotDownloadUpdateChunk | identifier_name |
JsonpErrorHandlerPlugin.js | .
* This is mostly taken from 'webpack/lib/JsonpMainTemplatePlugin'.
* @param {MainTemplate} mainTemplate The main template.
*/
JsonpErrorHandlerPlugin.prototype._apply = function(mainTemplate) {
mainTemplate.plugin("local-vars", function(source, chunk, hash) {
if(chunk.chunks.length > 0) {
return this.asStri... | var requestPath = $require$.p + $hotMainFilename$;
request.open("GET", requestPath, true); | random_line_split | |
libtodaytodolistplugin.ts | <!DOCTYPE TS><TS>
<context>
<name>QObject</name>
<message>
<source>Todolist plugin</source>
<translation>Todolist plugin</translation>
</message>
<message>
<source>There is <b> 1</b> active task: <br></source>
<translation>Es gibt <b> 1</b> ... | </message>
</context>
<context>
<name>TodoPluginConfigBase</name>
<message>
<source>Set the maximum number of task that should be shown</source>
<translation>Setzt die Zahl der maximal angezeigten Aufgaben</translation>
</message>
<message>
<source>tasks shown</source>
... | random_line_split | |
description.py | # ----------------------------------------------------------------------
# Numenta Platform for Intelligent Computing (NuPIC)
# Copyright (C) 2013, Numenta, Inc. Unless you have purchased from
# Numenta, Inc. a separate commercial license for this software code, the
# following terms and conditions apply:
#
# This pro... | sensorVerbosity=0,
spVerbosity=0,
tpVerbosity=0,
ppVerbosity=2,
filenameTrain = 'confidence/confidence2.csv',
filenameTest = 'confidence/confidence2.csv',
iterationCountTrain=None,
iterationCo... | from nupic.frameworks.prediction.helpers import importBaseDescription
config = dict( | random_line_split |
read-exif-exifread.py | #!/usr/bin/env python
# python-gphoto2 - Python interface to libgphoto2
# http://github.com/jim-easterbrook/python-gphoto2
# Copyright (C) 2015-19 Jim Easterbrook jim@jim-easterbrook.me.uk
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License ... |
print('File list')
print('=========')
for path in files[:10]:
print(path)
print('...')
for path in files[-10:]:
print(path)
print()
print('Exif data')
print('=========')
for path in files:
if os.path.splitext(path)[1].lower() != '.jpg':
continue
... | print('No files found')
return 1 | conditional_block |
read-exif-exifread.py | #!/usr/bin/env python
# python-gphoto2 - Python interface to libgphoto2
# http://github.com/jim-easterbrook/python-gphoto2
# Copyright (C) 2015-19 Jim Easterbrook jim@jim-easterbrook.me.uk
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License ... | ():
logging.basicConfig(
format='%(levelname)s: %(name)s: %(message)s', level=logging.WARNING)
callback_obj = gp.check_result(gp.use_python_logging())
camera = gp.Camera()
camera.init()
files = list_files(camera)
if not files:
print('No files found')
return 1
print('F... | main | identifier_name |
read-exif-exifread.py | #!/usr/bin/env python
# python-gphoto2 - Python interface to libgphoto2
# http://github.com/jim-easterbrook/python-gphoto2
# Copyright (C) 2015-19 Jim Easterbrook jim@jim-easterbrook.me.uk
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License ... | import sys
import exifread
import gphoto2 as gp
def list_files(camera, path='/'):
result = []
# get files
for name, value in camera.folder_list_files(path):
result.append(os.path.join(path, name))
# read folders
folders = []
for name, value in camera.folder_list_folders(path):
... | import logging
import os | random_line_split |
read-exif-exifread.py | #!/usr/bin/env python
# python-gphoto2 - Python interface to libgphoto2
# http://github.com/jim-easterbrook/python-gphoto2
# Copyright (C) 2015-19 Jim Easterbrook jim@jim-easterbrook.me.uk
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License ... |
def tell(self):
return self._ptr
def get_file_exif(camera, path):
pf = PseudoFile(camera, path)
return exifread.process_file(pf)
def main():
logging.basicConfig(
format='%(levelname)s: %(name)s: %(message)s', level=logging.WARNING)
callback_obj = gp.check_result(gp.use_python_log... | if whence == 0:
self._ptr = offset
elif whence == 1:
self._ptr += offset
else:
self._ptr = self._size - self.ptr | identifier_body |
mylib.js | var EPG = {
pressLeft : function() {
},
pressRight : function() {
},
pressUp : function() {
var element = document.getElementsByClassName("selected")[0];
var previousSiblingElement = element.previousElementSibling;
if (null != previousSiblingElement) {
classList(element).remove("selected");
classList(p... | }
}; | var gameId = document.getElementsByClassName("selected")[0].id;
window.location.href = "http://39.98.243.254:8080/lobby/game.jsp?gamename="
+ gameId; | random_line_split |
mylib.js | var EPG = {
pressLeft : function() {
},
pressRight : function() {
},
pressUp : function() {
var element = document.getElementsByClassName("selected")[0];
var previousSiblingElement = element.previousElementSibling;
if (null != previousSiblingElement) {
classList(element).remove("selected");
classList(p... |
},
pressEnter : function() {
var gameId = document.getElementsByClassName("selected")[0].id;
window.location.href = "http://39.98.243.254:8080/lobby/game.jsp?gamename="
+ gameId;
}
};
| {
classList(element).remove("selected");
classList(nextSiblingElement).add("selected");
} | conditional_block |
test_long_future.py | -rounded true division for integers."""
negative = a^b < 0
a, b = abs(a), abs(b)
# exceptions: division by zero, overflow
if not b:
raise ZeroDivisionError("division by zero")
if a >= DBL_MIN_OVERFLOW * b:
raise OverflowError("int/int too large to represent as a float")
# find ... | (self):
huge = 1L << 40000
mhuge = -huge
self.assertEqual(huge / huge, 1.0)
self.assertEqual(mhuge / mhuge, 1.0)
self.assertEqual(huge / mhuge, -1.0)
self.assertEqual(mhuge / huge, -1.0)
self.assertEqual(1 / huge, 0.0)
self.assertEqual(1L / huge, 0.0)
... | test | identifier_name |
test_long_future.py | -rounded true division for integers."""
negative = a^b < 0
a, b = abs(a), abs(b)
# exceptions: division by zero, overflow
if not b:
raise ZeroDivisionError("division by zero")
if a >= DBL_MIN_OVERFLOW * b:
raise OverflowError("int/int too large to represent as a float")
# find ... | self.assertEqual((666 * huge + (huge >> 1)) / huge, 666.5)
self.assertEqual((666 * mhuge + (mhuge >> 1)) / mhuge, 666.5)
self.assertEqual((666 * huge + (huge >> 1)) / mhuge, -666.5)
self.assertEqual((666 * mhuge + (mhuge >> 1)) / huge, -666.5)
self.assertEqual(huge / (huge << 1),... | random_line_split | |
test_long_future.py | -rounded true division for integers."""
negative = a^b < 0
a, b = abs(a), abs(b)
# exceptions: division by zero, overflow
if not b:
raise ZeroDivisionError("division by zero")
if a >= DBL_MIN_OVERFLOW * b:
raise OverflowError("int/int too large to represent as a float")
# find ... | # overflow corner case
for m in [1, 2, 7, 17, 12345, 7**100,
-1, -2, -5, -23, -67891, -41**50]:
for n in range(-10, 10):
self.check_truediv(m*DBL_MIN_OVERFLOW + n, m)
self.check_truediv(m*DBL_MIN_OVERFLOW + n, -m)
# check detection o... | self.check_truediv(123, 0)
self.check_truediv(-456, 0)
self.check_truediv(0, 3)
self.check_truediv(0, -3)
self.check_truediv(0, 0)
# ... overflow or underflow by large margin
self.check_truediv(671 * 12345 * 2**DBL_MAX_EXP, 12345)
self.check_truediv(12345, 345678 ... | identifier_body |
test_long_future.py | -rounded true division for integers."""
negative = a^b < 0
a, b = abs(a), abs(b)
# exceptions: division by zero, overflow
if not b:
raise ZeroDivisionError("division by zero")
if a >= DBL_MIN_OVERFLOW * b:
raise OverflowError("int/int too large to represent as a float")
# find ... |
# compute 2**-exp * a / b for suitable exp
exp = max(d, DBL_MIN_EXP) - DBL_MANT_DIG
a, b = a << max(-exp, 0), b << max(exp, 0)
q, r = divmod(a, b)
# round-half-to-even: fractional part is r/b, which is > 0.5 iff
# 2*r > b, and == 0.5 iff 2*r == b.
if 2*r > b or 2*r == b and q % 2 == 1:
... | d += 1 | conditional_block |
base.py | )
def save_item(self, key, value, save=True, metadata=None, **kwargs):
"""Set one item in json"""
_json = self.json
if metadata:
if metadata not in _json:
_json[metadata] = {}
_json[metadata][key] = value
else:
_json[key] = value
... |
_json[metadata].update(key_value)
else:
_json.update(key_value)
self.json = _json
if save:
return self.save()
else:
return True
def delete_item(self, key, save=True, metadata=None, **kwargs):
"""Set one item in json"""
... | _json[metadata] = {} | conditional_block |
base.py | )
def save_item(self, key, value, save=True, metadata=None, **kwargs):
"""Set one item in json"""
_json = self.json
if metadata:
if metadata not in _json:
_json[metadata] = {}
_json[metadata][key] = value
else:
_json[key] = value
... | _json = self.json
try:
if metadata:
if metadata in _json:
del _json[metadata][key]
else:
del _json[key]
except KeyError:
pass
self.json = _json
if save:
return self.save(**kwarg... | def delete_item(self, key, save=True, metadata=None, **kwargs):
"""Set one item in json""" | random_line_split |
base.py | )
def save_item(self, key, value, save=True, metadata=None, **kwargs):
"""Set one item in json"""
_json = self.json
if metadata:
if metadata not in _json:
_json[metadata] = {}
_json[metadata][key] = value
else:
_json[key] = value
... |
# ostype = models.SmallIntegerField(_('Guest OS type'), choices=OSTYPE)
class _HVMType(models.Model):
"""
Abstract class used for children to inherit hvm_type attributes and field.
"""
Hypervisor_KVM = 1
Hypervisor_BHYVE = 2
Hypervisor_NONE = 3 # for zones
HVM_TYPE = (
(... | app_label = 'vms'
abstract = True | identifier_body |
base.py | (self, item):
return self._data.__getitem__(item)
def get(self, key, default=None):
return self._data.get(key, default)
def update(self, data):
self._data.update(data)
class _PickleModel(models.Model):
"""
Abstract class with pickle encoding and decoding of field attributes.
... | __getitem__ | identifier_name | |
job_delete.spec.js | var expect = require('expect.js');
var Promise = require('bluebird');
var ZugZug = require('../lib/zugzug');
var Job = require('../lib/job');
describe('job.delete():Promise(self)', function() {
var zz, job;
beforeEach(function() {
zz = new ZugZug();
job = new Job(zz, 'default');
});
afterEach(function(... | job.save()
.then(function() {
expect(job.id).to.equal('1');
id = job.id;
return job.delete();
})
.then(function() {
var m = zz._client.multi()
.llen('zugzug:job:' + id + ':log');
return Promise.promisify(m.exec, m)();
})
.spread(function(newlen) {
expect... | });
it('deletes the job\'s log', function(done) {
var id; | random_line_split |
info.tsx | import { FC } from 'react'
import { FormattedMessage } from 'react-intl'
import { makeStyles } from '@material-ui/core/styles' | import Grid from '@material-ui/core/Grid'
import { DialogsContextProps } from '@/components/providers/dialogs/DialogsProvider'
export interface InfoDialogProps {
dialogs: DialogsContextProps
}
const useStyles = makeStyles(() => ({
displayWrapper: {
textAlign: 'center',
},
}))
const InfoDialog: FC<InfoDial... |
import Dialog from '@material-ui/core/Dialog'
import DialogContent from '@material-ui/core/DialogContent'
import DialogTitle from '@material-ui/core/DialogTitle' | random_line_split |
test_inlinequeryresultgame.py | #!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2017
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as publis... |
class TestInlineQueryResultGame:
id = 'id'
type = 'game'
game_short_name = 'game short name'
reply_markup = InlineKeyboardMarkup([[InlineKeyboardButton('reply_markup')]])
def test_expected_values(self, inline_query_result_game):
assert inline_query_result_game.type == self.type... | return InlineQueryResultGame(TestInlineQueryResultGame.id,
TestInlineQueryResultGame.game_short_name,
reply_markup=TestInlineQueryResultGame.reply_markup) | identifier_body |
test_inlinequeryresultgame.py | #!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2017
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as publis... | ():
return InlineQueryResultGame(TestInlineQueryResultGame.id,
TestInlineQueryResultGame.game_short_name,
reply_markup=TestInlineQueryResultGame.reply_markup)
class TestInlineQueryResultGame:
id = 'id'
type = 'game'
game_short_... | inline_query_result_game | identifier_name |
test_inlinequeryresultgame.py | #!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2017
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as publis... |
def test_equality(self):
a = InlineQueryResultGame(self.id, self.game_short_name)
b = InlineQueryResultGame(self.id, self.game_short_name)
c = InlineQueryResultGame(self.id, "")
d = InlineQueryResultGame("", self.game_short_name)
e = InlineQueryResultVoice(self.id, "",... | assert inline_query_result_game_dict['reply_markup'] == \
inline_query_result_game.reply_markup.to_dict()
| random_line_split |
method-on-generic-struct.rs | // Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... |
}
fn main() {
let stack = Struct { x: (8888_u32, -8888_i32) };
let _ = stack.self_by_ref(-1, -2);
let _ = stack.self_by_val(-3, -4);
let owned = box Struct { x: 1234.5f64 };
let _ = owned.self_by_ref(-5, -6);
let _ = owned.self_by_val(-7, -8);
let _ = owned.self_owned(-9, -10);
}
fn zzz(... | {
zzz(); // #break
arg1 + arg2
} | identifier_body |
method-on-generic-struct.rs | // Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... | (self: Box<Struct<T>>, arg1: int, arg2: int) -> int {
zzz(); // #break
arg1 + arg2
}
}
fn main() {
let stack = Struct { x: (8888_u32, -8888_i32) };
let _ = stack.self_by_ref(-1, -2);
let _ = stack.self_by_val(-3, -4);
let owned = box Struct { x: 1234.5f64 };
let _ = owned.self_... | self_owned | identifier_name |
method-on-generic-struct.rs | // Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... | // lldb-command:continue
// STACK BY VAL
// lldb-command:print self
// lldb-check:[...]$3 = Struct<(u32, i32)> { x: (8888, -8888) }
// lldb-command:print arg1
// lldb-check:[...]$4 = -3
// lldb-command:print arg2
// lldb-check:[...]$5 = -4
// lldb-command:continue
// OWNED BY REF
// lldb-command:print *self
// lldb-c... | // lldb-command:print arg1
// lldb-check:[...]$1 = -1
// lldb-command:print arg2
// lldb-check:[...]$2 = -2 | random_line_split |
attention.py | super(Conv1D, self).__init__(**kwargs)
def _allocate(self):
self.parameters = [shared_floatx_nans((self.num_filters, self.filter_length),
name="filters")]
def _initialize(self):
self.weights_init.initialize(self.parameters[0], self.rng)
def apply... | return 0 | conditional_block | |
attention.py | Attention, SequenceContentAttention,
ShallowEnergyComputer)
from blocks.utils import (put_hook, ipdb_breakpoint, shared_floatx,
shared_floatx_nans)
from lvsr.expressions import conv1d
floatX = theano.config.floatX
import logging
logger = logging.getLogger(__name__)
class Conv1D(Initi... | (self, batch_size, attended):
return ([tensor.zeros((batch_size, self.attended_dim))]
+ 2 * [tensor.concatenate([
tensor.ones((batch_size, 1)),
tensor.zeros((batch_size, attended.shape[0] - 1))],
axis=1)]
+ [tensor.zero... | initial_glimpses | identifier_name |
attention.py | Attention, SequenceContentAttention,
ShallowEnergyComputer)
from blocks.utils import (put_hook, ipdb_breakpoint, shared_floatx,
shared_floatx_nans)
from lvsr.expressions import conv1d
floatX = theano.config.floatX
import logging
logger = logging.getLogger(__name__)
class Conv1D(Initi... | energies = energies - energies.max(axis=0)
unnormalized_weights = tensor.exp(energies)
elif self.energy_normalizer == 'logistic':
logger.debug("Using smoothfocus (logistic sigm) "
"attention weights normalization")
unnormalized_weights = te... |
@application
def compute_weights(self, energies, attended_mask):
if self.energy_normalizer == 'softmax':
logger.debug("Using softmax attention weights normalization") | random_line_split |
attention.py | SequenceAttention, SequenceContentAttention,
ShallowEnergyComputer)
from blocks.utils import (put_hook, ipdb_breakpoint, shared_floatx,
shared_floatx_nans)
from lvsr.expressions import conv1d
floatX = theano.config.floatX
import logging
logger = logging.getLogger(__name__)
class Conv... |
@application
def compute_energies(self, attended, preprocessed_attended,
previous_weights, states):
if not preprocessed_attended:
preprocessed_attended = self.preprocess(attended)
transformed_states = self.state_transformers.apply(as_dict=True,
... | self.state_transformers.input_dims = self.state_dims
self.state_transformers.output_dims = [self.match_dim
for name in self.state_names]
self.attended_transformer.input_dim = self.attended_dim
self.attended_transformer.output_dim = self.match_dim
... | identifier_body |
extensionsList.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... | const builtinStatusAction = this.instantiationService.createInstance(BuiltinStatusLabelAction);
const installAction = this.instantiationService.createInstance(InstallAction);
const updateAction = this.instantiationService.createInstance(UpdateAction);
const reloadAction = this.instantiationService.createInstanc... | const versionWidget = this.instantiationService.createInstance(Label, version, (e: IExtension) => e.version);
const installCountWidget = this.instantiationService.createInstance(InstallWidget, installCount, { small: true });
const ratingsWidget = this.instantiationService.createInstance(RatingsWidget, ratings, { ... | random_line_split |
extensionsList.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... | () { return 'extension'; }
renderTemplate(root: HTMLElement): ITemplateData {
const bookmark = append(root, $('span.bookmark'));
append(bookmark, $('span.octicon.octicon-star'));
const applyBookmarkStyle = (theme) => {
const bgColor = theme.getColor(extensionButtonProminentBackground);
const fgColor = the... | templateId | identifier_name |
extensionsList.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... | const ratings = append(header, $('span.ratings'));
const description = append(details, $('.description.ellipsis'));
const footer = append(details, $('.footer'));
const author = append(footer, $('.author.ellipsis'));
const actionbar = new ActionBar(footer, {
animated: false,
actionItemProvider: (action: ... | {
const bookmark = append(root, $('span.bookmark'));
append(bookmark, $('span.octicon.octicon-star'));
const applyBookmarkStyle = (theme) => {
const bgColor = theme.getColor(extensionButtonProminentBackground);
const fgColor = theme.getColor(extensionButtonProminentForeground);
bookmark.style.borderTopCo... | identifier_body |
extensionsList.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... | else {
data.icon.style.visibility = 'inherit';
}
data.root.setAttribute('aria-label', extension.displayName);
removeClass(data.root, 'recommended');
const extRecommendations = this.extensionTipsService.getAllRecommendationsWithReason();
if (extRecommendations[extension.id.toLowerCase()]) {
data.root.... | {
data.icon.style.visibility = 'hidden';
data.icon.onload = () => data.icon.style.visibility = 'inherit';
} | conditional_block |
setup.py | from setuptools import setup, find_packages
import os
import cms
CLASSIFIERS = [
'Development Status :: 5 - Production/Stable',
'Environment :: Web Environment',
'Framework :: Django',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independ... | 'djangocms-admin-style>=1.0',
]
setup(
author='Patrick Lauber',
author_email='digi@treepy.com',
name='django-cms',
version=cms.__version__+"+nimbis.1",
description='An Advanced Django CMS',
long_description=open(os.path.join(os.path.dirname(__file__), 'README.rst')).read(),
url='https:/... | 'django-formtools>=1.0',
'django-treebeard>=4.0.1',
'django-sekizai>=0.7', | random_line_split |
setup.py | #from distutils.core import setup
import setuptools
setuptools.setup(
name = 'p3270',
packages = ['p3270'],
version = '0.1.3',
description = 'Python library to communicate with IBM hosts',
author = 'Mossaab Stiri',
author_email = 'mossaab.stiri@gmail.com',
url = ... | It is written in Python 3, runs on Linux and Unix-like Operating Systems, and relies on the `s3270` utility. So it is required to have the `s3270` installed on your system and available on your PATH.
The library allows you to open a telnet connection to an IBM host, and execute a set of instructions as you spe... | random_line_split | |
procurement.py | # -*- encoding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (c) 2013 Acysos S.L. (http://acysos.com) All Rights Reserved.
# Ignacio Ibeas <ignacio@acysos.com>
# $Id$
#
# This program i... | #
##############################################################################
from datetime import datetime
from dateutil.relativedelta import relativedelta
from osv import fields
from osv import osv
from tools.translate import _
import ir
import netsvc
import time
class procurement_order(osv.osv):
_inherit = ... | # GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>. | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.