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 |
---|---|---|---|---|---|---|---|
// Copyright Ngo Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, 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.
package util
import "strings"
// Symbol 分隔符
type Symbol string
// 标记
const (
Point Symbol = "."
Comma Symbol = ","
Colon Symbol = ":"
Empty Symbol = ""
Blank Symbol = " "
Underline Symbol = "_"
DoubleVerticalBar Symbol = "||"
VerticalBar Symbol = "|"
QuestionMark Symbol = "?"
Percent Symbol = "%"
Enter Symbol = "\n"
)
// Join 通过分割符号将数组转换成字符串
func Join(list []string, symbol Symbol) string {
if len(list) == 0 {
return string(Empty)
}
var l []string
for _, v := range list {
// if v == "" { // 过滤掉为空的数据
// continue // 先去掉兼容java工程
// }
l = append(l, v)
}
r := strings.Join(l, string(symbol))
return strings.Trim(r, string(Blank))
}
// Split 将字符串根据分割符号转换成数组
func Split(s string, symbol Symbol) []string {
var r []string = make([]string, 0)
if s == "" {
return r
}
l := strings.Split(s, string(symbol))
if len(l) == 0 {
return r
}
for _, v := range l {
v = strings.Trim(v, " ")
if v == "" {
continue
}
r = append(r, v)
}
return r
}
// SplitNoRepeat 无重复的数组
func SplitNoRepeat(s string, symbol Symbol) []string {
var r []string = make([]string, 0)
if s == "" {
return r
}
l := strings.Split(s, string(symbol))
if len(l) == 0 {
return r
}
var checker map[string]int = make(map[string]int, len(l))
for _, v := range l {
v = strings.Trim(v, " ")
if v == "" {
continue
}
_, ok := checker[v]
if ok {
continue
}
checker[v] = 0 // 设置检查位
r = append(r, v)
}
return r
}
|
go
| 10 | 0.59645 | 75 | 20.19802 | 101 |
starcoderdata
|
// Import React
import React from "react";
// code slide
import CodeSlide from "spectacle-code-slide";
// Import Spectacle Core tags
import {
BlockQuote,
Cite,
Deck,
Heading,
ListItem,
List,
Quote,
Slide,
Text,
CodePane,
Appear,
Image
} from "spectacle";
// Import image preloader util
import preloader from "spectacle/lib/utils/preloader";
// Import theme
import createTheme from "spectacle/lib/themes/default";
// Require CSS
require("normalize.css");
require("spectacle/lib/themes/default/index.css");
const images = {
awsDiagram: require("../assets/comment-showcase-block-diagram-aws.png"),
onWriteTimeUpper: require("../assets/onWriteTimeUpper.gif"),
firebaseWebapp: require("../assets/webapp.gif"),
invocations: require("../assets/invocations.png"),
restTimestampOnWriteUpper: require("../assets/restTimestamp-onWriteUpper.gif")
};
preloader({ images });
const theme = createTheme({
primary: "#2d2d2d",
secondary: "#77aaff",
tertiary: "#99bbff",
quartenary: "#CECECE"
}, {
primary: "Lucida Grande",
secondary: "Lucida Grande"
});
export default class Presentation extends React.Component {
render() {
return (
<Deck transition={[]} transitionDuration={500} theme={theme} bgColor="primary">
<Slide transition={["fade"]} bgColor="primary" >
<Heading size={2} fill textFont="primary" textColor="secondary" caps>Comments Showcase
<Heading size={4} fit fill textFont="primary" textColor="tertiary" >with Firebase Functions
<Text margin="30px 0 0" textColor="quartenary" size={5} >
@l_kiraly
<Slide transition={["fade"]} bgColor="primary" textColor="secondary">
<Quote textColor="secondary">It is hard to write even the smallest piece of code correctly.
<Cite textColor="secondary">
<Text size={6} textColor="tertiary">https://research.googleblog.com/2006/06/extra-extra-read-all-about-it-nearly.html
<Slide transition={["fade", "zoom", "slide"]}>
<List textFont="secondary" textColor="tertiary">
hard
make it work
make it work right
make it work fast
make it serverless scalable
<Heading size={4} fit textFont="primary" textColor="secondary" caps>Writing Code
<Slide transition={["spin", "fade"]} bgColor="white" >
<Image src={images.firebaseWebapp.replace("/", "")} margin="0px" height="600px" />
<Heading size={4} textFont="primary" textColor="secondary" caps>The Frontend
<Slide transition={["spin", "fade"]} bgColor="white" >
<Image src={images.awsDiagram.replace("/", "")} margin="0px auto 10px" />
<Heading size={4} fit textFont="primary" textColor="secondary" caps>AWS - Comments Showcase
<Slide transition={["slide"]}>
<CodePane source={require("raw-loader!../assets/code/result.ascii")}/>
<Heading size={4} fit textFont="primary" textColor="secondary" caps>Firebase - Comments Showcase
{/* <Heading size={4} fit textFont="primary" textColor="secondary" caps>a case for upper */}
<CodeSlide
lang="js"
code={require("raw-loader!../assets/code/client-firebase.code")}
ranges={[
{ loc: [0, 11], title: "Client Side" },
{ loc: [0, 6], title: "Client Side" },
{ loc: [1, 2], title: "Client Side" },
{ loc: [3, 5], title: "Client Side" },
{ loc: [7, 10], title: "Client Side" }
]}
/>
<Slide transition={["slide"]}>
<CodePane source={require("raw-loader!../assets/code/firebase-uppercase.ascii")}/>
<Heading size={4} fit textFont="primary" textColor="secondary" caps>a case for upper
<CodeSlide
lang="js"
code={require("raw-loader!../assets/code/uppercasing.code")}
ranges={[
{ loc: [0, 11], title: "Uppercasing" },
{ loc: [0, 1], title: "Uppercasing" },
{ loc: [1, 2], title: "Uppercasing" },
{ loc: [2, 3], title: "Uppercasing" },
{ loc: [4, 8], title: "Uppercasing" },
{ loc: [7, 8], title: "Uppercasing", note: "Timeout bug: http://stackoverflow.com/questions/43151022/firebase-cloud-function-onwrite-timeout probably fixed by now" }
]}
/>
<Slide transition={["slide"]}>
<CodePane source={require("raw-loader!../assets/code/firebase-timestamp.ascii")}/>
<Heading size={4} fit textFont="primary" textColor="secondary" caps>let's add the timestamp
<CodeSlide transition={[]}
lang="js"
code={require("raw-loader!../assets/code/timestamp.code")}
ranges={[
{ loc: [0, 12], title: "Adding Timestamp" },
{ loc: [1, 3], title: "Adding Timestamp" },
{ loc: [4, 9], title: "Adding Timestamp" },
{ loc: [6, 9], title: "Adding Timestamp", note: "Can you spot the problem?" }
]}
/>
<Slide transition={[]} bgColor="white">
<Heading size={5} textFont="primary" textColor="secondary" caps>infinite loop!
<Image src={images.invocations.replace("/", "")} margin="0px" height="600px"/>
<CodeSlide
lang="js"
code={require("raw-loader!../assets/code/timestamp-guard.code")}
ranges={[
{ loc: [6, 13], title: "Adding Guard", note: "No more infinite loop!" }
]}
/>
<Slide transition={[]} bgColor="white">
<Heading size={5} textFont="primary" textColor="secondary" caps>push in action
<Image src={images.onWriteTimeUpper.replace("/", "")} margin="0px" height="600px"/>
<Slide transition={["slide"]}>
<CodePane lang="java" source={require("raw-loader!../assets/code/firebase-timestamp-uppercase.ascii")}/>
<Heading size={4} fit textFont="primary" textColor="secondary" caps>let's use REST
<CodeSlide
lang="js"
code={require("raw-loader!../assets/code/client-firebase-rest.code")}
ranges={[
{ loc: [0, 17], title: "Client Side Post" },
{ loc: [2, 4], title: "Client Side Post" },
{ loc: [5, 12], title: "Client Side Post" },
{ loc: [13, 14], title: "Client Side Post" }
]}
/>
<Slide transition={[]} bgColor="white">
<Heading size={5} textFont="primary" textColor="secondary" caps>REST in action
<Image src={images.restTimestampOnWriteUpper.replace("/", "")} margin="0px" height="600px"/>
<Slide transition={["slide"]}>
<CodePane lang="java" source={require("raw-loader!../assets/code/firebase-uppercase-inbox.ascii")}/>
<Heading size={4} fit textFont="primary" textColor="secondary" caps>Or use inbox
<Slide transition={["slide"]}>
<CodePane source={require("raw-loader!../assets/code/result.ascii")}/>
<Heading size={4} fit textFont="primary" textColor="secondary" caps>Firebase - Comments Showcase
{/* <Heading size={4} fit textFont="primary" textColor="secondary" caps>a case for upper */}
<CodeSlide
lang="js"
code={require("raw-loader!../assets/code/database-rules.json")}
ranges={[
{ loc: [0, 8], title: "firebase auth rules" }
]}
/>
<CodeSlide
lang="js"
code={require("raw-loader!../assets/code/client-firebase-auth.code")}
ranges={[
{ loc: [0, 11], title: "Client Side Auth" },
{ loc: [0, 4], title: "Client Side Auth", note: "https://firebase.google.com/docs/auth/web/google-signin#advanced-handle-the-sign-in-flow-manually" },
{ loc: [5, 8], title: "Client Side Auth", note: "https://firebase.google.com/docs/auth/web/google-signin#advanced-handle-the-sign-in-flow-manually" },
{ loc: [9, 10], title: "Client Side Auth" }
]}
/>
<CodeSlide
lang="js"
code={require("raw-loader!../assets/code/client-firebase-rest-auth.code")}
ranges={[
{ loc: [0, 19], title: "Post Auth" },
{ loc: [2, 4], title: "Post Auth" },
{ loc: [5, 14], title: "Post Auth" },
{ loc: [15, 16], title: "Post Auth" }
]}
/>
<Slide transition={["fade", "zoom", "slide"]}>
<List textFont="secondary" textColor="tertiary">
is a node project
built in
npm client libs
hosting, functions, database only
<Heading size={4} fit textFont="primary" textColor="secondary" caps>Developer Experience: The good
<Slide transition={["fade", "zoom", "slide"]}>
<List textFont="secondary" textColor="tertiary">
Deployment (minutes not seconds)
"before" write function
<Heading size={4} fit textFont="primary" textColor="secondary" caps>Developer Experience: The bad
<Slide transition={["fade", "zoom", "slide"]}>
<List textFont="secondary" textColor="tertiary">
failing Deployments
ending Deployment
Bug $$$
<Heading size={4} fit textFont="primary" textColor="secondary" caps>Developer Experience: The ugly
<Slide transition={["fade", "zoom", "slide"]}>
<List textFont="secondary" textColor="tertiary">
functions
and authorization
as plugins
Capabilities
<Heading size={4} fit textFont="primary" textColor="secondary" caps>What's next
<Slide transition={["fade"]} bgColor="primary" textColor="tertiary">
<Heading size={2} textColor="secondary" caps>Save the Dates
<Heading size={4} fit margin="40px 0px" textColor="tertiary" caps>May 10th, Coding Session, Stockwerk
<Heading size={4} fit margin="40px 0px" textColor="tertiary" caps>May 15th, Serverless and Microservices
<Slide transition={["fade"]} bgColor="primary" textColor="tertiary">
<Heading size={2} textColor="secondary" caps>Links
<Heading size={4} fit margin="40px 0px" textColor="tertiary" caps>https://github.com/Serverless-Vienna/Comments-Showcase/tree/firebase
<Heading size={4} fit margin="40px 0px" textColor="tertiary" caps>https://serverless-vienna.firebaseapp.com/
);
}
}
|
javascript
| 15 | 0.59123 | 178 | 46.972112 | 251 |
starcoderdata
|
;(window.webpackJsonp = window.webpackJsonp || []).push([
[22],
{
FoVR: function (e, a, t) {
"use strict"
t.r(a)
var i = t("q1tI"),
l = t.n(i),
r = t("7oih"),
n = t("Wbzz"),
o = t("9eSz"),
s = t.n(o)
a.default = function () {
var e = Object(n.c)("2784220179")
return l.a.createElement(
r.a,
null,
l.a.createElement(
"div",
{ className: "img-wrapper img-wrapper-about" },
l.a.createElement(s.a, {
Tag: "div",
fluid: e.file.childImageSharp.fluid,
className: " bcg bcg-about ",
}),
l.a.createElement(
"h2",
{ className: "about-header visibility-filter " },
"Upute za preuzimanje"
),
l.a.createElement(
"h2",
{ className: "about-header mobile-visible" },
"Podrška"
)
),
l.a.createElement(
"div",
{ className: "about-content visibility-filter" },
l.a.createElement(
"h4",
{ className: "about-paragraph support-paragraph " },
l.a.createElement(
"ol",
null,
l.a.createElement(
"li",
null,
"Pritisnuti ikonu TeamViewera (plava ikona desno)"
),
l.a.createElement(
"li",
null,
"Na sljedećem prozoru pritisnuti tipku “Run”"
),
l.a.createElement(
"li",
null,
"Nakon što se program izvrši molimo dostaviti sistem administratoru “Vaš ID”"
)
)
)
),
l.a.createElement(
"div",
{ className: "about-content support-mobile-visible" },
l.a.createElement(
"h4",
{ className: "about-paragraph " },
"Podrška je trenutno dostupna samo za osobna računala!"
)
),
l.a.createElement(
n.a,
{
to:
"https://dl.dropboxusercontent.com/s/7dlra3rudbrsuk3/Udaljena%20podrska.exe?dl=0",
className: "teamviewer-img visibility-filter",
},
l.a.createElement(s.a, { fluid: e.otherFile.childImageSharp.fluid })
)
)
}
},
},
])
//# sourceMappingURL=component---src-pages-podrska-js-189c8e0594d50e32a658.js.map
|
javascript
| 21 | 0.42905 | 98 | 29.511364 | 88 |
starcoderdata
|
/* eslint-disable jsx-a11y/href-no-hash */
import React from 'react';
import Designer from '@od/react-preview/Designer';
export default class extends React.Component {
constructor(props) {
super(props);
this.state = {
objects: [{
"width": 163,
"height": 84,
"rotate": 0,
"strokeWidth": 0,
"fill": "rgba(0, 123, 255, 1)",
"radius": "0",
"blendmode": "normal",
"type": "rectangle",
"x": 17,
"y": 15,
"isclosed": "true"
}, {
"width": 70,
"height": 146,
"rotate": 0,
"strokeWidth": 0,
"fill": "rgba(255, 255, 255, 1)",
"radius": "0",
"blendmode": "normal",
"type": "rectangle",
"x": 19,
"y": 109
}, {
"width": 81,
"height": 69,
"rotate": 0,
"strokeWidth": 0,
"fill": "rgba(241, 97, 99, 1)",
"radius": "0",
"blendmode": "normal",
"type": "rectangle",
"x": 100,
"y": 110
}, {
"width": 231,
"height": 70,
"rotate": 0,
"strokeWidth": 0,
"fill": "rgba(0, 123, 255, 1)",
"radius": "0",
"blendmode": "normal",
"type": "rectangle",
"x": 100,
"y": 187
}, {
"width": 183,
"height": 60,
"rotate": 0,
"strokeWidth": 0,
"fill": "rgba(255, 241, 0, 1)",
"radius": "0",
"blendmode": "normal",
"type": "rectangle",
"x": 19,
"y": 265
}, {
"width": 118,
"height": 119,
"rotate": 0,
"strokeWidth": 0,
"fill": "rgba(241, 97, 99, 1)",
"radius": "0",
"blendmode": "normal",
"type": "rectangle",
"x": 211,
"y": 266
}, {
"width": 82,
"height": 51,
"rotate": 0,
"strokeWidth": 0,
"fill": "rgba(255, 255, 255, 1)",
"radius": "0",
"blendmode": "normal",
"type": "rectangle",
"x": 120,
"y": 333
}, {
"width": 89,
"height": 50,
"rotate": 0,
"strokeWidth": 0,
"fill": "rgba(241, 97, 99, 1)",
"radius": "0",
"blendmode": "normal",
"type": "rectangle",
"x": 21,
"y": 334
}, {
"width": 143,
"height": 160,
"rotate": 0,
"strokeWidth": 0,
"fill": "rgba(255, 241, 0, 1)",
"radius": "0",
"blendmode": "normal",
"type": "rectangle",
"x": 190,
"y": 16
}]
}
}
handleUpdate(objects) {
this.setState({objects});
}
download(event) {
let realWidth = '36in';
let realHeight = '48in';
event.preventDefault();
let svgElement = this.designer.svgElement;
svgElement.setAttribute('xmlns', 'http://www.w3.org/2000/svg');
svgElement.setAttribute("width", realWidth);
svgElement.setAttribute("height", realHeight);
svgElement.setAttribute("viewBox", "64 11 318 424");
svgElement.setAttribute("xml:space", "preserve");
svgElement.setAttribute("preserveAspectRatio", "none");
let source = svgElement.outerHTML;
let wd = window.open("_blank");
wd.document.body.innerHTML = "";
wd.document.write(source);
wd.focus();
wd = null;
}
render() {
return (
<Designer
ref={(ref) => this.designer = ref}
width={350} height={400}
objects={this.state.objects}
onUpdate={this.handleUpdate.bind(this)}/>
<a href="#" onClick={this.download.bind(this)}>Export SVG
);
}
}
|
javascript
| 14 | 0.364234 | 81 | 29.616883 | 154 |
starcoderdata
|
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use App\data_web;
class GaleriController extends Controller
{
//
public function index(){
$logoweb = data_web::find(6);
$logolembaga = data_web::find(5);
$crfoot = data_web::find(14);
$albums = DB::table('albums')
->join('pictures', 'albums.idDisplay','pictures.id')
->select('albums.*','pictures.name as picture','pictures.location')
->paginate(4);
return view('galeri.index',[
'logoweb'=>$logoweb,
'logolembaga'=>$logolembaga,
'crfoot'=>$crfoot,
'albums'=>$albums
]);
}
public function showAlbum(Request $request, $id){
$request->session()->put('idAlbum',$id);
$picture = DB::table('album_picture')
->join('pictures','album_picture.idPicture','pictures.id')
->select('pictures.name')
->where('album_picture.idAlbum', $id)
->get();
$video = DB::table('album_video')
->join('videos','album_video.idVideo','videos.id')
->select('videos.name')
->where('album_video.idAlbum', $id)
->get();
return view('galeri.show',[
'video'=>$video,
'picture'=>$picture
]);
}
}
|
php
| 15 | 0.551051 | 75 | 29.976744 | 43 |
starcoderdata
|
package uzuzjmd.competence.config;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Properties;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
public class PropUtil {
public static HashMap defaults;
private static Logger logger = LogManager
.getLogger(PropUtil.class);
public static boolean _amServer() {
StackTraceElement[] elements = new Throwable()
.getStackTrace();
for (StackTraceElement element : elements) {
if (element
.getClassName()
.equals("org.apache.catalina.core.StandardEngineValve")) {
return true;
}
}
return false;
}
public static Properties getProperties() {
Properties prop = new Properties();
String propfFileName = "evidenceserver.properties";
InputStream inputStream = null;
if (_amServer()) {
// find file
inputStream = Thread.currentThread()
.getContextClassLoader()
.getResourceAsStream(propfFileName);
} else {
try {
inputStream = new FileInputStream(
propfFileName);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
try {
prop.load(inputStream);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return prop;
}
public static String getProp(String key) {
try {
return getProperties().getProperty(key)
.replaceAll("\"", "");
} catch (NullPointerException p) {
logger.error("property " + key
+ " is not set!!!");
}
return null;
}
/**
* adds the rootPath as prefix
*
* @param key
* @return
*/
public static String getRelativeFileProp(String key) {
return MagicStrings.ROOTPATH
+ getProperties().getProperty(key)
.replaceAll("\"", "");
}
public static String getRelativeOrAbsoluteFileProp(
String relativeKey, String absoluteKey) {
if (getProperties().getProperty(relativeKey) != null) {
return MagicStrings.ROOTPATH
+ getProperties().getProperty(
relativeKey).replaceAll("\"",
"");
} else {
return getProperties().getProperty(absoluteKey)
.replaceAll("\"", "");
}
}
}
|
java
| 14 | 0.687767 | 84 | 21.480769 | 104 |
starcoderdata
|
@Test
void getDataset_whenIdIsNotValid_throwException() {
// Set Security Context
SecurityContext.set(null);
assertThrows(NotFoundException.class,
() -> datasetService.getDataset("invalid_dataset_id", false)
);
}
|
java
| 10 | 0.620818 | 76 | 29 | 9 |
inline
|
// Copyright Giemsa 2015
// Distributed under the Boost Software License, Version 1.0
#ifndef MW_KOTO_STRING_BASE_HPP
#define MW_KOTO_STRING_BASE_HPP
namespace koto
{
namespace detail
{
template<typename E, bool D>
class string_base
{
public:
static const bool is_dynamic_encoding = D;
private:
template<bool C = D>
static const typename detail::enable_if<C, const encoding>::type *create_default_encoding();
template<bool C = D>
static const typename detail::enable_if<!C, const encoding>::type *create_default_encoding()
{
return NULL;
}
protected:
static const encoding *default_encoding_;
public:
static void set_default_encoding(const encoding *encoding)
{
default_encoding_ = encoding;
}
static const encoding *get_default_encoding()
{
return default_encoding_;
}
};
template<typename E, bool D>
const encoding *string_base<E, D>::default_encoding_ = string_base<E, D>::create_default_encoding();
}
}
#endif
|
c++
| 18 | 0.560618 | 108 | 26.311111 | 45 |
starcoderdata
|
package com.candeo.app.util;
import android.content.Context;
import android.text.TextUtils;
import android.util.Log;
import com.candeo.app.Configuration;
import com.candeo.app.algorithms.Security;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.DefaultHttpRequestRetryHandler;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
/**
* Created by partho on 25/10/14.
*/
public class JSONParser {
/*
* Parses GET request
* */
public static JSONObject parseGET(String url, Context mContext, String relativeUrl)
{
InputStream inputStream=null;
JSONObject json = null;
/*
API URL is getting read and stored to inputStream
*/
System.out.println("URL is: "+url);
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
httpClient.setHttpRequestRetryHandler(new DefaultHttpRequestRetryHandler(3,true));
HttpGet get = new HttpGet(url);
String secret="";
if(TextUtils.isEmpty(Preferences.getUserEmail(mContext)))
{
secret= Configuration.CANDEO_DEFAULT_SECRET;
}
else
{
secret=Preferences.getUserApiKey(mContext);
}
String message = relativeUrl;
String hash = Security.generateHmac(secret, message);
get.setHeader("message",message);
if(Configuration.DEBUG)Log.e("JsonParser","Message is "+message);
get.setHeader("email",Preferences.getUserEmail(mContext));
get.setHeader("Authorization", "Token token=" + hash);
if(Configuration.DEBUG)Log.e("JsonParser","Hash is "+hash);
HttpResponse response = httpClient.execute(get);
HttpEntity entity = response.getEntity();
inputStream = entity.getContent();
System.out.println("InputStream is: "+inputStream);
}catch (UnsupportedEncodingException ex)
{
ex.printStackTrace();
}catch (ClientProtocolException cpe)
{
cpe.printStackTrace();
}catch (IOException ie)
{
ie.printStackTrace();
}
/*
Inputstream is parsed to fetch string and convert in jsonObject to return
*/
StringBuilder result=new StringBuilder();
if(inputStream!=null)
{
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
String line="";
while ((line=reader.readLine())!= null)
{
result.append(line+"\n");
}
inputStream.close();
reader.close();
json = new JSONObject(result.toString());
}catch (UnsupportedEncodingException ue)
{
ue.printStackTrace();
}catch (IOException ie)
{
ie.printStackTrace();
}catch (JSONException je)
{
je.printStackTrace();
}
}
System.out.println("Incoming JSON: "+result.toString());
return json;
}
/*
* Parses POST request
* */
public static JSONObject parsePOST(String url)
{
InputStream inputStream=null;
JSONObject json = null;
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpResponse response = httpClient.execute(new HttpPost(url));
HttpEntity entity = response.getEntity();
inputStream = entity.getContent();
}catch (UnsupportedEncodingException ex)
{
ex.printStackTrace();
}catch (ClientProtocolException cpe)
{
cpe.printStackTrace();
}catch (IOException ie)
{
ie.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
StringBuffer result=new StringBuffer();
String line="";
while ((line=reader.readLine())!= null)
{
result.append(line+"\n");
}
inputStream.close();
reader.close();
json = new JSONObject(result.toString());
}catch (UnsupportedEncodingException ue)
{
ue.printStackTrace();
}catch (IOException ie)
{
ie.printStackTrace();
}catch (JSONException je)
{
je.printStackTrace();
}
return json;
}
}
|
java
| 16 | 0.582019 | 104 | 29.554217 | 166 |
starcoderdata
|
#!/usr/bin/env python3
## portproof.py
# Create test list, check for port collisions.
import sys
from wgcore import loadconfig, saveconfig, CheckConfig
import click
import loguru
import attr, inspect
from loguru import logger
@click.command()
@click.option('--debug','-d', is_flag=True, default=False, help="Activate Debug Logging.")
@click.option('--trace','-t', is_flag=True, default=False, help="Activate Trace Logging.")
@click.argument('infile')
def Main(debug, trace, infile):
f''' Update or publish INFILE to Folder specified by OUTPUT {output} for [SITES] '''
if not debug:
logger.info('Debug')
logger.remove()
logger.add(sys.stdout, level='INFO')
pass
if trace:
logger.info('Trace')
logger.remove()
logger.add(sys.stdout, level='TRACE')
pass
site, hosts = CheckConfig(*loadconfig(infile))
taken = []
closed = []
for me in hosts:
pb = site.portbase
my_octet = int(str(me.ipv4).split('.')[-1])
for this in hosts:
if me.hostname == this.hostname: continue
this_octet = int(str(this.ipv4).split('.')[-1])
sideA = f'{this.hostname}:{pb + my_octet}'
sideB = f'{me.hostname}:{pb + this_octet}'
temp = [ sideA, sideB ]
temp.sort()
if sideA in taken or sideB in taken:
if temp not in closed:
print(f'ERROR: {temp} Collsion but something WRONG.')
pass
else:
closed.append(temp)
continue
continue
return 0
if __name__ == "__main__":
sys.exit(Main())
|
python
| 18 | 0.579847 | 90 | 28.789474 | 57 |
starcoderdata
|
module.exports = (sequelize, DataTypes) => {
const PdfDoc = sequelize.define('PdfDoc', {
doctype: DataTypes.STRING,
expediteur: DataTypes.STRING,
subject: DataTypes.STRING,
pdfname: DataTypes.STRING,
}, {});
PdfDoc.associate = function(models) {
// associations can be defined here
};
return PdfDoc;
};
|
javascript
| 9 | 0.621176 | 51 | 25.625 | 16 |
starcoderdata
|
#!/usr/bin/env python3
import re
from collections import defaultdict, Counter
from flask_restful import Resource
import arrow
sep = re.compile(r'\n| ')
def separate_words(text):
return sep.split(text)
strip = re.compile(r'\(|\)|\'|\"|\?|,|\.|!')
def preprocess(text):
words = separate_words(text)
basic_words = (strip.sub('', word) for word in words)
return (word.lower() for word in basic_words)
def ngrams(corpus, n=2):
tokens = list(preprocess(corpus))
offsets = (tokens[offset:] for offset in range(n))
return set(zip(*offsets))
def sublist_index(lst, sublst):
n = len(sublst)
lst, sublst = list(lst), list(sublst)
matches = [sublst == lst[i:i+n] for i in range(len(lst))]
return matches.index(True) if True in matches else -1
from itertools import chain
def select_text(text, query):
cleaned_words = list(preprocess(query))
cleaned_text_words = list(preprocess(text))
words_combinations = list(chain.from_iterable(ngrams(query, n)
for n in range(1, len(cleaned_words) + 1)))
for words_combination in reversed(words_combinations):
start_location = sublist_index(cleaned_text_words, words_combination)
if start_location != -1:
text_words = list(separate_words(text))
lo = max(0, start_location - 5)
hi = min(len(text_words) - 1, start_location + len(words_combination) + 5)
first_words = ' '.join(text_words[lo: start_location])
last_words = ' '.join(text_words[start_location + len(words_combination): hi])
middle_words = ' '.join(text_words[start_location: start_location + len(words_combination)])
return '{} _{}_ {}'.format(first_words, middle_words, last_words)
class invertedindex:
def __init__(self, accuracy=8):
self.index = defaultdict(list)
self.texts = {}
self.text_lengths = {}
self.accuracy = accuracy
def __setitem__(self, date, text):
self.add(date, text)
def __getitem__(self, text):
return self.query(text)
def add(self, date, text):
self.texts[date] = text
self.text_lengths[date] = len(separate_words(text))
for n in range(1, self.accuracy):
for ngram in ngrams(text, n):
dates = self.index[ngram]
dates.append(date)
def query(self, text, count=10):
bigrams = ngrams(text)
results = Counter()
for n in range(1, self.accuracy):
for ngram in ngrams(text, n):
results.update(self.index[ngram] * (n ** 2))
return [(date, self.texts[date])
for date, count in results.most_common(count)]
def create_index(filename, accuracy=8):
with open(filename, 'r') as f:
text = f.read()
comics_sep = re.compile(r'(ch[\d]{6})(?:: )(.*?)(?= ch[0-9]{6})')
comics = comics_sep.findall(text)
index = invertedindex(accuracy)
for comic, text in comics:
date = arrow.get(comic, 'YYMMDD')
index[date] = text
return index
|
python
| 16 | 0.675273 | 95 | 30.609195 | 87 |
starcoderdata
|
@Override
public void onDisconnected(String endpointId, String endpointName) {
Log.i(TAG, String.format("onDisconnected called: userId=%s userName=%s", endpointId, endpointName));
// inform BertyBridge that there is a new connection
mTransport.handleLostPeer(endpointName);
}
|
java
| 9 | 0.67378 | 112 | 46 | 7 |
inline
|
package kariminf.nalangen.nlg.simplenlg;
import simplenlg.lexicon.Lexicon;
public class EngRealizer extends SNLGRealizer {
public EngRealizer() {
super(new EngSnlgMap(), Lexicon.getDefaultLexicon());
}
@Override
protected String getOrdinal(String number) {
int nbr = 0;
try {
nbr = Integer.parseInt(number);
}
catch (NumberFormatException e){
return "first";
}
switch(nbr){
case 1: return "first";
case 2: return "second";
case 3: return "third";
case 4: return "fourth";
case 5: return "fifth";
case 6: return "sixth";
case 7: return "seventh";
case 8: return "eighth";
case 9: return "nineth";
case 10: return "tenth";
}
return nbr + "th";
}
}
|
java
| 9 | 0.666667 | 55 | 17.923077 | 39 |
starcoderdata
|
Nodes/ShaderGraph_LightNodes-master/Editor/ShaderGraphNodes/LambertNode.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor.ShaderGraph;
using System.Reflection;
[Title("Custom", "Lambert")]
public class LambertNode : CodeFunctionNode
{
public LambertNode()
{
name = "Lambert";
}
protected override MethodInfo GetFunctionToConvert()
{
return GetType().GetMethod("LambertNodeFunction",
BindingFlags.Static | BindingFlags.NonPublic);
}
public override void GenerateNodeFunction(FunctionRegistry registry, GraphContext graphContext, GenerationMode generationMode)
{
base.GenerateNodeFunction(registry, graphContext, generationMode);
}
static string LambertNodeFunction(
[Slot(0, Binding.None)] Vector3 LightDirection,
[Slot(1, Binding.None)] Vector3 AttenuatedLightColor,
[Slot(2, Binding.WorldSpaceNormal)] Vector3 WorldNormal,
[Slot(3, Binding.None)] out Vector3 OutputColor
)
{
OutputColor = Vector3.zero;
return Shader;
}
public static string Shader = @"{
half NdotL = saturate(dot(WorldNormal, LightDirection));
OutputColor = AttenuatedLightColor * NdotL;
}";
}
|
c#
| 11 | 0.724421 | 157 | 34.263158 | 38 |
starcoderdata
|
// 期間の分割
var koyomi = require('../..').create();
var sp = koyomi.separate.bind(koyomi);
var eq = require('assert').deepEqual;
koyomi.startMonth = 1;
// 2015-1-1 .. 2015/12/31
var r = sp(new Date(2015, 0, 1), new Date(2015, 11, 31));
eq(r, {
years: [new Date(2015, 0, 1)],
months: [],
days: []
});
// ここのテストはutils/separate.jsで細かく行います
|
javascript
| 9 | 0.612903 | 57 | 20.375 | 16 |
starcoderdata
|
def __init__(self, sim=None, name="", boundary=None,
cam_object=None, cam_center=(0,0),
wt_object=None, wt_attach=(0,0),
length=None):
Constraint.__init__(self, sim, name=name)
self.frames = [cam_object.frame, wt_object.frame]
self.cam_frame = cam_object.frame
self.center = cam_object.obj2frame(mat(cam_center).T)
self.camu = 0.0 # cam parameter in range [0,1]
self.frame0 = self.cam_frame
self.frame1, self.xframe1 = wt_object.frame, wt_object.obj2frame(mat(wt_attach).T)
self.total_length = length
self.dim = 1
boundary = cam_object.obj2frame(boundary.T).T + self.center.T
boundary = convex_hull.hull(boundary)
# periodic cubic spline fit to boundary
self.camtck,foo = splprep([boundary[:,0],boundary[:,1]], # @UnusedVariable
per=True, quiet=0, k=3, s=0)
# build interpolation spline for line integral
u=linspace(0,1,num=1000)
v=splev(u, self.camtck)
diffx = diff(v[0])
diffy = diff(v[1])
l = sqrt(diffx**2.0 + diffy**2.0)
l = cumsum(hstack([0, l]))
self.lspline = UnivariateSpline(u, l, s=0)
self.camu = 0.5
|
python
| 11 | 0.561912 | 90 | 44.607143 | 28 |
inline
|
public OpcPackage clone() {
OpcPackage result = null;
// Zip it up
ByteArrayOutputStream baos = new ByteArrayOutputStream();
SaveToZipFile saver = new SaveToZipFile(this);
try {
saver.save(baos);
result = load(new ByteArrayInputStream(baos.toByteArray()));
} catch (Docx4JException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return result;
}
|
java
| 13 | 0.6875 | 63 | 21.277778 | 18 |
inline
|
<?php defined('BASEPATH') OR exit('No direct script access allowed');
class WORKOUT extends CI_Controller {
public function WORKOUT(){
parent::__construct();
$this->load->view('frontend/include/header');
$data['menunav'] = "workout";
$this->load->view('frontend/include/navbar', $data);
$this->load->model("WORKOUTMODEL");
$this->load->model("CENTRALCONTENTMODEL");
}
public function index(){
$data['vdoCentralMedia'] = $this->CENTRALCONTENTMODEL->getMediaByTypeAndPage("VDO", "WORKOUT")->result_array();
$this->load->view('frontend/home-section', $data);
$data['activityType'] = "all";
$data['allWeightTraining'] = $this->WORKOUTMODEL->getAllWorkOutByType("weightTraining")->result_array();
$data['allCardio'] = $this->WORKOUTMODEL->getAllWorkOutByType("cardio")->result_array();
$data['contentCentral'] = $this->CENTRALCONTENTMODEL->getContentByPage("WORKOUT")->result_array();
$data['imageCentralMedia'] = $this->CENTRALCONTENTMODEL->getMediaByTypeAndPage("IMAGE", "WORKOUT")->result_array();
$this->load->view('frontend/workout-item', $data);
$this->load->view('frontend/include/footer');
}
public function detail($workoutId){
if($workoutId != ''){
$this->WORKOUTMODEL->updateWorkoutViewById($workoutId);
$rs = $this->WORKOUTMODEL->getWorkOutByWorkOutId($workoutId);
$workout = $rs->result_array();
$data['workout'] = $workout;
$relatedWorkout = $this->WORKOUTMODEL->getLastFourWorkOutByTypeAndExceptCaller($workout[0]['workoutGroup'], $workoutId);
$data['relatedWorkout'] = $relatedWorkout->result_array();
$this->load->view('frontend/workout-detail', $data);
$this->load->view('frontend/include/footer');
}
}
public function detailcriteria($type){
$this->load->model("CENTRALCONTENTMODEL");
$data['vdoCentralMedia'] = $this->CENTRALCONTENTMODEL->getMediaByTypeAndPage("VDO", "WORKOUT")->result_array();
$this->load->view('frontend/home-section', $data);
$data['activityType'] = $type;
$data['allWeightTraining'] = $this->WORKOUTMODEL->getAllWorkOutByType("weightTraining")->result_array();
$data['allCardio'] = $this->WORKOUTMODEL->getAllWorkOutByType("cardio")->result_array();
$data['contentCentral'] = $this->CENTRALCONTENTMODEL->getContentByPage("WORKOUT")->result_array();
$data['imageCentralMedia'] = $this->CENTRALCONTENTMODEL->getMediaByTypeAndPage("IMAGE", "WORKOUT")->result_array();
$this->load->view('frontend/workout-item', $data);
$this->load->view('frontend/include/footer');
}
}
|
php
| 15 | 0.700662 | 123 | 41.114754 | 61 |
starcoderdata
|
def cov_matrix_f(data):
r'''
Calculate the covariance matrix.
'''
covariance_matrix = np.cov(data, rowvar=False)
if is_pos_def(covariance_matrix):
inv_covariance_matrix = np.linalg.inv(covariance_matrix)
if is_pos_def(inv_covariance_matrix):
return covariance_matrix, inv_covariance_matrix
else:
print("Error: Inverse of Covariance Matrix is not positive definite!")
else:
print("Error: Covariance Matrix is not positive definite!")
|
python
| 12 | 0.550987 | 90 | 45.846154 | 13 |
inline
|
static RISCV_CSR_WRITEFN(mstatushW) {
Uns32 mask = RD_CSR_MASK(riscv, mstatush);
// update the CSR
statushW(riscv, newValue, mask);
// return written value
return RD_CSR(riscv, mstatush);
}
|
c
| 7 | 0.660377 | 46 | 20.3 | 10 |
inline
|
from bisect import bisect_right
N, *A = map(int, open(0).read().split())
x = [1] * (N + 1)
for i in range(N):
j = bisect_right(x, -A[i])
x[j] = -A[i]
print(sum(v != 1 for v in x))
|
python
| 11 | 0.528796 | 40 | 18.1 | 10 |
codenet
|
package database
import (
"os"
"testing"
"time"
"github.com/pallscall/ghz/runner"
"github.com/pallscall/ghz/web/model"
"github.com/stretchr/testify/assert"
)
func TestDatabase_Detail(t *testing.T) {
os.Remove(dbName)
defer os.Remove(dbName)
db, err := New("sqlite3", dbName, false)
if err != nil {
assert.FailNow(t, err.Error())
}
defer db.Close()
var rid, rid2 uint
t.Run("new report", func(t *testing.T) {
p := model.Project{
Name: "Test Proj 111 ",
Description: "Test Description Asdf ",
}
r := model.Report{
Project: &p,
Name: "Test report",
EndReason: "normal",
Date: time.Date(2018, 12, 1, 8, 0, 0, 0, time.UTC),
Count: 200,
Total: time.Duration(2 * time.Second),
Average: time.Duration(10 * time.Millisecond),
Fastest: time.Duration(1 * time.Millisecond),
Slowest: time.Duration(100 * time.Millisecond),
Rps: 2000,
}
err := db.CreateReport(&r)
assert.NoError(t, err)
assert.NotZero(t, p.ID)
assert.NotZero(t, r.ID)
rid = r.ID
})
t.Run("new report 2", func(t *testing.T) {
p := model.Project{
Name: "Test Proj 222 ",
Description: "Test Description 222 ",
}
r := model.Report{
Project: &p,
Name: "Test report 2",
EndReason: "normal",
Date: time.Date(2018, 12, 1, 8, 0, 0, 0, time.UTC),
Count: 300,
Total: time.Duration(2 * time.Second),
Average: time.Duration(10 * time.Millisecond),
Fastest: time.Duration(1 * time.Millisecond),
Slowest: time.Duration(100 * time.Millisecond),
Rps: 3000,
}
err := db.CreateReport(&r)
assert.NoError(t, err)
assert.NotZero(t, p.ID)
assert.NotZero(t, r.ID)
rid2 = r.ID
})
t.Run("CreateDetailsBatch()", func(t *testing.T) {
M := 200
s := make([]*model.Detail, M)
for n := 0; n < M; n++ {
nd := &model.Detail{
ReportID: rid,
ResultDetail: runner.ResultDetail{
Timestamp: time.Now(),
Latency: time.Duration(1 * time.Millisecond),
Status: "OK",
},
}
s[n] = nd
}
created, errored := db.CreateDetailsBatch(rid, s)
assert.Equal(t, M, int(created))
assert.Equal(t, 0, int(errored))
})
t.Run("CreateDetailsBatch() 2", func(t *testing.T) {
M := 300
s := make([]*model.Detail, M)
for n := 0; n < M; n++ {
nd := &model.Detail{
ReportID: rid2,
ResultDetail: runner.ResultDetail{
Timestamp: time.Now(),
Latency: time.Duration(1 * time.Millisecond),
Status: "OK",
},
}
s[n] = nd
}
created, errored := db.CreateDetailsBatch(rid2, s)
assert.Equal(t, M, int(created))
assert.Equal(t, 0, int(errored))
})
t.Run("CreateDetailsBatch() for unknown", func(t *testing.T) {
M := 100
s := make([]*model.Detail, M)
for n := 0; n < M; n++ {
nd := &model.Detail{
ReportID: 43232,
ResultDetail: runner.ResultDetail{
Timestamp: time.Now(),
Latency: time.Duration(1 * time.Millisecond),
Status: "OK",
},
}
s[n] = nd
}
created, errored := db.CreateDetailsBatch(43232, s)
assert.Equal(t, 0, int(created))
assert.Equal(t, M, int(errored))
})
t.Run("ListAllDetailsForReport", func(t *testing.T) {
details, err := db.ListAllDetailsForReport(rid)
assert.NoError(t, err)
assert.Len(t, details, 200)
})
t.Run("ListAllDetailsForReport 2", func(t *testing.T) {
details, err := db.ListAllDetailsForReport(rid2)
assert.NoError(t, err)
assert.Len(t, details, 300)
})
t.Run("ListAllDetailsForReport unknown", func(t *testing.T) {
details, err := db.ListAllDetailsForReport(43332)
assert.NoError(t, err)
assert.Len(t, details, 0)
})
}
|
go
| 25 | 0.605534 | 63 | 20.430233 | 172 |
starcoderdata
|
func (ampmr *AzureMachinePoolMachineController) reconcileDelete(ctx context.Context, machineScope *scope.MachinePoolMachineScope) (_ reconcile.Result, reterr error) {
ctx, log, done := tele.StartSpanWithLogger(ctx, "controllers.AzureMachinePoolMachineController.reconcileDelete")
defer done()
log.Info("Handling deleted AzureMachinePoolMachine")
if machineScope.AzureMachinePool == nil || !machineScope.AzureMachinePool.ObjectMeta.DeletionTimestamp.IsZero() {
// deleting the entire VMSS, so just remove finalizer and VMSS delete remove the underlying infrastructure.
controllerutil.RemoveFinalizer(machineScope.AzureMachinePoolMachine, infrav1exp.AzureMachinePoolMachineFinalizer)
return reconcile.Result{}, nil
}
// deleting a single machine
// 1) drain the node (TODO: @devigned)
// 2) after drained, delete the infrastructure
// 3) remove finalizer
ampms := ampmr.reconcilerFactory(machineScope)
if err := ampms.Delete(ctx); err != nil {
// Handle transient and terminal errors
var reconcileError azure.ReconcileError
if errors.As(err, &reconcileError) {
if reconcileError.IsTerminal() {
log.Error(err, "failed to delete AzureMachinePoolMachine", "name", machineScope.Name())
return reconcile.Result{}, nil
}
if reconcileError.IsTransient() {
log.V(4).Info("failed to delete AzureMachinePoolMachine", "name", machineScope.Name(), "transient_error", err)
return reconcile.Result{RequeueAfter: reconcileError.RequeueAfter()}, nil
}
return reconcile.Result{}, errors.Wrapf(err, "failed to reconcile AzureMachinePool")
}
return reconcile.Result{}, err
}
return reconcile.Result{}, nil
}
|
go
| 17 | 0.764813 | 166 | 40.375 | 40 |
inline
|
import React, { Component } from 'react'
import { StyleSheet, TouchableOpacity, Text, View } from 'react-native'
import { AppStyles, Colors, Fonts, Metrics, Strings } from '../../theme'
import { AwesomeButton } from '../../components'
type Props = {
navigation: Object,
counterActions: Function,
counter: number
}
class CounterView extends Component {
increment = () => {
this.props.counterActions.increment()
}
reset = () => {
this.props.counterActions.reset()
}
bored = () => {
this.props.navigation.goBack()
}
render() {
return (
<View style={styles.container}>
<TouchableOpacity
accessibilityLabel="Increment counter"
onPress={this.increment}
style={styles.counterButton}
>
<Text style={styles.counter}>{this.props.counter}
<AwesomeButton text="Reset" onPress={this.reset} style={styles.linkButton} />
<AwesomeButton text="Go Back" onPress={this.bored} />
)
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
...AppStyles.centerChild,
backgroundColor: Colors.coal
},
counterButton: {
backgroundColor: Colors.panther,
...AppStyles.centerChild,
...AppStyles.buttonBorder,
margin: Metrics.section,
padding: Metrics.baseMargin
},
counter: {
...Fonts.style.h2,
color: Colors.snow,
textAlign: 'center'
},
linkButton: {
marginBottom: Metrics.baseMargin
}
})
export default CounterView
|
javascript
| 11 | 0.637013 | 85 | 22.333333 | 66 |
starcoderdata
|
uint32_t
gsm_sys_mbox_put(gsm_sys_mbox_t* b, void* m) {
struct timespec before_call, after_call, elapsed;
clock_gettime(CLOCK_MONOTONIC, &before_call); //get time before call
if( mq_send(b->mq, m, sizeof(m), 0) == -1)
return GSM_SYS_TIMEOUT;
clock_gettime(CLOCK_MONOTONIC, &after_call); //get time after call
timespec_sub(&elapsed, &after_call, &before_call);
return timespec_to_msec(&elapsed);
}
|
c
| 10 | 0.655172 | 74 | 35.333333 | 12 |
inline
|
import datetime
import time
import logging
import os
from itertools import cycle
from shiftregister import ShiftRegister
from mapping import *
numerals = [ '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' ]
def tester():
shiftreg = ShiftRegister(num_registers=1)
chars = cycle(numerals)
while True:
bytelist = []
char = segment_map[str(next(chars))]
bytelist.append(char)
logging.warning(str_rep(char))
#shiftreg.write(bytelist)
time.sleep(1)
if __name__ == '__main__':
tester()
|
python
| 12 | 0.596774 | 63 | 18.964286 | 28 |
starcoderdata
|
async ValueTask<KResponse<TNodeId, TResponse>> InvokeAsync<TRequest, TResponse>(KProtocolEndpointSet<TNodeId> endpoints, TRequest request, CancellationToken cancellationToken)
where TRequest : struct, IKRequestBody<TNodeId>
where TResponse : struct, IKResponseBody<TNodeId>
{
// replace token with linked timeout
cancellationToken = CancellationTokenSource.CreateLinkedTokenSource(new CancellationTokenSource(defaultTimeout).Token, cancellationToken).Token;
// continue until timeout
while (cancellationToken.IsCancellationRequested == false && endpoints.Acquire() is IKProtocolEndpoint<TNodeId> endpoint)
{
var r = await TryAsync<TRequest, TResponse>(endpoints, endpoint, request, cancellationToken);
if (r.Status == KResponseStatus.Success)
return r;
}
return default;
}
|
c#
| 14 | 0.671579 | 175 | 54.941176 | 17 |
inline
|
package com.balsikandar.android.robin.callbacks;
/**
* Created by bali on 27/05/18.
*/
/**
* This interface provides Activity/Fragment Lifecycle callbacks
* which can be logged to Crashlytics using
*
* {@code Crashlytics.log()} to track user interaction if a crash occurs
*
* It'll be highly useful for crash logs where we can't determine point of origin
*/
public interface LifeCycleCallbacks {
void breadCrumps(String className, String callback);
}
|
java
| 6 | 0.731092 | 81 | 24.052632 | 19 |
starcoderdata
|
int main(int argc, char **argv) {
int numprocs, /* number of processes in partition */
procid, /* a process identifier */
numworkers, /* number of worker processes */
NRA, NCA, NCB;
NRA = atoi(argv[1]);
NCA = NRA;
NCB = 1;
MPI_Init(&argc, &argv);
MPI_Comm_rank(MPI_COMM_WORLD, &procid);
MPI_Comm_size(MPI_COMM_WORLD, &numprocs);
numworkers = numprocs-1;
multiply_two_arrays(NRA, NCA, NCB, numworkers, procid);
MPI_Finalize();
return 0;
}
|
c
| 8 | 0.590643 | 59 | 22.363636 | 22 |
inline
|
void Window::getSettings(std::map <std::string, int> &settings) const //This function needs to be called before exiting the programm in order to save the settings
{ //Note: this function only update the settings than CAN be modified within the programm
settings["windowWidth"] = m_winsize.x;
settings["windowHeight"] = m_winsize.y;
settings["windowMaximized"] = m_maximized;
settings["sceneTheme"] = m_scene->getTheme();
settings["sceneTimeToTop"] = m_scene->getTime();
settings["sceneRenderMethod"] = m_scene->getRenderMethod();
settings["objectNumber"] = m_scene->getObjectNumber();
settings["objectSize"] = m_scene->getObjectSize();
settings["musicAutoplay"] = m_music->getAutoplay();
settings["musicRepeat"] = m_music->getRepeat();
settings["musicRandom"] = m_music->getRandom();
settings["musicMute"] = m_music->getMute();
settings["musicVolume"] = m_music->getVolume();
settings["spectrumScaleAdjustmentTime"] = m_music->getScaleAdjustmentTime();
}
|
c++
| 10 | 0.650823 | 162 | 62.470588 | 17 |
inline
|
// +build !darwin
package startup
func mode() Mode {
return ManualLaunch
}
func reset() {
return
}
|
go
| 9 | 0.721893 | 64 | 13.083333 | 12 |
starcoderdata
|
import sys
readline = sys.stdin.readline
sys.setrecursionlimit(10**8)
mod = 10**9+7
#mod = 998244353
INF = 10**18
eps = 10**-7
s = readline().rstrip()
t = readline().rstrip()
ls = len(s)
lt = len(t)
ans = INF
for i in range(ls-lt+1):
c = 0
for j in range(lt):
if s[i+j] != t[j]:
c += 1
ans = min(ans,c)
print(ans)
|
python
| 9 | 0.557471 | 29 | 15.571429 | 21 |
codenet
|
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Estabelecimento;
use App\Http\Middleware\LogAcessoMiddleware;
class EstabelecimentoController extends Controller
{
//adiciona o middleware diretamente na rota sem ter que ser feita passagem pela view
//// public function __construct()
// {
// $this->middleware('log.acesso');
// }
public function create(){
return view('estabelecimento');
}
public function store(Request $request){
Estabelecimento::create([
'nome'=> $request->nome,
'cnpj'=> $request->cnpj,
'endereco'=> $request->endereco,
'telefone'=> $request->telefone,
'celular'=> $request->celular,
'whatsapp'=> $request->whatsapp,
'servicos'=> $request->servicos,
'data_inauguracao'=> $request->data_inauguracao,
'diferencial'=> $request->diferencial,
'proposta_trabalho'=> $request->proposta_trabalho,
'publico_alvo'=> $request->publico_alvo,
]);
return "Estabelecimento cadastrado com sucesso!";
}
public function salvar(Request $request){
//criação id recebido seja nulo
if($request->input('id') == ''){
$regras = [
'nome'=> 'required|min:3|max:40',
'cnpj'=> 'required',
'endereco'=> 'required',
'servicos'=> 'required',
'data_inauguracao'=> 'required',
'diferencial'=> 'required',
'proposta_trabalho'=> 'required',
'publico_alvo'=> 'required'
];
$feedback =[
'required'=> 'O campo :attribute deve ser preenchido',
'nome.min'=> 'O campo nome presisa ter no minimo 3 caracteres',
'nome.max'=>'O campo nome deve ter no maximo 40 caracteres',
];
$request->validate($regras,$feedback);
Estabelecimento:: create($request->all());
echo 'tika';
}
//edição o id recebido não e nulo
if($request->input('id') != ''){
//eu pego o id que ja esiste para atualizar
$estabelecimento = Estabelecimento:: find($request->input('id'));
//tudo recuperado em cima e atualizado aqui
$update = $estabelecimento->update($request->all());
if($update){
echo 'Update realizado';
}else{
echo 'Update não realizado';
}
}
return view('home');
}
public function editar($id){
$estabelecimento = Estabelecimento::find($id);
//dd($estabelecimento);
//pego id e todo resto e passo para a view estabelecimento
return view('estabelecimento',['estabelecimento'=>$estabelecimento]);
}
public function excluir($id){
Estabelecimento:: find($id)->delete();
return redirect()->route('app.home');
}
}
|
php
| 16 | 0.557162 | 88 | 29.659794 | 97 |
starcoderdata
|
#pragma once
#include "Hazel/Renderer/HazelTexture.h"
#include "Material/Material.h"
#include "Texture/MoravaTexture.h"
#include
class ResourceManager
{
public:
static void Init();
static void LoadTexture(std::string name, std::string filePath);
static void LoadTexture(std::string name, std::string filePath, GLenum filter, bool force);
static void LoadMaterial(std::string name, TextureInfo textureInfo);
static Hazel::Ref HotLoadTexture(std::string textureName);
static Hazel::Ref HotLoadMaterial(std::string materialName);
// Getters
static inline Hazel::Ref GetTexture(std::string textureName) { return s_Textures[textureName]; };
static inline std::map<std::string, Hazel::Ref GetTextures() { return &s_Textures; };
static inline std::map<std::string, Hazel::Ref GetMaterials() { return &s_Materials; };
static inline std::map<std::string, std::string>* GetTextureInfo() { return &s_TextureInfo; };
static inline std::map<std::string, TextureInfo>* GetMaterialInfo() { return &s_MaterialInfo; };
static inline std::map<std::string, Hazel::Ref GetShaders() { return &s_ShaderCacheByTitle; };
// Loading HazelTexture2D
static Hazel::Ref LoadHazelTexture2D(std::string filePath);
static void AddShader(std::string name, Hazel::Ref shader);
static const Hazel::Ref GetShader(std::string name);
// Caching shaders
static const Hazel::Ref CreateOrLoadShader(MoravaShaderSpecification moravaShaderSpecification);
public:
static float s_MaterialSpecular;
static float s_MaterialShininess;
private:
// Asset loading
static std::map<std::string, std::string> s_TextureInfo;
static std::map<std::string, TextureInfo> s_MaterialInfo;
static std::map<std::string, Hazel::Ref s_Textures;
static std::map<std::string, Hazel::Ref s_Materials;
static std::map<std::string, Hazel::Ref s_HazelTextures2D;
static std::map<std::string, Hazel::Ref s_ShaderCacheByTitle;
static std::map<std::string, Hazel::Ref s_ShadersCacheByFilepath;
};
|
c
| 8 | 0.7605 | 113 | 38.263158 | 57 |
starcoderdata
|
@{
Layout = "_VueLayout";
ViewData["Title"] = ViewBag.ViewTitle;
var viewName = ViewBag.ViewName;
var properties = ViewBag.Properties;
}
@foreach (var property in @properties)
{
<input type="hidden" id="@property.Name" value="@property.Value" />
}
<vc:vue view-name="@viewName">
|
c#
| 9 | 0.659091 | 71 | 27.090909 | 11 |
starcoderdata
|
const path = require('path');
const withSass = require('@zeit/next-sass');
const withImages = require('next-images');
const withBundleAnalyzer = require('@next/bundle-analyzer')({
enabled: process.env.ANALYZE === 'true',
});
const ApiHost = process.env.REACT_APP_API_HOST || 'https://api.refine.bio';
// trigger dev change
module.exports = withImages(
withSass(
withBundleAnalyzer({
target: 'serverless',
env: {
REACT_APP_API_HOST: ApiHost,
},
webpack: (config, { isServer, dev, webpack }) => {
// add custom webpack config only for the client side in production
if (!isServer && !dev) {
// ignore momentjs locales
config.plugins.push(
new webpack.IgnorePlugin(/^\.\/locale$/, /moment$/)
);
// lodash is referenced by multiple libraries, this makes sure we only
// inlcude it once
config.resolve.alias = {
...config.resolve.alias,
lodash: path.resolve(__dirname, 'node_modules/lodash'),
};
config.optimization.splitChunks = {
chunks: 'all',
cacheGroups: {
default: false,
vendors: false,
commons: {
name: 'commons',
chunks: 'all',
minChunks: 3,
},
charts: {
name: 'charts',
chunks: 'all',
test: /[\\/]node_modules[\\/](recharts|d3.*)[\\/]/,
enforce: true,
priority: 10,
},
// Only create one CSS file
styles: {
name: `styles`,
// This should cover all our types of CSS.
test: /\.(css|scss|sass)$/,
chunks: `all`,
enforce: true,
// this rule trumps all other rules because of the priority.
priority: 10,
},
},
};
}
return config;
},
})
)
);
|
javascript
| 16 | 0.48415 | 80 | 29.173913 | 69 |
starcoderdata
|
<?php
/**
* Created by IntelliJ IDEA.
* User: dominik
* Date: 1/27/19
* Time: 4:14 PM
*/
namespace Dominikb\LaravelApiDocumentationGenerator;
use Dominikb\LaravelApiDocumentationGenerator\Contracts\Formatter;
use Dominikb\LaravelApiDocumentationGenerator\Exceptions\EmptyRoutesException;
use Illuminate\Routing\Router;
use Illuminate\Support\Collection;
use Illuminate\Support\Str;
use Spatie\Regex\Regex;
class RouteParser {
/** @var Formatter */
protected $formatter;
/** @var Router */
protected $router;
/** @var RouteCollection */
private $routes;
public function __construct(Router $router, Formatter $formatter)
{
$this->routes = new RouteCollection;
$this->formatter = $formatter;
$this->router = $router;
}
public function format(): string
{
$routes = $this->parseRoutes();
return $this->formatter->format($routes);
}
private function parseRoutes(): RouteCollection
{
$routes = $this->router->getRoutes()->getRoutes();
$mappedRoutes = array_map(function(\Illuminate\Routing\Route $route){
return new Route(
$route->methods(),
$route->getDomain() . $route->getPrefix() . $route->uri(),
$route->middleware(),
get_class($route->getController()),
$route->getActionMethod()
);
}, $routes);
return new RouteCollection($mappedRoutes);
}
}
|
php
| 21 | 0.62173 | 78 | 25.175439 | 57 |
starcoderdata
|
package org.satochip.android;
import android.nfc.tech.IsoDep;
import android.util.Log;
import org.satochip.io.APDUCommand;
import org.satochip.io.APDUResponse;
import org.satochip.io.CardChannel;
import java.io.IOException;
/**
* Implementation of the CardChannel interface using the Android NFC API.
*/
public class NFCCardChannel implements CardChannel {
private static final String TAG = "CardChannel";
private IsoDep isoDep;
public NFCCardChannel(IsoDep isoDep) {
this.isoDep = isoDep;
}
@Override
public APDUResponse send(APDUCommand cmd) throws IOException {
byte[] apdu = cmd.serialize();
Log.d(TAG, String.format("COMMAND CLA: %02X INS: %02X P1: %02X P2: %02X LC: %02X", cmd.getCla(), cmd.getIns(), cmd.getP1(), cmd.getP2(), cmd.getData().length));
byte[] resp = this.isoDep.transceive(apdu);
APDUResponse response = new APDUResponse(resp);
Log.d(TAG, String.format("RESPONSE LEN: %02X, SW: %04X %n-----------------------", response.getData().length, response.getSw()));
return response;
}
@Override
public boolean isConnected() {
return this.isoDep.isConnected();
}
}
|
java
| 13 | 0.704274 | 164 | 29.789474 | 38 |
starcoderdata
|
package com.vspr.ai.slack.api;
import com.fasterxml.jackson.annotation.JsonAnyGetter;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import org.immutables.value.Value;
/**
* Response to {@link com.vspr.ai.slack.service.SlackAPI#listUsers(String, String, int, boolean)}
*/
@Value.Immutable
@JsonSerialize(as = ImmutableListUsersResponse.class)
@JsonDeserialize(as = ImmutableListUsersResponse.class)
@SlackApiImmutableStyle
public abstract class ListUsersResponse extends BaseSlackResponse {
/**
* List of users returned in the query
*/
public abstract List getMembers();
/**
* Response Metadata contains information about response pagination
*/
@JsonProperty("response_metadata")
public abstract Optional getResponseMetadata();
/**
* Contains all json data not explicitly found in this DTO.
*/
@JsonAnyGetter
@AllowNulls
public abstract Map<String, Object> getOther();
}
|
java
| 8 | 0.778553 | 97 | 29.184211 | 38 |
starcoderdata
|
package ippacket
import (
"errors"
"net"
)
type Packet interface {
IsV4() bool
IsV6() bool
Src() net.IP
Dst() net.IP
Which() uint16
}
type packetContent struct {
SrcAddress net.IP
DstAddress net.IP
I4 bool
Protocol uint16
}
func TryParse(stream []byte) (Packet, error) {
p := &packetContent{
I4: true,
}
if len(stream) < 20 {
return nil, errors.New("not ipv4")
}
if (stream[0] & 0xf0) == 0x60 {
p.I4 = false
if len(stream) < 40 {
return nil, errors.New("not ipv6")
}
p.SrcAddress = net.IP(stream[8:24])
p.DstAddress = net.IP(stream[24:40])
p.Protocol = uint16(stream[6])
} else {
p.SrcAddress = net.IP(stream[12:16])
p.DstAddress = net.IP(stream[16:20])
p.Protocol = uint16(stream[9])
}
return p, nil
}
func (p *packetContent) IsV4() bool {
return p.I4
}
func (p *packetContent) IsV6() bool {
return !p.I4
}
func (p *packetContent) Src() net.IP {
return p.SrcAddress
}
func (p *packetContent) Dst() net.IP {
return p.DstAddress
}
func (p *packetContent) Which() uint16 {
return p.Protocol
}
|
go
| 12 | 0.639098 | 46 | 14.42029 | 69 |
starcoderdata
|
# Write a program that asks the user to input a set of floating-point
# values. When the user enters a value that is not a number,
# give the user a second chance to enter the value. After two chances,
# quit reading input. Add all correctly specified values and
# print the sum when the user is done entering data. Use exception
# handling to detect improper inputs.
# IMPORTS
# FUNCTIONS
# main
def main():
inputList = []
tries = 1
while tries < 3:
try:
inputN = int(input("Enter a number: "))
inputList.append(inputN)
except ValueError:
print("Not a number! Enter a number to continue")
print("or enter a character to quit")
tries += 1
print("Sum: %d" % sum(inputList))
# PROGRAM RUN
if __name__ == "__main__":
main()
|
python
| 14 | 0.654477 | 71 | 23.78125 | 32 |
starcoderdata
|
package memcache
// This package implements the util/singleton interface, on top of a memcache client lib.
import(
"bytes"
"encoding/gob"
"fmt"
"io"
"net"
"time"
"golang.org/x/net/context"
// Use a forked version of bradfitz's lib, so that we can pass in a dialer func
mclib "github.com/skypies/gomemcache/memcache"
"github.com/skypies/util/singleton"
)
const Chunksize = 950000 // A single memcache item can't be bigger than 1000000 bytes
type SingletonProvider struct {
*mclib.Client
ErrIfNotFound bool // By default, we swallow 'item not found' errors.
ShardCount int // defaults to no sharding. Set this if you need to store >Chunksize
}
func NewProvider(servers ...string) SingletonProvider {
sp := SingletonProvider{
Client: mclib.New(servers...),
}
return sp
}
func (sp SingletonProvider)SetDialer(dialer func(network, addr string, timeout time.Duration) (net.Conn, error)) {
sp.Client.CustomDialer = dialer
}
func (sp SingletonProvider)ReadSingleton(ctx context.Context, name string, f singleton.NewReaderFunc, obj interface{}) error {
var myBytes []byte
var err error
if sp.ShardCount > 2 {
myBytes,err = sp.loadSingletonShardedBytes(name)
} else {
myBytes,err = sp.loadSingletonBytes(name)
}
if err == singleton.ErrNoSuchEntity {
return err // Don't decorate this error
} else if err != nil {
return fmt.Errorf("ReadSingleton/loadBytes: %v", err)
} else if myBytes == nil {
// This happens if the object was not found; don't try to decode it.
return nil
}
var reader io.Reader
buf := bytes.NewBuffer(myBytes)
reader = buf
if f != nil {
if reader,err = f(buf); err != nil {
return fmt.Errorf("ReadSingleton/NewReaderFunc: %v", err)
}
}
if err := gob.NewDecoder(reader).Decode(obj); err != nil {
return fmt.Errorf("ReadSingleton/Decode: %v (%d bytes)", err, len(myBytes))
}
// fmt.Printf("(loaded %d bytes from memcache)\n", len(myBytes))
return nil
}
func (sp SingletonProvider)WriteSingleton(ctx context.Context, name string, f singleton.NewWriteCloserFunc, obj interface{}) error {
var buf bytes.Buffer
var writer io.Writer
var writecloser io.WriteCloser
// All this type chicanery is so we can call Close() on the NewWriterFunc's thing, which is
// needed for gzip.
writer = &buf
if f != nil {
writecloser = f(&buf)
writer = writecloser
}
if err := gob.NewEncoder(writer).Encode(obj); err != nil {
return err
}
if f != nil {
if err := writecloser.Close(); err != nil {
return err
}
}
data := buf.Bytes()
if sp.ShardCount > 1 {
return sp.saveSingletonShardedBytes(name, data)
} else {
return sp.saveSingletonBytes(name, data)
}
}
func singletonMCKey(name string) string { return "singleton:"+name }
func (sp SingletonProvider)deleteSingleton(name string) (error) {
return sp.Client.Delete(name)
}
func (sp SingletonProvider)loadSingletonBytes(name string) ([]byte, error) {
item,err := sp.Client.Get(singletonMCKey(name))
if err == mclib.ErrCacheMiss {
// Swallow this error, if we need to.
if sp.ErrIfNotFound {
return nil, singleton.ErrNoSuchEntity
}
return nil, nil
} else if err != nil {
return nil, err
}
return item.Value, nil
}
func (sp SingletonProvider)saveSingletonBytes(name string, data []byte) error {
if len(data) > Chunksize {
return fmt.Errorf("singleton too large (name=%s, size=%d)", name, len(data))
}
item := mclib.Item{Key:singletonMCKey(name), Value:data}
return sp.Client.Set(&item)
}
func (sp SingletonProvider)saveSingletonShardedBytes(key string, b []byte) error {
if sp.ShardCount < 2 { return fmt.Errorf("saveSingletonShardedBytes: .ShardCount not set") }
if len(b) > sp.ShardCount * Chunksize {
return fmt.Errorf("obj '%s' was too large; %d > (%d shards x %d bytes)", key,
len(b), sp.ShardCount, Chunksize)
}
// fmt.Printf("(saving over %d shards)\n", sp.ShardCount)
for i:=0; i<len(b); i+=Chunksize {
k := fmt.Sprintf("=%d=%s",i,key)
s,e := i, i+Chunksize-1
if e>=len(b) { e = len(b)-1 }
item := mclib.Item{ Key:k , Value:b[s:e+1] } // slice sytax is [s,e)
// fmt.Printf(" (saving shard %d ...)\n", i)
if err := sp.Client.Set(&item); err != nil {
return err
}
// fmt.Printf(" (... shard %d saved !)\n", i)
}
return nil
}
// err might be .ErrCacheMiss
func (sp SingletonProvider)loadSingletonShardedBytes(key string) ([]byte, error) {
if sp.ShardCount < 2 { return nil, fmt.Errorf("loadSingletonShardedBytes: .ShardCount not set") }
keys := []string{}
for i:=0; i<sp.ShardCount; i++ { keys = append(keys, fmt.Sprintf("=%d=%s",i*Chunksize,key)) }
// fmt.Printf("(loading over %d shards)\n", sp.ShardCount)
if items,err := sp.Client.GetMulti(keys); err != nil {
return nil, fmt.Errorf("MCShards/GetMulti/'%s' err: %v\n", key, err)
} else {
b := []byte{}
for i:=0; i<sp.ShardCount; i++ {
if item,exists := items[keys[i]]; exists==false {
break
} else {
// fmt.Printf(" (shard %d loaded)\n", i)
b = append(b, item.Value...)
}
}
if len(b) > 0 {
return b, nil
} else {
return nil, singleton.ErrNoSuchEntity
}
}
}
|
go
| 15 | 0.672937 | 132 | 24.772727 | 198 |
starcoderdata
|
from os import path, listdir
from kivy.core.image import Image as CoreImage
from icon_get import get_urls, url_to_bytes, crop_icon_back, core_img_from_url
class UrlBytes:
def __init__(self, url, bytes):
self.url = url
self.bytes = bytes
class IconManager:
"""
Manages the icons for an app.
"""
# TODO: use official Google API
GOOGLE_URL_TEMPLATE = "https://www.google.com/search?q={}+icon+filetype:png&tbm=isch&source=lnt&tbs=iar:s"
def __init__(self, name: str,
image_save_path: str,
app_path: str):
self.name = name
self.image_save_path = image_save_path
self.app_path = app_path
self.index = -1
self.url_bytes = []
self.icon_path = self.bytes_on_disk = None
self.set_icon_path() # sets icon_path and bytes_on_disk
@property
def core_image(self):
if self.icon_on_disk:
self.bytes_on_disk.seek(0)
return CoreImage(self.bytes_on_disk, ext="png")
else:
return core_img_from_url(self.get_next_icon_url())
@property
def icon_on_disk(self):
return bool(self.bytes_on_disk)
def set_icon_path(self):
icon_name = self.name + " icon.png"
self.icon_path = path.join(path.abspath(self.image_save_path), icon_name)
if icon_name in listdir(self.image_save_path):
self.load_icon_from_disk()
def load_icon_from_disk(self):
self.bytes_on_disk = crop_icon_back(self.icon_path)
def current_icon_bytes(self):
if self.index == -1 and self.bytes_on_disk:
self.bytes_on_disk.seek(0)
return self.bytes_on_disk
current_urlbytes = self.url_bytes[self.index]
if current_urlbytes.bytes is None:
current_urlbytes.bytes = url_to_bytes(current_urlbytes.url)
current_urlbytes.bytes.seek(0)
return current_urlbytes.bytes
def check_urls(self):
if not self.url_bytes:
self.update_urls()
def update_urls(self):
urls = get_urls(self.name)
for url in urls:
self.url_bytes.append(UrlBytes(url, None))
self.index = -1
def get_current_icon_url(self):
if self.index == len(self.url_bytes):
self.index = 0
elif self.index == -1:
self.index = len(self.url_bytes) - 1
if self.url_bytes:
return self.url_bytes[self.index].url
else:
return None
def get_next_icon_url(self):
self.index += 1
return self.get_current_icon_url()
def get_previous_icon_url(self):
self.index -= 1
return self.get_current_icon_url()
|
python
| 14 | 0.6813 | 107 | 22.69 | 100 |
starcoderdata
|
//-*-C++-*-
/***************************************************************************
*
* Copyright (C) 2004 by
* Licensed under the Academic Free License version 2.1
*
***************************************************************************/
// psrchive/More/MEAL/MEAL/ProjectGradient.h
#ifndef __ProjectProductGradient_H
#define __ProjectProductGradient_H
#include "MEAL/Projection.h"
namespace MEAL {
template <class Function, class Grad>
void ProjectGradient (const Project model, unsigned& igrad,
const std::vector input,
std::vector output)
{
unsigned nparam = model->get_nparam();
for (unsigned iparam = 0; iparam < nparam; iparam++)
{
unsigned imap = model.get_map()->get_imap (iparam);
if (Function::verbose)
std::cerr << "ProjectGradient iparam=" << iparam << " imap=" << imap
<< " igrad=" << igrad << std::endl;
if (imap >= output.size())
throw Error (InvalidRange, "MEAL::ProjectGradient",
"iparam=%u -> imap=%u >= composite.nparam=%u",
iparam, imap, output.size());
output[imap] += input[igrad];
igrad ++;
}
}
template <class Function, class Grad>
void ProjectGradient (const Project model,
const std::vector input,
std::vector output)
{
unsigned igrad = 0;
ProjectGradient (model, igrad, input, output);
}
template <class Function, class Grad>
void ProjectGradient (const std::vector >& model,
const std::vector input,
std::vector output)
{
unsigned nparam = output.size();
unsigned nmodel = model.size();
// set each element of the gradient to zero
for (unsigned iparam=0; iparam<nparam; iparam++)
output[iparam] = 0.0;
unsigned igrad = 0;
for (unsigned imodel=0; imodel<nmodel; imodel++)
{
if (Function::verbose)
std::cerr << "ProjectGradient imodel=" << imodel
<< " igrad=" << igrad << std::endl;
ProjectGradient (model[imodel], igrad, input, output);
}
// sanity check, ensure that all elements have been set
if (igrad != input.size())
throw Error (InvalidState, "MEAL::ProjectGradient",
"on completion igrad=%d != ngrad=%d",
igrad, input.size());
}
}
#endif
|
c
| 19 | 0.582938 | 77 | 26.630952 | 84 |
starcoderdata
|
from app import db
class Tipo_Cuenta(db.Model):
__tablename__ = 'tipo_cuenta'
id_tipo_cuenta = db.Column(db.INTEGER, primary_key=True)
nombre = db.Column(db.String(100), nullable=False, unique=True)
descripcion = db.Column(db.String(200))
saldo = db.Column(db.BOOLEAN, default=False)#True = Acreedor, False = Deudor
def __repr__(self):
return f'Tipo_Cuenta {self.nombre}'
def save(self):
if not self.id_tipo_cuenta:
db.session.add(self)
db.session.commit()
def delete(self):
db.session.delete(self)
db.session.commit()
@staticmethod
def get_all():
return Tipo_Cuenta.query.all()
@staticmethod
def get_by_id(id):
return Tipo_Cuenta.query.get(id)
@staticmethod
def get_by_userName(nombre):
return Tipo_Cuenta.query.filter_by(nombre=nombre).first()
|
python
| 12 | 0.628668 | 80 | 25.088235 | 34 |
starcoderdata
|
/* eslint-disable no-await-in-loop */
const assert = require('assert');
const TestUtils = require('../utils');
/**
* Logs body to a JSON file. Useful for debug/generating JSON examples for documentation
* @param {object} body
*/
// eslint-disable-next-line no-unused-vars
function logBody(body) {
const fs = require('fs');
const path = require('path');
fs.writeFileSync(
path.join(__dirname, '/webhook.json'),
JSON.stringify(body, null, 2),
'utf8'
);
}
function wait(ms) {
return new Promise((resolve) => setTimeout(resolve, ms));
}
describe('api/webhooks', function () {
it('does not fire if not enabled', async function () {
const hookServer = await TestUtils.makeHookServer();
const utils = new TestUtils({
port: 9000,
publicUrl: 'http://mysqlpad.com',
baseUrl: '/sqlpad',
webhookSecret: 'secret',
webhookUserCreatedUrl: hookServer.url,
});
await utils.init(true);
await utils.post('admin', '/sqlpad/api/users', {
email: '
name: 'user1',
role: 'editor',
data: {
create: true,
},
});
await wait(200);
assert.equal(hookServer.responses.length, 0);
});
it('userCreated', async function () {
const hookServer = await TestUtils.makeHookServer();
const utils = new TestUtils({
port: 9000,
publicUrl: 'http://mysqlpad.com',
baseUrl: '/sqlpad',
webhookEnabled: true,
webhookSecret: 'secret',
webhookUserCreatedUrl: hookServer.url,
});
await utils.init(true);
const user = await utils.post('admin', '/sqlpad/api/users', {
email: '
name: 'user1',
role: 'editor',
});
await wait(200);
assert.deepStrictEqual(hookServer.responses[0].body, {
action: 'user_created',
sqlpadUrl: 'http://mysqlpad.com:9000/sqlpad',
user: {
id: user.id,
name: user.name,
role: user.role,
email: user.email,
createdAt: user.createdAt,
},
});
// Only need to test this once
// Ensure headers are sent as expected
assert.equal(hookServer.responses[0].headers['sqlpad-secret'], 'secret');
hookServer.server.close();
});
it('queryCreated', async function () {
const hookServer = await TestUtils.makeHookServer();
const utils = new TestUtils({
webhookEnabled: true,
webhookQueryCreatedUrl: hookServer.url,
});
await utils.init(true);
const connection = await utils.post('admin', '/api/connections', {
name: 'test connection',
driver: 'sqlite',
data: {
filename: './test/fixtures/sales.sqlite',
},
});
const queryWithoutCon = await utils.post('admin', '/api/queries', {
name: 'test query',
tags: ['one', 'two'],
queryText: 'SELECT * FROM some_table',
});
await utils.post('admin', '/api/queries', {
name: 'test query 2',
tags: ['one', 'two'],
connectionId: connection.id,
queryText: 'SELECT * FROM some_table',
});
await wait(200);
// no secret or url headers this time
assert.equal(hookServer.responses[0].headers['sqlpad-secret'], '');
const body1 = hookServer.responses[0].body;
assert.equal(body1.action, 'query_created');
assert.equal(body1.sqlpadUrl, '');
assert.equal(body1.query.id, queryWithoutCon.id, 'query r1');
assert.equal(body1.query.name, queryWithoutCon.name);
assert.deepStrictEqual(body1.query.tags, queryWithoutCon.tags);
assert.equal(body1.query.queryText, queryWithoutCon.queryText);
assert.equal(body1.query.createdAt, queryWithoutCon.createdAt);
assert.deepEqual(body1.query.createdByUser, queryWithoutCon.createdByUser);
assert(!body1.connection);
const body2 = hookServer.responses[1].body;
assert.equal(body2.connection.id, connection.id, 'connection r2');
assert.equal(body2.connection.name, connection.name);
assert.equal(body2.connection.driver, connection.driver);
hookServer.server.close();
});
it('batchCreated / batchFinished / statementCreated / statementFinished', async function () {
const hookServer = await TestUtils.makeHookServer();
const utils = new TestUtils({
webhookEnabled: true,
webhookBatchCreatedUrl: hookServer.url,
webhookBatchFinishedUrl: hookServer.url,
webhookStatementCreatedUrl: hookServer.url,
webhookStatementFinishedUrl: hookServer.url,
});
await utils.init(true);
const connection = await utils.post('admin', '/api/connections', {
name: 'test connection',
driver: 'sqlite',
data: {
filename: './test/fixtures/sales.sqlite',
},
});
const queryText = `SELECT 1 AS id, 'blue' AS color UNION ALL SELECT 2 AS id, 'red' AS color`;
const query = await utils.post('admin', '/api/queries', {
name: 'test query',
tags: ['test'],
connectionId: connection.id,
queryText,
});
let batch = await utils.post('admin', `/api/batches`, {
connectionId: connection.id,
queryId: query.id,
batchText: queryText,
selectedText: queryText,
});
batch = await utils.get('admin', `/api/batches/${batch.id}`);
while (batch.status !== 'finished' && batch.status !== 'error') {
await wait(50);
batch = await utils.get('admin', `/api/batches/${batch.id}`);
}
const statements = await utils.get(
'admin',
`/api/batches/${batch.id}/statements`
);
assert.equal(statements.length, 1);
const statement1 = statements[0];
await wait(500);
const { body: batchCreatedBody } = hookServer.responses.find(
(r) => r.body.action === 'batch_created'
);
assert.equal(batchCreatedBody.batch.id, batch.id);
assert.equal(batchCreatedBody.user.id, utils.users.admin.id);
const { body: batchFinishedBody } = hookServer.responses.find(
(r) => r.body.action === 'batch_finished'
);
assert.equal(batchFinishedBody.batch.id, batch.id);
assert.equal(batchFinishedBody.user.id, utils.users.admin.id);
const { body: statementCreatedBody } = hookServer.responses.find(
(r) => r.body.action === 'statement_created'
);
assert.equal(statementCreatedBody.statement.id, statement1.id);
assert.equal(statementCreatedBody.user.id, utils.users.admin.id);
assert.equal(statementCreatedBody.batch.id, batch.id);
assert.equal(statementCreatedBody.connection.id, connection.id);
const { body: statementFinishedBody } = hookServer.responses.find(
(r) => r.body.action === 'statement_finished'
);
assert.equal(statementFinishedBody.statement.id, statement1.id);
assert.deepEqual(statementFinishedBody.results, [
[1, 'blue'],
[2, 'red'],
]);
assert.equal(statementFinishedBody.user.id, utils.users.admin.id);
assert.equal(statementFinishedBody.batch.id, batch.id);
assert.equal(statementFinishedBody.connection.id, connection.id);
// Ensure connection does not have sensitive data
assert(!statementFinishedBody.connection.data);
assert(!statementFinishedBody.connection.filename);
});
});
|
javascript
| 21 | 0.645288 | 97 | 30.320175 | 228 |
starcoderdata
|
package zy.blue7.myimport;
import org.springframework.context.annotation.DeferredImportSelector;
import org.springframework.core.type.AnnotationMetadata;
import java.util.ArrayList;
import java.util.List;
/**
* @author blue7
* @create 2021/2/3 10:08
*/
public class MyGroup implements DeferredImportSelector.Group {
private AnnotationMetadata metadata;
@Override
public void process(AnnotationMetadata metadata, DeferredImportSelector selector) {
this.metadata=metadata;
}
@Override
public Iterable selectImports() {
Entry entry = new Entry(metadata, "zy.blue7.lookupandreplace.Apple");
Entry entry2 = new Entry(metadata, "zy.blue7.lookupandreplace.Fruit");
List entries=new ArrayList<>();
entries.add(entry);
entries.add(entry2);
return entries;
}
}
|
java
| 12 | 0.77309 | 84 | 26.40625 | 32 |
starcoderdata
|
private void StructureDropdownChanged()
{
if(!_viewModel.InitialTableLoad)
{
//change other dropdowns
foreach(DVHTableRow row in _viewModel.DVHTable)
{
if (Structure == row.Structure && SelectedStructure != row.SelectedStructure)
row.SelectedStructure = SelectedStructure;
}
//recompute planned values
ComputePlanValues();
ComputePlanResult();
}
}
|
c#
| 12 | 0.6875 | 82 | 24.0625 | 16 |
inline
|
import { eventFullTransforms } from './event-full-transforms';
describe('eventFullTransforms', () => {
describe('MarkerRecorded', () => {
describe('When passed event.markerName === "SideEffect"', () => {
let event;
beforeEach(() => {
event = {
decisionTaskCompletedEventId: 'decisionTaskCompletedEventIdValue',
details: [
'sideEffectIdValue',
'eyAiaGVsbG8iOiAid29ybGQiIH0', // { "hello": "world" }
],
markerName: 'SideEffect',
};
});
it('should return an object with property sideEffectId.', () => {
const output = eventFullTransforms.MarkerRecorded(event);
expect(output.sideEffectId).toEqual('sideEffectIdValue');
});
it('should return an object with property data.', () => {
const output = eventFullTransforms.MarkerRecorded(event);
expect(output.data).toEqual({ hello: 'world' });
});
it('should return an object with property decisionTaskCompletedEventId.', () => {
const output = eventFullTransforms.MarkerRecorded(event);
expect(output.decisionTaskCompletedEventId).toEqual(
'decisionTaskCompletedEventIdValue'
);
});
});
});
describe('When passed event.markerName !== "SideEffect"', () => {
let event;
beforeEach(() => {
event = {
decisionTaskCompletedEventId: 'decisionTaskCompletedEventIdValue',
details: [
'sideEffectIdValue',
'eyAiaGVsbG8iOiAid29ybGQiIH0', // { "hello": "world" }
],
markerName: 'NotSideEffect',
};
});
it('should return original event object.', () => {
const output = eventFullTransforms.MarkerRecorded(event);
expect(output).toEqual(event);
});
});
});
|
javascript
| 24 | 0.595604 | 87 | 28.354839 | 62 |
starcoderdata
|
@Override
public ResourceGeneration exec(final DownloadQueryAction action) {
return securityContext.secureResult(() -> {
try {
if (action.getSearchRequest() == null) {
throw new EntityServiceException("Query is empty");
}
final SearchRequest searchRequest = action.getSearchRequest();
//API users will typically want all data so ensure Fetch.ALL is set regardless of what it was before
if (searchRequest != null && searchRequest.getComponentResultRequests() != null) {
searchRequest.getComponentResultRequests()
.forEach((k, componentResultRequest) ->
componentResultRequest.setFetch(ResultRequest.Fetch.ALL));
}
//convert our internal model to the model used by the api
stroom.query.api.v2.SearchRequest apiSearchRequest = searchRequestMapper.mapRequest(
action.getDashboardQueryKey(),
searchRequest);
if (apiSearchRequest == null) {
throw new EntityServiceException("Query could not be mapped to a SearchRequest");
}
//generate the export file
String fileName = action.getDashboardQueryKey().toString();
fileName = NON_BASIC_CHARS.matcher(fileName).replaceAll("");
fileName = MULTIPLE_SPACE.matcher(fileName).replaceAll(" ");
fileName = fileName + ".json";
final ResourceKey resourceKey = resourceStore.createTempFile(fileName);
final Path outputFile = resourceStore.getTempFile(resourceKey);
JsonUtil.writeValue(outputFile, apiSearchRequest);
return new ResourceGeneration(resourceKey, new ArrayList<>());
} catch (final RuntimeException e) {
throw EntityServiceExceptionUtil.create(e);
}
});
}
|
java
| 20 | 0.578794 | 116 | 47.97619 | 42 |
inline
|
@Bean
public PoolingHttpClientConnectionManager StructureConnectionManager(Registry<ConnectionSocketFactory> registry) {
PoolingHttpClientConnectionManager ccm = new PoolingHttpClientConnectionManager(registry);
ccm.setMaxTotal(defaultProperties.getMaxTotal());
// Default max per route is used in case it's not set for a specific route
ccm.setDefaultMaxPerRoute(defaultProperties.getDefaultMaxPerRoute());
final HttpHost host = new HttpHost(restProperties.getHostConfig().getHost(),restProperties
.getHostConfig().getPort(), restProperties.getHostConfig().getScheme());
// Max per route for a specific host route
ccm.setMaxPerRoute(new HttpRoute(host), restProperties.getHostConfig().getMaxPerRoute());
//ccm.setValidateAfterInactivity(250000);
return ccm;
}
|
java
| 10 | 0.806369 | 115 | 51.4 | 15 |
inline
|
[SetUp]
public void Init()
{
String ruleset = "& C < ch, cH, Ch, CH & Five, 5 & Four, 4 & one, 1 & Ampersand; '&' & Two, 2 ";
// String ruleset = "& Four, 4";
myCollation = new RuleBasedCollator(ruleset);
}
|
c#
| 9 | 0.466165 | 108 | 37.142857 | 7 |
inline
|
private void InitTableAdapters(string path)
{
// Create table adapter to read/write data
animalsTableAdapter = new AnimalsTableAdapter();
photosTableAdapter = new PhotosTableAdapter();
anchorsTableAdapter = new AnchorsTableAdapter();
featuresTableAdapter = new FeaturesTableAdapter();
// Create connection string to indicate filename to read from
string connectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + path;
// Set table adapters' connection string
animalsTableAdapter.Connection.ConnectionString = connectionString;
photosTableAdapter.Connection.ConnectionString = connectionString;
anchorsTableAdapter.Connection.ConnectionString = connectionString;
featuresTableAdapter.Connection.ConnectionString = connectionString;
}
|
c#
| 9 | 0.67679 | 94 | 52.352941 | 17 |
inline
|
using Microsoft.AspNetCore.Components;
using Neptuo.Logging;
using Neptuo.Recollections.Accounts.Components;
using Neptuo.Recollections.Components;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Neptuo.Recollections.Entries.Pages
{
public partial class Timeline
{
[Inject]
protected Api Api { get; set; }
[Inject]
protected Navigator Navigator { get; set; }
[Inject]
protected UiOptions UiOptions { get; set; }
[Inject]
protected MarkdownConverter MarkdownConverter { get; set; }
[Inject]
protected ILog Log { get; set; }
[CascadingParameter]
protected UserState UserState { get; set; }
private int offset;
protected List Entries { get; } = new List
protected bool HasMore { get; private set; }
protected bool IsLoading { get; private set; } = true;
protected async override Task OnInitializedAsync()
{
Log.Debug("Timeline.Init");
await base.OnInitializedAsync();
await UserState.EnsureAuthenticatedAsync();
Log.Debug("Timeline.Load");
await LoadAsync();
}
private async Task LoadAsync()
{
try
{
IsLoading = true;
TimelineListResponse response = await Api.GetTimelineListAsync(offset);
Entries.AddRange(response.Entries);
HasMore = response.HasMore;
offset = Entries.Count;
}
finally
{
IsLoading = false;
}
}
public Task LoadMoreAsync()
=> LoadAsync();
}
}
|
c#
| 17 | 0.580868 | 99 | 26.180556 | 72 |
starcoderdata
|
int CreateUFO()
{
Vector3 Coords = ENTITY::GET_ENTITY_COORDS(PLAYER::PLAYER_PED_ID(), true, true);
Vector3 UFOCoords;
//s_ufo01x s_ufo02x
//Hash Model_121 = -1221640793;
Hash Model_122 = -1074960068;
Hash Model_FX = 1198653116;
Hash Red_UFO = joaat("s_ufo01x");
Hash Green_UFO = joaat("s_ufo02x");
int LocalModel_121 = 0;
int LocalModel_122 = 0;
//PED::_0xED9582B3DA8F02B4(1); //IDK Scripts something about ped
//AUDIO::_0xD9130842D7226045("Ufos_Sounds", 0); // think has to do with checking the sound
//STREAMING::REQUEST_MODEL(Model_122, 0); // We shal see wtf is this
if (STREAMING::IS_MODEL_IN_CDIMAGE(Red_UFO))
{
STREAMING::REQUEST_MODEL(Red_UFO, 0); //UFO model
while (!STREAMING::HAS_MODEL_LOADED(Red_UFO))
{
STREAMING::REQUEST_MODEL(Red_UFO, 0);
scriptWait(0);
}
if (STREAMING::HAS_MODEL_LOADED(Red_UFO))
{
LocalModel_121 = OBJECT::CREATE_OBJECT(Red_UFO, Coords.x, Coords.y, Coords.z + 8.0f, 1, 1, 0, 0, 1);
}
}
else
{
PrintSubtitle("MODEL NOT IN CDIMAGE");
}
//if (TXD::_0xBA0163B277C2D2D0(Model_FX))
//{
//Hmm UFO PFX ???
//TXD::_0xDB1BD07FB464584D(Model_FX, 0);
//}
if (ENTITY::DOES_ENTITY_EXIST(LocalModel_121))
{
UFOCoords = ENTITY::GET_ENTITY_COORDS(LocalModel_121, true, true);
// Should play UFO sounds at its coord ?!
AUDIO::PLAY_SOUND_FROM_COORD("Arrive", UFOCoords.x, UFOCoords.y, UFOCoords.z, "Ufos_Sounds", 0, 0, 1);
AUDIO::PLAY_SOUND_FRONTEND("Arrive", "Ufos_Sounds", true, 1);
}
return LocalModel_121;
}
|
c++
| 13 | 0.664452 | 104 | 28.529412 | 51 |
inline
|
#define USE_OWN_TESTS
using System;
using Microsoft.Extensions.DependencyInjection;
#if USE_OWN_TESTS
using FactoryFactory.Tests.MicrosoftTests;
#else
using Microsoft.Extensions.DependencyInjection.Specification;
#endif
namespace FactoryFactory.Tests
{
public class MicrosoftSpecificationFixture : DependencyInjectionSpecificationTests
{
protected override IServiceProvider CreateServiceProvider(IServiceCollection serviceCollection)
{
var registry = new Registry();
registry.AddRange(serviceCollection);
return registry.CreateContainer();
}
}
}
|
c#
| 13 | 0.768913 | 106 | 30.608696 | 23 |
starcoderdata
|
//*********************************************************************
//xCAD
//Copyright(C) 2021 Xarial Pty Limited
//Product URL: https://www.xcad.net
//License: https://xcad.xarial.com/license/
//*********************************************************************
using SolidWorks.Interop.sldworks;
using SolidWorks.Interop.swconst;
using System;
using System.Windows.Forms;
using Xarial.XCad.SolidWorks.Services;
using Xarial.XCad.SolidWorks.UI.Commands.Exceptions;
using Xarial.XCad.SolidWorks.Utils;
using Xarial.XCad.UI;
using Xarial.XCad.Toolkit;
using System.Linq;
namespace Xarial.XCad.SolidWorks.UI.Toolkit
{
internal class FeatureManagerTabCreator : CustomControlCreator<Tuple<IFeatMgrView, string>, TControl>
{
private readonly IServiceProvider m_SvcProvider;
private readonly ModelViewManager m_ModelViewMgr;
private readonly IFeatureManagerTabControlProvider m_TabProvider;
internal FeatureManagerTabCreator(ModelViewManager modelViewMgr, IServiceProvider svcProvider)
{
m_ModelViewMgr = modelViewMgr;
m_SvcProvider = svcProvider;
m_TabProvider = m_SvcProvider.GetService
}
protected override Tuple<IFeatMgrView, string> HostComControl(string progId, string title, IXImage image,
out TControl specCtrl)
{
using (var iconsConv = m_SvcProvider.GetService
{
var imgPath = iconsConv.ConvertIcon(new FeatMgrViewIcon(image)).First();
var featMgrView = m_TabProvider.ProvideComControl(m_ModelViewMgr, imgPath, progId, title);
specCtrl = default;
if (featMgrView != null)
{
specCtrl = (TControl)featMgrView.GetControl();
}
if (specCtrl == null)
{
throw new ComControlHostException(progId);
}
return new Tuple<IFeatMgrView, string>(featMgrView, title);
}
}
protected override Tuple<IFeatMgrView, string> HostNetControl(Control winCtrlHost, TControl ctrl,
string title, IXImage image)
{
using (var iconsConv = m_SvcProvider.GetService
{
var imgPath = iconsConv.ConvertIcon(new FeatMgrViewIcon(image)).First();
var featMgrView = m_TabProvider.ProvideNetControl(m_ModelViewMgr, winCtrlHost, imgPath, title);
if (featMgrView != null)
{
return new Tuple<IFeatMgrView, string>(featMgrView, title);
}
else
{
throw new NetControlHostException(winCtrlHost.Handle);
}
}
}
}
}
|
c#
| 21 | 0.587707 | 115 | 35.658228 | 79 |
starcoderdata
|
#ifndef POLYNOMIAL2_H
#define POLYNOMIAL2_H
#include "./Global.h"
class Polynomial2
{
private:
int n;
public:
Polynomial2();//构造函数
~Polynomial2();//析构函数
float fn();//求值
private:
float fn(int n);//递归调用
};
#endif
|
c
| 9 | 0.591731 | 92 | 16.571429 | 21 |
starcoderdata
|
'use strict';
require('dotenv').config();
const path = require('path');
const handlersConfig = require('./handlers');
module.exports = {
client: {
shopName: process.env.SHOPIFY_NAME,
apiKey: process.env.SHOPIFY_API_KEY,
password:
autoLimit: { calls: 2, interval: 1000, bucketSize: 35 }
// autoLimit: true
},
handlers: [
{
handler: require('../src/handlers/shopify/vendor'),
config: handlersConfig.vendor
},
{
handler: require('../src/handlers/shopify/tags'),
config: handlersConfig.tags
},
function(product) {
product.product_type = 'Watches';
return product;
}
],
softRemove: process.env.SHOPIFY_SOFT_REMOVE,
outputDir: path.resolve(__dirname, '../var/shopify'),
// cacheDir: false
cacheDir: path.resolve(__dirname, '../var/shopify/cache')
};
|
javascript
| 8 | 0.581582 | 63 | 28.382353 | 34 |
starcoderdata
|
static float ComputeAccumulatedScale(float Exponent, int32 CascadeIndex, int32 CascadeCount)
{
if(CascadeIndex <= 0)
{
return 0.0f;
}
float CurrentScale = 1;
float TotalScale = 0.0f;
float Ret = 0.0f;
// lame implementation for simplicity, CascadeIndex is small anyway
for(int i = 0; i < CascadeCount; ++i)
{
if(i < CascadeIndex)
{
Ret += CurrentScale;
}
TotalScale += CurrentScale;
CurrentScale *= Exponent;
}
return Ret / TotalScale;
}
|
c++
| 9 | 0.660494 | 92 | 19.291667 | 24 |
inline
|
using System.Threading;
using System.Threading.Tasks;
using AspNetCore.Authentication.ApiToken.Abstractions;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
namespace AspNetCore.Authentication.ApiToken
{
public class ApiTokenInitializeService: IHostedService
{
private readonly IApiTokenCacheService _cacheService;
private readonly ILogger _logger;
public ApiTokenInitializeService(IApiTokenCacheService cacheService,ILogger logger)
{
_cacheService = cacheService;
_logger = logger;
}
public async Task StartAsync(CancellationToken cancellationToken)
{
await _cacheService.InitializeAsync();
}
public Task StopAsync(CancellationToken cancellationToken)
{
return Task.CompletedTask;
}
}
}
|
c#
| 11 | 0.712105 | 118 | 30.655172 | 29 |
starcoderdata
|
import os
SITE_ID = 1
DEBUG = True
MEDIA_ROOT = os.path.normcase(os.path.dirname(os.path.abspath(__file__)))
MEDIA_URL = '/media/'
DATABASE_ENGINE = 'sqlite3'
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': 'drf_example',
}
}
INSTALLED_APPS = [
'django.contrib.contenttypes',
'django.contrib.staticfiles',
'django.contrib.sites',
'django.contrib.sessions',
'django.contrib.auth',
'django.contrib.admin',
'rest_framework',
'example',
]
STATIC_URL = '/static/'
ROOT_URLCONF = 'example.urls'
SECRET_KEY = 'abc123'
PASSWORD_HASHERS = ('django.contrib.auth.hashers.UnsaltedMD5PasswordHasher', )
MIDDLEWARE_CLASSES = ()
JSON_API_FORMAT_KEYS = 'camelize'
JSON_API_FORMAT_TYPES = 'camelize'
REST_FRAMEWORK = {
'PAGE_SIZE': 5,
'EXCEPTION_HANDLER': 'rest_framework_json_api.exceptions.exception_handler',
'DEFAULT_PAGINATION_CLASS':
'rest_framework_json_api.pagination.PageNumberPagination',
'DEFAULT_PARSER_CLASSES': (
'rest_framework_json_api.parsers.JSONParser',
'rest_framework.parsers.FormParser',
'rest_framework.parsers.MultiPartParser'
),
'DEFAULT_RENDERER_CLASSES': (
'rest_framework_json_api.renderers.JSONRenderer',
'rest_framework.renderers.BrowsableAPIRenderer',
),
'DEFAULT_METADATA_CLASS': 'rest_framework_json_api.metadata.JSONAPIMetadata',
}
|
python
| 10 | 0.67182 | 81 | 24.410714 | 56 |
starcoderdata
|
public ActionConsequence checkResult(Action action) {
Position pacmanPos = pacman.getCurrentPosition();
/*Check if there is a wall*/
int pos = pacmanPos.x + colAmount * pacmanPos.y;
switch (action) {
case LEFT:
if ((boardData[pos] & 1) != 0 || (pacmanPos.x == 0))
return ActionConsequence.WALL;
break;
case RIGHT:
if ((boardData[pos] & 4) != 0 || (pacmanPos.x == colAmount - 1))
return ActionConsequence.WALL;
break;
case UP:
if ((boardData[pos] & 2) != 0 || (pacmanPos.y == 0))
return ActionConsequence.WALL;
break;
case DOWN:
if ((boardData[pos] & 8) != 0 || (pacmanPos.y == (rowAmount - 1)))
return ActionConsequence.WALL;
}
Position pacmanNextPos = Position.giveConsequence(pacmanPos, action);
//Check if there is a monster
for (Monster m : monsters) {
Action[] actions = m.giveActionsToDo(1);
Position currentMonsterPos = new Position(m.getCurrentPosition().y, m.getCurrentPosition().x);
Position nextMonsterPos = Position.giveConsequence(currentMonsterPos, actions[0]);
//Two cases: 1) MonsterPosNextTime = PacmanPosNextTime
if (Position.isEqual(nextMonsterPos, pacmanNextPos))
return ActionConsequence.MONSTER;
//2) MonsterCurrentPos = PacmanNextPos AND MonsterNextPos = PacmanCurrentPos
if (Position.isEqual(currentMonsterPos, pacmanNextPos) && Position.isEqual(nextMonsterPos, pacmanPos))
return ActionConsequence.MONSTER;
}
return ActionConsequence.FREE;
}
|
java
| 13 | 0.555675 | 114 | 39.355556 | 45 |
inline
|
package io.quarkiverse.jberet.it.chunk;
import java.util.Properties;
import javax.batch.operations.JobOperator;
import javax.batch.runtime.BatchRuntime;
import javax.batch.runtime.JobExecution;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import io.quarkus.runtime.annotations.RegisterForReflection;
/**
* To verify that BatchRuntime.getJobOperator() returns the right operator in native mode.
*/
@Path("/batch")
@Produces(MediaType.APPLICATION_JSON)
public class BatchResource {
@GET
@Path("/job/execute/{auctionsFile}")
public Response executeJob(@PathParam("auctionsFile") final String auctionsFile) {
JobOperator jobOperator = BatchRuntime.getJobOperator();
Properties jobParameters = new Properties();
jobParameters.put("auctions.file", auctionsFile);
long executionId = jobOperator.start("auctions", jobParameters);
JobExecution jobExecution = jobOperator.getJobExecution(executionId);
return Response.ok(new JobData(executionId, jobExecution.getBatchStatus().toString())).build();
}
@RegisterForReflection
public static class JobData {
private Long executionId;
private String status;
public JobData() {
}
public JobData(final Long executionId, final String status) {
this.executionId = executionId;
this.status = status;
}
public Long getExecutionId() {
return executionId;
}
public void setExecutionId(final Long executionId) {
this.executionId = executionId;
}
public String getStatus() {
return status;
}
public void setStatus(final String status) {
this.status = status;
}
}
}
|
java
| 14 | 0.689915 | 103 | 29.661538 | 65 |
starcoderdata
|
func (db *psqlxStore) CreateFinding(eventTime time.Time, f Finding, sourceID string) (*Finding, error) {
tx, err := db.DB.Beginx()
if err != nil {
return nil, err
}
// Create finding.
_, err = tx.Exec("INSERT INTO findings (issue_id, target_id, affected_resource, fingerprint, score, status, details, resources) VALUES ($1, $2, $3, $4, $5, $6, $7, $8)",
f.IssueID, f.TargetID, f.AffectedResource, f.Fingerprint, f.Score, f.Status, f.Details, f.Resources)
if err != nil {
tx.Rollback()
return nil, err
}
// Retrieve.
finding := Finding{}
err = tx.Get(&finding, "SELECT * FROM findings WHERE issue_id = $1 AND target_id = $2 AND affected_resource = $3 ", f.IssueID, f.TargetID, f.AffectedResource)
if err != nil {
tx.Rollback()
return nil, err
}
// Create finding event.
_, err = tx.Exec("INSERT INTO finding_events (finding_id, source_id, time) VALUES ($1, $2, $3)",
finding.ID, sourceID, eventTime)
if err != nil {
tx.Rollback()
return nil, err
}
if err = tx.Commit(); err != nil {
tx.Rollback()
return nil, err
}
return &finding, nil
}
|
go
| 8 | 0.648799 | 170 | 28.27027 | 37 |
inline
|
[TestMethod()]
public void ExecuteTest_ConcurrencyByNumber_2()
{
Initialization init = GetInitializationObject();
string sbmFileName = Path.GetTempPath() + System.Guid.NewGuid().ToString() + ".sbm";
File.WriteAllBytes(sbmFileName, Properties.Resources.InsertForThreadedTest);
init.CopyDbConfigFileLongToTestPath();
string multiDbOverrideSettingFileName = Initialization.DbConfigFileName;
string loggingPath = Path.GetTempPath() + System.Guid.NewGuid().ToString();
string[] args = new string[] {
"threaded", "run",
"--authtype", AuthenticationType.Windows.ToString(),
"--rootloggingpath", loggingPath,
"--transactional" , "true",
"--trial", "false",
"--override", multiDbOverrideSettingFileName,
"--packagename", sbmFileName,
"--timeoutretrycount", "0",
"--concurrency", "2",
"--concurrencytype", "Count"
};
var cmdLine = CommandLineBuilder.ParseArguments(args);
ThreadedExecution target = new ThreadedExecution(cmdLine);
int actual;
actual = target.Execute();
try
{
if (actual == -600)
Assert.Fail("Unable to completed test.");
SqlBuildManager.Logging.Configure.CloseAndFlushAllLoggers();
string[] executionLogFile = ReadLines(Path.Combine(loggingPath, "SqlBuildManager.ThreadedExecution.log")).ToArray();
//Should not all sequential!
Assert.IsTrue(executionLogFile[2].IndexOf("SqlBuildTest: Queuing up thread") > -1);
Assert.IsTrue(executionLogFile[3].IndexOf("SqlBuildTest: Starting up thread") > -1);
Assert.IsTrue(executionLogFile[4].IndexOf("SqlBuildTest11: Queuing up thread") > -1);
Assert.IsTrue(executionLogFile[5].IndexOf("SqlBuildTest11: Starting up thread") > -1);
}
finally
{
try
{
if (File.Exists(sbmFileName))
File.Delete(sbmFileName);
if (File.Exists(multiDbOverrideSettingFileName))
File.Delete(multiDbOverrideSettingFileName);
if (Directory.Exists(loggingPath))
Directory.Delete(loggingPath, true);
}
catch { }
}
}
|
c#
| 19 | 0.545384 | 132 | 41.459016 | 61 |
inline
|
def casval(cls, row, updating):
changeset = cls._cast(updating, row)
changeset = cls._validate(updating, changeset)
# A user specified validation function
validate_func = getattr(cls, "validate", lambda x: x)
changeset = validate_func(changeset)
return changeset
|
python
| 9 | 0.647436 | 61 | 33.777778 | 9 |
inline
|
import append from '../append';
import render from '../../render';
describe('append modifier', () => {
test('causes text to appear with the previous block', () => {
const output = render(
{
blocks: [
{type: 'text', content: 'Hello'},
{type: 'modifier', content: 'append'},
{type: 'text', content: 'there'}
],
vars: []
},
[],
[append]
);
expect(output.trim()).toBe(' there
});
});
|
javascript
| 21 | 0.536036 | 62 | 20.142857 | 21 |
starcoderdata
|
package utils
import (
"errors"
"fmt"
)
type Task struct {
Id int
Name string
Description string
IsComplete bool
IsActive bool
}
type TaskList struct {
Tasks []*Task
}
func (t *Task) print() {
fmt.Printf("%+v\n", t)
}
func (t *TaskList) search(id int) (Task, error) {
for _, v := range t.Tasks {
if v.Id == id {
return *v, nil
}
}
return Task{}, errors.New("Task not found")
}
func (t *TaskList) ShowTasks() {
for _, v := range t.Tasks {
v.print()
}
}
// Create a new task
func (t *TaskList) CreateTask(name string, description string) {
id := len(t.Tasks)
newTask := Task{id + 1, name, description, false, true}
t.Tasks = append(t.Tasks, &newTask)
fmt.Print("Task created: ")
newTask.print()
}
func (t *TaskList) CompleteTask(id int) {
task, err := t.search(id)
if err != nil {
fmt.Println(err)
} else {
task.IsComplete = true
}
}
func (t *TaskList) DeleteTask(id int) {
task, err := t.search(id)
if err != nil {
fmt.Println(err)
} else {
task.IsActive = false
}
}
|
go
| 10 | 0.615602 | 64 | 15.369231 | 65 |
starcoderdata
|
private async void OnGPSResponse(bool success, LocationInfo locationInfo)
{
// Try to get buildings
await Buildings();
if (!success || buildingID.IsNullOrEmpty())
{
SelectLocationDialog();
}
}
|
c#
| 9 | 0.581028 | 73 | 24.4 | 10 |
inline
|
"""
Copyright (C) 2005, 2006, 2007
Copyright (C) 2005
Copyright (C) 2005
This file is part of QuantLib, a free-software/open-source library
for financial quantitative analysts and developers - http://quantlib.org/
QuantLib is free software: you can redistribute it and/or modify it
under the terms of the QuantLib license. You should have received a
copy of the license along with this program; if not, please email
The license is also available online at
This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the license for more details.
"""
"""Encapsulate state and behavior required to generate source code for a
function."""
from gensrc.utilities import common
from gensrc.utilities import buffer
from gensrc.serialization import serializable
from gensrc.functions import behavior
from gensrc.parameters import parameterlist
from gensrc.parameters import parameter
from gensrc.configuration import environment
# possible states for the implementation of a function on a given platform
DOC_ONLY = 0 # only autogenerate documentation for this function - no code
MANUAL = 1 # function hand-written - registration may be autogenerated
AUTO = 2 # autogenerate all code and documentation (the default)
class SupportedPlatform(serializable.Serializable):
"""Define the implementation of a particular function on a particular
platform."""
#############################################
# class variables
#############################################
groupName_ = 'SupportedPlatforms'
# map to take the implementation as a string loaded from XML metadata
# and convert it to one of the constants defined above
implStrToInt = {
'documentationOnly' : DOC_ONLY,
'manual' : MANUAL,
'auto' : AUTO }
#############################################
# public interface
#############################################
def implNum(self):
"""Return the constant which corresponds to the string describing this
platform."""
return self.implNum_
def xlMacro(self):
"""Return a boolean indicating whether this Addin function should
acquire macro capabilities on the Excel platform."""
return self.xlMacro_
def calcInWizard(self):
"""Return a boolean indicating whether this Addin function should
execute under the Function Wizard on the Excel platform."""
return self.calcInWizard_
#############################################
# serializer interface
#############################################
def serialize(self, serializer):
"""Load/unload class state to/from serializer object."""
serializer.serializeAttribute(self, common.NAME)
serializer.serializeAttribute(self, common.IMPLEMENTATION, 'auto')
serializer.serializeAttributeBoolean(self, common.XL_MACRO, True)
serializer.serializeAttributeBoolean(self, common.CALC_IN_WIZARD, True)
def postSerialize(self):
"""Derive the integer constant associated with the deserialized
string."""
self.implNum_ = SupportedPlatform.implStrToInt[self.implementation_]
|
python
| 9 | 0.668893 | 79 | 37.685393 | 89 |
starcoderdata
|
def __init__(self, key_name, key_value, namespace, queue_name, device_name):
"""initializes the object with the values needed to operate """
self.key_name = key_name
self.key_value = key_value
self.namespace = namespace
self.queue_name = queue_name
self.device_name = device_name
|
python
| 6 | 0.636086 | 76 | 45.857143 | 7 |
inline
|
load("@bazel_tools//tools/build_defs/repo:git.bzl", "git_repository")
load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")
def toolchains_cloudabi_dependencies():
http_archive(
name = "org_llvm_llvm_x86_64_apple_darwin",
build_file = "@org_cloudabi_bazel_toolchains_cloudabi//:BUILD.llvm",
sha256 = "b3ad93c3d69dfd528df9c5bb1a434367babb8f3baea47fbb99bf49f1b03c94ca",
strip_prefix = "clang+llvm-7.0.0-x86_64-apple-darwin",
urls = ["https://releases.llvm.org/7.0.0/clang+llvm-7.0.0-x86_64-apple-darwin.tar.xz"],
)
http_archive(
name = "org_llvm_llvm_x86_64_unknown_freebsd",
build_file = "@org_cloudabi_bazel_toolchains_cloudabi//:BUILD.llvm",
sha256 = "95ceb933ccf76e3ddaa536f41ab82c442bbac07cdea6f9fbf6e3b13cc1711255",
strip_prefix = "clang+llvm-7.0.0-amd64-unknown-freebsd11",
urls = ["https://releases.llvm.org/7.0.0/clang+llvm-7.0.0-amd64-unknown-freebsd11.tar.xz"],
)
http_archive(
name = "org_llvm_llvm_x86_64_unknown_linux_gnu",
build_file = "@org_cloudabi_bazel_toolchains_cloudabi//:BUILD.llvm",
sha256 = "5c90e61b06d37270bc26edb305d7e498e2c7be22d99e0afd9f2274ef5458575a",
strip_prefix = "clang+llvm-7.0.0-x86_64-linux-gnu-ubuntu-14.04",
urls = ["https://releases.llvm.org/7.0.0/clang+llvm-7.0.0-x86_64-linux-gnu-ubuntu-14.04.tar.xz"],
)
git_repository(
name = "org_cloudabi_argdata",
commit = "191ab391fbe0be3edbee59bedd73165de9b3abf5",
remote = "https://github.com/NuxiNL/argdata.git",
)
git_repository(
name = "org_cloudabi_cloudabi",
commit = "af51ede669dbca0875d20893dae7f760b052b238",
remote = "https://github.com/NuxiNL/cloudabi.git",
)
if "org_cloudabi_cloudabi_utils" not in native.existing_rules():
git_repository(
name = "org_cloudabi_cloudabi_utils",
commit = "be1ce21e1dded9c0c0a6ebe144cbea01cf44a874",
remote = "https://github.com/NuxiNL/cloudabi-utils.git",
)
if "org_cloudabi_cloudlibc" not in native.existing_rules():
git_repository(
name = "org_cloudabi_cloudlibc",
commit = "04a34ca2ead2408dde759395cc370b373ce8ed64",
remote = "https://github.com/NuxiNL/cloudlibc.git",
)
http_archive(
name = "org_llvm_cfe",
build_file = "@org_cloudabi_bazel_toolchains_cloudabi//:BUILD.cfe",
sha256 = "a45b62dde5d7d5fdcdfa876b0af92f164d434b06e9e89b5d0b1cbc65dfe3f418",
strip_prefix = "cfe-7.0.1.src",
urls = ["https://releases.llvm.org/7.0.1/cfe-7.0.1.src.tar.xz"],
)
http_archive(
name = "org_llvm_compiler_rt",
build_file = "@org_cloudabi_bazel_toolchains_cloudabi//:BUILD.compiler-rt",
sha256 = "782edfc119ee172f169c91dd79f2c964fb6b248bd9b73523149030ed505bbe18",
strip_prefix = "compiler-rt-7.0.1.src",
urls = ["https://releases.llvm.org/7.0.1/compiler-rt-7.0.1.src.tar.xz"],
)
http_archive(
name = "org_llvm_libcxx",
build_file = "@org_cloudabi_bazel_toolchains_cloudabi//:BUILD.libcxx",
patches = [
"@org_cloudabi_bazel_toolchains_cloudabi//:patches/libcxx-no-std-funcs.diff",
"@org_cloudabi_bazel_toolchains_cloudabi//:patches/libcxx-unsafe-string-includes.diff",
],
sha256 = "020002618b319dc2a8ba1f2cba88b8cc6a209005ed8ad29f9de0c562c6ebb9f1",
strip_prefix = "libcxx-7.0.1.src",
urls = ["https://releases.llvm.org/7.0.1/libcxx-7.0.1.src.tar.xz"],
)
http_archive(
name = "org_llvm_libcxxabi",
build_file = "@org_cloudabi_bazel_toolchains_cloudabi//:BUILD.libcxxabi",
sha256 = "8168903a157ca7ab8423d3b974eaa497230b1564ceb57260be2bd14412e8ded8",
strip_prefix = "libcxxabi-7.0.1.src",
urls = ["https://releases.llvm.org/7.0.1/libcxxabi-7.0.1.src.tar.xz"],
)
http_archive(
name = "org_llvm_libunwind",
build_file = "@org_cloudabi_bazel_toolchains_cloudabi//:BUILD.libunwind",
sha256 = "89c852991dfd9279dbca9d5ac10b53c67ad7d0f54bbab7156e9f057a978b5912",
strip_prefix = "libunwind-7.0.1.src",
urls = ["https://releases.llvm.org/7.0.1/libunwind-7.0.1.src.tar.xz"],
)
http_archive(
name = "org_musl_libc_musl",
patches = [
"@org_cloudabi_bazel_toolchains_cloudabi//:patches/musl-bazel.diff",
"@org_cloudabi_bazel_toolchains_cloudabi//:patches/musl-cloudabi.diff",
"@org_cloudabi_bazel_toolchains_cloudabi//:patches/musl-warnings.diff",
],
sha256 = "44be8771d0e6c6b5f82dd15662eb2957c9a3173a19a8b49966ac0542bbd40d61",
strip_prefix = "musl-1.1.20",
urls = ["https://www.musl-libc.org/releases/musl-1.1.20.tar.gz"],
)
http_archive(
name = "net_jemalloc_jemalloc",
build_file = "@org_cloudabi_bazel_toolchains_cloudabi//:BUILD.jemalloc",
patches = [
"@org_cloudabi_bazel_toolchains_cloudabi//:patches/jemalloc-cloudabi.diff",
"@org_cloudabi_bazel_toolchains_cloudabi//:patches/jemalloc-generated.diff",
],
sha256 = "5396e61cc6103ac393136c309fae09e44d74743c86f90e266948c50f3dbb7268",
strip_prefix = "jemalloc-5.1.0",
urls = ["https://github.com/jemalloc/jemalloc/releases/download/5.1.0/jemalloc-5.1.0.tar.bz2"],
)
http_archive(
name = "com_google_double_conversion",
patches = ["@org_cloudabi_bazel_toolchains_cloudabi//:patches/double-conversion-pull-54.diff"],
sha256 = "aef5f528dab826b269b54766a4c2d179e361866c75717af529f91c56b4034665",
strip_prefix = "double-conversion-3.1.0",
urls = ["https://github.com/google/double-conversion/archive/3.1.0.tar.gz"],
)
|
python
| 10 | 0.651959 | 105 | 44.153846 | 130 |
starcoderdata
|
import { action } from 'easy-peasy'
const uiModel = {
currentNavigationItem: ''
}
export default uiModel
|
javascript
| 6 | 0.715596 | 35 | 14.571429 | 7 |
starcoderdata
|
internal async Task<WhoAmIResponse> GetWhoAmIDetails(IOrganizationService dvService, Guid trackingID = default)
{
if (dvService != null)
{
Stopwatch dtQueryTimer = new Stopwatch();
dtQueryTimer.Restart();
try
{
if (trackingID == Guid.Empty)
trackingID = Guid.NewGuid();
WhoAmIRequest req = new WhoAmIRequest();
if (trackingID != Guid.Empty) // Add Tracking number of present.
req.RequestId = trackingID;
logEntry.Log(string.Format(CultureInfo.InvariantCulture, "Execute Command - WhoAmIRequest : RequestId={0}", trackingID.ToString()));
WhoAmIResponse resp;
if (_configuration.Value.UseWebApiLoginFlow)
{
resp = (WhoAmIResponse)(await Command_WebAPIProcess_ExecuteAsync(
req, null, false, null, Guid.Empty, false, _configuration.Value.MaxRetryCount, _configuration.Value.RetryPauseTime, new CancellationToken()).ConfigureAwait(false));
}
else
{
resp = (WhoAmIResponse)dvService.Execute(req);
}
// Left in information mode intentionally.
logEntry.Log(string.Format(CultureInfo.InvariantCulture, "Executed Command - WhoAmIRequest : RequestId={1} : total duration: {0}", dtQueryTimer.Elapsed.ToString(), trackingID.ToString()));
return resp;
}
catch (Exception ex)
{
logEntry.Log(string.Format(CultureInfo.InvariantCulture, "Failed to Executed Command - WhoAmIRequest : RequestId={1} : total duration: {0}", dtQueryTimer.Elapsed.ToString(), trackingID.ToString()), TraceEventType.Error);
logEntry.Log("************ Exception - Failed to lookup current user", TraceEventType.Error, ex);
throw new DataverseOperationException("Exception - Failed to lookup current user", ex);
}
finally
{
dtQueryTimer.Stop();
}
}
else
logEntry.Log("Cannot Look up current user - No Connection to work with.", TraceEventType.Error);
return null;
}
|
c#
| 22 | 0.535671 | 240 | 50.708333 | 48 |
inline
|
kern_return_t UserPatcher::vmProtect(vm_map_t map, vm_offset_t start, vm_size_t size, boolean_t set_maximum, vm_prot_t new_protection) {
// On 10.14 XNU attempted to fix broken W^X and introduced several changes:
// 1. vm_protect (vm_map_protect) got a call to cs_process_enforcement (formerly cs_enforcement), which aborts
// with a KERN_PROTECTION_FAILURE abort on failure. So far global codesign enforcement is not enabled,
// and it is enough to remove CS_ENFORCEMENT from each process specifically. A thing to consider in future
// macOS versions. Watch out for sysctl vm.cs_process_enforcemen.
// 2. More processes get CS_KILL in addition to CS_ENFORCEMENT, which does not let us easily lift CS_ENFORCEMENT
// during the vm_protect call, we also should remove CS_KILL from the process we patch. This slightly lowers
// the security, but only for the patched process, and in no worse way than 10.13 by default. Watch out for
// vm.cs_force_kill in the future.
auto currproc = reinterpret_cast<procref *>(current_proc());
if ((new_protection & (VM_PROT_EXECUTE|VM_PROT_WRITE)) == (VM_PROT_EXECUTE|VM_PROT_WRITE) &&
getKernelVersion() >= KernelVersion::Mojave && currproc != nullptr) {
DBGLOG("user", "found request for W^X switch-off %d", new_protection);
// struct proc layout usually changes with time, so we will calculate the offset based on partial layout:
// struct pgrp *p_pgrp Pointer to process group. (LL)
// uint32_t p_csflags flags for codesign (PL)
// uint32_t p_pcaction action for process control on starvation
// uint8_t p_uuid[16] from LC_UUID load command
// cpu_type_t p_cputype
// cpu_subtype_t p_cpusubtype
if (csFlagsOffset == 0) {
for (size_t off = 0x200; off < 0x400; off += sizeof (uint32_t)) {
auto csOff = off - sizeof(uint8_t[16]) - sizeof(uint32_t)*2;
auto cpu = getMember<uint32_t>(currproc, off);
auto subcpu = getMember<uint32_t>(currproc, off + sizeof (uint32_t)) & ~CPU_SUBTYPE_MASK;
if ((cpu == CPU_TYPE_X86_64 || cpu == CPU_TYPE_I386) &&
(subcpu == CPU_SUBTYPE_X86_64_ALL || subcpu == CPU_SUBTYPE_X86_64_H) &&
!(getMember<uint32_t>(currproc, csOff) & CS_KILLED)) {
csFlagsOffset = csOff;
break;
}
}
// Force xnu-4903.221.2 offset by default, 10.14.1 b5
if (csFlagsOffset != 0) {
DBGLOG("user", "found p_csflags offset %X", (uint32_t)csFlagsOffset);
} else {
SYSLOG("user", "falling back to hardcoded p_csflags offset");
csFlagsOffset = 0x308;
}
}
uint32_t &flags = getMember<uint32_t>(currproc, csFlagsOffset);
if (flags & CS_ENFORCEMENT) {
DBGLOG("user", "W^X is enforced %X, disabling", flags);
flags &= ~(CS_KILL|CS_HARD|CS_ENFORCEMENT);
// Changing CS_HARD, CS_DEBUGGED, and vm_map switch protection is not required, yet may avoid issues
// in the future.
flags |= CS_DEBUGGED;
if (that->orgVmMapSwitchProtect)
that->orgVmMapSwitchProtect(that->orgGetTaskMap(currproc->task), false);
auto r = vm_protect(map, start, size, set_maximum, new_protection);
SYSLOG_COND(r != KERN_SUCCESS, "user", "W^X removal failed with %d", r);
// Initially thought that we could return CS_ENFORCEMENT, yet this causes certain binaries to crash,
// like WindowServer patched by -cdfon.
return r;
}
}
// Forward to the original proc routine
return vm_protect(map, start, size, set_maximum, new_protection);
}
|
c++
| 19 | 0.682636 | 136 | 52.828125 | 64 |
inline
|
#%%
# %load_ext autoreload
# %autoreload 2
"""
run_mapper.py
=============
Sample code for running the BioRadMapper in the ODM-Import library.
The lab_data parameter passed to run_mapper is the output of QPCRExtracter. static_data is not used by the mapper but included here for completeness.
"""
from wbe_odm.odm_mappers import biorad_mapper
from easydict import EasyDict
import argparse
import os
def run_mapper(config_file, map_path, lab_data, static_data, remove_duplicates, start_date, end_date, output):
mapper_dir = os.path.dirname(biorad_mapper.__file__)
config_file = config_file or os.path.join(mapper_dir, "biorad_mapper.yaml")
map_path = map_path or os.path.join(mapper_dir, "biorad_map.csv")
mapper = biorad_mapper.BioRadMapper(config_file=config_file)
mapper.read(lab_data,
static_data,
map_path=map_path,
remove_duplicates=bool(remove_duplicates),
startdate=start_date,
enddate=end_date)
output_file, duplicates_file = mapper.save_all(output, duplicates_file=remove_duplicates)
print("Finished mapping!")
return output_file, duplicates_file
if __name__ == "__main__":
if "get_ipython" in globals():
mapper_dir = os.path.dirname(biorad_mapper.__file__)
opts = EasyDict({
"config_file" : os.path.join(mapper_dir, "biorad_mapper.yaml"),
"map_path" : os.path.join(mapper_dir, "biorad_map.csv"),
"lab_data" : "/Users/martinwellman/Documents/Health/Wastewater/Code/extracted/merged-dec26.xlsx",
"static_data" : "",
"start_date" : "",
"end_date" : "",
"remove_duplicates" : "/Users/martinwellman/Documents/Health/Wastewater/Code/odmdata/dupes.xlsx",
"output" : "/Users/martinwellman/Documents/Health/Wastewater/Code/odmdata/odm_merged-dec26.xlsx",
})
else:
args = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)
args.add_argument("--config_file", type=str, help="Path to the mapper YAML config file. (Required)", required=True)
args.add_argument("--map_path", type=str, help="Path to the mapper CSV file. (Required)", required=True)
args.add_argument("--lab_data", type=str, help="Path to the lab data Excel file. (Required)", required=True)
args.add_argument("--static_data", type=str, help="Path to the static data Excel file. (Optional)", default=None)
args.add_argument("--start_date", type=str, help="Filter sample dates starting on this date (exclusive) (yyyy-mm-dd). (Optional)", default=None)
args.add_argument("--end_date", type=str, help="Filter sample dates ending on this date (exclusive) (yyyy-mm-dd). (Optional)", default=None)
args.add_argument("--remove_duplicates", type=str, help="If set then remove duplicates from all WW tables based on each table's primary key, and save the duplicates in this additional file. (Optional)", default=None)
args.add_argument("--output", type=str, help="Path to the Excel output file. (Required)", required=True)
opts = args.parse_args()
run_mapper(
config_file=opts.config_file,
map_path=opts.map_path,
lab_data=opts.lab_data,
static_data=opts.static_data,
remove_duplicates=opts.remove_duplicates,
start_date=opts.start_date,
end_date=opts.end_date,
output=opts.output
)
|
python
| 14 | 0.660519 | 224 | 50.029412 | 68 |
starcoderdata
|
const noop = () => {}
global.Ti = {
UI: {},
API: {
trace: console.log,
debug: console.log,
info: console.log,
warn: console.log,
error: console.log,
critical: console.log,
},
Platform: {
osname: 'iphone'
},
Stream: {
pump: (v, fn) => fn({buffer: 'buffer-mock'})
},
Network: {
createHTTPClient: v => {
return {
open: noop,
setRequestHeader: noop,
send: noop,
readyState: 4,
status: 200,
responseText: 'module.exports = "abc"'
}
},
Socket: {
createTCP: (options) => {
options.connect = noop
return options
}
}
},
App: {
_restart: val => val
}
}
|
javascript
| 14 | 0.397025 | 54 | 18 | 46 |
starcoderdata
|
#include <iostream>
#include <string>
#include <algorithm>
#include <cmath>
#include <map>
#define MOD 1000000007LL
using namespace std;
int main(){
string seq[3];
cin >> seq[0] >> seq[1] >> seq[2];
int win[3] = { };
int tmp = 0;
while(win[tmp] != seq[tmp].size()){
int x = (seq[tmp][win[tmp]] - 'a');
win[tmp]++;
tmp = x;
}
cout << (char)('A' + tmp) << endl;
return 0;
}
|
c++
| 13 | 0.572539 | 37 | 17.428571 | 21 |
codenet
|
#include "DataGenericInternalEnergySensor.h"
#include "DataDomainFactory.h"
# define YARS_STRING_MAPPING (char*)"mapping"
# define YARS_STRING_POSE (char*)"pose"
# define YARS_STRING_NAME (char*)"name"
# define YARS_STRING_MIN_MAX_DEFINITION (char*)"min_max_definition"
DataGenericInternalEnergySensor::DataGenericInternalEnergySensor(DataNode* parent)
: DataSensor(parent, DATA_GENERIC_INTERNAL_ENERGY_SENSOR)
{ }
DataGenericInternalEnergySensor::~DataGenericInternalEnergySensor()
{
}
void DataGenericInternalEnergySensor::add(DataParseElement *element)
{
if(element->closing(YARS_STRING_GENERIC_INTERNAL_ENERGY_SENSOR))
{
current = parent;
}
if(element->opening(YARS_STRING_GENERIC_INTERNAL_ENERGY_SENSOR))
{
element->set(YARS_STRING_NAME, _name);
}
if(element->opening(YARS_STRING_NOISE))
{
_noise = new DataNoise(this);
current = _noise;
_noise->add(element);
}
if(element->opening(YARS_STRING_FILTER))
{
_filter = new DataFilter(this);
current = _filter;
_filter->add(element);
}
if(element->opening(YARS_STRING_MAPPING))
{
DataDomainFactory::set(_mapping, element);
}
}
void DataGenericInternalEnergySensor::createXsd(XsdSpecification *spec)
{
XsdSequence *sensor = new XsdSequence(YARS_STRING_GENERIC_INTERNAL_ENERGY_SENSOR_DEFINITION);
sensor->add(NA(YARS_STRING_NAME, YARS_STRING_XSD_STRING, false));
sensor->add(XE(YARS_STRING_MAPPING, YARS_STRING_MIN_MAX_DEFINITION, 1, 1));
sensor->add(XE(YARS_STRING_NOISE, YARS_STRING_NOISE_DEFINITION, 0, 1));
sensor->add(XE(YARS_STRING_FILTER, YARS_STRING_FILTER_DEFINITION, 0, 1));
spec->add(sensor);
DataNoise::createXsd(spec);
DataFilter::createXsd(spec);
}
DataGenericInternalEnergySensor* DataGenericInternalEnergySensor::_copy()
{
DataGenericInternalEnergySensor *copy = new DataGenericInternalEnergySensor(NULL);
copy->_name = _name;
if (_noise != NULL) copy->_noise = _noise->copy();
if (_filter != NULL) copy->_filter = _filter->copy();
copy->_mapping = _mapping;
return copy;
}
void DataGenericInternalEnergySensor::_resetTo(const DataSensor *sensor)
{
DataGenericInternalEnergySensor *other = (DataGenericInternalEnergySensor*)sensor;
_name = other->name();
_noise = other->noise();
_filter = other->filter();
_mapping = other->mapping();
}
|
c++
| 9 | 0.706723 | 95 | 30.315789 | 76 |
research_code
|
// @flow
import React, { Fragment, useCallback, useReducer, useState } from 'react'
import classNames from 'classnames'
import debounce from 'lodash/debounce'
import type { Element } from 'react'
import type {
PairT,
} from '../types'
import DeleteButton from './DeleteButton'
import Checkbox from '@material-ui/core/Checkbox'
import TextField from '@material-ui/core/TextField'
type PropsT = {
allPairs: Array
index: number,
onDelete?: Function,
pair: PairT,
readOnly?: boolean,
setPair?: Function,
setter?: Function,
}
function Pair(props: PropsT): Element<typeof Fragment> {
const {
allPairs,
index,
onDelete,
pair,
readOnly = false,
setPair,
setter,
} = props
const debouncedSave = useCallback(debounce((key, value, enabled) => {
if (setPair) {
console.log('key, value, enabled', key, value, enabled)
setPair(pair, setter, allPairs, index, key, value, enabled)
}
}, 1000), [])
const reducer = (state: PairT, action: { type: string, payload: string | boolean }): PairT => {
switch (action.type) {
case 'setKey':
debouncedSave(action.payload, state.value, state.enabled)
// $FlowExpectedError
return { ...state, key: action.payload }
case 'setValue':
debouncedSave(state.key, action.payload, state.enabled)
// $FlowExpectedError
return { ...state, value: action.payload }
case 'setEnabled':
debouncedSave(state.key, state.value, action.payload)
// $FlowExpectedError
return { ...state, enabled: action.payload }
default:
throw new Error()
}
}
const { key, value, enabled } = pair
const [state, dispatch] = useReducer(reducer, { key, value, enabled })
const [valid, setValid] = useState(true)
const updatePair = ({ type, payload }: { type: string, payload: string | boolean }) => {
let pairValid = true
if (type === 'setKey') {
pairValid = !allPairs.some(pair => pair.key !== state.key && pair.key === payload)
setValid(pairValid)
}
if (pairValid) {
dispatch({ type, payload })
}
}
return (
<TextField
className={classNames('pairText', { disabled: readOnly })}
defaultValue={state.key}
disabled={readOnly}
error={!valid}
label="Key"
onChange={(e) => updatePair({ type: 'setKey', payload: e.currentTarget.value })}
placeholder="Key"
/>
<TextField
className={classNames('pairText', { disabled: readOnly })}
defaultValue={state.value}
disabled={readOnly}
label="Value"
onChange={(e) => updatePair({ type: 'setValue', payload: e.currentTarget.value })}
placeholder="Value"
/>
{ !readOnly && (
<Checkbox
checked={state.enabled}
className={classNames('pairAction')}
onChange={(e) => updatePair({ type: 'setEnabled', payload: !state.enabled })}
/>
<DeleteButton
Element="span"
className={classNames('pairAction')}
onDelete={() => onDelete && onDelete(allPairs, setter, index)}
value={state.key + '/' + state.value}
/>
)}
)
}
export default Pair
|
javascript
| 18 | 0.596044 | 97 | 26.578512 | 121 |
starcoderdata
|
#include
#include
#include
#include
#include
// This is probably not needed to save space,
// in case you encounter any issues aliasing builtins remove this.
#define DUK_USE_LIGHTFUNC_BUILTINS
#include "duktape.h"
#include "dukbridge.h"
#include "dialog.h"
void Initialize();
void MainLoop();
void Terminate();
int main()
{
Initialize();
MainLoop();
Terminate();
return 0;
}
void Initialize()
{
#if !TARGET_API_MAC_CARBON
InitGraf(&qd.thePort);
InitFonts();
InitWindows();
InitMenus();
TEInit();
InitDialogs(NULL);
#endif
}
char * readFromResource(int resourceId) {
Handle hnd = GetResource('TEXT', resourceId);
long size = GetResourceSizeOnDisk(hnd);
char * out = malloc(size + 1);
ReadPartialResource(hnd, 0, out, size);
out[size] = '\0';
return out;
}
void MainLoop()
{
char * fakeReact = readFromResource(129); // app/fakeReact.js
duk_context *ctx = duk_create_heap_default();
duk_eval_string(ctx, fakeReact);
free(fakeReact);
emptyStack(ctx);
populateCtx(ctx);
emptyStack(ctx);
char * source = readFromResource(128); // app/index.js
duk_eval_string(ctx, source);
free(source);
emptyStack(ctx);
duk_eval_string(ctx, "React.mount(main())");
emptyStack(ctx);
}
void Terminate()
{
ExitToShell();
}
|
c
| 9 | 0.646728 | 66 | 18.465753 | 73 |
starcoderdata
|
export const types = {
CHECKOUT_WALLETS: "@@walletList/CHECKOUT_WALLETS",
MOUNT_WALLETS: "@@walletList/MOUNT_WALLETS",
CREATE_WALLET: "@@walletList/CREATE_WALLET",
DELETE_WALLET: "@@walletList/DELETE_WALLET",
UPDATE_WALLET_LIST: "@@walletList/UPDATE_WALLET_LIST",
FETCH_WALLET_INFO: "@@walletList/FETCH_WALLET_INFO",
MOUNT_WALLET_INFO: "@@walletList/MOUNT_WALLET_INFO",
UPDATE_WALLET_BY_WID: "@@walletList/UPDATE_WALLET_BY_WID"
};
|
javascript
| 7 | 0.724832 | 59 | 43.7 | 10 |
starcoderdata
|
//from leetcode easy: https://leetcode.com/problems/maximum-number-of-balloons/
var maxNumberOfBalloons = function(s) {
//set balloon object to count letters
let balloon = {
'b': 0,
'a': 0,
'l': 0,
'o': 0,
'n': 0
};
//loop s counting the letters using the balloon object
for (let i = 0; i < s.length; i++) {
if (balloon[s[i]] != undefined) {
if (s[i] === 'l' || s[i] === 'o') {
balloon[s[i]] += .5;
} else {
balloon[s[i]] += 1;
}
}
}
if (Object.values(balloon).every(b => b >= 1)) {
let min = Math.min(...Object.values(balloon));
return Math.floor(min);
} else {
return 0
}
};
//edge cases: len(t) < 7,
//?'s: limits on time, space
//PSEUDO:
//set balloon = {
// 'b': 0,
// 'a': 0,
// 'l': 0,//2 times
// 'o': 0,//2 times
// 'n': 0
// }
//loop s incrementing balloon[s[i]] if balloon[s[i]]!= undefined
//if s[i] === 'l' || s[i] === 'o'
//increment by .5
//if Object.values(balloon).every(b => b >= 1):
//let min = Math.min(...Object.values(balloon))
//return math.floor(min)
//else:
//return 0
|
javascript
| 11 | 0.483764 | 79 | 21.240741 | 54 |
starcoderdata
|
@Test
public void testWithoutNameTypeAndInvalidData() {
try (NameSampleDataStream sampleStream = new NameSampleDataStream(
ObjectStreamUtils.createObjectStream("<START> <START> Name <END>"))) {
sampleStream.read();
fail();
} catch (IOException expected) {
// the read above is expected to throw an exception
}
try (NameSampleDataStream sampleStream = new NameSampleDataStream(
ObjectStreamUtils.createObjectStream("<START> Name <END> <END>"))) {
sampleStream.read();
fail();
} catch (IOException expected) {
// the read above is expected to throw an exception
}
try (NameSampleDataStream sampleStream = new NameSampleDataStream(
ObjectStreamUtils.createObjectStream(
"<START> <START> Person <END> Street <END>"))) {
sampleStream.read();
fail();
} catch (IOException expected) {
// the read above is expected to throw an exception
}
}
|
java
| 11 | 0.660455 | 78 | 33.535714 | 28 |
inline
|
using DeploymentCockpit.ApiDtos;
using DeploymentCockpit.Common;
using DeploymentCockpit.Interfaces;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Insula.Common;
namespace DeploymentCockpit.Data.Repositories
{
public class DashboardRepository : IDashboardRepository
{
protected readonly DeploymentCockpitEntities _db;
public DashboardRepository(DeploymentCockpitEntities db)
{
if (db == null)
throw new ArgumentNullException("db");
_db = db;
}
public IEnumerable GetProjectVersionInfo()
{
var statusKey = DeploymentStatus.Finished.GetName();
return _db.ProjectEnvironments
.Select(e =>
new
{
ProjectName = e.Project.Name,
EnvironmentName = e.Name,
DeploymentJob = e.DeploymentJobs
.Where(j => j.StatusKey == statusKey)
.OrderByDescending(j => j.DeploymentJobID)
.FirstOrDefault()
})
.ToList()
.Select(i =>
new ProjectVersionInfo
{
ProjectName = i.ProjectName,
EnvironmentName = i.EnvironmentName,
DeploymentJobID = i.DeploymentJob != null
? i.DeploymentJob.DeploymentJobID as int?
: null,
DeploymentJobTime = i.DeploymentJob != null
? i.DeploymentJob.SubmissionTime.ToString(DomainContext.DateTimeFormatString)
: null,
ProductVersion = i.DeploymentJob != null
? i.DeploymentJob.ProductVersion
: null,
})
.ToList();
}
}
}
|
c#
| 29 | 0.504766 | 105 | 34.559322 | 59 |
starcoderdata
|
public void append(byte[] data) throws NoSuchAlgorithmException{
if(count == 0){
Leaf leaf = new Leaf(data);
root = leaf;
leaves.add(leaf);
count++;
} else if(Integer.bitCount(count) == 1){
// add to right subtree, if number of leaves is power of 2
Leaf leaf = new Leaf(data);
List<Leaf> list = new ArrayList<>();
list.add(leaf);
MerkleTree tree = new MerkleTree(list).build();
root = new Node(root, tree.root, hash(root.hash, tree.root.hash));
leaves.add(leaf);
nodes_count++;
count++;
} else {
// nearest power of 2
int nearest = Integer.highestOneBit(count);
List<Leaf> remain = new ArrayList<>(count - nearest);
for (int i = nearest; i < count; i++) {
remain.add(leaves.get(i));
}
Leaf leaf = new Leaf(data);
remain.add(leaf);
MerkleTree tree = new MerkleTree(remain).build();
root = new Node(root.left, tree.root, hash(root.left.hash, tree.root.hash));
leaves.add(leaf);
nodes_count++;
count++;
}
}
|
java
| 14 | 0.494479 | 88 | 37.454545 | 33 |
inline
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
__doc__ = """
Test yaml parser
----------------
Test suite for yaml_parser.
"""
from os.path import join
from unittest import TestCase, mock
import yaml
from dataf import YamlParser
from dataf.yaml_parser import YamlConstructor
class TestYamlConstructor(TestCase):
"""
Test for YamlConstructor classe.
"""
@property
def _node(self):
"""
Create a yaml node object.
"""
node = yaml.SequenceNode(
tag='tag:yaml.org,2002:seq',
value=[
yaml.ScalarNode(tag='tag:yaml.org,2002:str', value='a'),
yaml.ScalarNode(tag='tag:yaml.org,2002:str', value='b'),
yaml.ScalarNode(tag='tag:yaml.org,2002:str', value='c'),
]
)
return node
@property
def _loader(self):
"""
Create a yaml loader object.
"""
return yaml.Loader('test')
def test_simple_join(self):
"""
Test simple_join method.
"""
result = YamlConstructor.simple_join(self._loader, self._node)
self.assertEqual(result, 'abc')
def test_string_join(self):
"""
Test string_join method.
"""
result = YamlConstructor.string_join(self._loader, self._node)
self.assertEqual(result, 'bac')
def test_yaml_getter(self):
"""
Test yaml_getter method.
"""
data = {'a': 'OK', 'b': 'KO'}
result = YamlConstructor.yaml_getter(self._loader, self._node, data=data)
self.assertEqual(result, 'OK')
class TestYamlParser(TestCase):
"""
Test for YamlParser classe.
"""
@classmethod
def setUpClass(cls):
cls.yaml_parser = YamlParser(True)
def test_init_attr_default(self):
"""
Test __init__ method with default arguments.
"""
self.assertEqual('prod', self.yaml_parser.prod_block)
self.assertEqual('dev', self.yaml_parser.dev_block)
self.assertEqual(True, self.yaml_parser.debug)
self.assertEqual(
YamlParser.custom_constructors, self.yaml_parser.custom_constructors
)
def test_init_attr_custom(self):
"""
Test __init__ method with custom arguments.
"""
custom_constructors = {'!test': YamlConstructor.simple_join}
yaml_parser = YamlParser(
True, prod_block='test_prod', dev_block='test_dev',
custom_constructors=custom_constructors
)
self.assertEqual('test_prod', yaml_parser.prod_block)
self.assertEqual('test_dev', yaml_parser.dev_block)
self.assertEqual(True, yaml_parser.debug)
custom_constructors.update(YamlParser.custom_constructors)
self.assertEqual(
custom_constructors,
yaml_parser.custom_constructors
)
@mock.patch('dataf.YamlParser.add_custom_constructors')
def test_init_add_custom_constructors(self, mock):
"""
Test __init__ method call YamlParser.add_custom_constructors.
"""
yaml_parser = YamlParser(True)
mock.assert_called_with(yaml_parser.custom_constructors)
@mock.patch('dataf.yaml_parser.yaml.add_constructor')
def test_add_custom_constructors(self, mock):
"""
Test add_custom_constructors method return value and call yaml.add_constructor.
"""
custom_constructors = {'!test': YamlConstructor.simple_join}
ret = self.yaml_parser.add_custom_constructors(custom_constructors)
mock.assert_called_with('!test', custom_constructors['!test'])
self.assertEqual(self.yaml_parser, ret)
@mock.patch('dataf.yaml_parser.partial')
@mock.patch('dataf.yaml_parser.yaml.add_constructor')
def test_add_getter_constructor(self, mock, mock_partial):
"""
Test add_getter_constructor method.
"""
name = '!test'
data = {}
ret = self.yaml_parser.add_getter_constructor(name, data)
mock.assert_called_with(name, mock_partial())
self.assertEqual(self.yaml_parser, ret)
def test_update_with_dict(self):
"""
Test _update method with a dict.
"""
source = {
'test': 'KO',
'test2': {'nested': 'KO'},
'test3': {'nested1': {'nested2': 'KO'}},
'test4': {'nested1': {'nested2': 'KO'}}
}
update_dict = {
'test': 'OK',
'test2': {'nested': 'OK'},
'test3': {'nested1': {'nested2': 'OK'}}
}
expected = {
'test': 'OK',
'test2': {'nested': 'OK'},
'test3': {'nested1': {'nested2': 'OK'}},
'test4': {'nested1': {'nested2': 'KO'}}
}
ret = self.yaml_parser._update(source, update_dict)
self.assertEqual(ret, expected)
def test_update_without_dict(self):
"""
Test _update method without dict.
"""
source = {'test': 'test'}
update_dict = ['test']
ret = self.yaml_parser._update(source, update_dict)
self.assertEqual(ret, update_dict)
@mock.patch('builtins.open', new_callable=mock.mock_open, read_data="{'prod': {'data': 'OK'}}")
def test_parse_without_dev_section(self, mock_open):
"""
Test parse method without dev section in yaml loaded.
"""
yaml_var = {}
yaml_to_dict = {'config.yml': yaml_var}
yaml_dir_path = '/path/to/yaml'
ret = self.yaml_parser.parse(yaml_to_dict, yaml_dir_path)
mock_open.assert_called_with(join(yaml_dir_path, 'config.yml'), 'r')
self.assertEqual(yaml_var, {'data': 'OK'})
self.assertEqual(ret, self.yaml_parser)
@mock.patch(
'builtins.open', new_callable=mock.mock_open,
read_data="{'prod': {'data': 'KO'}, 'dev': {'data': 'OK'}}"
)
def test_parse_with_dev_section(self, mock_open):
"""
Test parse method with dev section in yaml loaded.
"""
yaml_var = {}
yaml_to_dict = {'config.yml': yaml_var}
yaml_dir_path = '/path/to/yaml'
ret = self.yaml_parser.parse(yaml_to_dict, yaml_dir_path)
mock_open.assert_called_with(join(yaml_dir_path, 'config.yml'), 'r')
self.assertEqual(yaml_var, {'data': 'OK'})
self.assertEqual(ret, self.yaml_parser)
|
python
| 16 | 0.572976 | 99 | 31.467337 | 199 |
starcoderdata
|
/*=========================================================================
Program: Visualization Toolkit
Module: TestSimpleFontRendering.cxx
Copyright (c)
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
#include "vtkRenderer.h"
#include "vtkRenderWindow.h"
#include "vtkRenderWindowInteractor.h"
#include "vtkContext2D.h"
#include "vtkContextItem.h"
#include "vtkContextView.h"
#include "vtkContextScene.h"
#include "vtkFreeTypeTools.h"
#include "vtkTextProperty.h"
#include "vtkObjectFactory.h"
#include "vtkOpenGLContextDevice2D.h"
#include "vtkNew.h"
#include "vtkRegressionTestImage.h"
//----------------------------------------------------------------------------
class SystemFontRenderTest : public vtkContextItem
{
public:
static SystemFontRenderTest *New();
vtkTypeMacro(SystemFontRenderTest, vtkContextItem);
// Paint event for the chart, called whenever the chart needs to be drawn
bool Paint(vtkContext2D *painter) override;
};
//----------------------------------------------------------------------------
int TestSystemFontRendering( int, char * [] )
{
// Set up a 2D context view, context test object and add it to the scene
vtkNew view;
view->GetRenderer()->SetBackground(1.0, 1.0, 1.0);
view->GetRenderWindow()->SetSize(580, 360);
vtkNew test;
view->GetScene()->AddItem(test);
// Force the use of the freetype based rendering strategy
vtkOpenGLContextDevice2D::SafeDownCast(view->GetContext()->GetDevice())
->SetStringRendererToFreeType();
// Use the FontConfig font lookup
vtkFreeTypeTools::GetInstance()->ForceCompiledFontsOff();
view->GetRenderWindow()->SetMultiSamples(0);
view->GetInteractor()->Initialize();
view->GetInteractor()->Start();
return EXIT_SUCCESS;
}
// Make our new derived class to draw a diagram
vtkStandardNewMacro(SystemFontRenderTest);
bool SystemFontRenderTest::Paint(vtkContext2D *painter)
{
painter->GetTextProp()->SetColor(0.0, 0.0, 0.0);
painter->GetTextProp()->SetFontSize(24);
int y = 360;
painter->GetTextProp()->SetFontFamilyToArial();
const char *testString =
"ABCDEFGHIJKLMNOPQRSTUVWXYZ\xce\xb1\xce\xb2\xce\xb3\xce\xb4";
y -= 30;
painter->GetTextProp()->SetBold(false);
painter->GetTextProp()->SetItalic(false);
painter->DrawString(5, y, testString);
y -= 30;
painter->GetTextProp()->SetBold(false);
painter->GetTextProp()->SetItalic(true);
painter->DrawString(5, y, testString);
y -= 30;
painter->GetTextProp()->SetBold(true);
painter->GetTextProp()->SetItalic(false);
painter->DrawString(5, y, testString);
y -= 30;
painter->GetTextProp()->SetBold(true);
painter->GetTextProp()->SetItalic(true);
painter->DrawString(5, y, testString);
painter->GetTextProp()->SetFontFamilyToTimes();
y -= 30;
painter->GetTextProp()->SetBold(false);
painter->GetTextProp()->SetItalic(false);
painter->DrawString(5, y, testString);
y -= 30;
painter->GetTextProp()->SetBold(false);
painter->GetTextProp()->SetItalic(true);
painter->DrawString(5, y, testString);
y -= 30;
painter->GetTextProp()->SetBold(true);
painter->GetTextProp()->SetItalic(false);
painter->DrawString(5, y, testString);
y -= 30;
painter->GetTextProp()->SetBold(true);
painter->GetTextProp()->SetItalic(true);
painter->DrawString(5, y, testString);
painter->GetTextProp()->SetFontFamilyToCourier();
y -= 30;
painter->GetTextProp()->SetBold(false);
painter->GetTextProp()->SetItalic(false);
painter->DrawString(5, y, testString);
y -= 30;
painter->GetTextProp()->SetBold(false);
painter->GetTextProp()->SetItalic(true);
painter->DrawString(5, y, testString);
y -= 30;
painter->GetTextProp()->SetBold(true);
painter->GetTextProp()->SetItalic(false);
painter->DrawString(5, y, testString);
y -= 30;
painter->GetTextProp()->SetBold(true);
painter->GetTextProp()->SetItalic(true);
painter->DrawString(5, y, testString);
return true;
}
|
c++
| 12 | 0.666359 | 78 | 29.286713 | 143 |
starcoderdata
|
<?php
namespace Bstage\App;
class Module {
protected $name;
protected $dir;
protected $version;
protected $requires = [];
protected $app;
public function __construct(array $opts=[]) {
//loop through opts
foreach($opts as $k => $v) {
if(property_exists($this, $k)) {
$this->$k = $v;
}
}
//set module name?
if(!$this->name) {
$this->name = strtolower(explode('\\', get_class($this))[0]);
}
//load config
$this->config();
//check for update?
if($to = $this->version) {
//get stored version
$from = $this->app->config->get("modules.$this->name.version", 0);
//update now?
if($to > $from) {
//update module
$this->update($from, $to);
//update version
$this->app->config->set("modules.$this->name.version", $to);
}
}
//load templates
$this->templates();
//init hook
$this->init();
//load additional modules
foreach($this->requires as $module => $opts) {
$this->app->module($module, $opts);
}
}
public function isAppModule() {
return $this->name === $this->app->meta('name');
}
protected function config() {
$this->app->config->mergePath($this->dir . '/config');
}
protected function update($from, $to) {
$this->app->db->createSchema($this->dir . '/database/schema.sql');
}
protected function templates() {
$this->app->templates->addPath($this->dir . '/templates');
}
protected function init() {
}
}
|
php
| 20 | 0.599858 | 69 | 19.478261 | 69 |
starcoderdata
|
#!/usr/bin/python3
"""
Implement Dijkstra's shortest path algorithm using 'dijkstraData.txt' graph.
Source Vertex = 1.
Report shortest path distance to the following vertices in the same order:
7,37,59,82,99,115,133,165,188,197
Problem answer: [2599, 2610, 2947, 2052, 2367, 2399, 2029, 2442, 2505, 3068]
"""
|
python
| 6 | 0.747396 | 76 | 28.538462 | 13 |
starcoderdata
|
namespace Entities {
enum UserPrivileges
{
/// <summary>
/// Guest user, usually the lowest level in the permission scale
/// </summary>
USERPRIVILEGES_GUEST = 0,
/// <summary>
/// The standard user is usally registered in system and uses a unique name and password to login
/// </summary>
USERPRIVILEGES_STANDARD = 1,
/// <summary>
/// The moderator has powers to send ModeratorMessages, kicking users and banning them
/// </summary>
USERPRIVILEGES_MODERATOR = 2,
/// <summary>
/// The administrator has powers to send AdminMessages, kicking users and banning them
/// </summary>
USERPRIVILEGES_ADMINISTRATOR = 3
};
}
|
c
| 6 | 0.675112 | 99 | 24.846154 | 26 |
inline
|
package com.atjl.common.api.resp;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import java.util.List;
/**
* 分页结果对象
*/
@ApiModel("分页结果对象,页码整型")
public class PageIntResp {
@ApiModelProperty(value = "总页数")
private Integer totalSize;
@ApiModelProperty(value = "分页后的实体列表")
private List objects;
public PageIntResp() {
this.totalSize = 0;
}
public PageIntResp(Integer totalSize, List objects) {
this.totalSize = totalSize;
this.objects = objects;
}
public Integer getTotalSize() {
return totalSize;
}
public void setTotalSize(Integer totalSize) {
this.totalSize = totalSize;
}
public List getObjects() {
return objects;
}
public void setObjects(List objects) {
this.objects = objects;
}
}
|
java
| 7 | 0.62302 | 60 | 19.545455 | 44 |
starcoderdata
|
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Loan extends Model
{
use HasFactory;
protected static function boot()
{
parent::boot();
static::creating(function (self $loan) {
$loan->due_amount = $loan->loan_amount;
});
}
public function account(): \Illuminate\Database\Eloquent\Relations\BelongsTo
{
return $this->belongsTo(Account::class);
}
public function borrower(): \Illuminate\Database\Eloquent\Relations\BelongsTo
{
return $this->belongsTo(Borrower::class);
}
public function installments(): \Illuminate\Database\Eloquent\Relations\HasMany
{
return $this->hasMany(Installment::class);
}
public function scopeActive(Builder $builder): Builder
{
return $builder->where("status", "=", 'active');
}
}
|
php
| 15 | 0.670498 | 83 | 24.463415 | 41 |
starcoderdata
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
""" Ball detector - Deeplearning Session 1 Exercice 1
.. moduleauthor::
.. See https://perso.liris.cnrs.fr/christian.wolf/teaching/deeplearning/tp.html and https://github.com/PaulEmmanuelSotir/BallDetectionAndForecasting
"""
import argparse
import torch
import torch.nn as nn
import torch.backends.cudnn as cudnn
import balldetect.torch_utils as torch_utils
import balldetect.ball_detector as ball_detector
import balldetect.seq_prediction as seq_prediction
__author__ = '
# Torch CuDNN configuration
torch.backends.cudnn.deterministic = True
cudnn.benchmark = torch.cuda.is_available() # Enable builtin CuDNN auto-tuner, TODO: benchmarking isn't deterministic, disable this if this is an issue
cudnn.fastest = torch.cuda.is_available() # Disable this if memory issues
DETECTOR_HP = {
'batch_size': 16,
'bce_loss_scale': 0.1,
'early_stopping': 30,
'epochs': 400,
'optimizer_params': {'amsgrad': False, 'betas': (0.9, 0.999), 'eps': 1e-08, 'lr': 6.537177808319479e-4, 'weight_decay': 6.841231983628692e-06},
'scheduler_params': {'gamma': 0.3, 'step_size': 40},
'architecture': {
'act_fn': nn.ReLU,
'batch_norm': {'affine': True, 'eps': 1e-05, 'momentum': 0.07359778246238029},
'dropout_prob': 0.0,
'layers_param': (('conv2d', {'kernel_size': (3, 3), 'out_channels': 4, 'padding': 0}),
('conv2d', {'kernel_size': (3, 3), 'out_channels': 4, 'padding': 0}),
('conv2d', {'kernel_size': (3, 3), 'out_channels': 4, 'padding': 0}),
('avg_pooling', {'kernel_size': (2, 2), 'stride': (2, 2)}),
('conv2d', {'kernel_size': (5, 5), 'out_channels': 16, 'padding': 0}),
('conv2d', {'kernel_size': (5, 5), 'out_channels': 16, 'padding': 0}),
('avg_pooling', {'kernel_size': (2, 2), 'stride': (2, 2)}),
('conv2d', {'kernel_size': (5, 5), 'out_channels': 32, 'padding': 2}),
('conv2d', {'kernel_size': (7, 7), 'out_channels': 32, 'padding': 3}),
('avg_pooling', {'kernel_size': (2, 2), 'stride': (2, 2)}),
('conv2d', {'kernel_size': (5, 5), 'out_channels': 64, 'padding': 2}),
('flatten', {}),
('fully_connected', {}))
}
}
SEQ_PRED_HP = {
'batch_size': 16,
'early_stopping': 30,
'epochs': 400,
'optimizer_params': {'amsgrad': False, 'betas': (0.9, 0.999), 'eps': 1e-08, 'lr': 9.891933484569264e-05, 'weight_decay': 2.0217734556558288e-4},
'scheduler_params': {'gamma': 0.3, 'step_size': 30},
'architecture': {
'act_fn': nn.Tanh,
'dropout_prob': 0.44996724122672166,
'fc_params': ({'out_features': 512}, {'out_features': 256}, {'out_features': 128}, {'out_features': 128})
}
}
def main():
# Parse arguments
_DETECT, _FORECAST = 'detect', 'forecast'
parser = argparse.ArgumentParser(description='Train ball detector or ball position forecasting model(s).')
parser.add_argument('--model', nargs=1, type=str, required=True, choices=[_DETECT, _FORECAST],
help=f'Determines model to train ("{_DETECT}" or "{_FORECAST}").')
train_model = parser.parse_args().model[0]
torch_utils.set_seeds() # Set seeds for better repducibility
if train_model == _DETECT:
print('> Initializing and training ball detection model (mini_balls dataset)...')
ball_detector.train(**DETECTOR_HP)
# TODO: save model: ball_detector.save_experiment(Path(r'../models/task1_experiments/train_0001/'), model, hp)
elif train_model == _FORECAST:
print('> Initializing and training ball position forecasting model (mini_balls dataset)...')
seq_prediction.train(**SEQ_PRED_HP)
# TODO: save model
if __name__ == "__main__":
main()
|
python
| 12 | 0.580265 | 152 | 44.375 | 88 |
starcoderdata
|
[Fact]
public void Create_ReturnsBadRequest_GivenNullModel()
{
// Arrange & Act
var mockRepo = new Mock<ITodosRepository>();
var controller = new TodoController(mockRepo.Object, GetMapper());
controller.ModelState.AddModelError("error", "some error");
// Act
var result = controller.CreateTodo(todoModel: null);
// Assert
Assert.IsType<BadRequestObjectResult>(result.Result);
}
|
c#
| 13 | 0.58517 | 78 | 34.714286 | 14 |
inline
|
package protocol
import (
"crypto/rand"
"encoding/binary"
"io"
"github.com/codahale/veil/pkg/veil/internal"
"github.com/gtank/ristretto255"
"github.com/sammyne/strobe"
)
type Protocol struct {
s *strobe.Strobe
}
func New(name string) *Protocol {
s, err := strobe.New(name, strobe.Bit256)
if err != nil {
panic(err)
}
return &Protocol{s: s}
}
func (p *Protocol) MetaAD(data []byte) {
if err := p.s.AD(data, metaOpts); err != nil {
panic(err)
}
}
func (p *Protocol) AD(data []byte) {
if err := p.s.AD(data, defaultOpts); err != nil {
panic(err)
}
}
func (p *Protocol) KEY(key []byte) {
k := make([]byte, len(key))
copy(k, key)
if err := p.s.KEY(k, false); err != nil {
panic(err)
}
}
func (p *Protocol) KEYRand(n int) error {
k := make([]byte, n)
if _, err := rand.Read(k); err != nil {
return err
}
if err := p.s.KEY(k, false); err != nil {
panic(err)
}
return nil
}
func (p *Protocol) Ratchet() {
// Setting L = sec/8 bytes is sufficient when R ≥ sec/8. That is, set L to 16 bytes or 32 bytes
// for Strobe-128/b and Strobe-256/b, respectively.
if err := p.s.RATCHET(int(strobe.Bit256) / 8); err != nil {
panic(err)
}
}
func (p *Protocol) PRF(dst []byte, n int) []byte {
ret, out := internal.SliceForAppend(dst, n)
if err := p.s.PRF(out, false); err != nil {
panic(err)
}
return ret
}
func (p *Protocol) PRFScalar() *ristretto255.Scalar {
buf := make([]byte, internal.UniformBytestringSize)
return ristretto255.NewScalar().FromUniformBytes(p.PRF(buf[:0], internal.UniformBytestringSize))
}
func (p *Protocol) SendENC(dst, plaintext []byte) []byte {
ret, out := internal.SliceForAppend(dst, len(plaintext))
copy(out, plaintext)
if _, err := p.s.SendENC(out, defaultOpts); err != nil {
panic(err)
}
return ret
}
func (p *Protocol) RecvENC(dst, ciphertext []byte) []byte {
ret, out := internal.SliceForAppend(dst, len(ciphertext))
copy(out, ciphertext)
if _, err := p.s.RecvENC(out, defaultOpts); err != nil {
panic(err)
}
return ret
}
func (p *Protocol) SendMAC(dst []byte) []byte {
ret, out := internal.SliceForAppend(dst, internal.MACSize)
if err := p.s.SendMAC(out, defaultOpts); err != nil {
panic(err)
}
return ret
}
func (p *Protocol) RecvMAC(mac []byte) error {
m := make([]byte, len(mac))
copy(m, mac)
return p.s.RecvMAC(m, defaultOpts)
}
func (p *Protocol) SendCLR(data []byte) {
if err := p.s.SendCLR(data, defaultOpts); err != nil {
panic(err)
}
}
func (p *Protocol) RecvCLR(data []byte) {
if err := p.s.RecvCLR(data, defaultOpts); err != nil {
panic(err)
}
}
func (p *Protocol) SendENCStream(dst io.Writer) io.Writer {
p.SendENC(nil, nil)
// Return a writer.
return &callbackWriter{
callback: func(dst, b []byte) []byte {
return p.moreSendENC(dst, b)
},
dst: dst,
}
}
func (p *Protocol) RecvENCStream(dst io.Writer) io.Writer {
p.RecvENC(nil, nil)
// Return a writer.
return &callbackWriter{
callback: func(dst, b []byte) []byte {
return p.moreRecvENC(dst, b)
},
dst: dst,
}
}
func (p *Protocol) RecvCLRStream(dst io.Writer) io.Writer {
p.RecvCLR(nil)
return &callbackWriter{
callback: func(_, b []byte) []byte {
p.moreRecvCLR(b)
return b
},
dst: dst,
}
}
func (p *Protocol) SendCLRStream(dst io.Writer) io.Writer {
p.SendCLR(nil)
return &callbackWriter{
callback: func(_, b []byte) []byte {
p.moreSendCLR(b)
return b
},
dst: dst,
}
}
func (p *Protocol) Clone() *Protocol {
return &Protocol{s: p.s.Clone()}
}
func (p *Protocol) moreSendENC(dst, plaintext []byte) []byte {
ret, out := internal.SliceForAppend(dst, len(plaintext))
copy(out, plaintext)
if _, err := p.s.SendENC(out, streamingOpts); err != nil {
panic(err)
}
return ret
}
func (p *Protocol) moreRecvENC(dst, ciphertext []byte) []byte {
ret, out := internal.SliceForAppend(dst, len(ciphertext))
copy(out, ciphertext)
if _, err := p.s.RecvENC(out, streamingOpts); err != nil {
panic(err)
}
return ret
}
func (p *Protocol) moreSendCLR(data []byte) {
if err := p.s.SendCLR(data, streamingOpts); err != nil {
panic(err)
}
}
func (p *Protocol) moreRecvCLR(data []byte) {
if err := p.s.RecvCLR(data, streamingOpts); err != nil {
panic(err)
}
}
// LittleEndianU32 returns n as a 32-bit little endian bit string.
func LittleEndianU32(n int) []byte {
b := make([]byte, 4)
binary.LittleEndian.PutUint32(b, uint32(n))
return b
}
type callbackWriter struct {
buf []byte
callback func([]byte, []byte) []byte
dst io.Writer
}
func (w *callbackWriter) Write(p []byte) (n int, err error) {
w.buf = w.callback(w.buf[:0], p)
return w.dst.Write(w.buf)
}
//nolint:gochecknoglobals // constants
var (
defaultOpts = &strobe.Options{}
metaOpts = &strobe.Options{Meta: true}
streamingOpts = &strobe.Options{Streaming: true}
)
|
go
| 16 | 0.642175 | 97 | 18.427419 | 248 |
starcoderdata
|
<?php
/**
* Created by PhpStorm.
* User: xiaozhuai
* Date: 16/12/19
* Time: 下午7:09
*/
class TestController extends EZController
{
public function index(){
$this->getView()->route = "manager/test.index";
$this->getView()->render();
}
public function test(){
$this->getView()->route = "manager/test.test";
$this->getView()->render();
}
private function test2(){
echo "manager/test.test2";
}
}
|
php
| 10 | 0.583673 | 55 | 17.884615 | 26 |
starcoderdata
|
module.exports = {
name:"확률",
description: "자신의 확률을 확인 합니다!",
execute(message,args){
const playerDice1 = Math.floor(Math.random() * 100 + 1)
if(args[0] == "여친"){
message.channel.send(`${message.author.username}님이 여친이 생길확률은 ${playerDice1}% 입니다.`)
}
if(args[0] == "오늘의운세"){
message.channel.send(`${message.author.username}님이 운세가 좋을 확률은 ${playerDice1}% 입니다.`)
}
if(args[0] == "새해운세"){
message.channel.send(`${message.author.username}님의 2022년 운세가 좋을 확률은 ${playerDice1}% 입니다.`)
}
if(args[0] == "결혼나이"){
message.channel.send(`${message.author.username}님의 예상 결혼나이는 ${playerDice1}살 입니다.`)
}
}
}
|
javascript
| 15 | 0.555091 | 98 | 35.736842 | 19 |
starcoderdata
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.