file_name large_stringlengths 4 140 | prefix large_stringlengths 0 39k | suffix large_stringlengths 0 36.1k | middle large_stringlengths 0 29.4k | fim_type large_stringclasses 4
values |
|---|---|---|---|---|
joiner.rs | // Exercise 2.3
// I were better to be eaten to death with a rust than to be scoured to nothing with perpetual motion.
use std::os;
use std::io::File;
fn xor(a: &[u8], b: &[u8]) -> ~[u8] {
let mut ret = ~[];
for i in range(0, a.len()) {
ret.push(a[i] ^ b[i]);
}
ret
}
fn main() | {
let args: ~[~str] = os::args();
if args.len() != 3 {
println!("Usage: {:s} <inputfile1> <inputfile2>", args[0]);
} else {
let fname1 = &args[1];
let fname2 = &args[2];
let path1 = Path::new(fname1.clone());
let path2 = Path::new(fname2.clone());
let share_f... | identifier_body | |
joiner.rs | // Exercise 2.3
// I were better to be eaten to death with a rust than to be scoured to nothing with perpetual motion.
use std::os;
use std::io::File;
fn xor(a: &[u8], b: &[u8]) -> ~[u8] {
let mut ret = ~[];
for i in range(0, a.len()) {
ret.push(a[i] ^ b[i]);
}
ret
}
fn main() {
let args: ... | ,
(_, _) => fail!("Error opening input files!")
}
}
}
| {
let share1bytes: ~[u8] = share1.read_to_end();
let share2bytes: ~[u8] = share2.read_to_end();
print!("{:s}", std::str::from_utf8_owned(
xor(share1bytes, share2bytes)));
} | conditional_block |
joiner.rs | // Exercise 2.3
// I were better to be eaten to death with a rust than to be scoured to nothing with perpetual motion.
use std::os;
use std::io::File;
fn xor(a: &[u8], b: &[u8]) -> ~[u8] {
let mut ret = ~[];
for i in range(0, a.len()) {
ret.push(a[i] ^ b[i]);
}
ret
}
fn main() {
let args: ... | print!("{:s}", std::str::from_utf8_owned(
xor(share1bytes, share2bytes)));
} ,
(_, _) => fail!("Error opening input files!")
}
}
} | random_line_split | |
joiner.rs | // Exercise 2.3
// I were better to be eaten to death with a rust than to be scoured to nothing with perpetual motion.
use std::os;
use std::io::File;
fn xor(a: &[u8], b: &[u8]) -> ~[u8] {
let mut ret = ~[];
for i in range(0, a.len()) {
ret.push(a[i] ^ b[i]);
}
ret
}
fn | () {
let args: ~[~str] = os::args();
if args.len() != 3 {
println!("Usage: {:s} <inputfile1> <inputfile2>", args[0]);
} else {
let fname1 = &args[1];
let fname2 = &args[2];
let path1 = Path::new(fname1.clone());
let path2 = Path::new(fname2.clone());
let shar... | main | identifier_name |
main.rs | extern crate rand;
use std::io;
use std::cmp::Ordering;
use rand::Rng;
/// GuessGame from std docs of rust
fn main() {
println!("Guess the number!");
let mut chances: u32 = 0;
// Generate and store a randowm number b/w 1<->100
let secret_number = rand::thread_rng().gen_range(1, 101);
// Go int... |
println!("You guessed: {}", guess);
// Match the respective value of guess wrt secret number
match guess.cmp(&secret_number) {
Ordering::Less => println!("Too small! \n"),
Ordering::Greater => println!("Too big! \n"),
Ordering::Equal => {
... | let guess: u32 = match guess.trim().parse() {
Ok(num) => num, // Match num if everything is OK
Err(_) => continue, // Continue even if anything != OK happens
}; | random_line_split |
main.rs | extern crate rand;
use std::io;
use std::cmp::Ordering;
use rand::Rng;
/// GuessGame from std docs of rust
fn | () {
println!("Guess the number!");
let mut chances: u32 = 0;
// Generate and store a randowm number b/w 1<->100
let secret_number = rand::thread_rng().gen_range(1, 101);
// Go into a infinite loop
loop {
println!("Chances used {}", chances);
println!("Please input your guess... | main | identifier_name |
main.rs | extern crate rand;
use std::io;
use std::cmp::Ordering;
use rand::Rng;
/// GuessGame from std docs of rust
fn main() | {
println!("Guess the number!");
let mut chances: u32 = 0;
// Generate and store a randowm number b/w 1<->100
let secret_number = rand::thread_rng().gen_range(1, 101);
// Go into a infinite loop
loop {
println!("Chances used {}", chances);
println!("Please input your guess.")... | identifier_body | |
BombManager.js | /**
* Created with JetBrains PhpStorm.
* User: Mrkupi
* Date: 9/22/13
* Time: 9:34 AM
* To change this template use File | Settings | File Templates.
*/
var BombManager = cc.Node.extend({
bombs:null,
effectManager:null,
initialize:function()
{
this.bombs = new Array();
this.schedul... | });
BombManager.prototype.setEffectManager = function(manager)
{
this.effectManager = manager;
this.addChild(this.effectManager);
}
BombManager.prototype.removeWithExplodeBomb = function()
{
if(this.bombs != null)
{
for(var i = 0; i < this.bombs.length; ++i)
{
if(this.bombs... | } | random_line_split |
BombManager.js | /**
* Created with JetBrains PhpStorm.
* User: Mrkupi
* Date: 9/22/13
* Time: 9:34 AM
* To change this template use File | Settings | File Templates.
*/
var BombManager = cc.Node.extend({
bombs:null,
effectManager:null,
initialize:function()
{
this.bombs = new Array();
this.schedul... |
} | {
for(var i = 0; i < this.bombs.length; ++i)
{
if(this.bombs[i].isExplode == true)
{
// Now call to fire effect on screen
this.effectManager.fire(this.bombs[i].chopEffectTexture, this.bombs[i].bodyEffectTexture, this.bombs[i].centerEffectTexture,
... | conditional_block |
test_import.py | # -*- coding: utf-8 -*-
#-----------------------------------------------------------------------------
# Copyright (c) 2005-2016, PyInstaller Development Team.
#
# Distributed under the terms of the GNU General Public License with exception
# for distributing bootloader.
#
# The full license is in the file COPYING.txt,... |
parameters.append(params)
@pytest.mark.parametrize("funcname,test_id", parameters, ids=ids)
def test_ctypes_gen(pyi_builder, monkeypatch, funcname, compiled_dylib, test_id):
# evaluate the soname here, so the test-code contains a constant.
# We want the name of the dynamically-loaded library only, not... | params = skipif_notwin(params) | conditional_block |
test_import.py | # -*- coding: utf-8 -*-
#-----------------------------------------------------------------------------
# Copyright (c) 2005-2016, PyInstaller Development Team.
#
# Distributed under the terms of the GNU General Public License with exception
# for distributing bootloader.
#
# The full license is in the file COPYING.txt,... | # * __init__.py -- inserts a/ into __path__, then imports b, which now refers
# to a/b.py, not ./b.py.
# * b.py - raises an exception. **Should not be imported.**
# * a/ -- contains no __init__.py.
#
# * b.py - Empty. Should be imported.
@xfail(reason='__path__ not respected for filesystem modules.')
def ... | # Verify that __path__ is respected for imports from the filesystem:
#
# * pyi_testmod_path/
# | random_line_split |
test_import.py | # -*- coding: utf-8 -*-
#-----------------------------------------------------------------------------
# Copyright (c) 2005-2016, PyInstaller Development Team.
#
# Distributed under the terms of the GNU General Public License with exception
# for distributing bootloader.
#
# The full license is in the file COPYING.txt,... | (pyi_builder, data_dir, monkeypatch):
from PyInstaller.building.build_main import Analysis
class MyAnalysis(Analysis):
def __init__(self, *args, **kwargs):
kwargs['datas'] = datas
# Setting back is required to make `super()` within
# Analysis access the correct class... | test_app_with_plugin | identifier_name |
test_import.py | # -*- coding: utf-8 -*-
#-----------------------------------------------------------------------------
# Copyright (c) 2005-2016, PyInstaller Development Team.
#
# Distributed under the terms of the GNU General Public License with exception
# for distributing bootloader.
#
# The full license is in the file COPYING.txt,... |
@pytest.mark.parametrize("funcname,test_id", parameters, ids=ids)
def test_ctypes_in_func_gen(pyi_builder, monkeypatch, funcname,
compiled_dylib, test_id):
"""
This is much like test_ctypes_gen except that the ctypes calls
are in a function. See issue #1620.
"""
soname... | soname = compiled_dylib.basename
source = """
import ctypes ; from ctypes import *
lib = %s(%%(soname)r)
""" % funcname + _template_ctypes_test
__monkeypatch_resolveCtypesImports(monkeypatch, compiled_dylib.dirname)
pyi_builder.test_source(source % locals(), test_id=test_id) | identifier_body |
components.component.ts | import { Component, HostBinding, AfterViewInit, ElementRef, Inject, Renderer2 } from '@angular/core';
import { DOCUMENT } from '@angular/platform-browser';
import { TdMediaService } from '@covalent/core';
import { fadeAnimation } from '../../app.animations';
@Component({
selector: 'app-components',
styleUrls: ['.... | }
} | }
changeDir(dir: string): void {
this._renderer.setAttribute(this._document.querySelector('html'), 'dir', dir); | random_line_split |
components.component.ts | import { Component, HostBinding, AfterViewInit, ElementRef, Inject, Renderer2 } from '@angular/core';
import { DOCUMENT } from '@angular/platform-browser';
import { TdMediaService } from '@covalent/core';
import { fadeAnimation } from '../../app.animations';
@Component({
selector: 'app-components',
styleUrls: ['.... | (public media: TdMediaService,
private _renderer: Renderer2,
@Inject(DOCUMENT) private _document: any) {}
ngAfterViewInit(): void {
// broadcast to all listener observables when loading the page
this.media.broadcast();
}
changeDir(dir: string): void {
this._renderer.setAt... | constructor | identifier_name |
components.component.ts | import { Component, HostBinding, AfterViewInit, ElementRef, Inject, Renderer2 } from '@angular/core';
import { DOCUMENT } from '@angular/platform-browser';
import { TdMediaService } from '@covalent/core';
import { fadeAnimation } from '../../app.animations';
@Component({
selector: 'app-components',
styleUrls: ['.... |
changeDir(dir: string): void {
this._renderer.setAttribute(this._document.querySelector('html'), 'dir', dir);
}
}
| {
// broadcast to all listener observables when loading the page
this.media.broadcast();
} | identifier_body |
Solution020.py | # https://projecteuler.net/problem=20
#
# n! means n × (n − 1) × ... × 3 × 2 × 1
#
# For example, 10! = 10 × 9 × ... × 3 × 2 × 1 = 3628800,
# and the sum of the digits in the number 10! is 3 + 6 + 2 + 8 + 8 + 0 + 0 = 27.
#
# Find the sum of the digits in the number 100!
def preCalcFactSum(limit):
ary = [1]
f = 1
... |
if __name__ == '__main__':
table = preCalcFactSum(100)
print(table[-1]) | f
s = 0
while n:
s, n = s + n % 10, n // 10
ary.append(s)
return ary | conditional_block |
Solution020.py | # https://projecteuler.net/problem=20
#
# n! means n × (n − 1) × ... × 3 × 2 × 1
#
# For example, 10! = 10 × 9 × ... × 3 × 2 × 1 = 3628800,
# and the sum of the digits in the number 10! is 3 + 6 + 2 + 8 + 8 + 0 + 0 = 27.
#
# Find the sum of the digits in the number 100!
def preCalcFactS | y = [1]
f = 1
for i in range(1, limit+1):
f *= i
n = f
s = 0
while n:
s, n = s + n % 10, n // 10
ary.append(s)
return ary
if __name__ == '__main__':
table = preCalcFactSum(100)
print(table[-1]) | um(limit):
ar | identifier_name |
Solution020.py | # https://projecteuler.net/problem=20
#
# n! means n × (n − 1) × ... × 3 × 2 × 1
#
# For example, 10! = 10 × 9 × ... × 3 × 2 × 1 = 3628800,
# and the sum of the digits in the number 10! is 3 + 6 + 2 + 8 + 8 + 0 + 0 = 27.
#
# Find the sum of the digits in the number 100!
def preCalcFactSum(limit):
ary = [1]
f | _ == '__main__':
table = preCalcFactSum(100)
print(table[-1]) | = 1
for i in range(1, limit+1):
f *= i
n = f
s = 0
while n:
s, n = s + n % 10, n // 10
ary.append(s)
return ary
if __name_ | identifier_body |
Solution020.py | # https://projecteuler.net/problem=20
#
# n! means n × (n − 1) × ... × 3 × 2 × 1
#
# For example, 10! = 10 × 9 × ... × 3 × 2 × 1 = 3628800,
# and the sum of the digits in the number 10! is 3 + 6 + 2 + 8 + 8 + 0 + 0 = 27.
#
# Find the sum of the digits in the number 100!
def preCalcFactSum(limit):
ary = [1]
f = 1
... |
if __name__ == '__main__':
table = preCalcFactSum(100)
print(table[-1]) | ary.append(s)
return ary | random_line_split |
parentElement.test.ts | import { remote } from '../../../src'
describe('parent element test', () => {
it('should return parent element of an element', async () => {
const browser = await remote({
capabilities: {
browserName: 'foobar'
}
})
const elem = await browser.$('#foo')... | }) | expect(err.message)
.toContain('parent element of element with selector "#foo"')
}) | random_line_split |
mobile.js | /*
* VITacademics
* Copyright (C) 2014-2016 Aneesh Neelam <neelam.aneesh@gmail.com>
* Copyright (C) 2014-2016 Ayush Agarwal <agarwalayush161@gmail.com>
*
* This file is part of VITacademics.
*
* VITacademics is free software: you can redistribute it and/or modify
* it under the terms of the GNU General ... | * You should have received a copy of the GNU General Public License
* along with VITacademics. If not, see <http://www.gnu.org/licenses/>.
*/
'use strict';
const path = require('path');
const status = require(path.join(__dirname, '..', 'status'));
const handler = function (app) {
const onJob = function (job... | * | random_line_split |
test_default_pricing.py | # -*- coding: utf-8 -*-
# This file is part of Shoop.
#
# Copyright (c) 2012-2016, Shoop Ltd. All rights reserved.
#
# This source code is licensed under the AGPLv3 license found in the
# LICENSE file in the root directory of this source tree.
import pytest
from django.conf import settings
from shoop.core.pricing impo... | @pytest.mark.django_db
def test_non_one_quantity(rf):
request, shop, group = initialize_test(rf, False)
shop = get_default_shop()
product = create_product("test-product", shop=shop, default_price=100)
assert product.get_price(request, quantity=5) == shop.create_price(500) | random_line_split | |
test_default_pricing.py | # -*- coding: utf-8 -*-
# This file is part of Shoop.
#
# Copyright (c) 2012-2016, Shoop Ltd. All rights reserved.
#
# This source code is licensed under the AGPLv3 license found in the
# LICENSE file in the root directory of this source tree.
import pytest
from django.conf import settings
from shoop.core.pricing impo... | (rf):
request, shop, group = initialize_test(rf, False)
shop = get_default_shop()
product = create_product("test-product", shop=shop, default_price=100)
assert product.get_price(request, quantity=5) == shop.create_price(500)
| test_non_one_quantity | identifier_name |
test_default_pricing.py | # -*- coding: utf-8 -*-
# This file is part of Shoop.
#
# Copyright (c) 2012-2016, Shoop Ltd. All rights reserved.
#
# This source code is licensed under the AGPLv3 license found in the
# LICENSE file in the root directory of this source tree.
import pytest
from django.conf import settings
from shoop.core.pricing impo... |
@pytest.mark.django_db
def test_default_price_value_allowed(rf):
request, shop, group = initialize_test(rf, False)
shop = get_default_shop()
product = create_product("test-product", shop=shop, default_price=100)
assert product.get_price(request) == shop.create_price(100)
@pytest.mark.django_db
def ... | request, shop, group = initialize_test(rf, False)
shop = get_default_shop()
product = create_product("test-product", shop=shop, default_price=0)
assert product.get_price(request) == shop.create_price(0) | identifier_body |
arbitrator.rs | // Copyright 2015-2016 ZFilexfer Developers. See the COPYRIGHT file at the
// top-level directory of this distribution and at
// https://intecture.io/COPYRIGHT.
//
// Licensed under the Mozilla Public License 2.0 <LICENSE or
// https://www.tldrlegal.com/l/mpl-2.0>. This file may not be copied,
// modified, or distribut... | () {
ZSys::init();
let (mut client, router) = ZSys::create_pipe().unwrap();
client.set_rcvtimeo(Some(500));
let (comm, thread) = ZSys::create_pipe().unwrap();
let chunks = vec![
TimedChunk::new("abc".as_bytes(), 0),
TimedChunk::new("abc".as_bytes(), 1),... | test_arbitrator_request | identifier_name |
arbitrator.rs | // Copyright 2015-2016 ZFilexfer Developers. See the COPYRIGHT file at the
// top-level directory of this distribution and at
// https://intecture.io/COPYRIGHT.
//
// Licensed under the Mozilla Public License 2.0 <LICENSE or
// https://www.tldrlegal.com/l/mpl-2.0>. This file may not be copied,
// modified, or distribut... |
fn run(mut self) {
loop {
// Terminate on ZSock signal or system signal (SIGTERM)
if self.comm.wait().is_ok() || ZSys::is_interrupted() {
break;
}
for chunk in self.chunks.read().unwrap().iter() {
if chunk.is_expired() {
... | })
} | random_line_split |
__init__.py | from decimal import Decimal
import random
import hashlib
from django.conf import settings
from django.core.cache import cache
from django.db.models.signals import post_save, post_delete, m2m_changed
from waffle.models import Flag, Sample, Switch
VERSION = (0, 9, 2)
__version__ = '.'.join(map(str, VERSION))
CACHE_... | return True
set_flag(request, flag_name, False, flag.rollout)
return False
def switch_is_active(switch_name):
switch = cache.get(keyfmt(SWITCH_CACHE_KEY, switch_name))
if switch is None:
try:
switch = Switch.objects.get(name=switch_name)
cache_switch(in... | return flag_active
if Decimal(str(random.uniform(0, 100))) <= flag.percent:
set_flag(request, flag_name, True, flag.rollout) | random_line_split |
__init__.py | from decimal import Decimal
import random
import hashlib
from django.conf import settings
from django.core.cache import cache
from django.db.models.signals import post_save, post_delete, m2m_changed
from waffle.models import Flag, Sample, Switch
VERSION = (0, 9, 2)
__version__ = '.'.join(map(str, VERSION))
CACHE_... |
request.waffles[flag_name] = [active, session_only]
def flag_is_active(request, flag_name):
flag = cache.get(keyfmt(FLAG_CACHE_KEY, flag_name))
if flag is None:
try:
flag = Flag.objects.get(name=flag_name)
cache_flag(instance=flag)
except Flag.DoesNotExist:
... | request.waffles = {} | conditional_block |
__init__.py | from decimal import Decimal
import random
import hashlib
from django.conf import settings
from django.core.cache import cache
from django.db.models.signals import post_save, post_delete, m2m_changed
from waffle.models import Flag, Sample, Switch
VERSION = (0, 9, 2)
__version__ = '.'.join(map(str, VERSION))
CACHE_... | (**kwargs):
sample = kwargs.get('instance')
cache.set(keyfmt(SAMPLE_CACHE_KEY, sample.name), None, 5)
cache.set(keyfmt(SAMPLES_ALL_CACHE_KEY), None, 5)
post_save.connect(uncache_sample, sender=Sample, dispatch_uid='save_sample')
post_delete.connect(uncache_sample, sender=Sample,
dispatc... | uncache_sample | identifier_name |
__init__.py | from decimal import Decimal
import random
import hashlib
from django.conf import settings
from django.core.cache import cache
from django.db.models.signals import post_save, post_delete, m2m_changed
from waffle.models import Flag, Sample, Switch
VERSION = (0, 9, 2)
__version__ = '.'.join(map(str, VERSION))
CACHE_... |
def flag_is_active(request, flag_name):
flag = cache.get(keyfmt(FLAG_CACHE_KEY, flag_name))
if flag is None:
try:
flag = Flag.objects.get(name=flag_name)
cache_flag(instance=flag)
except Flag.DoesNotExist:
return getattr(settings, 'WAFFLE_FLAG_DEFAULT', Fal... | """Set a flag value on a request object."""
if not hasattr(request, 'waffles'):
request.waffles = {}
request.waffles[flag_name] = [active, session_only] | identifier_body |
composition-card.tsx | import React from 'react';
import { Box, Stack, Heading, Icon, Text, HStack, Avatar } from 'native-base'; | MaterialCommunityIcons,
SimpleLineIcons,
MaterialIcons,
} from '@expo/vector-icons';
export const Example = () => {
return (
<Box p={5} rounded="xl" shadow={4} w="100%">
<Stack space={6}>
<HStack justifyContent="space-between" alignItems="center">
<Avatar
size={'sm'}
... | import { | random_line_split |
getlyrics.py | # -*- coding: utf-8 -*-
u"""歌詞コーパスの取得
"""
import argparse
import requests
import logging
import urllib, urllib2
import re
import time
from BeautifulSoup import BeautifulSoup
verbose = False
logger = None
def init_logger():
global logger
logger = logging.getLogger('GetLyrics')
logger.setLevel(logging.DEB... | "j-lyrics.netでのアーティストのIDを取得
"""
params = {"ka": artist,}
baseurl = "http://search.j-lyric.net/index.php"
r = requests.get(baseurl, params=params)
soup = BeautifulSoup(r.content)
urls = soup.find("div", id="lyricList").findAll("a")
r = re.compile(r'http://j-lyric.net/artist/\w+/')
for url in urls:
... | + " similar artists")
return artist_list
def getArtistId(artist):
u"" | conditional_block |
getlyrics.py | # -*- coding: utf-8 -*-
u"""歌詞コーパスの取得
"""
import argparse
import requests
import logging
import urllib, urllib2
import re
import time
from BeautifulSoup import BeautifulSoup
verbose = False
logger = None
def init_logger():
global logger
logger = logging.getLogger('GetLyrics')
logger.setLevel(logging.DEB... | t in artist_list[:args.n_artists]:
urls = getLyricUrlList(artist)
if verbose:
logger.info('{}: {} songs'.format(artist, len(urls)))
for i, url in enumerate(urls, start=1):
if verbose:
if i%10 == 0: logger.info("Wrote " + str(i) + " songs")
lyric = getLyricText(url[1])
print("... | rtist_list = getSimilarArtist(args.artist)
artist_list = [args.artist,] + artist_list
print("artist\ttitle\ttext")
for artis | identifier_body |
getlyrics.py | # -*- coding: utf-8 -*-
u"""歌詞コーパスの取得
"""
import argparse
import requests
import logging
import urllib, urllib2
import re
import time
from BeautifulSoup import BeautifulSoup
verbose = False
logger = None
def init_logger():
global logger
logger = logging.getLogger('GetLyrics')
logger.setLevel(logging.DEB... | ArtistId(artist)
baseurl = "http://j-lyric.net/artist/" + artist_id + "/"
r = requests.get(baseurl)
soup = BeautifulSoup(r.content)
a_tags = soup.find("div", id="lyricList").findAll("a")
urls = map(lambda t: (t.string, t.get("href")), a_tags)
# 歌詞以外のリンクを除く
urls = filter(lambda t: t[1].startswith('/artist... | artist_id = get | identifier_name |
getlyrics.py | # -*- coding: utf-8 -*-
u"""歌詞コーパスの取得
"""
import argparse
import requests
import logging
import urllib, urllib2
import re
import time
from BeautifulSoup import BeautifulSoup
verbose = False
logger = None
def init_logger():
global logger
logger = logging.getLogger('GetLyrics')
logger.setLevel(logging.DEB... | return href.split("/")[-2]
if verbose:
logger.warning(artist + ": Not found")
return None
def getLyricUrlList(artist):
u"""アーティストのすべての歌詞ページのUrlを取得
j-lyrics.net
"""
artist_id = getArtistId(artist)
baseurl = "http://j-lyric.net/artist/" + artist_id + "/"
r = requests.get(baseurl)
soup = Bea... | if href.startswith("http://j-lyric.net/artist/"): | random_line_split |
rebuild_thumbnails.py | """
Custom management command to rebuild thumbnail images
- May be required after importing a new dataset, for example
"""
import os
import logging
from PIL import UnidentifiedImageError
from django.core.management.base import BaseCommand
from django.conf import settings
from django.db.utils import OperationalError... | """
Rebuild all thumbnail images
"""
def rebuild_thumbnail(self, model):
"""
Rebuild the thumbnail specified by the "image" field of the provided model
"""
if not model.image:
return
img = model.image
url = img.thumbnail.name
loc = os.pa... | identifier_body | |
rebuild_thumbnails.py | """
Custom management command to rebuild thumbnail images
- May be required after importing a new dataset, for example
"""
import os
import logging
from PIL import UnidentifiedImageError
from django.core.management.base import BaseCommand
from django.conf import settings
from django.db.utils import OperationalError... | try:
self.rebuild_thumbnail(company)
except (OperationalError, ProgrammingError):
logger.error("ERROR: abase read error.")
break | conditional_block | |
rebuild_thumbnails.py | """
Custom management command to rebuild thumbnail images
- May be required after importing a new dataset, for example
"""
import os
import logging
from PIL import UnidentifiedImageError
from django.core.management.base import BaseCommand
from django.conf import settings
from django.db.utils import OperationalError... | (BaseCommand):
"""
Rebuild all thumbnail images
"""
def rebuild_thumbnail(self, model):
"""
Rebuild the thumbnail specified by the "image" field of the provided model
"""
if not model.image:
return
img = model.image
url = img.thumbnail.name
... | Command | identifier_name |
fr.js | export const messages = {
resources: {
posts: {
name: 'Article |||| Articles',
fields: {
allow_comments: 'Accepte les commentaires ?',
average_note: 'Note moyenne',
body: 'Contenu',
comments: 'Commentaires',
... | title: 'Article "%{title}"',
},
},
comment: {
list: {
about: 'Au sujet de',
},
},
};
export default messages; | comments: 'Commentaires',
},
edit: { | random_line_split |
test_mqtt.py | """The tests for the MQTT sensor platform."""
import unittest
from homeassistant.bootstrap import setup_component
import homeassistant.components.sensor as sensor
from tests.common import mock_mqtt_component, fire_mqtt_message
from tests.common import get_test_home_assistant
class TestSensorMQTT(unittest.TestCase):... |
self.assertEqual('100', state.state) | fire_mqtt_message(self.hass, 'test-topic', '{ "val": "100" }')
self.hass.block_till_done()
state = self.hass.states.get('sensor.test') | random_line_split |
test_mqtt.py | """The tests for the MQTT sensor platform."""
import unittest
from homeassistant.bootstrap import setup_component
import homeassistant.components.sensor as sensor
from tests.common import mock_mqtt_component, fire_mqtt_message
from tests.common import get_test_home_assistant
class TestSensorMQTT(unittest.TestCase):... | (self): # pylint: disable=invalid-name
"""Stop down everything that was started."""
self.hass.stop()
def test_setting_sensor_value_via_mqtt_message(self):
"""Test the setting of the value via MQTT."""
self.hass.config.components = ['mqtt']
assert setup_component(self.hass, ... | tearDown | identifier_name |
test_mqtt.py | """The tests for the MQTT sensor platform."""
import unittest
from homeassistant.bootstrap import setup_component
import homeassistant.components.sensor as sensor
from tests.common import mock_mqtt_component, fire_mqtt_message
from tests.common import get_test_home_assistant
class TestSensorMQTT(unittest.TestCase):... |
def test_setting_sensor_value_via_mqtt_json_message(self):
"""Test the setting of the value via MQTT with JSON playload."""
self.hass.config.components = ['mqtt']
assert setup_component(self.hass, sensor.DOMAIN, {
sensor.DOMAIN: {
'platform': 'mqtt',
... | """Test the setting of the value via MQTT."""
self.hass.config.components = ['mqtt']
assert setup_component(self.hass, sensor.DOMAIN, {
sensor.DOMAIN: {
'platform': 'mqtt',
'name': 'test',
'state_topic': 'test-topic',
'unit_of_m... | identifier_body |
chunked-batch.test.ts | import { TestSuite } from '../../../../client-common/src/__tests__/TestSuite';
const testSuite = new TestSuite('chunked_batch');
test(testSuite.testName, async () => {
const index = testSuite.makeIndex();
| expect(saveObjectResponse.taskID).toBeDefined();
const saveObjectsResponse = await index.saveObjects([{ objectID: 1 }]);
expect(saveObjectsResponse.objectIDs).toEqual(['1']);
expect(saveObjectsResponse.taskIDs).toHaveLength(1);
const secondSaveObjectsResponse = await index.saveObjects([{ objectID: 1 }, { ob... | const saveObjectResponse = await index.saveObject({ objectID: 1 });
expect(saveObjectResponse.objectID).toEqual('1'); | random_line_split |
angular-locale_en-bw.js | angular.module("ngLocale", [], ["$provide", function($provide) {
var PLURAL_CATEGORY = {ZERO: "zero", ONE: "one", TWO: "two", FEW: "few", MANY: "many", OTHER: "other"};
$provide.value("$locale", {
"DATETIME_FORMATS": {
"AMPMS": [
"AM",
"PM"
],
"DAY": [
"Sunday",
"Monday",... | "Jun",
"Jul",
"Aug",
"Sep",
"Oct",
"Nov",
"Dec"
],
"fullDate": "EEEE dd MMMM y",
"longDate": "dd MMMM y",
"medium": "MMM d, y h:mm:ss a",
"mediumDate": "MMM d, y",
"mediumTime": "h:mm:ss a",
"short": "dd/MM/yy h:mm a",
"shortDate": ... | "May",
| random_line_split |
angular-locale_en-bw.js | angular.module("ngLocale", [], ["$provide", function($provide) {
var PLURAL_CATEGORY = {ZERO: "zero", ONE: "one", TWO: "two", FEW: "few", MANY: "many", OTHER: "other"};
$provide.value("$locale", {
"DATETIME_FORMATS": {
"AMPMS": [
"AM",
"PM"
],
"DAY": [
"Sunday",
"Monday",... | return PLURAL_CATEGORY.OTHER;}
});
}]); | { return PLURAL_CATEGORY.ONE; } | conditional_block |
sphereimpostor-buffer.ts | /**
* @file Sphere Impostor Buffer
* @author Alexander Rose <alexander.rose@weirdbyte.de>
* @private
*/
import { Matrix4 } from 'three'
import '../shader/SphereImpostor.vert'
import '../shader/SphereImpostor.frag'
import MappedQuadBuffer from './mappedquad-buffer'
import { SphereBufferData } from './sphere-buffe... | */
constructor (data: SphereBufferData, params: Partial<BufferParameters> = {}) {
super(data, params)
this.addUniforms({
'projectionMatrixInverse': { value: new Matrix4() },
'ortho': { value: 0.0 }
})
this.addAttributes({
'radius': { type: 'f', value: null }
})
this.set... | * @param {Float32Array} data.radius - radii
* @param {Picker} [data.picking] - picking ids
* @param {BufferParameters} params - parameter object | random_line_split |
sphereimpostor-buffer.ts | /**
* @file Sphere Impostor Buffer
* @author Alexander Rose <alexander.rose@weirdbyte.de>
* @private
*/
import { Matrix4 } from 'three'
import '../shader/SphereImpostor.vert'
import '../shader/SphereImpostor.frag'
import MappedQuadBuffer from './mappedquad-buffer'
import { SphereBufferData } from './sphere-buffe... | (data: SphereBufferData, params: Partial<BufferParameters> = {}) {
super(data, params)
this.addUniforms({
'projectionMatrixInverse': { value: new Matrix4() },
'ortho': { value: 0.0 }
})
this.addAttributes({
'radius': { type: 'f', value: null }
})
this.setAttributes(data)
... | constructor | identifier_name |
aggregate-accessibility.ts | //
// disable a few ESLint rules that choke on pretty-printed arrays below
/* eslint indent: 0, no-multi-spaces: 0 */
/** Test that the aggregate accessibility selector works correctly */
import {expect} from '@jest/globals'
import range from 'lodash/range'
import getAggregateAccessibility from '../aggregate-accessi... | 10000,
100,
25, // aggregation area overlaps rightmost two cells
10000,
10000,
10000
],
height: 2,
min: 0,
north: 50,
west: 49,
width: 3,
zoom: 9
}
// The aggregation area starts in the second cell of the weights and does... | it('should work', () => {
// if we think of these as population, the two right cells of the top row have population of 100 and 25
const population = {
contains: contains(3, 2),
data: [ | random_line_split |
aggregate-accessibility.ts | //
// disable a few ESLint rules that choke on pretty-printed arrays below
/* eslint indent: 0, no-multi-spaces: 0 */
/** Test that the aggregate accessibility selector works correctly */
import {expect} from '@jest/globals'
import range from 'lodash/range'
import getAggregateAccessibility from '../aggregate-accessi... |
expect(aggregateAccessibility.bins).toHaveLength(15)
expect(aggregateAccessibility.bins[0].min).toEqual(1000)
expect(aggregateAccessibility.bins[0].max).toEqual(1300)
expect(aggregateAccessibility.bins[0].value).toEqual(50)
expect(aggregateAccessibility.bins[14].min).toEqual(5200)
expect(agg... | {
throw new Error('expected aggregate accessibility to be defined')
} | conditional_block |
theme.js | /*!
| * http://plugins.krajee.com/file-input
*
* Krajee Explorer theme configuration for bootstrap-fileinput. Load this theme file after loading `fileinput.js`.
*
* Author: Kartik Visweswaran
* Copyright: 2014 - 2018, Kartik Visweswaran, Krajee.com
*
* Licensed under the BSD 3-Clause
* https://github.com/kar... | * bootstrap-fileinput v4.5.1
| random_line_split |
base64.js | /*
* author: Lisa
* Info: Base64 / UTF8
* 编码 & 解码
*/
function base64Encode(input) {
var keyStr = "ABCDEFGHIJKLMNOP" + "QRSTUVWXYZabcdef" + "ghijklmnopqrstuv" + "wxyz0123456789+/" + "=";
var output = "";
var chr1, chr2, chr3 = "";
var enc1, enc2, enc3, enc4 = "";
var i = 0;
do {
chr1 = input[i++];
chr2 =... | function UTF8Encode(str){
var temp = "",rs = "";
for( var i=0 , len = str.length; i < len; i++ ){
temp = str.charCodeAt(i).toString(16);
rs += "\\u"+ new Array(5-temp.length).join("0") + temp;
}
return rs;
}
function UTF8Decode(str){
return str.replace(/(\\u)(\w{4}|\w{2})/gi, fun... | random_line_split | |
base64.js | /*
* author: Lisa
* Info: Base64 / UTF8
* 编码 & 解码
*/
function base64En | {
var keyStr = "ABCDEFGHIJKLMNOP" + "QRSTUVWXYZabcdef" + "ghijklmnopqrstuv" + "wxyz0123456789+/" + "=";
var output = "";
var chr1, chr2, chr3 = "";
var enc1, enc2, enc3, enc4 = "";
var i = 0;
do {
chr1 = input[i++];
chr2 = input[i++];
chr3 = input[i++];
enc1 = chr1 >> 2;
enc2 = ((chr1 & 3) << 4) | (ch... | code(input) | identifier_name |
base64.js | /*
* author: Lisa
* Info: Base64 / UTF8
* 编码 & 解码
*/
function base64Encode(input) {
var keyStr = "ABCDEFGHIJKLMNOP" + "QRSTUVWXYZabcdef" + "ghijklmnopqrstuv" + "wxyz0123456789+/" + "=";
var output = "";
var chr1, chr2, chr3 = "";
var enc1, enc2, enc3, enc4 = "";
var i = 0;
do {
chr1 = input[i++];
chr2 =... | urn rs;
}
function UTF8Decode(str){
return str.replace(/(\\u)(\w{4}|\w{2})/gi, function($0,$1,$2){
return String.fromCharCode(parseInt($2,16));
});
}
exports.base64Encode = base64Encode;
exports.base64Decode = base64Decode;
exports.UTF8Encode = UTF8Encode;
exports.UTF8Decode = UTF8Decode;
| temp = str.charCodeAt(i).toString(16);
rs += "\\u"+ new Array(5-temp.length).join("0") + temp;
}
ret | conditional_block |
base64.js | /*
* author: Lisa
* Info: Base64 / UTF8
* 编码 & 解码
*/
function base64Encode(input) {
var keyStr = "ABCDEFGHIJKLMNOP" + "QRSTUVWXYZabcdef" + "ghijklmnopqrstuv" + "wxyz0123456789+/" + "=";
var output = "";
var chr1, chr2, chr3 = "";
var enc1, enc2, enc3, enc4 = "";
var i = 0;
do {
chr1 = input[i++];
chr2 =... | s.base64Encode = base64Encode;
exports.base64Decode = base64Decode;
exports.UTF8Encode = UTF8Encode;
exports.UTF8Decode = UTF8Decode;
| turn str.replace(/(\\u)(\w{4}|\w{2})/gi, function($0,$1,$2){
return String.fromCharCode(parseInt($2,16));
});
}
export | identifier_body |
utils.py | # Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# License: GNU General Public License v3. See license.txt
from __future__ import unicode_literals
import frappe
from frappe.utils import nowdate, cstr, flt, now, getdate, add_months
from frappe import throw, _
from frappe.utils import formatdate
imp... | (company, fieldname):
value = frappe.db.get_value("Company", company, fieldname)
if not value:
throw(_("Please set default value {0} in Company {1}").format(frappe.get_meta("Company").get_label(fieldname), company))
return value
def fix_total_debit_credit():
vouchers = frappe.db.sql("""select voucher_type, vou... | get_company_default | identifier_name |
utils.py | # Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# License: GNU General Public License v3. See license.txt
from __future__ import unicode_literals
import frappe
from frappe.utils import nowdate, cstr, flt, now, getdate, add_months
from frappe import throw, _
from frappe.utils import formatdate
imp... |
if d.invoice_amount > payment_amount:
all_outstanding_vouchers.append({
'voucher_no': d.voucher_no,
'voucher_type': d.voucher_type,
'posting_date': d.posting_date,
'invoice_amount': flt(d.invoice_amount, precision),
'outstanding_amount': flt(d.invoice_amount - payment_amount, precision)
})... | "amount_query": amount_query
}), (account, party_type, party, d.voucher_type, d.voucher_no))
payment_amount = -1*payment_amount[0][0] if payment_amount else 0
precision = frappe.get_precision("Sales Invoice", "outstanding_amount") | random_line_split |
utils.py | # Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# License: GNU General Public License v3. See license.txt
from __future__ import unicode_literals
import frappe
from frappe.utils import nowdate, cstr, flt, now, getdate, add_months
from frappe import throw, _
from frappe.utils import formatdate
imp... |
def fix_total_debit_credit():
vouchers = frappe.db.sql("""select voucher_type, voucher_no,
sum(debit) - sum(credit) as diff
from `tabGL Entry`
group by voucher_type, voucher_no
having sum(ifnull(debit, 0)) != sum(ifnull(credit, 0))""", as_dict=1)
for d in vouchers:
if abs(d.diff) > 0:
dr_or_cr = d.vou... | value = frappe.db.get_value("Company", company, fieldname)
if not value:
throw(_("Please set default value {0} in Company {1}").format(frappe.get_meta("Company").get_label(fieldname), company))
return value | identifier_body |
utils.py | # Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# License: GNU General Public License v3. See license.txt
from __future__ import unicode_literals
import frappe
from frappe.utils import nowdate, cstr, flt, now, getdate, add_months
from frappe import throw, _
from frappe.utils import formatdate
imp... |
def get_allocated_budget(distribution_id, posting_date, fiscal_year, yearly_budget):
if distribution_id:
distribution = {}
for d in frappe.db.sql("""select mdp.month, mdp.percentage_allocation
from `tabMonthly Distribution Percentage` mdp, `tabMonthly Distribution` md
where mdp.parent=md.name and md.fiscal... | yearly_action, monthly_action = frappe.db.get_value("Company", args.company,
["yearly_bgt_flag", "monthly_bgt_flag"])
action_for = action = ""
if monthly_action in ["Stop", "Warn"]:
budget_amount = get_allocated_budget(budget[0].distribution_id,
args.posting_date, args.fiscal_year, budget[0].bu... | conditional_block |
gamekings.py | import re
from .common import InfoExtractor
class GamekingsIE(InfoExtractor):
_VALID_URL = r'http://www\.gamekings\.tv/videos/(?P<name>[0-9a-z\-]+)'
_TEST = {
u"url": u"http://www.gamekings.tv/videos/phoenix-wright-ace-attorney-dual-destinies-review/",
u'file': u'20130811.mp4',
# MD5 ... | mobj = re.match(self._VALID_URL, url)
name = mobj.group('name')
webpage = self._download_webpage(url, name)
video_url = self._og_search_video_url(webpage)
video = re.search(r'[0-9]+', video_url)
video_id = video.group(0)
# Todo: add medium format
video_u... | random_line_split | |
gamekings.py | import re
from .common import InfoExtractor
class GamekingsIE(InfoExtractor):
| _VALID_URL = r'http://www\.gamekings\.tv/videos/(?P<name>[0-9a-z\-]+)'
_TEST = {
u"url": u"http://www.gamekings.tv/videos/phoenix-wright-ace-attorney-dual-destinies-review/",
u'file': u'20130811.mp4',
# MD5 is flaky, seems to change regularly
#u'md5': u'2f32b1f7b80fdc5cb616efb4f387f8... | identifier_body | |
gamekings.py | import re
from .common import InfoExtractor
class | (InfoExtractor):
_VALID_URL = r'http://www\.gamekings\.tv/videos/(?P<name>[0-9a-z\-]+)'
_TEST = {
u"url": u"http://www.gamekings.tv/videos/phoenix-wright-ace-attorney-dual-destinies-review/",
u'file': u'20130811.mp4',
# MD5 is flaky, seems to change regularly
#u'md5': u'2f32b1f7b... | GamekingsIE | identifier_name |
mergedDeclarationsWithExportAssignment1.ts | /// <reference path='fourslash.ts'/>
////declare module 'M'
| ////{
//// class Foo {
//// doStuff(x: number): number;
//// }
//// module Foo {
//// export var x: number;
//// }
//// export = Foo;
////}
////import Foo/*1*/ = require('M');
////var z/*3*/ = new /*2*/Foo();
////var r2/*5*/ = Foo./*4*/z;
goTo.marker('1');
verify.quickI... | random_line_split | |
__init__.py | #! ../env/bin/python
from flask import Flask
from webassets.loaders import PythonLoader as PythonAssetsLoader
from appname import assets
from appname.models import db
from appname.controllers.main import main
from appname.controllers.categories import categories
from appname.controllers.products import products
from ... |
Bootstrap(app)
app.config.from_object(object_name)
# initialize the cache
cache.init_app(app)
# initialize the debug tool bar
debug_toolbar.init_app(app)
# initialize SQLAlchemy
db.init_app(app)
db.app = app
login_manager.init_app(app)
# Import and register the differ... | return send_from_directory('/home/ahmad/workspace/python/Flask-CRUD/uploads/', filename) | identifier_body |
__init__.py | #! ../env/bin/python
from flask import Flask
from webassets.loaders import PythonLoader as PythonAssetsLoader
from appname import assets
from appname.models import db
from appname.controllers.main import main
from appname.controllers.categories import categories
from appname.controllers.products import products
from ... | (object_name):
"""
An flask application factory, as explained here:
http://flask.pocoo.org/docs/patterns/appfactories/
Arguments:
object_name: the python path of the config object,
e.g. appname.settings.ProdConfig
"""
app = Flask(__name__)
@app.route('/uploads... | create_app | identifier_name |
__init__.py | #! ../env/bin/python
from flask import Flask
from webassets.loaders import PythonLoader as PythonAssetsLoader | from appname.controllers.products import products
from appname.controllers.catalogs import catalogs
from flask_bootstrap import Bootstrap
from flask import send_from_directory
import os
from appname.extensions import (
cache,
assets_env,
debug_toolbar,
login_manager
)
def create_app(object_name):
... |
from appname import assets
from appname.models import db
from appname.controllers.main import main
from appname.controllers.categories import categories | random_line_split |
__init__.py | #! ../env/bin/python
from flask import Flask
from webassets.loaders import PythonLoader as PythonAssetsLoader
from appname import assets
from appname.models import db
from appname.controllers.main import main
from appname.controllers.categories import categories
from appname.controllers.products import products
from ... |
# register our blueprints
app.register_blueprint(main)
app.register_blueprint(categories)
app.register_blueprint(products)
app.register_blueprint(catalogs)
return app
| assets_env.register(name, bundle) | conditional_block |
generic-functions-nested.rs | // Copyright 2013-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-MI... |
// lldb-command:print x
// lldb-check:[...]$2 = -1
// lldb-command:print y
// lldb-check:[...]$3 = 2.5
// lldb-command:continue
// lldb-command:print x
// lldb-check:[...]$4 = -2.5
// lldb-command:print y
// lldb-check:[...]$5 = 1
// lldb-command:continue
// lldb-command:print x
// lldb-check:[...]$6 = -2.5
// lldb-... | // lldb-command:continue | random_line_split |
generic-functions-nested.rs | // Copyright 2013-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-MI... |
fn zzz() { () }
| {
outer(-1);
outer(-2.5f64);
} | identifier_body |
generic-functions-nested.rs | // Copyright 2013-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-MI... | () { () }
| zzz | identifier_name |
admin.ts | import {Component, OnInit} from "@angular/core";
import {Router, RouteConfig, ROUTER_DIRECTIVES} from "@angular/router-deprecated";
import {AuthService} from "../../services/auth.service";
import {AdminUsersComponent} from "./users/users";
import {AdminSubjectsComponent} from "./subjects/subjects";
import {AdminLocatio... | implements OnInit {
constructor(private router: Router, private auth: AuthService) {
this.auth.getUser().then(user => {
if (user) {
if (user.rights !== "Admin") {
this.router.navigate(["MainPath"]);
}
// User is admin
} else {
this.router.navigate(["MainPath"... | AdminpageComponent | identifier_name |
admin.ts | import {Component, OnInit} from "@angular/core";
import {Router, RouteConfig, ROUTER_DIRECTIVES} from "@angular/router-deprecated";
import {AuthService} from "../../services/auth.service";
import {AdminUsersComponent} from "./users/users";
import {AdminSubjectsComponent} from "./subjects/subjects";
import {AdminLocatio... |
// User is admin
} else {
this.router.navigate(["MainPath"]);
}
}).catch(err => {
this.router.navigate(["MainPath"]);
});
}
ngOnInit() {}
}
| {
this.router.navigate(["MainPath"]);
} | conditional_block |
admin.ts | import {Component, OnInit} from "@angular/core";
import {Router, RouteConfig, ROUTER_DIRECTIVES} from "@angular/router-deprecated";
import {AuthService} from "../../services/auth.service";
import {AdminUsersComponent} from "./users/users";
import {AdminSubjectsComponent} from "./subjects/subjects";
import {AdminLocatio... | }
ngOnInit() {}
} | }
}).catch(err => {
this.router.navigate(["MainPath"]);
}); | random_line_split |
union.rs | use racer_testutils::*;
#[test]
fn completes_union() {
let src = r#"
#[repr(C)]
union MyUnion {
f1: u32,
f2: f32,
}
let u: MyU~
"#;
let got = get_only_completion(src, None);
assert_eq!(got.matchstr, "MyUnion");
}
#[test]
fn completes_maybe_uninit() |
#[test]
fn completes_union_member() {
let src = r#"
#[repr(C)]
union MyUnion {
uint_member: u32,
float_member: f32,
}
impl MyUnion {
fn new() -> Self { Self { uint_member: 10 } }
}
let uni = unsafe { MyUnion::new().uint~ };
"#;
let got = get_only_completion(src,... | {
let src = r#"
let u: std::mem::Mayb~
"#;
let got = get_only_completion(src, None);
assert_eq!(got.matchstr, "MaybeUninit");
} | identifier_body |
union.rs | use racer_testutils::*;
#[test]
fn | () {
let src = r#"
#[repr(C)]
union MyUnion {
f1: u32,
f2: f32,
}
let u: MyU~
"#;
let got = get_only_completion(src, None);
assert_eq!(got.matchstr, "MyUnion");
}
#[test]
fn completes_maybe_uninit() {
let src = r#"
let u: std::mem::Mayb~
"#;
let got = get_only_co... | completes_union | identifier_name |
union.rs | use racer_testutils::*;
#[test]
fn completes_union() {
let src = r#"
#[repr(C)]
union MyUnion {
f1: u32,
f2: f32,
}
let u: MyU~
"#;
let got = get_only_completion(src, None);
assert_eq!(got.matchstr, "MyUnion");
}
#[test]
fn completes_maybe_uninit() {
let src = r#"
l... | }
#[test]
fn completes_union_member() {
let src = r#"
#[repr(C)]
union MyUnion {
uint_member: u32,
float_member: f32,
}
impl MyUnion {
fn new() -> Self { Self { uint_member: 10 } }
}
let uni = unsafe { MyUnion::new().uint~ };
"#;
let got = get_only_completion(src... | assert_eq!(got.matchstr, "MaybeUninit"); | random_line_split |
jquery.swipe-events.js | (function($) {
$.fn.swipeEvents = function() {
return this.each(function() {
var startX,
startY,
$this = $(this);
$this.on('touchstart', touchstart);
function touchstart(event) {
var touches = event.originalEvent.touches;
if (touches && t... | var deltaX = startX - touches[0].pageX;
var deltaY = startY - touches[0].pageY;
if (deltaX >= 50) {
$this.trigger("swipeLeft");
}
if (deltaX <= -50) {
$this.trigger("swipeRight");
}
if (deltaY >= 50) {
$... | var touches = event.originalEvent.touches;
if (touches && touches.length) { | random_line_split |
jquery.swipe-events.js | (function($) {
$.fn.swipeEvents = function() {
return this.each(function() {
var startX,
startY,
$this = $(this);
$this.on('touchstart', touchstart);
function touchstart(event) {
var touches = event.originalEvent.touches;
if (touches && t... |
});
};
})(jQuery);
| {
$this.off('touchmove', touchmove);
event.preventDefault();
} | identifier_body |
jquery.swipe-events.js | (function($) {
$.fn.swipeEvents = function() {
return this.each(function() {
var startX,
startY,
$this = $(this);
$this.on('touchstart', touchstart);
function touchstart(event) {
var touches = event.originalEvent.touches;
if (touches && t... |
}
event.preventDefault();
}
function touchend(event) {
$this.off('touchmove', touchmove);
event.preventDefault();
}
});
};
})(jQuery);
| {
$this.off('touchmove', touchmove);
$this.off('touchend', touchend);
} | conditional_block |
jquery.swipe-events.js | (function($) {
$.fn.swipeEvents = function() {
return this.each(function() {
var startX,
startY,
$this = $(this);
$this.on('touchstart', touchstart);
function touchstart(event) {
var touches = event.originalEvent.touches;
if (touches && t... | (event) {
var touches = event.originalEvent.touches;
if (touches && touches.length) {
var deltaX = startX - touches[0].pageX;
var deltaY = startY - touches[0].pageY;
if (deltaX >= 50) {
$this.trigger("swipeLeft");
}
if (deltaX <= -... | touchmove | identifier_name |
fmbt.py | # fMBT, free Model Based Testing tool
# Copyright (c) 2012 Intel Corporation.
#
# This program is free software; you can redistribute it and/or modify it
# under the terms and conditions of the GNU Lesser General Public License,
# version 2.1, as published by the Free Software Foundation.
#
# This program is distribute... | rv = "".join(msg)
elif c == "\n":
rv = "".join(msg)
elif len(msg) == bytes:
rv = "".join(msg)
else:
c = self._conn.recv(1)
return rv
def readline(self):
return ... | while c and not rv:
msg.append(c)
if c == "\r": | random_line_split |
fmbt.py | # fMBT, free Model Based Testing tool
# Copyright (c) 2012 Intel Corporation.
#
# This program is free software; you can redistribute it and/or modify it
# under the terms and conditions of the GNU Lesser General Public License,
# version 2.1, as published by the Free Software Foundation.
#
# This program is distribute... |
def reportOutput(msg):
try: file("/tmp/fmbt.reportOutput", "a").write("%s\n" % (msg,))
except: pass
def setAdapterLogTimeFormat(strftime_format):
"""
Use given time format string in timestamping adapterlog messages
"""
global _g_fmbt_adapterlogtimeformat
_g_fmbt_adapterlogtimeformat = str... | """
Return current low-level adapter log writer function.
"""
global _adapterlogWriter
return _adapterlogWriter | identifier_body |
fmbt.py | # fMBT, free Model Based Testing tool
# Copyright (c) 2012 Intel Corporation.
#
# This program is free software; you can redistribute it and/or modify it
# under the terms and conditions of the GNU Lesser General Public License,
# version 2.1, as published by the Free Software Foundation.
#
# This program is distribute... |
else:
c = self._conn.recv(1)
return rv
def readline(self):
return self.read()
def write(self, msg):
self._conn.sendall(msg)
def flush(self):
pass
connfile = SocketToFile(_g_debug_conn)
debugger = pdb.Pd... | rv = "".join(msg) | conditional_block |
fmbt.py | # fMBT, free Model Based Testing tool
# Copyright (c) 2012 Intel Corporation.
#
# This program is free software; you can redistribute it and/or modify it
# under the terms and conditions of the GNU Lesser General Public License,
# version 2.1, as published by the Free Software Foundation.
#
# This program is distribute... | (self, socket_conn):
self._conn = socket_conn
def read(self, bytes=-1):
msg = []
rv = ""
try:
c = self._conn.recv(1)
except KeyboardInterrupt:
self._conn.close()
raise
while c and not rv:
... | __init__ | identifier_name |
NesingwarysTrappingApparatus.tsx | import { formatNumber } from 'common/format';
import SPELLS from 'common/SPELLS';
import RESOURCE_TYPES from 'game/RESOURCE_TYPES';
import { ResourceIcon } from 'interface';
import Analyzer, { Options, SELECTED_PLAYER } from 'parser/core/Analyzer';
import Events, { ResourceChangeEvent } from 'parser/core/Events';
impor... | () {
return (
<Statistic
position={STATISTIC_ORDER.CORE()}
size="flexible"
category={STATISTIC_CATEGORY.ITEMS}
>
<BoringSpellValueText spellId={SPELLS.NESINGWARYS_TRAPPING_APPARATUS_EFFECT.id}>
<ResourceIcon id={RESOURCE_TYPES.FOCUS.id} noLink /> {this.focusGain... | statistic | identifier_name |
NesingwarysTrappingApparatus.tsx | import { formatNumber } from 'common/format';
import SPELLS from 'common/SPELLS';
import RESOURCE_TYPES from 'game/RESOURCE_TYPES';
import { ResourceIcon } from 'interface';
import Analyzer, { Options, SELECTED_PLAYER } from 'parser/core/Analyzer';
import Events, { ResourceChangeEvent } from 'parser/core/Events';
impor... |
this.addEventListener(
Events.resourcechange
.by(SELECTED_PLAYER)
.spell(SPELLS.NESINGWARYS_TRAPPING_APPARATUS_ENERGIZE),
this.onEnergize,
);
}
onEnergize(event: ResourceChangeEvent) {
this.focusGained += event.resourceChange;
this.focusWasted += event.waste;
}
get... | {
return;
} | conditional_block |
NesingwarysTrappingApparatus.tsx | import { formatNumber } from 'common/format';
import SPELLS from 'common/SPELLS';
import RESOURCE_TYPES from 'game/RESOURCE_TYPES';
import { ResourceIcon } from 'interface';
import Analyzer, { Options, SELECTED_PLAYER } from 'parser/core/Analyzer';
import Events, { ResourceChangeEvent } from 'parser/core/Events';
impor... | }
get possibleFocus() {
return formatNumber(
this.steadyShot.possibleAdditionalFocusFromNesingwary +
this.rapidFire.possibleAdditionalFocusFromNesingwary,
);
}
statistic() {
return (
<Statistic
position={STATISTIC_ORDER.CORE()}
size="flexible"
category={... | random_line_split | |
NesingwarysTrappingApparatus.tsx | import { formatNumber } from 'common/format';
import SPELLS from 'common/SPELLS';
import RESOURCE_TYPES from 'game/RESOURCE_TYPES';
import { ResourceIcon } from 'interface';
import Analyzer, { Options, SELECTED_PLAYER } from 'parser/core/Analyzer';
import Events, { ResourceChangeEvent } from 'parser/core/Events';
impor... |
onEnergize(event: ResourceChangeEvent) {
this.focusGained += event.resourceChange;
this.focusWasted += event.waste;
}
get effectiveFocus() {
return formatNumber(
this.steadyShot.additionalFocusFromNesingwary + this.rapidFire.additionalFocusFromNesingwary,
);
}
get possibleFocus() {
... | {
super(options);
this.active = this.selectedCombatant.hasLegendaryByBonusID(
SPELLS.NESINGWARYS_TRAPPING_APPARATUS_EFFECT.bonusID,
);
if (!this.active) {
return;
}
this.addEventListener(
Events.resourcechange
.by(SELECTED_PLAYER)
.spell(SPELLS.NESINGWARYS_TRAPP... | identifier_body |
method_definitions.rs | struct Point<T> {
x: T,
y: T,
}
/* Declare `impl<T>` to specify we are implementing
* methods on type `Point<T>`
*/
impl<T> Point<T> { | &self.x
}
// fn distance_from_origin<f32>(&self) -> f32 {
// (self.x.powi(2) + self.y.powi(2)).sqrt()
// }
}
struct PointMixed<T, U> {
x: T,
y: U,
}
impl<T, U> PointMixed<T, U> {
// `V` and `W` types are only relevant to the method definition
fn mixup<V, W>(self, other: Po... | /* Getter method `x` returns "reference" to the
* data in field type `T`
*/
fn x(&self) -> &T { | random_line_split |
method_definitions.rs | struct Point<T> {
x: T,
y: T,
}
/* Declare `impl<T>` to specify we are implementing
* methods on type `Point<T>`
*/
impl<T> Point<T> {
/* Getter method `x` returns "reference" to the
* data in field type `T`
*/
fn | (&self) -> &T {
&self.x
}
// fn distance_from_origin<f32>(&self) -> f32 {
// (self.x.powi(2) + self.y.powi(2)).sqrt()
// }
}
struct PointMixed<T, U> {
x: T,
y: U,
}
impl<T, U> PointMixed<T, U> {
// `V` and `W` types are only relevant to the method definition
fn mixup<V, W>... | x | identifier_name |
process.assets.pre.js.typescript.ts | import * as gulp from 'gulp';
import * as gulpLoadPlugins from 'gulp-load-plugins';
import * as merge from 'merge-stream';
import { join } from 'path';
import { TMP_DIR, TOOLS_DIR, BOOTSTRAP_MODULE, ENV } from '../../config';
import { makeTsProject, templateLocals } from '../../utils';
const plugins = <any>gulpLoadPl... | (env: string): string[] {
switch (env) {
case 'dev':
return ['!' + join(TMP_DIR, '**/*.spec.ts'),
'!' + join(TMP_DIR, '**/*.e2e-spec.ts')];
case 'test':
return ['!' + join(TMP_DIR, '**/*.e2e-spec.ts'),
'!' + join(TMP_DIR, `${BOOTSTRAP_MODULE}.ts`)];
case 'e2e':
... | getGlobBasedOnEnv | identifier_name |
process.assets.pre.js.typescript.ts | import * as gulp from 'gulp';
import * as gulpLoadPlugins from 'gulp-load-plugins';
import * as merge from 'merge-stream';
import { join } from 'path';
import { TMP_DIR, TOOLS_DIR, BOOTSTRAP_MODULE, ENV } from '../../config';
import { makeTsProject, templateLocals } from '../../utils';
const plugins = <any>gulpLoadPl... | switch (env) {
case 'dev':
return ['!' + join(TMP_DIR, '**/*.spec.ts'),
'!' + join(TMP_DIR, '**/*.e2e-spec.ts')];
case 'test':
return ['!' + join(TMP_DIR, '**/*.e2e-spec.ts'),
'!' + join(TMP_DIR, `${BOOTSTRAP_MODULE}.ts`)];
case 'e2e':
return ['!' + join(TMP_D... | .pipe(gulp.dest(TMP_DIR));
};
function getGlobBasedOnEnv(env: string): string[] { | random_line_split |
process.assets.pre.js.typescript.ts | import * as gulp from 'gulp';
import * as gulpLoadPlugins from 'gulp-load-plugins';
import * as merge from 'merge-stream';
import { join } from 'path';
import { TMP_DIR, TOOLS_DIR, BOOTSTRAP_MODULE, ENV } from '../../config';
import { makeTsProject, templateLocals } from '../../utils';
const plugins = <any>gulpLoadPl... | {
switch (env) {
case 'dev':
return ['!' + join(TMP_DIR, '**/*.spec.ts'),
'!' + join(TMP_DIR, '**/*.e2e-spec.ts')];
case 'test':
return ['!' + join(TMP_DIR, '**/*.e2e-spec.ts'),
'!' + join(TMP_DIR, `${BOOTSTRAP_MODULE}.ts`)];
case 'e2e':
return ['!' + join(TMP... | identifier_body | |
0056_v350_custom_venv_history.py | # -*- coding: utf-8 -*-
# Generated by Django 1.11.16 on 2019-01-22 22:20
from __future__ import unicode_literals
from django.db import migrations, models
class | (migrations.Migration):
dependencies = [
('main', '0055_v340_add_grafana_notification'),
]
operations = [
migrations.AddField(
model_name='inventoryupdate',
name='custom_virtualenv',
field=models.CharField(blank=True, default=None, help_text='Local absol... | Migration | identifier_name |
0056_v350_custom_venv_history.py | # -*- coding: utf-8 -*-
# Generated by Django 1.11.16 on 2019-01-22 22:20
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
| dependencies = [
('main', '0055_v340_add_grafana_notification'),
]
operations = [
migrations.AddField(
model_name='inventoryupdate',
name='custom_virtualenv',
field=models.CharField(blank=True, default=None, help_text='Local absolute file path containing a cu... | identifier_body | |
0056_v350_custom_venv_history.py | # -*- coding: utf-8 -*-
# Generated by Django 1.11.16 on 2019-01-22 22:20
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('main', '0055_v340_add_grafana_notification'),
]
operations = [
migrations.... | ),
migrations.AddField(
model_name='job',
name='custom_virtualenv',
field=models.CharField(blank=True, default=None, help_text='Local absolute file path containing a custom Python virtualenv to use', max_length=100, null=True),
),
] | field=models.CharField(blank=True, default=None, help_text='Local absolute file path containing a custom Python virtualenv to use', max_length=100, null=True), | random_line_split |
frame.ts |
function moveStart (event) {
let dragFrame = event.target.closest(".window")
let rect = dragFrame.getBoundingClientRect()
let dragOffX = rect.left - event.pageX
let dragOffY = rect.top - event.pageY
function move (event) {
dragFrame.style.left = event.pageX + dragOffX + "px"
dragF... | (f : () => void) : void {
this.closeFrame = f
}
constructor (settings) {
/* Create the frame div */
this.container = document.createElement("div")
this.container.className = "window"
if (settings.frameId == null) {
this.container.style.height = settings.h +... | onClose | identifier_name |
frame.ts |
function moveStart (event) {
let dragFrame = event.target.closest(".window")
let rect = dragFrame.getBoundingClientRect()
let dragOffX = rect.left - event.pageX
let dragOffY = rect.top - event.pageY
function move (event) {
dragFrame.style.left = event.pageX + dragOffX + "px"
dragF... |
/* Add everything to the Frame and add it to the document */
this.container.appendChild(tb)
this.container.appendChild(this.content)
document.body.appendChild(this.container)
}
} | {
this.content.id = settings.contentId
} | conditional_block |
frame.ts |
function moveStart (event) {
let dragFrame = event.target.closest(".window")
let rect = dragFrame.getBoundingClientRect()
let dragOffX = rect.left - event.pageX
let dragOffY = rect.top - event.pageY
function move (event) {
dragFrame.style.left = event.pageX + dragOffX + "px"
dragF... |
document.addEventListener("mousemove", move)
document.addEventListener("mouseup", moveEnd)
}
export class Frame {
public container: HTMLDivElement
public content: HTMLDivElement
private closeFrame () : void {
document.body.removeChild(this.container)
}
public onClose (f : () => ... | {
document.removeEventListener("mousemove", move)
document.removeEventListener("mouseup", moveEnd)
} | identifier_body |
frame.ts | function moveStart (event) {
let dragFrame = event.target.closest(".window")
let rect = dragFrame.getBoundingClientRect()
let dragOffX = rect.left - event.pageX
let dragOffY = rect.top - event.pageY
function move (event) {
dragFrame.style.left = event.pageX + dragOffX + "px"
dragFr... | }
document.addEventListener("mousemove", move)
document.addEventListener("mouseup", moveEnd)
}
export class Frame {
public container: HTMLDivElement
public content: HTMLDivElement
private closeFrame () : void {
document.body.removeChild(this.container)
}
public onClose (f : (... | function moveEnd (event) {
document.removeEventListener("mousemove", move)
document.removeEventListener("mouseup", moveEnd) | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.