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 |
|---|---|---|---|---|
test_compressed_int_list.py | # -*- coding: utf-8 -*-
# Copyright 2017 GIG Technology NV
#
# 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... |
class TestCase(mc_unittest.TestCase):
l = [1, 1, 1, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1]
def setUp(self, datastore_hr_probability=0):
mc_unittest.TestCase.setUp(self, datastore_hr_probability=datastore_hr_probability)
class MyModel(db.Expando):
pass
m = MyModel(key_name='test')
... | from google.appengine.ext import db
import mc_unittest
from rogerthat.models import CompressedIntegerListExpando
| random_line_split |
test_compressed_int_list.py | # -*- coding: utf-8 -*-
# Copyright 2017 GIG Technology NV
#
# 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... |
m = MyModel.get_by_key_name('test')
m.test.append(5)
m.put()
m = MyModel.get_by_key_name('test')
self.assertListEqual(TestCase.l + [5], m.test)
def test_ljust(self):
class MyModel(CompressedIntegerListExpando):
_attribute_prefix = 'test'
m = M... | _attribute_prefix = 'test' | identifier_body |
test_compressed_int_list.py | # -*- coding: utf-8 -*-
# Copyright 2017 GIG Technology NV
#
# 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):
class MyModel(CompressedIntegerListExpando):
_attribute_prefix = 'test'
m = MyModel.get_by_key_name('test')
print 'Before: %r' % m.test
m.test.ljust(5, 0, 10) # will append 5 zeroes, and limit the number of entries to 10
print 'After: %r' % m.test
ex... | test_ljust | identifier_name |
uploaded_file.rs | // Copyright © 2015 by Michael Dilger (of New Zealand)
// This code is licensed under the MIT license (see LICENSE-MIT for details)
use std::path::PathBuf;
use std::ops::Drop;
use mime::Mime;
use tempdir::TempDir;
use error::Error;
use textnonce::TextNonce;
/// An uploaded file that was received as part of `multipart... | path: path,
filename: None,
content_type: content_type,
size: 0,
tempdir: tempdir,
})
}
}
impl Drop for UploadedFile {
fn drop(&mut self) {
let _ = ::std::fs::remove_file(&self.path);
let _ = ::std::fs::remove_dir(&self.tempdir... | let tempdir = try!(TempDir::new("formdata")).into_path();
let mut path = tempdir.clone();
path.push(TextNonce::sized_urlsafe(32).unwrap().into_string());
Ok(UploadedFile { | random_line_split |
uploaded_file.rs | // Copyright © 2015 by Michael Dilger (of New Zealand)
// This code is licensed under the MIT license (see LICENSE-MIT for details)
use std::path::PathBuf;
use std::ops::Drop;
use mime::Mime;
use tempdir::TempDir;
use error::Error;
use textnonce::TextNonce;
/// An uploaded file that was received as part of `multipart... | &mut self) {
let _ = ::std::fs::remove_file(&self.path);
let _ = ::std::fs::remove_dir(&self.tempdir);
}
}
| rop( | identifier_name |
modalTemplate.ts | /*
* Copyright 2017 TWO SIGMA OPEN SOURCE, 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
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by appl... | <div class="form-group has-feedback">
<label>Personal Access Token</label>
<input required type="password" class="form-control">
</div>
<p class="help-block">
<span>Enter a <a target="_blank" href="https://github.com/settings/tokens">Personal Access Token</a> to publish the notebook as a g... | <form> | random_line_split |
sfc_main.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Testing module from creating product using
http://www.sendfromchina.com/default/index/webservice
"""
from flask import Flask, render_template, request
from flask_wtf.csrf import CSRFProtect
from werkzeug.datastructures import MultiDict
from forms import SFCCreateO... |
return render_template('create_asn.html', form_master=form_asn, form_detail=form_order_detail, res=res)
@app.route("/get_order_by_code", methods=['GET', 'POST'])
def get_order():
res = None
if request.method == 'POST':
res = sfcapi.get_order_by_code(order_code=request.form['ordersCode'], detail_... | form_asn = SFCASNInfo()
form_order_detail = SFCOrderDetail() | conditional_block |
sfc_main.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Testing module from creating product using
http://www.sendfromchina.com/default/index/webservice
"""
from flask import Flask, render_template, request
from flask_wtf.csrf import CSRFProtect
from werkzeug.datastructures import MultiDict
from forms import SFCCreateO... | ():
return render_template('index.html')
@app.route("/create_product", methods=['GET', 'POST'])
def create_product():
res = None
if request.method == 'POST':
product_info = {k: v for k, v in request.form.items() if k not in ('csrf_token', 'pocId', 'poValue', 'imgUrl')}
product_info['image'... | hello | identifier_name |
sfc_main.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Testing module from creating product using
http://www.sendfromchina.com/default/index/webservice
"""
from flask import Flask, render_template, request
from flask_wtf.csrf import CSRFProtect
from werkzeug.datastructures import MultiDict
from forms import SFCCreateO... |
@app.route("/create_asn", methods=['GET', 'POST'])
def create_asn():
res = None
if request.method == 'POST':
asn_info = {k: v for k, v in request.form.items() if k in
[i for i in SFCASNInfo.__dict__.keys() if i[0] != '_']}
order_detail = {k: v for k, v in request.form.item... | res = None
if request.method == 'POST':
order_info = {k: v for k, v in request.form.items() if k in
[i for i in SFCCreateOrder.__dict__.keys() if i[0] != '_']}
order_detail = {k: v for k, v in request.form.items() if
k in [i for i in SFCOrderDetail.__dic... | identifier_body |
sfc_main.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Testing module from creating product using
http://www.sendfromchina.com/default/index/webservice
"""
from flask import Flask, render_template, request
from flask_wtf.csrf import CSRFProtect
from werkzeug.datastructures import MultiDict
from forms import SFCCreateO... | app.secret_key = 's3cr3tasdasdasdasd'
header_request = {'customerId': 'R2036',
'appToken': 'MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDK1YNcdunmWXoK1ys6hyi+LWQdPx6Vmr/9kNlKOw4cK5Q8FWA3nfGeeG49Pq2TlYKVLdSw1fr60AAJFQOuXmol6lmyn+/xwx6j21XLx9/4vdDNSTR8Hcp7oqGNNr5DlI0onhJ7sd+rAxhIOwLNnZv6T/XtVqQNuGVXTq/dX0zkaQ... | random_line_split | |
urls.py | from __future__ import absolute_import, unicode_literals
from django.conf import settings
from django.conf.urls import include, url
from django.contrib import admin
from django.contrib.auth import urls as djangoauth_urls
from search import views as search_views
from blog import views as blog_views
from wagtail.wagtai... | from django.conf.urls.static import static
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
# Serve static and media files from development server
urlpatterns += staticfiles_urlpatterns()
urlpatterns += static(settings.MEDIA_URL,
document_root=settings.MEDIA... | conditional_block | |
urls.py | from __future__ import absolute_import, unicode_literals
from django.conf import settings
from django.conf.urls import include, url
from django.contrib import admin
from django.contrib.auth import urls as djangoauth_urls
from search import views as search_views
from blog import views as blog_views
from wagtail.wagtai... | url(r'^', include(djangoauth_urls)),
url(r'^django-admin/', include(admin.site.urls)),
url(r'^admin/', include(wagtailadmin_urls)),
url(r'^documents/', include(wagtaildocs_urls)),
url(r'^search/$', search_views.search, name='search'),
# For anything not caught by a more specific rule above, h... | random_line_split | |
create_rating.rs | use super::*;
use diesel::connection::Connection;
pub fn create_rating(
connections: &sqlite::Connections,
indexer: &mut dyn PlaceIndexer,
rate_entry: usecases::NewPlaceRating,
) -> Result<(String, String)> {
// Add new rating to existing entry
let (rating_id, comment_id, place, status, ratings) =... | })?;
Ok((rating_id, comment_id, place, status, ratings))
}
Err(err) => {
prepare_err = Some(err);
Err(diesel::result::Error::RollbackTransaction)
}
... | diesel::result::Error::RollbackTransaction | random_line_split |
create_rating.rs | use super::*;
use diesel::connection::Connection;
pub fn | (
connections: &sqlite::Connections,
indexer: &mut dyn PlaceIndexer,
rate_entry: usecases::NewPlaceRating,
) -> Result<(String, String)> {
// Add new rating to existing entry
let (rating_id, comment_id, place, status, ratings) = {
let connection = connections.exclusive()?;
let mut pr... | create_rating | identifier_name |
create_rating.rs | use super::*;
use diesel::connection::Connection;
pub fn create_rating(
connections: &sqlite::Connections,
indexer: &mut dyn PlaceIndexer,
rate_entry: usecases::NewPlaceRating,
) -> Result<(String, String)> | Err(diesel::result::Error::RollbackTransaction)
}
}
})
.map_err(|err| {
if let Some(err) = prepare_err {
err
} else {
RepoError::from(err).into()
}
... | {
// Add new rating to existing entry
let (rating_id, comment_id, place, status, ratings) = {
let connection = connections.exclusive()?;
let mut prepare_err = None;
connection
.transaction::<_, diesel::result::Error, _>(|| {
match usecases::prepare_new_rating(... | identifier_body |
CustomSlider.web.tsx | /*!
Copyright 2016-2021 Brazil Ltd.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
... | else if (theme.Slider?.onValueChange) {
theme.Slider.onValueChange(parseFloat(value));
}
},
[onValueChange]
);
return (
<View style={style}>
<style>{cssStyles}</style>
<input
type="range"
className={thumbRound ? "slider slider-round" : "slider"}
disabl... | {
onValueChange(parseFloat(value));
} | conditional_block |
CustomSlider.web.tsx | /*!
Copyright 2016-2021 Brazil Ltd.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
... | }
.slider:focus {
outline: none;
}
.slider::-webkit-slider-runnable-track {
height: 1px;
border: 2px solid rgba(255, 255, 255, 0.2);
border-radius: 8px;
background: rgba(255, 255, 255, 0.2);
cursor: pointer;
}
.slider::-webkit-slider-thumb {
background: ... |
-webkit-appearance: none; | random_line_split |
play_20170606144659.js | var playState = {
create: function(){
var background = game.add.sprite(0, 0, 'cidade');
background.width = 1300;
background.height = 650;
graphics = game.add.graphics(0, 0);
groupCidade = game.add.group();
groupCidade.inputEnableChildren = true;
var x = 1... | graphics.destroy();
var cachorro = game.add.sprite(110, 210, 'cachorro');
cachorro.width = 300;
cachorro.height = 170;
// Desenha o gato e a borda da box
var gato = game.add.sprite(510, 210, 'gato');
gato.width = 300;
gato.height = 170;
... | {
// Gera os retangulos que ficarão atras das imagens
graphics.beginFill(0xFFFFFF);
graphics.lineStyle(3, 0x05005e, 1);
graphics.drawRoundedRect(x, 200, 315, 190, 10);
graphics.endFill();
var button = groupCidade.create(x, 200, graphics.generateTe... | conditional_block |
play_20170606144659.js | var playState = {
create: function(){
var background = game.add.sprite(0, 0, 'cidade');
background.width = 1300;
background.height = 650;
graphics = game.add.graphics(0, 0);
groupCidade = game.add.group();
groupCidade.inputEnableChildren = true;
var x = 1... |
function initial(){
game.add.tween(groupCidade.children[0].scale).to( { x: 1, y: 1 }, 1000, Phaser.Easing.Linear.In, true);
game.add.tween(cachorro.scale).to( { x: 0.5, y: 0.5 }, 1000, Phaser.Easing.Linear.In, true);
groupCidade.children[0].x -= 230;
cachorro.x ... |
groupCidade.children[1].alpha = 0;
groupCidade.children[2].alpha = 0;
gato.alpha = 0;
passaro.alpha = 0;
background.alpha = 0.5;
groupCidade.children[0].x += 230;
cachorro.x += 230;
groupCidade.children[0].y -= 70;
... | identifier_body |
play_20170606144659.js | var playState = {
create: function(){
var background = game.add.sprite(0, 0, 'cidade');
background.width = 1300;
background.height = 650;
graphics = game.add.graphics(0, 0);
groupCidade = game.add.group();
groupCidade.inputEnableChildren = true;
var x = 1... |
function initial(){
game.add.tween(groupCidade.children[0].scale).to( { x: 1, y: 1 }, 1000, Phaser.Easing.Linear.In, true);
game.add.tween(cachorro.scale).to( { x: 0.5, y: 0.5 }, 1000, Phaser.Easing.Linear.In, true);
groupCidade.children[0].x -= 230;
cachorro.x ... | random_line_split | |
play_20170606144659.js | var playState = {
create: function(){
var background = game.add.sprite(0, 0, 'cidade');
background.width = 1300;
background.height = 650;
graphics = game.add.graphics(0, 0);
groupCidade = game.add.group();
groupCidade.inputEnableChildren = true;
var x = 1... | ){
game.add.tween(groupCidade.children[0].scale).to( { x: 1, y: 1 }, 1000, Phaser.Easing.Linear.In, true);
game.add.tween(cachorro.scale).to( { x: 0.5, y: 0.5 }, 1000, Phaser.Easing.Linear.In, true);
groupCidade.children[0].x -= 230;
cachorro.x -= 230;
groupC... | nitial( | identifier_name |
setup.py | "build directory (where to install from)"),
('force', 'f', "force installation (overwrite existing files)"),
('skip-build', None, "skip the build steps"),
]
boolean_options = ['force', 'skip-build']
def initialize_options(self):
self.install_dir = None
self.build_dir = None... |
def get_outputs(self):
return self.outfiles
class picard_install(install):
user_options = install.user_options + [
('install-locales=', None,
"installation directory for locales"),
('localedir=', None, ''),
('disable-autoupdate', None, ''),
('disable-locales... | return self.locales or [] | identifier_body |
setup.py | .localedir is None:
self.localedir = '/usr/share/locale'
if self.disable_autoupdate is None:
self.disable_autoupdate = False
if self.disable_locales is None:
self.sub_commands.append(('build_locales', None))
def run(self):
if 'bdist_nsis' not in sys.argv:... | if loc in extract_attributes:
attributes[u"%s:%03d" % (loc, pos)] = message.id | conditional_block | |
setup.py | comma-separated list of files to rebuild"),
]
def initialize_options(self):
self.files = []
def finalize_options(self):
if self.files:
files = []
for f in self.files.split(","):
head, tail = os.path.split(f)
m = re.match(r'(?:ui_)?([^... | log.info("%s was rewritten (%d countries)" % (filename,
len(countries)))
def attributes_py_file(self, attributes): | random_line_split | |
setup.py | "build directory (where to install from)"),
('force', 'f', "force installation (overwrite existing files)"),
('skip-build', None, "skip the build steps"),
]
boolean_options = ['force', 'skip-build']
def initialize_options(self):
self.install_dir = None
self.build_dir = None... | (self):
self.minimum_perc = int(self.minimum_perc)
def run(self):
if tx_executable is None:
sys.exit('Transifex client executable (tx) not found.')
txpull_cmd = [
tx_executable,
'pull',
'--force',
'--all',
'--minimum-pe... | finalize_options | identifier_name |
metadata_synchronizer.py | #!/usr/bin/python
#
# Copyright 2020 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
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or ag... | (self,
datacatalog_project_id,
datacatalog_location_id,
atlas_connection_args,
atlas_entity_types=None,
enable_monitoring=None):
self._project_id = datacatalog_project_id
self._location_id = datacatalog_location_id
... | __init__ | identifier_name |
metadata_synchronizer.py | #!/usr/bin/python
#
# Copyright 2020 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
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or ag... |
def _clean_up_obsolete_metadata(self, assembled_entries):
logging.info('===> Deleting Data Catalog obsolete metadata...')
self._delete_obsolete_entries(assembled_entries)
logging.info('==== DONE ========================================')
logging.info('')
def _log_metadata(self... | logging.info('')
logging.info('===> Mapping Data Catalog entries relationships...')
self._map_datacatalog_relationships(assembled_entries)
logging.info('==== DONE ========================================')
logging.info(
'===> Synchronizing Apache Atlas :: ... | conditional_block |
metadata_synchronizer.py | #!/usr/bin/python
#
# Copyright 2020 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
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or ag... | self._atlas_entity_types = atlas_entity_types
event_hook = atlas_connection_args.get('event_hook')
if not event_hook:
self._metadata_scraper = scrape.MetadataScraper(
atlas_connection_args)
self._tag_template_factory = prepare.DataCatalogTagTemplateFactory(... | atlas_entity_types=None,
enable_monitoring=None):
self._project_id = datacatalog_project_id
self._location_id = datacatalog_location_id
self._atlas_connection_args = atlas_connection_args | random_line_split |
metadata_synchronizer.py | #!/usr/bin/python
#
# Copyright 2020 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
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or ag... |
def _sync_assembled_entries(self, assembled_entries, tag_templates_dict):
self._log_entries(assembled_entries)
if assembled_entries:
logging.info('')
logging.info('===> Mapping Data Catalog entries relationships...')
self._map_datacatalog_relationships(assembled... | """Coordinates a full scrape > prepare > ingest process."""
logging.info('')
logging.info('===> Scraping Apache Atlas metadata...')
metadata_dict, _ = self._metadata_scraper.get_metadata()
self._log_metadata(metadata_dict)
tag_templates_dict = self._make_tag_templates_dict(metada... | identifier_body |
users.service.ts | import { Injectable } from '@angular/core';
import { Http, Headers, RequestOptions, Response } from '@angular/http';
import { User } from './_models/index';
@Injectable()
export class UsersService {
constructor(private http: Http) { }
usersData = [{
'uid': '23554654235325',
'firstname': 'Fir... |
getAll() {
return this.http.get('http://51.255.196.182:3000/user', this.jwt()).map((response: Response) => response.json());
}
getById(id: number) {
return this.http.get('http://51.255.196.182:3000/user/' + id, this.jwt()).map((response: Response) => response.json());
}
refresh(... | {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve(this.usersData[0]);
}, 1);
});
} | identifier_body |
users.service.ts | import { Injectable } from '@angular/core';
import { Http, Headers, RequestOptions, Response } from '@angular/http';
import { User } from './_models/index';
@Injectable()
export class UsersService {
constructor(private http: Http) { }
usersData = [{
'uid': '23554654235325',
'firstname': 'Fir... | resolve(this.usersData);
}, 1);
});
}
getOne(): Promise<any> {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve(this.usersData[0]);
}, 1);
});
}
getAll() {
return this.http.get('http://51.255.196... | getData(): Promise<any> {
return new Promise((resolve, reject) => {
setTimeout(() => { | random_line_split |
users.service.ts | import { Injectable } from '@angular/core';
import { Http, Headers, RequestOptions, Response } from '@angular/http';
import { User } from './_models/index';
@Injectable()
export class UsersService {
constructor(private http: Http) { }
usersData = [{
'uid': '23554654235325',
'firstname': 'Fir... |
}
} | {
let headers = new Headers({ 'Authorization': 'Bearer ' + currentUser.token });
return new RequestOptions({ headers: headers });
} | conditional_block |
users.service.ts | import { Injectable } from '@angular/core';
import { Http, Headers, RequestOptions, Response } from '@angular/http';
import { User } from './_models/index';
@Injectable()
export class UsersService {
constructor(private http: Http) { }
usersData = [{
'uid': '23554654235325',
'firstname': 'Fir... | (): Promise<any> {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve(this.usersData);
}, 1);
});
}
getOne(): Promise<any> {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve(this.usersData[0]);
... | getData | identifier_name |
datetime.rs | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This software may be used and distributed according to the terms of the
* GNU General Public License version 2.
*/
use chrono::{FixedOffset, TimeZone};
use lazy_static::lazy_static;
use mononoke_types::DateTime;
/// Return a `DateTime` corresponding to ... | (year: i32, offset: i32) -> DateTime {
DateTime::new(FixedOffset::west(offset).ymd(year, 1, 1).and_hms(0, 0, 0))
}
pub const PST_OFFSET: i32 = 7 * 3600;
lazy_static! {
/// 1970-01-01 00:00:00 UTC.
pub static ref EPOCH_ZERO: DateTime = DateTime::from_timestamp(0, 0).unwrap();
/// 1970-01-01 00:00:00 UT... | day_1_tz | identifier_name |
datetime.rs | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This software may be used and distributed according to the terms of the
* GNU General Public License version 2.
*/
use chrono::{FixedOffset, TimeZone};
use lazy_static::lazy_static;
use mononoke_types::DateTime;
/// Return a `DateTime` corresponding to ... |
/// 1900-01-01 00:00:00 UTC.
pub static ref YEAR_1900: DateTime = day_1_utc(1900);
/// 1900-01-01 00:00:00 UTC-07.
pub static ref YEAR_1900_PST: DateTime = day_1_tz(1900, PST_OFFSET);
/// 2000-01-01 00:00:00 UTC.
pub static ref YEAR_2000: DateTime = day_1_utc(2000);
/// 2000-01-01 00:00:00... | pub static ref EPOCH_ZERO_PST: DateTime = DateTime::from_timestamp(0, PST_OFFSET).unwrap(); | random_line_split |
datetime.rs | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This software may be used and distributed according to the terms of the
* GNU General Public License version 2.
*/
use chrono::{FixedOffset, TimeZone};
use lazy_static::lazy_static;
use mononoke_types::DateTime;
/// Return a `DateTime` corresponding to ... |
/// Return a `DateTime` corresponding to <year>-01-01 00:00:00 UTC,
/// with the specified offset applied.
pub fn day_1_tz(year: i32, offset: i32) -> DateTime {
DateTime::new(FixedOffset::west(offset).ymd(year, 1, 1).and_hms(0, 0, 0))
}
pub const PST_OFFSET: i32 = 7 * 3600;
lazy_static! {
/// 1970-01-01 00:... | {
DateTime::new(FixedOffset::west(0).ymd(year, 1, 1).and_hms(0, 0, 0))
} | identifier_body |
signalr.d.ts | // Type definitions for SignalR 1.0
// Project: http://www.asp.net/signalr
// Definitions by: Boris Yankov <https://github.com/borisyankov/>, T. Michael Keesey <https://github.com/keesey/>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="../jquery/jquery.d.ts" />
interface HubMetho... | log(msg: string, logging: boolean): void;
isCrossDomain(url: string): boolean;
changeState(connection: SignalR, expectedState: number, newState: number): boolean;
isDisconnecting(connection: SignalR): boolean;
// createHubProxy(hubName: string): SignalR;
start(): JQueryPromise<any>;
start(c... | hubConnection(url?: string): SignalR;
| random_line_split |
hammingdb.py | import lmdb
from zounds.nputil import Growable, packed_hamming_distance
import numpy as np
from multiprocessing.dummy import Pool as ThreadPool
from multiprocessing import cpu_count
import os
import binascii
class HammingDb(object):
def __init__(self, path, map_size=1000000000, code_size=8, writeonly=False):
... |
def _add_code(self, _id, code):
if self.writeonly:
return
arr = self._append_buffer
arr[0]['id'] = _id
arr[0]['code'] = self._np_code(code)
self._codes.append(arr)
self._ids.add(_id)
def _check_for_external_modifications(self):
if self.__le... | code_len = len(code)
if code_len != self.code_size:
fmt = '''code must be equal to code_size
({self.code_size}), but was {code_len}'''
raise ValueError(fmt.format(**locals())) | identifier_body |
hammingdb.py | import lmdb
from zounds.nputil import Growable, packed_hamming_distance
import numpy as np
from multiprocessing.dummy import Pool as ThreadPool
from multiprocessing import cpu_count
import os
import binascii
class HammingDb(object):
def __init__(self, path, map_size=1000000000, code_size=8, writeonly=False):
... |
if self._codes is not None:
return
initial_size = max(int(1e6), len(self))
self._codes = Growable(self._recarray(initial_size))
def _np_code(self, code):
self._code_bytearray[:] = code
return self._code_buffer
def _validate_code_size(self, code):
c... | return | conditional_block |
hammingdb.py | import lmdb
from zounds.nputil import Growable, packed_hamming_distance
import numpy as np
from multiprocessing.dummy import Pool as ThreadPool
from multiprocessing import cpu_count
import os
import binascii
class HammingDb(object):
def __init__(self, path, map_size=1000000000, code_size=8, writeonly=False):
... | (self):
with self.env.begin() as txn:
lmdb_size = txn.stat(self.index)['entries']
if not lmdb_size:
return 0
return lmdb_size
def _recarray(self, size):
return np.recarray(
size,
dtype=[
('id', 'S32'),
... | __len__ | identifier_name |
hammingdb.py | import lmdb
from zounds.nputil import Growable, packed_hamming_distance
import numpy as np
from multiprocessing.dummy import Pool as ThreadPool
from multiprocessing import cpu_count
import os
import binascii
class HammingDb(object):
def __init__(self, path, map_size=1000000000, code_size=8, writeonly=False):
... | self._catch_up_on_in_memory_store()
self._thread_count = cpu_count()
self._pool = ThreadPool(processes=self._thread_count)
def close(self):
self.env.close()
def __del__(self):
self.close()
def __enter__(self):
return self
def __exit__(self, exc_type, ... | self._ids = set() | random_line_split |
CRLList.tsx | import PropTypes from "prop-types";
import React from "react";
import { connect } from "react-redux";
import { loadAllCertificates } from "../../AC";
import accordion from "../../decorators/accordion";
import { filteredCrlsSelector } from "../../selectors/crlsSelectors";
import ProgressBars from "../ProgressBars";
impo... |
getCollapsibleBody() {
const { crls, activeCert, selectedCert, operation, toggleOpenItem, isItemOpened } = this.props;
if (!crls || crls.length === 0) {
return null;
}
const elements = crls.map((crl: any) =>
<CRLListItem
key={crl.id}
crl={crl}
chooseCert={() => ... | {
const { isLoading } = this.props;
if (isLoading) {
return <ProgressBars />;
}
return (
<React.Fragment>
<ul className="collapsible" data-collapsible="accordion">
{this.getCollapsibleBody()}
</ul>
</React.Fragment>
);
} | identifier_body |
CRLList.tsx | import PropTypes from "prop-types";
import React from "react";
import { connect } from "react-redux";
import { loadAllCertificates } from "../../AC";
import accordion from "../../decorators/accordion";
import { filteredCrlsSelector } from "../../selectors/crlsSelectors";
import ProgressBars from "../ProgressBars";
impo... |
const elements = crls.map((crl: any) =>
<CRLListItem
key={crl.id}
crl={crl}
chooseCert={() => activeCert(crl)}
operation={operation}
selectedCert={() => selectedCert(crl)}
isOpen={isItemOpened(crl.id.toString())}
toggleOpen={toggleOpenItem(crl.id.toStr... | {
return null;
} | conditional_block |
CRLList.tsx | import PropTypes from "prop-types";
import React from "react";
import { connect } from "react-redux";
import { loadAllCertificates } from "../../AC";
import accordion from "../../decorators/accordion";
import { filteredCrlsSelector } from "../../selectors/crlsSelectors";
import ProgressBars from "../ProgressBars";
impo... | () {
// tslint:disable-next-line:no-shadowed-variable
const { isLoaded, isLoading, loadAllCertificates } = this.props;
if (!isLoading && !isLoaded) {
loadAllCertificates();
}
$(".collapsible").collapsible();
}
render() {
const { isLoading } = this.props;
if (isLoading) {
... | componentDidMount | identifier_name |
CRLList.tsx | import PropTypes from "prop-types";
import React from "react";
import { connect } from "react-redux";
import { loadAllCertificates } from "../../AC";
import accordion from "../../decorators/accordion";
import { filteredCrlsSelector } from "../../selectors/crlsSelectors";
import ProgressBars from "../ProgressBars";
impo... | isLoaded: state.crls.loaded,
isLoading: state.crls.loading,
};
}, { loadAllCertificates })(accordion(CRLList)); | random_line_split | |
utils.py | from __future__ import unicode_literals
"""
This module abstracts all the bytes<-->string conversions so that the python 2
and 3 code everywhere else is similar. This also has a few simple functions
that deal with the fact that bytes are different between the 2 versions even
when using from __future__ import unicode_... |
try:
from cStringIO import StringIO as SimIO
except:
from StringIO import StringIO as SimIO
def string_to_bytes(text):
"""
See other implementation for notes
"""
return b"".join([c for c in text])
def bytes_to_string(byte_array):
"""
Se... | return d.iteritems() | identifier_body |
utils.py | from __future__ import unicode_literals
"""
This module abstracts all the bytes<-->string conversions so that the python 2
and 3 code everywhere else is similar. This also has a few simple functions
that deal with the fact that bytes are different between the 2 versions even
when using from __future__ import unicode_... | """
See other implementation for notes
"""
return ''.join([b for b in byte_array])
def bytestr_to_string(bytestr):
"""
See other implementation for notes
"""
return unicode(bytestr, 'utf-8')
def byte_chr(bytes_str):
"""
See other ... | range = xrange
unicode = unicode
long = long
unichr = unichr
def iteritems(d):
return d.iteritems()
try:
from cStringIO import StringIO as SimIO
except:
from StringIO import StringIO as SimIO
def string_to_bytes(text):
"""
See other implementation f... | conditional_block |
utils.py | from __future__ import unicode_literals
"""
This module abstracts all the bytes<-->string conversions so that the python 2
and 3 code everywhere else is similar. This also has a few simple functions
that deal with the fact that bytes are different between the 2 versions even
when using from __future__ import unicode_... | def string_to_bytes(text):
"""
See other implementation for notes
"""
return b"".join([c for c in text])
def bytes_to_string(byte_array):
"""
See other implementation for notes
"""
return ''.join([b for b in byte_array])
def bytestr_to_string... | try:
from cStringIO import StringIO as SimIO
except:
from StringIO import StringIO as SimIO
| random_line_split |
utils.py | from __future__ import unicode_literals
"""
This module abstracts all the bytes<-->string conversions so that the python 2
and 3 code everywhere else is similar. This also has a few simple functions
that deal with the fact that bytes are different between the 2 versions even
when using from __future__ import unicode_... | (string):
"""
Convert a string to a bytes object. This encodes the object as well which
will typically change ord on each element & change the length (i.e. 1 char
could become 1/2/3 bytes)
"""
return string.encode('utf-8')
def bytestr_to_string(bytestr):
"""... | string_to_bytestr | identifier_name |
min_order_common.py | # -*- coding: utf-8 -*-
"""
Common design parameters for minimum order design methods
@author: Christian Muenker
"""
from __future__ import print_function, division, unicode_literals
#from importlib import import_module
#import filterbroker as fb
class min_order_common(object):
| "LP": {"min":{"par":['f_S','A_PB','A_SB','F_PB','F_SB']}},
"HP": {"min":{"par":['f_S','A_PB','A_SB','F_SB','F_PB']}},
"BP": {"min":{"par":['f_S','A_PB','A_SB','A_SB2',
'F_SB','F_PB','F_PB2','F_SB2']}},
... | def __init__(self):
self.name = {'common':'Common filter params'}
# message for min. filter order response types:
msg_min = ("Enter the maximum pass band ripple, minimum stop band "
"attenuation and the corresponding corner frequencies.")
# VISIBLE widget... | identifier_body |
min_order_common.py | # -*- coding: utf-8 -*-
"""
Common design parameters for minimum order design methods
@author: Christian Muenker
"""
from __future__ import print_function, division, unicode_literals
#from importlib import import_module
#import filterbroker as fb
class min_order_common(object):
def __init__(self):
... | "BS": {"min":{"par":['f_S','A_PB','A_SB','A_PB2',
'F_PB','F_SB','F_SB2','F_PB2']}}
# "HIL": {"man":{"par":['F_SB', 'F_PB', 'F_PB2', 'F_SB2','A_SB','A_PB','A_SB2']}}
#"DIFF":
} | "BP": {"min":{"par":['f_S','A_PB','A_SB','A_SB2',
'F_SB','F_PB','F_PB2','F_SB2']}}, | random_line_split |
min_order_common.py | # -*- coding: utf-8 -*-
"""
Common design parameters for minimum order design methods
@author: Christian Muenker
"""
from __future__ import print_function, division, unicode_literals
#from importlib import import_module
#import filterbroker as fb
class | (object):
def __init__(self):
self.name = {'common':'Common filter params'}
# message for min. filter order response types:
msg_min = ("Enter the maximum pass band ripple, minimum stop band "
"attenuation and the corresponding corner frequencies.")
... | min_order_common | identifier_name |
file.js | // Editor.js
(function() {
var STORAGE_KEY = slingUserId+'-browser-file';
var editor = ace.edit("editor");
var saveBtn = $('#saveBtn');
// parent file should set the aceMode variable
editor.getSession().setMode(aceMode);
editor.getSession().setUseWrapMode(false);
editor.getSession().on('change', function(e) {
... |
})()
| {
$('#aceThemeSelect').val(storage.theme).trigger('change');
} | conditional_block |
file.js | // Editor.js
(function() {
var STORAGE_KEY = slingUserId+'-browser-file';
var editor = ace.edit("editor");
var saveBtn = $('#saveBtn');
// parent file should set the aceMode variable
editor.getSession().setMode(aceMode);
editor.getSession().setUseWrapMode(false);
editor.getSession().on('change', function(e) {
... | saveBtn.on('click', function(e) {
this.disabled=true;
$('input#jcrData').val(editor.getValue());
$('#updateForm').submit();
});
$('#editor').css('opacity',1);
var storage = getJsonLocalStorage(STORAGE_KEY);
if (storage && storage.theme) {
$('#aceThemeSelect').val(storage.theme).trigger('change');
}
})() | $('#aceThemeSelect').on('change',function () {
var theme = $(this).val();
editor.setTheme("ace/theme/"+theme);
setLocalStorage(STORAGE_KEY, {theme:theme});
}) | random_line_split |
enum_list.rs | // Copyright (c) 2013-2015 Sandstorm Development Group, Inc. and contributors
// Licensed under the MIT License:
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, inc... |
pub fn len(&self) -> u32 { self.reader.len() }
}
impl <'a, T : FromU16> FromPointerReader<'a> for Reader<'a, T> {
fn get_from_pointer(reader : &PointerReader<'a>) -> Result<Reader<'a, T>> {
Ok(Reader { reader : try!(reader.get_list(TwoBytes, ::std::ptr::null())),
marker : ::std::... | {
Reader::<'b, T> { reader : reader, marker : ::std::marker::PhantomData }
} | identifier_body |
enum_list.rs | // Copyright (c) 2013-2015 Sandstorm Development Group, Inc. and contributors
// Licensed under the MIT License:
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, inc... | (&self, index : u32) -> ::std::result::Result<T, NotInSchema> {
assert!(index < self.len());
let result : u16 = PrimitiveElement::get(&self.reader, index);
FromU16::from_u16(result)
}
}
pub struct Builder<'a, T> {
marker : ::std::marker::PhantomData<T>,
builder : ListBuilder<'a>
}
... | get | identifier_name |
enum_list.rs | // Copyright (c) 2013-2015 Sandstorm Development Group, Inc. and contributors
// Licensed under the MIT License:
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, inc... | FromU16::from_u16(result)
}
}
impl <'a, T> ::traits::SetPointerBuilder<Builder<'a, T>> for Reader<'a, T> {
fn set_pointer_builder<'b>(pointer : ::private::layout::PointerBuilder<'b>,
value : Reader<'a, T>) -> Result<()> {
pointer.set_list(&value.reader)
}
} |
impl <'a, T : ToU16 + FromU16> Builder<'a, T> {
pub fn get(&self, index : u32) -> ::std::result::Result<T, NotInSchema> {
assert!(index < self.len());
let result : u16 = PrimitiveElement::get_from_builder(&self.builder, index); | random_line_split |
jsgrid.field.js | (function(jsGrid, $, undefined) {
function Field(config) {
$.extend(true, this, config);
this.sortingFunc = this._getSortingFunc();
}
Field.prototype = {
name: "",
title: null,
css: "",
align: "",
width: 100,
visible: true,
filtering... |
if(typeof sorter === "string") {
return jsGrid.sortStrategies[sorter];
}
throw Error("wrong sorter for the field \"" + this.name + "\"!");
}
};
jsGrid.Field = Field;
}(jsGrid, jQuery));
| {
return sorter;
} | conditional_block |
jsgrid.field.js | (function(jsGrid, $, undefined) {
function | (config) {
$.extend(true, this, config);
this.sortingFunc = this._getSortingFunc();
}
Field.prototype = {
name: "",
title: null,
css: "",
align: "",
width: 100,
visible: true,
filtering: true,
inserting: true,
editing: tru... | Field | identifier_name |
jsgrid.field.js | (function(jsGrid, $, undefined) {
function Field(config) {
$.extend(true, this, config);
this.sortingFunc = this._getSortingFunc();
}
Field.prototype = {
name: "",
title: null,
css: "",
align: "",
width: 100,
visible: true,
filtering... |
jsGrid.Field = Field;
}(jsGrid, jQuery)); | throw Error("wrong sorter for the field \"" + this.name + "\"!");
}
}; | random_line_split |
jsgrid.field.js | (function(jsGrid, $, undefined) {
function Field(config) |
Field.prototype = {
name: "",
title: null,
css: "",
align: "",
width: 100,
visible: true,
filtering: true,
inserting: true,
editing: true,
sorting: true,
sorter: "string", // name of SortStrategy or function to compare elemen... | {
$.extend(true, this, config);
this.sortingFunc = this._getSortingFunc();
} | identifier_body |
topic_notification.py | #-*- coding: utf-8 -*-
from django.db import models
from django.utils.translation import ugettext_lazy as _
from django.core.urlresolvers import reverse
from django.conf import settings
from django.utils import timezone
from django.db import IntegrityError
from spirit.signals.comment import comment_posted
from spirit... | (self):
return self.comment.get_absolute_url()
@property
def text_action(self):
return ACTION_CHOICES[self.action][1]
@property
def is_mention(self):
return self.action == MENTION
@property
def is_comment(self):
return self.action == COMMENT
def __unicode_... | get_absolute_url | identifier_name |
topic_notification.py | #-*- coding: utf-8 -*-
from django.db import models
from django.utils.translation import ugettext_lazy as _
from django.core.urlresolvers import reverse
from django.conf import settings
from django.utils import timezone
from django.db import IntegrityError
from spirit.signals.comment import comment_posted
from spirit... |
TopicNotification.objects.filter(user=request.user, topic=topic)\
.update(is_read=True)
comment_posted.connect(comment_posted_handler, dispatch_uid=__name__)
topic_private_post_create.connect(topic_private_post_create_handler, dispatch_uid=__name__)
topic_private_access_pre_create.connect(topic_private_... | return | conditional_block |
topic_notification.py | #-*- coding: utf-8 -*-
from django.db import models
from django.utils.translation import ugettext_lazy as _
from django.core.urlresolvers import reverse
from django.conf import settings
from django.utils import timezone
from django.db import IntegrityError
from spirit.signals.comment import comment_posted
from spirit... |
@property
def is_comment(self):
return self.action == COMMENT
def __unicode__(self):
return "%s in %s" % (self.user, self.topic)
def notification_comment_posted_handler(sender, comment, **kwargs):
# Create Notification for poster
# if not exists create a dummy one with defaults
... |
@property
def is_mention(self):
return self.action == MENTION | random_line_split |
topic_notification.py | #-*- coding: utf-8 -*-
from django.db import models
from django.utils.translation import ugettext_lazy as _
from django.core.urlresolvers import reverse
from django.conf import settings
from django.utils import timezone
from django.db import IntegrityError
from spirit.signals.comment import comment_posted
from spirit... |
def mention_comment_posted_handler(sender, comment, mentions, **kwargs):
if not mentions:
return
for username, user in mentions.iteritems():
try:
TopicNotification.objects.create(user=user, topic=comment.topic,
comment=comment, action=... | try:
TopicNotification.objects.get_or_create(user=comment.user, topic=comment.topic,
defaults={'action': COMMENT,
'is_read': True,
'is_active': True... | identifier_body |
regular_expression_matching.py | class R:
def __init__(self, c):
self.c = c
self.is_star = False
def match(self, c):
return self.c == '.' or self.c == c
class Solution(object):
def isMatch(self, s, p):
"""
:type s: str
:type p: str
:rtype: bool
"""
rs = []
"... |
return dp[-1][-1]
| c = s[j - 1]
if r.is_star:
dp[i + 1][j] = dp[i][j]
if j and r.match(c):
dp[i + 1][j] |= dp[i + 1][j - 1]
else:
if j and r.match(c):
dp[i + 1][j] = dp[i][j - 1] | conditional_block |
regular_expression_matching.py | class R:
def __init__(self, c):
self.c = c
self.is_star = False
def match(self, c):
return self.c == '.' or self.c == c
class Solution(object):
def | (self, s, p):
"""
:type s: str
:type p: str
:rtype: bool
"""
rs = []
""":type: list[R]"""
for c in p:
if c == '*':
rs[-1].is_star = True
else:
rs.append(R(c))
lr = len(rs)
ls = len(s... | isMatch | identifier_name |
regular_expression_matching.py | class R:
def __init__(self, c):
self.c = c
self.is_star = False
def match(self, c):
return self.c == '.' or self.c == c
class Solution(object):
def isMatch(self, s, p):
"""
:type s: str
:type p: str
:rtype: bool
"""
rs = []
"... | for j in range(ls + 1):
c = s[j - 1]
if r.is_star:
dp[i + 1][j] = dp[i][j]
if j and r.match(c):
dp[i + 1][j] |= dp[i + 1][j - 1]
else:
if j and r.match(c):
... |
for i, r in enumerate(rs): | random_line_split |
regular_expression_matching.py | class R:
|
class Solution(object):
def isMatch(self, s, p):
"""
:type s: str
:type p: str
:rtype: bool
"""
rs = []
""":type: list[R]"""
for c in p:
if c == '*':
rs[-1].is_star = True
else:
rs.append(R(c)... | def __init__(self, c):
self.c = c
self.is_star = False
def match(self, c):
return self.c == '.' or self.c == c | identifier_body |
threshold.tsx | import React from 'react';
import Show from '../components/Show';
import Threshold from '../sandboxes/visx-threshold/Example';
import ThresholdSource from '!!raw-loader!../sandboxes/visx-threshold/Example';
import packageJson from '../sandboxes/visx-threshold/package.json';
function Description({ width }: { widt... | component={Threshold}
title="Threshold"
description={Description}
codeSandboxDirectoryName="visx-threshold"
packageJson={packageJson}
>
{ThresholdSource}
</Show>
);
export default ThresholdPage; | const ThresholdPage = () => (
<Show
| random_line_split |
download-exercise-images.py | # -*- coding: utf-8 *-*
# This file is part of wger Workout Manager.
#
# wger Workout Manager is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any ... | image_name = os.path.basename(result['original'])
self.stdout.write(' Fetching image {0} - {1}'.format(image_id, image_name))
try:
image = ExerciseImage.objects.get(pk=image_id)
self.stdout.write(' --> Ima... |
for image_json in images['results']:
image_id = image_json['id']
result = requests.get(thumbnail_api.format(remote_url, image_id)).json()
| random_line_split |
download-exercise-images.py | # -*- coding: utf-8 *-*
# This file is part of wger Workout Manager.
#
# wger Workout Manager is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any ... | (BaseCommand):
'''
Download exercise images from wger.de and updates the local database
The script assumes that the local IDs correspond to the remote ones, which
is the case if the user installed the exercises from the JSON fixtures.
Otherwise, the exercise is simply skipped
'''
option_li... | Command | identifier_name |
download-exercise-images.py | # -*- coding: utf-8 *-*
# This file is part of wger Workout Manager.
#
# wger Workout Manager is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any ... | for image_json in images['results']:
image_id = image_json['id']
result = requests.get(thumbnail_api.format(remote_url, image_id)).json()
image_name = os.path.basename(result['original'])
self.stdout.write(' Fetching ima... | exercise_name = exercise_json['name'].encode('utf-8')
exercise_uuid = exercise_json['uuid']
exercise_id = exercise_json['id']
self.stdout.write('')
self.stdout.write(u"*** Processing {0} (ID: {1}, UUID: {2})".format(exercise_name,
... | conditional_block |
download-exercise-images.py | # -*- coding: utf-8 *-*
# This file is part of wger Workout Manager.
#
# wger Workout Manager is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any ... |
self.stdout.write('')
self.stdout.write(u"*** Processing {0} (ID: {1}, UUID: {2})".format(exercise_name,
exercise_id,
exercise_uuid))
... | if not settings.MEDIA_ROOT:
raise ImproperlyConfigured('Please set MEDIA_ROOT in your settings file')
remote_url = options['remote_url']
try:
val = URLValidator()
val(remote_url)
except ValidationError:
raise CommandError('Please enter a valid URL... | identifier_body |
vkvalidation.js | /**
* @package Extly.Components
* @subpackage com_autotweet - AutoTweet posts content to social channels
* (Twitter, Facebook, LinkedIn, etc).
*
* @author Prieco S.A.
* @copyright Copyright (C) 2007 - 2014 Prieco, S.A. All rights reserved.
* @license http://www.gnu.org/licenses/gpl-3.0.html GNU/GPL
... | {
params = hash.split('&');
_.each(params, function(param) {
var kv = param.split('='), k, v;
if (_.size(kv) == 2) {
k = kv[0];
v = kv[1];
jQuery('#raw_' + k).val(v);
access_token[k] = v;
}
}
);
jQuery('#access_token').val(JSON.stringify(access_token));
r... | if (!_.isEmpty(hash)) | random_line_split |
vkvalidation.js | /**
* @package Extly.Components
* @subpackage com_autotweet - AutoTweet posts content to social channels
* (Twitter, Facebook, LinkedIn, etc).
*
* @author Prieco S.A.
* @copyright Copyright (C) 2007 - 2014 Prieco, S.A. All rights reserved.
* @license http://www.gnu.org/licenses/gpl-3.0.html GNU/GPL
... |
access_token = view.$('#access_token').val();
view.$(".loaderspinner").addClass('loading');
this.collection.create(this.collection.model, {
attrs : {
channel_id : channel_id,
access_token : access_token,
token : token
},
wait : true,
dataType: 'text',
error : function(model, fa... | {
validationHelper.showError(view, 'Invalid Token Url');
} | conditional_block |
mod.rs | //! Implementation of mio for Windows using IOCP
//!
//! This module uses I/O Completion Ports (IOCP) on Windows to implement mio's
//! Unix epoll-like interface. Unfortunately these two I/O models are
//! fundamentally incompatible:
//!
//! * IOCP is a completion-based model where work is submitted to the kernel and
/... |
}
| {
Err(io::Error::last_os_error())
} | conditional_block |
mod.rs | //! Implementation of mio for Windows using IOCP
//!
//! This module uses I/O Completion Ports (IOCP) on Windows to implement mio's
//! Unix epoll-like interface. Unfortunately these two I/O models are
//! fundamentally incompatible:
//!
//! * IOCP is a completion-based model where work is submitted to the kernel and
/... | (handle: winapi::HANDLE) -> io::Result<()> {
// TODO: move those to winapi
const FILE_SKIP_COMPLETION_PORT_ON_SUCCESS: winapi::UCHAR = 1;
const FILE_SKIP_SET_EVENT_ON_HANDLE: winapi::UCHAR = 2;
let flags = FILE_SKIP_COMPLETION_PORT_ON_SUCCESS | FILE_SKIP_SET_EVENT_ON_HANDLE;
let r = kernel32::SetF... | no_notify_on_instant_completion | identifier_name |
mod.rs | //! Implementation of mio for Windows using IOCP
//!
//! This module uses I/O Completion Ports (IOCP) on Windows to implement mio's
//! Unix epoll-like interface. Unfortunately these two I/O models are
//! fundamentally incompatible:
//!
//! * IOCP is a completion-based model where work is submitted to the kernel and
/... | io::Error::new(io::ErrorKind::WouldBlock, "operation would block")
}
unsafe fn cancel(socket: &AsRawSocket,
overlapped: &Overlapped) -> io::Result<()> {
let handle = socket.as_raw_socket() as winapi::HANDLE;
let ret = kernel32::CancelIoEx(handle, overlapped.as_mut_ptr());
if ret == 0 {... | fn wouldblock() -> io::Error { | random_line_split |
mod.rs | //! Implementation of mio for Windows using IOCP
//!
//! This module uses I/O Completion Ports (IOCP) on Windows to implement mio's
//! Unix epoll-like interface. Unfortunately these two I/O models are
//! fundamentally incompatible:
//!
//! * IOCP is a completion-based model where work is submitted to the kernel and
/... | {
// TODO: move those to winapi
const FILE_SKIP_COMPLETION_PORT_ON_SUCCESS: winapi::UCHAR = 1;
const FILE_SKIP_SET_EVENT_ON_HANDLE: winapi::UCHAR = 2;
let flags = FILE_SKIP_COMPLETION_PORT_ON_SUCCESS | FILE_SKIP_SET_EVENT_ON_HANDLE;
let r = kernel32::SetFileCompletionNotificationModes(handle, flag... | identifier_body | |
args.rs | const str as *const Arg) }
}
}
impl ops::Deref for Arg {
type Target = str;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl fmt::Display for Arg {
/// Quotes the argument such that it is safe to pass to the shell.
#[cfg(windows)]
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fm... | random_line_split | ||
args.rs | AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
use std::ffi::OsStr;
use std::fmt::{self, Write as FmtWrite};
use std::io::{self, Write};
use std::iter;
use std::ops;
use serde::{Deserialize, Serialize};
use tempfile... |
/// Generates a temporary response file for the list of arguments.
pub fn response_file(&self) -> io::Result<TempPath> {
let tempfile = NamedTempFile::new()?;
{
let mut writer = io::BufWriter::new(&tempfile);
// Write UTF-8 BOM. Some tools require this to properly dec... | {
#[cfg(windows)]
{
self.byte_count() > 32768
}
#[cfg(unix)]
{
self.byte_count() > 0x20000
}
} | identifier_body |
args.rs | AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
use std::ffi::OsStr;
use std::fmt::{self, Write as FmtWrite};
use std::io::{self, Write};
use std::iter;
use std::ops;
use serde::{Deserialize, Serialize};
use tempfile... |
Ok(())
}
/// Quotes the argument such that it is safe to pass to the shell.
#[cfg(unix)]
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let quote = self.0.chars().any(|c| " \n\t#<>'&|".contains(c))
|| self.0.is_empty();
if quote {
f.write_c... | {
// Escape any trailing backslashes.
for _ in 0..backslashes {
f.write_char('\\')?;
}
f.write_char('"')?;
} | conditional_block |
args.rs | IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
use std::ffi::OsStr;
use std::fmt::{self, Write as FmtWrite};
use std::io::{self, Write};
use std::iter;
use std::ops;
use serde::{Deserialize, Serialize};
use tempf... | (s: &'a str) -> ArgBuf {
ArgBuf::from(s.to_string())
}
}
impl ops::Deref for ArgBuf {
type Target = Arg;
fn deref(&self) -> &Self::Target {
&Arg::new(&self.0)
}
}
impl AsRef<Arg> for ArgBuf {
fn as_ref(&self) -> &Arg {
self
}
}
impl AsRef<OsStr> for ArgBuf {
fn as... | from | identifier_name |
chrome-extension.js | Path = function (srcDirectory) {
let manifest
let manifestContent
try {
manifestContent = fs.readFileSync(path.join(srcDirectory, 'manifest.json'))
} catch (readError) {
console.warn(`Reading ${path.join(srcDirectory, 'manifest.json')} failed.`)
console.warn(readError.stack || readError)
throw ... | const extensionInfoArray = manifests.map(manifestToExtensionInfo)
win.devToolsWebContents.executeJavaScript(`DevToolsAPI.addExtensions(${JSON.stringify(extensionInfoArray)})`)
}
app.on('web-contents-created', function (event, webContents) {
if (!isWindowOrWebView(webContents)) return
hookWebContentsEvents(web... |
manifests.forEach(loadExtension)
| random_line_split |
chrome-extension.js | Path = function (srcDirectory) {
let manifest
let manifestContent
try {
manifestContent = fs.readFileSync(path.join(srcDirectory, 'manifest.json'))
} catch (readError) {
console.warn(`Reading ${path.join(srcDirectory, 'manifest.json')} failed.`)
console.warn(readError.stack || readError)
throw ... |
let code, url
if (details.file) {
const manifest = manifestMap[extensionId]
code = String(fs.readFileSync(path.join(manifest.srcDirectory, details.file)))
url = `chrome-extension://${extensionId}${details.file}`
} else {
code = details.code
url = `chrome-extension://${extensionId}/${String(M... | {
console.error(`Sending message to unknown tab ${tabId}`)
return
} | conditional_block |
models.py | (self, lang, attach_excel=False):
"""
Get the report's HTML content as rendered by the static view format.
"""
try:
if self.report is None:
return _("The report used to create this scheduled report is no"
" longer available on CommCar... | include_errors = BooleanProperty(default=False) | random_line_split | |
models.py | (self, domain, username, uuid):
if username == HQUserType.human_readable[HQUserType.DEMO_USER]:
filter_flag = HQUserType.DEMO_USER
elif username == HQUserType.human_readable[HQUserType.ADMIN]:
filter_flag = HQUserType.ADMIN
else:
filter_flag = HQUserType.UNKNO... | __init__ | identifier_name | |
models.py | handle inclusiveness
else:
end_date = today
if date_range == 'last7':
days = 7
elif date_range == 'last30':
days = 30
elif date_range == 'lastn':
days = self.days
else:
raise Exception("... | if self.owner.is_web_user():
emails.append(self.owner.username)
else:
email = self.owner.get_email()
try:
validate_email(email)
emails.append(email)
except Exception:
pass | conditional_block | |
models.py |
class HQUserToggle(HQToggle):
def __init__(self, type, show):
name = _(HQUserType.human_readable[type])
super(HQUserToggle, self).__init__(type, show, name)
class TempCommCareUser(CommCareUser):
filter_flag = IntegerProperty()
def __init__(self, domain, username, uuid):
if use... | type = None
show = False
name = None
def __init__(self, type, show, name):
self.type = type
self.name = name
self.show = show
def __repr__(self):
return "%(klass)s[%(type)s:%(show)s:%(name)s]" % dict(
klass = self.__class__.__name__,
type=self.ty... | identifier_body | |
vrframedata.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
use crate::dom::bindings::codegen::Bindings::VRFrameDataBinding;
use crate::dom::bindings::codegen::Bindings::VRF... |
#[dom_struct]
pub struct VRFrameData {
reflector_: Reflector,
left_proj: Heap<*mut JSObject>,
left_view: Heap<*mut JSObject>,
right_proj: Heap<*mut JSObject>,
right_view: Heap<*mut JSObject>,
pose: Dom<VRPose>,
timestamp: Cell<f64>,
first_timestamp: Cell<f64>,
}
impl VRFrameData {
... | random_line_split | |
vrframedata.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
use crate::dom::bindings::codegen::Bindings::VRFrameDataBinding;
use crate::dom::bindings::codegen::Bindings::VRF... |
}
}
impl VRFrameDataMethods for VRFrameData {
// https://w3c.github.io/webvr/#dom-vrframedata-timestamp
fn Timestamp(&self) -> Finite<f64> {
Finite::wrap(self.timestamp.get() - self.first_timestamp.get())
}
#[allow(unsafe_code)]
// https://w3c.github.io/webvr/#dom-vrframedata-leftproj... | {
self.first_timestamp.set(data.timestamp);
} | conditional_block |
vrframedata.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
use crate::dom::bindings::codegen::Bindings::VRFrameDataBinding;
use crate::dom::bindings::codegen::Bindings::VRF... | {
reflector_: Reflector,
left_proj: Heap<*mut JSObject>,
left_view: Heap<*mut JSObject>,
right_proj: Heap<*mut JSObject>,
right_view: Heap<*mut JSObject>,
pose: Dom<VRPose>,
timestamp: Cell<f64>,
first_timestamp: Cell<f64>,
}
impl VRFrameData {
fn new_inherited(pose: &VRPose) -> VR... | VRFrameData | identifier_name |
vrframedata.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
use crate::dom::bindings::codegen::Bindings::VRFrameDataBinding;
use crate::dom::bindings::codegen::Bindings::VRF... |
#[allow(unsafe_code)]
// https://w3c.github.io/webvr/#dom-vrframedata-leftprojectionmatrix
unsafe fn LeftProjectionMatrix(&self, _cx: *mut JSContext) -> NonNull<JSObject> {
NonNull::new_unchecked(self.left_proj.get())
}
#[allow(unsafe_code)]
// https://w3c.github.io/webvr/#dom-vrframe... | {
Finite::wrap(self.timestamp.get() - self.first_timestamp.get())
} | identifier_body |
wincon.rs | = *mut KEY_EVENT_RECORD;
pub const RIGHT_ALT_PRESSED: ::DWORD = 0x0001;
pub const LEFT_ALT_PRESSED: ::DWORD = 0x0002;
pub const RIGHT_CTRL_PRESSED: ::DWORD = 0x0004;
pub const LEFT_CTRL_PRESSED: ::DWORD = 0x0008;
pub const SHIFT_PRESSED: ::DWORD = 0x0010;
pub const NUMLOCK_ON: ::DWORD = 0x0020;
pub const SCROLLLOCK_ON... | pub const ENABLE_EXTENDED_FLAGS: ::DWORD = 0x0080;
pub const ENABLE_AUTO_POSITION: ::DWORD = 0x0100;
pub const ENABLE_PROCESSED_OUTPUT: ::DWORD = 0x0001;
pub const ENABLE_WRAP_AT_EOL_OUTPUT: ::DWORD = 0x0002; | random_line_split | |
predict.rs | #[macro_use]
extern crate log;
extern crate fern;
extern crate time;
extern crate gpredict;
use gpredict::{Predict, Location, Tle};
use std::thread;
fn conf_logger() |
fn main() {
// setup fern logger
conf_logger();
// start processing
info!("predict example started");
let tle: Tle = Tle {
name: "GRIFEX".to_string(),
line1: "1 40379U 15003D 15243.42702278 .00003367 00000-0 17130-3 0 9993".to_string(),
line2: "2 40379 99.1124 290.... | {
let logger_config = fern::DispatchConfig {
format: Box::new(|msg: &str, level: &log::LogLevel, _location: &log::LogLocation| {
let t = time::now();
let ms = t.tm_nsec/1000_000;
format!("{}.{:3} [{}] {}", t.strftime("%Y-%m-%dT%H:%M:%S").unwrap(), ms, level, msg)
... | identifier_body |
predict.rs | #[macro_use]
extern crate log;
extern crate fern;
extern crate time;
extern crate gpredict;
use gpredict::{Predict, Location, Tle};
use std::thread;
fn conf_logger() {
let logger_config = fern::DispatchConfig {
format: Box::new(|msg: &str, level: &log::LogLevel, _location: &log::LogLocation| {
... |
}
fn main() {
// setup fern logger
conf_logger();
// start processing
info!("predict example started");
let tle: Tle = Tle {
name: "GRIFEX".to_string(),
line1: "1 40379U 15003D 15243.42702278 .00003367 00000-0 17130-3 0 9993".to_string(),
line2: "2 40379 99.1124 29... | {
panic!("Failed to initialize global logger: {}", e);
} | conditional_block |
predict.rs | #[macro_use]
extern crate log;
extern crate fern;
extern crate time;
extern crate gpredict;
use gpredict::{Predict, Location, Tle};
use std::thread;
fn conf_logger() {
let logger_config = fern::DispatchConfig {
format: Box::new(|msg: &str, level: &log::LogLevel, _location: &log::LogLocation| {
... | level: log::LogLevelFilter::Trace,
};
if let Err(e) = fern::init_global_logger(logger_config, log::LogLevelFilter::Trace) {
panic!("Failed to initialize global logger: {}", e);
}
}
fn main() {
// setup fern logger
conf_logger();
// start processing
info!("predict example s... | let ms = t.tm_nsec/1000_000;
format!("{}.{:3} [{}] {}", t.strftime("%Y-%m-%dT%H:%M:%S").unwrap(), ms, level, msg)
}),
output: vec![fern::OutputConfig::stderr()], | random_line_split |
predict.rs | #[macro_use]
extern crate log;
extern crate fern;
extern crate time;
extern crate gpredict;
use gpredict::{Predict, Location, Tle};
use std::thread;
fn conf_logger() {
let logger_config = fern::DispatchConfig {
format: Box::new(|msg: &str, level: &log::LogLevel, _location: &log::LogLocation| {
... | () {
// setup fern logger
conf_logger();
// start processing
info!("predict example started");
let tle: Tle = Tle {
name: "GRIFEX".to_string(),
line1: "1 40379U 15003D 15243.42702278 .00003367 00000-0 17130-3 0 9993".to_string(),
line2: "2 40379 99.1124 290.6779 0157... | main | identifier_name |
directives.d.ts | import { Type } from 'angular2/src/core/facade/lang';
export { NgControlName } from './directives/ng_control_name';
export { NgFormControl } from './directives/ng_form_control';
export { NgModel } from './directives/ng_model';
export { NgControl } from './directives/ng_control';
export { NgControlGroup } from './d... | * ```typescript
* @Component({
* selector: 'my-app',
* directives: [FORM_DIRECTIVES]
* })
* class MyApp {}
* ```
*/
export declare const FORM_DIRECTIVES: Type[]; | *
| random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.