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 |
|---|---|---|---|---|
script.js | /*jslint browser: true*/
/*global $, jQuery, QRCode, alert, console*/
/*
to-do
=====================================================================
- disable add button while waiting for ajax request so that user
doesn't send too many ajax requests
*/
function addRowToTable(action, name, instructions) |
function extractName(medicineName) {
'use strict';
return medicineName.substr(medicineName.indexOf('_') + 1);
}
$(document).ready(function () {
'use strict';
var request, qrcode, width, nameElement, dataElement, text;
//jQuery('#qrcode').qrcode("this plugin is great");
//new QRCode(docu... | {
'use strict';
var htmlName, newElement, pictureElement, medicineName, row;
htmlName = JSON.stringify("medicine_" + name);
console.log(name, instructions);
if (action === "insert") {
newElement = $("<tr name=" + htmlName + ">").append(
$('<td/>').text(name),
$('... | identifier_body |
script.js | /*jslint browser: true*/
/*global $, jQuery, QRCode, alert, console*/
/*
to-do
=====================================================================
- disable add button while waiting for ajax request so that user
doesn't send too many ajax requests
*/
function | (action, name, instructions) {
'use strict';
var htmlName, newElement, pictureElement, medicineName, row;
htmlName = JSON.stringify("medicine_" + name);
console.log(name, instructions);
if (action === "insert") {
newElement = $("<tr name=" + htmlName + ">").append(
$('<td/>'... | addRowToTable | identifier_name |
script.js | /*jslint browser: true*/
/*global $, jQuery, QRCode, alert, console*/
/*
to-do
=====================================================================
- disable add button while waiting for ajax request so that user
doesn't send too many ajax requests
*/
function addRowToTable(action, name, instructions) {
'u... |
});
/*
setTimeout(
function () {nameElement.trigger("input");},
0
);
*/
$('div#searchTable').height($('div#formDiv').height());
//Ajax call to getAll.php to get all medicine entries in database
request = $.ajax({
url: 'getAll.php',
type: 'p... | {
$("tr[name='google']").css("display", "none");
} | conditional_block |
script.js | /*jslint browser: true*/
/*global $, jQuery, QRCode, alert, console*/
/*
to-do
=====================================================================
- disable add button while waiting for ajax request so that user
doesn't send too many ajax requests
*/
function addRowToTable(action, name, instructions) {
'u... | // Serialize the data in the form
//serializedData = form.serialize();
console.log(inputs);
// Let's disable the inputs for the duration of the Ajax request.
// Note: we disable elements AFTER the form data has been serialized.
// Disabled form elements will not be seria... |
inputs = form.find("input, select, button, textarea"); | random_line_split |
fourier.py | #
# Copyright (c) 2020 Idiap Research Institute, http://www.idiap.ch/
# Written by Angelos Katharopoulos <angelos.katharopoulos@idiap.ch>
#
"""Implement the positive orthogonal random features from the paper
"Rethinking Attention with Performers" https://arxiv.org/pdf/2009.14794.pdf
and the traditional random Fourier ... |
def orthogonal_matrix_chunk(
cols: int,
device: torch.device = None
) -> torch.Tensor:
unstructured_block = torch.randn((cols, cols), device=device)
q, _ = torch.qr(unstructured_block.cpu(), some=True)
q = q.to(device)
return q.t()
class RandomFourierFeatures(Kernel):
"""Random ... | num_full_blocks = int(num_rows / num_columns)
block_list = []
for _ in range(num_full_blocks):
q = orthogonal_matrix_chunk(num_columns, device)
block_list.append(q)
remaining_rows = num_rows - (num_full_blocks * num_columns)
if remaining_rows > 0:
q = orthogonal_matrix_chunk(n... | identifier_body |
fourier.py | #
# Copyright (c) 2020 Idiap Research Institute, http://www.idiap.ch/
# Written by Angelos Katharopoulos <angelos.katharopoulos@idiap.ch>
#
"""Implement the positive orthogonal random features from the paper
"Rethinking Attention with Performers" https://arxiv.org/pdf/2009.14794.pdf
and the traditional random Fourier ... |
else:
raise ValueError(f"Invalid scaling {scaling}")
return torch.diag(multiplier) @ final_matrix
def orthogonal_matrix_chunk(
cols: int,
device: torch.device = None
) -> torch.Tensor:
unstructured_block = torch.randn((cols, cols), device=device)
q, _ = torch.qr(unstructured_... | multiplier = sqrt((float(num_columns))) * torch.ones((num_rows,), device=device) | conditional_block |
fourier.py | #
# Copyright (c) 2020 Idiap Research Institute, http://www.idiap.ch/
# Written by Angelos Katharopoulos <angelos.katharopoulos@idiap.ch>
#
"""Implement the positive orthogonal random features from the paper
"Rethinking Attention with Performers" https://arxiv.org/pdf/2009.14794.pdf
and the traditional random Fourier ... | query_dimensions: int, The input query dimensions in order to sample
the noise matrix
n_dims: int, The size of the feature map (default: query_dimensions)
softmax_temp: float, A normalizer for the dot products that is
multiplied to the input feature... | passed in `kernel_fn`.
Arguments
--------- | random_line_split |
fourier.py | #
# Copyright (c) 2020 Idiap Research Institute, http://www.idiap.ch/
# Written by Angelos Katharopoulos <angelos.katharopoulos@idiap.ch>
#
"""Implement the positive orthogonal random features from the paper
"Rethinking Attention with Performers" https://arxiv.org/pdf/2009.14794.pdf
and the traditional random Fourier ... | (
self,
device: Optional[torch.device] = "cpu"
):
return orthogonal_random_matrix_(
self.kernel_size,
self.head_size,
scaling=self.ortho_scaling,
device=device
)
def forward(
self,
x: torch.Tensor,... | new_kernel | identifier_name |
differentiation.go | package gorgonia
import (
"github.com/pkg/errors"
"gonum.org/v1/gonum/graph"
)
/*
This file holds code for symbolic differentiation.
The purpose of the symbolic differentiation is to analyze and prepare the nodes for automatic differentiation.
The main function that does all the magic is in Backpropagate().
see ... | {
deriv.derivOf = append(deriv.derivOf, of)
of.deriv = deriv
} | identifier_body | |
differentiation.go | package gorgonia
import (
"github.com/pkg/errors"
"gonum.org/v1/gonum/graph"
)
/*
This file holds code for symbolic differentiation.
The purpose of the symbolic differentiation is to analyze and prepare the nodes for automatic differentiation.
The main function that does all the magic is in Backpropagate().
see ... |
symdiffLogf("reduced to... %x", n.ID())
// node.derives = append(node.derives, n)
n.derivOf = append(n.derivOf, node)
node.deriv = n
nodeGradMap[node] = Nodes{n}
// }
} else if len(nodeGradMap[node]) == 1 {
deriv := nodeGradMap[node][0]
deriv.derivOf = append(deriv.derivOf, node)
node.deri... | {
leaveLogScope()
return nil, SymDiffError{
single: node,
nodes: nodeGradMap[node],
gradMap: nodeGradMap,
err: errors.Wrap(err, "ReduceAdd failed during differentiation"),
}
} | conditional_block |
differentiation.go | package gorgonia
import (
"github.com/pkg/errors"
"gonum.org/v1/gonum/graph"
)
/*
This file holds code for symbolic differentiation.
The purpose of the symbolic differentiation is to analyze and prepare the nodes for automatic differentiation.
The main function that does all the magic is in Backpropagate().
see ... | single: node,
nodes: nodeGradMap[node],
gradMap: nodeGradMap,
err: errors.Wrap(err, "ReduceAdd failed during differentiation"),
}
}
symdiffLogf("reduced to... %x", n.ID())
// node.derives = append(node.derives, n)
n.derivOf = append(n.derivOf, node)
node.deriv = n
nodeG... | leaveLogScope()
return nil, SymDiffError{ | random_line_split |
differentiation.go | package gorgonia
import (
"github.com/pkg/errors"
"gonum.org/v1/gonum/graph"
)
/*
This file holds code for symbolic differentiation.
The purpose of the symbolic differentiation is to analyze and prepare the nodes for automatic differentiation.
The main function that does all the magic is in Backpropagate().
see ... | (outputs, sortedNodes Nodes) (retVal NodeSet, err error) {
symdiffLogf("Forward analysis. Already sorted?")
enterLogScope()
defer leaveLogScope()
if !outputs.AllSameGraph() {
return nil, errors.New("The supplied output Nodes are not the same graph")
}
diffSet := outputs.mapSet()
symdiffLogf("Diff Set: %v", ... | forwardDiffAnalysis | identifier_name |
TypedAction.ts | /**
* @license
* Copyright 2017 Palantir Technologies, 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.org/licenses/LICENSE-2.0
*
* Unless required by... | * All Definitions for a Redux-enabled application MUST have unique strings.
*/
export interface NoPayloadDefinition<E extends string> {
/**
* Creates an Action of this type (and no payload).
* Functionally equivalent to the explicit NoPayloadDefinition.create().
*/
(): { type: E; payload:... | *
* - Definitions should be used to create Actions.
* - Definitions can be used to identify an Action, based on its own `type`.
* | random_line_split |
TypedAction.ts | /**
* @license
* Copyright 2017 Palantir Technologies, 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.org/licenses/LICENSE-2.0
*
* Unless required by... |
return { type, payload };
};
const createWithMeta = <M>(
payload: T,
meta: M,
): { type: E; payload: T; meta: M } => {
if (!validate(payload)) {
throw new Error(`'${type}' validation failed`);
}
return { type, payload, meta };
};
const is = (action: A... | {
throw new Error(`'${type}' validation failed`);
} | conditional_block |
TypedAction.ts | /**
* @license
* Copyright 2017 Palantir Technologies, 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.org/licenses/LICENSE-2.0
*
* Unless required by... | <E extends string>(
type: E,
): NoPayloadDefinition<E> {
const create = (): { type: E; payload: never } => {
return { type } as { type: E; payload: never };
};
const createWithMeta = <M>(
meta: M,
): { type: E; payload: never; meta: M } => {
return { type, meta } as { type: E; p... | createNoPayloadDefinition | identifier_name |
TypedAction.ts | /**
* @license
* Copyright 2017 Palantir Technologies, 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.org/licenses/LICENSE-2.0
*
* Unless required by... |
/**
* **DEPRECATED**: As of Redoodle 2.5.0, consumers should prefer `defineAction()`
* over than `TypedAction.define()`. See https://github.com/palantir/redoodle/issues/35
*
* Similar to TypedAction.define, creates a NoPayloadDefinition for the given Action type
* string, like `"example::clear_foo"`.... | {
return <T>(options?: DefineOptions<T>) => {
if (
process.env.NODE_ENV !== "production" &&
options !== undefined &&
options.validate !== undefined
) {
return createDefinitionWithValidator<E, T>(type, options.validate);
} else {
return createDefinition<E, T>... | identifier_body |
time-sentiment.component.ts | import { Component, OnInit, ElementRef } from '@angular/core';
import { ChartService } from '../../services/chart.service';
import * as d3 from 'd3';
import * as crossfilter from 'crossfilter';
import * as dc from 'dc';
@Component({
selector: 'app-time-sentiment',
templateUrl: './time-sentiment.component.html',
... |
});
return colorArray;
}
// Reorder groups
reorderGroups() {
const groups: { group: CrossFilter.Group<{}, Date, any>, sent: string}[] = [];
this.sentGroups.forEach((g) => {
if (g.sent === 'Pos') {
groups[0] = g;
} else if (g.sent === 'Neu') {
groups[1] = g;
} ... | {
colorArray.push('#DDDDDD');
} | conditional_block |
time-sentiment.component.ts | import { Component, OnInit, ElementRef } from '@angular/core';
import { ChartService } from '../../services/chart.service';
import * as d3 from 'd3';
import * as crossfilter from 'crossfilter';
import * as dc from 'dc';
@Component({
selector: 'app-time-sentiment',
templateUrl: './time-sentiment.component.html', | styleUrls: ['./time-sentiment.component.scss']
})
export class TimeSentimentComponent implements OnInit {
aggrView = true;
compView = false;
data: any[];
cfilter: CrossFilter.CrossFilter<{}>;
dimension: CrossFilter.Dimension<{}, Date>;
sentGroups: { group: CrossFilter.Group<{}, Date, any>, sent: string}[]... | random_line_split | |
time-sentiment.component.ts | import { Component, OnInit, ElementRef } from '@angular/core';
import { ChartService } from '../../services/chart.service';
import * as d3 from 'd3';
import * as crossfilter from 'crossfilter';
import * as dc from 'dc';
@Component({
selector: 'app-time-sentiment',
templateUrl: './time-sentiment.component.html',
... |
// Buttons and Front-End ////////////////////////////////////////////////////////////////////////////////////////////
// sets the tooltip on mouseover
setTooltipInfo(event: MouseEvent, tooltip: HTMLSpanElement) {
tooltip.style.position = 'fixed';
tooltip.style.top = (event.clientY) + 'px';
tooltip.... | {
this.sentimentLineChart = dc.lineChart('#sentimentChartLine');
this.chartService.GetData().subscribe((data) => { this.data = data; });
// Crossfilter
this.chartService.getCrossfilter().subscribe((filter) => {
this.cfilter = filter;
this.setDimension();
if (this.data && this.data.len... | identifier_body |
time-sentiment.component.ts | import { Component, OnInit, ElementRef } from '@angular/core';
import { ChartService } from '../../services/chart.service';
import * as d3 from 'd3';
import * as crossfilter from 'crossfilter';
import * as dc from 'dc';
@Component({
selector: 'app-time-sentiment',
templateUrl: './time-sentiment.component.html',
... | implements OnInit {
aggrView = true;
compView = false;
data: any[];
cfilter: CrossFilter.CrossFilter<{}>;
dimension: CrossFilter.Dimension<{}, Date>;
sentGroups: { group: CrossFilter.Group<{}, Date, any>, sent: string}[];
sentimentLineChart: dc.LineChart;
renderedChart = false;
notDataWarn = false;
... | TimeSentimentComponent | identifier_name |
text.rs | use crate::shared::syntax::*;
use std::convert::TryFrom;
use std::fmt::{Display, Formatter, Result as FmtResult};
use std::str::FromStr;
// ------------------------------------------------------------------------------------------------
// Public Types
// --------------------------------------------------------------... | || (c >= '\u{D8}' && c <= '\u{F6}')
|| (c >= '\u{0F8}' && c <= '\u{2FF}')
|| (c >= '\u{370}' && c <= '\u{37D}')
|| (c >= '\u{037F}' && c <= '\u{1FFF}')
|| (c >= '\u{200C}' && c <= '\u{200D}')
|| (c >= '\u{2070}' && c <= '\u{218F}')
|| (c >= '\u{2C00}' && c <= '\u{... | || c == '_'
|| (c >= 'a' && c <= 'z')
|| (c >= '\u{C0}' && c <= '\u{D6}') | random_line_split |
text.rs | use crate::shared::syntax::*;
use std::convert::TryFrom;
use std::fmt::{Display, Formatter, Result as FmtResult};
use std::str::FromStr;
// ------------------------------------------------------------------------------------------------
// Public Types
// --------------------------------------------------------------... | else if let Some(a_match) = capture.name("char") {
let replacement = char_from_entity(a_match.as_str());
(a_match.start(), a_match.end(), replacement)
} else if let Some(a_match) = capture.name("char_hex") {
let replacement = char_from_entity(a_match.as_str())... |
//
// TODO: this does not yet deal with entity references.
//
let replacement = match resolver.resolve(a_match.as_str()) {
None => panic!("unknown entity reference {}", a_match.as_str()),
Some(replacement) => {
... | conditional_block |
text.rs | use crate::shared::syntax::*;
use std::convert::TryFrom;
use std::fmt::{Display, Formatter, Result as FmtResult};
use std::str::FromStr;
// ------------------------------------------------------------------------------------------------
// Public Types
// --------------------------------------------------------------... | ------------------------------------------------------------------------------------------------
// Unit Tests
// ------------------------------------------------------------------------------------------------
#[cfg(test)]
mod tests {
use super::*;
use std::borrow::Borrow;
use std::collections::HashMap;
... | if s == XML_NS_ATTR_SPACE_DEFAULT {
Ok(SpaceHandling::Default)
} else if s == XML_NS_ATTR_SPACE_PRESERVE {
Ok(SpaceHandling::Preserve)
} else {
Err(())
}
}
}
// | identifier_body |
text.rs | use crate::shared::syntax::*;
use std::convert::TryFrom;
use std::fmt::{Display, Formatter, Result as FmtResult};
use std::str::FromStr;
// ------------------------------------------------------------------------------------------------
// Public Types
// --------------------------------------------------------------... | let resolver = test_resolver();
let resolver = resolver.borrow();
assert_eq!(
normalize_attribute_value("10$ in £s please", resolver, true),
"10$ in £s please"
);
assert_eq!(
normalize_attribute_value("¥ to €", resolver, false),
... | lize_avalue_entity_resolver() {
| identifier_name |
ionic-native-map.ts | import { Component,
OnInit,
ViewChild,
ElementRef,
} from '@angular/core';
import { NavController,
NavParams,
Platform,
ToastController,
AlertController,
PopoverController } from 'ionic-angular';
import { GoogleMaps,
GoogleMap... | }
).catch(
() => {
console.log('Map is ready!');
// Now you can add elements to the map like the marker
}
);
return latLng;
}
addMarker(map, latLng: LatLng){
this.map.clear();
this.map.addMarker({
position: latLng
});
}
moveCamera(map, latLng... | };
this.addMarker(map, this.newLocation); | random_line_split |
ionic-native-map.ts | import { Component,
OnInit,
ViewChild,
ElementRef,
} from '@angular/core';
import { NavController,
NavParams,
Platform,
ToastController,
AlertController,
PopoverController } from 'ionic-angular';
import { GoogleMaps,
GoogleMap... |
listenToSearchInput() {
this.hide = false;
let location: string;
console.log('location1:', location)
// let searchInput$ = Observable.fromEvent(this.button.nativeElement, 'keyup')
// .map(e => location = e['srcElement'].value.trim())
// .distinctUntilChanged()
// .switchMap(() =>... | {
console.log("ngAfterViewInit", this.newLocation);
// this.androidPermissions.checkPermission(this.androidPermissions.PERMISSION.ACCESS_FINE_LOCATION).then(
// success => console.log('Permission granted'),
// err => this.androidPermissions.requestPermissions(this.androidPermissions.PERMISSION.ACCES... | identifier_body |
ionic-native-map.ts | import { Component,
OnInit,
ViewChild,
ElementRef,
} from '@angular/core';
import { NavController,
NavParams,
Platform,
ToastController,
AlertController,
PopoverController } from 'ionic-angular';
import { GoogleMaps,
GoogleMap... | (){
let element: HTMLElement = ViewChild('map');
let mapOptions = {
"featureType": "all",
"elementType": "geometry",
styles: [
{ elementType: 'geometry', stylers: [{ color: '#15151b' }] },
{ elementType: 'labels.text.stroke', stylers: [{ color: '#242f3e' }] },
... | loadMap | identifier_name |
ionic-native-map.ts | import { Component,
OnInit,
ViewChild,
ElementRef,
} from '@angular/core';
import { NavController,
NavParams,
Platform,
ToastController,
AlertController,
PopoverController } from 'ionic-angular';
import { GoogleMaps,
GoogleMap... |
}
savedButtonClicked(myEvent) {
this.saved = this.saved ? false : true;
setTimeout(()=>{
this.saved = this.saved ? false : true;
}, 200);
let inputs;
this.addressResponse = inputs;
let URL = globalVars.getUsersAddress(this.userID);
this.authService.getCall(U... | {
// let location$ = this.mapService.getJSON(location, this.latLng);
// location$.subscribe(res => console.log)
} | conditional_block |
lib.rs | // Copyright 2018. Matthew Pelland <matt@pelland.io>.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applica... | <Input, Output>(input: Input, expected_outputs: Output)
where
Input: AsRef<Path>,
Output: IntoIterator + Copy,
Output::Item: AsRef<Path>,
{
let rel_include_path = PathBuf::from("test/assets/protos");
let abs_include_path = Path::new(env!("CARGO_MANIFEST_DIR")).join(&rel_i... | assert_compile_grpc_protos | identifier_name |
lib.rs | // Copyright 2018. Matthew Pelland <matt@pelland.io>.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applica... |
fn normalize<Paths, Bases>(
paths: Paths,
bases: Bases,
) -> CompileResult<(Vec<PathBuf>, Vec<PathBuf>, Vec<PathBuf>)>
where
Paths: IntoIterator,
Paths::Item: AsRef<Path>,
Bases: IntoIterator,
Bases::Item: AsRef<Path>,
{
let absolutized_bases = bases
.into_iter()
.map(absol... | {
let p = path.as_ref();
if p.is_relative() {
match std::env::current_dir() {
Ok(cwd) => Ok(cwd.join(p)),
Err(err) => Err(format_err!(
"Failed to determine CWD needed to absolutize a relative path: {:?}",
err
)),
}
} else {
... | identifier_body |
lib.rs | // Copyright 2018. Matthew Pelland <matt@pelland.io>.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applica... | .as_slice(),
includes: stringified_includes
.iter()
.map(String::as_str)
.collect::<Vec<&str>>()
.as_slice(),
include_imports: true,
})
.context("failed to write descriptor set")?;
let mut serial... | .iter()
.map(String::as_str)
.collect::<Vec<&str>>() | random_line_split |
baselines_utils.py | import numpy as np
import tensorflow as tf # pylint: ignore-module
import copy
import os
import functools
import collections
import multiprocessing
import random
def switch(condition, then_expression, else_expression):
"""Switches between two operations depending on a scalar value (int or bool).
Note that bot... |
def sum(self, start=0, end=None):
"""Returns arr[start] + ... + arr[end]"""
return super(SumSegmentTree, self).reduce(start, end)
def find_prefixsum_idx(self, prefixsum):
"""Find the highest index `i` in the array such that
sum(arr[0] + arr[1] + ... + arr[i - i]) <= prefix... | super(SumSegmentTree, self).__init__(
capacity=capacity,
operation=operator.add,
neutral_element=0.0
) | identifier_body |
baselines_utils.py | import numpy as np
import tensorflow as tf # pylint: ignore-module
import copy
import os
import functools
import collections
import multiprocessing
import random
def switch(condition, then_expression, else_expression):
"""Switches between two operations depending on a scalar value (int or bool).
Note that bot... | """Returns result of applying `self.operation`
to a contiguous subsequence of the array.
self.operation(arr[start], operation(arr[start+1], operation(... arr[end])))
Parameters
----------
start: int
beginning of the subsequence
end: int
... | )
def reduce(self, start=0, end=None): | random_line_split |
baselines_utils.py | import numpy as np
import tensorflow as tf # pylint: ignore-module
import copy
import os
import functools
import collections
import multiprocessing
import random
def switch(condition, then_expression, else_expression):
"""Switches between two operations depending on a scalar value (int or bool).
Note that bot... | (x):
out = x.get_shape().as_list()
assert all(isinstance(a, int) for a in out), \
"shape function assumes that shape is fully known"
return out
def numel(x):
return intprod(var_shape(x))
def intprod(x):
return int(np.prod(x))
def flatgrad(loss, var_list, clip_norm=None):
grads = tf.gr... | var_shape | identifier_name |
baselines_utils.py | import numpy as np
import tensorflow as tf # pylint: ignore-module
import copy
import os
import functools
import collections
import multiprocessing
import random
def switch(condition, then_expression, else_expression):
"""Switches between two operations depending on a scalar value (int or bool).
Note that bot... |
self.op = tf.group(*assigns)
def __call__(self, theta):
tf.get_default_session().run(self.op, feed_dict={self.theta: theta})
class GetFlat(object):
def __init__(self, var_list):
self.op = tf.concat(axis=0, values=[tf.reshape(v, [numel(v)]) for v in var_list])
def __call__(self):
... | size = intprod(shape)
assigns.append(tf.assign(v, tf.reshape(theta[start:start + size], shape)))
start += size | conditional_block |
encoder.rs | extern crate deflate;
use std::borrow::Cow;
use std::error;
use std::fmt;
use std::io::{self, Write};
use std::mem;
use std::result;
use chunk;
use crc::Crc32;
use common::{AnimationControl, FrameControl, Info, ColorType, BitDepth};
use filter::{FilterType, filter};
use traits::{WriteBytesExt, HasParameters, Paramete... | else {
Err(EncodingError::Format("invalid number of frames for an animated PNG".into()))
}
}
pub fn write_header(self) -> Result<Writer<W>> {
Writer::new(self.w, self.info).init()
}
}
impl<W: Write> HasParameters for Encoder<W> {}
impl<W: Write> Parameter<Encoder<W>> for Col... | {
let mut encoder = Encoder::new(w, width, height);
let animation_ctl = AnimationControl { num_frames: frames, num_plays: 0 };
let mut frame_ctl = FrameControl::default();
frame_ctl.width = width;
frame_ctl.height = height;
encoder.info.animation... | conditional_block |
encoder.rs | extern crate deflate;
use std::borrow::Cow;
use std::error;
use std::fmt;
use std::io::{self, Write};
use std::mem;
use std::result;
use chunk;
use crc::Crc32;
use common::{AnimationControl, FrameControl, Info, ColorType, BitDepth};
use filter::{FilterType, filter};
use traits::{WriteBytesExt, HasParameters, Paramete... | use self::EncodingError::*;
match *self {
IoError(ref err) => err.description(),
Format(ref desc) => &desc,
}
}
}
impl fmt::Display for EncodingError {
fn fmt(&self, fmt: &mut fmt::Formatter) -> result::Result<(), fmt::Error> {
write!(fmt, "{}", (self as ... | fn description(&self) -> &str { | random_line_split |
encoder.rs | extern crate deflate;
use std::borrow::Cow;
use std::error;
use std::fmt;
use std::io::{self, Write};
use std::mem;
use std::result;
use chunk;
use crc::Crc32;
use common::{AnimationControl, FrameControl, Info, ColorType, BitDepth};
use filter::{FilterType, filter};
use traits::{WriteBytesExt, HasParameters, Paramete... | (&mut self) {
let _ = self.write_chunk(chunk::IEND, &[]);
}
}
#[test]
fn roundtrip() {
use std::fs::File;
// Decode image
let decoder = ::Decoder::new(File::open("tests/pngsuite/basi0g01.png").unwrap());
let (info, mut reader) = decoder.read_info().unwrap();
let mut buf = vec![0; info.b... | drop | identifier_name |
encoder.rs | extern crate deflate;
use std::borrow::Cow;
use std::error;
use std::fmt;
use std::io::{self, Write};
use std::mem;
use std::result;
use chunk;
use crc::Crc32;
use common::{AnimationControl, FrameControl, Info, ColorType, BitDepth};
use filter::{FilterType, filter};
use traits::{WriteBytesExt, HasParameters, Paramete... |
}
/// PNG Encoder
pub struct Encoder<W: Write> {
w: W,
info: Info,
}
impl<W: Write> Encoder<W> {
pub fn new(w: W, width: u32, height: u32) -> Encoder<W> {
let mut info = Info::default();
info.width = width;
info.height = height;
Encoder { w: w, info: info }
}
pub ... | {
io::Error::new(io::ErrorKind::Other, (&err as &error::Error).description())
} | identifier_body |
conn.rs | use serialize::json;
use std::comm;
use std::io;
use std::io::{BufferedReader, LineBufferedWriter, Reader, Writer};
use std::io::net::addrinfo;
use std::io::net::tcp::TcpStream;
use std::io::net::ip::SocketAddr;
use std::io::process;
use std::io::stdio::StdWriter;
use rand;
use rand::Rng;
use std::str;
use term;
use ... | else if packet_id == 0x2 {
let json = packet.read_string();
debug!("Got chat message: {}", json);
// Let's wrap up the Json so that we can
// deal with it more easily
let j = json::from_str(json).unwrap();
let j = ExtraJSON::new(j);
... | {
let x = packet.read_be_i32().unwrap();
// Need to respond
let mut resp = Packet::new_out(0x0);
resp.write_be_i32(x);
self.write_packet(resp);
// Chat Message
} | conditional_block |
conn.rs | use serialize::json;
use std::comm;
use std::io;
use std::io::{BufferedReader, LineBufferedWriter, Reader, Writer};
use std::io::net::addrinfo;
use std::io::net::tcp::TcpStream;
use std::io::net::ip::SocketAddr;
use std::io::process;
use std::io::stdio::StdWriter;
use rand;
use rand::Rng;
use std::str;
use term;
use ... |
}
| {
match *self {
Some(ref mut s) => s.flush(),
None => Err(io::standard_error(io::OtherIoError))
}
} | identifier_body |
conn.rs | use serialize::json;
use std::comm;
use std::io;
use std::io::{BufferedReader, LineBufferedWriter, Reader, Writer};
use std::io::net::addrinfo;
use std::io::net::tcp::TcpStream;
use std::io::net::ip::SocketAddr;
use std::io::process;
use std::io::stdio::StdWriter;
use rand;
use rand::Rng;
use std::str;
use term;
use ... | {
addr: SocketAddr,
host: ~str,
sock: Option<Sock>,
name: ~str,
term: term::Terminal<LineBufferedWriter<StdWriter>>
}
impl Connection {
pub fn new(name: ~str, host: ~str, port: u16) -> Result<Connection, ~str> {
// Resolve host
let addr = match addrinfo::get_host_addresses(hos... | Connection | identifier_name |
conn.rs | use serialize::json;
use std::comm;
use std::io;
use std::io::{BufferedReader, LineBufferedWriter, Reader, Writer};
use std::io::net::addrinfo;
use std::io::net::tcp::TcpStream;
use std::io::net::ip::SocketAddr;
use std::io::process;
use std::io::stdio::StdWriter;
use rand;
use rand::Rng;
use std::str;
use term;
use ... | "selectedProfile": "{}",
"serverId": "{}"
\}"#, token, profile, hash);
p.stdin = None;
// read response
let out = p.wait_with_output().output;
let out = str::from_utf8_owned(out.move_iter().collect()).unwrap();
debug!("Got - {}", out);... |
// write json to stdin and close it
write!(p.stdin.get_mut_ref() as &mut Writer, r#"
\{
"accessToken": "{}", | random_line_split |
prefix_code.rs | #![macro_escape]
use std::mem;
use std::intrinsics::ctlz32;
use std::cmp::max;
use std::iter::range_step;
static MAX_SUPPORTED_SYMS: u32 = 1024;
static MAX_EVER_CODE_SIZE: u32 = 34;
static MAX_EXPECTED_CODE_SIZE: uint = 16;
pub struct OrdFreq {
f: u16,
s: u16
}
impl OrdFreq {
pub fn new(sym: u32, freq: u32) -> O... |
}
}
for p in decoder_table.mut_iter() {
*p = 0xffff;
}
for i in range(0, sizes.len()) {
let s = sizes[i] as uint;
let code = next_code[s];
next_code[s] += 1;
let offset = (code as u16 + dec_first_offset[s]) as uint;
dec_offset_to_sym[offset] = i as u16;
let rev_code = reverse_u16(code) >> (16 ... | {
//return false; // Error, sizes don't add up
fail!("Code sizes don't add up");
} | conditional_block |
prefix_code.rs | #![macro_escape]
use std::mem;
use std::intrinsics::ctlz32;
use std::cmp::max;
use std::iter::range_step;
static MAX_SUPPORTED_SYMS: u32 = 1024;
static MAX_EVER_CODE_SIZE: u32 = 34;
static MAX_EXPECTED_CODE_SIZE: uint = 16;
pub struct OrdFreq {
f: u16,
s: u16
}
impl OrdFreq {
pub fn new(sym: u32, freq: u32) -> O... | (self) -> u16 {
self.s
}
}
pub fn sort_symbols2<'a>(mut first: &'a mut [OrdFreq], mut second: &'a mut [OrdFreq]) -> &'a mut [OrdFreq] {
let mut hist = [0u32, ..256 * 2];
for &s in first.iter() {
let f = s.freq();
hist[ (f & 0xff) as uint] += 1;
hist[256 + ((f >> 8) & 0xff) as uint] += 1;
}
l... | sym | identifier_name |
prefix_code.rs | #![macro_escape]
use std::mem;
use std::intrinsics::ctlz32;
use std::cmp::max;
use std::iter::range_step;
static MAX_SUPPORTED_SYMS: u32 = 1024;
static MAX_EVER_CODE_SIZE: u32 = 34;
static MAX_EXPECTED_CODE_SIZE: uint = 16;
pub struct OrdFreq {
f: u16,
s: u16
}
impl OrdFreq {
pub fn new(sym: u32, freq: u32) -> O... |
let mut code = 0u32;
let mut offset = 0u32;
for i in range(1, MAX_EXPECTED_CODE_SIZE + 1) {
next_code[i] = code;
dec_first_offset[i] = offset as u16 - code as u16;
code += num_codes[i];
dec_max_code[i] = code << (16 - i);
code <<= 1;
offset += num_codes[i];
}
dec_max_code[17] = 0x10000;
if code != ... | let mut next_code: [u32, ..MAX_EXPECTED_CODE_SIZE + 1] = [0, ..MAX_EXPECTED_CODE_SIZE + 1];
for &s in sizes.iter() {
num_codes[s as uint] += 1;
} | random_line_split |
fma_utils.py | """FMA Utils from https://github.com/mdeff/fma/blob/master/utils.py"""
import dotenv
import pydot
import requests
import numpy as np
import pandas as pd
import ctypes
import shutil
import multiprocessing
import multiprocessing.sharedctypes as sharedctypes
import os.path
import ast
# Number of samples per 30s audio c... |
return tracks, artists, date_created
def _get_data(self, dataset, fma_id, fields=None):
url = self.BASE_URL + dataset + 's.json?'
url += dataset + '_id=' + str(fma_id) + '&api_key=' + self.api_key
# print(url)
r = requests.get(url)
r.raise_for_status()
if r.... | tracks.append(track['track_id'])
artists.append(track['artist_name'])
date_created.append(track['track_date_created']) | conditional_block |
fma_utils.py | """FMA Utils from https://github.com/mdeff/fma/blob/master/utils.py"""
import dotenv
import pydot
import requests
import numpy as np
import pandas as pd
import ctypes
import shutil
import multiprocessing
import multiprocessing.sharedctypes as sharedctypes
import os.path
import ast
# Number of samples per 30s audio c... | :
def load(self, filepath):
raise NotImplemented()
class RawAudioLoader(Loader):
def __init__(self, sampling_rate=SAMPLING_RATE):
self.sampling_rate = sampling_rate
self.shape = (NB_AUDIO_SAMPLES * sampling_rate // SAMPLING_RATE, )
def load(self, filepath):
return self._lo... | Loader | identifier_name |
fma_utils.py | """FMA Utils from https://github.com/mdeff/fma/blob/master/utils.py"""
import dotenv
import pydot
import requests
import numpy as np
import pandas as pd
import ctypes
import shutil
import multiprocessing
import multiprocessing.sharedctypes as sharedctypes
import os.path
import ast
# Number of samples per 30s audio c... |
def get_track(self, track_id, fields=None):
return self._get_data('track', track_id, fields)
def get_album(self, album_id, fields=None):
return self._get_data('album', album_id, fields)
def get_artist(self, artist_id, fields=None):
return self._get_data('artist', artist_id, field... | url = self.BASE_URL + dataset + 's.json?'
url += dataset + '_id=' + str(fma_id) + '&api_key=' + self.api_key
# print(url)
r = requests.get(url)
r.raise_for_status()
if r.json()['errors']:
raise Exception(r.json()['errors'])
data = r.json()['dataset'][0]
... | identifier_body |
fma_utils.py | """FMA Utils from https://github.com/mdeff/fma/blob/master/utils.py"""
import dotenv
import pydot
import requests
import numpy as np
import pandas as pd
import ctypes
import shutil
import multiprocessing
import multiprocessing.sharedctypes as sharedctypes
import os.path
import ast
# Number of samples per 30s audio c... | def create_tree(root_id, node_p, depth):
if depth == 0:
return
children = self.df[self.df['parent'] == root_id]
for child in children.iterrows():
genre_id = child[0]
node_c = create_node(genre_id)
graph.add_edge(... | #name = self.df.at[genre_id, 'title'] + '\n' + str(genre_id)
name = '"{}\n{} / {}"'.format(title, genre_id, ntracks)
return pydot.Node(name)
| random_line_split |
main.rs | //! # Rust practice
#![warn(missing_docs)]
#![doc(html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
html_favicon_url = "https://www.rust-lang.org/favicon.ico",
html_root_url = "https://doc.rust-lang.org/")]
extern crate phrases;
pub use phrases::english::greetings::hello as h... | impl Circle {
fn area(&self) -> f64 {
std::f64::consts::PI * (self.radius * self.radius)
}
fn reference(&self) -> &Circle{
println!("taking self by reference!");
self
}
fn mutable_reference(&mut self) {
println!("taking self by mutable reference!");
}
... | random_line_split | |
main.rs | //! # Rust practice
#![warn(missing_docs)]
#![doc(html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
html_favicon_url = "https://www.rust-lang.org/favicon.ico",
html_root_url = "https://doc.rust-lang.org/")]
extern crate phrases;
pub use phrases::english::greetings::hello as h... | (&self) -> String { format!("string: {}", *self) }
}
fn do_something<T: FooBar>(x: T) {
x.method();
}
let x = 5u8;
let y = "Hello".to_string();
do_something(x);
do_something(y);
fn do_something2(x: &FooBar) {
x.method();
}
let x = 5u8;
//casting
do_something2(&x as &FooBar);
... | method | identifier_name |
main.rs | //! # Rust practice
#![warn(missing_docs)]
#![doc(html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
html_favicon_url = "https://www.rust-lang.org/favicon.ico",
html_root_url = "https://doc.rust-lang.org/")]
extern crate phrases;
pub use phrases::english::greetings::hello as h... |
let graph = MyGraph;
let obj = Box::new(graph) as Box<Graph<N=Node, E=Edge>>;
struct FooUnsized<T: ?Sized> {
f: T,
}
fn testUnsized(){
println!("unsized");
}
let mut fooUnsized = FooUnsized { f: testUnsized };
use std::ops::Add;
impl Add<i32> for Point {
type Output = f64;
fn add(self, ... | Vec::new()
}
}
| identifier_body |
static.go | package auth
import (
"bytes"
"crypto/hmac"
cryptorand "crypto/rand"
"crypto/sha256"
"crypto/sha512"
"encoding/base64"
"encoding/json"
"fmt"
pbauth "github.com/hwsc-org/hwsc-api-blocks/protobuf/lib"
"github.com/hwsc-org/hwsc-lib/consts"
"github.com/hwsc-org/hwsc-lib/validation"
"hash"
"strings"
"sync"
"... |
if err := ValidateSecret(secret); err != nil {
return "", err
}
if body.Permission == Admin && header.Alg != Hs512 {
return "", consts.ErrInvalidPermission
}
// Currently supports JWT, JET
if header.TokenTyp != Jwt && header.TokenTyp != Jet {
return "", consts.ErrUnknownTokenType
}
tokenString, err := ge... | {
return "", err
} | conditional_block |
static.go | package auth
import (
"bytes"
"crypto/hmac"
cryptorand "crypto/rand"
"crypto/sha256"
"crypto/sha512"
"encoding/base64"
"encoding/json"
"fmt"
pbauth "github.com/hwsc-org/hwsc-api-blocks/protobuf/lib"
"github.com/hwsc-org/hwsc-lib/consts"
"github.com/hwsc-org/hwsc-lib/validation"
"hash"
"strings"
"sync"
"... | encodedSignature, err := hashSignature(alg, encodedHeaderBody, secret)
if err != nil {
return "", nil
}
// 5. Build Token Signature = <encoded header>.<encoded body>.<hashed(<encoded header>.<encoded body>)>
var bufferTokenSignature bytes.Buffer
bufferTokenSignature.WriteString(encodedHeaderBody)
bufferTokenSi... | encodedHeaderBody := bufferHeaderBody.String()
// 4. Build <hashed(<encoded header>.<encoded body>)> | random_line_split |
static.go | package auth
import (
"bytes"
"crypto/hmac"
cryptorand "crypto/rand"
"crypto/sha256"
"crypto/sha512"
"encoding/base64"
"encoding/json"
"fmt"
pbauth "github.com/hwsc-org/hwsc-api-blocks/protobuf/lib"
"github.com/hwsc-org/hwsc-lib/consts"
"github.com/hwsc-org/hwsc-lib/validation"
"hash"
"strings"
"sync"
"... |
func isExpired(timestamp int64) bool {
if timestamp <= 0 || time.Now().UTC().Unix() >= timestamp {
return true
}
return false
}
// NewToken generates token string using a header, body, and secret.
// Return error if an error exists during signing.
func NewToken(header *Header, body *Body, secret *pbauth.Secret)... | {
if secret == nil {
return consts.ErrNilSecret
}
if strings.TrimSpace(secret.Key) == "" {
return consts.ErrEmptySecret
}
createTime := secret.CreatedTimestamp
if createTime == 0 || createTime > time.Now().UTC().Unix() {
return consts.ErrInvalidSecretCreateTimestamp
}
if isExpired(secret.ExpirationTimesta... | identifier_body |
static.go | package auth
import (
"bytes"
"crypto/hmac"
cryptorand "crypto/rand"
"crypto/sha256"
"crypto/sha512"
"encoding/base64"
"encoding/json"
"fmt"
pbauth "github.com/hwsc-org/hwsc-api-blocks/protobuf/lib"
"github.com/hwsc-org/hwsc-lib/consts"
"github.com/hwsc-org/hwsc-lib/validation"
"hash"
"strings"
"sync"
"... | (header *Header, body *Body, secret *pbauth.Secret) (string, error) {
if err := ValidateHeader(header); err != nil {
return "", err
}
if err := ValidateBody(body); err != nil {
return "", err
}
if err := ValidateSecret(secret); err != nil {
return "", err
}
if body.Permission == Admin && header.Alg != Hs51... | getTokenSignature | identifier_name |
reader.rs | use std::cmp::Reverse;
use std::sync::Arc;
use aexecutor::SearcherExecutorPool;
use anyhow::{Error, Result};
use serde::{Deserialize, Serialize};
use tantivy::collector::{Count, TopDocs};
use tantivy::fastfield::FastFieldReader;
use tantivy::query::{Query, TermQuery};
use tantivy::schema::{Field, FieldType, IndexRecor... |
#[derive(Debug, Serialize)]
pub struct QueryResults {
/// The retrieved documents.
pub(crate) hits: Vec<DocumentHit>,
/// The total amount of documents matching the search
count: usize,
/// The amount of time taken to search in seconds.
time_taken: f32,
}
impl QueryResults {
#[inline]
... | impl Default for Sort {
fn default() -> Self {
Self::Desc
}
} | random_line_split |
reader.rs | use std::cmp::Reverse;
use std::sync::Arc;
use aexecutor::SearcherExecutorPool;
use anyhow::{Error, Result};
use serde::{Deserialize, Serialize};
use tantivy::collector::{Count, TopDocs};
use tantivy::fastfield::FastFieldReader;
use tantivy::query::{Query, TermQuery};
use tantivy::schema::{Field, FieldType, IndexRecor... | ,
_ => Err(Error::msg("field is not a fast field")),
};
}
let out = match field_type {
FieldType::I64(_) => {
let collector =
collector.custom_score(move |segment_reader: &SegmentReader| {
let reader = segment_reader
... | {
let out: (Vec<(DateTime, DocAddress)>, usize) =
order_and_search(&searcher, field, query, collector, executor)?;
Ok((process_search(&searcher, schema, out.0)?, out.1))
} | conditional_block |
reader.rs | use std::cmp::Reverse;
use std::sync::Arc;
use aexecutor::SearcherExecutorPool;
use anyhow::{Error, Result};
use serde::{Deserialize, Serialize};
use tantivy::collector::{Count, TopDocs};
use tantivy::fastfield::FastFieldReader;
use tantivy::query::{Query, TermQuery};
use tantivy::schema::{Field, FieldType, IndexRecor... | (&self) -> Result<()> {
if self.max_concurrency == 0 {
return Err(Error::msg("max concurrency must be at least 1."));
}
Ok(())
}
}
impl ReaderContext {
fn default_reader_threads() -> usize {
1
}
}
/// A given query payload that describes how the reader should
/... | validate | identifier_name |
reader.rs | use std::cmp::Reverse;
use std::sync::Arc;
use aexecutor::SearcherExecutorPool;
use anyhow::{Error, Result};
use serde::{Deserialize, Serialize};
use tantivy::collector::{Count, TopDocs};
use tantivy::fastfield::FastFieldReader;
use tantivy::query::{Query, TermQuery};
use tantivy::schema::{Field, FieldType, IndexRecor... |
/// Searches the index reader with the given query payload.
///
/// The payload determines the behaviour of the query results.
/// The actual behaviour of how a query is built is upto the query handler
/// which will parse and interpret the given data.
pub(crate) async fn search(&self, qry: Qu... | {
let id_field = self.query_handler.id_field();
let document = self
.pool
.spawn(move |searcher, executor| {
let qry = TermQuery::new(
Term::from_field_u64(id_field, id),
IndexRecordOption::Basic,
);
... | identifier_body |
LibphysGRU.py | from DeepLibphys.models_tf.LibphysDNN import *
class LibphysGRU(LibphysDNN):
def __init__(self, signal2model=None):
super().__init__(signal2model)
def get_specific_variables(self):
self.trainables = self.parameters
def get_common_variables(self):
Hd = self.signal2model.hidden_di... | # [s, o, l] = tf.scan(self.GRUnn, x_batch, initializer=[initial_s, initial_out, initial_l], parallel_iterations=1,
# name="network_output")
[s, o] = tf.scan(self.GRUnn, x_batch, initializer=[initial_s, initial_out], parallel_iterations=1,
name="networ... | random_line_split | |
LibphysGRU.py | from DeepLibphys.models_tf.LibphysDNN import *
class LibphysGRU(LibphysDNN):
def __init__(self, signal2model=None):
super().__init__(signal2model)
def get_specific_variables(self):
self.trainables = self.parameters
def get_common_variables(self):
Hd = self.signal2model.hidden_di... |
self.train_time = self.start_time - time.time()
plt.figure()
plt.plot(self.loss_history)
plt.show()
return True
# labnotebook.end_experiment(experiment,
# final_trainloss=full_loss)
@staticmethod
def load_full_model(self, mode... | self.epoch += 1
# tic = time.time()
random_indexes = np.random.permutation(self.signal2model.batch_size)
groups = np.reshape(random_indexes,
(int(self.signal2model.batch_size/self.signal2model.mini_batch_size),
self.sig... | conditional_block |
LibphysGRU.py | from DeepLibphys.models_tf.LibphysDNN import *
class LibphysGRU(LibphysDNN):
def __init__(self, signal2model=None):
super().__init__(signal2model)
def get_specific_variables(self):
self.trainables = self.parameters
def get_common_variables(self):
Hd = self.signal2model.hidden_di... |
@property
def optimize_op(self):
""" An Operation that takes one optimization step. """
return self._optimize_op
def train(self, X, Y, signal2model=None):
self.batch_size += np.shape(X)[0]
self.init_time = time.time()
plt.ion()
if signal2model is not None:
... | trainables = self.parameters
grads = tf.gradients(self.loss, trainables)
grad_var_pairs = zip(grads, trainables)
# grads, _ = tf.clip_by_global_norm(grads, clip_norm=1.0)
# self.learning_rate = tf.train.exponential_decay(
# self.signal2model.learning_rate_val, self.epoch, sel... | identifier_body |
LibphysGRU.py | from DeepLibphys.models_tf.LibphysDNN import *
class LibphysGRU(LibphysDNN):
def __init__(self, signal2model=None):
super().__init__(signal2model)
def get_specific_variables(self):
self.trainables = self.parameters
def get_common_variables(self):
Hd = self.signal2model.hidden_di... | (self, x_batch):
initial_s = tf.zeros((self.signal2model.n_grus, self.signal2model.hidden_dim, tf.shape(x_batch)[1]), dtype=np.float32)
initial_out = tf.zeros((self.signal2model.signal_dim, tf.shape(x_batch)[1]), dtype=np.float32)
# initial_l = tf.zeros((self.signal2model.signal_dim, tf.shape(x_... | feed_forward_predict | identifier_name |
search-table.controller.js | /**
* (c) Copyright 2015 Hewlett-Packard Development Company, L.P.
*
* 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 requir... |
if ( searchlight_item ) {
searchlight_item.dirty = true;
searchlight_item.deleted = deleted;
cache.add(searchlight_item, searchlight_item._id, getSearchlightTimestamp(searchlight_item));
}
}
});
}
function actionErrorHandler(reason) { // es... | {
ctrl.hitsSrc.splice(index,1);
} | conditional_block |
search-table.controller.js | /**
* (c) Copyright 2015 Hewlett-Packard Development Company, L.P.
*
* 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 requir... | 'horizon.framework.conf.resource-type-registry.service',
'horizon.app.core.openstack-service-api.userSession',
'horizon.dashboard.project.search.searchlightFacetUtils',
'horizon.dashboard.project.search.searchlightSearchHelper',
'horizon.dashboard.project.search.settingsService',
'horizon.dashbo... | random_line_split | |
search-table.controller.js | /**
* (c) Copyright 2015 Hewlett-Packard Development Company, L.P.
*
* 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 requir... |
if ( items ) {
result = items.reduce(typeIdReduce, []);
} else {
result = [];
}
return result;
}
function getSearchlightTimestamp(searchlight_item) {
var timestamp = '';
if (searchlight_item._version) {
timestamp = searchlight_item._version;
... | {
if (type === undefined || item.type === type) {
accumulator.push(item.id);
}
return accumulator;
} | identifier_body |
search-table.controller.js | /**
* (c) Copyright 2015 Hewlett-Packard Development Company, L.P.
*
* 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 requir... | (searchlight_item) {
return cache.sync(searchlight_item, searchlight_item._id, getSearchlightTimestamp(searchlight_item));
}
function removeDeletedItems(searchlight_item) {
if ( searchlight_item.deleted ) {
return false;
} else {
return true;
}
}
function action... | syncWithCache | identifier_name |
modal-gallery.component.ts | /*
The MIT License (MIT)
Copyright (c) 2017 Stefano Cappa (Ks89)
Copyright (c) 2016 vimalavinisha (only for version 1)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, i... | this.description = description;
this.extUrl = extUrl;
this.selected = selected;
}
}
/**
* Enum `Keyboard` with keys and their relative key codes.
*/
export enum Keyboard {
ESC = 27,
LEFT_ARROW = 37,
RIGHT_ARROW = 39,
UP_ARROW = 38,
DOWN_ARROW = 40
}
/**
* Interface `Description` to change t... | this.width = width;
this.height = height;
this.thumb = thumb; | random_line_split |
modal-gallery.component.ts | /*
The MIT License (MIT)
Copyright (c) 2017 Stefano Cappa (Ks89)
Copyright (c) 2016 vimalavinisha (only for version 1)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, i... |
const esc: number = this.keyboardConfig && this.keyboardConfig.esc ? this.keyboardConfig.esc : Keyboard.ESC;
const right: number = this.keyboardConfig && this.keyboardConfig.right ? this.keyboardConfig.right : Keyboard.RIGHT_ARROW;
const left: number = this.keyboardConfig && this.keyboardConfig.left ? this... | {
return;
} | conditional_block |
modal-gallery.component.ts | /*
The MIT License (MIT)
Copyright (c) 2017 Stefano Cappa (Ks89)
Copyright (c) 2016 vimalavinisha (only for version 1)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, i... | tImageCountsToDisplay(){
var selectedImages = this.images.filter(image=>{
return image.selected === true;
});
var selectedImageCount = selectedImages.length;
var tobeselected = this.selectionLimit - selectedImageCount;
this.canSelectImage = tobeselected <= 0 && !this.currentImage.selected;
... | // to prevent errors when you pass to this library
// the array of images inside a subscribe block, in this way: `...subscribe(val => { this.images = arrayOfImages })`
// As you can see, I'm providing examples in these situations in all official demos
if (this.modalImages) {
// I pass `false` as param... | identifier_body |
modal-gallery.component.ts | /*
The MIT License (MIT)
Copyright (c) 2017 Stefano Cappa (Ks89)
Copyright (c) 2016 vimalavinisha (only for version 1)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, i... | if (!this.downloadable) {
return;
}
// for all browsers
// Attention: with IE is not working, but it will navigate to the image
let link = document.createElement('a');
link.href = this.currentImage.img;
link.setAttribute('download', this.getFileName(this.currentImage.img));
document... | adImage() {
| identifier_name |
lib.rs | /// Return an error from a function
/// Assumes that 'Locatable' is in scope and that the function it is called in
/// returns a 'Result<Locatable<T>>'
macro_rules! semantic_err {
($message: expr, $location: expr $(,)?) => {
return Err(CompileError::semantic(Locatable {
data: $message,
... | (jit: bool) -> Box<dyn TargetIsa + 'static> {
let mut flags_builder = cranelift::codegen::settings::builder();
// `simplejit` requires non-PIC code
if !jit {
// allow creating shared libraries
flags_builder
.enable("is_pic")
.expect("is_pic should be a valid option");... | get_isa | identifier_name |
lib.rs | /// Return an error from a function
/// Assumes that 'Locatable' is in scope and that the function it is called in
/// returns a 'Result<Locatable<T>>'
macro_rules! semantic_err {
($message: expr, $location: expr $(,)?) => {
return Err(CompileError::semantic(Locatable {
data: $message,
... |
// TODO: this is grossly inefficient, ask Cranelift devs if
// there's an easier way to make parameters modifiable.
fn store_stack_params(
&mut self,
params: &[Symbol],
func_start: Block,
location: &Location,
builder: &mut FunctionBuilder,
) -> CompileResult<()> ... | {
match init {
Initializer::Scalar(expr) => {
let val = self.compile_expr(*expr, builder)?;
// TODO: replace with `builder.ins().stack_store(val.ir_val, stack_slot, 0);`
// when Cranelift implements stack_store for i8 and i16
let addr =... | identifier_body |
lib.rs | /// Return an error from a function
/// Assumes that 'Locatable' is in scope and that the function it is called in
/// returns a 'Result<Locatable<T>>'
macro_rules! semantic_err {
($message: expr, $location: expr $(,)?) => {
return Err(CompileError::semantic(Locatable {
data: $message,
... | // link the .o file using host linker
let status = Command::new("cc")
.args(&[&obj_file, Path::new("-o"), output])
.status()
.map_err(|err| {
if err.kind() == ErrorKind::NotFound {
Error::new(
ErrorKind::NotFound,
"could... | use std::io::{Error, ErrorKind};
use std::process::Command;
| random_line_split |
cef.go | // Copyright (c) 2014 The cef2go authors. All rights reserved.
// License: BSD 3-clause.
// Website: https://github.com/CzarekTomczak/cef2go
// Website: https://github.com/fromkeith/cef2go
package cef2go
/*
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
CEF capi fixes
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!... |
func (d defaultLogger) Panicf(fmt string, args ... interface{}) {
log.Panicf("[cef] " + fmt, args...)
}
// Sandbox is disabled. Including the "cef_sandbox.lib"
// library results in lots of GCC warnings/errors. It is
// compatible only with VS 2010. It would be required to
// build it using GCC. Add -lcef_sandbo... | {
log.Printf("[cef] " + fmt, args...)
} | identifier_body |
cef.go | // Copyright (c) 2014 The cef2go authors. All rights reserved.
// License: BSD 3-clause.
// Website: https://github.com/CzarekTomczak/cef2go
// Website: https://github.com/fromkeith/cef2go
package cef2go
/*
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
CEF capi fixes
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!... | Logger.Infof("CreateBrowser, url=%s\n", url)
// Initialize cef_window_info_t structure.
var windowInfo *C.cef_window_info_t
windowInfo = (*C.cef_window_info_t)(
C.calloc(1, C.sizeof_cef_window_info_t))
FillWindowInfo(windowInfo, hwnd)
// url
var cefUrl *C.cef_string_t
cefU... | url string) bool { | random_line_split |
cef.go | // Copyright (c) 2014 The cef2go authors. All rights reserved.
// License: BSD 3-clause.
// Website: https://github.com/CzarekTomczak/cef2go
// Website: https://github.com/fromkeith/cef2go
package cef2go
/*
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
CEF capi fixes
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!... | (fmt string, args ... interface{}) {
log.Printf("[cef] " + fmt, args...)
}
func (d defaultLogger) Panicf(fmt string, args ... interface{}) {
log.Panicf("[cef] " + fmt, args...)
}
// Sandbox is disabled. Including the "cef_sandbox.lib"
// library results in lots of GCC warnings/errors. It is
// compatible only... | Errorf | identifier_name |
cef.go | // Copyright (c) 2014 The cef2go authors. All rights reserved.
// License: BSD 3-clause.
// Website: https://github.com/CzarekTomczak/cef2go
// Website: https://github.com/fromkeith/cef2go
package cef2go
/*
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
CEF capi fixes
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!... |
numValsForKey := C.cef_string_multimap_find_count(cefMapPointer, C.cefString16CastToCefString(key))
if numValsForKey >= 0 {
goVals := make([]string, numValsForKey)
for k := 0; k < int(numValsForKey); k++ {
var val *C.cef_string_utf16_t = C.cef_string_userfree_ut... | {
continue
} | conditional_block |
romaO.py | #
# romaO
# www.fabiocrameri.ch/colourmaps
from matplotlib.colors import LinearSegmentedColormap
cm_data = [[0.45137, 0.22346, 0.34187],
[0.45418, 0.22244, 0.3361],
[0.45696, 0.22158, 0.33043],
[0.45975, 0.2209, 0.32483],
... | import matplotlib.pyplot as plt
import numpy as np
try:
from viscm import viscm
viscm(romaO_map)
except ImportError:
print("viscm not found, falling back on simple display")
plt.imshow(np.linspace(0, 100, 256)[None, :], aspect=... | conditional_block | |
romaO.py | #
# romaO
# www.fabiocrameri.ch/colourmaps
from matplotlib.colors import LinearSegmentedColormap
cm_data = [[0.45137, 0.22346, 0.34187],
[0.45418, 0.22244, 0.3361],
[0.45696, 0.22158, 0.33043],
[0.45975, 0.2209, 0.32483],
... | [0.54332, 0.79522, 0.81088],
[0.53412, 0.78958, 0.81105],
[0.525, 0.7838, 0.81105],
[0.51593, 0.77791, 0.81088],
[0.50695, 0.77189, 0.81055],
[0.49808, 0.76577, 0.81007],
[0.48928, 0.75954, 0.80944],
... | [0.58965, 0.82137, 0.80743],
[0.58037, 0.81644, 0.80848],
[0.57108, 0.81135, 0.80935],
[0.56181, 0.80612, 0.81004],
[0.55255, 0.80074, 0.81055], | random_line_split |
tags.rs | use std::{str::FromStr, sync::Arc, time::Duration};
use eyre::Report;
use rand::RngCore;
use rosu_v2::model::GameMode;
use tokio::fs;
use tokio_stream::StreamExt;
use twilight_model::{channel::ReactionType, gateway::event::Event, http::attachment::Attachment};
use super::ReactionWrapper;
use crate::{
database::Ma... | &ctx, builder).await?;
break;
}
}
Ok(())
}
async fn get_random_image(mut mapsets: Vec<MapsetTagWrapper>, mode: GameMode) -> (u32, Vec<u8>) {
let mut path = CONFIG.get().unwrap().paths.backgrounds.clone();
match mode {
GameMode::Osu => path.push(OSU),
GameMode::Man... | let builder = MessageBuilder::new().content("Exiting loop :wave:");
msg.create_message( | conditional_block |
tags.rs | use std::{str::FromStr, sync::Arc, time::Duration};
use eyre::Report;
use rand::RngCore;
use rosu_v2::model::GameMode;
use tokio::fs;
use tokio_stream::StreamExt;
use twilight_model::{channel::ReactionType, gateway::event::Event, http::attachment::Attachment};
use super::ReactionWrapper;
use crate::{
database::Ma... | let mode = match args.next() {
Some(arg) => match arg.cow_to_ascii_lowercase().as_ref() {
"mna" | "mania" | "m" => GameMode::Mania,
"osu" | "std" | "standard" | "o" => GameMode::Osu,
_ => {
let content = "Could not parse first argument as mode. \
... | CommandData::Interaction { .. } => unreachable!(),
};
// Parse arguments as mode | random_line_split |
tags.rs | use std::{str::FromStr, sync::Arc, time::Duration};
use eyre::Report;
use rand::RngCore;
use rosu_v2::model::GameMode;
use tokio::fs;
use tokio_stream::StreamExt;
use twilight_model::{channel::ReactionType, gateway::event::Event, http::attachment::Attachment};
use super::ReactionWrapper;
use crate::{
database::Ma... | tch mode {
GameMode::Osu => path.push(OSU),
GameMode::Mania => path.push(MANIA),
_ => unreachable!(),
}
loop {
let random_idx = {
let mut rng = rand::thread_rng();
rng.next_u32() as usize % mapsets.len()
};
let mapset = mapsets.swap_remov... | clone();
ma | identifier_name |
tags.rs | use std::{str::FromStr, sync::Arc, time::Duration};
use eyre::Report;
use rand::RngCore;
use rosu_v2::model::GameMode;
use tokio::fs;
use tokio_stream::StreamExt;
use twilight_model::{channel::ReactionType, gateway::event::Event, http::attachment::Attachment};
use super::ReactionWrapper;
use crate::{
database::Ma... | ackgrounds.clone();
match mode {
GameMode::Osu => path.push(OSU),
GameMode::Mania => path.push(MANIA),
_ => unreachable!(),
}
loop {
let random_idx = {
let mut rng = rand::thread_rng();
rng.next_u32() as usize % mapsets.len()
};
let ... | let (msg, mut args) = match data {
CommandData::Message { msg, args, .. } => (msg, args),
CommandData::Interaction { .. } => unreachable!(),
};
// Parse arguments as mode
let mode = match args.next() {
Some(arg) => match arg.cow_to_ascii_lowercase().as_ref() {
"mna" | ... | identifier_body |
golem_renderer.rs | use crate::*;
use golem::*;
use std::cell::RefCell;
use std::collections::HashMap;
impl Renderer {
/// Constructs a new `Renderer` that will draw onto the given golem `Context` within the given
/// *initial_viewport*. Normally, only the *wrapper* should use this function.
pub fn new(context: Context, initi... | );
}
for int_counter in 1 ..= shader.description.num_ints {
let _result = shader_program.set_uniform(
&format!("int{}", int_counter),
UniformValue::Int(parameters.ints[int_counter as usize - 1])
... | UniformValue::Float(parameters.floats[float_counter as usize - 1]) | random_line_split |
golem_renderer.rs | use crate::*;
use golem::*;
use std::cell::RefCell;
use std::collections::HashMap;
impl Renderer {
/// Constructs a new `Renderer` that will draw onto the given golem `Context` within the given
/// *initial_viewport*. Normally, only the *wrapper* should use this function.
pub fn new(context: Context, initi... | (&self) -> &ElementBuffer {
&self.storage.quad_indices
}
/// Gets the number of indices in the `ElementBuffer` given by the `get_quad_indices`
/// method, in integers (which is just 6).
pub fn get_num_quad_indices(&self) -> usize {
6
}
/// Checks if the shader with the given *i... | get_quad_indices | identifier_name |
golem_renderer.rs | use crate::*;
use golem::*;
use std::cell::RefCell;
use std::collections::HashMap;
impl Renderer {
/// Constructs a new `Renderer` that will draw onto the given golem `Context` within the given
/// *initial_viewport*. Normally, only the *wrapper* should use this function.
pub fn new(context: Context, initi... |
// Now that we are sure we won't exceed the maximum number of shaders, we can insert the
// new shader, and return a reference to it.
let value = self.map.entry(id.clone()).or_insert(CachedShader {
last_used: self.current_time,
shader: create_shader()?,
});
... | {
let mut last_used_times: Vec<u64> = self
.map
.values()
.map(|cached_shader| cached_shader.last_used)
.collect();
last_used_times.sort();
let median = last_used_times[last_used_times.len() / 2];
// Remove ... | conditional_block |
TheGiver.py | #!/usr/bin/python
import os
import sys
import random
import json
import shutil
import time
import datetime
from pprint import pprint
userFile = os.path.join(os.path.dirname(__file__), 'data/users.json')
saveFile = os.path.join(os.path.dirname(__file__), 'data/save.json')
browsersFile = os.path.join(os.path.dirname(_... | currentLoser = users[0]
currentScore = usersPreviousScore(currentLoser["name"])
for user in users:
userScore = usersPreviousScore(user["name"])
if userScore > currentScore:
currentLoser = user
currentScore = userScore
return currentLoser
# Clean up object
for user in users:
user["score"] = 0.0
user["la... |
def previousRoundLoser(): | random_line_split |
TheGiver.py | #!/usr/bin/python
import os
import sys
import random
import json
import shutil
import time
import datetime
from pprint import pprint
userFile = os.path.join(os.path.dirname(__file__), 'data/users.json')
saveFile = os.path.join(os.path.dirname(__file__), 'data/save.json')
browsersFile = os.path.join(os.path.dirname(_... |
user["last_score"] = scoreThisRound
user["score"] = user["score"] + scoreThisRound
# Laugh at big losers
if scoreThisRound > 12:
usersBrowsersString = usersBrowsersString + ' <-- Sheesh!'
# Track losers
if scoreThisRound > thisLosingScore:
thisLoser = user["name"]
thisLosingScore = scoreThisRoun... | scoreThisRound = scoreThisRound + browser["score"]
usersBrowsersString = usersBrowsersString + '[' + browser["name"] + '] '
# update the number of times user has tested this browser
browserCount = usersBrowserCount(user["name"], browser["name"])
browserCount["count"] = browserCount["count"] + 1 | conditional_block |
TheGiver.py | #!/usr/bin/python
import os
import sys
import random
import json
import shutil
import time
import datetime
from pprint import pprint
userFile = os.path.join(os.path.dirname(__file__), 'data/users.json')
saveFile = os.path.join(os.path.dirname(__file__), 'data/save.json')
browsersFile = os.path.join(os.path.dirname(_... | ():
currentLoser = users[0]
currentScore = usersPreviousScore(currentLoser["name"])
for user in users:
userScore = usersPreviousScore(user["name"])
if userScore > currentScore:
currentLoser = user
currentScore = userScore
return currentLoser
# Clean up object
for user in users:
user["score"] = 0.0
user... | previousRoundLoser | identifier_name |
TheGiver.py | #!/usr/bin/python
import os
import sys
import random
import json
import shutil
import time
import datetime
from pprint import pprint
userFile = os.path.join(os.path.dirname(__file__), 'data/users.json')
saveFile = os.path.join(os.path.dirname(__file__), 'data/save.json')
browsersFile = os.path.join(os.path.dirname(_... |
def previousRoundLoser():
currentLoser = users[0]
currentScore = usersPreviousScore(currentLoser["name"])
for user in users:
userScore = usersPreviousScore(user["name"])
if userScore > currentScore:
currentLoser = user
currentScore = userScore
return currentLoser
# Clean up object
for user in users:
u... | return sum(b["score"] for b in usersObj[userName]["previous_browsers"]) | identifier_body |
repr.rs | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
//! Flattened Representation of an AssumeRole chain
//!
//! Assume Role credentials in profile files can chain together credentials from multiple
//! different providers with subsequent credentials bein... | {
AssumeRole {
role_arn: String,
external_id: Option<String>,
role_session_name: Option<String>,
},
AccessKey {
access_key_id: String,
secret_access_key: String,
session_token: Option<String>,
},
NamedSource... | Provider | identifier_name |
repr.rs | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
//! Flattened Representation of an AssumeRole chain
//!
//! Assume Role credentials in profile files can chain together credentials from multiple
//! different providers with subsequent credentials bein... |
/// Load static credentials from a profile
///
/// Example:
/// ```ini
/// [profile B]
/// aws_access_key_id = abc123
/// aws_secret_access_key = def456
/// ```
fn static_creds_from_profile(profile: &Profile) -> Result<Credentials, ProfileFileError> {
use static_credentials::*;
let access_key = profile.get(AW... | {
let session_name = profile.get(role::SESSION_NAME);
match (
profile.get(role::ROLE_ARN),
profile.get(web_identity_token::TOKEN_FILE),
) {
(Some(role_arn), Some(token_file)) => Some(Ok(BaseProvider::WebIdentityTokenRole {
role_arn,
web_identity_token_file: to... | identifier_body |
repr.rs | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
//! Flattened Representation of an AssumeRole chain
//!
//! Assume Role credentials in profile files can chain together credentials from multiple
//! different providers with subsequent credentials bein... | }
pub fn chain(&self) -> &[RoleArn<'a>] {
&self.chain.as_slice()
}
}
/// A base member of the profile chain
///
/// Base providers do not require input credentials to provide their own credentials,
/// eg. IMDS, ECS, Environment variables
#[derive(Debug, Clone)]
#[non_exhaustive]
pub enum BaseProv... | random_line_split | |
neural_network.py | from __future__ import print_function
import itertools
import sys
import re
from collections import Counter
from functools import partial
from functools import reduce
from multiprocessing import Pool
from random import shuffle
from sys import stderr
import numpy as np
from numpy import diag
from numpy import inf
from ... |
def estimate_grad__L__V_h(self, h, x, V, W, y, grad):
eps = EPSILON_FINITE_DIFFERENCE
def d(j):
eps_vec = np.zeros_like(V)
eps_vec[h, j] = eps
z_plus = tanh((V + eps_vec) @ x)
z_minus = tanh((V - eps_vec) @ x)
z_plus[-1] = 1
z... | eps = EPSILON_FINITE_DIFFERENCE
def d(h):
eps_vec = np.zeros_like(z)
eps_vec[h] = eps
yhat_plus = logistic(W @ (z + eps_vec))
yhat_minus = logistic(W @ (z - eps_vec))
L_plus = self.loss(yhat_plus, y)
L_minus = self.loss(yhat_minus, y)
... | identifier_body |
neural_network.py | from __future__ import print_function
import itertools
import sys
import re
from collections import Counter
from functools import partial
from functools import reduce
from multiprocessing import Pool
from random import shuffle
from sys import stderr
import numpy as np
from numpy import diag
from numpy import inf
from ... | # grad__z_h__V_h = x * (1 - z[h] ** 2)
# grad__L__V_h = grad__L__z[h] * grad__z_h__V_h
# V[h, :] -= self.learning_rate * grad__L__V_h
xx = x.reshape((1, d + 1)).repeat(H + 1, 0)
grad__L__V = diag((1 - z ** 2) * grad__L__z) @ xx
return grad__L__V, grad__L__W
... | random_line_split | |
neural_network.py | from __future__ import print_function
import itertools
import sys
import re
from collections import Counter
from functools import partial
from functools import reduce
from multiprocessing import Pool
from random import shuffle
from sys import stderr
import numpy as np
from numpy import diag
from numpy import inf
from ... |
assert set(y) == set(np.arange(K) + 1), \
'Some labels are not represented in training data'
self.K = K
Y = one_hot_encode_array(y)
return X, Y
class Layer:
"""
Each layer has two attributes:
- W a (j x k) weight matrix, where j is the number of units in the... | y_int = np.floor(y).astype(np.int)
assert (y_int == y).all()
y = y_int | conditional_block |
neural_network.py | from __future__ import print_function
import itertools
import sys
import re
from collections import Counter
from functools import partial
from functools import reduce
from multiprocessing import Pool
from random import shuffle
from sys import stderr
import numpy as np
from numpy import diag
from numpy import inf
from ... | (self, yhat):
"""
Map values in output layer to classification predictions.
"""
raise NotImplementedError
class SingleLayerTanhLogisticNeuralNetwork(NeuralNetwork):
"""
A classification neural net with one hidden layer.
The hidden layer uses the tanh activation function.
... | prediction_fn | identifier_name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.