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 |
|---|---|---|---|---|
dx.aspnet.mvc.js | /*!
* DevExtreme (dx.aspnet.mvc.js)
* Version: 20.1.8 (build 20303-1716)
* Build date: Thu Oct 29 2020
*
* Copyright (c) 2012 - 2020 Developer Express Inc. ALL RIGHTS RESERVED
* Read about DevExtreme licensing here: https://js.devexpress.com/Licensing/
*/
! function(factory) {
if ("function" === typeof define && d... |
}
acceptText(bag, chunks.shift());
for (var i = 0; i < chunks.length; i++) {
var tmp = chunks[i].split(enableAlternativeTemplateTags ? EXTENDED_CLOSE_TAG : CLOSE_TAG);
if (2 !== tmp.length) {
throw "Template syntax error"
... | {
console.logger.warn("Please use an alternative template syntax: https://community.devexpress.com/blogs/aspnet/archive/2020/01/29/asp-net-core-new-syntax-to-fix-razor-issue.aspx");
warnBug17028 = false
} | conditional_block |
dx.aspnet.mvc.js | /*!
* DevExtreme (dx.aspnet.mvc.js)
* Version: 20.1.8 (build 20303-1716)
* Build date: Thu Oct 29 2020
*
* Copyright (c) 2012 - 2020 Developer Express Inc. ALL RIGHTS RESERVED
* Read about DevExtreme licensing here: https://js.devexpress.com/Licensing/
*/
! function(factory) {
if ("function" === typeof define && d... | (bag, code) {
var encode = code.charAt(0) === ENCODE_QUALIFIER,
value = code.substr(1),
interpolate = code.charAt(0) === INTERPOLATE_QUALIFIER;
if (encode || interpolate) {
bag.push("_.push(");
bag.push(encode ? "arguments[1](... | acceptCode | identifier_name |
index.tsx | import { GetStaticProps } from 'next'
import { useTranslation } from 'next-i18next'
import { Box, Divider } from '@chakra-ui/react'
import { translationProps } from '@utils/i18n'
import { getGithubStars } from '@utils/getGithubStars'
import { getDiscordMembers } from '@utils/getDiscordMembers'
import { getTestCoverage... | import { SEO } from '@components/SEO'
import { Announcer } from '@components/Announcer'
import { Header } from '@components/Header'
import { Hero } from '@components/Hero'
import { Features } from '@components/Features'
import { Stats } from '@components/Stats'
import { Demo } from '@components/Demo'
import { DiscordBa... | } from '@utils/getNpmDownloads'
| random_line_split |
index.tsx | import { GetStaticProps } from 'next'
import { useTranslation } from 'next-i18next'
import { Box, Divider } from '@chakra-ui/react'
import { translationProps } from '@utils/i18n'
import { getGithubStars } from '@utils/getGithubStars'
import { getDiscordMembers } from '@utils/getDiscordMembers'
import { getTestCoverage... | (props: IHomeProps) {
const { t } = useTranslation('common')
return (
<>
<SEO
title={t('homepage.seo.title')}
description={t('homepage.seo.description')}
/>
<Announcer
message={t('announcement.message')}
link={t('announcement.link.href')}
title={t('anno... | IndexPage | identifier_name |
index.tsx | import { GetStaticProps } from 'next'
import { useTranslation } from 'next-i18next'
import { Box, Divider } from '@chakra-ui/react'
import { translationProps } from '@utils/i18n'
import { getGithubStars } from '@utils/getGithubStars'
import { getDiscordMembers } from '@utils/getDiscordMembers'
import { getTestCoverage... | githubStars={props.githubStars}
totalDownloads={props.totalDownloads}
monthlyDownloads={props.monthlyDownloads}
discordMembers={props.discordMembers}
testCoverage={props.testCoverage}
codeQuality={props.codeQuality}
/>
<Divider />
<Demo... | {
const { t } = useTranslation('common')
return (
<>
<SEO
title={t('homepage.seo.title')}
description={t('homepage.seo.description')}
/>
<Announcer
message={t('announcement.message')}
link={t('announcement.link.href')}
title={t('announcement.link.title')... | identifier_body |
command.rs | #[derive(Clone, Copy, PartialEq, Debug)]
pub struct DataPointer {
offset: u32,
size: u32,
}
pub struct DataBuffer(Vec<u8>);
impl DataBuffer {
/// Create a new empty data buffer.
pub fn new() -> DataBuffer {
DataBuffer(Vec::new())
}
/// Reset the contents.
pub fn reset(&mut self) {
... | /// The place of some data in the data buffer. | random_line_split | |
command.rs | State,
depth_stencil: *const ID3D11DepthStencilState,
stencil_ref: UINT,
blend: *const ID3D11BlendState,
blend_ref: [FLOAT; 4],
}
unsafe impl Send for Cache {}
impl Cache {
fn new() -> Cache {
Cache {
attrib_strides: [None; MAX_VERTEX_ATTRIBUTES],
rasterizer: ptr::nu... | {
match value {
command::ClearColor::Float(data) => {
self.parser.parse(Command::ClearColor(target, data));
},
_ => {
error!("Unable to clear int/uint target");
},
}
} | identifier_body | |
command.rs | UINT),
DrawIndexed(UINT, UINT, INT),
DrawIndexedInstanced(UINT, UINT, UINT, INT, UINT),
}
unsafe impl Send for Command {}
struct Cache {
attrib_strides: [Option<pso::ElemStride>; MAX_VERTEX_ATTRIBUTES],
rasterizer: *const ID3D11RasterizerState,
depth_stencil: *const ID3D11DepthStencilState,
s... | clear_color | identifier_name | |
command.rs | -> DataBuffer {
DataBuffer(Vec::new())
}
/// Reset the contents.
pub fn reset(&mut self) {
self.0.clear();
}
/// Copy a given vector slice into the buffer.
pub fn add(&mut self, data: &[u8]) -> DataPointer {
self.0.extend_from_slice(data);
DataPointer {
... |
}
}
fn bind_unordered_views(&mut self, uvs: &[pso::UnorderedViewParam<Resources>]) {
let mut views = [(); MAX_UNORDERED_VIEWS];
let mut count = 0;
for view in uvs.iter() {
views[view.2 as usize] = view.0;
count += 1;
}
if count != 0 {
... | {
self.parser.parse(Command::BindShaderResources(stage, views));
} | conditional_block |
startup.legacy.js | define(['jquery', 'knockout', './router', 'bootstrap', 'knockout-projections', 'knockout-select-on-focus'], function($, ko, router) {
// Components can be packaged as AMD modules, such as the following: | ko.components.register('home-page', { require: 'components/home-page/legacy/home' });
ko.components.register('ko-gmap', { require: 'components/ko-gmap/legacy/ko-gmap' });
ko.components.register('ko-gmap-search', { require: 'components/ko-gmap-search/legacy/ko-gmap-search' });
ko.components.register('gll-map', {... | random_line_split | |
node.rs | // Copyright 2018 Pants project contributors (see CONTRIBUTORS.md).
// Licensed under the Apache License, Version 2.0 (see LICENSE).
use std::fmt::{Debug, Display};
use std::hash::Hash;
use boxfuture::BoxFuture;
use hashing::Digest;
use futures01::future::Future;
use petgraph::stable_graph;
use crate::entry::Entry;... | /// Creates an instance that represents that a Node dependency was cyclic along the given path.
///
fn cyclic(path: Vec<String>) -> Self;
}
///
/// A trait used to visualize Nodes in either DOT/GraphViz format.
///
pub trait NodeVisualizer<N: Node> {
///
/// Returns a GraphViz color scheme name for this visu... | /// Graph (generally while running).
///
fn invalidated() -> Self;
/// | random_line_split |
node.rs | // Copyright 2018 Pants project contributors (see CONTRIBUTORS.md).
// Licensed under the Apache License, Version 2.0 (see LICENSE).
use std::fmt::{Debug, Display};
use std::hash::Hash;
use boxfuture::BoxFuture;
use hashing::Digest;
use futures01::future::Future;
use petgraph::stable_graph;
use crate::entry::Entry;... | (&self) -> Option<String> {
None
}
}
pub trait NodeError: Clone + Debug + Eq + Send {
///
/// Creates an instance that represents that a Node was invalidated out of the
/// Graph (generally while running).
///
fn invalidated() -> Self;
///
/// Creates an instance that represents that a Node depend... | user_facing_name | identifier_name |
node.rs | // Copyright 2018 Pants project contributors (see CONTRIBUTORS.md).
// Licensed under the Apache License, Version 2.0 (see LICENSE).
use std::fmt::{Debug, Display};
use std::hash::Hash;
use boxfuture::BoxFuture;
use hashing::Digest;
use futures01::future::Future;
use petgraph::stable_graph;
use crate::entry::Entry;... |
}
pub trait NodeError: Clone + Debug + Eq + Send {
///
/// Creates an instance that represents that a Node was invalidated out of the
/// Graph (generally while running).
///
fn invalidated() -> Self;
///
/// Creates an instance that represents that a Node dependency was cyclic along the given path.
... | {
None
} | identifier_body |
default.py |
def index_Menu():
#Menu('Favourites','',5,'','','','','')
Menu('List of Index\'s','',10,'','','')
# Menu('Search','',6,ICON,FANART,'','','')
# Menu('[COLORred]Press here to add a source url[/COLOR] ','',2,'','','','','')
def Index_List():
OPEN = Open_Url(source_file)
Regex = re.compile('url="(... | OPEN = Open_Url(url)
Regex = re.compile('<a href="(.+?)" target="_blank"><img src="(.+?)" style="max-width:200px;" /><description = "(.+?)" /><background = "(.+?)" </background></a><br><b>(.+?)</b>').findall(OPEN)
for url,icon,desc,fanart,name in Regex:
Watched = re.compile('item="(.+?)"\n').findall(str... | identifier_body | |
default.py | replace('S04',' ').replace('S05','').replace('S06','').replace('S07','').replace('S08','').replace('S09','').replace('E01','')
name25=(name24).replace('E02','').replace('E03','').replace('E04','').replace('E05','').replace('E06','').replace('E07','').replace('E08','').replace('E09','').replace('e01','')
name25=... | Menu(name,url,i[4],iconimage,fanart,'','fav') | conditional_block | |
default.py | art,desc)
setView('tvshows', 'Media Info 3')
####################################################################PROCESSES###################################################
def Open_Url(url):
req = urllib2.Request(url)
req.add_header('User-Agent', 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-GB; rv:1... | random_line_split | ||
default.py | List of Index\'s','',10,'','','')
# Menu('Search','',6,ICON,FANART,'','','')
# Menu('[COLORred]Press here to add a source url[/COLOR] ','',2,'','','','','')
def Index_List():
OPEN = Open_Url(source_file)
Regex = re.compile('url="(.+?)">name="(.+?)"').findall(OPEN)
for url,name in Regex:
... | (url):
HTML = Open_Url(url)
match = re.compile('<a href="(.+?)">(.+?)</a>').findall(HTML)
for url2,name in match:
url3 = url + url2
if '..' in url3:
pass
elif 'rar' in url3:
pass
elif 'jpg' in url3:
pass
elif 'vtx' in url3:
... | Main_Loop | identifier_name |
CardHeader.d.ts | import * as React from 'react';
import { TypographyProps } from '../Typography';
import { OverridableComponent, OverrideProps } from '../OverridableComponent';
export interface CardHeaderTypeMap<P = {}, D extends React.ElementType = 'div'> {
props: P & {
action?: React.ReactNode;
avatar?: React.ReactNode;
... | defaultComponent: D;
classKey: CardHeaderClassKey;
}
/**
*
* Demos:
*
* - [Cards](https://material-ui.com/components/cards/)
*
* API:
*
* - [CardHeader API](https://material-ui.com/api/card-header/)
*/
declare const CardHeader: OverridableComponent<CardHeaderTypeMap>;
export type CardHeaderClassKey = 'roo... | subheaderTypographyProps?: Partial<TypographyProps>;
title?: React.ReactNode;
titleTypographyProps?: Partial<TypographyProps>;
}; | random_line_split |
CensusDataSourceEditor.tsx | import * as React from "react";
import * as weavejs from "weavejs";
import * as _ from "lodash";
import Weave = weavejs.Weave;
import StatefulTextField = weavejs.ui.StatefulTextField;
import ComboBox = weavejs.ui.ComboBox;
import WeaveReactUtils = weavejs.util.WeaveReactUtils
import HBox = weavejs.ui.flexbox.HBox;
impo... |
static isInFamily(family: string, dataset: CensusApiDataSet): boolean {
return family && dataset && ((family == "All") || (dataset.c_dataset.indexOf(family) != -1));
}
static isOfVintage(vintage: string, dataset: CensusApiDataSet): boolean {
return vintage && dataset && ((vintage == "All") || (dataset.c_vinta... | {
return family && (family.indexOf("acs") == 0 || family.indexOf("sf") == 0);
} | identifier_body |
CensusDataSourceEditor.tsx | import * as React from "react";
import * as weavejs from "weavejs";
import * as _ from "lodash";
import Weave = weavejs.Weave;
import StatefulTextField = weavejs.ui.StatefulTextField;
import ComboBox = weavejs.ui.ComboBox;
import WeaveReactUtils = weavejs.util.WeaveReactUtils
import HBox = weavejs.ui.flexbox.HBox;
impo... | ():string[]
{
let raw_datasets = this.state.datasets;
if (!raw_datasets)
return ["All"];
let families_set = new Set<string>(_.flatten(_.map(raw_datasets, (d) => d.c_dataset)).filter(CensusDataSourceEditor.isUsableFamily));
let families_list = _.sortBy(Array.from(families_set));
families_list.unshift("All... | getDataFamilies | identifier_name |
CensusDataSourceEditor.tsx | import * as React from "react";
import * as weavejs from "weavejs";
import * as _ from "lodash";
import Weave = weavejs.Weave;
import StatefulTextField = weavejs.ui.StatefulTextField;
import ComboBox = weavejs.ui.ComboBox;
import WeaveReactUtils = weavejs.util.WeaveReactUtils
import HBox = weavejs.ui.flexbox.HBox;
impo... | this.api = ds.getAPI();
this.api.getDatasets().then(
(result: { dataset: CensusApiDataSet[] }) => { this.state = { datasets: result.dataset } }
);
ds.dataSet.addGroupedCallback(this, this.getGeographies, true);
ds.geographicScope.addGroupedCallback(this, this.updateRequiresAndOptional, true);
}
updateRe... | {
constructor(props:IDataSourceEditorProps)
{
super(props);
let ds = (this.props.dataSource as CensusDataSource); | random_line_split |
test_marshal.py | from __future__ import print_function, absolute_import
import random
import unittest
from pysmoke import marshal
from pysmoke.smoke import ffi, Type, TypedValue, pystring, smokec, not_implemented, charp, dbg
from pysmoke import QtCore, QtGui
qtcore = QtCore.__binding__
qtgui = QtGui.__binding__
class MarshalTestCa... | import gc; gc.collect()
qstr2 = marshal.QString.from_py(pstr)
print('QS:', qstr, pstr, qstr2, marshal.QString.to_py(qstr))
obj = QtGui.QObject()
print('obj', obj.__cval__.value.s_voidp)
obj.setObjectName('my_object')
self.assertEqual(obj.objectName(), 'my_object'... | random_line_split | |
test_marshal.py | from __future__ import print_function, absolute_import
import random
import unittest
from pysmoke import marshal
from pysmoke.smoke import ffi, Type, TypedValue, pystring, smokec, not_implemented, charp, dbg
from pysmoke import QtCore, QtGui
qtcore = QtCore.__binding__
qtgui = QtGui.__binding__
class MarshalTestCa... | (self):
pass
def tearDown(self):
pass
def test_qstring(self):
qstr = marshal.QString.from_py('aqstring')
print(qstr)
pstr = marshal.QString.to_py(qstr)
#dbg()
self.assertEqual(pstr, 'aqstring')
import gc; gc.collect()
qstr2 = marshal.QStr... | setUp | identifier_name |
test_marshal.py | from __future__ import print_function, absolute_import
import random
import unittest
from pysmoke import marshal
from pysmoke.smoke import ffi, Type, TypedValue, pystring, smokec, not_implemented, charp, dbg
from pysmoke import QtCore, QtGui
qtcore = QtCore.__binding__
qtgui = QtGui.__binding__
class MarshalTestCa... |
if __name__ == '__main__':
unittest.main()
| def setUp(self):
pass
def tearDown(self):
pass
def test_qstring(self):
qstr = marshal.QString.from_py('aqstring')
print(qstr)
pstr = marshal.QString.to_py(qstr)
#dbg()
self.assertEqual(pstr, 'aqstring')
import gc; gc.collect()
qstr2 = mar... | identifier_body |
test_marshal.py | from __future__ import print_function, absolute_import
import random
import unittest
from pysmoke import marshal
from pysmoke.smoke import ffi, Type, TypedValue, pystring, smokec, not_implemented, charp, dbg
from pysmoke import QtCore, QtGui
qtcore = QtCore.__binding__
qtgui = QtGui.__binding__
class MarshalTestCa... | unittest.main() | conditional_block | |
toolkit.py | from abc import abstractmethod
from threading import Timer
from ctx.uncertainty.measurers import clear_dobson_paddy
class Event:
def __init__(self, type, **kwargs):
self.type = type
self.properties = kwargs
class Observer:
def update(self):
raise NotImplementedError("Not implemented"... |
class Generator(Observable):
def __init__(self, type, relevance, threshold, certainty_measurer=clear_dobson_paddy):
super().__init__()
self.certainty_measurer = certainty_measurer
self.property = None
self.type = type
self.relevance = relevance
self.threshold = thr... | for generator in self.generators:
if generator.type == type:
return generator.property | identifier_body |
toolkit.py | from abc import abstractmethod
from threading import Timer
from ctx.uncertainty.measurers import clear_dobson_paddy
class Event:
def __init__(self, type, **kwargs):
self.type = type
self.properties = kwargs
class | :
def update(self):
raise NotImplementedError("Not implemented")
class Observable:
def __init__(self):
self._observers = []
def register(self, observer):
self._observers.append(observer)
def notify(self, event):
event.source = self
for observer in self._observ... | Observer | identifier_name |
toolkit.py | from abc import abstractmethod
from threading import Timer
from ctx.uncertainty.measurers import clear_dobson_paddy
class Event:
def __init__(self, type, **kwargs):
self.type = type
self.properties = kwargs
class Observer:
def update(self):
raise NotImplementedError("Not implemented"... | def register(self, observer):
self._observers.append(observer)
def notify(self, event):
event.source = self
for observer in self._observers:
observer.update(event)
class Widget(Observable, Observer):
@abstractmethod
def update(self, event):
pass
def __... |
class Observable:
def __init__(self):
self._observers = []
| random_line_split |
toolkit.py | from abc import abstractmethod
from threading import Timer
from ctx.uncertainty.measurers import clear_dobson_paddy
class Event:
def __init__(self, type, **kwargs):
self.type = type
self.properties = kwargs
class Observer:
def update(self):
raise NotImplementedError("Not implemented"... |
class Generator(Observable):
def __init__(self, type, relevance, threshold, certainty_measurer=clear_dobson_paddy):
super().__init__()
self.certainty_measurer = certainty_measurer
self.property = None
self.type = type
self.relevance = relevance
self.threshold = thr... | if generator.type == type:
return generator.property | conditional_block |
index.js | are provided.
if (typeof max !== 'number') {
msg = max
max = Infinity
}
if (typeof keys === 'number') {
if (!demanded._) demanded._ = { count: 0, msg: null, max: max }
demanded._.count = keys
demanded._.msg = msg
} else if (Array.isArray(keys)) {
keys.forEach(functi... | if (exitProcess) { | random_line_split | |
index.js | Arg = function (requiresArgs) {
options.requiresArg.push.apply(options.requiresArg, [].concat(requiresArgs))
return self
}
self.implies = function (key, value) {
validation.implies(key, value)
return self
}
self.usage = function (msg, opts) {
if (!opts && typeof msg === 'object') {
o... | setPlaceholderKeys | identifier_name | |
index.js | )
if (opts) self.options(opts)
return self
}
self.epilogue = self.epilog = function (msg) {
usage.epilog(msg)
return self
}
self.fail = function (f) {
usage.failFn(f)
return self
}
self.check = function (f) {
validation.check(f)
return self
}
self.defaults = self.de... | {
return path.relative(base, dir)
} | identifier_body | |
mappers.js | import mapValues from 'lodash/mapValues';
import snakeCase from 'lodash/snakeCase';
function ensureTypeSnakeCase(value) |
export function assessmentMetaDataState(data) {
const blankState = {
assessment: false,
assessmentIds: [],
masteryModel: null,
randomize: false,
};
if (typeof data.assessmentmetadata === 'undefined') {
return blankState;
}
// Data is from a serializer for a one to many key, so it will re... | {
if (typeof value === 'string') {
return snakeCase(value);
}
return value;
} | identifier_body |
mappers.js | import mapValues from 'lodash/mapValues';
import snakeCase from 'lodash/snakeCase';
function | (value) {
if (typeof value === 'string') {
return snakeCase(value);
}
return value;
}
export function assessmentMetaDataState(data) {
const blankState = {
assessment: false,
assessmentIds: [],
masteryModel: null,
randomize: false,
};
if (typeof data.assessmentmetadata === 'undefined') {... | ensureTypeSnakeCase | identifier_name |
mappers.js | import mapValues from 'lodash/mapValues';
import snakeCase from 'lodash/snakeCase';
function ensureTypeSnakeCase(value) {
if (typeof value === 'string') {
return snakeCase(value);
}
return value;
}
export function assessmentMetaDataState(data) {
const blankState = {
assessment: false,
assessmentId... | const assessmentIds = assessmentMetaData.assessment_item_ids;
const masteryModel = mapValues(assessmentMetaData.mastery_model, ensureTypeSnakeCase);
if (!assessmentIds.length || !Object.keys(masteryModel).length) {
return blankState;
}
return {
assessment: true,
assessmentIds,
masteryModel,
... | const assessmentMetaData = data.assessmentmetadata[0];
if (!assessmentMetaData) {
return blankState;
} | random_line_split |
mappers.js | import mapValues from 'lodash/mapValues';
import snakeCase from 'lodash/snakeCase';
function ensureTypeSnakeCase(value) {
if (typeof value === 'string') |
return value;
}
export function assessmentMetaDataState(data) {
const blankState = {
assessment: false,
assessmentIds: [],
masteryModel: null,
randomize: false,
};
if (typeof data.assessmentmetadata === 'undefined') {
return blankState;
}
// Data is from a serializer for a one to many ... | {
return snakeCase(value);
} | conditional_block |
index.ts | import { EMPTY_P } from '../../../utils/const'
import Editor from '../../../editor/index'
import $, { DomElement } from '../../../utils/dom-core'
function | (editor: Editor) {
function quoteEnter(e: Event) {
const $selectElem = editor.selection.getSelectionContainerElem() as DomElement
const $topSelectElem = editor.selection.getSelectionRangeTopNodes()[0]
// 对quote的enter进行特殊处理
//最后一行为空标签时再按会出跳出blockquote
if ($topSelectElem?.getNo... | bindEvent | identifier_name |
index.ts | import { EMPTY_P } from '../../../utils/const'
import Editor from '../../../editor/index'
import $, { DomElement } from '../../../utils/dom-core'
function bindEvent(editor: Editor) {
function quoteEnter(e: Event) | // 当blockQuote中没有内容回车后移除blockquote
if ($topSelectElem.text() === '') {
$topSelectElem.remove()
}
}
}
editor.txt.eventHooks.enterDownEvents.push(quoteEnter)
}
export default bindEvent
| {
const $selectElem = editor.selection.getSelectionContainerElem() as DomElement
const $topSelectElem = editor.selection.getSelectionRangeTopNodes()[0]
// 对quote的enter进行特殊处理
//最后一行为空标签时再按会出跳出blockquote
if ($topSelectElem?.getNodeName() === 'BLOCKQUOTE') {
// firefox下点... | identifier_body |
index.ts | import { EMPTY_P } from '../../../utils/const'
import Editor from '../../../editor/index'
import $, { DomElement } from '../../../utils/dom-core'
function bindEvent(editor: Editor) {
function quoteEnter(e: Event) {
const $selectElem = editor.selection.getSelectionContainerElem() as DomElement
const ... | efault()
$selectElem.remove()
const $newLine = $(EMPTY_P)
$newLine.insertAfter($topSelectElem)
// 将光标移动br前面
editor.selection.moveCursor($newLine.getNode(), 0)
}
// 当blockQuote中没有内容回车后移除blockquote
if ($to... | as Node
editor.selection.moveCursor(selectNode)
}
if ($selectElem.text() === '') {
e.preventD | conditional_block |
index.ts | import { EMPTY_P } from '../../../utils/const'
import Editor from '../../../editor/index'
import $, { DomElement } from '../../../utils/dom-core'
function bindEvent(editor: Editor) {
function quoteEnter(e: Event) {
const $selectElem = editor.selection.getSelectionContainerElem() as DomElement
const ... | // 当blockQuote中没有内容回车后移除blockquote
if ($topSelectElem.text() === '') {
$topSelectElem.remove()
}
}
}
editor.txt.eventHooks.enterDownEvents.push(quoteEnter)
}
export default bindEvent | $newLine.insertAfter($topSelectElem)
// 将光标移动br前面
editor.selection.moveCursor($newLine.getNode(), 0)
}
| random_line_split |
methods.py | import json
from math import ceil
from asyncpg import Connection
from qllr.common import MATCH_LIST_ITEM_COUNT
from qllr.db import cache
from qllr.settings import PLAYER_COUNT_PER_PAGE
KEEPING_TIME = 60 * 60 * 24 * 30
SQL_TOP_PLAYERS_BY_GAMETYPE = """
SELECT
p.steam_id,
p.name,
p.model,
... |
player_count = row[6]
steam_ids = list(map(lambda player: int(player["_id"]), result))
query = """
SELECT
s.steam_id,
CEIL(AVG(CASE
WHEN m.team1_score > m.team2_score AND s.team = 1 THEN 1
WHEN m.team2_score > m.team1_score AND s.team = 2 THEN 1
... | result.append(
{
"_id": str(row[0]),
"name": row[1],
"model": (
row[2] + ("/default" if row[2].find("/") == -1 else "")
).lower(),
"rating": round(row[3], 2),
"... | conditional_block |
methods.py | from asyncpg import Connection
from qllr.common import MATCH_LIST_ITEM_COUNT
from qllr.db import cache
from qllr.settings import PLAYER_COUNT_PER_PAGE
KEEPING_TIME = 60 * 60 * 24 * 30
SQL_TOP_PLAYERS_BY_GAMETYPE = """
SELECT
p.steam_id,
p.name,
p.model,
gr.rating,
gr.devia... | import json
from math import ceil
| random_line_split | |
methods.py | import json
from math import ceil
from asyncpg import Connection
from qllr.common import MATCH_LIST_ITEM_COUNT
from qllr.db import cache
from qllr.settings import PLAYER_COUNT_PER_PAGE
KEEPING_TIME = 60 * 60 * 24 * 30
SQL_TOP_PLAYERS_BY_GAMETYPE = """
SELECT
p.steam_id,
p.name,
p.model,
... | (con: Connection, gametype_id: int, page: int, show_inactive=False):
await con.set_type_codec(
"json", encoder=json.dumps, decoder=json.loads, schema="pg_catalog"
)
query = get_sql_top_players_query_by_gametype_id(
gametype_id
) + "LIMIT {LIMIT} OFFSET {OFFSET}".format(
LIMIT=i... | get_list | identifier_name |
methods.py | import json
from math import ceil
from asyncpg import Connection
from qllr.common import MATCH_LIST_ITEM_COUNT
from qllr.db import cache
from qllr.settings import PLAYER_COUNT_PER_PAGE
KEEPING_TIME = 60 * 60 * 24 * 30
SQL_TOP_PLAYERS_BY_GAMETYPE = """
SELECT
p.steam_id,
p.name,
p.model,
... | "_id": str(row[0]),
"name": row[1],
"model": (
row[2] + ("/default" if row[2].find("/") == -1 else "")
).lower(),
"rating": round(row[3], 2),
"rd": round(row[4], 2),
... | await con.set_type_codec(
"json", encoder=json.dumps, decoder=json.loads, schema="pg_catalog"
)
query = get_sql_top_players_query_by_gametype_id(
gametype_id
) + "LIMIT {LIMIT} OFFSET {OFFSET}".format(
LIMIT=int(PLAYER_COUNT_PER_PAGE), OFFSET=int(PLAYER_COUNT_PER_PAGE * page)
)
... | identifier_body |
downloadFiles.py | # -*- coding: utf-8 -*-
import datetime
import os
import urllib.request
import re
def getUrlList(url):
ret = []
baseUrl = re.findall('(http://.+?)/',url)[0]
httpRequest = urllib.request.Request(url)
httpResponse = urllib.request.urlopen(httpRequest)
html = httpResponse.read()... | (url, downloadDir):
print('[start] %s' % url)
ul = getUrlList(url)
for u in ul:
f = re.findall('http://.+/(.+\.)(pdf|xls|xlsx|zip)',u)[0]
downloadFiles_exe(u, os.path.join(downloadDir, f[0]+f[1]))
return
def main(argv):
if len(argv) == 3:
urlList = ... | downloadFiles | identifier_name |
downloadFiles.py | # -*- coding: utf-8 -*-
import datetime
import os
import urllib.request
import re
def getUrlList(url):
ret = []
baseUrl = re.findall('(http://.+?)/',url)[0]
httpRequest = urllib.request.Request(url)
httpResponse = urllib.request.urlopen(httpRequest)
html = httpResponse.read()... | ret.append(baseUrl + u[0][0] + u[0][1])
return ret
def downloadFiles_exe(url, downloadPath):
try:
urllib.request.urlretrieve(url,downloadPath)
print('[ok] %s' % url)
except:
print('[ng] %s' % url)
return
def downloadFiles(url, downlo... | random_line_split | |
downloadFiles.py | # -*- coding: utf-8 -*-
import datetime
import os
import urllib.request
import re
def getUrlList(url):
ret = []
baseUrl = re.findall('(http://.+?)/',url)[0]
httpRequest = urllib.request.Request(url)
httpResponse = urllib.request.urlopen(httpRequest)
html = httpResponse.read()... |
def downloadFiles(url, downloadDir):
print('[start] %s' % url)
ul = getUrlList(url)
for u in ul:
f = re.findall('http://.+/(.+\.)(pdf|xls|xlsx|zip)',u)[0]
downloadFiles_exe(u, os.path.join(downloadDir, f[0]+f[1]))
return
def main(argv):
if len(argv) == 3:
... | try:
urllib.request.urlretrieve(url,downloadPath)
print('[ok] %s' % url)
except:
print('[ng] %s' % url)
return | identifier_body |
downloadFiles.py | # -*- coding: utf-8 -*-
import datetime
import os
import urllib.request
import re
def getUrlList(url):
ret = []
baseUrl = re.findall('(http://.+?)/',url)[0]
httpRequest = urllib.request.Request(url)
httpResponse = urllib.request.urlopen(httpRequest)
html = httpResponse.read()... |
today = datetime.datetime.today().strftime('%Y%m%d')
#./dl/yyyyMMdd/
os.mkdir(os.path.join(downloadDir, today))
for line in open(urlList,'r'):
#tag \t url
l = line.split('\t')
os.mkdir(os.path.join(downloadDir, today, l[0]))
downloadFiles(l[1]... | f = open('win.ini','r')
s = f.read().split('\n')
urlList = s[0]
downloadDir = s[1]
f.close() | conditional_block |
cssparse.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 http://mozilla.org/MPL/2.0/. */
/// Some little helpers for hooking up the HTML parser with the CSS parser.
use std::cell::Cell;
use std::comm;
u... | do task::spawn {
// TODO: CSS parsing should take a base URL.
let _url = do provenance_cell.with_ref |p| {
match *p {
UrlProvenance(ref the_url) => (*the_url).clone(),
InlineProvenance(ref the_url, _) => (*the_url).clone()
}
};
... | random_line_split | |
cssparse.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 http://mozilla.org/MPL/2.0/. */
/// Some little helpers for hooking up the HTML parser with the CSS parser.
use std::cell::Cell;
use std::comm;
u... | (provenance: StylesheetProvenance,
resource_task: ResourceTask)
-> Port<Stylesheet> {
let (result_port, result_chan) = comm::stream();
let provenance_cell = Cell::new(provenance);
do task::spawn {
// TODO: CSS parsing should take a base URL.
let ... | spawn_css_parser | identifier_name |
fluent-ffmpeg-tests.ts | import ffmpeg = require('fluent-ffmpeg');
import { createWriteStream } from 'fs';
const stream = createWriteStream('outputfile.divx');
ffmpeg('/path/to/file.avi')
.output('outputfile.mp4')
.output(stream);
ffmpeg('/path/to/file.avi')
// You may pass a pipe() options object when using a stream
.output... | ffmpeg.getAvailableEncoders((err, encoders) => {
console.log('Available encoders:');
console.dir(encoders);
});
ffmpeg.getAvailableFilters((err, filters) => {
console.log("Available filters:");
console.dir(filters);
}); | });
| random_line_split |
menu.test.ts | import '@toba/test';
import { MockRequest, MockResponse } from '@toba/test';
import { Header } from '@toba/tools';
import { menu } from '../controllers/';
import { Page } from '../views/';
const req = new MockRequest();
const res = new MockResponse(req);
beforeEach(() => {
res.reset();
req.reset();
});
test('b... | expect(res).toRenderTemplate(Page.MobileMenuData);
expect(res.rendered.context).toHaveProperty('blog');
done();
};
menu.mobile(req, res);
}); | });
it('renders mobile menu', done => {
res.onEnd = () => { | random_line_split |
apsim75.py | import glob
import os
import shutil
import sys
import tarfile
import traceback
from model import Model
from subprocess import Popen, PIPE
class Apsim75(Model):
def run(self, latidx, lonidx):
try:
apsim_bin = self.config.get('executable')
# The apsim 'executable' is a gzipped tarba... | for xml_file in glob.glob('*.xml'):
if os.path.basename(xml_file) == 'Apsim.xml':
continue
old_xml = '%s/%s' % (model_dir, os.path.basename(xml_file))
if os.path.isfile(old_xml):
os.remove(old_xml)
if o... | random_line_split | |
apsim75.py | import glob
import os
import shutil
import sys
import tarfile
import traceback
from model import Model
from subprocess import Popen, PIPE
class Apsim75(Model):
| shutil.copy(link, model_dir)
else:
shutil.copy(xml_file, model_dir)
# Create sim files
p = Popen('source paths.sh ; mono Model/ApsimToSim.exe Generic.apsim', shell=True, executable='/bin/bash', stdout=PIPE, stderr=PIPE)... | def run(self, latidx, lonidx):
try:
apsim_bin = self.config.get('executable')
# The apsim 'executable' is a gzipped tarball that needs to be extracted into the current working directory
tar = tarfile.open(apsim_bin)
tar.extractall()
tar.close()
... | identifier_body |
apsim75.py | import glob
import os
import shutil
import sys
import tarfile
import traceback
from model import Model
from subprocess import Popen, PIPE
class Apsim75(Model):
def run(self, latidx, lonidx):
try:
apsim_bin = self.config.get('executable')
# The apsim 'executable' is a gzipped tarba... |
# Create sim files
p = Popen('source paths.sh ; mono Model/ApsimToSim.exe Generic.apsim', shell=True, executable='/bin/bash', stdout=PIPE, stderr=PIPE)
stdout, stderr = p.communicate()
stdout_file = open('RESULT.OUT', 'w')
stdout_file.write(stdout)
... | shutil.copy(xml_file, model_dir) | conditional_block |
apsim75.py | import glob
import os
import shutil
import sys
import tarfile
import traceback
from model import Model
from subprocess import Popen, PIPE
class | (Model):
def run(self, latidx, lonidx):
try:
apsim_bin = self.config.get('executable')
# The apsim 'executable' is a gzipped tarball that needs to be extracted into the current working directory
tar = tarfile.open(apsim_bin)
tar.extractall()
tar.... | Apsim75 | identifier_name |
int32_test.py | # Copyright 2018 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
from tensorflow.python.compiler.tensorrt.test import tf_trt_integration_test_base as trt_test
from tensorflow.python.framework import constant_op
from tensorflow.python.framework import dtyp... | # ==============================================================================
"""Test conversion of graphs involving INT32 tensors and operations."""
| random_line_split |
int32_test.py | # Copyright 2018 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... |
def GetParams(self):
return self.BuildParams(self.GraphFn, dtypes.int32, [[100, 4]], [[100, 10]])
def GetConversionParams(self, run_params):
"""Return a ConversionParams for test."""
conversion_params = super(ExcludeUnsupportedInt32Test,
self).GetConversionParams(run_par... | dtype = x.dtype
b = self._ConstOp((4, 10), dtype)
x = math_ops.matmul(x, b)
b = self._ConstOp((10,), dtype)
x = nn.bias_add(x, b)
return array_ops.identity(x, name='output_0') | identifier_body |
int32_test.py | # Copyright 2018 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | (self, run_params):
"""Return the expected engines to build."""
return []
if __name__ == '__main__':
test.main()
| ExpectedEnginesToBuild | identifier_name |
int32_test.py | # Copyright 2018 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | test.main() | conditional_block | |
certificates.py | org=org, number=number, name=name)
world.scenario_dict['course_id'] = course_id
world.scenario_dict['COURSE'] = world.CourseFactory.create(
org=org, number=number, display_name=name)
audit_mode = world.CourseModeFactory.create(
course_id=course_id,
mode_slug='audit',
... |
# Make sure you didn't advance the carousel
assert world.css_has_class(wrapper_css[name], 'carousel-active')
@step(u'I select a contribution amount$')
def select_contribution_amount(step):
select_contribution(32)
@step(u'I confirm that the details match$')
def confirm_details_match(step):
# First ... | world.css_click(button_css[name]) | conditional_block |
certificates.py | org=org, number=number, name=name)
world.scenario_dict['course_id'] = course_id
world.scenario_dict['COURSE'] = world.CourseFactory.create(
org=org, number=number, display_name=name)
audit_mode = world.CourseModeFactory.create(
course_id=course_id,
mode_slug='audit',
... |
@step(u'I should see the course on my dashboard$')
def should_see_the_course_on_my_dashboard(step):
course_css = 'li.course-item'
assert world.is_css_present(course_css)
@step(u'I go to step "([^"]*)"$')
def goto_next_step(step, step_num):
btn_css = {
'1': '#face_next_button',
'2': '#fa... | create_cert_course()
register()
select_contribution(32)
click_verified_track_button()
assert world.is_css_present('section.progress') | identifier_body |
certificates.py | org=org, number=number, name=name)
world.scenario_dict['course_id'] = course_id
world.scenario_dict['COURSE'] = world.CourseFactory.create(
org=org, number=number, display_name=name)
audit_mode = world.CourseModeFactory.create(
course_id=course_id,
mode_slug='audit',
... | (step):
world.wait_for_present('input[name=transactionSignature]')
@step(u'I submit valid payment information$')
def submit_payment(step):
# First make sure that the page is done if it still executing
# an ajax query.
world.wait_for_ajax_complete()
button_css = 'input[value=Submit]'
world.css_... | at_the_payment_page | identifier_name |
certificates.py | org=org, number=number, name=name)
world.scenario_dict['course_id'] = course_id
world.scenario_dict['COURSE'] = world.CourseFactory.create(
org=org, number=number, display_name=name)
audit_mode = world.CourseModeFactory.create(
course_id=course_id,
mode_slug='audit',
... | assert world.css_find(radio_css).selected
def click_verified_track_button():
world.wait_for_ajax_complete()
btn_css = 'input[value="Select Certificate"]'
world.css_click(btn_css)
@step(u'I select the verified track for upgrade')
def select_verified_track_upgrade(step):
select_contribution(32)
... | world.css_click(radio_css) | random_line_split |
char.rs | #[stable(feature = "rust1", since = "1.0.0")]
pub struct ToUppercase(CaseMappingIter);
#[stable(feature = "rust1", since = "1.0.0")]
impl Iterator for ToUppercase {
type Item = char;
fn next(&mut self) -> Option<char> { self.0.next() }
}
/// An iterator over the titlecase mapping of a given character, returne... | /// An iterator over the uppercase mapping of a given character, returned from
/// the [`to_uppercase` method](../primitive.char.html#method.to_uppercase) on
/// characters. | random_line_split | |
char.rs | /// let result = 'ß'.encode_utf8(&mut b);
///
/// assert_eq!(result, Some(2));
/// ```
///
/// A buffer that's too small:
///
/// ```
/// # #![feature(unicode)]
/// let mut b = [0; 1];
///
/// let result = 'ß'.encode_utf8(&mut b);
///
/// assert_eq!(result, None);... | gIter::new(conversions::to_upper(self)))
}
/// Returns this character | identifier_body | |
char.rs | mut self) -> Option<char> { self.0.next() }
}
enum CaseMappingIter {
Three(char, char, char),
Two(char, char),
One(char),
Zero
}
impl CaseMappingIter {
fn new(chars: [char; 3]) -> CaseMappingIter {
if chars[2] == '\0' {
if chars[1] == '\0' {
CaseMappingIter::On... | f) -> EscapeDefault { C::escape_default(self) }
/// Returns the number of bytes this character would need if encoded in
/// UTF-8.
///
/// # Examples
///
/// ```
/// let n = 'ß'.len_utf8();
///
/// assert_eq!(n, 2);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
p... | pe_default(sel | identifier_name |
basename.rs | #![crate_name = "uu_basename"]
/*
* This file is part of the uutils coreutils package.
*
* (c) Jimmy Lu <jimmy.lu.2011@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
#[macro_use]
extern crate uucore;
use std::io::Wri... | if name.ends_with(suffix) {
return name[..name.len() - suffix.len()].to_owned();
}
name.to_owned()
} | fn strip_suffix(name: &str, suffix: &str) -> String {
if name == suffix {
return name.to_owned();
}
| random_line_split |
basename.rs | #![crate_name = "uu_basename"]
/*
* This file is part of the uutils coreutils package.
*
* (c) Jimmy Lu <jimmy.lu.2011@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
#[macro_use]
extern crate uucore;
use std::io::Wri... | {
if name == suffix {
return name.to_owned();
}
if name.ends_with(suffix) {
return name[..name.len() - suffix.len()].to_owned();
}
name.to_owned()
} | identifier_body | |
basename.rs | #![crate_name = "uu_basename"]
/*
* This file is part of the uutils coreutils package.
*
* (c) Jimmy Lu <jimmy.lu.2011@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
#[macro_use]
extern crate uucore;
use std::io::Wri... | (args: Vec<String>) -> i32 {
//
// Argument parsing
//
let matches = new_coreopts!(SYNTAX, SUMMARY, LONG_HELP)
.optflag("a", "multiple", "Support more than one argument. Treat every argument as a name.")
.optopt("s", "suffix", "Remove a trailing suffix. This option implies the -a option.... | uumain | identifier_name |
basename.rs | #![crate_name = "uu_basename"]
/*
* This file is part of the uutils coreutils package.
*
* (c) Jimmy Lu <jimmy.lu.2011@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
#[macro_use]
extern crate uucore;
use std::io::Wri... | ;
for path in paths {
print!("{}{}", basename(&path, &suffix), line_ending);
}
0
}
fn basename(fullname: &str, suffix: &str) -> String {
// Remove all platform-specific path separators from the end
let mut path: String = fullname.chars().rev().skip_while(|&ch| is_separator(ch)).collect();
... | { "\n" } | conditional_block |
Suite.ts | import o from "ospec"
import "./common/LoggerTest.js"
import "./common/BirthdayUtilsTest"
import "./rest/EntityRestClientTest"
import "./crypto/CryptoFacadeTest.js"
import "./crypto/CompatibilityTest"
import "./error/RestErrorTest"
import "./error/TutanotaErrorTest"
import "./rest/RestClientTest"
import "./rest/Entity... |
}
// setup the Entropy for all testcases
await random.addEntropy([{data: 36, entropy: 256, source: "key"}])
preTest()
o.before(function () {
// testdouble complains about certain mocking related code smells, and also prints a warning whenever you replace a property on an object.
// it's very very noisy, so ... | {
console.log("\nRunning without integration tests because run without -i\n")
} | conditional_block |
Suite.ts | import o from "ospec"
import "./common/LoggerTest.js"
import "./common/BirthdayUtilsTest"
import "./rest/EntityRestClientTest"
import "./crypto/CryptoFacadeTest.js"
import "./crypto/CompatibilityTest"
import "./error/RestErrorTest"
import "./error/TutanotaErrorTest"
import "./rest/RestClientTest"
import "./rest/Entity... | td.reset()
})
// @ts-ignore
o.run(reportTest)
})() | random_line_split | |
filecache.py | # Bulletproof Arma Launcher
# Copyright (C) 2017 Lukasz Taczuk
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 3 as
# published by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# b... |
def save_file(url, data):
"""Save the file contents to the cache.
The contents of the file are saved to a temporary file and then moved to
ensure that no truncated file is present in the cache.
"""
# Ensure the directory exists
paths.mkdir_p(get_cache_directory())
path = map_file(url)
... | """Get the file contents from the cache or None if the file is not present
in the cache.
"""
path = map_file(url)
f = None
try:
f = open(path, 'rb')
return f.read()
except IOError as ex:
if ex.errno == errno.ENOENT: # No such file
return None
rais... | identifier_body |
filecache.py | # Bulletproof Arma Launcher
# Copyright (C) 2017 Lukasz Taczuk
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 3 as
# published by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# b... |
def save_file(url, data):
"""Save the file contents to the cache.
The contents of the file are saved to a temporary file and then moved to
ensure that no truncated file is present in the cache.
"""
# Ensure the directory exists
paths.mkdir_p(get_cache_directory())
path = map_file(url)
... |
finally:
if f:
f.close() | random_line_split |
filecache.py | # Bulletproof Arma Launcher
# Copyright (C) 2017 Lukasz Taczuk
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 3 as
# published by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# b... | (url):
"""Get the path where the file should be stored in the cache."""
file_name = hashlib.sha256(url).hexdigest()
return os.path.join(get_cache_directory(), file_name)
def get_file(url):
"""Get the file contents from the cache or None if the file is not present
in the cache.
"""
path =... | map_file | identifier_name |
filecache.py | # Bulletproof Arma Launcher
# Copyright (C) 2017 Lukasz Taczuk
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 3 as
# published by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# b... |
def save_file(url, data):
"""Save the file contents to the cache.
The contents of the file are saved to a temporary file and then moved to
ensure that no truncated file is present in the cache.
"""
# Ensure the directory exists
paths.mkdir_p(get_cache_directory())
path = map_file(url)
... | f.close() | conditional_block |
triggerHandler.js |
if (typeof error !== 'undefined') {
history.error = error;
}
if (typeof errorStack !== 'undefined') {
history.errorStack = errorStack;
}
if (historyId) {
RocketChat.models.IntegrationHistory.update({ _id: historyId }, { $set: history });
return historyId;
} else {
history._createdAt = new... | {
history.httpResult = httpResult;
} | conditional_block | |
triggerHandler.js |
isTriggerEnabled(trigger) {
for (const trig of Object.values(this.triggers)) {
if (trig[trigger._id]) {
return trig[trigger._id].enabled;
}
}
return false;
}
updateHistory({ historyId, step, integration, event, data, triggerWord, ranPrepareScript, prepareSentMessage, processSentMessage, resultMes... | {
for (const trigger of Object.values(this.triggers)) {
delete trigger[record._id];
}
} | identifier_body | |
triggerHandler.js | ({ historyId, step, integration, event, data, triggerWord, ranPrepareScript, prepareSentMessage, processSentMessage, resultMessage, finished, url, httpCallData, httpError, httpResult, error, errorStack }) {
const history = {
type: 'outgoing-webhook',
step
};
// Usually is only added on initial insert
if ... | updateHistory | identifier_name | |
triggerHandler.js | //If no room could be found, we won't be sending any messages but we'll warn in the logs
if (!tmpRoom) {
logger.outgoing.warn(`The Integration "${ trigger.name }" doesn't have a room configured nor did it provide a room to send the message to.`);
return;
}
logger.outgoing.debug(`Found a room for ${ trigg... |
//Each type of event should have an event and a room attached, otherwise we
//wouldn't know how to handle the trigger nor would we have anywhere to send the
//result of the integration | random_line_split | |
pad-test.js | var assert = require('chai').assert;
var Pad = require('../lib/pad');
describe('Pad', function() {
it('should be an object', function() {
var pad = new Pad();
assert.isObject(pad);
});
it('should have a x coordinate of 310 by default', function() {
var terminator = new Pad();
assert.equal(termin... |
it('should have an eAngle value of 2*Math.PI by default', function() {
var jon = new Pad();
assert.equal(jon.eAngle, 2*Math.PI);
});
it('should have a draw function', function(){
var jon = new Pad();
assert.isFunction(jon.draw);
});
}); | random_line_split | |
views.py | from django.http import HttpResponse
from django.core.servers.basehttp import FileWrapper
from django.contrib.auth.models import User
from django.shortcuts import render_to_response, redirect, get_object_or_404
from requests import get
from urllib import urlretrieve
from common.models import Repository
from common.ut... |
def repo_snapshot(request, user_name, repo_name, path):
user = request.user
owner = get_object_or_404(User, username=user_name)
repo = get_object_or_404(Repository, owner=owner, name=repo_name)
collaborators = repo.collaborators.all()
access = repo.user_access(user)
if access is None:... | user = request.user
owner = get_object_or_404(User, username=user_name)
repo = get_object_or_404(Repository, owner=owner, name=repo_name)
collaborators = repo.collaborators.all()
access = repo.user_access(user)
if access is None:
return HttpResponse('Not authorized', status=401)
query... | identifier_body |
views.py | from django.http import HttpResponse
from django.core.servers.basehttp import FileWrapper
from django.contrib.auth.models import User
from django.shortcuts import render_to_response, redirect, get_object_or_404
from requests import get
from urllib import urlretrieve
from common.models import Repository
from common.ut... | return HttpResponse('Not authorized', status=401)
query = request.GET.urlencode()
filename = path.split('/')[-1]
url = cgit_url(user_name, repo_name, 'snapshot', path, query)
(fname, info) = urlretrieve(url)
response = HttpResponse(FileWrapper(open(fname)), content_type='application/force... |
access = repo.user_access(user)
if access is None: | random_line_split |
views.py | from django.http import HttpResponse
from django.core.servers.basehttp import FileWrapper
from django.contrib.auth.models import User
from django.shortcuts import render_to_response, redirect, get_object_or_404
from requests import get
from urllib import urlretrieve
from common.models import Repository
from common.ut... |
query = request.GET.urlencode()
print query
url = cgit_url(user_name, repo_name, prefix, path, query)
(fname, info) = urlretrieve(url)
response = HttpResponse(FileWrapper(open(fname)), content_type='text/plain')
return response
def repo_snapshot(request, user_name, repo_name, path):
... | return HttpResponse('Not authorized', status=401) | conditional_block |
views.py | from django.http import HttpResponse
from django.core.servers.basehttp import FileWrapper
from django.contrib.auth.models import User
from django.shortcuts import render_to_response, redirect, get_object_or_404
from requests import get
from urllib import urlretrieve
from common.models import Repository
from common.ut... | (request, user_name, repo_name, method='summary', path=None):
user = request.user
owner = get_object_or_404(User, username=user_name)
repo = get_object_or_404(Repository, owner=owner, name=repo_name)
collaborators = repo.collaborators.all()
access = repo.user_access(user)
if access is None:
... | repo_browse | identifier_name |
structarm__dct4__instance__q31.js | var structarm__dct4__instance__q31 =
| [ "N", "structarm__dct4__instance__q31.html#a46a9f136457350676e2bfd3768ff9d6d", null ],
[ "Nby2", "structarm__dct4__instance__q31.html#a32d3268ba4629908dba056599f0a904d", null ],
[ "normalize", "structarm__dct4__instance__q31.html#ac80ff7b28fca36aeef74dea12e8312dd", null ],
[ "pCfft", "structarm__dct... | [
| random_line_split |
test.py | # Copyright (c) 2006 The Regents of The University of Michigan
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met: redistributions of source code must retain the above copyright
# notice, this list ... | options.options = '1024 1 0' | options.cmd = 'gem5_gpu_bh' | random_line_split |
markers.py | # The plot server must be running
# Go to http://localhost:5006/bokeh to view this plot
from numpy.random import random
from bokeh.plotting import *
def mscatter(p, x, y, typestr): |
def mtext(p, x, y, textstr):
p.text(x, y, text=textstr,
text_color="#449944", text_align="center", text_font_size="10pt")
output_server("markers")
p = figure(title="markers.py example")
N = 10
mscatter(p, random(N)+2, random(N)+1, "circle")
mscatter(p, random(N)+4, random(N)+1, "square")
mscatter(p, r... | p.scatter(x, y, marker=typestr,
line_color="#6666ee", fill_color="#ee6666", fill_alpha=0.5, size=12) | random_line_split |
markers.py | # The plot server must be running
# Go to http://localhost:5006/bokeh to view this plot
from numpy.random import random
from bokeh.plotting import *
def | (p, x, y, typestr):
p.scatter(x, y, marker=typestr,
line_color="#6666ee", fill_color="#ee6666", fill_alpha=0.5, size=12)
def mtext(p, x, y, textstr):
p.text(x, y, text=textstr,
text_color="#449944", text_align="center", text_font_size="10pt")
output_server("markers")
p = figure(title="ma... | mscatter | identifier_name |
markers.py | # The plot server must be running
# Go to http://localhost:5006/bokeh to view this plot
from numpy.random import random
from bokeh.plotting import *
def mscatter(p, x, y, typestr):
|
def mtext(p, x, y, textstr):
p.text(x, y, text=textstr,
text_color="#449944", text_align="center", text_font_size="10pt")
output_server("markers")
p = figure(title="markers.py example")
N = 10
mscatter(p, random(N)+2, random(N)+1, "circle")
mscatter(p, random(N)+4, random(N)+1, "square")
mscatter(p, ... | p.scatter(x, y, marker=typestr,
line_color="#6666ee", fill_color="#ee6666", fill_alpha=0.5, size=12) | identifier_body |
camera_utils.py | from bpy_extras.view3d_utils import location_3d_to_region_2d
def render_get_resolution_(r):
xres = int(r.resolution_x * r.resolution_percentage * 0.01)
yres = int(r.resolution_y * r.resolution_percentage * 0.01)
return xres, yres
def render_get_aspect_(r, camera=None, x=-1, y=-1):
if x != -1 and y... | (ob, render, region, region_data, scene):
# Code reference:
# https://blender.stackexchange.com/questions/6377/coordinates-of-corners-of-camera-view-border
cam = ob.data
frame = cam.view_frame(scene=scene)
# move from object-space into world-space
frame = [ob.matrix_world @ v for v in frame]
# ... | get_viewport_cam_borders | identifier_name |
camera_utils.py | from bpy_extras.view3d_utils import location_3d_to_region_2d
def render_get_resolution_(r):
xres = int(r.resolution_x * r.resolution_percentage * 0.01)
yres = int(r.resolution_y * r.resolution_percentage * 0.01)
return xres, yres
def render_get_aspect_(r, camera=None, x=-1, y=-1):
if x != -1 and y... | if min_y == -1:
min_y = v[1]
elif min_y > v[1]:
min_y = v[1]
if max_y < v[1]:
max_y = v[1]
cam_width = max_x - min_x
cam_height = max_y - min_y
x0 = min_x + render.border_min_x * cam_width
x1 = min_x + render.border_max_x * cam_width
y0 = ... | cam = ob.data
frame = cam.view_frame(scene=scene)
# move from object-space into world-space
frame = [ob.matrix_world @ v for v in frame]
# move into pixelspace
frame_px = [location_3d_to_region_2d(region, region_data, v) for v in frame]
min_x = -1
min_y = -1
max_x = -1
max_y = -1... | identifier_body |
camera_utils.py | from bpy_extras.view3d_utils import location_3d_to_region_2d
def render_get_resolution_(r):
xres = int(r.resolution_x * r.resolution_percentage * 0.01)
yres = int(r.resolution_y * r.resolution_percentage * 0.01)
return xres, yres
def render_get_aspect_(r, camera=None, x=-1, y=-1):
if x != -1 and y... | # https://blender.stackexchange.com/questions/6377/coordinates-of-corners-of-camera-view-border
cam = ob.data
frame = cam.view_frame(scene=scene)
# move from object-space into world-space
frame = [ob.matrix_world @ v for v in frame]
# move into pixelspace
frame_px = [location_3d_to_region_2d... |
def get_viewport_cam_borders(ob, render, region, region_data, scene):
# Code reference: | random_line_split |
camera_utils.py | from bpy_extras.view3d_utils import location_3d_to_region_2d
def render_get_resolution_(r):
xres = int(r.resolution_x * r.resolution_percentage * 0.01)
yres = int(r.resolution_y * r.resolution_percentage * 0.01)
return xres, yres
def render_get_aspect_(r, camera=None, x=-1, y=-1):
if x != -1 and y... |
if fit == 'HORIZONTAL' or fit == 'AUTO' and xratio > yratio:
aspectratio = xratio / yratio
xaspect = aspectratio
yaspect = 1.0
elif fit == 'VERTICAL' or fit == 'AUTO' and yratio > xratio:
aspectratio = yratio / xratio
xaspect = 1.0
yaspect = aspectratio
else... | fit = camera.sensor_fit | conditional_block |
address-select.component.spec.ts | /*
* Copyright (c) 2014-2021 Bjoern Kimminich.
* SPDX-License-Identifier: MIT
*/
import { TranslateModule, TranslateService } from '@ngx-translate/core'
import { HttpClientTestingModule } from '@angular/common/http/testing'
import { MatCardModule } from '@angular/material/card'
import { MatFormFieldModule } from '@... | { provide: MatSnackBar, useValue: snackBar }]
})
.compileComponents()
}))
beforeEach(() => {
fixture = TestBed.createComponent(AddressSelectComponent)
component = fixture.componentInstance
fixture.detectChanges()
})
it('should create', () => {
expect(component).toBeTruthy()
... | declarations: [AddressSelectComponent, AddressComponent, DeliveryMethodComponent],
providers: [{ provide: TranslateService, useValue: translateService }, | random_line_split |
serial.js | /**
* Filter to keep request sequence.
*/
var logger = require('pomelo-logger').getLogger('pomelo', __filename);
var taskManager = require('../../common/manager/taskManager');
module.exports = function() {
return new Filter();
};
var Filter = function() {
};
/**
* request serialization after filter
*/
Filter.p... |
next(err);
};
| {
if(!task.done() && !err) {
err = new Error('task time out. msg:' + JSON.stringify(msg));
}
} | conditional_block |
serial.js | /**
* Filter to keep request sequence.
*/
var logger = require('pomelo-logger').getLogger('pomelo', __filename);
var taskManager = require('../../common/manager/taskManager');
module.exports = function() {
return new Filter();
};
var Filter = function() {
};
/**
* request serialization after filter
*/
Filter.p... | };
/**
* request serialization after filter
*/
Filter.prototype.after = function(err, msg, session, resp, next) {
var task = session.__serialTask__;
if(task) {
if(!task.done() && !err) {
err = new Error('task time out. msg:' + JSON.stringify(msg));
}
}
next(err);
}; | session.__serialTask__ = task;
next();
}, function() {
logger.error('[serial filter] msg timeout, msg:' + JSON.stringify(msg));
}); | random_line_split |
ThreeMFWriter.py | # Copyright (c) 2015 Ultimaker B.V.
# Uranium is released under the terms of the AGPLv3 or higher.
from UM.Mesh.MeshWriter import MeshWriter
from UM.Math.Vector import Vector
from UM.Logger import Logger
from UM.Math.Matrix import Matrix
from UM.Application import Application
import UM.Scene.SceneNode
import Savitar
... | (self, stream, nodes, mode = MeshWriter.OutputMode.BinaryMode):
self._archive = None # Reset archive
archive = zipfile.ZipFile(stream, "w", compression = zipfile.ZIP_DEFLATED)
try:
model_file = zipfile.ZipInfo("3D/3dmodel.model")
# Because zipfile is stupid and ignores ar... | write | identifier_name |
ThreeMFWriter.py | # Copyright (c) 2015 Ultimaker B.V.
# Uranium is released under the terms of the AGPLv3 or higher.
from UM.Mesh.MeshWriter import MeshWriter
from UM.Math.Vector import Vector
from UM.Logger import Logger
from UM.Math.Matrix import Matrix
from UM.Application import Application
import UM.Scene.SceneNode
import Savitar
... | try:
model_file = zipfile.ZipInfo("3D/3dmodel.model")
# Because zipfile is stupid and ignores archive-level compression settings when writing with ZipInfo.
model_file.compress_type = zipfile.ZIP_DEFLATED
# Create content types file
content_types_file ... |
def write(self, stream, nodes, mode = MeshWriter.OutputMode.BinaryMode):
self._archive = None # Reset archive
archive = zipfile.ZipFile(stream, "w", compression = zipfile.ZIP_DEFLATED) | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.