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 |
|---|---|---|---|---|
GeneratorTest.py | # Copyright (c) 2011 Nokia
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, s... | unittest.main() | conditional_block | |
GeneratorTest.py | # Copyright (c) 2011 Nokia
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, s... |
# Register some types
self.library.typeMap["int"] = "int"
self.library.typeMap["void"] = "void"
# Define platform properties
self.platform = SymbianPlatform(self.config)
def testCheetah(self):
t = Template("Hello, $who!")
t.who = "World"
self.assertEquals(str(t), "Hello,... | self.config = Config.Config()
self.config["library"] = "testlib"
# Create a basic library for testing
self.library = Library.Library("test")
voidType = Library.Type("void")
intType = Library.Type("int")
f = Library.Function("func1", voidType)
p = Library.Parameter("parameter"... | identifier_body |
GeneratorTest.py | # Copyright (c) 2011 Nokia
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, s... | (self):
# Parse the preprocessed GL header
l = Library.Library("GL", "libgles_cm_orig.dll")
l.merge(Parser.parseSource(open("data/gl-cpp.h").read()))
l.merge(Parser.parseSource(open("data/egl-cpp.h").read()))
defFile = open("data/opengles11u.def").read()
for function, ordinal in Parser.parseDefF... | testGlTracerGeneration | identifier_name |
GeneratorTest.py | # Copyright (c) 2011 Nokia
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, s... | def testGlTracerGeneration(self):
# Parse the preprocessed GL header
l = Library.Library("GL", "libgles_cm_orig.dll")
l.merge(Parser.parseSource(open("data/gl-cpp.h").read()))
l.merge(Parser.parseSource(open("data/egl-cpp.h").read()))
defFile = open("data/opengles11u.def").read()
for function,... | g = TracerGenerator(self.config, self.platform, [self.library])
o = StringIO()
g.generate(outputFile = o)
| random_line_split |
Navigation.js | $p.currentIndex = function (array) {
return array.indexOf($('#Id').val())
}
$p.switchTargets = function () {
var $control = $('#SwitchTargets');
return $control.length === 1
? $control.val().split(',')
: [];
}
$p.setSwitchTargets = function () {
var $control = $('#SwitchTargets');
... | $('#CurrentIndex').hide();
$('#Next').hide();
}
}
$p.back = function () {
var $control = $('#BackUrl');
if ($control.length === 1) {
location.href = $control.val();
}
} | $('#Previous').hide(); | random_line_split |
Navigation.js | $p.currentIndex = function (array) {
return array.indexOf($('#Id').val())
}
$p.switchTargets = function () {
var $control = $('#SwitchTargets');
return $control.length === 1
? $control.val().split(',')
: [];
}
$p.setSwitchTargets = function () {
var $control = $('#SwitchTargets');
... |
$p.setCurrentIndex = function () {
var array = $p.switchTargets();
if (array.length > 1) {
var index = $p.currentIndex(array);
$('#CurrentIndex').text(index + 1 + '/' + array.length);
} else {
$('#Previous').hide();
$('#CurrentIndex').hide();
$('#Next').hide();
... | $control.appendTo('body');
$p.setCurrentIndex();
}
} | conditional_block |
TypeSubjectFromRIFCS.py | # TypeSubjectFromRIFCS.py takes input xml in RIFCS format and outputs subjectType and subjectText to .csv file per line as:
# subjectType|subjectText
#
#
#Usage: TypeSubjectFromRIFCS.py [options] arg1
#
#Options:
# -h, --help show this help message and exit
# --input_xml=INPUT_XML
# ... |
def openFile(fileName, mode):
file = open(("output/"+fileName), mode)
if file is None:
print("Unable to open file %s for %s" % (fileName, mode))
os.sys.exit(-1)
print("Opened file %s for %s" % (fileName, mode))
return file
usage = "usage: %prog [options] arg1"
parser = Op... | from xml.etree import ElementTree as ET
from xml.etree.ElementTree import parse
| random_line_split |
TypeSubjectFromRIFCS.py | # TypeSubjectFromRIFCS.py takes input xml in RIFCS format and outputs subjectType and subjectText to .csv file per line as:
# subjectType|subjectText
#
#
#Usage: TypeSubjectFromRIFCS.py [options] arg1
#
#Options:
# -h, --help show this help message and exit
# --input_xml=INPUT_XML
# ... |
print("Opened file %s for %s" % (fileName, mode))
return file
usage = "usage: %prog [options] arg1"
parser = OptionParser(usage=usage)
parser.add_option("--input_xml", action="store", dest="input_xml", help="e.g ExampleRIFCS.xml - xml in RIFCS format")
(options, args) = parser.parse_args()
# Va... | print("Unable to open file %s for %s" % (fileName, mode))
os.sys.exit(-1) | conditional_block |
TypeSubjectFromRIFCS.py | # TypeSubjectFromRIFCS.py takes input xml in RIFCS format and outputs subjectType and subjectText to .csv file per line as:
# subjectType|subjectText
#
#
#Usage: TypeSubjectFromRIFCS.py [options] arg1
#
#Options:
# -h, --help show this help message and exit
# --input_xml=INPUT_XML
# ... | (fileName, mode):
file = open(("output/"+fileName), mode)
if file is None:
print("Unable to open file %s for %s" % (fileName, mode))
os.sys.exit(-1)
print("Opened file %s for %s" % (fileName, mode))
return file
usage = "usage: %prog [options] arg1"
parser = OptionParser(us... | openFile | identifier_name |
TypeSubjectFromRIFCS.py | # TypeSubjectFromRIFCS.py takes input xml in RIFCS format and outputs subjectType and subjectText to .csv file per line as:
# subjectType|subjectText
#
#
#Usage: TypeSubjectFromRIFCS.py [options] arg1
#
#Options:
# -h, --help show this help message and exit
# --input_xml=INPUT_XML
# ... |
usage = "usage: %prog [options] arg1"
parser = OptionParser(usage=usage)
parser.add_option("--input_xml", action="store", dest="input_xml", help="e.g ExampleRIFCS.xml - xml in RIFCS format")
(options, args) = parser.parse_args()
# Validate options
if not options.input_xml:
parser.error("Requires input_xml. Try... | file = open(("output/"+fileName), mode)
if file is None:
print("Unable to open file %s for %s" % (fileName, mode))
os.sys.exit(-1)
print("Opened file %s for %s" % (fileName, mode))
return file | identifier_body |
middleware.py | from django.conf import settings
from django.contrib.auth.models import AnonymousUser
from threading import local
USER_ATTR_NAME = getattr(settings, 'LOCAL_USER_ATTR_NAME', '_current_user')
_thread_locals = local()
def _do_set_current_user(user_fun):
setattr(_thread_locals, USER_ATTR_NAME, user_fun.__get__(user... |
return current_user
def get_current_authenticated_user():
current_user = get_current_user()
if isinstance(current_user, AnonymousUser):
return None
return current_user
| return current_user() | conditional_block |
middleware.py | from django.conf import settings
from django.contrib.auth.models import AnonymousUser
from threading import local
USER_ATTR_NAME = getattr(settings, 'LOCAL_USER_ATTR_NAME', '_current_user')
_thread_locals = local()
def _do_set_current_user(user_fun):
setattr(_thread_locals, USER_ATTR_NAME, user_fun.__get__(user... | class ThreadLocalUserMiddleware(object):
def __init__(self, get_response):
self.get_response = get_response
def __call__(self, request):
# request.user closure; asserts laziness;
# memorization is implemented in
# request.user (non-data descriptor)
_do_set_current_user(... | '''
_do_set_current_user(lambda self: user)
| random_line_split |
middleware.py | from django.conf import settings
from django.contrib.auth.models import AnonymousUser
from threading import local
USER_ATTR_NAME = getattr(settings, 'LOCAL_USER_ATTR_NAME', '_current_user')
_thread_locals = local()
def _do_set_current_user(user_fun):
setattr(_thread_locals, USER_ATTR_NAME, user_fun.__get__(user... | ():
current_user = get_current_user()
if isinstance(current_user, AnonymousUser):
return None
return current_user
| get_current_authenticated_user | identifier_name |
middleware.py | from django.conf import settings
from django.contrib.auth.models import AnonymousUser
from threading import local
USER_ATTR_NAME = getattr(settings, 'LOCAL_USER_ATTR_NAME', '_current_user')
_thread_locals = local()
def _do_set_current_user(user_fun):
|
def _set_current_user(user=None):
'''
Sets current user in local thread.
Can be used as a hook e.g. for shell jobs (when request object is not
available).
'''
_do_set_current_user(lambda self: user)
class ThreadLocalUserMiddleware(object):
def __init__(self, get_response):
sel... | setattr(_thread_locals, USER_ATTR_NAME, user_fun.__get__(user_fun, local)) | identifier_body |
get_nn.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
import numpy as np
import matplotlib.pyplot as plt
import matplotlib
import scipy
from sklearn.neighbors import KNeighborsClassifier
from scipy.cluster import hierarchy as hier
from scipy.spatial import distance
import json
import codecs
import sys
if le... |
print "Start"
fi = codecs.open(sys.argv[1],"r","utf-8")
words = []
data = []
for line in fi:
if not len(line.strip()): continue
k = line.strip().split()
words.append(k[0])
data.append([float(i) for i in k[-200:]])
fi.close()
vectors = np.array(data)
print "Pre-processing done"
# Calculate the distance matri... | out_file = sys.argv[2] | conditional_block |
get_nn.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
import numpy as np
import matplotlib.pyplot as plt
import matplotlib
import scipy | from sklearn.neighbors import KNeighborsClassifier
from scipy.cluster import hierarchy as hier
from scipy.spatial import distance
import json
import codecs
import sys
if len(sys.argv) < 2:
print "Provide file name"
sys.exit(1)
elif len(sys.argv) < 3:
out_file = "nn9m.dat"
else:
out_file = sys.argv[2]
print "Start... | random_line_split | |
get_nn.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
import numpy as np
import matplotlib.pyplot as plt
import matplotlib
import scipy
from sklearn.neighbors import KNeighborsClassifier
from scipy.cluster import hierarchy as hier
from scipy.spatial import distance
import json
import codecs
import sys
if le... |
knn = KNeighborsClassifier()
knn.fit(vectors,[0]*len(vectors))
fo = codecs.open(out_file,"w","utf-8")
for i,word in enumerate(words):
d,n = knn.kneighbors(vectors[i], n_neighbors = 25, return_distance = True)
if i%1000==0: print d,n
fo.write(word+"\t")
for j in range(1,len(n[0])):
fo.write(words[n[0][j]]+" ({:... | return np.dot(x,y) | identifier_body |
get_nn.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
import numpy as np
import matplotlib.pyplot as plt
import matplotlib
import scipy
from sklearn.neighbors import KNeighborsClassifier
from scipy.cluster import hierarchy as hier
from scipy.spatial import distance
import json
import codecs
import sys
if le... | (x,y):
return np.dot(x,y)
knn = KNeighborsClassifier()
knn.fit(vectors,[0]*len(vectors))
fo = codecs.open(out_file,"w","utf-8")
for i,word in enumerate(words):
d,n = knn.kneighbors(vectors[i], n_neighbors = 25, return_distance = True)
if i%1000==0: print d,n
fo.write(word+"\t")
for j in range(1,len(n[0])):
fo.... | dist | identifier_name |
test_base_client.py | import requests
import httpretty
from nose.tools import nottest
from pyrelic import BaseClient
@nottest # Skip until we can properly simulate timeouts
@httpretty.activate
def test_make_request_timeout():
"""
Remote calls should time out
"""
httpretty.register_uri(httpretty.GET, "www.example.com",
... | ():
"""
Base Client should parse proxy dicts
"""
# When I create a client with a proxy as a dict
proxy = {"baz": "1234"}
c = BaseClient(proxy=proxy)
# Then the Client should create the proxy config as a dictionary
c.proxy.should.equal(proxy)
| test_client_proxy_dict | identifier_name |
test_base_client.py | import requests
import httpretty
from nose.tools import nottest
from pyrelic import BaseClient
@nottest # Skip until we can properly simulate timeouts
@httpretty.activate
def test_make_request_timeout():
"""
Remote calls should time out
"""
httpretty.register_uri(httpretty.GET, "www.example.com",
... |
def test_client_proxy_dict():
"""
Base Client should parse proxy dicts
"""
# When I create a client with a proxy as a dict
proxy = {"baz": "1234"}
c = BaseClient(proxy=proxy)
# Then the Client should create the proxy config as a dictionary
c.proxy.should.equal(proxy)
| """
Base Client should parse proxy strings
"""
# When I create a client with a proxy as a string
proxy = "baz:1234"
c = BaseClient(proxy=proxy)
# Then the Client should create the proxy config as a dictionary
c.proxy.should.equal({"http": proxy, "https": proxy}) | identifier_body |
test_base_client.py | import requests
import httpretty
from nose.tools import nottest
from pyrelic import BaseClient
@nottest # Skip until we can properly simulate timeouts
@httpretty.activate
def test_make_request_timeout():
"""
Remote calls should time out
"""
httpretty.register_uri(httpretty.GET, "www.example.com",
... | Bad HTTP Responses should throw an error
"""
httpretty.register_uri(httpretty.GET, "http://foobar.com",
body="123", status=400)
# When I make an API request and receive a 400
c = BaseClient()
# Then I should raise the appropriate requests exception
c._make_request... |
@httpretty.activate
def test_make_request_non_200():
""" | random_line_split |
workbook.py | # file openpyxl/workbook.py
# Copyright (c) 2010-2011 openpyxl
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, ... |
return requested_range
def remove_named_range(self, named_range):
"""Remove a named_range from this workbook."""
self._named_ranges.remove(named_range)
def save(self, filename):
"""Save the current workbook under the given `filename`.
Use this function instead of using... | requested_range = named_range
break | conditional_block |
workbook.py | # file openpyxl/workbook.py
# Copyright (c) 2010-2011 openpyxl
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, ... | return [s.title for s in self.worksheets]
def create_named_range(self, name, worksheet, range, scope=None):
"""Create a new named_range on a worksheet"""
assert isinstance(worksheet, self._worksheet_class)
named_range = NamedRange(name, [(worksheet, range)], scope)
self.add_... |
""" | random_line_split |
workbook.py | # file openpyxl/workbook.py
# Copyright (c) 2010-2011 openpyxl
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, ... | (self, optimized_write=False, encoding='utf-8',
worksheet_class=Worksheet,
optimized_worksheet_class=DumpWorksheet,
guess_types=True):
self.worksheets = []
self._active_sheet_index = 0
self._named_ranges = []
self.properties = DocumentPr... | __init__ | identifier_name |
workbook.py | # file openpyxl/workbook.py
# Copyright (c) 2010-2011 openpyxl
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, ... |
def _set_optimized_read(self):
self.__optimized_read = True
def get_active_sheet(self):
"""Returns the current active sheet."""
return self.worksheets[self._active_sheet_index]
def create_sheet(self, index=None, title=None):
"""Create a worksheet (at an optional index).
... | return self.properties.excel_base_date | identifier_body |
facet-typeahead-list.component.ts | import { Component } from '@angular/core';
import { Facet } from '@ux-aspects/ux-aspects';
import 'chance';
import { Observable, Observer } from 'rxjs';
import { BaseDocumentationSection } from '../../../../../components/base-documentation-section/base-documentation-section';
import { DocumentationSectionComponent } fr... |
if (userOne.title > userTwo.title) {
return 1;
}
return 0;
});
// present the top 6 items as suggestions
this.suggestions = this.users.slice(0, 6);
// Create an observable which can be used for fetching data from server
this... | return -1;
} | random_line_split |
facet-typeahead-list.component.ts | import { Component } from '@angular/core';
import { Facet } from '@ux-aspects/ux-aspects';
import 'chance';
import { Observable, Observer } from 'rxjs';
import { BaseDocumentationSection } from '../../../../../components/base-documentation-section/base-documentation-section';
import { DocumentationSectionComponent } fr... |
// sort the users alphabetically
this.users.sort((userOne, userTwo) => {
if (userOne.title < userTwo.title) {
return -1;
}
if (userOne.title > userTwo.title) {
return 1;
}
return 0;
});
// pr... | {
this.users.push(new Facet(chance.name(), null, chance.integer({ min: 0, max: 100 })));
} | conditional_block |
facet-typeahead-list.component.ts | import { Component } from '@angular/core';
import { Facet } from '@ux-aspects/ux-aspects';
import 'chance';
import { Observable, Observer } from 'rxjs';
import { BaseDocumentationSection } from '../../../../../components/base-documentation-section/base-documentation-section';
import { DocumentationSectionComponent } fr... |
// present the top 6 items as suggestions
this.suggestions = this.users.slice(0, 6);
// Create an observable which can be used for fetching data from server
this.facets = Observable.create((observer: Observer<Facet[]>) => {
// simulate server request
setTimeout(... | {
super(require.context('./snippets/', false, /\.(html|css|js|ts)$/));
// generate random facet data
for (let idx = 0; idx < 1000; idx++) {
this.users.push(new Facet(chance.name(), null, chance.integer({ min: 0, max: 100 })));
}
// sort the users alphabetically
... | identifier_body |
facet-typeahead-list.component.ts | import { Component } from '@angular/core';
import { Facet } from '@ux-aspects/ux-aspects';
import 'chance';
import { Observable, Observer } from 'rxjs';
import { BaseDocumentationSection } from '../../../../../components/base-documentation-section/base-documentation-section';
import { DocumentationSectionComponent } fr... | () {
super(require.context('./snippets/', false, /\.(html|css|js|ts)$/));
// generate random facet data
for (let idx = 0; idx < 1000; idx++) {
this.users.push(new Facet(chance.name(), null, chance.integer({ min: 0, max: 100 })));
}
// sort the users alphabetically
... | constructor | identifier_name |
floatingip.py | # Copyright 2016 Sungard Availability Services
# Copyright 2016 Red Hat
# Copyright 2012 eNovance <licensing@enovance.com>
# Copyright 2013 IBM Corp
# 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 obtai... | (plugin_base.PollsterBase):
STATUS = {
'inactive': 0,
'active': 1,
'pending_create': 2,
}
def __init__(self):
self.neutron_cli = neutron_client.Client()
@property
def default_discovery(self):
return 'endpoint:%s' % cfg.CONF.service_types.neutron
@stati... | FloatingIPPollster | identifier_name |
floatingip.py | # Copyright 2016 Sungard Availability Services
# Copyright 2016 Red Hat
# Copyright 2012 eNovance <licensing@enovance.com>
# Copyright 2013 IBM Corp
# 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 obtai... | for fip in self.neutron_cli.fip_get_all():
status = self.STATUS.get(fip['status'].lower())
if status is None:
LOG.warning(_LW("Invalid status, skipping IP address %s") %
fip['floating_ip_address'])
continue
res_metadata = se... | identifier_body | |
floatingip.py | # Copyright 2016 Sungard Availability Services
# Copyright 2016 Red Hat
# Copyright 2012 eNovance <licensing@enovance.com>
# Copyright 2013 IBM Corp
# 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 obtai... | resource_metadata=res_metadata
) | random_line_split | |
floatingip.py | # Copyright 2016 Sungard Availability Services
# Copyright 2016 Red Hat
# Copyright 2012 eNovance <licensing@enovance.com>
# Copyright 2013 IBM Corp
# 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 obtai... | status = self.STATUS.get(fip['status'].lower())
if status is None:
LOG.warning(_LW("Invalid status, skipping IP address %s") %
fip['floating_ip_address'])
continue
res_metadata = self._form_metadata_for_fip(fip)
yield sample... | conditional_block | |
lib.rs | //! Isbfc is an optimizing brainfuck compiler targeting x86_64 Linux
//!
//! # Examples
//! ```
//! extern crate isbfc;
//!
//! fn main() {
//! // 2048 is the tape length to use
//! let assembly = isbfc::parse(",[.,]").unwrap().optimize().compile(2048);
//! print!("{}", assembly);
//! }
//! ```
use std::fm... |
}
fn ast_to_tokens(ast: Vec<AST>) -> Vec<Token> {
let mut tokens = Vec::new();
for i in ast {
match i {
AST::Output => {
tokens.push(Token::LoadOut(0, 0));
tokens.push(Token::Output);
},
AST::Input => tokens.push(Token::Input),
... | {
self.tokens.fmt(f)
} | identifier_body |
lib.rs | //! Isbfc is an optimizing brainfuck compiler targeting x86_64 Linux
//!
//! # Examples
//! ```
//! extern crate isbfc;
//!
//! fn main() {
//! // 2048 is the tape length to use
//! let assembly = isbfc::parse(",[.,]").unwrap().optimize().compile(2048);
//! print!("{}", assembly);
//! }
//! ```
use std::fm... | (ast: Vec<AST>) -> Self {
IsbfcIR {
tokens: ast_to_tokens(ast)
}
}
}
| from_ast | identifier_name |
lib.rs | //! Isbfc is an optimizing brainfuck compiler targeting x86_64 Linux
//!
//! # Examples
//! ```
//! extern crate isbfc;
//!
//! fn main() {
//! // 2048 is the tape length to use
//! let assembly = isbfc::parse(",[.,]").unwrap().optimize().compile(2048);
//! print!("{}", assembly);
//! }
//! ```
use std::fm... | impl IsbfcIR {
pub fn from_ast(ast: Vec<AST>) -> Self {
IsbfcIR {
tokens: ast_to_tokens(ast)
}
}
} | }
| random_line_split |
test_k_hardwoodspecies.py | import io
import unittest
from unittest.mock import patch
from kattis import k_hardwoodspecies
###############################################################################
class | (unittest.TestCase):
'''Problem statement sample inputs and outputs'''
def test_sample_input(self):
'''Run and assert problem statement sample input and output.'''
inputs = '''
Red Alder
Ash
Aspen
Basswood
Ash
Beech
Yellow Birch
Ash
Cherry
Cottonwood
Ash
Cypress
Red Elm
Gum
Hackberry
White Oak
... | SampleInput | identifier_name |
test_k_hardwoodspecies.py | import io
import unittest
from unittest.mock import patch
from kattis import k_hardwoodspecies
###############################################################################
class SampleInput(unittest.TestCase):
'''Problem statement sample inputs and outputs'''
def test_sample_input(self):
| Hard Maple
White Oak
Soft Maple
Red Oak
Red Oak
White Oak
Poplan
Sassafras
Sycamore
Black Walnut
Willow
'''
outputs = '''
Ash 13.793103
Aspen 3.448276
Basswood 3.448276
Beech 3.448276
Black Walnut 3.448276
Cherry 3.448276
Cottonwood 3.448276
Cypress 3.448276
Gum 3.448276
Hackberry 3.448276
Hard Maple 3.448276
... | '''Run and assert problem statement sample input and output.'''
inputs = '''
Red Alder
Ash
Aspen
Basswood
Ash
Beech
Yellow Birch
Ash
Cherry
Cottonwood
Ash
Cypress
Red Elm
Gum
Hackberry
White Oak
Hickory
Pecan | identifier_body |
test_k_hardwoodspecies.py | import io
import unittest
from unittest.mock import patch
from kattis import k_hardwoodspecies
###############################################################################
class SampleInput(unittest.TestCase):
'''Problem statement sample inputs and outputs'''
def test_sample_input(self):
'''Run an... | unittest.main() | conditional_block | |
test_k_hardwoodspecies.py | import io
import unittest
from unittest.mock import patch
from kattis import k_hardwoodspecies
###############################################################################
class SampleInput(unittest.TestCase):
'''Problem statement sample inputs and outputs'''
| inputs = '''
Red Alder
Ash
Aspen
Basswood
Ash
Beech
Yellow Birch
Ash
Cherry
Cottonwood
Ash
Cypress
Red Elm
Gum
Hackberry
White Oak
Hickory
Pecan
Hard Maple
White Oak
Soft Maple
Red Oak
Red Oak
White Oak
Poplan
Sassafras
Sycamore
Black Walnut
Willow
'''
outputs = '''
Ash 13.793103
Aspen 3.448276
Basswoo... | def test_sample_input(self):
'''Run and assert problem statement sample input and output.''' | random_line_split |
NewApacheConfig.js | this.getApacheConfigWin().set({
showMinimize: true,
allowMinimize: false,
allowMaximize: true
});
this.getApacheConfigWin().setSpace( 200, 400, 0, 450 ); // left spacing // width // top spacing // height
this.getApacheConfigWin().removeAll()... | {
// Invoke callback method to refresh browser table
this.getCallback()( this.getParentDn() );
// Update the status bar
this.getWireFrame()._setStatusText( "Ready" );
// Close the add repository window
this.getApacheConfigWin().close();
... | conditional_block | |
NewApacheConfig.js | view.ListView)
#require(qx.io.remote.Rpc);
************************************************************************ */
qx.Class.define( "packages.com.makeabyte.vhf.ldapbrowser.ui.NewApacheConfig", {
extend : vhf.Main,
properties : {
WireFrame : { init : vhf.Main.getInstance() },
ApacheConfig... | random_line_split | ||
CodeFormatter.py | # @author Avtandil Kikabidze
# @copyright Copyright (c) 2008-2015, Avtandil Kikabidze aka LONGMAN (akalongman@gmail.com)
# @link http://longman.me
# @license The MIT License (MIT)
import os
import sys
import sublime
import sublime_plugin
st_version = 2
if sublime.version() == '... |
class CodeFormatterOpenTabsCommand(sublime_plugin.TextCommand):
def run(self, edit, syntax=None):
window = sublime.active_window()
for view in window.views():
run_formatter(view, edit, quiet=True)
class CodeFormatterEventListener(sublime_plugin.EventListener):
def on_pre_save(... | def run(self, edit, syntax=None, saving=None):
run_formatter(self.view, edit, syntax=syntax, saving=saving) | identifier_body |
CodeFormatter.py | # @author Avtandil Kikabidze
# @copyright Copyright (c) 2008-2015, Avtandil Kikabidze aka LONGMAN (akalongman@gmail.com)
# @link http://longman.me
# @license The MIT License (MIT)
import os
import sys
import sublime
import sublime_plugin
st_version = 2
if sublime.version() == '... | (self, edit, syntax=False):
import subprocess
import re
platform = sublime.platform()
settings = sublime.load_settings('CodeFormatter.sublime-settings')
opts = settings.get('codeformatter_php_options')
php_path = 'php'
if ('php_path' in opts and opts['php_path... | run | identifier_name |
CodeFormatter.py | # @author Avtandil Kikabidze
# @copyright Copyright (c) 2008-2015, Avtandil Kikabidze aka LONGMAN (akalongman@gmail.com)
# @link http://longman.me
# @license The MIT License (MIT)
import os
import sys
import sublime
import sublime_plugin
st_version = 2
if sublime.version() == '... |
else:
p = subprocess.Popen(
cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
stdout, stderr = p.communicate()
except Exception as e:
stderr = str(e)
if (not stderr and not stdout):
... | startupinfo = subprocess.STARTUPINFO()
startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
startupinfo.wShowWindow = subprocess.SW_HIDE
p = subprocess.Popen(
cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE,
stderr=subprocess.P... | conditional_block |
CodeFormatter.py | # @author Avtandil Kikabidze
# @copyright Copyright (c) 2008-2015, Avtandil Kikabidze aka LONGMAN (akalongman@gmail.com)
# @link http://longman.me
# @license The MIT License (MIT)
import os
import sys
import sublime
import sublime_plugin
st_version = 2
if sublime.version() == '... | if len(stderr) == 0 and len(stdout) > 0:
text = stdout.decode('utf-8')
text = re.sub(
'Usage:.*?PASSNAME', 'Available PHP Tranformations:', text)
window = self.view.window()
pt = window.get_output_panel('paneltranformations')
pt.set_rea... | stderr = 'Error while gethering list of php transformations'
| random_line_split |
release.model.ts | import { Model } from '../../model/model.service';
import { GameBuild } from '../build/build.model';
import { GamePackage } from '../package/package.model';
import { Game } from '../game.model';
export class GameRelease extends Model {
static readonly STATUS_HIDDEN = 'hidden';
static readonly STATUS_PUBLISHED = 'pub... |
get isScheduled() {
return !!this.scheduled_for;
}
$save() {
if (!this.id) {
return this.$_save(
'/web/dash/developer/games/releases/save/' +
this.game_id +
'/' +
this.game_package_id,
'gameRelease'
);
} else {
return this.$_save(
'/web/dash/developer/games/releases/save/'... | // These fields get added only during GamePackagePayloadModel.
_package?: GamePackage;
_builds?: GameBuild[]; | random_line_split |
release.model.ts | import { Model } from '../../model/model.service';
import { GameBuild } from '../build/build.model';
import { GamePackage } from '../package/package.model';
import { Game } from '../game.model';
export class GameRelease extends Model {
static readonly STATUS_HIDDEN = 'hidden';
static readonly STATUS_PUBLISHED = 'pub... | }
async $publish(game: Game) {
const response = await this.$_save(
'/web/dash/developer/games/releases/publish/' +
this.game_id +
'/' +
this.game_package_id +
'/' +
this.id,
'gameRelease'
);
if (game && response.game) {
game.assign(response.game);
}
return response;
}
asy... | {
if (!this.id) {
return this.$_save(
'/web/dash/developer/games/releases/save/' +
this.game_id +
'/' +
this.game_package_id,
'gameRelease'
);
} else {
return this.$_save(
'/web/dash/developer/games/releases/save/' +
this.game_id +
'/' +
this.game_package_id +
... | identifier_body |
release.model.ts | import { Model } from '../../model/model.service';
import { GameBuild } from '../build/build.model';
import { GamePackage } from '../package/package.model';
import { Game } from '../game.model';
export class GameRelease extends Model {
static readonly STATUS_HIDDEN = 'hidden';
static readonly STATUS_PUBLISHED = 'pub... | (game: Game) {
const response = await this.$_save(
'/web/dash/developer/games/releases/publish/' +
this.game_id +
'/' +
this.game_package_id +
'/' +
this.id,
'gameRelease'
);
if (game && response.game) {
game.assign(response.game);
}
return response;
}
async $unpublish(game: ... | $publish | identifier_name |
release.model.ts | import { Model } from '../../model/model.service';
import { GameBuild } from '../build/build.model';
import { GamePackage } from '../package/package.model';
import { Game } from '../game.model';
export class GameRelease extends Model {
static readonly STATUS_HIDDEN = 'hidden';
static readonly STATUS_PUBLISHED = 'pub... |
return response;
}
}
Model.create(GameRelease);
| {
game.assign(response.game);
} | conditional_block |
connection.py | # Copyright 2009 Max Klymyshyn, Sonettic
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writ... |
else:
executable = ssl_command
if not executable:
raise APNSNoCommandFound, "SSL Executable [%s] not found in your PATH environment" % str(ssl_command)
self.connectionContext = OpenSSLCommandLine(certificate, executable, debug = debug)
self... | executable = find_executable(ssl_command) | conditional_block |
connection.py | # Copyright 2009 Max Klymyshyn, Sonettic
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writ... | (self):
raise APNSNotImplementedMethod, "APNSConnectionContext.read method not implemented"
def close(self):
raise APNSNotImplementedMethod, "APNSConnectionContext.close method not implemented"
class OpenSSLCommandLine(APNSConnectionContext):
"""
This class execute and send data with open... | read | identifier_name |
connection.py | # Copyright 2009 Max Klymyshyn, Sonettic
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writ... | certfile = self.certificate
)
return self
def certificate(self, path):
self.certificate = path
return self
def read(self, blockSize = 1024):
"""
Make connection to the host and port.
"""
return self.connectionContex... | random_line_split | |
connection.py | # Copyright 2009 Max Klymyshyn, Sonettic
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writ... |
def _command(self):
command = "%(executable)s s_client -ssl3 -cert %(cert)s -connect %(host)s:%(port)s" % \
{
'executable' : self.executable,
'cert' : self.certificate,
'host' : self.host,
'port' : self.port
}
return subproce... | self.host = host
self.port = port | identifier_body |
leaf.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
use leaf alogrithm to remove redundancy
this algorithm is published in this following paper
1. Bull, S. C., Muldoon, M. R. & Doig, A. J. Maximising the Size of Non-Redundant Protein Datasets Using Graph Theory. PLoS One 8, (2013).
Simon Bull gives an implementation for ... |
def leaf(labels, similarities, cutoff, filename):
matrix = [map(lambda x: 1 if x > cutoff else 0, row)
for row in similarities]
for i in range(len(matrix)):
matrix[i][i] = 0
# use igraph to plot the initial network
graph = igraph.Graph.Adjacency(matrix, mode='undirected')
i... | def pim(seq1, seq2):
identity = len([i for i, s in enumerate(seq1) if s == seq2[i]])
return identity * 1.0 / len(seq1)
scores = []
seqlen = len(seqs)
for i in range(seqlen):
score_i = []
for j in range(seqlen):
if j < i:
score_i.append(scores[j][i... | identifier_body |
leaf.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
use leaf alogrithm to remove redundancy
this algorithm is published in this following paper
1. Bull, S. C., Muldoon, M. R. & Doig, A. J. Maximising the Size of Non-Redundant Protein Datasets Using Graph Theory. PLoS One 8, (2013).
Simon Bull gives an implementation for ... | neighbors[i].remove(r)
remove += remove_iter
print 'after leaf: ',neighbors
nr_matrix = [matrix[i] for i in range(len(matrix)) if not i in remove]
nr_matrix = [[row[i] for i in range(
len(matrix)) if not i in remove] for row in nr_ma... | nodesofinterest = neighbors[i].union([i])
print 'initial nodesofinterest: ',nodesofinterest
if set.intersection(*[neighbors[i].union([i]) for i in nodesofinterest]) == nodesofinterest:
print 'clique nodesofinterest: ',nodesofinterest
# detect verte... | conditional_block |
leaf.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
use leaf alogrithm to remove redundancy
this algorithm is published in this following paper
1. Bull, S. C., Muldoon, M. R. & Doig, A. J. Maximising the Size of Non-Redundant Protein Datasets Using Graph Theory. PLoS One 8, (2013).
Simon Bull gives an implementation for ... | main() |
if __name__ == "__main__": | random_line_split |
leaf.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
use leaf alogrithm to remove redundancy
this algorithm is published in this following paper
1. Bull, S. C., Muldoon, M. R. & Doig, A. J. Maximising the Size of Non-Redundant Protein Datasets Using Graph Theory. PLoS One 8, (2013).
Simon Bull gives an implementation for ... | (msa_f):
with open(msa_f) as o_f:
lines = o_f.readlines()
lines = [line.rstrip('\r\n') for line in lines if line]
pro_line_num = [i for i, line in enumerate(
lines) if '>' in line] + [len(lines)]
seqs = [lines[n:pro_line_num[i + 1]]
for i, n in enumerate(p... | read_msa | identifier_name |
scripts.js | let countdown;
const timerDisplay = document.querySelector('.display__time-left');
const endTime = document.querySelector('.display__end-time');
const buttons = document.querySelectorAll('[data-time]');
function timer(seconds) {
// clean any existing timers
clearInterval(countdown);
const now = Date.no... | this.reset();
}); | random_line_split | |
scripts.js | let countdown;
const timerDisplay = document.querySelector('.display__time-left');
const endTime = document.querySelector('.display__end-time');
const buttons = document.querySelectorAll('[data-time]');
function timer(seconds) {
// clean any existing timers
clearInterval(countdown);
const now = Date.no... |
buttons.forEach(button => button.addEventListener('click', startTimer));
document.customForm.addEventListener('submit', function(e) {
e.preventDefault();
const mins = this.minutes.value;
console.log(mins);
timer(mins * 60);
this.reset();
}); | {
const seconds = parseInt(this.dataset.time);
timer(seconds);
} | identifier_body |
scripts.js | let countdown;
const timerDisplay = document.querySelector('.display__time-left');
const endTime = document.querySelector('.display__end-time');
const buttons = document.querySelectorAll('[data-time]');
function | (seconds) {
// clean any existing timers
clearInterval(countdown);
const now = Date.now();
const then = now + seconds * 1000;
displayTimeLeft(seconds);
displayEndTime(then);
countdown = setInterval(() => {
const secondsLeft = Math.round((then - Date.now()) / 1000);
// check if we shou... | timer | identifier_name |
scripts.js | let countdown;
const timerDisplay = document.querySelector('.display__time-left');
const endTime = document.querySelector('.display__end-time');
const buttons = document.querySelectorAll('[data-time]');
function timer(seconds) {
// clean any existing timers
clearInterval(countdown);
const now = Date.no... |
// display it
displayTimeLeft(secondsLeft);
}, 1000);
}
function displayTimeLeft(seconds) {
const minutes = Math.floor(seconds / 60);
const reminderSeconds = seconds % 60;
const display = `${minutes}:${reminderSeconds < 10 ? '0' : ''}${reminderSeconds}`;
timerDisplay.textContent = display;... | {
clearInterval(countdown);
return;
} | conditional_block |
MapDetailView.js | /*
* @constructor
* @implements {IDetailView}
*/
var MapDetailView = function (facade) {
var app = facade, _self = this, Device, Styles, LocalDictionary, UI, mapDetailTableView,
_detailView, locationDetailTitleBar, locationDetailMap, locationDetail, locationPhoto, topDetailView,
onBackBtnClick;... |
mapDetailTableView = Ti.UI.createTableView(Styles.mapDetailTableView);
_detailView.add(mapDetailTableView);
mapDetailTableView.setData(_tableViewData);
};
this.hide = function () {
if (_detailView) {
_detailView.hide();
}
};
onBack... | {
mapImageGroup = Ti.UI.createTableViewSection({
headerTitle: LocalDictionary.locationImage
});
detailImageRow = Ti.UI.createTableViewRow();
detailImage = Titanium.UI.createImageView({
image: viewModel.img.replace(/\/thumbnail\//,'/photo/')... | conditional_block |
MapDetailView.js | /*
* @constructor
* @implements {IDetailView}
*/
var MapDetailView = function (facade) {
var app = facade, _self = this, Device, Styles, LocalDictionary, UI, mapDetailTableView,
_detailView, locationDetailTitleBar, locationDetailMap, locationDetail, locationPhoto, topDetailView,
onBackBtnClick;... | Device = app.models.deviceProxy;
Styles = app.styles;
LocalDictionary = app.localDictionary;
UI = app.UI;
Ti.App.addEventListener('updatestylereference', function (e) {
Styles = app.styles;
});
};
this.getDetailView = function () {
... | Ti.API.debug("Creating titleBackButton in MapDetailViewController");
//Declare pointers to facade modules | random_line_split |
instancePropertyInStructType_basic.ts | // @target: ES5
// ok
module NonGeneric {
struct C {
x: string;
/* get y() {
return 1;
}
set y(v) { } */
| var c = new C(1, 2);
var r = c.fn();
var r2 = r.x;
// var r3 = r.y;
// r.y = 4;
// var r6 = c.y(); // error, should be c.y
}
module Generic {
struct C<T,U> {
x: T;
/* get y() {
return null;
}
set y(v: U) { } */
fn() { retu... | fn() { return this; }
constructor(public a: number, private b: number) { }
}
| random_line_split |
test_ml.py | """
Predict labels using trained ML models. Use average probability ensemble.
"""
__author__ = 'bshang'
import numpy as np
import pandas as pd
from sklearn import preprocessing
from sklearn.externals import joblib
def | (str_label):
str_label = str_label.split(' ')
return [int(x) for x in str_label if len(x) > 0]
MODEL = 'inception-v3'
LAYER = 'global_pool_output'
NUM_EPOCH = 30
BIZ_FEATURES_PATH = '/data/test_biz_features_{0}_{1}_{2}.h5'.format(MODEL, LAYER, NUM_EPOCH)
df = pd.read_csv(BIZ_FEATURES_PATH, header=0)
cols = [... | convert_label_to_array | identifier_name |
test_ml.py | """
Predict labels using trained ML models. Use average probability ensemble.
"""
__author__ = 'bshang'
import numpy as np
import pandas as pd
from sklearn import preprocessing
from sklearn.externals import joblib
def convert_label_to_array(str_label):
|
MODEL = 'inception-v3'
LAYER = 'global_pool_output'
NUM_EPOCH = 30
BIZ_FEATURES_PATH = '/data/test_biz_features_{0}_{1}_{2}.h5'.format(MODEL, LAYER, NUM_EPOCH)
df = pd.read_csv(BIZ_FEATURES_PATH, header=0)
cols = ["F" + str(i+1) for i in range(0, 2048)]
X = df[cols].values
model_svc = joblib.load('/data/skmodels/s... | str_label = str_label.split(' ')
return [int(x) for x in str_label if len(x) > 0] | identifier_body |
test_ml.py | """
Predict labels using trained ML models. Use average probability ensemble.
"""
__author__ = 'bshang'
| import pandas as pd
from sklearn import preprocessing
from sklearn.externals import joblib
def convert_label_to_array(str_label):
str_label = str_label.split(' ')
return [int(x) for x in str_label if len(x) > 0]
MODEL = 'inception-v3'
LAYER = 'global_pool_output'
NUM_EPOCH = 30
BIZ_FEATURES_PATH = '/data/te... | import numpy as np | random_line_split |
main.js | /*************************************************
* Copyright (c) 2016 Ansible, Inc.
*
* All Rights Reserved
*************************************************/
import UsersList from './list/users-list.controller';
import UsersAdd from './add/users-add.controller';
import UsersEdit from './edit/users-edit.controll... | },
data: {
activityStream: true,
activityStreamTarget: 'user'
},
ncyBreadcrumb: {
label: N_('USERS')
}
})
});
}
... | random_line_split | |
tests.py | # Copyright 2012, Julius Seporaitis
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wr... | (unittest.TestCase):
def test_example_sign(self):
"""Test with example data"""
req = urllib2.Request("https://johnsmith.s3.amazonaws.com/photos/puppy.jpg")
grabber = s3iam.S3Grabber("http://johnsmith.s3.amazonaws.com/", iamrole="s3access")
grabber.access_key = "AKIAIOSFODNN7EXAMPLE"... | S3GrabberTest | identifier_name |
tests.py | # Copyright 2012, Julius Seporaitis
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wr... | grabber.access_key = "AKIAIOSFODNN7EXAMPLE"
grabber.secret_key = "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY"
grabber.token = None
request = grabber._request("photos/puppy.jpg")
signature = grabber.sign(request, timeval=time.mktime(time.struct_time(
tm_year=2007,
... | """Test with example data"""
req = urllib2.Request("https://johnsmith.s3.amazonaws.com/photos/puppy.jpg")
grabber = s3iam.S3Grabber("http://johnsmith.s3.amazonaws.com/", iamrole="s3access") | random_line_split |
tests.py | # Copyright 2012, Julius Seporaitis
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wr... | unittest.main() | conditional_block | |
tests.py | # Copyright 2012, Julius Seporaitis
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wr... |
if __name__ == '__main__':
unittest.main()
| def test_example_sign(self):
"""Test with example data"""
req = urllib2.Request("https://johnsmith.s3.amazonaws.com/photos/puppy.jpg")
grabber = s3iam.S3Grabber("http://johnsmith.s3.amazonaws.com/", iamrole="s3access")
grabber.access_key = "AKIAIOSFODNN7EXAMPLE"
grabber.secret_ke... | identifier_body |
urls.py | # Copyright 2020 Nokia.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wr... | url(r'^$', gw_views.IndexView.as_view(), name='index'),
url(GATEWAY % '$', gw_views.DetailView.as_view(), name='detail'),
url(r'^ports/', include((port_urls, 'ports'), namespace='ports')),
] |
GATEWAY = r'^(?P<gateway_id>[^/]+)/%s'
urlpatterns = [ | random_line_split |
issue-10902.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | {} | identifier_body | |
issue-10902.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | }
}
pub mod two_fields {
pub trait T { fn dummy(&self) { } }
pub struct P<'a> { car: &'a (T + 'a), cdr: &'a (T + 'a) }
pub fn f<'a>(car: &'a T, cdr: &'a T) -> P<'a> {
P{ car: car, cdr: cdr }
}
}
fn main() {} | pub fn f<'a>(car: &'a T, cdr: &'a T) -> P<'a> {
P(car, cdr) | random_line_split |
issue-10902.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | <'a> { car: &'a (T + 'a), cdr: &'a (T + 'a) }
pub fn f<'a>(car: &'a T, cdr: &'a T) -> P<'a> {
P{ car: car, cdr: cdr }
}
}
fn main() {}
| P | identifier_name |
timer.js | /**
* PipelineTimer
* Keeps track of the time left for a HIT and updates the page as necessary.
* onExpiration will be de-thunked when the timer expires.
*/
PipelineTimer.create = function(serverTimestamp, counterId, totalSeconds, endTime, onExpiration) {
var offset = new ClientOffset(serverTimestamp);
OnLoadH... |
disp += this.formatNumber(hours) + ':' + this.formatNumber(minutes) + ':' + this.formatNumber(seconds);
return disp;
}
PipelineTimer.prototype.formatNumber = function(value) {
var string = value + '';
if (string.length < 2) { string = '0' + string }
return string;
}
/**
* ClientOffset
* Ca... | {
disp += days + (days == 1 ? ' day ' : ' days ')
} | conditional_block |
timer.js | /**
* PipelineTimer
* Keeps track of the time left for a HIT and updates the page as necessary.
* onExpiration will be de-thunked when the timer expires.
*/
PipelineTimer.create = function(serverTimestamp, counterId, totalSeconds, endTime, onExpiration) {
var offset = new ClientOffset(serverTimestamp);
OnLoadH... | (offset, counterElement, totalSeconds, endTime, onExpiration) {
this.offset = offset;
this.counterElement = counterElement;
this.totalSeconds = totalSeconds;
this.endTime = endTime;
this.onExpiration = onExpiration;
}
PipelineTimer.prototype.start = function() {
this.looping = true;
this.lo... | PipelineTimer | identifier_name |
timer.js | /**
* PipelineTimer
* Keeps track of the time left for a HIT and updates the page as necessary.
* onExpiration will be de-thunked when the timer expires.
*/
PipelineTimer.create = function(serverTimestamp, counterId, totalSeconds, endTime, onExpiration) {
var offset = new ClientOffset(serverTimestamp);
OnLoadH... |
/**
* ClientOffset
* Calculates the client's offset from the server's time
*/
ClientOffset.cookieName = 'clientOffset';
ClientOffset.loadDelayMilliseconds = 500;
function ClientOffset(serverTimestamp) {
var cookie = Cookie.get(ClientOffset.cookieName);
if (cookie && cookie.value) {
this.millisecon... | if (string.length < 2) { string = '0' + string }
return string;
} | random_line_split |
timer.js | /**
* PipelineTimer
* Keeps track of the time left for a HIT and updates the page as necessary.
* onExpiration will be de-thunked when the timer expires.
*/
PipelineTimer.create = function(serverTimestamp, counterId, totalSeconds, endTime, onExpiration) {
var offset = new ClientOffset(serverTimestamp);
OnLoadH... |
Cookie.prototype.remove = function() {
document.cookie = this.name + '=' +
(this.path ? '; path=' + this.path : '') +
(this.domain ? '; domain=' + this.domain : '') +
'; expires=Thu, 01-Jan-70 00:00:01 GMT';
}
| {
this.name = name;
this.value = value;
this.path = path;
this.domain = domain;
} | identifier_body |
Summary.ts | import { Component, OnInit, OnDestroy } from "@angular/core";
import { SummaryInterface } from './Service/Summary.interface';
import { SummaryService } from './Service/Summary.service';
import { SummaryObserver } from './Service/Summary.observer';
import { NgForm, Validators, FormGroup, FormArray, FormBuilder } from '@... |
test(){
var diff=[];
for(let i=0;i<this.inventorySummaryPOS.length;i++){
// if(this.inventorySummaryPOS[i].key[0] === this.inventorySummary[i].key[0]){}
diff[i]=this.inventorySummary[i].value.sum[0]-(this.inventorySummaryPOS[i].value.sum[0] || 0)
console.log('... | {
// this.repository.fetchSupplierTotal().then((sum:any) =>console.log("------Supplier function summary ts--------", this.fetchSupplier =sum));
this.repository.inventorySummary().then((sum:any) =>console.log("------ Inventory summary ts--------", this.inventorySummary =sum));
// this.repository.p... | identifier_body |
Summary.ts | import { Component, OnInit, OnDestroy } from "@angular/core";
import { SummaryInterface } from './Service/Summary.interface';
import { SummaryService } from './Service/Summary.service';
import { SummaryObserver } from './Service/Summary.observer';
import { NgForm, Validators, FormGroup, FormArray, FormBuilder } from '@... | implements OnInit, OnDestroy {
entries: Array<SummaryInterface> = [];
fetchSupplier: any;
inventorySummary: any;
inventorySummaryPOS : any;
purchaseInvoiceSummary :any;
purchaseOrderSummary :any;
expenseSummary :any;
customerSummary: any;
saleInvoiceSummary: any;
diffArray:any... | SummaryReadComponent | identifier_name |
Summary.ts | import { Component, OnInit, OnDestroy } from "@angular/core";
import { SummaryInterface } from './Service/Summary.interface';
import { SummaryService } from './Service/Summary.service';
import { SummaryObserver } from './Service/Summary.observer';
import { NgForm, Validators, FormGroup, FormArray, FormBuilder } from '@... |
console.log('gg',this.diffArray)
}
ngOnDestroy(): void {
}
}
| {
// if(this.inventorySummaryPOS[i].key[0] === this.inventorySummary[i].key[0]){}
diff[i]=this.inventorySummary[i].value.sum[0]-(this.inventorySummaryPOS[i].value.sum[0] || 0)
console.log('>>>>>>>>>>>>>>diff',diff)
this.diffArray.push({name:this.inventorySummaryPOS[i].k... | conditional_block |
Summary.ts | import { Component, OnInit, OnDestroy } from "@angular/core";
import { SummaryInterface } from './Service/Summary.interface';
import { SummaryService } from './Service/Summary.service';
import { SummaryObserver } from './Service/Summary.observer';
import { NgForm, Validators, FormGroup, FormArray, FormBuilder } from '@... | constructor( private repository: SummaryService) {
}
ngOnInit() {
// this.repository.fetchSupplierTotal().then((sum:any) =>console.log("------Supplier function summary ts--------", this.fetchSupplier =sum));
this.repository.inventorySummary().then((sum:any) =>console.log("------ Inven... | saleInvoiceSummary: any;
diffArray:any= [ ];
| random_line_split |
index.js | //MyWidget Script
/**************************
Add a link for a CSS file that styles .mywidget
Add a script tag that points to CDN version of jQuery 1.*
Add a script tag that loads your script file from http://m.edumedia.ca/
**************************/
document.addEventListener("DOMContentLoaded", function(){
var w =... |
var jq = document.createElement("script");
jq.addEventListener("load", function(){
scriptsLoaded++;
if(scriptsLoaded === 2){
//call the function in My widget script to load the JSON and build the widget
buildWidget(".mywidget");
console.log("both scripts loaded");
}
});
document.q... | var css = document.createElement("link");
css.setAttribute("rel", "stylesheet");
css.setAttribute("href", "main.css");
//loads the CSS file and applies it to the page
var scriptsLoaded = 0; | random_line_split |
index.js | //MyWidget Script
/**************************
Add a link for a CSS file that styles .mywidget
Add a script tag that points to CDN version of jQuery 1.*
Add a script tag that loads your script file from http://m.edumedia.ca/
**************************/
document.addEventListener("DOMContentLoaded", function(){
var w =... |
});
document.querySelector("head").appendChild(script);
script.setAttribute("src","js/widget.js");
}); | {
//call the function in My widget script to load the JSON and build the widget
buildWidget(".mywidget");
console.log("both scripts loaded");
} | conditional_block |
fixtures.js | var albumPicasso = {
title: 'The Colors',
artist: 'Pablo Picasso',
label: "Cubism",
year: '1881',
albumArtUrl: 'assets/images/album_covers/01.png',
songs: [
{title: 'Blue', duration: 161.71, audioUrl:'assets/music/blue'},
{title: 'Green', duration: 103.96, audioUrl:'assets/music/green'},
{title: 'Red'... | {title: 'Pink', duration: 153.14, audioUrl: 'assets/music/pink'}
]
};
var albumMacroni = {
title: 'The Telephone',
artist: 'Guglielmo Marconi',
label: "EM",
year: '1909',
albumArtUrl: 'assets/images/album_covers/20.png',
songs: [
{title: 'Hello, Operator?', duration: '1:01'},
{title: 'Ring, ring, r... | random_line_split | |
htmltimeelement.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::codegen::Bindings::HTMLTimeElementBinding;
use dom::bindings::js::Root;
use dom::bindings::str:... |
}
| {
let element = HTMLTimeElement::new_inherited(localName, prefix, document);
Node::reflect_node(box element, document, HTMLTimeElementBinding::Wrap)
} | identifier_body |
htmltimeelement.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::codegen::Bindings::HTMLTimeElementBinding;
use dom::bindings::js::Root;
use dom::bindings::str:... | }
} | Node::reflect_node(box element, document, HTMLTimeElementBinding::Wrap) | random_line_split |
htmltimeelement.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::codegen::Bindings::HTMLTimeElementBinding;
use dom::bindings::js::Root;
use dom::bindings::str:... | (localName: Atom, prefix: Option<DOMString>, document: &Document) -> HTMLTimeElement {
HTMLTimeElement {
htmlelement: HTMLElement::new_inherited(localName, prefix, document)
}
}
#[allow(unrooted_must_root)]
pub fn new(localName: Atom,
prefix: Option<DOMString>,
... | new_inherited | identifier_name |
share-wallet.ts | /**
* Share a BitGo multi-sig wallet with another BitGo user.
*
* This tool will help you see how to use the BitGo API to easily share your
* BitGo wallet with another BitGo user.
*
* Copyright 2019, BitGo, Inc. All Rights Reserved.
*/
import { BitGo } from 'bitgo';
const bitgo = new BitGo({ env: 'test' });
//... |
main().catch((e) => console.error(e));
| {
bitgo.authenticateWithAccessToken({ accessToken });
const wallet = await bitgo.coin(coin).wallets().get({ id: walletId });
const shareResult = await wallet.shareWallet({
email: recipient,
walletPassphrase: passphrase,
permissions: perms,
});
console.log('Wallet was shared successfully');
co... | identifier_body |
share-wallet.ts | /**
* Share a BitGo multi-sig wallet with another BitGo user.
*
* This tool will help you see how to use the BitGo API to easily share your
* BitGo wallet with another BitGo user.
*
* Copyright 2019, BitGo, Inc. All Rights Reserved.
*/
import { BitGo } from 'bitgo';
const bitgo = new BitGo({ env: 'test' });
//... | // TODO: set BitGo account email of wallet share recipient
const recipient = null;
// TODO: set share permissions as a comma-separated list
// Valid permissions to choose from are: view, spend, manage, admin
const perms = 'view';
// TODO: provide the passphrase for the wallet being shared
const passphrase = null;
co... |
// TODO: set the id of the wallet to share
const walletId = '';
| random_line_split |
share-wallet.ts | /**
* Share a BitGo multi-sig wallet with another BitGo user.
*
* This tool will help you see how to use the BitGo API to easily share your
* BitGo wallet with another BitGo user.
*
* Copyright 2019, BitGo, Inc. All Rights Reserved.
*/
import { BitGo } from 'bitgo';
const bitgo = new BitGo({ env: 'test' });
//... | () {
bitgo.authenticateWithAccessToken({ accessToken });
const wallet = await bitgo.coin(coin).wallets().get({ id: walletId });
const shareResult = await wallet.shareWallet({
email: recipient,
walletPassphrase: passphrase,
permissions: perms,
});
console.log('Wallet was shared successfully');
... | main | identifier_name |
gftools-nametable-from-filename.py | macStyle also get updated
to reflect the new names.
"""
from __future__ import print_function
import re
import ntpath
from argparse import (ArgumentParser,
RawTextHelpFormatter)
from fontTools.ttLib import TTFont, newTable
WIN_SAFE_STYLES = [
'Regular',
'Bold',
'Italic',
'BoldItalic',
]
... | (family_name, style_name):
name = family_name
if style_name not in WIN_SAFE_STYLES:
name = '%s %s' % (family_name, style_name)
if 'Italic' in name:
name = re.sub(r'Italic', r'', name)
return name
def _win_subfamily_name(style_name):
name = style_name
if 'BoldItalic' == name:
return 'Bold Itali... | _win_family_name | identifier_name |
gftools-nametable-from-filename.py | ),
(8, 1, 0, 0),
(9, 1, 0, 0),
(11, 1, 0, 0),
(12, 1, 0, 0),
(13, 1, 0, 0),
(14, 1, 0, 0),
(0, 3, 1, 1033),
(1, 3, 1, 1033),
(1, 3, 1, 1033),
(2, 3, 1, 1033),
(3, 3, 1, 1033),
(4, 3, 1, 1033),
(5, 3, 1, 1033),
(6, 3, 1, 1033),
(7, 3, 1, 1033),
(8, 3, 1, 1033),
(9, 3, 1, 1033),
(11, 3... | for font_path in args.fonts:
nametable = nametable_from_filename(font_path)
font = TTFont(font_path) | random_line_split | |
gftools-nametable-from-filename.py | macStyle also get updated
to reflect the new names.
"""
from __future__ import print_function
import re
import ntpath
from argparse import (ArgumentParser,
RawTextHelpFormatter)
from fontTools.ttLib import TTFont, newTable
WIN_SAFE_STYLES = [
'Regular',
'Bold',
'Italic',
'BoldItalic',
]
... |
def _win_subfamily_name(style_name):
name = style_name
if 'BoldItalic' == name:
return 'Bold Italic'
elif 'Italic' in name:
return 'Italic'
elif name == 'Bold':
return 'Bold'
else:
return 'Regular'
def set_usWeightClass(style_name):
name = style_name
if name != 'Italic':
name = re... | name = family_name
if style_name not in WIN_SAFE_STYLES:
name = '%s %s' % (family_name, style_name)
if 'Italic' in name:
name = re.sub(r'Italic', r'', name)
return name | identifier_body |
gftools-nametable-from-filename.py | macStyle also get updated
to reflect the new names.
"""
from __future__ import print_function
import re
import ntpath
from argparse import (ArgumentParser,
RawTextHelpFormatter)
from fontTools.ttLib import TTFont, newTable
WIN_SAFE_STYLES = [
'Regular',
'Bold',
'Italic',
'BoldItalic',
]
... |
else:
return 'Regular'
def set_usWeightClass(style_name):
name = style_name
if name != 'Italic':
name = re.sub(r'Italic', r'', style_name)
return WEIGHTS[name]
def set_macStyle(style_name):
return MACSTYLE[style_name]
def set_fsSelection(fsSelection, style):
bits = fsSelection
if 'Regular... | return 'Bold' | conditional_block |
options.py | #
# Copyright (c) 2013-2020 Contributors to the Eclipse Foundation
#
# See the NOTICE file distributed with this work for additional information regarding copyright
# ownership. All rights reserved. This program and the accompanying materials are made available
# under the terms of the Apache License, Version 2.0 whic... |
def set_verify_coprocessors(self, verify_coprocessors):
"""
Sets whether or not to verify coprocessors when performing operations.
Args:
verify_coprocessors (bool): Whether or not to verify coprocessors.
"""
self._base_options.setVerifyCoprocessors(verify_copro... | """
Returns:
The scan cache size of the HBase instance.
"""
return self._base_options.getScanCacheSize() | identifier_body |
options.py | #
# Copyright (c) 2013-2020 Contributors to the Eclipse Foundation
#
# See the NOTICE file distributed with this work for additional information regarding copyright
# ownership. All rights reserved. This program and the accompanying materials are made available
# under the terms of the Apache License, Version 2.0 whic... | (self, scan_cache_size):
"""
Sets the scan cache size of the HBase instance.
Args:
scan_cache_size (int): The scan cache size to use.
"""
self._base_options.setScanCacheSize(scan_cache_size)
def get_scan_cache_size(self):
"""
Returns:
... | set_scan_cache_size | identifier_name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.