file_name stringlengths 3 137 | prefix stringlengths 0 918k | suffix stringlengths 0 962k | middle stringlengths 0 812k |
|---|---|---|---|
types.rs | /// A temperature measurement.
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub struct Temperature(i32);
/// A humidity measurement.
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub struct Humidity(i32);
/// A combined temperature / humidity measurement.
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub struct Measure... | (humi_raw: u16) -> i32 {
(((humi_raw as u32) * 12500) >> 13) as i32
}
#[cfg(test)]
mod tests {
use super::*;
/// Test conversion of raw measurement results into °C.
#[test]
fn test_convert_temperature() {
let test_data = [
(0x0000, -45000),
// Datasheet setion 5.11 ... | convert_humidity |
ld-header-with-filter.ts | import {
LitElement, css, customElement, html, property
} from 'lit-element';
import '@polymer/paper-input/paper-input';
import '@polymer/paper-icon-button/paper-icon-button';
import type { Language, Resources } from '../localize';
import Localize from '../localize';
import { ironFlexLayoutAlignTheme, ironFlexLayout... | }
paper-icon-button {
--paper-icon-button: {
color: var(--paper-icon-button-color);
}
--paper-icon-button-hover: {
color: var(--paper-icon-button-color-hover);
}
}
</style>
<paper-input
... | --paper-input-container-input: {
font-size: 7px;
}; |
777_all_in_one_v1.py | #=========================================================
# Developer: Vajira Thambawita
# Reference: https://github.com/meetshah1995/pytorch-semseg
#=========================================================
import argparse
from datetime import datetime
import os
import copy
from tqdm import tqdm
import matplotlib.... |
print("Model best epoch:", test_epoch)
preprocessing_fn = smp.encoders.get_preprocessing_fn(opt.encoder, opt.encoder_weights)
test_dataset = prepare_test_data(opt, preprocessing_fn=None)
test_dataset_vis = prepare_test_data(opt, preprocessing_fn=None)
for i in range(opt.num_test_samples)... |
test_epoch = checkpoint_dict["epoch"]
best_model = checkpoint_dict["model"] |
command_runner.go | package powercycle
import (
"bytes"
"context"
"io"
"strings"
"time"
"go.skia.org/infra/go/executil" | "go.skia.org/infra/go/skerr"
)
// execTimeout is the timeout when we exec a command over SSH.
const execTimeout = 10 * time.Second
// The CommandRunner interface adds a layer of abstraction around sending commands to powercycle
// Controllers. It is not meant to be a general purpose interface or a robust implementat... | |
a_star_03.py | maze = [[0,0,0,0,0,0,0,0,0,0],
[0,1,1,1,1,1,1,1,1,0],
[0,1,1,1,1,1,1,1,1,0],
[0,1,1,1,1,1,1,1,1,0],
[0,1,1,1,1,1,1,1,1,0],
[0,1,1,1,1,1,1,1,1,0],
[0,1,1,1,1,1,1,1,1,0],
[0,1,1,1,1,1,1,1,1,0],
[0,1,1,1,1,1,1,1,1,0],
[0,0,0,0,0,0,0,0,0,0]]
# we start... | (p,q):
t = 1+abs(p-h)+abs(q-k)
return t
while(a!=4 and b!=4):
# checking the posibility of motion
maze[a][b] = '*'
if(maze[a+1][b]==1): #checking for right
t_r=cost(a+1,b)
else:
t_r = cost(a,b)
if(maze[a][b+1]==1):
t_d = cost(a,b+1)
else:
t_d = cost(a,b... | cost |
stats.py | """Miscellaneous statistical functions."""
import numpy as np
import scipy.stats as ss
from scipy.optimize import Bounds, minimize
def weighted_least_squares(y, v, X, tau2=0.0, return_cov=False):
"""2-D weighted least squares.
Args:
y (NDArray): 2-d array of estimates (studies x parallel datasets)
... | # Use the D-L estimate of tau^2 as a starting point; when using a fixed
# value, minimize() sometimes fails to stay in bounds.
from .estimators import DerSimonianLaird
ub_start = 2 * DerSimonianLaird().fit(y, v, X).params_["tau2"]
lb = minimize(lambda x: (q_gen(*args, x) - l_crit) ** 2, [0], bound... | u_crit = ss.chi2.ppf(alpha / 2, df)
args = (ensure_2d(y), ensure_2d(v), X)
bds = Bounds([0], [np.inf], keep_feasible=True)
|
releases.rs | use std::env;
use std::ffi::OsStr;
use std::fs;
use std::io::Read;
use std::path::{Path, PathBuf};
use failure::{bail, Error};
use if_chain::if_chain;
use lazy_static::lazy_static;
use regex::Regex;
use crate::utils::cordova::CordovaConfig;
use crate::utils::vcs;
use crate::utils::xcode::InfoPlist;
pub fn get_cordov... |
pub fn get_xcode_release_name(plist: Option<InfoPlist>) -> Result<Option<String>, Error> {
// if we are executed from within xcode, then we can use the environment
// based discovery to get a release name without any interpolation.
if let Some(plist) = plist.or(InfoPlist::discover_from_env()?) {
r... | {
let here = path.unwrap_or(env::current_dir()?);
let platform = match here.file_name().and_then(OsStr::to_str) {
Some("android") => "android",
Some("ios") => "ios",
_ => return Ok(None),
};
l... |
_match.rs | // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... | <'a, 'p, 'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
m: &[Match<'a, 'p, 'blk, 'tcx>],
vals: &[MatchInput],
chk: &FailureHandler,
has_genuine_default: bool) {
debug!... | compile_submatch |
RemoveButton.js | import React from 'react';
import IconButton from 'material-ui/IconButton'; | import Clear from 'material-ui/svg-icons/content/clear';
import './RemoveButton.scss';
const RemoveButton = ({removePlayer, position}) => (
<div className="remove-btn"
onClick={() => removePlayer(position)}
>
<Clear />
</div>
);
export default RemoveButton; | |
api_op_GetDocumentVersion.go | // Code generated by smithy-go-codegen DO NOT EDIT.
package workdocs
import (
"context"
awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware"
"github.com/aws/aws-sdk-go-v2/aws/signer/v4"
"github.com/aws/aws-sdk-go-v2/service/workdocs/types"
"github.com/aws/smithy-go/middleware"
smithyhttp "github.com/aws/... |
if err = stack.Initialize.Add(newServiceMetadataMiddleware_opGetDocumentVersion(options.Region), middleware.Before); err != nil {
return err
}
if err = addRequestIDRetrieverMiddleware(stack); err != nil {
return err
}
if err = addResponseErrorMiddleware(stack); err != nil {
return err
}
if err = addReques... | {
return err
} |
donate.rs | use super::prelude::*;
interaction_setup! {
name = "donate",
group = "utility",
description = "Support me peko!"
}
#[interaction_cmd]
pub async fn donate(
ctx: &Ctx,
interaction: &ApplicationCommandInteraction,
config: &Config,
) -> anyhow::Result<()> | {
interaction
.create_interaction_response(&ctx.http, |r| {
r.kind(InteractionResponseType::ChannelMessageWithSource)
.interaction_response_data(|d| {
d.flags(InteractionApplicationCommandCallbackDataFlags::EPHEMERAL)
... | |
basic_ref_types.rs | #![allow(improper_ctypes)]
use marine_rs_sdk::marine;
fn | () {}
#[marine]
#[link(wasm_import_module = "arguments_passing_effector")]
extern "C" {
pub fn all_ref_types(
arg_0: &i8,
arg_1: &i16,
arg_2: &i32,
arg_3: &i64,
arg_4: &u8,
arg_5: &u16,
arg_6: &u32,
arg_7: &u64,
arg_8: &f32,
arg_9: &f6... | main |
utils.py | from datetime import timedelta, date
def | (local_date):
if isinstance(local_date, str):
d, m, y = local_date.split('.')
return '{0}-{1}-{2}'.format(y, m, d)
elif isinstance(local_date, date):
return local_date.strftime('%Y-%m-%d')
else:
return local_date
def req_timedelta(arg):
if isinstance(arg, timedelta):
... | req_date |
error.go | // Copyright 2015 The etcd Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed t... | // See the License for the specific language governing permissions and
// limitations under the License.
package runner
import (
"fmt"
"os"
"github.com/dimandzhi/etcd/client"
)
const (
// http://tldp.org/LDP/abs/html/exitcodes.html
ExitSuccess = iota
ExitError
ExitBadConnection
ExitInvalidInput // for txn, ... | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
getAUsersVideos.py | from TikTokApi import TikTokApi
# Starts TikTokApi
api = TikTokApi.get_instance()
# The Number of trending TikToks you want to be displayed
results = 10
# Returns a list of dictionaries of the trending object
userPosts = api.userPosts(
"6745191554350760966", | )
# Loops over every tiktok
for tiktok in userPosts:
# Prints the text of the tiktok
print(tiktok["desc"])
print(len(userPosts)) | "MS4wLjABAAAAM3R2BtjzVT-uAtstkl2iugMzC6AtnpkojJbjiOdDDrdsTiTR75-8lyWJCY5VvDrZ",
30, |
MicroBit.tsx | import React from 'react';
class MicroBit extends React.PureComponent {
render() {
return (
<div className="main-wrapper">
<h2 style={{padding: '5%'}}> microBit here ! </h2>
</div>
);
}
}
| export default MicroBit; | |
getMeetings.js | import axios from "axios";
import {
GET_MEETING_CALLED,
GET_MEETING_RETURNED,
GET_MEETING_ERROR
} from "./types";
export const getMeetings = () => {
const header = { Authorization: localStorage.getItem("jwt") };
const local = "http://localhost:8080";
const server = process.env.REACT_APP_TOML_PRODUCTION_UR... | });
})
.catch(err => console.log(err));
dispatch({ type: GET_MEETING_ERROR });
};
}; | |
service.py | from twisted.application import internet, service
from twisted.web import server, resource, client
from twisted.internet import defer, reactor, threads, utils, task
from zope import interface
import yaml
import time
import cgi
import random
from distributex.backends import in_memory_backend, memcached_backend
class ... | reactor.callLater(random.random()/5, self.request_wait,
request, pool, host)
elif call == 'release':
# Release a lock
self.request_release(request, pool, host)
elif call == 'get':
# Get a lock, don't wait for ... | # Wait for a lock |
catalogs_with_extra.rs | use crate::constants::CATALOG_PREVIEW_SIZE;
use crate::models::common::{
eq_update, resources_update_with_vector_content, ResourceLoadable, ResourcesAction,
};
use crate::models::ctx::Ctx;
use crate::runtime::msg::{Action, ActionLoad, Internal, Msg};
use crate::runtime::{Effects, Env, UpdateWithCtx};
use crate::typ... | }
Msg::Internal(Internal::ResourceRequestResult(request, result)) => {
resources_update_with_vector_content::<E, _>(
&mut self.catalogs,
ResourcesAction::ResourceRequestResult {
request,
resul... | let selected_effects = eq_update(&mut self.selected, None);
let catalogs_effects = eq_update(&mut self.catalogs, vec![]);
selected_effects.join(catalogs_effects) |
user.py | #!/usr/bin/env python3
#
# Copyright 2020 IBM
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed t... | class User(base_class.Base):
id = sql.Column('id', sql.Integer, nullable=False, unique=True, index=True, primary_key=True)
username = sql.Column(sql.NCHAR(32), nullable=False, index=True, unique=True)
# hashed_password = sql.Column(sql.BINARY(64), nullable=False)
hashed_password = sql.Column(sql.String(... |
import app.db.base_class as base_class
|
styles.js | !function(n){function | (e){if(t[e])return t[e].exports;var o=t[e]={i:e,l:!1,exports:{}};return n[e].call(o.exports,o,o.exports,r),o.l=!0,o.exports}var t={};r.m=n,r.c=t,r.i=function(n){return n},r.d=function(n,t,e){r.o(n,t)||Object.defineProperty(n,t,{configurable:!1,enumerable:!0,get:e})},r.n=function(n){var t=n&&n.__esModule?function(){retu... | r |
search_numeric_range_test.go | // Copyright (c) 2014 Couchbase, 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 applicable law or agreed... | in: []byte{0, 255},
out: []byte{1, 0},
},
}
for _, test := range tests {
actual := incrementBytes(test.in)
if !reflect.DeepEqual(actual, test.out) {
t.Errorf("expected %#v, got %#v", test.out, actual)
}
}
} | { |
http.go | package influxdb
import (
"context"
"crypto/tls"
"encoding/json"
"fmt"
"github.com/geekflow/straw/internal"
"github.com/geekflow/straw/plugins/serializers/influx"
log "github.com/sirupsen/logrus"
"io"
"io/ioutil"
"net"
"net/http"
"net/url"
"path"
"strings"
"time"
)
const (
defaultRequestTimeout ... |
func (c *httpClient) Close() {
internal.CloseIdleConnections(c.client)
}
| {
u := *loc
switch u.Scheme {
case "unix":
u.Scheme = "http"
u.Host = "127.0.0.1"
u.Path = "/query"
case "http", "https":
u.Path = path.Join(u.Path, "query")
default:
return "", fmt.Errorf("unsupported scheme: %q", loc.Scheme)
}
return u.String(), nil
} |
test.rs | use assert_cmd;
use std::env;
fn setup_command() -> assert_cmd::cmd::Command {
assert_cmd::Command::cargo_bin("file-has").unwrap()
}
#[test]
fn fails_with_nonexistant_file() {
setup_command()
.arg("Great googly moogly!")
.assert()
.failure();
}
// Test most basic functionality
#[test]... | } | |
stdcopy.go | package utils
import (
"encoding/binary"
"errors"
"io"
| const (
StdWriterPrefixLen = 8
StdWriterFdIndex = 0
StdWriterSizeIndex = 4
)
type StdType [StdWriterPrefixLen]byte
var (
Stdin StdType = StdType{0: 0}
Stdout StdType = StdType{0: 1}
Stderr StdType = StdType{0: 2}
)
type StdWriter struct {
io.Writer
prefix StdType
sizeBuf []byte
}
func (w *StdWriter) Wr... | "example.com/m/v2/pkg/log"
)
|
booking.model.js | const mongoose = require('mongoose');
const autopopulate = require('mongoose-autopopulate'); |
const Schema = mongoose.Schema;
// schema
const bookingSchema = new Schema({
trainId: {
type: mongoose.Schema.Types.ObjectId,
ref: 'trains',
},
passengerIds: [{
passenger: {
type: mongoose.Schema.Types.ObjectId,
ref: 'passengers',
autopopulate: {
select: ['firstName', 'last... | |
error.rs | use std::{error, fmt};
use std::string::FromUtf8Error;
use std::str::Utf8Error;
#[derive(Debug)]
pub enum Error {
StreamExpected(usize),
LimitReached(usize),
DecodeStringFailed(usize, FromUtf8Error),
DecodeStrFailed(usize, Utf8Error),
}
impl fmt::Display for Error { | match *self {
Error::DecodeStringFailed(index, ref e) => write!(f, "cannot decode string at index {}: {}", index, e),
_ => write!(f, "unimplemented")
}
}
}
impl error::Error for Error {
fn description(&self) -> &str {
match *self {
_ => "unknown opera... | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { |
fillpdf.go | /*
* FillPDF - Fill PDF forms
* Copyright 2022 Karel Bilek
* Copyright DesertBit
* Author: Roland Singer
*
* 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.a... | {
const xfdfHeader = `<?xml version="1.0" encoding="UTF-8" standalone="no"?><xfdf><fields>`
const xfdfFooter = `</fields></xfdf>`
bsb := &bytes.Buffer{}
if _, err := fmt.Fprintln(bsb, xfdfHeader); err != nil {
retur... | |
mod.rs | pub type PrintWorkflowBackgroundSession = *mut ::core::ffi::c_void;
pub type PrintWorkflowBackgroundSetupRequestedEventArgs = *mut ::core::ffi::c_void;
pub type PrintWorkflowConfiguration = *mut ::core::ffi::c_void;
pub type PrintWorkflowForegroundSession = *mut ::core::ffi::c_void;
pub type PrintWorkflowForegroundSetu... | pub const XpsToPwgr: Self = Self(1i32);
pub const XpsToPclm: Self = Self(2i32);
}
impl ::core::marker::Copy for PrintWorkflowPdlConversionType {}
impl ::core::clone::Clone for PrintWorkflowPdlConversionType {
fn clone(&self) -> Self {
*self
}
}
pub type PrintWorkflowPdlConverter = *mut ::core::f... | |
validation_test.go | /*
Copyright 2014 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, ... | (t *testing.T) {
config := clientcmdapi.NewConfig()
config.AuthInfos["error"] = &clientcmdapi.AuthInfo{
ClientCertificate: "missing",
ClientKey: "missing",
}
test := configValidationTest{
config: config,
expectedErrorSubstring: []string{"unable to read client-cert", "unable to read c... | TestValidateCertFilesNotFoundAuthInfo |
Section.js | import React from "react"
import styled from "styled-components"
import Title from "./Title"
import { getBgColor } from "../theme/utils"
const padding = `
@media (max-width: 899px) {
padding: 1rem 2rem;
}
@media (min-width: 900px) {
padding: 4.375rem 5.25rem 3.375rem;
}
`
const Main = styled.div`
ba... | `
const SectionTitle = styled(Title)`
text-transform: uppercase;
letter-spacing: .15rem;
font-weight: lighter;
opacity: .5;
`
const getColumnNode = props => {
if (props.columnNode) {
return props.columnNode
}
return <SectionTitle level={2}>{props.title || ""}</SectionTitle>
}
const Section = ({ chi... | } |
zeros.rs | //! Tests auto-converted from "sass-spec/spec/values/numbers/modulo/zeros.hrx"
#[allow(unused)]
fn | () -> crate::TestRunner {
super::runner()
}
#[test]
fn negative_negative() {
assert_eq!(
runner().ok("a {\
\n b: -0 % -1;\
\n}\n"),
"a {\
\n b: 0;\
\n}\n"
);
}
#[test]
fn negative_positive() {
assert_eq!(
runner().ok("a {\
... | runner |
list.rs | use crate::prelude::*;
use crate::types::pointer_tagging;
use std::{cmp, convert, fmt, iter, mem};
lazy_static! {
static ref LIST_TYPE_NAME: GcRef<Symbol> = { symbol_lookup::make_symbol(b"list") };
}
#[derive(Copy, Clone)]
pub enum List {
Nil,
Cons(GcRef<Cons>),
}
impl cmp::PartialEq for List {
fn eq... | (mut self) -> List {
let mut prev = Object::nil();
loop {
match self {
List::Nil => {
return List::from_unchecked(prev);
}
List::Cons(c) => {
let mut copy = c;
let &mut Cons { ref mut ... | nreverse |
exec_linux.go | package daemon // import "github.com/docker/docker/daemon"
import (
"context"
"github.com/docker/docker/container"
"github.com/docker/docker/daemon/exec"
"github.com/docker/docker/oci/caps"
"github.com/opencontainers/runc/libcontainer/apparmor"
"github.com/opencontainers/runtime-spec/specs-go"
)
func (daemon *... | p.Capabilities.Inheritable = p.Capabilities.Bounding
p.Capabilities.Effective = p.Capabilities.Bounding
}
if apparmor.IsEnabled() {
var appArmorProfile string
if c.AppArmorProfile != "" {
appArmorProfile = c.AppArmorProfile
} else if c.HostConfig.Privileged {
// `docker exec --privileged` does not cur... | p.Capabilities.Permitted = p.Capabilities.Bounding |
convert.go | // Package convert provides functions for converting to and from Lua structures
package convert
import (
"bytes"
"errors"
"fmt"
"io"
"strings"
log "github.com/sirupsen/logrus"
"github.com/xyproto/gluamapper"
"github.com/xyproto/gopher-lua"
"github.com/xyproto/jpath"
)
var (
errToMap = errors.New("could not... | (L *lua.LState, sl []string) *lua.LTable {
table := L.NewTable()
for _, element := range sl {
table.Append(lua.LString(element))
}
return table
}
// Map2table converts a map[string]string to a Lua table
func Map2table(L *lua.LState, m map[string]string) *lua.LTable {
table := L.NewTable()
for key, value := ran... | Strings2table |
MySpace.go | package main
import (
"github.com/xiaonanln/goworld"
"github.com/xiaonanln/goworld/engine/gwlog" |
// MySpace is the custom space type
type MySpace struct {
goworld.Space // Space type should always inherit from entity.Space
}
// OnGameReady is called when the game server is ready
func (space *MySpace) OnGameReady() {
gwlog.Infof("Game %d Is Ready", goworld.GetGameID())
} | ) |
endpoints.go | // Code generated by smithy-go-codegen DO NOT EDIT.
package batch
import (
"context"
"errors"
"fmt"
"github.com/aws/aws-sdk-go-v2/aws"
awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware"
internalendpoints "github.com/aws/aws-sdk-go-v2/service/batch/internal/endpoints"
"github.com/aws/smithy-go/middlewa... |
type ResolveEndpoint struct {
Resolver EndpointResolver
Options EndpointResolverOptions
}
func (*ResolveEndpoint) ID() string {
return "ResolveEndpoint"
}
func (m *ResolveEndpoint) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) (
out middleware.SerializeOut... | {
e := aws.Endpoint{URL: url, Source: aws.EndpointSourceCustom}
for _, fn := range optFns {
fn(&e)
}
return EndpointResolverFunc(
func(region string, options EndpointResolverOptions) (aws.Endpoint, error) {
if len(e.Sig... |
tracker-service.test.js | 'use strict';
var expect = require('chai').expect;
var sinon = require('sinon');
var createAnnounceParams = require('./helpers/create-announce-params');
describe('TrackerService', function () {
var TrackerService = require('../release/tracker-service').default,
MemoryTorrentStore = require('../release/memory-tor... | () {
it('returns object', function () {
expect(output).to.be.an('object');
});
}
function returnsResponse(isCompact, noPeers) {
returnsObject();
describe('[peers]', function () {
if (isCompact) {
if (noPeers) {
it("return an empty buffer", function... | returnsObject |
step.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 ... | self.librustc(self.compiler(stage))]
}
Source::CheckTidy { stage } => {
vec![self.tool_tidy(stage)]
}
Source::CheckMirOpt { compiler} |
Source::CheckPrettyRPass { compiler } |
Source::CheckPrettyRFail { compiler... | }
Source::CheckCargoTest { stage } => {
vec![self.tool_cargotest(stage), |
switch_profile_port_model.py | # -*- coding: utf-8 -*-
"""
meraki_sdk
This file was automatically generated for meraki by APIMATIC v2.0 ( https://apimatic.io ).
"""
class SwitchProfilePortModel(object):
"""Implementation of the 'SwitchProfilePort' model.
TODO: type model description here.
Attributes:
... | profile = dictionary.get('profile')
port_id = dictionary.get('portId')
# Return an object of this model
return cls(profile,
port_id) |
# Extract variables from the dictionary
|
jni_generator.py | #!/usr/bin/env python
# Copyright (c) 2012 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Extracts native methods from a Java file and generates the JNI bindings.
If you change this, please run and update the tests."""... |
return template.substitute(values)
def GetKMethodArrayEntry(self, native):
template = Template("""\
{ "native${NAME}", ${JNI_SIGNATURE}, reinterpret_cast<void*>(${NAME}) },""")
values = {'NAME': native.name,
'JNI_SIGNATURE': JniParams.Signature(native.params,
... | values['FUNCTION_HEADER'] = function_header_template.substitute(values) |
acl.rs | // This file is generated by rust-protobuf 2.23.0. Do not edit
// @generated
// https://github.com/rust-lang/rust-clippy/issues/702
#![allow(unknown_lints)]
#![allow(clippy::all)]
#![allow(unused_attributes)]
#![cfg_attr(rustfmt, rustfmt::skip)]
#![allow(box_pointers)]
#![allow(dead_code)]
#![allow(missing_docs)]
#!... |
// Mutable pointer to the field.
// If field is not initialized, it is initialized with default value first.
pub fn mut_src(&mut self) -> &mut ::std::string::String {
if self.src.is_none() {
self.src.set_default();
}
self.src.as_mut().unwrap()
}
// Take field
... | {
self.src = ::protobuf::SingularField::some(v);
} |
instance_in_model.py | from models import User
| user = User(name='jack')
if user in User:
print 'Some one in table is named jack' | |
TitleBar.tsx | import React from 'react';
import { RaceDistance } from '../defy/models';
import styled from 'styled-components';
import { humanizeDuration } from '../defy/models'
interface Props {
distance: RaceDistance,
time: number,
}
const H2 = styled.h2`
width: 100%;
text-align: center;
`
const TitleBar: React.... | }
export default TitleBar | |
node_fs.ts | import file = require('./file');
import api_error = require('./api_error');
import file_system = require('./file_system');
import file_flag = require('./file_flag');
import buffer = require('./buffer');
import node_path = require('./node_path');
import node_fs_stats = require('./node_fs_stats');
var ApiError = api_erro... | * @param [Function(BrowserFS.ApiError)] callback
*/
public static fdatasync(fd: file.File, cb: Function = nopCb): void {
var newCb = wrapCb(cb, 1);
try {
checkFd(fd);
fd.datasync(newCb);
} catch (e) {
newCb(e);
}
}
/**
* Synchronous fdatasync.
* @param [BrowserFS.Fil... | * @param [BrowserFS.File] fd |
index.js | import React, { useRef, useState, useEffect } from 'react';
import { useDispatch } from "react-redux";
import { sendToServer } from "../../features/post/postSlice";
export default function CreatePost() {
const dispatch = useDispatch();
const title = useRef();
const text = useRef();
const button = use... |
const textChange = () => {
setSended("no");
if (title.current.value === "" || text.current.value === "") {
button.current.classList.remove("buttomReady");
}
else {
button.current.classList.add("buttomReady");
}
};
const sendPost = () => {
... |
}
}; |
cardMysqlViewModel.ts | import { ICardViewModel } from '@/data/models/cardViewModel'
import { RowDataPacket } from 'mysql2'
export interface ICardMysqlViewModel extends ICardViewModel, RowDataPacket {
cod: number
front: string
back: string
interval_time: number | } | |
0006_alter_blogpost_image.py | # Generated by Django 4.0.3 on 2022-03-06 12:36
from django.db import migrations, models
class Migration(migrations.Migration):
| dependencies = [
('BlogApp', '0005_alter_blogpost_image'),
]
operations = [
migrations.AlterField(
model_name='blogpost',
name='image',
field=models.ImageField(upload_to=''),
),
] | |
azure_privatecluster.go | // +build e2e
/*
Copyright 2020 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed ... |
// SetupExistingVNet creates a resource group and a VNet to be used by a workload cluster.
func SetupExistingVNet(ctx context.Context, vnetCidr string, cpSubnetCidrs, nodeSubnetCidrs map[string]string) {
By("creating Azure clients with the workload cluster's subscription")
settings, err := auth.GetSettingsFromEnvir... | {
var (
specName = "azure-private-cluster"
input AzurePrivateClusterSpecInput
publicClusterProxy framework.ClusterProxy
publicNamespace *corev1.Namespace
publicCancelWatches contex... |
actix.rs | #[cfg(feature = "actix")]
mod actix {
use std::env;
use actix_web::{test, App};
use matrix_sdk_appservice::*;
async fn appservice() -> Appservice {
env::set_var("RUST_LOG", "mockito=debug,matrix_sdk=debug,ruma=debug,actix_web=debug");
let _ = tracing_subscriber::fmt::try_init();
... | () {
let appservice = appservice().await;
let app = test::init_service(App::new().service(appservice.actix_service())).await;
let transactions = r#"{
"events": [
{
"content": {},
"type": "m.dummy"
}
... | test_no_access_token |
docker_compose.py | import importlib
import logging
from zygoat.constants import Phases, Projects
from zygoat.components import Component
from zygoat.config import yaml
from . import resources
log = logging.getLogger()
file_name = 'docker-compose.yml'
class DockerCompose(Component):
def _dump_config(self, data):
with open(... | (self):
config = self._load_config()
log.info('Removing backend and DB services from config')
del config['services'][Projects.BACKEND]
del config['services']['db']
log.info('Dumping updated docker-compose config')
self._dump_config(config)
@property
def install... | delete |
spider.py | # coding=utf-8
# Copyright 2020 The HuggingFace Datasets Authors and the current dataset script contributor.
#
# 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/lice... | (datasets.GeneratorBasedBuilder):
VERSION = datasets.Version("1.0.0")
BUILDER_CONFIGS = [
datasets.BuilderConfig(
name="spider",
version=VERSION,
description="Spider: A Large-Scale Human-Labeled Dataset for Text-to-SQL Tasks",
),
]
def _info(self):
... | Spider |
collapse.js | /*!
* Boosted v4.5.3 (https://boosted.orange.com)
* Copyright 2014-2020 The Boosted Authors
* Copyright 2014-2020 Orange
* Licensed under MIT (https://github.com/orange-opensource/orange-boosted-bootstrap/blob/master/LICENSE)
* This a fork of Bootstrap : Initial license below
* Bootstrap collapse.js v4.5.3 ... | (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
var $__default = /*#__PURE__*/_interopDefaultLegacy($);
var Util__default = /*#__PURE__*/_interopDefaultLegacy(Util);
function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i... | _interopDefaultLegacy |
storage-info.go | // +build ignore
//
// MinIO Object Storage (c) 2021 MinIO, 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 applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.... | // |
request.ts | interface RequestOptions {
body?: string | object;
headers?: {[name: string]: string};
}
interface MockResponse {
method: string;
url: string;
options: RequestOptions; | }
export async function request(
method: string,
url: string,
options: RequestOptions,
): Promise<string> {
return new Promise<string>((resolve) => {
setTimeout(() => {
resolve(JSON.stringify({method, url, options}));
});
});
} | |
common_tags.py | from django import template
from django.conf import settings
from django.utils.safestring import mark_safe
register = template.Library()
# settings value
@register.simple_tag
def settings_value(name):
| defaults = {
'SITE_HEADER': '<b>Map</b>Ground',
'SITE_TITLE': 'MapGround'
}
if name in defaults:
return mark_safe(getattr(settings, name, defaults[name]))
else:
return '' | |
metasrv_flight_tls.rs | // Copyright 2021 Datafuse Labs.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to ... | async fn test_tls_server_config_failure() -> anyhow::Result<()> {
let (_log_guards, ut_span) = init_meta_ut!();
let _ent = ut_span.enter();
let mut tc = MetaSrvTestContext::new(0);
tc.config.flight_tls_server_key = "../tests/data/certs/not_exist.key".to_owned();
tc.config.flight_tls_server_cert = ... | }
#[tokio::test(flavor = "multi_thread", worker_threads = 1)] |
azdo.py | import os
def | (outputlist, jsonObject):
"""
This function convert a dict to Azure DevOps pipelines variable
outputlist : dict { terraform_output : azure devpops variable}
jsonOject : the terraform output in Json format (terraform output -json)
"""
if(len(outputlist) > 0):
for k, v in outputlist.... | tfoutputtoAzdo |
nexus_model_fetch_result.go | // Code generated by go-swagger; DO NOT EDIT.
package models
// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command
import (
"context"
"strconv"
"github.com/go-openapi/errors"
"github.com/go-openapi/strfmt"
"github.com/go-openapi/swa... |
return nil
}
func (m *NexusModelFetchResult) contextValidateValue(ctx context.Context, formats strfmt.Registry) error {
for i := 0; i < len(m.Value); i++ {
if m.Value[i] != nil {
if err := m.Value[i].ContextValidate(ctx, formats); err != nil {
if ve, ok := err.(*errors.Validation); ok {
return ve.Va... | {
return errors.CompositeValidationError(res...)
} |
thorlabs_mpc320.py | """ Module for controlling Thorlabs motorized pollarization paddles """
import ctypes
from ctypes import Structure
import time
from pylabnet.utils.logging.logger import LogHandler
#from comtypes.typeinfo import SAFEARRAYABOUND
#enum FT_Status
FT_OK = ctypes.c_short(0x00)
FT_InvalidHandle = ctypes.c_short(0x0)
FT_Dev... | (self, paddle_num, pos, sleep_time):
#posinitial = self._polarizationdll.MPC_GetPosition(self.device, self.paddles[paddle_num])
move_result = self._polarizationdll.MPC_MoveToPosition(self.device, self.paddles[paddle_num], pos)
time.sleep(abs(sleep_time * pos / 170))
#posfinal = self._po... | move |
injection.packager.ts | // tslint:disable:no-namespace
// tslint:disable:max-classes-per-file
// tslint:disable:object-literal-sort-keys
declare var Json: any;
export namespace Packager {
export function join(...items: any[]): string | Uint8Array | Error {
if (items instanceof Array && items.length === 1 && items[0] instanceof ... | (source: string | Uint8Array): string[] | Uint8Array[] | Error {
if (!isPackage(source)) {
return new Error(`Source isn't a package of protocol data.`);
}
if (source instanceof ArrayBuffer) {
source = new Uint8Array(source);
}
if (source instanceof Uint8Ar... | split |
test_re.py | import sys
sys.path = ['.'] + sys.path
from test.test_support import verbose, run_unittest
import re
from sre import Scanner
import sys, os, traceback
# Misc tests from Tim Peters' re.doc
# WARNING: Don't change details in these tests if you don't know
# what you're doing. Some of these tests were carefuly modeled t... | (self):
self.assertEqual(re.split(":", ":a:b::c", 2), ['', 'a', 'b::c'])
self.assertEqual(re.split(':', 'a:b:c:d', 2), ['a', 'b', 'c:d'])
self.assertEqual(re.split("(:)", ":a:b::c", 2),
['', ':', 'a', ':', 'b::c'])
self.assertEqual(re.split("(:*)", ":a:b::c", 2),... | test_qualified_re_split |
testes_basicos.py | import unittest
def soma(param, param1):
return param + param1
class BasicoTests(unittest.TestCase):
def test_soma(self):
resultado = soma(1, 2)
self.assertEqual(3, resultado)
resultado = soma(3, 2)
self.assertEqual(5, resultado)
if __name__ == '__main__': | unittest.main() | |
additional_unattend_content.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 ... | """Additional XML formatted information that can be included in the
Unattend.xml file, which is used by Windows Setup. Contents are defined by
setting name, component name, and the pass in which the content is a
applied.
:param pass_name: The pass name. Currently, the only allowable value is
o... | |
UpdateTransitRouterVbrAttachmentAttributeRequest.py | # Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... | (self,ResourceOwnerId):
self.add_query_param('ResourceOwnerId',ResourceOwnerId)
def get_ClientToken(self):
return self.get_query_params().get('ClientToken')
def set_ClientToken(self,ClientToken):
self.add_query_param('ClientToken',ClientToken)
def get_TransitRouterAttachmentName(self):
return se... | set_ResourceOwnerId |
layer_norm.py | import torch
import torch.nn as nn
class LayerNorm(nn.Module):
|
class T5LayerNorm(nn.Module):
"""
Construct a layernorm module in the T5 style No bias and no subtraction of mean.
"""
def __init__(self, hidden_size, eps=1e-6):
super().__init__()
self.weight = nn.Parameter(torch.ones(hidden_size))
self.variance_epsilon = eps
def forwar... | """
Layer Normalization.
https://arxiv.org/abs/1607.06450
"""
def __init__(self, hidden_size, eps=1e-6):
super(LayerNorm, self).__init__()
self.eps = eps
self.gamma = nn.Parameter(torch.ones(hidden_size))
self.beta = nn.Parameter(torch.zeros(hidden_size))
def for... |
serializers.go | // Code generated by smithy-go-codegen DO NOT EDIT.
package marketplacemetering
import (
"bytes"
"context"
"fmt"
"github.com/aws/aws-sdk-go-v2/service/marketplacemetering/types"
smithy "github.com/aws/smithy-go"
"github.com/aws/smithy-go/encoding/httpbinding"
smithyjson "github.com/aws/smithy-go/encoding/json"... |
if request, err = request.SetStream(bytes.NewReader(jsonEncoder.Bytes())); err != nil {
return out, metadata, &smithy.SerializationError{Err: err}
}
if request.Request, err = httpBindingEncoder.Encode(request.Request); err != nil {
return out, metadata, &smithy.SerializationError{Err: err}
}
in.Request = re... | {
return out, metadata, &smithy.SerializationError{Err: err}
} |
test_code_style.py | """
@brief test log(time=150s)
"""
import os
import unittest | from pyquickhelper.pycode import check_pep8, ExtTestCase
class TestCodeStyle(ExtTestCase):
"""Test style."""
def test_style_src(self):
thi = os.path.abspath(os.path.dirname(__file__))
src_ = os.path.normpath(os.path.join(thi, "..", "..", "src"))
check_pep8(src_, fLOG=fLOG,
... | from pyquickhelper.loghelper import fLOG |
mgan_head.py | import torch.nn as nn
from ..registry import HEADS
from ..utils import ConvModule
from mmdetection.core import auto_fp16
@HEADS.register_module
class MGANHead(nn.Module):
def __init__(self,
num_convs=2,
roi_feat_size=7,
in_channels=512,
conv_ou... | padding=1,
conv_cfg=conv_cfg,
norm_cfg=norm_cfg))
logits_in_channel = self.conv_out_channels
self.conv_logits = nn.Conv2d(logits_in_channel, 1, 1)
self.relu = nn.ReLU(inplace=True)
self.debug_imgs = None
@auto_fp16()
de... | 3, |
index.ts | //================================================================
export * as billing from "./billing";
export * as internal from "./internal";
export * as payments from "./payments";
export * as virtual_accounts from "./virtual_accounts"; | /**
* @packageDocumentation
* @module api.functional
*/ | |
authorizeec2securitygroupingress_controller.go | /*
Copyright 2018 Jeff Nickoloff (jeff@allingeek.com).
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to... | if i == `authorizeec2securitygroupingress.ecc.aws.gotopple.com` {
ingressFinalizerPresent = true
}
}
// If there isn't a finalizer already on the security group, place it and create an empty list for ingress rules
if ingressFinalizerPresent != true {
ec2SecurityGroup.ObjectMeta.Finalizers = append(e... | ingressFinalizerPresent := false
for _, i := range ec2SecurityGroup.ObjectMeta.Finalizers { |
link.rs | use super::FileAction;
use crate::manifests::Manifest;
use crate::steps::Step;
use crate::{actions::Action, contexts::Contexts};
use serde::{Deserialize, Serialize};
use std::path::PathBuf;
use tracing::error;
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
pub struct FileLink {
pub from: Optio... |
}
| {
let yaml = r#"
- action: file.link
source: a
target: b
"#;
let mut actions: Vec<Actions> = serde_yaml::from_str(yaml).unwrap();
match actions.pop() {
Some(Actions::FileLink(action)) => {
assert_eq!("a", action.action.source());
... |
build.rs | extern crate bindgen;
extern crate cc;
extern crate num_cpus;
extern crate pkg_config;
extern crate regex;
use std::env;
use std::fs::{self, create_dir, symlink_metadata, File};
use std::io::{self, BufRead, BufReader, Write};
use std::path::PathBuf;
use std::process::Command;
use std::str;
use bindgen::callbacks::{In... | (statik: bool) {
let ffmpeg_ty = if statik { "static" } else { "dylib" };
for lib in LIBRARIES {
let feat_is_enabled = lib.feature_name().and_then(|f| env::var(&f).ok()).is_some();
if !lib.is_feature || feat_is_enabled {
println!("cargo:rustc-link-lib={}={}", ffmpeg_ty, lib.name);
... | link_to_libraries |
useTitle.ts | import { watch, unref } from 'vue';
import { useI18n } from '@/hooks/web/useI18n';
import { useTitle as usePageTitle } from '@vueuse/core';
import { useGlobSetting } from '@/hooks/setting';
import { useRouter } from 'vue-router';
import { REDIRECT_NAME } from '@/router/constant';
export function useTitle() {
const ... | const route = unref(currentRoute);
if (route.name === REDIRECT_NAME) {
return;
}
const tTitle = t(route?.meta?.title as string);
pageTitle.value = tTitle ? ` ${tTitle} - ${title} ` : `${title}`;
},
{ immediate: true }
);
} | () => { |
service_plan.go | package ccv3
import (
"code.cloudfoundry.org/cli/api/cloudcontroller/ccv3/constant"
"code.cloudfoundry.org/cli/api/cloudcontroller/ccv3/internal"
"code.cloudfoundry.org/cli/resources"
"code.cloudfoundry.org/jsonry"
)
// ServicePlan represents a Cloud Controller V3 Service Plan.
type ServicePlan struct {
// GUID ... |
var offeringsWithPlans []ServiceOfferingWithPlans
offeringGUIDLookup := make(map[string]int)
indexOfOffering := func(serviceOfferingGUID string) int {
if i, ok := offeringGUIDLookup[serviceOfferingGUID]; ok {
return i
}
i := len(offeringsWithPlans)
offeringGUIDLookup[serviceOfferingGUID] = i
offerin... | {
return nil, warnings, err
} |
template.test.ts | import { expect } from 'chai';
describe('Addition', () => {
it('1 + 1 should equal 2', () => { | });
}); | expect(1 + 1).to.equal(2); |
dd_dialog.rs | #[cfg(target_family = "unix")]
use std::cmp::min;
use tui::{
backend::Backend,
layout::{Alignment, Constraint, Direction, Layout, Rect},
terminal::Frame,
text::{Span, Spans, Text},
widgets::{Block, Borders, Paragraph, Wrap},
};
use crate::{
app::{App, KillSignal},
canvas::Painter,
};
const... | cfg(target_family = "unix")]
fn draw_dd_confirm_buttons<B: Backend>(
&self, f: &mut Frame<'_, B>, button_draw_loc: &Rect, app_state: &mut App,
) {
let signal_text;
#[cfg(target_os = "linux")]
{
signal_text = vec![
"0: Cancel",
"1: HUP",... | let (yes_button, no_button) = match app_state.delete_dialog_state.selected_signal {
KillSignal::KILL(_) => (
Span::styled("Yes", self.colours.currently_selected_text_style),
Span::raw("No"),
),
KillSignal::CANCEL => (
Span::raw(... |
persistent_volumes-gce.go | /*
Copyright 2017 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, ... |
// initializeGCETestSpec creates a PV, PVC, and ClientPod that will run until killed by test or clean up.
func initializeGCETestSpec(c clientset.Interface, ns string, pvConfig framework.PersistentVolumeConfig, pvcConfig framework.PersistentVolumeClaimConfig, isPrebound bool) (*v1.Pod, *v1.PersistentVolume, *v1.Persis... | {
gceCloud, err := gce.GetGCECloud()
framework.ExpectNoError(err)
isAttached, err := gceCloud.DiskIsAttached(diskName, nodeName)
framework.ExpectNoError(err)
return isAttached
} |
models.py | # -*- coding: utf-8 -*-
import datetime
from django.db.models import Count
import os
from django.db import models
from django.contrib.auth.models import User
from django.contrib.contenttypes.models import ContentType
from django.core.urlresolvers import reverse
from django.db.models.signals import post_save
from djang... |
def category_upload_path(instance, filename):
from utils import timestampbased_filename
category_slug = slugify(instance.title)
path = os.path.join(
'article_category',
category_slug,
timestampbased_filename(filename)
)
return path
def article_upload_path(instance, filen... |
from tags.models import Tag, TaggedItem
from comments.models import Comment, CommentAnswer |
main.js | /**
* Copyright (c) 2006
* Martin Czuchra, Nicolas Peters, Daniel Polak, Willi Tscheschner
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limit... | () {
/* When the blank image url is not set programatically to a local
* representation, a spacer gif on the site of ext is loaded from the
* internet. This causes problems when internet or the ext site are not
* available. */
Ext.BLANK_IMAGE_URL = ORYX.BASE_FILE_PATH + 'lib/ext-2.0.2/resources/images/default/s... | init |
TagForm.test.tsx | import { mount, ReactWrapper } from "enzyme";
import TagForm from "../index";
const resetMessage = jest.fn();
const resetForm = jest.fn();
const cancelForm = jest.fn();
const submitAction = jest.fn();
const initialProps = {
_id: "",
resetMessage,
serverError: "",
serverMessage: "",
resetForm,
cancelForm,
... | });
}); | expect(submitButton()).toHaveProp("disabled", false);
}); |
kubelet_common.go | // Unless explicitly stated otherwise all files in this repository are licensed
// under the Apache License Version 2.0.
// This product includes software developed at Datadog (https://www.datadoghq.com/).
// Copyright 2018 Datadog, Inc.
package kubelet
import (
"bufio"
"bytes"
"errors"
"fmt"
"strings"
)
var (
... | return ""
}
return fmt.Sprintf("%s%s", KubePodPrefix, uid)
}
// ParseMetricFromRaw parses a metric from raw prometheus text
func ParseMetricFromRaw(raw []byte, metric string) (string, error) {
bytesReader := bytes.NewReader(raw)
scanner := bufio.NewScanner(bytesReader)
for scanner.Scan() {
// skipping comment... | // PodUIDToEntityName returns a prefixed entity name from a pod UID
func PodUIDToEntityName(uid string) string {
if uid == "" { |
solution.go | package main
import (
"bufio"
"bytes"
"fmt"
"os"
)
func | () {
reader := bufio.NewReader(os.Stdin)
tc := readNum(reader)
var buf bytes.Buffer
for tc > 0 {
tc--
n := readNum(reader)
S := readString(reader)
E := make([][]int, n-1)
for i := 0; i < n-1; i++ {
E[i] = readNNums(reader, 2)
}
q := readNum(reader)
Q := make([][]int, q)
for i := 0; i <... | main |
TreeExample.shorthand.tsx | import * as React from 'react';
import { Tree } from '@fluentui/react-northstar';
const items = [
{
id: 'tree-item-1',
title: 'House Lannister',
items: [
{
id: 'tree-item-11',
title: 'Tywin',
items: [
{
id: 'tree-item-111',
title: 'Jaime',
... | title: 'Viserys',
},
{
id: 'tree-item-213',
title: 'Daenerys',
},
],
},
],
},
];
const TreeExampleShorthand = () => <Tree aria-label="default" items={items} />;
export default TreeExampleShorthand; | |
test_polynomial.py | import numpy as np
import pytest
from scipy import sparse
from scipy.sparse import random as sparse_random
from sklearn.utils._testing import assert_array_almost_equal
from numpy.testing import assert_allclose, assert_array_equal
from scipy.interpolate import BSpline
from sklearn.linear_model import LinearRegression
f... |
@pytest.mark.parametrize(
["deg", "include_bias", "interaction_only", "dtype"],
[
(1, True, False, int),
(2, True, False, int),
(2, True, False, np.float32),
(2, True, False, np.float64),
(3, False, False, np.float64),
(3, False, True, np.float64),
],
)
def... | rng = np.random.RandomState(0)
X = rng.randint(0, 2, (100, 2))
X_csc = sparse.csc_matrix(X)
est = PolynomialFeatures(
deg, include_bias=include_bias, interaction_only=interaction_only
)
Xt_csc = est.fit_transform(X_csc.astype(dtype))
Xt_dense = est.fit_transform(X.astype(dtype))
... |
setup.py | # -*- coding: utf-8 -*-
############################################################################
#
# Copyright © 2011, 2012, 2013, 2014, 2015 OnlineGroups.net and
# Contributors.
#
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the Z... | url='https://source.iopen.net/groupserver/gs.site.change.name/',
license='ZPL 2.1',
packages=find_packages(exclude=['ez_setup']),
namespace_packages=['gs', 'gs.site', 'gs.site.change', ],
include_package_data=True,
zip_safe=False,
install_requires=[
'setuptools',
'zope.formli... | ],
keywords='site ,groupserver, name, configure, admin',
author='Michael JasonSmith',
author_email='mpj17@onlinegroups.net', |
quick_sort.rs | fn quick_sort(list: &mut Vec<i32>, left: usize, right: usize) |
fn main() {
let my_vec = &mut vec![5,3,4,1,2];
let size = my_vec.len() - 1;
quick_sort(my_vec, 0, size);
println!("Hello world!! {:?}", my_vec);
}
| {
let (mut i, mut j) = (left, right);
let pivot = list[(left+right)/2];
while i <= j {
while list[i] < pivot {
i = i + 1;
}
while list[j] > pivot {
j = j - 1;
}
if i <= j {
... |
default_service_account.rs | use crate::authentication_manager::ServiceAccount;
use crate::prelude::*;
use hyper::body::Body;
use hyper::Method;
use std::str;
use std::sync::RwLock;
#[derive(Debug)]
pub struct DefaultServiceAccount {
token: RwLock<Token>,
}
impl DefaultServiceAccount {
const DEFAULT_PROJECT_ID_GCP_URI: &'static str =
... | .map_err(Error::ConnectionError)?;
match str::from_utf8(&body) {
Ok(s) => Ok(s.to_owned()),
Err(_) => Err(Error::ProjectIdNonUtf8),
}
}
fn get_token(&self, _scopes: &[&str]) -> Option<Token> {
Some(self.token.read().unwrap().clone())
}
async ... | .await |
mod.rs | /*
Copyright (C) 2018-2019 de4dot@gmail.com
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distr... | let result = if value.starts_with("0x") { u64::from_str_radix(&value[2..], 16) } else { value.trim().parse() };
match result {
Ok(value) => Ok(value),
Err(_) => Err(format!("Invalid number: {}", value)),
}
}
#[cfg(any(feature = "encoder", feature = "instr_info", feature = "gas", feature = "intel", feature = "ma... |
pub(crate) fn to_u64(value: &str) -> Result<u64, String> {
let value = value.trim(); |
socket.rs | use crate::{
sinks::util::tcp::{Encoding, TcpSinkConfig, TlsConfig},
topology::config::{DataType, SinkConfig, SinkContext, SinkDescription},
};
use serde::{Deserialize, Serialize};
#[derive(Deserialize, Serialize, Debug)]
// TODO: add back when serde-rs/serde#1358 is addressed
// #[serde(deny_unknown_fields)]
... | {
#[serde(flatten)]
pub mode: Mode,
}
#[derive(Deserialize, Serialize, Debug, Clone)]
#[serde(tag = "mode", rename_all = "snake_case")]
pub enum Mode {
Tcp(TcpSinkConfig),
}
inventory::submit! {
SinkDescription::new_without_default::<SocketSinkConfig>("socket")
}
impl SocketSinkConfig {
pub fn m... | SocketSinkConfig |
app.ts | import {Component} from "angular2/core";
import {SideMenu} from "./sideMenu.component.ts";
import {TopBar} from "./topBar.component.ts";
import {RouteConfig, RouterLink} from "angular2/router";
import {MainView} from "./mainView.component";
import {EventsHome} from "./../../events/components/eventsHome.component";
impo... | } | constructor(){
} |
0003_auto_20190709_2301.py | # Generated by Django 2.1.7 on 2019-07-09 23:01
from django.db import migrations, models
class Migration(migrations.Migration):
|
operations = [
migrations.AlterField(
model_name='timeseries',
name='begin_date',
field=models.DateField(blank=True, default=None, null=True),
),
migrations.AlterField(
model_name='timeseries',
name='end_date',
field=mo... | dependencies = [
('hydroserver_core', '0002_auto_20190709_2226'),
] |
map.js | !function(e){var r={};function t(n){if(r[n])return r[n].exports;var a=r[n]={i:n,l:!1,exports:{}};return e[n].call(a.exports,a,a.exports,t),a.l=!0,a.exports}t.m=e,t.c=r,t.d=function(e,r,n){t.o(e,r)||Object.defineProperty(e,r,{enumerable:!0,get:n})},t.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.d... | (){throw new Error("setTimeout has not been defined")}function o(){throw new Error("clearTimeout has not been defined")}function s(e){if(t===setTimeout)return setTimeout(e,0);if((t===i||!t)&&setTimeout)return t=setTimeout,setTimeout(e,0);try{return t(e,0)}catch(r){try{return t.call(null,e,0)}catch(r){return t.call(this... | i |
table.rs | use crate::commands::WholeStreamCommand;
use crate::format::TableView;
use crate::prelude::*;
use nu_errors::ShellError;
use nu_protocol::{Primitive, ReturnSuccess, Signature, SyntaxShape, UntaggedValue, Value};
use std::time::Instant;
const STREAM_PAGE_SIZE: usize = 1000;
const STREAM_TIMEOUT_CHECK_INTERVAL: usize = ... |
fn run(
&self,
args: CommandArgs,
registry: &CommandRegistry,
) -> Result<OutputStream, ShellError> {
table(args, registry)
}
}
fn table(args: CommandArgs, registry: &CommandRegistry) -> Result<OutputStream, ShellError> {
let mut args = args.evaluate_once(registry)?;
... | {
"View the contents of the pipeline as a table."
} |
types.go | package weave
import (
"fmt"
. "github.com/kocircuit/kocircuit/lang/circuit/model"
. "github.com/kocircuit/kocircuit/lang/go/eval"
. "github.com/kocircuit/kocircuit/lang/go/eval/symbol"
"github.com/kocircuit/kocircuit/lang/go/runtime"
)
func init() |
type WeaveStepCtx struct {
Origin *Span `ko:"name=origin"` // evaluation span (not weave span)
Pkg string `ko:"name=pkg"`
Func string `ko:"name=func"`
Step string `ko:"name=step"`
Logic string `ko:"name=logic"`
Source string `ko:"name=source"`
Ctx Symbol `ko:"name=ctx"` // user ctx object
}
func (... | {
RegisterEvalGateAt("", "WeaveFigure", new(WeaveFigure))
RegisterEvalGateAt("", "WeaveTransform", new(WeaveTransform))
RegisterEvalGateAt("", "WeaveFunc", new(WeaveFunc))
RegisterEvalGateAt("", "WeaveOperator", new(WeaveOperator))
} |
bad-assoc-ty.rs | type A = [u8; 4]::AssocTy;
//~^ ERROR missing angle brackets in associated item path
//~| ERROR ambiguous associated type
type B = [u8]::AssocTy;
//~^ ERROR missing angle brackets in associated item path
//~| ERROR ambiguous associated type
type C = (u8)::AssocTy;
//~^ ERROR missing angle brackets in associated item ... |
//~^ ERROR the placeholder `_` is not allowed within types on item signatures for functions
struct L<F>(F) where F: Fn() -> _;
//~^ ERROR the placeholder `_` is not allowed within types on item signatures for structs
struct M<F> where F: Fn() -> _ {
//~^ ERROR the placeholder `_` is not allowed within types on item s... | {} |
exclusions.py | # testing/exclusions.py
# Copyright (C) 2005-2019 the SQLAlchemy authors and contributors
# <see AUTHORS file>
#
# This module is part of SQLAlchemy and is released under
# the MIT License: http://www.opensource.org/licenses/mit-license.php
import contextlib
import operator
import re
from . import config
from .. imp... |
def only_on(dbs, reason=None):
return only_if(
OrPredicate(
[Predicate.as_predicate(db, reason) for db in util.to_list(dbs)]
)
)
def exclude(db, op, spec, reason=None):
return skip_if(SpecPredicate(db, op, spec), reason)
def against(config, *queries):
assert queries, "... | return skip_if(db, reason) |
python.py | import gevent
import structlog
from eth_utils import is_binary_address, is_hex, to_bytes, to_checksum_address
from gevent import Greenlet
import raiden.blockchain.events as blockchain_events
from raiden import waiting
from raiden.constants import (
GENESIS_BLOCK_NUMBER,
RED_EYES_PER_TOKEN_NETWORK_LIMIT,
SE... | (
self,
registry_address: PaymentNetworkID,
token_address: TokenAddress,
partner_address: Address,
retry_timeout: NetworkTimeout = DEFAULT_RETRY_TIMEOUT,
):
"""Close a channel opened with `partner_address` for the given
`token_address`.
Race condition... | channel_close |
asyncssh-server.py | #!/usr/bin/env python
"""
Example of running a prompt_toolkit application in an asyncssh server.
"""
import asyncio
import logging
import asyncssh
from pygments.lexers.html import HtmlLexer
from prompt_toolkit.completion import WordCompleter
from prompt_toolkit.contrib.ssh import PromptToolkitSSHServer, PromptToolkit... |
if __name__ == "__main__":
main()
| logging.basicConfig()
logging.getLogger().setLevel(logging.DEBUG)
loop = asyncio.get_event_loop()
loop.run_until_complete(
asyncssh.create_server(
lambda: PromptToolkitSSHServer(interact),
"",
port,
server_host_keys=["/etc/ssh/ssh_host_ecdsa_key"]... |
APIDef.py | {
###################################
# User data should be added below # | # e.g. "aidPage" is default function in W3 and do not need to specify here #
#"aidPage": {
# W3Const.w3ElementType: W3Const.w3TypeApi,
# W3Const.w3ApiName: "page",
# W3Const.w3ApiParams: [
# {
# W3Const.w3ApiDataType: W3Const.w3ApiDataTypeString,
# W3Const.w3Api... | ###################################
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.