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 |
|---|---|---|---|---|
cost.py | # Copyright (c) 2016, the GPyOpt Authors
# Licensed under the BSD 3-clause license (see LICENSE.txt)
from ...models import GPModel
import numpy as np
class CostModel(object):
"""
Class to handle the cost of evaluating the function.
param cost_withGradients: function that returns the cost of evaluating ... |
def constant_cost_withGradients(x):
"""
Constant cost function used by default: cost = 1, d_cost = 0.
"""
return np.ones(x.shape[0])[:,None], np.zeros(x.shape)
| cost_evals = np.log(np.atleast_2d(np.asarray(cost_x)).T)
if self.num_updates == 0:
X_all = x
costs_all = cost_evals
else:
X_all = np.vstack((self.cost_model.model.X,x))
costs_all = np.vstack((self.cost_model.model.Y,cost_evals))
... | conditional_block |
cost.py | # Copyright (c) 2016, the GPyOpt Authors
# Licensed under the BSD 3-clause license (see LICENSE.txt)
from ...models import GPModel
import numpy as np
class CostModel(object):
"""
Class to handle the cost of evaluating the function.
param cost_withGradients: function that returns the cost of evaluating ... | def constant_cost_withGradients(x):
"""
Constant cost function used by default: cost = 1, d_cost = 0.
"""
return np.ones(x.shape[0])[:,None], np.zeros(x.shape) | random_line_split | |
cost.py | # Copyright (c) 2016, the GPyOpt Authors
# Licensed under the BSD 3-clause license (see LICENSE.txt)
from ...models import GPModel
import numpy as np
class CostModel(object):
"""
Class to handle the cost of evaluating the function.
param cost_withGradients: function that returns the cost of evaluating ... | (self,x):
"""
Predicts the time cost and its gradient of evaluating the function at x.
"""
m, _, dmdx, _= self.cost_model.predict_withGradients(x)
return np.exp(m), np.exp(m)*dmdx
def update_cost_model(self, x, cost_x):
"""
Updates the GP used to handle the c... | _cost_gp_withGradients | identifier_name |
filemanager_thread.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/. */
use ipc_channel::ipc::IpcSender;
use std::path::PathBuf;
use super::{LoadConsumer, LoadData};
#[derive(Clone, Deb... |
/// Read file, return the bytes
ReadFile(IpcSender<FileManagerResult<Vec<u8>>>, SelectedFileId),
/// Delete the FileID entry
DeleteFileID(SelectedFileId),
/// Load resource by Blob URL
LoadBlob(LoadData, LoadConsumer),
/// Shut down this thread
Exit,
}
pub type FileManagerResult<T> ... | SelectFile(Vec<FilterPattern>, IpcSender<FileManagerResult<SelectedFile>>),
/// Select multiple files, return a vector of triples
SelectFiles(Vec<FilterPattern>, IpcSender<FileManagerResult<Vec<SelectedFile>>>), | random_line_split |
filemanager_thread.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/. */
use ipc_channel::ipc::IpcSender;
use std::path::PathBuf;
use super::{LoadConsumer, LoadData};
#[derive(Clone, Deb... | (pub String);
#[derive(Deserialize, Serialize)]
pub enum FileManagerThreadMsg {
/// Select a single file, return triple (FileID, FileName, lastModified)
SelectFile(Vec<FilterPattern>, IpcSender<FileManagerResult<SelectedFile>>),
/// Select multiple files, return a vector of triples
SelectFiles(Vec<Fil... | FilterPattern | identifier_name |
setup.py | "Pyrex",
"distutils",
"pydoc",
"py_compile",
"compiler",
]
}
# Copy then specialize the command-specific options.
options = {
'py2exe': common_options.copy(),
'py2app': common_options.copy(),
}
options['py2exe'].update({
"dll_excludes": [
"msvcp90.dll",
"mswsock.dll",
"powrprof.dll... | s
| identifier_body | |
setup.py | ": "FoFiX.py",
"icon_resources": [(1, "./win32/fofix.ico")],
"other_resources": [(RT_VERSION, 1, VersionResource(
#stump: the parameter below must consist only of up to four numerical fields separated by dots
Version.versionNum(),
fil... | #stump: when run from the exe, FoFiX will claim to be "FoFiX v" + product_version
product_version=Version.version()
).resource_bytes())]
}
]
})
elif sys.platform == 'darwin':
try:
import py2app
except ImportError:
if 'py... | legal_copyright=r"© 2008-2013 FoFiX Team. GNU GPL v2 or later.",
company_name="FoFiX Team",
internal_name="FoFiX.exe",
original_filename="FoFiX.exe",
product_name=Version.PROGRAM_NAME, | random_line_split |
setup.py | ": "FoFiX.py",
"icon_resources": [(1, "./win32/fofix.ico")],
"other_resources": [(RT_VERSION, 1, VersionResource(
#stump: the parameter below must consist only of up to four numerical fields separated by dots
Version.versionNum(),
fil... | :
pair = list(x.split('=', 1))
if len(pair) == 1:
pair.append(None)
return tuple(pair)
info = {
'define_macros': [def_split(x[2:]) for x in cflags if x[:2] == '-D'],
'include_dirs': [x[2:] for x in cflags if x[:2] == '-I'],
'libraries': [x[2:] for x in libs if x... | _split(x) | identifier_name |
setup.py | ": "FoFiX.py",
"icon_resources": [(1, "./win32/fofix.ico")],
"other_resources": [(RT_VERSION, 1, VersionResource(
#stump: the parameter below must consist only of up to four numerical fields separated by dots
Version.versionNum(),
fil... | else:
print('not found')
sys.stderr.write('Could not find required library "%s".\n' % pkg)
sys.stderr.write('(Also tried the following alternative names: %s)\n' % ', '.join(altnames))
if os.name == 'nt':
sys.stderr.write('(Check that you have the lat... | = name
sys.stdout.write('(using alternative name %s) ' % pkg)
break
| conditional_block |
timer.py | # -*- coding: utf-8 -*-
import time
class Timer(object):
'''
Simple timer control
'''
def __init__(self, delay):
self.current_time = 0
self.set_delay(delay)
def pause(self, pause):
if pause >= self.delay:
self.current_time = time.clock()
... | '''
Verify if the timer is idle
'''
self.current_time = time.clock()
## if next frame occurs in the future, now it's idle time
if self.next_time > self.current_time:
return True
# if pass more than one delay time, synchronize it
if (self.curren... | identifier_body | |
timer.py | # -*- coding: utf-8 -*-
import time
class Timer(object):
'''
Simple timer control
'''
def | (self, delay):
self.current_time = 0
self.set_delay(delay)
def pause(self, pause):
if pause >= self.delay:
self.current_time = time.clock()
self.next_time = self.current_time + pause
def set_delay(self, delay):
assert delay >= 0
self.d... | __init__ | identifier_name |
timer.py | # -*- coding: utf-8 -*-
import time
class Timer(object):
'''
Simple timer control
'''
def __init__(self, delay):
self.current_time = 0
self.set_delay(delay)
def pause(self, pause):
if pause >= self.delay:
self.current_time = time.clock()
... |
return False
| self.next_time += self.delay | conditional_block |
timer.py | # -*- coding: utf-8 -*-
import time
class Timer(object):
'''
Simple timer control
'''
def __init__(self, delay):
self.current_time = 0
self.set_delay(delay)
def pause(self, pause):
if pause >= self.delay:
self.current_time = time.clock()
... | self.next_time = self.current_time + self.delay
else:
self.next_time += self.delay
return False | if self.next_time > self.current_time:
return True
# if pass more than one delay time, synchronize it
if (self.current_time - self.next_time) > self.delay:
| random_line_split |
content-type.ts | 8859-1', 'latin1']
]);
const defaultCharset = originalCharset && charsetAliases.get(originalCharset) || originalCharset;
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
const typeInfo = (mimeDB as any)[mediaType || ''];
let determinedCharset = typeInfo && normalizeString(type... |
// Use the media types from `mime-db`, not `file-type`.
return getMediaTypeBasedOnFileExtension(detectedFileType.ext);
}
return null;
};
/* istanbul ignore next */
const getPreferedMediaType = (mediaType: string | null): string | null => {
// Prefer certain media types over others.
... | {
// See: https://www.w3.org/TR/SVG/mimereg.html.
return 'image/svg+xml';
} | conditional_block |
content-type.ts | * From: https://www.w3.org/TR/WD-html40-970708/html40.txt
*
* However, `ISO-8859-1` is not supported by node directly.
* https://github.com/webhintio/hint/issues/89
*/
const charsetAliases: Map<string, string> = new Map([
['iso-8859-1', 'latin1']
]);
const defaultCharset =... | *
* " For example, user agents typically assume that
* in the absence of other indicators, the character
* encoding is ISO-8859-1. "
* | random_line_split | |
settings.js | <?php
/** This file is part of KCFinder project
*
* @desc Settings panel functionality
* @package KCFinder | * @license http://www.opensource.org/licenses/gpl-2.0.php GPLv2
* @license http://www.opensource.org/licenses/lgpl-2.1.php LGPLv2
* @link http://kcfinder.sunhater.com
*/?>
browser.initSettings = function() {
if (!this.shows.length) {
var showInputs = $('#show input[type="checkbox"]').toAr... | * @version 2.31
* @author Pavel Tzonkov <pavelc@users.sourceforge.net>
* @copyright 2010, 2011 KCFinder Project | random_line_split |
no_backspace_delete.js | /**
* Tom Select v1.7.5
* Licensed under the Apache License, Version 2.0 (the "License");
*/
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(require('../../tom-select.js')) :
typeof define === 'function' && define.amd ? define(['../../tom-select'], factory) :
(gl... | (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
var TomSelect__default = /*#__PURE__*/_interopDefaultLegacy(TomSelect);
/**
* Plugin: "input_autogrow" (Tom Select)
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this
* file except in c... | _interopDefaultLegacy | identifier_name |
no_backspace_delete.js | /**
* Tom Select v1.7.5
* Licensed under the Apache License, Version 2.0 (the "License");
*/
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(require('../../tom-select.js')) :
typeof define === 'function' && define.amd ? define(['../../tom-select'], factory) :
(gl... | * ANY KIND, either express or implied. See the License for the specific language
* governing permissions and limitations under the License.
*
*/
TomSelect__default['default'].define('no_backspace_delete', function () {
var self = this;
var orig_deleteSelection = self.deleteSelection;
this.hook('instea... | * http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under
* the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF | random_line_split |
no_backspace_delete.js | /**
* Tom Select v1.7.5
* Licensed under the Apache License, Version 2.0 (the "License");
*/
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(require('../../tom-select.js')) :
typeof define === 'function' && define.amd ? define(['../../tom-select'], factory) :
(gl... |
return false;
});
});
})));
//# sourceMappingURL=no_backspace_delete.js.map
| {
return orig_deleteSelection.apply(self, arguments);
} | conditional_block |
no_backspace_delete.js | /**
* Tom Select v1.7.5
* Licensed under the Apache License, Version 2.0 (the "License");
*/
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(require('../../tom-select.js')) :
typeof define === 'function' && define.amd ? define(['../../tom-select'], factory) :
(gl... |
var TomSelect__default = /*#__PURE__*/_interopDefaultLegacy(TomSelect);
/**
* Plugin: "input_autogrow" (Tom Select)
*
* 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.... | { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; } | identifier_body |
date.rs | use header::HttpDate;
header! {
/// `Date` header, defined in [RFC7231](http://tools.ietf.org/html/rfc7231#section-7.1.1.2)
///
/// The `Date` header field represents the date and time at which the
/// message was originated.
///
/// # ABNF
/// ```plain
/// Date = HTTP-date
/// ```
... | (Date, "Date") => [HttpDate]
test_date {
test_header!(test1, vec![b"Tue, 15 Nov 1994 08:12:31 GMT"]);
}
}
bench_header!(imf_fixdate, Date, { vec![b"Sun, 07 Nov 1994 08:48:37 GMT".to_vec()] });
bench_header!(rfc_850, Date, { vec![b"Sunday, 06-Nov-94 08:49:37 GMT".to_vec()] });
bench_header!(asctime... | /// use std::time::SystemTime;
///
/// let mut headers = Headers::new();
/// headers.set(Date(SystemTime::now().into()));
/// ``` | random_line_split |
Subscriber.ts | import { isFunction } from './util/isFunction';
import { empty as emptyObserver } from './Observer';
import { Observer, PartialObserver } from './types';
import { Subscription } from './Subscription';
import { rxSubscriber as rxSubscriberSymbol } from '../internal/symbol/rxSubscriber';
/**
* Implements the {@link Obs... |
error(err?: any): void {
if (!this.isStopped) {
if (this._error) {
try {
this._error.call(this._context, err);
} catch (err) {
this._hostReportError(err);
}
} else {
this._hostReportError(err);
}
this.unsubscribe();
}
}
complet... | {
if (!this.isStopped && this._next) {
try {
this._next.call(this._context, value);
} catch (err) {
this._hostReportError(err);
this.unsubscribe();
}
}
} | identifier_body |
Subscriber.ts | import { isFunction } from './util/isFunction';
import { empty as emptyObserver } from './Observer';
import { Observer, PartialObserver } from './types';
import { Subscription } from './Subscription';
import { rxSubscriber as rxSubscriberSymbol } from '../internal/symbol/rxSubscriber';
/**
* Implements the {@link Obs... | this.unsubscribe();
}
}
}
error(err?: any): void {
if (!this.isStopped) {
if (this._error) {
try {
this._error.call(this._context, err);
} catch (err) {
this._hostReportError(err);
}
} else {
this._hostReportError(err);
}
... | } catch (err) {
this._hostReportError(err); | random_line_split |
Subscriber.ts | import { isFunction } from './util/isFunction';
import { empty as emptyObserver } from './Observer';
import { Observer, PartialObserver } from './types';
import { Subscription } from './Subscription';
import { rxSubscriber as rxSubscriberSymbol } from '../internal/symbol/rxSubscriber';
/**
* Implements the {@link Obs... | (err: any): void {
this.destination.error(err);
this.unsubscribe();
}
protected _complete(): void {
this.destination.complete();
this.unsubscribe();
}
protected _unsubscribeAndRecycle(): Subscriber<T> {
const { _parent, _parents } = this;
this._parent = null;
this._parents = null;
... | _error | identifier_name |
file.rs | // Copyright 2018 Google Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable... | }
fn try_load_file<P>(path: P) -> Result<(Rope, FileInfo), FileError>
where P: AsRef<Path>
{
// TODO: support for non-utf8
// it's arguable that the rope crate should have file loading functionality
let mut f = File::open(path.as_ref())?;
let mod_time = f.metadata()?.modified().ok();
let mut bytes ... | } | random_line_split |
file.rs | // Copyright 2018 Google Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable... |
fn try_decode(bytes: Vec<u8>,
encoding: CharacterEncoding) -> Result<Rope, FileError> {
match encoding {
CharacterEncoding::Utf8 =>
Ok(Rope::from(str::from_utf8(&bytes)?)),
CharacterEncoding::Utf8WithBom => {
let s = String::from_utf8(bytes).map_err(|e| e.utf8... | {
let mut f = File::create(path)?;
match encoding {
CharacterEncoding::Utf8WithBom => f.write_all(UTF8_BOM.as_bytes())?,
CharacterEncoding::Utf8 => (),
}
for chunk in text.iter_chunks(0, text.len()) {
f.write_all(chunk.as_bytes())?;
}
Ok((... | identifier_body |
file.rs | // Copyright 2018 Google Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable... | else {
let encoding = self.file_info.get(&id).unwrap().encoding;
try_save(path, text, encoding)?;
self.file_info.get_mut(&id).unwrap()
.mod_time = get_mod_time(path);
}
Ok(())
}
}
fn try_load_file<P>(path: P) -> Result<(Rope, FileInfo), FileError... | {
return Err(FileError::HasChanged);
} | conditional_block |
file.rs | // Copyright 2018 Google Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable... | (&mut self, path: &Path, text: &Rope, id: BufferId)
-> Result<(), FileError>
{
let prev_path = self.file_info.get(&id).unwrap().path.clone();
if prev_path != path {
self.save_new(path, text, id)?;
self.open_files.remove(&prev_path);
#[cfg(feature = "notify... | save_existing | identifier_name |
__init__.py | =None, globe='earth',
typ="", name="", dim=None, site=None, entity=''):
"""
Represent a geo coordinate.
@param lat: Latitude
@type lat: float
@param lon: Longitude
@type lon: float
@param alt: Altitute? TODO FIXME
@param precision: precis... | f, amoun | identifier_name | |
__init__.py | = "%Y%m%d%H%M%S"
ISO8601Format = "%Y-%m-%dT%H:%M:%SZ"
def clone(self):
"""Clone this instance."""
return self.replace(microsecond=self.microsecond)
@classmethod
def fromISOformat(cls, ts):
"""Convert an ISO 8601 timestamp to a Timestamp object."""
# If inadvertantly pa... |
def __sub__(self, other):
"""Perform substraction, returning a Timestamp instead of datetime."""
newdt = super(Timestamp, self).__sub__(other)
if isinstance(newdt, datetime.datetime):
return Timestamp(newdt.year, newdt.month, newdt.day, newdt.hour,
... | return newdt | conditional_block |
__init__.py | = "%Y%m%d%H%M%S"
ISO8601Format = "%Y-%m-%dT%H:%M:%SZ"
def clone(self):
"""Clone this instance."""
return self.replace(microsecond=self.microsecond)
@classmethod
def fromISOformat(cls, ts):
"""Convert an ISO 8601 timestamp to a Timestamp object."""
# If inadvertantly pa... | for k in site.globes():
globes[site.globes()[k]] = k
globekey = data['globe']
if globekey:
globe = globes.get(data['globe'])
else:
# Default to earth or should we use None here?
globe = 'earth'
return cls(data['latitude'], data['l... | @classmethod
def fromWikibase(cls, data, site):
"""Constructor to create an object from Wikibase's JSON output."""
globes = {} | random_line_split |
__init__.py | , unit=None, error=None):
u"""
Create a new WbQuantity object.
@param amount: number representing this quantity
@type amount: float
@param unit: not used (only unit-less quantities are supported)
@param error: the uncertainty of the amount (e.g. ±1)
@type error: ... | ke requests from the queue and execute them in background."""
while True:
(request, args, kwargs) = page_put_queue.get()
if request is None:
break
request(*args, **kwargs)
page_put_queue.task_done()
def async_ | identifier_body | |
sql_client.py | .get('rows')
else:
return response
def execute(self, query):
"""Run a long running query. It returns an object with the
status and information of the job. For more information check the `Batch API
documentation
<https://carto.com/developers/sql-api/reference/#tag... | _row_values_format | identifier_name | |
sql_client.py | a specific column.
Args:
table_name (str): name of the table.
column_name (str): name of the column.
Example:
>>> sql.distinct('table_name', 'column_name')
[('value1', 10), ('value2', 5)]
"""
query = '''
SELECT {0}, COUNT(*)... | print(row_format.format(*row)) | conditional_block | |
sql_client.py | def __init__(self, credentials=None):
self._context_manager = ContextManager(credentials)
def query(self, query, verbose=False):
"""Run a SQL query. It returns a `list` with content of the response.
If the `verbose` param is True it returns the full SQL response in a `dict`.
For mo... | cnames = columns_values.keys()
cvalues = [self._row_values_format(v) for v in zip(*columns_values.values())]
query = '''
INSERT INTO {0} ({1}) VALUES {2};
'''.format(table_name, ','.join(cnames), ','.join(cvalues))
self.execute(query)
def update_table(self, table... |
""" | random_line_split |
sql_client.py | def __init__(self, credentials=None):
self._context_manager = ContextManager(credentials)
def query(self, query, verbose=False):
"""Run a SQL query. It returns a `list` with content of the response.
If the `verbose` param is True it returns the full SQL response in a `dict`.
For mo... |
def distinct(self, table_name, column_name):
"""Get the distict values and their count in a table
for a specific column.
Args:
table_name (str): name of the table.
column_name (str): name of the column.
Example:
>>> sql.distinct('table_name', '... | """Run a long running query. It returns an object with the
status and information of the job. For more information check the `Batch API
documentation
<https://carto.com/developers/sql-api/reference/#tag/Batch-Queries>`.
Args:
query (str): SQL query.
Example:
... | identifier_body |
genTutorial.js | function tutorial() {
| row.append(video2);
} else if (i == 3) {
row.append(video3);
}else {
row.append(video4);
}
content.append(row);
}
var mainC = document.getElementById("mainContainer");
mainC.append(content);
} |
var videos = ["1", "2", "3", "4", "5"];
var content = cEl("div").attr("id", "videoContainer").attr("class","row");
var video0 = cEl("div").attr("class", "description").tEl("How to play #1");
var video1 = cEl("div").attr("class", "description").tEl("How To Predict");
var video2 = cEl("div").attr... | identifier_body |
genTutorial.js | function tu | {
var videos = ["1", "2", "3", "4", "5"];
var content = cEl("div").attr("id", "videoContainer").attr("class","row");
var video0 = cEl("div").attr("class", "description").tEl("How to play #1");
var video1 = cEl("div").attr("class", "description").tEl("How To Predict");
var video2 = cEl("div").a... | torial() | identifier_name |
genTutorial.js | function tutorial() {
var videos = ["1", "2", "3", "4", "5"];
var content = cEl("div").attr("id", "videoContainer").attr("class","row");
var video0 = cEl("div").attr("class", "description").tEl("How to play #1");
var video1 = cEl("div").attr("class", "description").tEl("How To Predict");
var v... | }else if(i == 2){
row.append(video2);
} else if (i == 3) {
row.append(video3);
}else {
row.append(video4);
}
content.append(row);
}
var mainC = document.getElementById("mainContainer");
mainC.append(content);
... | }else if(i == 1){
row.append(video1);
| random_line_split |
genTutorial.js | function tutorial() {
var videos = ["1", "2", "3", "4", "5"];
var content = cEl("div").attr("id", "videoContainer").attr("class","row");
var video0 = cEl("div").attr("class", "description").tEl("How to play #1");
var video1 = cEl("div").attr("class", "description").tEl("How To Predict");
var v... |
}
var mainC = document.getElementById("mainContainer");
mainC.append(content);
} |
var row = cEl("div").attr("class", "span5").attr("style","display:inline-block");
var video = cEl("video").attr("width","100%").attr("height","100%").attr("controls");
video.append(cEl("source").attr("src", "../style/videos/" + videos[i] + ".webm").attr("type", "video/mp4"))
.append(... | conditional_block |
comment.py | # -*- coding: utf-8 -*-
import hashlib
import json
import locale
import re
import trac.wiki.formatter
from trac.mimeview.api import Context
from time import strftime, localtime
from code_comments import db
from trac.util import Markup
from trac.web.href import Href
from trac.test import Mock, MockPerm
def md5_hexdi... |
return href
def link_text(self):
if self.is_comment_to_changeset:
return self.changeset_link_text()
if self.is_comment_to_attachment:
return self.attachment_link_text()
# except the two special cases of changesets (revision-only)
# and attachments (... | href += '#L' + str(self.line) | conditional_block |
comment.py | # -*- coding: utf-8 -*-
import hashlib
import json
import locale
import re
import trac.wiki.formatter
from trac.mimeview.api import Context
from time import strftime, localtime
from code_comments import db
from trac.util import Markup
from trac.web.href import Href
from trac.test import Mock, MockPerm
def md5_hexdi... |
class CommentJSONEncoder(json.JSONEncoder):
def default(self, o):
if isinstance(o, Comment):
for_json = dict([
(name, getattr(o, name))
for name in o.__dict__
if isinstance(getattr(o, name), (basestring, int, list, dict))
])
... | self.env.db_transaction("""
DELETE FROM code_comments WHERE id=%s
""", (self.id,)) | identifier_body |
comment.py | # -*- coding: utf-8 -*-
import hashlib
import json
import locale
import re
import trac.wiki.formatter
from trac.mimeview.api import Context
from time import strftime, localtime
from code_comments import db
from trac.util import Markup
from trac.web.href import Href
from trac.test import Mock, MockPerm
def md5_hexdi... | (self):
if self.is_comment_to_attachment:
return '[%s %s]' % (self.req.href())
return 'source:' + self.link_text()
def attachment_info(self):
info = {'ticket': None, 'filename': None}
if not self.path.startswith('attachment'):
return info
match = re.m... | trac_link | identifier_name |
comment.py | # -*- coding: utf-8 -*-
import hashlib
import json
import locale
import re
import trac.wiki.formatter
from trac.mimeview.api import Context
from time import strftime, localtime
from code_comments import db
from trac.util import Markup
from trac.web.href import Href
from trac.test import Mock, MockPerm
def md5_hexdi... | info = {'ticket': None, 'filename': None}
if not self.path.startswith('attachment'):
return info
match = re.match(r'attachment:/ticket/(\d+)/(.*)', self.path)
if not match:
return info
info['ticket'] = int(match.group(1))
info['filename'] = match.g... | return 'source:' + self.link_text()
def attachment_info(self): | random_line_split |
snip.py | import json
import logging
from flask import abort, redirect, render_template, request, send_file
import ctrl.snip
from . import handlers
@handlers.route('/snip/<slug>.png')
def snip_view(slug):
filename = ctrl.snip.getSnipPath(slug)
if filename == None:
logging.warning("invalid slug: " + slug)
abort(400... |
@handlers.route('/snip/new')
def snip_new():
return render_template('snip-new.html')
| if 'file' not in request.files:
abort(400)
file = request.files['file']
snip = ctrl.snip.saveSnip(file)
if request.args.get('redirect') == '0':
return json.dumps({'slug': snip.slug})
else:
return redirect('/snip/' + snip.slug) | identifier_body |
snip.py | import json
import logging
from flask import abort, redirect, render_template, request, send_file
import ctrl.snip
from . import handlers
@handlers.route('/snip/<slug>.png')
def snip_view(slug):
filename = ctrl.snip.getSnipPath(slug)
if filename == None:
logging.warning("invalid slug: " + slug)
abort(400... |
file = request.files['file']
snip = ctrl.snip.saveSnip(file)
if request.args.get('redirect') == '0':
return json.dumps({'slug': snip.slug})
else:
return redirect('/snip/' + snip.slug)
@handlers.route('/snip/new')
def snip_new():
return render_template('snip-new.html')
| abort(400) | conditional_block |
snip.py | import json
import logging
from flask import abort, redirect, render_template, request, send_file
import ctrl.snip
from . import handlers
@handlers.route('/snip/<slug>.png')
def snip_view(slug):
filename = ctrl.snip.getSnipPath(slug)
if filename == None:
logging.warning("invalid slug: " + slug)
abort(400... | (slug):
snip = ctrl.snip.getSnip(slug)
return render_template('snip.html', snip=snip)
@handlers.route('/snip/upload', methods=['POST'])
def snip_upload():
if 'file' not in request.files:
abort(400)
file = request.files['file']
snip = ctrl.snip.saveSnip(file)
if request.args.get('redirect') == '0':
... | snip_page | identifier_name |
snip.py | import json
import logging
from flask import abort, redirect, render_template, request, send_file
import ctrl.snip
from . import handlers
@handlers.route('/snip/<slug>.png')
def snip_view(slug):
filename = ctrl.snip.getSnipPath(slug)
if filename == None:
logging.warning("invalid slug: " + slug)
abort(400... | return json.dumps({'slug': snip.slug})
else:
return redirect('/snip/' + snip.slug)
@handlers.route('/snip/new')
def snip_new():
return render_template('snip-new.html') | snip = ctrl.snip.saveSnip(file)
if request.args.get('redirect') == '0': | random_line_split |
detail.py | """Detail firewall."""
# :license: MIT, see LICENSE for more details.
import click
import SoftLayer
from SoftLayer.CLI import environment
from SoftLayer.CLI import firewall
from SoftLayer.CLI import formatting
from SoftLayer import utils
@click.command()
@click.argument('identifier')
@environment.pass_env
def cli(e... | (rules):
"""Helper to format the rules into a table.
:param list rules: A list containing the rules of the firewall
:returns: a formatted table of the firewall rules
"""
table = formatting.Table(['#', 'action', 'protocol', 'src_ip', 'src_mask',
'dest', 'dest_mask'])
... | get_rules_table | identifier_name |
detail.py | """Detail firewall."""
# :license: MIT, see LICENSE for more details.
import click
import SoftLayer
from SoftLayer.CLI import environment
from SoftLayer.CLI import firewall
from SoftLayer.CLI import formatting
from SoftLayer import utils
@click.command()
@click.argument('identifier')
@environment.pass_env
def cli(e... | """Helper to format the rules into a table.
:param list rules: A list containing the rules of the firewall
:returns: a formatted table of the firewall rules
"""
table = formatting.Table(['#', 'action', 'protocol', 'src_ip', 'src_mask',
'dest', 'dest_mask'])
table.sortb... | identifier_body | |
detail.py | """Detail firewall."""
# :license: MIT, see LICENSE for more details.
import click
import SoftLayer
from SoftLayer.CLI import environment
from SoftLayer.CLI import firewall
from SoftLayer.CLI import formatting
from SoftLayer import utils
@click.command()
@click.argument('identifier')
@environment.pass_env
def cli(e... |
env.fout(get_rules_table(rules))
def get_rules_table(rules):
"""Helper to format the rules into a table.
:param list rules: A list containing the rules of the firewall
:returns: a formatted table of the firewall rules
"""
table = formatting.Table(['#', 'action', 'protocol', 'src_ip', 'src_m... | rules = mgr.get_standard_fwl_rules(firewall_id) | conditional_block |
detail.py | """Detail firewall."""
# :license: MIT, see LICENSE for more details.
import click
import SoftLayer
from SoftLayer.CLI import environment
from SoftLayer.CLI import firewall
from SoftLayer.CLI import formatting
from SoftLayer import utils
@click.command()
@click.argument('identifier')
@environment.pass_env
def cli(e... | rule['action'],
rule['protocol'],
rule['sourceIpAddress'],
utils.lookup(rule, 'sourceIpSubnetMask'),
'%s:%s-%s' % (rule['destinationIpAddress'],
rule['destinationPortRangeStart'],
rule['destinationPortRangeEn... | table.add_row([
rule['orderValue'], | random_line_split |
dashboard-view.js | import '@polymer/iron-icon/iron-icon.js';
import '@polymer/iron-icons/iron-icons.js';
import '@polymer/paper-card/paper-card.js';
import '@polymer/paper-ripple/paper-ripple.js';
import '@polymer/paper-item/paper-icon-item.js';
import '@polymer/paper-icon-button/paper-icon-button.js';
import {html, PolymerElement} from... |
this.platformDetails = getGCPData(gcpProject);
}
}
/**
* Rewrites the links adding the namespace as a query parameter.
* @param {namespace} namespace
*/
_namespaceChanged(namespace) {
this.quickLinks.map((quickLink) => {
quickLink.link = this.buildHre... | {
gcpProject = pieces[2];
} | conditional_block |
dashboard-view.js | import '@polymer/iron-icon/iron-icon.js';
import '@polymer/iron-icons/iron-icons.js';
import '@polymer/paper-card/paper-card.js';
import '@polymer/paper-ripple/paper-ripple.js';
import '@polymer/paper-item/paper-icon-item.js';
import '@polymer/paper-icon-button/paper-icon-button.js';
import {html, PolymerElement} from... | () {
return html([`
<style include="card-styles">
${css.toString()}
</style>
${template()}
`]);
}
/**
* Object describing property-related metadata used by Polymer features
*/
static get properties() {
return {
... | template | identifier_name |
dashboard-view.js | import '@polymer/iron-icon/iron-icon.js';
import '@polymer/iron-icons/iron-icons.js';
import '@polymer/paper-card/paper-card.js';
import '@polymer/paper-ripple/paper-ripple.js'; | import '@polymer/paper-icon-button/paper-icon-button.js';
import {html, PolymerElement} from '@polymer/polymer';
import css from './dashboard-view.css';
import template from './dashboard-view.pug';
import './card-styles.js';
import './iframe-link.js';
import './notebooks-card.js';
import './pipelines-card.js';
import... | import '@polymer/paper-item/paper-icon-item.js'; | random_line_split |
tight_bbox.py | """
This module is to support *bbox_inches* option in savefig command.
"""
from __future__ import (absolute_import, division, print_function,
unicode_literals)
import six
import warnings
from matplotlib.transforms import Bbox, TransformedBbox, Affine2D
def adjust_bbox(fig, bbox_inches, fixe... | tr = Affine2D().scale(fixed_dpi)
dpi_scale = fixed_dpi / fig.dpi
else:
tr = Affine2D().scale(fig.dpi)
dpi_scale = 1.
_bbox = TransformedBbox(bbox_inches, tr)
fig.bbox_inches = Bbox.from_bounds(0, 0,
bbox_inches.width, bbox_inches.heigh... | fig.transFigure.invalidate()
fig.patch.set_bounds(0, 0, 1, 1)
if fixed_dpi is not None: | random_line_split |
tight_bbox.py | """
This module is to support *bbox_inches* option in savefig command.
"""
from __future__ import (absolute_import, division, print_function,
unicode_literals)
import six
import warnings
from matplotlib.transforms import Bbox, TransformedBbox, Affine2D
def adjust_bbox(fig, bbox_inches, fixe... |
def _l(a, r, pos=pos):
return pos
ax.set_axes_locator(_l)
ax.set_aspect("auto")
def restore_bbox():
for ax, asp, loc in zip(fig.axes, asp_list, locator_list):
ax.set_aspect(asp)
ax.set_axes_locator(loc)
fig.bbox = origBbox
fig.b... | """
Temporarily adjust the figure so that only the specified area
(bbox_inches) is saved.
It modifies fig.bbox, fig.bbox_inches,
fig.transFigure._boxout, and fig.patch. While the figure size
changes, the scale of the original figure is conserved. A
function which restores the original values ... | identifier_body |
tight_bbox.py | """
This module is to support *bbox_inches* option in savefig command.
"""
from __future__ import (absolute_import, division, print_function,
unicode_literals)
import six
import warnings
from matplotlib.transforms import Bbox, TransformedBbox, Affine2D
def | (fig, bbox_inches, fixed_dpi=None):
"""
Temporarily adjust the figure so that only the specified area
(bbox_inches) is saved.
It modifies fig.bbox, fig.bbox_inches,
fig.transFigure._boxout, and fig.patch. While the figure size
changes, the scale of the original figure is conserved. A
func... | adjust_bbox | identifier_name |
tight_bbox.py | """
This module is to support *bbox_inches* option in savefig command.
"""
from __future__ import (absolute_import, division, print_function,
unicode_literals)
import six
import warnings
from matplotlib.transforms import Bbox, TransformedBbox, Affine2D
def adjust_bbox(fig, bbox_inches, fixe... |
_bbox = TransformedBbox(bbox_inches, tr)
fig.bbox_inches = Bbox.from_bounds(0, 0,
bbox_inches.width, bbox_inches.height)
x0, y0 = _bbox.x0, _bbox.y0
w1, h1 = fig.bbox.width * dpi_scale, fig.bbox.height * dpi_scale
fig.transFigure._boxout = Bbox.from_bounds(-... | tr = Affine2D().scale(fig.dpi)
dpi_scale = 1. | conditional_block |
typescriptMain.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... | if (body.diagnostics) {
let diagnostics = this.createMarkerDatas(body.diagnostics);
let syntaxMarkers = this.syntaxDiagnostics[body.file];
if (syntaxMarkers) {
delete this.syntaxDiagnostics[body.file];
diagnostics = syntaxMarkers.concat(diagnostics);
}
this.currentDiagnostics.set(Uri.file(body.... | random_line_split | |
typescriptMain.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... | (event: Proto.DiagnosticEvent): void {
let body = event.body;
if (body.diagnostics) {
let markers = this.createMarkerDatas(body.diagnostics);
this.syntaxDiagnostics[body.file] = markers;
}
}
/* internal */ semanticDiagnosticsReceived(event: Proto.DiagnosticEvent): void {
let body = event.body;
if (bo... | syntaxDiagnosticsReceived | identifier_name |
typescriptMain.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... |
public reloadProjects(): void {
this.client.execute('reloadProjects', null, false);
this.triggerAllDiagnostics();
}
public addBufferSyncSupport(support: BufferSyncSupport): void {
this.bufferSyncSupports.push(support);
}
private triggerAllDiagnostics() {
this.bufferSyncSupports.forEach(support => suppo... | {
return this.client;
} | identifier_body |
typescriptMain.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... |
}
/* internal */ semanticDiagnosticsReceived(event: Proto.DiagnosticEvent): void {
let body = event.body;
if (body.diagnostics) {
let diagnostics = this.createMarkerDatas(body.diagnostics);
let syntaxMarkers = this.syntaxDiagnostics[body.file];
if (syntaxMarkers) {
delete this.syntaxDiagnostics[bod... | {
let markers = this.createMarkerDatas(body.diagnostics);
this.syntaxDiagnostics[body.file] = markers;
} | conditional_block |
app.component.ts | /*
* Copyright 2021 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to ... |
ngOnInit(): void {
if (!environment.e2e) this._maintenanceService.checkForMaintenanceMode();
if (!environment.pwa) this.handleUnregister();
this.registerSessionRefreshOnVisibilityChange();
}
ngAfterViewInit() {
if (!environment.production || !environment.pwa) return;
this._swUpdate.availabl... | {} | identifier_body |
app.component.ts | /*
* Copyright 2021 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to ... | () {
getDocumentVisibilityEvent$().subscribe(this.checkForAuthSession);
}
/**
* Checks to see if a local file request is being redirected due to expired cookies
* https://developer.mozilla.org/en-US/docs/Web/API/Response/type
*/
checkForAuthSession = async () => {
try {
const res = await ... | registerSessionRefreshOnVisibilityChange | identifier_name |
app.component.ts | /*
* Copyright 2021 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to ... | }
/**
* Checks to see if a local file request is being redirected due to expired cookies
* https://developer.mozilla.org/en-US/docs/Web/API/Response/type
*/
checkForAuthSession = async () => {
try {
const res = await fetch('session-refresh.js', { cache: 'no-cache', redirect: 'manual' });
... | }
/** On doc visibility change, we check to see if the user's auth token has expired */
registerSessionRefreshOnVisibilityChange() {
getDocumentVisibilityEvent$().subscribe(this.checkForAuthSession); | random_line_split |
strings.rs | pub fn strings() {
string_concatenation();
string_indexing();
string_slices();
iterating_over_strings();
}
fn | () {
let s1 = String::from("Hello");
let s2 = String::from(", world!");
// Various approaches to concatenating strings
let mut s = s1.clone();
s.push_str(", world!");
let mut s = s1.clone();
let mut s = String::from("Hello");
let s = s1 + &s2; // NOTE: s1 is moved
}
fn string_indexi... | string_concatenation | identifier_name |
strings.rs | pub fn strings() {
string_concatenation();
string_indexing();
string_slices();
iterating_over_strings();
}
fn string_concatenation() { |
// Various approaches to concatenating strings
let mut s = s1.clone();
s.push_str(", world!");
let mut s = s1.clone();
let mut s = String::from("Hello");
let s = s1 + &s2; // NOTE: s1 is moved
}
fn string_indexing() {
// NOTE: Strings do not support indexing
// See: https://doc.rust... | let s1 = String::from("Hello");
let s2 = String::from(", world!"); | random_line_split |
strings.rs | pub fn strings() {
string_concatenation();
string_indexing();
string_slices();
iterating_over_strings();
}
fn string_concatenation() {
let s1 = String::from("Hello");
let s2 = String::from(", world!");
// Various approaches to concatenating strings
let mut s = s1.clone();
s.push_st... | s() {
let s = "नमस्ते";
for c in s.chars() {
println!("{}", c);
}
for b in s.bytes() {
println!("{}", b);
}
}
| llo = "Здравствуйте";
println!("{}", &hello[..4]); // Зд
// println!("{}", &hello[..3]); // Error: panic
// let z = &hello[..1]; // Error: panic
}
fn iterating_over_string | identifier_body |
routes.ts | /*
* Copyright (c) 2017 Michael Krotscheck
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy
* of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agr... | */
export const ROUTES: ModuleWithProviders = RouterModule.forChild([
{
path: 'login',
component: LoginComponent,
canActivate: [RequireLoggedOutGuard],
}
]); | *
* @author Michael Krotscheck | random_line_split |
desoggy.py | # -*- coding: utf-8 -*-
# -----------------------------------------------------------------------------
# (C) British Crown Copyright 2012-7 Met Office.
#
# This file is part of Rose, a framework for meteorological suites.
#
# Rose is free software: you can redistribute it and/or modify
# it under the terms of the GNU ... | # 1 g cm^-3 is pure water, so this is pretty soggy.
config.set(["env", "SPONGE_DENSITY"], "0.3")
self.add_report(
"env", "SPONGE_DENSITY", "0.3", self.SOGGY_FIX_TEXT)
return config, self.reports | sponge_density = config.get_value(["env", "SPONGE_DENSITY"])
if sponge_density is not None and float(sponge_density) > 0.5: | random_line_split |
desoggy.py | # -*- coding: utf-8 -*-
# -----------------------------------------------------------------------------
# (C) British Crown Copyright 2012-7 Met Office.
#
# This file is part of Rose, a framework for meteorological suites.
#
# Rose is free software: you can redistribute it and/or modify
# it under the terms of the GNU ... | """Reduce the density of the sponge."""
sponge_density = config.get_value(["env", "SPONGE_DENSITY"])
if sponge_density is not None and float(sponge_density) > 0.5:
# 1 g cm^-3 is pure water, so this is pretty soggy.
config.set(["env", "SPONGE_DENSITY"], "0.3")
self.ad... | identifier_body | |
desoggy.py | # -*- coding: utf-8 -*-
# -----------------------------------------------------------------------------
# (C) British Crown Copyright 2012-7 Met Office.
#
# This file is part of Rose, a framework for meteorological suites.
#
# Rose is free software: you can redistribute it and/or modify
# it under the terms of the GNU ... | (self, config, meta_config=None):
"""Reduce the density of the sponge."""
sponge_density = config.get_value(["env", "SPONGE_DENSITY"])
if sponge_density is not None and float(sponge_density) > 0.5:
# 1 g cm^-3 is pure water, so this is pretty soggy.
config.set(["env", "SP... | transform | identifier_name |
desoggy.py | # -*- coding: utf-8 -*-
# -----------------------------------------------------------------------------
# (C) British Crown Copyright 2012-7 Met Office.
#
# This file is part of Rose, a framework for meteorological suites.
#
# Rose is free software: you can redistribute it and/or modify
# it under the terms of the GNU ... |
return config, self.reports
| config.set(["env", "SPONGE_DENSITY"], "0.3")
self.add_report(
"env", "SPONGE_DENSITY", "0.3", self.SOGGY_FIX_TEXT) | conditional_block |
test_ssh.py | # Copyright (c) 2012 Spotify AB
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may not
# use this file except in compliance with the License. You may obtain a copy of
# the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, s... | (self):
""" Test subprocess call structure using mock module """
orig_Popen = subprocess.Popen
self.last_test = None
def Popen(cmd, **kwargs):
self.last_test = cmd
subprocess.Popen = Popen
context = RemoteContext(
"some_host",
usernam... | test_subprocess_delegation | identifier_name |
test_ssh.py | # Copyright (c) 2012 Spotify AB
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may not
# use this file except in compliance with the License. You may obtain a copy of
# the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, s... | self.assertTrue("/some/key.pub" in self.last_test)
self.assertTrue("luigi@some_host" in self.last_test)
self.assertTrue("ls" in self.last_test)
subprocess.Popen = orig_Popen
def test_check_output_fail_connect(self):
""" Test check_output to a non-existing host """
c... | self.assertTrue("ssh" in self.last_test)
self.assertTrue("-i" in self.last_test) | random_line_split |
test_ssh.py | # Copyright (c) 2012 Spotify AB
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may not
# use this file except in compliance with the License. You may obtain a copy of
# the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, s... |
subprocess.Popen = orig_Popen
def test_check_output_fail_connect(self):
""" Test check_output to a non-existing host """
context = RemoteContext("__NO_HOST_LIKE_THIS__")
self.assertRaises(
subprocess.CalledProcessError,
context.check_output, ["ls"]
)... | def test_subprocess_delegation(self):
""" Test subprocess call structure using mock module """
orig_Popen = subprocess.Popen
self.last_test = None
def Popen(cmd, **kwargs):
self.last_test = cmd
subprocess.Popen = Popen
context = RemoteContext(
"s... | identifier_body |
views.py | # Create your views here.
import random
import json
import hashlib
import smtplib
from django.shortcuts import render_to_response, get_object_or_404
from django.conf import settings
from django.template import RequestContext
from django.contrib.auth.models import User
from django.contrib import messages
from django.h... | "mep": feedback.mep,
"type": feedback.type,
"result": feedback.response,
"comment": feedback.text})
msg['Subject'] = _('Memopol2 feedback moderation')
msg['From'] = 'memopol2@memopol2.lqdn.fr'
msg['To'] = ', '.join(to)
... | % {"root_url": settings.ROOT_URL or 'http://localhost:8001/',
"feedback_id": feedback.id,
"actid": actid,
"from": feedback.usercontact, | random_line_split |
views.py | # Create your views here.
import random
import json
import hashlib
import smtplib
from django.shortcuts import render_to_response, get_object_or_404
from django.conf import settings
from django.template import RequestContext
from django.contrib.auth.models import User
from django.contrib import messages
from django.h... |
if form.cleaned_data['staff']:
query['organizationmep__organization__name__in'] = form.cleaned_data['staff']
query['organizationmep__end'] = date(9999, 12, 31)
if form.cleaned_data['staffRole']:
query['organizationmep__role__in'] = form.cleaned_data['staffRole']
if form.c... | query['delegationrole__delegation__name__in'] = form.cleaned_data['delegation']
query['delegationrole__end'] = date(9999, 12, 31)
if form.cleaned_data['delegationRole']:
query['delegationrole__role__in'] = form.cleaned_data['delegationRole'] | conditional_block |
views.py | # Create your views here.
import random
import json
import hashlib
import smtplib
from django.shortcuts import render_to_response, get_object_or_404
from django.conf import settings
from django.template import RequestContext
from django.contrib.auth.models import User
from django.contrib import messages
from django.h... | (l, n):
res = []
for _ in xrange(n):
res.append(random.choice([x for li in [[x[1]] * x[0] for x in l if x[1] not in res] for x in li]))
return res
def getCampaignMeps(request, pk):
c=get_object_or_404(Campaign, pk=pk)
if not 'chosen' in request.session:
request.session['chosen']={}
... | randomsubset | identifier_name |
views.py | # Create your views here.
import random
import json
import hashlib
import smtplib
from django.shortcuts import render_to_response, get_object_or_404
from django.conf import settings
from django.template import RequestContext
from django.contrib.auth.models import User
from django.contrib import messages
from django.h... |
def randomsubset(l, n):
res = []
for _ in xrange(n):
res.append(random.choice([x for li in [[x[1]] * x[0] for x in l if x[1] not in res] for x in li]))
return res
def getCampaignMeps(request, pk):
c=get_object_or_404(Campaign, pk=pk)
if not 'chosen' in request.session:
request.ses... | c = get_object_or_404(Campaign, pk=pk)
if not request.user.is_authenticated():
messages.add_message(request,
messages.ERROR,
"You should login to edit the campaign.")
return HttpResponseRedirect("/campaign/view/%s/" % c.id)
data = { 'camp... | identifier_body |
noUndefined.js | /*
* /MathJax/extensions/TeX/noUndefined.js
*
* Copyright (c) 2010 Design Science, Inc.
*
* Part of the MathJax library.
* See http://www.mathjax.org for details.
*
* Licensed under the Apache License, Version 2.0;
* you may not use this file except in compliance with the License.
*
* ... |
MathJax.Extension["TeX/noUndefined"]={version:"1.1",config:MathJax.Hub.CombineConfig("TeX.noUndefined",{attributes:{mathcolor:"red"}})};MathJax.Hub.Register.StartupHook("TeX Jax Ready",function(){var b=MathJax.Extension["TeX/noUndefined"].config;var a=MathJax.ElementJax.mml;MathJax.InputJax.TeX.Parse.Augment({csUndef... | */
| random_line_split |
test_readlink.rs | use common::util::*;
static GIBBERISH: &'static str = "supercalifragilisticexpialidocious";
#[test]
fn test_canonicalize() {
let (at, mut ucmd) = at_and_ucmd!();
ucmd.arg("-f")
.arg(".")
.run() | #[test]
fn test_canonicalize_existing() {
let (at, mut ucmd) = at_and_ucmd!();
ucmd.arg("-e")
.arg(".")
.run()
.stdout_is(at.root_dir_resolved());
}
#[test]
fn test_canonicalize_missing() {
let (at, mut ucmd) = at_and_ucmd!();
let expected = path_concat!(at.root_dir_resolved(), ... | .stdout_is(at.root_dir_resolved());
}
| random_line_split |
test_readlink.rs | use common::util::*;
static GIBBERISH: &'static str = "supercalifragilisticexpialidocious";
#[test]
fn test_canonicalize() |
#[test]
fn test_canonicalize_existing() {
let (at, mut ucmd) = at_and_ucmd!();
ucmd.arg("-e")
.arg(".")
.run()
.stdout_is(at.root_dir_resolved());
}
#[test]
fn test_canonicalize_missing() {
let (at, mut ucmd) = at_and_ucmd!();
let expected = path_concat!(at.root_dir_resolved()... | {
let (at, mut ucmd) = at_and_ucmd!();
ucmd.arg("-f")
.arg(".")
.run()
.stdout_is(at.root_dir_resolved());
} | identifier_body |
test_readlink.rs | use common::util::*;
static GIBBERISH: &'static str = "supercalifragilisticexpialidocious";
#[test]
fn test_canonicalize() {
let (at, mut ucmd) = at_and_ucmd!();
ucmd.arg("-f")
.arg(".")
.run()
.stdout_is(at.root_dir_resolved());
}
#[test]
fn | () {
let (at, mut ucmd) = at_and_ucmd!();
ucmd.arg("-e")
.arg(".")
.run()
.stdout_is(at.root_dir_resolved());
}
#[test]
fn test_canonicalize_missing() {
let (at, mut ucmd) = at_and_ucmd!();
let expected = path_concat!(at.root_dir_resolved(), GIBBERISH);
ucmd.arg("-m")
... | test_canonicalize_existing | identifier_name |
rustc-diagnostics-1.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
__build_diagnostic_array!(DIAGNOSTICS)
//~^ WARN diagnostic code E0003 never used
| {
__diagnostic_used!(E0002);
//~^ ERROR unknown diagnostic code E0002
__diagnostic_used!(E0001);
//~^ NOTE previous invocation
__diagnostic_used!(E0001);
//~^ WARNING diagnostic code E0001 already used
} | identifier_body |
rustc-diagnostics-1.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | () {
__diagnostic_used!(E0002);
//~^ ERROR unknown diagnostic code E0002
__diagnostic_used!(E0001);
//~^ NOTE previous invocation
__diagnostic_used!(E0001);
//~^ WARNING diagnostic code E0001 already used
}
__build_diagnostic_array!(DIAGNOSTICS)
//~^ WARN diagnostic code E0003 never used
| main | identifier_name |
rustc-diagnostics-1.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | __build_diagnostic_array!(DIAGNOSTICS)
//~^ WARN diagnostic code E0003 never used | //~^ WARNING diagnostic code E0001 already used
}
| random_line_split |
courses.py | # pylint: disable=missing-docstring
# pylint: disable=redefined-outer-name
# pylint: disable=unused-argument
from lettuce import step, world
from common import *
############### ACTIONS ####################
@step('There are no courses$')
def no_courses(step):
world.clear_courses()
create_studio_user()
@... | (step):
create_a_course()
@step('I click the course link in Studio Home$')
def i_click_the_course_link_in_studio_home(step): # pylint: disable=invalid-name
course_css = 'a.course-link'
world.css_click(course_css)
@step('I see an error about the length of the org/course/run tuple')
def i_see_error_about... | i_create_a_course | identifier_name |
courses.py | # pylint: disable=missing-docstring
# pylint: disable=redefined-outer-name
# pylint: disable=unused-argument
from lettuce import step, world
from common import *
############### ACTIONS ####################
@step('There are no courses$')
def no_courses(step):
world.clear_courses()
create_studio_user()
@... |
@step('I see a link for adding a new section$')
def i_see_new_section_link(step):
link_css = '.outline .button-new'
assert world.css_has_text(link_css, 'New Section')
| header_css = 'div.inner-wrapper h1'
assert world.css_has_text(header_css, tab_name) | identifier_body |
courses.py | # pylint: disable=missing-docstring
# pylint: disable=redefined-outer-name
# pylint: disable=unused-argument
from lettuce import step, world
from common import *
############### ACTIONS ####################
@step('There are no courses$')
def no_courses(step):
world.clear_courses()
create_studio_user()
@... | course_css = 'h3.class-title'
assert world.css_has_text(course_css, world.scenario_dict['COURSE'].display_name)
@step('I am on the "([^"]*)" tab$')
def i_am_on_tab(step, tab_name):
header_css = 'div.inner-wrapper h1'
assert world.css_has_text(header_css, tab_name)
@step('I see a link for adding a ne... | def i_see_the_course_in_studio_home(step): | random_line_split |
image.ts | import {error, warning, HELP_IDS} from '../createValidationResult'
import {validateFields, validateField} from './object'
const autoMeta = ['dimensions', 'hasAlpha', 'isOpaque']
export default (typeDef, visitorContext) => {
const problems = []
const fields = typeDef.fields
if (fields) {
problems.push(...va... |
return {
...typeDef,
options,
fields: (Array.isArray(fields) ? fields : []).map((field, index) => {
const {name, ...fieldTypeDef} = field
const {_problems, ...fieldType} = visitorContext.visit(fieldTypeDef, index)
return {
name,
...fieldType,
_problems: validate... | {
problems.push(
warning(
`Image \`metadata\` field contains superfluous properties (they are always included): ${superfluousMeta.join(
', '
)}`
)
)
options = {...options, metadata: metadata.filter((meta) => !autoMeta.includes(meta))}
} | conditional_block |
image.ts | import {error, warning, HELP_IDS} from '../createValidationResult'
import {validateFields, validateField} from './object'
const autoMeta = ['dimensions', 'hasAlpha', 'isOpaque']
export default (typeDef, visitorContext) => {
const problems = []
const fields = typeDef.fields
if (fields) {
problems.push(...va... | )
)
} else if (superfluousMeta.length > 0) {
problems.push(
warning(
`Image \`metadata\` field contains superfluous properties (they are always included): ${superfluousMeta.join(
', '
)}`
)
)
options = {...options, metadata: metadata.filter((meta) => !autoMe... | if (typeof metadata !== 'undefined' && !Array.isArray(metadata)) {
problems.push(
error(
`Invalid type for image \`metadata\` field - must be an array of strings`,
HELP_IDS.ASSET_METADATA_FIELD_INVALID | random_line_split |
index.js | = require('./lib/webextension-channels');
const settings = {};
let prefs;
let app;
// Canned selectable server environment configs
const SERVER_ENVIRONMENTS = {
local: {
BASE_URL: 'http://testpilot.dev:8000',
TESTPILOT_PREFIX: 'testpilot.addon.LOCAL.',
WHITELIST_URLS: 'https://www.mozilla.org/*,about:ho... | };
if ('sourceURI' in install) {
formatted.sourceURI = install.sourceURI.prePath + install.sourceURI.path;
}
if (addon) {
Object.assign(formatted, {
'id': addon.id,
'description': addon.description,
'homepageURL': addon.homepageURL,
'iconURL': addon.iconURL,
'size': addon... | 'state': install.state,
'version': install.version || '',
'progress': install.progress,
'maxProgress': install.maxProgress | random_line_split |
index.js | aws.net',
TESTPILOT_PREFIX: 'testpilot.addon.STAGE.',
WHITELIST_URLS: 'https://www.mozilla.org/*,about:home',
BADGE_COLOR: '#A0AAA0'
},
production: {
BASE_URL: 'https://testpilot.firefox.com',
TESTPILOT_PREFIX: 'testpilot.addon.MAIN.',
WHITELIST_URLS: 'https://www.mozilla.org/*,about:home',
... | {
// Generate a UUID for this client, so we can manage experiment
// installations for multiple browsers per user. DO NOT USE IN METRICS.
store.clientUUID = require('sdk/util/uuid').uuid().toString().slice(1, -1);
store.firstRun = true;
} | conditional_block | |
index.js | require('./lib/webextension-channels');
const settings = {};
let prefs;
let app;
// Canned selectable server environment configs
const SERVER_ENVIRONMENTS = {
local: {
BASE_URL: 'http://testpilot.dev:8000',
TESTPILOT_PREFIX: 'testpilot.addon.LOCAL.',
WHITELIST_URLS: 'https://www.mozilla.org/*,about:home... | (experiment) {
if (isTestpilotAddonID(experiment.addon_id)) {
AddonManager.getAddonByID(experiment.addon_id, a => {
if (a) { a.uninstall(); }
});
}
}
function installExperiment(experiment) {
if (isTestpilotAddonID(experiment.addon_id)) {
AddonManager.getInstallForURL(experiment.xpi_url, install... | uninstallExperiment | identifier_name |
index.js | require('./lib/webextension-channels');
const settings = {};
let prefs;
let app;
// Canned selectable server environment configs
const SERVER_ENVIRONMENTS = {
local: {
BASE_URL: 'http://testpilot.dev:8000',
TESTPILOT_PREFIX: 'testpilot.addon.LOCAL.',
WHITELIST_URLS: 'https://www.mozilla.org/*,about:home... |
function formatInstallData(install, addon) {
const formatted = {
'name': install.name || '',
'error': install.error,
'state': install.state,
'version': install.version || '',
'progress': install.progress,
'maxProgress': install.maxProgress
};
if ('sourceURI' in install) {
formatted.... | {
AddonManager.getAddonByID(self.id, a => a.uninstall());
} | identifier_body |
util.rs | <'tcx>>)
-> Supertraits<'cx, 'tcx>
{
//! Returns an iterator over the trait reference `T` and all of its supertrait references. May
//! contain duplicates. In general the ordering is not defined.
//!
//! Example:
//!
//! ```
//! trait Foo { ... }
//! trait B... | (&mut self, trait_ref: &ty::TraitRef<'tcx>) {
let ty::ParamBounds { builtin_bounds, mut trait_bounds, .. } =
ty::bounds_for_trait_ref(self.tcx, trait_ref);
for builtin_bound in builtin_bounds.iter() {
let bound_trait_ref = trait_ref_for_builtin_bound(self.tcx,
... | push | identifier_name |
util.rs | ::from_fn(bounds.len(), |i| bounds[i].clone());
let visited: HashSet<Rc<ty::TraitRef>> =
bounds.iter()
.map(|b| (*b).clone())
.collect();
let entry = SupertraitEntry { position: 0, supertraits: bounds };
Supertraits { tcx: tcx, stack: vec![entry], visited: visited }
}
... |
super::VtableParam(ref v) =>
format!("VtableParam({})", v.repr(tcx)),
super::VtableBuiltin(ref d) => | random_line_split | |
util.rs | ferCtxt<'a, 'tcx>,
span: Span,
impl_def_id: ast::DefId)
-> Substs<'tcx>
{
let tcx = infcx.tcx;
let impl_generics = ty::lookup_item_type(tcx, impl_def_id).generics;
infcx.fresh_substs_for_gene... | {
ty::type_err_to_str(tcx, self)
} | identifier_body |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.