code
stringlengths 0
29.6k
| language
stringclasses 9
values | AST_depth
int64 3
30
| alphanumeric_fraction
float64 0.2
0.86
| max_line_length
int64 13
399
| avg_line_length
float64 5.02
139
| num_lines
int64 7
299
| source
stringclasses 4
values |
---|---|---|---|---|---|---|---|
#ifndef __ASMS390_AUXVEC_H
#define __ASMS390_AUXVEC_H
#define AT_SYSINFO_EHDR 33
#define AT_VECTOR_SIZE_ARCH 1 /* entries in ARCH_DLINFO */
#endif
|
c
| 3 | 0.715232 | 58 | 17.875 | 8 |
starcoderdata
|
def merge_results(self,xml_files):
for file_name in xml_files:
tree = ET.parse(file_name)
root = tree.getroot()
if root.tag == 'testsuites':
for testsuite in root.getchildren():
self.process_testsuite(testsuite)
elif root.tag == 'testsuite':
self.process_testsuite(root)
else:
# unrecognized root note
pass
# write the new xml file out
new_root = ET.Element('testsuites')
# new_root.attrib['failures'] = '%s' % failures
# new_root.attrib['tests'] = '%s' % tests
# new_root.attrib['errors'] = '%s' % errors
# new_root.attrib['time'] = '%s' % time
for testsuite in self.testsuites:
new_root.append(testsuite)
new_tree = ET.ElementTree(new_root)
ET.dump(new_tree)
|
python
| 12 | 0.52514 | 54 | 36.333333 | 24 |
inline
|
import pMemoize from 'p-memoize'
import camelcaseKeys from 'camelcase-keys'
import format from 'date-fns/format'
import Cookies from 'js-cookie'
import browser from 'webextension-polyfill'
import { ACTION_FETCH_FACEIT_API } from '../../shared/constants'
import { mapTotalStatsMemoized, mapAverageStatsMemoized } from './stats'
export const CACHE_TIME = 600000
async function fetchApi(path) {
if (typeof path !== 'string') {
throw new TypeError(`Expected \`path\` to be a string, got ${typeof path}`)
}
try {
const token = Cookies.get('t') || localStorage.getItem('token')
const options = { headers: {} }
if (token) {
options.headers.Authorization = `Bearer ${token}`
}
const response = await browser.runtime.sendMessage({
action: ACTION_FETCH_FACEIT_API,
path,
options
})
const {
result, // Status for old API(?)
code, // Status for new API(?)
payload
} = response
if (
(result && result.toUpperCase() !== 'OK') ||
(code && code.toUpperCase() !== 'OPERATION-OK')
) {
throw new Error(response)
}
return camelcaseKeys(payload || response, { deep: true })
} catch (err) {
console.error(err)
return null
}
}
const fetchApiMemoized = pMemoize(fetchApi, {
maxAge: CACHE_TIME
})
export const getUser = userId => fetchApiMemoized(`/users/v1/users/${userId}`)
export const getPlayer = nickname =>
fetchApiMemoized(`/users/v1/nicknames/${nickname}`)
export const getPlayerMatches = (userId, game, size = 20) =>
fetchApiMemoized(
`/stats/v1/stats/time/users/${userId}/games/${game}?size=${size}`
)
export const getPlayerStats = async (userId, game, size = 20) => {
if (game !== 'csgo') {
return false
}
let totalStats = await fetchApiMemoized(
`/stats/v1/stats/users/${userId}/games/${game}`
)
if (!totalStats || Object.keys(totalStats).length === 0) {
return null
}
totalStats = mapTotalStatsMemoized(totalStats.lifetime)
let averageStats = await fetchApiMemoized(
`/stats/v1/stats/time/users/${userId}/games/${game}?size=${size}`
)
if (!averageStats || !Array.isArray(averageStats)) {
return null
}
averageStats = averageStats.filter(stats => stats.gameMode.includes('5v5'))
if (averageStats.length <= 1) {
return null
}
averageStats = mapAverageStatsMemoized(averageStats)
return {
...totalStats,
...averageStats
}
}
export const getQuickMatch = matchId =>
fetchApiMemoized(`/core/v1/matches/${matchId}?withStats=true`)
export const getMatch = matchId =>
fetchApiMemoized(`/match/v2/match/${matchId}`)
export const getTeam = teamId => fetchApiMemoized(`/teams/v1/teams/${teamId}`)
export const getSelf = () => fetchApiMemoized('/users/v1/sessions/me')
export const getHubQueue = async id =>
(await fetchApi(`/queue/v1/queue/hub/${id}`))[0]
export const getPlayerHistory = async (userId, page = 0) => {
const size = 50
const offset = 0
const from = encodeURIComponent(`1970-01-01T01:00:00+0000`)
const to = encodeURIComponent(
format(new Date(), `yyyy-MM-dd'T'HH:mm:ss'+0000'`)
)
return fetchApiMemoized(
`/match-history/v5/players/${userId}/history/?from=${from}&to=${to}&page=${page}&size=${size}&offset=${offset}`
)
}
export const getMatchmakingQueue = queueId =>
fetchApiMemoized(`/queue/v1/queue/matchmaking/${queueId}`)
|
javascript
| 14 | 0.665598 | 115 | 25.384615 | 130 |
starcoderdata
|
# Copyright 2020 NREL
# 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.
"""
converts simple example files into rst files, to then be converted to html for documentation.
commandline args:
arg[0]: Name of this Python script
arg[1]: Name of Python script to convert
arg[2]: Name of output rst file
arg[3]: Number of headerlines in input python file
"""
import sys
# get command line arguments
inputs = sys.argv
# default values
infile = "dummy.py"
outfile = "dummy.rst"
headerlines = 13
# assign input values
if len(inputs) > 1:
infile = inputs[1]
outfile = infile.split(".")[0] + ".rst"
if len(inputs) > 2:
outfile = inputs[2]
if len(inputs) > 3:
headerlines = int(inputs[3])
# read file contents as a list
f = open(infile, "r")
fileContents = f.readlines()
# remove copyright/headerlines
for ii, x in enumerate(fileContents[: headerlines + 1]):
fileContents.remove(x)
# block of text to add to signify codeblocks for rst
codeblock = "\n.. code-block:: python3 \n\n"
# flag to determine indentation
codesec = False
commentsec = False
# make title and section header
title = infile.split("/")[-1]
fileContents.insert(0, title + " \n")
fileContents.insert(1, "".join(["="] * len(title) + [" \n\n"]))
# append 'EOF' to filecontents to signify end of list
fileContents += ["EOF"]
flag = None
ii = 2
while flag is not "EOF":
# detect beginning/end of docstring
if '"""' in fileContents[ii]:
fileContents[ii] = "\n"
if commentsec == False:
commentsec = True
else:
commentsec = False
# prepend lines in docstring with hash
if commentsec:
fileContents[ii] = "# " + fileContents[ii]
# lines of code do NOT start with a hash or newline
if fileContents[ii][0] not in [
"#",
"\n",
]:
commentsec = False
if not codesec:
fileContents.insert(ii, codeblock)
codesec = True
else:
fileContents[ii] = "\t" + fileContents[ii]
codesec = True
# add new line to end of code section
elif codesec and fileContents[ii][0] in ["#", "\n"]:
# fileContents.insert(ii, '\n')
codesec = False
# comment lines DO start with a hash
else:
fileContents[ii] = fileContents[ii][2:]
codesec = False
ii += 1
flag = fileContents[ii]
# trim off 'EOF'
dump = fileContents.pop(-1)
# write to rst file
with open(outfile, "w") as filehandle:
for item in fileContents:
filehandle.write(item)
|
python
| 13 | 0.651786 | 93 | 26.243243 | 111 |
starcoderdata
|
def get(self, request, author_id, post_id):
""" GET - Get a list of authors who like {post_id} """
logger.info(f"GET /author/{author_id}/posts/{post_id}/likes API endpoint invoked")
author = get_object_or_404(Author, id=author_id)
post = get_object_or_404(LocalPost, id=post_id, author=author)
try:
post_likes = post.likes.all()
items = []
for like in post_likes:
like_author_json = like.author.as_json()
like = {
"@context": "https://www.w3.org/ns/activitystreams",
"summary": f"{like_author_json['displayName']} Likes your post",
"type": "Like",
"author": like_author_json,
"object": f"{API_BASE}/author/{post.author.id}/posts/{post.id}"
}
items.append(like)
response = {
"type": "likes",
"items": items
}
except Exception as e:
logger.error(e, exc_info=True)
return HttpResponseServerError()
return JsonResponse(response)
|
python
| 15 | 0.498288 | 90 | 33.382353 | 34 |
inline
|
using System;
namespace LightRail.ServiceBus.Config
{
public class ServiceBusFactory
{
public static readonly ServiceBusFactory Factory = new ServiceBusFactory();
private ServiceBusFactory() { }
public IBusControl Create cfg)
where TConfig : BaseServiceBusConfig, new()
{
var _config = new TConfig();
cfg(_config);
var bus = _config.CreateServiceBus();
return bus;
}
}
}
|
c#
| 13 | 0.577068 | 83 | 24.6 | 20 |
starcoderdata
|
import classnames from 'classnames';
import { h } from 'preact';
import {
Bar,
Container,
Section,
} from 'react-simple-resizer';
import { composeQueries } from '../graphql/';
import { dictionaryItem } from '../graphql/queries.graphql';
import {
Error,
Loading,
} from '../ui-messages/';
import { QA } from '../tests/constants';
import Thesaurus from '../thesaurus/Thesaurus';
import DeleteItem from './DeleteItem';
import Phrases from './Phrases';
import S from './DictionaryEditor.sass';
import Title from './Title';
export default composeQueries({
dictionaryItem: [ dictionaryItem, { id: 'itemId' }],
})(({
closeEditor,
dictionaryItem: {
dictionaryItem: item,
error: itemError,
loading: itemLoading,
},
}) =>
<Container className={ classnames( S.className, QA.DICT_ITEM_EDITOR ) }>
<Section defaultSize={ 100 }>
<Thesaurus className={ S.thesaurus } />
<Bar className={ S.separator } />
<Section className={ S.editor } defaultSize={ 300 } minSize="25%">
<div className={ S.header }>
<Title className={ S.title } item={ item || {} } />
<div className={ S.close }>
<button
children="✖️ close"
className={ QA.DICT_ITEM_EDITOR_CLOSE }
onClick={ closeEditor }
/>
<div className={ S.main }>
{ itemError
? <Error message={ itemError } />
: item
? <Phrases
itemId={ item.id }
phrases={ item.phrases }
/>
: null
}
{ itemLoading
&& <Loading />
}
<DeleteItem
className={ S.deleteItem }
itemId={ item.id }
onDelete={ closeEditor }
/>
);
|
javascript
| 12 | 0.4327 | 76 | 32.638889 | 72 |
starcoderdata
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
PyDashing CLI Handler:
---------------------
"""
import sys
import os
import argparse
class CliHandler(object):
"""CLI Handler."""
SUCCESS = 0
ERROR = 1
def __init__(self):
"""Initialize CLI Handler."""
if len(sys.argv) <= 1:
print "%s requires arguments. Use -h to see usage help." % \
sys.argv[0]
sys.exit()
self.namespace = self.parse_arguments()
self.validate_arguments()
def parse_arguments(self):
"""Parse CLI arguments."""
parser = argparse.ArgumentParser(
prog="PyDashing",
description=self.show_help(),
formatter_class=argparse.RawTextHelpFormatter)
parser.add_argument("--config",
dest="config_file",
required=True,
help="Path to configuration file")
parser.add_argument("--render-path",
dest="render_path",
required=True,
help="Path to stage the rendered templates")
namespace = parser.parse_args()
return namespace
@staticmethod
def show_help():
"""Display Help for CLI."""
msg = "PyDashing : A simple python utility to generate nice" + "\n" \
+ "dashboards" + "\n" \
+ "" + "\n" \
+ "Example Usage: ./pydashing.py --config ../config/simple.yaml" \
+ "\n"
return msg
def validate_arguments(self):
"""Validate that arguments passed are valid."""
if not os.path.exists(self.namespace.config_file):
print "%s file does not exists." % self.namespace.config_file
return CliHandler.ERROR
if not os.path.exists(self.namespace.render_path) or \
not os.path.isdir(self.namespace.render_path):
print "%s is an invalid render path" % self.namespace.render_path
return CliHandler.ERROR
return CliHandler.SUCCESS
|
python
| 17 | 0.530029 | 78 | 27.739726 | 73 |
starcoderdata
|
package steps
import (
"github.com/AlecAivazis/survey/v2"
"github.com/Samasource/jen/src/internal/evaluation"
"github.com/Samasource/jen/src/internal/exec"
logging "github.com/Samasource/jen/src/internal/logging"
)
// Confirm represents a conditional step that executes its child executable only if
// user answers Yes when prompted for given message
type Confirm struct {
Message string
Then exec.Executables
}
func (c Confirm) String() string {
return "confirm"
}
// Execute executes a child action only if user answers Yes when prompted for given message
func (c Confirm) Execute(context exec.Context) error {
message, err := evaluation.EvalTemplate(context, c.Message)
if err != nil {
return err
}
prompt := &survey.Confirm{
Message: message,
Default: false,
}
value := false
if err := survey.AskOne(prompt, &value); err != nil {
return err
}
if !value {
logging.Log("Skipping sub-steps because user cancelled")
return nil
}
logging.Log("Executing sub-steps because user confirmed")
return c.Then.Execute(context)
}
|
go
| 10 | 0.741348 | 91 | 25.142857 | 42 |
starcoderdata
|
import React from "react";
import styled from 'styled-components';
import Background from '../../../data/images/VigilImage.png'
const AboutMe = styled.div`
width: 50%;
float: left;
height: 100vh;
background-image: linear-gradient(to bottom, rgba(245, 246, 252, 0.52), rgba(117, 19, 93, 0.73)),
url(${Background});
background-size: cover;
`
const AboutMeText = styled.div`
margin-top: 20%;
width: 100%;
text-align: center;
color: black;
`
const ImageSide = () => (
there, I'm Joey.
and mechatronics engineer based in Colorado.
looking for opportunites to expand my expertise.
)
export default ImageSide
|
javascript
| 9 | 0.645939 | 101 | 24.419355 | 31 |
starcoderdata
|
[InlineData("TestInputFiles/HighDpiHappyPathInput.txt", false, true, "TestExpectedFiles/HighDpiHappyPathExpected.txt")] // Happy Path
[InlineData("TestInputFiles/HighDpiNoUpdateInput.txt", true, false, "TestExpectedFiles/HighDpiEmptyExpected.txt")] // Do Nothing Scenario
[InlineData("TestInputFiles/HighDpiEmptyInput.txt", false, false, "TestExpectedFiles/HighDpiEmptyExpected.txt")] // No Program.cs
[InlineData("TestInputFiles/HighDpiEmptyInput.txt", true, false, "TestExpectedFiles/HighDpiEmptyExpected.txt")] // Negative Test
[InlineData("TestInputFiles/HighDpiNoNewLineAddedInput.txt", false, true, "TestExpectedFiles/HighDpiNoNewLineAddedExpected.txt")] // No new line added since existing line does not exist
[Theory]
public async Task UpdateDpiSettingTests(string inputFilePath, bool isDpiSettingSetInProgramFile, bool expectedOutputFile, string expectedFilePath)
{
// Arrange
using var mock = AutoMock.GetLoose();
var random = new Random();
var logger = mock.Mock<ILogger<WinformsDpiSettingUpdater>>();
var updater = new WinformsDpiSettingUpdater(logger.Object);
var projectFile = mock.Mock<IProjectFile>();
projectFile.Setup(f => f.IsSdk).Returns(true);
var project = mock.Mock<IProject>();
project.Setup(p => p.GetFile()).Returns(projectFile.Object);
project.Setup(p => p.FileInfo).Returns(new FileInfo("./test"));
var context = mock.Mock<IUpgradeContext>();
context.Setup(c => c.Projects).Returns(new[] { project.Object });
var programFilePath = Path.Combine(Path.GetTempPath(), string.Concat("TestFile", random.Next(), ".txt"));
var programFileContent = File.ReadAllLines(inputFilePath);
var expectedFileContent = File.ReadAllLines(expectedFilePath);
// Act
await updater.UpdateHighDPISetting(project.Object, programFileContent, isDpiSettingSetInProgramFile, programFilePath);
// Assert
Assert.Equal(File.Exists(programFilePath), expectedOutputFile);
if (File.Exists(programFilePath))
{
Assert.Equal(File.ReadAllLines(programFilePath), expectedFileContent);
File.Delete(programFilePath);
}
}
|
c#
| 16 | 0.674536 | 193 | 58.325 | 40 |
inline
|
<?php
namespace Foobooks\Http\Controllers;
use Illuminate\Http\Request;
use Foobooks\Http\Controllers\Controller;
class BookController extends Controller {
/**
* Responds to GET /books
*/
public function index() {
return view('books.index');
}
public function create() {
// $view = '<form method="POST" action="/books">';
// $view .= csrf_field();
// $view .= ' <input type="text" name="title"/>
// $view .= '<input type="submit"/>';
// $view .= '
// return $view;
return view('books.create');
}
public function store(Request $request) {
#dd(Request::all());
$this->validate($request, [
'title' => 'required|min:3'
]);
$title = $request->input('title');
return 'Storing a book ' .$title;
}
public function show($title) {
return view('books.show')->with('title', $title);
}
public function edit($title) {
return view('books.edit')->with('title', $title);
}
public function update($book) {
return 'Updating book ' .$book;
}
public function delete($book) {
return 'Deleteing book ' .$book;
}
}
|
php
| 12 | 0.595156 | 73 | 20.407407 | 54 |
starcoderdata
|
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Dtr_summary_Model extends CI_Model {
function __construct() {
parent::__construct();
}
public function proc_dtr_summary($vAction, $aData) {
return json_encode(array("action" => $vAction));
}
}
?>
|
php
| 12 | 0.538028 | 71 | 22.733333 | 15 |
starcoderdata
|
func (c *Conn) readAll(ctx context.Context) ([]byte, error) {
t, r, err := c.Conn.Reader(ctx)
if err != nil {
return nil, err
}
if t == websocket.MessageBinary {
// Probably a zlib payload
z, err := zlib.NewReader(r)
if err != nil {
c.Conn.CloseRead(ctx)
return nil,
errors.Wrap(err, "Failed to create a zlib reader")
}
defer z.Close()
r = z
}
b, err := ioutil.ReadAll(r)
if err != nil {
c.Conn.CloseRead(ctx)
return nil, err
}
return b, nil
}
|
go
| 12 | 0.607438 | 61 | 16.962963 | 27 |
inline
|
# Modified from https://github.com/facebookresearch/deit/blob/c890ceb9303468cf47553da8764d7febabd9df68/cait_models.py
import torch
import torch.nn as nn
from mmcv.cnn.bricks.transformer import FFN
from mmcv.cnn.bricks.drop import build_dropout
from mmcv.cnn import build_norm_layer
from mmcv.runner import BaseModule, ModuleList
from mmcv.cnn.bricks.transformer import MultiheadAttention
from ..builder import BACKBONES
from .vit import VisionTransformer
class Attention_talking_head(BaseModule):
# taken from https://github.com/facebookresearch/deit/blob/main/cait_models.py
# with slight modifications (https://arxiv.org/pdf/2003.02436v1.pdf)
def __init__(self, dim, num_heads=8, qkv_bias=False, qk_scale=None, attn_drop=0., proj_drop=0.):
super().__init__()
self.num_heads = num_heads
head_dim = dim // num_heads
self.scale = qk_scale or head_dim ** -0.5
self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias)
self.attn_drop = nn.Dropout(attn_drop)
self.proj = nn.Linear(dim, dim)
self.proj_l = nn.Linear(num_heads, num_heads)
self.proj_w = nn.Linear(num_heads, num_heads)
self.proj_drop = nn.Dropout(proj_drop)
def forward(self, x):
B, N, C = x.shape
qkv = self.qkv(x).reshape(B, N, 3, self.num_heads, C // self.num_heads).permute(2, 0, 3, 1, 4).contiguous() # (3,B,n_head,n_q,n_head_dim)
q, k, v = qkv[0] * self.scale , qkv[1], qkv[2]
attn = (q @ k.transpose(-2, -1)) # (B,n_head,n_q,n_k)
# talking head: use linear combination of different heads (B,n_q,n_k,n_head) → (B,n_q,n_k,n_head)
attn = self.proj_l(attn.permute(0,2,3,1).contiguous()).permute(0,3,1,2).contiguous()
attn = attn.softmax(dim=-1) # convert from logits to probs
# talking head: use linear in head-dimension again
attn = self.proj_w(attn.permute(0,2,3,1).contiguous()).permute(0,3,1,2).contiguous()
attn = self.attn_drop(attn)
x = (attn @ v).transpose(1, 2).reshape(B, N, C)
x = self.proj(x)
x = self.proj_drop(x)
return x
class LayerScale_Block(BaseModule):
"""
In LayerScale, each embed_dim in the output of the residual block has a weight, which is
given by a learnable vector (namely gamma_1 and gamma_2).
"""
def __init__(self,
embed_dims,
num_heads,
init_scale=1e-4,
qkv_bias=False,
qk_scale=None,
drop=0.,
attn_drop_rate=0.,
drop_path=0.,
mlp_ratio=4.,
num_fcs=2,
norm_cfg=dict(type='LN'),
act_cfg=dict(type='GELU'),
batch_first=True):
super(LayerScale_Block, self).__init__()
self.norm1_name, norm1 = build_norm_layer(
norm_cfg, embed_dims, postfix=1)
self.add_module(self.norm1_name, norm1)
self.attn = Attention_talking_head(
embed_dims,
num_heads=num_heads,
attn_drop=attn_drop_rate,
proj_drop=drop,
qkv_bias=qkv_bias)
self.norm2_name, norm2 = build_norm_layer(
norm_cfg, embed_dims, postfix=2)
self.add_module(self.norm2_name, norm2)
# Note: default:drop_prob = 0.0 in cait and 0.1 in mmcv
self.dropout_layer = build_dropout(
dict(type='DropPath', drop_prob=drop_path)) if drop_path > 0. else nn.Identity()
feedforward_channels = int(embed_dims * mlp_ratio)
self.mlp = FFN(
embed_dims = embed_dims,
feedforward_channels = feedforward_channels,
num_fcs = num_fcs,
ffn_drop=drop,
dropout_layer=None,
act_cfg=act_cfg,
)
# LayerScale:
self.gamma_1 = nn.Parameter(init_scale * torch.ones((embed_dims)),requires_grad=True) # for atten
self.gamma_2 = nn.Parameter(init_scale * torch.ones((embed_dims)),requires_grad=True) # for ffn
@property
def norm1(self):
return getattr(self, self.norm1_name)
@property
def norm2(self):
return getattr(self, self.norm2_name)
def forward(self, x):
x = x + self.dropout_layer(self.gamma_1 * self.attn(self.norm1(x)))
x = x + self.dropout_layer(self.gamma_2 * self.mlp(self.norm2(x)))
return x
@BACKBONES.register_module()
class LayerScaleTransformer(VisionTransformer):
def __init__(self,
num_layers=12,
drop_path_rate=0.,
embed_dims=768,
num_heads=12,
mlp_ratio=4,
qkv_bias=False,
qk_scale=None,
drop_rate=0.,
attn_drop_rate=0.,
norm_cfg=dict(type='LN'),
act_cfg=dict(type='GELU'),
init_scale=1e-4,
**kwargs):
super(LayerScaleTransformer, self).__init__(
num_layers=num_layers,
drop_path_rate=drop_path_rate,
embed_dims=embed_dims,
num_heads=num_heads,
mlp_ratio=mlp_ratio,
qkv_bias=qkv_bias,
drop_rate=drop_rate,
attn_drop_rate=attn_drop_rate,
norm_cfg=norm_cfg,
act_cfg=act_cfg,
**kwargs)
dpr = [drop_path_rate for i in range(num_layers)]
self.layers = ModuleList()
for i in range(num_layers):
self.layers.append(
LayerScale_Block(
embed_dims=embed_dims,
num_heads=num_heads,
mlp_ratio=mlp_ratio,
qkv_bias=qkv_bias,
qk_scale=qk_scale,
drop=drop_rate,
attn_drop_rate=attn_drop_rate,
drop_path=dpr[i],
norm_cfg=norm_cfg,
act_cfg=act_cfg,
init_scale=init_scale))
|
python
| 17 | 0.516887 | 146 | 34.095506 | 178 |
starcoderdata
|
package main
import (
"strings"
"github.com/dynport/gocloud/digitalocean/v2/digitalocean"
)
type dropletCreate struct {
Name string `cli:"opt --name required"` // required
Region string `cli:"opt --region required"` // required
Size string `cli:"opt --size required"` // required
Image string `cli:"opt --image required"` // required
SshKeys string `cli:"opt --ssh-keys"`
Backups bool `cli:"opt --backups"`
IPv6 bool `cli:"opt --ipv6"`
PrivateNetworking bool `cli:"opt --private-networking"`
}
func (r *dropletCreate) Run() error {
cl, e := client()
if e != nil {
return e
}
a := digitalocean.CreateDroplet{
Name: r.Name,
Region: r.Region,
Size: r.Size,
Image: r.Image,
Backups: r.Backups,
IPv6: r.IPv6,
PrivateNetworking: r.PrivateNetworking,
}
if r.SshKeys != "" {
a.SshKeys = strings.Split(r.SshKeys, ",")
}
rsp, e := a.Execute(cl)
if e != nil {
return e
}
printDroplet(rsp.Droplet)
return nil
}
|
go
| 10 | 0.574413 | 67 | 24.533333 | 45 |
starcoderdata
|
using ImageBed.Common;
using ImageBed.Data.Entity;
using Microsoft.EntityFrameworkCore;
using System.Linq.Expressions;
namespace ImageBed.Data.Access
{
public class SqlImageData
{
public OurDbContext? _context { get; set; }
public SqlImageData(OurDbContext context)
{
_context = context;
}
///
/// 获取数据库中符合条件的所有图片信息
///
/// <param name="predicate">
///
public IEnumerable GetAll(Func<ImageEntity, bool> predicate)
{
if ((_context != null) && (_context.Images != null))
{
return _context.Images.Where(predicate);
}
return Array.Empty
}
///
/// 获取符合条件的第一张图片的信息
///
/// <param name="predicate">
///
public ImageEntity? GetFirst(Expression<Func<ImageEntity, bool>> predicate)
{
if ((_context != null) && (_context.Images != null))
{
return _context.Images.FirstOrDefault(predicate);
}
return null;
}
///
/// 获取符合条件的第一张图片的信息
///
/// <param name="predicate">
///
public async Task GetFirstAsync(Expression<Func<ImageEntity, bool>> predicate)
{
if ((_context != null) && (_context.Images != null))
{
return await _context.Images.FirstOrDefaultAsync(predicate);
}
return null;
}
///
/// 添加图片信息至数据库
///
/// <param name="image">
///
public async Task AddAsync(ImageEntity image)
{
if ((_context != null) && (_context.Images != null) && (image != null))
{
try
{
await _context.Images.AddAsync(image);
if(await _context.SaveChangesAsync() > 0)
{
return true;
}
}
catch (Exception ex)
{
GlobalValues.Logger.Error($"Add {image.Name} to database failed, {ex.Message}");
}
}
return false;
}
///
/// 添加多张图片至数据库
///
/// <param name="images">
/// 否则返回false
public async Task AddRangeAsync(IEnumerable images)
{
if ((_context != null) && (_context.Images != null) && (images != null))
{
try
{
await _context.Images.AddRangeAsync(images);
if(await _context.SaveChangesAsync() == images.Count())
{
return true;
}
}
catch (Exception ex)
{
GlobalValues.Logger.Error($"Add pictures to database failed, {ex.Message}");
}
}
return false;
}
///
/// 更新图片信息
///
/// <param name="image">
/// 否则返回false
public async Task UpdateAsync(ImageEntity image)
{
if ((_context != null) && (_context.Images != null))
{
try
{
_context.Images.Update(image);
if(await _context.SaveChangesAsync() > 0)
{
return true;
}
}
catch (Exception ex)
{
GlobalValues.Logger.Error($"Update {image.Name} failed, {ex.Message}");
}
}
return false;
}
///
/// 移除图片(和磁盘文件)
///
/// <param name="id">
/// 否则返回false
public async Task RemoveAsync(string id)
{
ImageEntity? image = null;
if ((_context != null) && (_context.Images != null) && ((image = await GetFirstAsync(i => i.Id == id)) != null))
{
try
{
_context.Images.Remove(image);
if (await _context.SaveChangesAsync() > 0)
{
// 删除磁盘上的文件
File.Delete($"{GlobalValues.AppSetting?.Data.Image.RootPath}/{image.Name}");
File.Delete($"{GlobalValues.AppSetting?.Data.Image.RootPath}/thumbnails_{image.Name}");
return true;
}
}
catch (Exception ex)
{
GlobalValues.Logger.Error($"Remove {image.Name} failed, {ex.Message}");
}
}
return false;
}
///
/// 移除图片信息(和磁盘文件)
///
/// <param name="image">
/// 否则返回false
public async Task RemoveAsync(ImageEntity image)
{
if ((_context != null) && (_context.Images != null))
{
try
{
_context.Images.Remove(image);
if(await _context.SaveChangesAsync() > 0)
{
File.Delete($"{GlobalValues.AppSetting?.Data.Image.RootPath}/{image.Name}");
File.Delete($"{GlobalValues.AppSetting?.Data.Image.RootPath}/thumbnails_{image.Name}");
return true;
}
}
catch (Exception ex)
{
GlobalValues.Logger.Error($"Remove {image.Name} failed, {ex.Message}");
}
}
return false;
}
///
/// 移除图片信息
///
/// <param name="image">
/// 否则返回false
public bool Remove(ImageEntity image)
{
if ((_context != null) && (_context.Images != null))
{
try
{
_context.Images.Remove(image);
if(_context.SaveChanges() > 0)
{
File.Delete($"{GlobalValues.AppSetting?.Data.Image.RootPath}/{image.Name}");
File.Delete($"{GlobalValues.AppSetting?.Data.Image.RootPath}/thumbnails_{image.Name}");
return true;
}
}
catch (Exception ex)
{
GlobalValues.Logger.Error($"Remove {image.Name} failed, {ex.Message}");
}
}
return false;
}
///
/// 移除多个图片信息
///
/// <param name="images">
/// 否则返回false
public async Task RemoveRangeAsync(IEnumerable images)
{
if ((_context != null) && (_context.Images != null))
{
try
{
_context.Images.RemoveRange(images);
if(await _context.SaveChangesAsync() == images.Count())
{
foreach (var image in images)
{
File.Delete($"{GlobalValues.AppSetting.Data.Image.RootPath}/{image.Name}");
File.Delete($"{GlobalValues.AppSetting.Data.Image.RootPath}/thumbnails_{image.Name}");
}
return true;
}
}
catch (Exception ex)
{
GlobalValues.Logger.Error($"Remove images failed, {ex.Message}");
}
}
return false;
}
}
}
|
c#
| 25 | 0.435619 | 124 | 31.575875 | 257 |
starcoderdata
|
//
// XHBaseTabBarVC.h
// XHDesign
//
// Created by cnest on 2019/9/29.
// Copyright © 2019 huan. All rights reserved.
//
#import
NS_ASSUME_NONNULL_BEGIN
@interface XHBaseTabBarVC : UITabBarController
@end
NS_ASSUME_NONNULL_END
|
c
| 6 | 0.726688 | 53 | 13.136364 | 22 |
starcoderdata
|
# Copyright 2021-2022 Huawei Technologies Co., Ltd
#
# 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.
# ==============================================================================
"""
This module is to support audio augmentations.
It includes two parts: audio transforms and utils.
audio transforms is a high performance processing module with common audio operations.
utils provides some general methods for audio processing.
Common imported modules in corresponding API examples are as follows:
.. code-block::
import mindspore.dataset as ds
import mindspore.dataset.audio as audio
from mindspore.dataset.audio import utils
Alternative and equivalent imported audio module is as follows:
.. code-block::
import mindspore.dataset.audio.transforms as audio
Descriptions of common data processing terms are as follows:
- TensorOperation, the base class of all data processing operations implemented in C++.
- AudioTensorOperation, the base class of all audio processing operations. It is a derived class of TensorOperation.
The data transform operation can be executed in the data processing pipeline or in the eager mode:
- Pipeline mode is generally used to process big datasets. Examples refer to
`introduction to data processing pipeline <https://www.mindspore.cn/docs/en/master/api_python/
mindspore.dataset.html#introduction-to-data-processing-pipeline>`_ .
- Eager mode is more like a function call to process data. Examples refer to
`Lightweight Data Processing <https://www.mindspore.cn/tutorials/en/master/advanced/dataset/eager.html>`_ .
"""
from __future__ import absolute_import
from mindspore.dataset.audio import transforms
from mindspore.dataset.audio import utils
from mindspore.dataset.audio.transforms import AllpassBiquad, AmplitudeToDB, Angle, BandBiquad, \
BandpassBiquad, BandrejectBiquad, BassBiquad, Biquad, ComplexNorm, ComputeDeltas, Contrast, DBToAmplitude, \
DCShift, DeemphBiquad, DetectPitchFrequency, Dither, EqualizerBiquad, Fade, Filtfilt, Flanger, FrequencyMasking, \
Gain, GriffinLim, HighpassBiquad, InverseMelScale, InverseSpectrogram, LFCC, LFilter, LowpassBiquad, Magphase, \
MaskAlongAxis, MaskAlongAxisIID, MelScale, MelSpectrogram, MFCC, MuLawDecoding, MuLawEncoding, Overdrive, \
Phaser, PhaseVocoder, PitchShift, Resample, RiaaBiquad, SlidingWindowCmn, SpectralCentroid, Spectrogram, \
TimeMasking, TimeStretch, TrebleBiquad, Vad, Vol
from mindspore.dataset.audio.utils import BorderType, DensityFunction, FadeShape, GainType, Interpolation, \
MelType, Modulation, NormMode, NormType, ResampleMethod, ScaleType, WindowType, create_dct, linear_fbanks, \
melscale_fbanks
|
python
| 3 | 0.771122 | 118 | 51 | 61 |
research_code
|
package me.shoutto.sdk.internal.usecases;
import android.util.Log;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Captor;
import org.mockito.Mock;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import java.util.ArrayList;
import java.util.List;
import me.shoutto.sdk.StmBaseEntity;
import me.shoutto.sdk.StmCallback;
import me.shoutto.sdk.StmError;
import me.shoutto.sdk.User;
import me.shoutto.sdk.internal.StmObservableResults;
import me.shoutto.sdk.internal.StmObserver;
import me.shoutto.sdk.internal.http.HttpMethod;
import me.shoutto.sdk.internal.http.StmRequestProcessor;
import static junit.framework.Assert.assertEquals;
import static junit.framework.Assert.assertNotNull;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.doNothing;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
/**
* GetChannelSubscriptionTest
*/
@RunWith(PowerMockRunner.class)
@PrepareForTest({Log.class})
public class GetChannelSubscriptionTest {
private static final String CHANNEL_ID = "channelId";
private static final String USER_ID = "userId";
@Mock
private StmRequestProcessor mockStmRequestProcessor;
@Mock
private StmCallback mockCallback;
@Captor
private ArgumentCaptor userArgumentCaptor;
@Captor
private ArgumentCaptor errorArgumentCaptor;
@Captor
private ArgumentCaptor stmErrorArgumentCaptor;
@Test
public void get_WithNullChannelId_ShouldCallBackWithError() {
doNothing().when(mockStmRequestProcessor).addObserver(any(StmObserver.class));
GetChannelSubscription getChannelSubscription = new GetChannelSubscription(mockStmRequestProcessor);
getChannelSubscription.get(null, USER_ID, mockCallback);
verify(mockCallback, times(1)).onError(errorArgumentCaptor.capture());
assertNotNull(errorArgumentCaptor.getValue());
verify(mockCallback, times(0)).onResponse(any(Boolean.class));
}
@Test
public void get_WithEmptyStringChannelId_ShouldCallBackWithError() {
doNothing().when(mockStmRequestProcessor).addObserver(any(StmObserver.class));
GetChannelSubscription getChannelSubscription = new GetChannelSubscription(mockStmRequestProcessor);
getChannelSubscription.get("", USER_ID, mockCallback);
verify(mockCallback, times(1)).onError(errorArgumentCaptor.capture());
assertNotNull(errorArgumentCaptor.getValue());
verify(mockCallback, times(0)).onResponse(any(Boolean.class));
}
@Test
public void get_WithNullUserId_ShouldCallBackWithError() {
doNothing().when(mockStmRequestProcessor).addObserver(any(StmObserver.class));
GetChannelSubscription getChannelSubscription = new GetChannelSubscription(mockStmRequestProcessor);
getChannelSubscription.get(CHANNEL_ID, null, mockCallback);
verify(mockCallback, times(1)).onError(errorArgumentCaptor.capture());
assertNotNull(errorArgumentCaptor.getValue());
verify(mockCallback, times(0)).onResponse(any(Boolean.class));
}
@Test
public void get_WithEmptyStringUserId_ShouldCallBackWithError() {
doNothing().when(mockStmRequestProcessor).addObserver(any(StmObserver.class));
GetChannelSubscription getChannelSubscription = new GetChannelSubscription(mockStmRequestProcessor);
getChannelSubscription.get(CHANNEL_ID, "", mockCallback);
verify(mockCallback, times(1)).onError(errorArgumentCaptor.capture());
assertNotNull(errorArgumentCaptor.getValue());
verify(mockCallback, times(0)).onResponse(any(Boolean.class));
}
@Test
public void get_WithValidInput_ShouldCallProcessRequestWithUser() {
doNothing().when(mockStmRequestProcessor).addObserver(any(StmObserver.class));
GetChannelSubscription getChannelSubscription = new GetChannelSubscription(mockStmRequestProcessor);
getChannelSubscription.get(CHANNEL_ID, USER_ID, null);
verify(mockStmRequestProcessor, times(1))
.processRequest(any(HttpMethod.class), userArgumentCaptor.capture());
assertEquals(USER_ID, userArgumentCaptor.getValue().getId());
}
@Test
public void get_WithValidInput_ShouldReturnFalseWithNullArray() {
doNothing().when(mockStmRequestProcessor).addObserver(any(StmObserver.class));
GetChannelSubscription getChannelSubscription = new GetChannelSubscription(mockStmRequestProcessor);
getChannelSubscription.get(CHANNEL_ID, USER_ID, mockCallback);
User user = new User();
StmObservableResults stmObservableResults = new StmObservableResults<>();
stmObservableResults.setResult(user);
getChannelSubscription.processCallback(stmObservableResults);
verify(mockCallback, times(1)).onResponse(false);
}
@Test
public void get_WithValidInput_ShouldReturnFalseWithEmptyArray() {
doNothing().when(mockStmRequestProcessor).addObserver(any(StmObserver.class));
GetChannelSubscription getChannelSubscription = new GetChannelSubscription(mockStmRequestProcessor);
getChannelSubscription.get(CHANNEL_ID, USER_ID, mockCallback);
User user = new User();
StmObservableResults stmObservableResults = new StmObservableResults<>();
user.setChannelSubscriptions(new ArrayList
stmObservableResults.setResult(user);
getChannelSubscription.processCallback(stmObservableResults);
verify(mockCallback, times(1)).onResponse(false);
}
@Test
public void get_WithValidInput_ShouldReturnFalseIfChannelNotInArray() {
doNothing().when(mockStmRequestProcessor).addObserver(any(StmObserver.class));
GetChannelSubscription getChannelSubscription = new GetChannelSubscription(mockStmRequestProcessor);
getChannelSubscription.get(CHANNEL_ID, USER_ID, mockCallback);
User user = new User();
StmObservableResults stmObservableResults = new StmObservableResults<>();
List channelSubscriptions = new ArrayList<>();
channelSubscriptions.add("different channel 1");
channelSubscriptions.add("different channel 2");
channelSubscriptions.add("different channel 3");
user.setChannelSubscriptions(channelSubscriptions);
stmObservableResults.setResult(user);
getChannelSubscription.processCallback(stmObservableResults);
verify(mockCallback, times(1)).onResponse(false);
}
@Test
public void get_WithValidInput_ShouldReturnTrueIfChannelInArray() {
doNothing().when(mockStmRequestProcessor).addObserver(any(StmObserver.class));
GetChannelSubscription getChannelSubscription = new GetChannelSubscription(mockStmRequestProcessor);
getChannelSubscription.get(CHANNEL_ID, USER_ID, mockCallback);
User user = new User();
StmObservableResults stmObservableResults = new StmObservableResults<>();
List channelSubscriptions = new ArrayList<>();
channelSubscriptions.add("different channel 1");
channelSubscriptions.add(CHANNEL_ID);
channelSubscriptions.add("different channel 2");
user.setChannelSubscriptions(channelSubscriptions);
stmObservableResults.setResult(user);
getChannelSubscription.processCallback(stmObservableResults);
verify(mockCallback, times(1)).onResponse(true);
}
@Test
public void get_WithValidInput_ShouldCallBackErrorOnProcessingError() {
doNothing().when(mockStmRequestProcessor).addObserver(any(StmObserver.class));
GetChannelSubscription getChannelSubscription = new GetChannelSubscription(mockStmRequestProcessor);
getChannelSubscription.get(CHANNEL_ID, USER_ID, mockCallback);
getChannelSubscription.processCallbackError(new StmObservableResults());
verify(mockCallback, times(1)).onError(stmErrorArgumentCaptor.capture());
assertNotNull(stmErrorArgumentCaptor.getValue());
assertEquals(StmError.SEVERITY_MINOR, stmErrorArgumentCaptor.getValue().getSeverity());
}
}
|
java
| 9 | 0.75198 | 108 | 40.462687 | 201 |
starcoderdata
|
package com.samsung.sec.dexter.executor.cli;
import com.samsung.sec.dexter.core.analyzer.AnalysisResult;
import com.samsung.sec.dexter.core.analyzer.IAnalysisResultHandler;
import com.samsung.sec.dexter.core.util.IDexterClient;
import java.util.List;
public class EmptyAnalysisResultHandler implements IAnalysisResultHandler {
@Override
public void handleAnalysisResult(List analysisResult, IDexterClient client) {}
@Override
public void printLogAfterAnalyze() {}
@Override
public void handleBeginnigOfResultFile() {}
@Override
public void handleEndOfResultFile() {}
}
|
java
| 8 | 0.785256 | 98 | 27.363636 | 22 |
starcoderdata
|
package ecr
import (
b64 "encoding/base64"
"log"
"os"
awsSession "github.com/aws/aws-sdk-go/aws/session"
awsECR "github.com/aws/aws-sdk-go/service/ecr"
_ "github.com/aditmeno/registry-credential-helper/interface"
)
type ECRCredentialHelper struct {
Token string
Session interface{}
}
func GetECRCredentialHelper() *ECRCredentialHelper {
return &ECRCredentialHelper{}
}
func (credHelper *ECRCredentialHelper) Login() {
session := login()
credHelper.Session = session
}
func (credHelper *ECRCredentialHelper) GetToken() string {
awsRegistry := os.Getenv("AWS_ECR_REGISTRY")
if awsRegistry == "" {
log.Fatal("AWS Registry missing, aborting!!")
}
credHelper.Token = getToken(awsRegistry, credHelper.Session.(*awsECR.ECR))
return credHelper.Token
}
func login() *awsECR.ECR {
awsSession := awsSession.Must(awsSession.NewSession())
ecrSession := awsECR.New(awsSession)
return ecrSession
}
func getToken(registryID string, session *awsECR.ECR) string {
registry := awsECR.GetAuthorizationTokenInput{
RegistryIds: []*string{
®istryID,
},
}
tokenOutput, err := session.GetAuthorizationToken(®istry)
if err != nil {
log.Fatalf("Encountered an error: %s", err.Error())
}
payload := tokenOutput.AuthorizationData[0].AuthorizationToken
decodedString, _ := b64.StdEncoding.DecodeString(*payload)
extractedToken := string(decodedString)[4:]
return extractedToken
}
|
go
| 13 | 0.746556 | 75 | 24.034483 | 58 |
starcoderdata
|
/**
* Created by on 30/12/2015.
*/
/*
* The module ‘hujinet’ which is in charge of communication with
* the node ‘net’ module including receiving and sending HTTP calls.
* This module should ‘understand’ what part of the network stream is
* actually an HTTP message and then it should parse it.
*/
/* Global variables */
var fs = require('fs'),
util = require('util'),
eventEmitter = require("events"),
constants = require('./Constants'),
CRLF = require('./Constants').CRLF,
DOUBLE_CRLF = require('./Constants').DOUBLE_CRLF,
statusCodes = require('./Constants').statusCodesByMessage,
OK = statusCodes['OK'], // 200
timeOut2sec = require('./Constants').timeOut2sec,
pathModule = require('path'),
httpRequest = require('./Request'),
httpRespond = require('./Response'),
notExist = require('./Constants').notExist,
isRequestPartial = require('./Request').isRequestPartial,
net = require('net');
exports.StaticServer = StaticServer;
/**
* This is a server-object-wrapper "StaticServer" for actual realServer object.
* This StaticServer maintain a dictionary (like a hash) of all connected sockets
* in order to be able to end all of them in case the server stops.
* @param port
* @param rootFolder
* @constructor
*/
function StaticServer( port, rootFolder) {
// private fields
var serverPort = port;
var serverRootDir = rootFolder;
// public fields
this.realServer = undefined; // actual realServer object
/* serverObj should have a two read-only properties (Object.defineProperty()) */
/**
* port property
* @returns {*serverPort}
*/
this.port = function(){
return serverPort;
};
/**
* rootFolder property
* @returns {*serverRootDir}
*/
this.rootFolder = function(){
return serverRootDir;
};
} // end of StaticServer class definition
/**
* Gets the address of the server
* @returns {*this.realServer.address}
*/
StaticServer.prototype.address = function() {
if ( typeof this.realServer !== "undefined") {
return this.realServer.address();
}
return notExist;
};
/**
* Function that creates the actual net server which maintain the sockets.
* @param serverIndex
* @returns {*this.realServer}
*/
StaticServer.prototype.createStaticServer = function() {
var rootFolder = this.rootFolder();
var port = this.port();
var sockets = []; // all connected sockets
// Create a new TCP server
this.realServer = net.createServer( function( socket){
// add a new connected socket into sockets
sockets.push( socket);
var requestStr = ''; // request string
// on data event - keep alive and handle an incoming request
socket.on('data', function( chunk) {
socket.setKeepAlive( true);
var requestChunk = chunk.toString();
requestStr += requestChunk; // collect chunks
// in case it is a full request string - handle it
if ( !isRequestPartial (requestStr)) {
StaticServer.handleRequest( socket, requestStr, rootFolder);
requestStr = ''; // initialize string for next request
}
});
// on end event - remove this socket from sockets
socket.on( 'end', function () {
sockets.splice( sockets.indexOf(socket), 1);
});
// on error event - ensure that no more I/O activity happens on socket
socket.on( 'error', function ( error) {
var socketId = sockets.indexOf( socket);
sockets[socketId].destroy();
sockets.splice( socketId, 1);
});
socket.on( 'close', function () {
sockets.splice( sockets.indexOf(socket), 1);
});
// after no request in 2 seconds - end socket activity
socket.setTimeout( timeOut2sec ,function() {
socket.end();
});
});
this.realServer.maxConnections = constants.maxLimitConnect;
this.realServer.listen( port);
return this.realServer;
};
/**
* Function sets the netSever object to listen to the given port.
* @param port
*/
StaticServer.prototype.listen = function( port){
if ( this.realServer !== undefined){
this.realServer.listen( port);
}
};
/**
* Function that stops the server - ends all the sockets on server and closes the server.
* this calls the callback once the server is down.
* Function that stops the server. serverObj should have a .stop(callback).
* @param callback
*/
StaticServer.prototype.stop = function( callback) {
this.realServer.close( callback);
};
/**
* Function handles an incoming request on socket on server
* static function of StaticServer
* @param socket
* @param request
*/
StaticServer.handleRequest = function( socket, request, rootFolder) {
var hujiRequest = new httpRequest.HttpRequest( request, rootFolder);
hujiRequest.parseRequestString();
// var fullPath = pathModule.resolve(rootDir, relativePath);
var fullPath = hujiRequest.fullPath;
var hujiResponse = new httpRespond.HttpRespond();
// check error#1 - http version is not supported
hujiRequest.validateHttpVersion( hujiResponse);
if ( hujiRequest.statusCode !== OK) {
socketWriteEnd( socket, hujiResponse, fullPath);
return;
}
/* set connectionMode of request and response according to request*/
hujiRequest.setConnection( hujiResponse);
// check error#2 - method request is not supported
hujiRequest.validateMethod( hujiResponse);
if ( hujiRequest.statusCode !== OK) {
socketWriteEnd( socket, hujiResponse, fullPath);
return;
}
// check error#3 - path url in request is relative, or invalid
hujiRequest.validatePath( hujiResponse);
if ( hujiRequest.statusCode !== OK) {
socketWriteEnd( socket, hujiResponse, fullPath);
return;
}
// check error#4 - file extension is unsupported
hujiRequest.validateFileExtension( hujiResponse);
if ( hujiRequest.statusCode !== OK) {
socketWriteEnd( socket, hujiResponse, fullPath);
return;
}
// check error#5 - if file path exists and leads to a readable file
validateFileExist( socket, hujiRequest, hujiResponse);
return;
};
/**
* Function checks if file exists, not a directory, can be read and opened.
* The function sets the hujiResponse headers string according to the error or success.
*/
function validateFileExist( socket, hujiRequest, hujiResponse) {
var lastModified = undefined, fileSize = 0;
var fullPath = hujiRequest.fullPath;
var statObj = fs.stat( fullPath, function (err, fileStat) {
// check error#5 - file path does not exist
if ( err) {
hujiRequest.statusCode = 404;
hujiRequest.statusErrorMessage = 'Not Found';
} else {
// check error#6 - file path is directory
if ( fileStat.isDirectory()) {
hujiRequest.statusCode = 404;
hujiRequest.statusErrorMessage = 'Directory Path';
} else if ( fileStat.isFile()) {
// try to read the file
var readStream = fs.createReadStream( fullPath);
// check error#7 - can't read and open file
readStream.on( 'error', function(err) {
hujiRequest.statusCode = 404;
hujiRequest.statusErrorMessage = 'Error File Reading';
});
// in case file opens ok - collect data:
lastModified = new Date(fileStat['mtime']); // modify time
fileSize = fileStat.size;
}
}
/* if statusCode was changed */
if ( hujiRequest.statusCode !== OK) {
hujiResponse.setErrorHeaders( hujiRequest.statusCode, hujiRequest.statusErrorMessage);
} else {
hujiResponse.setOkHeaders( hujiRequest.statusCode, fileSize, hujiRequest.extension, lastModified);
}
socketWriteEnd( socket, hujiResponse, fullPath);
});
}
/**
* Function writes the response into socket and then ends it after timeOut2sec.
* @param socket
* @param responseStr
*/
function socketWriteEnd( socket, hujiResponse, fullPath) {
var response = hujiResponse.getRespondString();
socket.write(response);
// in case file was found - pipe it
if ( hujiResponse.statusCode === OK) {
var readStream = fs.createReadStream( fullPath);
// wait til the readable stream is valid prior to piping
readStream.on('open', function() {
readStream.pipe(socket);
});
}
/* If the http version is 1.0 and there is no Connection header,
or if the http is 1.1 and there is 'Connection: close' header =>
both case follow the same rule */
if ( hujiResponse.connectionMode === 'close') {
socket.end();
}
}
|
javascript
| 24 | 0.617928 | 110 | 31.434783 | 276 |
starcoderdata
|
package com.home.commonData.message.game.serverRequest.game.func.base;
import com.home.commonData.message.game.serverRequest.game.base.PlayerGameToGameMO;
public class FuncPlayerGameToGameMO extends PlayerGameToGameMO
{
/** 功能ID */
int funcID;
}
|
java
| 10 | 0.816 | 83 | 26.777778 | 9 |
starcoderdata
|
namespace Square.Models
{
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using Square;
using Square.Utilities;
///
/// InventoryAdjustmentGroup.
///
public class InventoryAdjustmentGroup
{
///
/// Initializes a new instance of the <see cref="InventoryAdjustmentGroup"/> class.
///
/// <param name="id">id.
/// <param name="rootAdjustmentId">root_adjustment_id.
/// <param name="fromState">from_state.
/// <param name="toState">to_state.
public InventoryAdjustmentGroup(
string id = null,
string rootAdjustmentId = null,
string fromState = null,
string toState = null)
{
this.Id = id;
this.RootAdjustmentId = rootAdjustmentId;
this.FromState = fromState;
this.ToState = toState;
}
///
/// A unique ID generated by Square for the
/// `InventoryAdjustmentGroup`.
///
[JsonProperty("id", NullValueHandling = NullValueHandling.Ignore)]
public string Id { get; }
///
/// The inventory adjustment of the composed variation.
///
[JsonProperty("root_adjustment_id", NullValueHandling = NullValueHandling.Ignore)]
public string RootAdjustmentId { get; }
///
/// Indicates the state of a tracked item quantity in the lifecycle of goods.
///
[JsonProperty("from_state", NullValueHandling = NullValueHandling.Ignore)]
public string FromState { get; }
///
/// Indicates the state of a tracked item quantity in the lifecycle of goods.
///
[JsonProperty("to_state", NullValueHandling = NullValueHandling.Ignore)]
public string ToState { get; }
///
public override string ToString()
{
var toStringOutput = new List
this.ToString(toStringOutput);
return $"InventoryAdjustmentGroup : ({string.Join(", ", toStringOutput)})";
}
///
public override bool Equals(object obj)
{
if (obj == null)
{
return false;
}
if (obj == this)
{
return true;
}
return obj is InventoryAdjustmentGroup other &&
((this.Id == null && other.Id == null) || (this.Id?.Equals(other.Id) == true)) &&
((this.RootAdjustmentId == null && other.RootAdjustmentId == null) || (this.RootAdjustmentId?.Equals(other.RootAdjustmentId) == true)) &&
((this.FromState == null && other.FromState == null) || (this.FromState?.Equals(other.FromState) == true)) &&
((this.ToState == null && other.ToState == null) || (this.ToState?.Equals(other.ToState) == true));
}
///
public override int GetHashCode()
{
int hashCode = -1783874998;
hashCode = HashCode.Combine(this.Id, this.RootAdjustmentId, this.FromState, this.ToState);
return hashCode;
}
///
/// ToString overload.
///
/// <param name="toStringOutput">List of strings.
protected void ToString(List toStringOutput)
{
toStringOutput.Add($"this.Id = {(this.Id == null ? "null" : this.Id == string.Empty ? "" : this.Id)}");
toStringOutput.Add($"this.RootAdjustmentId = {(this.RootAdjustmentId == null ? "null" : this.RootAdjustmentId == string.Empty ? "" : this.RootAdjustmentId)}");
toStringOutput.Add($"this.FromState = {(this.FromState == null ? "null" : this.FromState.ToString())}");
toStringOutput.Add($"this.ToState = {(this.ToState == null ? "null" : this.ToState.ToString())}");
}
///
/// Converts to builder object.
///
/// Builder.
public Builder ToBuilder()
{
var builder = new Builder()
.Id(this.Id)
.RootAdjustmentId(this.RootAdjustmentId)
.FromState(this.FromState)
.ToState(this.ToState);
return builder;
}
///
/// Builder class.
///
public class Builder
{
private string id;
private string rootAdjustmentId;
private string fromState;
private string toState;
///
/// Id.
///
/// <param name="id"> id.
/// Builder.
public Builder Id(string id)
{
this.id = id;
return this;
}
///
/// RootAdjustmentId.
///
/// <param name="rootAdjustmentId"> rootAdjustmentId.
/// Builder.
public Builder RootAdjustmentId(string rootAdjustmentId)
{
this.rootAdjustmentId = rootAdjustmentId;
return this;
}
///
/// FromState.
///
/// <param name="fromState"> fromState.
/// Builder.
public Builder FromState(string fromState)
{
this.fromState = fromState;
return this;
}
///
/// ToState.
///
/// <param name="toState"> toState.
/// Builder.
public Builder ToState(string toState)
{
this.toState = toState;
return this;
}
///
/// Builds class object.
///
/// InventoryAdjustmentGroup.
public InventoryAdjustmentGroup Build()
{
return new InventoryAdjustmentGroup(
this.id,
this.rootAdjustmentId,
this.fromState,
this.toState);
}
}
}
}
|
c#
| 20 | 0.504413 | 171 | 33.489899 | 198 |
starcoderdata
|
<?php
namespace Wifinder\LayoutBundle\Entity\Repository;
use Doctrine\ORM\EntityRepository;
class LayoutRepository extends EntityRepository
{
public function retriveLayout($request){
$query = $this->_em->createQueryBuilder()
->select("c")
->from("LayoutBundle:Layout", "c")
->getQuery()->execute();
return $query;
}
}
|
php
| 14 | 0.628788 | 50 | 21.055556 | 18 |
starcoderdata
|
package com.auto.test.controller;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;
import com.auto.test.common.controller.BaseController;
import com.auto.test.entity.UDevice;
import com.auto.test.service.IUiDeviceService;
@RestController
@RequestMapping(value = "ui/device")
public class UiDeviceController extends BaseController{
private static Logger logger = LoggerFactory.getLogger(UiDeviceController.class);
@Resource
private IUiDeviceService deviceService;
@RequestMapping(value = "/list", method = RequestMethod.GET)
public ModelAndView getAllDevice(HttpServletRequest request) {
logger.info("[Device]==>请求页面[ui/device],登录用户[" + getCurrentUserName(request) + "]");
return success("ui/device", getCurrentUserName(request));
}
@RequestMapping(value = "/list/data", method = RequestMethod.GET)
@ResponseBody
public Map<String, Object> getAllDeviceData() {
logger.info("[Device]==>获取所有设备数据!");
List list = deviceService.findAll();
return successJson(list);
}
@RequestMapping(value = "/id={id}", method = RequestMethod.GET)
@ResponseBody
public Map<String, Object> getDeviceById(@PathVariable("id") String id) {
UDevice uDevice = deviceService.findById(Integer.parseInt(id));
if(uDevice != null){
logger.info("[Device]==>获取设备[id=" + id + "]数据!");
return successJson(uDevice);
}
logger.error("[Device]==>获取设备[id=" + id + "]不存在!");
return failedJson("获取设备[id=" + id + "]不存在!");
}
@RequestMapping(value = "/repeat", method = RequestMethod.POST)
@ResponseBody
public Map<String, Object> getDeviceByName(@RequestParam("ui-device-id") String id, @RequestParam("ui-device-udid") String udid) {
if(!isNull(id)){
UDevice uDevice = deviceService.findById(Integer.parseInt(id));
if(uDevice != null && uDevice.getUdid() != null && uDevice.getUdid().equals(udid)){
logger.info("[Device]==>验证设备[udid=" + udid + "]是本身!");
return successJson();
}
}
List list = deviceService.findByUdid(udid);
if(list == null || list.isEmpty()){
logger.info("[Device]==>验证设备[udid=" + udid + "]不存在!");
return successJson();
}
logger.error("[Device]==>验证设备[udid=" + udid + "]已存在!");
return failedJson("验证设备[udid=" + udid + "]已存在!");
}
@RequestMapping(value = "/create/update", method = RequestMethod.POST)
@ResponseBody
public Map<String, Object> createOrUpdate(@RequestParam("ui-device-id") String id, @RequestParam("ui-platform-name") String pname,
@RequestParam("ui-platform-version") String pver, @RequestParam("ui-nickname") String nickname,
@RequestParam("ui-device-name") String deviceName, @RequestParam("ui-device-udid") String udid,
@RequestParam("ui-server-url") String serverUrl, @RequestParam("ui-device-app") String app) {
try {
if(isNull(id)){
Integer did = deviceService.create(new UDevice(pname.trim(), pver.trim(), nickname.trim(), deviceName.trim(), udid.trim(), serverUrl.trim(), app.trim()));
if(did != null){
logger.info("[Device]==>添加设备[id=" + did + ",udid=" + udid + "]成功!");
return successJson();
}else{
logger.error("[Device]==>添加设备[udid=" + udid + "]失败!");
return failedJson("添加设备[udid=" + udid + "]失败!");
}
}else{
UDevice uDevice = deviceService.update(new UDevice(Integer.parseInt(id), pname.trim(), pver.trim(), nickname.trim(), deviceName.trim(), udid.trim(), serverUrl.trim(), app.trim()));
if(uDevice != null){
logger.info("[Device]==>更新设备[id=" + id + ",udid=" + udid + "]成功!");
return successJson();
}else{
logger.error("[Device]==>更新设备[id=" + id + ",udid=" + udid + "]失败!");
return failedJson("更新设备[id=" + id + ",udid=" + udid + "]失败!");
}
}
} catch (Exception e) {
e.printStackTrace();
logger.error("[Device]==>添加/更新设备失败[" + e.getMessage() + "]");
return failedJson(e.getMessage());
}
}
@RequestMapping(value = "/delete/id={id}", method = RequestMethod.GET)
@ResponseBody
public Map<String, Object> deleteDevice(@PathVariable("id") String id) {
try {
deviceService.delete(Integer.parseInt(id));
logger.info("[Device]==>删除设备[id=" + id + "]成功!");
return successJson();
} catch (Exception e) {
e.printStackTrace();
logger.error("[Device]==>删除设备失败[" + e.getMessage() + "]");
return failedJson(e.getMessage());
}
}
}
|
java
| 17 | 0.673695 | 184 | 39.165289 | 121 |
starcoderdata
|
package com.jd.socialmanager.dao;
import com.jd.socialmanager.entity.ParkDO;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import java.util.List;
@Mapper
public interface IParkDao {
/**
* 通过ID查询单条数据
*
* @param parkId 主键
* @return 实例对象
*/
ParkDO queryById(Integer parkId);
/**
* 通过实体作为筛选条件查询
*
* @param park 实例对象
* @param offset 查询起始位置
* @param limit 查询条数
* @return 对象列表
*/
List queryAll(ParkDO park, @Param("offset") int offset, @Param("limit") int limit);
/**
* 新增数据
*
* @param part 实例对象
* @return 影响行数
*/
int insert(ParkDO part);
/**
* 修改数据
*
* @param part 实例对象
* @return 影响行数
*/
int update(ParkDO part);
/**
* 通过主键删除数据
*
* @param parkId 主键
* @return 影响行数
*/
int deleteById(Integer parkId);
}
|
java
| 10 | 0.567132 | 95 | 16.240741 | 54 |
starcoderdata
|
public override async Task<InputFormatterResult> ReadRequestBodyAsync(InputFormatterContext context, Encoding encoding)
{
if (context == null) throw new ArgumentNullException(nameof(context));
if (encoding == null) throw new ArgumentNullException(nameof(encoding));
var request = context.HttpContext.Request;
if (!request.Body.CanSeek)
request.EnableRewind();
// XML serializer does synchronous reads. This loads everything
// into the buffer without blocking
await request.Body.DrainAsync(CancellationToken.None);
request.Body.Seek(0L, SeekOrigin.Begin);
SoapV11Envelope soapEnvelope;
using (var stream = new NonDisposableStream(request.Body))
using (var reader = new XmlTextReader(stream))
{
soapEnvelope = (SoapV11Envelope) EnvelopeSerializer.Deserialize(reader);
}
if (context.ModelType == typeof(SoapV11Envelope))
return InputFormatterResult.Success(soapEnvelope);
using (var stream = new StringReader(soapEnvelope.Body.ToString()))
using (var reader = new XmlTextReader(stream))
{
return InputFormatterResult.Success(
new XmlSerializer(context.ModelType).Deserialize(reader));
}
}
|
c#
| 17 | 0.623404 | 119 | 43.09375 | 32 |
inline
|
"""Script used to calculate the error between the actual and the predicted annotations produced by Annotator"""
import json
import os.path
import sys
from itertools import product
def calc_annotation_error(annotation1, annotation2, annoyances):
markers = []
for event in annotation1:
markers.append({'soundscape': 1, 'isStart': True, 'time': event['start'], 'class': event['class']})
markers.append({'soundscape': 1, 'isStart': False, 'time': event['end'], 'class': event['class']})
for event in annotation2:
markers.append({'soundscape': 2, 'isStart': True, 'time': event['start'], 'class': event['class']})
markers.append({'soundscape': 2, 'isStart': False, 'time': event['end'], 'class': event['class']})
markers.sort(key=lambda k: k['time'])
error = 0
classes1 = []
classes2 = []
a = 0
for marker in markers:
b = marker['time']
if classes1:
if classes2:
error += (b - a) * min(abs(annoyances[d] - annoyances[c]) for c, d in product(classes1, classes2))
else:
error += (b - a) * min([annoyances[c] for c in classes1])
else:
if classes2:
error += (b - a) * min([annoyances[c] for c in classes2])
else:
error += (b - a) * 0
a = b
if marker['soundscape'] == 1:
if marker['isStart']:
classes1.append(marker['class'])
else:
classes1.remove(marker['class'])
elif marker['soundscape'] == 2:
if marker['isStart']:
classes2.append(marker['class'])
else:
classes2.remove(marker['class'])
return error
if __name__ == '__main__':
true_annotation_filepath = sys.argv[1]
pred_annotation_filepath = sys.argv[2]
def read_annotation(filepath):
events = []
with open(filepath) as file:
for line in file:
try:
split = line.split('\t')
event = {'start': float(split[0]), 'end': float(split[1]), 'class': split[2].rstrip()}
events.append(event)
except:
pass # skip line
return events
true_annotation = read_annotation(true_annotation_filepath)
pred_annotation = read_annotation(pred_annotation_filepath)
with open(os.path.dirname(os.path.realpath(__file__)) + "/../annoyances.json") as file:
annoyances = json.load(file)
match = calc_annotation_error(true_annotation, pred_annotation, annoyances)
print(match)
|
python
| 18 | 0.554924 | 114 | 33.285714 | 77 |
starcoderdata
|
from . import Object
from typing import List
import FishEngineInternal
class Scene:
__slots__ = ('m_Handle', 'cpp')
def __init__(self, cppScene=None):
self.m_Handle:int = 0
self.cpp = None
# interal
@property
def gameObjects(self):
raise NotImplementedError
def Clean(self):
self.cpp.Clean()
@property
def rootCount(self):
raise NotImplementedError
def GetRootGameObjects(self):
result = []
FishEngineInternal.Scene_GetRootGameObjects(self.cpp, result)
return result
def Backup(self):
pass
def Restore(self):
pass
class SceneManager:
__Handle2Scene = {}
@staticmethod
def CreateScene(sceneName: str):
s = FishEngineInternal.SceneManager.CreateScene(sceneName)
return SceneManager.__Wrap(s)
@staticmethod
def sceneCount():
raise NotImplementedError
@staticmethod
def __Wrap(cppScene:FishEngineInternal.Scene)->Scene:
handle = cppScene.GetHandle()
if handle in SceneManager.__Handle2Scene:
return SceneManager.__Handle2Scene[handle]
else:
s = Scene()
s.cpp = cppScene
SceneManager.__Handle2Scene[handle] = s
return s
@staticmethod
def GetActiveScene()->Scene:
cpp = FishEngineInternal.SceneManager.GetActiveScene()
return SceneManager.__Wrap(cpp)
@staticmethod
def SetActiveScene(scene:Scene):
FishEngineInternal.SceneManager.SetActiveScene(scene.cpp)
# @staticmethod
# def StaticClean():
# pass
|
python
| 13 | 0.627692 | 69 | 22.228571 | 70 |
starcoderdata
|
# Copyright 2017 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may 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.
# ==============================================================================
"""Networks for MNIST example using TFGAN."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import tensorflow as tf
ds = tf.contrib.distributions
layers = tf.contrib.layers
tfgan = tf.contrib.gan
def _generator_helper(
noise, is_conditional, one_hot_labels, weight_decay, is_training):
"""Core MNIST generator.
This function is reused between the different GAN modes (unconditional,
conditional, etc).
Args:
noise: A 2D Tensor of shape [batch size, noise dim].
is_conditional: Whether to condition on labels.
one_hot_labels: Optional labels for conditioning.
weight_decay: The value of the l2 weight decay.
is_training: If `True`, batch norm uses batch statistics. If `False`, batch
norm uses the exponential moving average collected from population
statistics.
Returns:
A generated image in the range [-1, 1].
"""
with tf.contrib.framework.arg_scope(
[layers.fully_connected, layers.conv2d_transpose],
activation_fn=tf.nn.relu, normalizer_fn=layers.batch_norm,
weights_regularizer=layers.l2_regularizer(weight_decay)):
with tf.contrib.framework.arg_scope(
[layers.batch_norm], is_training=is_training):
net = layers.fully_connected(noise, 1024)
if is_conditional:
net = tfgan.features.condition_tensor_from_onehot(net, one_hot_labels)
net = layers.fully_connected(net, 7 * 7 * 128)
net = tf.reshape(net, [-1, 7, 7, 128])
net = layers.conv2d_transpose(net, 64, [4, 4], stride=2)
net = layers.conv2d_transpose(net, 32, [4, 4], stride=2)
# Make sure that generator output is in the same range as `inputs`
# ie [-1, 1].
net = layers.conv2d(
net, 1, [4, 4], normalizer_fn=None, activation_fn=tf.tanh)
return net
def unconditional_generator(noise, weight_decay=2.5e-5, is_training=True):
"""Generator to produce unconditional MNIST images.
Args:
noise: A single Tensor representing noise.
weight_decay: The value of the l2 weight decay.
is_training: If `True`, batch norm uses batch statistics. If `False`, batch
norm uses the exponential moving average collected from population
statistics.
Returns:
A generated image in the range [-1, 1].
"""
return _generator_helper(noise, False, None, weight_decay, is_training)
def conditional_generator(inputs, weight_decay=2.5e-5, is_training=True):
"""Generator to produce MNIST images conditioned on class.
Args:
inputs: A 2-tuple of Tensors (noise, one_hot_labels).
weight_decay: The value of the l2 weight decay.
is_training: If `True`, batch norm uses batch statistics. If `False`, batch
norm uses the exponential moving average collected from population
statistics.
Returns:
A generated image in the range [-1, 1].
"""
noise, one_hot_labels = inputs
return _generator_helper(
noise, True, one_hot_labels, weight_decay, is_training)
def infogan_generator(inputs, categorical_dim, weight_decay=2.5e-5,
is_training=True):
"""InfoGAN generator network on MNIST digits.
Based on a paper https://arxiv.org/abs/1606.03657, their code
https://github.com/openai/InfoGAN, and code by pooleb@.
Args:
inputs: A 3-tuple of Tensors (unstructured_noise, categorical structured
noise, continuous structured noise). `inputs[0]` and `inputs[2]` must be
2D, and `inputs[1]` must be 1D. All must have the same first dimension.
categorical_dim: Dimensions of the incompressible categorical noise.
weight_decay: The value of the l2 weight decay.
is_training: If `True`, batch norm uses batch statistics. If `False`, batch
norm uses the exponential moving average collected from population
statistics.
Returns:
A generated image in the range [-1, 1].
"""
unstructured_noise, cat_noise, cont_noise = inputs
cat_noise_onehot = tf.one_hot(cat_noise, categorical_dim)
all_noise = tf.concat(
[unstructured_noise, cat_noise_onehot, cont_noise], axis=1)
return _generator_helper(all_noise, False, None, weight_decay, is_training)
_leaky_relu = lambda x: tf.nn.leaky_relu(x, alpha=0.01)
def _discriminator_helper(img, is_conditional, one_hot_labels, weight_decay):
"""Core MNIST discriminator.
This function is reused between the different GAN modes (unconditional,
conditional, etc).
Args:
img: Real or generated MNIST digits. Should be in the range [-1, 1].
is_conditional: Whether to condition on labels.
one_hot_labels: Labels to optionally condition the network on.
weight_decay: The L2 weight decay.
Returns:
Final fully connected discriminator layer. [batch_size, 1024].
"""
with tf.contrib.framework.arg_scope(
[layers.conv2d, layers.fully_connected],
activation_fn=_leaky_relu, normalizer_fn=None,
weights_regularizer=layers.l2_regularizer(weight_decay),
biases_regularizer=layers.l2_regularizer(weight_decay)):
net = layers.conv2d(img, 64, [4, 4], stride=2)
net = layers.conv2d(net, 128, [4, 4], stride=2)
net = layers.flatten(net)
if is_conditional:
net = tfgan.features.condition_tensor_from_onehot(net, one_hot_labels)
net = layers.fully_connected(net, 1024, normalizer_fn=layers.layer_norm)
return net
def unconditional_discriminator(img, unused_conditioning, weight_decay=2.5e-5):
"""Discriminator network on unconditional MNIST digits.
Args:
img: Real or generated MNIST digits. Should be in the range [-1, 1].
unused_conditioning: The TFGAN API can help with conditional GANs, which
would require extra `condition` information to both the generator and the
discriminator. Since this example is not conditional, we do not use this
argument.
weight_decay: The L2 weight decay.
Returns:
Logits for the probability that the image is real.
"""
net = _discriminator_helper(img, False, None, weight_decay)
return layers.linear(net, 1)
def conditional_discriminator(img, conditioning, weight_decay=2.5e-5):
"""Conditional discriminator network on MNIST digits.
Args:
img: Real or generated MNIST digits. Should be in the range [-1, 1].
conditioning: A 2-tuple of Tensors representing (noise, one_hot_labels).
weight_decay: The L2 weight decay.
Returns:
Logits for the probability that the image is real.
"""
_, one_hot_labels = conditioning
net = _discriminator_helper(img, True, one_hot_labels, weight_decay)
return layers.linear(net, 1)
def infogan_discriminator(img, unused_conditioning, weight_decay=2.5e-5,
categorical_dim=10, continuous_dim=2):
"""InfoGAN discriminator network on MNIST digits.
Based on a paper https://arxiv.org/abs/1606.03657, their code
https://github.com/openai/InfoGAN, and code by pooleb@.
Args:
img: Real or generated MNIST digits. Should be in the range [-1, 1].
unused_conditioning: The TFGAN API can help with conditional GANs, which
would require extra `condition` information to both the generator and the
discriminator. Since this example is not conditional, we do not use this
argument.
weight_decay: The L2 weight decay.
categorical_dim: Dimensions of the incompressible categorical noise.
continuous_dim: Dimensions of the incompressible continuous noise.
Returns:
Logits for the probability that the image is real, and a list of posterior
distributions for each of the noise vectors.
"""
net = _discriminator_helper(img, False, None, weight_decay)
logits_real = layers.fully_connected(net, 1, activation_fn=None)
# Recognition network for latent variables has an additional layer
with tf.contrib.framework.arg_scope([layers.batch_norm], is_training=False):
encoder = layers.fully_connected(net, 128, normalizer_fn=layers.batch_norm,
activation_fn=_leaky_relu)
# Compute logits for each category of categorical latent.
logits_cat = layers.fully_connected(
encoder, categorical_dim, activation_fn=None)
q_cat = ds.Categorical(logits_cat)
# Compute mean for Gaussian posterior of continuous latents.
mu_cont = layers.fully_connected(encoder, continuous_dim, activation_fn=None)
sigma_cont = tf.ones_like(mu_cont)
q_cont = ds.Normal(loc=mu_cont, scale=sigma_cont)
return logits_real, [q_cat, q_cont]
|
python
| 14 | 0.686089 | 80 | 37.783898 | 236 |
starcoderdata
|
// Copyright (C) 2020 即时通讯网(52im.net) &
// The RainbowChat Project. All rights reserved.
//
// 【本产品为著作权产品,合法授权后请放心使用,禁止外传!】
// 【本次授权给:
// 【授权寄送:
//
// 【本系列产品在国家版权局的著作权登记信息如下】:
// 1)国家版权局登记名(简称)和权证号:RainbowChat (证书号:软著登字第1220494号、登记号:2016SR041877)
// 2)国家版权局登记名(简称)和权证号:RainbowChat-Web(证书号:软著登字第3743440号、登记号:2019SR0322683)
// 3)国家版权局登记名(简称)和权证号:RainbowAV (证书号:软著登字第2262004号、登记号:2017SR676720)
// 4)国家版权局登记名(简称)和权证号:MobileIMSDK-Web(证书号:软著登字第2262073号、登记号:2017SR676789)
// 5)国家版权局登记名(简称)和权证号:MobileIMSDK (证书号:软著登字第1220581号、登记号:2016SR041964)
// * 著作权所有人:江顺/苏州网际时代信息科技有限公司
//
// 【违法或违规使用投诉和举报方式】:
// 联系邮件:
// 联系微信:hellojackjiang
// 联系QQ号:413980957
// 授权说明:http://www.52im.net/thread-1115-1-1.html
// 官方社区:http://www.52im.net
package com.eva.android.widget;
//import net.dmkx.mobi1.R;
//import com.eva.android.RHolder;
import android.app.Activity;
import android.content.Context;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.tang.R;
/**
*
* 一个自定义的通用标题栏实列类.
* 它常用于activity中用作自定义标题栏.
*
* 本自定义标题栏
* 这样的自定义方式
* 比没有什么优势),
* contentView上加上自定义标题栏组件
* 编程者完全定义,因而非常灵活——想怎么实现、实现成什么样都行,而且主流的像360通讯录等商业
* 程序都是这种方式(看来这种方式是经过实践检验可行的且是较优的),值得一试.
*
*
* @author
* @version 1.0
* @see "widget_title_bar.xml"
*/
public class CustomeTitleBar extends LinearLayout
{
/** 左返回按钮 */
private Button leftBackButton = null;
/** 左通用按钮 */
private Button leftGeneralButton = null;
/** 中间标题文本按钮 */
private TextView titleView = null;
/**
* 本组件仅用于为标题的显示留白占位(一般在没有左边返回按钮
时,显示本占位,否则不显示),用这个控件而不在代码中动态设置
titleView的marginLeft的目的是因为这样更简单实用 */
private View titleLeftGapView = null;
/** 右通用按钮 */
private Button rightGeneralButton = null;
/** 整个标题栏的总体布局 */
private FrameLayout mainLayout = null;
/** 左按钮区布局 */
private LinearLayout leftBtnLayout = null;
/** 中间标题展示区布局 */
private LinearLayout titleLayout = null;
/** 右按钮区布局 */
private LinearLayout rightBtnLayout = null;
public CustomeTitleBar(Context context)
{
this(context, null);
}
public CustomeTitleBar(final Context context, AttributeSet attrs)
{
super(context, attrs);
initViews();
initListeners();
}
/**
* 初始化UI组件.
* 默认 {@link #rightGeneralButton}是不可见的哦.
*/
protected void initViews()
{
if (isInEditMode()) { return;}
LayoutInflater.from(this.getContext()).inflate(R.layout.widget_title_bar
,this,true);
leftBackButton = (Button)this.findViewById(R.id.widget_title_left_backBtn);
leftGeneralButton = (Button)this.findViewById(R.id.widget_title_left_generalBtn);
titleView = (TextView)this.findViewById(R.id.widget_title_textView);
titleLeftGapView = this.findViewById(R.id.widget_title_leftGapView);
rightGeneralButton = (Button)this.findViewById(R.id.widget_title_right_generalBtn);
titleLayout = (LinearLayout)this.findViewById(R.id.widget_title_textLayout);
leftBtnLayout = (LinearLayout)this.findViewById(R.id.widget_title_leftBtnLayout);
rightBtnLayout = (LinearLayout)this.findViewById(R.id.widget_title_rightBtnLayout);
mainLayout = (FrameLayout)this.findViewById(R.id.widget_title_bar);
//默认右边的这个操作按钮是隐藏的,留作第3方调用时自行设置成Visible并使用之
// leftBackButton.setVisibility(View.GONE);
rightGeneralButton.setVisibility(View.GONE);
leftGeneralButton.setVisibility(View.GONE);
}
protected void initListeners()
{
leftBackButton.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v)
{
fireBack();
}
});
}
/**
*
* 点击返回按钮要调用的方法.
*
* 如果this.getContext()是Activity的子类则调用其finish方法实列返回(
* 相当于按了手机上的back键),否则本方法默认什么也不做.
*
*/
protected void fireBack()
{
if(this.getContext() instanceof Activity)
((Activity)this.getContext()).finish();
}
public Button getLeftBackButton()
{
return leftBackButton;
}
public TextView getTitleView()
{
return titleView;
}
public Button getRightGeneralButton()
{
return rightGeneralButton;
}
public Button getLeftGeneralButton()
{
return leftGeneralButton;
}
public void setText(String txt)
{
titleView.setText(txt);
}
public LinearLayout getLeftBtnLayout()
{
return leftBtnLayout;
}
public LinearLayout getRightBtnLayout()
{
return rightBtnLayout;
}
public LinearLayout getTitleLayout()
{
return titleLayout;
}
public FrameLayout getMainLayout()
{
return mainLayout;
}
/**
* 设置左边返回按钮的可见性。
*
* @param visible true表示可见,否则GONE
*/
public void setLeftBackButtonVisible(boolean visible)
{
this.leftBackButton.setVisibility(visible?View.VISIBLE:View.GONE);
this.titleLeftGapView.setVisibility(visible?View.GONE:View.VISIBLE);
}
// /**
// * 设置标题下方的立体阴影横线的可见性.
// *
// * @param visible true表示设置它可见,否则不可见(View.GONE)
// */
// public void setBottomShadowLineVisible(boolean visible)
// {
// ((View)this.findViewById(R.id.widget_title_bottomShadowLine_ll))
// .setVisibility(visible?View.VISIBLE:View.GONE);
// }
}
|
java
| 15 | 0.727838 | 106 | 25.558252 | 206 |
starcoderdata
|
using NUnit.Framework;
using Assert = ModestTree.Assert;
namespace Zenject.Tests.Bindings
{
[TestFixture]
public class TestFromIFactory2 : ZenjectUnitTestFixture
{
[Test]
public void Test1()
{
Container.BindFactory<int, Foo, Foo.Factory>().WithId("foo1")
.FromIFactory(x => x.To
Container.BindFactory<int, Foo, Foo.Factory>().WithId("foo2")
.FromIFactory(x => x.To
var factory1 = Container.ResolveId
var factory2 = Container.ResolveId
var foo1 = factory1.Create(5);
var foo2 = factory2.Create(2);
Assert.IsEqual(foo1.Value, "asdf");
Assert.IsEqual(foo1.Value2, 5);
Assert.IsEqual(foo2.Value, "zxcv");
Assert.IsEqual(foo2.Value2, 2);
}
public class Foo
{
public Foo(string value, int value2)
{
Value = value;
Value2 = value2;
}
public int Value2
{
get; private set;
}
public string Value
{
get; private set;
}
public class Factory : PlaceholderFactory<int, Foo>
{
}
}
public class FooFactory : IFactory<int, Foo>
{
readonly string _value;
readonly DiContainer _container;
public FooFactory(
DiContainer container,
string value)
{
_value = value;
_container = container;
}
public Foo Create(int value)
{
return _container.Instantiate object [] { value, _value });
}
}
}
}
|
c#
| 20 | 0.476237 | 88 | 25.581081 | 74 |
starcoderdata
|
ToLinkColourSequence(unsigned int toLinkId = 0) : toLink(toLinkId)
{
colorSequence.addColorDuration(TRAFFIC_COLOUR_GREEN, 0);
//A portion of the total time of the phase length is taken by amber
colorSequence.addColorDuration(TRAFFIC_COLOUR_AMBER, 3);
//All red moment usually takes 1 second
colorSequence.addColorDuration(TRAFFIC_COLOUR_RED, 1);
currColor = TRAFFIC_COLOUR_RED;
}
|
c++
| 6 | 0.669604 | 75 | 36.916667 | 12 |
inline
|
YUI.add('moodle-core-blocks', function(Y) {
var AJAXURL = '/lib/ajax/blocks.php',
CSS = {
BLOCK : 'block',
BLOCKREGION : 'block-region',
BLOCKADMINBLOCK : 'block_adminblock',
EDITINGMOVE : 'editing_move',
HEADER : 'header',
LIGHTBOX : 'lightbox',
REGIONCONTENT : 'region-content',
SKIPBLOCK : 'skip-block',
SKIPBLOCKTO : 'skip-block-to'
}
var DRAGBLOCK = function() {
DRAGBLOCK.superclass.constructor.apply(this, arguments);
};
Y.extend(DRAGBLOCK, M.core.dragdrop, {
skipnodetop : null,
skipnodebottom : null,
dragsourceregion : null,
initializer : function(params) {
// Set group for parent class
this.groups = ['block'];
this.samenodeclass = CSS.BLOCK;
this.parentnodeclass = CSS.REGIONCONTENT;
// Initialise blocks dragging
// Find all block regions on the page
var blockregionlist = Y.Node.all('div.'+CSS.BLOCKREGION);
if (blockregionlist.size() === 0) {
return false;
}
// See if we are missing either of block regions,
// if yes we need to add an empty one to use as target
if (blockregionlist.size() != this.get('regions').length) {
var blockregion = Y.Node.create('
.addClass(CSS.BLOCKREGION);
var regioncontent = Y.Node.create('
.addClass(CSS.REGIONCONTENT);
blockregion.appendChild(regioncontent);
var regionid = this.get_region_id(blockregionlist.item(0));
if (regionid === 'post') {
// pre block is missing, instert it before post
blockregion.setAttrs({id : 'region-pre'});
blockregionlist.item(0).insert(blockregion, 'before');
blockregionlist.unshift(blockregion);
} else {
// post block is missing, instert it after pre
blockregion.setAttrs({id : 'region-post'});
blockregionlist.item(0).insert(blockregion, 'after');
blockregionlist.push(blockregion);
}
}
blockregionlist.each(function(blockregionnode) {
// Setting blockregion as droptarget (the case when it is empty)
// The region-post (the right one)
// is very narrow, so add extra padding on the left to drop block on it.
var tar = new Y.DD.Drop({
node: blockregionnode.one('div.'+CSS.REGIONCONTENT),
groups: this.groups,
padding: '40 240 40 240'
});
// Make each div element in the list of blocks draggable
var del = new Y.DD.Delegate({
container: blockregionnode,
nodes: '.'+CSS.BLOCK,
target: true,
handles: ['.'+CSS.HEADER],
invalid: '.block-hider-hide, .block-hider-show, .moveto',
dragConfig: {groups: this.groups}
});
del.dd.plug(Y.Plugin.DDProxy, {
// Don't move the node at the end of the drag
moveOnEnd: false
});
del.dd.plug(Y.Plugin.DDWinScroll);
var blocklist = blockregionnode.all('.'+CSS.BLOCK);
blocklist.each(function(blocknode) {
var move = blocknode.one('a.'+CSS.EDITINGMOVE);
if (move) {
move.remove();
blocknode.one('.'+CSS.HEADER).setStyle('cursor', 'move');
}
}, this);
}, this);
},
get_block_id : function(node) {
return Number(node.get('id').replace(/inst/i, ''));
},
get_block_region : function(node) {
var region = node.ancestor('div.'+CSS.BLOCKREGION).get('id').replace(/region-/i, '');
if (Y.Array.indexOf(this.get('regions'), region) === -1) {
// Must be standard side-X
if (right_to_left()) {
if (region == 'post') {
region = 'pre';
} else if (region == 'pre') {
region = 'post';
}
}
return 'side-' + region;
}
// Perhaps custom region
return region;
},
get_region_id : function(node) {
return node.get('id').replace(/region-/i, '');
},
drag_start : function(e) {
// Get our drag object
var drag = e.target;
// Store the parent node of original drag node (block)
// we will need it later for show/hide empty regions
this.dragsourceregion = drag.get('node').ancestor('div.'+CSS.BLOCKREGION);
// Determine skipnodes and store them
if (drag.get('node').previous() && drag.get('node').previous().hasClass(CSS.SKIPBLOCK)) {
this.skipnodetop = drag.get('node').previous();
}
if (drag.get('node').next() && drag.get('node').next().hasClass(CSS.SKIPBLOCKTO)) {
this.skipnodebottom = drag.get('node').next();
}
},
drop_over : function(e) {
// Get a reference to our drag and drop nodes
var drag = e.drag.get('node');
var drop = e.drop.get('node');
// We need to fix the case when parent drop over event has determined
// 'goingup' and appended the drag node after admin-block.
if (drop.hasClass(this.parentnodeclass) && drop.one('.'+CSS.BLOCKADMINBLOCK) && drop.one('.'+CSS.BLOCKADMINBLOCK).next('.'+CSS.BLOCK)) {
drop.prepend(drag);
}
// Block is moved within the same region
// stop here, no need to modify anything.
if (this.dragsourceregion.contains(drop)) {
return false;
}
// TODO: Hiding-displaying block region only works for base theme blocks
// (region-pre, region-post) at the moment. It should be improved
// to work with custom block regions as well.
// TODO: Fix this for the case when user drag block towards empty section,
// then the section appears, then user chnages his mind and moving back to
// original section. The opposite section remains opened and empty.
var documentbody = Y.one('body');
// Moving block towards hidden region-content, display it
var regionname = this.get_region_id(this.dragsourceregion);
if (documentbody.hasClass('side-'+regionname+'-only')) {
documentbody.removeClass('side-'+regionname+'-only');
}
// Moving from empty region-content towards the opposite one,
// hide empty one (only for region-pre, region-post areas at the moment).
regionname = this.get_region_id(drop.ancestor('div.'+CSS.BLOCKREGION));
if (this.dragsourceregion.all('.'+CSS.BLOCK).size() == 0 && this.dragsourceregion.get('id').match(/(region-pre|region-post)/i)) {
if (!documentbody.hasClass('side-'+regionname+'-only')) {
documentbody.addClass('side-'+regionname+'-only');
}
}
},
drop_end : function(e) {
// clear variables
this.skipnodetop = null;
this.skipnodebottom = null;
this.dragsourceregion = null;
},
drag_dropmiss : function(e) {
// Missed the target, but we assume the user intended to drop it
// on the last last ghost node location, e.drag and e.drop should be
// prepared by global_drag_dropmiss parent so simulate drop_hit(e).
this.drop_hit(e);
},
drop_hit : function(e) {
var drag = e.drag;
// Get a reference to our drag node
var dragnode = drag.get('node');
var dropnode = e.drop.get('node');
// Amend existing skipnodes
if (dragnode.previous() && dragnode.previous().hasClass(CSS.SKIPBLOCK)) {
// the one that belongs to block below move below
dragnode.insert(dragnode.previous(), 'after');
}
// Move original skipnodes
if (this.skipnodetop) {
dragnode.insert(this.skipnodetop, 'before');
}
if (this.skipnodebottom) {
dragnode.insert(this.skipnodebottom, 'after');
}
// Add lightbox if it not there
var lightbox = M.util.add_lightbox(Y, dragnode);
// Prepare request parameters
var params = {
sesskey : M.cfg.sesskey,
courseid : this.get('courseid'),
pagelayout : this.get('pagelayout'),
pagetype : this.get('pagetype'),
subpage : this.get('subpage'),
action : 'move',
bui_moveid : this.get_block_id(dragnode),
bui_newregion : this.get_block_region(dropnode)
};
if (this.get('cmid')) {
params.cmid = this.get('cmid');
}
if (dragnode.next('.'+this.samenodeclass) && !dragnode.next('.'+this.samenodeclass).hasClass(CSS.BLOCKADMINBLOCK)) {
params.bui_beforeid = this.get_block_id(dragnode.next('.'+this.samenodeclass));
}
// Do AJAX request
Y.io(M.cfg.wwwroot+AJAXURL, {
method: 'POST',
data: params,
on: {
start : function(tid) {
lightbox.show();
},
success: function(tid, response) {
window.setTimeout(function(e) {
lightbox.hide();
}, 250);
try {
var responsetext = Y.JSON.parse(response.responseText);
if (responsetext.error) {
new M.core.ajaxException(responsetext);
}
} catch (e) {}
},
failure: function(tid, response) {
this.ajax_failure(response);
lightbox.hide();
}
},
context:this
});
}
}, {
NAME : 'core-blocks-dragdrop',
ATTRS : {
courseid : {
value : null
},
cmid : {
value : null
},
pagelayout : {
value : null
},
pagetype : {
value : null
},
subpage : {
value : null
},
regions : {
value : null
}
}
});
M.core_blocks = M.core_blocks || {};
M.core_blocks.init_dragdrop = function(params) {
new DRAGBLOCK(params);
}
}, '@VERSION@', {requires:['base', 'node', 'io', 'dom', 'dd', 'dd-scroll', 'moodle-core-dragdrop', 'moodle-core-notification']});
|
javascript
| 25 | 0.487627 | 148 | 38.585034 | 294 |
starcoderdata
|
<?php
namespace App\Models\DAO;
use App\Models\Entidades\EditalStatus;
use App\Models\Entidades\Usuario;
use App\Models\Entidades\Instituicao;
use Exception;
class EditalStatusDAO extends BaseDAO
{
public function listar(EditalStatus $editalStatus)
{
$stEdtCodigo = $editalStatus->getStEdtId();
$stEdtNome = $editalStatus->getStEdtNome();
/*$proposta = $editalStatus->getEdtProposta();
$numeroLicitacao = $editalStatus->getEdtNumero();
$status = $editalStatus->getEdtStatus();
$modalidade = $editalStatus->getEdtModalidade();
$representante = $editalStatus->getEdtRepresentante();*/
$SQL = " SELECT *
FROM editalStatus stedt
INNER JOIN instituicao i ON i.inst_id = stedt.stedt_instituicao
INNER JOIN usuarios u ON u.id = stedt.stedt_usuario ";
$where = Array();
if( $stEdtCodigo ){ $where[] = " stedt.stedt_id = {$stEdtCodigo}"; }
if( $stEdtNome ){ $where[] = " stedt.stedt_nome = '{$stEdtNome}'"; }
/* if( $proposta ){ $where[] = " stedt.edt_proposta = '{$proposta}'"; }
if( $status ){ $where[] = " stedt.edt_status = '{$status}'"; }
if( $representante ){ $where[] = " r.codRepresentante = {$representante}"; }
if( $modalidade ){ $where[] = " stedt.edt_modalidade = '{$modalidade}'"; }
if( $numeroLicitacao ){ $where[] = " stedt.edt_numero = '{$numeroLicitacao}'"; } */
if( sizeof( $where ) ){
$SQL .= ' WHERE '.implode( ' AND ',$where );
}else {
$SQL .= " ORDER BY stedt.stedt_id ASC ";
}
$resultado = $this->select($SQL);
$dados = $resultado->fetchAll();
$lista = [];
foreach ($dados as $dado) {
$editalStatus = new EditalStatus();
$editalStatus->setStEdtId($dado['stedt_id']);;
$editalStatus->setStEdtNome($dado['stedt_nome']);
$editalStatus->setStEdtObservacao($dado['stedt_observacao']);
$editalStatus->setStEdtDataCadastro($dado['stedt_datacadastro']);
$editalStatus->setStEdtDataAlteracao($dado['stedt_dataalteracao']);
$editalStatus->setStEdtInstituicao(new Instituicao());
$editalStatus->getStEdtInstituicao()->setInst_Id($dado['inst_id']);
$editalStatus->getStEdtInstituicao()->setInst_Nome($dado['inst_nome']);
$editalStatus->setStEdtUsuario(new Usuario());
$editalStatus->getStEdtUsuario()->setId($dado['id']);
$editalStatus->getStEdtUsuario()->setNome($dado['nome']);
$lista[] = $editalStatus;
}
return $lista;
}
public function salvar(EditalStatus $editalStatus)
{
try {
$stEdtNome = $editalStatus->getStEdtNome();
$stEdtObservacao = $editalStatus->getStEdtObservacao();
$stEdtUsuario = $editalStatus->getStEdtUsuario()->getId();
$stEdtInstituicao = $editalStatus->getStEdtInstituicao()->getInst_Id();
$stEdtDataAltercacao = $editalStatus->getStEdtDataAlteracao()->format('Y-m-d h:m:s');
$stEdtDataCadastro = $editalStatus->getStEdtDataCadastro()->format('Y-m-d h:m:s');
return $this->insert(
'editalStatus',
":nome, :observacao, :usuario, :instituicao, :datacadastro, :dataalteracao",
[
':nome' => $stEdtNome,
':observacao' => $stEdtObservacao,
':usuario' => $stEdtUsuario,
':instituicao' => $stEdtInstituicao,
':datacadastro' => $stEdtDataCadastro,
':dataalteracao' => $stEdtDataAltercacao
]
);
} catch (\Exception $e) {
throw new \Exception("Erro na gravação de dados. " . $e, 500);
}
}
public function atualizar(EditalStatus $editalStatus)
{
try {
$stEdtId = $editalStatus->getStEdtId();
$stEdtDataAltercacao = $editalStatus->getStEdtDataAlteracao()->format('Y-m-d h:m:s');
$stEdtDataCadastro = $editalStatus->getStEdtDataCadastro()->format('Y-m-d h:m:s');
$stEdtNome = $editalStatus->getStEdtNome();
$stEdtObservacao = $editalStatus->getStEdtObservacao();
$stEdtUsuario = $editalStatus->getStEdtUsuario()->getId();
$stEdtInstituicao = $editalStatus->getStEdtInstituicao()->getInst_Id();;
return $this->update(
'editalStatus',
"stedt_nome= :nome, stedt_observacao= :observacao, stedt_usuario= :usuario, stedt_instituicao= :instituicao,
stedt_datacadastro= :datacadastro, stedt_dataalteracao= :dataalteracao",
[
':edtId' => $stEdtId,
':nome' => $stEdtNome,
':observacao' => $stEdtObservacao,
':usuario' => $stEdtUsuario,
':instituicao' => $stEdtInstituicao,
':datacadastro' => $stEdtDataCadastro,
':dataalteracao' => $stEdtDataCadastro,
],
"stedt_id = :edtId"
);
} catch (\Exception $e) {
throw new \Exception("Erro na gravação de dados. ".$e, 500);
}
}
public function excluir(EditalStatus $editalStatus)
{
try {
$edtId = $editalStatus->getStEdtId();
$this->delete('editalStatus', "stedt_id = $edtId");
} catch (Exception $e) {
throw new \Exception("Erro ao excluir edital", 500);
}
}
}
|
php
| 15 | 0.467867 | 126 | 22.336879 | 282 |
starcoderdata
|
// DEPRECATED FILE!
// replaced by scitbx/array_family/accessors/c_grid_padded_periodic.h
#ifndef CCTBX_MAPTBX_ACCESSORS_C_GRID_PADDED_P1_H
#define CCTBX_MAPTBX_ACCESSORS_C_GRID_PADDED_P1_H
#include
#include
#include
namespace cctbx { namespace maptbx {
template <std::size_t Nd>
class c_grid_padded_p1;
template <>
class c_grid_padded_p1
{
public:
typedef af::tiny<int, 3> index_type;
typedef index_type::value_type index_value_type;
c_grid_padded_p1()
: all_(0,0,0),
focus_(0,0,0)
{}
c_grid_padded_p1(index_type const& all,
index_type const& focus)
: all_(all),
focus_(focus)
{}
template <typename FlexIndexType>
c_grid_padded_p1(af::flex_grid const& flex_g)
:
all_(af::adapt(flex_g.all()))
{
SCITBX_ASSERT(flex_g.is_0_based());
focus_ = index_type(af::adapt(flex_g.focus()));
}
af::flex_grid<>
as_flex_grid() const
{
return af::flex_grid<>(af::adapt(all_))
.set_focus(af::adapt(focus_));
}
std::size_t
size_1d() const
{
return all_[0] * all_[1] * all_[2];
}
index_type const&
all() const { return all_; }
index_type const&
focus() const { return focus_; }
std::size_t
focus_size_1d() const
{
return focus_[0] * focus_[1] * focus_[2];
}
bool is_padded() const
{
SCITBX_ASSERT(all_.all_ge(focus_));
return !all_.all_eq(focus_);
}
std::size_t operator()(index_type const& i) const
{
return (scitbx::math::mod_positive(i[0], focus_[0]) * all_[1]
+ scitbx::math::mod_positive(i[1], focus_[1])) * all_[2]
+ scitbx::math::mod_positive(i[2], focus_[2]);
}
std::size_t
operator()(index_value_type const& i0,
index_value_type const& i1,
index_value_type const& i2) const
{
return (scitbx::math::mod_positive(i0, focus_[0]) * all_[1]
+ scitbx::math::mod_positive(i1, focus_[1])) * all_[2]
+ scitbx::math::mod_positive(i2, focus_[2]);
}
protected:
index_type all_;
index_type focus_;
};
}} // namespace cctbx::maptbx
#endif // CCTBX_MAPTBX_ACCESSORS_C_GRID_PADDED_P1_H
|
c
| 17 | 0.545852 | 70 | 24.444444 | 99 |
starcoderdata
|
/**
* This function takes a validation function as an argument and returns a function that takes a request
* and a response object as arguments.
*
* The returned function calls the validation function with the request object and throws an error if
* the validation function returns an error.
*
* If the validation function doesn't throw an error, the returned function calls the next function in
* the middleware chain.
* @param validation - The validation function that will be run against the request.
* @returns A middleware function.
*/
function validate(validation) {
return (req, res, next) => {
try {
validation(req)
next()
} catch (error) {
next(error)
}
}
}
module.exports = {
validate
}
|
javascript
| 12 | 0.704698 | 103 | 27.653846 | 26 |
starcoderdata
|
def _get_bb_of_item(self, item, height, width):
''' Helper function to find the bounding box (bb) of an item in the xml file.
All the characters within the item are found and the left-most (min) and right-most (max + length)
are found.
The bounding box emcompasses the left and right most characters in the x and y direction.
Parameter
---------
item: xml.etree object for a word/line/form.
height: int
Height of the form to calculate percentages of bounding boxes
width: int
Width of the form to calculate percentages of bounding boxes
Returns
-------
list
The bounding box [x, y, w, h] in percentages that encompasses the item.
'''
character_list = [a for a in item.iter("cmp")]
if len(character_list) == 0: # To account for some punctuations that have no words
return None
x1 = np.min([int(a.attrib['x']) for a in character_list])
y1 = np.min([int(a.attrib['y']) for a in character_list])
x2 = np.max([int(a.attrib['x']) + int(a.attrib['width']) for a in character_list])
y2 = np.max([int(a.attrib['y']) + int(a.attrib['height'])for a in character_list])
x1 = float(x1) / width
x2 = float(x2) / width
y1 = float(y1) / height
y2 = float(y2) / height
bb = [x1, y1, x2 - x1, y2 - y1]
return bb
|
python
| 13 | 0.575569 | 106 | 39.277778 | 36 |
inline
|
fn converting() {
use palette::{FromColor, Hsl, IntoColor, Lch, Srgb};
let my_rgb = Srgb::new(0.8, 0.3, 0.3);
let mut my_lch = Lch::from_color(my_rgb);
my_lch.hue += 180.0;
let mut my_hsl: Hsl = my_lch.into_color();
my_hsl.lightness *= 0.6;
let my_new_rgb = Srgb::from_color(my_hsl);
// Write example image
display_colors(
"example-data/output/readme_converting.png",
&[DisplayType::Discrete(&[
my_rgb.into_format(),
Srgb::from_linear(my_lch.into_color()).into_format(),
Srgb::from_color(my_hsl).into_format(), // my_new_rgb is the same as my_hsl
])],
);
}
|
rust
| 18 | 0.565809 | 87 | 27.782609 | 23 |
inline
|
from flask import (
Blueprint, flash, g, redirect, render_template, request, session, url_for
)
from flaskr import db
blueprint = Blueprint('login', __name__, url_prefix='/auth')
@blueprint.before_app_request
def load_logged_in_user():
user_id = session.get('user_id')
g.user = None
if user_id is not None:
g.user = db.get_user('id', user_id)
@blueprint.route('/login')
def new():
return render_template('auth/login.html')
@blueprint.route('/login', methods=['POST'])
def create():
username = request.form['username']
password = request.form['password']
user = db.get_user('username', username)
error = _validate_form(user, password)
if error is not None:
flash(error)
return render_template('auth/login.html')
session.clear()
session['user_id'] = user['id']
return redirect(url_for('index'))
@blueprint.route('/logout')
def logout():
session.clear()
return redirect(url_for('index'))
def _validate_form(user, password):
if user is None:
return 'Incorrect username. Not registered?'
if not db.is_same_password(user, password):
return 'Incorrect password.'
|
python
| 11 | 0.647756 | 77 | 21.711538 | 52 |
starcoderdata
|
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('d3-scale'), require('d3-array')) :
typeof define === 'function' && define.amd ? define(['exports', 'd3-scale', 'd3-array'], factory) :
(factory((global.d3 = global.d3 || {}),global.d3Scale,global.d3Array));
}(this, function (exports,d3Scale,d3Array) { 'use strict';
function matrix(data) {
var matrix = {},
size = [],
padding,
cell,
rows,
columns;
matrix.data = function(_data) {
if (!arguments.length) return data;
data = _data;
return matrix;
}
matrix.sort = function(_fn) {
data.sort(_fn);
return matrix;
}
matrix.size = function(_size) {
if (!arguments.length) return size;
size = dimensions(_size);
return matrix;
}
matrix.padding = function(_padding) {
if (!arguments.length) return padding;
padding = _padding;
return matrix;
}
matrix.cell = function(_cell, _padding) {
if (!arguments.length) return cell;
cell = _cell;
matrix.padding(_padding);
return matrix;
}
matrix.layout = function() {
var each = cell + padding;
var numRows = (size[0] + padding) / each;
var numColumns = (size[1] + padding) / each;
var indiciesWidth = Array.apply(null, {length: numRows}).map(Number.call, Number);
var indiciesHeight = Array.apply(null, {length: numColumns}).map(Number.call, Number);
matrix.x = d3.scaleOrdinal(indiciesWidth.map(function(i) { return i * each; }))
matrix.y = d3.scaleOrdinal(indiciesHeight.map(function(i) { return i * each; }))
return matrix;
}
matrix.rows = function(_rows) {
if (!arguments.length) return rows;
rows = matrix.y.domain(data.map(_rows));
return matrix;
}
matrix.columns = function(_columns) {
if (!arguments.length) return columns;
columns = matrix.x.domain(data.map(_columns));
return matrix;
}
function dimensions(o) {
return (Array.isArray(o)) ? o : [o, o];
}
return matrix;
}
exports.matrix = matrix;
Object.defineProperty(exports, '__esModule', { value: true });
}));
|
javascript
| 23 | 0.588727 | 125 | 26.373494 | 83 |
starcoderdata
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.IO;
using System.Reflection;
using System.Runtime.InteropServices;
using Xunit;
namespace CopyConstructorMarshaler
{
class CopyConstructorMarshaler
{
static int Main(string[] args)
{
if(Environment.OSVersion.Platform != PlatformID.Win32NT || TestLibrary.Utilities.IsWindows7)
{
return 100;
}
try
{
Assembly ijwNativeDll = Assembly.Load("IjwCopyConstructorMarshaler");
Type testType = ijwNativeDll.GetType("TestClass");
object testInstance = Activator.CreateInstance(testType);
MethodInfo testMethod = testType.GetMethod("PInvokeNumCopies");
// PInvoke will copy twice. Once from argument to parameter, and once from the managed to native parameter.
Assert.Equal(2, (int)testMethod.Invoke(testInstance, null));
testMethod = testType.GetMethod("ReversePInvokeNumCopies");
// Reverse PInvoke will copy 3 times. Two are from the same paths as the PInvoke,
// and the third is from the reverse P/Invoke call.
Assert.Equal(3, (int)testMethod.Invoke(testInstance, null));
testMethod = testType.GetMethod("PInvokeNumCopiesDerivedType");
// PInvoke will copy twice. Once from argument to parameter, and once from the managed to native parameter.
Assert.Equal(2, (int)testMethod.Invoke(testInstance, null));
testMethod = testType.GetMethod("ReversePInvokeNumCopiesDerivedType");
// Reverse PInvoke will copy 3 times. Two are from the same paths as the PInvoke,
// and the third is from the reverse P/Invoke call.
Assert.Equal(3, (int)testMethod.Invoke(testInstance, null));
}
catch (Exception ex)
{
Console.WriteLine(ex);
return 101;
}
return 100;
}
[DllImport("kernel32.dll")]
static extern IntPtr LoadLibraryEx(string lpFileName, IntPtr hReservedNull, int dwFlags);
[DllImport("kernel32.dll")]
static extern IntPtr GetModuleHandle(string lpModuleName);
}
}
|
c#
| 17 | 0.620633 | 123 | 38.241935 | 62 |
starcoderdata
|
/**
* Created by Fredrik on 2017-03-21.
*/
window.sr = ScrollReveal({
reset: true
});
// Customizing a reveal set
sr.reveal('.featurette', {
duration: 1000
});
sr.reveal('.reveal', 100);
$("#current-year").html(new Date().getFullYear());
$('.nav a').on('click', function(){
$('.navbar-collapse').collapse('hide')
});
// Show and hide tabs in "Previous work" page
$(".expand").click(function (e) {
var target = $(this).data("target");
if ($(target).is(":visible")) {
$(this).html("show")
} else {
$(this).html("hide")
}
$(target).collapse("toggle");
});
// GitHub
var source = $("#github-template").html();
var template = Handlebars.compile(source);
$("#github-placeholder").html(template());
$.ajax({
url: "https:/api.github.com/users/heekzz/repos",
success: function (response) {
var context = {repos: response};
var html = template(context);
$("#github-placeholder").html(html);
}
});
|
javascript
| 14 | 0.580875 | 52 | 19.914894 | 47 |
starcoderdata
|
namespace Clix.QA.Selenium
{
using OpenQA.Selenium;
using OpenQA.Selenium.IE;
///
/// The web driver factory ie.
///
public class WebDriverFactoryIE : WebDriverFactory
{
///
/// Create an IE web driver.
///
///
/// The <see cref="IWebDriver"/>.
///
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification = "Reviewed.")]
protected override IWebDriver CreateWebDriver()
{
InternetExplorerOptions options = new InternetExplorerOptions();
options.BrowserCommandLineArguments += " -private";
options.AddAdditionalCapability("ignoreZoomSetting", true);
return new InternetExplorerDriver(
InternetExplorerDriverService.CreateDefaultService(),
options);
}
}
}
|
c#
| 13 | 0.704046 | 151 | 28.827586 | 29 |
starcoderdata
|
<?php
/*
* Copyright 2015 RhubarbPHP
*
* 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.
*/
namespace Rhubarb\Scaffolds\Authentication\Leaves;
use Rhubarb\Leaf\Controls\Common\Buttons\Button;
use Rhubarb\Leaf\Controls\Common\Text\TextBox;
use Rhubarb\Leaf\Views\View;
use Rhubarb\Scaffolds\Authentication\Settings\AuthenticationSettings;
class ResetPasswordView extends View
{
/**
* @var ResetPasswordModel
*/
protected $model;
public function createSubLeaves()
{
parent::createSubLeaves();
$this->registerSubLeaf(
new TextBox("username"),
new Button("ResetPassword", "Continue", function () {
$this->model->resetPasswordEvent->raise();
})
);
}
public function printViewContent()
{
if ($this->model->usernameNotFound){
print " the user `" . $this->model->username . "` couldn't be found.
check your typing and try again.
}
if ($this->model->sent){
print " you, a password reset invitation has been sent by the email address associated
with the username `" . $this->model->username . "`
the email arrives it should contain a link which will let you supply a new password.
have 24 hours to complete the reset before the invitation will expire.
href='/login/'>Login
return;
}
$this->layoutItemsWithContainer("Resetting your password",
"<div class='c-form__help'>
a password reset will send an email to the email address associated with your account
containing a link to reset your password.
on the link within 24 hours will allow you to enter a new password for your account.
[
$this->model->identityColumnName => "username",
"" => "
]
);
}
}
|
php
| 19 | 0.645136 | 106 | 32.44 | 75 |
starcoderdata
|
"""
71
medium
simplify path
"""
class Solution:
def simplifyPath(self, path: str) -> str:
# after seeing the solution
stack = []
for part in path.split("/"):
if part == "." or not part:
continue
elif part == "..":
if stack:
stack.pop()
else:
stack.append(part)
return "/" + "/".join(stack)
path1 = "/home/"
path2 = "/../"
path3 = "/home//foo/"
path4 = "/a/./b/../../c/"
path5 = "/../"
path6 = "/..."
path7 = "/a//b////c/d//././/.."
sol = Solution()
print(sol.simplifyPath(path7))
|
python
| 15 | 0.445122 | 45 | 14.255814 | 43 |
starcoderdata
|
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
namespace Box2DSharp.Common
{
[StructLayout(LayoutKind.Sequential)]
public struct FixedArray2
where T : unmanaged
{
public T Value0;
public T Value1;
public unsafe T* Values
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get
{
fixed (T* ptr = &Value0)
{
return ptr;
}
}
}
public unsafe T this[int index]
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => Values[index];
[MethodImpl(MethodImplOptions.AggressiveInlining)]
set => Values[index] = value;
}
}
[StructLayout(LayoutKind.Sequential)]
public struct FixedArray3
where T : unmanaged
{
public T Value0;
public T Value1;
public T Value2;
public unsafe T* Values
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get
{
fixed (T* ptr = &Value0)
{
return ptr;
}
}
}
public unsafe T this[int index]
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => Values[index];
[MethodImpl(MethodImplOptions.AggressiveInlining)]
set => Values[index] = value;
}
}
[StructLayout(LayoutKind.Sequential)]
public struct FixedArray4
where T : unmanaged
{
public T Value0;
public T Value1;
public T Value2;
public T Value3;
public unsafe T* Values
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get
{
fixed (T* ptr = &Value0)
{
return ptr;
}
}
}
public unsafe T this[int index]
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => Values[index];
[MethodImpl(MethodImplOptions.AggressiveInlining)]
set => Values[index] = value;
}
}
[StructLayout(LayoutKind.Sequential)]
public struct FixedArray8
where T : unmanaged
{
public T Value0;
public T Value1;
public T Value2;
public T Value3;
public T Value4;
public T Value5;
public T Value6;
public T Value7;
public unsafe T* Values
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get
{
fixed (T* ptr = &Value0)
{
return ptr;
}
}
}
public unsafe T this[int index]
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => Values[index];
[MethodImpl(MethodImplOptions.AggressiveInlining)]
set => Values[index] = value;
}
}
}
|
c#
| 14 | 0.498582 | 62 | 21.671429 | 140 |
starcoderdata
|
namespace DI10.Services
{
public interface IHandler
{
void Handle(TEvent args);
}
}
|
c#
| 6 | 0.635659 | 37 | 15.25 | 8 |
starcoderdata
|
# -*- coding: utf-8 -*-
"""
Created on Sat May 18 02:48:23 2019
@author: Administrator
"""
cityWhiteList = [
'三明市',
'上海',
'上饶市',
'东营市',
'丽水市',
'乐山市',
'九江市',
'迪庆藏族自治州',
'云浮市',
'仙桃市',
'佛山市',
'佳木斯市',
'保定市',
'兰州市',
'乌兰察布市',
'乌海市',
'呼和浩特市',
'呼伦贝尔市',
'鄂尔多斯市',
'锡林郭勒盟',
'阿拉善盟',
'凉山彝族自治州',
'北京',
'南京市',
'南充市',
'南昌市',
'南通市',
'厦门市',
'台州市',
'合肥市',
'吉安市',
'吉林市',
'哈尔滨市',
'商洛市',
'大庆市',
'大连市',
'南开区',
'天津',
'太原市',
'银川市',
'宁波市',
'定西市',
'宜昌市',
'宿州市',
'巢湖市',
'平顶山市',
'广州市',
'北海市',
'南宁市',
'柳州市',
'河池市',
'贵港市',
'钦州市',
'延安市',
'张掖市',
'德州市',
'惠州市',
'成都市',
'抚州市',
'新乡市',
'乌鲁木齐市',
'哈萨克自治州',
'石河子市',
'昆明市',
'晋中市',
'杭州市',
'株洲市',
'武汉市',
'汕尾市',
'江门市',
'沈阳市',
'泉州市',
'泰安市',
'泰州市',
'洛阳市',
'济南市',
'深圳市',
'温州市',
'澳门',
'香港',
'湖州市',
'湘潭市',
'湛江市',
'滁州市',
'玉溪市',
'白城市',
'白山市',
'石家庄市',
'福州市',
'秦皇岛市',
'绍兴市',
'绥化市',
'聊城市',
'舟山市',
'苏州市',
'荆州市',
'莆田市',
'葫芦岛市',
'衢州市',
'襄樊市',
'西宁市',
'西安市',
'山南地区',
'拉萨市',
'昌都地区',
'林芝地区',
'那曲地区',
'毕节地区',
'黔南布依族苗族自治州',
'贵阳市',
'赣州市',
'辽源市',
'辽阳市',
'运城市',
'连云港市',
'遵义市',
'邯郸市',
'郑州市',
'郴州市',
'酒泉市',
'万州区',
'开县',
'重庆',
'金华市',
'铜川市',
'铜陵市',
'锦州市',
'镇江市',
'长春市',
'长沙市',
'阜新市',
'陇南市',
'青岛市',
'海东地区',
'海南藏族自治州',
'鞍山市',
'马鞍山市',
'驻马店市',
'鹤岗市',
'鹰潭市',
'黄山市',
'黄石市',
'龙岩市'
]
majorWhiteList=[
'中国工程院院士',
'文学',
'中国科学院院士',
'工商管理',
'高级编辑',
'中文',
'信息论',
'内燃机',
'军事学',
'军人',
'医学',
'历史学',
'合同战役指挥',
'哲学',
'经济师',
'高级工程师',
'工学',
'工程硕士',
'建筑学',
'思想政治',
'战略学',
'挪威语',
'政治学',
'文哲史',
'水工',
'法学',
'物理学',
'理学',
'电子',
'社会主义专业',
'管理学',
'经济学',
'经济管理',
'自动化',
'行政管理',
'财政学',
'轻工二系硅酸盐专业',
'马克思主义',
]
|
python
| 5 | 0.37797 | 35 | 7.512821 | 195 |
starcoderdata
|
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ParameterRequirementMismatchError = void 0;
var tslib_1 = require("tslib");
var ParameterRequirementMismatchError = /** @class */ (function (_super) {
tslib_1.__extends(ParameterRequirementMismatchError, _super);
function ParameterRequirementMismatchError(_command, _paramName, _paramSpec, _givenValue) {
var _this = _super.call(this, "required parameter \"" + _paramName + "\" did not validate against " + (_paramSpec.type || 'regex') + " validation: \"" + _givenValue + "\"") || this;
_this._command = _command;
_this._paramName = _paramName;
_this._paramSpec = _paramSpec;
_this._givenValue = _givenValue;
Object.setPrototypeOf(_this, ParameterRequirementMismatchError.prototype);
if (Error.captureStackTrace) {
Error.captureStackTrace(_this, ParameterRequirementMismatchError);
}
return _this;
}
Object.defineProperty(ParameterRequirementMismatchError.prototype, "command", {
get: function () {
return this._command;
},
enumerable: false,
configurable: true
});
Object.defineProperty(ParameterRequirementMismatchError.prototype, "paramName", {
get: function () {
return this._paramName;
},
enumerable: false,
configurable: true
});
Object.defineProperty(ParameterRequirementMismatchError.prototype, "paramSpec", {
get: function () {
return this._paramSpec;
},
enumerable: false,
configurable: true
});
Object.defineProperty(ParameterRequirementMismatchError.prototype, "givenValue", {
get: function () {
return this._givenValue;
},
enumerable: false,
configurable: true
});
return ParameterRequirementMismatchError;
}(Error));
exports.ParameterRequirementMismatchError = ParameterRequirementMismatchError;
|
javascript
| 21 | 0.647529 | 189 | 39.877551 | 49 |
starcoderdata
|
using System;
namespace VddsMediaNet.Exceptions
{
public class AlreadyRegisteredException : Exception
{
}
}
|
c#
| 5 | 0.733333 | 55 | 14.125 | 8 |
starcoderdata
|
/* @flow */
import React, {useState} from 'react';
import {Text, TouchableOpacity} from 'react-native';
import {HIT_SLOP} from '../common-styles/button';
import {IconCaretDownUp} from '../icon/icon';
import styles from './details.styles';
import type {Node} from 'React';
import type {TextStyleProp} from 'react-native/Libraries/StyleSheet/StyleSheet';
type Props = {
renderer: () => any,
style?: TextStyleProp,
title?: ?string,
toggler?:?string,
}
const Details = (props: Props): Node => {
const {toggler = 'Details'} = props;
const [expanded, updateExpanded] = useState(false);
return (
<>
<TouchableOpacity
testID="details"
style={styles.button}
onPress={() => updateExpanded(!expanded)}
hitSlop={HIT_SLOP}
>
{!!props.title && <Text style={styles.title}>
{`${props.title}: `}
<Text style={[styles.toggle, props.style]}>
<IconCaretDownUp size={12} isDown={!expanded} style={styles.toggleIcon} color={props?.style?.color || styles.toggle.color}/>
<Text style={styles.toggleText}>{' '}{toggler}
{expanded && props.renderer()}
);
};
export default (React.memo React$AbstractComponent<Props, mixed>);
|
javascript
| 16 | 0.623476 | 134 | 26.333333 | 48 |
starcoderdata
|
import { orderBy } from 'lodash';
import { state } from 'cerebral';
/**
* gets the most recent message from state.messageDetail
*
* @param {object} providers the providers object
* @param {object} providers.get the cerebral get method
* @returns {object} object containing mostRecentMessage
*/
export const getMostRecentMessageInThreadAction = ({ get }) => {
const messageDetail = get(state.messageDetail);
const sortedMessages = orderBy(messageDetail, 'createdAt', 'desc');
return { mostRecentMessage: sortedMessages[0] };
};
|
javascript
| 11 | 0.730627 | 69 | 30.882353 | 17 |
starcoderdata
|
/* $Id: VBoxVideoIPRT.h 71590 2018-03-31 18:34:28Z vboxsync $ */
/*
* Copyright (C) 2017 Oracle Corporation
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following
* conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*/
/* In builds inside of the VirtualBox source tree we override the default
* VBoxVideoIPRT.h using -include, therefore this define must match the one
* there. */
#ifndef ___VBox_Graphics_VBoxVideoIPRT_h
#define ___VBox_Graphics_VBoxVideoIPRT_h
# include "VBoxVideoErr.h"
#ifndef __cplusplus
typedef enum
{
false = 0,
true
} bool;
# define RT_C_DECLS_BEGIN
# define RT_C_DECLS_END
#else
# define RT_C_DECLS_BEGIN extern "C" {
# define RT_C_DECLS_END }
#endif
#if defined(IN_XF86_MODULE) && !defined(NO_ANSIC)
# ifdef __cplusplus
/* xf86Module.h redefines this. */
# define NULL 0
# endif
RT_C_DECLS_BEGIN
# include "xf86_ansic.h"
RT_C_DECLS_END
#endif /* defined(IN_XF86_MODULE) && !defined(NO_ANSIC) */
#define __STDC_LIMIT_MACROS /* define *INT*_MAX on C++ too. */
#include "compiler.h" /* Can pull in Must come after xf86_ansic.h on XFree86. */
#include
#include
#if defined(IN_XF86_MODULE) && !defined(NO_ANSIC)
/* XFree86 did not have these. Not that I care much for micro-optimisations
* in most cases anyway. */
# define _X_LIKELY(x) (x)
# define _X_UNLIKELY(x) (x)
# ifndef offsetof
# define offsetof(type, member) ( (int)(uintptr_t)&( ((type *)(void *)0)->member) )
# endif
#else /* !(defined(IN_XF86_MODULE) && !defined(NO_ANSIC)) */
# include
# include
# include
#endif /* !(defined(IN_XF86_MODULE) && !defined(NO_ANSIC)) */
RT_C_DECLS_BEGIN
extern int RTASSERTVAR[1];
RT_C_DECLS_END
#define AssertCompile(expr) \
extern int RTASSERTVAR[1] __attribute__((__unused__)), \
RTASSERTVAR[(expr) ? 1 : 0] __attribute__((__unused__))
#define AssertCompileSize(type, size) \
AssertCompile(sizeof(type) == (size))
#define AssertPtrNullReturnVoid(a) do { } while(0)
#if !defined(IN_XF86_MODULE) && defined(DEBUG)
# include
# define Assert assert
# define AssertFailed() assert(0)
# define AssertMsg(expr, msg) \
do { \
if (!(expr)) xf86ErrorF msg; \
assert((expr)); \
} while (0)
# define AssertPtr assert
# define AssertPtrReturn(pv, rcRet) do { assert(pv); if (pv) {} else return(rcRet); } while(0)
# define AssertRC(expr) assert (!expr)
#else
# define Assert(expr) do { } while(0)
# define AssertFailed() do { } while(0)
# define AssertMsg(expr, msg) do { } while(0)
# define AssertPtr(ptr) do { } while(0)
# define AssertPtrReturn(pv, rcRet) do { if (pv) {} else return(rcRet); } while(0)
# define AssertRC(expr) do { } while(0)
#endif
#define DECLCALLBACK(type) type
#define DECLCALLBACKMEMBER(type, name) type (* name)
#if __GNUC__ >= 4
# define DECLHIDDEN(type) __attribute__((visibility("hidden"))) type
#else
# define DECLHIDDEN(type) type
#endif
#define DECLINLINE(type) static __inline__ type
#define _1K 1024
#define ASMCompilerBarrier mem_barrier
#define RT_BIT(bit) ( 1U << (bit) )
#define RT_BOOL(Value) ( !!(Value) )
#define RT_BZERO(pv, cb) do { memset((pv), 0, cb); } while (0)
#define RT_CLAMP(Value, Min, Max) ( (Value) > (Max) ? (Max) : (Value) < (Min) ? (Min) : (Value) )
#define RT_ELEMENTS(aArray) ( sizeof(aArray) / sizeof((aArray)[0]) )
#define RTIOPORT unsigned short
#define RT_NOREF(...) (void)(__VA_ARGS__)
#define RT_OFFSETOF(type, member) offsetof(type, member)
#define RT_ZERO(Obj) RT_BZERO(&(Obj), sizeof(Obj))
#define VALID_PTR(ptr) ( (uintptr_t)(ptr) + 0x1000U >= 0x2000U )
#ifndef INT16_C
# define INT16_C(Value) (Value)
#endif
#ifndef UINT16_C
# define UINT16_C(Value) (Value)
#endif
#ifndef INT32_C
# define INT32_C(Value) (Value ## U)
#endif
#ifndef UINT32_C
# define UINT32_C(Value) (Value ## U)
#endif
#define RT_UNTRUSTED_GUEST
#define RT_UNTRUSTED_VOLATILE_GUEST volatile
#define RT_UNTRUSTED_HOST
#define RT_UNTRUSTED_VOLATILE_HOST volatile
#define RT_UNTRUSTED_HSTGST
#define RT_UNTRUSTED_VOLATILE_HSTGST volatile
#define likely _X_LIKELY
#define unlikely _X_UNLIKELY
/**
* A point in a two dimentional coordinate system.
*/
typedef struct RTPOINT
{
/** X coordinate. */
int32_t x;
/** Y coordinate. */
int32_t y;
} RTPOINT;
/**
* Rectangle data type, double point.
*/
typedef struct RTRECT
{
/** left X coordinate. */
int32_t xLeft;
/** top Y coordinate. */
int32_t yTop;
/** right X coordinate. (exclusive) */
int32_t xRight;
/** bottom Y coordinate. (exclusive) */
int32_t yBottom;
} RTRECT;
/**
* Rectangle data type, point + size.
*/
typedef struct RTRECT2
{
/** X coordinate.
* Unless stated otherwise, this is the top left corner. */
int32_t x;
/** Y coordinate.
* Unless stated otherwise, this is the top left corner. */
int32_t y;
/** The width.
* Unless stated otherwise, this is to the right of (x,y) and will not
* be a negative number. */
int32_t cx;
/** The height.
* Unless stated otherwise, this is down from (x,y) and will not be a
* negative number. */
int32_t cy;
} RTRECT2;
/**
* The size of a rectangle.
*/
typedef struct RTRECTSIZE
{
/** The width (along the x-axis). */
uint32_t cx;
/** The height (along the y-axis). */
uint32_t cy;
} RTRECTSIZE;
/** @name Port I/O helpers
* @{ */
/** Write an 8-bit value to an I/O port. */
#define VBVO_PORT_WRITE_U8(Port, Value) \
outb(Port, Value)
/** Write a 16-bit value to an I/O port. */
#define VBVO_PORT_WRITE_U16(Port, Value) \
outw(Port, Value)
/** Write a 32-bit value to an I/O port. */
#define VBVO_PORT_WRITE_U32(Port, Value) \
outl(Port, Value)
/** Read an 8-bit value from an I/O port. */
#define VBVO_PORT_READ_U8(Port) \
inb(Port)
/** Read a 16-bit value from an I/O port. */
#define VBVO_PORT_READ_U16(Port) \
inw(Port)
/** Read a 32-bit value from an I/O port. */
#define VBVO_PORT_READ_U32(Port) \
inl(Port)
/** @} */
#endif
|
c
| 7 | 0.65571 | 111 | 29.685345 | 232 |
starcoderdata
|
package com.dexter.tong.chapter02;
import com.dexter.tong.common.LinkedListNode;
import org.junit.Test;
import java.util.Arrays;
import java.util.List;
import static org.junit.Assert.*;
public class Question05Test {
@Test
public void reverseSumList_should_sum_two_lists() {
LinkedListNode numberA = utils.createLinkedList(new Integer[]{2, 5, 3}); // 352
LinkedListNode numberB = utils.createLinkedList(new Integer[]{9, 1, 2}); // + 219
List expected = Arrays.asList(1, 7, 5); // = 571
assertEquals(expected, Question05.reverseSumList(numberA, numberB).asList());
}
@Test
public void reverseSumList_should_sum_two_lists_with_carryover() {
LinkedListNode numberA = utils.createLinkedList(new Integer[]{2, 4, 6}); // 642
LinkedListNode numberB = utils.createLinkedList(new Integer[]{5, 1, 8}); // + 815
List expected = Arrays.asList(7, 5, 4, 1); // = 1457
assertEquals(expected, Question05.reverseSumList(numberA, numberB).asList());
}
@Test
public void reverseSumList_should_sum_two_lists_with_different_lengths() {
LinkedListNode numberA = utils.createLinkedList(new Integer[]{0, 9, 1}); // 190
LinkedListNode numberB = utils.createLinkedList(new Integer[]{0, 4}); // + 40
List expected = Arrays.asList(0, 3, 2); // = 230
assertEquals(expected, Question05.reverseSumList(numberA, numberB).asList());
}
@Test
public void forwardSumList_should_sum_two_lists() {
LinkedListNode numberA = utils.createLinkedList(new Integer[]{3, 5, 2}); // 352
LinkedListNode numberB = utils.createLinkedList(new Integer[]{2, 1, 9}); // + 219
List expected = Arrays.asList(5, 7, 1); // = 571
assertEquals(expected, Question05.forwardSumList(numberA, numberB).asList());
}
@Test
public void forwardSumList_should_sum_two_lists_with_carryover() {
LinkedListNode numberA = utils.createLinkedList(new Integer[]{6, 4, 2}); // 642
LinkedListNode numberB = utils.createLinkedList(new Integer[]{8, 1, 5}); // + 815
List expected = Arrays.asList(1, 4, 5, 7); // = 1457
assertEquals(expected, Question05.forwardSumList(numberA, numberB).asList());
}
@Test
public void forwardSumList_should_sum_two_lists_with_different_lengths() {
LinkedListNode numberA = utils.createLinkedList(new Integer[]{1, 9, 0}); // 190
LinkedListNode numberB = utils.createLinkedList(new Integer[]{4, 0}); // + 40
List expected = Arrays.asList(2, 3, 0); // = 230
assertEquals(expected, Question05.forwardSumList(numberA, numberB).asList());
}
}
|
java
| 9 | 0.619576 | 101 | 50.770492 | 61 |
starcoderdata
|
#include<bits/stdc++.h>
using namespace std;
int main(){
int n,i,j,n3,n5,n7,ans=0;
cin>>n;
for(i=357;i<=min(n,77777753);i++){
n3=0;n5=0;n7=0;
j=i;
while(j>0){
if(j%10==3) n3++;
else if(j%10==5) n5++;
else if(j%10==7) n7++;
else break;
j/=10;
}
if(j==0&&n3>0&&n5>0&&n7>0) ans++;
}
for(i=333333357;i<=min(n,777777753);i++){
n3=0;n5=0;n7=0;
j=i;
while(j>0){
if(j%10==3) n3++;
else if(j%10==5) n5++;
else if(j%10==7) n7++;
else break;
j/=10;
}
if(j==0&&n3>0&&n5>0&&n7>0) ans++;
}
cout<<ans<<endl;
}
|
c++
| 15 | 0.453947 | 43 | 18.645161 | 31 |
codenet
|
@{
Check.User(new[] {Can.EditUser, Can.ActivateUser, Can.DeleteUser});
var db = Database.Open((string) App.Database);
var commandText = "SELECT Users.UserId, UserName, IsConfirmed FROM Users INNER JOIN webpages_Membership ON Users.UserId = webpages_Membership.UserId";
var users = db.Query(commandText);
var grid = new WebGrid(users, canPage: false, canSort: false);
}
Users
@grid.GetHtml("table",
columns: grid.Columns(
grid.Column("UserName", "User"),
grid.Column("", format: @
@if (Permissions.User(Can.EditUser)) {
<a href="~/Admin/Users/EditUser/@item.UserId">Edit
}
@if (Permissions.User(Can.EditUser) && (Permissions.User(Can.DeleteUser) || Permissions.User(Can.ActivateUser))) {
@: |
}
@if (Permissions.User(Can.DeleteUser)) {
<a href="~/Admin/Users/DeleteUser/@item.UserId">Delete
}
@if (Permissions.User(Can.DeleteUser) && Permissions.User(Can.ActivateUser)) {
@: |
}
@if (Permissions.User(Can.ActivateUser)) {
if (item.IsConfirmed == true) {
<a href="~/Admin/Users/ActivateUser/@item.UserId/False">Deactivate
}
else {
<a href="~/Admin/Users/ActivateUser/@item.UserId/True">Reactivate
}
}
)
)
|
c#
| 16 | 0.413607 | 154 | 50.1 | 40 |
starcoderdata
|
#ifndef _CUSTOM_MESH_SHADER_H_
#define _CUSTOM_MESH_SHADER_H_
#include "renderObject.h"
int createCustomMeshRenderer();
void releaseCustomMeshRenderer();
void beginCustomMeshRenderer();
void endCustomMeshRenderer();
void drawMeshRenderObject(const RENDER_OBJECT *pObj, const FLOAT_MATRIX *pVP);
#endif
|
c
| 7 | 0.798246 | 78 | 21.8 | 15 |
starcoderdata
|
public void Write(bool s, int p)
{
//Note: using string interpolation in the assert msg caused a major bottleneck in debug builds...
Debug.Assert(p >= 0 && p < K, "Probability must be >= 0 and < K");
Debug.Assert(s || p != 0, "Probability cannot be 0 when s == 0");
Write(s, (uint)p);
}
|
c#
| 10 | 0.538462 | 109 | 43 | 8 |
inline
|
#pragma once
#ifndef CPU_H
#define CPU_H
#include
#define EL0 0
#define EL1 1
#define EL2 2
#define EL3 3
/*
//exception flags ?
enum class cpu_irq_flag_t: uint32_t
{
// IRQ_FLAG_T = 1 <<5 //reserved (RESERVED) aarch64 used for exception from aarch32//
IRQ_FLAG_F = 1<<6, //FIQ
IRQ_FLAG_I = 1<<7, //IRQ
IRQ_FLAG_A = 1<<8, //SError
IRQ_FLAG_D = 1<<9 //Endianess in AARCH32 and Debug exception mask in aarch64
};// cpu_irq_flag_t;
*/
#if defined(__cplusplus)
extern "C" {
#endif
void cpu_fiq_enable();
void cpu_irq_enable();
void cpu_serror_enable();
void cpu_debug_enable();
void cpu_fiq_disable();
void cpu_irq_disable();
void cpu_serror_disable();
void cpu_debug_disable();
void cpu_disable_all_exceptions();
void cpu_wfi();
void cpu_disable_exceptions(uint32_t irq);
void cpu_enable_exceptions(uint32_t irq);
uint32_t cpu_get_current_el();
void cpu_print_current_el();
#if defined(__cplusplus)
}
#endif
#endif //CPU_H
|
c
| 9 | 0.637438 | 86 | 16.20339 | 59 |
starcoderdata
|
/**
*
*/
package org.iplantc.service.jobs.managers.launchers;
import org.apache.log4j.Logger;
import org.iplantc.service.apps.exceptions.UnknownSoftwareException;
import org.iplantc.service.apps.model.Software;
import org.iplantc.service.jobs.exceptions.MissingSoftwareDependencyException;
import org.iplantc.service.jobs.exceptions.SoftwareUnavailableException;
import org.iplantc.service.jobs.managers.JobManager;
import org.iplantc.service.jobs.model.Job;
import org.iplantc.service.systems.exceptions.SystemUnavailableException;
import org.iplantc.service.systems.exceptions.SystemUnknownException;
import org.iplantc.service.systems.model.ExecutionSystem;
import org.iplantc.service.systems.model.StorageSystem;
import org.iplantc.service.systems.model.enumerations.ExecutionType;
import org.iplantc.service.transfer.RemoteDataClient;
/**
* @author dooley
*
*/
public class JobLauncherFactory
{
private static final Logger log = Logger.getLogger(JobLauncherFactory.class);
protected JobManager jobManager = null;
/**
* Basic getter for job manager instance. Useful for testing
* @return JobManager instance
*/
protected JobManager getJobManager() {
if (jobManager == null) {
jobManager = new JobManager();
}
return jobManager;
}
/**
* Returns an intance of a {@link JobLauncher} based on the parameters of the job.
* Prior to creating the {@link JobLauncher}, this method validates the availability
* of the {@link Software} and {@link ExecutionSystem}.
*
* @param job the job for which to create a {@link JobLauncher}
* @throws SystemUnavailableException when the job {@link ExecutionSystem} or {@link Software#getStorageSystem()} is disabled or has a non-UP status.
* @throws SystemUnknownException when the job {@link ExecutionSystem} or {@link Software#getStorageSystem()}does not exist
* @throws SoftwareUnavailableException when the {@link Software} is unavailable due to explicit or implicit reasons
* @throws UnknownSoftwareException when the {@link Software} has been deleted
*/
public JobLauncher getInstance(Job job) throws SystemUnknownException, SystemUnavailableException, UnknownSoftwareException, SoftwareUnavailableException
{
Software software = getJobManager().getJobSoftware(job.getSoftwareName());
// Fetch the execution system info and ensure it's available.
ExecutionSystem executionSystem = (ExecutionSystem) getJobManager().getAvailableSystem(job.getSystem());
assertSoftwareExecutionTypeMatchesSystem(executionSystem, software);
assertSoftwareWrapperTemplateExists(software);
// now submit the job to the target system using the correct launcher.
if (software.getExecutionType().equals(ExecutionType.HPC)){
return new HPCLauncher(job, software, executionSystem);
}else if (software.getExecutionType().equals(ExecutionType.CONDOR)) {
return new CondorLauncher(job, software, executionSystem);
} else {
return new CLILauncher(job, software, executionSystem);
}
}
/**
* Verifies that the {@link Software#getExecutionType()} is supported by the system matching the
* {@code executionSystemId}. An exception is thrown if they do not line up.
*
* @param executionSystem the system whose {@link ExecutionSystem#getExecutionType()} will be checked
* for compatibility with the {@link Software#getExecutionType()}
* @param software the {@link Software} whose {@link ExecutionType} will be checked
* @throws SystemUnavailableException when the job {@link ExecutionSystem} is disabled or has a non-UP status.
* @throws SystemUnknownException when the job {@link ExecutionSystem} does not exist
* @throws SoftwareUnavailableException when the execution system cannot support the {@link ExecutionType}
* required by the {@link Software}
*/
protected void assertSoftwareExecutionTypeMatchesSystem(ExecutionSystem executionSystem, Software software) throws SystemUnavailableException, SystemUnknownException, SoftwareUnavailableException {
// ensure the execution system supports the execution type configured for the app. This may change over time,
// so we ensure it's still possible to do so here.
if (!software.getExecutionType().getCompatibleExecutionTypes().contains(executionSystem.getExecutionType())) {
throw new SoftwareUnavailableException("The software requested by for this job requires an execution type of " +
software.getExecutionType() + ", but the requested execution system, " + executionSystem.getSystemId() +
", has an incompatible execution type, " + executionSystem.getExecutionType() +
", which prevents this job from being launched.");
}
}
/**
* Ensures the {@link Software#getStorageSystem()} is available and has the {@link Software#getExecutablePath()}
* present.
* @param software the application whose deployment assets will be validated
* @throws SystemUnknownException if the {@link Software#getStorageSystem()} does not exist.
* @throws SystemUnavailableException if the {@link Software#getStorageSystem()} is not available and up.
* @throws SoftwareUnavailableException if the {@link Software#getExecutablePath()} is not present on the remote system.
*/
protected void assertSoftwareWrapperTemplateExists(Software software) throws SystemUnknownException, SystemUnavailableException, SoftwareUnavailableException {
// if the software assets are missing...
RemoteDataClient remoteDataClient = null;
try {
StorageSystem storageSystem = (StorageSystem) getJobManager().getAvailableSystem(software.getStorageSystem().getSystemId());
remoteDataClient = storageSystem.getRemoteDataClient();
remoteDataClient.authenticate();
if (software.isPubliclyAvailable()) {
if (!remoteDataClient.doesExist(software.getDeploymentPath())) {
throw new MissingSoftwareDependencyException("Public app assets were not present at agave://" +
remoteDataClient.getHost() + ":" +
software.getDeploymentPath() + ". Job cannot run until the assets are restored.");
}
} else if (!remoteDataClient.doesExist(software.getDeploymentPath() + '/' + software.getExecutablePath())) {
throw new MissingSoftwareDependencyException("App wrapper template expected at agave://" +
remoteDataClient.getHost() + ":" + software.getDeploymentPath() + '/' +
software.getExecutablePath() + ". Job cannot run until the assets are restored.");
}
} catch (SystemUnknownException e) {
throw new SystemUnknownException("No system found matching id of app deployment system, " +
software.getStorageSystem().getSystemId() + ".");
} catch (SystemUnavailableException e) {
throw new SystemUnavailableException("App deployment system " + software.getStorageSystem().getSystemId() +
" is currently unavailable.");
} catch (MissingSoftwareDependencyException e) {
throw new SoftwareUnavailableException(e);
} catch (Throwable e) {
throw new SoftwareUnavailableException("Unable to verify the availability of the wrapper " +
"template at agave://" + software.getStorageSystem().getStorageConfig().getHost() + ":" +
software.getDeploymentPath() + '/' + software.getExecutablePath() +
".Job cannot run until the assets are restored.", e);
}
finally {
try { if (remoteDataClient != null) remoteDataClient.disconnect(); } catch(Exception ignored) {}
}
}
}
|
java
| 21 | 0.760514 | 198 | 50.713287 | 143 |
starcoderdata
|
#region Copyright Syncfusion Inc. 2001-2020.
// Copyright Syncfusion Inc. 2001-2020. All rights reserved.
// Use of this code is subject to the terms of our license.
// A copy of the current license can be obtained at any time by e-mailing
// Any infringement will be prosecuted under
// applicable laws.
#endregion
using System;
using System.Collections.Generic;
using System.Text;
namespace SampleBrowser.SfDataForm
{
///
/// Represents the view model of data form dynamic forms sample.
///
[Xamarin.Forms.Internals.Preserve(AllMembers = true)]
public class ViewModel
{
///
/// Represents the selectionForm information.
///
private List selectedForm;
///
/// Gets or sets the SelectionForm information.
///
public List SelectedForm
{
get { return this.selectedForm; }
set { this.selectedForm = value; }
}
///
/// Initializes a new list of the <see cref="SelectedForm"/>.
///
public ViewModel()
{
List list = new List
list.Add("Organization Form");
list.Add("Employee Form");
list.Add("Ecommerce");
this.selectedForm = list;
}
}
}
|
c#
| 14 | 0.601707 | 73 | 28.914894 | 47 |
starcoderdata
|
/*
*
* TabsPage actions
*
*/
import {
LOAD_TABS, LOAD_SUCCESS,
CLOSE_TAB, CLOSE_TAB_SUCCESS,
CANCEL_TAB, CANCEL_SUCCESS,
CLOSE_TAB_MODAL, SHOW_TAB_MODAL, NAME_TAB_MODAL,
} from './constants';
export const load = () => ({ type: LOAD_TABS });
export const loadSuccess = (data) => ({
type: LOAD_SUCCESS,
payload: data,
});
export const cancelTab = (id) => ({
type: CANCEL_TAB,
payload: id,
});
export const cancelSuccess = (id) => ({
type: CANCEL_SUCCESS,
payload: id,
});
export const closeTab = (id, parcels) => ({
type: CLOSE_TAB,
payload: { id, parcels },
});
export const closeTabSuccess = (id) => ({
type: CLOSE_TAB_SUCCESS,
payload: id,
});
export const toggleCloseModal = (id, total) => ({
type: CLOSE_TAB_MODAL,
payload: { id, total },
});
export const toggleShowTabModal = (id) => ({
type: SHOW_TAB_MODAL,
payload: id,
});
export const toggleNameTabModal = (id) => ({
type: NAME_TAB_MODAL,
payload: id,
});
|
javascript
| 11 | 0.618756 | 50 | 16.517857 | 56 |
starcoderdata
|
import traceback
import sys
from eccodes import *
VERBOSE = 1 # verbose error reporting
# open bufr file
f = open(sys.argv[1], "rb")
# loop for the messages in the file
while 1:
# get handle for message
bufr = codes_bufr_new_from_file(f)
if bufr is None:
break
codes_set(bufr, 'unpack', 1)
try:
compressed = codes_get(bufr,'compressedData')
numberOfSubsets = codes_get(bufr,'numberOfSubsets')
print "Number of Subsets %d" % (numberOfSubsets)
if compressed:
print "not implemented"
else:
for i in range(numberOfSubsets):
blockNo = codes_get(bufr,'/subsetNumber=' + str(i+1) + '/blockNumber')
stationNo = codes_get(bufr,'/subsetNumber=' + str(i+1) + '/stationNumber')
t2m = codes_get(bufr,'/subsetNumber=' + str(i+1) + '/airTemperature')
rh = codes_get(bufr,'/subsetNumber=' + str(i+1) + '/relativeHumidity')
print "Subset: %d Station %.2d%.3d T2m %f RH %f " % (i+1, blockNo, stationNo, t2m, rh)
except CodesInternalError as err:
print 'Loop: Error with key="%s" : %s' % (key, err.msg)
# delete handle
codes_release(bufr)
# close the file
f.close()
|
python
| 19 | 0.594533 | 102 | 28.266667 | 45 |
starcoderdata
|
# ______ __ __
# /_ __/_ __ __ __ / /_ / /_ ____ ____
# / / | | /| / // / / // __// __ \ / __ \ / __ \
# / / | |/ |/ // /_/ // /_ / / / // /_/ // / / /
# /_/ |__/|__/ \__, / \__//_/ /_/ \____//_/ /_/
# /____/
"""
Twython
-------
Twython is a library for Python that wraps the Twitter API.
It aims to abstract away all the API endpoints, so that
additions to the library and/or the Twitter API won't
cause any overall problems.
Questions, comments?
"""
__author__ = '
__version__ = '3.1.2'
from .api import Twython
from .streaming import TwythonStreamer
from .exceptions import (
TwythonError, TwythonRateLimitError, TwythonAuthError,
TwythonStreamError
)
|
python
| 4 | 0.473952 | 59 | 25.233333 | 30 |
starcoderdata
|
<?php
namespace App\Http\Repositories\Theme;
use App\Http\Repositories\RepositoryInterface;
interface ThemeRepositoryInterface extends RepositoryInterface
{
}
|
php
| 6 | 0.818182 | 62 | 13.666667 | 12 |
starcoderdata
|
//
// XCShareProtocol.h
// Pods-XCShareManager_Example
//
// Created by 樊小聪 on 2017/11/6.
//
/*
* 备注:具体分享协议 🐾
*/
#import
#import "XCSharePlatformConfigure.h"
@protocol XCShareProtocol
@required
/**
* 分享(标题+缩略图片+描述+链接地址)
*
* @param title 标题
* @param thumbImage 缩略图片(类型可以是 NSURL、UIImage、NSData)
* @param desc 描述
* @param URLString 分享链接地址
*/
- (void)sahreWithTitle:(NSString *)title
thumbImage:(id)thumbImage
description:(NSString *)desc
URLString:(NSString *)URLString;
/**
* 分享(标题+缩略图片+描述+链接地址+完成的回调)
*
* @param title 标题
* @param thumbImage 缩略图片(类型可以是 NSURL、UIImage、NSData)
* @param desc 描述
* @param URLString 分享链接地址
* @param complete 完成的回调
*/
- (void)shareWithTitle:(NSString *)title
thumbImage:(id)thumbImage
description:(NSString *)desc
URLString:(NSString *)URLString
complete:(void(^)(XCSharePlatformType platformType, BOOL isSuccess))complete;
@end
|
c
| 9 | 0.645129 | 91 | 20.404255 | 47 |
starcoderdata
|
func (out *ByteSequenceOutputs) Subtract(_output, _inc interface{}) interface{} {
assert(_output != nil)
assert(_inc != nil)
if _output == NO_OUTPUT || _inc == NO_OUTPUT {
// no prefix removed
return _output
}
output, inc := _output.([]byte), _inc.([]byte)
assert(util.StartsWith(output, inc))
if len(inc) == len(output) {
// entire output removed
return NO_OUTPUT
}
assert2(len(inc) < len(output), "len(inc)=%v vs len(output)=%v", len(inc), len(output))
assert(len(inc) > 0)
return output[len(inc):]
}
|
go
| 9 | 0.641075 | 88 | 29.705882 | 17 |
inline
|
import FeatureBase from './FeatureBase.js';
export default class CellClick extends FeatureBase {
handleTap(grid, event) {
const fixedRowsHeight = grid.getFixedRowsHeight();
const fixedColsWidth = grid.getFixedColumnsWidth();
if ((event.primitiveEvent.detail.mouse.y > fixedRowsHeight) &&
(event.primitiveEvent.detail.mouse.x > fixedColsWidth)) {
grid.cellClicked(event);
} else if (this.next) {
this.next.handleTap(grid, event);
}
}
}
|
javascript
| 15 | 0.732484 | 64 | 30.466667 | 15 |
starcoderdata
|
import { gql } from "apollo-server-express";
export default gql`
extend type Query {
products: [Product!]!
product(id: ID): Product
}
extend type Mutation {
addProduct(
name: String!
sku : String!
category : String!
price: Int!
weight: String!
quantity : String!
description : String!
brand: String!
dimension: String!
color: String!
material: String!
hardware: String!
): Product!
editProduct(
id: ID!
name: String
sku : String
category : String
price: Int
weight: String
quantity : String
description : String
brand: String
dimension: String
color: String
material: String
hardware: String
):Product!
deleteProduct(
id:ID!
):Product!
}
type attribute{
brand: String
dimension: String
color: String
material: String
hardware: String
}
type Product {
id: ID!
name: String
sku : String
category : String
price: Int
weight: String
quantity : String
description : String
availability: String
attributes: String
stock: Boolean
statusCode: String
message: String
createAt: String!
updateAt: String!
}
`;
|
javascript
| 9 | 0.666667 | 65 | 15.684932 | 73 |
starcoderdata
|
/*
* ----------------------------------------
* Json Upgrading and
* Persistence Architecture
* ----------------------------------------
* Produced by
* 2016
* ----------------------------------------
*/
package uk.dangrew.jupa.update.view.button;
import uk.dangrew.jupa.update.model.ReleaseDefinition;
/**
* The {@link OverwriteConfirmation} provides a specific {@link ConfirmationPane} that
* confirms a file should be overwritten.
*/
public class OverwriteConfirmation extends ConfirmationWithControllerAction {
static final String MESSAGE_SUFFIX = " already exists, overwrite?";
/**
* Constructs a new {@link OverwriteConfirmation}.
* @param controller the {@link InstallerButtonController} for performing actions.
* @param release the {@link ReleaseDefinition} in question.
*/
public OverwriteConfirmation( InstallerButtonController controller, ReleaseDefinition release ) {
super( release.getArtifactName() + MESSAGE_SUFFIX, controller, release );
setYesAction( event -> controller.startDownload( release ) );
setNoAction( event -> controller.cancelDownload() );
}//End Constructor
}//End Class
|
java
| 11 | 0.631621 | 100 | 34.6 | 35 |
starcoderdata
|
#include<bits/stdc++.h>
using namespace std;
#define rep(i,l,r) for(int i=l;i<=r;++i)
void out()
{
puts("Impossible");
exit(0);
}
const int N=100+5;
int cnt[N];
int main()
{
//freopen("1.in","r",stdin);
int n;
cin>>n;
rep(i,1,n)
{
int a;
cin>>a;
++cnt[a];
}
int mx=n;
while(!cnt[mx])--mx;
rep(i,0,mx)
{
int d=max(i,mx-i);
if(!cnt[d])out();
--cnt[d];
}
rep(i,1,(mx+1)/2)
if(cnt[i])out();
puts("Possible");
}
|
c++
| 9 | 0.527523 | 40 | 11.485714 | 35 |
codenet
|
var cLexer = require('./Lexer');
var cException = require('./Exception');
var fParseExpr = require('./../expressions/ParseExpr');
function cExpression(sExpression, oStaticContext) {
var oLexer = new cLexer(sExpression),
oExpr = fParseExpr(oLexer, oStaticContext);
//
if (!oLexer.eof())
throw new cException("XPST0003"
//->Debug
, "Unexpected token beyond end of query"
//<-Debug
);
//
if (!oExpr)
throw new cException("XPST0003"
//->Debug
, "Expected expression"
//<-Debug
);
this.internalExpression = oExpr;
};
cExpression.prototype.internalExpression = null;
// Public methods
cExpression.prototype.evaluate = function(oContext) {
return this.internalExpression.evaluate(oContext);
};
//
module.exports = cExpression;
|
javascript
| 15 | 0.690758 | 61 | 22.852941 | 34 |
starcoderdata
|
import React from "react"
import PropTypes from "prop-types"
import Image from "gatsby-image"
import { FaGithubSquare, FaShareSquare } from "react-icons/fa"
import styled from "styled-components"
const ProjectInfoDiv = styled.div`
background: #f8f9fa;
padding: 1rem 2rem;
border-bottom-left-radius: 0.25rem;
border-bottom-right-radius: 0.25rem;
/* box-shadow: 0 5px 15px rgba(0, 0, 0, 0.2); */
h3 {
font-weight: 500;
margin-bottom: 1.5rem;
font-size: 1.5rem;
}
`
const ProjectDescriptionParagraph = styled.p`
color: var(--clr-primary-2);
`
const ProjectArticle = styled.article`
display: grid;
margin-bottom: 4rem;
transition: all 0.3s linear;
.project-img {
border-top-left-radius: 0.25rem;
border-top-right-radius: 0.25rem;
height: 19rem;
z-index: 0;
/* ::after {
content: "";
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: linear-gradient(to bottom right, var(--clr-primary-5), #222);
opacity: 0.35;
} */
}
.project-icon {
color: var(--clr-primary-2);
font-size: 1.4rem;
margin-right: 0.5rem;
:hover {
color: var(--clr-primary-5);
}
}
:hover {
transform: scale(1.02);
}
@media screen and (min-width: 576px) {
.project-img {
height: 19rem;
}
}
@media screen and (min-width: 768px) {
.project-img {
height: 22rem;
}
}
@media screen and (min-width: 992px) {
grid-template-columns: repeat(12, 1fr);
align-items: center;
/* cursor: pointer; */
.project-img {
grid-column: 1 / span 8;
grid-row: 1 / 1;
height: 30rem;
border-radius: 0.25rem;
box-shadow: 0 5px 15px rgba(0, 0, 0, 0.2);
}
${ProjectInfoDiv} {
box-shadow: 0 5px 15px rgba(0, 0, 0, 0.2);
border-radius: 0.25rem;
z-index: 1;
grid-column: 5/12;
grid-row: 1/1;
/*
:hover {
opacity: 40%;
transition-delay: 0.5s;
} */
}
:nth-of-type(even) ${ProjectInfoDiv} {
grid-column: 2 / span 7;
grid-row: 1 / 1;
text-align: left;
}
:nth-of-type(even) .project-img {
grid-column: 5 / -1;
grid-row: 1 / 1;
}
}
`
const ProjectNumberSpan = styled.span`
display: inline-block;
font-size: 1.25rem;
color: var(--clr-primary-5);
margin-bottom: 0.75rem;
`
const TechTags = styled.div`
margin-bottom: 1rem;
span {
display: inline-block;
background: var(--clr-primary-6);
color: var(--clr-primary-2);
margin-right: 0.5rem;
padding: 0.25rem 0.5rem;
border-radius: 0.25rem;
text-transform: uppercase;
letter-spacing: 2px;
font-size: 0.85rem;
}
`
const Project = ({ description, title, github, url, tag, image, index }) => {
return (
{Image && (
<Image fluid={image.childImageSharp.fluid} className="project-img" />
)}
+ 1}
{tag.map(item => (
<span key={item.id}>{item.description}
))}
{github && (
<a href={github} target="__blank" rel="noreferrer">
<FaGithubSquare className="project-icon" />
)}
{url && (
<a href={url} target="__blank" rel="noreferrer">
<FaShareSquare className="project-icon" />
)}
)
}
Project.propTypes = {
title: PropTypes.string.isRequired,
github: PropTypes.string.isRequired,
url: PropTypes.string.isRequired,
description: PropTypes.string.isRequired,
image: PropTypes.object.isRequired,
tag: PropTypes.arrayOf(PropTypes.object).isRequired,
}
export default Project
|
javascript
| 20 | 0.58054 | 80 | 21.715909 | 176 |
starcoderdata
|
# coding: utf-8
import os
from django.conf import settings
from onadata.apps.main.tests.test_base import TestBase
from onadata.apps.logger.models.xform import XForm
from onadata.apps.restservice.RestServiceInterface import RestServiceInterface
from onadata.apps.restservice.models import RestService
class RestServiceTest(TestBase):
def setUp(self):
super().setUp()
xls_file_path = os.path.join(
os.path.dirname(os.path.abspath(__file__)),
'fixtures',
'dhisform.xls'
)
self._publish_xls_file_and_set_xform(xls_file_path)
def _create_rest_service(self):
rs = RestService(
service_url=settings.KPI_HOOK_ENDPOINT_PATTERN.format(
asset_uid='aAAAAAAAAAAA'),
xform=XForm.objects.all().reverse()[0],
name='kpi_hook')
rs.save()
self.restservice = rs
def test_create_rest_service(self):
count = RestService.objects.all().count()
self._create_rest_service()
self.assertEqual(RestService.objects.all().count(), count + 1)
def test_service_definition(self):
self._create_rest_service()
sv = self.restservice.get_service_definition()()
self.assertEqual(isinstance(sv, RestServiceInterface), True)
|
python
| 16 | 0.650228 | 78 | 30.380952 | 42 |
starcoderdata
|
"""Specific tests for topoaa."""
from math import isnan
import pytest
from haddock.gear.yaml2cfg import read_from_yaml_config
from haddock.modules.topology.topoaa import DEFAULT_CONFIG
DEFAULT_DICT = read_from_yaml_config(DEFAULT_CONFIG)
@pytest.mark.parametrize(
"param",
["hisd_1", "hise_1"],
)
def test_variable_defaults_are_nan_in_mol1(param):
"""Test some variable defaults are as expected."""
assert isnan(DEFAULT_DICT["mol1"][param])
def test_there_is_only_one_mol():
"""Test there is only one mol parameter in topoaa."""
r = set(p for p in DEFAULT_DICT if p.startswith("mol"))
assert len(r) == 1
|
python
| 11 | 0.695652 | 59 | 24.76 | 25 |
starcoderdata
|
inline void device_t::logerror(Format &&fmt, Params &&... args) const
{
if (m_machine != nullptr && m_machine->allow_logging())
{
g_profiler.start(PROFILER_LOGERROR);
// dump to the buffer
m_string_buffer.clear();
m_string_buffer.seekp(0);
util::stream_format(m_string_buffer, "[%s] ", tag());
util::stream_format(m_string_buffer, std::forward<Format>(fmt), std::forward<Params>(args)...);
m_string_buffer.put('\0');
m_machine->strlog(&m_string_buffer.vec()[0]);
g_profiler.stop();
}
}
|
c++
| 14 | 0.64833 | 97 | 27.333333 | 18 |
inline
|
<?php declare(strict_types=1);
namespace Stratadox\CardGame\Match;
use DateTimeInterface;
use Stratadox\CardGame\DomainEvent;
use Stratadox\CardGame\Match\Event\AttackPhaseStarted;
use Stratadox\CardGame\Match\Event\DefendPhaseStarted;
use Stratadox\CardGame\Match\Event\PlayPhaseStarted;
final class TurnPhase
{
private const DEFEND = 0;
private const PLAY = 1;
private const ATTACK = 2;
private const ALLOWED_TIME_FOR = [
self::DEFEND => 20,
self::PLAY => 20,
self::ATTACK => 10,
];
/** @var int */
private $phase;
/** @var DateTimeInterface */
private $since;
/** @var DomainEvent[] */
private $events;
private function __construct(
int $phase,
DateTimeInterface $since,
DomainEvent ...$events
) {
$this->phase = $phase;
$this->since = $since;
$this->events = $events;
}
public static function defendOrPlay(
bool $shouldWeDefend,
DateTimeInterface $now,
MatchId $match
): self {
return $shouldWeDefend ?
self::defend($now, $match) :
self::play($now, $match);
}
public static function play(DateTimeInterface $now, MatchId $match): self
{
return new self(TurnPhase::PLAY, $now, new PlayPhaseStarted($match));
}
private static function defend(DateTimeInterface $now, MatchId $match): self
{
return new self(TurnPhase::DEFEND, $now, new DefendPhaseStarted($match));
}
public function prohibitsDefending(DateTimeInterface $now): bool
{
return $this->phase !== TurnPhase::DEFEND || $this->hasExpired($now);
}
public function prohibitsPlaying(DateTimeInterface $now): bool
{
return $this->phase !== TurnPhase::PLAY || $this->hasExpired($now);
}
public function prohibitsAttacking(DateTimeInterface $now): bool
{
return $this->phase !== TurnPhase::ATTACK || $this->hasExpired($now);
}
public function prohibitsCombat(): bool
{
return $this->phase !== TurnPhase::DEFEND;
}
public function isAfterCombat(): bool
{
return $this->phase === TurnPhase::PLAY
|| $this->phase === TurnPhase::ATTACK;
}
public function hasExpired(DateTimeInterface $now): bool
{
return $this->isTooFarApart(
$now->getTimestamp(),
$this->since->getTimestamp()
);
}
public function startPlay(DateTimeInterface $now, MatchId $match): TurnPhase
{
return new self(TurnPhase::PLAY, $now, new PlayPhaseStarted($match));
}
public function startAttack(DateTimeInterface $now, MatchId $match): TurnPhase
{
return new self(TurnPhase::ATTACK, $now, new AttackPhaseStarted($match));
}
/** @throws NoNextPhase|NeedCombatFirst */
public function next(DateTimeInterface $now, MatchId $match): TurnPhase
{
switch ($this->phase) {
case self::DEFEND: throw NeedCombatFirst::cannotJustSwitchPhase();
case self::PLAY: return $this->startAttack($now, $match);
default: throw NoNextPhase::available();
}
}
public function events(): array
{
return $this->events;
}
private function isTooFarApart(int $nowTime, int $backThenTime): bool
{
return $nowTime - $backThenTime >= self::ALLOWED_TIME_FOR[$this->phase];
}
}
|
php
| 13 | 0.620659 | 82 | 26.861789 | 123 |
starcoderdata
|
package com.jbetfair;
import java.util.List;
import junit.framework.TestCase;
import com.jbetfair.api.ApiOperation;
import com.jbetfair.api.entities.MarketBook;
import com.jbetfair.api.entities.MarketCatalogue;
import com.jbetfair.api.params.MarketFilter;
import com.jbetfair.api.responses.EventTypeResult;
import com.jbetfair.api.responses.ListCompetitionResult;
import com.jbetfair.api.responses.ListCountriesResult;
import com.jbetfair.api.responses.ListEventsResult;
import com.jbetfair.api.responses.ListMarketTypesResult;
import com.jbetfair.api.responses.ListTimeRangesResult;
import com.jbetfair.api.responses.ListVenuesResult;
public class JBetfairTest extends TestCase {
private JBetfair jBetfair = new JBetfair();
public void testLogin() throws Exception {
try {
jBetfair.login();
} catch (Exception e) {
fail();
}
}
public void testOperationWithRequests() throws Exception {
assertNotNull(jBetfair.makeRequest(ApiOperation.LIST_EVENT_TYPES, new MarketFilter()));
}
public void testListEventTypes() throws Exception {
List result = jBetfair.listEventTypes();
assertTrue(result.size() > 0);
for (EventTypeResult e : result) {
assertNotNull(e.getEventType().getId());
assertNotNull(e.getEventType().getName());
assertNotNull(e.getMarketCount());
}
}
public void testListCompetitions() throws Exception {
List result = jBetfair.listCompetitions();
assertTrue(result.size() > 0);
for (ListCompetitionResult c : result) {
assertNotNull(c.getCompetition().getId());
assertNotNull(c.getCompetition().getName());
assertNotNull(c.getCompetitionRegion());
assertNotNull(c.getMarketCount());
}
}
public void testListTimeRanges() throws Exception {
List result = jBetfair.listTimeRanges();
assertTrue(result.size() > 0);
for (ListTimeRangesResult t : result) {
assertNotNull(t.getMarketCount());
assertNotNull(t.getTimeRange().getFrom());
assertNotNull(t.getTimeRange().getTo());
}
}
public void testListEvents() throws Exception {
List result = jBetfair.listEvents();
assertTrue(result.size() > 0);
for (ListEventsResult e : result) {
assertNotNull(e.getMarketCount());
assertNotNull(e.getEvent().getId());
assertNotNull(e.getEvent().getName());
assertNotNull(e.getEvent().getTimezone());
assertNotNull(e.getEvent().getOpenDate());
}
}
public void testListMarketTypes() throws Exception {
List result = jBetfair.listMarketTypes();
assertTrue(result.size() > 0);
for (ListMarketTypesResult m : result) {
assertNotNull(m.getMarketCount());
assertNotNull(m.getMarketType());
}
}
public void testListCountries() throws Exception {
List result = jBetfair.listCountries();
assertTrue(result.size() > 0);
for (ListCountriesResult c : result) {
assertNotNull(c.getMarketCount());
assertNotNull(c.getCountryCode());
}
}
public void testListVenues() throws Exception {
List result = jBetfair.listVenues();
assertTrue(result.size() > 0);
for (ListVenuesResult v : result) {
assertNotNull(v.getMarketCount());
assertNotNull(v.getVenue());
}
}
public void testListMarketCatalogue() throws Exception {
List result = jBetfair.listMarketCatalogue();
assertTrue(result.size() > 0);
for (MarketCatalogue c : result) {
assertNotNull(c.getMarketId());
assertNotNull(c.getMarketName());
assertNotNull(c.getDescription());
assertNotNull(c.getEvent());
assertNotNull(c.getEventType());
assertNotNull(c.getRunners());
}
}
public void testListMarketBook() throws Exception {
List catalogue = jBetfair.listMarketCatalogue(new MarketFilter(), 1);
List result = jBetfair.listMarketBook(catalogue.get(0).getMarketId());
assertTrue(result.size() > 0);
for (MarketBook b : result) {
assertNotNull(b.getMarketId());
assertNotNull(b.getStatus());
assertNotNull(b.getBetDelay());
assertNotNull(b.getBspReconciled());
assertNotNull(b.getComplete());
assertNotNull(b.getCrossMatching());
assertNotNull(b.getInplay());
assertNotNull(b.getIsMarketDataDelayed());
assertNotNull(b.getLastMatchTime());
assertNotNull(b.getNumberOfActiveRunners());
assertNotNull(b.getNumberOfRunners());
assertNotNull(b.getNumberOfWinners());
assertNotNull(b.getRunners());
assertNotNull(b.getRunnersVoidable());
assertNotNull(b.getTotalAvailable());
assertNotNull(b.getTotalMatched());
assertNotNull(b.getVersion());
}
}
}
|
java
| 13 | 0.70587 | 91 | 32.833333 | 144 |
starcoderdata
|
# flake8: noqa
from __future__ import absolute_import, division, print_function
import sys
import utool as ut
ut.noinject(__name__, '[cyth.__init__]')
__version__ = '1.0.0.dev1'
from cyth.cyth_args import WITH_CYTH, CYTH_WRITE, DYNAMIC
from cyth.cyth_importer import import_cyth_execstr
from cyth.cyth_script import translate, translate_all
from cyth.cyth_decorators import macro
from cyth import cyth_helpers
from cyth import cyth_importer
from cyth import cyth_decorators
from cyth import cyth_macros
'''
Cyth:
* Create Cyth, to cythonize the code, make it faster
annotate variable names with types in a scoped comment
then type the variable names
* Cythonize spatial verification and other parts of vtool
* Cythonize matching_functions
Cyth Technical Description:
Overview - cyth works by parsing a .py file for comments specified in comments:
"""
cyth code
"""
it deterines scope using the indentation. In multiples of 4.
If any module (__name__ + '.py') has at least one CYTH tag in, then a pyx file named (__name__ + '_cython.pyx') file will be generated.
Global CYTH tags will be simply copied into the pyx file.
CYTH tags in functions will also be copied and pasted, but a cython version of the function will be generated (at first as a strict copy, but we may be able to add improvements later).
CYTH will have a module
import cythe
@cythe.cythonize(return_type=None, dtype_list=[])
def python_func(*args, **kwargs):
...
@cythe.cythonize():
class SomeClass(object):
def __init__(self):
...
This will simply grab the code object and parse out the same info.
# this will do magic
# Apply at the end of the module
exec(cythe.exec_module_definitions())
The _cython.pyx file will be autogenerated. This file will be converted into .c file and
compiled unless the user defers this step to the setup.py file.
'''
|
python
| 5 | 0.739611 | 184 | 27.373134 | 67 |
starcoderdata
|
def hist_plot():
''' Create a canvas with width 10, height 7.5 '''
fig_obj = plt.figure(figsize=(10, 7.5))
''' Place an 2-D axis system on the Canvas '''
ax = plt.subplot(111)
ax.spines["bottom"].set_visible(True) # Set the spines, or box bounds visibility
ax.spines["left"].set_visible(True)
ax.spines['right'].set_visible(False)
ax.spines['top'].set_visible(False)
''' Plot the histogram of '''
p = plt.hist(data.mpg, bins = 30)
plt.title("MPG", fontsize=14, fontweight='bold')
''' Save figure '''
plt.tight_layout()
plt.savefig('histogram.png', bbox_inches='tight')
plt.show()
|
python
| 9 | 0.607034 | 85 | 35.388889 | 18 |
inline
|
#pragma once
#include
#include
namespace DeusCore
{
// from https://www.justsoftwaresolutions.co.uk/threading/implementing-a-thread-safe-queue-using-condition-variables.html
// Written by
template<typename T>
class concurrent_queue
{
private:
std::queue m_queue;
mutable std::mutex m_mutex;
std::condition_variable m_condition_variable;
public:
void push(T const& data)
{
std::unique_lock lock(m_mutex);
m_queue.push(data);
lock.unlock();
m_condition_variable.notify_one();
}
bool empty() const
{
std::unique_lock lock(m_mutex);
return m_queue.empty();
}
bool try_pop(T& popped_value)
{
std::unique_lock lock(m_mutex);
if (m_queue.empty())
return false;
popped_value = m_queue.front();
m_queue.pop();
return true;
}
void wait_and_pop(T& popped_value)
{
std::unique_lock lock(m_mutex);
while (m_queue.empty())
m_condition_variable.wait(lock);
popped_value = m_queue.front();
m_queue.pop();
}
};
}
|
c
| 11 | 0.618037 | 122 | 17.5 | 58 |
starcoderdata
|
void FilesystemRecord::initialize(const ::WIN32_FIND_DATA& data)
{
// Save the data.
::CopyMemory(&data_, &data, sizeof(data_));
if (isReparsePoint())
{
reparse_tag_ = data.dwReserved0;
}
}
|
c++
| 8 | 0.561702 | 64 | 25.222222 | 9 |
inline
|
def calculate_deterministic_metrics(processed_fx_obs, categories, metrics):
"""
Calculate deterministic metrics for the processed data using the provided
categories and metric types.
Normalization is determined by the attributes of the input objects.
If ``processed_fx_obs.uncertainty`` is not ``None``, a deadband
equal to the uncertainty will be used by the metrics that support it.
Parameters
----------
processed_fx_obs : datamodel.ProcessedForecastObservation
categories : list of str
List of categories to compute metrics over.
metrics : list of str
List of metrics to be computed.
Returns
-------
solarforecastarbiter.datamodel.MetricResult
Contains all the computed metrics by categories.
Raises
------
RuntimeError
If there is no forecast, observation timeseries data or no metrics
are specified.
"""
out = {
'name': processed_fx_obs.name,
'forecast_id': processed_fx_obs.original.forecast.forecast_id,
}
try:
out['observation_id'] = processed_fx_obs.original.observation.observation_id # NOQA: E501
except AttributeError:
out['aggregate_id'] = processed_fx_obs.original.aggregate.aggregate_id
fx = processed_fx_obs.forecast_values
obs = processed_fx_obs.observation_values
# Check reference forecast is from processed pair, if needed
ref_fx = processed_fx_obs.reference_forecast_values
if ref_fx is None:
ref_fx = np.nan # avoids issues with None and deadband masking
# No data or metrics
if fx.empty:
raise RuntimeError("No forecast timeseries data.")
elif obs.empty:
raise RuntimeError("No observation timeseries data.")
elif len(metrics) == 0:
raise RuntimeError("No metrics specified.")
# Dataframe for grouping
df = pd.DataFrame({'forecast': fx,
'observation': obs,
'reference': ref_fx})
# get normalization factor
normalization = processed_fx_obs.normalization_factor
# get uncertainty.
deadband = processed_fx_obs.uncertainty
cost_params = processed_fx_obs.cost
# Force `groupby` to be consistent with `interval_label`, i.e., if
# `interval_label == ending`, then the last interval should be in the bin
if processed_fx_obs.interval_label == "ending":
df.index -= pd.Timedelta("1ns")
metric_vals = []
# Calculate metrics
for category in set(categories):
index_category = _index_category(category, df)
# Calculate each metric
for metric_ in metrics:
# Group by category
for cat, group in df.groupby(index_category):
# Calculate
res = _apply_deterministic_metric_func(
metric_, group.forecast, group.observation,
ref_fx=group.reference, normalization=normalization,
deadband=deadband, cost_params=cost_params)
# Change category label of the group from numbers
# to e.g. January or Monday
if category == 'month':
cat = calendar.month_abbr[cat]
elif category == 'weekday':
cat = calendar.day_abbr[cat]
metric_vals.append(datamodel.MetricValue(
category, metric_, str(cat), res))
out['values'] = _sort_metrics_vals(
metric_vals, datamodel.ALLOWED_DETERMINISTIC_METRICS)
calc_metrics = datamodel.MetricResult.from_dict(out)
return calc_metrics
|
python
| 16 | 0.631302 | 98 | 33.721154 | 104 |
inline
|
<?php
namespace App\Http\Controllers;
use App\Models\Proposal;
use Illuminate\Http\Request;
use App\Models\User;
use Illuminate\Support\Facades\DB;
use Auth;
use Mail;
use PDF;
use App\Mail\RevMail;
use Validator;
class VerifikasiProposalPengabdianController extends Controller
{
public function index()
{
// $proposal= DB::table('proposals')->where('user_id', '=',Auth::User()->id)->get();
$user=User::all();
$proposal= DB::table('proposals')
->select('user_id','reviewer_id','category_id')
->where('reviewer_id','=',Auth::user()->id)
->where('category_id','=',2)
->where('status_id','=',3)
->distinct()->get();
return view("reviewer.verifikasi_proposal_pengabdian", compact('proposal','user'));
}
public function terima(Request $request, $id){
$proposal=Proposal::Find($id);
if ($proposal->id= $id){
$proposal1= Proposal::where('user_id','=',$proposal->user_id)
->update(['status_id' => 1]);
}
$prop =DB::table('proposals')->where('id','=',$proposal->id)->Value('judul');
$user2 =DB::table('users')->where('id','=',$proposal->user_id)->Value('name');
$prop1 =Proposal::where('id','=',$proposal->id)->get();
$user1 =DB::table('users')->where('id','=',$proposal->reviewer_id)->Value('name');
$user =DB::table('users')->where('id','=',$proposal->user_id)->value('email');
// ->where('id','=',$proposal->user_id);
$data["email"] = $user;
$data["title"] = "Proposal Diterima";
$data["body"] = ' Proposal Penelitian , atas nama '. $user2 . ' dengan judul ' .$prop. ' sudah diterima untuk direview oleh saudara , silahkan cek website';
$pdf = PDF::loadView('admin.surattugas',['prop1'=>$prop1]);
Mail::send('admin.pil', $data, function($message)use($data, $pdf) {
$message->to($data["email"], $data["email"])
->subject($data["title"])
->attachData($pdf->output(), "SuratTugas.pdf");
});
return redirect('reviewer/verifikasi_proposal_pengabdian')->with(['success' => 'Proposal Diterima']);
}
public function revisi(Request $request, $id){
$rules = [
'detail_revisi' => 'required',
];
$messages = [
'detail_revisi.required' => 'Detail revisi wajib diisi.',
];
$validator = Validator::make($request->all(), $rules, $messages);
if($validator->fails()){
return redirect()->back()->withErrors($validator)->withInput($request->all());
}
$proposal = Proposal::find($id);
$user1 =DB::table('users')->where('id','=',$proposal->user_id)->pluck('name');
$user =DB::table('users')->where('id','=',$proposal->user_id)->pluck('email');
// ->where('id','=',$proposal->user_id);
$detail =[
'title'=>'Revisi Proposal',
'body'=> $user1.' Proposal Pengabdian anda mendapat beberapa koreksi , silahkan cek website'
];
Mail::to($user)->send(new RevMail($detail));
$proposal->detail_revisi=$request->detail_revisi;
$proposal->status_id=3;
$proposal->save();
// $proposal->update([
// 'status_id' => 3
// ]);
return redirect('reviewer/verifikasi_proposal_pengabdian')->with(['success' => 'Proposal Direvisi']);
}
public function detail(Request $request, $id){
$proposal = Proposal::where('user_id','=',$id)
->where('category_id','=',2)
->where('status_id','=',3)
->get();
return view("reviewer.reviewproposalpengabdian", compact('proposal'));
}
}
|
php
| 19 | 0.532751 | 164 | 32.560345 | 116 |
starcoderdata
|
<?php
return [
'INVOICE'=>'HOÁ ĐƠN',
'Date'=>'Ngày',
'Number'=>'Số',
'Ref ID'=>'Ref ID',
'Note'=>'Ghi chú',
'Bill to'=>'Người trả',
'Due date'=>'Thời hạn',
'Service & Description'=>'Service & Description',
'Price'=>'Giá',
'Qty'=>'SL',
'Total'=>'Thành tiền',
'Payment made in'=>'Thanh toán bằng',
'Method of payment'=>'Phương thức thanh toán',
'SUB TOTAL'=>'THÀNH TIỀN',
'GRAND TOTAL'=>'TỔNG THANH TOÁN',
'Customer'=>'Khách hàng ký',
'For Amica Travel'=>'T/M Amica Travel',
'For Secret Indochina'=>'T/M Secret Indochina',
'THANK YOU FOR YOUR BUSINESS'=>'XIN CHÂN THÀNH CẢM ƠN QUÝ KHÁCH',
'OVERDUE'=>'QUÁ HẠN',
'PAID'=>'ĐÃ TRẢ',
'3rd Floor, Nikko Building'=>'Tầng 3, toà nhà Nikko',
'6th Floor, Nikko Building'=>'Tầng 6, toà nhà Nikko',
'27 Nguyen Truong To str, Hanoi, Vietnam'=>'Số 27 phố Nguyễn Trường Tộ, quận Ba Đình, Hà Nội',
'You are responsible for all bank fees'=>'Quý khách vui lòng thanh toán mọi khoản phí ngân hàng nếu có',
'Link to payment page'=>'Link đến trang thanh toán trực tuyến',
];
|
php
| 5 | 0.649464 | 105 | 34.448276 | 29 |
starcoderdata
|
package org.uscxml;
import java.util.BitSet;
import java.util.Deque;
import java.util.List;
import java.util.Map;
/** Base class for generated StateCharts */
public abstract class StateChart {
public enum InterpreterState {
USCXML_FINISHED,
USCXML_UNDEF,
USCXML_IDLE,
USCXML_INITIALIZED,
USCXML_INSTANTIATED,
USCXML_MICROSTEPPED,
USCXML_MACROSTEPPED,
USCXML_CANCELLED
}
public enum StateType {
USCXML_STATE_ATOMIC,
USCXML_STATE_PARALLEL,
USCXML_STATE_COMPOUND,
USCXML_STATE_FINAL,
USCXML_STATE_HISTORY_DEEP,
USCXML_STATE_HISTORY_SHALLOW,
USCXML_STATE_INITIAL,
USCXML_STATE_HAS_HISTORY
}
public enum TransitionType {
USCXML_TRANS_SPONTANEOUS,
USCXML_TRANS_TARGETLESS,
USCXML_TRANS_INTERNAL,
USCXML_TRANS_HISTORY,
USCXML_TRANS_INITIAL
}
public abstract class State {
String name;
int parent;
BitSet children;
BitSet completion;
BitSet ancestors;
Data data;
StateType type;
public abstract void onEntry() throws InterpreterException;
public abstract void onExit() throws InterpreterException;
public abstract void invoke(Invoke invoker, boolean invoke) throws InterpreterException;
}
public abstract class Transition {
int source;
BitSet target;
String event;
String condition;
TransitionType type;
BitSet conflicts;
BitSet exitSet;
public abstract boolean isEnabled();
public abstract boolean isMatched();
public abstract void onTransition();
}
public class Data {
String id;
String src;
String expr;
String content;
}
public class Assign {
String location;
String expr;
String content;
}
public class Foreach {
String array;
String item;
String index;
}
public class Param {
String name;
String expr;
String location;
}
public class DoneData {
int source;
String content;
String contentExpr;
List params;
}
public abstract class Invoke {
StateChart machine;
String type;
String typeExpr;
String src;
String srcExpr;
String id;
String idlocation;
String sourceName;
String namelist;
boolean autoForward;
String content;
String contentExpr;
List params;
public abstract void finalize();
}
public class Send {
String event;
String eventExpr;
String target;
String targetExpr;
String type;
String typeExpr;
String id;
String idlocation;
String delay;
String delayExpr;
String namelist;
String content;
String contentExpr;
List params;
}
public List transitions;
public List states;
public Deque externalQueue;
public Deque internalQueue;
protected InterpreterState state = InterpreterState.USCXML_UNDEF;
protected Object event;
protected BitSet flags;
protected BitSet config;
protected BitSet history;
protected BitSet invocations;
protected BitSet initializedData;
protected Map<String, Integer> stateNamesToIndex;
public InterpreterState step() throws org.uscxml.InterpreterException {
return step(0);
}
public InterpreterState step(long blockMs) throws org.uscxml.InterpreterException {
/** Here you would implement microstep(T) as in the book chapter */
/** Just to silence the compiler warning */
if (true) throw new InterpreterException("", "");
return state;
}
public void cancel() {
state = InterpreterState.USCXML_CANCELLED;
}
public void reset() {
history.clear();
config.clear();
flags.clear();
// @TODO: uninvoke any invokers
invocations.clear();
}
public InterpreterState getState() { return state; }
public boolean isInState(String stateId) {
if (!stateNamesToIndex.containsKey(stateId))
return false;
return config.get((int) stateNamesToIndex.get(stateId));
}
public void receive(Object event) {
externalQueue.addLast(event);
}
protected Object dequeueInternal() {
try {
return internalQueue.removeLast();
} catch(Exception e) {
return null;
}
}
protected Object dequeueExternal() {
try {
return externalQueue.removeLast();
} catch(Exception e) {
return null;
}
}
public abstract boolean isTrue(String expression);
public abstract void raiseDoneEvent(State state, DoneData doneData);
public abstract void execContentLog(String label, String expression);
public abstract void execContentRaise(String event);
public abstract void execContentSend(Send send);
public abstract void execContentForeachInit(Foreach foreach);
public abstract void execContentForeachNext(Foreach foreach);
public abstract void execContentForeachDone(Foreach foreach);
public abstract void execContentAssign(Assign assign);
public abstract void execContentInit(Data data);
public abstract void execContentCancel(String sendId, String sendIdExpr);
public abstract void execContentScript(String src, String content);
public abstract void execContentFinalize(Invoke invoker, Object event);
}
|
java
| 11 | 0.740892 | 90 | 21.135135 | 222 |
starcoderdata
|
const puppeteer = require('puppeteer');
const sleep = require('sleep');
(async () => {
const browser = await puppeteer.launch()
const page = await browser.newPage()
await page.goto('https://www.goibibo.com/hotels/')
await sleep.sleep(5);
await page.setViewport({ width: 1301, height: 623 })
await page.waitForSelector('#content #Home')
await page.click('#content #Home')
await page.waitForSelector('.blueBg #gosuggest_inputL')
await page.click('.blueBg #gosuggest_inputL')
console.log('reached');
await page.waitForSelector('#react-autosuggest-1 > #react-autosuggest-1-suggestion--3 > div > .dib > .mainTxt')
await page.click('#react-autosuggest-1 > #react-autosuggest-1-suggestion--3 > div > .dib > .mainTxt')
console.log('reached1');
await page.waitForSelector('.shCalenderBox > .col-md-6:nth-child(1) > div > .col-md-12 > .form-control')
await page.click('.shCalenderBox > .col-md-6:nth-child(1) > div > .col-md-12 > .form-control')
await page.waitForSelector('.DayPicker > .DayPicker-Month > .DayPicker-Body > .DayPicker-Week:nth-child(4) > .DayPicker-Day:nth-child(5)')
await page.click('.DayPicker > .DayPicker-Month > .DayPicker-Body > .DayPicker-Week:nth-child(4) > .DayPicker-Day:nth-child(5)')
await page.waitForSelector('.DayPicker > .DayPicker-Month > .DayPicker-Body > .DayPicker-Week:nth-child(5) > .DayPicker-Day:nth-child(6)')
await page.click('.DayPicker > .DayPicker-Month > .DayPicker-Body > .DayPicker-Week:nth-child(5) > .DayPicker-Day:nth-child(6)')
await page.waitForSelector('.col-md-12 > .width100 > div > .col-md-3 > .width100')
await page.click('.col-md-12 > .width100 > div > .col-md-3 > .width100')
await page.screenshot({path: 'budds.png'});
await browser.close()
})()
|
javascript
| 13 | 0.689949 | 140 | 50.823529 | 34 |
starcoderdata
|
'use strict'
/* global describe, it, inject, expect, beforeEach */
describe('myLangFooter directive', function () {
beforeEach(module('ui.bootstrap'))
beforeEach(module('myApp.templates'))
// ErrorServiceProvider in myApp.services is needed by
// AppLangSelectController in myApp.controllers
beforeEach(module('myApp.services'))
beforeEach(module('myApp.controllers'))
beforeEach(module('myApp.directives'))
beforeEach(inject(function (_$compile_, _$rootScope_) {
this.$compile = _$compile_
this.$rootScope = _$rootScope_
}))
it('compiles a my-lang-footer attribute', function () {
var compiledElement = this.$compile('<div my-lang-footer>
this.$rootScope.$digest()
expect(compiledElement.html()).toContain('footer_lang_link')
expect(compiledElement.html()).toContain('AppLangSelectController')
})
it('compiles a my-lang-footer element', function () {
var compiledElement = this.$compile('
this.$rootScope.$digest()
expect(compiledElement.html()).toContain('footer_lang_link')
expect(compiledElement.html()).toContain('AppLangSelectController')
})
})
|
javascript
| 15 | 0.721793 | 95 | 39.4375 | 32 |
starcoderdata
|
import xarray as xr
da = xr.DataArray([1, 2, 3], [("x", [0, 1, 2])])
x = da.sel(x=[1.1, 1.9], method="nearest")
ds = xr.Dataset(data_vars={'tas': da})
y = ds.sel(x=1.9, method="nearest")
def find_nearest(array, value):
n = [abs(i-value) for i in array]
idx = n.index(min(n))
return array[idx]
def nudgeSingleValuesToAxisValues(value, array):
return find_nearest(value, array)
|
python
| 9 | 0.620438 | 48 | 20.631579 | 19 |
starcoderdata
|
// Based on Go on iOS(https://github.com/golang/go/blob/master/misc/ios/go_ios_exec.go)
// The license of Go on iOS can be checked in the CREDITS file.
package idevice
import (
"bytes"
"encoding/xml"
"errors"
"fmt"
"io"
"net"
"os"
"os/exec"
"path/filepath"
"strings"
"time"
)
var deviceID string
func Init() (string, error) {
udid, err := fetchUDID()
if err != nil {
return "", err
}
deviceID = udid
return udid, nil
}
func fetchUDID() (string, error) {
udids := getLines(exec.Command("idevice_id", "-l"))
if len(udids) == 0 {
return "", fmt.Errorf("No UDID found; is a device connected?")
}
deviceID := string(udids[0])
return deviceID, nil
}
func getLines(cmd *exec.Cmd) [][]byte {
out := output(cmd)
lines := bytes.Split(out, []byte("\n"))
// Skip the empty line at the end.
if len(lines[len(lines)-1]) == 0 {
lines = lines[:len(lines)-1]
}
return lines
}
func output(cmd *exec.Cmd) []byte {
out, err := cmd.Output()
if err != nil {
fmt.Println(strings.Join(cmd.Args, "\n"))
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
return out
}
func idevCmd(cmd *exec.Cmd) *exec.Cmd {
if deviceID != "" {
// Inject -u device_id after the executable, but before the arguments.
args := []string{cmd.Args[0], "-u", deviceID}
cmd.Args = append(args, cmd.Args[1:]...)
}
return cmd
}
// startDebugBridge ensures that the idevicedebugserverproxy runs on
// port 3222.
func StartDebugBridge() (func(), error) {
// Kill any hanging debug bridges that might take up port 3222.
exec.Command("killall", "idevicedebugserverproxy").Run()
errChan := make(chan error, 1)
cmd := idevCmd(exec.Command("idevicedebugserverproxy", "-d", "3222"))
var stderr bytes.Buffer
cmd.Stderr = &stderr
if err := cmd.Start(); err != nil {
return nil, fmt.Errorf("idevicedebugserverproxy: %v", err)
}
go func() {
if err := cmd.Wait(); err != nil {
if _, ok := err.(*exec.ExitError); ok {
errChan <- fmt.Errorf("idevicedebugserverproxy: %s", stderr.Bytes())
} else {
errChan <- fmt.Errorf("idevicedebugserverproxy: %v", err)
}
}
errChan <- nil
}()
closer := func() {
cmd.Process.Kill()
<-errChan
}
// Dial localhost:3222 to ensure the proxy is ready.
delay := time.Second / 4
for attempt := 0; attempt < 5; attempt++ {
conn, err := net.DialTimeout("tcp", "localhost:3222", 5*time.Second)
if err == nil {
conn.Close()
return closer, nil
}
select {
case <-time.After(delay):
delay *= 2
case err := <-errChan:
return nil, err
}
}
closer()
return nil, errors.New("failed to set up idevicedebugserverproxy")
}
// findDevImage use the device iOS version and build to locate a suitable
// developer image.
func findDevImage() (string, error) {
cmd := idevCmd(exec.Command("ideviceinfo"))
out, err := cmd.Output()
if err != nil {
return "", fmt.Errorf("ideviceinfo: %v", err)
}
var iosVer, buildVer string
lines := bytes.Split(out, []byte("\n"))
for _, line := range lines {
spl := bytes.SplitN(line, []byte(": "), 2)
if len(spl) != 2 {
continue
}
key, val := string(spl[0]), string(spl[1])
switch key {
case "ProductVersion":
iosVer = val
case "BuildVersion":
buildVer = val
}
}
if iosVer == "" || buildVer == "" {
return "", errors.New("failed to parse ideviceinfo output")
}
verSplit := strings.Split(iosVer, ".")
if len(verSplit) > 2 {
// Developer images are specific to major.minor ios version.
// Cut off the patch version.
iosVer = strings.Join(verSplit[:2], ".")
}
sdkBase := "/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/DeviceSupport"
patterns := []string{fmt.Sprintf("%s (%s)", iosVer, buildVer), fmt.Sprintf("%s (*)", iosVer), fmt.Sprintf("%s*", iosVer)}
for _, pattern := range patterns {
matches, err := filepath.Glob(filepath.Join(sdkBase, pattern, "DeveloperDiskImage.dmg"))
if err != nil {
return "", fmt.Errorf("findDevImage: %v", err)
}
if len(matches) > 0 {
return matches[0], nil
}
}
return "", fmt.Errorf("failed to find matching developer image for iOS version %s build %s", iosVer, buildVer)
}
func MountDevImage() error {
// Check for existing mount.
cmd := idevCmd(exec.Command("ideviceimagemounter", "-l", "-x"))
out, err := cmd.CombinedOutput()
if err != nil {
os.Stderr.Write(out)
return fmt.Errorf("ideviceimagemounter: %v", err)
}
var info struct {
Dict struct {
Data []byte `xml:",innerxml"`
} `xml:"dict"`
}
if err := xml.Unmarshal(out, &info); err != nil {
return fmt.Errorf("mountDevImage: failed to decode mount information: %v", err)
}
dict, err := parsePlistDict(info.Dict.Data)
if err != nil {
return fmt.Errorf("mountDevImage: failed to parse mount information: %v", err)
}
if dict["ImagePresent"] == "true" && dict["Status"] == "Complete" {
return nil
}
// Some devices only give us an ImageSignature key.
if _, exists := dict["ImageSignature"]; exists {
return nil
}
// No image is mounted. Find a suitable image.
imgPath, err := findDevImage()
if err != nil {
return err
}
sigPath := imgPath + ".signature"
cmd = idevCmd(exec.Command("ideviceimagemounter", imgPath, sigPath))
if out, err := cmd.CombinedOutput(); err != nil {
os.Stderr.Write(out)
return fmt.Errorf("ideviceimagemounter: %v", err)
}
return nil
}
// Parse an xml encoded plist. Plist values are mapped to string.
func parsePlistDict(dict []byte) (map[string]string, error) {
d := xml.NewDecoder(bytes.NewReader(dict))
values := make(map[string]string)
var key string
var hasKey bool
for {
tok, err := d.Token()
if err == io.EOF {
break
}
if err != nil {
return nil, err
}
if tok, ok := tok.(xml.StartElement); ok {
if tok.Name.Local == "key" {
if err := d.DecodeElement(&key, &tok); err != nil {
return nil, err
}
hasKey = true
} else if hasKey {
var val string
var err error
switch n := tok.Name.Local; n {
case "true", "false":
// Bools are represented as and
val = n
err = d.Skip()
default:
err = d.DecodeElement(&val, &tok)
}
if err != nil {
return nil, err
}
values[key] = val
hasKey = false
} else {
if err := d.Skip(); err != nil {
return nil, err
}
}
}
}
return values, nil
}
// findDeviceAppPath returns the device path to the app with the
// given bundle ID. It parses the output of ideviceinstaller -l -o xml,
// looking for the bundle ID and the corresponding Path value.
func FindDeviceAppPath(bundleID string) (string, error) {
cmd := idevCmd(exec.Command("ideviceinstaller", "-l", "-o", "xml"))
out, err := cmd.CombinedOutput()
if err != nil {
os.Stderr.Write(out)
return "", fmt.Errorf("ideviceinstaller: -l -o xml %v", err)
}
var list struct {
Apps []struct {
Data []byte `xml:",innerxml"`
} `xml:"array>dict"`
}
if err := xml.Unmarshal(out, &list); err != nil {
return "", fmt.Errorf("failed to parse ideviceinstaller output: %v", err)
}
for _, app := range list.Apps {
values, err := parsePlistDict(app.Data)
if err != nil {
return "", fmt.Errorf("findDeviceAppPath: failed to parse app dict: %v", err)
}
if values["CFBundleIdentifier"] == bundleID {
if path, ok := values["Path"]; ok {
return path, nil
}
}
}
return "", fmt.Errorf("failed to find device path for bundle: %s", bundleID)
}
|
go
| 17 | 0.637203 | 122 | 25.397849 | 279 |
starcoderdata
|
#!/usr/bin/env python
"""try:
raise ImportError
from setuptools import setup
from distutils.sysconfig import get_python_version
except ImportError:"""
from distutils.core import setup
import os
init_files = ('/etc/init.d/', ['smartproxyd'])
conf_files = ('/etc/lounge/', ['smartproxy.xml', 'smartproxy.tac', 'cacheable.json.example'])
check_files = ('/root/bin/', ['check-smartproxy.py'])
cron_files = ('/etc/cron.d/', ['check-smartproxy'])
cache_files = ('/var/lib/lounge/smartproxy', ['cache.dat'])
data_files = [init_files, conf_files, check_files, cron_files, cache_files]
py_modules = ["smartproxy.proxy", "smartproxy.fetcher", "smartproxy.reducer", "smartproxy.streaming"]
setup( version = '1.3.0',
name = 'lounge-smartproxy',
author='meebo',
author_email='
url='http://tilgovi.gthhub.com/couchdb-lounge',
data_files = data_files,
py_modules = py_modules)
|
python
| 6 | 0.68847 | 101 | 33.692308 | 26 |
starcoderdata
|
/**
* Jatabase
*
* @author
* @license MIT License
* @package jatabase
*/
'use strict';
module.exports = function (Model) {
return function (data, where) {
if (typeof data != 'object') {
throw new Error('You have to indicate the data to update.');
}
where = typeof where == 'undefined' || where === null ? {} : where;
if (Model._validateFields(data) && Model._validateFields(where)) {
let db = require(Model.file),
collection = db[Model.collection],
result = Model.findSync(where);
if (typeof where == 'object') {
for (let k in result) {
if (result.hasOwnProperty(k)) {
for (let i in data) {
result[k][i] = data[i];
}
}
}
for (let k in collection) {
if (collection.hasOwnProperty(k)) {
for (let i in result) {
if (result.hasOwnProperty(i)) {
if (parseInt(collection[k]._id) == parseInt(result[i]._id)) {
collection[k] = result[i];
}
}
}
}
}
} else {
for (let i in data) {
result[i] = data[i];
}
for (let k in collection) {
if (collection.hasOwnProperty(k)) {
if (parseInt(collection[k]._id) == parseInt(result._id)) {
collection[k] = result;
}
}
}
}
Model._saveModificationOnKey(Model.collection, collection);
}
}
};
|
javascript
| 24 | 0.491688 | 77 | 24.241935 | 62 |
starcoderdata
|
<?
/* This file will do all the Sox edits. Each function accepts a file name, an edit to perform, and variables
**/
include 'vars.php';
if (isset($_POST[change_file]) || isset($_POST[revers]) || isset($_POST[highpass]) || isset($_POST[lowpass]) || isset($_POST[speed_change_big]) || isset($_POST[speed_change_small]) || isset($_POST[undo])) {
$current_file = $_POST[file_swap];
$orig_file_name = substr($current_file, 0, strlen($current_file) - 4); //extract original filename pre extension
$orig_file_ext = substr($current_file,strlen($current_file)-4,4); //extract original extension
$undo_file = $orig_file_name."_undo".$orig_file_ext;
//echo($_post[cfile]);
} else {
$current_file = $files_list[0];
}
//if undo, then undo file becomes current file, and current file becomes the undo file (you only get one step of undo capability, in the future would be cool to make this an array)
//
// (add code here) //
if (isset($_POST[undo])) {
//create a new file that has the same name as the old file but subtract ".wav" then add time then add wav again
$orig_file_name = substr($current_file, 0, strlen($current_file) - 4); //extract original filename pre extension
$orig_file_ext = substr($current_file,strlen($current_file)-4,4); //extract original extension
//change the name of undo file to _temp
exec("mv ".$ssh_dir."/".$undo_file." ".$ssh_dir."/".$orig_file_name."_temp".$orig_file_ext);
//change the name of current_file to _undo
exec("mv ".$ssh_dir."/".$current_file." ".$ssh_dir."/".$orig_file_name."_undo".$orig_file_ext);
//change the name of undo file (now known as "_temp") to current file's name
exec("mv ".$ssh_dir."/".$orig_file_name."_temp".$orig_file_ext." ".$ssh_dir."/".$current_file);
}
if (isset($_POST[revers])) {
//create a new file that has the same name as the old file but subtract ".wav" then add time then add wav again
$orig_file_name = substr($current_file, 0, strlen($current_file) - 4); //extract original filename pre extension
$orig_file_ext = substr($current_file,strlen($current_file)-4,4); //extract original extension
$temp_file = $orig_file_name.time().$orig_file_ext; //combine with timestamp
$output = exec("/home/jasonsigal/soxtest/bin/sox ".$ssh_dir."/".$current_file." ".$ssh_dir."/".$temp_file." reverse");
//mv oldname newname rename current file to undo file so the name is $orig_file_name."_undo".$orig_file_ext
//echo($output."\n");
exec("mv ".$ssh_dir."/".$current_file." ".$ssh_dir."/".$orig_file_name."_undo".$orig_file_ext);
//echo($output."\n");
//rename temp file to current file
exec("mv ".$ssh_dir."/".$temp_file." ".$ssh_dir."/".$current_file);
//echo($output."\n");
$undo_file = $orig_file_name."_undo".$orig_file_ext;
/*
echo("The Current File is ".$ssh_dir."/".$current_file);
echo("\n");
echo("The Undo File is ".$ssh_dir."/".$undo_file);
echo($temp_file);
echo($ssh_dir."/".$current_file);
//echo($output);
*/
echo($current_file);
}
if (isset($_POST[speed_change_small])) {
$speed_change = $_POST[speed_amt_small];
//echo("speed changed by ".$_POST[speed_amt_small]."%");
$speed_change = $speed_change/100;
echo("speed changed by ".$_POST[speed_amt_small]."%");
//create a new file that has the same name as the old file but subtract ".wav" then add time then add wav again
$orig_file_name = substr($current_file, 0, strlen($current_file) - 4); //extract original filename pre extension
$orig_file_ext = substr($current_file,strlen($current_file)-4,4); //extract original extension
$temp_file = $orig_file_name.time().$orig_file_ext; //combine with timestamp
$output = exec("/home/jasonsigal/soxtest/bin/sox ".$ssh_dir."/".$current_file." ".$ssh_dir."/".$temp_file." speed ".$speed_change);
//mv oldname newname rename current file to undo file so the name is $orig_file_name."_undo".$orig_file_ext
exec("mv ".$ssh_dir."/".$current_file." ".$ssh_dir."/".$orig_file_name."_undo".$orig_file_ext);
//rename temp file to current file
exec("mv ".$ssh_dir."/".$temp_file." ".$ssh_dir."/".$current_file);
$undo_file = $orig_file_name."_undo".$orig_file_ext;
}
if (isset($_POST[speed_change_big])) {
$speed_change = $_POST[speed_amt_big];
echo("speed changed by ".$_POST[speed_amt_big]."%");
$speed_change = $_POST[speed_amt_big]/100;
//create a new file that has the same name as the old file but subtract ".wav" then add time then add wav again
$orig_file_name = substr($current_file, 0, strlen($current_file) - 4); //extract original filename pre extension
$orig_file_ext = substr($current_file,strlen($current_file)-4,4); //extract original extension
$temp_file = $orig_file_name.time().$orig_file_ext; //combine with timestamp
$output = exec("/home/jasonsigal/soxtest/bin/sox ".$ssh_dir."/".$current_file." ".$ssh_dir."/".$temp_file." speed ".$speed_change);
//mv oldname newname rename current file to undo file so the name is $orig_file_name."_undo".$orig_file_ext
exec("mv ".$ssh_dir."/".$current_file." ".$ssh_dir."/".$orig_file_name."_undo".$orig_file_ext);
//rename temp file to current file
exec("mv ".$ssh_dir."/".$temp_file." ".$ssh_dir."/".$current_file);
$undo_file = $orig_file_name."_undo".$orig_file_ext;
}
if (isset($_POST[lowpass])) {
$freq = $_POST[freq];
echo("Low Pass Filter Applied at ".$freq."Hz");
//create a new file that has the same name as the old file but subtract ".wav" then add time then add wav again
$orig_file_name = substr($current_file, 0, strlen($current_file) - 4); //extract original filename pre extension
$orig_file_ext = substr($current_file,strlen($current_file)-4,4); //extract original extension
$temp_file = $orig_file_name.time().$orig_file_ext; //combine with timestamp
$output = exec("/home/jasonsigal/soxtest/bin/sox ".$ssh_dir."/".$current_file." ".$ssh_dir."/".$temp_file." lowpass ".$freq);
//mv oldname newname rename current file to undo file so the name is $orig_file_name."_undo".$orig_file_ext
exec("mv ".$ssh_dir."/".$current_file." ".$ssh_dir."/".$orig_file_name."_undo".$orig_file_ext);
//rename temp file to current file
exec("mv ".$ssh_dir."/".$temp_file." ".$ssh_dir."/".$current_file);
$undo_file = $orig_file_name."_undo".$orig_file_ext;
}
if (isset($_POST[highpass])) {
$freq = $_POST[freq];
echo("High Pass Filter Applied at ".$freq."Hz");
//create a new file that has the same name as the old file but subtract ".wav" then add time then add wav again
$orig_file_name = substr($current_file, 0, strlen($current_file) - 4); //extract original filename pre extension
$orig_file_ext = substr($current_file,strlen($current_file)-4,4); //extract original extension
$temp_file = $orig_file_name.time().$orig_file_ext; //combine with timestamp
$output = exec("/home/jasonsigal/soxtest/bin/sox ".$ssh_dir."/".$current_file." ".$ssh_dir."/".$temp_file." highpass ".$freq);
//mv oldname newname rename current file to undo file so the name is $orig_file_name."_undo".$orig_file_ext
exec("mv ".$ssh_dir."/".$current_file." ".$ssh_dir."/".$orig_file_name."_undo".$orig_file_ext);
//rename temp file to current file
exec("mv ".$ssh_dir."/".$temp_file." ".$ssh_dir."/".$current_file);
$undo_file = $orig_file_name."_undo".$orig_file_ext;
}
|
php
| 18 | 0.66375 | 206 | 53.55303 | 132 |
starcoderdata
|
JobHandle ComputeSeamVoxelGrid(ABB chunkBox, int3 seamLocation, out VoxelGrid voxelGrid, JobHandle dependsOn = default)
{
float chunkSize = chunkBox.GetSize().x;
lodOctree.TryGetSeamBox(chunkBox, seamLocation, out ABB seamBox); //TODO: Unnecessary work if there's no seam
float3 seamSize = seamBox.GetSize();
float voxelSize = math.min(seamSize.x, math.min(seamSize.y, seamSize.z));
float3 offset = seamLocation * new float3(chunkSize / 2f) + seamLocation * new float3(voxelSize / 2f);
return ComputeVoxelGrid(seamBox, voxelSize, offset, out voxelGrid, dependsOn);
}
|
c#
| 15 | 0.709265 | 119 | 51.25 | 12 |
inline
|
@RequestMapping(value = "/register/{userType}", method = RequestMethod.POST, consumes = "application/json")
public ResponseEntity<ResponseDTO> saveCustomer(@PathVariable String userType, @RequestBody UserDTO userDTO) {
BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
User user;
UserAuthority authority = new UserAuthority();
if (userType.equalsIgnoreCase("customer")) {
user = new Customer();
authority.setAuthority(authorityRepository.findByName(("CUSTOMER")));
authority.setUser(user);
}
else if (userType.equalsIgnoreCase("advertiser")) {
user = new Advertiser();
authority.setAuthority(authorityRepository.findByName(("ADVERTISER")));
authority.setUser(user);
} else {
return new ResponseEntity<ResponseDTO>(
new ResponseDTO("Cant create that type of user, ony Customer and Advertiser allowed"),
HttpStatus.BAD_REQUEST);
}
user.setFirstName(userDTO.getFirstName());
user.setLastName(userDTO.getLastName());
user.setEmail(userDTO.getEmail());
user.setUsername(userDTO.getUsername());
user.setPassword(encoder.encode(userDTO.getPassword()));
user.setVerifyCode(UUID.randomUUID().toString());
// check if user with the email exist
if (service.findByEmail(user.getEmail()) != null || service.findByUsername(user.getUsername()) != null) {
return new ResponseEntity<ResponseDTO>(new ResponseDTO("User with that username, or email already exists"),
HttpStatus.CONFLICT);
}
user = service.save(user);
userAuthorityRepository.save(authority);
mailSender.sendMail(user.getEmail(), "Registration",
"Click her to finish registration: <a href='http://localhost:8080/api/users/verify/"
+ user.getVerifyCode() + "'>Click</a>");
ResponseDTO dto = new ResponseDTO();
dto.setResponse("Customer has been created Go to " + user.getEmail() + " to verify your account");
return new ResponseEntity<ResponseDTO>(dto, HttpStatus.CREATED);
}
|
java
| 13 | 0.736679 | 111 | 43.976744 | 43 |
inline
|
class Solution {
public int numSubarraysWithSum(int[] nums, int goal) {
int i1 = 0, i2 = 0, s1 = 0, s2 = 0, j = 0, ans = 0;
int n = nums.length;
while (j < n) {
s1 += nums[j];
s2 += nums[j];
while (i1 <= j && s1 > goal) {
s1 -= nums[i1++];
}
while (i2 <= j && s2 >= goal) {
s2 -= nums[i2++];
}
ans += i2 - i1;
++j;
}
return ans;
}
}
|
java
| 13 | 0.338583 | 59 | 25.789474 | 19 |
research_code
|
<?php
/**
* Utility functions
*
* @package wpinstructions
*/
namespace WPInstructions\Utils;
/**
* Check if WP db tables exist
*
* @return boolean
*/
function wp_tables_exist( $host, $database, $user, $password, $table_prefix ) {
$mysqli = mysqli_init();
if ( ! @$mysqli->real_connect( $host, $user, $password, $database ) ) {
return false;
}
$result = $mysqli->query( 'SHOW TABLES' );
$tables = [];
while ( $row = $result->fetch_array() ) {
$tables[] = $row[0];
}
return in_array( $table_prefix . 'users', $tables, true );
}
/**
* Get wp-config.php table prefix
*
* @param string $wp_config_path Path to wp-config.php
* @return string
*/
function get_table_prefix( $wp_config_path ) {
$wp_config_code = explode( "\n", file_get_contents( $wp_config_path ) );
$prefix = null;
foreach ( $wp_config_code as $line ) {
if ( preg_match( '#^[\s]*\$table_prefix.*("|\')(.*?)("|\').*$#', $line ) ) {
return preg_replace( '#^[\s]*\$table_prefix.*?("|\')(.*?)("|\').*$#', '$2', $line );
}
}
return $prefix;
}
|
php
| 12 | 0.570209 | 87 | 20.510204 | 49 |
starcoderdata
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.