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 |
|---|---|---|---|---|
GameClient.ts | import * as WS from "ws";
import {Faction} from "Common/Models";
import * as RPC from "Common/RPC";
import {ServerGame} from "./ServerGame";
export class GameClient extends RPC.RemotePeer {
public ws: WS;
public faction: Faction;
private joinedGame: ServerGame;
constructor(id: string, ws: WS) {
... | this.onMessage(data);
});
}
public get game() {
if (!this.joinedGame) {
throw new Error("Client is not in any game");
}
return this.joinedGame;
}
public set game(value: ServerGame) {
if (value) {
value.addPeer(this);
... | this.ws.on("message", (data) => { | random_line_split |
GameClient.ts | import * as WS from "ws";
import {Faction} from "Common/Models";
import * as RPC from "Common/RPC";
import {ServerGame} from "./ServerGame";
export class GameClient extends RPC.RemotePeer {
public ws: WS;
public faction: Faction;
private joinedGame: ServerGame;
constructor(id: string, ws: WS) {
... |
this.joinedGame.endTurn();
}
protected send(data: string) {
this.ws.send(data);
}
}
| {
throw new Error("Can't end turn when it's not your turn");
} | conditional_block |
log.py | #!/usr/bin/python3.4
# -*-coding:Utf-8 -*
'''module who manage the log of the script'''
import os
class Log:
'''class who manage the log of the script
there is to log:
the file where is save the log at each new line,
the string who is print eache time that the standart output is erase'''
def __init__(self, star... | 'print th running menu'''
if self.runMenu is not None:
print(self.runMenu)
| f):
'' | identifier_name |
log.py | #!/usr/bin/python3.4
# -*-coding:Utf-8 -*
'''module who manage the log of the script'''
import os
class Log:
'''class who manage the log of the script
there is to log:
the file where is save the log at each new line,
the string who is print eache time that the standart output is erase'''
def __init__(self, star... |
self.menu = []
self.runMenu = None
def __del__(self):
'''close the log file when the object is deleted'''
self.logFile.close()
del(self.log)
del(self.logFile)
def __str__(self):
'''return string log'''
return self.log
def print(self, menu = True):
'''print the log'''
... | self.write('log creation\n') | random_line_split |
log.py | #!/usr/bin/python3.4
# -*-coding:Utf-8 -*
'''module who manage the log of the script'''
import os
class Log:
'''class who manage the log of the script
there is to log:
the file where is save the log at each new line,
the string who is print eache time that the standart output is erase'''
def __init__(self, star... |
def menuIn(self, menu):
'''add a menu'''
self.menu.append(menu)
def menuOut(self):
'''quit a menu'''
return self.menu.pop()
def printMenu(self):
'''print three structure to current menu position'''
bar = '=========================='
print(bar)
if len(self.menu) == 0 :
prin... | '''redirect '+=' operator to the write()method'''
self.write(txt); | identifier_body |
log.py | #!/usr/bin/python3.4
# -*-coding:Utf-8 -*
'''module who manage the log of the script'''
import os
class Log:
'''class who manage the log of the script
there is to log:
the file where is save the log at each new line,
the string who is print eache time that the standart output is erase'''
def __init__(self, star... |
def write(self, txt, sep = '\n'):
'''add lines to the log'''
self.logFile.write(txt+sep)
self.log += txt+sep
def error(self, err, log = True):
'''Display a error message and add it to the log'''
err = '\033[31mError : '+err+'\033[0m\n'
self.menuIn('Error Message')
self.print()
prin... | self.printMenu() | conditional_block |
const.ts | import strings from './strings';
import * as Pages from './pages';
import * as Services from './services';
import * as Dao from './dao';
export const DEFAULT_PAGE: any = Pages.MainPage;
export const DEFAULT_LANG: string = 'en-US';
export const TABS: any[] = [
{ icon: 'people', title: strings.TAB_CARDS, component:... | 'public_profile',
'user_about_me',
'user_birthday',
'user_location',
];
export const GOOGLEPLUS_OPTIONS: any = {
scopes: [
'https://www.googleapis.com/auth/plus.login',
'https://www.googleapis.com/auth/plus.me',
'https://www.googleapis.com/auth/user.birthday.read',
'... | 'email', | random_line_split |
config.py | from pathlib import Path
import os
import structlog
log = structlog.get_logger()
_config = None
def get():
global _config
if not isinstance(_config, _build_config):
_config = _build_config()
return _config
class _build_config:
def __init__(self):
self._config = {}
self.dos... | if ctx not in self.env_var_contexts:
continue
log.info(f"discovered environ config", key=key)
if len(parts) == 2:
self.add_config_value(
parts[1], # key
os.environ[key], # value from env
c... | random_line_split | |
config.py | from pathlib import Path
import os
import structlog
log = structlog.get_logger()
_config = None
def get():
global _config
if not isinstance(_config, _build_config):
_config = _build_config()
return _config
class _build_config:
def __init__(self):
self._config = {}
self.dos... | log.info(f"dev ops shell bin: {self.dos_install_dir}")
dos_bin = Path(self.dos_install_dir)
dos_bin.mkdir(parents=True, exist_ok=True)
return dos_bin | identifier_body | |
config.py | from pathlib import Path
import os
import structlog
log = structlog.get_logger()
_config = None
def get():
global _config
if not isinstance(_config, _build_config):
_config = _build_config()
return _config
class _build_config:
def __init__(self):
self._config = {}
self.dos... |
log.info(f"discovered environ config", key=key)
if len(parts) == 2:
self.add_config_value(
parts[1], # key
os.environ[key], # value from env
context=ctx, # give context
)
elif len(parts)... | continue | conditional_block |
config.py | from pathlib import Path
import os
import structlog
log = structlog.get_logger()
_config = None
def get():
global _config
if not isinstance(_config, _build_config):
_config = _build_config()
return _config
class _build_config:
def __init__(self):
self._config = {}
self.dos... | (self, key, value, context="default"):
ctx_key = f"{context}_{key}"
self._config[ctx_key] = value
log.debug("set config", context=context, key=key, ctx_key=ctx_key)
def add_path_value(self, key, value, context):
self.add_config_value(key, Path(value), context=context)
def _load... | add_config_value | identifier_name |
conf.py |
import shlex
from datetime import date
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
#sys.path.insert(0, os.path.abspath('.'))... | # If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
# using the given strftime format.
#html_last_updated_fmt = '%b %d, %Y'
# If true, SmartyPants will be used to convert quotes and dashes to
# typographically correct entities.
#html_use_smartypants = True
# Custom sidebar templates, maps do... | random_line_split | |
i18n_ru.ts | <?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE TS><TS version="1.1" language="ru">
<defaultcodec></defaultcodec>
<context>
<name>MainView</name>
<message>
<source>View</source>
<translation>Вид</translation>
</message>
<message>
<source>&File</source>
<translation>Ф... | <translation>Первый</translation>
</message>
<message>
<source>Third</source>
<translation>Третий</translation>
</message>
<message>
<source>Language: %1</source>
<translation>Язык: %1</translation>
</message>
<message>
<source>English</source>
... | <source>First</source> | random_line_split |
test_executeSoon.js | /* Any copyright is dedicated to the Public Domain.
http://creativecommons.org/publicdomain/zero/1.0/ */
"use strict";
/**
* Client request stacks should span the entire process from before making the
* request to handling the reply from the server. The server frames are not
* included, nor can they be in most... | () {
let deferred = defer();
executeSoon(deferred.resolve);
return deferred.promise;
}
| waitForTick | identifier_name |
test_executeSoon.js | /* Any copyright is dedicated to the Public Domain.
http://creativecommons.org/publicdomain/zero/1.0/ */
"use strict";
/**
* Client request stacks should span the entire process from before making the
* request to handling the reply from the server. The server frames are not
* included, nor can they be in most... |
stack = stack.asyncCaller || stack.caller;
}
ok(false, "Incomplete stack");
});
function waitForTick() {
let deferred = defer();
executeSoon(deferred.resolve);
return deferred.promise;
}
| {
// Reached back to outer function before executeSoon
ok(true, "Complete stack");
return;
} | conditional_block |
test_executeSoon.js | /* Any copyright is dedicated to the Public Domain.
http://creativecommons.org/publicdomain/zero/1.0/ */
"use strict";
/**
* Client request stacks should span the entire process from before making the
* request to handling the reply from the server. The server frames are not
* included, nor can they be in most... | let stack = Components.stack;
while (stack) {
do_print(stack.name);
if (stack.name == "waitForTick") {
// Reached back to outer function before executeSoon
ok(true, "Complete stack");
return;
}
stack = stack.asyncCaller || stack.caller;
}
ok(false, "Incomplete stack");
});
fun... | random_line_split | |
test_executeSoon.js | /* Any copyright is dedicated to the Public Domain.
http://creativecommons.org/publicdomain/zero/1.0/ */
"use strict";
/**
* Client request stacks should span the entire process from before making the
* request to handling the reply from the server. The server frames are not
* included, nor can they be in most... | {
let deferred = defer();
executeSoon(deferred.resolve);
return deferred.promise;
} | identifier_body | |
communication.rs | use futures_util::{SinkExt, StreamExt};
use log::*;
use tokio::{
io::{AsyncRead, AsyncWrite},
net::{TcpListener, TcpStream},
};
use tokio_tungstenite::{accept_async, client_async, WebSocketStream};
use tungstenite::Message;
async fn run_connection<S>(
connection: WebSocketStream<S>,
msg_tx: futures_cha... |
con_rx.await.expect("Server not ready");
let tcp = TcpStream::connect("127.0.0.1:12346").await.expect("Failed to connect");
let url = url::Url::parse("ws://localhost:12345/").unwrap();
let (stream, _) = client_async(url, tcp).await.expect("Client failed to connect");
let (mut tx, _rx) = stream.spli... | {
let _ = env_logger::try_init();
let (con_tx, con_rx) = futures_channel::oneshot::channel();
let (msg_tx, msg_rx) = futures_channel::oneshot::channel();
let f = async move {
let listener = TcpListener::bind("127.0.0.1:12346").await.unwrap();
info!("Server ready");
con_tx.send(... | identifier_body |
communication.rs | use futures_util::{SinkExt, StreamExt};
use log::*;
use tokio::{
io::{AsyncRead, AsyncWrite},
net::{TcpListener, TcpStream},
};
use tokio_tungstenite::{accept_async, client_async, WebSocketStream};
use tungstenite::Message;
async fn run_connection<S>(
connection: WebSocketStream<S>,
msg_tx: futures_cha... | let (mut stream, _) = client_async(url, tcp).await.expect("Client failed to connect");
for i in 1..10 {
info!("Sending message");
stream.send(Message::Text(format!("{}", i))).await.expect("Failed to send message");
}
stream.close(None).await.expect("Failed to close");
info!("Waiti... | info!("Waiting for server to be ready");
con_rx.await.expect("Server not ready");
let tcp = TcpStream::connect("127.0.0.1:12345").await.expect("Failed to connect");
let url = "ws://localhost:12345/"; | random_line_split |
communication.rs | use futures_util::{SinkExt, StreamExt};
use log::*;
use tokio::{
io::{AsyncRead, AsyncWrite},
net::{TcpListener, TcpStream},
};
use tokio_tungstenite::{accept_async, client_async, WebSocketStream};
use tungstenite::Message;
async fn | <S>(
connection: WebSocketStream<S>,
msg_tx: futures_channel::oneshot::Sender<Vec<Message>>,
) where
S: AsyncRead + AsyncWrite + Unpin,
{
info!("Running connection");
let mut connection = connection;
let mut messages = vec![];
while let Some(message) = connection.next().await {
info!... | run_connection | identifier_name |
UsersListActions.tsx | import clsx from 'clsx'
import React, { useState } from 'react'
import { fade, makeStyles, Button, Tooltip, InputBase } from '@material-ui/core'
import {
MoreVert as IconMore,
Tune as IconFilter,
// ArrowDropDown as IconDropDown,
Add as IconNew,
Search as IconSearch,
Clear as IconClear,
} from '@material-... | height: '100%',
top: 0,
right: 0,
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
},
searchInputRoot: {
color: 'inherit',
},
searchInputInput: {
padding: theme.spacing(1, 1, 1, 0),
// vertical padding + font size from searchIcon
paddingLeft: `calc(1em + $... | justifyContent: 'center',
},
searchButtonClear: {
position: 'absolute', | random_line_split |
atomic_max_acq.rs | #![feature(core, core_intrinsics)]
extern crate core;
#[cfg(test)]
mod tests {
use core::intrinsics::atomic_max_acq;
use core::cell::UnsafeCell;
use std::sync::Arc;
use std::thread;
// pub fn atomic_max_acq<T>(dst: *mut T, src: T) -> T;
struct A<T> {
v: UnsafeCell<T>
}
unsafe imp... | () {
atomic_max_acq_test!( !0, 0, 0 );
}
}
| atomic_max_acq_test1 | identifier_name |
atomic_max_acq.rs | #![feature(core, core_intrinsics)]
extern crate core;
#[cfg(test)]
mod tests {
use core::intrinsics::atomic_max_acq;
use core::cell::UnsafeCell;
use std::sync::Arc;
use std::thread;
// pub fn atomic_max_acq<T>(dst: *mut T, src: T) -> T;
struct A<T> {
v: UnsafeCell<T>
}
unsafe imp... |
assert_eq!(old, $init);
});
thread::sleep_ms(10);
let ptr: *mut T = data.v.get();
assert_eq!(unsafe { *ptr }, $result);
})
}
#[test]
fn atomic_max_acq_test1() {
atomic_max_acq_test!( !0, 0, 0 );
}
} |
thread::spawn(move || {
let dst: *mut T = clone.v.get();
let src: T = $value;
let old: T = unsafe { atomic_max_acq::<T>(dst, src) }; | random_line_split |
_error.component.ts | <%#
Copyright 2013-2017 the original author or authors from the StackStack project.
This file is part of the StackStack project, see http://www.jhipster.tech/
for more information.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
Yo... |
});
}
}
| {
this.errorMessage = routeData.errorMessage;
} | conditional_block |
_error.component.ts | <%#
Copyright 2013-2017 the original author or authors from the StackStack project.
This file is part of the StackStack project, see http://www.jhipster.tech/
for more information.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
Yo... | () {
this.route.data.subscribe((routeData) => {
if (routeData.error403) {
this.error403 = routeData.error403;
}
if (routeData.errorMessage) {
this.errorMessage = routeData.errorMessage;
}
});
}
}
| ngOnInit | identifier_name |
_error.component.ts | <%#
Copyright 2013-2017 the original author or authors from the StackStack project.
This file is part of the StackStack project, see http://www.jhipster.tech/
for more information.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
Yo... | if (routeData.error403) {
this.error403 = routeData.error403;
}
if (routeData.errorMessage) {
this.errorMessage = routeData.errorMessage;
}
});
}
} |
ngOnInit() {
this.route.data.subscribe((routeData) => { | random_line_split |
buildServerApp.test.tsx | /**
* @jest-environment node
*/
import { SystemContextConsumer } from "Artsy"
import { createRelaySSREnvironment } from "Artsy/Relay/createRelaySSREnvironment"
import {
__THOU_SHALT_NOT_FAFF_AROUND_WITH_THIS_HERE_OBJECT_WE_ARE_SERIOUS__,
buildServerApp,
ServerRouterConfig,
} from "Artsy/Router/buildServerApp"
... | it("renders some media queries for known devices", async () => {
const { wrapper } = await getWrapper({
Component: MediaComponent,
userAgent: "Something iPhone; something",
})
expect(
wrapper
.find("span")
.map((_, el) => el.firstChild.data)
.g... | random_line_split | |
lbfgs.py | from cantilever_divingboard import *
# We need to scale the parameters before applying the optimization algorithm
# Normally there are about 20 orders of magnitude between the dimensions and |
# Run the script
freq_min = 1e3
freq_max = 1e5
omega_min = 100e3
initial_guess = (50e-6, 1e-6, 1e-6,
30e-6, 1e-6, 1e-6, 500e-9, 5., 1e15)
constraints = ((30e-6, 100e-6), (500e-9, 20e-6), (1e-6, 10e-6),
(2e-6, 100e-6), (500e-9, 5e-6), (500e-9, 20e-6), (30e-9, 10e-6),
... | # the doping concentration, so this is a critical step | random_line_split |
moderator.py | # Copyright 2014 The Oppia 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 applicable ... | """Provide default email templates for moderator emails."""
GET_HANDLER_ERROR_RETURN_TYPE = feconf.HANDLER_TYPE_JSON
@acl_decorators.can_send_moderator_emails
def get(self, action):
"""Handles GET requests."""
self.render_json({
'draft_email_body': (
email_manag... | identifier_body | |
moderator.py | # Copyright 2014 The Oppia 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 applicable ... | (self, action):
"""Handles GET requests."""
self.render_json({
'draft_email_body': (
email_manager.get_draft_moderator_action_email(action)),
})
| get | identifier_name |
moderator.py | # Copyright 2014 The Oppia 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 applicable ... | """Handles GET requests."""
self.render_json({
'draft_email_body': (
email_manager.get_draft_moderator_action_email(action)),
}) | random_line_split | |
setup.py | from setuptools import setup, find_packages # Always prefer setuptools over distutils
from codecs import open # To use a consistent encoding
from os import path
here = path.abspath(path.dirname(__file__))
# Get the long description from the relevant file
#with open(path.join(here, 'DESCRIPTION.rst'), encoding='utf-... | # 3 - Alpha
# 4 - Beta
# 5 - Production/Stable
'Development Status :: 4 - Beta',
# Indicate who your project is intended for
'Intended Audience :: Developers',
# Pick your license as you wish (should match "license" above)
'License :: OSI Approved ... | # See https://pypi.python.org/pypi?%3Aaction=list_classifiers
classifiers=[
# How mature is this project? Common values are | random_line_split |
field_collection.py | from office365.runtime.client_object_collection import ClientObjectCollection
from office365.runtime.client_query import CreateEntityQuery
from office365.runtime.resource_path_service_operation import ResourcePathServiceOperation
from office365.sharepoint.field import Field
class FieldCollection(ClientObjectCollectio... | """Returns the first field object in the collection based on the title of the specified field."""
return Field(self.context,
ResourcePathServiceOperation("getByTitle", [title], self.resourcePath)) | identifier_body | |
field_collection.py | from office365.runtime.client_object_collection import ClientObjectCollection
from office365.runtime.client_query import CreateEntityQuery
from office365.runtime.resource_path_service_operation import ResourcePathServiceOperation
from office365.sharepoint.field import Field
class FieldCollection(ClientObjectCollectio... | (self, name_title):
"""Returns the first Field object with the specified internal name or title from the collection."""
return Field(self.context,
ResourcePathServiceOperation("getByInternalNameOrTitle", [name_title], self.resourcePath))
def get_by_title(self, title):
"... | get_by_internal_name_or_title | identifier_name |
field_collection.py | from office365.runtime.client_object_collection import ClientObjectCollection
from office365.runtime.client_query import CreateEntityQuery
from office365.runtime.resource_path_service_operation import ResourcePathServiceOperation
from office365.sharepoint.field import Field
| def __init__(self, context, resource_path=None):
super(FieldCollection, self).__init__(context, Field, resource_path)
def add(self, field_creation_information):
"""Adds a field to the field collection."""
field = Field(self.context)
self.add_child(field)
qry = CreateEnti... | class FieldCollection(ClientObjectCollection):
"""Represents a collection of Field resource."""
| random_line_split |
viewer.js | import React, {Component} from 'react';
import PdfJS from './pdfJS';
import Contract from "../../contract";
import Event from '../../event';
import AnnotationLoader from '../../annotator/loader';
class Viewer extends Component {
constructor(props) {
super(props);
this.state = ({
page_n... | <div id={this.getPageID()} className="pdf-wrapper">
<PdfJS onPageRendered={this.onPageRendered.bind(this)}
file={this.state.pdf_url}
page={this.state.page_no}
scale={this.state.scale}/>
<... | </div>);
}
return (
<div className="pdf-viewer pdf-annotator"> | random_line_split |
viewer.js | import React, {Component} from 'react';
import PdfJS from './pdfJS';
import Contract from "../../contract";
import Event from '../../event';
import AnnotationLoader from '../../annotator/loader';
class Viewer extends Component {
constructor(props) {
super(props);
this.state = ({
page_n... |
Event.publish('annotation:loaded', 'pdf');
}
componentWillReceiveProps(props) {
this.updateState(props);
}
shouldComponentUpdate(nextProps, nextState) {
return (nextProps.page.page_no !== this.state.page_no || this.state.scale !== nextState.scale);
}
render() {
... | {
this.annotator.content.annotator("loadAnnotations", annotations);
} | conditional_block |
viewer.js | import React, {Component} from 'react';
import PdfJS from './pdfJS';
import Contract from "../../contract";
import Event from '../../event';
import AnnotationLoader from '../../annotator/loader';
class Viewer extends Component {
constructor(props) {
super(props);
this.state = ({
page_n... |
onPageRendered() {
if (!this.annotator) {
this.annotator = new AnnotationLoader('.pdf-annotator');
this.annotator.init();
Contract.setAnnotatorInstance(this.annotator);
}
const annotations = this.getAnnotations();
if (annotations.length > 0) {
... | {
let page = [];
let annotations = Contract.getAnnotations();
annotations.result.forEach(annotation=> {
if (typeof annotation.shapes == 'object' && this.state.page_no == annotation.page_no) {
page.push(annotation);
}
});
return page;
... | identifier_body |
viewer.js | import React, {Component} from 'react';
import PdfJS from './pdfJS';
import Contract from "../../contract";
import Event from '../../event';
import AnnotationLoader from '../../annotator/loader';
class Viewer extends Component {
constructor(props) {
super(props);
this.state = ({
page_n... | () {
return 'pdf-' + this.state.page_no;
}
getAnnotations() {
let page = [];
let annotations = Contract.getAnnotations();
annotations.result.forEach(annotation=> {
if (typeof annotation.shapes == 'object' && this.state.page_no == annotation.page_no) {
... | getPageID | identifier_name |
tests.py | import sys
from snf_django.management import utils
# Use backported unittest functionality if Python < 2.7
try:
import unittest2 as unittest | if sys.version_info < (2, 7):
raise Exception("The unittest2 package is required for Python < 2.7")
import unittest
class ParseFiltersTestCase(unittest.TestCase):
def test_parse_empty(self):
res = utils.parse_queryset_filters("")
self.assertEqual(res, ({}, {}))
def test_parse_... | except ImportError: | random_line_split |
tests.py | import sys
from snf_django.management import utils
# Use backported unittest functionality if Python < 2.7
try:
import unittest2 as unittest
except ImportError:
if sys.version_info < (2, 7):
raise Exception("The unittest2 package is required for Python < 2.7")
import unittest
class ParseFiltersTe... |
def test_parse_many(self):
res = utils.parse_queryset_filters("x=2,x>=3,y!=4,z<3")
filters = {"x": "2", "x__gte": "3", "z__lt": "3"}
excludes = {"y": "4"}
self.assertEqual(res, (filters, excludes))
if __name__ == '__main__':
unittest.main()
| res = utils.parse_queryset_filters("x=2")
self.assertEqual(res, ({"x": "2"}, {}))
res = utils.parse_queryset_filters("x!=2")
self.assertEqual(res, ({}, {"x": "2"})) | identifier_body |
tests.py | import sys
from snf_django.management import utils
# Use backported unittest functionality if Python < 2.7
try:
import unittest2 as unittest
except ImportError:
if sys.version_info < (2, 7):
|
import unittest
class ParseFiltersTestCase(unittest.TestCase):
def test_parse_empty(self):
res = utils.parse_queryset_filters("")
self.assertEqual(res, ({}, {}))
def test_parse_one(self):
res = utils.parse_queryset_filters("x=2")
self.assertEqual(res, ({"x": "2"}, {}))
... | raise Exception("The unittest2 package is required for Python < 2.7") | conditional_block |
tests.py | import sys
from snf_django.management import utils
# Use backported unittest functionality if Python < 2.7
try:
import unittest2 as unittest
except ImportError:
if sys.version_info < (2, 7):
raise Exception("The unittest2 package is required for Python < 2.7")
import unittest
class ParseFiltersTe... | (self):
res = utils.parse_queryset_filters("x=2,x>=3,y!=4,z<3")
filters = {"x": "2", "x__gte": "3", "z__lt": "3"}
excludes = {"y": "4"}
self.assertEqual(res, (filters, excludes))
if __name__ == '__main__':
unittest.main()
| test_parse_many | identifier_name |
websocket.js | ;Quintus.Websocket = function (Q) {
// prepare websocket connection
var connection;
var connect = function() {
var url = "ws://" + window.location.host + "/ws/";
connection = new WebSocket(url);
connection.onopen = function(){
console.log("webSocket open");
... | sendMessage(commandString);
};
// generate a unique id
var generateUUID = function () {
var d = new Date().getTime();
var uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
var r = (d + Math.random() * 16) % 16 | 0;
d = Math.floor(d... | var commandString = JSON.stringify(jsonCommand); | random_line_split |
websocket.js | ;Quintus.Websocket = function (Q) {
// prepare websocket connection
var connection;
var connect = function() {
var url = "ws://" + window.location.host + "/ws/";
connection = new WebSocket(url);
connection.onopen = function(){
console.log("webSocket open");
... |
else {
var data = {};
data[WSC_REGISTER_CAR_NAME] = name;
Q.sendCommand(WSC_REGISTER_CAR, data);
return false;
}
};
connect();
}; | {
alert("Please enter your name");
return false;
} | conditional_block |
no-access-key.js | /**
* @fileoverview Enforce no accesskey attribute on element.
* @author Ethan Cohen
*/
// ----------------------------------------------------------------------------
// Rule Definition
// ----------------------------------------------------------------------------
import { getProp, getPropValue } from 'jsx-ast-u... | }; | }), | random_line_split |
no-access-key.js | /**
* @fileoverview Enforce no accesskey attribute on element.
* @author Ethan Cohen
*/
// ----------------------------------------------------------------------------
// Rule Definition
// ----------------------------------------------------------------------------
import { getProp, getPropValue } from 'jsx-ast-u... |
},
}),
};
| {
context.report({
node,
message: errorMessage,
});
} | conditional_block |
modeman.py | parsers, keyparser
from qutebrowser.config import config
from qutebrowser.commands import cmdexc, cmdutils
from qutebrowser.utils import usertypes, log, objreg, utils
from qutebrowser.misc import objects
class KeyEvent:
"""A small wrapper over a QKeyEvent storing its data.
This is needed because Qt apparent... |
elif (m == | raise cmdexc.CommandError(
"Mode {} can't be entered manually!".format(mode)) | conditional_block |
modeman.py | parsers, keyparser
from qutebrowser.config import config
from qutebrowser.commands import cmdexc, cmdutils
from qutebrowser.utils import usertypes, log, objreg, utils
from qutebrowser.misc import objects
class | :
"""A small wrapper over a QKeyEvent storing its data.
This is needed because Qt apparently mutates existing events with new data.
It doesn't store the modifiers because they can be different for a key
press/release.
Attributes:
key: A Qt.Key member (QKeyEvent::key).
text: A stri... | KeyEvent | identifier_name |
modeman.py | .partial(objreg.delete, 'keyparsers', scope='window',
window=win_id))
for mode, parser in keyparsers.items():
modeman.register(mode, parser)
return modeman
def instance(win_id):
"""Get a modemanager object."""
return objreg.get('mode-manager', scope='window', window=w... | """Clear the currently entered key chain."""
self._parsers[self.mode].clear_keystring() | identifier_body | |
modeman.py | modeparsers, keyparser |
class KeyEvent:
"""A small wrapper over a QKeyEvent storing its data.
This is needed because Qt apparently mutates existing events with new data.
It doesn't store the modifiers because they can be different for a key
press/release.
Attributes:
key: A Qt.Key member (QKeyEvent::key).
... | from qutebrowser.config import config
from qutebrowser.commands import cmdexc, cmdutils
from qutebrowser.utils import usertypes, log, objreg, utils
from qutebrowser.misc import objects | random_line_split |
server.py | #!/usr/bin/python3
import _thread
import RPi.GPIO as GPIO
import socket
import time
from time import sleep
from sys import exit
import datetime
#import MySQLdb
# Start task command
# sleep 30 && python /home/pi/Scripts/Sprinkler/Sprinkler.py > /home/pi/Scripts/Sprinkler/log.txt 2>&1
# Set GPIO output poi... |
def statusLED(status):
if status == "blink":
GPIO.output(StatusLED, GPIO.HIGH)
sleep(0.5)
GPIO.output(StatusLED, GPIO.LOW)
sleep(0.5)
elif status == "solid":
GPIO.output(StatusLED, GPIO.HIGH)
elif status == "off":
GPIO.output(StatusLED, GPIO.LOW)
def addLog(currentZone, addedText):
now ... | if GPIO.input(WaterSensor):
isRaining = True
else:
isRaining = False | conditional_block |
server.py | #!/usr/bin/python3
import _thread
import RPi.GPIO as GPIO
import socket
import time
from time import sleep
from sys import exit
import datetime
#import MySQLdb
# Start task command
# sleep 30 && python /home/pi/Scripts/Sprinkler/Sprinkler.py > /home/pi/Scripts/Sprinkler/log.txt 2>&1
# Set GPIO output poi... | (zoneNum, duration):
# Turn on zone
zone(int(zoneNum), "ON")
statusLED("on")
# Sleep for that amount
sleep(int(duration) * 60)
# Turn off zone
zone(int(zoneNum), "OFF")
statusLED("off")
# Zone Control Setup
def zone(zoneSelect, onoff):
if(onoff == "ON"):
GPIO.output(Zones[zoneSelect], 0)... | water | identifier_name |
server.py | #!/usr/bin/python3
import _thread
import RPi.GPIO as GPIO
import socket
import time
from time import sleep
from sys import exit
import datetime
#import MySQLdb
# Start task command
| # sleep 30 && python /home/pi/Scripts/Sprinkler/Sprinkler.py > /home/pi/Scripts/Sprinkler/log.txt 2>&1
# Set GPIO output points
Zones = [5, 6, 13, 19]
StatusLED = 16
# Set GPIO input points
CancelButton = 18
WaterSensor = 10
# Water Sensor Enabled?
Sensor = False
#Is it currently raining
isRaining = F... | random_line_split | |
server.py | #!/usr/bin/python3
import _thread
import RPi.GPIO as GPIO
import socket
import time
from time import sleep
from sys import exit
import datetime
#import MySQLdb
# Start task command
# sleep 30 && python /home/pi/Scripts/Sprinkler/Sprinkler.py > /home/pi/Scripts/Sprinkler/log.txt 2>&1
# Set GPIO output poi... |
if __name__ == '__main__':
setup()
try:
mainRun()
except KeyboardInterrupt:
destroy()
finally:
GPIO.cleanup()
exit()
else:
destroy()
| global serversocket
serversocket.shutdown(socket.SHUT_RDWR)
for i in Zones:
GPIO.output(i, GPIO.LOW)
GPIO.output(StatusLED, GPIO.LOW)
addLog('System', 'Sprinkler Script OFF')
exit() | identifier_body |
istr.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | fn test_append() {
let mut s = ~"";
s += ~"a";
assert!((s == ~"a"));
let mut s = ~"a";
s += ~"b";
debug!(s.clone());
assert!((s == ~"ab"));
let mut s = ~"c";
s += ~"offee";
assert!((s == ~"coffee"));
s += ~"&tea";
assert!((s == ~"coffee&tea"));
}
pub fn main() {
t... | }
| random_line_split |
istr.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
fn test_stack_add() {
assert!((~"a" + ~"b" == ~"ab"));
let s: ~str = ~"a";
assert!((s + s == ~"aa"));
assert!((~"" + ~"" == ~""));
}
fn test_stack_heap_add() { assert!((~"a" + ~"bracadabra" == ~"abracadabra")); }
fn test_heap_add() {
assert!((~"this should" + ~" totally work" == ~"this should to... | { let s = ~"a big ol' string"; debug!(s); } | identifier_body |
istr.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | () {
assert!((~"this should" + ~" totally work" == ~"this should totally work"));
}
fn test_append() {
let mut s = ~"";
s += ~"a";
assert!((s == ~"a"));
let mut s = ~"a";
s += ~"b";
debug!(s.clone());
assert!((s == ~"ab"));
let mut s = ~"c";
s += ~"offee";
assert!((s == ~"... | test_heap_add | identifier_name |
zip.py | # Copyright (c) 2017 Civic Knowledge. This file is licensed under the terms of the
# MIT, included in this distribution as LICENSE
""" """
from rowgenerators.appurl.file.file import FileUrl |
class ZipUrlError(AppUrlError):
pass
class ZipUrl(FileUrl):
"""Zip URLS represent a zip file, as a local resource. """
match_priority = FileUrl.match_priority - 10
def __init__(self, url=None, downloader=None, **kwargs):
kwargs['resource_format'] = 'zip'
super().__init__(url, downlo... | from rowgenerators.exceptions import AppUrlError
| random_line_split |
zip.py | # Copyright (c) 2017 Civic Knowledge. This file is licensed under the terms of the
# MIT, included in this distribution as LICENSE
""" """
from rowgenerators.appurl.file.file import FileUrl
from rowgenerators.exceptions import AppUrlError
class ZipUrlError(AppUrlError):
pass
class ZipUrl(FileUrl):
|
if self.fragment[0]:
return self.fragment[0]
for ext in ('csv', 'xls', 'xlsx'):
if self.resource_file.endswith('.' + ext + '.zip'):
return self.resource_file.replace('.zip', '')
# Want to return none, so get_files_from-zip can assume to use the first fi... | """Zip URLS represent a zip file, as a local resource. """
match_priority = FileUrl.match_priority - 10
def __init__(self, url=None, downloader=None, **kwargs):
kwargs['resource_format'] = 'zip'
super().__init__(url, downloader=downloader, **kwargs)
@property
def target_file(self):
... | identifier_body |
zip.py | # Copyright (c) 2017 Civic Knowledge. This file is licensed under the terms of the
# MIT, included in this distribution as LICENSE
""" """
from rowgenerators.appurl.file.file import FileUrl
from rowgenerators.exceptions import AppUrlError
class ZipUrlError(AppUrlError):
pass
class ZipUrl(FileUrl):
"""Zip ... |
# Want to return none, so get_files_from-zip can assume to use the first file in the archive.
return None
def join_target(self, tf):
"""
Joins the target ``tf`` by setting the value of the first slot of the fragment.
:param tf:
:return: a clone of this url with a ... | return self.resource_file.replace('.zip', '') | conditional_block |
zip.py | # Copyright (c) 2017 Civic Knowledge. This file is licensed under the terms of the
# MIT, included in this distribution as LICENSE
""" """
from rowgenerators.appurl.file.file import FileUrl
from rowgenerators.exceptions import AppUrlError
class ZipUrlError(AppUrlError):
pass
class ZipUrl(FileUrl):
"""Zip ... | (self):
"""
Returns the target file, which is usually stored in the first slot in the ``fragment``,
but may have been overridden with a ``fragment_query``.
:return:
"""
if self._target_file:
return self._target_file
if self.fragment[0]:
r... | target_file | identifier_name |
PyGdbDb.py | 数据库游标: ' + str(self.cursor) if self.cursor else '数据库游标异常'
print '数据库连接测试完毕'
print '检查表 aabb 是否存在'
if self.exist_table('aabb'):
print '存在'
else:
print '不存在'
print '初始化项目 example'
self.init_project('example', 'example_')
self.new_project()
... | TestCase')
return int(self.cursor.fetchone()[0])
# 获取指定程序的断点列表
def get_breakpoint_list(self, pid):
self.execute('SELECT lineNumber FROM ' + self.table_prefix + 'BreakPoint WHERE pid="%s"' % pid)
all = self.cursor.fetchall()
return [x[0] for x in all]
# 执行 sql 语句
def exe... | prefix + ' | identifier_name |
PyGdbDb.py | 数据库游标: ' + str(self.cursor) if self.cursor else '数据库游标异常'
print '数据库连接测试完毕'
print '检查表 aabb 是否存在'
if self.exist_table('aabb'):
print '存在'
else:
print '不存在'
print '初始化项目 example'
self.init_project('example', 'example_')
self.new_project()
... | return False
# 创建表
def create_table(self, table_name):
try:
PyGdbUtil.log(0, "创建表" + table_name)
self.execute("create table if not exists " + table_name)
except Exception as e:
# print e
PyGdbUtil.log(2, "创建表" + table_name + "失败! 请检查数据表前缀是否有非法字符... | ('select * from ' + table_name)
return True
except Exception:
| conditional_block |
PyGdbDb.py | 数据库游标: ' + str(self.cursor) if self.cursor else '数据库游标异常'
print '数据库连接测试完毕'
print '检查表 aabb 是否存在'
if self.exist_table('aabb'):
print '存在'
else:
print '不存在'
print '初始化项目 example'
self.init_project('example', 'example_')
self.new_project()
... |
# 创建数据库表
if not exist_project:
self.create_table(self.table_prefix + "BreakPoint(bid INT AUTO_INCREMENT primary key, pid INT, lineNumber INT, funcName TEXT, funcList TEXT)")
self.create_table(self.table_prefix + "PStackSize(pid INT, tid INT, stackSize INT, pass TINYINT)")
... | if not self.table_prefix:
PyGdbUtil.log(2, '未指定数据库前缀')
exist_project = self.exist_table(self.table_prefix + 'BreakPoint') | random_line_split |
PyGdbDb.py | ')
exist_project = self.exist_table(self.table_prefix + 'BreakPoint')
# 创建数据库表
if not exist_project:
self.create_table(self.table_prefix + "BreakPoint(bid INT AUTO_INCREMENT primary key, pid INT, lineNumber INT, funcName TEXT, funcList TEXT)")
self.create_table(self.tabl... | _pid, tid_list):
| identifier_body | |
derivedInterfaceCallSignature.ts | interface D3SvgPath {
(data: any, index?: number): string;
x(): (data: any, index?: number) => number;
y(): (data: any, index?: number) => number;
interpolate(): string;
tension(): number;
defined(): (data: any, index?: number) => boolean;
}
interface D3SvgArea extends D3SvgPath {
| y0(y: number): D3SvgArea;
y0(y: (data: any, index?: number) => number): D3SvgArea;
y1(): (data: any, index?: number) => number;
y1(y: number): D3SvgArea;
y1(y: (data: any, index?: number) => number): D3SvgArea;
interpolate(interpolator: string): D3SvgArea;
tension(tension: number): D... | x(x: (data: any, index?: number) => number): D3SvgArea;
y(y: (data: any, index?: number) => number): D3SvgArea;
y0(): (data: any, index?: number) => number;
| random_line_split |
symbolic_color.rs | // This file was generated by gir (https://github.com/gtk-rs/gir)
// from gir-files (https://github.com/gtk-rs/gir-files)
// DO NOT EDIT
use StyleProperties;
use ffi;
use gdk;
use glib::translate::*;
use glib_ffi;
use gobject_ffi;
use std::fmt;
use std::mem;
use std::ptr;
glib_wrapper! {
#[derive(Debug, PartialEq... | unsafe {
from_glib_full(ffi::gtk_symbolic_color_new_alpha(color.to_glib_none().0, factor))
}
}
#[cfg_attr(feature = "v3_8", deprecated)]
pub fn new_literal(color: &gdk::RGBA) -> SymbolicColor {
assert_initialized_main_thread!();
unsafe {
from_glib_ful... | assert_initialized_main_thread!(); | random_line_split |
symbolic_color.rs | // This file was generated by gir (https://github.com/gtk-rs/gir)
// from gir-files (https://github.com/gtk-rs/gir-files)
// DO NOT EDIT
use StyleProperties;
use ffi;
use gdk;
use glib::translate::*;
use glib_ffi;
use gobject_ffi;
use std::fmt;
use std::mem;
use std::ptr;
glib_wrapper! {
#[derive(Debug, PartialEq... | <'a, P: Into<Option<&'a StyleProperties>>>(&self, props: P) -> Option<gdk::RGBA> {
let props = props.into();
let props = props.to_glib_none();
unsafe {
let mut resolved_color = gdk::RGBA::uninitialized();
let ret = from_glib(ffi::gtk_symbolic_color_resolve(self.to_glib_no... | resolve | identifier_name |
symbolic_color.rs | // This file was generated by gir (https://github.com/gtk-rs/gir)
// from gir-files (https://github.com/gtk-rs/gir-files)
// DO NOT EDIT
use StyleProperties;
use ffi;
use gdk;
use glib::translate::*;
use glib_ffi;
use gobject_ffi;
use std::fmt;
use std::mem;
use std::ptr;
glib_wrapper! {
#[derive(Debug, PartialEq... |
#[cfg_attr(feature = "v3_8", deprecated)]
pub fn new_name(name: &str) -> SymbolicColor {
assert_initialized_main_thread!();
unsafe {
from_glib_full(ffi::gtk_symbolic_color_new_name(name.to_glib_none().0))
}
}
#[cfg_attr(feature = "v3_8", deprecated)]
pub fn new... | {
assert_initialized_main_thread!();
unsafe {
from_glib_full(ffi::gtk_symbolic_color_new_mix(color1.to_glib_none().0, color2.to_glib_none().0, factor))
}
} | identifier_body |
symbolic_color.rs | // This file was generated by gir (https://github.com/gtk-rs/gir)
// from gir-files (https://github.com/gtk-rs/gir-files)
// DO NOT EDIT
use StyleProperties;
use ffi;
use gdk;
use glib::translate::*;
use glib_ffi;
use gobject_ffi;
use std::fmt;
use std::mem;
use std::ptr;
glib_wrapper! {
#[derive(Debug, PartialEq... |
}
}
#[cfg_attr(feature = "v3_8", deprecated)]
fn to_string(&self) -> String {
unsafe {
from_glib_full(ffi::gtk_symbolic_color_to_string(self.to_glib_none().0))
}
}
}
impl fmt::Display for SymbolicColor {
#[inline]
fn fmt(&self, f: &mut fmt::Formatter) -> fm... | { None } | conditional_block |
lib.rs |
pub trait TakeWhileWithFailureIterator: Iterator {
fn take_while_with_failure<P>(self, predicate: P) -> TakeWhileWithFailure<Self, P> where
P: FnMut(&Self::Item) -> bool, Self: Sized {
TakeWhileWithFailure{iter: self, flag: false, predicate: predicate}
}
}
/// An iterator that accepts ... |
#[test]
fn it_works_on_empty_vecs() {
let empty_vec: Vec<i64> = Vec::new();
assert_eq!(empty_vec.iter().take_while_with_failure(|_| true).collect::<Vec<&i64>>().len(), 0);
}
| {
assert_eq!(vec![2,4,5,6].iter().take_while_with_failure(|_| true).collect::<Vec<&i64>>(), vec![&2,&4,&5,&6]);
} | identifier_body |
lib.rs | pub trait TakeWhileWithFailureIterator: Iterator {
fn take_while_with_failure<P>(self, predicate: P) -> TakeWhileWithFailure<Self, P> where
P: FnMut(&Self::Item) -> bool, Self: Sized {
TakeWhileWithFailure{iter: self, flag: false, predicate: predicate}
}
}
/// An iterator that accepts e... | (0, upper) // can't know a lower bound, due to the predicate
}
}
impl<'a, I: Iterator + ?Sized> TakeWhileWithFailureIterator for I {
/// Creates an iterator that yields elements as long as the predicate returns true.
/// Additionally, it includes the first element that returns false, after which ... | #[inline]
fn size_hint(&self) -> (usize, Option<usize>) {
let (_, upper) = self.iter.size_hint(); | random_line_split |
lib.rs |
pub trait TakeWhileWithFailureIterator: Iterator {
fn take_while_with_failure<P>(self, predicate: P) -> TakeWhileWithFailure<Self, P> where
P: FnMut(&Self::Item) -> bool, Self: Sized {
TakeWhileWithFailure{iter: self, flag: false, predicate: predicate}
}
}
/// An iterator that accepts ... | (&self) -> (usize, Option<usize>) {
let (_, upper) = self.iter.size_hint();
(0, upper) // can't know a lower bound, due to the predicate
}
}
impl<'a, I: Iterator + ?Sized> TakeWhileWithFailureIterator for I {
/// Creates an iterator that yields elements as long as the predicate returns true.
... | size_hint | identifier_name |
lib.rs |
pub trait TakeWhileWithFailureIterator: Iterator {
fn take_while_with_failure<P>(self, predicate: P) -> TakeWhileWithFailure<Self, P> where
P: FnMut(&Self::Item) -> bool, Self: Sized {
TakeWhileWithFailure{iter: self, flag: false, predicate: predicate}
}
}
/// An iterator that accepts ... |
Some(x)
})
}
}
#[inline]
fn size_hint(&self) -> (usize, Option<usize>) {
let (_, upper) = self.iter.size_hint();
(0, upper) // can't know a lower bound, due to the predicate
}
}
impl<'a, I: Iterator + ?Sized> TakeWhileWithFailureIterator for I {
... | {
self.flag = true;
} | conditional_block |
layouts.module.ts | import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { layoutsRoutes } from './layouts.routes';
import { LayoutsComponent } from './layouts.component';
import { LayoutsOverviewComponent } from './overview/overview.component';
import { NavViewComponent } from './nav-view/nav... | {}
| LayoutsModule | identifier_name |
layouts.module.ts | import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { layoutsRoutes } from './layouts.routes';
import { LayoutsComponent } from './layouts.component';
import { LayoutsOverviewComponent } from './overview/overview.component';
import { NavViewComponent } from './nav-view/nav... | ToolbarModule,
],
})
export class LayoutsModule {} | random_line_split | |
factories.py | import factory
from api import models
class ClientFactory(factory.DjangoModelFactory):
class Meta:
model = models.Client
name = 'Coaxis'
@factory.django.mute_signals(models.post_save)
class UserFactory(factory.DjangoModelFactory):
class Meta:
model = models.MyUser
email = factory.... |
class TechnicianFactory(EmployeeFactory):
is_technician = True
class DaemonFactory(factory.DjangoModelFactory):
class Meta:
model = models.Daemon
client = factory.SubFactory(ClientFactory)
| for client in extracted:
self.clients.add(client) | conditional_block |
factories.py | import factory
from api import models
class ClientFactory(factory.DjangoModelFactory):
class Meta:
model = models.Client
name = 'Coaxis'
@factory.django.mute_signals(models.post_save)
class UserFactory(factory.DjangoModelFactory):
class Meta:
model = models.MyUser
email = factory.... | :
model = models.Employee
user = factory.SubFactory(UserFactory)
is_technician = False
@factory.post_generation
def clients(self, create, extracted, **kwargs):
if not create: # Simple build, do nothing.
return
if extracted: # A list of objects were passed in, use... | Meta | identifier_name |
factories.py | import factory
from api import models
class ClientFactory(factory.DjangoModelFactory):
class Meta:
model = models.Client
name = 'Coaxis'
@factory.django.mute_signals(models.post_save)
class UserFactory(factory.DjangoModelFactory):
class Meta:
model = models.MyUser
email = factory.... | client = factory.SubFactory(ClientFactory) | random_line_split | |
factories.py | import factory
from api import models
class ClientFactory(factory.DjangoModelFactory):
class Meta:
model = models.Client
name = 'Coaxis'
@factory.django.mute_signals(models.post_save)
class UserFactory(factory.DjangoModelFactory):
class Meta:
model = models.MyUser
email = factory.... |
class DaemonFactory(factory.DjangoModelFactory):
class Meta:
model = models.Daemon
client = factory.SubFactory(ClientFactory)
| is_technician = True | identifier_body |
index.d.ts | // Type definitions for linkedin dustjs 1.2.1
// Project: https://github.com/linkedin/dustjs
// Definitions by: Marcelo Dezem <http://github.com/mdezem>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
//
// Due to a lack of documentation it's not possible
// to know which methods are intended to be ... |
/**
* Renders a template block, such as a default block or an else block.
*/
render(body: any, context: Context): Chunk;
/**
* Sets an error on this chunk and immediately flushes the output.
*/
setError(err: any): Chunk;
}
export interface Context {
/**
* Retrieves the value a... | * Removes the head tap function from the list.
*/
untap(): Chunk; | random_line_split |
unrooted_must_root.rs | Context};
use rustc::ty;
use syntax::{ast, codemap};
use utils::{match_def_path, in_derive_expn};
declare_lint!(UNROOTED_MUST_ROOT, Deny,
"Warn and report usage of unrooted jsmanaged objects");
/// Lint for ensuring safe usage of unrooted pointers
///
/// This lint (disable with `-A unrooted-must-root`/... | () -> UnrootedPass {
UnrootedPass
}
}
/// Checks if a type is unrooted or contains any owned unrooted types
fn is_unrooted_ty(cx: &LateContext, ty: &ty::TyS, in_new_function: bool) -> bool {
let mut ret = false;
ty.maybe_walk(|t| {
match t.sty {
ty::TyAdt(did, _) => {
... | new | identifier_name |
unrooted_must_root.rs | intContext};
use rustc::ty;
use syntax::{ast, codemap};
use utils::{match_def_path, in_derive_expn};
declare_lint!(UNROOTED_MUST_ROOT, Deny,
"Warn and report usage of unrooted jsmanaged objects");
/// Lint for ensuring safe usage of unrooted pointers
///
/// This lint (disable with `-A unrooted-must-roo... | ty::TyRef(..) => false, // don't recurse down &ptrs
ty::TyRawPtr(..) => false, // don't recurse down *ptrs
ty::TyFnDef(..) | ty::TyFnPtr(_) => false,
_ => true
}
});
ret
}
impl LintPass for UnrootedPass {
fn get_lints(&self) -> LintArray {
lin... | true
}
},
ty::TyBox(..) if in_new_function => false, // box in new() is okay | random_line_split |
unrooted_must_root.rs | Context};
use rustc::ty;
use syntax::{ast, codemap};
use utils::{match_def_path, in_derive_expn};
declare_lint!(UNROOTED_MUST_ROOT, Deny,
"Warn and report usage of unrooted jsmanaged objects");
/// Lint for ensuring safe usage of unrooted pointers
///
/// This lint (disable with `-A unrooted-must-root`/... | else if match_def_path(cx, did.did, &["core", "cell", "Ref"])
|| match_def_path(cx, did.did, &["core", "cell", "RefMut"])
|| match_def_path(cx, did.did, &["core", "slice", "Iter"])
|| match_def_path(cx, did.did, &["std", "collections", "hash", "ma... | {
false
} | conditional_block |
FileUploader.tsx | import * as React from 'react'
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'
import { classes, bytesToSize } from '@framework/Globals'
import { ModifiableEntity, JavascriptMessage } from '@framework/Signum.Entities'
import { IFile, IFilePath, FileMessage, FileTypeSymbol } from './Signum.Entities.... | multiple?: boolean;
buttonCss?: string;
fileDropCssClass?: string;
divHtmlAttributes?: React.HTMLAttributes<HTMLDivElement>;
maxSizeInBytes?: number;
}
export interface FileUploaderState {
isLoading?: boolean;
isOver?: boolean;
errors: string[];
}
export function FileUploader(p: FileUploa... | dragAndDrop?: boolean;
dragAndDropMessage?: string;
accept?: string;
| random_line_split |
FileUploader.tsx | import * as React from 'react'
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'
import { classes, bytesToSize } from '@framework/Globals'
import { ModifiableEntity, JavascriptMessage } from '@framework/Signum.Entities'
import { IFile, IFilePath, FileMessage, FileTypeSymbol } from './Signum.Entities.... | (e: React.DragEvent<any>) {
e.stopPropagation();
e.preventDefault();
uploadAll(e.dataTransfer.files);
}
function handleFileChange(e: React.FormEvent<any>) {
e.preventDefault();
var input = e.target as HTMLInputElement;
uploadAll(input.files!);
}
function uploadAll(fil... | handleDrop | identifier_name |
FileUploader.tsx | import * as React from 'react'
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'
import { classes, bytesToSize } from '@framework/Globals'
import { ModifiableEntity, JavascriptMessage } from '@framework/Signum.Entities'
import { IFile, IFilePath, FileMessage, FileTypeSymbol } from './Signum.Entities.... |
if (file.name.contains("%")) {
reject(new Error(FileMessage.TheNameOfTheFileMustNotContainPercentSymbol.niceToString()));
return;
}
const fileReader = new FileReader();
fileReader.onerror = e => { reject(e); };
fileReader.onload = e => {
const fileEntity = New(o.type) ... | {
reject(new Error(FileMessage.File0IsTooBigTheMaximumSizeIs1.niceToString(file.name, bytesToSize(o.maxSizeInBytes))));
return;
} | conditional_block |
FileUploader.tsx | import * as React from 'react'
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'
import { classes, bytesToSize } from '@framework/Globals'
import { ModifiableEntity, JavascriptMessage } from '@framework/Signum.Entities'
import { IFile, IFilePath, FileMessage, FileTypeSymbol } from './Signum.Entities.... |
function handleFileChange(e: React.FormEvent<any>) {
e.preventDefault();
var input = e.target as HTMLInputElement;
uploadAll(input.files!);
}
function uploadAll(files: FileList) {
setErrors([]);
setIsOver(false);
setIsLodaing(true);
var promises: Promise<void>[] = ... | {
e.stopPropagation();
e.preventDefault();
uploadAll(e.dataTransfer.files);
} | identifier_body |
UploadPhoto.jest.tsx | import UploadPhoto from "desktop/apps/consign/components/upload_photo"
import UploadedImage from "desktop/apps/consign/components/uploaded_image"
import * as actions from "desktop/apps/consign/client//actions"
import reducers from "desktop/apps/consign/client/reducers"
import { createStore } from "redux"
import { mount... |
it("disables the submit button when there are no photos", () => {
const wrapper = mount(<UploadPhoto store={initialStore} />)
expect(
wrapper.find(
".consignments-submission-upload-photo__submit-button[disabled]"
).length
).toBe(1)
})
describe("with photos", () => {
it("enabl... | })
beforeEach(() => {
UploadedImage.mockImplementation(() => <div className="uploaded-image" />)
}) | random_line_split |
percent_page_viewed.js | // change these variables
var data_source_name = "";
// end changes
if(a=="view"){
(function (u,c,p,a,r,q) {
if (!utag.ut) utag.ut = {};
r = function (w, x, y, z) {
// read cookie
x = w + "=";
y = document.cookie.split(';');
for (var i = 0; i < y... | if (!utag.ut.getPPVid) {
utag.ut.getPPVid = (p) ? (p) : document.location.href;
q(c, escape(utag.ut.getPPVid));
if (window.addEventListener) {
window.addEventListener('load', utag.ut.hppv, false);
window.addEventListener('scroll', utag.ut.hppv,... | }
a[0] = unescape(a[0]);
q(c, escape(p)); | random_line_split |
gcmt_utils.py | #!/usr/bin/env/python
'''
Set of moment tensor utility functions
'''
import numpy as np
from math import fabs, log10, sqrt, acos, atan2, pi
def tensor_components_to_use(mrr, mtt, mpp, mrt, mrp, mtp):
'''
Converts components to Up, South, East definition
USE = [[mrr, mrt, mrp],
[mtt, mtt, mtp],... |
if alpha == 0.5 * pi and beta >= pi:
gamma = - gamma
beta = np.mod(beta-pi, 2.0 * pi)
gamma = np.mod( gamma + pi, 2.0 * pi) - pi
assert 0. <= beta < pi
assert -pi <= gamma < pi
if alpha < 1e-7:
beta = np.mod(beta + gamma, 2.0 * pi)
gamma = 0... | beta = 0. | conditional_block |
gcmt_utils.py | #!/usr/bin/env/python
'''
Set of moment tensor utility functions
'''
import numpy as np
from math import fabs, log10, sqrt, acos, atan2, pi
def tensor_components_to_use(mrr, mtt, mpp, mrt, mrp, mtp):
'''
Converts components to Up, South, East definition
USE = [[mrr, mrt, mrp],
[mtt, mtt, mtp],... | return eigenvalues, eigenvectors
def matrix_to_euler( rotmat ):
'''Inverse of euler_to_matrix().'''
if not isinstance(rotmat, np.matrixlib.defmatrix.matrix):
# As this calculation relies on np.matrix algebra - convert array to
# matrix
rotmat = np.matrix(rotmat)
cvec = lambda ... | eigenvalues = eigvals[isrt] * tensor_norm
eigenvectors = eigvects[:, isrt] | random_line_split |
gcmt_utils.py | #!/usr/bin/env/python
'''
Set of moment tensor utility functions
'''
import numpy as np
from math import fabs, log10, sqrt, acos, atan2, pi
def tensor_components_to_use(mrr, mtt, mpp, mrt, mrp, mtp):
'''
Converts components to Up, South, East definition
USE = [[mrr, mrt, mrp],
[mtt, mtt, mtp],... | ( rotmat ):
'''Inverse of euler_to_matrix().'''
if not isinstance(rotmat, np.matrixlib.defmatrix.matrix):
# As this calculation relies on np.matrix algebra - convert array to
# matrix
rotmat = np.matrix(rotmat)
cvec = lambda x, y, z: np.matrix([[x, y, z]]).T
ex = cvec(1., 0., 0.)... | matrix_to_euler | identifier_name |
gcmt_utils.py | #!/usr/bin/env/python
'''
Set of moment tensor utility functions
'''
import numpy as np
from math import fabs, log10, sqrt, acos, atan2, pi
def tensor_components_to_use(mrr, mtt, mpp, mrt, mrp, mtp):
'''
Converts components to Up, South, East definition
USE = [[mrr, mrt, mrp],
[mtt, mtt, mtp],... |
def ned_to_use(tensor):
'''
Converts a tensor in NED coordinate sytem to USE
'''
return np.array(ROT_NED_USE * np.matrix(tensor) * ROT_NED_USE.T)
def tensor_to_6component(tensor, frame='USE'):
'''
Returns a tensor to six component vector [Mrr, Mtt, Mpp, Mrt, Mrp, Mtp]
'''
if 'NED' in... | '''
Converts a tensor in USE coordinate sytem to NED
'''
return np.array(ROT_NED_USE.T * np.matrix(tensor) * ROT_NED_USE) | identifier_body |
base-repository.ts | import { BehaviorSubject, Observable } from 'rxjs';
import { OpenSlidesComponent } from '../../openslides.component';
import { BaseViewModel } from './base-view-model';
import { BaseModel, ModelConstructor } from '../../shared/models/base/base-model';
import { CollectionStringModelMapperService } from '../../core/serv... | * Triggers both the observable update routines
*/
protected updateAllObservables(id: number): void {
this.updateViewModelListObservable();
this.updateViewModelObservable(id);
}
} | /** | random_line_split |
base-repository.ts | import { BehaviorSubject, Observable } from 'rxjs';
import { OpenSlidesComponent } from '../../openslides.component';
import { BaseViewModel } from './base-view-model';
import { BaseModel, ModelConstructor } from '../../shared/models/base/base-model';
import { CollectionStringModelMapperService } from '../../core/serv... | (id: number): void {
if (this.viewModelSubjects[id]) {
this.viewModelSubjects[id].next(this.viewModelStore[id]);
}
}
/**
* update the observable of the list
*/
protected updateViewModelListObservable(): void {
this.viewModelListSubject.next(this.getViewModelLis... | updateViewModelObservable | identifier_name |
base-repository.ts | import { BehaviorSubject, Observable } from 'rxjs';
import { OpenSlidesComponent } from '../../openslides.component';
import { BaseViewModel } from './base-view-model';
import { BaseModel, ModelConstructor } from '../../shared/models/base/base-model';
import { CollectionStringModelMapperService } from '../../core/serv... |
/**
* helper function to return the viewModel as array
*/
public getViewModelList(): V[] {
return Object.values(this.viewModelStore);
}
/**
* returns the current observable for one viewModel
*/
public getViewModelObservable(id: number): Observable<V> {
if (!thi... | {
return this.viewModelStore[id];
} | identifier_body |
base-repository.ts | import { BehaviorSubject, Observable } from 'rxjs';
import { OpenSlidesComponent } from '../../openslides.component';
import { BaseViewModel } from './base-view-model';
import { BaseModel, ModelConstructor } from '../../shared/models/base/base-model';
import { CollectionStringModelMapperService } from '../../core/serv... |
return this.viewModelSubjects[id].asObservable();
}
/**
* Return the Observable of the whole store.
*
* All data is piped through an auditTime of 1ms. This is to prevent massive
* updates, if e.g. an autoupdate with a lot motions come in. The result is just one
* update of the... | {
this.viewModelSubjects[id] = new BehaviorSubject<V>(this.viewModelStore[id]);
} | conditional_block |
index.ts | import * as accounts from './accounts';
import * as addAccount from './add-account';
import * as addressBook from './address-book';
import * as application from './application';
import * as blockchains from './blockchains';
import * as connection from './conn';
import * as hwkey from './hwkey';
import * as screen from ... | } from './types';
export {
IBalanceValue, BalanceValueConverted
} from './accounts/types';
export {default as rootReducer} from './root-reducer';
export { default as BackendApi } from './BackendApi';
export { default as reduxLogger } from './redux-logger';
export {createStore} from './create-store';
export {RemoteV... | config
};
export {
IState | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.