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 |
|---|---|---|---|---|
index.js | const path = require('path');
const consoleLogger = require('./logger');
const _ = require('lodash');
module.exports = (config, logger, metrics, next) => {
if (!next) { next = metrics; metrics = { increment: _.noop }; }
if (!next) |
require('../db')(config, logger, (err, client) => {
if (err) { return next(err); }
const messaging = require('../db/messaging')(config);
const urls = require('./urls');
const visibility = require('./visibility');
const api = {
logger,
metrics,
client,
config,
mes... | { next = logger; logger = consoleLogger; } | conditional_block |
issue-6128.rs | // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
fn g(&self, _e: isize) {
panic!();
}
}
pub fn main() {
let g : Box<HashMap<isize,isize>> = box HashMap::new();
let _g2 : Box<Graph<isize,isize>> = g as Box<Graph<isize,isize>>;
}
| {
panic!();
} | identifier_body |
issue-6128.rs | // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | extern crate collections;
use std::collections::HashMap;
trait Graph<Node, Edge> {
fn f(&self, Edge);
fn g(&self, Node);
}
impl<E> Graph<isize, E> for HashMap<isize, isize> {
fn f(&self, _e: E) {
panic!();
}
fn g(&self, _e: isize) {
panic!();
}
}
pub fn main() {
let g : ... |
#![allow(unknown_features)]
#![feature(box_syntax, collections)]
| random_line_split |
issue-6128.rs | // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | (&self, _e: E) {
panic!();
}
fn g(&self, _e: isize) {
panic!();
}
}
pub fn main() {
let g : Box<HashMap<isize,isize>> = box HashMap::new();
let _g2 : Box<Graph<isize,isize>> = g as Box<Graph<isize,isize>>;
}
| f | identifier_name |
sync.ts | import * as akala from '@akala/core'
import * as mongo from 'mongodb'
if (require.main == module)
{
var client = new mongo.MongoClient('mongodb://172.17.0.5:27017'/*, { useNewUrlParser: true, useUnifiedTopology: true }*/);
client.connect().then(async (c) =>
{
var db = c.db('kitchen');
... | {
return await http.getJSON<any>(`https://fr-icookin.group-taurus.com/categories`)
} | identifier_body | |
sync.ts | import * as akala from '@akala/core'
import * as mongo from 'mongodb'
if (require.main == module)
| for (var recipe of result.result)
{
if (lastRecord && recipe.niceName === lastRecord.niceName)
{
console.log('less than ' + (start + step));
break;
}
if ... | {
var client = new mongo.MongoClient('mongodb://172.17.0.5:27017'/*, { useNewUrlParser: true, useUnifiedTopology: true }*/);
client.connect().then(async (c) =>
{
var db = c.db('kitchen');
var recipes = db.collection('recipes');
var totalCount = 0;
var dbCount = await r... | conditional_block |
sync.ts | import * as akala from '@akala/core'
import * as mongo from 'mongodb'
| var client = new mongo.MongoClient('mongodb://172.17.0.5:27017'/*, { useNewUrlParser: true, useUnifiedTopology: true }*/);
client.connect().then(async (c) =>
{
var db = c.db('kitchen');
var recipes = db.collection('recipes');
var totalCount = 0;
var dbCount = await reci... |
if (require.main == module)
{
| random_line_split |
sync.ts | import * as akala from '@akala/core'
import * as mongo from 'mongodb'
if (require.main == module)
{
var client = new mongo.MongoClient('mongodb://172.17.0.5:27017'/*, { useNewUrlParser: true, useUnifiedTopology: true }*/);
client.connect().then(async (c) =>
{
var db = c.db('kitchen');
... | (category: string, skip: number, limit: number)
{
return await http.getJSON<any>(`https://fr-icookin.group-taurus.com/recipes?sortBy=recent&limit=${limit}&skip=${skip}&category=${category}`)
}
export async function getCategories()
{
return await http.getJSON<any>(`https://fr-icookin.group-taurus.com/cat... | get | identifier_name |
XHtmlPrinter.py | import string
import Printer
from xml.dom import XHTML_NAMESPACE
# Wrapper classes to convert nodes from HTML to XHTML
class XHtmlDocType:
def __init__(self, doctype):
self.name = 'html' | self.entities = doctype and doctype.entities or []
self.notations = doctype and doctype.notation or []
return
class XHtmlAttr:
def __init__(self, node):
self.namespaceURI = XHTML_NAMESPACE
self.name = string.lower(node.name)
self.node = node
return
def _... | self.publicId = "-//W3C//DTD XHTML 1.0 Strict//EN"
self.systemId = "DTD/xhtml1-strict.dtd" | random_line_split |
XHtmlPrinter.py | import string
import Printer
from xml.dom import XHTML_NAMESPACE
# Wrapper classes to convert nodes from HTML to XHTML
class XHtmlDocType:
|
class XHtmlAttr:
def __init__(self, node):
self.namespaceURI = XHTML_NAMESPACE
self.name = string.lower(node.name)
self.node = node
return
def __getattr__(self, key):
return getattr(self.node, key)
class XHtmlElement:
def __init__(self, node):
self.tagName... | def __init__(self, doctype):
self.name = 'html'
self.publicId = "-//W3C//DTD XHTML 1.0 Strict//EN"
self.systemId = "DTD/xhtml1-strict.dtd"
self.entities = doctype and doctype.entities or []
self.notations = doctype and doctype.notation or []
return | identifier_body |
XHtmlPrinter.py | import string
import Printer
from xml.dom import XHTML_NAMESPACE
# Wrapper classes to convert nodes from HTML to XHTML
class XHtmlDocType:
def __init__(self, doctype):
self.name = 'html'
self.publicId = "-//W3C//DTD XHTML 1.0 Strict//EN"
self.systemId = "DTD/xhtml1-strict.dtd"
self... | (self, stream, encoding, indent):
xhtml = {None: 'http://www.w3.org/1999/xhtml'}
Printer.PrintVisitor.__init__(self, stream, encoding, indent, nsHints=xhtml)
self._html = 0
return
def visitDocument(self,node):
self.visitProlog()
self._tryIndent()
self.visitDo... | __init__ | identifier_name |
database_type.py | # -*- coding: utf-8 -*-
##############################################################################
#
# Infrastructure
# Copyright (C) 2014 Ingenieria ADHOC
# No email
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License... |
database_type()
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: | random_line_split | |
database_type.py | # -*- coding: utf-8 -*-
##############################################################################
#
# Infrastructure
# Copyright (C) 2014 Ingenieria ADHOC
# No email
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License... | (osv.osv):
""""""
_name = 'infrastructure.database_type'
_description = 'database_type'
_columns = {
'name': fields.char(string='Name', required=True),
'prefix': fields.char(string='Prefix', required=True, size=4),
'url_prefix': fields.char(string='URL Prefix'),
'au... | database_type | identifier_name |
database_type.py | # -*- coding: utf-8 -*-
##############################################################################
#
# Infrastructure
# Copyright (C) 2014 Ingenieria ADHOC
# No email
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License... | _defaults = {
}
_constraints = [
]
database_type()
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
| """"""
_name = 'infrastructure.database_type'
_description = 'database_type'
_columns = {
'name': fields.char(string='Name', required=True),
'prefix': fields.char(string='Prefix', required=True, size=4),
'url_prefix': fields.char(string='URL Prefix'),
'automatic_drop': ... | identifier_body |
utilities.js | function Vec2(_x, _y) |
function getMCC(c, e) {
var x;
var y;
if (e.pageX || e.pageY) {
x = e.pageX;
y = e.pageY;
} else {
x = e.clientX + document.body.scrollLeft + document.documentElement.scrollLeft;
y = e.clientY + document.body.scrollTop + document.documentElement.scrollTop;
}
x -... | {
var self = this;
self.x = _x;
self.y = _y;
self.Distance = function (OtherPoint) {
try {
return Math.sqrt(Math.pow(OtherPoint.x - self.x, 2) + Math.pow(OtherPoint.y - self.y, 2));
} catch (e) {
console.error(e);
return false;
}
}
} | identifier_body |
utilities.js | function Vec2(_x, _y) {
var self = this;
self.x = _x;
self.y = _y;
self.Distance = function (OtherPoint) {
try {
return Math.sqrt(Math.pow(OtherPoint.x - self.x, 2) + Math.pow(OtherPoint.y - self.y, 2));
} catch (e) {
console.error(e);
return false;
... |
function getMCC(c, e) {
var x;
var y;
if (e.pageX || e.pageY) {
x = e.pageX;
y = e.pageY;
} else {
x = e.clientX + document.body.scrollLeft + document.documentElement.scrollLeft;
y = e.clientY + document.body.scrollTop + document.documentElement.scrollTop;
}
x -=... | }
} | random_line_split |
utilities.js | function Vec2(_x, _y) {
var self = this;
self.x = _x;
self.y = _y;
self.Distance = function (OtherPoint) {
try {
return Math.sqrt(Math.pow(OtherPoint.x - self.x, 2) + Math.pow(OtherPoint.y - self.y, 2));
} catch (e) {
console.error(e);
return false;
... |
x -= c.offsetLeft + c.clientLeft;
y -= c.offsetTop + c.clientTop;
return new Vec2(x, y);
} | {
x = e.clientX + document.body.scrollLeft + document.documentElement.scrollLeft;
y = e.clientY + document.body.scrollTop + document.documentElement.scrollTop;
} | conditional_block |
utilities.js | function Vec2(_x, _y) {
var self = this;
self.x = _x;
self.y = _y;
self.Distance = function (OtherPoint) {
try {
return Math.sqrt(Math.pow(OtherPoint.x - self.x, 2) + Math.pow(OtherPoint.y - self.y, 2));
} catch (e) {
console.error(e);
return false;
... | (c, e) {
var x;
var y;
if (e.pageX || e.pageY) {
x = e.pageX;
y = e.pageY;
} else {
x = e.clientX + document.body.scrollLeft + document.documentElement.scrollLeft;
y = e.clientY + document.body.scrollTop + document.documentElement.scrollTop;
}
x -= c.offsetLeft + ... | getMCC | identifier_name |
UnmountOldrootState.py | #!/usr/bin/env python
#
# VM Backup extension
#
# Copyright 2015 Microsoft Corporation
#
# 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
#
# U... | (OSEncryptionState):
def __init__(self, context):
super(UnmountOldrootState, self).__init__('UnmountOldrootState', context)
def should_enter(self):
self.context.logger.log("Verifying if machine should enter unmount_oldroot state")
if not super(UnmountOldrootState, self).should_enter():... | UnmountOldrootState | identifier_name |
UnmountOldrootState.py | #!/usr/bin/env python
#
# VM Backup extension
#
# Copyright 2015 Microsoft Corporation
#
# 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
#
# U... |
self.context.logger.log("Performing enter checks for unmount_oldroot state")
self.command_executor.ExecuteInBash('[ -e "/oldroot" ]', True)
if self.command_executor.Execute('mountpoint /oldroot') != 0:
return False
return True
def ent... | return False | conditional_block |
UnmountOldrootState.py | #!/usr/bin/env python
#
# VM Backup extension
#
# Copyright 2015 Microsoft Corporation
#
# 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
#
# U... | if not "running" in line:
continue
if "walinuxagent.service" in line or "sshd.service" in line:
continue
match = re.search(r'\s(\S*?\.service)', line)
if match:
service = match.groups()[0]
self.command_exec... | self.command_executor.Execute(command_to_execute="systemctl list-units",
raise_exception_on_failure=True,
communicator=proc_comm)
for line in proc_comm.stdout.split('\n'): | random_line_split |
UnmountOldrootState.py | #!/usr/bin/env python
#
# VM Backup extension
#
# Copyright 2015 Microsoft Corporation
#
# 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
#
# U... |
def enter(self):
if not self.should_enter():
return
self.context.logger.log("Entering unmount_oldroot state")
self.command_executor.Execute('systemctl rescue', True)
self.command_executor.Execute('systemctl start sshd.service', True)
self.command_execu... | self.context.logger.log("Verifying if machine should enter unmount_oldroot state")
if not super(UnmountOldrootState, self).should_enter():
return False
self.context.logger.log("Performing enter checks for unmount_oldroot state")
self.command_executor.ExecuteInBash('[ -e "/... | identifier_body |
const-eval-overflow2c.rs | // Copyright 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-MIT or ... | <T>(_: T) {
}
| foo | identifier_name |
const-eval-overflow2c.rs | // Copyright 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-MIT or ... | );
fn main() {
foo(VALS_I8);
foo(VALS_I16);
foo(VALS_I32);
foo(VALS_I64);
foo(VALS_U8);
foo(VALS_U16);
foo(VALS_U32);
foo(VALS_U64);
}
fn foo<T>(_: T) {
} | u64::MAX * 2, | random_line_split |
const-eval-overflow2c.rs | // Copyright 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-MIT or ... | {
} | identifier_body | |
SaleList.tsx | import { isEmpty } from "lodash"
import React, { Component } from "react"
import { Dimensions, FlatList, LayoutChangeEvent, View } from "react-native"
import SaleListItem from "./SaleListItem"
import { SectionHeader } from "./SectionHeader"
interface Props {
item: {
data: any[]
}
section: {
isFirstItem?... | () {
const { item, section } = this.props
const { columnCount, columnWidth } = this.state
if (isEmpty(item.data)) {
return null
}
const style = {
marginTop: section.isFirstItem ? -9 : 0, // Offset spaced section headers
}
return (
<View style={style} onLayout={this.onLay... | render | identifier_name |
SaleList.tsx | import { isEmpty } from "lodash"
import React, { Component } from "react"
import { Dimensions, FlatList, LayoutChangeEvent, View } from "react-native"
import SaleListItem from "./SaleListItem"
import { SectionHeader } from "./SectionHeader"
interface Props {
item: {
data: any[]
}
section: {
isFirstItem?... | }
render() {
const { item, section } = this.props
const { columnCount, columnWidth } = this.state
if (isEmpty(item.data)) {
return null
}
const style = {
marginTop: section.isFirstItem ? -9 : 0, // Offset spaced section headers
}
return (
<View style={style} onLayou... | const screenWidth = event.nativeEvent.layout.width
const isIPad = screenWidth > 700
const gutterSize = isIPad ? 80 : 40
const columnWidth = (screenWidth - gutterSize) / this.state.columnCount
this.setState({ columnWidth }) | random_line_split |
SaleList.tsx | import { isEmpty } from "lodash"
import React, { Component } from "react"
import { Dimensions, FlatList, LayoutChangeEvent, View } from "react-native"
import SaleListItem from "./SaleListItem"
import { SectionHeader } from "./SectionHeader"
interface Props {
item: {
data: any[]
}
section: {
isFirstItem?... |
const style = {
marginTop: section.isFirstItem ? -9 : 0, // Offset spaced section headers
}
return (
<View style={style} onLayout={this.onLayout}>
<SectionHeader title={section.title} />
{columnCount > 0 ? (
<FlatList
contentContainerStyle={{
... | {
return null
} | conditional_block |
ClassroomDataObjectFactorySpec.ts | // Copyright 2018 The Oppia Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by ap... | description: 'Topic description',
canonical_story_count: 4,
subtopic_count: 5,
total_skill_count: 20,
uncategorized_skill_count: 5,
thumbnail_filename: 'image.svg',
thumbnail_bg_color: '#C6DCDA'
}, {
id: 'topic2',
name: 'Topic name 2',
description: 'Topic ... | name: 'Topic name', | random_line_split |
imap_attachment_to_s3_operator.py | #
# 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 may not... | stacklevel=2,
) | random_line_split | |
similarity_checker.py | .2
BETA = 0.45
ETA = 0.4
PHI = 0.2
DELTA = 0.85
brown_freqs = dict()
N = 0
######################### word similarity ##########################
def get_best_synset_pair(word_1, word_2):
"""
Choose the pair with highest path similarity among all pairs.
Mimics pattern-seeking behavior of humans.
"""
... | def semantic_vector(words, joint_words, info_content_norm):
"""
Computes the semantic vector of a sentence. The sentence is passed in as
a collection of words. The size of the semantic vector is the same as the
size of the joint word set. The elements are 1 if a word in the sentence
already exists i... | random_line_split | |
similarity_checker.py | .2
BETA = 0.45
ETA = 0.4
PHI = 0.2
DELTA = 0.85
brown_freqs = dict()
N = 0
######################### word similarity ##########################
def get_best_synset_pair(word_1, word_2):
"""
Choose the pair with highest path similarity among all pairs.
Mimics pattern-seeking behavior of humans.
"""
... |
def semantic_vector(words, joint_words, info_content_norm):
"""
Computes the semantic vector of a sentence. The sentence is passed in as
a collection of words. The size of the semantic vector is the same as the
size of the joint word set. The elements are 1 if a word in the sentence
already exists... | """
Uses the Brown corpus available in NLTK to calculate a Laplace
smoothed frequency distribution of words, then uses this information
to compute the information content of the lookup_word.
"""
global N
if N == 0:
# poor man's lazy evaluation
for sent in brown.sents():
... | identifier_body |
similarity_checker.py | ):
"""
Return a measure of the length of the shortest path in the semantic
ontology (Wordnet in our case as well as the paper's) between two
synsets.
"""
l_dist = sys.maxint
if synset_1 is None or synset_2 is None:
return 0.0
if synset_1 == synset_2:
# if synset_1 and syn... | similarity | identifier_name | |
similarity_checker.py | .2
BETA = 0.45
ETA = 0.4
PHI = 0.2
DELTA = 0.85
brown_freqs = dict()
N = 0
######################### word similarity ##########################
def get_best_synset_pair(word_1, word_2):
"""
Choose the pair with highest path similarity among all pairs.
Mimics pattern-seeking behavior of humans.
"""
... |
else:
max_sim = -1.0
best_pair = None, None
for synset_1 in synsets_1:
for synset_2 in synsets_2:
sim = wn.path_similarity(synset_1, synset_2)
if sim > max_sim:
max_sim = sim
best_pair = synset_1, synset_2
... | return None, None | conditional_block |
randomtrees.py | #!/usr/bin/env python3
import random
"""
Generates random trees
"""
import argparse
alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
def generate_random_item(length=8, chars=alphabet):
item = ""
for i in range(length):
index = random.randint(0, len(chars) - 1)
... | print(line) | conditional_block | |
randomtrees.py | #!/usr/bin/env python3
import random
"""
Generates random trees
"""
import argparse
alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
def generate_random_item(length=8, chars=alphabet):
item = ""
for i in range(length):
index = random.randint(0, len(chars) - 1)
... | parser.add_argument('--Items',
help='The number of items for each node of the tree.',
type=int,
default=10)
parser.add_argument('--Length',
help='The length of each item.',
type=int,
... |
parser.add_argument('--Depth',
help='The depth of the trees.',
type=int,
default=3) | random_line_split |
randomtrees.py | #!/usr/bin/env python3
import random
"""
Generates random trees
"""
import argparse
alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
def generate_random_item(length=8, chars=alphabet):
|
def generate_random_tree_lines(
depth,
items,
length,
chars=alphabet,
current_indentation=''):
lines = []
if depth > 0:
remaining_items_to_add = items
while remaining_items_to_add > 0:
lines.append('{0}{1}'.format(current_indentation, gene... | item = ""
for i in range(length):
index = random.randint(0, len(chars) - 1)
item += chars[index]
return item | identifier_body |
randomtrees.py | #!/usr/bin/env python3
import random
"""
Generates random trees
"""
import argparse
alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
def generate_random_item(length=8, chars=alphabet):
item = ""
for i in range(length):
index = random.randint(0, len(chars) - 1)
... | (
depth,
items,
length,
chars=alphabet,
current_indentation=''):
lines = []
if depth > 0:
remaining_items_to_add = items
while remaining_items_to_add > 0:
lines.append('{0}{1}'.format(current_indentation, generate_random_item(length, chars)))... | generate_random_tree_lines | identifier_name |
ca-multicore.py | #!/usr/bin/python
import numpy as np
from sklearn.metrics import mutual_info_score
import MDAnalysis
import os
import re
import math
import sys
from itertools import combinations_with_replacement,permutations
from concurrent.futures import ProcessPoolExecutor, Future, wait
usecpus = 10#how many cores to use
frms_num ... | (X, n, tx):
T = tx
return T[n-1]
"""
waiting time function W(X, t) to get the time interval
from t until the next transition/peak of X
"""
def wait_time(X, t, tx):
#if t < 0 :
# sys.exit("Error: time needs to be a positive number")
wait = 0
T = tx
for i in range(0,len(T)-1):
if ... | trans_time_n | identifier_name |
ca-multicore.py | #!/usr/bin/python
import numpy as np
from sklearn.metrics import mutual_info_score
import MDAnalysis
import os
import re
import math
import sys
from itertools import combinations_with_replacement,permutations
from concurrent.futures import ProcessPoolExecutor, Future, wait
usecpus = 10#how many cores to use
frms_num ... |
return k_k
"""
transition time function T(X, n) to get the time of
N th transition of a time series X time unit is 100 picosecond
"""
def trans_time_n(X, n, tx):
T = tx
return T[n-1]
"""
waiting time function W(X, t) to get the time interval
from t until the next transition/peak of X
"""
def wait_time(... | peak1 = min(t_t, key=lambda x:abs(x-i))
peak2 = min(t_t, key=lambda x:abs(x-(i+rg)))
if peak1 != peak2:
k_k.append(i) | conditional_block |
ca-multicore.py | #!/usr/bin/python
import numpy as np
from sklearn.metrics import mutual_info_score
import MDAnalysis
import os
import re
import math
import sys
from itertools import combinations_with_replacement,permutations
from concurrent.futures import ProcessPoolExecutor, Future, wait
usecpus = 10#how many cores to use
frms_num ... |
"""
waiting time function W(X, t) to get the time interval
from t until the next transition/peak of X
"""
def wait_time(X, t, tx):
#if t < 0 :
# sys.exit("Error: time needs to be a positive number")
wait = 0
T = tx
for i in range(0,len(T)-1):
if t > T[i] and t < T[i+1]:
wai... | T = tx
return T[n-1] | identifier_body |
ca-multicore.py | #!/usr/bin/python
import numpy as np
from sklearn.metrics import mutual_info_score
import MDAnalysis
import os
import re
import math
import sys
from itertools import combinations_with_replacement,permutations
from concurrent.futures import ProcessPoolExecutor, Future, wait
usecpus = 10#how many cores to use
frms_num ... | def new_dihedral(p):
p0 = p[0]
p1 = p[1]
p2 = p[2]
p3 = p[3]
b0 = -1.0*(p1 - p0)
b1 = p2 - p1
b2 = p3 - p2
b1 /= np.linalg.norm(b1)
v = b0 - np.dot(b0, b1)*b1
w = b2 - np.dot(b2, b1)*b1
x = np.dot(v, w)
y = np.dot(np.cross(b1, v), w)
return np.degrees(np.arctan2(y, x)... | random_line_split | |
karma.conf.js | // Karma configuration
// Generated on Fri Nov 08 2013 09:25:16 GMT-0600 (Central Standard Time)
var util = require('../lib/grunt/utils.js');
var grunt = require('grunt');
module.exports = function(config) {
config.set({
// base path, that will be used to resolve files and exclude
basePath: '../',
// f... | 'src/js/**/*.js',
'src/features/**/js/**/*.js',
'test/unit/**/*.spec.js',
'src/features/**/test/**/*.spec.js',
'dist/release/ui-grid.css',
'.tmp/template.js' //templates
],
// list of files to exclude
exclude: [
],
// test results reporter to use
// poss... | 'lib/test/jquery.simulate.js',
'bower_components/lodash/dist/lodash.min.js',
'src/js/core/bootstrap.js', | random_line_split |
karma.conf.js | // Karma configuration
// Generated on Fri Nov 08 2013 09:25:16 GMT-0600 (Central Standard Time)
var util = require('../lib/grunt/utils.js');
var grunt = require('grunt');
module.exports = function(config) {
config.set({
// base path, that will be used to resolve files and exclude
basePath: '../',
// f... |
}; | {
var bs = grunt.option('browsers').split(/,/).map(function(b) { return b.trim(); });
config.browsers = bs;
} | conditional_block |
FacebookConnect.spec.ts | import {addProviders} from '@angular/core/testing'
import {testBootstrap, injectAsync, defaultProviders} from '../../../testing/Utils'
import {FacebookConnect} from './FacebookConnect'
import {Facebook} from 'ionic-native'
let testProviders: Array<any> = [
//custom providers
];
describe('FacebookConnect component',... |
this.clickButton()
})
}) | this.instance.onError.subscribe((ev) => {
expect(Facebook.login).toHaveBeenCalledTimes(1)
expect(this.instance.onFacebookCancel).toHaveBeenCalledTimes(1)
done()
}) | random_line_split |
stream.rs | //! Convenience wrapper for streams to switch between plain TCP and TLS at runtime.
//!
//! There is no dependency on actual TLS implementations. Everything like
//! `native_tls` or `openssl` will work as long as there is a TLS stream supporting standard
//! `Read + Write` traits.
use std::{
pin::Pin,
task::{C... |
}
impl<S: AsyncRead + AsyncWrite + Unpin> AsyncWrite for MaybeTlsStream<S> {
fn poll_write(
self: Pin<&mut Self>,
cx: &mut Context<'_>,
buf: &[u8],
) -> Poll<Result<usize, std::io::Error>> {
match self.get_mut() {
MaybeTlsStream::Plain(ref mut s) => Pin::new(s).poll... | {
match self.get_mut() {
MaybeTlsStream::Plain(ref mut s) => Pin::new(s).poll_read(cx, buf),
#[cfg(feature = "native-tls")]
MaybeTlsStream::NativeTls(s) => Pin::new(s).poll_read(cx, buf),
#[cfg(feature = "__rustls-tls")]
MaybeTlsStream::Rustls(s) => Pi... | identifier_body |
stream.rs | //! Convenience wrapper for streams to switch between plain TCP and TLS at runtime.
//!
//! There is no dependency on actual TLS implementations. Everything like
//! `native_tls` or `openssl` will work as long as there is a TLS stream supporting standard
//! `Read + Write` traits.
use std::{
pin::Pin,
task::{C... | match self.get_mut() {
MaybeTlsStream::Plain(ref mut s) => Pin::new(s).poll_shutdown(cx),
#[cfg(feature = "native-tls")]
MaybeTlsStream::NativeTls(s) => Pin::new(s).poll_shutdown(cx),
#[cfg(feature = "__rustls-tls")]
MaybeTlsStream::Rustls(s) => Pin::n... | fn poll_shutdown(
self: Pin<&mut Self>,
cx: &mut Context<'_>,
) -> Poll<Result<(), std::io::Error>> { | random_line_split |
stream.rs | //! Convenience wrapper for streams to switch between plain TCP and TLS at runtime.
//!
//! There is no dependency on actual TLS implementations. Everything like
//! `native_tls` or `openssl` will work as long as there is a TLS stream supporting standard
//! `Read + Write` traits.
use std::{
pin::Pin,
task::{C... | (self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), std::io::Error>> {
match self.get_mut() {
MaybeTlsStream::Plain(ref mut s) => Pin::new(s).poll_flush(cx),
#[cfg(feature = "native-tls")]
MaybeTlsStream::NativeTls(s) => Pin::new(s).poll_flush(cx),
#[c... | poll_flush | identifier_name |
ConfirmationModal.tsx | // Copyright 2019-2020 Signal Messenger, LLC
// SPDX-License-Identifier: AGPL-3.0-only
import * as React from 'react';
import classNames from 'classnames';
import { createPortal } from 'react-dom';
import {
ConfirmationDialog,
Props as ConfirmationDialogProps,
} from './ConfirmationDialog';
import { LocalizerType ... | document.removeEventListener('keydown', handler);
};
}, [onClose]);
const handleCancel = React.useCallback(
(e: React.MouseEvent) => {
if (e.target === e.currentTarget) {
onClose();
}
},
[onClose]
);
const handleKeyCancel = React.useCallback(
... | }
};
document.addEventListener('keydown', handler);
return () => { | random_line_split |
ConfirmationModal.tsx | // Copyright 2019-2020 Signal Messenger, LLC
// SPDX-License-Identifier: AGPL-3.0-only
import * as React from 'react';
import classNames from 'classnames';
import { createPortal } from 'react-dom';
import {
ConfirmationDialog,
Props as ConfirmationDialogProps,
} from './ConfirmationDialog';
import { LocalizerType ... |
};
document.addEventListener('keydown', handler);
return () => {
document.removeEventListener('keydown', handler);
};
}, [onClose]);
const handleCancel = React.useCallback(
(e: React.MouseEvent) => {
if (e.target === e.currentTarget) {
onClose();
... | {
onClose();
event.preventDefault();
event.stopPropagation();
} | conditional_block |
workflow.py | from orchestra.workflow import Step
from orchestra.workflow import Workflow
from simple_workflow.crawl import crawl_page
crawl_step = Step(
slug='crawl',
name='Web Crawling',
description='Find an awesome image on a website',
worker_type=Step.WorkerType.MACHINE,
creation_depends_on=[],
function... | user_interface={
'javascript_includes': [
'/static/simple_workflow/rate/js/modules.js',
'/static/simple_workflow/rate/js/controllers.js',
'/static/simple_workflow/rate/js/directives.js',
],
'stylesheet_includes': [],
'angular_module': 'simple_workf... | creation_depends_on=[crawl_step],
required_certifications=[],
review_policy={'policy': 'no_review'}, | random_line_split |
QueriesList.tsx | import React, { FC, useCallback } from 'react';
import dayjs from 'dayjs';
import { useTranslation } from 'react-i18next';
import {
QueriesTable,
Header,
QueriesTableBody,
QueriesTableHeader,
QueriesTableHeaderRow,
} from './QueriesList.styles';
import QueriesListItem from '../QueriesListItem';
import SortI... | else {
const sortDirection =
sortSettings.direction === 'ascending' ? 'descending' : 'ascending';
onSortQueries({ property, direction: sortDirection });
}
},
[sortSettings]
);
return (
<QueriesTable>
<QueriesTableHeader>
<QueriesTableHeaderRow>
<... | {
onSortQueries({ property, direction: 'ascending' });
} | conditional_block |
QueriesList.tsx | import React, { FC, useCallback } from 'react';
import dayjs from 'dayjs';
import { useTranslation } from 'react-i18next';
import {
QueriesTable,
Header,
QueriesTableBody,
QueriesTableHeader,
QueriesTableHeaderRow,
} from './QueriesList.styles';
import QueriesListItem from '../QueriesListItem';
import SortI... | paddingLeft={10}
paddingRight={20}
sortable
onClick={() => sortHandler('lastModifiedDate')}
data-testid="table-header-date"
>
<Heading>{t('queries_list.updated')}</Heading>
<SortIndicators
sortDirection={
... | <Heading>{t('queries_list.labels')}</Heading>
</Header>
<Header | random_line_split |
day-and-night.js | 'use babel';
import { CompositeDisposable } from 'atom';
import request from 'request'
import SolarCalc from 'solar-calc'
import _ from 'underscore-plus';
import MyConfig from './config-schema.json';
// Use raw API rather than navigator due to unavailability in Atom
const GEOLOCATION_API = 'https://maps.googleapis.co... | else {
reject({
reason: 'Unable to download page'
})
}
})
})
},
// Run general setup functions
setup(){
// Save the theme settings so aren't reloaded each time
daytime_themes = [
atom.config.get('day-and-night.Appearance.daytime_ui_theme'),
... | {
resolve(body)
} | conditional_block |
day-and-night.js | 'use babel';
import { CompositeDisposable } from 'atom';
import request from 'request'
import SolarCalc from 'solar-calc'
import _ from 'underscore-plus';
import MyConfig from './config-schema.json';
// Use raw API rather than navigator due to unavailability in Atom
const GEOLOCATION_API = 'https://maps.googleapis.co... | console.log(syntaxThemesEnum)
// Calculate the solar times
_this.sunTimes();
// Events subscribed to in atom's system can be easily cleaned up with a CompositeDisposable
_this.subscriptions = new CompositeDisposable();
// Register command that toggles
_this.subscriptions.add(atom.commands... | {
_this = this
_this.setup()
// TODO: Allow user configurable refresh interval
// TODO: Done, I think? Maybe check.
interval = atom.config.get('day-and-night.Activation.interval')
tock = setInterval(_this.tick, interval * 60 * 1000)
// Enumerate the theme options and set in config page
... | identifier_body |
day-and-night.js | 'use babel';
import { CompositeDisposable } from 'atom';
import request from 'request'
import SolarCalc from 'solar-calc'
import _ from 'underscore-plus';
import MyConfig from './config-schema.json';
// Use raw API rather than navigator due to unavailability in Atom
const GEOLOCATION_API = 'https://maps.googleapis.co... | ({ metadata: { name } }) {
return {
value: name,
description: getThemeTitle(name),
};
}
// From https://github.com/as-cii/theme-flux/blob/master/lib/theme-flux.js
const loadedThemes = atom.themes.getLoadedThemes();
const uiThemesEnum = loadedThemes
.filter(theme => theme.metadata.theme === 'ui')
.map(... | themeToConfigStringEnum | identifier_name |
day-and-night.js | 'use babel';
import { CompositeDisposable } from 'atom';
import request from 'request'
import SolarCalc from 'solar-calc'
import _ from 'underscore-plus';
import MyConfig from './config-schema.json'; | var day, sunset, sunrise, daytime_themes, nighttime_themes, lat, lng
// Attempting to resolve "this" issue
// suggestion implemented (roughly) from here:
// https://stackoverflow.com/questions/20279484/how-to-access-the-correct-this-context-inside-a-callback
var _this
// From https://github.com/qwtel/theme-flux-solar... |
// Use raw API rather than navigator due to unavailability in Atom
const GEOLOCATION_API = 'https://maps.googleapis.com/maps/api/browserlocation/json?browser=chromium&sensor=true'
// Global variables to be accessed and checked from functions | random_line_split |
gift_for_new.js | (uid){
if(isApp){
return 'user-info://'+uid;
}else{
return '/User/index/index/id/'+ uid +'.html';
}
}
//返回商品标签url
function tagUrl(id){
if(isApp){
return 'product-tag://'+id;
}else{
return '/HsCategories/tag_index/tag/'+ ... | random_line_split | ||
gift_for_new.js | 如果是app,领取中心url 卖家中心url 商品标签url都需要做处理,ajax headers携带身份不一样
var isApp = false;
var $isApp = $('.is_app');
var Authorization = $isApp.attr('authorization');
var uid = $isApp.attr('uid');
// var version = $isApp.attr('version');
var loginStatus = true;
if(Authorization && Authorization.length>0... | error: function(xhr, type){
console.log(xhr);
$(that).attr('loading','0');
}
});
} else {
$.ajax({
type: 'POST',
url: ApiBaseUrl + '/appv1/unfollow'... | r isAtten = $(this).data('isatten');
if(isAtten == 0){
$.ajax({
type: 'POST',
url: ApiBaseUrl + '/appv1/follow',
data: {
to_user_id:$(that).data('uid')
},
headers: ajax... | identifier_body |
gift_for_new.js | 如果是app,领取中心url 卖家中心url 商品标签url都需要做处理,ajax headers携带身份不一样
var isApp = false;
var $isApp = $('.is_app');
var Authorization = $isApp.attr('authorization');
var uid = $isApp.attr('uid');
// var version = $isApp.attr('version');
var loginStatus = true;
if(Authorization && Authorization.length>0... | tag://'+id;
}else{
return '/HsCategories/tag_index/tag/'+ id +'.html';
}
}
getCoupon();
//获取所有信息
function getCoupon(){
var url = ApiBaseUrl + '/appv6/coupon/newUserCouponList';
$.ajax({
type: "GET",
url: url,
dataType: 'j... | 'product- | identifier_name |
gift_for_new.js | 如果是app,领取中心url 卖家中心url 商品标签url都需要做处理,ajax headers携带身份不一样
var isApp = false;
var $isApp = $('.is_app');
var Authorization = $isApp.attr('authorization');
var uid = $isApp.attr('uid');
// var version = $isApp.attr('version');
var loginStatus = true;
if(Authorization && Authorization.length>0... | function initRecommendGoods(goods){
var html = '';
var good = {};
for(var i=0;i<goods.length;i++){
good = goods[i];
html+= '<li class="goods_li hs-cf">'
html+= '<a href="/Portal/HsArticle/index/id/'+ good.id +'.html" class="filepath" external>'
... | $(that).attr('data-isatten', 0).attr('isatten', 0);
$.toast('取消关注成功');
// }else{
// $.toast('操作失败');
// }
setTimeout(function(){
$(that).attr... | conditional_block |
selective.py | stdout
requirements:
- set as main display callback
short_description: only print certain tasks
version_added: "2.4"
description:
- This callback only prints tasks that have been tagged with `print_action` or that have failed.
This allows operators to focus on the tasks that provide... |
def colorize(msg, color):
"""Given a string add necessary codes to format the string."""
if DONT_COLORIZE:
return msg
else:
return '{0}{1}{2}'.format(COLORS[color], msg, COLORS['endc'])
class CallbackModule(CallbackBase):
"""selective.py callback plugin."""
CALLBACK_VERSION = 2... | """Return a dict of keys that differ with another config object."""
keys = set(prv.keys() + nxt.keys())
result = {}
for k in keys:
if prv.get(k) != nxt.get(k):
result[k] = (prv.get(k), nxt.get(k))
return result | identifier_body |
selective.py |
requirements:
- set as main display callback
short_description: only print certain tasks
version_added: "2.4"
description:
- This callback only prints tasks that have been tagged with `print_action` or that have failed.
This allows operators to focus on the tasks that provide value ... |
else:
indent_level = 4
if isinstance(host_or_item, dict):
if 'key' in host_or_item.keys():
host_or_item = host_or_item['key']
name = colorize(to_text(host_or_item), 'bold')
if error:
color = 'failed'
change... | indent_level = 0
name = colorize(host_or_item.name, 'not_so_bold') | conditional_block |
selective.py |
requirements:
- set as main display callback
short_description: only print certain tasks
version_added: "2.4"
description:
- This callback only prints tasks that have been tagged with `print_action` or that have failed.
This allows operators to focus on the tasks that provide value ... | (self, task, **kwargs):
"""Run when a task starts."""
self.last_task_name = task.get_name()
self.printed_last_task = False
def _print_task_result(self, result, error=False, **kwargs):
"""Run when a task finishes correctly."""
if 'print_action' in result._task.tags or error ... | v2_playbook_on_task_start | identifier_name |
selective.py | stdout
requirements:
- set as main display callback
short_description: only print certain tasks
version_added: "2.4"
description:
- This callback only prints tasks that have been tagged with `print_action` or that have failed.
This allows operators to focus on the tasks that provide... | return '\n'.join(result_lines)
def _print_diff(self, diff, indent_level):
if isinstance(diff, dict):
try:
diff = '\n'.join(difflib.unified_diff(diff['before'].splitlines(),
diff['after'].splitlines(),
... | lines = text.splitlines()
result_lines = []
for l in lines:
result_lines.append("{0}{1}".format(' ' * indent_level, l)) | random_line_split |
lib.rs | Defining reflectable struct types only requires wrapping the struct definition in
//! [`def!`](macro.def!.html):
//!
//! ```ignore
//! #[use_macro]
//! extern crate typeinfo;
//! use typeinfo::TypeInfo;
//!
//! def! {
//! #[derive(Debug)]
//! pub struct Color { r: u16, g: u16, b: u16, }
//!
//! #[derive(De... | (&self) -> usize {
match *self {
Type::Int8 | Type::UInt8 | Type::Bool => 1,
Type::Int16 | Type::UInt16 => 2,
Type::Int32 | Type::UInt32 | Type::Float32 | Type::Char => 4,
Type::Int64 | Type::UInt64 | Type::Float64 => 8,
Type::Array(ref ty, num) => ty.... | size | identifier_name |
lib.rs | //! Defining reflectable struct types only requires wrapping the struct definition in
//! [`def!`](macro.def!.html):
//!
//! ```ignore
//! #[use_macro]
//! extern crate typeinfo;
//! use typeinfo::TypeInfo;
//!
//! def! {
//! #[derive(Debug)]
//! pub struct Color { r: u16, g: u16, b: u16, }
//!
//! #[derive... | /// fixed-size array with POD elements
Array(Box<Type>, usize),
/// compound type whose fields are POD
Compound(Vec<Field>, usize),
}
impl Type {
/// Returns the total size of a type value in bytes.
pub fn size(&self) -> usize {
match *self {
Type::Int8 | Type::UInt8 | Type:... | random_line_split | |
vm.reducers.spec.ts | import { VirtualMachine } from '../../../vm';
import * as vmActions from './vm.actions';
import * as fromVM from './vm.reducers';
import * as mockData from '../../../../testutils/data/vitrual-machines';
import { virtualMachineTagKeys } from '../../../shared/services/tags/vm-tag-keys';
describe('VM listReducer', () => ... | });
}); | expect(finalTags.length).toBe(vm.tags.length + 1);
expect(addedTag).toEqual({ key: virtualMachineTagKeys.passwordTag, value: password }); | random_line_split |
AsyncFilterTable.js | /**
* Created by saf on 1/6/17.
*/
import React, {Component} from 'react';
import {observer} from 'mobx-react';
import {observable, computed} from 'mobx';
import * as Table from 'reactabular-table';
import * as search from 'searchtabular';
import * as resolve from 'table-resolver';
@observer
export default class As... | () {
return search.multipleColumns({
columns: this.resolvedColumns,
query: this.query
})(this.resolvedRows);
}
@computed get headerRows() {
return resolve.headerRows({columns: this.props.columns})
}
render() {
return (
<Table.Provider
className="table is-striped"
... | searchedRows | identifier_name |
AsyncFilterTable.js | /**
* Created by saf on 1/6/17.
*/
import React, {Component} from 'react';
import {observer} from 'mobx-react';
import {observable, computed} from 'mobx';
import * as Table from 'reactabular-table';
import * as search from 'searchtabular';
import * as resolve from 'table-resolver';
@observer
export default class As... |
onRow(row, {rowIndex}) {
return {
onClick: () => this.props.onSelectRow(this._data[rowIndex])
};
}
componentDidMount() {
this.fetch()
}
@computed get _data() {
return this.props.data.slice()
}
@computed get resolvedColumns() {
return resolve.columnChildren({columns: this.pro... | {
this.props.fetch()
} | identifier_body |
AsyncFilterTable.js | /**
* Created by saf on 1/6/17.
*/
import React, {Component} from 'react';
import {observer} from 'mobx-react';
import {observable, computed} from 'mobx';
import * as Table from 'reactabular-table';
import * as search from 'searchtabular';
import * as resolve from 'table-resolver';
@observer
export default class As... | }
@computed get resolvedColumns() {
return resolve.columnChildren({columns: this.props.columns});
}
@computed get resolvedRows() {
return resolve.resolve({
columns: this.resolvedColumns,
method: resolve.nested
})(this._data);
}
@computed get searchedRows() {
return search.mult... | }
@computed get _data() {
return this.props.data.slice() | random_line_split |
jquery.glob.fr-MC.js | (function($) {
var cultures = $.global.cultures,
en = cultures.en,
standard = en.calendars.standard,
culture = cultures["fr-MC"] = $.extend(true, {}, en, {
name: "fr-MC",
englishName: "French (Monaco)",
nativeName: "français (Principauté de Monaco)",
language:... | })(jQuery); | }, cultures["fr-MC"]);
culture.calendar = culture.calendars.standard; | random_line_split |
pack_dialog.ts | // Copyright 2016 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.
import 'chrome://resources/cr_elements/cr_button/cr_button.m.js';
import 'chrome://resources/cr_elements/cr_dialog/cr_dialog.m.js';
import 'chrome://resou... |
private onRootBrowse_() {
this.delegate.choosePackRootDirectory().then(path => {
if (path) {
this.set('packDirectory_', path);
}
});
}
private onKeyBrowse_() {
this.delegate.choosePrivateKeyPath().then(path => {
if (path) {
this.set('keyFile_', path);
}
}... | {
super.connectedCallback();
this.$.dialog.showModal();
} | identifier_body |
pack_dialog.ts | // Copyright 2016 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.
import 'chrome://resources/cr_elements/cr_button/cr_button.m.js';
import 'chrome://resources/cr_elements/cr_dialog/cr_dialog.m.js';
import 'chrome://resou... |
});
}
private onKeyBrowse_() {
this.delegate.choosePrivateKeyPath().then(path => {
if (path) {
this.set('keyFile_', path);
}
});
}
private onCancelTap_() {
this.$.dialog.cancel();
}
private onConfirmTap_() {
this.delegate.packExtension(
this.packDirectory_... | {
this.set('packDirectory_', path);
} | conditional_block |
pack_dialog.ts | // Copyright 2016 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.
import 'chrome://resources/cr_elements/cr_button/cr_button.m.js';
import 'chrome://resources/cr_elements/cr_dialog/cr_dialog.m.js';
import 'chrome://resou... |
private onRootBrowse_() {
this.delegate.choosePackRootDirectory().then(path => {
if (path) {
this.set('packDirectory_', path);
}
});
}
private onKeyBrowse_() {
this.delegate.choosePrivateKeyPath().then(path => {
if (path) {
this.set('keyFile_', path);
}
})... | this.$.dialog.showModal();
} | random_line_split |
pack_dialog.ts | // Copyright 2016 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.
import 'chrome://resources/cr_elements/cr_button/cr_button.m.js';
import 'chrome://resources/cr_elements/cr_dialog/cr_dialog.m.js';
import 'chrome://resou... | () {
this.delegate.packExtension(
this.packDirectory_, this.keyFile_, 0, this.onPackResponse_.bind(this));
}
/**
* @param response The response from request to pack an extension.
*/
private onPackResponse_(response:
chrome.developerPrivate.PackDirectoryResponse) {
... | onConfirmTap_ | identifier_name |
shatteredSunCleric.js | var cardFunctions = require('../cardFunctions')
var ent = require('../../entityManager');
var cardTags = require('../cardTags');
var Rune = require('../../RuneVM');
var DamageRune = require('../../runes/DamageRune');
var Options = require('../../createOptions')
var AddEnchantments = require("../../runes/AddEnchantment"... |
if(controller.hero.health < controller.hero.baseHealth)
{
var playOption = {
"option":Options.PLAY_CARD_TYPE,
"cardGuid":card.cardGuid,
"target":controller.guid
}
options.push(playOption... | {
var playOption = {
"option":Options.PLAY_CARD_TYPE,
"cardGuid":card.cardGuid,
"target":eneCont.guid
}
options.push(playOption);
} | conditional_block |
shatteredSunCleric.js | var cardFunctions = require('../cardFunctions')
var ent = require('../../entityManager');
var cardTags = require('../cardTags');
var Rune = require('../../RuneVM');
var DamageRune = require('../../runes/DamageRune');
var Options = require('../../createOptions')
var AddEnchantments = require("../../runes/AddEnchantment"... |
targets.forEach(function(element){
var playOption = {
"option":Options.PLAY_CARD_TYPE,
"cardGuid":card.cardGuid,
"target":element.cardGuid
}
options.push(playOption);
})
if(eneCont.hero.health < eneCont.hero.b... | var eneCont = ent.getOtherController(controller, state); | random_line_split |
Swipe.js | ( function ( M, $ ) {
/**
* Class to assist a view in implementing swipe gestures on a specific element
*
* @class Swipe
* @extends OO.EventEmitter
*
* Use this class in a view to help it do things on swipe gestures.
*
* 1. Initialize it in the constructor `initialize` and listen to the
* 'swipe-{u... |
OO.inheritClass( Swipe, OO.EventEmitter );
OO.mfExtend( Swipe, {
/**
* Constructor.
* @param {Number} minDistance minimal distance in pixel between touchstart and touchend
* to be recognized as a swipe event. Default: 200
*/
initialize: function ( minDistance ) {
this.minDistance = minDistance ||... | {
Swipe.super.apply( this, arguments );
this.initialize.apply( this, arguments );
} | identifier_body |
Swipe.js | ( function ( M, $ ) {
/**
* Class to assist a view in implementing swipe gestures on a specific element
*
* @class Swipe
* @extends OO.EventEmitter
*
* Use this class in a view to help it do things on swipe gestures.
*
* 1. Initialize it in the constructor `initialize` and listen to the
* 'swipe-{u... | () {
Swipe.super.apply( this, arguments );
this.initialize.apply( this, arguments );
}
OO.inheritClass( Swipe, OO.EventEmitter );
OO.mfExtend( Swipe, {
/**
* Constructor.
* @param {Number} minDistance minimal distance in pixel between touchstart and touchend
* to be recognized as a swipe event. Defau... | Swipe | identifier_name |
Swipe.js | ( function ( M, $ ) {
/**
* Class to assist a view in implementing swipe gestures on a specific element
*
* @class Swipe
* @extends OO.EventEmitter
*
* Use this class in a view to help it do things on swipe gestures.
*
* 1. Initialize it in the constructor `initialize` and listen to the
* 'swipe-{u... | * this.swipe.setElement( this.$el );
* // identify last thumbnail
* // ...
* }
* },
* } );
* </code>
*/
function Swipe() {
Swipe.super.apply( this, arguments );
this.initialize.apply( this, arguments );
}
OO.inheritClass( Swipe, OO.E... | * postRender: function () {
* if ( thumbs.length < 2 ) {
* this.$( '.prev, .next' ).remove();
* this.swipe.disable();
* } else { | random_line_split |
Swipe.js | ( function ( M, $ ) {
/**
* Class to assist a view in implementing swipe gestures on a specific element
*
* @class Swipe
* @extends OO.EventEmitter
*
* Use this class in a view to help it do things on swipe gestures.
*
* 1. Initialize it in the constructor `initialize` and listen to the
* 'swipe-{u... |
},
/**
* Set the element where swipe gestures should be recognized
* @param {jQuery.Object} $el jQuery element where we want to listen for swipe
* gestures.
*/
setElement: function ( $el ) {
// unbind all events from the old element
this._unbindTouchEvents();
// set the new element
this.$... | {
// select the correct direction for the next image
if ( this.startTouch.pageY < this.endTouch.pageY ) {
// swiped up
this.emit( 'swipe-up', ev );
} else {
// swiped down
this.emit( 'swipe-down', ev );
}
} | conditional_block |
club-model.ts | export enum CLUB_USER_STATUS {
MEMBER,
NOT_MEMBER,
PENDING
}
export class ClubModel {
public title: string;
public description: string;
public thumbnailURL: string;
public creationDate: object;
public admins: Array<string>;
public maxMembers: number;
public qntdMembers: number;... | () {
let jua = {};
for (let ua of this.admins) {
jua[ua] = true;
}
return {"title": this.title,
"description": this.description,
"thumbnailURL": this.thumbnailURL,
"creationDate": this.creationDate,
"maxMembers"... | toJSON | identifier_name |
club-model.ts | export enum CLUB_USER_STATUS {
MEMBER,
NOT_MEMBER,
PENDING
}
export class ClubModel {
public title: string;
public description: string;
public thumbnailURL: string;
public creationDate: object;
public admins: Array<string>;
public maxMembers: number;
public qntdMembers: number;... |
getClubKey = function(): string {
return this._clubKey;
}
setClubKey = function(key: string) {
this._clubKey = key;
}
setClubUserStatus(status: CLUB_USER_STATUS) {
this.clubUserStatus = status;
}
getClubUserStatus(): CLUB_USER_STATUS {
return this.clubUse... | {
this.clubUserStatus = CLUB_USER_STATUS.NOT_MEMBER;
this.admins = new Array<string>();
// There is always at least one admin.
this.qntdMembers = 1;
} | identifier_body |
club-model.ts | export enum CLUB_USER_STATUS {
MEMBER,
NOT_MEMBER,
PENDING
}
export class ClubModel {
public title: string;
public description: string;
public thumbnailURL: string;
public creationDate: object;
public admins: Array<string>;
public maxMembers: number;
public qntdMembers: number;... | }
getClubUserStatus(): CLUB_USER_STATUS {
return this.clubUserStatus;
}
public static toClubModel(jsonLike: any): ClubModel {
let club = new ClubModel();
club.title = jsonLike.title;
club.description = jsonLike.description;
club.thumbnailURL = jsonLike.thumbnail... | random_line_split | |
ApiClient2.js | 'use strict';
var request = require('request');
var utilities = require('./utilities');
var settings = require('../settings');
function | (baseUrl, token) {
this.__token = token || settings.access_token;
this.request = request.defaults({
baseUrl: baseUrl || settings.apiUrl,
proxy: settings.proxyUrl || process.env.HTTPS_PROXY || process.env.https_proxy
});
};
APIClient2.prototype.updateToken = function(token) {
this.__token = token;
};
APIClient... | APIClient2 | identifier_name |
ApiClient2.js | 'use strict';
var request = require('request');
var utilities = require('./utilities');
var settings = require('../settings');
function APIClient2(baseUrl, token) {
this.__token = token || settings.access_token;
this.request = request.defaults({
baseUrl: baseUrl || settings.apiUrl,
proxy: settings.proxyUrl || p... |
cb(null, body);
});
};
module.exports = APIClient2;
| {
return cb(new Error('Unable to list devices'));
} | conditional_block |
ApiClient2.js | 'use strict';
var request = require('request');
var utilities = require('./utilities');
var settings = require('../settings');
function APIClient2(baseUrl, token) {
this.__token = token || settings.access_token;
this.request = request.defaults({
baseUrl: baseUrl || settings.apiUrl,
proxy: settings.proxyUrl || p... | APIClient2.prototype.clearToken = function() {
this.__token = null;
};
APIClient2.prototype.login = function(clientId, user, pass, cb) {
this.createAccessToken(clientId, user, pass, function tokenResponse(err, dat) {
if (err) {
return cb(err);
}
cb(null, dat);
});
};
APIClient2.prototype.createUser = fun... | APIClient2.prototype.updateToken = function(token) {
this.__token = token;
};
| random_line_split |
ApiClient2.js | 'use strict';
var request = require('request');
var utilities = require('./utilities');
var settings = require('../settings');
function APIClient2(baseUrl, token) | ;
APIClient2.prototype.updateToken = function(token) {
this.__token = token;
};
APIClient2.prototype.clearToken = function() {
this.__token = null;
};
APIClient2.prototype.login = function(clientId, user, pass, cb) {
this.createAccessToken(clientId, user, pass, function tokenResponse(err, dat) {
if (err) {
r... | {
this.__token = token || settings.access_token;
this.request = request.defaults({
baseUrl: baseUrl || settings.apiUrl,
proxy: settings.proxyUrl || process.env.HTTPS_PROXY || process.env.https_proxy
});
} | identifier_body |
about.ts | import { Component } from '@angular/core';
import { NavController, NavParams } from 'ionic-angular';
import { LoadingController } from 'ionic-angular';
import { ContactSource } from "../../providers/contactsource";
import { RedAlert } from "../../components/redalert";
@Component({
selector: 'page-about',
templ... | } | random_line_split | |
about.ts | import { Component } from '@angular/core';
import { NavController, NavParams } from 'ionic-angular';
import { LoadingController } from 'ionic-angular';
import { ContactSource } from "../../providers/contactsource";
import { RedAlert } from "../../components/redalert";
@Component({
selector: 'page-about',
templ... | () {
let loaderIndicator = this.loadingCtrl.create({
content: "Загрузка..."
});
loaderIndicator.present();
this.contactSource.get().then(
data => {
if (data.success) {
//console.log(data);
if (data.data.lengt... | getContacts | identifier_name |
about.ts | import { Component } from '@angular/core';
import { NavController, NavParams } from 'ionic-angular';
import { LoadingController } from 'ionic-angular';
import { ContactSource } from "../../providers/contactsource";
import { RedAlert } from "../../components/redalert";
@Component({
selector: 'page-about',
templ... | }
loaderIndicator.dismiss();
},
error => {
this.redAlert.show(this.navCtrl, error);
loaderIndicator.dismiss();
}
);
}
}
| this.all = data.data;
}
| conditional_block |
about.ts | import { Component } from '@angular/core';
import { NavController, NavParams } from 'ionic-angular';
import { LoadingController } from 'ionic-angular';
import { ContactSource } from "../../providers/contactsource";
import { RedAlert } from "../../components/redalert";
@Component({
selector: 'page-about',
templ... |
getContacts() {
let loaderIndicator = this.loadingCtrl.create({
content: "Загрузка..."
});
loaderIndicator.present();
this.contactSource.get().then(
data => {
if (data.success) {
//console.log(data);
if... | {
this.getContacts();
} | identifier_body |
hero-search.component.ts | import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { Observable } from 'rxjs/Observable';
import { Subject } from 'rxjs/Subject';
// import 'rxjs/add/operator/debounceTime';
import '../rxjs-extensions';
import { HeroSearchService } from '.... | (private heroSearchService: HeroSearchService,
private router: Router) {
}
// Push a search term into the observable stream.
search(term: string): void {
console.log(term);
this.searchTerms.next(term);
}
ngOnInit(): void {
this.heroes = this.searchTerms
.debounceTime(300) ... | constructor | identifier_name |
hero-search.component.ts | import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { Observable } from 'rxjs/Observable';
import { Subject } from 'rxjs/Subject';
// import 'rxjs/add/operator/debounceTime';
import '../rxjs-extensions';
import { HeroSearchService } from '.... |
// Push a search term into the observable stream.
search(term: string): void {
console.log(term);
this.searchTerms.next(term);
}
ngOnInit(): void {
this.heroes = this.searchTerms
.debounceTime(300) // wait for 300ms pause in events
.distinctUntilChanged() // ignore if next s... | {
} | identifier_body |
hero-search.component.ts | import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { Observable } from 'rxjs/Observable';
import { Subject } from 'rxjs/Subject';
// import 'rxjs/add/operator/debounceTime';
import '../rxjs-extensions';
import { HeroSearchService } from '.... | }
} | random_line_split | |
ranking.service.ts | /BehaviorSubject';
import { TranslateService } from '@ngx-translate/core';
import { environment } from '../../environments/environment';
import { REGIONS } from './ranking-regions';
import { RankingLocation } from './ranking-location';
export class RankingEvictor {
plaintiff: string;
placeId?: string; // optional... | (sortProperty: string, invert?: boolean): Array<RankingLocation> {
return this.evictions.sort(this.getComparator(sortProperty, invert));
}
/**
* Sorts and returns the full dataset by sortProperty
* @param sortProperty
* @param invert
*/
getSortedEvictors(sortProperty: string, invert?: boolean): A... | getSortedEvictions | identifier_name |
ranking.service.ts | ;
placeId?: string; // optional for now, not in the mock data
placeName: string;
renterHomes: number;
filings: number;
evictions: number;
evictionRate: number;
filingRate: number;
}
@Injectable()
export class RankingService {
year = environment.rankingsYear;
regions: Object = REGIONS;
regionList: A... | if (t.langKey) { t['name'] = rankings[t.langKey.split('.')[1]]; }
return t;
});
} | random_line_split | |
ranking.service.ts | BehaviorSubject';
import { TranslateService } from '@ngx-translate/core';
import { environment } from '../../environments/environment';
import { REGIONS } from './ranking-regions';
import { RankingLocation } from './ranking-location';
export class RankingEvictor {
plaintiff: string;
placeId?: string; // optional ... |
/** Set the ready status for the service */
setReady(isReady: boolean) {
this.ready.next(isReady);
}
/**
* Sorts and returns the full dataset by sortProperty
* @param sortProperty
* @param invert
*/
getSortedEvictions(sortProperty: string, invert?: boolean): Array<RankingLocation> {
ret... | {
return this.http.get(this.config.stateUrl, { responseType: 'text' })
.map((csvString) => this.parseEvictionsData(csvString))
.subscribe(locations => this.stateData = locations);
} | identifier_body |
_steps.js | var locastyle = locastyle || {};
locastyle.steps = (function() {
'use strict';
var config = {
selectors: {
moduleActive: '.ls-actived [data-ls-module="steps"]',
nav: '.ls-steps-nav',
button: '.ls-steps-btn',
container: '.ls-steps-content',
steps: '.ls-steps',
moduleVisible:... | () {
$(config.selectors.nav).on("click.steps", config.selectors.moduleActive, function(evt) {
evt.preventDefault();
changeStep($(this));
});
}
// Bind the target to cal the nextStep on click
function bindNextStep() {
$(config.actions.next).on('click.steps', function(evt) {
evt.preve... | bindClickOnTriggers | identifier_name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.