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 |
|---|---|---|---|---|
tree.controller.ts | import {Body, Controller, Delete, Get, HttpStatus, Param, Post, Put, Res, Response} from '@nestjs/common';
import {IOuterNode} from '../../../src/interfaces/IOuterNode';
import {TreeDataService} from './tree-data.service'; | @Controller('tree')
export class TreeController {
public constructor(private treeData: TreeDataService) {
}
@Get()
public getRoot(): IOuterNode[] {
return this.treeData.getChildren(null);
}
@Get(':id')
public getChildren(@Param('id') nodeId: string): IOuterNode[] {
if (nodeId === 'null') {
... | random_line_split | |
tree.controller.ts | import {Body, Controller, Delete, Get, HttpStatus, Param, Post, Put, Res, Response} from '@nestjs/common';
import {IOuterNode} from '../../../src/interfaces/IOuterNode';
import {TreeDataService} from './tree-data.service';
@Controller('tree')
export class TreeController {
public constructor(private treeData: TreeDa... |
@Post()
public add(@Body() node: Partial<IOuterNode>): IOuterNode {
return this.treeData.add(node);
}
@Delete(':id')
public remove(@Res() response: Response, @Param('id') nodeId: string): any {
const result = this.treeData.remove(nodeId);
if (result) {
response.status(HttpStatus.NO_CONTE... | {
if (nodeId === 'null') {
return this.getRoot();
}
return this.treeData.getChildren(nodeId);
} | identifier_body |
tree.controller.ts | import {Body, Controller, Delete, Get, HttpStatus, Param, Post, Put, Res, Response} from '@nestjs/common';
import {IOuterNode} from '../../../src/interfaces/IOuterNode';
import {TreeDataService} from './tree-data.service';
@Controller('tree')
export class TreeController {
public constructor(private treeData: TreeDa... |
return this.treeData.getChildren(nodeId);
}
@Post()
public add(@Body() node: Partial<IOuterNode>): IOuterNode {
return this.treeData.add(node);
}
@Delete(':id')
public remove(@Res() response: Response, @Param('id') nodeId: string): any {
const result = this.treeData.remove(nodeId);
if (... | {
return this.getRoot();
} | conditional_block |
tree.controller.ts | import {Body, Controller, Delete, Get, HttpStatus, Param, Post, Put, Res, Response} from '@nestjs/common';
import {IOuterNode} from '../../../src/interfaces/IOuterNode';
import {TreeDataService} from './tree-data.service';
@Controller('tree')
export class | {
public constructor(private treeData: TreeDataService) {
}
@Get()
public getRoot(): IOuterNode[] {
return this.treeData.getChildren(null);
}
@Get(':id')
public getChildren(@Param('id') nodeId: string): IOuterNode[] {
if (nodeId === 'null') {
return this.getRoot();
}
return thi... | TreeController | identifier_name |
cerberus_run.py | #!/usr/bin/env python
import syslog
from subprocess import call
import urllib2
import json
import re
import docker_login
from user_data import get_user_data
# Starts a docker run for a given repo
# This will effectively call `docker run <flags> <repo>:<tag>`
# This service is monitored by Upstart
# User Data
# docker.... |
syslog.syslog(syslog.LOG_WARNING, 'Booting %s with %s...' % (repo_with_tag, flags))
if call(['docker','run','--cidfile=/var/run/docker/container.cid'] + flags + [repo_with_tag]) != 0:
raise Exception("Failed to run docker repo %s" % repo_with_tag)
| raise Exception("Failed to pull docker repo %s" % repo_with_tag) | conditional_block |
cerberus_run.py | #!/usr/bin/env python
import syslog
from subprocess import call
import urllib2
import json
import re
import docker_login
from user_data import get_user_data
# Starts a docker run for a given repo
# This will effectively call `docker run <flags> <repo>:<tag>`
# This service is monitored by Upstart
# User Data
# docker.... | repo = docker['repo']
tag = docker.get('tag', 'latest')
repo_with_tag = "%s:%s" % (repo, tag)
flags = docker.get('flags', [])
# Allow flags to be a string or an array
if isinstance(flags,basestring):
flags = [flags]
flags = map(lambda flag: re.sub('-(\w)\s', r'-\1=', flag), flags) # Change `-x ...` to `-x=...`
# ... |
user_data = get_user_data()
docker = user_data['docker'] | random_line_split |
_operation_status_operations.py | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may ... |
def get(
self,
location, # type: str
operation_id, # type: str
**kwargs # type: Any
):
# type: (...) -> "_models.OperationResource"
"""Gets the operation status for a resource.
Gets the operation status for a resource.
:param location:
... | self._client = client
self._serialize = serializer
self._deserialize = deserializer
self._config = config | identifier_body |
_operation_status_operations.py | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may ... | url = self.get.metadata['url'] # type: ignore
path_format_arguments = {
'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'),
'location': self._serialize.url("location", location, 'str'),
'operationId': self._seri... | error_map.update(kwargs.pop('error_map', {}))
api_version = "2021-07-01"
accept = "application/json"
# Construct URL | random_line_split |
_operation_status_operations.py | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may ... | (self, client, config, serializer, deserializer):
self._client = client
self._serialize = serializer
self._deserialize = deserializer
self._config = config
def get(
self,
location, # type: str
operation_id, # type: str
**kwargs # type: Any
):
... | __init__ | identifier_name |
_operation_status_operations.py | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may ... |
return deserialized
get.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.DataProtection/locations/{location}/operationStatus/{operationId}'} # type: ignore
| return cls(pipeline_response, deserialized, {}) | conditional_block |
range_set.rs | #![allow(dead_code)]
//! A set library to aid character set manipulation.
//!
//! `range_set` aims to make it easier to handle set manipulation for characters
//! over ranges. For example, a unicode library may expose character ranges such
//! as `('0', '9')` as a sequence of digits. If I was already later state I wou... |
}
// Insert value only when it's not a subset.
if !subset { ret.insert(Range(min_val, max_val)); }
}
*self = Set(ret);
}
pub fn is_empty(&self) -> bool { self.0.is_empty() }
pub fn remove(&mut self, value: Range) {
let mut ret = BTreeSet::new();... | { ret.insert(Range(min, max)); } | conditional_block |
range_set.rs | #![allow(dead_code)]
//! A set library to aid character set manipulation.
//!
//! `range_set` aims to make it easier to handle set manipulation for characters
//! over ranges. For example, a unicode library may expose character ranges such
//! as `('0', '9')` as a sequence of digits. If I was already later state I wou... | () -> Self { Set(BTreeSet::new()) }
pub fn insert(&mut self, value: Range) {
let mut ret = BTreeSet::new();
// value is a complete subset of one of the other ranges.
let mut subset = false;
// Borrowing self blocks later operation. Add a new scope.
{ let Set(ref set) = *se... | new | identifier_name |
range_set.rs | #![allow(dead_code)]
//! A set library to aid character set manipulation.
//!
//! `range_set` aims to make it easier to handle set manipulation for characters
//! over ranges. For example, a unicode library may expose character ranges such
//! as `('0', '9')` as a sequence of digits. If I was already later state I wou... |
// Intersection of `A` & `B` is `A - (A - B)`: 123 & 345 = 3.
pub fn intersection(&self, value: &Self) -> Self {
let diff = self.difference(value);
self.difference(&diff)
}
// 123 - 345 = 12.
pub fn difference(&self, value: &Self) -> Self {
let mut ret = self.clone();
... | {
let mut ret = self.clone();
// Loop over the btreeset of Range(char, char).
for &x in &value.0 { ret.insert(x) }
ret
} | identifier_body |
range_set.rs | #![allow(dead_code)]
//! A set library to aid character set manipulation.
//!
//! `range_set` aims to make it easier to handle set manipulation for characters
//! over ranges. For example, a unicode library may expose character ranges such
//! as `('0', '9')` as a sequence of digits. If I was already later state I wou... |
#[derive(Clone, Copy, Debug, PartialOrd, Ord, PartialEq, Eq)]
pub struct Range(pub char, pub char);
impl fmt::Display for Range {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "({}, {})", self.0, self.1)
}
}
impl Range {
fn contains(&self, c: char) -> bool {
self.0 <= c... |
use std::collections::BTreeSet;
use std::fmt::{self, Display};
use parse::NextPrev; | random_line_split |
dma.rs | use hardware::cpu;
use hardware::cpu::MapperHolder;
pub struct DmaController {
running: bool,
base: u16,
cycles: usize,
pub oam_ram: [u8; 160],
}
impl cpu::Handler for DmaController {
fn read(&self, address: u16) -> u8 {
match address {
0xFE00..=0xFE9F => self.oam_ram[address a... | }
self.cycles += 1;
}
}
| {
if !self.running {
return;
}
match self.cycles {
0 => {
// There's a 1 cycle wait after enabling DMA
}
1..=160 => {
let dma_step = self.cycles as u16 - 1;
let from = self.base + dma_step;
... | identifier_body |
dma.rs | use hardware::cpu;
use hardware::cpu::MapperHolder;
pub struct DmaController {
running: bool,
base: u16,
cycles: usize,
pub oam_ram: [u8; 160],
}
impl cpu::Handler for DmaController {
fn | (&self, address: u16) -> u8 {
match address {
0xFE00..=0xFE9F => self.oam_ram[address as usize - 0xFE00],
// TODO: not sure what should happen here, so let's just crash
0xFF46 => panic!("Trying to read from DMA."),
_ => unreachable!(),
}
}
fn writ... | read | identifier_name |
dma.rs | use hardware::cpu;
use hardware::cpu::MapperHolder;
| cycles: usize,
pub oam_ram: [u8; 160],
}
impl cpu::Handler for DmaController {
fn read(&self, address: u16) -> u8 {
match address {
0xFE00..=0xFE9F => self.oam_ram[address as usize - 0xFE00],
// TODO: not sure what should happen here, so let's just crash
0xFF46 =... | pub struct DmaController {
running: bool,
base: u16, | random_line_split |
live_audio_sample.py | import numpy as np
import matplotlib.pyplot as plt #Used for graphing audio tests
import pyaudio as pa
import wave
from time import sleep
#Constants used for sampling audio
CHUNK = 1024
FORMAT = pa.paInt16
CHANNELS = 1
RATE = 44100 # Must match rate at which mic actually samples sound
RECORD_TIMEFRAME = 1.0 #Time in s... | (wav_file=OUTPUT_FILE):
"""Analyzes the audio sample [wav_file] (must be a 16-bit WAV file with
one channel) and returns maximum magnitude of the most prominent sound
and the frequency thresholds it falls between.
Basic procedure of processing audio taken from:
< http://samcarcagno.altervista.org/b... | getAvgFreq | identifier_name |
live_audio_sample.py | import numpy as np
import matplotlib.pyplot as plt #Used for graphing audio tests
import pyaudio as pa
import wave
from time import sleep
#Constants used for sampling audio
CHUNK = 1024
FORMAT = pa.paInt16
CHANNELS = 1
RATE = 44100 # Must match rate at which mic actually samples sound
RECORD_TIMEFRAME = 1.0 #Time in s... |
#Get sampling frequency
sample_freq = sound_sample.getframerate()
#Extract audio frames to be analyzed
# audio_frames = sound_sample.readframes(sound_sample.getnframes())
audio_frames = sound_sample.readframes(1024)
converted_val = []
#COnvert byte objects into frequency values per frame
for i in range(0,le... | #Open wav file for analysis
sound_sample = wave.open(wav_file, "rb") | random_line_split |
live_audio_sample.py | import numpy as np
import matplotlib.pyplot as plt #Used for graphing audio tests
import pyaudio as pa
import wave
from time import sleep
#Constants used for sampling audio
CHUNK = 1024
FORMAT = pa.paInt16
CHANNELS = 1
RATE = 44100 # Must match rate at which mic actually samples sound
RECORD_TIMEFRAME = 1.0 #Time in s... |
else:
converted_val.append(ord(audio_frames[i])+(256*ord(audio_frames[i+1])))
#Fit into numpy array for FFT analysis
freq_per_frame = np.array(converted_val)
# Get amplitude of soundwave section
freq = np.fft.fft(freq_per_frame)
amplitude = np.abs(freq)
amplitude = amplitude/float(len(freq_per_frame))
... | converted_val.append(-(ord(audio_frames[i])+(256*(255-ord(audio_frames[i+1]))))) | conditional_block |
live_audio_sample.py | import numpy as np
import matplotlib.pyplot as plt #Used for graphing audio tests
import pyaudio as pa
import wave
from time import sleep
#Constants used for sampling audio
CHUNK = 1024
FORMAT = pa.paInt16
CHANNELS = 1
RATE = 44100 # Must match rate at which mic actually samples sound
RECORD_TIMEFRAME = 1.0 #Time in s... | for i in range(0,len(audio_frames),2):
if ord(audio_frames[i+1])>127:
converted_val.append(-(ord(audio_frames[i])+(256*(255-ord(audio_frames[i+1])))))
else:
converted_val.append(ord(audio_frames[i])+(256*ord(audio_frames[i+1])))
#Fit into numpy array for FFT analysis
freq_per_frame = np.array(converted_v... | """Analyzes the audio sample [wav_file] (must be a 16-bit WAV file with
one channel) and returns maximum magnitude of the most prominent sound
and the frequency thresholds it falls between.
Basic procedure of processing audio taken from:
< http://samcarcagno.altervista.org/blog/basic-sound-processin... | identifier_body |
index.ts | import { observable } from 'mobx';
import { generateId } from 'utils/generate-id';
import { TimelineVector } from 'core/primitives/timeline-vector';
import { Data } from 'core/models/graph/node';
export interface SnipParams {
length: TimelineVector;
data?: Data;
}
export const enum SnipType {
container = 'cont... | length: TimelineVector;
@observable
data: Data = null;
constructor(params: SnipParams) {
const { data = null, length } = params;
this.length = length || new TimelineVector(2);
this.data = data;
}
end(position: TimelineVector): TimelineVector {
return position.add(this.length);
}
stat... | id = generateId();
@observable | random_line_split |
index.ts | import { observable } from 'mobx';
import { generateId } from 'utils/generate-id';
import { TimelineVector } from 'core/primitives/timeline-vector';
import { Data } from 'core/models/graph/node';
export interface SnipParams {
length: TimelineVector;
data?: Data;
}
export const enum SnipType {
container = 'cont... | (clip: Snip) {
return new Snip({
length: clip.length,
});
}
}
| copy | identifier_name |
index.ts | import { observable } from 'mobx';
import { generateId } from 'utils/generate-id';
import { TimelineVector } from 'core/primitives/timeline-vector';
import { Data } from 'core/models/graph/node';
export interface SnipParams {
length: TimelineVector;
data?: Data;
}
export const enum SnipType {
container = 'cont... |
}
| {
return new Snip({
length: clip.length,
});
} | identifier_body |
dsb.ts | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
// THIS CODE IS GENERATED - DO NOT MODIFY
// See angular/tools/gulp-tasks/cldr/extract.js
function plural(n: number... | 'dsb',
[
['dop.', 'wótp.'],
['dopołdnja', 'wótpołdnja'],
],
[
['dopołdnja', 'wótpołdnja'],
,
],
[
['n', 'p', 'w', 's', 's', 'p', 's'], ['nje', 'pón', 'wał', 'srj', 'stw', 'pět', 'sob'],
['njeźela', 'pónjeźele', 'wałtora', 'srjoda', 'stwórtk', 'pětk', 'sobota'],
['nj', 'pó', 'wa',... | return 3;
return 5;
}
export default [ | random_line_split |
dsb.ts | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
// THIS CODE IS GENERATED - DO NOT MODIFY
// See angular/tools/gulp-tasks/cldr/extract.js
function | (n: number): number {
let i = Math.floor(Math.abs(n)), v = n.toString().replace(/^[^.]*\.?/, '').length,
f = parseInt(n.toString().replace(/^[^.]*\.?/, ''), 10) || 0;
if (v === 0 && i % 100 === 1 || f % 100 === 1) return 1;
if (v === 0 && i % 100 === 2 || f % 100 === 2) return 2;
if (v === 0 && i % 100 ==... | plural | identifier_name |
dsb.ts | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
// THIS CODE IS GENERATED - DO NOT MODIFY
// See angular/tools/gulp-tasks/cldr/extract.js
function plural(n: number... |
export default [
'dsb',
[
['dop.', 'wótp.'],
['dopołdnja', 'wótpołdnja'],
],
[
['dopołdnja', 'wótpołdnja'],
,
],
[
['n', 'p', 'w', 's', 's', 'p', 's'], ['nje', 'pón', 'wał', 'srj', 'stw', 'pět', 'sob'],
['njeźela', 'pónjeźele', 'wałtora', 'srjoda', 'stwórtk', 'pětk', 'sobota'],
... | {
let i = Math.floor(Math.abs(n)), v = n.toString().replace(/^[^.]*\.?/, '').length,
f = parseInt(n.toString().replace(/^[^.]*\.?/, ''), 10) || 0;
if (v === 0 && i % 100 === 1 || f % 100 === 1) return 1;
if (v === 0 && i % 100 === 2 || f % 100 === 2) return 2;
if (v === 0 && i % 100 === Math.floor(i % 100... | identifier_body |
util_spec.js | /*************************GO-LICENSE-START*********************************
* Copyright 2018 ThoughtWorks, Inc.
*
* 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... |
Util.enable("btn");
assertFalse($("btn").disabled);
assertFalse($("btn").hasClassName("disabled"));
});
it("test_escapeDotsFromId", function () {
assertEquals("#2\\.1\\.1\\.2", Util.escapeDotsFromId("2.1.1.2"));
});
it("test_ajax_modal_success", function () {
... | assertTrue($("btn").hasClassName("disabled")); | random_line_split |
record-pat.rs | // Copyright 2012 The Rust Project Developers. See the 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 http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
enum t1 { a(int)... | // file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT. | random_line_split |
record-pat.rs | // Copyright 2012 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 fn main() {
assert_eq!(m(c(T2 {x: a(10), y: 5}, 4u)), 10);
assert_eq!(m(c(T2 {x: b(10u), y: 5}, 4u)), 19);
}
| { return ((m + z) as int) + y; } | conditional_block |
record-pat.rs | // Copyright 2012 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 ... | {
assert_eq!(m(c(T2 {x: a(10), y: 5}, 4u)), 10);
assert_eq!(m(c(T2 {x: b(10u), y: 5}, 4u)), 19);
} | identifier_body | |
record-pat.rs | // Copyright 2012 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 ... | {x: t1, y: int}
enum t3 { c(T2, uint), }
fn m(input: t3) -> int {
match input {
c(T2 {x: a(m), ..}, _) => { return m; }
c(T2 {x: b(m), y: y}, z) => { return ((m + z) as int) + y; }
}
}
pub fn main() {
assert_eq!(m(c(T2 {x: a(10), y: 5}, 4u)), 10);
assert_eq!(m(c(T2 {x: b(10u), y: 5}, 4u))... | T2 | identifier_name |
Gruntfile.js | /* License: MIT.
* Copyright (C) 2013, 2014, Uri Shaked.
*/
'use strict';
module.exports = function (grunt) {
// load all grunt tasks
require('matchdep').filterDev('grunt-*').forEach(grunt.loadNpmTasks);
grunt.initConfig({
karma: {
unit: {
configFile: 'karma.conf.js',
singleRun: true
... | 'jshint',
'karma'
]);
grunt.registerTask('build', [
'jshint',
'uglify'
]);
grunt.registerTask('default', ['build']);
}; | }
}
});
grunt.registerTask('test', [
| random_line_split |
conf.py |
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
#sys.path.insert(0, os.path.abspath('.'))
# -- General configuration ----------... | sys.modules[mod_name] = mock.Mock() | conditional_block | |
conf.py | extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
#sys.path.insert(0, os.path.abspath('.'))
# -- General configuration ----------------... |
# -- Options for LaTeX output ---------------------------------------------
latex_elements = {
# The paper size ('letterpaper' or 'a4paper').
#'papersize': 'letterpaper',
# The font size ('10pt', '11pt' or '12pt').
#'pointsize': '10pt',
# Additional stuff for the LaTeX preamble.
#'preamble': '',
}
# Grouping the ... | # Output file base name for HTML help builder.
htmlhelp_basename = 'hdfsdoc' | random_line_split |
sintesi-richiesta.model.ts | import {Tipologia} from './tipologia.model';
import {Sede} from './sede.model';
import {Localita} from './localita.model';
import {Richiedente} from './richiedente.model';
import {Fonogramma} from './fonogramma.model';
import {Complessita} from './complessita.model';
import { Partenza } from './partenza.model';
import ... | /**
* ricezione della richiesta (via telefono, ecc.)
*/
public istanteRicezioneRichiesta: Date,
/**
* Indica lo stato della richiesa di soccorso
*/
public stato: string,
/**
* priorita della richiesta (da 0 a 4). 0 = Altissima, 1 = Alt... | /**
* è l'operatore che inserisce la richiesta
*/
public operatore: Operatore, | random_line_split |
sintesi-richiesta.model.ts | import {Tipologia} from './tipologia.model';
import {Sede} from './sede.model';
import {Localita} from './localita.model';
import {Richiedente} from './richiedente.model';
import {Fonogramma} from './fonogramma.model';
import {Complessita} from './complessita.model';
import { Partenza } from './partenza.model';
import ... | (
/**
* id
*/
public id: string,
/**
* E' il codice della Richiesta di Assistenza
*/
public codice: string,
/**
* è l'operatore che inserisce la richiesta
*/
public operatore: Operatore,
/**
* ricezion... | constructor | identifier_name |
UploadRosters.tsx | import * as React from "react";
import XLSX from 'xlsx'
import request from 'request'
export const UploadRosters = () => {
const [schoolId, setSchoolId] = React.useState<Number>();
const [teachers, setTeachers] = React.useState<Array<any>>([]);
const [students, setStudents] = React.useState<Array<any>>([])
... | (e) {
setSchoolId(e.target.value)
}
function handleChangeFile(file) {
const fileReader = new FileReader();
fileReader.onload = (e) => {
const data = new Uint8Array(e.target.result);
const workbook = XLSX.read(data, { type: 'array', });
const sheet1 = workbook.Sheets[workbook.SheetNam... | handleSchoolIdChange | identifier_name |
UploadRosters.tsx | import * as React from "react";
import XLSX from 'xlsx'
import request from 'request'
export const UploadRosters = () => {
const [schoolId, setSchoolId] = React.useState<Number>();
const [teachers, setTeachers] = React.useState<Array<any>>([]);
const [students, setStudents] = React.useState<Array<any>>([])
... | else {
alert("Rosters uploaded successfully!")
}
}
);
}
return (
<div>
<h2>Upload Teacher and Student Rosters</h2>
<div className="roster-input-container">
<label className="roster-school-id" htmlFor="school-id-input">School ID
<p className="control" id="sch... | {
alert(response.errors)
} | conditional_block |
UploadRosters.tsx | import * as React from "react";
import XLSX from 'xlsx'
import request from 'request'
export const UploadRosters = () => {
const [schoolId, setSchoolId] = React.useState<Number>();
const [teachers, setTeachers] = React.useState<Array<any>>([]);
const [students, setStudents] = React.useState<Array<any>>([])
... | fileReader.readAsArrayBuffer(file);
}
function submitRosters() {
request.post(`${process.env.DEFAULT_URL}/cms/rosters/upload_teachers_and_students`, {
json: {
authenticity_token: getAuthToken(),
school_id: schoolId,
teachers: teachers,
students: students
}}, (e,... | {
const fileReader = new FileReader();
fileReader.onload = (e) => {
const data = new Uint8Array(e.target.result);
const workbook = XLSX.read(data, { type: 'array', });
const sheet1 = workbook.Sheets[workbook.SheetNames[0]]
const sheet1Array = XLSX.utils.sheet_to_json(sheet1, {header:1})... | identifier_body |
UploadRosters.tsx | import * as React from "react";
import XLSX from 'xlsx'
import request from 'request'
export const UploadRosters = () => {
const [schoolId, setSchoolId] = React.useState<Number>();
const [teachers, setTeachers] = React.useState<Array<any>>([]);
const [students, setStudents] = React.useState<Array<any>>([])
... | });
setTeachers(teachers)
setStudents(students)
};
fileReader.readAsArrayBuffer(file);
}
function submitRosters() {
request.post(`${process.env.DEFAULT_URL}/cms/rosters/upload_teachers_and_students`, {
json: {
authenticity_token: getAuthToken(),
school_id: school... |
const sheet2 = workbook.Sheets[workbook.SheetNames[1]]
const sheet2Array = XLSX.utils.sheet_to_json(sheet2, {header:1})
const students = sheet2Array.slice(1).map((row: Array<String>) => {
return { "name": row[0], "email": row[1], "password": row[2], classroom: row[3], teacher_name: row[4], te... | random_line_split |
setup.rs | use docopt_args::DocoptArgs;
use ProtonConfig;
use std::io::{self, BufRead, stdout, StdinLock, Write};
pub fn initial_setup(_args: DocoptArgs) {
configure(ProtonConfig::default_config())
}
pub fn configure(old_config: ProtonConfig) | }
// Gets a config value from user input. Uses default value if nothing is provided
fn get_config_value<'a>(prompt: &'a str, default: String, handle: &'a mut StdinLock) -> String {
print!("{} [{}]: ", prompt, default);
let _ = stdout().flush();
let mut value = String::new();
handle.read_line(&mut valu... | {
// Setup IO stuff
let stdin = io::stdin();
let mut handle = stdin.lock();
// Get config values
let key_path = get_config_value("key_path", old_config.key, &mut handle);
let vixen_folder = get_config_value("vixen_folder", old_config.vixen_folder, &mut handle);
let vixen_converter_py = get_... | identifier_body |
setup.rs | use docopt_args::DocoptArgs;
use ProtonConfig;
use std::io::{self, BufRead, stdout, StdinLock, Write};
pub fn initial_setup(_args: DocoptArgs) {
configure(ProtonConfig::default_config())
}
pub fn configure(old_config: ProtonConfig) {
// Setup IO stuff
let stdin = io::stdin();
let mut handle = stdin.l... | // Get config values
let key_path = get_config_value("key_path", old_config.key, &mut handle);
let vixen_folder = get_config_value("vixen_folder", old_config.vixen_folder, &mut handle);
let vixen_converter_py = get_config_value("vixen_converter_py", old_config.vixen_converter_py, &mut handle);
let d... | random_line_split | |
setup.rs | use docopt_args::DocoptArgs;
use ProtonConfig;
use std::io::{self, BufRead, stdout, StdinLock, Write};
pub fn initial_setup(_args: DocoptArgs) {
configure(ProtonConfig::default_config())
}
pub fn configure(old_config: ProtonConfig) {
// Setup IO stuff
let stdin = io::stdin();
let mut handle = stdin.l... | <'a>(prompt: &'a str, default: String, handle: &'a mut StdinLock) -> String {
print!("{} [{}]: ", prompt, default);
let _ = stdout().flush();
let mut value = String::new();
handle.read_line(&mut value).expect("Failed to read line of user input");
value = value.trim().to_string();
if value == "" ... | get_config_value | identifier_name |
setup.rs | use docopt_args::DocoptArgs;
use ProtonConfig;
use std::io::{self, BufRead, stdout, StdinLock, Write};
pub fn initial_setup(_args: DocoptArgs) {
configure(ProtonConfig::default_config())
}
pub fn configure(old_config: ProtonConfig) {
// Setup IO stuff
let stdin = io::stdin();
let mut handle = stdin.l... |
value
}
| {
value = default;
} | conditional_block |
main.ts | import WeCheat from '../src/WeCheat';
const qrcodeTerminal = require('qrcode-terminal');
(async () => {
const wecheat: WeCheat = new WeCheat();
wecheat.on('qrcode', (qrcode, uuid) => {
const loginUrl = qrcode.replace(/\/qrcode\//, '/l/');
console.log('qrcode', qrcode); |
wecheat.on('login', (userInfo: UserInfo) => {
console.log('login success', userInfo);
});
wecheat.on('onReceiveMsg', (type, msg) => {
console.log('onReceiveMsg', type, msg);
});
wecheat.on('onModContactList', (modContactList) => {
console.log('modContactList', modContactList);
});
wecheat.... | qrcodeTerminal.generate(loginUrl);
}); | random_line_split |
GridFilters.js | .filters[i]);
this.deferredUpdate = new Ext.util.DelayedTask(this.reload, this);
delete config.filters;
Ext.apply(this, config);
};
Ext.extend(Ext.ux.grid.GridFilters, Ext.util.Observable, {
/**
* @cfg {Integer} updateBuffer
* Number of milisecond to defer store updates since the last filter change.
*/
u... | for(var key in f.data)
p[[dataPrefix, '[', key, ']'].join | var dataPrefix = root + '[data]'; | random_line_split |
test-examples-server-pre-post-functions.js | /*jshint expr: true*/
"use strict";
var chai = require("chai");
var expect = chai.expect;
chai.config.includeStack = true;
var request = require("supertest");
var alexaAppServer = require("../index");
var fs = require("fs");
describe("Alexa App Server with Examples & Pre/Post functions", function() { | testServer = alexaAppServer.start({
port: 3000,
server_root: 'examples',
pre: function(appServer) {
fired.pre = true;
},
post: function(appServer) {
fired.post = true;
},
preRequest: function(json, request, response) {
fired.preRequest = true;
... | var testServer, fired;
var sampleLaunchReq;
before(function() {
fired = {}; | random_line_split |
owrocanalysis.py | item = pg.PlotCurveItem(
points.fpr, points.tpr, pen=pen, shadowPen=shadow_pen,
name=name, antialias=True
)
sp = pg.ScatterPlotItem(
curve.points.fpr, curve.points.tpr, symbol=symbol,
size=symbol_size, pen=shadow_pen,
name=name
)
sp.setParentItem(item)
hu... | """
Construct a `PlotCurve` for the given `ROCCurve`.
:param ROCCurve curve:
Source curve.
The other parameters are passed to pg.PlotDataItem
:rtype: PlotCurve
"""
def extend_to_origin(points):
"Extend ROCPoints to include coordinate origin if not already present"
if p... | identifier_body | |
owrocanalysis.py | error_item = pg.ErrorBarItem(
x=points.fpr[1:-1], y=points.tpr[1:-1],
height=2 * tpr_std[1:-1], width=2 * fpr_std[1:-1],
pen=pen, beam=0.025,
antialias=True,
)
return PlotAvgCurve(curve, pc.curve_item, pc.hull_item, error_item)
PlotAvgCurve.from_roc_curve = ... | if (target, clf_idx) not in self._plot_curves:
pen, shadow_pen = generate_pens(self.colors[clf_idx])
name = self.classifier_names[clf_idx]
@once | random_line_split | |
owrocanalysis.py | in selected]
selected = [self.curve_data(target, i) for i in selected]
if self.roc_averaging == OWROCAnalysis.Merge:
for curve in curves:
graphics = curve.merge()
curve = graphics.curve
self.plot.addItem(graphics.curve_item)
... | slope | identifier_name | |
owrocanalysis.py | Level=0)
item.setZValue(-10000)
pen = QPen(QColor(100, 100, 100, 100), 1, Qt.DashLine)
pen.setCosmetic(True)
self.plot.plot([0, 1], [0, 1], pen=pen, antialias=True)
if self.roc_averaging == OWROCAnalysis.Merge:
self._update_perf_line()
def _on_target_change... | return numpy.inf | conditional_block | |
user.py | #
# Copyright 2008 Google Inc. All Rights Reserved.
"""
The user module contains the objects and methods used to
manage users in Autotest.
The valid action is:
list: lists user(s)
The common options are:
--ulist / -U: file containing a list of USERs
See topic_common.py for a High Level Design and Algorithm.
"""
... |
def execute(self):
filters = {}
check_results = {}
if self.acl:
filters['aclgroup__name__in'] = [self.acl]
check_results['aclgroup__name__in'] = None
if self.access_level:
filters['access_level__in'] = [self.access_level]
check_resul... | (options, leftover) = super(user_list, self).parse()
self.acl = options.acl
self.access_level = options.access_level
return (options, leftover) | identifier_body |
user.py | #
# Copyright 2008 Google Inc. All Rights Reserved.
"""
The user module contains the objects and methods used to
manage users in Autotest.
The valid action is:
list: lists user(s)
The common options are:
--ulist / -U: file containing a list of USERs
See topic_common.py for a High Level Design and Algorithm.
"""
... | (action_common.atest_list, user):
"""atest user list <user>|--ulist <file>
[--acl <ACL>|--access_level <n>]"""
def __init__(self):
super(user_list, self).__init__()
self.parser.add_option('-a', '--acl',
help='Only list users within this ACL')
self.p... | user_list | identifier_name |
user.py | #
# Copyright 2008 Google Inc. All Rights Reserved.
"""
The user module contains the objects and methods used to
manage users in Autotest.
The valid action is:
list: lists user(s)
The common options are:
--ulist / -U: file containing a list of USERs
See topic_common.py for a High Level Design and Algorithm.
"""
... | filters=filters,
check_results=check_results)
def output(self, results):
if self.verbose:
keys = ['id', 'login', 'access_level']
else:
keys = ['login']
super(user_list, self)... | filters['login__in'] = self.users
check_results['login__in'] = 'login'
return super(user_list, self).execute(op='get_users', | random_line_split |
user.py | #
# Copyright 2008 Google Inc. All Rights Reserved.
"""
The user module contains the objects and methods used to
manage users in Autotest.
The valid action is:
list: lists user(s)
The common options are:
--ulist / -U: file containing a list of USERs
See topic_common.py for a High Level Design and Algorithm.
"""
... |
if self.access_level:
filters['access_level__in'] = [self.access_level]
check_results['access_level__in'] = None
if self.users:
filters['login__in'] = self.users
check_results['login__in'] = 'login'
return super(user_list, self).execute(op='get... | filters['aclgroup__name__in'] = [self.acl]
check_results['aclgroup__name__in'] = None | conditional_block |
conf.py | here, relative to this directory.
# html_theme_path = []
# The name for this set of Sphinx documents.
# "<project> v<release> documentation" by default.
#
# html_title = 'Site Analytics v1.0.0'
# A shorter title for the navigation bar. Default is the same as html_title.
#
# html_short_title = None
# The name of an... | _django_major_version = '{}.{}'.format(*django.VERSION[:2])
intersphinx_mapping['django'] = (
'https://docs.djangoproject.com/en/{}/'.format(_django_major_version),
'https://docs.djangoproject.com/en/{}/_objects/'.format(_django_major_version)
)
os.environ['DJANGO_SETTINGS_MODULE'] = 'site_a... | conditional_block | |
conf.py | ['_templates']
# The suffix(es) of source filenames.
# You can specify multiple suffix as a list of string:
#
# source_suffix = ['.rst', '.md']
source_suffix = '.rst'
# The encoding of source files.
#
# source_encoding = 'utf-8-sig'
# The master toctree document.
master_doc = 'index'
# General information about th... | # Documents to append as an appendix to all manuals | random_line_split | |
issue-36116.rs | // Copyright 2016 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | }
fn main() {} | fn f() {
let f = Some(Foo { _a: 42 }).map(|a| a as Foo::<i32>); //~ WARN unnecessary path disambiguator
let g: Foo::<i32> = Foo { _a: 42 }; //~ WARN unnecessary path disambiguator
m!(S::<u8>); // OK, no warning | random_line_split |
issue-36116.rs | // Copyright 2016 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 ... | () {
let f = Some(Foo { _a: 42 }).map(|a| a as Foo::<i32>); //~ WARN unnecessary path disambiguator
let g: Foo::<i32> = Foo { _a: 42 }; //~ WARN unnecessary path disambiguator
m!(S::<u8>); // OK, no warning
}
fn main() {}
| f | identifier_name |
clamav.py | # This file is part of Viper - https://github.com/botherder/viper
# See the file 'LICENSE' for copying permission.
import getopt
try:
import pyclamd
HAVE_CLAMD = True
except ImportError:
HAVE_CLAMD = False
from viper.common.out import *
from viper.common.abstracts import Module
from viper.core.session im... | if not HAVE_CLAMD:
self.log('error', "Missing dependency, install requests (`pip install pyclamd`)")
return
try:
opts, argv = getopt.getopt(self.args, 'hs:', ['help', 'socket='])
except getopt.GetoptError as e:
self.log('', e)
usage()
... | random_line_split | |
clamav.py | # This file is part of Viper - https://github.com/botherder/viper
# See the file 'LICENSE' for copying permission.
import getopt
try:
import pyclamd
HAVE_CLAMD = True
except ImportError:
HAVE_CLAMD = False
from viper.common.out import *
from viper.common.abstracts import Module
from viper.core.session im... |
if not HAVE_CLAMD:
self.log('error', "Missing dependency, install requests (`pip install pyclamd`)")
return
try:
opts, argv = getopt.getopt(self.args, 'hs:', ['help', 'socket='])
except getopt.GetoptError as e:
self.log('', e)
usage(... | usage()
self.log('', "")
self.log('', "Options:")
self.log('', "\t--help (-h)\tShow this help message")
self.log('', "\t--socket(-s)\tSpecify an unix socket (default: Clamd Unix Socket)")
self.log('', "") | identifier_body |
clamav.py | # This file is part of Viper - https://github.com/botherder/viper
# See the file 'LICENSE' for copying permission.
import getopt
try:
import pyclamd
HAVE_CLAMD = True
except ImportError:
HAVE_CLAMD = False
from viper.common.out import *
from viper.common.abstracts import Module
from viper.core.session im... | ():
self.log('', "usage: clamav [-h] [-s]")
def help():
usage()
self.log('', "")
self.log('', "Options:")
self.log('', "\t--help (-h)\tShow this help message")
self.log('', "\t--socket(-s)\tSpecify an unix socket (default: Clamd Unix Socke... | usage | identifier_name |
clamav.py | # This file is part of Viper - https://github.com/botherder/viper
# See the file 'LICENSE' for copying permission.
import getopt
try:
import pyclamd
HAVE_CLAMD = True
except ImportError:
HAVE_CLAMD = False
from viper.common.out import *
from viper.common.abstracts import Module
from viper.core.session im... |
if not __sessions__.is_set():
self.log('error', "No session opened")
return
try:
if not daemon:
daemon = pyclamd.ClamdUnixSocket()
socket = 'Clamav'
except Exception as e:
self.log('error', "Daemon connection fail... | if opt in ('-h', '--help'):
help()
return
elif opt in ('-s', '--socket'):
self.log('info', "Using socket {0} to connect to ClamAV daemon".format(value))
socket = value
try:
daemon = pyclamd.ClamdUnixSocket(so... | conditional_block |
index.tsx | import React from "react";
import Scrap from "../../Models/Scrap";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { faEdit } from "@fortawesome/free-solid-svg-icons";
import WindowService from "../../../Services/Window";
class ScrapCell extends React.Component<{
scrap: Scrap,
}, {}> {
ren... | () {
const { scraps } = this.state;
return (
<div className="container">
<div className="columns">
{scraps.map(scrap => <ScrapCell key={scrap._id} scrap={scrap} />)}
</div>
<div className="columns">
<div className="column">TOTAL: {scraps.length}</div>
</... | render | identifier_name |
index.tsx | import React from "react";
import Scrap from "../../Models/Scrap";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { faEdit } from "@fortawesome/free-solid-svg-icons";
import WindowService from "../../../Services/Window";
class ScrapCell extends React.Component<{
scrap: Scrap,
}, {}> {
ren... | {scrap.name}
</div>
</div>
</div>
);
}
}
export default class ArchiveView extends React.Component<{}, {
scraps: Scrap[],
}> {
constructor(props) {
super(props);
this.state = {
scraps: Scrap.list(),
};
}
render() {
const { scraps } = this.state;
... | WindowService.getInstance().openCapturePage({ url: scrap.url, filename: scrap.name });
}} />
</button> | random_line_split |
config.global.js | = true;
{%- endif %}
/****************************************************************************
* This boolean flag indicates to communicate with Orchestration
* modules(networkManager, imageManager, computeManager, identityManager,
* storageManager), should the webServer communicate using the
* ip/port/authPro... | debug, info, notice, warning, error, crit, alert, emerg
*/
config.logs = {};
config.logs.level = 'debug';
/******************************************************************************
* Boolean flag getDomainProjectsFromApiServer indicates wheather the project
* list should come from API Server or Identity Man... | config.qe = {};
config.qe.enable_stat_queries = false;
/* Configure level of logs, supported log levels are: | random_line_split |
slice-panic-2.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 ... | ;
static mut DTOR_COUNT: isize = 0;
impl Drop for Foo {
fn drop(&mut self) { unsafe { DTOR_COUNT += 1; } }
}
fn bar() -> usize {
panic!();
}
fn foo() {
let x: &[_] = &[Foo, Foo];
&x[3..bar()];
}
fn main() {
let _ = thread::spawn(move|| foo()).join();
unsafe { assert!(DTOR_COUNT == 2); }
}
| Foo | identifier_name |
slice-panic-2.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 ... | } | random_line_split | |
slice-panic-2.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 ... |
fn foo() {
let x: &[_] = &[Foo, Foo];
&x[3..bar()];
}
fn main() {
let _ = thread::spawn(move|| foo()).join();
unsafe { assert!(DTOR_COUNT == 2); }
}
| {
panic!();
} | identifier_body |
issue-30530.rs | // Copyright 2012-2016 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... | {
Default,
#[allow(dead_code)]
Custom(*mut Box<dyn Fn()>),
}
fn main() {
#[allow(unused_must_use)] {
take(Handler::Default, Box::new(main));
}
}
#[inline(never)]
pub fn take(h: Handler, f: Box<dyn Fn()>) -> Box<dyn Fn()> {
unsafe {
match h {
Handler::Custom(ptr) =>... | Handler | identifier_name |
issue-30530.rs | // Copyright 2012-2016 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... | Custom(*mut Box<dyn Fn()>),
}
fn main() {
#[allow(unused_must_use)] {
take(Handler::Default, Box::new(main));
}
}
#[inline(never)]
pub fn take(h: Handler, f: Box<dyn Fn()>) -> Box<dyn Fn()> {
unsafe {
match h {
Handler::Custom(ptr) => *Box::from_raw(ptr),
Handle... | #[allow(dead_code)] | random_line_split |
issue-30530.rs | // Copyright 2012-2016 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... | {
unsafe {
match h {
Handler::Custom(ptr) => *Box::from_raw(ptr),
Handler::Default => f,
}
}
} | identifier_body | |
grid-layout.helper.ts | import { scaleBand } from 'd3-scale';
export function gridSize(dims, len, minWidth) {
let rows = 1;
let cols = len;
const width = dims.width;
if (width > minWidth) |
return [cols, rows];
}
export function gridLayout(dims, data, minWidth, designatedTotal) {
const xScale: any = scaleBand<number>();
const yScale: any = scaleBand<number>();
const width = dims.width;
const height = dims.height;
const [columns, rows] = gridSize(dims, data.length, minWidth);
const xDoma... | {
while (width / cols < minWidth) {
rows += 1;
cols = Math.ceil(len / rows);
}
} | conditional_block |
grid-layout.helper.ts | import { scaleBand } from 'd3-scale';
export function gridSize(dims, len, minWidth) {
let rows = 1;
let cols = len;
const width = dims.width;
if (width > minWidth) {
while (width / cols < minWidth) {
rows += 1;
cols = Math.ceil(len / rows);
}
}
return [cols, rows];
}
export function | (dims, data, minWidth, designatedTotal) {
const xScale: any = scaleBand<number>();
const yScale: any = scaleBand<number>();
const width = dims.width;
const height = dims.height;
const [columns, rows] = gridSize(dims, data.length, minWidth);
const xDomain = [];
const yDomain = [];
for (let i = 0; i < r... | gridLayout | identifier_name |
grid-layout.helper.ts | import { scaleBand } from 'd3-scale';
export function gridSize(dims, len, minWidth) {
let rows = 1;
let cols = len;
const width = dims.width;
if (width > minWidth) {
while (width / cols < minWidth) {
rows += 1;
cols = Math.ceil(len / rows);
}
}
return [cols, rows];
}
export function ... | {
return results
.map(d => d ? d.value : 0)
.reduce((sum, val) => sum + val, 0);
} | identifier_body | |
grid-layout.helper.ts | import { scaleBand } from 'd3-scale';
export function gridSize(dims, len, minWidth) {
let rows = 1;
let cols = len;
const width = dims.width;
if (width > minWidth) {
while (width / cols < minWidth) {
rows += 1;
cols = Math.ceil(len / rows);
}
}
return [cols, rows];
}
export function ... | const res = [];
const total = designatedTotal ? designatedTotal : getTotal(data);
const cardWidth = xScale.bandwidth();
const cardHeight = yScale.bandwidth();
for (let i = 0; i < data.length; i++) {
res[i] = {};
res[i].data = {
name: data[i] ? data[i].name : '',
value: data[i] ? data[i].v... | xScale.rangeRound([0, width], 0.1);
yScale.rangeRound([0, height], 0.1);
| random_line_split |
security-group-page.component.ts | import { Component, Input } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { SecurityGroup } from '../sg.model';
import { ViewMode } from '../../shared/components/view-mode-switch/view-mode-switch.component';
import { ListService } from '../../shared/components/list/list.service... |
constructor(
private router: Router,
private activatedRoute: ActivatedRoute,
public listService: ListService,
) {}
public get showSidebarDetails(): boolean {
return this.activatedRoute.snapshot.firstChild.firstChild.routeConfig.path === 'details';
}
public changeMode(mode) {
this.mode ... | {
return this.viewMode !== SecurityGroupViewMode.Private;
} | identifier_body |
security-group-page.component.ts | import { Component, Input } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { SecurityGroup } from '../sg.model';
import { ViewMode } from '../../shared/components/view-mode-switch/view-mode-switch.component';
import { ListService } from '../../shared/components/list/list.service... |
public get showSidebarDetails(): boolean {
return this.activatedRoute.snapshot.firstChild.firstChild.routeConfig.path === 'details';
}
public changeMode(mode) {
this.mode = mode;
}
public showCreationDialog(): void {
this.router.navigate(['./create'], {
queryParamsHandling: 'preserve',
... | random_line_split | |
security-group-page.component.ts | import { Component, Input } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { SecurityGroup } from '../sg.model';
import { ViewMode } from '../../shared/components/view-mode-switch/view-mode-switch.component';
import { ListService } from '../../shared/components/list/list.service... | (
private router: Router,
private activatedRoute: ActivatedRoute,
public listService: ListService,
) {}
public get showSidebarDetails(): boolean {
return this.activatedRoute.snapshot.firstChild.firstChild.routeConfig.path === 'details';
}
public changeMode(mode) {
this.mode = mode;
}
... | constructor | identifier_name |
remoteIndicator.ts | EntryAccessor | undefined;
private readonly legacyIndicatorMenu = this._register(this.menuService.createMenu(MenuId.StatusBarWindowIndicatorMenu, this.contextKeyService)); // to be removed once migration completed
private readonly remoteIndicatorMenu = this._register(this.menuService.createMenu(MenuId.StatusBarRemot... |
run = () => that.showRemoteMenu();
});
// Close Remote Connection
if (RemoteStatusIndicator.SHOW_CLOSE_REMOTE_COMMAND_ID) {
registerAction2(class extends Action2 {
constructor() {
super({
id: RemoteStatusIndicator.CLOSE_REMOTE_COMMAND_ID,
category,
title: { value: nls.localize('... | {
super({
id: RemoteStatusIndicator.REMOTE_ACTIONS_COMMAND_ID,
category,
title: { value: nls.localize('remote.showMenu', "Show Remote Menu"), original: 'Show Remote Menu' },
f1: true,
});
} | identifier_body |
remoteIndicator.ts | EntryAccessor | undefined;
private readonly legacyIndicatorMenu = this._register(this.menuService.createMenu(MenuId.StatusBarWindowIndicatorMenu, this.contextKeyService)); // to be removed once migration completed
private readonly remoteIndicatorMenu = this._register(this.menuService.createMenu(MenuId.StatusBarRemot... | (): void {
// Menu changes
const updateRemoteActions = () => {
this.remoteMenuActionsGroups = undefined;
this.updateRemoteStatusIndicator();
};
this._register(this.legacyIndicatorMenu.onDidChange(updateRemoteActions));
this._register(this.remoteIndicatorMenu.onDidChange(updateRemoteActions));
// Up... | registerListeners | identifier_name |
remoteIndicator.ts | if (this.remoteAuthority) {
this.connectionState = 'initializing';
this.connectionStateContextKey.set(this.connectionState);
} else {
this.updateVirtualWorkspaceLocation();
}
this.registerActions();
this.registerListeners();
this.updateWhenInstalledExtensionsRegistered();
this.updateRemoteStatus... | {
tooltip.appendText(nls.localize({ key: 'workspace.tooltip', comment: ['{0} is a remote workspace name, e.g. GitHub'] }, "Editing on {0}", workspaceLabel));
} | conditional_block | |
remoteIndicator.ts | Menu.getActions());
}
return this.remoteMenuActionsGroups;
}
private updateRemoteStatusIndicator(): void {
// Remote Indicator: show if provided via options, e.g. by the web embedder API
const remoteIndicator = this.environmentService.options?.windowIndicator;
if (remoteIndicator) {
this.renderRemoteSt... | random_line_split | ||
parks.js | //Author: Sam
var parkIds = [];
$(document).ready(function() {
$('#toMap').on('click', function() {
if (typeof map == 'undefined') {
initialize();
}
});
$('.park').on('click', '.select', function(e) {
e.preventDefault();
var parkId = $(this).attr('data-id');... |
handleCompareButton();
});
$('#compare-parks-body').on('click', '.selected-park', function() {
var parkId = $(this).data('park');
unselectPark(parkId, this);
handleCompareButton();
});
});
function handleCompareButton() {
if (parkIds.length == 2) {
... | {
if (parkIds.length != 2) {
$(this).addClass('btn-success');
$(this).text('Selected');
$('#compare-parks-body').append('<button data-park="' + parkId + '" id="compare-park-' + parkId +'" class="btn btn-warning selected-park" aria-label="Right Align">' + $(thi... | conditional_block |
parks.js | //Author: Sam
var parkIds = [];
$(document).ready(function() {
$('#toMap').on('click', function() {
if (typeof map == 'undefined') {
initialize();
}
});
$('.park').on('click', '.select', function(e) {
e.preventDefault();
var parkId = $(this).attr('data-id');... | });
function handleCompareButton() {
if (parkIds.length == 2) {
$('#compare').attr('disabled', false);
var url = '../compare?park1=' + parkIds[0] + '&park2=' + parkIds[1];
$('#compare').attr('href', url);
} else {
$('#compare').attr('disabled', true);
}
}
function unselectP... | random_line_split | |
parks.js | //Author: Sam
var parkIds = [];
$(document).ready(function() {
$('#toMap').on('click', function() {
if (typeof map == 'undefined') {
initialize();
}
});
$('.park').on('click', '.select', function(e) {
e.preventDefault();
var parkId = $(this).attr('data-id');... | {
$('#park-' + parkId).find('.select').removeClass('btn-success').text('compare');
parkIds.splice(parkIds.indexOf(parkId), 1);
$('#compare-park-' + parkId).remove();
} | identifier_body | |
parks.js | //Author: Sam
var parkIds = [];
$(document).ready(function() {
$('#toMap').on('click', function() {
if (typeof map == 'undefined') {
initialize();
}
});
$('.park').on('click', '.select', function(e) {
e.preventDefault();
var parkId = $(this).attr('data-id');... | (parkId) {
$('#park-' + parkId).find('.select').removeClass('btn-success').text('compare');
parkIds.splice(parkIds.indexOf(parkId), 1);
$('#compare-park-' + parkId).remove();
} | unselectPark | identifier_name |
workerTest.py | # Copyright (C) 2015-2021 Regents of the University of California
#
# 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 app... | (self):
"""Make sure chainable/non-chainable jobs are identified correctly."""
def createTestJobDesc(memory, cores, disk, preemptable, checkpoint):
"""
Create a JobDescription with no command (representing a Job that
has already run) and return the JobDescription.
... | testNextChainable | identifier_name |
workerTest.py | # Copyright (C) 2015-2021 Regents of the University of California
#
# 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 app... |
@travis_test
def testNextChainable(self):
"""Make sure chainable/non-chainable jobs are identified correctly."""
def createTestJobDesc(memory, cores, disk, preemptable, checkpoint):
"""
Create a JobDescription with no command (representing a Job that
has alr... | super(WorkerTests, self).setUp()
path = self._getTestJobStorePath()
self.jobStore = FileJobStore(path)
self.config = Config()
self.config.jobStore = 'file:%s' % path
self.jobStore.initialize(self.config)
self.jobNumber = 0 | identifier_body |
workerTest.py | # Copyright (C) 2015-2021 Regents of the University of California
#
# 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 app... | jobDesc3 = createTestJobDesc(1, 2, 3, True, False)
getattr(jobDesc1, successorType)(jobDesc2.jobStoreID)
getattr(jobDesc1, successorType)(jobDesc3.jobStoreID)
self.assertEqual(None, nextChainable(jobDesc1, self.jobStore, self.config))
# If there is an increas... | jobDesc1 = createTestJobDesc(1, 2, 3, True, False)
jobDesc2 = createTestJobDesc(1, 2, 3, True, False)
getattr(jobDesc1, successorType)(jobDesc2.jobStoreID)
chainable = nextChainable(jobDesc1, self.jobStore, self.config)
self.assertNotEqual(chainable, None)
sel... | conditional_block |
workerTest.py | # Copyright (C) 2015-2021 Regents of the University of California
#
# 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 app... | self.jobStore = FileJobStore(path)
self.config = Config()
self.config.jobStore = 'file:%s' % path
self.jobStore.initialize(self.config)
self.jobNumber = 0
@travis_test
def testNextChainable(self):
"""Make sure chainable/non-chainable jobs are identified correctly... | class WorkerTests(ToilTest):
"""Test miscellaneous units of the worker."""
def setUp(self):
super(WorkerTests, self).setUp()
path = self._getTestJobStorePath() | random_line_split |
lobby.module.ts | import { NgModule } from '@angular/core'
import { SharedModule } from '@app/shared/shared.module'
import { LobbyComponent } from './lobby.component'
// message-window
import { LobbyMessagesComponent } from './lobby-messages/lobby-messages.component'
import { ItemGroupComponent } from './lobby-messages/... | { }
| LobbyModule | identifier_name |
lobby.module.ts | import { NgModule } from '@angular/core'
import { SharedModule } from '@app/shared/shared.module'
import { LobbyComponent } from './lobby.component'
// message-window
import { LobbyMessagesComponent } from './lobby-messages/lobby-messages.component'
import { ItemGroupComponent } from './lobby-messages/... | // Allow the DIALOGS to be made into componentFactories for the MdDialog to use!
entryComponents: [...DIALOGS],
providers: [ LobbyRendererService, LobbyItemOptionsDialogService ]
})
export class LobbyModule { } | random_line_split | |
payment-merchant-manage-page.effects.ts | import {HttpClient} from '@angular/common/http';
import {Injectable} from '@angular/core';
import {Router} from '@angular/router';
import {Actions, Effect} from '@ngrx/effects';
import {Action, Store} from '@ngrx/store';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/exhaustMap';
import 'rxjs/add/operator/... | {
@Effect()
init$: Observable<Action> = this.actions$
.ofType(paymentMerchantManagePageActions.INIT)
.exhaustMap(() => {
return this.enlistService.listPaymentMerchant()
.map(res => new paymentMerchantManagePageActions.InitSuccess(res))
.catch(error => of(new ShowError(error)));
})... | PaymentMerchantManagePageEffects | identifier_name |
payment-merchant-manage-page.effects.ts | import {HttpClient} from '@angular/common/http';
import {Injectable} from '@angular/core';
import {Router} from '@angular/router';
import {Actions, Effect} from '@ngrx/effects';
import {Action, Store} from '@ngrx/store';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/exhaustMap';
import 'rxjs/add/operator/... |
}
| {
} | identifier_body |
payment-merchant-manage-page.effects.ts | import {HttpClient} from '@angular/common/http';
import {Injectable} from '@angular/core';
import {Router} from '@angular/router';
import {Actions, Effect} from '@ngrx/effects';
import {Action, Store} from '@ngrx/store';
import 'rxjs/add/operator/catch'; | import {Observable} from 'rxjs/Observable';
import {of} from 'rxjs/observable/of';
import {UtilService} from '../../../core/services/util.service';
import {ShowError, ShowWxQrcoode} from '../../../core/store/actions/core';
import {EnlistService} from '../../services/enlist.service';
import {paymentMerchantManagePageAct... | import 'rxjs/add/operator/exhaustMap';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/pluck';
import 'rxjs/add/operator/switchMap'; | random_line_split |
analytics.service.ts | import { Injectable } from '@angular/core';
import { environment } from '../../../environments/environment';
import { AppInsights } from 'applicationinsights-js';
// Declare ga function as ambient
declare const ga: Function;
@Injectable()
export class AnalyticsService {
private config: Microsoft.ApplicationInsig... | emitEvent(eventCategory: string,
eventAction: string,
eventLabel: string = null,
eventValue: number = null) {
ga(
'send',
'event',
{
eventCategory: eventCategory,
eventLabel: eventLabel,
... | AppInsights.trackPageView(
name,
url,
properties,
measurements,
duration);
ga('set', 'page', url);
ga('send', 'pageview');
}
| identifier_body |
analytics.service.ts | import { Injectable } from '@angular/core';
import { environment } from '../../../environments/environment';
import { AppInsights } from 'applicationinsights-js';
// Declare ga function as ambient
declare const ga: Function;
@Injectable()
export class An |
private config: Microsoft.ApplicationInsights.IConfig = {
instrumentationKey: environment.appInsights.instrumentationKey
};
constructor() {
if (!AppInsights.config) {
AppInsights.downloadAndSetup(this.config);
}
}
logPageView(name?: string,
url?... | alyticsService { | identifier_name |
analytics.service.ts |
// Declare ga function as ambient
declare const ga: Function;
@Injectable()
export class AnalyticsService {
private config: Microsoft.ApplicationInsights.IConfig = {
instrumentationKey: environment.appInsights.instrumentationKey
};
constructor() {
if (!AppInsights.config) {
Ap... | import { Injectable } from '@angular/core';
import { environment } from '../../../environments/environment';
import { AppInsights } from 'applicationinsights-js'; | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.