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
package com.macro.mall.dao; import java.util.List; import org.apache.ibatis.annotations.Param; import com.macro.mall.dto.Banner; import com.macro.mall.dto.GoodDetail; import com.macro.mall.dto.GoodMeasurement; import com.macro.mall.dto.GoodParam; import com.macro.mall.dto.Goods; public interface GoodsDao { int insertList(@Param("goods") Goods goods); List list(Integer pageSize, Integer pageNum); void delete(@Param("id")String id); int insertGoodDetail(@Param("param")GoodDetail goodDetail); int insertGoodParam(@Param("param")GoodParam goodParam); int insertGoodMeasurement(@Param("param")GoodMeasurement goodMeasurement); }
java
8
0.782107
75
23.75
28
starcoderdata
/** * Module dependencies. */ const utils = require('@helpers/utils'); const users = require('../controllers/users.server.controller'); const updateProfileSchema = require('../schemas/update_profile.server.schema.json'); module.exports = { prefix: '/me', routes: [ { path: '/', methods: { /** * @params * [{ * "key": "$expand", * "value": "iams", * "description": "You can use this parameter to expand related attributes" * }, { * "key": "$select", * "value": "name.first,email,iams", * "description": "Use this parameter to select specific attributes" * }, { * "key": "$sess", * "value": "true", * "description": "Set to true to get the session info" * }] */ get: { parents: [ 'vendor:users', 'vendor:users:user', 'vendor:users:user:profile', 'vendor:users:public', ], middlewares: [users.me], iam: 'vendor:users:user:profile:get', title: 'Get current user details', description: 'API to fetch the current user details', }, /** * @body * { * "name": { * "first": "{{$randomFirstName}}", * "last": "{{$randomLastName}}" * }, * "isMale": true, * "data": { * * } * } * * @params * [{ * "key": "$merge", * "value": "true", * "description": "Merge the existing user data with the sent one" * }] */ post: { parents: ['vendor:users', 'vendor:users:user', 'vendor:users:auth:profile'], middlewares: [utils.validate(updateProfileSchema), users.update], iam: 'vendor:users:user:profile:edit', title: 'Update profile', description: 'Update current user details', }, }, }, { path: '/accounts', methods: { delete: { parents: ['vendor:users', 'vendor:users:user'], middlewares: [users.removeOAuthProvider], iam: 'vendor:users:user:oauth:remove', title: 'Remove a social network account', description: 'API to remove an linked social network account', }, }, }, { path: '/picture', methods: { get: { parents: ['vendor:users', 'vendor:users:user', 'vendor:users:user:profile'], middlewares: [users.getProfilePicture], iam: 'vendor:users:auth:profile:picture:get', title: 'Get current user profile picture', description: 'API to fetch the image of the current user', }, }, }, ], };
javascript
15
0.480634
86
27.979592
98
starcoderdata
<?php namespace Cloudy\Bundle\CrudBundle\Entity; use Doctrine\ORM\Mapping as ORM; /** *@ORM\Entity *@ORM\Table(name="plants") *@ORM\HasLifecycleCallbacks */ class Plant { /** *@ORM\Id *@ORM\Column(type="integer") * @ORM\GeneratedValue(strategy="AUTO") */ protected $id; /** *@ORM\Column(name="location", type="string") */ protected $location; /** *@ORM\Column(name="flat_surface", type="integer") */ protected $flatSurface; /** *@ORM\Column(name="residents_count", type="integer") */ protected $residentsCount; /** *@ORM\Column(type="datetime", name="posted_at") */ protected $postedAt; /** *@ORM\Column(type="datetime", name="udpated_at") */ protected $updatedAt; protected $user; /** *@ORM\Column(name="if_gas_stove", type="boolean") */ protected $ifGasStove; /** *@ORM\Column(name="electronics_amount", type="integer") */ protected $electronicsAmount; /** *@ORM\Column(name="if_garage", type="boolean") */ protected $ifGarage; public function __construct() { $this->setPostedAt(new \DateTime()); $this->setUpdatedAt(new \DateTime()); } /** * Get id * * @return integer */ public function getId() { return $this->id; } /** * Set location * * @param string $location * * @return Plant */ public function setLocation($location) { $this->location = $location; return $this; } /** * Get location * * @return string */ public function getLocation() { return $this->location; } /** * Set flatSurface * * @param integer $flatSurface * * @return Plant */ public function setFlatSurface($flatSurface) { $this->flatSurface = $flatSurface; return $this; } /** * Get flatSurface * * @return integer */ public function getFlatSurface() { return $this->flatSurface; } /** * Set residentsCount * * @param integer $residentsCount * * @return Plant */ public function setResidentsCount($residentsCount) { $this->residentsCount = $residentsCount; return $this; } /** * Get residentsCount * * @return integer */ public function getResidentsCount() { return $this->residentsCount; } /** * Set postedAt * * @param \DateTime $postedAt * * @return Plant */ public function setPostedAt($postedAt) { $this->postedAt = $postedAt; return $this; } /** * Get postedAt * * @return \DateTime */ public function getPostedAt() { return $this->postedAt; } /** * Set ifGasStove * * @param boolean $ifGasStove * * @return Plant */ public function setIfGasStove($ifGasStove) { $this->ifGasStove = $ifGasStove; return $this; } /** * Get ifGasStove * * @return boolean */ public function getIfGasStove() { return $this->ifGasStove; } /** * Set electronicsAmount * * @param integer $electronicsAmount * * @return Plant */ public function setElectronicsAmount($electronicsAmount) { $this->electronicsAmount = $electronicsAmount; return $this; } /** * Get electronicsAmount * * @return integer */ public function getElectronicsAmount() { return $this->electronicsAmount; } /** * Set ifGarage * * @param boolean $ifGarage * * @return Plant */ public function setIfGarage($ifGarage) { $this->ifGarage = $ifGarage; return $this; } /** * Get ifGarage * * @return boolean */ public function getIfGarage() { return $this->ifGarage; } /** * Set updatedAt * * @param \DateTime $updatedAt * * @return Plant */ public function setUpdatedAt($updatedAt) { $this->updatedAt = $updatedAt; return $this; } /** *@ORM\PreUpdate */ public function setUpdatedValue() { $this->setUpdatedAt(new \DateTime()); } /** * Get updatedAt * * @return \DateTime */ public function getUpdatedAt() { return $this->updatedAt; } }
php
12
0.522456
60
16.197761
268
starcoderdata
<!DOCTYPE html> <html lang="pt-br"> <meta charset="UTF-8"> PHP - Replicas e Clonagem <?php require('./class/ReplicaClonagem.class.php'); $readA = new ReplicaClonagem("posts","categoria = 'noticia'", 'ODER BY data DESC'); $readA->ler(); $readA->setTermos("categoria = 'internet'"); $readA->ler(); $readB = clone($readA); $readB->setTermos("categoria = 'redes socias'"); $readB->ler(); $readC = clone($readA); $readC->setTabela('comentarios'); $readC->setTermos("post = 25"); $readC->ler(); var_dump($readA,$readB,$readC); ?>
php
7
0.478873
92
25.625
32
starcoderdata
import { handleActions } from 'redux-actions'; import { RESET_HUB_CSR, SET_HUB_CSR_DFSP_ID, SET_HUB_CSR_CERTIFICATE, SET_HUB_CSR_CSR_TYPE, SET_HUB_CSR_COMMON_NAME, SET_HUB_CSR_ORGANIZATION, SET_HUB_CSR_ORGANIZATION_UNIT, SET_HUB_CSR_EMAIL, SET_HUB_CSR_LOCALITY, SET_HUB_CSR_COUNTRY, SET_HUB_CSR_STATE, CHANGE_HUB_CSR_DNS, ADD_HUB_CSR_DNS, REMOVE_HUB_CSR_DNS, CHANGE_HUB_CSR_IP, ADD_HUB_CSR_IP, REMOVE_HUB_CSR_IP, SHOW_HUB_CSR_CERTIFICATE_MODAL, HIDE_HUB_CSR_CERTIFICATE_MODAL, } from './actions'; import { CSR_TYPES } from './constants'; const dnsInitialState = undefined; const ipInitialState = undefined; const initialState = { hubCsrDfspId: undefined, hubCsrCertificate: undefined, hubCsrCsrType: CSR_TYPES.FILE, hubCsrCommonName: undefined, hubCsrOrganization: undefined, hubCsrOrganizationUnit: undefined, hubCsrEmail: undefined, hubCsrLocality: undefined, hubCsrCountry: undefined, hubCsrState: undefined, hubCsrDnss: [], hubCsrIps: [], isHubCsrModalVisible: false, }; const HubCsr = handleActions( { [RESET_HUB_CSR]: () => initialState, [SET_HUB_CSR_DFSP_ID]: (state, action) => ({ ...state, hubCsrDfspId: action.payload, }), [SET_HUB_CSR_CERTIFICATE]: (state, action) => ({ // the server sends null for a non-existing certificate // causing the ui to fail on the fileuploader component // so it needs to be stored as an undefined value ...state, hubCsrCertificate: action.payload || null, }), [SET_HUB_CSR_CSR_TYPE]: (state, action) => ({ // reset the certificate when changing the CSR type ...state, hubCsrCsrType: action.payload, hubCsrCertificate: undefined, }), [SET_HUB_CSR_COMMON_NAME]: (state, action) => ({ ...state, hubCsrCommonName: action.payload, }), [SET_HUB_CSR_ORGANIZATION]: (state, action) => ({ ...state, hubCsrOrganization: action.payload, }), [SET_HUB_CSR_ORGANIZATION_UNIT]: (state, action) => ({ ...state, hubCsrOrganizationUnit: action.payload, }), [SET_HUB_CSR_EMAIL]: (state, action) => ({ ...state, hubCsrEmail: action.payload, }), [SET_HUB_CSR_LOCALITY]: (state, action) => ({ ...state, hubCsrLocality: action.payload, }), [SET_HUB_CSR_COUNTRY]: (state, action) => ({ ...state, hubCsrCountry: action.payload, }), [SET_HUB_CSR_STATE]: (state, action) => ({ ...state, hubCsrState: action.payload, }), [CHANGE_HUB_CSR_DNS]: (state, action) => { const { index, value } = action.payload; return { ...state, hubCsrDnss: [...state.hubCsrDnss.slice(0, index), value, ...state.hubCsrDnss.slice(index + 1)], }; }, [ADD_HUB_CSR_DNS]: (state, action) => ({ ...state, hubCsrDnss: [...state.hubCsrDnss, dnsInitialState], }), [REMOVE_HUB_CSR_DNS]: (state, action) => { const index = action.payload; return { ...state, hubCsrDnss: [...state.hubCsrDnss.slice(0, index), ...state.hubCsrDnss.slice(index + 1)], }; }, [CHANGE_HUB_CSR_IP]: (state, action) => { const { index, value } = action.payload; return { ...state, hubCsrIps: [...state.hubCsrIps.slice(0, index), value, ...state.hubCsrIps.slice(index + 1)], }; }, [ADD_HUB_CSR_IP]: (state, action) => ({ ...state, hubCsrIps: [...state.hubCsrIps, ipInitialState], }), [REMOVE_HUB_CSR_IP]: (state, action) => { const index = action.payload; return { ...state, hubCsrIps: [...state.hubCsrIps.slice(0, index), ...state.hubCsrIps.slice(index + 1)], }; }, [SHOW_HUB_CSR_CERTIFICATE_MODAL]: (state, action) => ({ ...state, isHubCsrModalVisible: true, }), [HIDE_HUB_CSR_CERTIFICATE_MODAL]: (state, action) => ({ ...state, isHubCsrModalVisible: false, }), }, initialState ); export default HubCsr; export { initialState };
javascript
17
0.601386
103
27.85
140
starcoderdata
#include "actiontypes.h" QString ActionTypes::value1 = "value1"; int ActionTypes::value2 = 2; qreal ActionTypes::value3 = 3.2999999999999998; bool ActionTypes::value4 = true; bool ActionTypes::value4b = false; QPointF ActionTypes::value5 = QPointF(5,6); QRectF ActionTypes::value6 = QRect(6,7,8,9);
c++
5
0.738562
47
19.4
15
starcoderdata
def socks5(s,host,port,proto=1): # input: # s - socket object # host - destination host either IP or a name # port - destination port # return: # 1 - if ready # 0 - if needs authentication error = ["succeeded", "general SOCKS server failure", "connection not allowed by ruleset", "Network unreachable", "Host unreachable", "Connection refused", "TTL expired", "Command not supported", "Address type not supported", "unassigned"] data = pack('!3B',5,1,0) s.send(data) data = s.recv(2) auth = unpack('2B',data)[1] if proto == 3: # in UDP we are setting our _source_ address at this stage host = "0.0.0.0" port = 0 if auth != 255: nport = pack('!H',port) try: if ":" in host: data = pack('!4B',5,proto,0,4)+socket.inet_pton(socket.AF_INET6,host)+nport else: data = pack('!4B',5,proto,0,1)+socket.inet_pton(socket.AF_INET,host)+nport except socket.error: data = pack('!5B',5,proto,0,3,len(host))+host+nport s.send(data) data = s.recv(256) dhost = "" dport = 0 try: code = unpack('BBBB',data[:4]) if code[3] == 1: dhost = socket.inet_ntop(socket.AF_INET,data[4:8]) dport = (unpack("!H",data[8:10]))[0] elif code[3] == 4: dhost = socket.inet_ntop(socket.AF_INET6,data[4:20]) dport = (unpack("!H",data[20:22]))[0] elif code[3] == 3: dhost = data[4:-2] except: sys.stderr.write("[-] socks server sent a wrong replay\n") return (-1,-1,-1) sys.stderr.write("[?] host:"+str(dhost)+" port:"+str(dport)+"\n") if code[1] == 0: return (code[3],dhost,dport) else: if code[1] > 9: code[1] = 9 sys.stderr.write("[-] socks server sent an error: "+error[code[1]]+"\n") return (-1,-1,-1) else: sys.stderr.write("[-] socks server requires authentication\n") return (-1,-1,-1)
python
18
0.574211
241
30.683333
60
inline
// RUN: %clang_cc1 %s -emit-llvm -o - int bar(); int foo() { int i; i = 1 + 2; while(1) { i = bar(); i = bar(); }; return i; } int foo1() { int i; i = 1 + 2; while(1) { i = bar(); if (i == 42) break; i = bar(); }; return i; } int foo2() { int i; i = 1 + 2; while(1) { i = bar(); if (i == 42) continue; i = bar(); }; return i; } int foo3() { int i; i = 1 + 2; while(1) { i = bar(); if (i == 42) break; }; return i; } int foo4() { int i; i = 1 + 2; while(1) { i = bar(); if (i == 42) continue; }; return i; }
c
9
0.374608
37
9.290323
62
starcoderdata
namespace content_settings { // A ConfigurationPolicyHandler which forces kCookieControlsEnabled to false // when BlockThirdPartyCookies is set by policy. class CookieSettingsPolicyHandler : public policy::ConfigurationPolicyHandler { public: CookieSettingsPolicyHandler(); ~CookieSettingsPolicyHandler() override; // ConfigurationPolicyHandler: bool CheckPolicySettings(const policy::PolicyMap& policies, policy::PolicyErrorMap* errors) override; void ApplyPolicySettings(const policy::PolicyMap& policies, PrefValueMap* prefs) override; private: DISALLOW_COPY_AND_ASSIGN(CookieSettingsPolicyHandler); }; }
c
10
0.751105
79
33
20
inline
@import Foundation; @interface NSString (ZENInflections) + (NSString *)zen_stringWithCamelCase:(NSString *)string; + (NSString *)zen_stringWithClassifiedCase:(NSString *)string; + (NSString *)zen_stringWithDashedCase:(NSString *)string; + (NSString *)zen_stringWithUnderscoreCase:(NSString *)string; + (NSString *)zen_stringWithHumanizeUppercase:(NSString *)string; + (NSString *)zen_stringWithHumanizeLowercase:(NSString *)string; + (NSString *)zen_stringWithSnakeCase:(NSString *)string; - (NSString *)zen_camelCase; - (NSString *)zen_classify; - (NSString *)zen_dashed; - (NSString *)zen_dotNetCase; - (NSString *)zen_javascriptCase; - (NSString *)zen_lispCase; - (NSString *)zen_objcCase; - (NSString *)zen_pythonCase; - (NSString *)zen_rubyCase; - (NSString *)zen_snakeCase; - (NSString *)zen_underscore; - (NSString *)zen_upperCamelCase; - (NSString *)zen_humanizeUppercase; - (NSString *)zen_humanizeLowercase; @end
c
6
0.739505
65
29.966667
30
starcoderdata
using System.Collections; using System.Collections.Generic; using UnityEngine; public class UI_Inventory : MonoBehaviour { [SerializeField] private Inventory inventory; private Transform itemSlotContainer; private Transform itemSlotTemplate; [SerializeField] private GameObject ItemInventoryUI; [SerializeField] private GameObject OpenButton; [SerializeField] private GameObject CloseButton; [Header("UIItemElement")] [SerializeField] private GameObject nullPrefab; public void SetInventory(Inventory inventory) { this.inventory = inventory; } public void Awake() { ItemInventoryUI.SetActive(false); CloseButton.SetActive(false); } public void OpenItemInventory() { OpenButton.SetActive(false); CloseButton.SetActive(true); ItemInventoryUI.SetActive(true); RefreshInventoryItems(); } public void CloseInventory() { GameObject inventoryUI = ItemInventoryUI.gameObject; foreach(Transform child in inventoryUI.transform) { GameObject.Destroy(child.gameObject); } OpenButton.SetActive(true); CloseButton.SetActive(false); ItemInventoryUI.SetActive(false); ItemInventoryUI.transform.parent = transform; } private void RefreshInventoryItems() { foreach (ItemName item in inventory.ItemDict.Keys) { //have all ui prefab under here to instantiate elements switch (item) { default: case ItemName.Null: var prefab = Instantiate(nullPrefab, ItemInventoryUI.transform); break; } } UpdateCanvas(); } private void UpdateCanvas() { Canvas.ForceUpdateCanvases(); } }
c#
18
0.618524
84
23.818182
77
starcoderdata
// pages/goods_detail/goods_detail.js import request from '../../request/index' import regeneratorRuntime from '../../lib/runtime/runtime' Page({ data: { goodsObj: {}, isCollect: false }, goods_id: 0, goodsInfo: {}, // onLoad: function(options) { // this.goods_id = options.goods_id // this.getGoodsDetail(this.goods_id) // }, onShow: function() { // onshow里拿不到参数,到页面栈里拿 let pages = getCurrentPages() let currentPage = pages[pages.length-1] let options = currentPage.options const { goods_id } = options this.getGoodsDetail(goods_id) // 缓存中的商品收藏 let collect = wx.getStorageSync('collect') || [] let isCollect = collect.some(v => v.goods_id == goods_id) this.setData({ isCollect }) }, async getGoodsDetail(goods_id) { const { data: res } = await request({ url: '/goods/detail', data: { goods_id } }).catch(e => e) if (!res) return console.log('商品详情获取出错') if (res.meta.status !== 200) { console.log('商品详情获取失败:' + res.meta.msg) return } console.log(res) const goodsObj = res.message this.goodsInfo = goodsObj this.setData({ // goodsObj: res.message // 优化页面数据大小 goodsObj: { goods_name: goodsObj.goods_name, goods_price: goodsObj.goods_price, goods_introduce: goodsObj.goods_introduce, pics: goodsObj.pics } }) }, handlePrevewImage(e) { const urls = this.GoodsInfo.pics.map(v => v.pics_mid) const current = e.currentTarget.dataset.url wx.previewImage({ current: current, urls: urls }); }, handleCartAdd() { let cart = wx.getStorageSync('cart') || [] let index = cart.findIndex(v => v.goods_id === this.goodsInfo.goods_id) if(index === -1) { let cartItem = { // goods_id: this.goodsInfo.goods_id, ...this.goodsInfo, num: 1, checked: true } cart.push(cartItem) wx.setStorageSync('cart', cart); } else { cart[index].num += 1 wx.setStorageSync('cart', cart) } // console.log(cart) wx.showToast({ title: '加入成功', icon: 'success', mask: true }) }, handleCollect() { let isCollect = this.data.isCollect let collect = wx.getStorageSync('collect') || [] isCollect = !isCollect if (isCollect) { collect.push(this.goodsInfo) wx.showToast({ title: '收藏成功', icon: 'success', mask: true }) } else { collect.some((item, i) => { if (item.goods_id === this.goodsInfo.goods_id) { collect.splice(i, 1) return true } }) wx.showToast({ title: '取消成功', icon: 'success', mask: true }) } wx.setStorageSync('collect', collect) this.setData({ isCollect }) } })
javascript
16
0.569804
75
24.681416
113
starcoderdata
<?php namespace App\Services; interface CartServiceInterface { public function index(); public function addToCart($request,$productId,$itemQty); public function removeProductIntoCart($productId); public function updateProductIntoCart($request, $productId); }
php
7
0.759857
64
20.461538
13
starcoderdata
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package test; import javafx.application.Application; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.scene.Scene; import javafx.scene.control.Label; import javafx.scene.control.TextField; import javafx.scene.layout.GridPane; import javafx.stage.Stage; import np.com.ngopal.control.AutoFillTextBox; /** * * @author WEBNEP */ public class Test extends Application{ ObservableList data = FXCollections.observableArrayList("abc","cde","hij","klm"); @Override public void start(Stage stage) throws Exception { AutoFillTextBox tbox = new AutoFillTextBox(data); tbox.setPrefHeight(50); tbox.setPrefWidth(140); TextField field1 = new TextField(); TextField field2 = new TextField(); TextField field3 = new TextField(); Label l = new Label("Name"); Label l1 = new Label("Address"); Label l2 = new Label("DOB"); Label l3 = new Label("Street"); GridPane gridpane = new GridPane(); gridpane.add(field1,2,1); gridpane.add(tbox, 2, 2); gridpane.add(field2,2,3); gridpane.add(field3,2,4); gridpane.add(l, 1, 1); gridpane.add(l1, 1, 2); gridpane.add(l2, 1, 3); gridpane.add(l3, 1, 4); // VBox box = new VBox(); // box.getChildren().add(tbox); Scene scene = new Scene(gridpane); scene.getStylesheets().add(getClass().getResource("main.css").toExternalForm()); stage.setScene(scene); stage.show(); } public static void main(String[] args) { Application.launch(args); } }
java
12
0.60074
93
26.014286
70
starcoderdata
/* * Changing the name of a parameter gives an error * More rigorous than c, won't compile with this error */ #include #include void foo(int8_t a, char c); void foo(int8_t a, char d) { return; }
c
6
0.684211
54
16.733333
15
starcoderdata
const request = require('supertest'); const server = require('../Api/server'); const db = require('../database/db'); describe('/teams endpoints', () => { beforeAll(async () => { await db('projects').truncate(); }); let token = ' it('Should return 200 for project list', async () => { await request(server) .get('/api/projects') .set('Authorization', token) .expect(200); }); it('Should return 201 success for creating project', async () => { await request(server) .post('/api/projects') .set('Authorization', token) .send({ title: 'Testing Application', description: "It's a to-do list", is_approved: true, front_end_spots: 8, back_end_spots: 2, ios_spots: 2, android_spots: 2, data_science_spots: 1, ux_spots: 1, creator_id: 1, hackathon_id: 2 }) .expect(201); }); it('Should return 200 success for updating a project', async () => { await request(server) .put('/api/projects/1') .set('Authorization', token) .send({ id: 1, title: 'Testing Application - Update' }) .expect(200); }); it('Should return 200 for specific project', async () => { await request(server) .get('/api/projects/1') .set('Authorization', token) .expect(200); }); it('Should return a 200 success for deleting a project', async () => { await request(server) .delete('/api/projects/1') .set('Authorization', token) .expect(200); }); });
javascript
23
0.511008
73
27.295082
61
starcoderdata
import path from "path"; import ora from "ora"; import { copy, remove, move } from "fs-extra"; import { get, set } from "lodash"; import download from "./download-npm-package"; import * as jsonfile from "./lib/jsonfile-then"; async function initExpo(tpl, dest = ".", options = {}, spinner) { try { const pkgFile = path.join(dest, "package.json"); const pkgJson = await jsonfile.readFile(pkgFile); delete pkgJson.version; delete pkgJson.name; await jsonfile.writeFile(pkgFile, pkgJson, { spaces: 2 }); spinner.succeed(`Package.json cooked! ${path.resolve(dest)}`); } catch (err) { spinner.fail("Modifying package.json failed."); throw err; } try { spinner.text = "Modifying app.json ..."; spinner.start(); const appFile = path.join(dest, "app.json"); const appJson = await jsonfile.readFile(appFile); let { appName, appSlug, bundleIdentifier, androidPackage } = options; appJson.expo = appJson.expo || {}; appJson.expo.version = "0.0.0"; appJson.expo.name = appName; appJson.expo.slug = appSlug; appJson.expo.ios = appJson.expo.ios || {}; appJson.expo.ios.bundleIdentifier = bundleIdentifier; appJson.expo.android = appJson.expo.android || {}; appJson.expo.android.package = androidPackage; await jsonfile.writeFile(appFile, appJson, { spaces: 2 }); spinner.succeed(`App.json cooked! ${path.resolve(dest)}`); } catch (err) { spinner.fail("Modifying app.json failed."); throw err; } } export default async function init(tpl, dest = ".", options = {}) { const pkg = `@36node/template-${tpl}`; const spinner = ora(`Downloading template ${pkg}...`); try { spinner.start(); await download(pkg, dest); spinner.succeed("Downloading success."); } catch (err) { spinner.fail("Downloading failed."); throw err; } // generate common template files try { spinner.text = "Generating common template files ..."; spinner.start(); await remove(path.join(dest, "CHANGELOG.md")); await copy(path.join(__dirname, "../template"), dest, { overwrite: false }); await move(path.join(dest, "gitignore"), path.join(dest, ".gitignore"), { overwrite: true, }); spinner.succeed("Generating common template files success!"); } catch (err) { spinner.fail("Generating common template files failed!"); throw err; } if (tpl === "expo") { return initExpo(tpl, dest, options, spinner); } try { spinner.text = "Modifying package.json ..."; spinner.start(); const pkgFile = path.join(dest, "package.json"); const pkgJson = await jsonfile.readFile(pkgFile); let { name, owner, scope } = options; pkgJson.files = ["bin", "dist", "mock", "typings"]; pkgJson.version = "0.0.0"; pkgJson.repository = { url: `${owner}/${name}`, type: "git", }; pkgJson.name = scope ? `@${scope}/${name}` : name; if (pkgJson["config-overrides-path"]) { pkgJson["config-overrides-path"] = "node_modules/@36node/sketch/config-overrides"; } if (get(pkgJson, "scripts.styleguide")) { set( pkgJson, "scripts.styleguide", "styleguidist server --config node_modules/@36node/sketch/styleguide.config.js" ); } if (get(pkgJson, "scripts.styleguide:build")) { set( pkgJson, "scripts.styleguide:build", "styleguidist build --config node_modules/@36node/sketch/styleguide.config.js" ); } await jsonfile.writeFile(pkgFile, pkgJson, { spaces: 2 }); spinner.succeed(`Package.json cooked! ${path.resolve(dest)}`); } catch (err) { spinner.fail("Modifying package.json failed."); throw err; } }
javascript
13
0.630119
87
30.193277
119
starcoderdata
package py.com.volpe.cotizacion.gatherer; import lombok.RequiredArgsConstructor; import lombok.Value; import lombok.extern.log4j.Log4j2; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; import org.springframework.stereotype.Service; import py.com.volpe.cotizacion.AppException; import py.com.volpe.cotizacion.HTTPHelper; import py.com.volpe.cotizacion.domain.Place; import py.com.volpe.cotizacion.domain.PlaceBranch; import py.com.volpe.cotizacion.domain.QueryResponse; import py.com.volpe.cotizacion.domain.QueryResponseDetail; import java.util.*; import java.util.stream.Collectors; /** * @author * @since 4/26/18 */ @Log4j2 @Service @RequiredArgsConstructor public class MyD implements Gatherer { private static final String CODE = "MyD"; private static final List ASU_CODE = Arrays.asList("2", "3"); private static final List CDE_CODE = Collections.singletonList("4"); private static final String URL = "https://www.mydcambios.com.py/"; private final HTTPHelper helper; @Override public List doQuery(Place p, List branches) { String query = helper.doGet(URL); return branches.stream().map(branch -> { QueryResponse qr = new QueryResponse(branch); int dataIndex = ASU_CODE.contains(branch.getRemoteCode()) ? 0 : 1; List fullTable = getData(query, dataIndex); fullTable.forEach(data -> { String isoCode = getISOName(data); Long purchase = parse(data.getPurchasePrice()); Long sale = parse(data.getSalePrice()); if (isoCode == null || purchase < 1 || sale < 1) { return; } qr.addDetail(new QueryResponseDetail( parse(data.getPurchasePrice()), parse(data.getSalePrice()), isoCode)); }); return qr; }).filter(Objects::nonNull).collect(Collectors.toList()); } @Override public String getCode() { return CODE; } @Override public Place build() { log.info("Creating place MyD"); Place place = new Place("Cambios MyD", CODE); PlaceBranch matriz = new PlaceBranch(); matriz.setName(" matriz.setRemoteCode("2"); matriz.setPhoneNumber("021451377/9"); matriz.setLatitude(-25.281474); matriz.setLongitude(-57.637259); matriz.setImage("https://www.mydcambios.com.py/uploads/sucursal/2/_principal_myd_cambios_matriz.jpg"); PlaceBranch villa = new PlaceBranch(); villa.setName(" villa.setRemoteCode("3"); villa.setPhoneNumber("021-662537 / 021-609662"); villa.setLatitude(-25.294182); villa.setLongitude(-57.579190); villa.setImage("https://www.mydcambios.com.py/uploads/sucursal/3/_principal_img_20160205_wa0007.jpg"); PlaceBranch cde = new PlaceBranch(); cde.setName("Agencia KM4 - Cotizaciones"); cde.setRemoteCode("4"); cde.setPhoneNumber("021-662537 / 021-609662"); cde.setLatitude(-25.508799); cde.setLongitude(-54.639613); cde.setImage("https://www.mydcambios.com.py/uploads/sucursal/4/_principal_img_20160218_wa0060.jpg"); place.setBranches(Arrays.asList(matriz, villa, cde)); return place; } private static List getData(String html, int idx) { try { Document doc = Jsoup.parse(html); List data = new ArrayList<>(); Elements tables = doc.select(".cambios-banner-text.scrollbox"); Element mainTables = tables.get(idx); Elements rows = mainTables.select("ul"); for (Element e : rows) { Elements columns = e.select("li"); if (".".equals(columns.get(0).text())) { continue; } data.add(new ExchangeData( getCurrencyName(columns.get(0).getElementsByTag("img").get(0).attr("src")), columns.get(2).text().trim(), columns.get(1).text().trim())); } return data; } catch (Exception e) { throw new AppException(500, "Can't connect to to MyD page (branch: " + idx + ")", e); } } private static String getISOName(ExchangeData data) { switch (data.getCurrency()) { case "DOLARES AMERICANOS": case "us-1": return "USD"; case "REALES": case "descarga": case "br": return "BRL"; case "PESOS ARGENTINOS": case "ar": return "ARS"; case "EUROS": case "640px-Flag_of_Europe.svg": return "EUR"; case "YEN JAPONES": case "jp[1]": return "JPY"; case "LIBRAS ESTERLINAS": case "260px-Bandera-de-inglaterra-400x240": return "GBP"; case " case "175-suiza_400px[1]": return "CHF"; case " case "ca[2]": return "CAD"; case " case "cl[1]": return "CLP"; case "PESO URUGUAYO": case "200px-Flag_of_Uruguay_(1828-1830).svg": case "uy[1]": return "UYU"; default: log.warn("Currency not mapped {}, returning null", data.getCurrency()); return null; } } protected static String getCurrencyName(String img) { return img.substring(img.lastIndexOf('/') + 1, img.lastIndexOf('.')); } private static Long parse(String s) { return Long.parseLong(s.replaceAll(",", "").replaceAll("\\..*", "")); } @Value private static final class ExchangeData { private String currency; private String salePrice; private String purchasePrice; } }
java
26
0.682203
104
24.326829
205
starcoderdata
@Test public void ldAddedForcedAlways() { Gadget gadget = mockGadget(); TestDefaultIframeUriManager manager = makeManager( false, // security token beacon not required true); // locked domain always required Uri result = manager.makeRenderingUri(gadget); assertNotNull(result); UriBuilder uri = new UriBuilder(result); assertEquals("", uri.getScheme()); assertEquals(LD_PREFIX + LD_SUFFIX, uri.getAuthority()); assertEquals(IFRAME_PATH, uri.getPath()); // Basic sanity checks on params assertEquals(TYPE_HTML_NUM_BASE_PARAMS, uri.getQueryParameters().size()); assertEquals(0, uri.getFragmentParameters().size()); }
java
9
0.679487
77
34.15
20
inline
package io.github.marcelbraghetto.sunshinewatch; import android.content.Context; import android.content.res.Resources; import android.graphics.Canvas; import android.graphics.Point; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.util.TypedValue; import android.view.Display; import android.view.View; import android.view.ViewGroup; import android.view.WindowManager; import android.widget.ImageView; import android.widget.RelativeLayout; import android.widget.TextView; import org.joda.time.DateTime; import org.joda.time.format.DateTimeFormat; import org.joda.time.format.DateTimeFormatter; import java.util.Locale; import butterknife.Bind; import butterknife.ButterKnife; import io.github.marcelbraghetto.sunshinewatch.sharedlib.weather.WeatherForecast; import io.github.marcelbraghetto.sunshinewatch.sharedlib.weather.WeatherUtils; /** * Created by on 24/04/16. * * Custom view to encapsulate the watch face using a layout rather than manually painting. * * Inspired by this post: https://sterlingudell.wordpress.com/2015/05/10/layout-based-watch-faces-for-android-wear/ */ //region Watch Face View /* package */ class SunshineWatchFaceView extends RelativeLayout { @Bind(R.id.watch_face_container) ViewGroup mRoot; private final Point mDisplaySize = new Point(); private int mSpecWidth; private int mSpecHeight; private ActiveLayout mActiveLayout; private AmbientLayout mAmbientLayout; private WeatherForecast mWeatherForecast; private enum RenderMode { None, Active, Ambient } private final DateTimeFormatter mTimeFormatter; private RenderMode mRenderMode; private DateTime mNow; public SunshineWatchFaceView(Context context) { super(context); inflate(getContext(), R.layout.watch_face_root, this); ButterKnife.bind(this); Display display = ((WindowManager) getContext().getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay(); display.getSize(mDisplaySize); updateMeasureSpec(); // Android Wear devices don't appear to respect the standard resource qualifiers - it // is not possible to tell the difference between a 280x280 vs a 360x360 device using // the resource system - so unfortunately we have to use the pixel dimension of the // screen to programmatically decide on what resources to apply. boolean isLarge = mDisplaySize.x >= 360; mActiveLayout = new ActiveLayout(getContext()); mAmbientLayout = new AmbientLayout(getContext()); if(isLarge) { mActiveLayout.initLargeUI(); mAmbientLayout.initLargeUI(); } mTimeFormatter = DateTimeFormat.forPattern("h:mm"); mRenderMode = RenderMode.None; mNow = DateTime.now(); } public void setWeatherForecast(@Nullable WeatherForecast weatherForecast) { mWeatherForecast = weatherForecast; } public void updateMeasureSpec() { mSpecWidth = View.MeasureSpec.makeMeasureSpec(mDisplaySize.x, View.MeasureSpec.EXACTLY); mSpecHeight = View.MeasureSpec.makeMeasureSpec(mDisplaySize.y, View.MeasureSpec.EXACTLY); } public void render(@NonNull Canvas canvas, boolean ambient) { RenderMode renderMode = getRenderMode(ambient); // If we encounter a render mode that differs from our current mode, we need to adopt it // then assign the correct child view to represent that mode. if(mRenderMode != renderMode) { mRenderMode = renderMode; mRoot.removeAllViews(); switch (mRenderMode) { case Active: mRoot.addView(mActiveLayout); break; case Ambient: mRoot.addView(mAmbientLayout); break; } } mNow = DateTime.now(); switch (mRenderMode) { case Active: mActiveLayout.updateUI(mTimeFormatter.print(mNow), mNow, mWeatherForecast); break; case Ambient: mAmbientLayout.updateUI(mTimeFormatter.print(mNow)); break; } render(canvas); } private void render(Canvas canvas) { measure(mSpecWidth, mSpecHeight); layout(0, 0, getMeasuredWidth(), getMeasuredHeight()); draw(canvas); } private RenderMode getRenderMode(boolean ambient) { return ambient ? SunshineWatchFaceView.RenderMode.Ambient : SunshineWatchFaceView.RenderMode.Active; } //endregion //region Ambient Watch Face /* package */ static class AmbientLayout extends RelativeLayout { @Bind(R.id.watch_face_time_text) TextView mTimeTextView; public AmbientLayout(Context context) { super(context); inflate(getContext(), R.layout.watch_face_ambient, this); ButterKnife.bind(this); mTimeTextView.getPaint().setAntiAlias(false); } public void initLargeUI() { } public void updateUI(@NonNull String timeText) { mTimeTextView.setText(timeText); } } //endregion //region Active Watch Face /* package */ static class ActiveLayout extends RelativeLayout { @Bind(R.id.watch_face_logo) View mLogoView; @Bind(R.id.watch_face_time_text) TextView mTimeTextView; @Bind(R.id.watch_face_date_text) TextView mDateTextView; @Bind(R.id.watch_face_weather_container) View mForecastContainer; @Bind(R.id.watch_face_weather_icon) ImageView mForecastIcon; @Bind(R.id.watch_face_weather_temperature_max) TextView mMaxTempTextView; @Bind(R.id.watch_face_weather_temperature_min) TextView mMinTempTextView; private final DateTimeFormatter mDateFormatter; public ActiveLayout(Context context) { super(context); mDateFormatter = DateTimeFormat.forPattern("EEE, MMM d yyyy"); inflate(getContext(), R.layout.watch_face_active, this); ButterKnife.bind(this); } public void initLargeUI() { Resources res = getContext().getResources(); mLogoView.getLayoutParams().height = res.getDimensionPixelSize(R.dimen.WatchFaceLogoHeightLarge); mTimeTextView.setTextSize(TypedValue.COMPLEX_UNIT_PX, res.getDimension(R.dimen.WatchFaceTimeTextSizeLarge)); mDateTextView.setTextSize(TypedValue.COMPLEX_UNIT_PX, res.getDimension(R.dimen.WatchFaceDateTextSizeLarge)); mForecastIcon.getLayoutParams().width = res.getDimensionPixelSize(R.dimen.WatchFaceIconSizeLarge); mForecastIcon.getLayoutParams().height = res.getDimensionPixelSize(R.dimen.WatchFaceIconSizeLarge); mMaxTempTextView.setTextSize(TypedValue.COMPLEX_UNIT_PX, res.getDimension(R.dimen.WatchFaceTemperatureTextSizeLarge)); mMinTempTextView.setTextSize(TypedValue.COMPLEX_UNIT_PX, res.getDimension(R.dimen.WatchFaceTemperatureTextSizeLarge)); } public void updateUI(@NonNull String timeText, @NonNull DateTime now, @Nullable WeatherForecast weatherForecast) { mTimeTextView.setText(timeText); mDateTextView.setText(mDateFormatter.print(now).toUpperCase(Locale.ENGLISH)); if(weatherForecast == null) { mForecastContainer.setVisibility(GONE); return; } mForecastContainer.setVisibility(VISIBLE); mForecastIcon.setImageResource(WeatherUtils.getIconResourceForWeatherCondition(weatherForecast.getWeatherId())); mMaxTempTextView.setText(getContext().getString(R.string.format_temperature, weatherForecast.getMaxTemperature())); mMinTempTextView.setText(getContext().getString(R.string.format_temperature, weatherForecast.getMinTemperature())); } } //endregion }
java
14
0.686755
130
37.478261
207
starcoderdata
#pragma once #include #include "LuaCallCpp.h" #include #include #include #include class IOStuff { lua_State *state; std::string dirpath; std::map<std::string, time_t> modFiles; public: IOStuff() { state = luaL_newstate(); luaL_openlibs(state); dirpath = IOStuff::getexepath(); using namespace LuaToCpp; lua_pushcfunction(state, lua_sleep); lua_setglobal(state, "sleep"); } ~IOStuff() { lua_close(state); } static std::string getexepath() { char result[MAX_PATH]; std::string filepath = std::string(result, GetModuleFileName(NULL, result, MAX_PATH)); while (filepath.size() > 0 && filepath[filepath.size() - 1] != '\\') { filepath = filepath.substr(0, filepath.size() - 1); } return filepath; } bool isFileModified(std::string filename) { struct stat result; std::string dirpath = IOStuff::getexepath() + filename; if (stat(dirpath.c_str(), &result) == 0) { time_t mod_time = result.st_mtime; std::map<std::string, time_t>::iterator lb = modFiles.lower_bound(filename); if (lb != modFiles.end()) { // key already exists time_t oldTime = lb->second; modFiles[filename] = mod_time; return oldTime != mod_time; } else { // the key does not exist in the map modFiles.insert(lb, std::map<std::string, time_t>::value_type(filename, mod_time)); return true; } } return false; } /*static long getFileSize(std::string filename) { struct stat stat_buf; std::string dirpath = IOStuff::getexepath() + filename; int rc = stat(dirpath.c_str(), &stat_buf); return rc == 0 ? stat_buf.st_size : -1; }*/ void scriptNoArgs(std::string filename) { std::string scripts = dirpath + filename; int error = luaL_loadfile(state, scripts.c_str()); if (error == LUA_ERRFILE) { std::cout << "READ ERROR!" << std::endl; return; } lua_pcall(state, 0, LUA_MULTRET, 0); } };
c
16
0.642197
88
20.898876
89
starcoderdata
<!DOCTYPE html> body { margin: 14px; font-size: 18px; } .search { width: 400px; box-align: center; border: 1px inset black; padding: 5px; } .results { width: 400px; box-align: center; border: 1px edge black; padding: 5px; } table { border: 1px solid black; } thead { font-size: 22px; font-weight: bold italic; border-bottom: 1px double black; } tbody { font-size: 18px; } td { border-bottom: 1px dashed black; } tfoot { font-size: 14px; text-align: right; margin-top: 10px; } .footer { font-size: 14px; text-align: right; border-top: 1px double black; margin-top: 20px; } <?php $srch = "BA%"; $db = new SQLite3('sandbox.db'); ?> <div class="search"> Static search for <?php echo "'",$srch,"'" ?> <hr /> <div class="results"> Name Name <?php $result = $db->query("select * from namedb where surname like 'Ba%'"); while ($data = $result->fetchArray()) { ?> <?php echo $data['givenname']; ?> <?php echo $data['surname']; ?> <?php } ?> <td colspan=2>... retrieved <?php echo date("Y-m-d H:i:s"); ?> <div class="footer"> &copy;<?php echo date("Y") ?>
php
7
0.388784
88
19.028302
106
starcoderdata
# -*- coding: utf-8 -*- """ Created on Fri Apr 23 11:38:36 2021 @author: Sandip.Khairnar """ import websocket import six import base64 import zlib import datetime import time import json import threading import ssl class SmartWebSocket(object): ROOT_URI = 'wss://wsfeeds.angelbroking.com/NestHtml5Mobile/socket/stream' HB_INTERVAL = 30 HB_THREAD_FLAG = False WS_RECONNECT_FLAG = False feed_token = None client_code = None ws = None task_dict = {} def __init__(self, FEED_TOKEN, CLIENT_CODE): self.root = self.ROOT_URI self.feed_token = FEED_TOKEN self.client_code = CLIENT_CODE if self.client_code == None or self.feed_token == None: return "client_code or feed_token or task is missing" def _subscribe_on_open(self): request = {"task": "cn", "channel": "NONLM", "token": self.feed_token, "user": self.client_code, "acctid": self.client_code} print(request) self.ws.send( six.b(json.dumps(request)) ) thread = threading.Thread(target=self.run, args=()) thread.daemon = True thread.start() def run(self): while True: # More statements comes here if self.HB_THREAD_FLAG: break print(datetime.datetime.now().__str__() + ' : Start task in the background') self.heartBeat() time.sleep(self.HB_INTERVAL) def subscribe(self, task, token): # print(self.task_dict) self.task_dict.update([(task, token), ]) # print(self.task_dict) if task in ("mw", "sfi", "dp"): strwatchlistscrips = token # dynamic call try: request = {"task": task, "channel": strwatchlistscrips, "token": self.feed_token, "user": self.client_code, "acctid": self.client_code} self.ws.send( six.b(json.dumps(request)) ) return True except Exception as e: self._close( reason="Error while request sending: {}".format(str(e))) raise else: print("The task entered is invalid, Please enter correct task(mw,sfi,dp) ") def resubscribe(self): for task, marketwatch in self.task_dict.items(): print(task, '->', marketwatch) try: request = {"task": task, "channel": marketwatch, "token": self.feed_token, "user": self.client_code, "acctid": self.client_code} self.ws.send( six.b(json.dumps(request)) ) return True except Exception as e: self._close( reason="Error while request sending: {}".format(str(e))) raise def heartBeat(self): try: request = {"task": "hb", "channel": "", "token": self.feed_token, "user": self.client_code, "acctid": self.client_code} print(request) self.ws.send( six.b(json.dumps(request)) ) except: print("HeartBeat Sending Failed") # time.sleep(60) def _parse_text_message(self, message): """Parse text message.""" data = base64.b64decode(message) try: data = bytes((zlib.decompress(data)).decode("utf-8"), 'utf-8') data = json.loads(data.decode('utf8').replace("'", '"')) data = json.loads(json.dumps(data, indent=4, sort_keys=True)) except ValueError: return # return data if data: self._on_message(self.ws, data) def connect(self): # websocket.enableTrace(True) self.ws = websocket.WebSocketApp(self.ROOT_URI, on_message=self.__on_message, on_close=self.__on_close, on_open=self.__on_open, on_error=self.__on_error) self.ws.run_forever(sslopt={"cert_reqs": ssl.CERT_NONE}) def __on_message(self, ws, message): self._parse_text_message(message) # print(msg) def __on_open(self, ws): print("__on_open################") self.HB_THREAD_FLAG = False self._subscribe_on_open() if self.WS_RECONNECT_FLAG: self.WS_RECONNECT_FLAG = False self.resubscribe() else: self._on_open(ws) def __on_close(self, ws): self.HB_THREAD_FLAG = True print("__on_close################") self._on_close(ws) def __on_error(self, ws, error): if ("timed" in str(error)) or ("Connection is already closed" in str(error)) or ("Connection to remote host was lost" in str(error)): self.WS_RECONNECT_FLAG = True self.HB_THREAD_FLAG = True if (ws is not None): ws.close() ws.on_message = None ws.on_open = None ws.close = None # print (' deleting ws') del ws self.connect() else: print('Error info: %s' % (error)) self._on_error(ws, error) def _on_message(self, ws, message): pass def _on_open(self, ws): pass def _on_close(self, ws): pass def _on_error(self, ws, error): pass
python
18
0.490172
141
29.02139
187
starcoderdata
void test(String input, String cmd) throws Exception { lastInput = input; lastCommand = cmd; // "X" is appended so that we can precisely test how input is consumed HumanInputStream in = new HumanInputStream(input+"X"); test(in, cmd); // make sure the input string is no more no less if(in.read() != 'X' || in.read() != -1) throw new Exception("Input not consumed exactly"); }
java
9
0.598214
78
39.818182
11
inline
#include "../src/parser.h" #include using namespace std; int main() { CsvParser csv; }
c++
4
0.653465
26
11.75
8
starcoderdata
public void onDeviceConnected(String name, String address) { status_conect = "Conectado: " + name; Toast.makeText(getApplicationContext(), status_conect, Toast.LENGTH_SHORT).show(); existe_conec_bluetooth = true; Actualizar_ventana_bluetooth(); //envia datos al fragmento actualizar_ventana_bluetooth_frame(); //actualiza frament bluetooth }
java
9
0.610478
98
61.857143
7
inline
#!/usr/bin/python3 import requests import json # define the URL we want to use GETURL = "http://validate.jsontest.com/" def main(): # test data to validate as legal json mydata = {"fruit": ["apple", "pear"], "vegetable": ["carrot"]} ## the next two lines do the same thing ## we take python, convert to a string, then strip out whitespace #jsonToValidate = "json=" + str(mydata).replace(" ", "") #jsonToValidate = f"json={ str(mydata).replace(' ', '') }" ## slightly different thinking ## user json library to convert to legal json, then strip out whitespace jsonToValidate = f"json={ json.dumps(mydata).replace(' ', '') }" # use requests library to send an HTTP GET resp = requests.get(f"{GETURL}?{jsonToValidate}") # strip off JSON response # and convert to PYTHONIC LIST / DICT respjson = resp.json() # display our PYTHONIC data (LIST / DICT) print(respjson) # JUST display the value of "validate" print(f"Is your JSON valid? {respjson['validate']}") if __name__ == "__main__": main()
python
11
0.647321
76
29.27027
37
starcoderdata
public Future<Void> add(CoreHandler handler) { Promise<Void> promise = Promise.promise(); // if already started - start up the handler. if (started.get()) { if (map.containsKey(handler.address())) { throw new CoreRuntimeException("A deployed handler already exists with address: " + handler.address()); } else { handler.init(core); handler.start(promise); } } map.put(handler.address(), handler); promise.complete(); return promise.future(); }
java
13
0.552721
119
35.8125
16
inline
// Copyright (c) 2020 // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. #include "target/new/binary_type.hpp" auto kdl::build_target::binary_type_for_name(const std::string& name) -> enum binary_type { if (name == "HBYT") { return binary_type::HBYT; } else if (name == "DBYT") { return binary_type::DBYT; } // else if (name == "FBYT") { // return binary_type::FBYT; // } else if (name == "HWRD") { return binary_type::HWRD; } else if (name == "DWRD") { return binary_type::DWRD; } // else if (name == "FWRD") { // return binary_type::FWRD; // } else if (name == "HLNG") { return binary_type::HLNG; } else if (name == "DLNG") { return binary_type::DLNG; } // else if (name == "FLNG") { // return binary_type::FLNG; // } else if (name == "HQAD") { return binary_type::HQAD; } else if (name == "DQAD") { return binary_type::DQAD; } // else if (name == "FQAD") { // return binary_type::FQAD; // } // else if (name == "AWRD") { // return binary_type::AWRD; // } // else if (name == "ALNG") { // return binary_type::ALNG; // } // else if (name == "AQAD") { // return binary_type::AQAD; // } else if (name == "HEXD") { return binary_type::HEXD; } else if (name == "PSTR") { return binary_type::PSTR; } // else if (name == "LSTR") { // return binary_type::LSTR; // } // else if (name == "WSTR") { // return binary_type::WSTR; // } // else if (name == "ESTR") { // return binary_type::ESTR; // } // else if (name == "OSTR") { // return binary_type::OSTR; // } else if (name == "CSTR") { return binary_type::CSTR; } // else if (name == "ECST") { // return binary_type::ECST; // } // else if (name == "OCST") { // return binary_type::OCST; // } // else if (name == "BOOL") { // return binary_type::BOOL; // } // else if (name == "BBIT") { // return binary_type::BBIT; // } // else if (name == "TNAM") { // return binary_type::TNAM; // } // else if (name == "CHAR") { // return binary_type::CHAR; // } else if (name == "RECT") { return binary_type::RECT; } else if (name[0] == 'C') { auto width = static_cast nullptr, 16)); return static_cast | width); } // else if (name[0] == 'H') { // auto width = static_cast nullptr, 16)); // return static_cast | width); // } // else if (name[0] == 'P' && name[1] == '0') { // auto width = static_cast nullptr, 16)); // return static_cast | width); // } else if (name == "OCNT") { return binary_type::OCNT; } // else if (name == "LSTZ") { // return binary_type::LSTZ; // } // else if (name == "LSTE") { // return binary_type::LSTE; // } // else if (name == "ZCNT") { // return binary_type::ZCNT; // } // else if (name == "LSTC") { // return binary_type::LSTC; // } // else if (name == "LSTB") { // return binary_type::LSTB; // } return binary_type::INVALID; }; auto kdl::build_target::binary_type_base_size(const enum kdl::build_target::binary_type& type) -> std::size_t { switch (type & ~0xFFF) { case binary_type::CSTR: case binary_type::PSTR: case binary_type::HBYT: case binary_type::DBYT: { return 1; } case binary_type::HWRD: case binary_type::DWRD: case binary_type::OCNT: { return 2; } case binary_type::HLNG: case binary_type::DLNG: { return 4; } case binary_type::RECT: case binary_type::HQAD: case binary_type::DQAD: { return 8; } case binary_type::Cnnn: { return type & 0xFFF; } case binary_type::HEXD: { return 0; } default: return 0; } }
c++
10
0.544189
109
29.089385
179
starcoderdata
// // main.cpp // Max_Sub_Array_Brute // // Created by on 15/07/16. // Copyright © 2016 All rights reserved. // // Brute force implementation of the Maximum Sub Array Problem #include #include #include using namespace::std; int main(int argc, const char * argv[]) { vector A ={13, -3, -25, 20, -3, -16, -23, 18, 20, -7, 12, -5, -22, 15, -4, 7}; unsigned long n = A.size(); int sum; int moall = INT_MIN; unsigned long mindex = 0; vector maxprofit(n, INT_MIN); vector<unsigned long> index(n, 0); for (unsigned long i = 0; i<=n-1; i++){ sum = 0; for(unsigned long j = i; j <=n-1; j++){ sum = sum + A[j]; if(sum > maxprofit[i]){ maxprofit[i]= sum; index[i] = j; } } if(maxprofit[i] > moall) { moall = maxprofit[i]; mindex = i; } } for(int m = 0; m<=n-1; m++){ cout<<maxprofit[m]<<" "; } cout<<"\n"; for(unsigned long k = mindex; k<=index[mindex]; k++) { cout<<A[k]<<" "; } cout<<"\n"<<moall<<"\n"; }
c++
13
0.472153
88
21.698113
53
starcoderdata
jQuery(document).ready(function() { window.i = 0; $.history.init(pageload); $("#pause_stream").click(function () { if (window.pause == true) { window.intervalID = setInterval("getStream()", 10000); window.pause = false; $('#pause_stream').text(' Pause'); $('#pause_stream').removeClass('btn-info icon-play'); $('#pause_stream').addClass('btn-warning icon-pause'); getStream(); } else { clearInterval(window.intervalID); window.pause = true; $('#pause_stream').text(' Play'); $('#pause_stream').removeClass('btn-warning icon-pause'); $('#pause_stream').addClass('btn-info icon-play'); } }); }); function pageload(hash) { if (hash) { window.last_time = ""; window.hasHead = false; clearInterval(window.intervalID); window.hashjson = JSON.parse(Base64.decode(hash)); window.hashjson.fields = window.hashjson.fields.length > 0 ? window.hashjson.fields : new Array('@message'); $('#query h4').html(window.hashjson.search); getStream(); window.intervalID = setInterval("getStream()", 10000); } else { $('#tweets').html(' query } } function getStream() { var timeframe = 10; var maxEvents = 15; var b64json = Base64.encode(JSON.stringify(window.hashjson)); var from = "" if (window.last_time != "") { from = "/" + window.last_time; } $.getJSON("api/stream/" + b64json + from, null, function(data) { if (data != null) { window.i++; var fields = window.hashjson.fields var has_time = false; var header = ""; var str = ""; var id = ""; var hit = ""; var i = 0; for (var obj in data.hits.hits) { hit = data.hits.hits[obj] id = hit['_id'] index = hit['_index'] if (!(has_time)) { window.last_time = get_field_value(hit,'@timestamp'); has_time = true; } if ($('#logrow_' + id).length == 0) { str += "<tr id=logrow_" + id + ">"; i++; hash = Base64.encode(JSON.stringify( { "timeframe":"900", "mode":"id", "fields":"", "id":id, "index":index, "offset":0 } )); str += "<td style='white-space:nowrap;'><a class=jlink href='../#"+hash+"'><i class='icon-link'> " + prettyDateString(Date.parse(get_field_value(hit,'@timestamp')) + tOffset) + " for (var field in fields) { str += " + get_field_value(hit,fields[field]) + " } str += " } } $(str).prependTo('#tweets tbody'); $('#counter h3').fadeOut(100) $('#counter h3').html(data.hits.total/timeframe+'/second'); $('#counter h3').fadeIn(500) $( 'tr:gt(' + ( maxEvents ) + ')' ).fadeOut( "normal", function() { $(this).remove(); } ); if(!window.hasHead) { header += " for (var field in fields) { header += " + fields[field] + " } window.hasHead = true; $('#tweets thead').html(header) } } }); }
javascript
26
0.504917
118
27.295652
115
starcoderdata
package pluginv2 import ( "skynet/util" "skynet/neutron" "github.com/containernetworking/cni/pkg/skel" "os" "fmt" "errors" ) func SetupMacVlanInterface(args *skel.CmdArgs, podName string, namespace string, network *neutron.OpenStackNetwork, subnet *neutron.OpenStackSubnet, port *neutron.OpenStackPort, podIp neutron.FixIP, conf util.NetConf) (err error) { portId := port.Id portMac := port.MacAddress fmt.Fprintf(os.Stderr, "Skynet set container interface with port id %s\n", portId) vifName := "vif" + portId[:11] containerInterface := args.IfName if containerInterface == "" { containerInterface = "eth0" } networkType := network.NetworkType segmentId := network.SegmentId containerNs := args.Netns var parentNic string if networkType != VLAN_TYPE&&networkType != FLAT_TYPE { return errors.New("macvlan DO NOT support network type: " + networkType) } switch networkType { case VLAN_TYPE: parentNic, err = ensureVlanDevice(conf.Plugin.TrunkNic, segmentId) ensureDeviceUp(parentNic) case FLAT_TYPE: parentNic = conf.Plugin.TrunkNic default: err = errors.New("macvlan DO NOT support network type: " + networkType) } if err != nil { return err } fmt.Fprintf(os.Stderr, "Skynet set container interface with %s\n", containerInterface) if err = createMacvlanDevice(vifName, parentNic); err != nil { return err } if err = setupContainer(containerNs, vifName, containerInterface, portMac, podIp, subnet.GatewayIp); err != nil { deleteVeth(vifName) return err } return nil } func createMacvlanDevice(vifName, parentNic string) error { return Exec([]string{"ip", "link", "add", "link", parentNic, vifName, "type", "macvlan", "mode", "bridge"}) }
go
11
0.600969
177
37.259259
54
starcoderdata
/* * Copyright (c) 2009, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the Willow Garage, Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ /** \author */ #ifndef ROSTEST_PERMUTER_H #define ROSTEST_PERMUTER_H #include #include "boost/thread/mutex.hpp" namespace rostest { /** \brief A base class for storing pointers to generic data types */ class PermuteOptionBase { public: virtual void reset() =0; virtual bool step() =0; virtual ~PermuteOptionBase() {}; }; /**\brief A class to hold a set of option values and currently used state * This class holds */ template<class T> class PermuteOption : public PermuteOptionBase { public: PermuteOption(const std::vector options, T* output) { options_ = options; output_ = output; reset(); } virtual ~PermuteOption(){}; void reset(){ boost::mutex::scoped_lock lock(access_mutex_); current_element_ = options_.begin(); *output_ = *current_element_; }; bool step() { boost::mutex::scoped_lock lock(access_mutex_); current_element_++; if (current_element_ == options_.end()) return false; *output_ = *current_element_; return true; }; private: /// Local storage of the possible values std::vector options_; /// The output variable T* output_; typedef typename std::vector V_T_iterator; /// The last updated element V_T_iterator current_element_; boost::mutex access_mutex_; }; /** \brief A class to provide easy permutation of options * This class provides a way to collapse independent * permutations of options into a single loop. */ class Permuter { public: /** \brief Destructor to clean up allocated data */ virtual ~Permuter(){ clearAll();}; /** \brief Add a set of values and an output to the iteration * @param values The set of possible values for this output * @param output The value to set at each iteration */ template<class T> void addOptionSet(const std::vector values, T* output) { boost::mutex::scoped_lock lock(access_mutex_); options_.push_back(static_cast (new PermuteOption output))); lock.unlock();//reset locks on its own reset(); }; /** \brief Reset the internal counters */ void reset(){ boost::mutex::scoped_lock lock(access_mutex_); for (unsigned int level= 0; level < options_.size(); level++) options_[level]->reset(); }; /** \brief Iterate to the next value in the iteration * Returns true unless done iterating. */ bool step() { boost::mutex::scoped_lock lock(access_mutex_); // base case just iterating for (unsigned int level= 0; level < options_.size(); level++) { if(options_[level]->step()) { //printf("stepping level %d returning true \n", level); return true; } else { //printf("reseting level %d\n", level); options_[level]->reset(); } } return false; }; /** \brief Clear all stored data */ void clearAll() { boost::mutex::scoped_lock lock(access_mutex_); for ( unsigned int i = 0 ; i < options_.size(); i++) { delete options_[i]; } options_.clear(); }; private: std::vector options_; ///< Store all the option objects boost::mutex access_mutex_; }; } #endif //ROSTEST_PERMUTER_H
c
17
0.673306
95
27.313953
172
starcoderdata
#include #include void readin(uint8_t* c) { *c = getchar(); } void print(uint8_t* c) { putchar(*c); }
c
7
0.6
25
14.1
10
starcoderdata
/** * Copyright 2017-2018 the original author or 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 com.flowyun.cornerstone.db.mybatis.pagination; import com.flowyun.cornerstone.db.mybatis.MybatisException; import com.flowyun.cornerstone.db.mybatis.enums.DBType; import com.flowyun.cornerstone.db.mybatis.pagination.dialects.*; import com.flowyun.cornerstone.db.mybatis.util.MybatisStringUtils; /** * * 分页方言工厂类 * */ public class DialectFactory { /** * Physical Pagination Interceptor for all the queries with parameter * {@link org.apache.ibatis.session.RowBounds} * @param dialectClazz * @return * @throws Exception */ public static String buildPaginationSql(PaginationContext paginationContext,String dialectClazz) throws Exception { IDialect dialect = getDialect(paginationContext.getDbType(), dialectClazz); return dialect.buildPaginationSql(paginationContext); } public static String buildPaginationSql(PaginationContext paginationContext) throws Exception { IDialect dialect = getDialect(paginationContext.getDbType(),null); return dialect.buildPaginationSql(paginationContext); } /** * * 获取数据库方言 * * * @param dbType 数据库类型 * @param dialectClazz 自定义方言实现类 * @return * @throws Exception */ private static IDialect getDialect(DBType dbType, String dialectClazz) throws Exception { IDialect dialect = null; if (MybatisStringUtils.isNotEmpty(dialectClazz)) { try { Class clazz = Class.forName(dialectClazz); if (IDialect.class.isAssignableFrom(clazz)) { dialect = (IDialect) clazz.newInstance(); } } catch (ClassNotFoundException e) { throw new MybatisException("Class :" + dialectClazz + " is not found"); } } else if (null != dbType) { dialect = getDialectByDbType(dbType); } /* 未配置方言则抛出异常 */ if (dialect == null) { throw new MybatisException("The value of the dialect property in mybatis configuration.xml is not defined."); } return dialect; } /** * * 根据数据库类型选择不同分页方言 * * * @param dbType 数据库类型 * @return * @throws Exception */ private static IDialect getDialectByDbType(DBType dbType) { IDialect dialect; switch (dbType) { case MYSQL8: dialect = MySql8Dialect.INSTANCE; break; case MYSQL: dialect = MySqlDialect.INSTANCE; break; case ORACLE: dialect = OracleDialect.INSTANCE; break; case H2: dialect = H2Dialect.INSTANCE; break; case POSTGRE: dialect = PostgreDialect.INSTANCE; break; case HSQL: dialect = HSQLDialect.INSTANCE; break; case SQLITE: dialect = SQLiteDialect.INSTANCE; break; default: throw new MybatisException("The Database's Not Supported! DBType:" + dbType); } return dialect; } }
java
16
0.608074
121
32.233333
120
starcoderdata
using System; using NUnit.Framework; using Responsible.Tests.Utilities; using static Responsible.Responsibly; namespace Responsible.Tests { public class ExceptionMessageTests : ResponsibleTestBase { [Test] public void ExceptionMessage_IncludesAllDetails() { var task = Do("Throw", () => throw new Exception("An exception")) .ToTask(this.Executor); var failureException = GetFailureException(task); Console.WriteLine(failureException.Message); StateAssert .StringContainsInOrder(failureException.Message) .Details("Test operation execution failed") .Failed("Throw") .Details("Failed with:") .Details("An exception") .Details("Test operation stack:") .Details(@"\[Do\].*?\(at") .Details(@"\[ToTask\].*?\(at") .Details("Error:"); } [Test] public void ExceptionMessage_DoesNotIncludeEmptyLines() { var task = Do("Throw", () => throw new Exception()) .ToTask(this.Executor); var lines = GetFailureException(task).Message.Split('\n'); CollectionAssert.Contains(lines, " "); CollectionAssert.DoesNotContain(lines, ""); } } }
c#
28
0.692516
68
26.04878
41
starcoderdata
define([ 'angular', 'directives/afClick', 'directives/afContext', 'directives/afModifier', 'directives/afRenderNode', 'directives/afSurface', 'directives/afView', 'services/afUtils', 'famousModule' ], function (angular) { return angular.module('angularFamous', [ 'angularFamous.afClick', 'angularFamous.afContext', 'angularFamous.afModifier', 'angularFamous.afRenderNode', 'angularFamous.afSurface', 'angularFamous.afView', 'angularFamous.afUtils', 'famous' ]); });
javascript
7
0.69788
46
23.652174
23
starcoderdata
def elfsXompletionWrapper(prefix: str, line: str, begidx: int, endidx: int, ctx: dict) -> typing.Union[None, set]: if line.startswith("elfs "): # get regular completions sys.argv = ["elfs", "--_return_completion", line] completions = main() # xonsh seems to need quotes to autocomplete paths, and splits off prefix on a space (even when escaped) # this slightly improves it for paths without spaces (without needing quotes) # trying anything more, eg. with shlex is problematic if os.path.isdir(os.path.dirname(prefix)): completions += os.listdir(os.path.dirname(prefix)) else: completions += os.listdir() # format completions for xonsh -remove descriptions -escape spaces -filter by prefix if len(completions) >= 1: return {completion.split("\t")[0].replace(" ", "\\ ") for completion in completions if completion.startswith(prefix)} return None
python
16
0.641624
129
59.6875
16
inline
void GlobalRoutingAStarSequential::waiveNetInGr(IndexType netIdx) { // Remove the existing paths in the net _db.grDB().ripupNet(netIdx); // No need to push back the net into the heap (gave up) // Set the properties INF("GlobalRoutingAStarSequential::waiveNetInGr: waive net %d in global routing \n", netIdx); _db.grDB().nets().at(netIdx).setIsRouted(false); _db.grDB().nets().at(netIdx).setWaiveGR(true); }
c++
12
0.700461
97
42.5
10
inline
<?php /** * This file is part of OXID eShop Community Edition. * * OXID eShop Community Edition is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * OXID eShop Community Edition 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 * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with OXID eShop Community Edition. If not, see * * @link http://www.oxid-esales.com * @copyright (C) OXID eSales AG 2003-2017 * @version OXID eShop CE */ /** * Smarty {mailto} function plugin extension, fixes character encoding problem * * @param array $aParams parameters * @param Smarty &$oSmarty smarty object * * @return string */ function smarty_function_oxmailto( $aParams, &$oSmarty ) { if ( isset( $aParams['encode'] ) && $aParams['encode'] == 'javascript' ) { $sAddress = isset( $aParams['address'] ) ? $aParams['address'] : ''; $sText = $sAddress; $aMailParms = array(); foreach ( $aParams as $sVarName => $sValue ) { switch ( $sVarName ) { case 'cc': case 'bcc': case 'followupto': if ( $sValue ) { $aMailParms[] = $sVarName . '=' . str_replace( array( '%40', '%2C' ), array( '@', ',' ), rawurlencode( $sValue ) ); } break; case 'subject': case 'newsgroups': $aMailParms[] = $sVarName . '=' . rawurlencode( $sValue ); break; case 'extra': case 'text': $sName = "s".ucfirst( $sVarName ); $$sName = $sValue; default: } } for ( $iCtr = 0; $iCtr < count( $aMailParms ); $iCtr++ ) { $sAddress .= ( $iCtr == 0 ) ? '?' : '&'; $sAddress .= $aMailParms[$iCtr]; } $sString = 'document.write(\'<a href="mailto:'.$sAddress.'" '.$sExtra.'>'.$sText.' $sEncodedString = "%".wordwrap( current( unpack( "H*", $sString ) ), 2, "%", true ); return '<script type="text/javascript">eval(decodeURIComponent(\''.$sEncodedString.'\')) } else { include_once $oSmarty->_get_plugin_filepath( 'function', 'mailto' ); return smarty_function_mailto($aParams, $oSmarty ); } }
php
22
0.553276
139
37.054795
73
starcoderdata
package math import ( "fmt" "strconv" ) func Float64ToInt64(f float64) int64 { floatStr := fmt.Sprintf("%.0f", f) inst, _ := strconv.ParseInt(floatStr, 10, 64) return inst } func Float64ToUint64(f float64) uint64 { floatStr := fmt.Sprintf("%.0f", f) inst, _ := strconv.ParseUint(floatStr, 10, 64) return inst }
go
8
0.684507
47
17.684211
19
starcoderdata
from random import randrange from seraphim.util.polynom_helper import get_minimal_polynomial from seraphim.finite_fields.polynomial import Polynomial from seraphim.finite_fields.finite_field_element import FiniteFieldElement class FiniteField(object): """ Endlicher Körper der Form p^n. Optional kann ein Generator-Polynom übergeben werden. p ist der Modulus und die Charakteristik des Körpers und muss eine Primzahl sein n ist die Dimension und Exponent """ def __init__(self, n, p, generator=None): assert p > 1 assert n > 0 self.p = p self.n = n if isinstance(generator, Polynomial): self.generator = generator else: self.generator = get_minimal_polynomial(p, n) def __str__(self): s = "FiniteField(%s^%s)" % (str(self.p), str(self.n)) s += "\n" s += "Erzeugerpolynom:\n" s += str(self.generator) return str(s) def generate_random_element(self, maxint=100): polynom = generate_random_polynomial(self.n, maxint) return FiniteFieldElement(self, polynom) def generate_random_polynomial(degree, maxint=100, mod=True): coef = [] for _ in range(0, degree): val = randrange(maxint) if mod is True: coef.append(val % degree) else: coef.append(val) coef.append(1) return Polynomial(coef)
python
12
0.631356
88
28.5
48
starcoderdata
import React, { Component } from 'react'; import FlagQuestion, { QuestionStates } from './FlagQuestion.js'; import shuffle from 'shuffle-array'; class Game extends Component { constructor (props) { super(props); this.state = { countries: [], options: [], correctOption: undefined, questionState: undefined }; this.onGuess = this.onGuess.bind(this); this.nextQuestion = this.nextQuestion.bind(this); } componentDidMount () { fetch('https://restcountries.eu/rest/v2/all') .then(resp => resp.json()) .then(countries => { const correctOption = Math.floor(Math.random() * countries.length); const options = this._getOptions(correctOption, countries); this.setState({ countries, correctOption, options, questionState: QuestionStates.QUESTION }); }) .catch(console.warn); } onGuess (answer) { const { correctOption } = this.state; const questionState = answer === correctOption ? QuestionStates.ANSWER_CORRECT : QuestionStates.ANSWER_WRONG; this.setState({ questionState }); } nextQuestion () { const { countries } = this.state; const correctOption = Math.floor(Math.random() * countries.length); const options = this._getOptions(correctOption, countries); this.setState({ correctOption, options, questionState: QuestionStates.QUESTION }); } _getOptions (correctOption, countries) { const options = [correctOption]; let tries = 0; while (options.length < 4 && tries < 15) { const option = Math.floor(Math.random() * countries.length); if (options.indexOf(option) === -1) { options.push(option); } else { tries++; } } return shuffle(options); } render () { const { countries, correctOption, options, questionState } = this.state; let output = if (correctOption !== undefined) { const { flag, name } = countries[correctOption]; const opts = options.map(opt => { return { id: opt, name: countries[opt].name }; }); output = ( <FlagQuestion answerText={name} onGuess={this.onGuess} onNext={this.nextQuestion} options={opts} questionState={questionState} flag={flag} /> ); } return ( <div style={{ marginTop: '15px' }}> {output} ); } } export default Game;
javascript
19
0.579273
75
23.875
104
starcoderdata
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import random from typing import List from fairseq.data import BaseWrapperDataset, data_utils class RandomInputDataset(BaseWrapperDataset): def __init__( self, dataset, random_input_dataset, input_key_path: List[str], add_to_input, pad_idx, ): super().__init__(dataset) self.random_input_dataset = random_input_dataset if isinstance(input_key_path, str): input_key_path = [input_key_path] assert len(input_key_path) > 0 self.input_key_path = input_key_path self.add_to_input = add_to_input self.pad_idx = pad_idx def get_target(self, item): target_loc = item for p in self.input_key_path[:-1]: target_loc = target_loc[p] return self.input_key_path[-1], target_loc def get_target_value(self, item): k, target_loc = self.get_target(item) return target_loc[k] def __getitem__(self, index): item = self.dataset[index] k, target_loc = self.get_target(item) target_loc[k] = random.choice(self.random_input_dataset) return item def collater(self, samples): collated = self.dataset.collater(samples) if len(collated) == 0: return collated indices = set(collated["id"].tolist()) random_inputs = data_utils.collate_tokens( [self.get_target_value(s) for s in samples if s["id"] in indices], pad_idx=self.pad_idx, left_pad=False, ) k, target_loc = self.get_target( collated if not self.add_to_input else collated["net_input"] ) target_loc[k] = random_inputs return collated
python
14
0.599475
78
29.725806
62
research_code
 namespace SinglyLinkedList.Tests { using System; using Microsoft.VisualStudio.TestTools.UnitTesting; using SinglyLinkedList; [TestClass] public class ListTest { private List list; [TestInitialize] public void Initialize() { list = new List(); } [TestMethod] public void AddFirstTest() { list.Add(1, 3); Assert.AreEqual(3, list.GetValue(1)); list.Add(1, 5); Assert.AreEqual(5, list.GetValue(1)); } [TestMethod] public void AddTest() { list.Add(1, 5); list.Add(2, -9); list.Add(3, 10); Assert.AreEqual(5, list.GetValue(1)); Assert.AreEqual(-9, list.GetValue(2)); Assert.AreEqual(10, list.GetValue(3)); } [TestMethod] public void AddAtWrongPositionTest() { list.Clear(); list.Add(56, 1); list.Add(-5, 1); Assert.IsTrue(list.IsEmpty()); } [TestMethod] public void RemoveTest() { list.Add(1, 8); list.Add(2, 70); list.Add(3, 0); list.Remove(2); Assert.AreEqual(0, list.GetValue(2)); } [TestMethod] public void RemoveFirstTest() { list.Add(1, 5); list.Add(2, 8); list.Remove(1); Assert.AreEqual(8, list.GetValue(1)); } [TestMethod] public void SetValueTest() { list.Add(1, 4); list.Add(1, 15); list.SetValue(2, 7); Assert.AreEqual(7, list.GetValue(2)); } [TestMethod] public void GetValueFromWrongPositionTest() { Assert.AreEqual(-1, list.GetValue(9)); Assert.AreEqual(-1, list.GetValue(-6)); } [TestMethod] public void ClearTest() { for (int i = 1; i <= 3; ++i) { list.Add(1, i); } list.Clear(); Assert.IsTrue(list.IsEmpty()); } [TestMethod] public void LengthTest() { list.Clear(); for (int i = 0; i < 5; ++i) { list.Add(1, i); } Assert.AreEqual(5, list.Length); list.Remove(1); Assert.AreEqual(4, list.Length); } [TestMethod] public void RemoveFromEmptyListTest() { list.Clear(); list.Remove(1); } [TestMethod] public void EmptyListLengthTest() { list.Clear(); Assert.AreEqual(0, list.Length); } } }
c#
15
0.445822
55
20.891473
129
starcoderdata
package group // import "github.com/docker/infrakit/pkg/controller/group" import ( "sort" "testing" group_types "github.com/docker/infrakit/pkg/controller/group/types" "github.com/docker/infrakit/pkg/spi/instance" "github.com/stretchr/testify/require" ) func TestSortByID(t *testing.T) { { list := []instance.Description{ {ID: "d", LogicalID: logicalID("4")}, {ID: "c", LogicalID: logicalID("3")}, {ID: "b", LogicalID: logicalID("2")}, {ID: "a", LogicalID: logicalID("1")}, } sort.Sort(sortByID{list: list}) require.Equal(t, []instance.Description{ {ID: "a", LogicalID: logicalID("1")}, {ID: "b", LogicalID: logicalID("2")}, {ID: "c", LogicalID: logicalID("3")}, {ID: "d", LogicalID: logicalID("4")}, }, list) } { list := []instance.Description{ {ID: "d", LogicalID: logicalID("4")}, {ID: "c", LogicalID: logicalID("3")}, {ID: "b", LogicalID: logicalID("2")}, {ID: "a", LogicalID: logicalID("1")}, } sort.Sort(sortByID{list: list, settings: &groupSettings{ self: logicalID("1"), options: group_types.Options{}}}) require.Equal(t, []instance.Description{ {ID: "b", LogicalID: logicalID("2")}, {ID: "c", LogicalID: logicalID("3")}, {ID: "d", LogicalID: logicalID("4")}, {ID: "a", LogicalID: logicalID("1")}, }, list) } { list := []instance.Description{ {ID: "d", LogicalID: logicalID("4")}, {ID: "c", LogicalID: logicalID("3")}, {ID: "b", LogicalID: logicalID("2")}, {ID: "a", LogicalID: logicalID("1")}, } sort.Sort(sortByID{list: list, settings: &groupSettings{ self: logicalID("3"), options: group_types.Options{}}}) require.Equal(t, []instance.Description{ {ID: "a", LogicalID: logicalID("1")}, {ID: "b", LogicalID: logicalID("2")}, {ID: "d", LogicalID: logicalID("4")}, {ID: "c", LogicalID: logicalID("3")}, }, list) } tagsWithLogicalID := func(v string) map[string]string { return map[string]string{ instance.LogicalIDTag: v, } } { list := []instance.Description{ {ID: "d", Tags: tagsWithLogicalID("4")}, {ID: "c", Tags: tagsWithLogicalID("3")}, {ID: "b", Tags: tagsWithLogicalID("2")}, {ID: "a", Tags: tagsWithLogicalID("1")}, } sort.Sort(sortByID{list: list, settings: &groupSettings{ self: logicalID("1"), options: group_types.Options{}}}) require.Equal(t, []instance.Description{ {ID: "b", Tags: tagsWithLogicalID("2")}, {ID: "c", Tags: tagsWithLogicalID("3")}, {ID: "d", Tags: tagsWithLogicalID("4")}, {ID: "a", Tags: tagsWithLogicalID("1")}, }, list) } }
go
19
0.589109
73
23.091743
109
starcoderdata
<?php use Illuminate\Support\Facades\Route; use App\Http\Controllers\Registeruser; use App\Http\Controllers\Loginruser; use App\Http\Controllers\CategoryController; use App\Http\Controllers\UserController; use App\Http\Controllers\ExpenseController; use App\Http\Controllers\LoginController; use App\Http\Controllers\AdminController; /* |-------------------------------------------------------------------------- | Web Routes |-------------------------------------------------------------------------- | | Here is where you can register web routes for your application. These | routes are loaded by the RouteServiceProvider within a group which | contains the "web" middleware group. Now create something great! | */ // Route::get('/', function () { // return view('welcome'); // }); // Route::post("users",[Registeruser::class,'uregistration']); // Route::view("registration","users"); // //Route::post("login",[Loginuser::class,'ulogin']); // Route::get("category",[CategoryController::class,'getData']); // //Route::post("expense",[Expense::class,'expenses']); // Route::view("expenseuser","expense"); // //Route::view("userlist","userlist"); // Route::get('userlist',[UserController::class,'ulist']); // Route::view("createuser","createuser"); // Route::post("createuser",[UserController::class,'store']); // Route::get('edituser/{id}',[UserController::class,'edit']); // Route::post('edituser/{id}',[UserController::class,'update']); // Route::get("deleteuser/{id}",[UserController::class,'delete']); // Route::get('categorylist',[CategoryController::class,'list']); // Route::view('createcategory','createcategory'); // Route::post('createcategory',[CategoryController::class,'store']); // Route::get("deletecategory/{id}",[CategoryController::class,'delete']); // Route::get('editcategory/{id}',[CategoryController::class,'edit']); // Route::post('editcategory/{id}',[CategoryController::class,'update']); // Route::get('expenselist',[ExpenseController::class,'elist']); // Route::get("createexpense",[ExpenseController::class,'show']); // Route::post('createexpense',[ExpenseController::class,'store']); // Route::view('calculate','demo'); // Route::get('calculateexpense/{id}',[ExpenseController::class,'calculate']); // Route::get('editexpense/{id}',[ExpenseController::class,'edit']); // Route::post('editexpense/{id}',[ExpenseController::class,'update']); // Route::view("ulogin","ulogin"); // Route::view("home","home"); // //Route::get("ulogin",[LoginController::class,'login']); // Route::post("ulogin",[LoginController::class,'authenticate']); // //Route::view('userdashbord','userdashbord'); // Route::get("logout",[LoginController::class,'logout']); // Route::get('userdashbord',[UserController::class,'dashbord']); // // Route::group(['middleware'=>['AuthCheck']],function() // // { // // Route::get('userdashbord',[UserController::class,'dashbord']); // // // Route::get("ulogin",[LoginController::class,'login']); // // Route::view("createuser","createuser"); // // } // // ); // Route::get('userdashbord',[UserController::class,'dashbord']); Route::group(['middleware'=>"web"],function(){ Route::get('/', function () { return view('ulogin'); }); Route::post("users",[Registeruser::class,'uregistration']); Route::view("registration","users"); //Route::post("login",[Loginuser::class,'ulogin']); Route::get("category",[CategoryController::class,'getData']); //Route::post("expense",[Expense::class,'expenses']); Route::view("expenseuser","expense"); //Route::view("userlist","userlist"); Route::view("createuser","createuser"); Route::post("createuser",[UserController::class,'store']); Route::get('edituser/{id}',[UserController::class,'edit']); Route::post('edituser/{id}',[UserController::class,'update']); Route::get("deleteuser/{id}",[UserController::class,'delete']); Route::get("search",[UserController::class,'search']); Route::get("searchexpenseuser",[UserController::class,'searchu']); Route::get("userprofile",[UserController::class,'profile']); Route::get('categorylist',[CategoryController::class,'list']); Route::view('createcategory','createcategory'); Route::post('createcategory',[CategoryController::class,'store']); Route::get("deletecategory/{id}",[CategoryController::class,'delete']); Route::get('editcategory/{id}',[CategoryController::class,'edit']); Route::post('editcategory/{id}',[CategoryController::class,'update']); Route::get("searchcategory",[CategoryController::class,'search']); Route::get('expenselist',[ExpenseController::class,'elist']); Route::get("createexpense",[ExpenseController::class,'show']); Route::post('createexpense',[ExpenseController::class,'store']); Route::view('calculate','demo'); Route::get('calculateexpense/{id}',[ExpenseController::class,'calculate']); Route::get('editexpense/{id}',[ExpenseController::class,'edit']); Route::post('editexpense/{id}',[ExpenseController::class,'update']); Route::get("searchexpense",[ExpenseController::class,'search']); Route::get("searchexpenses",[ExpenseController::class,'searche']); Route::view("ulogin","ulogin"); //Route::view("home","home"); Route::get("home",[UserController::class,'mexpense']); //Route::get("ulogin",[LoginController::class,'login']); Route::post("ulogin",[LoginController::class,'authenticate']); //Route::view('userdashbord','userdashbord'); Route::get("logout",[LoginController::class,'logout']); Route::get('userdashbord',[UserController::class,'dashbord']); // Route::group(['middleware'=>['AuthCheck']],function() // { // Route::get('userdashbord',[UserController::class,'dashbord']); // // Route::get("ulogin",[LoginController::class,'login']); // Route::view("createuser","createuser"); // } // ); Route::get('userdashbord',[UserController::class,'dashbord']); Route::get("deleteex/{id}",[UserController::class,'expensedelete']); // Route::view('admindashbord','admindashbord'); Route::get('admindashbord',[UserController::class,'count']); Route::get('alogout',[LoginController::class,'alogout']); Route::get('userlist',[UserController::class,'ulist']); Route::view('adminprof','adminprof'); Route::get('editperuser/{id}',[LoginController::class,'edit']); Route::post('editperuser/{id}',[LoginController::class,'update']); //Route::view('editperuser','editperuser'); Route::get('pppp',[LoginController::class,'pppp']); }); // Route::view('admindashbord','admindashbord'); // Route::get('admindashbord',[UserController::class,'count']); // Route::get('alogout',[LoginController::class,'alogout']); // Route::get('userlist',[UserController::class,'ulist']);
php
18
0.65062
79
40.053892
167
starcoderdata
const { model, Schema } = require("mongoose"); const ObjectId = require("mongoose").ObjectId; module.exports.cartSchema = new Schema( { userId: ObjectId, sessionID: String, token: String, status: Number, firstName: String, middleName: String, lastName: String, mobile: String, email: String, line1: String, line2: String, city: String, province: String, country: String, content: String, }, { timestamps: true } ); module.exports.cartModel = model("cart", this.cartSchema);
javascript
6
0.605572
73
25.230769
26
starcoderdata
package wrappers type AbsolutePathWrappers struct { PathWrappers } func (a *AbsolutePathWrappers) initialise( absolutePathString string) { a.PathWrappers.Initialise(absolutePathString) } func (a *AbsolutePathWrappers) AbsolutePathString() string { absolutePathString := a.PathString() return absolutePathString } func (a *AbsolutePathWrappers) AbsoluteLevel() int { absoluteLevel := a.Level() return absoluteLevel }
go
7
0.789144
60
16.740741
27
starcoderdata
namespace Fluxera.Extensions.Hosting.Modules.Caching { using JetBrains.Annotations; using Microsoft.Extensions.Caching.Distributed; /// /// The options for the caching module. /// [PublicAPI] public sealed class CachingOptions { /// /// Creates a new instance of the <see cref="CachingOptions" /> type. /// public CachingOptions() { this.DistributedCache = new DistributedCacheEntryOptions(); } /// /// Gets or sets the distributed cache options. /// public DistributedCacheEntryOptions DistributedCache { get; set; } } }
c#
11
0.691456
75
24.28
25
starcoderdata
package impl import ( "context" "database/sql" "fmt" "github.com/ericyaoxr/cmdb/app/bill" ) func (s *service) save(ctx context.Context, ins *bill.Bill) error { var ( stmt *sql.Stmt err error ) // 开启一个事务 tx, err := s.db.BeginTx(ctx, nil) if err != nil { return err } // 执行结果提交或者回滚事务 // 当使用sql.Tx的操作方式操作数据后,需要我们使用sql.Tx的Commit()方法显式地提交事务, // 如果出错,则可以使用sql.Tx中的Rollback()方法回滚事务,保持数据的一致性 defer func() { if err != nil { tx.Rollback() return } }() // 避免SQL注入, 请使用Prepare stmt, err = tx.Prepare(insertBillSQL) if err != nil { return err } defer stmt.Close() app := ins _, err = stmt.Exec( &app.Vendor, &app.Month, &app.OwnerId, &app.OwnerName, &app.ProductType, &app.ProductCode, &app.ProductDetail, &app.PayMode, &app.PayModeDetail, &app.OrderId, &app.InstanceId, &app.InstanceName, &app.PublicIp, &app.PrivateIp, &app.InstanceConfig, &app.RegionCode, &app.RegionName, &app.SalePrice, &app.SaveCost, &app.RealCost, &app.CreditPay, &app.VoucherPay, &app.CashPay, &app.StoredcardPay, &app.OutstandingAmount, ) if err != nil { return fmt.Errorf("save bill resource info error, %s", err) } return tx.Commit() }
go
12
0.682125
224
22.254902
51
starcoderdata
package com.ssafy.wine.service; import java.util.List; import com.ssafy.wine.dto.UserDto; import com.ssafy.wine.entity.Follow; public interface FollowService { public Follow create(Long fromUid, Long toUid); public List findByFollowing(Long fromUid); public List findByFollower(Long toUid); public void delete(Long fromUid, Long toUid); }
java
6
0.777778
52
19.5
18
starcoderdata
import * as Actions from '../actions/Actions'; let instance = null; let SINGLETON_ENFORCER = Symbol(); export default class StationData{ constructor(enforcer){ if (enforcer !== SINGLETON_ENFORCER){ throw new Error("Use StationData.getInstance()"); } this.stationData = { "6XyY86QOPPrYVGvF9ch6wz" : { id: "6XyY86QOPPrYVGvF9ch6wz", name: " image: "https://i.scdn.co/image/441d13790c1da86b7f869ff42ef7828faa8d3f87" }, "7rEIUw67hRTgievwuKQGSj" : { id: "7rEIUw67hRTgievwuKQGSj", name: "Manga", image: "https://i.scdn.co/image/4acc9117c6704523d299cc7eea99522246bfc103" }, "0L8ExT028jH3ddEcZwqJJ5" : { id: "0L8ExT028jH3ddEcZwqJJ5", name: "Red Hot Chili Peppers", image: "https://i.scdn.co/image/5b2072e522bf3324019a8c2dc3db20116dff0b87" } } this.activeStation = "6XyY86QOPPrYVGvF9ch6wz"; } requestStationData(){ $.ajax({ type: "GET", url: "https://api.spotify.com/v1/artists/" + this.getStationID() + "/top-tracks", data: "country=GB", success: (response) => { Actions.update(response); }, error: (XMLHttpRequest, textStatus, errorThrown) => { console.log("Status: " + textStatus); console.log("Error: " + errorThrown); } }); } getStationData(){ return this.stationData[this.activeStation]; } getStationID(){ return this.stationData[this.activeStation].id; } getStationName(){ return this.stationData[this.activeStation].name; } getStationImage(){ return this.stationData[this.activeStation].image; } switchStation(id){ this.activeStation = id; this.requestStationData(); } getInactiveStations(){ let inactiveStations = Object.assign({}, this.stationData); delete inactiveStations[this.activeStation]; return inactiveStations; } static getInstance(){ if (!instance){ instance = new StationData(SINGLETON_ENFORCER); } return instance; } }
javascript
18
0.568142
93
26.759036
83
starcoderdata
void CMergedMeshesManager::AddProjectile(const SProjectile& projectile) { WriteLock _lock(m_ProjectileLock); // Skip already added entities and only add till end if (m_Projectiles.size() >= MaxProjectiles) { return; } m_Projectiles.push_back(projectile); }
c++
8
0.694444
71
27.9
10
inline
<?php /** * Created by PhpStorm. * User: levsemin * Date: 07.07.2018 * Time: 1:52 */ namespace Darvin\PaymentBundle\UrlBuilder; use Darvin\PaymentBundle\Entity\PaymentInterface; /** * Interface PaymentUrlBuilderInterface * @package Darvin\PaymentBundle\UrlBuilder */ interface PaymentUrlBuilderInterface { /** * @param PaymentInterface $payment * @param null|string $gateway * * @return string */ public function getAuthorizationUrl(PaymentInterface $payment, $gateway = null); /** * @param PaymentInterface $payment * @param null|string $gateway * * @return string */ public function getCaptureUrl(PaymentInterface $payment, $gateway = null); /** * @param PaymentInterface $payment * @param null|string $gateway * * @return string */ public function getPurchaseUrl(PaymentInterface $payment, $gateway = null); /** * @param PaymentInterface $payment * @param null|string $gateway * * @param string $action * * @return string */ public function getSuccessUrl(PaymentInterface $payment, $gateway = null, $action = 'purchase'); /** * @param PaymentInterface $payment * @param null|string $gateway * * @param string $action * * @return string */ public function getCanceledUrl(PaymentInterface $payment, $gateway = null, $action = 'purchase'); /** * @param PaymentInterface $payment * @param null|string $gateway * * @param string $action * * @return string */ public function getFailedUrl(PaymentInterface $payment, $gateway = null, $action = 'purchase'); /** * @param PaymentInterface $payment * @param null|string $gateway * * @return string */ public function getRefundUrl(PaymentInterface $payment, $gateway = null); /** * @param PaymentInterface $payment * @param null|string $gateway * * @return string */ public function getNotifyUrl(PaymentInterface $payment, $gateway = null); }
php
8
0.609599
101
23.359551
89
starcoderdata
def countAccessPoint(self, filename, scan_time, location): ap_bssid = dict() scan_time = scan_time[:-4] rssi_sum = 0 rssi_count = 0 with open("data/" + filename) as f: for line in f: ssid = "" bssid = "" regex = r'(.*) ([a-z|0-9]{2}:[a-z|0-9]{2}:[a-z|0-9]{2}:[a-z|0-9]{2}:[a-z|0-9]{2}:[a-z|0-9]{2}) (-[0-9]* )' # get the bssid matches = re.search(regex, line) if matches: bssid = matches.group(2) # get the ssid (name) matches = re.match(regex, line) if matches: ssid = matches.group(1).strip() # append that to the list # beware of doubled mac addresses if bssid and ssid: # check if already in a list if bssid not in ap_bssid: ap_bssid[bssid] = ssid # get the rssi # the pattern: # [:e8 ]-85[ 136] regex = r':[a-z|0-9]{2}\s\-[0-9]+\s' matches = re.findall(regex, line) # get the snr if matches: current_rssi = int(matches[0][4:]) rssi_sum += current_rssi rssi_count += 1 else: continue if location not in self.access_point: # new record self.access_point[location] = {'total': ap_bssid, 'timely': [len(ap_bssid)]} else: self.access_point[location]['total'].update(ap_bssid) self.access_point[location]['timely'].append(len(ap_bssid)) # count the average snr if location not in self.rssi: # new record self.rssi[location] = [rssi_sum/rssi_count] else: self.rssi[location].append(rssi_sum/rssi_count)
python
15
0.588911
110
25.428571
56
inline
// Copyright eeGeo Ltd (2012-2015), All Rights Reserved #pragma once #include #include #include #include "Search.h" #include "SearchQuery.h" #include "SearchResultModel.h" #include "SearchServiceBase.h" #include "ICallback.h" #include "TagSearchModel.h" #include "Interiors.h" namespace ExampleApp { namespace Search { namespace Combined { namespace SdkModel { class CombinedSearchService : public Search::SdkModel::SearchServiceBase { public: CombinedSearchService(const std::map<std::string, Search::SdkModel::ISearchService*>& searchServices, Eegeo::Resources::Interiors::InteriorInteractionModel& interiorInteractionModel); ~CombinedSearchService(); bool CanHandleTag(const std::string& tag) const; void CancelInFlightQueries(); void PerformLocationQuerySearch(const Search::SdkModel::SearchQuery& query); void PerformIdentitySearch(const Search::SdkModel::SearchResultModel& outdatedSearchResult, Eegeo::Helpers::ICallback1<const Search::SdkModel::IdentitySearchCallbackData&>& callback); private: void OnSearchResponseRecieved(const bool& didSucceed, const Search::SdkModel::SearchQuery& query, const std::vector results); bool CanPerformLocationQuerySearch(const Search::SdkModel::SearchQuery& query, const Search::SdkModel::ISearchService& searchService) const; private: std::map m_searchServices; Eegeo::Helpers::TCallback3<CombinedSearchService, const bool&, const Search::SdkModel::SearchQuery&, const std::vector m_searchQueryResponseCallback; int m_pendingResultsLeft; std::vector m_combinedResults; Search::SdkModel::SearchQuery m_currentQueryModel; Eegeo::Resources::Interiors::InteriorInteractionModel& m_interiorInteractionModel; bool m_hasActiveQuery; }; } } } }
c
18
0.544974
183
40.086957
69
starcoderdata
package i2.act.packrat.cst.metrics; import i2.act.packrat.cst.Node; import i2.act.packrat.cst.TerminalNode; import i2.act.packrat.cst.visitors.SyntaxTreeVisitor; import i2.act.packrat.nfa.NFA; import i2.act.peg.ast.Grammar; import i2.act.peg.ast.LexerProduction; import i2.act.peg.symbols.LexerSymbol; import java.util.HashSet; import java.util.List; import java.util.Locale; import java.util.Set; public final class Halstead { public static final String ANNOTATION_OPERAND = "operand"; public static final String ANNOTATION_OPERATOR = "operator"; public static final class Result { private final int numberOfDistinctOperands; private final int numberOfDistinctOperators; private final int vocabulary; private final int numberOfOperands; private final int numberOfOperators; private final int length; private final double estimatedLength; private final double volume; private final double difficulty; private final double effort; private final double codingTime; private final double deliveredBugs; public Result(final int numberOfDistinctOperands, final int numberOfDistinctOperators, final int numberOfOperands, final int numberOfOperators) { this.numberOfDistinctOperands = numberOfDistinctOperands; this.numberOfDistinctOperators = numberOfDistinctOperators; this.numberOfOperands = numberOfOperands; this.numberOfOperators = numberOfOperators; this.vocabulary = numberOfDistinctOperands + numberOfDistinctOperators; this.length = numberOfOperands + numberOfOperators; this.estimatedLength = numberOfDistinctOperands * log2(numberOfDistinctOperands) + numberOfDistinctOperators * log2(numberOfDistinctOperators); this.volume = this.length * log2(this.vocabulary); this.difficulty = (numberOfDistinctOperators / 2.0) * (((double) numberOfOperands) / numberOfDistinctOperands); this.effort = this.difficulty * this.volume; this.codingTime = this.effort / 18.0; this.deliveredBugs = Math.pow(this.effort, 2.0 / 3.0) / 3000.0; } @Override public final String toString() { final StringBuilder builder = new StringBuilder(); builder.append("{\n"); builder.append( String.format(" \"distinct operands\": %d,\n", this.numberOfDistinctOperands)); builder.append( String.format(" \"distinct operators\": %d,\n", this.numberOfDistinctOperators)); builder.append(String.format(" \"vocabulary\": %d,\n", this.vocabulary)); builder.append(String.format(" \"operands\": %d,\n", this.numberOfOperands)); builder.append(String.format(" \"operators\": %d,\n", this.numberOfOperators)); builder.append(String.format(" \"length\": %d,\n", this.length)); builder.append( String.format(Locale.US," \"estimated length\": %.2f,\n", this.estimatedLength)); builder.append(String.format(Locale.US, " \"volume\": %.2f,\n", this.volume)); builder.append(String.format(Locale.US, " \"difficulty\": %.2f,\n", this.difficulty)); builder.append(String.format(Locale.US, " \"effort\": %.2f,\n", this.effort)); builder.append(String.format(Locale.US, " \"coding time\": %.2f,\n", this.codingTime)); builder.append(String.format(Locale.US, " \"bugs\": %.2f\n", this.deliveredBugs)); builder.append("}"); return builder.toString(); } } public static final Result compute(final Node program, final Grammar grammar) { final Set operandSymbols = new HashSet<>(); final Set operatorSymbols = new HashSet<>(); final List lexerProductions = grammar.getLexerProductions(); for (final LexerProduction lexerProduction : lexerProductions) { final LexerSymbol symbol = lexerProduction.getSymbol(); assert (symbol != null); if (isOperand(lexerProduction)) { operandSymbols.add(symbol); } else { assert (isOperator(lexerProduction)); operatorSymbols.add(symbol); } } final Set distinctOperands = new HashSet<>(); final Set distinctOperators = new HashSet<>(); final int[] numberOfOperandsContainer = {0}; final int[] numberOfOperatorsContainer = {0}; program.accept(new SyntaxTreeVisitor<Void, Void>() { @Override public final Void visit(final TerminalNode terminalNode, final Void parameter) { final LexerSymbol symbol = terminalNode.getSymbol(); assert (symbol != null); if (operandSymbols.contains(symbol)) { final String terminalValue = terminalNode.getToken().getValue(); distinctOperands.add(terminalValue); ++numberOfOperandsContainer[0]; } else if (operatorSymbols.contains(symbol)) { distinctOperators.add(symbol); ++numberOfOperatorsContainer[0]; } return null; } }, null); final int numberOfDistinctOperands = distinctOperands.size(); final int numberOfDistinctOperators = distinctOperators.size(); final int numberOfOperands = numberOfOperandsContainer[0]; final int numberOfOperators = numberOfOperatorsContainer[0]; final Result result = new Result(numberOfDistinctOperands, numberOfDistinctOperators, numberOfOperands, numberOfOperators); return result; } private static final boolean isOperand(final LexerProduction lexerProduction) { if (lexerProduction.hasAnnotation(ANNOTATION_OPERAND)) { return true; } if (lexerProduction.hasAnnotation(ANNOTATION_OPERATOR)) { return false; } // if there is no manual annotation, we assume that a terminal is an operand if its regular // expression is not just a literal string return !NFA.fromRegularExpression(lexerProduction.getRegularExpression()).hasLiteralString(); } private static final boolean isOperator(final LexerProduction lexerProduction) { return !isOperand(lexerProduction); } private static final double log2(final double value) { return Math.log(value) / Math.log(2); } }
java
19
0.694584
97
32.432432
185
starcoderdata
static rt_err_t miniStm32_camera_unit_init( struct miniStm32_camera_unit_init_struct *init) { rt_device_t device; struct miniStm32_camera_device *cam; do { device = &(init->unit)->device; cam = &(init->unit)->camera; /* Find SCCB device */ cam->sccb = rt_device_find(CAMERA_USING_DEVICE_NAME); if (cam->sccb == RT_NULL) { camera_debug("CAM err: Can't find device %s!\n", CAMERA_USING_DEVICE_NAME); break; } camera_debug("CAM: Find device %s\n", CAMERA_USING_DEVICE_NAME); cam->counter = 0; cam->number = init->number; cam->status = 0; cam->reply = RT_NULL; /* Register camera device */ device->type = RT_Device_Class_Graphic; device->init = miniStm32_camera_init; device->open = miniStm32_camera_open; device->close = miniStm32_camera_close; device->read = RT_NULL; device->write = RT_NULL; device->control = miniStm32_camera_control; device->user_data = (void *)cam; return rt_device_register(device, CAMERA_DEVICE_NAME,RT_DEVICE_FLAG_RDWR); } while (0); return -RT_ERROR; }
c
11
0.507681
82
32.365854
41
inline
#pragma once #include "Component.h" #include "../../utils/Math.h" namespace thomas { namespace object { namespace component { class THOMAS_API Transform: public Component { private: void Decompose(); void UpdateLocalMatrix(); public: Transform(); math::Vector3 Forward(); math::Vector3 Up(); math::Vector3 Right(); math::Matrix GetLocalWorldMatrix(); void SetLocalMatrix(math::Matrix matrix); math::Matrix GetWorldMatrix(); math::Matrix SetWorldMatrix(math::Matrix matrix); void LookAt(Transform* target); void LookAt(math::Vector3 target); void Rotate(math::Vector3 angles); void Rotate(float x, float y, float z); void RotateByAxis(math::Vector3 axis, float angle); void Translate(math::Vector3 translation); void Translate(float x, float y, float z); math::Vector3 GetPosition(); math::Quaternion GetRotation(); math::Vector3 GetEulerAngles(); math::Vector3 GetScale(); void SetPosition(math::Vector3 position); void SetPosition(float x, float y, float z); void SetRotation(math::Quaternion rotation); void SetRotation(float yaw, float pitch, float roll); void SetScale(math::Vector3 scale); void SetScale(float x, float y, float z); void SetScale(float scale); void SetLocalPosition(math::Vector3 position); void SetLocalPosition(float x, float y, float z); void SetLocalRotation(math::Quaternion rotation); void SetLocalRotation(float yaw, float pitch, float roll); void SetLocalScale(math::Vector3 scale); void SetLocalScale(float x, float y, float z); void SetLocalScale(float scale); math::Vector3 GetLocalPosition(); math::Quaternion GetLocalRotation(); math::Vector3 GetLocalEulerAngles(); math::Vector3 GetLocalScale(); //void UpdateChildren(); void SetParent(Transform* parent); Transform* GetParent(); std::vector GetChildren(); void RemoveParent(); void OnDestroy(); void SetDirty(bool dirty); bool IsDirty(); private: bool m_dirty; Transform* m_parent; math::Vector3 m_localEulerAngles; math::Quaternion m_localRotation; math::Vector3 m_localPosition; math::Vector3 m_localScale; math::Matrix m_localWorldMatrix; std::vector m_children; }; } } }
c
14
0.685807
106
25.891304
92
starcoderdata
package cn.jiguang.imui.messages; import android.content.Context; import android.support.annotation.Nullable; import android.support.v7.widget.DefaultItemAnimator; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.SimpleItemAnimator; import android.util.AttributeSet; import android.view.GestureDetector; import android.view.MotionEvent; import cn.jiguang.imui.commons.models.IMessage; public class MessageList extends RecyclerView implements GestureDetector.OnGestureListener { private Context mContext; private MessageListStyle mMsgListStyle; private final GestureDetector mGestureDetector; private MsgListAdapter mAdapter; public MessageList(Context context) { this(context, null); } public MessageList(Context context, @Nullable AttributeSet attrs) { this(context, attrs, 0); } public MessageList(Context context, @Nullable AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); parseStyle(context, attrs); mGestureDetector = new GestureDetector(context, this); } @SuppressWarnings("ResourceType") private void parseStyle(Context context, AttributeSet attrs) { mContext = context; mMsgListStyle = MessageListStyle.parse(context, attrs); } /** * Set adapter for MessageList. * * @param adapter Adapter, extends MsgListAdapter. * @param Message model extends IMessage. */ public <MESSAGE extends IMessage> void setAdapter(MsgListAdapter adapter) { mAdapter = adapter; SimpleItemAnimator itemAnimator = new DefaultItemAnimator(); itemAnimator.setSupportsChangeAnimations(false); setItemAnimator(itemAnimator); LinearLayoutManager layoutManager = new LinearLayoutManager( getContext(), LinearLayoutManager.VERTICAL, true); layoutManager.setStackFromEnd(true); setLayoutManager(layoutManager); adapter.setLayoutManager(layoutManager); adapter.setStyle(mContext, mMsgListStyle); addOnScrollListener(new ScrollMoreListener(layoutManager, adapter)); super.setAdapter(adapter); } public void setSendBubbleDrawable(int resId) { mMsgListStyle.setSendBubbleDrawable(resId); } public void setSendBubbleColor(int color) { mMsgListStyle.setSendBubbleColor(color); } public void setSendBubblePressedColor(int color) { mMsgListStyle.setSendBubblePressedColor(color); } public void setSendBubbleTextSize(int size) { mMsgListStyle.setSendBubbleTextSize(size); } public void setSendBubbleTextColor(int color) { mMsgListStyle.setSendBubbleTextColor(color); } public void setSendBubblePaddingLeft(int paddingLeft) { mMsgListStyle.setSendBubblePaddingLeft(paddingLeft); } public void setSendBubblePaddingTop(int paddingTop) { mMsgListStyle.setSendBubblePaddingTop(paddingTop); } public void setSendBubblePaddingRight(int paddingRight) { mMsgListStyle.setSendBubblePaddingRight(paddingRight); } public void setSendBubblePaddingBottom(int paddingBottom) { mMsgListStyle.setSendBubblePaddingBottom(paddingBottom); } public void setReceiveBubbleDrawable(int resId) { mMsgListStyle.setReceiveBubbleDrawable(resId); } public void setReceiveBubbleColor(int color) { mMsgListStyle.setReceiveBubbleColor(color); } public void setReceiveBubblePressedColor(int color) { mMsgListStyle.setReceiveBubblePressedColor(color); } public void setReceiveBubbleTextSize(int size) { mMsgListStyle.setReceiveBubbleTextSize(size); } public void setReceiveBubbleTextColor(int color) { mMsgListStyle.setReceiveBubbleTextColor(color); } public void setReceiveBubblePaddingLeft(int paddingLeft) { mMsgListStyle.setReceiveBubblePaddingLeft(paddingLeft); } public void setReceiveBubblePaddingTop(int paddingTop) { mMsgListStyle.setReceiveBubblePaddingTop(paddingTop); } public void setReceiveBubblePaddingRight(int paddingRight) { mMsgListStyle.setReceiveBubblePaddingRight(paddingRight); } public void setReceiveBubblePaddingBottom(int paddingBottom) { mMsgListStyle.setReceiveBubblePaddingBottom(paddingBottom); } public void setDateTextSize(int size) { mMsgListStyle.setDateTextSize(size); } public void setDateTextColor(int color) { mMsgListStyle.setDateTextColor(color); } public void setDatePadding(int padding) { mMsgListStyle.setDatePadding(padding); } public void setEventTextColor(int color) { mMsgListStyle.setEventTextColor(color); } public void setEventTextSize(int size) { mMsgListStyle.setEventTextSize(size); } public void setEventTextPadding(int padding) { mMsgListStyle.setEventTextPadding(padding); } public void setAvatarWidth(int width) { mMsgListStyle.setAvatarWidth(width); } public void setAvatarHeight(int height) { mMsgListStyle.setAvatarHeight(height); } public void setShowDisplayName(int showDisplayName) { mMsgListStyle.setShowDisplayName(showDisplayName); } public void setSendVoiceDrawable(int resId) { mMsgListStyle.setSendVoiceDrawable(resId); } public void setReceiveVoiceDrawable(int resId) { mMsgListStyle.setReceiveVoiceDrawable(resId); } public void setPlaySendVoiceAnim(int playSendVoiceAnim) { mMsgListStyle.setPlaySendVoiceAnim(playSendVoiceAnim); } public void setPlayReceiveVoiceAnim(int playReceiveVoiceAnim) { mMsgListStyle.setPlayReceiveVoiceAnim(playReceiveVoiceAnim); } public void setBubbleMaxWidth(float maxWidth) { mMsgListStyle.setBubbleMaxWidth(maxWidth); } public void setSendingProgressDrawable(String drawableName, String packageName) { int resId = getResources().getIdentifier(drawableName, "drawable", packageName); mMsgListStyle.setSendingProgressDrawable(getResources().getDrawable(resId)); } public void setSendingIndeterminateDrawable(String drawableName, String packageName) { int resId = getResources().getIdentifier(drawableName, "drawable", packageName); mMsgListStyle.setSendingIndeterminateDrawable(getResources().getDrawable(resId)); } @Override public boolean onDown(MotionEvent e) { return false; } @Override public void onShowPress(MotionEvent e) { } @Override public boolean onSingleTapUp(MotionEvent e) { return false; } @Override public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) { return false; } @Override public void onLongPress(MotionEvent e) { } @Override public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) { if (Math.abs(velocityY) > 4000) { mAdapter.setScrolling(true); } return false; } }
java
11
0.719585
95
29.485232
237
starcoderdata
package bio.singa.mathematics.graphs.parser; import bio.singa.mathematics.graphs.model.RegularNode; import bio.singa.mathematics.graphs.model.UndirectedEdge; import bio.singa.mathematics.graphs.model.UndirectedGraph; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.w3c.dom.Document; import org.w3c.dom.Element; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.OutputKeys; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import java.io.File; /** * This class contains a single static method to export a * Graph to a GraphML * file. * * @author cl */ public class GraphMLExportService { private static final Logger logger = LoggerFactory.getLogger(GraphMLExportService.class); /** * Exports a Graph to a GraphML file. * * @param graph The graph. * @param file The new target file. */ public static void exportGraph(UndirectedGraph graph, File file) { logger.info("Writing graph to file {}", file.getAbsolutePath()); try { DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = docFactory.newDocumentBuilder(); Document doc = docBuilder.newDocument(); // root element Element rootElement = doc.createElement("graphml"); doc.appendChild(rootElement); // x coordiante key Element keyXCoordinate = doc.createElement("key"); keyXCoordinate.setAttribute("id", "x"); keyXCoordinate.setAttribute("for", "node"); keyXCoordinate.setAttribute("attr.name", "xCoordinate"); keyXCoordinate.setAttribute("attr.type", "double"); rootElement.appendChild(keyXCoordinate); // y coordiante key Element keyYCoordinate = doc.createElement("key"); keyYCoordinate.setAttribute("id", "y"); keyYCoordinate.setAttribute("for", "node"); keyYCoordinate.setAttribute("attr.name", "yCoordinate"); keyYCoordinate.setAttribute("attr.type", "double"); rootElement.appendChild(keyYCoordinate); // Graph Element graphElement = doc.createElement("graph"); graphElement.setAttribute("id", "BioGraph"); graphElement.setAttribute("edgedefault", "undirected"); rootElement.appendChild(graphElement); // Nodes for (RegularNode node : graph.getNodes()) { Element nodeElement = doc.createElement("node"); nodeElement.setAttribute("id", String.valueOf(node.getIdentifier())); graphElement.appendChild(nodeElement); Element nodeX = doc.createElement("data"); nodeX.setAttribute("key", "x"); nodeX.appendChild(doc.createTextNode(String.valueOf(node.getPosition().getX()))); nodeElement.appendChild(nodeX); Element nodeY = doc.createElement("data"); nodeY.setAttribute("key", "y"); nodeY.appendChild(doc.createTextNode(String.valueOf(node.getPosition().getY()))); nodeElement.appendChild(nodeY); } // Edges for (UndirectedEdge edge : graph.getEdges()) { Element edgeElement = doc.createElement("edge"); edgeElement.setAttribute("id", String.valueOf(edge.getIdentifier())); edgeElement.setAttribute("source", String.valueOf(edge.getSource().getIdentifier())); edgeElement.setAttribute("target", String.valueOf(edge.getTarget().getIdentifier())); graphElement.appendChild(edgeElement); } // write the content into xml file TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2"); DOMSource source = new DOMSource(doc); StreamResult result = new StreamResult(file); // Output to console for testing // StreamResult result = new StreamResult(System.out); transformer.transform(source, result); } catch (ParserConfigurationException | TransformerException pce) { pce.printStackTrace(); } } }
java
19
0.650751
101
40.344828
116
starcoderdata
# Copyright 2017 # Modified by Sandia National Labs # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to 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. # from laikaboss.objectmodel import ExternalVars, ModuleObject, ScanError from laikaboss.si_module import SI_MODULE from laikaboss.util import laika_temp_dir from laikaboss import config import os import tempfile import getnetguids class META_DOTNET(SI_MODULE): def __init__(self): self.module_name = "META_DOTNET" def _run(self, scanObject, result, depth, args): moduleResult = [] guids = {} try: with laika_temp_dir() as temp_dir, tempfile.NamedTemporaryFile(dir=temp_dir) as temp_file_input: temp_file_input_name = temp_file_input.name temp_file_input.write(scanObject.buffer) temp_file_input.flush() # Get guids netguids = getnetguids.get_assembly_guids(temp_file_input_name) if netguids: if "typelib_id" in netguids: guids['Typelib_ID'] = netguids['typelib_id'] else: guids['Typelib_ID'] = "None" if "mvid" in netguids: guids['MVID'] = netguids['mvid'] else: guids['MVID'] = "None" # Only attach metadata if metadata exists if guids: scanObject.addMetadata(self.module_name, 'DotNet_GUIDs', guids) except ScanError: raise return moduleResult
python
18
0.679052
102
29.95
60
starcoderdata
<?php $type='TrueTypeUnicode'; $name='TamilSangamMN-Bold'; $desc=array('Ascent'=>750,'Descent'=>-250,'CapHeight'=>2,'Flags'=>32,'FontBBox'=>'[-44 -266 1961 795]','ItalicAngle'=>0,'StemV'=>120,'MissingWidth'=>600); $up=-153; $ut=20; $dw=600; $cw=array( 0=>0,32=>250,33=>184,34=>344,35=>734,36=>564,37=>844,38=>686,39=>165,40=>287, 41=>268,42=>478,43=>609,44=>203,45=>325,46=>193,47=>333,48=>560,49=>560,50=>560, 51=>560,52=>560,53=>560,54=>560,55=>560,56=>560,57=>560,58=>193,59=>203,60=>569, 61=>609,62=>569,63=>505,64=>787,65=>644,66=>592,67=>677,68=>660,69=>569,70=>541, 71=>705,72=>644,73=>194,74=>458,75=>620,76=>497,77=>745,78=>625,79=>711,80=>575, 81=>726,82=>585,83=>588,84=>572,85=>623,86=>593,87=>872,88=>580,89=>615,90=>581, 91=>224,92=>288,93=>203,94=>489,95=>585,96=>200,97=>527,98=>519,99=>513,100=>517, 101=>540,102=>315,103=>534,104=>509,105=>188,106=>184,107=>479,108=>183,109=>783,110=>503, 111=>542,112=>542,113=>532,114=>304,115=>474,116=>313,117=>498,118=>487,119=>706,120=>482, 121=>478,122=>489,123=>303,124=>181,125=>285,126=>618,8216=>200,8217=>200,8220=>394,8221=>394, 8226=>325,8211=>676,8212=>798,160=>300,169=>771,8729=>200,188=>818,189=>813,190=>853,2947=>695, 2949=>886,2950=>1048,2951=>921,2952=>639,2953=>929,2954=>1168,2958=>712,2959=>712,2960=>780,2962=>750, 2963=>750,2964=>1533,2965=>712,2969=>780,2970=>654,2972=>752,2974=>954,2975=>761,2979=>1229,2980=>694, 2984=>662,2985=>916,2986=>598,2990=>673,2991=>684,2992=>550,2993=>642,2994=>791,2995=>831,2996=>673, 2997=>731,2998=>832,2999=>924,3000=>983,3001=>1162,3006=>550,3007=>502,3008=>439,3009=>571,3010=>723, 3014=>744,3015=>636,3016=>947,3018=>1721,3019=>1610,3020=>1999,3021=>271,3024=>830,3031=>831,3046=>548, 3047=>635,3048=>636,3049=>606,3050=>612,3051=>738,3052=>822,3053=>643,3054=>850,3055=>834,3056=>709, 3057=>693,3058=>774,3059=>817,3060=>712,3061=>1424,3062=>733,3063=>1135,3064=>1252,3065=>730,3066=>1005, 8203=>0,8204=>0,8205=>0,8377=>615,9676=>526); $enc=''; $diff=''; $file='tamilsangammnb.z'; $ctg='tamilsangammnb.ctg.z'; $originalsize=283732; // --- EOF ---
php
6
0.658596
154
61.606061
33
starcoderdata
"""Exercício 11: Crie um algoritmo que execute os passos definidos na conjectura de Collatz, definidos abaixo: 1: Comece com um número n > 1 2: Encontre o número de Passos necessários pra chegar em 1 3: Se n é par, divida por 2 4: Se n é ímpar, multiplique por 3 e adicione 1 """ def conjectura_collatz(n: int): if n <= 1: return "O número deve ser maior que 1." passos = 0 while n > 1: if n % 2 == 0: # se o número é par n /= 2 else: n = n * 3 + 1 passos += 1 return passos print(conjectura_collatz(5))
python
12
0.620032
93
24.16
25
starcoderdata
/* * * Confidential Information of Telekinesys Research Limited (t/a Havok). Not for disclosure or distribution without Havok's * prior written consent. This software contains code, techniques and know-how which is confidential and proprietary to Havok. * Product and Trade Secret source code contains trade secrets of Havok. Havok Software (C) Copyright 1999-2013 Telekinesys Research Limited t/a Havok. All Rights Reserved. Use of this software is subject to the terms of an end user license agreement. * */ #ifndef HK_BASE_SORTED_TREE_H #define HK_BASE_SORTED_TREE_H /// Sorted tree base, declare default comparator. struct hkSortedTreeBase { HK_DECLARE_NONVIRTUAL_CLASS_ALLOCATOR(HK_MEMORY_CLASS_TREE, hkSortedTreeBase); // Default comparators. /// Values. struct CompareValues { template <typename T> static HK_FORCE_INLINE int compare(const T& a, const T& b) { return a < b ? -1 : (b < a ? 1 : 0); } }; /// Pointers. struct ComparePointers { template <typename T> static HK_FORCE_INLINE int compare(const T& a, const T& b) { return (*a) < (*b) ? -1 : ((*b) < (*a) ? 1 : 0); } }; /// PRNG. struct Prng { // KISS Based PRNG (http://www.cs.ucl.ac.uk/staff/d.jones/GoodPracticeRNG.pdf) HK_FORCE_INLINE Prng() { reset(); } HK_FORCE_INLINE void reset() { m_x=123456789; m_y=234567891; m_z=345678912; m_w=456789123; m_c=0; } HK_FORCE_INLINE hkUint32 nextUint32(); HK_FORCE_INLINE hkInt32 nextInt32() { return hkInt32(nextUint32() >> 1); } hkUint32 m_x, m_y, m_z, m_w, m_c; }; }; /// Sorted tree template. template <typename T, typename COMP = hkSortedTreeBase::CompareValues, typename INDEX = int, int GROWTH = 16> struct hkSortedTree : hkSortedTreeBase { HK_DECLARE_NONVIRTUAL_CLASS_ALLOCATOR(HK_MEMORY_CLASS_TREE, hkSortedTree); /// Tree node. struct Node { T m_value; ///< Node value. INDEX m_children[2]; ///< Node children. INDEX m_parent; ///< Node parent. }; /// Constructor. hkSortedTree(int numNodes = 0) { clear(numNodes); } /// Reset the tree. inline void clear(int numNodes = 0); /// Returns the number of used nodes. HK_FORCE_INLINE int getSize() const { return m_size; } /// Pre-allocate 'count' nodes. inline void preAllocateNodes(int count); /// Insert a new node. inline INDEX insert(const T& value); /// Update an existing node. inline void update(INDEX nodeIndex); /// Update an existing node. inline void update(INDEX nodeIndex, const T& newValue); /// Remove an existing node. inline void remove(INDEX nodeIndex); /// Optimize the tree by re-inserting 'count' nodes 'iterations' times. /// Note: If count is zero, all the nodes will be optimized. inline void optimize(int count = 0, int iterations = 1); /// Find a value. inline INDEX find(const T& value) const; /// Find a value. inline INDEX find(const T& value, INDEX& closest, int& iterations) const; /// Get tree root HK_FORCE_INLINE INDEX getRoot() const { return m_root; } /// Get node from index. HK_FORCE_INLINE const Node& getNode(INDEX index) const { return m_nodes[index]; } /// Get node value from index. HK_FORCE_INLINE const T& getValue(INDEX index) const { return getNode(index).m_value; } /// Get node value from index. HK_FORCE_INLINE T& getValue(INDEX index) { return m_nodes[index].m_value; } /// Get the node with the minimum value. inline INDEX getMin() const; /// Get the node with the maximum value. inline INDEX getMax() const; /// Get the first node. inline INDEX getFirst() const; /// Get the next node. inline INDEX getNext(INDEX nodeIndex) const; /// Traverse all node from min to max. template <typename FUNCTOR> inline void traverseMinMax(FUNCTOR& functor, INDEX root = 0) const; /// Traverse all node from max to min. template <typename FUNCTOR> inline void traverseMaxMin(FUNCTOR& functor, INDEX root = 0) const; // // Internals. // // inline void insertNode(INDEX nodeIndex); // inline void removeNode(INDEX nodeIndex); // inline bool checkIntegrity() const; hkArray m_nodes; ///< Nodes storage. int m_size; ///< Number of used nodes. INDEX m_root; ///< Tree root node. INDEX m_free; ///< First free node. Prng m_prng; ///< PRNG. }; #include #endif //HK_BASE_SORTED_TREE_H /* * Havok SDK - NO SOURCE PC DOWNLOAD, BUILD(#20130718) * * Confidential Information of Havok. (C) Copyright 1999-2013 * Telekinesys Research Limited t/a Havok. All Rights Reserved. The Havok * Logo, and the Havok buzzsaw logo are trademarks of Havok. Title, ownership * rights, and intellectual property rights in the Havok software remain in * Havok and/or its suppliers. * * Use of this software for evaluation purposes is subject to and indicates * acceptance of the End User licence Agreement for this product. A copy of * the license is included with this software and is also available at www.havok.com/tryhavok. * */
c
15
0.688322
251
30.257669
163
starcoderdata
import React, {Component} from 'react'; import {Platform, TextInput} from 'react-native'; export default class QIMTextInput extends Component { //解决iOS下不能输入中文的bug shouldComponentUpdate (nextProps){ return Platform.OS !== 'ios' || (this.props.value === nextProps.value && (nextProps.defaultValue == undefined || nextProps.defaultValue == '' )) || (this.props.defaultValue === nextProps.defaultValue && (nextProps.value == undefined || nextProps.value == '' )); } render() { return <TextInput {...this.props} />; } };
javascript
15
0.631034
128
31.277778
18
starcoderdata
// // Generated by class-dump 3.5 (64 bit). // // class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2013 by // #import #import "CHAutoStyling.h" @class NSString; __attribute__((visibility("hidden"))) @interface CHXAutoStyling : CHAutoStyling { BOOL __autoChartFillIsHollow; BOOL __autoChartStrokeIsHollow; } + (int)styleIdWithStyleRow:(int)arg1 styleColumn:(int)arg2; + (int)styleColumnWithStyleId:(int)arg1; + (int)styleRowWithStyleId:(int)arg1; + (id)colorWithSchemeColorId:(int)arg1 shade:(float)arg2; + (id)colorWithSchemeColorId:(int)arg1 tint:(float)arg2; + (id)colorWithSchemeColorId:(int)arg1 transformType:(int)arg2 transformValue:(float)arg3; @property BOOL _autoChartStrokeIsHollow; // @synthesize _autoChartStrokeIsHollow=__autoChartStrokeIsHollow; @property BOOL _autoChartFillIsHollow; // @synthesize _autoChartFillIsHollow=__autoChartFillIsHollow; - (void)setAutoChartStrokeIsHollow:(BOOL)arg1; - (void)setAutoChartFillIsHollow:(BOOL)arg1; - (void)resolveMarker:(id)arg1 withSeriesGraphicProperties:(id)arg2 forSeriesIndex:(unsigned long long)arg3 clientGraphicPropertyDefaults:(CDUnknownBlockType)arg4; - (void)resolveGraphicPropertiesOfErrorBar:(id)arg1 forSeriesIndex:(unsigned long long)arg2; - (void)resolveGraphicPropertiesOfTrendline:(id)arg1 forSeriesIndex:(unsigned long long)arg2; - (void)resolveGraphicPropertiesOfSeries:(id)arg1 forSeriesIndex:(unsigned long long)arg2 isLine:(_Bool)arg3; - (void)resolveGraphicPropertiesOfSeries:(id)arg1 forSeriesIndex:(unsigned long long)arg2; - (id)autoStrokeForSeriesIndex:(unsigned long long)arg1; - (id)autoTextFill; - (void)resolveLegendGraphicProperties:(id)arg1; - (void)resolveMinorGridLinesGraphicProperties:(id)arg1; - (void)resolveMajorGridLinesGraphicProperties:(id)arg1; - (void)resolveAxisGraphicProperties:(id)arg1; - (void)resolvePlotAreaGraphicProperties:(id)arg1; - (void)resolveFloorGraphicProperties:(id)arg1; - (void)resolveWallGraphicProperties:(id)arg1; - (void)resolveChartAreaGraphicProperties:(id)arg1; - (id)autoColorOfSeriesWithIndex:(unsigned long long)arg1; - (id)autoColorOfFirstColumnSeriesWithIndex:(unsigned long long)arg1 seriesCount:(unsigned long long)arg2; - (void)setDefaultErrorBarPropertiesInGraphicProperties:(id)arg1; - (unsigned int)autoFloorAndChartAreaStrokeIndex; - (unsigned int)autoFloorAndWallsFillIndex; - (id)autoFloorAndWallsAndPlotArea2DFillColor; - (id)autoChartAreaFillColor; - (id)autoOtherStrokeColor; - (id)autoChartAreaAndDataTableAndFloorStrokeColor; - (id)autoMinorGridColor; - (id)autoAxisAndMajorGridColor; - (int)styleColumn; - (int)styleRow; - (int)styleId; // Remaining properties @property(readonly, copy) NSString *debugDescription; @property(readonly, copy) NSString *description; @property(readonly) unsigned long long hash; @property(readonly) Class superclass; @end
c
7
0.801109
163
42.074627
67
starcoderdata
/* * Copyright (C) 2015-2019 Alibaba Group Holding Limited */ #include "ulog/ulog.h" #include "ulog_api.h" #include #include #include #include #include "k_api.h" #include "aos/cli.h" bool log_init = false; #ifdef AOS_COMP_CLI #ifdef ULOG_CONFIG_ASYNC __attribute__((weak)) void update_net_cli(const char cmd, const char* param) { /* Will be overwrite in session_udp, as this implement take effect only the UDP feature support, I don't like so many compile switcher in the code which result reader is not so comfortable, so weak attribute used here. */ } __attribute__((weak)) void fs_control_cli(const char cmd, const char* param) { /* Will be overwrite in session_fs */ } __attribute__((weak)) void on_show_ulog_file() { /* Will be overwrite in session_fs */ } static void cmd_cli_ulog(char *pwbuf, int blen, int argc, char *argv[]) { bool exit_loop = false; uint8_t session = 0xFF; uint8_t level = 0xFF; uint8_t i; if (argc == 2) { const char* option = argv[1]; switch (option[0]) { case 'f': on_show_ulog_file(); break; default: break; } } for (i = 1; i < argc && !exit_loop; i += 2) { const char* option = argv[i]; const char* param = argv[i + 1]; if (option != NULL && param != NULL && strlen(option) == 1) { switch (option[0]) { case 's':/* session */ session = strtoul(param, NULL, 10); break; case 'l':/* level */ level = strtoul(param, NULL, 10); break; case 'a':/* syslog watcher address */ update_net_cli(option[0], param); case 't':/* terminate record on fs */ fs_control_cli(option[0], param); break; default: /* unknown option */ exit_loop = true; break; } } else {/* unknown format */ break; } } if ((session < SESSION_CNT) && (level <= LOG_NONE)) { on_filter_level_change((SESSION_TYPE)session, level); } } #endif static void sync_log_cmd(char *buf, int len, int argc, char **argv) { if (argc < 2) { aos_cli_printf("stop filter level : %c\r\n", get_sync_stop_level()); return; }else if (argc == 2) { const char* option = argv[1]; switch (option[0]) { case 'F': case 'E': case 'W': case 'I': case 'D': case 'N': /* none stop filter, i.e. all pass */ on_sync_filter_level_change(option[0]); break; default: aos_cli_printf("unknown option %c, only support[fewidn]\r\n", option[0]); break; } } } static struct cli_command ulog_cmd[] = { { "loglevel","set sync log level",sync_log_cmd }, #ifdef ULOG_CONFIG_ASYNC { "ulog", "ulog [option param]",cmd_cli_ulog }, #endif }; #endif /* AOS_COMP_CLI */ void ulog_init(const char host_name[8]) { if (!log_init) { log_init_mutex(); #ifdef ULOG_CONFIG_ASYNC ulog_async_init(host_name); #endif #ifdef AOS_COMP_CLI aos_cli_register_commands(&ulog_cmd[0], sizeof(ulog_cmd) / sizeof(struct cli_command)); #endif log_init = true; } }
c
17
0.529102
100
23.077465
142
starcoderdata
/** * Will set the `flex-wrap` css rule based on the current component's props. * @typedef {object} Props * @property {boolean} wrap * @property {boolean} wrapReverse * @returns { T & Props) => string} */ const setWrap = () => ({ wrap, wrapReverse }) => { if (wrap) { return 'flex-wrap: wrap;' } else if (wrapReverse) { return 'flex-wrap: wrap-reverse;' } return 'flex-wrap: nowrap;' } export default setWrap
javascript
12
0.62754
76
23.611111
18
starcoderdata
/******************************************************************************* * NAME * vector_vminusv - vector minus vector * * SYNOPSIS * #include * * VECTOR vector_vminusv(VECTOR v1, VECTOR v2); * * DESCRIPTION * The vector_vminusv() function returns the resulted vector of v1 minus * v2. * * RETURN VALUE * The returned value is in VECTOR type. * * SEE ALSO * vector_vplusv, vector_vxv * * EXAMPLE * #include * ... * VECTOR v1, v2, v3; * ... * v3=vector_vminusv(v1, v2); * * AUTHOR * 05/28/2003 *******************************************************************************/ #include "mcce.h" VECTOR vector_vminusv(VECTOR v1, VECTOR v2) { VECTOR z; z.x = v1.x - v2.x; z.y = v1.y - v2.y; z.z = v1.z - v2.z; return z; }
c
7
0.430508
81
21.692308
39
starcoderdata
package ladder.models; import com.avaje.ebean.Model; import controllers.CommonConfig; import javax.persistence.Entity; import javax.persistence.Id; import java.util.Date; /** * Created by lengxia on 2018/11/23. */ @Entity public class DeviceInfo extends Model{ @Id public Integer id; public String IMEI; public Integer IPlocation_id; public Integer cellocation_id; public String device_name; public String maintenance_type; public String maintenance_nexttime; public String maintenance_remind; public String maintenance_lasttime; public String inspection_type; public String inspection_lasttime; public String inspection_nexttime; public String inspection_remind; public String install_date; public String install_addr; public String register; public String tagcolor; public String state; public String device_type; public String commond; public String delay; public Integer rssi; public Integer runtime_state; public Integer group_id; public Integer ladder_id; public static Finder<Integer, DeviceInfo> finder = new Finder<Integer, DeviceInfo>(CommonConfig.LADDER_SERVER,Integer.class,DeviceInfo.class){}; }
java
6
0.723817
105
17.681159
69
starcoderdata
void deleteReport(long id) throws ModelNotFoundException { Report report = getReportById(id); try { deleteModel(report); } catch (BadParametersException e) { log.severe(String.format("Error deleting report due it's null: %s", e.getMessage())); // todo: throw exception about error deleting report. } catch (BadOperationException e) { log.severe(String.format("Error deleting report due it doesn't exist by id (%d): %s.", id, e.getMessage())); } }
java
13
0.615242
120
48
11
inline
package de.bornemisza.ds.users.subscriber; import de.bornemisza.ds.users.subscriber.ChangeEmailRequestListener; import de.bornemisza.ds.users.subscriber.AbstractConfirmationMailListener; import java.io.IOException; import javax.mail.NoSuchProviderException; import javax.mail.internet.AddressException; import org.junit.Test; import com.hazelcast.core.HazelcastInstance; import de.bornemisza.ds.users.MailSender; public class ChangeEmailRequestListenerTest extends AbstractConfirmationMailListenerTestbase { @Override AbstractConfirmationMailListener getRequestListener(MailSender mailSender, HazelcastInstance hz) { return new ChangeEmailRequestListener(mailSender, hz); } @Override String getConfirmationLinkPrefix() { return "https://" + System.getProperty("FQDN") + "/generic.html?action=confirm&type=email&uuid="; } @Test public void onMessage_mailSent_styledTemplate() throws AddressException, NoSuchProviderException, IOException { onMessage_mailSent_styledTemplate_Base(); } @Test public void onMessage_mailNotSent() throws AddressException, NoSuchProviderException, IOException { onMessage_mailNotSent_Base(); } @Test public void onMessage_userExists_doNotSendAdditionalMail() throws AddressException, NoSuchProviderException { onMessage_userExists_doNotSendAdditionalMail_Base(); } @Test public void onMessage_uuidExists_doNotSendAdditionalMail_locked() throws AddressException, NoSuchProviderException { onMessage_uuidExists_doNotSendAdditionalMail_locked_Base(); } @Test public void onMessage_uuidExists_sendAdditionalMailIfAddressDifferent() throws AddressException, NoSuchProviderException { onMessage_uuidExists_sendAdditionalMail_Base(); } }
java
11
0.77649
126
33.188679
53
starcoderdata
const mongoose = require("mongoose"); const log = require('./logger'); const fs = require('fs'); const username = 'admin'; //const passwordOld = process.env.MONGODB_PW || ''; databaseName = 'ChefmateDB' //databaseName = 'ChefmateDB_Alt'; const host = '192.168.3.11'; //NEW DB //host = 'localhost' //host = '172.16.31.10' //OLD DB const port = 27017; var password = ' ' fs.readFile('../../Chefmate_auth/pw.txt', "utf8", (err, data) => { if(err) { console.log("Error getting Mongo password. Make sure Chefmate_auth/pw.txt exists and is populated."); } else { //Do *NOT* hardcode password, ever password = const mongoUri = 'mongodb://' + username + ":" + password.replace(/\n$/, "") + "@" + host + ":" + port + "/" + databaseName; mongoose .connect(mongoUri, { useNewUrlParser: true, useUnifiedTopology: true, dbName: databaseName }) .then(() => { log('info', "Connected to database"); }) .catch(err => { log('error', "Error: Not connected to database."); }); } }); const CrawlerSchema = new mongoose.Schema( { _id: { type: String, required: [true, "URL is required "] }, title: { type: String, required: [true, "Web Page title is required"] }, body: { type: String, required: [true, "Body of web page is required"] }, description: { type: String, required: [true, "Description is required."]}, hub: { type: Number, required: [true, "Hub is required"], default: 1 }, authority: { type: Number, required: [true, "Authority is required"], default: 1 }, pageRank: { type: Number, required: [true, "PageRank is required"], default: 1 }, tfidf: { type: {}, required: [true, 'Initial TFIDF is required. Default is {}'], default: {} } }, { timestamps: true } ); mongoose.model("Crawler", CrawlerSchema); const Crawler = mongoose.model("Crawler"); const UserSchema = new mongoose.Schema( { userid: { type: String, required: [true, "Identifier is required for user"], }, password: { type: String, // required: [true, "Password is required. Make sure it is hashed."] }, likes: { type: {}, required: [true, "Likes are required. Resort to default {}"], default: {} }, dislikes: { type: {}, required: [true, "Dislikes are required. Resort to default {}"], default: {} }, history: { type: [String], required: [true, "History required. Resort to default {}"], default: [] }, recent_queries: { type: [String], required: [true, "Recent Queries required. Resort to default {}"], default: [] } }, { timestamps: true } ); mongoose.model("User", UserSchema); const User = mongoose.model("User"); const InvertedIndexSchema = new mongoose.Schema( { term: { type: String, required: [true, "Term is required for InvertedIndex table"] }, doc_info: { type: [{ url: String, termCount: Number, pos: [Number] }], required: [ true, "Doc Info is required, resort to default [] if needed. {}" ], default: [] }, idf: { type: Number, default: 1, required: [true, "IDF is required, resort to default (1) if needed."] }, }, { timestamps: true } ); mongoose.model("InvertedIndex", InvertedIndexSchema); const InvertedIndex = mongoose.model("InvertedIndex"); const QuerySchema = new mongoose.Schema( { _id: { type: String, required: [true, "Query is required for Query object."], }, count: { type: Number, required: [ true, "Count is required for query term. Default is 1" ], default: 1 } }, { timestamps: true } ); mongoose.model("Query", QuerySchema); const Query = mongoose.model("Query") module.exports = { mongoose, Crawler, User, InvertedIndex, Query };
javascript
16
0.588175
128
27.028571
140
starcoderdata
/************************************************************************************ Implementation of Columnar Transposition Cypher Utility Functions Author: Email: GitHub: https://github.com/AKD92 *************************************************************************************/ #include #include #include #include #define BUFFERSIZE 10 #define cmp_char(c1, c2) ((*c1) - (*c2)) int util_convStringToInteger(const char *inputString, char endInputMark, List *integerList); int util_transformExtendedKey(unsigned int key, List *extendedKey); int util_convKeywordToExtendedKey(const char *keywordString, int keywordLen, List **extendedKey); int util_convStringToInteger(const char *inputString, char endInputMark, List *integerList) { register unsigned int globalInputIndex; register unsigned int bufferIndex; int intValue, *pInteger; register char digit; char tempBuffer[BUFFERSIZE]; int isDigit, isSpace, isEndReached, isBufferEmpty; int isIntegerAvailable; ListElem *elem_before; globalInputIndex = 0; bufferIndex = 0; list_init(integerList, free); memset((void*) tempBuffer, 0, BUFFERSIZE); LOOP_BEGIN: digit = *(inputString + globalInputIndex); isDigit = isdigit(digit) != 0 ? 1 : 0; isSpace = isspace(digit) != 0 ? 1 : 0; isEndReached = digit == endInputMark ? 1 : 0; isBufferEmpty = bufferIndex == 0 ? 1 : 0; isIntegerAvailable = (isSpace | isEndReached) & !(isBufferEmpty); if (isDigit == 1) { *(tempBuffer + bufferIndex) = digit; bufferIndex = bufferIndex + 1; } else if (isIntegerAvailable == 1) { intValue = (int) strtol((const char*) tempBuffer, 0, 10); pInteger = (int*) malloc(sizeof(int)); *pInteger = intValue; elem_before = list_tail(integerList); list_ins_next(integerList, elem_before, (const void*) pInteger); memset((void*) tempBuffer, 0, bufferIndex); bufferIndex = 0; pInteger = 0; } if (isEndReached == 1) goto LOOP_END; globalInputIndex = globalInputIndex + 1; goto LOOP_BEGIN; LOOP_END: return 0; } int util_transformExtendedKey(unsigned int key, List *extendedKey) { int *tempArray; int *pValue; register unsigned int index; ListElem *elem; if (key != list_size(extendedKey)) return -2; tempArray = (int*) malloc(sizeof(int) * key); if (tempArray == 0) return -1; index = 1; elem = list_head(extendedKey); while (elem != 0) { pValue = (int*) list_data(elem); *(tempArray + *pValue - 1) = (int) index; elem = list_next(elem); index = index + 1; } index = 0; elem = list_head(extendedKey); while (elem != 0) { pValue = (int*) list_data(elem); *pValue = *(tempArray + index); elem = list_next(elem); index = index + 1; } free((void*) tempArray); return 0; } int util_convKeywordToExtendedKey(const char *keywordString, int keywordLen, List **extendedKey) { List *keyList; ListElem *elem; register unsigned int outerIndex; register unsigned int innerIndex; const char *currentChar, *prevChar; int *newInt, *prevInt; int cmpResult; keyList = (List*) malloc(sizeof(List)); list_init(keyList, free); newInt = (int*) malloc(sizeof(int)); *newInt = 1; elem = list_tail(keyList); list_ins_next(keyList, elem, (const void*) newInt); outerIndex = 1; while (outerIndex < keywordLen) { currentChar = keywordString + outerIndex; newInt = (int*) malloc(sizeof(int)); *newInt = 1; innerIndex = 0; elem = list_head(keyList); while (innerIndex < outerIndex) { prevChar = keywordString + innerIndex; prevInt = (int*) list_data(elem); cmpResult = cmp_char(prevChar, currentChar); if (cmpResult > 0) *prevInt = *prevInt + 1; else *newInt = *newInt + 1; innerIndex = innerIndex + 1; elem = list_next(elem); } elem = list_tail(keyList); list_ins_next(keyList, elem, (const void*) newInt); outerIndex = outerIndex + 1; } *extendedKey = keyList; return 0; }
c
15
0.611898
98
20.183246
191
starcoderdata
// Copyright 2021 All Rights Reserved. // Released under a MIT (SEI)-style license. See LICENSE.md in the project root for license information. using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Metadata.Builders; using System.Text.Json.Serialization; namespace Player.Api.Data.Data.Models { public class ViewMembershipEntity { public ViewMembershipEntity() { } public ViewMembershipEntity(Guid viewId, Guid userId) { ViewId = viewId; UserId = userId; } [Key] [DatabaseGenerated(DatabaseGeneratedOption.Identity)] public Guid Id { get; set; } public Guid ViewId { get; set; } public virtual ViewEntity View { get; set; } public Guid UserId { get; set; } public virtual UserEntity User { get; set; } public Guid? PrimaryTeamMembershipId { get; set; } public virtual TeamMembershipEntity PrimaryTeamMembership { get; set; } public virtual ICollection TeamMemberships { get; set; } = new List } public class ViewMembershipConfiguration : IEntityTypeConfiguration { public void Configure(EntityTypeBuilder builder) { builder.HasIndex(e => new { e.ViewId, e.UserId }).IsUnique(); builder .HasOne(em => em.View) .WithMany(e => e.Memberships) .HasForeignKey(em => em.ViewId); builder .HasOne(em => em.User) .WithMany(u => u.ViewMemberships) .HasForeignKey(em => em.UserId) .HasPrincipalKey(u => u.Id); builder .HasOne(x => x.PrimaryTeamMembership); //.WithOne(y => y.ViewMembership) //.HasForeignKey => x.PrimaryTeamMembershipId); } } }
c#
20
0.632672
122
31.584615
65
starcoderdata
/* +-------------------------------------------------------------------------- | Mblog [#RELEASE_VERSION#] | ======================================== | Copyright (c) 2014, 2015 mtons. All Rights Reserved | http://www.mtons.com | +--------------------------------------------------------------------------- */ package mblog.core.persist.entity; import java.util.ArrayList; import java.util.Date; import java.util.List; import javax.persistence.*; import org.hibernate.annotations.Cache; import org.hibernate.annotations.CacheConcurrencyStrategy; /** * 用户信息 * * @author wangpeiguang * */ @Entity @Table(name = "mto_users") @Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE) public class UserPO { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private long id; @Column(name = "username", unique = true, length = 64) private String username; // 用户名 @Column(name = "password", length = 64) private String password; // 密码 private String avatar; // 头像 @Column(name = "name", length = 18) private String name; // 昵称 private int gender; // 性别 @Column(name = "email", unique = true, length = 128) private String email; // 邮箱 @Column(name = "mobile", length = 11) private String mobile; // 手机号 private int posts; // 文章数 private int comments; // 发布评论数 private int follows; // 关注人数 private int fans; // 粉丝数 private int favors; // 收到的喜欢数 private Date created; // 注册时间 private int source; // 注册来源:主要用于区别第三方登录 @Column(name = "last_login") private Date lastLogin; private String signature; // 个性签名 @ManyToMany(cascade = CascadeType.MERGE, fetch = FetchType.EAGER) @JoinTable(name = "mto_user_role", joinColumns = { @JoinColumn(name = "user_id") }, inverseJoinColumns = { @JoinColumn(name = "role_id") }) @Cache(usage = CacheConcurrencyStrategy.READ_WRITE) private List roles = new ArrayList<>(); @Column(name = "active_email") private int activeEmail; // 邮箱激活状态 private int status; // 用户状态 public UserPO() { } public UserPO(long id) { this.id = id; } public long getId() { return id; } public void setId(long id) { this.id = id; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getMobile() { return mobile; } public void setMobile(String mobile) { this.mobile = mobile; } public Date getCreated() { return created; } public void setCreated(Date created) { this.created = created; } public int getStatus() { return status; } public void setStatus(int status) { this.status = status; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Date getLastLogin() { return lastLogin; } public void setLastLogin(Date lastLogin) { this.lastLogin = lastLogin; } public String getAvatar() { return avatar; } public void setAvatar(String avatar) { this.avatar = avatar; } public int getGender() { return gender; } public void setGender(int gender) { this.gender = gender; } public List getRoles() { return roles; } public void setRoles(List roles) { this.roles = roles; } public int getSource() { return source; } public void setSource(int source) { this.source = source; } public int getActiveEmail() { return activeEmail; } public void setActiveEmail(int activeEmail) { this.activeEmail = activeEmail; } public int getPosts() { return posts; } public void setPosts(int posts) { this.posts = posts; } public int getComments() { return comments; } public void setComments(int comments) { this.comments = comments; } public int getFollows() { return follows; } public void setFollows(int follows) { this.follows = follows; } public int getFans() { return fans; } public void setFans(int fans) { this.fans = fans; } public int getFavors() { return favors; } public void setFavors(int favors) { this.favors = favors; } public String getSignature() { return signature; } public void setSignature(String signature) { this.signature = signature; } }
java
13
0.653342
140
16.712
250
starcoderdata
using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using Confuser.Core; using Confuser.Core.Helpers; using Confuser.Core.Services; using Confuser.Renamer; using dnlib.DotNet; using dnlib.DotNet.Emit; using dnlib.DotNet.Writer; namespace Confuser.Protections.Resources { internal class MDPhase { readonly REContext ctx; ByteArrayChunk encryptedResource; public MDPhase(REContext ctx) { this.ctx = ctx; } public void Hook() { ctx.Context.CurrentModuleWriterListener.OnWriterEvent += OnWriterEvent; } void OnWriterEvent(object sender, ModuleWriterListenerEventArgs e) { var writer = (ModuleWriterBase)sender; if (e.WriterEvent == ModuleWriterEvent.MDBeginAddResources) { ctx.Context.CheckCancellation(); ctx.Context.Logger.Debug("Encrypting resources..."); bool hasPacker = ctx.Context.Packer != null; List resources = ctx.Module.Resources.OfType if (!hasPacker) { ctx.Module.Resources.RemoveWhere(res => res is EmbeddedResource); } // move resources string asmName = ctx.Name.RandomName(RenameMode.Letters); PublicKey pubKey = null; if (writer.TheOptions.StrongNameKey != null) { pubKey = PublicKeyBase.CreatePublicKey(writer.TheOptions.StrongNameKey.PublicKey); } var module = new ModuleDefUser(asmName + ".dll", Guid.NewGuid(), ctx.Module.CorLibTypes.AssemblyRef); module.Kind = ModuleKind.Dll; var assembly = new AssemblyDefUser(asmName, new Version(1, 0), pubKey); assembly.Modules.Add(module); module.Characteristics = ctx.Module.Characteristics; module.Cor20HeaderFlags = ctx.Module.Cor20HeaderFlags; module.Cor20HeaderRuntimeVersion = ctx.Module.Cor20HeaderRuntimeVersion; module.DllCharacteristics = ctx.Module.DllCharacteristics; module.EncBaseId = ctx.Module.EncBaseId; module.EncId = ctx.Module.EncId; module.Generation = ctx.Module.Generation; module.Machine = ctx.Module.Machine; module.RuntimeVersion = ctx.Module.RuntimeVersion; module.TablesHeaderVersion = ctx.Module.TablesHeaderVersion; module.RuntimeVersion = ctx.Module.RuntimeVersion; var asmRef = new AssemblyRefUser(module.Assembly); if (pubKey == null) { asmRef.Attributes &= ~AssemblyAttributes.PublicKey; // ssdi: fix incorrect flags set in dnlib, "CS0009 .... -- Invalid public key." into VS2015, VS2017 msBuild } if (!hasPacker) { foreach (var res in resources) { res.Attributes = ManifestResourceAttributes.Public; module.Resources.Add(res); ctx.Module.Resources.Add(new AssemblyLinkedResource(res.Name, asmRef, res.Attributes)); } } byte[] moduleBuff; using (var ms = new MemoryStream()) { module.Write(ms, new ModuleWriterOptions(ctx.Module) { StrongNameKey = writer.TheOptions.StrongNameKey }); moduleBuff = ms.ToArray(); } // compress moduleBuff = ctx.Context.Registry.GetService moduleBuff, progress => ctx.Context.Logger.Progress((int)(progress * 10000), 10000)); ctx.Context.Logger.EndProgress(); ctx.Context.CheckCancellation(); uint compressedLen = (uint)(moduleBuff.Length + 3) / 4; compressedLen = (compressedLen + 0xfu) & ~0xfu; var compressedBuff = new uint[compressedLen]; Buffer.BlockCopy(moduleBuff, 0, compressedBuff, 0, moduleBuff.Length); Debug.Assert(compressedLen % 0x10 == 0); // encrypt uint keySeed = ctx.Random.NextUInt32() | 0x10; var key = new uint[0x10]; uint state = keySeed; for (int i = 0; i < 0x10; i++) { state ^= state >> 13; state ^= state << 25; state ^= state >> 27; key[i] = state; } var encryptedBuffer = new byte[compressedBuff.Length * 4]; int buffIndex = 0; while (buffIndex < compressedBuff.Length) { uint[] enc = ctx.ModeHandler.Encrypt(compressedBuff, buffIndex, key); for (int j = 0; j < 0x10; j++) key[j] ^= compressedBuff[buffIndex + j]; Buffer.BlockCopy(enc, 0, encryptedBuffer, buffIndex * 4, 0x40); buffIndex += 0x10; } Debug.Assert(buffIndex == compressedBuff.Length); var size = (uint)encryptedBuffer.Length; TablesHeap tblHeap = writer.MetaData.TablesHeap; tblHeap.ClassLayoutTable[writer.MetaData.GetClassLayoutRid(ctx.DataType)].ClassSize = size; tblHeap.FieldTable[writer.MetaData.GetRid(ctx.DataField)].Flags |= (ushort)FieldAttributes.HasFieldRVA; encryptedResource = writer.Constants.Add(new ByteArrayChunk(encryptedBuffer), 8); // inject key values MutationHelper.InjectKeys(ctx.InitMethod, new[] { 0, 1 }, new[] { (int)(size / 4), (int)(keySeed) }); } else if (e.WriterEvent == ModuleWriterEvent.EndCalculateRvasAndFileOffsets) { TablesHeap tblHeap = writer.MetaData.TablesHeap; tblHeap.FieldRVATable[writer.MetaData.GetFieldRVARid(ctx.DataField)].RVA = (uint)encryptedResource.RVA; } } } }
c#
21
0.662177
170
38.488889
135
starcoderdata
package net.minecraft.world.level.levelgen.feature; import com.google.common.cache.CacheBuilder; import com.google.common.cache.CacheLoader; import com.google.common.cache.LoadingCache; import com.google.common.collect.Lists; import com.mojang.serialization.Codec; import com.mojang.serialization.codecs.RecordCodecBuilder; import java.util.Collections; import java.util.List; import java.util.Random; import java.util.concurrent.TimeUnit; import java.util.stream.Collectors; import java.util.stream.IntStream; import net.minecraft.core.BlockPos; import net.minecraft.core.SectionPos; import net.minecraft.util.Mth; import net.minecraft.world.entity.EntityType; import net.minecraft.world.entity.boss.enderdragon.EndCrystal; import net.minecraft.world.level.ServerLevelAccessor; import net.minecraft.world.level.WorldGenLevel; import net.minecraft.world.level.block.Blocks; import net.minecraft.world.level.block.IronBarsBlock; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.dimension.DimensionType; import net.minecraft.world.level.levelgen.feature.configurations.SpikeConfiguration; import net.minecraft.world.phys.AABB; public class SpikeFeature extends Feature { public static final int NUMBER_OF_SPIKES = 10; private static final int SPIKE_DISTANCE = 42; private static final LoadingCache<Long, List SPIKE_CACHE = CacheBuilder.newBuilder().expireAfterWrite(5L, TimeUnit.MINUTES).build(new SpikeFeature.SpikeCacheLoader()); public SpikeFeature(Codec p_66852_) { super(p_66852_); } public static List getSpikesForLevel(WorldGenLevel p_66859_) { Random random = new Random(p_66859_.getSeed()); long i = random.nextLong() & 65535L; return SPIKE_CACHE.getUnchecked(i); } public boolean place(FeaturePlaceContext p_160372_) { SpikeConfiguration spikeconfiguration = p_160372_.config(); WorldGenLevel worldgenlevel = p_160372_.level(); Random random = p_160372_.random(); BlockPos blockpos = p_160372_.origin(); List list = spikeconfiguration.getSpikes(); if (list.isEmpty()) { list = getSpikesForLevel(worldgenlevel); } for(SpikeFeature.EndSpike spikefeature$endspike : list) { if (spikefeature$endspike.isCenterWithinChunk(blockpos)) { this.placeSpike(worldgenlevel, random, spikeconfiguration, spikefeature$endspike); } } return true; } private void placeSpike(ServerLevelAccessor p_66854_, Random p_66855_, SpikeConfiguration p_66856_, SpikeFeature.EndSpike p_66857_) { int i = p_66857_.getRadius(); for(BlockPos blockpos : BlockPos.betweenClosed(new BlockPos(p_66857_.getCenterX() - i, p_66854_.getMinBuildHeight(), p_66857_.getCenterZ() - i), new BlockPos(p_66857_.getCenterX() + i, p_66857_.getHeight() + 10, p_66857_.getCenterZ() + i))) { if (blockpos.distSqr((double)p_66857_.getCenterX(), (double)blockpos.getY(), (double)p_66857_.getCenterZ(), false) <= (double)(i * i + 1) && blockpos.getY() < p_66857_.getHeight()) { this.setBlock(p_66854_, blockpos, Blocks.OBSIDIAN.defaultBlockState()); } else if (blockpos.getY() > 65) { this.setBlock(p_66854_, blockpos, Blocks.AIR.defaultBlockState()); } } if (p_66857_.isGuarded()) { int j1 = -2; int k1 = 2; int j = 3; BlockPos.MutableBlockPos blockpos$mutableblockpos = new BlockPos.MutableBlockPos(); for(int k = -2; k <= 2; ++k) { for(int l = -2; l <= 2; ++l) { for(int i1 = 0; i1 <= 3; ++i1) { boolean flag = Mth.abs(k) == 2; boolean flag1 = Mth.abs(l) == 2; boolean flag2 = i1 == 3; if (flag || flag1 || flag2) { boolean flag3 = k == -2 || k == 2 || flag2; boolean flag4 = l == -2 || l == 2 || flag2; BlockState blockstate = Blocks.IRON_BARS.defaultBlockState().setValue(IronBarsBlock.NORTH, Boolean.valueOf(flag3 && l != -2)).setValue(IronBarsBlock.SOUTH, Boolean.valueOf(flag3 && l != 2)).setValue(IronBarsBlock.WEST, Boolean.valueOf(flag4 && k != -2)).setValue(IronBarsBlock.EAST, Boolean.valueOf(flag4 && k != 2)); this.setBlock(p_66854_, blockpos$mutableblockpos.set(p_66857_.getCenterX() + k, p_66857_.getHeight() + i1, p_66857_.getCenterZ() + l), blockstate); } } } } } EndCrystal endcrystal = EntityType.END_CRYSTAL.create(p_66854_.getLevel()); endcrystal.setBeamTarget(p_66856_.getCrystalBeamTarget()); endcrystal.setInvulnerable(p_66856_.isCrystalInvulnerable()); endcrystal.moveTo((double)p_66857_.getCenterX() + 0.5D, (double)(p_66857_.getHeight() + 1), (double)p_66857_.getCenterZ() + 0.5D, p_66855_.nextFloat() * 360.0F, 0.0F); p_66854_.addFreshEntity(endcrystal); this.setBlock(p_66854_, new BlockPos(p_66857_.getCenterX(), p_66857_.getHeight(), p_66857_.getCenterZ()), Blocks.BEDROCK.defaultBlockState()); } public static class EndSpike { public static final Codec CODEC = RecordCodecBuilder.create((p_66890_) -> { return p_66890_.group(Codec.INT.fieldOf("centerX").orElse(0).forGetter((p_160382_) -> { return p_160382_.centerX; }), Codec.INT.fieldOf("centerZ").orElse(0).forGetter((p_160380_) -> { return p_160380_.centerZ; }), Codec.INT.fieldOf("radius").orElse(0).forGetter((p_160378_) -> { return p_160378_.radius; }), Codec.INT.fieldOf("height").orElse(0).forGetter((p_160376_) -> { return p_160376_.height; }), Codec.BOOL.fieldOf("guarded").orElse(false).forGetter((p_160374_) -> { return p_160374_.guarded; })).apply(p_66890_, SpikeFeature.EndSpike::new); }); private final int centerX; private final int centerZ; private final int radius; private final int height; private final boolean guarded; private final AABB topBoundingBox; public EndSpike(int p_66881_, int p_66882_, int p_66883_, int p_66884_, boolean p_66885_) { this.centerX = p_66881_; this.centerZ = p_66882_; this.radius = p_66883_; this.height = p_66884_; this.guarded = p_66885_; this.topBoundingBox = new AABB((double)(p_66881_ - p_66883_), (double)DimensionType.MIN_Y, (double)(p_66882_ - p_66883_), (double)(p_66881_ + p_66883_), (double)DimensionType.MAX_Y, (double)(p_66882_ + p_66883_)); } public boolean isCenterWithinChunk(BlockPos p_66892_) { return SectionPos.blockToSectionCoord(p_66892_.getX()) == SectionPos.blockToSectionCoord(this.centerX) && SectionPos.blockToSectionCoord(p_66892_.getZ()) == SectionPos.blockToSectionCoord(this.centerZ); } public int getCenterX() { return this.centerX; } public int getCenterZ() { return this.centerZ; } public int getRadius() { return this.radius; } public int getHeight() { return this.height; } public boolean isGuarded() { return this.guarded; } public AABB getTopBoundingBox() { return this.topBoundingBox; } } static class SpikeCacheLoader extends CacheLoader<Long, List { public List load(Long p_66910_) { List list = IntStream.range(0, 10).boxed().collect(Collectors.toList()); Collections.shuffle(list, new Random(p_66910_)); List list1 = Lists.newArrayList(); for(int i = 0; i < 10; ++i) { int j = Mth.floor(42.0D * Math.cos(2.0D * (-Math.PI + (Math.PI / 10D) * (double)i))); int k = Mth.floor(42.0D * Math.sin(2.0D * (-Math.PI + (Math.PI / 10D) * (double)i))); int l = list.get(i); int i1 = 2 + l / 3; int j1 = 76 + l * 3; boolean flag = l == 1 || l == 2; list1.add(new SpikeFeature.EndSpike(j, k, i1, j1, flag)); } return list1; } } }
java
27
0.640269
338
44.546448
183
starcoderdata
"""Item constraint creation tests. The test check functionality of `Item.constraint` method, not constraints themselves. """ import pytest from gaphas.constraint import LineConstraint, EqualsConstraint, LessThanConstraint from gaphas.item import Item from gaphas.solver import Variable class ItemPosition(object): def __init__(self): self.item = Item() self.pos1 = Variable(1), Variable(2) self.pos2 = Variable(3), Variable(4) @pytest.fixture() def item_pos(): return ItemPosition() def test_line_constraint(item_pos): """Test line creation constraint. """ line = (Variable(3), Variable(4)), (Variable(5), Variable(6)) item_pos.item.constraint(line=(item_pos.pos1, line)) assert 1 == len(item_pos.item._constraints) c = item_pos.item._constraints[0] assert isinstance(c, LineConstraint) assert (1, 2) == c._point assert ((3, 4), (5, 6)) == c._line def test_horizontal_constraint(item_pos): """Test horizontal constraint creation. """ item_pos.item.constraint(horizontal=(item_pos.pos1, item_pos.pos2)) assert 1 == len(item_pos.item._constraints) c = item_pos.item._constraints[0] assert isinstance(c, EqualsConstraint) # Expect constraint on y-axis assert 2 == c.a assert 4 == c.b def test_vertical_constraint(item_pos): """Test vertical constraint creation. """ item_pos.item.constraint(vertical=(item_pos.pos1, item_pos.pos2)) assert 1 == len(item_pos.item._constraints) c = item_pos.item._constraints[0] assert isinstance(c, EqualsConstraint) # Expect constraint on x-axis assert 1 == c.a assert 3 == c.b def test_left_of_constraint(item_pos): """Test "less than" constraint (horizontal) creation. """ item_pos.item.constraint(left_of=(item_pos.pos1, item_pos.pos2)) assert 1 == len(item_pos.item._constraints) c = item_pos.item._constraints[0] assert isinstance(c, LessThanConstraint) assert 1 == c.smaller assert 3 == c.bigger def test_above_constraint(item_pos): """ Test "less than" constraint (vertical) creation. """ item_pos.item.constraint(above=(item_pos.pos1, item_pos.pos2)) assert 1 == len(item_pos.item._constraints) c = item_pos.item._constraints[0] assert isinstance(c, LessThanConstraint) assert 2 == c.smaller assert 4 == c.bigger
python
10
0.671984
82
25.576087
92
starcoderdata
<?php namespace App\Http\Controllers\Auth; use App\Http\Controllers\Controller; use Illuminate\Http\Request; use Hash; Use App\Models\Student; use App\Models\Register; use App\Models\StudentData; use Razorpay\Api\Api; use App\Models\Payment; class RegisterController extends Controller { public function register(Request $request){ $role=$request->role; if($request->role==3){ $student=[ 'name' => $request->firstname, 'mobile_no' => $request->mobile_no, 'email' => $request->email, 'role' => $request->role, 'otp' => mt_rand(100000, 999999), 'password_Key' => mt_rand(100000, 999999), 'password' => ]; $user=Student::create($student); }else{ $teacher=[ 'name' => $request->firstname, 'mobile_no' => $request->mobile_no, 'email' => $request->email, 'role' => $request->role, 'otp' => mt_rand(100000, 999999), 'password_Key' => mt_rand(100000, 999999), 'password' => ]; $user=Teacher::create($teacher); } $register=[ 'firstname' => $request->firstname, 'lastname' => $request->lastname, 'user_id' => $user->id, 'parentname' => 'abc', 'contactparent' => 12345678, 'address' => $request->address, 'city' => $request->city, 'district' => $request->district, 'state' => $request->state, 'pin' => $request->pin, 'dob' => $request->dob, 'grade_id' => $request->grade_id, 'otp' => mt_rand(100000, 999999), 'status' => 1 ]; Register::create( $register); $request->session()->put('id', $user->id); if( $request->role==2){ return redirect()->route('login'); } return redirect()->route('register.otp')->with('success', 'OTP Sent to Your Mobile Number!');; } public function otp_verification(){ return view('auth.otp'); } public function check_otp(Request $request){ $id = $request->session()->get('id'); $student=Student::where('id',$id)->first(); if($student->otp==$request->otp){ return redirect()->route('register.module'); } } public function view_module(){ return view('auth.module'); } public function store_module(Request $request){ $id = $request->session()->get('id'); $grade=Register::where('user_id',$id)->first(); $data=[ 'user_id'=>$id, 'grade_id'=>$grade->id, 'pack_id' => $request->pack, 'class_status' => 0, 'total_class' => 0, ]; StudentData::create($data); return redirect()->route('register.payment'); } public function payment(Request $request){ $id = $request->session()->get('id'); $amount=StudentData::where('id',$id)->with('package')->first(); return view('auth.payment',compact('amount')); } public function payment_store(Request $request){ $id = $request->session()->get('id'); $data=[ 'user_id'=> $id, 'pack_id'=>$request->pack_id, 'payment_id'=>$request->razorpay_payment_id, 'status'=>0, ]; // return response()->json( $data); $success=Payment::create($data); if($success){ return response()->json( [ 'success' => true, 'message' => 'Data inserted successfully' ] ); }else{ return response()->json( [ 'success' => true, 'message' => 'Data Not inserted successfully' ] ); } } }
php
16
0.449012
114
33.283465
127
starcoderdata
''' 满足条件的子序列数目 给你一个整数数组 nums 和一个整数 target 。 请你统计并返回 nums 中能满足其最小元素与最大元素的 和 小于或等于 target 的 非空 子序列的数目。 由于答案可能很大,请将结果对 10^9 + 7 取余后返回。   示例 1: 输入:nums = [3,5,6,7], target = 9 输出:4 解释:有 4 个子序列满足该条件。 [3] -> 最小元素 + 最大元素 <= target (3 + 3 <= 9) [3,5] -> (3 + 5 <= 9) [3,5,6] -> (3 + 6 <= 9) [3,6] -> (3 + 6 <= 9) 示例 2: 输入:nums = [3,3,6,8], target = 10 输出:6 解释:有 6 个子序列满足该条件。(nums 中可以有重复数字) [3] , [3] , [3,3], [3,6] , [3,6] , [3,3,6] 示例 3: 输入:nums = [2,3,3,4,6,7], target = 12 输出:61 解释:共有 63 个非空子序列,其中 2 个不满足条件([6,7], [7]) 有效序列总数为(63 - 2 = 61) 示例 4: 输入:nums = [5,2,4,1,7,6,8], target = 16 输出:127 解释:所有非空子序列都满足条件 (2^7 - 1) = 127   提示: 1 <= nums.length <= 10^5 1 <= nums[i] <= 10^6 1 <= target <= 10^6 ''' from typing import List ''' TODO ''' class Solution: def numSubseq(self, nums: List[int], target: int) -> int: pass
python
10
0.549701
61
14.754717
53
starcoderdata
package kg.apc.jmeter.modifiers; import java.awt.BorderLayout; import java.util.ArrayList; import java.util.Collection; import javax.swing.JScrollPane; import javax.swing.JTextArea; import kg.apc.jmeter.JMeterPluginsUtils; import org.apache.jmeter.processor.gui.AbstractPreProcessorGui; import org.apache.jmeter.testelement.TestElement; public class AnchorModifierGui extends AbstractPreProcessorGui { private static final String WIKIPAGE = "Spider"; public AnchorModifierGui() { super(); init(); } //do not insert this vizualiser in any JMeter menu private Collection emptyCollection = new ArrayList @Override public Collection getMenuCategories() { return emptyCollection; } @Override public String getStaticLabel() { return JMeterPluginsUtils.prefixLabel("Spider PreProcessor"); } @Override public String getLabelResource() { return this.getClass().getName(); } @Override public TestElement createTestElement() { AnchorModifier modifier = new AnchorModifier(); modifyTestElement(modifier); return modifier; } /** * Modifies a given TestElement to mirror the data in the gui components. * * @see * org.apache.jmeter.gui.JMeterGUIComponent#modifyTestElement(TestElement) */ @Override public void modifyTestElement(TestElement modifier) { configureTestElement(modifier); } private void init() { setLayout(new BorderLayout(0, 5)); setBorder(makeBorder()); add(JMeterPluginsUtils.addHelpLinkToPanel(makeTitlePanel(), WIKIPAGE), BorderLayout.NORTH); JTextArea info = new JTextArea(); info.setEditable(false); info.setWrapStyleWord(true); info.setOpaque(false); info.setLineWrap(true); info.setColumns(20); JScrollPane jScrollPane1 = new javax.swing.JScrollPane(); jScrollPane1.setViewportView(info); jScrollPane1.setBorder(null); info.setText("This item will create one HTTP request per link found in a page."); add(jScrollPane1, BorderLayout.CENTER); } }
java
4
0.689286
99
27.35443
79
starcoderdata
#include using namespace std; const int MAX = 3e5 + 5, LG = 21; int dp[MAX][LG], val[MAX][LG], dep[MAX]; vector<pair<int, int>> e[MAX]; void init() { memset(dp, -1, sizeof(dp)); fill(dep, dep + MAX, 0); for (int i = 0; i < MAX; i++) fill(val[i], val[i] + LG, 2e9); } void dfs(int n, int pre, int cost) { dp[n][0] = pre; val[n][0] = cost; for (auto i : e[n]) { if (pre != i.first) { dep[i.first] = dep[n] + 1; dfs(i.first, n, i.second); } } } int all; void initLCA() { for (int j = 1; j < LG; j++) for (int i = 1; i <= all; i++) if (dp[i][j - 1] != -1) dp[i][j] = dp[dp[i][j - 1]][j - 1], val[i][j] = min(val[i][j - 1], val[dp[i][j - 1]][j - 1]); } int LCA(int a, int b) { if (dep[a] > dep[b]) swap(a, b); for (int i = LG - 1; i >= 0; i--) if (dep[b] - (1 << i) >= dep[a]) b = dp[b][i]; if (a == b) return a; for (int i = LG - 1; i >= 0; i--) if (dp[a][i] != -1 && dp[b][i] != -1 && dp[b][i] != dp[a][i]) b = dp[b][i], a = dp[a][i]; return dp[a][0]; } int liftUp(int &n, int c) { int mn = 2e9; for (int i = LG - 1; i >= 0; i--) if (dp[n][i] != -1 && c - (1 << i) >= 0) mn = min(mn, val[n][i]), n = dp[n][i], c -= (1 << i); return mn; } int main() { ios_base::sync_with_stdio(0); cin.tie(NULL); freopen("D.txt", "r", stdin); int n, m; cin >> n >> m; all = n; for (int i = 0; i < m; i++) { int u, v, w; cin >> u >> v >> w; e[u].push_back({v, w}); e[v].push_back({u, w}); } init(); dfs(1, 1, 0); initLCA(); int q; cin >> q; while (q--) { int a, b; cin >> a >> b; int lc = LCA(a, b); int toA = dep[a] - dep[lc]; int toB = dep[b] - dep[lc]; int c1 = liftUp(a, toA); int c2 = liftUp(b, toB); c1 = min(c1, c2); if (c1 == 2e9) { cout << 0 << endl; } else { cout << c1 << endl; } } return 0; }
c++
17
0.379582
109
20.767677
99
starcoderdata
package com.sunyouwei.concurrent.chapter09; public class ClassInit { static class Parent { static int value = 10; static { value = 20; } } static class Child extends Parent { static int i = value; } public static void main(String[] args) { System.out.println(Child.i); } }
java
7
0.611511
63
19.85
20
starcoderdata
import { fillNumberUniqueBox } from '../fillNumber/fillNumberByBox.js'; import { concatBoxArr, getBoxEachNumber } from '../settings/arrays.js'; const uniqueOptionInBox = (arr, concatArr) => { const boxArr = concatArr; const filterArr = arr; const concatRes = concatBoxArr(filterArr, boxArr); const concatBoxRes = getBoxEachNumber(concatRes); const fillNumberRes = fillNumberUniqueBox(filterArr, concatBoxRes); return fillNumberRes; }; export { uniqueOptionInBox };
javascript
9
0.755187
71
29.125
16
starcoderdata
/* * Copyright (c) 2018 Nordic Semiconductor ASA * * SPDX-License-Identifier: LicenseRef-BSD-5-Clause-Nordic */ #ifndef NRF_ERRNO_H__ #define NRF_ERRNO_H__ /** * @file bsdlib/include/nrf_errno.h * @brief Defines integer values for errno. * Used by system calls to indicates the latest error. * * @defgroup nrf_errno Integer values for errno */ #ifdef __cplusplus extern "C" { #endif #define NRF_EPERM 1 /**< Operation not permitted */ #define NRF_ENOENT 2 /**< No such file or directory */ #define NRF_EIO 5 /**< Input/output error */ #define NRF_ENOEXEC 8 /**< Exec format error */ #define NRF_EBADF 9 /**< Bad file descriptor */ #define NRF_ENOMEM 12 /**< Cannot allocate memory */ #define NRF_EACCES 13 /**< Permission denied */ #define NRF_EFAULT 14 /**< Bad address */ #define NRF_EINVAL 22 /**< Invalid argument */ #define NRF_EMFILE 24 /**< Too many open files */ #define NRF_ENOSPC 28 /**< No space left on device */ #define NRF_EAGAIN 35 /**< Resource temporarily unavailable*/ #define NRF_EDOM 37 /**< Domain error */ #define NRF_EMSGSIZE 40 /**< Message too long */ #define NRF_EPROTOTYPE 41 /**< Protocol wrong type for socket */ #define NRF_ENOPROTOOPT 42 /**< Protocol not available */ #define NRF_EPROTONOSUPPORT 43 /**< Protocol not supported */ #define NRF_ESOCKTNOSUPPORT 44 /**< Socket type not supported */ #define NRF_EOPNOTSUPP 45 /**< Operation not supported */ #define NRF_EAFNOSUPPORT 47 /**< Address family not supported by protocol */ #define NRF_EADDRINUSE 48 /**< Address already in use */ #define NRF_ENETDOWN 50 /**< Network is down */ #define NRF_ENETUNREACH 51 /**< Network is unreachable */ #define NRF_ENETRESET 52 /**< Connection aborted by network */ #define NRF_ECONNRESET 54 /**< Connection reset by peer */ #define NRF_EISCONN 56 /**< Transport endpoint is already connected */ #define NRF_ENOTCONN 57 /**< Transport endpoint is not connected */ #define NRF_ETIMEDOUT 60 /**< Connection timed out */ #define NRF_ENOBUFS 105 /**< No buffer space available */ #define NRF_EHOSTDOWN 112 /**< Host is down */ #define NRF_EALREADY 114 /**< Operation already in progress */ #define NRF_EINPROGRESS 115 /**< Operation in progress */ #define NRF_ECANCELED 125 /**< Operation canceled */ #define NRF_ENOKEY 126 /**< Required key not available */ #define NRF_EKEYEXPIRED 127 /**< Key has expired */ #define NRF_EKEYREVOKED 128 /**< Key has been revoked */ #define NRF_EKEYREJECTED 129 /**< Key was rejected by service */ #ifdef __cplusplus } #endif #endif // NRF_ERRNO_H__
c
6
0.632675
80
42.6
65
starcoderdata
ArrayList<Integer> performSearch(String query){ ArrayList<Integer> searchResult = new ArrayList<Integer>(); // Search in Post Table. String selection = "PostIndex MATCH '" + query + "'"; String columns[] = {"docid"}; Cursor cursor = data_base.query("PostIndex", columns, selection, null, null, null, null); if(cursor.moveToFirst()){ do{ searchResult.add(cursor.getInt(0)); } while(cursor.moveToNext()); } cursor.close(); // Search in Comments Table selection = "CommentsIndex MATCH '" + query + "'"; String columns1[] = {"PostId"}; cursor = data_base.query("CommentsIndex", columns1, selection, null, null, null, null); if(cursor.moveToFirst()){ do{ searchResult.add(cursor.getInt(0)); } while(cursor.moveToNext()); } cursor.close(); return searchResult; }
java
12
0.638298
91
23.2
35
inline
#!/usr/bin/env python2.7 import re import sys class StringValidator(object): INTERPOLATION_PATTERN = re.compile(r'^.*\$[a-zA-Z\{].*$') INTERPOLATION_CHARS = {'s', 'f'} def __init__(self, filename): def _parse_file(f): self.lines = [l.strip() for l in f.readlines()] if filename == '-': _parse_file(sys.stdin) else: with open(filename, 'rb') as f: _parse_file(f) def find_strings(self): """Scan lines for strings and summarise them""" found = [] curr_string = '' open_string = False interpolated = None last_char = None last_non_quote = None open_triple = False quote_count = 0 # Find strings semi-intelligently for i, line in enumerate(self.lines): for c in line: if c == '"': quote_count += 1 # Looks like the string is being terminated if open_string: if ( quote_count == 3 or not open_triple and last_char != '\\' ): # This might be the start of a triple; we'll # decide on the next character if quote_count == 2: continue found.append({ 'content': curr_string, 'interpolated': interpolated, 'line_num': i + 1 }) # Reset values open_string = False curr_string = '' interpolated = None quote_count = 0 continue # Looks like a string is starting else: open_triple = quote_count == 3 interpolated = ( last_char if last_char in self.INTERPOLATION_CHARS else None ) open_string = True continue else: # Suspected a 3-opener but it was actually just an empty # string. Close it off and add it to the strings now if quote_count == 2: found.append({ 'content': curr_string, 'interpolated': interpolated, 'line_num': i + 1 }) open_string = False curr_string = '' interpolated = None quote_count = 0 continue quote_count = 0 last_char = c if open_string: curr_string += c if not open_triple: open_string = False quote_count = 0 curr_string = '' interpolated = None last_char = None else: last_char = '\n' return found def validate_string(self, details): """ Check if the string found seems to be missing an s (or vice verca) :returns: None if valid, reason string if invalid """ seems_interpolated = bool(self.INTERPOLATION_PATTERN.match( details['content'] )) if seems_interpolated and not details['interpolated']: return ( 'Possible missing s or f on string "%(content)s", ' 'line %(line_num)d' ) % details if not seems_interpolated and details['interpolated']: return ( 'Possible unneeded %(interpolated)s on string ' '%(interpolated)s"%(content)s", line %(line_num)d' ) % details return None def run(self): found = self.find_strings() n = 0 for s in found: error = self.validate_string(s) if error: n += 1 print error if n: print '%d string interpolation issues found' % n return n if __name__ == '__main__': sys.exit(StringValidator(sys.argv[1]).run())
python
21
0.411092
78
30.555556
144
starcoderdata
def group_same_area_time_observations(arae_ini_files): # group the observation with the same area name and time. same_area_time_obs_ini = {} for area_ini in arae_ini_files: area_name = parameters.get_string_parameters(area_ini, 'area_name') area_time = parameters.get_string_parameters(area_ini, 'area_time') area_time_key = area_name + '-' + area_time # use '-' instead of '_' ('_ has been used in many place') if area_time_key not in same_area_time_obs_ini.keys(): same_area_time_obs_ini[area_time_key] = [] same_area_time_obs_ini[area_time_key].append(area_ini) return same_area_time_obs_ini
python
10
0.64521
114
50.461538
13
inline
/* * Copyright (C) 2017-2018 Intel Corporation * * SPDX-License-Identifier: MIT * */ #pragma once #include "runtime/indirect_heap/indirect_heap.h" namespace OCLRT { class CommandQueue; struct IndirectHeapFixture { IndirectHeapFixture() : pDSH(nullptr), pIOH(nullptr), pSSH(nullptr) { } virtual void SetUp(CommandQueue *pCmdQ); virtual void TearDown() { } IndirectHeap *pDSH; IndirectHeap *pIOH; IndirectHeap *pSSH; }; } // namespace OCLRT
c
12
0.632107
58
18.290323
31
starcoderdata
# -*- coding: utf-8 -*- """ """ import os from datetime import datetime from typing import Union, Optional, Any, List, NoReturn from numbers import Real import wfdb import numpy as np np.set_printoptions(precision=5, suppress=True) import pandas as pd from ..utils.common import ( ArrayLike, get_record_list_recursive, ) from ..base import PhysioNetDataBase __all__ = [ "STDB", ] class STDB(PhysioNetDataBase): """ NOT finished, MIT-BIH ST Change Database ABOUT stdb ---------- 1. includes 28 ECG recordings of varying lengths, most of which were recorded during exercise stress tests and which exhibit transient ST depression 2. the last five records (323 through 327) are excerpts of long-term ECG recordings and exhibit ST elevation 3. annotation files contain only beat labels; they do not include ST change annotations NOTE ---- ISSUES ------ Usage ----- 1. ST segment References ---------- [1] https://physionet.org/content/stdb/1.0.0/ """ def __init__(self, db_dir:Optional[str]=None, working_dir:Optional[str]=None, verbose:int=2, **kwargs:Any) -> NoReturn: """ Parameters ---------- db_dir: str, optional, storage path of the database if not specified, data will be fetched from Physionet working_dir: str, optional, working directory, to store intermediate files and log file verbose: int, default 2, log verbosity kwargs: auxilliary key word arguments """ super().__init__(db_name="stdb", db_dir=db_dir, working_dir=working_dir, verbose=verbose, **kwargs) self.fs = None # to check self.data_ext = "dat" self.ann_ext = "atr" self._ls_rec() self.all_leads = ["ECG"] def _ls_rec(self, local:bool=True) -> NoReturn: """ finished, checked, find all records (relative path without file extension), and save into `self._all_records` for further use Parameters ---------- local: bool, default True, if True, read from local storage, prior to using `wfdb.get_record_list` """ try: super()._ls_rec(local=local) except: self._all_records = [ "300", "301", "302", "303", "304", "305", "306", "307", "308", "309", "310", "311", "312", "313", "314", "315", "316", "317", "318", "319", "320", "321", "322", "323", "324", "325", "326", "327", ] def get_subject_id(self, rec) -> int: """ """ raise NotImplementedError def database_info(self) -> NoReturn: """ """ print(self.__doc__)
python
12
0.562611
152
25.196262
107
starcoderdata
package org.kuali.coeus.propdev.impl.budget.modular; import java.util.List; import org.kuali.coeus.common.budget.framework.period.BudgetPeriod; import org.kuali.coeus.common.framework.ruleengine.KcBusinessRule; import org.kuali.coeus.common.framework.ruleengine.KcEventMethod; import org.kuali.coeus.sys.framework.gv.GlobalVariableService; import org.kuali.kra.infrastructure.KeyConstants; import org.kuali.rice.krad.util.GlobalVariables; import org.kuali.rice.krad.util.ObjectUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; @KcBusinessRule("syncModularBudgetRule") public class SyncModularBudgetKcRule { @Autowired @Qualifier("globalVariableService") private GlobalVariableService globalVariableService; @KcEventMethod public Boolean processSyncModularBusinessRules(SyncModularBudgetKcEvent event) { Boolean valid = true; List budgetPeriods = event.getBudget().getBudgetPeriods(); if (ObjectUtils.isNotNull(budgetPeriods) && !budgetPeriods.isEmpty()) { BudgetPeriod period1 = (BudgetPeriod) budgetPeriods.get(0); if (ObjectUtils.isNull(period1.getBudgetLineItems()) || period1.getBudgetLineItems().isEmpty()) { valid = false; } } else { valid = false; } if (!valid) { globalVariableService.getMessageMap().putError("modularBudget", KeyConstants.ERROR_NO_DETAILED_BUDGET); } return valid; } public GlobalVariableService getGlobalVariableService() { return globalVariableService; } public void setGlobalVariableService(GlobalVariableService globalVariableService) { this.globalVariableService = globalVariableService; } }
java
14
0.743733
115
35.632653
49
starcoderdata
/* * 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 com.addthis.hydra.job; import com.addthis.codec.Codec; import com.addthis.hydra.job.mq.JobKey; /** */ public class JobTaskDirectoryMatch implements Codec.Codable { @Codec.Set(codable = true) private final JobKey jobKey; @Codec.Set(codable = true) private final String hostId; @Codec.Set(codable = true) private final MatchType type; public JobKey getJobKey() { return jobKey; } public String getHostId() { return hostId; } public MatchType getType() { return type; } public JobTaskDirectoryMatch(MatchType type, JobKey jobKey, String hostId) { this.type = type; this.jobKey = jobKey; this.hostId = hostId; } public String getDirName() { return "live"; } public enum MatchType { /** * The task is on the correct host in the correct form */ MATCH, /** * Spawn thinks the live should be on this host, but there is no live */ MISMATCH_MISSING_LIVE, /** * There's a live directory on the host, but Spawn doesn't know about it */ ORPHAN_LIVE, /** * The task is actively replicating to the target host */ REPLICATE_IN_PROGRESS } public String getTypeDesc() { switch (type) { case MATCH: return "CORRECT"; case MISMATCH_MISSING_LIVE: return "FAIL: MISSING LIVE"; case ORPHAN_LIVE: return "ORPHAN: LIVE"; case REPLICATE_IN_PROGRESS: return "REPLICATE IN PROGRESS"; default: return "UNKNOWN"; } } public String toString() { return getDirName() + " on " + hostId + ": " + getTypeDesc(); } }
java
12
0.605305
83
26.043478
92
starcoderdata
namespace DmuFileUploader.ODataFilter { using System; public class ODataEqualsFilter : ODataValueFilterBase where T : IComparable { public ODataEqualsFilter(string field, T value) : base(field, CompareOperator.Equals, value) { } } }
c#
10
0.641638
85
23.416667
12
starcoderdata
list *list::addFast(OID x) {// printf("WTF call addFast on %x ===\n",this); {Cint i, m = length; if (m + 1 == (*this)[0]) // the memory zone is full {OID *y = ClAlloc->makeContent(m + 1); if (length) memcpy(y+1, content+1, sizeof(OID) * length); //<sb> v3.3.33 content = y;} length = m + 1; (*this)[m + 1] = x; // add the element return this;}}
c++
13
0.534211
80
33.636364
11
inline
// |reftest| module async function f() { return "success"; } var AsyncFunction = (async function(){}).constructor; assertEq(f instanceof AsyncFunction, true); f().then(v => { reportCompare("success", v); });
javascript
10
0.65
53
15.923077
13
starcoderdata
$('#show-user-form').click(function() { $('#user-form').toggle(); }); function success() { alert('Successfully updated!'); } function error() { alert('Something went wrong :('); } function submit(errors, values) { errors ? error() : $.post('/config', JSON.stringify(values)).done(success).fail(error); }
javascript
12
0.68
89
42.875
8
starcoderdata
// Produces search based on incremental reactive reusable lists 'use strict'; module.exports = function (list, searchFilter, value) { list = list.filter(searchFilter(value[0])); if (!value[1]) return list; list = list.filter(searchFilter(value.slice(0, 2))); if (!value[2]) return list; list = list.filter(searchFilter(value.slice(0, 3))); if (!value[3]) return list; return list.filter(searchFilter(value)); };
javascript
13
0.727468
63
32.285714
14
starcoderdata