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 |
|---|---|---|---|---|
messages.js | var Message = require('../models/message');
exports.create = function(req, res) {
new Message({
senderID: req.body.senderID,
senderAlias: req.body.senderAlias,
acceptorID: req.body.acceptorID,
acceptorAlias: req.body.acceptorAlias,
subject: req.body.subject,
content: req.body.content
}).sav... | })
}
if(delFlag){
doc.remove(function(err, doc) {
err ? res.send(500, err) : res.send('');
});
}
});
}; | random_line_split | |
messages.js | var Message = require('../models/message');
exports.create = function(req, res) {
new Message({
senderID: req.body.senderID,
senderAlias: req.body.senderAlias,
acceptorID: req.body.acceptorID,
acceptorAlias: req.body.acceptorAlias,
subject: req.body.subject,
content: req.body.content
}).sav... |
}
if(doc.acceptorID == req.user._id){
if(doc.delFromSender == 'true'){
delFlag = true;
}else{
doc.delFromAcceptor = true;
saveFlag = true;
}
}
if(saveFlag){
doc.save(function(err, doc){
... | {
doc.delFromSender = true;
saveFlag = true;
} | conditional_block |
FormEditUserController.js | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you ... | var modalInstance = $uibModal.open({
templateUrl: 'common/modules/dialog/delete/dialog.delete.tpl.html',
controller: 'DialogDeleteController',
size: 'md',
resolve: {
params: function () {
return params;
}
... | key: user.username
}; | random_line_split |
Neuroevolution.js | }
}
// Overriding default options with the pass in options
self.set(options);
/*NEURON**********************************************************************/
/**
* Artificial Neuron class
*
* @constructor
*/
var Neuron = function(){
this.value = 0;
this.weights = [];
}
/**
* Initialize number... |
}
// Insert genome into correct position.
this.genomes.splice(i, 0, genome);
}
/**
* Breed to genomes to produce offspring(s).
*
* @param {g1} Genome 1.
* @param {g2} Genome 2.
* @param {nbChilds} Number of offspring (children).
*/
Generation.prototype.breed = function(g1, g2, nbChilds){
var ... | {
if(genome.score < this.genomes[i].score){
break;
}
} | conditional_block |
Neuroevolution.js | }
}
// Overriding default options with the pass in options
self.set(options);
/*NEURON**********************************************************************/
/**
* Artificial Neuron class
*
* @constructor
*/
var Neuron = function(){
this.value = 0;
this.weights = [];
}
/**
* Initialize number... | this.layers[0].neurons[i].value = inputs[i];
}
}
var prevLayer = this.layers[0]; // Previous layer is input layer.
for(var i = 1; i < this.layers.length; i++){
for(var j in this.layers[i].neurons){
// For each Neuron in each layer.
var sum = 0;
for(var k in prevLayer.neurons){
// Eve... | if(this.layers[0] && this.layers[0].neurons[i]){ | random_line_split |
use-selected-plan.ts | import { Site } from '@automattic/data-stores';
import { useLocale } from '@automattic/i18n-utils';
import { useSelect } from '@wordpress/data';
import { usePlanRouteParam } from '../path';
import { STORE_KEY as ONBOARD_STORE } from '../stores/onboard';
import { PLANS_STORE } from '../stores/plans';
import { WPCOM_FEAT... | select( PLANS_STORE ).getPlanByPath( planPath, locale ),
select( ONBOARD_STORE ).getSelectedFeatures(),
] );
// don't return Free plan if any feature is currently selected
if ( isPlanFree( planFromPath?.periodAgnosticSlug ) && selectedFeatures.length ) {
return;
}
return planFromPath;
}
export function us... | random_line_split | |
use-selected-plan.ts | import { Site } from '@automattic/data-stores';
import { useLocale } from '@automattic/i18n-utils';
import { useSelect } from '@wordpress/data';
import { usePlanRouteParam } from '../path';
import { STORE_KEY as ONBOARD_STORE } from '../stores/onboard';
import { PLANS_STORE } from '../stores/plans';
import { WPCOM_FEAT... | (): Plan | undefined {
const locale = useLocale();
// Pre-load the plans details to ensure the plans are fetched early from the API endpoint.
useSelect( ( select ) => select( PLANS_STORE ).getSupportedPlans( locale ) );
const selectedFeatures = useSelect( ( select ) => select( ONBOARD_STORE ).getSelectedFeatures()... | useSelectedPlan | identifier_name |
use-selected-plan.ts | import { Site } from '@automattic/data-stores';
import { useLocale } from '@automattic/i18n-utils';
import { useSelect } from '@wordpress/data';
import { usePlanRouteParam } from '../path';
import { STORE_KEY as ONBOARD_STORE } from '../stores/onboard';
import { PLANS_STORE } from '../stores/plans';
import { WPCOM_FEAT... |
return planFromPath;
}
export function useSelectedPlan(): Plan | undefined {
const locale = useLocale();
// Pre-load the plans details to ensure the plans are fetched early from the API endpoint.
useSelect( ( select ) => select( PLANS_STORE ).getSupportedPlans( locale ) );
const selectedFeatures = useSelect( (... | {
return;
} | conditional_block |
use-selected-plan.ts | import { Site } from '@automattic/data-stores';
import { useLocale } from '@automattic/i18n-utils';
import { useSelect } from '@wordpress/data';
import { usePlanRouteParam } from '../path';
import { STORE_KEY as ONBOARD_STORE } from '../stores/onboard';
import { PLANS_STORE } from '../stores/plans';
import { WPCOM_FEAT... | {
// The ecommerce plan follows another flow, so we shouldn't interrupt
// it by trying to redirect to the editor.
const currentSlug = useSelectedPlan()?.periodAgnosticSlug;
return ! useSelect( ( select ) => select( PLANS_STORE ).isPlanEcommerce( currentSlug ) );
} | identifier_body | |
package.py | ##############################################################################
# Copyright (c) 2013-2017, Lawrence Livermore National Security, LLC.
# Produced at the Lawrence Livermore National Laboratory.
#
# This file is part of Spack.
# Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved.
# LLNL-CODE-64... | (RPackage):
"""Data analysis, linear models and differential expression
for microarray data."""
homepage = "https://www.bioconductor.org/packages/limma/"
url = "https://www.bioconductor.org/packages/release/bioc/src/contrib/limma_3.32.6.tar.gz"
list_url = homepage
version('3.32.6', 'df5dc2... | RLimma | identifier_name |
package.py | ##############################################################################
# Copyright (c) 2013-2017, Lawrence Livermore National Security, LLC.
# Produced at the Lawrence Livermore National Laboratory.
#
# This file is part of Spack.
# Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved.
# LLNL-CODE-64... | """Data analysis, linear models and differential expression
for microarray data."""
homepage = "https://www.bioconductor.org/packages/limma/"
url = "https://www.bioconductor.org/packages/release/bioc/src/contrib/limma_3.32.6.tar.gz"
list_url = homepage
version('3.32.6', 'df5dc2b85189a24e939efa... | identifier_body | |
package.py | ##############################################################################
# Copyright (c) 2013-2017, Lawrence Livermore National Security, LLC.
# Produced at the Lawrence Livermore National Laboratory.
#
# This file is part of Spack.
# Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved. | # Please also see the NOTICE and LICENSE files for our notice and the LGPL.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License (as
# published by the Free Software Foundation) version 2.1, February 1999.
#
# This program is distributed ... | # LLNL-CODE-647188
#
# For details, see https://github.com/llnl/spack | random_line_split |
valueEvent.ts | // abstraction layer for pitch-bend and controller events
import { controllerMidiEvent, pitchBendMidiEvent } from "../midi/MidiEvent"
import { isControllerEventWithType, isPitchBendEvent } from "../track"
export type ValueEventType =
| { type: "pitchBend" }
| { type: "controller"; controllerType: number }
export... |
export const isValueEvent = (t: ValueEventType) => {
switch (t.type) {
case "pitchBend":
return isPitchBendEvent
case "controller":
return isControllerEventWithType(t.controllerType)
}
} | random_line_split | |
decompose.rs | // Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... |
}
impl<I: Iterator<Item=char>> Iterator for Decompositions<I> {
type Item = char;
#[inline]
fn next(&mut self) -> Option<char> {
while self.ready == 0 && !self.done {
match (self.iter.next(), &self.kind) {
(Some(ch), &DecompositionType::Canonical) => {
... | {
if self.ready == 0 {
None
} else {
self.ready -= 1;
Some(self.buffer.remove(0).1)
}
} | identifier_body |
decompose.rs | // Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... | ,
(None, _) => {
self.sort_pending();
self.done = true;
},
}
}
self.pop_front()
}
fn size_hint(&self) -> (usize, Option<usize>) {
let (lower, _) = self.iter.size_hint();
(lower, None)
}
}
im... | {
super::char::decompose_compatible(ch, |d| self.push_back(d));
} | conditional_block |
decompose.rs | // Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... |
#[inline]
fn next(&mut self) -> Option<char> {
while self.ready == 0 && !self.done {
match (self.iter.next(), &self.kind) {
(Some(ch), &DecompositionType::Canonical) => {
super::char::decompose_canonical(ch, |d| self.push_back(d));
},
... | type Item = char; | random_line_split |
decompose.rs | // Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... | (&self, f: &mut fmt::Formatter) -> fmt::Result {
for c in self.clone() {
f.write_char(c)?;
}
Ok(())
}
}
| fmt | identifier_name |
scrobctl.rs | #![deny(
missing_copy_implementations,
missing_debug_implementations,
// missing_docs, temp disable
clippy::all,
clippy::pedantic,
clippy::cargo,
trivial_casts,
trivial_numeric_casts,
unsafe_code,
unused_import_braces,
unused_qualifications,
unused_extern_crates,
varia... | () {
let _args = get_arguments();
unimplemented!();
}
| main | identifier_name |
scrobctl.rs | #![deny(
missing_copy_implementations,
missing_debug_implementations,
// missing_docs, temp disable
clippy::all,
clippy::pedantic, | unused_qualifications,
unused_extern_crates,
variant_size_differences
)]
use clap::{App, Arg, ArgMatches};
fn get_arguments() -> ArgMatches<'static> {
App::new("scrobc")
.version(env!("CARGO_PKG_VERSION"))
.author("Dom Rodriguez <shymega@shymega.org.uk>")
.about("Client for con... | clippy::cargo,
trivial_casts,
trivial_numeric_casts,
unsafe_code,
unused_import_braces, | random_line_split |
scrobctl.rs | #![deny(
missing_copy_implementations,
missing_debug_implementations,
// missing_docs, temp disable
clippy::all,
clippy::pedantic,
clippy::cargo,
trivial_casts,
trivial_numeric_casts,
unsafe_code,
unused_import_braces,
unused_qualifications,
unused_extern_crates,
varia... | {
let _args = get_arguments();
unimplemented!();
} | identifier_body | |
a3.py | def p5a():
|
def getdd123(xs,fxs,n):
#derivatives
l1stdd = []
l2nddd = []
l3rddd = []
for i in range(0,n):
l1stdd.append((fxs[i+1]-fxs[i])/(xs[i+1]-xs[i]))
for i in range(0,n-1):
l2nddd.append((l1stdd[i+1]-l1stdd[i])/(xs[i+2]-xs[i]))
for i in range(0,n-2):
l3rddd.append((l2nddd[i+1]-l2nddd[i])/(xs[i+3]-... | xs = [-.75, -0.5,-0.25,0]
fxs = [-.0718125, -.02475, .3349375, 1.101]
getdd123(xs,fxs,3) | identifier_body |
a3.py | def p5a():
xs = [-.75, -0.5,-0.25,0]
fxs = [-.0718125, -.02475, .3349375, 1.101]
getdd123(xs,fxs,3)
def getdd123(xs,fxs,n):
#derivatives
l1stdd = []
l2nddd = []
l3rddd = []
for i in range(0,n):
l1stdd.append((fxs[i+1]-fxs[i])/(xs[i+1]-xs[i]))
for i in range(0,n-1):
l2nddd.append((l1stdd[i+1]... | l3rddd.append((l2nddd[i+1]-l2nddd[i])/(xs[i+3]-xs[i]))
#print [l1stdd,l2nddd,l3rddd]
return [l1stdd,l2nddd,l3rddd]
def p7a():
xs = [-.1, 0,.2,.3]
fxs = [5.3, 2, 3.19, 1]
getdd123(xs,fxs,3)
def p14():
xs = [0, .25,.5,.75]
fxs = [1, 2, 3.5, 6]
getdd123(xs,fxs,3) | random_line_split | |
a3.py | def p5a():
xs = [-.75, -0.5,-0.25,0]
fxs = [-.0718125, -.02475, .3349375, 1.101]
getdd123(xs,fxs,3)
def | (xs,fxs,n):
#derivatives
l1stdd = []
l2nddd = []
l3rddd = []
for i in range(0,n):
l1stdd.append((fxs[i+1]-fxs[i])/(xs[i+1]-xs[i]))
for i in range(0,n-1):
l2nddd.append((l1stdd[i+1]-l1stdd[i])/(xs[i+2]-xs[i]))
for i in range(0,n-2):
l3rddd.append((l2nddd[i+1]-l2nddd[i])/(xs[i+3]-xs[i]))
#prin... | getdd123 | identifier_name |
a3.py | def p5a():
xs = [-.75, -0.5,-0.25,0]
fxs = [-.0718125, -.02475, .3349375, 1.101]
getdd123(xs,fxs,3)
def getdd123(xs,fxs,n):
#derivatives
l1stdd = []
l2nddd = []
l3rddd = []
for i in range(0,n):
l1stdd.append((fxs[i+1]-fxs[i])/(xs[i+1]-xs[i]))
for i in range(0,n-1):
l2nddd.append((l1stdd[i+1]... |
#print [l1stdd,l2nddd,l3rddd]
return [l1stdd,l2nddd,l3rddd]
def p7a():
xs = [-.1, 0,.2,.3]
fxs = [5.3, 2, 3.19, 1]
getdd123(xs,fxs,3)
def p14():
xs = [0, .25,.5,.75]
fxs = [1, 2, 3.5, 6]
getdd123(xs,fxs,3)
| l3rddd.append((l2nddd[i+1]-l2nddd[i])/(xs[i+3]-xs[i])) | conditional_block |
handler.ts |
// (C) Copyright 2015 Moodle Pty 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 agre... | (private questionProvider: CoreQuestionProvider, private questionHelper: CoreQuestionHelperProvider) { }
/**
* Return the name of the behaviour to use for the question.
* If the question should use the default behaviour you shouldn't implement this function.
*
* @param question The question.
... | constructor | identifier_name |
handler.ts |
// (C) Copyright 2015 Moodle Pty 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 agre... |
}
return 0;
}
/**
* Check if two responses are the same.
*
* @param question Question.
* @param prevAnswers Object with the previous question answers.
* @param newAnswers Object with the new question answers.
* @return Whether they're the same.
*/
isSame... | {
return 1;
} | conditional_block |
handler.ts | // (C) Copyright 2015 Moodle Pty 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
// | //
// 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 ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the Licen... | // http://www.apache.org/licenses/LICENSE-2.0 | random_line_split |
source.js | 'use strict';
module.exports = Source;
const inherits = require('util').inherits;
const Stream = require('../stream');
const Chunk = require('../chunk');
const Compose = require('../through/compose');
const Break = require('../through/break');
const Filter = require('../through/filter');
const Map = require('../throu... | (){
Stream.call(this);
this.async = false;
}
Source.prototype.iterator = function iterator() {
return new this.constructor.Iterator(this);
};
Source.prototype.pipe = function pipe(feed) {
return feed.feed([this]);
};
Source.prototype.break = function breake(fn, async){
return this.pipe(new Break(fn, async));
... | Source | identifier_name |
source.js | 'use strict';
module.exports = Source;
const inherits = require('util').inherits;
const Stream = require('../stream');
const Chunk = require('../chunk');
const Compose = require('../through/compose');
const Break = require('../through/break');
const Filter = require('../through/filter');
const Map = require('../throu... |
Source.prototype.iterator = function iterator() {
return new this.constructor.Iterator(this);
};
Source.prototype.pipe = function pipe(feed) {
return feed.feed([this]);
};
Source.prototype.break = function breake(fn, async){
return this.pipe(new Break(fn, async));
};
Source.prototype.filter = function filter(fn,... | {
Stream.call(this);
this.async = false;
} | identifier_body |
source.js | 'use strict';
module.exports = Source;
const inherits = require('util').inherits;
const Stream = require('../stream');
const Chunk = require('../chunk');
const Compose = require('../through/compose');
const Break = require('../through/break');
const Filter = require('../through/filter');
const Map = require('../throu... | };
Source.prototype.filter = function filter(fn, async){
return this.pipe(new Filter(fn, async));
};
Source.prototype.map = function map(fn, async){
return this.pipe(new Map(fn, async));
};
Source.prototype.take = function take(max){
return this.pipe(new Take(max));
};
Source.prototype.each = function each(fn){
... | random_line_split | |
build-locale.ts | import { getGlobalVariable } from '../../utils/env';
import { expectFileToMatch, rimraf } from '../../utils/fs';
import { ng } from '../../utils/process';
export default async function () {
const argv = getGlobalVariable('argv');
const veEnabled = argv['ve'];
if (!veEnabled) |
// These tests should be moved to the default when we use ng5 in new projects.
return Promise.resolve()
// tests for register_locale_data transformer
.then(() => ng('build', '--aot', '--i18n-locale=fr'))
.then(() => expectFileToMatch('dist/test-project/main-es5.js', /registerLocaleData/))
.then(()... | {
return;
} | conditional_block |
build-locale.ts | import { getGlobalVariable } from '../../utils/env';
import { expectFileToMatch, rimraf } from '../../utils/fs';
import { ng } from '../../utils/process';
export default async function () {
const argv = getGlobalVariable('argv');
const veEnabled = argv['ve'];
if (!veEnabled) {
return;
}
// These tests s... | .then(() => expectFileToMatch('dist/test-project/main-es5.js', /registerLocaleData/))
.then(() => expectFileToMatch('dist/test-project/main-es5.js', /angular_common_locales_fr/))
.then(() => expectFileToMatch('dist/test-project/main-es2015.js', /registerLocaleData/))
.then(() => expectFileToMatch('dist/... | random_line_split | |
user.js |
var users = [{
id: 1,
active: 1,
"name": "Вася",
"phone": "1114124"
}, {
id: 2,
active: 0,
"name": "Иван",
"phone": "1114123"
}
];
var next_id = 3;
function getUserById(id) {
var key = +id;
var l = users.length;
for (var i=0; i<l; i++) {
if(users[i].id === key) {
return users[i];
}
}
}
f... | end(user);
};
exports.del = function(req, res){
delUserById(req.params.id);
res.send({});
};
exports.create = function(req, res){
var update = req.body;
var user = {
id: next_id,
active:update.active,
name: update.name,
phone: update.phone
};
next_id++;
users.push(user);
res.send(user);
};
| .active = update.active;
user.name = update.name;
user.phone = update.phone;
}
res.s | conditional_block |
user.js | var users = [{
id: 1,
active: 1,
"name": "Вася",
"phone": "1114124"
}, {
id: 2,
active: 0,
"name": "Иван",
"phone": "1114123"
}
];
var next_id = 3;
function getUserById(id) {
var key = +id;
var l = users.length;
for (var i=0; i<l; i++) {
if(users[i].id === key) {
return users[i];
}
}
}
fu... |
exports.del = function(req, res){
delUserById(req.params.id);
res.send({});
};
exports.create = function(req, res){
var update = req.body;
var user = {
id: next_id,
active:update.active,
name: update.name,
phone: update.phone
};
next_id++;
users.push(user);
res.send(user);
}; |
res.send(user);
}; | random_line_split |
user.js |
var users = [{
id: 1,
active: 1,
"name": "Вася",
"phone": "1114124"
}, {
id: 2,
active: 0,
"name": "Иван",
"phone": "1114123"
}
];
var next_id = 3;
function getUserById(id) {
var k | on delUserById(id) {
var key = +id;
var l = users.length;
for (var i=0; i<l; i++) {
if (users[i].id === key) {
users.splice(i, 1);
return;
}
}
}
exports.list = function(req, res){
var data = {
"total_count":users.length,
"pos":0,
"data": users
};
res.send(data);
};
exports.show = function(req, ... | ey = +id;
var l = users.length;
for (var i=0; i<l; i++) {
if(users[i].id === key) {
return users[i];
}
}
}
functi | identifier_body |
user.js |
var users = [{
id: 1,
active: 1,
"name": "Вася",
"phone": "1114124"
}, {
id: 2,
active: 0,
"name": "Иван",
"phone": "1114123"
}
];
var next_id = 3;
function getUserB | var key = +id;
var l = users.length;
for (var i=0; i<l; i++) {
if(users[i].id === key) {
return users[i];
}
}
}
function delUserById(id) {
var key = +id;
var l = users.length;
for (var i=0; i<l; i++) {
if (users[i].id === key) {
users.splice(i, 1);
return;
}
}
}
exports.list = function(req, re... | yId(id) {
| identifier_name |
train.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# based on ideas in https://github.com/lethienhoa/Very-Deep-Convolutional-Networks-for-Natural-Language-Processing/blob/master/train.py
import tensorflow as tf
from vdcnn import VDCNN
import numpy as np
import os
import time
import datetime
import cPickle as pkl
import t... |
print("")
# ===================== Preparation des données =============================
# Load data
print("Loading data...")
alphabet = "abcdefghijklmnopqrstuvwxyz0123456789-,;.!?:'\"/\\|_@#$%^&*~`+-=<>()[]{} "
sequence_max_length = 1024
# shuffeling data for training
# Training
# ==========================... | print("{}={}".format(attr.upper(), value)) | conditional_block |
train.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# based on ideas in https://github.com/lethienhoa/Very-Deep-Convolutional-Networks-for-Natural-Language-Processing/blob/master/train.py
import tensorflow as tf
from vdcnn import VDCNN
import numpy as np
import os
import time
import datetime
import cPickle as pkl
import t... | optimizer = tf.train.AdamOptimizer(1e-3)
grads_and_vars = optimizer.compute_gradients(cnn.loss)
train_op = optimizer.apply_gradients(grads_and_vars, global_step=global_step)
# Initialize all variables
print("START %s" % datetime.datetime.now())
sess.run(tf.initialize_all_variables())
saver ... | with tf.control_dependencies(update_ops):
global_step = tf.Variable(0, name="global_step", trainable=False) | random_line_split |
forms.py | = _lazy(u'Please keep the length of the title to %(limit_value)s '
u'characters or less. It is currently %(show_value)s '
u'characters.')
SLUG_REQUIRED = _lazy(u'Please provide a slug.')
SLUG_INVALID = _lazy(u'The slug provided is not valid.')
SLUG_SHORT = _lazy(u'The slug is too ... | class Meta:
model = Document
fields = ('title', 'slug', 'category', 'is_localizable', 'products',
'topics', 'locale', 'is_archived', 'allow_discussion',
'needs_change', 'needs_change_comment', 'related_documents')
def save(self, parent_doc, **kwargs):
... | return c
| random_line_split |
forms.py | = _lazy(u'Please keep the length of the title to %(limit_value)s '
u'characters or less. It is currently %(show_value)s '
u'characters.')
SLUG_REQUIRED = _lazy(u'Please provide a slug.')
SLUG_INVALID = _lazy(u'The slug provided is not valid.')
SLUG_SHORT = _lazy(u'The slug is too ... | (object):
model = Revision
fields = ('keywords', 'summary', 'content', 'comment', 'based_on',
'expires')
def __init__(self, *args, **kwargs):
super(RevisionForm, self).__init__(*args, **kwargs)
self.fields['based_on'].widget = forms.HiddenInput()
self.field... | Meta | identifier_name |
forms.py | or less. It is currently '
u'%(show_value)s characters.')
COMMENT_LONG = _lazy(u'Please keep the length of the comment to '
u'%(limit_value)s characters or less. It is currently '
u'%(show_value)s characters.')
PRODUCT_REQUIRED = _lazy(u'Please select at l... | """Form to add contributors to a document."""
users = MultiUsernameField(
widget=forms.TextInput(attrs={'placeholder': _lazy(u'username'),
'class': 'user-autocomplete'})) | identifier_body | |
forms.py | = _lazy(u'Please keep the length of the title to %(limit_value)s '
u'characters or less. It is currently %(show_value)s '
u'characters.')
SLUG_REQUIRED = _lazy(u'Please provide a slug.')
SLUG_INVALID = _lazy(u'The slug provided is not valid.')
SLUG_SHORT = _lazy(u'The slug is too ... |
return c
class Meta:
model = Document
fields = ('title', 'slug', 'category', 'is_localizable', 'products',
'topics', 'locale', 'is_archived', 'allow_discussion',
'needs_change', 'needs_change_comment', 'related_documents')
def save(self, parent_doc... | raise forms.ValidationError(TOPIC_REQUIRED) | conditional_block |
test_util.py | import unittest
import numpy as np
from bayesnet.image.util import img2patch, patch2img
class TestImg2Patch(unittest.TestCase):
def test_img2patch(self):
img = np.arange(16).reshape(1, 4, 4, 1)
patch = img2patch(img, size=3, step=1)
expected = np.asarray([
[img[0, 0:3, 0:3, 0]... |
if __name__ == '__main__':
unittest.main()
| img = np.arange(16).reshape(1, 4, 4, 1)
patch = img2patch(img, size=2, step=2)
self.assertTrue((img == patch2img(patch, (2, 2), (1, 4, 4, 1))).all())
patch = img2patch(img, size=3, step=1)
expected = np.arange(0, 32, 2).reshape(1, 4, 4, 1)
expected[0, 0, 0, 0] /= 2
expect... | identifier_body |
test_util.py | import unittest
import numpy as np
from bayesnet.image.util import img2patch, patch2img
class TestImg2Patch(unittest.TestCase):
def test_img2patch(self):
img = np.arange(16).reshape(1, 4, 4, 1)
patch = img2patch(img, size=3, step=1)
expected = np.asarray([
[img[0, 0:3, 0:3, 0]... | (unittest.TestCase):
def test_patch2img(self):
img = np.arange(16).reshape(1, 4, 4, 1)
patch = img2patch(img, size=2, step=2)
self.assertTrue((img == patch2img(patch, (2, 2), (1, 4, 4, 1))).all())
patch = img2patch(img, size=3, step=1)
expected = np.arange(0, 32, 2).reshape(... | TestPatch2Img | identifier_name |
test_util.py | import unittest
import numpy as np
from bayesnet.image.util import img2patch, patch2img
class TestImg2Patch(unittest.TestCase):
def test_img2patch(self):
img = np.arange(16).reshape(1, 4, 4, 1)
patch = img2patch(img, size=3, step=1)
expected = np.asarray([
[img[0, 0:3, 0:3, 0]... | 2,
(3, 4)
]
steps = [
(1, 2),
(3, 1),
3
]
shapes = [
(2, 5, 3, 1, 1, 3),
(3, 3, 9, 2, 2, 2),
(1, 7, 5, 3, 4, 5)
]
for img, size, step, shape in zip(imgs, sizes, steps, shapes):... | (1, 1), | random_line_split |
test_util.py | import unittest
import numpy as np
from bayesnet.image.util import img2patch, patch2img
class TestImg2Patch(unittest.TestCase):
def test_img2patch(self):
img = np.arange(16).reshape(1, 4, 4, 1)
patch = img2patch(img, size=3, step=1)
expected = np.asarray([
[img[0, 0:3, 0:3, 0]... |
class TestPatch2Img(unittest.TestCase):
def test_patch2img(self):
img = np.arange(16).reshape(1, 4, 4, 1)
patch = img2patch(img, size=2, step=2)
self.assertTrue((img == patch2img(patch, (2, 2), (1, 4, 4, 1))).all())
patch = img2patch(img, size=3, step=1)
expected = np.ara... | self.assertEqual(shape, img2patch(img, size, step).shape) | conditional_block |
client.rs | the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Parity is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A ... |
/// Returns `true` if response status code is successful.
pub fn is_success(&self) -> bool {
self.status() == reqwest::StatusCode::Ok
}
/// Returns `true` if content type of this response is `text/html`
pub fn is_html(&self) -> bool {
match self.content_type() {
Some(Mime(mime::TopLevel::Text, mime::SubL... | {
match self.inner {
ResponseInner::Response(ref r) => *r.status(),
ResponseInner::NotFound => reqwest::StatusCode::NotFound,
_ => reqwest::StatusCode::Ok,
}
} | identifier_body |
client.rs | the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Parity is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A ... | }
let res = match self.inner {
ResponseInner::Response(ref mut response) => | random_line_split | |
client.rs | the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Parity is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A ... | (self) where Self: Sized {}
}
const CLIENT_TIMEOUT_SECONDS: u64 = 5;
/// Fetch client
pub struct Client {
client: RwLock<(time::Instant, Arc<reqwest::Client>)>,
pool: CpuPool,
limit: Option<usize>,
}
impl Clone for Client {
fn clone(&self) -> Self {
let (ref time, ref client) = *self.client.read();
Client {
... | close | identifier_name |
regenerate-definitions-db.py | #!/usr/bin/env python3
import os.path
import json
import sys
_MY_PATH = os.path.abspath(os.path.dirname(__file__))
sys.path.insert(0, os.path.join(_MY_PATH, '..', '..', '..'))
from qutepart.syntax.loader import loadSyntax
from qutepart.syntax import SyntaxManager, Syntax
def _add_php(targetFileName, srcFileName)... | }
with open('syntax_db.json', 'w', encoding='utf-8') as syntaxDbFile:
json.dump(result, syntaxDbFile, sort_keys=True, indent=4)
print('Done. Do not forget to commit the changes')
if __name__ == '__main__':
main() | 'extensionToXmlFileName' : extensionToXmlFileName,
'firstLineToXmlFileName' : firstLineToXmlFileName, | random_line_split |
regenerate-definitions-db.py | #!/usr/bin/env python3
import os.path
import json
import sys
_MY_PATH = os.path.abspath(os.path.dirname(__file__))
sys.path.insert(0, os.path.join(_MY_PATH, '..', '..', '..'))
from qutepart.syntax.loader import loadSyntax
from qutepart.syntax import SyntaxManager, Syntax
def _add_php(targetFileName, srcFileName)... |
def main():
os.chdir(_MY_PATH)
_add_php('javascript-php.xml', 'javascript.xml')
_add_php('css-php.xml', 'css.xml')
_add_php('html-php.xml', 'html.xml')
xmlFilesPath = os.path.join(_MY_PATH, 'xml')
xmlFileNames = [fileName for fileName in os.listdir(xmlFilesPath) \
if ... | os.system("./generate-php.pl > xml/{} < xml/{}".format(targetFileName, srcFileName)) | identifier_body |
regenerate-definitions-db.py | #!/usr/bin/env python3
import os.path
import json
import sys
_MY_PATH = os.path.abspath(os.path.dirname(__file__))
sys.path.insert(0, os.path.join(_MY_PATH, '..', '..', '..'))
from qutepart.syntax.loader import loadSyntax
from qutepart.syntax import SyntaxManager, Syntax
def _add_php(targetFileName, srcFileName)... |
if syntax.extensions:
for extension in syntax.extensions:
if extension not in extensionToXmlFileName or \
extensionToXmlFileName[extension][0] < syntax.priority:
extensionToXmlFileName[extension] = (syntax.priority, xmlFileName)
if sy... | if not mimetype in mimeTypeToXmlFileName or \
mimeTypeToXmlFileName[mimetype][0] < syntax.priority:
mimeTypeToXmlFileName[mimetype] = (syntax.priority, xmlFileName) | conditional_block |
regenerate-definitions-db.py | #!/usr/bin/env python3
import os.path
import json
import sys
_MY_PATH = os.path.abspath(os.path.dirname(__file__))
sys.path.insert(0, os.path.join(_MY_PATH, '..', '..', '..'))
from qutepart.syntax.loader import loadSyntax
from qutepart.syntax import SyntaxManager, Syntax
def _add_php(targetFileName, srcFileName)... | ():
os.chdir(_MY_PATH)
_add_php('javascript-php.xml', 'javascript.xml')
_add_php('css-php.xml', 'css.xml')
_add_php('html-php.xml', 'html.xml')
xmlFilesPath = os.path.join(_MY_PATH, 'xml')
xmlFileNames = [fileName for fileName in os.listdir(xmlFilesPath) \
if fileName.en... | main | identifier_name |
ef_list_punctuation.py | #!/usr/bin/env python
# -*- coding: utf-8
from __future__ import print_function
import argparse
import codecs
import cPickle as pickle
import numpy as np
import os
from load_tweets import load_tweets
NAME='ef_list_punctuation'
prefix='list_punctuation'
if __name__ == "__main__":
# Las opciones de línea de coman... | verbose("Total tweets : ",len(tweets))
try:
verbose("Total usuarios : ",len(set([id for x,id in ids])))
except ValueError:
verbose("Total usuarios : ",len(ids))
# Calculamos los features
# - Cargar lista de palabras uno
list_of_words1 = [line.strip() for line... | ose('Tweet example',i+1,tweet[:100])
| conditional_block |
ef_list_punctuation.py | #!/usr/bin/env python
# -*- coding: utf-8
from __future__ import print_function
import argparse
import codecs
import cPickle as pickle
import numpy as np
import os
from load_tweets import load_tweets
NAME='ef_list_punctuation'
prefix='list_punctuation'
if __name__ == "__main__":
# Las opciones de línea de coman... | usuario=usuario
vec1=[usuario.count(item) for item in list_of_words1]
vec=vec1
counts.append(vec)
# - Contamos las palabras en los tweets
feats = np.asarray(counts)
# Guarda la matrix de features
with open(os.path.join(opts.dir,opts.pref+'.dat'),'wb') as idxf:
p... | for usuario in tweets: | random_line_split |
ef_list_punctuation.py | #!/usr/bin/env python
# -*- coding: utf-8
from __future__ import print_function
import argparse
import codecs
import cPickle as pickle
import numpy as np
import os
from load_tweets import load_tweets
NAME='ef_list_punctuation'
prefix='list_punctuation'
if __name__ == "__main__":
# Las opciones de línea de coman... | rgs):
print(*args)
else:
verbose = lambda *a: None
# Colecta los tweets y sus identificadores (idtweet y idusuario)
tweets,ids=load_tweets(opts.DIR,opts.format,mix=opts.mix)
# Imprime alguna información sobre los tweets
if opts.verbose:
for i,tweet in enumerate(twe... | bose(*a | identifier_name |
ef_list_punctuation.py | #!/usr/bin/env python
# -*- coding: utf-8
from __future__ import print_function
import argparse
import codecs
import cPickle as pickle
import numpy as np
import os
from load_tweets import load_tweets
NAME='ef_list_punctuation'
prefix='list_punctuation'
if __name__ == "__main__":
# Las opciones de línea de coman... | else:
verbose = lambda *a: None
# Colecta los tweets y sus identificadores (idtweet y idusuario)
tweets,ids=load_tweets(opts.DIR,opts.format,mix=opts.mix)
# Imprime alguna información sobre los tweets
if opts.verbose:
for i,tweet in enumerate(tweets[:10]):
verbose('T... | nt(*args)
| identifier_body |
rating.js | import { Component, ChangeDetectionStrategy, Input, Output, EventEmitter, TemplateRef, ContentChild, forwardRef, ChangeDetectorRef } from '@angular/core';
import { NgbRatingConfig } from './rating-config';
import { toString, getValueInRange } from '../util/util';
import { NG_VALUE_ACCESSOR } from '@angular/forms';
var ... | (config, _changeDetectorRef) {
this._changeDetectorRef = _changeDetectorRef;
this.range = [];
/**
* An event fired when a user is hovering over a given rating.
* Event's payload equals to the rating being hovered over.
*/
this.hover = new EventEmitter();
... | NgbRating | identifier_name |
rating.js | import { Component, ChangeDetectionStrategy, Input, Output, EventEmitter, TemplateRef, ContentChild, forwardRef, ChangeDetectorRef } from '@angular/core';
import { NgbRatingConfig } from './rating-config';
import { toString, getValueInRange } from '../util/util';
import { NG_VALUE_ACCESSOR } from '@angular/forms';
var ... | this.max = config.max;
this.readonly = config.readonly;
}
NgbRating.prototype.ariaValueText = function () { return this.rate + " out of " + this.max; };
NgbRating.prototype.enter = function (value) {
if (!this.readonly) {
this.rate = value;
}
this.hover.e... | {
this._changeDetectorRef = _changeDetectorRef;
this.range = [];
/**
* An event fired when a user is hovering over a given rating.
* Event's payload equals to the rating being hovered over.
*/
this.hover = new EventEmitter();
/**
* An event fir... | identifier_body |
rating.js | import { Component, ChangeDetectionStrategy, Input, Output, EventEmitter, TemplateRef, ContentChild, forwardRef, ChangeDetectorRef } from '@angular/core';
import { NgbRatingConfig } from './rating-config';
import { toString, getValueInRange } from '../util/util';
import { NG_VALUE_ACCESSOR } from '@angular/forms';
var ... | * Rating directive that will take care of visualising a star rating bar.
*/
export var NgbRating = (function () {
function NgbRating(config, _changeDetectorRef) {
this._changeDetectorRef = _changeDetectorRef;
this.range = [];
/**
* An event fired when a user is hovering over a giv... | provide: NG_VALUE_ACCESSOR,
useExisting: forwardRef(function () { return NgbRating; }),
multi: true
};
/** | random_line_split |
rating.js | import { Component, ChangeDetectionStrategy, Input, Output, EventEmitter, TemplateRef, ContentChild, forwardRef, ChangeDetectorRef } from '@angular/core';
import { NgbRatingConfig } from './rating-config';
import { toString, getValueInRange } from '../util/util';
import { NG_VALUE_ACCESSOR } from '@angular/forms';
var ... |
return 0;
};
NgbRating.prototype.ngOnChanges = function (changes) {
if (changes['rate']) {
this.update(this.rate);
this._oldRate = this.rate;
}
};
NgbRating.prototype.ngOnInit = function () { this.range = Array.from({ length: this.max }, function (v, k) {... | {
return Number.parseInt((diff * 100).toFixed(2));
} | conditional_block |
form.component.spec.ts | /*
* Copyright (C) 2015 The Gravitee team (http://gravitee.io)
*
* 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 | * 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 ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.... | *
* http://www.apache.org/licenses/LICENSE-2.0
* | random_line_split |
marked.js | import { RocketChat } from 'meteor/rocketchat:lib';
import { Random } from 'meteor/random';
import _ from 'underscore';
import s from 'underscore.string';
import hljs from 'highlight.js';
import _marked from 'marked';
const renderer = new _marked.Renderer();
let msg = null;
renderer.code = function(code, lang, escap... |
if (tables == null) { tables = RocketChat.settings.get('Markdown_Marked_Tables'); }
if (breaks == null) { breaks = RocketChat.settings.get('Markdown_Marked_Breaks'); }
if (pedantic == null) { pedantic = RocketChat.settings.get('Markdown_Marked_Pedantic'); }
if (smartLists == null) { smartLists = RocketChat.setting... | { gfm = RocketChat.settings.get('Markdown_Marked_GFM'); } | conditional_block |
marked.js | import { RocketChat } from 'meteor/rocketchat:lib';
import { Random } from 'meteor/random';
import _ from 'underscore';
import s from 'underscore.string';
import hljs from 'highlight.js';
import _marked from 'marked';
const renderer = new _marked.Renderer();
let msg = null;
renderer.code = function(code, lang, escap... |
if (!lang) {
text = `<pre><code class="code-colors hljs">${ (escaped ? code : s.escapeHTML(code, true)) }</code></pre>`;
} else {
text = `<pre><code class="code-colors hljs ${ escape(lang, true) }">${ (escaped ? code : s.escapeHTML(code, true)) }</code></pre>`;
}
if (_.isString(msg)) {
return text;
}
con... | let text = null; | random_line_split |
defs.rs | String};
use std::fmt;
/// Type for content hashes of regular files and for blob identifiers on the
/// server.
///
/// In practise, this is a 256-bit SHA-3 sum.
pub type HashId = [u8; 32];
/// The sentinal hash value indicating an uncomputed hash.
///
/// One does not compare hashes against this, since the hashes on ... | (&self, other: &Self) -> bool {
match (self, other) {
(
&FileData::Regular(_, _, tself, _),
&FileData::Regular(_, _, tother, _),
) => tself > tother,
_ => false,
}
}
/// Returns whether this file object and another one represen... | newer_than | identifier_name |
defs.rs | use std::ffi::{OsStr, OsString};
use std::fmt;
/// Type for content hashes of regular files and for blob identifiers on the
/// server.
///
/// In practise, this is a 256-bit SHA-3 sum.
pub type HashId = [u8; 32];
/// The sentinal hash value indicating an uncomputed hash.
///
/// One does not compare hashes against th... | //
// You should have received a copy of the GNU General Public License along with
// Ensync. If not, see <http://www.gnu.org/licenses/>.
| random_line_split | |
app.component.ts | /// <reference path="../../../typings/tsd.d.ts" />
"use strict";
import { Component } from "@angular/core";
import { ROUTER_DIRECTIVES, Routes } from "@angular/router";
import { HeaderComponent } from "./layout/header.component";
import { HomeComponent } from "./home/home.component";
import { ProductsComponent } from... |
}
| {
NProgress.configure({
showSpinner: false
});
$(document).foundation();
} | identifier_body |
app.component.ts | /// <reference path="../../../typings/tsd.d.ts" />
"use strict";
import { Component } from "@angular/core";
import { ROUTER_DIRECTIVES, Routes } from "@angular/router";
import { HeaderComponent } from "./layout/header.component";
import { HomeComponent } from "./home/home.component";
import { ProductsComponent } from... | {
ngOnInit() {
NProgress.configure({
showSpinner: false
});
$(document).foundation();
}
}
| AppComponent | identifier_name |
app.component.ts | /// <reference path="../../../typings/tsd.d.ts" />
"use strict";
import { Component } from "@angular/core";
import { ROUTER_DIRECTIVES, Routes } from "@angular/router";
import { HeaderComponent } from "./layout/header.component";
import { HomeComponent } from "./home/home.component";
import { ProductsComponent } from... | ])
export class AppComponent {
ngOnInit() {
NProgress.configure({
showSpinner: false
});
$(document).foundation();
}
} | { path: "/products/:subCategoryId", component: ProductsComponent},
{ path: "/product/:productId", component: ProductDetailsComponent},
{ path: "/product_new", component: NewProductComponent} | random_line_split |
router.js | const RouteRecognizer = require('route-recognizer');
const glob = require('glob');
const router = new RouteRecognizer();
class Router {
constructor(paths = []) {
this.multiAdd(paths);
}
add(paths) {
paths = Array.isArray(paths) ? paths : [ paths ];
router.add(paths);
}
multiAdd(paths) {
paths ... | async install(ctx, next) {
const assemblyLine = router.recognize(ctx.path) || [];
for (let i = 0; i < assemblyLine.length; i++) {
const { handler, params } = assemblyLine[i];
delete params[''];
Object.assign(ctx.request.query, params);
await handler.apply(ctx, [ ctx ]);
}
await... | } | random_line_split |
router.js | const RouteRecognizer = require('route-recognizer');
const glob = require('glob');
const router = new RouteRecognizer();
class Router {
constructor(paths = []) {
this.multiAdd(paths);
}
add(paths) {
paths = Array.isArray(paths) ? paths : [ paths ];
router.add(paths);
}
multiAdd(paths) {
paths ... |
return paths;
}, [
{ path: '/', handler: require('../pages/index.js') },
{ path: '/static/*', handler: require('../pages/static.js') },
{ path: '/demos/*', handler: require('../pages/demos.js') },
{ path: '/manifest.json', handler: require('../pages/demos.js') },
{ path: '/auto/manifest.json', handler: req... | {
paths.push({ path: '/auto/', handler });
} | conditional_block |
router.js | const RouteRecognizer = require('route-recognizer');
const glob = require('glob');
const router = new RouteRecognizer();
class Router {
constructor(paths = []) {
this.multiAdd(paths);
}
| (paths) {
paths = Array.isArray(paths) ? paths : [ paths ];
router.add(paths);
}
multiAdd(paths) {
paths = Array.isArray(paths) ? paths : [ paths ];
paths.forEach(path => router.add([ path ]));
}
async install(ctx, next) {
const assemblyLine = router.recognize(ctx.path) || [];
for (let i... | add | identifier_name |
router.js | const RouteRecognizer = require('route-recognizer');
const glob = require('glob');
const router = new RouteRecognizer();
class Router {
constructor(paths = []) |
add(paths) {
paths = Array.isArray(paths) ? paths : [ paths ];
router.add(paths);
}
multiAdd(paths) {
paths = Array.isArray(paths) ? paths : [ paths ];
paths.forEach(path => router.add([ path ]));
}
async install(ctx, next) {
const assemblyLine = router.recognize(ctx.path) || [];
for ... | {
this.multiAdd(paths);
} | identifier_body |
tests.py | # -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
from django.contrib.auth.models import User
from django.test.utils import override_settings
from allauth.account import app_settings as account_settings
from allauth.account.models import EmailAddress
from allauth.socialaccount.models im... |
def test_account_connect(self):
email = "user@example.com"
user = User.objects.create(username='user',
is_active=True,
email=email)
user.set_password('test')
user.save()
EmailAddress.objects.create(user=u... | return MockedResponse(200, """
{"response": {"name": "%s",
"avatar": {
"permalink": "https://lh5.googleusercontent.com/photo.jpg"
},
"email": "%s",
"profileUrl": "https://plus.google.com/108204268033311374519",
"id"... | identifier_body |
tests.py | # -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
from django.contrib.auth.models import User
from django.test.utils import override_settings
from allauth.account import app_settings as account_settings
from allauth.account.models import EmailAddress
from allauth.socialaccount.models im... | SOCIALACCOUNT_AUTO_SIGNUP=True,
ACCOUNT_SIGNUP_FORM_CLASS=None,
ACCOUNT_EMAIL_VERIFICATION=account_settings
.EmailVerificationMethod.MANDATORY)
class DisqusTests(OAuth2TestsMixin, TestCase):
provider_id = DisqusProvider.id
def get_mocked_response(self,
name='Raymond ... |
@override_settings( | random_line_split |
tests.py | # -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
from django.contrib.auth.models import User
from django.test.utils import override_settings
from allauth.account import app_settings as account_settings
from allauth.account.models import EmailAddress
from allauth.socialaccount.models im... | (OAuth2TestsMixin, TestCase):
provider_id = DisqusProvider.id
def get_mocked_response(self,
name='Raymond Penners',
email="raymond.penners@example.com"):
return MockedResponse(200, """
{"response": {"name": "%s",
"avat... | DisqusTests | identifier_name |
auth.js | import {
addToken as _addToken,
removeToken as _removeToken,
replaceTokenList as _replaceTokenList,
isValidToken as _isValidToken,
clearTokenList as _clearTokenList,
} from 'utils/tokenHelper';
import { Auth } from 'utils/api';
// Export
export const UPDATE_TOKEN = 'UPDATE_TOKEN';
export const ad... | export const replaceTokenList = (_tokenList) => {
const { activeProviders } = _replaceTokenList(_tokenList);
return {
type: UPDATE_TOKEN,
payload: { activeProviders },
};
};
export const clearTokenIfTokenExpired = () => {
return dispatch => {
if (!_isValidToken()) {
c... | type: UPDATE_TOKEN,
payload: { activeProviders },
};
}; | random_line_split |
auth.js | import {
addToken as _addToken,
removeToken as _removeToken,
replaceTokenList as _replaceTokenList,
isValidToken as _isValidToken,
clearTokenList as _clearTokenList,
} from 'utils/tokenHelper';
import { Auth } from 'utils/api';
// Export
export const UPDATE_TOKEN = 'UPDATE_TOKEN';
export const ad... |
};
};
| {
const { activeProviders } = _clearTokenList();
dispatch({
type: UPDATE_TOKEN,
payload: { activeProviders },
});
} | conditional_block |
setup.py | #!/usr/bin/env python
#-------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#----------------------------------------------------------------... | # a-b-c => a/b/c
package_folder_path = PACKAGE_NAME.replace('-', '/')
# a-b-c => a.b.c
namespace_name = PACKAGE_NAME.replace('-', '.')
# azure v0.x is not compatible with this package
# azure v0.x used to have a __version__ attribute (newer versions don't)
try:
import azure
try:
ver = azure.__version__... | random_line_split | |
setup.py | #!/usr/bin/env python
#-------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#----------------------------------------------------------------... |
with open('README.rst', encoding='utf-8') as f:
readme = f.read()
with open('HISTORY.rst', encoding='utf-8') as f:
history = f.read()
setup(
name=PACKAGE_NAME,
version=version,
description='Microsoft Azure {} Client Library for Python'.format(PACKAGE_PPRINT_NAME),
long_description=readme + '\... | raise RuntimeError('Cannot find version information') | conditional_block |
userScript.js | "use strict";
const vm = require("vm");
const path = require("path");
const fs = require("fs-extra");
const JSZip = require("jszip");
const UserError = require("./userError");
const libDir = process.env.BLANK_DATA_DIR
? path.join(process.env.BLANK_DATA_DIR, "lib")
: path.join(process.cwd(), "var", "lib");
con... | "os",
"path",
"process",
"punycode",
"querystring",
"readline",
"repl",
"stream",
"string_decoder",
"timers",
"tls",
"tty",
"unstream",
"url",
"util",
// "v8",
"vm",
"zlib",
];
const internalModules = {
async: "async",
clickhouse: "./click... | "net", | random_line_split |
userScript.js | "use strict";
const vm = require("vm");
const path = require("path");
const fs = require("fs-extra");
const JSZip = require("jszip");
const UserError = require("./userError");
const libDir = process.env.BLANK_DATA_DIR
? path.join(process.env.BLANK_DATA_DIR, "lib")
: path.join(process.cwd(), "var", "lib");
con... | (moduleName) {
return require(path.join(libDir, moduleName));
}
}
process.on("exit", code => {
fs.emptyDirSync(libDir);
console.info(`Worker is about to exit with code: ${code}`);
});
var userScript = new UserScript();
module.exports = userScript;
| requireLib | identifier_name |
userScript.js | "use strict";
const vm = require("vm");
const path = require("path");
const fs = require("fs-extra");
const JSZip = require("jszip");
const UserError = require("./userError");
const libDir = process.env.BLANK_DATA_DIR
? path.join(process.env.BLANK_DATA_DIR, "lib")
: path.join(process.cwd(), "var", "lib");
con... |
}
function resolve(basePath, moduleName) {
//If path begins with './', join it with base path
if (/^\.\//.test(moduleName)) {
moduleName = path.join(basePath, moduleName).replace(/^\.\//, "");
}
if (externalModules.hasOwnProperty(moduleName)) {
return externalModules[moduleName];
... | {
let waiter = waiting[j];
for (let i = waiter.modules.length - 1; i >= 0; i--) {
let m = resolve(waiter.basePath, waiter.modules[i]);
if (m != null) {
loadModule(m);
waiter.modules.splice(i, 1);
}
}
if (waiter.modules.l... | conditional_block |
userScript.js | "use strict";
const vm = require("vm");
const path = require("path");
const fs = require("fs-extra");
const JSZip = require("jszip");
const UserError = require("./userError");
const libDir = process.env.BLANK_DATA_DIR
? path.join(process.env.BLANK_DATA_DIR, "lib")
: path.join(process.cwd(), "var", "lib");
con... |
function checkWaiting() {
for (let j = waiting.length - 1; j >= 0; j--) {
let waiter = waiting[j];
for (let i = waiter.modules.length - 1; i >= 0; i--) {
let m = resolve(waiter.basePath, waiter.modules[i]);
if (m != null) {
loadModule(m);
wai... | {
let d =
typeof cb !== "function"
? new Promise((f, r) => (cb = (e, d) => setImmediate(() => (e != null ? r(e) : f(d)))))
: null;
if (!Array.isArray(waitFor)) {
waitFor = [waitFor];
}
waiting.push({ modules: waitFor, basePath: basePath, cb: cb });
checkWaitin... | identifier_body |
test_base.py | # -*- coding: utf-8 -*-
"""Unit tests of assorted base data structures and common functions."""
import pytest
from simtools.base import Dict, is_iterable, is_string
def | ():
# List of integers
obj = [1, 2, 3]
assert is_iterable(obj) == True
# Tuple of integers
obj = 1, 2, 3
assert is_iterable(obj) == True
# List of strings
obj = ["abc", "def", "ghi"]
assert is_iterable(obj) == True
# Tuple of strings
obj = "abc", "def", "ghi"
assert is... | test_is_iterable | identifier_name |
test_base.py | # -*- coding: utf-8 -*-
"""Unit tests of assorted base data structures and common functions."""
import pytest
from simtools.base import Dict, is_iterable, is_string
def test_is_iterable():
# List of integers
obj = [1, 2, 3]
assert is_iterable(obj) == True
# Tuple of integers
obj = 1, 2, 3
a... | d = Dict()
d['a'] = 1
del d.a
with pytest.raises(KeyError):
d['a']
with pytest.raises(AttributeError):
d.a | identifier_body | |
test_base.py | # -*- coding: utf-8 -*-
"""Unit tests of assorted base data structures and common functions."""
import pytest
from simtools.base import Dict, is_iterable, is_string
def test_is_iterable():
# List of integers
obj = [1, 2, 3]
assert is_iterable(obj) == True
# Tuple of integers
obj = 1, 2, 3
a... |
def test_dict_attr_access():
d = Dict()
d['a'] = 1
assert d.a == 1
d.b = 2
assert d['b'] == 2
with pytest.raises(AttributeError):
d.c
def test_dict_attr_deletion():
d = Dict()
d['a'] = 1
del d.a
with pytest.raises(KeyError):
d['a']
with pytest.raises(A... | assert is_string(obj) == False
# Dictionary
obj = {"abc": 1, "def": 2, "ghi": 3}
assert is_string(obj) == False | random_line_split |
get_backup_keys.rs | //! `GET /_matrix/client/*/room_keys/keys`
//!
//! Retrieve all keys from a backup version.
pub mod v3 {
//! `/v3/` ([spec])
//!
//! [spec]: https://spec.matrix.org/v1.2/client-server-api/#get_matrixclientv3room_keyskeys
use std::collections::BTreeMap;
use ruma_common::{api::ruma_api, RoomId};
... | (rooms: BTreeMap<Box<RoomId>, RoomKeyBackup>) -> Self {
Self { rooms }
}
}
}
| new | identifier_name |
get_backup_keys.rs | //! `GET /_matrix/client/*/room_keys/keys`
//!
//! Retrieve all keys from a backup version.
pub mod v3 {
//! `/v3/` ([spec])
//!
//! [spec]: https://spec.matrix.org/v1.2/client-server-api/#get_matrixclientv3room_keyskeys
use std::collections::BTreeMap;
use ruma_common::{api::ruma_api, RoomId};
... | #[ruma_api(query)]
pub version: &'a str,
}
response: {
/// A map from room IDs to session IDs to key data.
pub rooms: BTreeMap<Box<RoomId>, RoomKeyBackup>,
}
error: crate::Error
}
impl<'a> Request<'a> {
/// Creates a new ... | random_line_split | |
get_backup_keys.rs | //! `GET /_matrix/client/*/room_keys/keys`
//!
//! Retrieve all keys from a backup version.
pub mod v3 {
//! `/v3/` ([spec])
//!
//! [spec]: https://spec.matrix.org/v1.2/client-server-api/#get_matrixclientv3room_keyskeys
use std::collections::BTreeMap;
use ruma_common::{api::ruma_api, RoomId};
... |
}
}
| {
Self { rooms }
} | identifier_body |
units.py | # -*- coding: utf-8 -*-
# Licensed under a 3-clause BSD style license - see LICENSE.rst
from __future__ import (absolute_import, division, print_function,
unicode_literals)
import numpy as np
__doctest_skip__ = ['quantity_support']
def quantity_support(format='latex_inline'):
"""
En... | class MplQuantityConverter(units.ConversionInterface):
def __init__(self):
if u.Quantity not in units.registry:
units.registry[u.Quantity] = self
self._remove = True
else:
self._remove = False
@staticmethod
def axisinfo(u... | n = int((x / np.pi) * 2.0 + 0.25)
if n == 0:
return '0'
elif n == 1:
return 'π/2'
elif n == 2:
return 'π'
elif n % 2 == 0:
return '{0}π'.format(n / 2)
else:
return '{0}π/2'.format(n)
| identifier_body |
units.py | # -*- coding: utf-8 -*-
# Licensed under a 3-clause BSD style license - see LICENSE.rst
from __future__ import (absolute_import, division, print_function,
unicode_literals)
import numpy as np
__doctest_skip__ = ['quantity_support']
def quantity_support(format='latex_inline'):
"""
En... | @staticmethod
def axisinfo(unit, axis):
if unit == u.radian:
return units.AxisInfo(
majloc=ticker.MultipleLocator(base=np.pi/2),
majfmt=ticker.FuncFormatter(rad_fn),
label=unit.to_string(),
)
... | ._remove = False
| conditional_block |
units.py | # -*- coding: utf-8 -*-
# Licensed under a 3-clause BSD style license - see LICENSE.rst
from __future__ import (absolute_import, division, print_function,
unicode_literals)
import numpy as np
__doctest_skip__ = ['quantity_support']
def | (format='latex_inline'):
"""
Enable support for plotting `astropy.units.Quantity` instances in
matplotlib.
May be (optionally) used with a ``with`` statement.
>>> import matplotlib.pyplot as plt
>>> from astropy import units as u
>>> from astropy import visualization
>>> with v... | quantity_support | identifier_name |
units.py | # -*- coding: utf-8 -*-
# Licensed under a 3-clause BSD style license - see LICENSE.rst
from __future__ import (absolute_import, division, print_function,
unicode_literals)
import numpy as np
__doctest_skip__ = ['quantity_support']
def quantity_support(format='latex_inline'):
"""
En... | return units.AxisInfo(
majloc=ticker.AutoLocator(),
majfmt=ticker.FormatStrFormatter('%i°'),
label=unit.to_string(),
)
elif unit is not None:
return units.AxisInfo(label=unit.to_string(format))
... | majloc=ticker.MultipleLocator(base=np.pi/2),
majfmt=ticker.FuncFormatter(rad_fn),
label=unit.to_string(),
)
elif unit == u.degree: | random_line_split |
awscreds-custom.py | #!/usr/local/bin/python3
import sys
import boto3
import os
from botocore.exceptions import ClientError
import json
import argparse
from botocore.utils import InstanceMetadataFetcher
from botocore.credentials import InstanceMetadataProvider
import platform
region = os.getenv('AWS_DEFAULT_REGION', 'us-east-1')
duration... |
try:
params = {"aws_access_key_id": aws_access_key_id, "aws_secret_access_key": aws_secret_access_key, "region_name": region}
temp_session = boto3.Session(**params)
sts_client = temp_session.client("sts", region_name=region)
params = {"DurationSeconds": duration}
response = ... | sys.exit(255) | conditional_block |
awscreds-custom.py | #!/usr/local/bin/python3
import sys
import boto3
import os
from botocore.exceptions import ClientError
import json
import argparse
from botocore.utils import InstanceMetadataFetcher
from botocore.credentials import InstanceMetadataProvider
import platform
region = os.getenv('AWS_DEFAULT_REGION', 'us-east-1')
duration... |
print(json.dumps(cred)) | random_line_split | |
json_parser.rs | // Copyright 2022 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// This file contains bindings to convert from JSON to C++ base::Value objects.
// The code related to `base::Value` can be found in 'values.rs'
// and 'v... |
Ok(_) => true,
}
}
| {
*error_line = err.line().try_into().unwrap_or(-1);
*error_column = err.column().try_into().unwrap_or(-1);
error_message.as_mut().clear();
// The following line pulls in a lot of binary bloat, due to all the formatter
// implementations required to stringify ... | conditional_block |
json_parser.rs | // Copyright 2022 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// This file contains bindings to convert from JSON to C++ base::Value objects.
// The code related to `base::Value` can be found in 'values.rs'
// and 'v... | } | random_line_split | |
json_parser.rs | // Copyright 2022 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// This file contains bindings to convert from JSON to C++ base::Value objects.
// The code related to `base::Value` can be found in 'values.rs'
// and 'v... | (
json: &[u8],
options: JsonOptions,
value_slot: ValueSlotRef,
) -> Result<(), serde_jsonrc::Error> {
let mut to_parse = json;
if to_parse.len() >= 3 && to_parse[0..3] == UTF8_BOM {
to_parse = &to_parse[3..];
}
let mut deserializer = serde_jsonrc::Deserializer::new(SliceRead::new(
... | decode_json | identifier_name |
uploadDataAndTransform.py | #!/bin/env python
try:
# For Python 3.0 and later
from urllib.request import urlopen, Request, HTTPError
except ImportError:
# Fallback to Python 2
from urllib2 import urlopen, Request, HTTPError
import sys
import os
if len(sys.argv) < 4:
print ("Usage:")
print ("\t %s input_rawData transf... |
output.write(buffer)
except HTTPError, error:
print error
print (error.read())
| break | conditional_block |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.