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 |
---|---|---|---|---|---|---|---|
def __init__(
self,
in_channels: int,
out_channels: Optional[int] = None,
n_local_filters: int = 32,
n_local_enhancers: int = 1,
n_down_blocks: int = 4,
n_local_res_blocks: int = 3,
n_global_res_blocks: int = 9,
padding_mode: str = "reflect",
normalization: str = "in",
activation: str = "relu",
) -> None:
super().__init__()
self.in_channels = in_channels
self.out_channels = out_channels or in_channels
self.n_local_filters = n_local_filters
self.n_local_enhancers = n_local_enhancers
self.global_generator = GlobalGenerator(
in_channels=self.in_channels,
out_channels=self.out_channels,
n_filters=self.n_local_filters * 2**self.n_local_enhancers,
n_down_blocks=n_down_blocks,
n_res_blocks=n_global_res_blocks,
padding_mode=padding_mode,
normalization=normalization,
activation=activation,
max_filters=2**10,
)
# Remove last convolution layer of GlobalGenerator to extract features
self.global_generator.upsamples = self.global_generator.upsamples[:-1]
for param in self.global_generator.parameters():
param.requires_grad = False
# fmt: off
self.downsamples = nn.ModuleList()
self.residuals = nn.ModuleList()
self.upsamples = nn.ModuleList()
downsample_kwargs = dict(bias=True, padding_mode=padding_mode, normalization=normalization, activation=activation)
residual_kwargs = dict(bias=True, padding_mode=padding_mode, normalization=normalization, activation=activation)
upsample_kwargs = dict(bias=True, normalization=normalization, activation=activation)
for i in range(self.n_local_enhancers):
global_filters = self.n_local_filters * 2**i
self.downsamples.append(nn.ModuleList([
layers.Conv2dBlock(self.in_channels, global_filters, 7, 1, 3, **downsample_kwargs),
layers.Conv2dBlock(global_filters, 2 * global_filters, 3, 2, 1, **downsample_kwargs)
]))
self.residuals.append(nn.ModuleList([
ResBlock(2 * global_filters, 3, 1, **residual_kwargs)
for _ in range(n_local_res_blocks)
]))
self.upsamples.append(nn.ModuleList([
layers.ConvTranspose2dBlock(2 * global_filters, global_filters, 3, 2, 1, output_padding=1, **upsample_kwargs),
]))
self.output_layer = layers.Conv2dBlock(self.n_local_filters, self.out_channels, 7, 1, "same", bias=True,
padding_mode=padding_mode, activation="tanh")
# fmt: on | python | 14 | 0.597347 | 126 | 44 | 62 | inline |
public enum VariableSynchronizer.AnimatorParameterType // TypeDefIndex: 4702
{
// Fields
public int value__; // 0x0
public const VariableSynchronizer.AnimatorParameterType Bool = 0;
public const VariableSynchronizer.AnimatorParameterType Float = 1;
public const VariableSynchronizer.AnimatorParameterType Integer = 2;
} | c# | 6 | 0.812883 | 76 | 35.222222 | 9 | starcoderdata |
inline
double operator()(double s) const {
// this->scale*s + this->bias;
if (s == fromValue)
return toValue;
else
return s;
} | c | 6 | 0.614286 | 36 | 16.625 | 8 | inline |
/*
* This file was automatically generated by EvoSuite
* Mon Jun 01 13:44:49 GMT 2020
*/
package com.capitalone.dashboard.model;
import org.junit.Test;
import static org.junit.Assert.*;
import com.capitalone.dashboard.model.TestCase;
import com.capitalone.dashboard.model.TestCaseStatus;
import com.capitalone.dashboard.model.TestSuite;
import com.capitalone.dashboard.model.TestSuiteType;
import java.util.Collection;
import org.evosuite.runtime.EvoRunner;
import org.evosuite.runtime.EvoRunnerParameters;
import org.junit.runner.RunWith;
@RunWith(EvoRunner.class) @EvoRunnerParameters(mockJVMNonDeterminism = true, useVFS = true, useVNET = true, resetStaticState = true, separateClassLoader = true, useJEE = true)
public class TestSuite_ESTest extends TestSuite_ESTest_scaffolding {
@Test(timeout = 4000)
public void test00() throws Throwable {
TestSuite testSuite0 = new TestSuite();
testSuite0.setUnknownStatusCount(2);
int int0 = testSuite0.getUnknownStatusCount();
assertEquals(2, int0);
}
@Test(timeout = 4000)
public void test01() throws Throwable {
TestSuite testSuite0 = new TestSuite();
testSuite0.setUnknownStatusCount((-1479));
int int0 = testSuite0.getUnknownStatusCount();
assertEquals((-1479), int0);
}
@Test(timeout = 4000)
public void test02() throws Throwable {
TestSuite testSuite0 = new TestSuite();
testSuite0.setTotalTestCaseCount(1);
int int0 = testSuite0.getTotalTestCaseCount();
assertEquals(1, int0);
}
@Test(timeout = 4000)
public void test03() throws Throwable {
TestSuite testSuite0 = new TestSuite();
testSuite0.setTotalTestCaseCount((-1479));
int int0 = testSuite0.getTotalTestCaseCount();
assertEquals((-1479), int0);
}
@Test(timeout = 4000)
public void test04() throws Throwable {
TestSuite testSuite0 = new TestSuite();
testSuite0.setTestCases((Collection null);
Collection collection0 = testSuite0.getTestCases();
assertNull(collection0);
}
@Test(timeout = 4000)
public void test05() throws Throwable {
TestSuite testSuite0 = new TestSuite();
testSuite0.setSuccessTestCaseCount(493);
int int0 = testSuite0.getSuccessTestCaseCount();
assertEquals(493, int0);
}
@Test(timeout = 4000)
public void test06() throws Throwable {
TestSuite testSuite0 = new TestSuite();
testSuite0.setSuccessTestCaseCount((-762));
int int0 = testSuite0.getSuccessTestCaseCount();
assertEquals((-762), int0);
}
@Test(timeout = 4000)
public void test07() throws Throwable {
TestSuite testSuite0 = new TestSuite();
TestCaseStatus testCaseStatus0 = TestCaseStatus.Success;
testSuite0.setStatus(testCaseStatus0);
TestCaseStatus testCaseStatus1 = testSuite0.getStatus();
assertEquals(TestCaseStatus.Success, testCaseStatus1);
}
@Test(timeout = 4000)
public void test08() throws Throwable {
TestSuite testSuite0 = new TestSuite();
testSuite0.setStartTime(415L);
long long0 = testSuite0.getStartTime();
assertEquals(415L, long0);
}
@Test(timeout = 4000)
public void test09() throws Throwable {
TestSuite testSuite0 = new TestSuite();
testSuite0.setStartTime((-1L));
long long0 = testSuite0.getStartTime();
assertEquals((-1L), long0);
}
@Test(timeout = 4000)
public void test10() throws Throwable {
TestSuite testSuite0 = new TestSuite();
testSuite0.setSkippedTestCaseCount(1);
int int0 = testSuite0.getSkippedTestCaseCount();
assertEquals(1, int0);
}
@Test(timeout = 4000)
public void test11() throws Throwable {
TestSuite testSuite0 = new TestSuite();
testSuite0.setSkippedTestCaseCount((-2341));
int int0 = testSuite0.getSkippedTestCaseCount();
assertEquals((-2341), int0);
}
@Test(timeout = 4000)
public void test12() throws Throwable {
TestSuite testSuite0 = new TestSuite();
testSuite0.setId("`:Wb;");
String string0 = testSuite0.getId();
assertEquals("`:Wb;", string0);
}
@Test(timeout = 4000)
public void test13() throws Throwable {
TestSuite testSuite0 = new TestSuite();
testSuite0.setId("");
String string0 = testSuite0.getId();
assertEquals("", string0);
}
@Test(timeout = 4000)
public void test14() throws Throwable {
TestSuite testSuite0 = new TestSuite();
testSuite0.setFailedTestCaseCount((-1));
int int0 = testSuite0.getFailedTestCaseCount();
assertEquals((-1), int0);
}
@Test(timeout = 4000)
public void test15() throws Throwable {
TestSuite testSuite0 = new TestSuite();
testSuite0.setEndTime(1579L);
long long0 = testSuite0.getEndTime();
assertEquals(1579L, long0);
}
@Test(timeout = 4000)
public void test16() throws Throwable {
TestSuite testSuite0 = new TestSuite();
testSuite0.setEndTime((-1L));
long long0 = testSuite0.getEndTime();
assertEquals((-1L), long0);
}
@Test(timeout = 4000)
public void test17() throws Throwable {
TestSuite testSuite0 = new TestSuite();
testSuite0.setDuration(1);
long long0 = testSuite0.getDuration();
assertEquals(1L, long0);
}
@Test(timeout = 4000)
public void test18() throws Throwable {
TestSuite testSuite0 = new TestSuite();
testSuite0.setDuration((-1068L));
long long0 = testSuite0.getDuration();
assertEquals((-1068L), long0);
}
@Test(timeout = 4000)
public void test19() throws Throwable {
TestSuite testSuite0 = new TestSuite();
testSuite0.setDescription("com.capitalone.dashboard.model.TestSuite");
String string0 = testSuite0.getDescription();
assertEquals("com.capitalone.dashboard.model.TestSuite", string0);
}
@Test(timeout = 4000)
public void test20() throws Throwable {
TestSuite testSuite0 = new TestSuite();
testSuite0.setDescription("");
String string0 = testSuite0.getDescription();
assertEquals("", string0);
}
@Test(timeout = 4000)
public void test21() throws Throwable {
TestSuite testSuite0 = new TestSuite();
testSuite0.getType();
}
@Test(timeout = 4000)
public void test22() throws Throwable {
TestSuite testSuite0 = new TestSuite();
int int0 = testSuite0.getFailedTestCaseCount();
assertEquals(0, int0);
}
@Test(timeout = 4000)
public void test23() throws Throwable {
TestSuite testSuite0 = new TestSuite();
testSuite0.getStatus();
}
@Test(timeout = 4000)
public void test24() throws Throwable {
TestSuite testSuite0 = new TestSuite();
Collection collection0 = testSuite0.getTestCases();
testSuite0.setTestCases(collection0);
assertNull(testSuite0.getType());
}
@Test(timeout = 4000)
public void test25() throws Throwable {
TestSuite testSuite0 = new TestSuite();
String string0 = testSuite0.getId();
assertNull(string0);
}
@Test(timeout = 4000)
public void test26() throws Throwable {
TestSuite testSuite0 = new TestSuite();
long long0 = testSuite0.getEndTime();
assertEquals(0L, long0);
}
@Test(timeout = 4000)
public void test27() throws Throwable {
TestSuite testSuite0 = new TestSuite();
int int0 = testSuite0.getSuccessTestCaseCount();
assertEquals(0, int0);
}
@Test(timeout = 4000)
public void test28() throws Throwable {
TestSuite testSuite0 = new TestSuite();
long long0 = testSuite0.getDuration();
assertEquals(0L, long0);
}
@Test(timeout = 4000)
public void test29() throws Throwable {
TestSuite testSuite0 = new TestSuite();
int int0 = testSuite0.getUnknownStatusCount();
assertEquals(0, int0);
}
@Test(timeout = 4000)
public void test30() throws Throwable {
TestSuite testSuite0 = new TestSuite();
int int0 = testSuite0.getTotalTestCaseCount();
assertEquals(0, int0);
}
@Test(timeout = 4000)
public void test31() throws Throwable {
TestSuite testSuite0 = new TestSuite();
int int0 = testSuite0.getSkippedTestCaseCount();
assertEquals(0, int0);
}
@Test(timeout = 4000)
public void test32() throws Throwable {
TestSuite testSuite0 = new TestSuite();
testSuite0.setFailedTestCaseCount(1);
int int0 = testSuite0.getFailedTestCaseCount();
assertEquals(1, int0);
}
@Test(timeout = 4000)
public void test33() throws Throwable {
TestSuite testSuite0 = new TestSuite();
long long0 = testSuite0.getStartTime();
assertEquals(0L, long0);
}
@Test(timeout = 4000)
public void test34() throws Throwable {
TestSuite testSuite0 = new TestSuite();
String string0 = testSuite0.getDescription();
assertNull(string0);
}
@Test(timeout = 4000)
public void test35() throws Throwable {
TestSuite testSuite0 = new TestSuite();
TestSuiteType testSuiteType0 = TestSuiteType.Unit;
testSuite0.setType(testSuiteType0);
TestSuiteType testSuiteType1 = testSuite0.getType();
assertEquals(TestSuiteType.Unit, testSuiteType1);
}
} | java | 11 | 0.678023 | 176 | 30.131313 | 297 | starcoderdata |
<?PHP
/*----------------------------------------------------------=Class=--------------------------------------------------------------*/
class Promotion{
private $Referenceproduit;
private $solde;
private $valablele;
private $valableleau;
private $Boutique;
/*--------------------------------------------------------=Constructeur=--------------------------------------------------------------*/
function __construct($Referenceproduit,$solde,$valablele,$valableau,$Boutique){
$this->Referenceproduit=$Referenceproduit;
$this->solde=$solde;
$this->valablele=$valablele;
$this->valableau=$valableau;
$this->Boutique=$Boutique;
}
/*----------------------------------------------------------=Getters=--------------------------------------------------------------*/
function getReferenceproduit(){
return $this->Referenceproduit;
}
function getsolde(){
return $this->solde;
}
function getvalablele(){
return $this->valablele;
}
function getvalableau(){
return $this->valableau;
}
function getBoutique(){
return $this->Boutique;
}
/*----------------------------------------------------------=Setters=--------------------------------------------------------------*/
function setReferenceproduit($Referenceproduit){
$this->Referenceproduit=$Referenceproduit;
}
function setsolde($solde){
$this->solde=$solde;
}
function setvalablele($valablele){
$this->valablele=$valablele;
}
function setvalableau($valableleau){
$this->valableleau=$valableleau;
}
function setBoutique($Boutique){
$this->Boutique=$Boutique;
}
}
?> | php | 9 | 0.491783 | 136 | 26.77193 | 57 | starcoderdata |
from django.http.response import HttpResponse
from django.shortcuts import render,redirect
from django.contrib import messages
from rest_framework import serializers
from rest_framework.response import Response
from rest_framework.views import APIView
from .models import Reviews
from .serializers import ReviewsSerializer
import json
# Create your views here.
def index(request):
request_body = json.loads(request.body)
print(request_body.get('id'))
if request.method == "POST":
Reviews_id = request_body.get('id')
Reviews_username = request_body.get("user_name")
Reviews_movieid = request_body.get("movie_id")
Reviews_moviename = request_body.get("movie_name")
Reviews_rate = request_body.get("rates")
Reviews_comment = request_body.get("comments")
# Reviews_commentimage = request.POST.get("review_commentimage")
Reviews.objects.create(
id=Reviews_id,
user_name=Reviews_username,
movie_id=Reviews_movieid,
movie_name=Reviews_moviename,
rates=Reviews_rate,
comments=Reviews_comment,
# comments_img=Reviews_commentimage
)
return render(request,'reviews/index.html')
'''
def list(request):
reviews=Reviews.objects.all()
return render(request,'reviews/views.html',{"reviews":reviews})
'''
class ReviewsAll(APIView):
def get(self,request):
reviews = Reviews.objects.all()
serializer = ReviewsSerializer(reviews,many=True)
return Response(serializer.data)
class ReviewsId(APIView):
def get(self,request,id):
try:
reviews = Reviews.objects.get(id=id)
serializer = ReviewsSerializer(reviews)
return Response(serializer.data)
except Reviews.DoesNotExist:
return HttpResponse(status=404)
def post(self,request,id):
serializer = ReviewsSerializer(data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data,status=201)
return Response(serializer.errors,status=400)
def put(self,request,id):
try:
reviews = Reviews.objects.get(id=id)
if id != request.data['id']:
return HttpResponse(status=400)
# update existing reviews with request.data
serializer = ReviewsSerializer(reviews,data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data)
return Response(serializer.errors,status=400)
except Reviews.DoesNotExist:
return HttpResponse(status=404)
def delete(self,request,id):
try:
reviews = Reviews.objects.get(id=id)
reviews.delete()
return HttpResponse(status=204)
except:
return HttpResponse(status=404)
class ReviewsUserName(APIView):
def get(self,request,name):
reviews = Reviews.objects.filter(user_name=name)
serializer = ReviewsSerializer(reviews, many=True)
return Response(serializer.data)
class ReviewsMoviesId(APIView):
def get(self,request,id):
reviews = Reviews.objects.filter(movie_id=id)
serializer = ReviewsSerializer(reviews, many=True)
return Response(serializer.data)
class ReviewsMoviesName(APIView):
def get(self, request, name):
reviews = Reviews.objects.filter(movie_name=name)
serializer = ReviewsSerializer(reviews, many=True)
return Response(serializer.data) | python | 13 | 0.6568 | 72 | 32.157407 | 108 | starcoderdata |
import test from 'ava'
import {shallow} from 'vue-test-utils'
import fake_responses_debug from 'apps/debug/pages/fake_data_debug.vue'
import * as exports from 'lib/models/geodata/geodata.valid'
import * as db from 'lib/models/geodata/local.geodata_store'
// What's this?!
db.hydrate_geodata_cache_from_idb = () => Promise.resolve()
test('can mock an import', t => {
exports.geodata_in_cache_and_valid = () => true
const actual = exports.geodata_in_cache_and_valid()
t.true(actual)
})
test.cb.failing('show message if geodata not loaded or valid (mock import)', t => {
// Ensure geodata is not valid
exports.geodata_in_cache_and_valid = () => false
const wrapper = shallow(fake_responses_debug)
// wrapper.vm.message_type = 'missing_geodata'
wrapper.vm.$nextTick(() => {
const actual = wrapper.find('div.applet_container').text()
t.true(/Missing geodata/.test(actual))
t.end()
})
})
test.cb('show message if geodata not loaded or valid (direct set value)', t => {
const wrapper = shallow(fake_responses_debug)
wrapper.vm.message_type = 'missing_geodata'
wrapper.vm.$nextTick(() => {
const actual = wrapper.find('div.applet_container').text()
t.true(/Missing geodata/.test(actual))
t.end()
})
})
test.cb.failing('sets message_type to `missing_geodata` if geodata not valid', t => {
exports.geodata_in_cache_and_valid = () => false
const wrapper = shallow(fake_responses_debug)
wrapper.vm.$nextTick(() => {
t.true(wrapper.vm.message_type === 'missing_geodata')
t.end()
})
})
test.cb('show input if geodata loaded and valid (mock import)', t => {
exports.geodata_in_cache_and_valid = () => true
const wrapper = shallow(fake_responses_debug)
wrapper.vm.$nextTick(() => {
const actual = wrapper.find('div.applet_container').text()
t.true(/Number of areas/.test(actual))
t.end()
})
})
test.cb('show input if geodata loaded and valid (direct set value)', t => {
const wrapper = shallow(fake_responses_debug)
wrapper.vm.message_type = ''
wrapper.vm.$nextTick(() => {
const actual = wrapper.find('div.applet_container').text()
t.true(/Number of areas/.test(actual))
t.end()
})
}) | javascript | 16 | 0.671227 | 85 | 27.3375 | 80 | starcoderdata |
from model.contact import Contact
def test_modify_contact_first_name(app):
if app.contact.count() == 0:
app.contact.create(Contact(first_name="test_name"))
old_contacts = app.contact.get_contact_list()
app.contact.modify_first_contact(Contact(first_name="
new_contacts = app.contact.get_contact_list()
assert len(old_contacts) == len(new_contacts)
def test_modify_contact_last_name(app):
if app.contact.count() == 0:
app.contact.create(Contact(first_name="test_name"))
old_contacts = app.contact.get_contact_list()
app.contact.modify_first_contact(Contact(last_name="
new_contacts = app.contact.get_contact_list()
assert len(old_contacts) == len(new_contacts) | python | 12 | 0.692412 | 66 | 37.842105 | 19 | starcoderdata |
using System.Collections.Generic;
using System.Linq;
namespace ApprovalTransactionCollector
{
public class UserReimbursementSummary
{
public string UserAddress { get; set; }
public int NumberOfApprovalTransactions { get { return UserTransactions.Count; } }
public decimal TotalGasFees { get { return UserTransactions?.Sum(x => x.GasFeeInEth) ?? 0.0m; } }
public decimal TopFiveGasFeesInEth { get { return UserTransactions?.OrderByDescending(x => x.GasFeeInEth).Take(5).Sum(x => x.GasFeeInEth) ?? 0.0m; } }
public decimal BottomFiveGasFeesInEth { get { return UserTransactions?.OrderBy(x => x.GasFeeInEth).Take(5).Sum(x => x.GasFeeInEth) ?? 0.0m; } }
public List UserTransactions { get; private set; }
public UserReimbursementSummary()
{
UserTransactions = new List
}
}
} | c# | 21 | 0.714836 | 158 | 46.181818 | 22 | starcoderdata |
package com.nj.zhihu.ui.activity;
import android.content.Context;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.ImageView;
import android.widget.ListView;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.nj.zhihu.GlideApp;
import com.nj.zhihu.R;
import com.nj.zhihu.bean.Editors;
import com.nj.zhihu.ui.adapter.editor.EditorAdpter;
import com.nj.zhihu.utils.NetWorkUtils;
import com.nj.zhihu.utils.SpUtils;
import com.zhy.adapter.recyclerview.CommonAdapter;
import com.zhy.adapter.recyclerview.base.ViewHolder;
import java.util.ArrayList;
import java.util.List;
public class EditorActivity extends AppCompatActivity {
private List mEditorsList = new ArrayList<>();
private Toolbar mToolbar;
private RecyclerView mRecyclerView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_editor);
initData();
initView();
}
private void initView() {
mToolbar = findViewById(R.id.toolbar);
mToolbar.setTitle("主编");
mToolbar.setNavigationIcon(R.drawable.ic_arrow_back);
mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
onBackPressed();
}
});
mRecyclerView = findViewById(R.id.editor_list);
// mListView.setAdapter(new EditorAdpter(mEditorsList));
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
mRecyclerView.setAdapter(new CommonAdapter R.layout.editor_list_item, mEditorsList) {
@Override
protected void convert(ViewHolder holder, Editors editors, int position) {
Context context = holder.getConvertView().getContext();
holder.setText(R.id.name, editors.getName());
holder.setText(R.id.bio, editors.getBio());
ImageView headImage = holder.getView(R.id.head);
if ((boolean) SpUtils.get(context, "NO_IMAGE_MODE", false)
&& !NetWorkUtils.isWifiConnected(context)) {
GlideApp.with(EditorActivity.this)
.load(R.drawable.editor_profile_avatar)
.diskCacheStrategy(DiskCacheStrategy.RESOURCE)
.into(headImage);
} else {
GlideApp.with(EditorActivity.this)
.load(editors.getAvatar())
.diskCacheStrategy(DiskCacheStrategy.RESOURCE)
.into(headImage);
}
}
});
}
private void initData() {
ArrayList arrayList = getIntent().getParcelableArrayListExtra("editor_list");
mEditorsList.addAll(arrayList);
}
} | java | 21 | 0.632487 | 108 | 38.367089 | 79 | starcoderdata |
package cn.com.yuns.dao;
import org.springframework.stereotype.Repository;
@Repository
public class WelcomeDao {
} | java | 4 | 0.815476 | 50 | 20 | 8 | starcoderdata |
AbstractMemoryReader::AbstractMemoryReader(const std::string& i_ncache_filename)
: _header_data_current_ptr(0)
, _channel_data_current_ptr(0)
, _header_data_end_ptr(0)
, _channel_data_end_ptr(0)
, _cache_filename(i_ncache_filename)
{
FILE *_fp = fopen(i_ncache_filename.c_str(),"rb");
if (_fp == 0)
throw std::runtime_error((boost::format("Failed to open file '%1%'")%i_ncache_filename).str());
else {
std::string tag;
size_t blob_size;
int32_t tag_value_int32;
int64_t tag_value_int64;
// Header
InterfaceReader::read_tag(_fp,tag);
if (tag.compare("FOR4")==0)
{
InterfaceReader::read_int32t(_fp,tag_value_int32);
blob_size = tag_value_int32;
}
else if (tag.compare("FOR8")==0)
{
InterfaceReader::read_int64t(_fp,tag_value_int64); // some 64bit data
InterfaceReader::read_int32t(_fp,tag_value_int32);
blob_size = tag_value_int32;
DLOG(INFO) << boost::format("FOR8 blob_size xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx %1%") % blob_size;
DLOG(INFO) << "00000000";
}
else
throw std::runtime_error((boost::format("Failed to open file '%1%', unknown format '%2%'")%i_ncache_filename%tag).str());
DLOG(INFO) << "00000001";
_header_data_unsigned_char_buffer.resize(blob_size);
DLOG(INFO) << "00000002";
_header_data_current_ptr = _header_data_unsigned_char_buffer.data();
DLOG(INFO) << "00000003";
_header_data_end_ptr = _header_data_current_ptr + _header_data_unsigned_char_buffer.size();
DLOG(INFO) << "00000004";
read_blob<DataBufferType>(_fp, blob_size, _header_data_unsigned_char_buffer.data());
DLOG(INFO) << boost::format("tag = '%1%', byte count = %2%") % tag % blob_size;
// Channels
InterfaceReader::read_tag(_fp,tag);
if (tag.compare("FOR4")==0)
{
InterfaceReader::read_int32t(_fp,tag_value_int32);
blob_size = tag_value_int32;
}
else if (tag.compare("FOR8")==0)
{
InterfaceReader::read_int64t(_fp,tag_value_int64); // some 64bit data
InterfaceReader::read_int32t(_fp,tag_value_int32);
blob_size = tag_value_int32;
}
else
throw std::runtime_error((boost::format("Failed to open file '%1%', unknown format '%2%'")%i_ncache_filename%tag).str());
_channel_data_unsigned_char_buffer.resize(blob_size);
_channel_data_current_ptr = _channel_data_unsigned_char_buffer.data();
_channel_data_end_ptr = _channel_data_current_ptr + _channel_data_unsigned_char_buffer.size();
read_blob<DataBufferType>(_fp, blob_size, _channel_data_unsigned_char_buffer.data());
DLOG(INFO) << boost::format("tag = '%1%', byte count = %2%") % tag % blob_size;
fclose(_fp);
}
} | c++ | 21 | 0.67096 | 124 | 38.430769 | 65 | inline |
<?php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\HomeController;
use App\Http\Controllers\AdminController;
use App\Http\Controllers\CategoryProduct;
use App\Http\Controllers\MaterialProduct;
use App\Http\Controllers\ProductController;
use App\Http\Controllers\CartController;
/*
|--------------------------------------------------------------------------
| 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('/',[HomeController::class,'index']);
Route::get('/trang-chu',[HomeController::class,'index']);
Route::get('/admin',[AdminController::class,'index']);
Route::get('/dashboard',[AdminController::class,'show_dashboard']);
Route::get('/logout',[AdminController::class,'logout']);
Route::post('/admin-dashboard',[AdminController::class,'dashboard']);
//category product: danh mục sản phẩm
Route::get('/add-category-product',[CategoryProduct::class,'add_category_product']);
Route::get('/edit-category-product/{category_product_id}',[CategoryProduct::class,'edit_category_product']);
Route::get('/delete-category-product/{category_product_id}',[CategoryProduct::class,'delete_category_product']);
Route::get('/all-category-product',[CategoryProduct::class,'all_category_product']);
Route::get('/unactive-category-product/{category_product_id}',[CategoryProduct::class,'unactive_category_product']);
Route::get('/active-category-product/{category_product_id}',[CategoryProduct::class,'active_category_product']);
Route::post('/save-category-product',[CategoryProduct::class,'save_category_product']);
Route::post('/update-category-product/{category_product_id}',[CategoryProduct::class,'update_category_product']);
//Material product: chất liệu sản phẩm
Route::get('/add-material-product',[MaterialProduct::class,'add_material_product']);
Route::get('/edit-material-product/{material_product_id}',[MaterialProduct::class,'edit_material_product']);
Route::get('/delete-material-product/{material_product_id}',[MaterialProduct::class,'delete_material_product']);
Route::get('/all-material-product',[MaterialProduct::class,'all_material_product']);
Route::get('/unactive-material-product/{material_product_id}',[MaterialProduct::class,'unactive_material_product']);
Route::get('/active-material-product/{material_product_id}',[MaterialProduct::class,'active_material_product']);
Route::post('/save-material-product',[MaterialProduct::class,'save_material_product']);
Route::post('/update-material-product/{material_product_id}',[MaterialProduct::class,'update_material_product']);
//product: sản phẩm
Route::get('/add-product',[ProductController::class,'add_product']);
Route::get('/edit-product/{product_id}',[ProductController::class,'edit_product']);
Route::get('/delete-product/{product_id}',[ProductController::class,'delete_product']);
Route::get('/all-product',[ProductController::class,'all_product']);
Route::get('/unactive-product/{product_id}',[ProductController::class,'unactive_product']);
Route::get('/active-product/{product_id}',[ProductController::class,'active_product']);
Route::post('/save-product',[ProductController::class,'save_product']);
Route::post('/update-product/{product_id}',[ProductController::class,'update_product']);
//post: bài viết
Route::get('/add-post',[PostController::class,'add_post']);
Route::get('/edit-post/{post_id}',[PostController::class,'edit_post']);
Route::get('/delete-post/{post_id}',[PostController::class,'delete_post']);
Route::get('/all-post',[PostController::class,'all_post']);
Route::get('/unactive-post/{post_id}',[PostController::class,'unactive_post']);
Route::get('/active-post/{post_id}',[PostController::class,'active_post']);
Route::post('/save-post',[PostController::class,'save_post']);
Route::post('/update-post/{post_id}',[PostController::class,'update_post']);
//Danh muc san pham trang chu
Route::get('/danh-muc-san-pham/{category_id}',[CategoryProduct::class,'show_category_home']);
Route::get('/chat-lieu-san-pham/{material_id}',[MaterialProduct::class,'show_material_home']);
Route::get('/chi-tiet-san-pham/{product_id}',[ProductController::class,'details_product']);
//cart
Route::post('/update-cart-quantity',[CartController::class,'update_cart_quantity']);
Route::post('/update-cart',[CartController::class,'update_cart']);
Route::post('/save-cart',[CartController::class,'save_cart']);
Route::post('/add-cart-ajax',[CartController::class,'add_cart_ajax']);
Route::get('/show-cart',[CartController::class,'show_cart']);
Route::get('/gio-hang',[CartController::class,'gio_hang']);
Route::get('/delete-to-cart/{rowId}',[CartController::class,'delete_to_cart']);
Route::get('/del-product/{session_id}',[CartController::class,'delete_product']);
Route::get('/del-all-product',[CartController::class,'delete_all_product']); | php | 8 | 0.719928 | 116 | 59.39759 | 83 | starcoderdata |
private void collectEntries(
ResolutionTreeNode node,
Stack<AbstractRoute> stack,
ImmutableCollection.Builder<FibEntry> entriesBuilder) {
AbstractRoute route = node.getRoute();
assert !route.getNonForwarding();
if (node.getChildren().isEmpty()) {
FibAction fibAction =
new NextHopVisitor<FibAction>() {
@Override
public FibAction visitNextHopIp(NextHopIp nextHopIp) {
checkState(
node.getUnresolvable(),
"FIB resolution failed to reach a terminal route for NHIP route not marked"
+ " unresolvable: %s",
route);
return FibNullRoute.INSTANCE;
}
@Override
public FibAction visitNextHopInterface(NextHopInterface nextHopInterface) {
return new FibForward(node.getFinalNextHopIp(), nextHopInterface.getInterfaceName());
}
@Override
public FibAction visitNextHopDiscard(NextHopDiscard nextHopDiscard) {
return FibNullRoute.INSTANCE;
}
@Override
public FibAction visitNextHopVrf(NextHopVrf nextHopVrf) {
return new FibNextVrf(nextHopVrf.getVrfName());
}
@Override
public FibAction visitNextHopVtep(NextHopVtep nextHopVtep) {
// Forward out the VXLAN "interface", which will send to the correct remote node by
// "ARPing" for the VTEP IP.
String forwardingIface = generatedTenantVniInterfaceName(nextHopVtep.getVni());
return new FibForward(nextHopVtep.getVtepIp(), forwardingIface);
}
}.visit(route.getNextHop());
entriesBuilder.add(new FibEntry(fibAction, stack));
return;
}
stack.push(route);
for (ResolutionTreeNode child : node.getChildren()) {
collectEntries(child, stack, entriesBuilder);
}
stack.pop();
} | java | 18 | 0.607952 | 99 | 37.230769 | 52 | inline |
package httpassert
import (
"encoding/json"
"io"
"io/ioutil"
"reflect"
"testing"
)
// EqualJSON assert http response body equal the exptected object. The body's
// decoder is json
func EqualJSON(t *testing.T, expected interface{}, r io.Reader) {
ev := reflect.ValueOf(expected)
if ev.Kind() == reflect.Ptr {
EqualJSON(t, ev.Elem().Interface(), r)
return
}
av := reflect.New(ev.Type())
b, err := ioutil.ReadAll(r)
if err != nil {
t.Errorf("unexpected error when decoding: %T(%v)", err, err)
return
}
if err := json.Unmarshal(b, av.Interface()); err != nil {
t.Errorf("unexpected error when decoding: %T(%v)", err, err)
return
}
if ok := compareValues(reflect.ValueOf(expected), av.Elem()); ok {
return
}
renderJSONError(t, expected, b)
} | go | 12 | 0.663354 | 77 | 18.634146 | 41 | starcoderdata |
package gregtech.api.capability.impl.energy;
import alexiil.mc.lib.attributes.misc.NullVariant;
import gregtech.api.capability.block.EnergySink;
public enum EmptyEnergySink implements EnergySink, NullVariant {
INSTANCE;
@Override
public int getVoltage() {
return 0;
}
@Override
public int acceptEnergyFromNetwork(int voltage, int amperage) {
return 0;
}
} | java | 5 | 0.738144 | 80 | 24.526316 | 19 | starcoderdata |
<!DOCTYPE html>
<html dir="ltr" lang="en">
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<!-- Tell the browser to be responsive to screen width -->
<meta name="viewport" content="width=device-width, initial-scale=1">
Queuing Management System
<!-- Favicon icon -->
<link rel="icon" type="image/png" sizes="16x16" href="<?php echo base_url() . "assets/new/"; ?>plugins/images/favicon.png">
<link href="<?php echo base_url() . "assets/new/"; ?>plugins/bower_components/chartist/dist/chartist.min.css" rel="stylesheet">
<link rel="stylesheet" href="<?php echo base_url() . "assets/new/"; ?>plugins/bower_components/chartist-plugin-tooltips/dist/chartist-plugin-tooltip.css">
<!-- Custom CSS -->
<link href="<?php echo base_url() . "assets/new/"; ?>css/style.min.css" rel="stylesheet">
<script src="https://code.jquery.com/jquery-3.6.0.js" integrity="sha256-H+K7U5CnXl1h5ywQfKtSj8PCmoN9aaq30gDh27Xc0jk=" crossorigin="anonymous">
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.11.3/css/jquery.dataTables.css">
<script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/1.11.3/js/jquery.dataTables.js">
<div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Modal title
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×
<div class="modal-body">
...
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close
<button type="button" class="btn btn-primary">Save changes
<!-- ============================================================== -->
<!-- Preloader - style you can find in spinners.css -->
<!-- ============================================================== -->
<div class="preloader">
<div class="lds-ripple">
<div class="lds-pos">
<div class="lds-pos">
<!-- ============================================================== -->
<!-- Main wrapper - style you can find in pages.scss -->
<!-- ============================================================== -->
<div id="main-wrapper" data-layout="vertical" data-navbarbg="skin5" data-sidebartype="full"
data-sidebar-position="absolute" data-header-position="absolute" data-boxed-layout="full">
<!-- ============================================================== -->
<!-- Topbar header - style you can find in pages.scss -->
<!-- ============================================================== -->
<header class="topbar" data-navbarbg="skin5">
<nav class="navbar top-navbar navbar-expand-md navbar-dark">
<div class="navbar-header" data-logobg="skin6">
<a class="navbar-brand" href="<?php echo base_url() . "admin/dashboard"; ?>">
<b class="logo-icon">
<img src="<?php echo base_url() . "assets/new/"; ?>plugins/images/logo-icon2.png" height="60" alt="homepage" />
<a class="nav-toggler waves-effect waves-light d-block d-md-none"
href="javascript:void(0)" style="color:white"><i class="ti-menu ti-close">
<div class="navbar-collapse collapse" id="navbarSupportedContent" data-navbarbg="skin4" style="background-color:#01579B">
<ul class="navbar-nav ms-auto d-flex align-items-center">
<?php
if($user['gender']) {
$image = base_url() . "assets/new/plugins/images/new-users/Cashier_Icon.png";
} else {
$image = base_url() . "assets/new/plugins/images/new-users/Admin_Icon.png";
}
?>
<a class="profile-pic" href="#">
<img src="<?php echo $image; ?>" alt="user-img" width="36"
class="img-circle"> Hi, <span class="text-white font-medium"> <?php echo $user['fname']?>
<!-- ============================================================== -->
<!-- End Topbar header -->
<!-- ============================================================== -->
<!-- ============================================================== -->
<!-- Left Sidebar - style you can find in sidebar.scss -->
<!-- ============================================================== -->
<aside class="left-sidebar" data-sidebarbg="skin6">
<!-- Sidebar scroll-->
<div class="scroll-sidebar">
<!-- Sidebar navigation-->
<nav class="sidebar-nav">
<ul id="sidebarnav">
<!-- User Profile-->
<li class="sidebar-item pt-2">
<a class="sidebar-link waves-effect waves-dark sidebar-link" href="<?php echo base_url() . "admin/dashboard"; ?>"
aria-expanded="false">
<i class="fas fa-desktop" aria-hidden="true">
<span class="hide-menu">Dashboard
<li class="sidebar-item">
<a class="sidebar-link waves-effect waves-dark sidebar-link" href="<?php echo base_url() . "admin/department"; ?>"
aria-expanded="false">
<i class="fas fa-archive" aria-hidden="true">
<span class="hide-menu">Department
<li class="sidebar-item">
<a class="sidebar-link waves-effect waves-dark sidebar-link" href="<?php echo base_url() . "admin/account"; ?>"
aria-expanded="false">
<i class="fas fa-archive" aria-hidden="true">
<span class="hide-menu">Visitor
<li class="sidebar-item">
<a class="sidebar-link waves-effect waves-dark sidebar-link" href="<?php echo base_url() . "admin/setting"; ?>"
aria-expanded="false">
<i class="fas fa-user" aria-hidden="true">
<span class="hide-menu">Profile
<li class="text-center p-20 upgrade-btn">
<a href="<?php echo base_url() . "admin/logout"; ?>"
class="btn d-grid btn-danger text-white">
LOGOUT
<!-- End Sidebar navigation -->
<!-- End Sidebar scroll-->
<!-- ============================================================== -->
<!-- End Left Sidebar - style you can find in sidebar.scss -->
<!-- ============================================================== -->
<!-- ============================================================== -->
<!-- Page wrapper -->
<!-- ============================================================== -->
<div class="page-wrapper">
<!-- ============================================================== -->
<!-- Bread crumb and right sidebar toggle -->
<!-- ============================================================== -->
<div class="page-breadcrumb bg-white">
<div class="row align-items-center">
<div class="col-lg-3 col-md-4 col-sm-4 col-xs-12">
<h4 class="page-title">VISITORS
<div class="col-lg-9 col-sm-8 col-md-8 col-xs-12">
<div class="d-md-flex">
<ol class="breadcrumb ms-auto">
href="#" class="fw-normal">VISITORS
<div class="container-fluid">
<div class="row">
<!-- Column -->
<?php if($this->session->flashdata('respond-student')): ?>
<div class="col-lg-12 col-xlg-12 col-md-12">
<div class="alert alert-success" role="alert">
<?php echo $this->session->flashdata('respond-student'); ?>
<?php endif; ?>
<!-- Column -->
<div class="col-lg-12 col-xlg-12 col-md-12">
<div class="card">
<div class="card-body">
<h4 class="box-title" style="margin-bottom:20px;font-weight:bold">ACCOUNT LIST
<a href="<?php echo base_url() . "admin/account/create"; ?>" style="margin-bottom:10px" class="btn btn-primary">CREATE ACCOUNT
<table id="table_id" class="display table table-bordered">
<thead class="table-bordered">
Name
Address
Created
<?php
foreach($users as $usr){
?>
echo $usr['username']; ?>
echo $usr['fname'] . " " . $usr['lname']; ?>
echo $usr['email']; ?>
echo date("F d, Y", strtotime($usr['created_at'])); ?>
<?php
}
?>
<footer class="footer text-center"> 2021 © cloudqms.live
<script type="text/javascript">
$(document).ready( function () {
$('#table_id').DataTable();
} );
<!-- Bootstrap tether Core JavaScript -->
<script src="<?php echo base_url() . "assets/new/"; ?>bootstrap/dist/js/bootstrap.bundle.min.js">
<script src="<?php echo base_url() . "assets/new/"; ?>js/app-style-switcher.js">
<script src="<?php echo base_url() . "assets/new/"; ?>plugins/bower_components/jquery-sparkline/jquery.sparkline.min.js">
<!--Wave Effects -->
<script src="<?php echo base_url() . "assets/new/"; ?>js/waves.js">
<!--Menu sidebar -->
<script src="<?php echo base_url() . "assets/new/"; ?>js/sidebarmenu.js">
<!--Custom JavaScript -->
<script src="<?php echo base_url() . "assets/new/"; ?>js/custom.js">
<!--This page JavaScript -->
<!--chartis chart-->
<script src="<?php echo base_url() . "assets/new/"; ?>plugins/bower_components/chartist/dist/chartist.min.js">
<script src="<?php echo base_url() . "assets/new/"; ?>plugins/bower_components/chartist-plugin-tooltips/dist/chartist-plugin-tooltip.min.js">
<script src="<?php echo base_url() . "assets/new/"; ?>js/pages/dashboards/dashboard1.js"> | php | 12 | 0.407597 | 162 | 54.627615 | 239 | starcoderdata |
void CModel::AddForcingGrid (CForcingGrid *pGrid, forcing_type typ)
{
if(GetForcingGridIndexFromType(typ) == DOESNT_EXIST) {
if(!DynArrayAppend((void**&)(_pForcingGrids),(void*)(pGrid),_nForcingGrids)){
ExitGracefully("CModel::AddForcingGrid: adding NULL ForcingGrid",BAD_DATA);
}
}
else { //overwrite grid
int f= GetForcingGridIndexFromType(typ);
if((_pForcingGrids[f])!=(pGrid)) {
delete _pForcingGrids[f]; //JRC: the big offender - usually we are overwriting with the same forcing grid instance
}
_pForcingGrids[f]=pGrid;
}
} | c++ | 15 | 0.674617 | 120 | 37.266667 | 15 | inline |
public static ulong[] CalcPairFreqs(int[] data, int[] codelist, CipherPair eof = null)
{
//convert the data into a string, so we can use regex on it
char[] ctext = new char[data.Length * 4];
Buffer.BlockCopy(data, 0, ctext, 0, data.Length * 4);
string text = new string(ctext);
var count = new SortedList<int, ulong>(codelist.Length * codelist.Length, new DuplicateKeyComparer<int>());
for (int i = 0; i < codelist.Length; i++)
{
for (int j = 0; j < codelist.Length; j++)
{
count.Add(Regex.Matches(text, string.Concat(codelist[i], codelist[j])).Count, ((ulong)i << 32) | (uint)j);
}
}
return count.Select(p => p.Value).ToArray();
} | c# | 22 | 0.523058 | 126 | 47.529412 | 17 | inline |
#define XK_MISCELLANY
#include
#include
#include
#include "interface-manager.h"
InterfaceManager::InterfaceManager(Display *display, Window window,
Scene *scene, Camera *camera, XInput2 *xinput2,
Gamepad *gamepad)
: display_(display), window_(window), scene_(scene),
camera_(camera), xinput2_(xinput2), gamepad_(gamepad),
mouse_state_(0), exit_(false) {
// Register events for gamepad
if (gamepad)
gamepad->SetEventCallback(
[&](const struct EventData &data) {
assert(false);
});
// Register mouse event callbacks
xinput2->OnButtonEvent([&](XInput2 *xinput2,
const XInput2::KeyButtonEventType e,
const unsigned int b) {
if (e == XInput2::KeyButtonEventType::kButtonReleased)
DisableDragMode();
else {
switch (b) {
case Button1:
EnableDragMode1();
break;
case Button3:
EnableDragMode2();
break;
}
}
});
xinput2->OnPointerMotionEvent([&](
XInput2 *xinput2,
double dx, double dy) {
DispatchPointerMotionEvent(dx, dy);
});
xinput2->OnWheelEvent([&](XInput2 *xinput2, float dz) {
DispatchWheelEvent(dz);
});
xinput2->OnKeyEvent([&](XInput2 *xinput2,
const XInput2::KeyButtonEventType e,
const unsigned int b) {
DispatchKeyPressEvent(b);
});
}
void InterfaceManager::EnableDragMode1() {
if (mouse_state_ == IDLE) {
xinput2_->GrabPointerDevice();
mouse_state_ = DRAG_MODE1;
}
}
void InterfaceManager::EnableDragMode2() {
if (mouse_state_ == IDLE) {
xinput2_->GrabPointerDevice();
mouse_state_ = DRAG_MODE2;
}
}
void InterfaceManager::DisableDragMode() {
if (mouse_state_ != IDLE) {
xinput2_->UngrabPointerDevice();
mouse_state_ = IDLE;
}
}
void InterfaceManager::DispatchPointerMotionEvent(double dx, double dy) {
XWindowAttributes attrs;
const float kPanSpeed = 5.0f;
const float kRotateSpeed = 2.0f;
XGetWindowAttributes(display_, window_, &attrs);
const unsigned int width = attrs.width;
const unsigned int height = attrs.height;
const int minor_axis = std::min(width, height) / 2;
const float dside = dx / minor_axis;
const float dup = -dy / minor_axis;
switch (mouse_state_) {
case DRAG_MODE1:
camera_->TrackballControlRotate(dside * kRotateSpeed, dup * kRotateSpeed);
break;
case DRAG_MODE2:
camera_->TrackballControlPan(dside * kPanSpeed, dup * kPanSpeed);
break;
}
}
void InterfaceManager::DispatchWheelEvent(float dz) {
camera_->TrackballControlZoom(dz);
}
void InterfaceManager::DispatchKeyPressEvent(unsigned int keysim) {
switch (keysim) {
case XK_Escape:
exit_ = true;
break;
}
} | c++ | 17 | 0.61705 | 82 | 25.159292 | 113 | starcoderdata |
def write(data):
f = open('scaled-data.dat','w')
if len(data) == 2:
for x,y in zip(data[0], data[1]):
f.write('%e %e\n'%(x,y))
elif len(data) == 4:
for x,y, dx, dy in zip(data[0], data[1], data[2], data[3]):
f.write('%e %e %e %e\n'%(x,y))
f.close()
def convertUnits(my_data, xscale, yscale):
data = np.matrix(my_data)
data[0] = data[0]*xscale
data[1] = data[1]*yscale
if len(data) == 4:
data[2] = data[2]*xscale
data[3] = data[3]*yscale
return data.tolist()
from plotting.read import readDat
import numpy as np
if __name__ == '__main__':
import argparse
parser = argparse.ArgumentParser(description='Convert units')
parser.add_argument('-f','--file',help='file name',type=str)
parser.add_argument('-xs','--xscale',help='x scale factor',
type=float,default=1.0)
parser.add_argument('-ys','--yscale',help='y scale factor',
type=float,default=1.0)
args = vars(parser.parse_args())
data = readDat(args['file'])
scaled = convertUnits(data, args['xscale'], args['yscale'])
write(scaled) | python | 14 | 0.561597 | 67 | 30.810811 | 37 | starcoderdata |
import { createReducer, createActions } from 'reduxsauce';
import Immutable from 'seamless-immutable';
/* Types & Action Creators */
const { Types, Creators } = createActions({
setPodcastRequest: ['podcast', 'episodeId'],
setPodcastSuccess: ['podcast'],
setCurrent: ['id'],
play: null,
pause: null,
reset: null,
prev: null,
next: null,
});
export const PlayerTypes = Types;
export default Creators;
/* Initial State */
export const INITIAL_STATE = Immutable({
podcast: null,
current: null,
playing: false,
});
/* Reducers to types */
export const reducer = createReducer(INITIAL_STATE, {
[Types.SET_PODCAST_SUCCESS]: (state, { podcast }) => state.merge({ podcast, current: podcast.tracks[0].id }),
[Types.SET_CURRENT]: (state, { id }) => state.merge({ current: id }),
[Types.PLAY]: state => state.merge({ playing: true }),
[Types.PAUSE]: state => state.merge({ playing: false }),
[Types.RESET]: state => state.merge({ podcast: null, current: null, playing: false }),
}); | javascript | 16 | 0.666337 | 111 | 27.055556 | 36 | starcoderdata |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MongoDB.Bson;
namespace StepsDBLib {
public class StepsNode {
private StepsNode() {
}
public static StepsNode Connect(string url) {
return new StepsNode();
}
public StepsDatabase GetDatabase(string dbname) {
return new StepsDatabase(this, dbname);
}
public StepsDatabase CreateDatabase(string dbname) {
throw new Exception("unimplemented");
}
}
public class StepsDatabase {
StepsNode mynode;
public StepsDatabase(StepsNode node, string dbname) {
mynode = node;
}
public StepsCollection GetCollection collection_name) where T : BsonDocument {
return new StepsCollection
}
}
public class StepsCollection where T:BsonDocument {
StepsDatabase db;
public StepsCollection(StepsDatabase db) {
this.db = db;
}
public void Insert(T doc) {
throw new Exception("unimplemented");
}
// perhaps make compatibility method for mongo, with a document batch?
public void InsertBatch(List batch) {
throw new Exception("unimplemented");
}
public StepsCursor Find(BsonDocument query) {
throw new Exception("unimplemented");
}
public StepsCursor FindAs query) where T_OTHER : BsonDocument {
throw new Exception("unimplemented");
}
public void Save(T doc) {
throw new Exception("unimplemented");
}
public void Update(T doc) {
throw new Exception("unimplemented");
}
}
public class StepsCursor where T : BsonDocument {
public IEnumerator GetEnumerator() {
throw new Exception("unimplemented");
}
}
} | c# | 12 | 0.583949 | 102 | 23.46988 | 83 | starcoderdata |
import React from "react";
import { Link } from "react-router-dom";
function GameMenu(props) {
const handleFormChanges = (e) => {
const propertyToUpdate = e.target.name;
let newPropertyValue = e.target.value;
if (propertyToUpdate === "name") {
return props.updatePlayerData(propertyToUpdate, newPropertyValue);
}
if (Number(newPropertyValue)) newPropertyValue = Number(newPropertyValue);
return props.updateQuestions(propertyToUpdate, newPropertyValue);
};
const setNewGame = () => {
props.resetTimeData(true);
return props.updateQuestions("currentQuestionNum", 0);
};
return (
<div id="game-menu">
to the Game Menu
<label htmlFor="name">Insert your name
<input
name="name"
defaultValue={props.playerData.name}
onChange={handleFormChanges}
>
<label htmlFor="numberOfQuestions">Set Number Of Questions:
<select
name="numberOfQuestions"
defaultValue={props.questions.numberOfQuestions}
onChange={handleFormChanges}
>
<option value="5">5
<option value="10">10
<option value="15">15
<option value="20">20
<option value="30">30
<div className="form-group">
<Link to="game">
<button type="submit" onClick={setNewGame}>
Create Game
);
}
export default GameMenu; | javascript | 16 | 0.577473 | 78 | 29.684211 | 57 | starcoderdata |
/* Copyright 2004 The Apache Software Foundation
*
* 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 org.apache.xmlbeans;
import javax.xml.namespace.QName;
/**
* A cache that can be used to pool QName instances. Each thread has one.
*/
public final class QNameCache
{
private static final float DEFAULT_LOAD = 0.70f;
private final float loadFactor;
private int numEntries = 0;
private int threshold;
private int hashmask;
private QName[] table;
/**
* Creates a QNameCache with the given initialCapacity and loadFactor.
*
* @param initialCapacity the number of entries to initially make space for
* @param loadFactor a number to control the density of the hashtable
*/
public QNameCache(int initialCapacity, float loadFactor)
{
assert initialCapacity > 0;
assert loadFactor > 0 && loadFactor < 1;
// Find a power of 2 >= initialCapacity
int capacity = 16;
while (capacity < initialCapacity)
capacity <<= 1;
this.loadFactor = loadFactor;
this.hashmask = capacity - 1;
threshold = (int)(capacity * loadFactor);
table = new QName[capacity];
}
/**
* Creates a QNameCache with the given initialCapacity.
*
* @param initialCapacity the number of entries to initially make space for
*/
public QNameCache(int initialCapacity)
{
this(initialCapacity, DEFAULT_LOAD);
}
public QName getName(String uri, String localName)
{
return getName( uri, localName, "" );
}
/**
* Fetches a QName with the given namespace and localname.
* Creates one if one is not found in the cache.
*
* @param uri the namespace
* @param localName the localname
* @param prefix the prefix
* @return the cached QName
*/
public QName getName(String uri, String localName, String prefix)
{
/*
return new QName(uri, localName, prefix);
*/
assert localName != null;
if (uri == null) uri = "";
if (prefix == null) prefix = "";
int index = hash(uri, localName, prefix) & hashmask;
while (true) {
QName q = table[index];
if (q == null)
{
numEntries++;
if (numEntries >= threshold)
rehash();
return table[index] = new QName(uri, localName, prefix);
}
else if (equals(q, uri, localName, prefix))
return q;
else
index = (index-1) & hashmask;
}
}
private void rehash()
{
int newLength = table.length * 2;
QName[] newTable = new QName[newLength];
int newHashmask = newLength - 1;
for (int i = 0 ; i < table.length ; i++)
{
QName q = table[i];
if (q != null)
{
int newIndex =
hash( q.getNamespaceURI(), q.getLocalPart(), q.getPrefix() ) & newHashmask;
while (newTable[newIndex] != null)
newIndex = (newIndex - 1) & newHashmask;
newTable[newIndex] = q;
}
}
table = newTable;
hashmask = newHashmask;
threshold = (int) (newLength * loadFactor);
}
private static int hash(String uri, String localName, String prefix)
{
int h = 0;
h += prefix.hashCode() << 10;
h += uri.hashCode() << 5;
h += localName.hashCode();
return h;
}
private static boolean equals(QName q, String uri, String localName, String prefix)
{
return
q.getLocalPart().equals(localName) &&
q.getNamespaceURI().equals(uri) &&
q.getPrefix().equals(prefix);
}
} | java | 16 | 0.56786 | 95 | 28.62 | 150 | starcoderdata |
'use strict';
import fixPrecision from 'math/fixPrecision'
/**
* Merge one object's properties onto another object. Note that although this method returns
* an object, it is the same object passed as and that object is modified
* directly. All number values are passed to for rounding.
*
* For properties that exist on both objects, values on will be replaced
* by the corresponding values from
*
* @param {Object} result The object to merge properties onto.
* @param {Object} obj The object whose properties should be copied onto
* @param {Number} precision An optional precision to pass to
* @param {Boolean} keepExisting If then do not overwrite existing properties.
*
* @returns {Object} The object.
*/
export default function mergeObjects(result, obj, precision, keepExisting) {
var prop;
if ( obj ) {
for ( prop in obj ) {
if ( obj.hasOwnProperty(prop) && (!keepExisting || !result.hasOwnProperty(prop)) ) {
result[prop] = fixPrecision(obj[prop], precision);
}
}
}
return result;
} | javascript | 16 | 0.704191 | 103 | 39.566667 | 30 | starcoderdata |
export default class PromiseNode {
constructor(fn) {
this.fn = fn
this.nextNode = null
}
setNext(node) {
return this.nextNode = node
}
next(...args) {
return this.nextNode && this.nextNode.start(...args)
}
start(...args) {
this.fn(...args)
}
fn() {
Function.prototype.setNext = function (fn) {
return this.nextFn = fn
}
Function.prototype.next = function (...args) {
return this.nextFn && this.nextFn(...args)
}
}
} | javascript | 12 | 0.584646 | 56 | 16.517241 | 29 | starcoderdata |
#include
#ifndef lint
__RCSID("$Id: prunei.c,v 1.1 2014/12/11 17:12:17 christos Exp $");
#endif
#include "global.h"
#include "structs.h"
void
prunei(lispval what)
{
extern struct types int_str;
if (((long) what) > ((long) gstart)) {
--(int_items->i);
what->i = (long) int_str.next_free;
int_str.next_free = (char *) what;
}
} | c | 10 | 0.625 | 66 | 17.526316 | 19 | starcoderdata |
public void readPuzzle() {
size = read.nextInt(); //size of puzzle
puzzleData = new int[size][size];
for(int i = 0; i < size; i++){
for (int j = 0; j < size ; j++) {
readVal = read.next(); //read each element in the text file
if(!readVal.equals("x")){
newVal = Integer.parseInt(readVal); //string is converted to an int
}
if(readVal.equals("x")){
newVal = 0; //set the string x to int 0
//get the co-ordinates for where x is located
row = i;
column = j;
}
puzzleData[i][j] = newVal; // store the int value into the 2D array
}
}
} | java | 13 | 0.42716 | 87 | 34.909091 | 22 | inline |
DWORD
VmDirThreadJoin(
PVMDIR_THREAD pThread,
PDWORD pRetVal
)
{
DWORD dwError = ERROR_SUCCESS;
union
{
DWORD dwError;
PVOID pvRet;
} retVal;
memset(&retVal, 0, sizeof(retVal));
if(pThread == NULL)
{
dwError = ERROR_INVALID_PARAMETER;
BAIL_ON_VMDIR_ERROR(dwError);
}
dwError = pthread_join(
(*pThread),
((pRetVal != NULL) ? &(retVal.pvRet) : NULL)
);
BAIL_ON_VMDIR_ERROR(dwError);
if( pRetVal != NULL )
{
// our ThreadFunction returns error code
*pRetVal = retVal.dwError;
}
error:
return dwError;
} | c | 12 | 0.555382 | 52 | 16.351351 | 37 | inline |
package br.com.zup.casadocodigo.exception.handler;
import br.com.zup.casadocodigo.exception.NotFoundException;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
@RestControllerAdvice
public class NotFoundExceptionHandler {
@ExceptionHandler(NotFoundException.class)
public ResponseEntity handle(NotFoundException e) {
return ResponseEntity.notFound().build();
}
} | java | 9 | 0.818882 | 68 | 33.6 | 15 | starcoderdata |
public static string Decrypt(string edata, string encKey, string encAlgoIvString, string saltString)
{
byte[] ddata = Convert.FromBase64String(edata);
byte[] encAlgoIv = Convert.FromBase64String(encAlgoIvString);
byte[] salt = Convert.FromBase64String(saltString);
Rfc2898DeriveBytes k2 = new Rfc2898DeriveBytes(encKey, salt);
// Try to decrypt, thus showing it can be round-tripped.
TripleDES decAlg = TripleDES.Create();
decAlg.Key = k2.GetBytes(16);
decAlg.IV = encAlgoIv;
MemoryStream decryptionStreamBacking = new MemoryStream();
CryptoStream decrypt = new CryptoStream(decryptionStreamBacking,
decAlg.CreateDecryptor(), CryptoStreamMode.Write);
decrypt.Write(ddata, 0, ddata.Length);
decrypt.Flush();
decrypt.Close();
k2.Reset();
string origData = new UTF8Encoding(false).GetString(
decryptionStreamBacking.ToArray());
return origData;
} | c# | 14 | 0.754781 | 100 | 34.6 | 25 | inline |
from __future__ import with_statement, print_function
import requests
import webbrowser
import tempfile
import os
session = requests.Session()
class Simbad(object):
URL = 'http://simbad.u-strasbg.fr/simbad/sim-coo'
def __init__(self, epic):
self.epic = epic
def form_data(self, radius):
return {
'Coord': '{0:.2f} {1:.2f}'.format(self.epic.ra, self.epic.dec),
'CooFrame': 'ICRS',
'CooEpoch': '2000',
'CooEqui': '2000',
'CooDefinedFrames': 'none',
'Radius': str(radius),
}
def send_request(self, radius=5.):
return session.post(self.URL, data=self.form_data(radius))
def open(self, radius=5.):
response = self.send_request(radius)
with tempfile.NamedTemporaryFile(suffix='.html', delete=False) as tfile:
tfile.write(response.text.encode('utf-8'))
tfile.seek(0)
url = 'file://{0}'.format(os.path.realpath(tfile.name))
webbrowser.open(url) | python | 14 | 0.582769 | 80 | 27.694444 | 36 | starcoderdata |
// $Id: TaskType.java,v 1.2 2008/09/19 03:38:21 jesse Exp $
package us.temerity.pipeline.builder.v2_4_28;
import java.util.*;
/*------------------------------------------------------------------------------------------*/
/* T A S K T Y P E */
/*------------------------------------------------------------------------------------------*/
/**
* A list of the standard task types used by version 2.4.28 of the Task Annotations, Task
* Extensions, Task Builders, and the template system.
*
* These are always used as Strings in the actual extensions and annotations, so are just
* provided here as annotations to ensure correctness between all the different pieces that
* use them. Methods are provided for String equivalents for each TaskType as well as
* retrieving a Collection of all the String equivalents which is perfect for use in dropdown
* menus and EnumParam types.
*/
public
enum TaskType
{
Concept,
Animatic,
Previs,
Setup,
Asset,
Modeling,
Rigging,
LookDev,
Shading,
Texturing,
Layout,
Assembly,
CameraLayout,
MotionEdit,
Animation,
BodyAnimation,
FaceAnimation,
Effects,
Lighting,
Rendering,
Plates,
Tracking,
Matchmove,
Mattes,
MattePainting,
PreComp,
Compositing,
CUSTOM;
/*----------------------------------------------------------------------------------------*/
/* C O N V E R S I O N */
/*----------------------------------------------------------------------------------------*/
@Override
public String
toString()
{
switch (this) {
case LookDev:
return "LookDev";
case CUSTOM:
return "[[CUSTOM]]";
default:
return super.toString();
}
}
/**
* Convert to a more human friendly string representation.
*/
public String
toTitle()
{
return toString();
}
/*----------------------------------------------------------------------------------------*/
/* A C C E S S */
/*----------------------------------------------------------------------------------------*/
/**
* Get the list of human friendly string representation for all possible values.
*/
public static ArrayList
titles()
{
ArrayList toReturn = new ArrayList
for (TaskType type : values()) {
toReturn.add(type.toTitle());
}
return toReturn;
}
/**
* Get the list of human friendly string representation for all possible values
* except the CUSTOM value.
*/
public static ArrayList
titlesNonCustom()
{
ArrayList toReturn = new ArrayList
for (TaskType type : values()) {
if (type != CUSTOM)
toReturn.add(type.toTitle());
}
return toReturn;
}
/**
* Get the list of all possible values.
*/
public static ArrayList
all()
{
return new ArrayList
}
} | java | 14 | 0.482473 | 94 | 24.104 | 125 | starcoderdata |
const func = require('../src/gas-station');
const assert = require('assert');
describe('gas-station', function () {
describe('#canCompleteCircuit()', function () {
it('should return -1 when given gas is [2,4] and cost is [3,4]', function () {
const ret = func([2, 4], [3, 4]);
assert.equal(ret, -1);
});
it('should return 0 when given gas is [2,0,1,2,3,4,0] and cost is [0,1,0,0,0,0,11]', function () {
const ret = func([2, 0, 1, 2, 3, 4, 0], [0, 1, 0, 0, 0, 0, 11]);
assert.equal(ret, 0);
});
});
}); | javascript | 21 | 0.504244 | 106 | 41.142857 | 14 | starcoderdata |
def preprocess_dataset(
epochs: int, batch_size: int, shuffle_buffer_size: int
) -> Callable[[tf.data.Dataset], tf.data.Dataset]:
"""Function returns a function for preprocessing of a dataset.
Args:
epochs (int): How many times to repeat a batch.\n
batch_size (int): Batch size.\n
shuffle_buffer_size (int): Buffer size for shuffling the dataset.\n
Returns:
Callable[[tf.data.Dataset], tf.data.Dataset]: A callable for preprocessing a dataset object.
"""
def _reshape(element: collections.OrderedDict) -> tf.Tensor:
return (tf.expand_dims(element["datapoints"], axis=-1), element["label"])
@tff.tf_computation(
tff.SequenceType(
collections.OrderedDict(
label=tff.TensorType(tf.int32, shape=(5,)),
datapoints=tff.TensorType(tf.float32, shape=(186,)),
)
)
)
def preprocess(dataset: tf.data.Dataset) -> tf.data.Dataset:
"""
Function returns shuffled dataset
"""
return (
dataset.shuffle(shuffle_buffer_size)
.repeat(epochs)
.batch(batch_size, drop_remainder=False)
.map(_reshape, num_parallel_calls=tf.data.experimental.AUTOTUNE)
)
return preprocess | python | 16 | 0.609435 | 100 | 33.052632 | 38 | inline |
/*****
*
* AbsoluteArcPath.js
*
* copyright 2002,
*
*****/
/*****
*
* setup inheritance
*
*****/
AbsoluteArcPath.prototype = new AbsolutePathSegment();
AbsoluteArcPath.prototype.constructor = AbsoluteArcPath;
AbsoluteArcPath.superclass = AbsolutePathSegment.prototype;
/*****
*
* constructor
*
*****/
function AbsoluteArcPath(params, owner, previous) {
if ( arguments.length > 0 ) {
this.init("A", params, owner, previous);
}
}
/*****
*
* init
*
*****/
AbsoluteArcPath.prototype.init = function(command, params, owner, previous) {
var point = new Array();
var y = params.pop();
var x = params.pop();
point.push( x, y );
AbsoluteArcPath.superclass.init.call(this, command, point, owner, previous);
this.rx = parseFloat( params.shift() );
this.ry = parseFloat( params.shift() );
this.angle = parseFloat( params.shift() );
this.arcFlag = parseFloat( params.shift() );
this.sweepFlag = parseFloat( params.shift() );
};
/*****
*
* toString
*
* override to handle case when Moveto is previous command
*
*****/
AbsoluteArcPath.prototype.toString = function() {
var points = new Array();
var command = "";
if ( this.previous.constructor != this.constuctor )
command = this.command;
return command +
[
this.rx, this.ry,
this.angle, this.arcFlag, this.sweepFlag,
this.handles[0].point.toString()
].join(",");
};
/*****
*
* get/set methods
*
*****/
/*****
*
* getIntersectionParams
*
*****/
AbsoluteArcPath.prototype.getIntersectionParams = function() {
return new IntersectionParams(
"Ellipse",
[
this.getCenter(),
this.rx, this.ry
]
);
};
/*****
*
* getCenter
*
*****/
AbsoluteArcPath.prototype.getCenter = function() {
var startPoint = this.previous.getLastPoint();
var endPoint = this.handles[0].point;
var rx = this.rx;
var ry = this.ry;
var angle = this.angle * Math.PI / 180;
var c = Math.cos(angle);
var s = Math.sin(angle);
var TOLERANCE = 1e-6;
var halfDiff = startPoint.subtract(endPoint).divide(2);
var x1p = halfDiff.x * c + halfDiff.y * s;
var y1p = halfDiff.x * -s + halfDiff.y * c;
var x1px1p = x1p*x1p;
var y1py1p = y1p*y1p;
var lambda = ( x1px1p / (rx*rx) ) + ( y1py1p / (ry*ry) );
if ( lambda > 1 ) {
var factor = Math.sqrt(lambda);
rx *= factor;
ry *= factor;
}
var rxrx = rx*rx;
var ryry = ry*ry;
var rxy1 = rxrx * y1py1p;
var ryx1 = ryry * x1px1p;
var factor = (rxrx*ryry - rxy1 - ryx1) / (rxy1 + ryx1);
if ( Math.abs(factor) < TOLERANCE ) factor = 0;
var sq = Math.sqrt(factor);
if ( this.arcFlag == this.sweepFlag ) sq = -sq;
var mid = startPoint.add(endPoint).divide(2);
var cxp = sq * rx*y1p / ry;
var cyp = sq * -ry*x1p / rx;
return new Point2D(
cxp*c - cyp*s + mid.x,
cxp*s + cyp*c + mid.y
);
}; | javascript | 15 | 0.555663 | 80 | 20.434483 | 145 | starcoderdata |
package cn.georgeyang.csdnblog.util;
import java.text.SimpleDateFormat;
import java.util.Locale;
public class DateUtil {
public static String getDate() {
SimpleDateFormat sdf = new SimpleDateFormat("MM月dd日 HH:mm",
Locale.CHINA);
return sdf.format(new java.util.Date());
}
} | java | 11 | 0.748252 | 61 | 22.833333 | 12 | starcoderdata |
import unittest
from pymatgen.util.testing import PymatgenTest
from matminer.featurizers.structure.symmetry import (
GlobalSymmetryFeatures,
Dimensionality,
)
from matminer.featurizers.structure.tests.base import StructureFeaturesTest
class StructureSymmetryFeaturesTest(StructureFeaturesTest):
def test_global_symmetry(self):
gsf = GlobalSymmetryFeatures()
self.assertEqual(gsf.featurize(self.diamond), [227, "cubic", 1, True, 48])
def test_dimensionality(self):
cscl = PymatgenTest.get_structure("CsCl")
graphite = PymatgenTest.get_structure("Graphite")
df = Dimensionality()
self.assertEqual(df.featurize(cscl)[0], 3)
self.assertEqual(df.featurize(graphite)[0], 2)
if __name__ == "__main__":
unittest.main() | python | 11 | 0.723235 | 82 | 29.275862 | 29 | starcoderdata |
import BaseValidator from 'ember-cp-validations/validators/base';
import Ember from 'ember';
import { validateSquareBracket } from 'gooru-web/utils/utils';
const SquareBracket = BaseValidator.extend({
/**
* @property {Service} I18N service
*/
i18n: Ember.inject.service(),
/**
* Validate string by checking square bracket formation
* @param {value} value string to validate
* @param {options} options
* @param {model} model check question type
* @return {Boolean}
*/
validate(value, options, model) {
let type = 'FIB';
var isValidFormat = validateSquareBracket(value);
var isFIB = model.get('type') === type;
if (isFIB) {
return isValidFormat
? true
: this.get('i18n').t(options.messageKey).string;
}
return true;
}
});
export default SquareBracket; | javascript | 18 | 0.662665 | 65 | 25.870968 | 31 | starcoderdata |
<?php
if (!isset($_SESSION['userlogin'])) { header("location:".$c_url."/keluar"); }
if(isset($_REQUEST['act'])){
$act=$_REQUEST['act'];
if($act=="1"){
$data = mysql_query ("select * from td_deploy_file where kd_permohonan=" . $_REQUEST['kd_download']);
if ($row = mysql_fetch_assoc($data)) {
$deskripsi = $row['deskripsi_usman'];
$filename = $row['fileusman'];
//$filename1 = $row['fileusman'];
//$filename2 = $row['filedetail'];
//$filename3 = $row['fileuat'];
$file=ROOT.DS.$deskripsi;
}
if( !file_exists($file)){ echo "Tidak Ada";}
else {
// http headers for zip downloads
header("Content-Description: File Transfer");
header("Content-type: application/octet-stream");
header("Content-Disposition: attachment; filename=\"".$filename."\"");
//header("Content-Disposition: attachment; filename1=\"".$filename1."\"");
//header("Content-Disposition: attachment; filename2=\"".$filename2."\"");
//header("Content-Disposition: attachment; filename3=\"".$filename3."\"");
header("Content-Length: ".filesize($file));
ob_end_flush();
@readfile($file);
echo '<META HTTP-EQUIV="Refresh" Content="0; URL='.$ref.'">';
}
}
else if($act=="2"){
$data = mysql_query ("select * from td_deploy_file where kd_permohonan=" . $_REQUEST['kd_download']);
if ($row = mysql_fetch_assoc($data)) {
$deskripsi = $row['deskripsi_detail'];
$filename = $row['filedetail'];
//$filename1 = $row['fileusman'];
//$filename2 = $row['filedetail'];
//$filename3 = $row['fileuat'];
$file=ROOT.DS.$deskripsi;
}
if( !file_exists($file)){ echo "Tidak Ada";}
else {
// http headers for zip downloads
header("Content-Description: File Transfer");
header("Content-type: application/octet-stream");
header("Content-Disposition: attachment; filename=\"".$filename."\"");
//header("Content-Disposition: attachment; filename1=\"".$filename1."\"");
//header("Content-Disposition: attachment; filename2=\"".$filename2."\"");
//header("Content-Disposition: attachment; filename3=\"".$filename3."\"");
header("Content-Length: ".filesize($file));
ob_end_flush();
@readfile($file);
echo '<META HTTP-EQUIV="Refresh" Content="0; URL='.$ref.'">';
}
}
else if($act=="3"){
$data = mysql_query ("select * from td_deploy_file where kd_permohonan=" . $_REQUEST['kd_download']);
if ($row = mysql_fetch_assoc($data)) {
$deskripsi = $row['deskripsi_uat'];
$filename = $row['fileuat'];
//$filename1 = $row['fileusman'];
//$filename2 = $row['filedetail'];
//$filename3 = $row['fileuat'];
$file=ROOT.DS.$deskripsi;
}
if( !file_exists($file)){ echo "Tidak Ada";}
else {
// http headers for zip downloads
header("Content-Description: File Transfer");
header("Content-type: application/octet-stream");
header("Content-Disposition: attachment; filename=\"".$filename."\"");
header("Content-Length: ".filesize($file));
ob_end_flush();
@readfile($file);
echo '<META HTTP-EQUIV="Refresh" Content="0; URL='.$ref.'">';
}
}
else if($act=="4"){
$data = mysql_query ("select * from td_deploy_file where kd_permohonan=" . $_REQUEST['kd_download']);
if ($row = mysql_fetch_assoc($data)) {
$deskripsi = $row['deskripsi'];
$filename = $row['file_name'];
$file=ROOT.DS.$deskripsi;
}
if( !file_exists($file)){ echo "Tidak Ada";}
else {
// http headers for zip downloads
header("Content-Description: File Transfer");
header("Content-type: application/octet-stream");
header("Content-Disposition: attachment; filename=\"".$filename."\"");
header("Content-Length: ".filesize($file));
ob_end_flush();
@readfile($file);
echo '<META HTTP-EQUIV="Refresh" Content="0; URL='.$ref.'">';
}
}
} | php | 23 | 0.626306 | 103 | 33.256881 | 109 | starcoderdata |
package co.fatboa.backsystem.rabbitmq;
import co.fatboa.rabbitmq.common.enums.ExchangeEnum;
import co.fatboa.rabbitmq.common.enums.QueueEnum;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
/**
* @Auther: hl
* @Date: 2018/9/6 13:16
* @Description: 消息队列业务接口
* @Modified By:
* @Version 1.0
*/
public interface IQueueMessageService extends RabbitTemplate.ConfirmCallback {
/**
* 发送消息到rabbitmq消息队列
*
* @param message 消息内容
* @param exchangeEnum 交换配置枚举
* @param queueEnum 队列配置枚举
* @throws Exception
*/
void send(Object message, ExchangeEnum exchangeEnum, QueueEnum queueEnum) throws Exception;
} | java | 7 | 0.71407 | 95 | 26.541667 | 24 | starcoderdata |
x = int(input())
ure = 0
while(1):
if(x>=500):
ure = ure+1000
x = x-500
elif(x>=5):
ure = ure+5
x = x-5
else:
break
print(ure)
| python | 9 | 0.401099 | 22 | 11.133333 | 15 | codenet |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
]
operations = [
migrations.CreateModel(
name='Event',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('name', models.CharField(max_length=255)),
('description', models.CharField(max_length=255)),
('importance', models.CharField(default=b'B', max_length=2, choices=[('A', 'Critical Importance'), ('B', 'Medium Importance'), ('C', 'Trivial Importance')])),
('date', models.DateField()),
],
options={
'ordering': ['date'],
'verbose_name': 'Event',
'verbose_name_plural': 'Events',
},
),
migrations.CreateModel(
name='EventType',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('name', models.CharField(max_length=255)),
],
options={
'ordering': ['name'],
'verbose_name': 'Event Type',
'verbose_name_plural': 'Event Types',
},
),
migrations.AddField(
model_name='event',
name='event_type',
field=models.ForeignKey(to='events.EventType'),
),
] | python | 17 | 0.5125 | 174 | 33.782609 | 46 | starcoderdata |
def _get_spatial_correlation_df(
data_root: pathlib.Path,
correlation: str,
max_delta: int = 10,
) -> pandas.DataFrame:
data_root = pathlib.Path(data_root).expanduser().resolve()
data_path = data_root.joinpath("training_dataset.nc")
logger.info(f"Loading data from {data_path.as_uri()}")
os.environ["HDF5_USE_FILE_LOCKING"] = "FALSE"
with xarray.open_dataset(data_path) as dataset:
xa = dataset["SMI"] # time x lat x lon
smi = numpy.asarray(xa.values)
lat = numpy.asarray(xa.coords["latitude"])
lon = numpy.asarray(xa.coords["longitude"])
dd_lat = lat[1] - lat[0]
dd_lon = lon[1] - lon[0]
logger.info(f"Loaded data: {smi.shape}")
data = []
corr_func = getattr(scipy.stats, correlation + "r")
for d_lat, d_lon in tqdm(itertools.product(range(-max_delta, max_delta + 1), repeat=2), total=(2 * max_delta + 1) ** 2):
a = smi
b = smi
if d_lat > 0:
a = a[:, d_lat:, :]
elif d_lat < 0:
b = b[:, -d_lat:, :]
if d_lon > 0:
a = a[:, :, d_lon:]
elif d_lon < 0:
b = b[:, :, -d_lon:]
i, j, k = list(map(min, zip(a.shape, b.shape)))
a = a[:i, :j, :k]
b = b[:i, :j, :k]
# TODO: this is wrong :)
d = ((d_lon * dd_lon * 110) ** 2 + (d_lat * dd_lat * 110) ** 2) ** 0.5
mask = numpy.isfinite(a) & numpy.isfinite(b)
corr, p = corr_func(a[mask], b[mask])
data.append((d, corr, p))
return pandas.DataFrame(data=data, columns=["distance", "correlation", "p"]) | python | 14 | 0.524734 | 124 | 39.974359 | 39 | inline |
onInput(event) {
// set the new current word
if (this.currentWord === null) {
this.currentWord = this.words[0].word;
}
// start the timer
if (this.timerStatus === _models_TimerStatus__WEBPACK_IMPORTED_MODULE_2__["TimerStatus"].DEFAULT || this.timerStatus === _models_TimerStatus__WEBPACK_IMPORTED_MODULE_2__["TimerStatus"].OFF) {
this.interactionService.setTimerStatus(_models_TimerStatus__WEBPACK_IMPORTED_MODULE_2__["TimerStatus"].ON);
}
this.checkCharacter(event);
} | javascript | 10 | 0.629295 | 199 | 49.363636 | 11 | inline |
def _select(self, to_select):
"""
Finally select photos
:param list to_select: list where process selection
:rtype: list
"""
for i in range(1, 21):
ratio = i * .05
ret = self._compute_packet_extractions(ratio, to_select)
if ret is not None:
break # use the lowest ratio found
(packet_sizes, extractions) = ret
current_packet = []
packet_size = packet_sizes.pop(0)
selected = []
for filename in to_select:
current_packet.append(filename)
if len(current_packet) == packet_size:
selected += self._process_packet(current_packet, extractions)
current_packet = []
if packet_sizes:
packet_size = packet_sizes.pop(0)
return selected | python | 13 | 0.528193 | 77 | 31.222222 | 27 | inline |
public static void configureServices (final String moduleClassName, final Object configItem,
final ConfigurableModule... extraModules)
{
// Set up the main module.
final ConfigurableModule mainModule = HcUtil.instantiate (moduleClassName);
configureAndRun (configItem, mainModule);
// And the extras.
configureServices (configItem, extraModules);
} | java | 7 | 0.701235 | 92 | 39.6 | 10 | inline |
func newPool() *pool {
p := &pool{
pool: &sync.Pool{
New: func() interface{} {
return new(bytes.Buffer)
},
},
ch: make(chan *bytes.Buffer, buffSize),
}
// It's faster with unused channel buffer in go1.7.
// TODO: need removed?
for i := 0; i < buffSize; i++ {
p.ch <- new(bytes.Buffer)
}
return p
} | go | 22 | 0.583333 | 52 | 17.055556 | 18 | inline |
package com.consol.citrus.endpoint.direct;
import com.consol.citrus.endpoint.AbstractEndpointConfiguration;
import com.consol.citrus.message.MessageQueue;
/**
* @author
*/
public class DirectEndpointConfiguration extends AbstractEndpointConfiguration {
/** Destination queue */
private MessageQueue queue;
/** Destination queue name */
private String queueName;
/**
* Set the message queue.
* @param queue the queue to set
*/
public void setQueue(MessageQueue queue) {
this.queue = queue;
}
/**
* Sets the destination queue name.
* @param queueName the queueName to set
*/
public void setQueueName(String queueName) {
this.queueName = queueName;
}
/**
* Gets the queue.
* @return the queue
*/
public MessageQueue getQueue() {
return queue;
}
/**
* Gets the queueName.
* @return the queueName
*/
public String getQueueName() {
return queueName;
}
} | java | 8 | 0.636537 | 80 | 20.44898 | 49 | starcoderdata |
// Copyright Fuzamei Corp. 2018 All Rights Reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package executor
import (
"github.com/33cn/chain33/types"
rty "github.com/GM-Publicchain/gm/plugin/dapp/relay/types"
)
func (r *relay) Exec_Create(payload *rty.RelayCreate, tx *types.Transaction, index int) (*types.Receipt, error) {
action := newRelayDB(r, tx)
return action.create(payload)
}
func (r *relay) Exec_Accept(payload *rty.RelayAccept, tx *types.Transaction, index int) (*types.Receipt, error) {
action := newRelayDB(r, tx)
return action.accept(payload)
}
func (r *relay) Exec_Revoke(payload *rty.RelayRevoke, tx *types.Transaction, index int) (*types.Receipt, error) {
action := newRelayDB(r, tx)
return action.relayRevoke(payload)
}
func (r *relay) Exec_ConfirmTx(payload *rty.RelayConfirmTx, tx *types.Transaction, index int) (*types.Receipt, error) {
action := newRelayDB(r, tx)
return action.confirmTx(payload)
}
func (r *relay) Exec_Verify(payload *rty.RelayVerify, tx *types.Transaction, index int) (*types.Receipt, error) {
action := newRelayDB(r, tx)
return action.verifyTx(payload)
}
func (r *relay) Exec_BtcHeaders(payload *rty.BtcHeaders, tx *types.Transaction, index int) (*types.Receipt, error) {
action := newRelayDB(r, tx)
return action.saveBtcHeader(payload, r.GetLocalDB())
} | go | 9 | 0.735836 | 119 | 33.439024 | 41 | starcoderdata |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Assertions;
public class SterileBag : GeneralItem {
#region fields
public Syringe syringe1;
public Syringe syringe2;
public Syringe syringe3;
public Syringe syringe4;
public Syringe syringe5;
public Syringe syringe6;
public List Syringes { get; private set; }
public bool IsClosed { get; private set; }
public bool IsSterile { get; private set; }
[SerializeField]
private GameObject childCollider;
[SerializeField]
private DragAcceptable closeButton;
private float ejectSpeed = 0.6f;
private float ejectDistance = 0.47f;
private bool finalClose;
#endregion
// Start is called before the first frame update
protected override void Start() {
base.Start();
Syringes = new List
if (syringe1 != null) SetSyringe(syringe1);
if (syringe2 != null) SetSyringe(syringe2);
if (syringe3 != null) SetSyringe(syringe3);
if (syringe4 != null) SetSyringe(syringe4);
if (syringe5 != null) SetSyringe(syringe5);
if (syringe6 != null) SetSyringe(syringe6);
ObjectType = ObjectType.SterileBag;
IsClosed = false;
IsSterile = true;
Type.On(InteractableType.Interactable);
CollisionSubscription.SubscribeToTrigger(childCollider, new TriggerListener().OnEnter(collider => OnBagEnter(collider)));
if (closeButton != null) {
closeButton.ActivateCountLimit = 1;
closeButton.OnAccept = CloseSterileBagFinal;
closeButton.Hide(true);
}
}
private void OnBagEnter(Collider other) {
Syringe syringe = Interactable.GetInteractable(other.transform) as Syringe;
if (syringe == null) {
return;
}
if (syringe.IsAttached) {
return;
}
if (Syringes.Count == 6) {
return;
}
if (syringe.State == InteractState.Grabbed) {
Hand.GrabbingHand(syringe).Connector.Connection.Remove();
}
VRInput.Hands[0].Hand.HandCollider.RemoveInteractable(syringe);
VRInput.Hands[0].Hand.ExtendedHandCollider.RemoveInteractable(syringe);
VRInput.Hands[1].Hand.HandCollider.RemoveInteractable(syringe);
VRInput.Hands[1].Hand.ExtendedHandCollider.RemoveInteractable(syringe);
SetSyringe(syringe);
if (syringe.IsClean) {
IsSterile = false;
}
if (Syringes.Count == 6) {
EnableClosing();
}
}
public override void Interact(Hand hand) {
base.Interact(hand);
if (finalClose) {
return;
}
DisableClosing();
float angle = Vector3.Angle(Vector3.down, transform.up);
if (angle < 45) {
return;
}
Logger.Print("Release syringes");
foreach (Syringe s in Syringes) {
ReleaseSyringe(s);
}
Syringes.Clear();
IsClosed = false;
}
private void SetSyringe(Syringe syringe) {
syringe.RigidbodyContainer.Disable();
SetColliders(syringe.transform, false);
syringe.transform.SetParent(transform);
syringe.transform.localPosition = ObjectPosition(Syringes.Count);
syringe.transform.localEulerAngles = new Vector3(180, 180, 0);
Syringes.Add(syringe);
}
private void SetColliders(Transform t, bool enabled) {
Collider coll = t.GetComponent
if (coll != null) {
coll.enabled = enabled;
}
foreach (Transform child in t) {
SetColliders(child, enabled);
}
}
private void ReleaseSyringe(Syringe syringe) {
StartCoroutine(MoveSyringe(syringe));
}
private IEnumerator MoveSyringe(Syringe syringe) {
float totalDistance = 0;
while (totalDistance < ejectDistance) {
float distance = Time.deltaTime * ejectSpeed;
totalDistance += distance;
syringe.transform.localPosition += Vector3.up * distance;
yield return null;
}
syringe.transform.SetParent(null);
SetColliders(syringe.transform, true);
syringe.RigidbodyContainer.Enable();
}
private void EnableClosing() {
if (closeButton == null) {
return;
}
System.Console.WriteLine("Opening sterilebag");
if (closeButton.IsGrabbed) {
Hand.GrabbingHand(closeButton).Uninteract();
}
closeButton.Hide(false);
closeButton.gameObject.SetActive(true);
}
private void DisableClosing() {
if (closeButton == null) {
return;
}
IsClosed = true;
closeButton.Hide(true);
}
public void CloseSterileBagFinal() {
finalClose = true;
closeButton.SafeDestroy();
Logger.Print("Close Sterile bag Final!");
Events.FireEvent(EventType.CloseSterileBag, CallbackData.Object(this));
CleanupObject.GetCleanup().EnableCleanup();
}
private Vector3 ObjectPosition(int index) {
Vector3 pos = new Vector3(0, 0.172f, 0);
pos.x = (0.2f / 5) * index - 0.1f;
return pos;
}
} | c# | 16 | 0.610633 | 129 | 25.450495 | 202 | starcoderdata |
package errors
// RootRepoType error value for invalid type of repo
const RootRepoType = "invalid repo, either \"bolt\" or \"legacy\" must be specified"
// ConfigureArgsMinimum error value when not enough args
const ConfigureArgsMinimum = "overrideDefaults requires at least one argument"
// EditID error value when requires an ID
const EditID = "edit requires a single ID of an existing worklog"
// PrintID error value when requires an ID
const PrintID = "no ids provided"
// PrintArgsMinimum error value when not enough args
const PrintArgsMinimum = "one flag is required"
// Format error value when wrong format
const Format = "format is not valid" | go | 5 | 0.77971 | 84 | 33.5 | 20 | starcoderdata |
package main
import (
"context"
"fmt"
"log"
"time"
"github.com/pkg/errors"
"google.golang.org/grpc"
article "github.com/tanimutomo/grpcapi-go-server/pkg/grpcs/article"
)
const host = "localhost:50051"
func main() {
doArticleRequests()
}
func doArticleRequests() {
fmt.Println("do articles")
conn, err := grpc.Dial(
host,
grpc.WithInsecure(),
grpc.WithBlock(),
)
if err != nil {
log.Fatalf("error in connection")
return
}
defer conn.Close()
c := article.NewArticleServiceClient(conn)
if err := articleGetArticleRequest(c, uint64(1)); err != nil {
log.Fatalf("error in Get: %v\n", err)
return
}
if err := articleListArticlesRequest(c); err != nil {
log.Fatalf("error in List: %v\n", err)
return
}
if err := articleCreateArticleRequest(c, "title"); err != nil {
log.Fatalf("error in Create: %v\n", err)
return
}
fmt.Println("\nend articles")
}
func articleGetArticleRequest(client article.ArticleServiceClient, id uint64) error {
fmt.Println("\ndo article/Get")
ctx, cancel := context.WithTimeout(
context.Background(),
time.Second,
)
defer cancel()
req := article.GetArticleRequest{
Id: id,
}
res, err := client.GetArticle(ctx, &req)
if err != nil {
return errors.Wrap(err, "failed to receive response")
}
log.Printf("response: %+v\n", res.GetArticle())
return nil
}
func articleListArticlesRequest(client article.ArticleServiceClient) error {
fmt.Println("\ndo article/List")
ctx, cancel := context.WithTimeout(
context.Background(),
time.Second,
)
defer cancel()
req := article.ListArticlesRequest{}
res, err := client.ListArticles(ctx, &req)
if err != nil {
return errors.Wrap(err, "failed to receive response")
}
log.Printf("response: %+v\n", res.GetArticles())
return nil
}
func articleCreateArticleRequest(client article.ArticleServiceClient, title string) error {
fmt.Println("\ndo article/Create")
ctx, cancel := context.WithTimeout(
context.Background(),
time.Second,
)
defer cancel()
req := article.CreateArticleRequest{
Title: title,
}
res, err := client.CreateArticle(ctx, &req)
if err != nil {
return errors.Wrap(err, "failed to receive response")
}
log.Printf("response: %+v\n", res.GetArticle())
return nil
} | go | 10 | 0.693252 | 91 | 19.93578 | 109 | starcoderdata |
/* eslint-disable no-console */
import pool from './index';
pool.on('connect', () => {
console.log('Connected to the database');
});
const queryText = `CREATE TABLE IF NOT EXISTS Users(
id SERIAL PRIMARY KEY,
firstname VARCHAR(128) NOT NULL,
lastname VARCHAR(128) NOT NULL,
othername VARCHAR(128) DEFAULT NULL,
email VARCHAR(128) UNIQUE NOT NULL,
phoneNo VARCHAR(128) DEFAULT NULL,
avatar VARCHAR(128) DEFAULT 'https://www.tannerfinancial.ca/wp-content/uploads/2019/01/person-placeholder-male-5-1-300x300-250x250.jpg',
partyId INTEGER DEFAULT NULL,
isAdmin BOOLEAN DEFAULT false,
password VARCHAR(124) NOT NULL,
resetPasswordToken VARCHAR(128) DEFAULT NULL,
resetPasswordExpiry BIGINT DEFAULT NULL,
created_at TIMESTAMP,
modified_at TIMESTAMP DEFAULT NULL
);
CREATE TABLE IF NOT EXISTS Parties(
id SERIAL PRIMARY KEY,
name VARCHAR(128) UNIQUE NOT NULL,
hqAddress VARCHAR(128) NOT NULL,
fullname VARCHAR(28) NOT NULL,
logoUrl VARCHAR(128) NOT NULL,
created_at TIMESTAMP,
modified_at TIMESTAMP DEFAULT NULL
);
CREATE TABLE IF NOT EXISTS Offices(
id SERIAL PRIMARY KEY,
name VARCHAR(128) UNIQUE NOT NULL,
electionDate DATE DEFAULT NULL,
type VARCHAR(128) NOT NULL,
created_at TIMESTAMP,
modified_at TIMESTAMP DEFAULT NULL
);
CREATE TABLE IF NOT EXISTS Petitions(
id SERIAL PRIMARY KEY,
created_by INTEGER REFERENCES Users(id),
officeId INTEGER REFERENCES Offices(id),
title VARCHAR(128) NOT NULL,
text TEXT NOT NULL,
evidence VARCHAR(128),
created_at TIMESTAMP
);
CREATE TABLE IF NOT EXISTS Candidates(
id SERIAL,
confirm BOOLEAN DEFAULT false,
officeId INTEGER REFERENCES Offices(id),
partyId INTEGER REFERENCES Parties(id) NOT NULL,
userId INTEGER REFERENCES Users(id),
PRIMARY KEY (userId, officeId)
);
CREATE TABLE IF NOT EXISTS Votes(
id SERIAL,
officeId INTEGER REFERENCES Offices(id),
candidateId INTEGER NOT NULL,
voterId INTEGER REFERENCES Users(id),
created_at TIMESTAMP,
PRIMARY KEY (officeId, voterId)
);
`;
pool.query(queryText)
.then((res) => {
console.log(res);
pool.end();
}).catch((err) => {
console.log(err);
pool.end();
}); | javascript | 11 | 0.634176 | 144 | 30.1625 | 80 | starcoderdata |
using FluentAssertions;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;
using SixLabors.ImageSharp.Formats;
using SixLabors.ImageSharp.Formats.Gif;
using SixLabors.ImageSharp.Formats.Jpeg;
using SixLabors.ImageSharp.Formats.Png;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using Timeline.Models;
using Timeline.Tests.Helpers;
using Xunit;
using Xunit.Abstractions;
namespace Timeline.Tests.IntegratedTests
{
public class UserAvatarTest : IntegratedTestBase
{
public UserAvatarTest(ITestOutputHelper testOutputHelper) : base(testOutputHelper)
{
}
[Fact]
public async Task Test()
{
ByteData mockAvatar = new ByteData(
ImageHelper.CreatePngWithSize(100, 100),
PngFormat.Instance.DefaultMimeType
);
using (var client = await CreateClientAsUser())
{
await client.TestGetAssertNotFoundAsync("users/usernotexist/avatar", errorCode: ErrorCodes.NotExist.User);
var env = TestApp.Host.Services.GetRequiredService
var defaultAvatarData = await File.ReadAllBytesAsync(Path.Combine(env.ContentRootPath, "default-avatar.png"));
async Task TestAvatar(string username, byte[] data)
{
var res = await client.GetAsync($"users/{username}/avatar");
res.StatusCode.Should().Be(HttpStatusCode.OK);
var contentTypeHeader = res.Content.Headers.ContentType;
contentTypeHeader.Should().NotBeNull();
contentTypeHeader!.MediaType.Should().Be("image/png");
var body = await res.Content.ReadAsByteArrayAsync();
body.Should().Equal(data);
}
await TestAvatar("user1", defaultAvatarData);
await CacheTestHelper.TestCache(client, "users/user1/avatar");
await TestAvatar("admin", defaultAvatarData);
{
using var content = new ByteArrayContent(new[] { (byte)0x00 });
content.Headers.ContentLength = null;
content.Headers.ContentType = new MediaTypeHeaderValue("image/png");
await client.TestSendAssertInvalidModelAsync(HttpMethod.Put, "users/user1/avatar", content);
}
{
using var content = new ByteArrayContent(new[] { (byte)0x00 });
content.Headers.ContentLength = 1;
await client.TestSendAssertInvalidModelAsync(HttpMethod.Put, "users/user1/avatar", content);
}
{
using var content = new ByteArrayContent(new[] { (byte)0x00 });
content.Headers.ContentLength = 0;
content.Headers.ContentType = new MediaTypeHeaderValue("image/png");
await client.TestSendAssertInvalidModelAsync(HttpMethod.Put, "users/user1/avatar", content);
}
{
await client.TestPutByteArrayAsync("users/user1/avatar", new[] { (byte)0x00 }, "image/notaccept", expectedStatusCode: HttpStatusCode.UnsupportedMediaType);
}
{
using var content = new ByteArrayContent(new[] { (byte)0x00 });
content.Headers.ContentLength = 1000 * 1000 * 11;
content.Headers.ContentType = new MediaTypeHeaderValue("image/png");
await client.TestSendAssertErrorAsync(HttpMethod.Put, "users/user1/avatar", content, errorCode: ErrorCodes.Common.Content.TooBig);
}
{
using var content = new ByteArrayContent(new[] { (byte)0x00 });
content.Headers.ContentLength = 2;
content.Headers.ContentType = new MediaTypeHeaderValue("image/png");
await client.TestSendAssertInvalidModelAsync(HttpMethod.Put, "users/user1/avatar", content);
}
{
using var content = new ByteArrayContent(new[] { (byte)0x00, (byte)0x01 });
content.Headers.ContentLength = 1;
content.Headers.ContentType = new MediaTypeHeaderValue("image/png");
await client.TestSendAssertInvalidModelAsync(HttpMethod.Put, "users/user1/avatar", content);
}
{
await client.TestPutByteArrayAssertErrorAsync("users/user1/avatar", new[] { (byte)0x00 }, "image/png", errorCode: ErrorCodes.Image.CantDecode);
await client.TestPutByteArrayAssertErrorAsync("users/user1/avatar", mockAvatar.Data, "image/jpeg", errorCode: ErrorCodes.Image.UnmatchedFormat);
await client.TestPutByteArrayAssertErrorAsync("users/user1/avatar", ImageHelper.CreatePngWithSize(100, 200), "image/png", errorCode: ErrorCodes.Image.BadSize);
}
{
await client.TestPutByteArrayAsync("users/user1/avatar", mockAvatar.Data, mockAvatar.ContentType);
await TestAvatar("user1", mockAvatar.Data);
}
IEnumerable<(string, IImageFormat)> formats = new (string, IImageFormat)[]
{
("image/jpeg", JpegFormat.Instance),
("image/gif", GifFormat.Instance),
("image/png", PngFormat.Instance),
};
foreach ((var mimeType, var format) in formats)
{
await client.TestPutByteArrayAsync("users/user1/avatar", ImageHelper.CreateImageWithSize(100, 100, format), mimeType);
}
await client.TestPutByteArrayAssertErrorAsync("users/admin/avatar", new[] { (byte)0x00 }, "image/png",
expectedStatusCode: HttpStatusCode.Forbidden, errorCode: ErrorCodes.Common.Forbid);
await client.TestDeleteAssertForbiddenAsync("users/admin/avatar", errorCode: ErrorCodes.Common.Forbid);
for (int i = 0; i < 2; i++) // double delete should work.
{
await client.TestDeleteAsync("users/user1/avatar");
await TestAvatar("user1", defaultAvatarData);
}
}
// Authorization check.
using (var client = await CreateClientAsAdministrator())
{
await client.TestPutByteArrayAsync("users/user1/avatar", mockAvatar.Data, mockAvatar.ContentType);
await client.TestDeleteAsync("users/user1/avatar");
await client.TestPutByteArrayAssertErrorAsync("users/usernotexist/avatar", new[] { (byte)0x00 }, "image/png", errorCode: ErrorCodes.NotExist.User);
await client.TestDeleteAssertErrorAsync("users/usernotexist/avatar");
}
// bad username check
using (var client = await CreateClientAsAdministrator())
{
await client.TestGetAssertInvalidModelAsync("users/u!ser/avatar");
await client.TestPutByteArrayAssertInvalidModelAsync("users/u!ser/avatar", ImageHelper.CreatePngWithSize(100, 100), "image/png");
await client.TestDeleteAssertInvalidModelAsync("users/u!ser/avatar");
}
}
[Fact]
public async Task AvatarPutReturnETag()
{
using var client = await CreateClientAsUser();
EntityTagHeaderValue? etag;
{
var image = ImageHelper.CreatePngWithSize(100, 100);
var res = await client.TestPutByteArrayAsync("users/user1/avatar", image, PngFormat.Instance.DefaultMimeType);
etag = res.Headers.ETag;
etag.Should().NotBeNull();
etag!.Tag.Should().NotBeNullOrEmpty();
}
{
var res = await client.GetAsync("users/user1/avatar");
res.StatusCode.Should().Be(HttpStatusCode.OK);
res.Headers.ETag.Should().Be(etag);
res.Headers.ETag!.Tag.Should().Be(etag.Tag);
}
}
}
} | c# | 21 | 0.578249 | 179 | 44.934426 | 183 | starcoderdata |
"""Given a matrix of size n X m find the number of unique paths that start from 0,0 of the matrix and end
at n-1,m-1 if you can only move RIGHT and DOWN."""
class Solution:
def numPaths(self, n, m):
memo = [[0 for _ in range(m)] for _ in range(n)]
for i in range(len(memo)):
memo[i][0] = 1
for i in range(len(memo[0])):
memo[0][i] = 1
for i in range(1, len(memo)):
for j in range(1, len(memo[0])):
memo[i][j] = memo[i-1][j] + memo[i][j-1]
return memo[-1][-1]
if __name__ == '__main__':
solution = Solution()
print(solution.numPaths(2, 3)) | python | 15 | 0.524615 | 105 | 26.125 | 24 | starcoderdata |
valor = int(input())
val = valor
cem = cinquenta = vinte = dez = cinco = dois = um = 0
if int(valor//100) >= 1:
cem = int(valor//100)
valor -= cem*100
if int(valor//50) >= 1:
cinquenta = int(valor//50)
valor -= cinquenta*50
if int(valor//20) >= 1:
vinte = int(valor//20)
valor -= vinte*20
if int(valor//10) >= 1:
dez = int(valor//10)
valor -= dez*10
if int(valor//5) >= 1:
cinco = int(valor//5)
valor -= cinco*5
if int(valor//2) >= 1:
dois = int(valor//2)
valor -= dois*2
if int(valor//1) >= 1:
um = int(valor//1)
valor -= um*1
print(val)
print("{} nota(s) de R$ 100,00\n{} nota(s) de R$ 50,00".format(cem, cinquenta))
print("{} nota(s) de R$ 20,00\n{} nota(s) de R$ 10,00".format(vinte, dez))
print("{} nota(s) de R$ 5,00\n{} nota(s) de R$ 2,00".format(cinco, dois))
print("{} nota(s) de R$ 1,00".format(um)) | python | 9 | 0.563555 | 79 | 20.820513 | 39 | starcoderdata |
package com.freedom.lauzy.ticktockmusic.presenter;
import com.freedom.lauzy.interactor.FavoriteSongUseCase;
import com.freedom.lauzy.model.FavoriteSongBean;
import com.freedom.lauzy.ticktockmusic.base.BaseRxPresenter;
import com.freedom.lauzy.ticktockmusic.contract.FavoriteContract;
import com.freedom.lauzy.ticktockmusic.function.DefaultDisposableObserver;
import com.freedom.lauzy.ticktockmusic.function.RxHelper;
import com.freedom.lauzy.ticktockmusic.model.SongEntity;
import com.freedom.lauzy.ticktockmusic.model.mapper.FavoriteMapper;
import com.lauzy.freedom.librarys.common.LogUtil;
import java.util.List;
import javax.inject.Inject;
import io.reactivex.annotations.NonNull;
/**
* Desc : 我的喜欢Presenter
* Author : Lauzy
* Date : 2017/9/13
* Blog : http://www.jianshu.com/u/e76853f863a9
* Email :
*/
public class FavoritePresenter extends BaseRxPresenter
implements FavoriteContract.Presenter {
private FavoriteSongUseCase mFavoriteSongUseCase;
private FavoriteMapper mFavoriteMapper;
@Inject
FavoritePresenter(FavoriteSongUseCase favoriteSongUseCase, FavoriteMapper favoriteMapper) {
mFavoriteSongUseCase = favoriteSongUseCase;
mFavoriteMapper = favoriteMapper;
}
@Override
public void loadFavoriteSongs() {
mFavoriteSongUseCase.favoriteSongObservable()
.compose(RxHelper.ioMain())
.subscribeWith(new DefaultDisposableObserver {
@Override
public void onNext(@NonNull List favoriteSongBeen) {
super.onNext(favoriteSongBeen);
if (getView() == null) {
return;
}
List songEntities = mFavoriteMapper.transform(favoriteSongBeen);
if (songEntities != null && !songEntities.isEmpty()) {
getView().getFavoriteSongs(songEntities);
} else {
getView().emptyView();
}
}
@Override
public void onError(@NonNull Throwable e) {
super.onError(e);
if (getView() == null) {
return;
}
getView().emptyView();
}
});
}
@Override
public void clearFavoriteSongs() {
mFavoriteSongUseCase.clearFavoriteSongs().compose(RxHelper.ioMain())
.subscribe(integer -> {
if (getView()==null) {
return;
}
getView().clearSongs();
});
}
@Override
public void deleteFavoriteSong(long songId, int position) {
mFavoriteSongUseCase.deleteFavoriteSong(songId).subscribe(aLong -> {
if (getView() == null) {
return;
}
getView().deleteFavoriteSong(position);
});
}
} | java | 18 | 0.58706 | 100 | 35.241379 | 87 | starcoderdata |
package quick
import (
"context"
"fmt"
"log"
"net/http"
"sync"
"time"
"github.com/go-redis/redis/v7"
"github.com/labstack/echo/v4"
"github.com/robfig/cron/v3"
"gorm.io/gorm"
)
type (
// OnShutdown 在App停止前执行的方法
OnShutdown func()
// Job 是定时任务
Job func(context.Context) error
// Context 是模块初始化时可获取的资源和可调用的方法
Context interface {
// GET 注册HTTP GET路由
GET(path string, h echo.HandlerFunc, m ...echo.MiddlewareFunc)
// POST 注册HTTP POST路由
POST(path string, h echo.HandlerFunc, m ...echo.MiddlewareFunc)
// 注册中间件
Use(middlewares ...echo.MiddlewareFunc)
// Schedule 注册定时任务
Schedule(expr string, job Job)
// Publish 发布事件
Publish(topic string, payload string)
// Subscribe 订阅事件
Subscribe(topic string, cb func(string))
// GetDB 获取数据库连接实例
GetDB() *gorm.DB
// GetRedis 获取Redis连接实例
GetRedis() *redis.Client
// Logf 日志方法
Logf(format string, args ...interface{})
// Provide 提供资源,和Take配套使用
Provide(id string, obj interface{})
// Take 获取资源,即通过Provide提供的资源
Take(id string) interface{}
// RegisterShutdown 注册停止服务前调用的方法
// 当服务停止时,会先停止HTTP服务、定时任务、事件系统,当这3者停止后,
// 调用通过ReigsterShutdown注册的方法
RegisterShutdown(hook OnShutdown)
}
)
type quickContext struct {
muModule sync.Mutex
mu sync.RWMutex
config Config
logger *log.Logger
c *cron.Cron
e *echo.Echo
db *gorm.DB
redisClient *redis.Client
resource map[string]interface{}
modules []Module
shutdownHooks []OnShutdown
pubsub PubSub
}
// GET 注册HTTP GET路由
func (a *quickContext) GET(path string, h echo.HandlerFunc, m ...echo.MiddlewareFunc) {
a.e.GET(path, h, m...)
}
// POST 注册HTTP POST路由
func (a *quickContext) POST(path string, h echo.HandlerFunc, m ...echo.MiddlewareFunc) {
a.e.POST(path, h, m...)
}
// Use 注册HTTP中间件
// 详细说明参考echo的文档 https://echo.labstack.com/middleware/#root-level-after-router
func (a *quickContext) Use(middlewares ...echo.MiddlewareFunc) {
a.e.Use(middlewares...)
}
// Schedule 注册定时任务
func (a *quickContext) Schedule(expr string, job Job) {
fn := func() {
ctx := context.Background()
if err := job(ctx); err != nil {
a.Logf("[ERROR] Cron Job Execute Failed: %s", err.Error())
}
}
job0 := cron.NewChain(cron.DelayIfStillRunning(cron.PrintfLogger(a.logger))).Then((cron.FuncJob(fn)))
entryID, err := a.c.AddJob(expr, job0)
if err != nil {
a.Logf("[ERROR] Cron Job Add Failed: %s, expr: %s", err.Error(), expr)
} else {
a.Logf("[INFO] Cron Job Add Success: %d", entryID)
}
}
// Publish 发布事件
func (a *quickContext) Publish(topic string, payload string) {
a.pubsub.Publish(topic, payload)
}
// Subscribe 订阅事件
func (a *quickContext) Subscribe(topic string, cb func(string)) {
a.pubsub.Subscribe(topic, cb)
}
// GetDB 获取数据库连接实例
func (a *quickContext) GetDB() *gorm.DB {
return a.db
}
// GetRedis 获取Redis连接实例
func (a *quickContext) GetRedis() *redis.Client {
return a.redisClient
}
// Provide 提供资源,和Take配套使用
func (a *quickContext) Provide(id string, obj interface{}) {
a.mu.Lock()
defer a.mu.Unlock()
a.resource[id] = obj
}
// Take 从quickContext中获取资源,即通过Provide提供的资源
func (a *quickContext) Take(id string) interface{} {
a.mu.RLock()
defer a.mu.RUnlock()
return a.resource[id]
}
// RegisterShutdown 注册停止服务前调用的方法
// 当服务停止时,会先停止HTTP服务、定时任务、事件系统,当这3者停止后,
// 调用通过ReigsterShutdown注册的方法
func (a *quickContext) RegisterShutdown(hook OnShutdown) {
a.mu.Lock()
defer a.mu.Unlock()
a.shutdownHooks = append(a.shutdownHooks, hook)
}
func (a *quickContext) Logf(format string, args ...interface{}) {
a.logger.Output(2, fmt.Sprintf(format, args...))
}
// registerModules 注册模块,详情见Module
func (a *quickContext) registerModules(modules ...Module) {
a.muModule.Lock()
defer a.muModule.Unlock()
for _, module := range modules {
module.Init(a)
}
a.modules = append(a.modules, modules...)
}
func (a *quickContext) migrate(migrators ...Migrator) {
for _, migrator := range migrators {
if err := migrator(a.db); err != nil {
panic(fmt.Sprintf("Migrate failed: %s\n", err.Error()))
}
}
}
// start 启动服务,并返回停止服务的方法
// 内部会根据配置启动HTTP服务、定时任务服务
func (a *quickContext) start() func() {
a.c.Start()
go func() {
if err := a.e.Start(a.config.APIAddr); err != nil && err != http.ErrServerClosed {
a.Logf("[ERROR] Echo Start Failed: %s", err.Error())
panic(err.Error())
}
}()
return func() {
var wg sync.WaitGroup
wg.Add(1)
go func() {
defer wg.Done()
cCtx := a.c.Stop()
<-cCtx.Done()
a.Logf("[INFO] Cron Stopped")
}()
wg.Add(1)
go func() {
defer wg.Done()
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
if err := a.e.Shutdown(ctx); err != nil {
a.Logf("[ERROR] Echo Shutdown Failed: %s", err.Error())
}
a.Logf("[INFO] Echo Stopped")
}()
wg.Add(1)
go func() {
defer wg.Done()
a.pubsub.Close()
a.Logf("[INFO] PubSub Stopped")
}()
wg.Wait()
for _, hook := range a.shutdownHooks {
func() {
defer func() {
if err := recover(); err != nil {
a.Logf("Shutdown Hook Triggered Error: %#v", err)
}
}()
hook()
}()
}
a.Logf("[INFO] Stopped")
}
} | go | 23 | 0.656493 | 102 | 22.171171 | 222 | starcoderdata |
from grpclib.exceptions import GRPCError
from insanic.exceptions import APIException
from interstellar.exceptions import InvalidArgumentError
from grpc_test_monkey_v1.monkey_grpc import ApeServiceBase, MonkeyServiceBase
from grpc_test_monkey_v1.monkey_pb2 import ApeResponse, MonkeyResponse
class PlanetOfTheApes(ApeServiceBase):
async def GetChimpanzee(self,
stream: 'grpclib.server.Stream[grpc_test_monkey.monkey_pb2.ApeRequest, grpc_test_monkey.monkey_pb2.ApeResponse]'):
request = await stream.recv_message()
if request.include == "sound":
response = ApeResponse(id=int(request.id), extra="woo woo ahh ahh")
else:
response = ApeResponse(id=int(request.id), extra="i don't know")
await stream.send_message(response)
async def GetGorilla(self,
stream: 'grpclib.server.Stream[grpc_test_monkey.monkey_pb2.ApeRequest, grpc_test_monkey.monkey_pb2.ApeResponse]'):
request = await stream.recv_message()
if request.include == "sound":
response = ApeResponse(id=int(request.id), extra="raaahhh")
else:
response = ApeResponse(id=int(request.id), extra="i don't know")
await stream.send_message(response)
class PlanetOfTheMonkeys(MonkeyServiceBase):
async def GetMonkey(self,
stream: 'grpclib.server.Stream[grpc_test_monkey.monkey_pb2.MonkeyRequest, grpc_test_monkey.monkey_pb2.MonkeyResponse]'):
request = await stream.recv_message()
if request.id == "uncaught_exception":
raise Exception("Something Broke")
elif request.id == "api_exception":
raise APIException("help")
elif request.id == "grpc_error":
raise InvalidArgumentError(message="bad bad")
response = MonkeyResponse()
await stream.send_message(response) | python | 16 | 0.66946 | 144 | 36.431373 | 51 | starcoderdata |
package com.jeremysu1.catscalore;
import android.graphics.Color;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import com.squareup.picasso.Picasso;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Random;
public class GameActivity extends AppCompatActivity {
private ArrayList gridButtons = new ArrayList<>();
private ArrayList gridColors = new ArrayList<>();
private ArrayList remainingButtons = new ArrayList<>(Arrays.asList(0,1,2,3,4,5,6,7,8,9,10,11));
private int current_button = -1;
private Random rand = new Random();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game2);
gridButtons.add((Button) findViewById(R.id.btn0));
gridButtons.add((Button) findViewById(R.id.btn1));
gridButtons.add((Button) findViewById(R.id.btn2));
gridButtons.add((Button) findViewById(R.id.btn3));
gridButtons.add((Button) findViewById(R.id.btn4));
gridButtons.add((Button) findViewById(R.id.btn5));
gridButtons.add((Button) findViewById(R.id.btn6));
gridButtons.add((Button) findViewById(R.id.btn7));
gridButtons.add((Button) findViewById(R.id.btn8));
gridButtons.add((Button) findViewById(R.id.btn9));
gridButtons.add((Button) findViewById(R.id.btn10));
gridButtons.add((Button) findViewById(R.id.btn11));
for(int i = 0; i < 12; i++) {
setRandomColors(i, rand);
}
getImage();
selectNewColor();
}
private void getImage(){
ImageView catPic = (ImageView) findViewById(R.id.catImage);
Picasso.with(this).load("https://thecatapi.com/api/images/get?type=jpg").into(catPic);
}
private void setRandomColors(int button_id, Random rand){
Button btn = gridButtons.get(button_id);
int R = rand.nextInt(256);
int G = rand.nextInt(256);
int B = rand.nextInt(256);
int A = 255;
int color = Color.argb(A, R, G, B);
gridColors.add(button_id, color);
btn.setBackgroundColor(color);
}
private void selectNewColor(){
int size = remainingButtons.size();
if(size == 0)
return;
int new_button_id_index = rand.nextInt(size);
int new_button_id = remainingButtons.get(new_button_id_index);
int color = gridColors.get(new Integer(new_button_id));
int red = Color.red(color);
int green = Color.green(color);
int blue = Color.blue(color);
current_button = new_button_id;
TextView r_view = (TextView) findViewById(R.id.redTextView);
TextView g_view = (TextView) findViewById(R.id.greenTextView);
TextView b_view = (TextView) findViewById(R.id.blueTextView);
r_view.setText(Integer.toString(red));
g_view.setText(Integer.toString(green));
b_view.setText(Integer.toString(blue));
}
public void gridButtonClick(View view){
Button btn;
int id = view.getId();
switch(id){
case R.id.btn0 :
if(current_button == 0) {
btn = (Button) findViewById(R.id.btn0);
btn.setVisibility(View.INVISIBLE);
//remainingButtons.set(0, -1);
remainingButtons.remove(new Integer(0));
selectNewColor();
}
break;
case R.id.btn1 :
if(current_button == 1) {
btn = (Button) findViewById(R.id.btn1);
btn.setVisibility(View.INVISIBLE);
//remainingButtons.set(1, -1);
remainingButtons.remove(new Integer(1));
selectNewColor();
}
break;
case R.id.btn2 :
if(current_button == 2) {
btn = (Button) findViewById(R.id.btn2);
btn.setVisibility(View.INVISIBLE);
//remainingButtons.set(2, -1);
remainingButtons.remove(new Integer(2));
selectNewColor();
}
break;
case R.id.btn3 :
if(current_button == 3) {
btn = (Button) findViewById(R.id.btn3);
btn.setVisibility(View.INVISIBLE);
//remainingButtons.set(3, -1);
remainingButtons.remove(new Integer(3));
selectNewColor();
}
break;
case R.id.btn4 :
if(current_button == 4) {
btn = (Button) findViewById(R.id.btn4);
btn.setVisibility(View.INVISIBLE);
//remainingButtons.set(4, -1);
remainingButtons.remove(new Integer(4));
selectNewColor();
}
break;
case R.id.btn5 :
if(current_button == 5) {
btn = (Button) findViewById(R.id.btn5);
btn.setVisibility(View.INVISIBLE);
//remainingButtons.set(5, -1);
remainingButtons.remove(new Integer(5));
selectNewColor();
}
break;
case R.id.btn6 :
if(current_button == 6) {
btn = (Button) findViewById(R.id.btn6);
btn.setVisibility(View.INVISIBLE);
//remainingButtons.set(6, -1);
remainingButtons.remove(new Integer(6));
selectNewColor();
}
break;
case R.id.btn7 :
if(current_button == 7) {
btn = (Button) findViewById(R.id.btn7);
btn.setVisibility(View.INVISIBLE);
//remainingButtons.set(7, -1);
remainingButtons.remove(new Integer(7));
selectNewColor();
}
break;
case R.id.btn8 :
if(current_button == 8) {
btn = (Button) findViewById(R.id.btn8);
btn.setVisibility(View.INVISIBLE);
//remainingButtons.set(8, -1);
remainingButtons.remove(new Integer(8));
selectNewColor();
}
break;
case R.id.btn9 :
if(current_button == 9) {
btn = (Button) findViewById(R.id.btn9);
btn.setVisibility(View.INVISIBLE);
//remainingButtons.set(9, -1);
remainingButtons.remove(new Integer(9));
selectNewColor();
}
break;
case R.id.btn10 :
if(current_button == 10) {
btn = (Button) findViewById(R.id.btn10);
btn.setVisibility(View.INVISIBLE);
//remainingButtons.set(10, -1);
remainingButtons.remove(new Integer(10));
selectNewColor();
}
break;
case R.id.btn11 :
if(current_button == 11) {
btn = (Button) findViewById(R.id.btn11);
btn.setVisibility(View.INVISIBLE);
//remainingButtons.set(11, -1);
remainingButtons.remove(new Integer(11));
selectNewColor();
}
break;
}
}
} | java | 17 | 0.516367 | 108 | 37.674877 | 203 | starcoderdata |
'use strict';
angular.module('BaubleApp')
.factory('DeleteModal', ['$modal', function DeleteModal($modal) {
return function(resource, resourceData, str) {
str = str || resourceData.str;
var modalInstance = $modal.open({
templateUrl: 'views/delete-modal.html',
controller: function($scope, $modalInstance) {
$scope.str = str;
//$scope.resourceName = resource.name;
$scope.delete = function() {
// return the $httpPromise
$modalInstance.close(resource.remove(resourceData));
};
$scope.cancel = function() {
$modalInstance.dismiss('cancel');
};
}
});
return modalInstance.result;
};
}]); | javascript | 22 | 0.477054 | 76 | 28.28125 | 32 | starcoderdata |
private void changesInAttribute(MeasurementDecision decision, UMLAttributeSlot slot)
{
// Check if the attribute has changed
org.eclipse.uml2.uml.Type type = main.umlAbstraction.getMeasurementType (decision);
org.eclipse.uml2.uml.Type pastType = slot.measurementAttribute.getType();
// If the past type was Custom
if (main.umlAbstraction.isCustomType(pastType))
{
// Simply delete the past CustomType (even if CustomType is chosen again FIXME)
main.umlAbstraction.removePackageableElement(slot.measurementAttribute.getType());
}
if (pastType != type)
{
// A change of type happened
// Update the type
slot.measurementAttribute.setType(type);
// TODO: display in the ui that a change happened
}
} | java | 10 | 0.714101 | 85 | 33.227273 | 22 | inline |
from pylights.program import Program
from animations.basic import ColorFade
class RedFade(Program):
def __init__(self):
super(RedFade, self).__init__('red fade')
def get_animation(self, led):
hue = 0
return ColorFade(hue, led)
def run():
print('running red fade')
RedFade()
if __name__ == "__main__":
run() | python | 10 | 0.605634 | 49 | 19.882353 | 17 | starcoderdata |
package PetSitters.repository;
import PetSitters.entity.Chat;
import PetSitters.entity.Contract;
import PetSitters.entity.Message;
import org.springframework.data.mongodb.repository.MongoRepository;
import java.util.List;
public interface MessageRepository extends MongoRepository<Message, String> {
List findByIsVisibleAndUserWhoSendsAndUserWhoReceivesOrderByWhenSentDesc(Boolean b, String usernameWhoSends, String usernameWhoReceives);
List findByUserWhoSendsAndUserWhoReceivesOrderByWhenSentDesc(String usernameWhoSends, String usernameWhoReceives);
List findByUserWhoSendsAndIsVisible(String usernameWhoSends,Boolean isVisible);
void deleteByUserWhoSendsAndUserWhoReceives(String usernameWhoSends, String usernameWhoReceives);
List findByIsMultimediaAndUserWhoSendsAndUserWhoReceives(Boolean b, String usernameWhoSends, String usernameWhoReceives);
boolean existsByIsVisibleAndUserWhoSendsAndUserWhoReceives(Boolean b, String usernameWhoSends, String usernameWhoReceives);
boolean existsByUserWhoSendsAndUserWhoReceives(String username, String usernameA);
} | java | 7 | 0.85815 | 150 | 46.291667 | 24 | starcoderdata |
namespace osu.Memory.Processes.Enums
{
public enum MemoryProtect
{
PageNoAccess = 0x00000001,
PageReadonly = 0x00000002,
PageReadWrite = 0x00000004,
PageWriteCopy = 0x00000008,
PageExecute = 0x00000010,
PageExecuteRead = 0x00000020,
PageExecuteReadWrite = 0x00000040,
PageExecuteWriteCopy = 0x00000080,
PageGuard = 0x00000100,
PageNoCache = 0x00000200,
PageWriteCombine = 0x00000400
}
} | c# | 7 | 0.661654 | 43 | 28.555556 | 18 | starcoderdata |
package org.xcorpion.jdiff.api;
import java.lang.reflect.Type;
import java.util.Set;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
public interface ObjectDiffMapper {
@Nonnull
DiffNode diff(@Nullable T src, @Nullable T target);
T applyDiff(@Nullable T src, @Nonnull DiffNode diffs);
T applyDiff(@Nullable T src, @Nonnull DiffNode diffs, @Nonnull Set mergingStrategies);
EqualityChecker getEqualityChecker(@Nonnull Class cls);
DiffingHandler getDiffingHandler(@Nonnull Class cls);
DiffingHandler getDiffingHandler(@Nonnull Type type);
MergingHandler getMergingHandler(@Nonnull Class cls);
MergingHandler getMergingHandler(@Nonnull Type type);
ObjectDiffMapper registerEqualityChecker(@Nonnull Class cls, @Nonnull EqualityChecker<? super T> equalityChecker);
ObjectDiffMapper registerDiffingHandler(@Nonnull Class cls, @Nonnull DiffingHandler<? super T> diffingHandler);
ObjectDiffMapper registerDiffingHandler(@Nonnull AbstractDiffingHandler diffingHandler);
ObjectDiffMapper registerMergingHandler(@Nonnull Class cls, @Nonnull MergingHandler<? super T> mergingHandler);
ObjectDiffMapper registerMergingHandler(@Nonnull AbstractMergingHandler mergingHandler);
ObjectDiffMapper enable(@Nonnull Feature feature);
ObjectDiffMapper disable(@Nonnull Feature feature);
boolean isEnabled(@Nonnull Feature feature);
boolean isMergingStrategyEnabled(
@Nonnull Feature.MergingStrategy strategy,
@Nullable Set oneOffStrategies
);
} | java | 9 | 0.754651 | 125 | 34.102041 | 49 | starcoderdata |
TEST_F(InstantSearchPrerendererTest, PrerenderRequestCancelled) {
PrerenderSearchQuery(ASCIIToUTF16("foo"));
// Cancel the prerender request.
InstantSearchPrerenderer* prerenderer = GetInstantSearchPrerenderer();
prerenderer->Cancel();
EXPECT_EQ(static_cast<PrerenderHandle*>(NULL), prerender_handle());
// Open a search results page. Prerendered page does not exists for |url|.
// Make sure the browser navigates the current tab to this |url|.
GURL url("https://www.google.com/alt#quux=foo&strk");
browser()->OpenURL(content::OpenURLParams(url, Referrer(), CURRENT_TAB,
ui::PAGE_TRANSITION_TYPED,
false));
EXPECT_NE(GetPrerenderURL(), GetActiveWebContents()->GetURL());
EXPECT_EQ(url, GetActiveWebContents()->GetURL());
} | c++ | 11 | 0.670264 | 76 | 48.117647 | 17 | inline |
using Newtonsoft.Json;
namespace Bot
{
public static class ObjectExtensions
{
public static string ToJson(this object update)
{
return JsonConvert.SerializeObject(update);
}
}
} | c# | 11 | 0.667845 | 55 | 20.769231 | 13 | starcoderdata |
package log
import (
"io"
"net"
"os"
"runtime"
"strconv"
"strings"
"sync"
)
// TSVLogger represents an active logging object that generates lines of TSV output to an io.Writer.
type TSVLogger struct {
Separator byte
Writer io.Writer
}
// TSVEntry represents a tsv log entry. It is instanced by one of TSVLogger and finalized by the Msg method.
type TSVEntry struct {
buf []byte
w io.Writer
sep byte
}
var tepool = sync.Pool{
New: func() interface{} {
return new(TSVEntry)
},
}
// New starts a new tsv message.
func (l *TSVLogger) New() (e *TSVEntry) {
e = tepool.Get().(*TSVEntry)
e.sep = l.Separator
if l.Writer != nil {
e.w = l.Writer
} else {
e.w = os.Stderr
}
if e.sep == 0 {
e.sep = '\t'
}
e.buf = e.buf[:0]
return
}
// Timestamp adds the current time as UNIX timestamp
func (e *TSVEntry) Timestamp() *TSVEntry {
var tmp [11]byte
sec, _ := walltime()
// separator
tmp[10] = e.sep
// seconds
is := sec % 100 * 2
sec /= 100
tmp[9] = smallsString[is+1]
tmp[8] = smallsString[is]
is = sec % 100 * 2
sec /= 100
tmp[7] = smallsString[is+1]
tmp[6] = smallsString[is]
is = sec % 100 * 2
sec /= 100
tmp[5] = smallsString[is+1]
tmp[4] = smallsString[is]
is = sec % 100 * 2
sec /= 100
tmp[3] = smallsString[is+1]
tmp[2] = smallsString[is]
is = sec % 100 * 2
tmp[1] = smallsString[is+1]
tmp[0] = smallsString[is]
// append to buf
e.buf = append(e.buf, tmp[:]...)
return e
}
// TimestampMS adds the current time with milliseconds as UNIX timestamp
func (e *TSVEntry) TimestampMS() *TSVEntry {
var tmp [14]byte
sec, nsec := walltime()
// separator
tmp[13] = e.sep
// milli seconds
a := int64(nsec) / 1000000
is := a % 100 * 2
tmp[12] = smallsString[is+1]
tmp[11] = smallsString[is]
tmp[10] = byte('0' + a/100)
// seconds
is = sec % 100 * 2
sec /= 100
tmp[9] = smallsString[is+1]
tmp[8] = smallsString[is]
is = sec % 100 * 2
sec /= 100
tmp[7] = smallsString[is+1]
tmp[6] = smallsString[is]
is = sec % 100 * 2
sec /= 100
tmp[5] = smallsString[is+1]
tmp[4] = smallsString[is]
is = sec % 100 * 2
sec /= 100
tmp[3] = smallsString[is+1]
tmp[2] = smallsString[is]
is = sec % 100 * 2
tmp[1] = smallsString[is+1]
tmp[0] = smallsString[is]
// append to buf
e.buf = append(e.buf, tmp[:]...)
return e
}
// Caller adds the file:line of to the entry.
func (e *TSVEntry) Caller(depth int) *TSVEntry {
_, file, line, _ := runtime.Caller(depth)
if i := strings.LastIndex(file, "/"); i >= 0 {
file = file[i+1:]
}
e.buf = append(e.buf, file...)
e.buf = append(e.buf, ':')
e.buf = strconv.AppendInt(e.buf, int64(line), 10)
e.buf = append(e.buf, e.sep)
return e
}
// Bool append the b as a bool to the entry.
func (e *TSVEntry) Bool(b bool) *TSVEntry {
if b {
e.buf = append(e.buf, '1', e.sep)
} else {
e.buf = append(e.buf, '0', e.sep)
}
return e
}
// Byte append the b as a byte to the entry.
func (e *TSVEntry) Byte(b byte) *TSVEntry {
e.buf = append(e.buf, b, e.sep)
return e
}
// Float64 adds a float64 to the entry.
func (e *TSVEntry) Float64(f float64) *TSVEntry {
e.buf = strconv.AppendFloat(e.buf, f, 'f', -1, 64)
e.buf = append(e.buf, e.sep)
return e
}
// Int64 adds a int64 to the entry.
func (e *TSVEntry) Int64(i int64) *TSVEntry {
e.buf = strconv.AppendInt(e.buf, i, 10)
e.buf = append(e.buf, e.sep)
return e
}
// Uint64 adds a uint64 to the entry.
func (e *TSVEntry) Uint64(i uint64) *TSVEntry {
e.buf = strconv.AppendUint(e.buf, i, 10)
e.buf = append(e.buf, e.sep)
return e
}
// Float32 adds a float32 to the entry.
func (e *TSVEntry) Float32(f float32) *TSVEntry {
return e.Float64(float64(f))
}
// Int adds a int to the entry.
func (e *TSVEntry) Int(i int) *TSVEntry {
return e.Int64(int64(i))
}
// Int32 adds a int32 to the entry.
func (e *TSVEntry) Int32(i int32) *TSVEntry {
return e.Int64(int64(i))
}
// Int16 adds a int16 to the entry.
func (e *TSVEntry) Int16(i int16) *TSVEntry {
return e.Int64(int64(i))
}
// Int8 adds a int8 to the entry.
func (e *TSVEntry) Int8(i int8) *TSVEntry {
return e.Int64(int64(i))
}
// Uint32 adds a uint32 to the entry.
func (e *TSVEntry) Uint32(i uint32) *TSVEntry {
return e.Uint64(uint64(i))
}
// Uint16 adds a uint16 to the entry.
func (e *TSVEntry) Uint16(i uint16) *TSVEntry {
return e.Uint64(uint64(i))
}
// Uint8 adds a uint8 to the entry.
func (e *TSVEntry) Uint8(i uint8) *TSVEntry {
return e.Uint64(uint64(i))
}
// Uint adds a uint to the entry.
func (e *TSVEntry) Uint(i uint) *TSVEntry {
return e.Uint64(uint64(i))
}
// Str adds a string to the entry.
func (e *TSVEntry) Str(val string) *TSVEntry {
e.buf = append(e.buf, val...)
e.buf = append(e.buf, e.sep)
return e
}
// Bytes adds a bytes as string to the entry.
func (e *TSVEntry) Bytes(val []byte) *TSVEntry {
e.buf = append(e.buf, val...)
e.buf = append(e.buf, e.sep)
return e
}
// IPAddr adds IPv4 or IPv6 Address to the entry.
func (e *TSVEntry) IPAddr(ip net.IP) *TSVEntry {
if ip4 := ip.To4(); ip4 != nil {
e.buf = strconv.AppendInt(e.buf, int64(ip4[0]), 10)
e.buf = append(e.buf, '.')
e.buf = strconv.AppendInt(e.buf, int64(ip4[1]), 10)
e.buf = append(e.buf, '.')
e.buf = strconv.AppendInt(e.buf, int64(ip4[2]), 10)
e.buf = append(e.buf, '.')
e.buf = strconv.AppendInt(e.buf, int64(ip4[3]), 10)
} else {
e.buf = append(e.buf, ip.String()...)
}
e.buf = append(e.buf, e.sep)
return e
}
// Msg sends the entry.
func (e *TSVEntry) Msg() {
if len(e.buf) != 0 {
e.buf[len(e.buf)-1] = '\n'
}
_, _ = e.w.Write(e.buf)
if cap(e.buf) <= bbcap {
tepool.Put(e)
}
} | go | 14 | 0.630004 | 108 | 21.095618 | 251 | starcoderdata |
#include
#include
#include
#include
int main()
{
const std::string client = "maimai_dump_.exe";
auto process = MaiSense::Process::Create(client, true);
auto injector = MaiSense::Launcher::Injector(&process);
auto remote = injector.Inject("MaiSense.dll");
process.Resume();
return 0;
} | c++ | 8 | 0.6875 | 60 | 24.0625 | 16 | starcoderdata |
<?php
namespace app\commands;
use yii\console\Controller;
class PartnerController extends Controller
{
/**
* 数据迁移
*/
public function actionTransfer()
{
}
} | php | 6 | 0.65566 | 42 | 10.833333 | 18 | starcoderdata |
const { readFile, writeFile } = require('fs').promises;
const path = require('path');
class Store {
constructor(filename) {
this.path = path.join(__dirname, `${filename}.json`);
}
getAll() {
return readFile(this.path, 'utf-8').then(data => JSON.parse(data));
}
write(data) {
return writeFile(this.path, JSON.stringify(data));
}
push(item) {
return this.getAll().then(data => this.write([...data, item]));
}
clear() {
return this.write([]);
}
}
const noteTaking = new Store('db');
module.exports = noteTaking; | javascript | 13 | 0.616216 | 71 | 18.857143 | 28 | starcoderdata |
action="index.php?Page=contact-form" method="post">
<label for="name/firstname">Nom/Prénom :
<input type="text" id="name" name="user_name">
<label for="mail">e-mail :
<input type="user_email" id="mail" name="user_mail">
<label for="msg"> Message :
<textarea id="msg" name="user_message">
<input type="submit" value="envoyer" />
<?php
echo "Nom prénom : ".$_POST['user_name'];
echo "Mail : ".$_POST['user_mail'];
echo "Message : ".$_POST['user_message'];
?> | php | 5 | 0.579032 | 64 | 27.227273 | 22 | starcoderdata |
// -------------------------------------------------------------
/*
* Copyright (c) 2013 Battelle Memorial Institute
* Licensed under modified BSD License. A copy of this license can be found
* in the LICENSE file in the top level directory of this distribution.
*/
// -------------------------------------------------------------
// -------------------------------------------------------------
/**
* @file small_matrix_solve.cpp
* @author William A. Perkins
* @date 2014-01-31 11:39:25 d3g096
*
* @brief
*
*
*/
// -------------------------------------------------------------
#include <iostream>
#include <boost/scoped_ptr.hpp>
#include <boost/format.hpp>
#include <boost/assert.hpp>
#include "gridpack/parallel/parallel.hpp"
#include "gridpack/environment/environment.hpp"
#include "gridpack/utilities/exception.hpp"
#include "math.hpp"
#include "linear_matrix_solver.hpp"
// -------------------------------------------------------------
// Main Program
// -------------------------------------------------------------
int
main(int argc, char **argv)
{
gridpack::Environment env(argc, argv);
gridpack::parallel::Communicator world;
gridpack::parallel::Communicator self = world.split(world.rank());
boost::scoped_ptr<gridpack::utility::Configuration>
config(gridpack::utility::Configuration::configuration());
config->open("small_matrix_solve.xml", world);
gridpack::utility::Configuration::CursorPtr configCursor = config->getCursor("SmallMatrixSolve");
BOOST_ASSERT(configCursor);
boost::scoped_ptr<gridpack::math::Matrix>
A(new gridpack::math::Matrix(self, 9, 9)),
B(new gridpack::math::Matrix(self, 9, 3, gridpack::math::Matrix::Dense)),
Xorig(new gridpack::math::Matrix(self, 9, 3, gridpack::math::Matrix::Dense));
A->setElement(0, 0, gridpack::ComplexType(0, -33.8085));
A->setElement(0, 3, gridpack::ComplexType(0, 17.3611));
A->setElement(1, 1, gridpack::ComplexType(0, -24.3472));
A->setElement(1, 7, gridpack::ComplexType(0, 16));
A->setElement(2, 2, gridpack::ComplexType(0, -22.5806));
A->setElement(2, 5, gridpack::ComplexType(0, 17.0648));
A->setElement(3, 0, gridpack::ComplexType(0, 17.3611));
A->setElement(3, 3, gridpack::ComplexType(0, -39.9954));
A->setElement(3, 4, gridpack::ComplexType(0, 10.8696));
A->setElement(3, 8, gridpack::ComplexType(0, 11.7647));
A->setElement(4, 3, gridpack::ComplexType(0, 10.8696));
A->setElement(4, 4, gridpack::ComplexType(0.934, -17.0633));
A->setElement(4, 5, gridpack::ComplexType(0, 5.88235));
A->setElement(5, 2, gridpack::ComplexType(0, 17.0648));
A->setElement(5, 4, gridpack::ComplexType(0, 5.88235));
A->setElement(5, 5, gridpack::ComplexType(0, -32.8678));
A->setElement(5, 6, gridpack::ComplexType(0, 9.92063));
A->setElement(6, 5, gridpack::ComplexType(0, 9.92063));
A->setElement(6, 6, gridpack::ComplexType(1.03854, -24.173));
A->setElement(6, 7, gridpack::ComplexType(0, 13.8889));
A->setElement(7, 1, gridpack::ComplexType(0, 16));
A->setElement(7, 6, gridpack::ComplexType(0, 13.8889));
A->setElement(7, 7, gridpack::ComplexType(0, -36.1001));
A->setElement(7, 8, gridpack::ComplexType(0, 6.21118));
A->setElement(8, 3, gridpack::ComplexType(0, 11.7647));
A->setElement(8, 7, gridpack::ComplexType(0, 6.21118));
A->setElement(8, 8, gridpack::ComplexType(1.33901, -18.5115));
A->ready();
A->print();
A->save("small_matrix_solve.mat");
B->setElement(0, 0, gridpack::ComplexType(0, 16.4474));
B->setElement(1, 1, gridpack::ComplexType(0, 8.34725));
B->setElement(2, 2, gridpack::ComplexType(0, 5.51572));
B->ready();
B->print();
// This is the expected answer
Xorig->setElement(0, 0, gridpack::ComplexType(-0.802694, 0.0362709));
Xorig->setElement(0, 1, gridpack::ComplexType(-0.0826026, 0.0215508));
Xorig->setElement(0, 2, gridpack::ComplexType(-0.066821, 0.0163025));
Xorig->setElement(1, 0, gridpack::ComplexType(-0.16276 , 0.0424636 ));
Xorig->setElement(1, 1, gridpack::ComplexType(-0.656183, 0.032619));
Xorig->setElement(1, 2, gridpack::ComplexType(-0.117946, 0.0235926));
Xorig->setElement(2, 0, gridpack::ComplexType(-0.199254 , 0.0486126));
Xorig->setElement(2, 1, gridpack::ComplexType(-0.178494, 0.035704));
Xorig->setElement(2, 2, gridpack::ComplexType(-0.55177, 0.0277253));
Xorig->setElement(3, 0, gridpack::ComplexType(-0.615773 , 0.0706327));
Xorig->setElement(3, 1, gridpack::ComplexType(-0.160858, 0.0419673));
Xorig->setElement(3, 2, gridpack::ComplexType(-0.130125, 0.031747));
Xorig->setElement(4, 0, gridpack::ComplexType(-0.478041 , 0.0933363));
Xorig->setElement(4, 1, gridpack::ComplexType(-0.180994, 0.052928));
Xorig->setElement(4, 2, gridpack::ComplexType(-0.220702, 0.0449514));
Xorig->setElement(5, 0, gridpack::ComplexType(-0.263657 , 0.0643252));
Xorig->setElement(5, 1, gridpack::ComplexType(-0.236187, 0.0472443));
Xorig->setElement(5, 2, gridpack::ComplexType(-0.406892, 0.0366867));
Xorig->setElement(6, 0, gridpack::ComplexType(-0.247322 , 0.0741512));
Xorig->setElement(6, 1, gridpack::ComplexType(-0.368152, 0.0637251));
Xorig->setElement(6, 2, gridpack::ComplexType(-0.268082, 0.0472012));
Xorig->setElement(7, 0, gridpack::ComplexType(-0.247672 , 0.0646169));
Xorig->setElement(7, 1, gridpack::ComplexType(-0.476813, 0.0496364));
Xorig->setElement(7, 2, gridpack::ComplexType(-0.179478, 0.0359009));
Xorig->setElement(8, 0, gridpack::ComplexType(-0.467188 , 0.100364));
Xorig->setElement(8, 1, gridpack::ComplexType(-0.257734, 0.0619692));
Xorig->setElement(8, 2, gridpack::ComplexType(-0.139857, 0.0423387));
Xorig->ready();
Xorig->print();
boost::scoped_ptr<gridpack::math::LinearMatrixSolver>
solver(new gridpack::math::LinearMatrixSolver(*A));
solver->configure(configCursor);
boost::scoped_ptr<gridpack::math::Matrix>
X(solver->solve(*B));
X->scale(-1.0);
X->add(*Xorig);
X->print();
std::cout << world.rank()
<< ": Solution norm2: " << X->norm2()
<< std::endl;
solver.reset();
A.reset();
B.reset();
Xorig.reset();
X.reset();
return 0;
}
| c++ | 11 | 0.630983 | 99 | 41.356164 | 146 | research_code |
import { LOGIN, SIGNUP, RESET,CUSTDETAILSUPDATE,CUSTGRPDETAILSUPDATE,PROFDTLS ,RECACTDTLS,PNDINVLIST} from "../constants/action-types";
export function login(payload) {
console.log("dispatching the login action", payload);
return { type: LOGIN, payload };
}
export function signup(payload) {
console.log("dispatching the signup action");
return { type: SIGNUP, payload };
}
export function reset(payload) {
console.log("dispatching the reset action");
return { type: RESET, payload };
}
export function updateCustDetails(payload) {
console.log("dispatching the update cust details action");
return { type: CUSTDETAILSUPDATE, payload };
}
export function updateUserGrpList(payload) {
console.log("dispatching the update cust group details action");
return { type: CUSTGRPDETAILSUPDATE, payload };
}
export function saveProfDtls(payload) {
console.log("dispatching the config details action");
return { type: PROFDTLS, payload };
}
export function saveRecentAct(payload) {
console.log("dispatching the config details action");
return { type: RECACTDTLS, payload };
}
export function pendingInviteList(payload) {
console.log("dispatching the config details action");
return { type: PNDINVLIST, payload };
} | javascript | 10 | 0.748403 | 135 | 31.947368 | 38 | starcoderdata |
// Native modules
const assert = require('assert');
const http = require('http');
// Express
const express = require('express');
const app = express();
app.use(express.json());
app.use(express.urlencoded({extended:true}));
// Middlewares
const error_middleware = require('../app/errors');
// Routes
const routes = require("./routes");
var server;
// init initializes a server with all its middlewares/routes
module.exports.init = function(){
return new Promise((resolve, reject) => {
if (server){
console.warn("Trying to init server again.");
reject('Server already initialized');
}
server = {};
server.app = app;
routes.setup(server.app);
// Setup error middleware
server.app.use(error_middleware.handler);
resolve();
});
}
// get returns the active server instance
module.exports.get = function() {
assert.ok(server, "Server not initialized, please call init().");
return server;
}
// run creates the server connection by listening
module.exports.run = function(port) {
assert.ok(server, "Server not initialized, please call init().");
server.conn = http.createServer(server.app);
return new Promise((resolve, reject) => {
server.conn.on('listening', () => {
resolve();
})
server.conn.on('error', err => {
reject(err);
})
server.conn.listen(port);
})
} | javascript | 16 | 0.618953 | 69 | 24.15 | 60 | starcoderdata |
def get_payment_info(self, call, keypair):
"""
Retrieves fee estimation via RPC for given extrinsic
Parameters
----------
call Call object to estimate fees for
keypair Keypair of the sender, does not have to include private key because no valid signature is required
Returns
-------
Dict with payment info
E.g. `{'class': 'normal', 'partialFee': 151000000, 'weight': 217238000}`
"""
# Check requirements
if not isinstance(call, GenericCall):
raise TypeError("'call' must be of type Call")
if not isinstance(keypair, Keypair):
raise TypeError("'keypair' must be of type Keypair")
# No valid signature is required for fee estimation
signature = '0x' + '00' * 64
# Create extrinsic
extrinsic = self.create_signed_extrinsic(
call=call,
keypair=keypair,
signature=signature
)
payment_info = self.rpc_request('payment_queryInfo', [str(extrinsic.data)])
# convert partialFee to int
if 'result' in payment_info:
payment_info['result']['partialFee'] = int(payment_info['result']['partialFee'])
return payment_info['result']
else:
raise SubstrateRequestException(payment_info['error']['message']) | python | 12 | 0.590116 | 114 | 31.785714 | 42 | inline |
async function main() {
const indexLines = [];
const outPath = resolve(ROOT, INDEX_JS);
const entries = await fs.promises.readdir(ROOT, { withFileTypes: true });
for (const entry of entries) {
if (entry.isSymbolicLink()) continue;
if (entry.isDirectory()) {
const submoduleIndexPath = resolve(ROOT, entry.name, INDEX_JS);
if (await canRead(submoduleIndexPath)) {
indexLines.push(exportLine(entry.name));
}
} else if (entry.isFile()) {
if (includeFile(entry.name)) {
if (entry.name !== INDEX_JS) {
const bareName = entry.name.slice(0, -3);
indexLines.push(exportLine(bareName));
}
}
}
}
indexLines.sort();
indexLines.push(''); // blank line at the end
await fs.promises.writeFile(outPath, indexLines.join('\n'), {
encoding: 'utf8',
});
} | javascript | 18 | 0.613396 | 75 | 28.37931 | 29 | inline |
public void setSession(IoSession newSession) {
logger.trace("setSession - addr: {} session: {} previous: {}", transportAddress, newSession, session.get());
if (newSession == null || newSession.equals(NULL_SESSION)) {
session.set(NULL_SESSION);
} else if (session.compareAndSet(NULL_SESSION, newSession)) {
// set the connection attribute
newSession.setAttribute(Ice.CONNECTION, this);
// flag the session as selected / active!
newSession.setAttribute(Ice.ACTIVE_SESSION, Boolean.TRUE);
//} else if (session.get().getId() != newSession.getId()) {
//logger.warn("Sessions don't match, current: {} incoming: {}", session.get(), newSession);
} else {
logger.warn("Session already set: {} incoming: {}", session.get(), newSession);
}
} | java | 11 | 0.604598 | 116 | 57.066667 | 15 | inline |
public void onClick(DialogInterface dialog, int whichButton) {
String fileName = editText.getText().toString();
if(operation == OPERATION_LOAD) {
loadDBFromFile(fileName);
//reload the content into the displaying fragment containing the RecyclerView
//https://developer.android.com/training/basics/fragments/communicating
ItemListAdminFragment fragment = (ItemListAdminFragment)
getSupportFragmentManager().findFragmentById(R.id.fragment_container);
fragment.setItems(store.getList());
}else if(operation == OPERATION_SAVE){
saveDBToFile(fileName);
}
} | java | 12 | 0.575835 | 98 | 50.933333 | 15 | inline |
<?php
namespace Acquia\Blt\Robo\Wizards;
/**
* Class SetupWizard.
*
* @package Acquia\Blt\Robo\Wizards
*/
class SetupWizard extends Wizard {
/**
* Wizard for generating setup files.
*
* Executes blt blt:init:settings command.
*/
public function wizardGenerateSettingsFiles() {
$missing = FALSE;
if (!$this->getInspector()->isDrupalLocalSettingsFilePresent()) {
$this->logger->warning(" is missing.");
$missing = TRUE;
}
elseif (!$this->getInspector()->isHashSaltPresent()) {
$this->logger->warning(" is missing.");
$missing = TRUE;
}
if ($missing) {
$confirm = $this->confirm("Do you want to generate this required settings file(s)?");
if ($confirm) {
$bin = $this->getConfigValue('composer.bin');
$this->executor
->execute("$bin/blt blt:init:settings")->printOutput(TRUE)->run();
}
}
}
/**
* Wizard for installing Drupal.
*
* Executes blt drupal:install.
*/
public function wizardInstallDrupal() {
if (!$this->getInspector()->isDatabaseAvailable()) {
return FALSE;
}
if (!$this->getInspector()->isDrupalInstalled()) {
$this->logger->warning('Drupal is not installed.');
$confirm = $this->confirm("Do you want to install Drupal?");
if ($confirm) {
$bin = $this->getConfigValue('composer.bin');
$this->executor
->execute("$bin/blt setup")
->interactive($this->input()->isInteractive())
->run();
$this->getInspector()->clearState();
}
}
}
} | php | 17 | 0.598571 | 117 | 26.983333 | 60 | starcoderdata |
#include "ViewportCameraController.h"
ViewportCameraController::ViewportCameraController()
:m_2DCamera(-m_AspectRatio * m_ZoomLevel, m_AspectRatio* m_ZoomLevel, -m_ZoomLevel, m_ZoomLevel),
m_3DCamera(m_FovY, m_AspectRatio, m_PerspectiveNearDepth, m_PerspectiveFarDepth)
{
m_Is3DCamera = false;
m_CurrentCamera = &m_2DCamera;
m_2DCameraPosition = Vector3f(0.0f, 0.0f, 0.0f);
m_3DCameraPosition = Vector3f(0.0f, 0.0f, 0.0f);
}
ViewportCameraController::~ViewportCameraController()
{
}
void ViewportCameraController::OnUpdate(float deltaTime)
{
PROFILE_FUNCTION();
if (m_Is3DCamera)
{
Vector2f movement;
if (Input::IsKeyPressed(KEY_A))
{
movement.x -= 1.0f;
}
if (Input::IsKeyPressed(KEY_D))
{
movement.x += 1.0f;
}
if (Input::IsKeyPressed(KEY_W))
{
movement.y += 1.0f;
}
if (Input::IsKeyPressed(KEY_S))
{
movement.y -= +1.0f;
}
movement.Normalize();
movement = movement * m_TranslationSpeed * deltaTime;
Strafe(movement.x);
Walk(movement.y);
if (Input::IsKeyPressed(KEY_Q))
{
Raise(-1.0f * m_TranslationSpeed * deltaTime, Vector3f(0.0f, 1.0f, 0.0f));
}
if (Input::IsKeyPressed(KEY_E))
{
Raise(+1.0f * m_TranslationSpeed * deltaTime, Vector3f(0.0f, 1.0f, 0.0f));
}
Pitch(-m_MouseRelativeVelocity.y * m_Sensitivity);
Yaw(-m_MouseRelativeVelocity.x * m_Sensitivity);
//make sure right and forward are orthogonal to each other
Vector3f up = Vector3f::Cross(m_Right, m_Forward).GetNormalized();
m_Right = Vector3f::Cross(m_Forward, up).GetNormalized();
//m_MouseRelativeVelocity = Vector2f();
}
else
{
//TODO: 2D camera controller
}
}
Vector3f ViewportCameraController::GetPosition() const
{
if (m_Is3DCamera)
return m_3DCameraPosition;
else
return m_2DCameraPosition;
}
void ViewportCameraController::SetAspectRatio(const float& aspectRatio)
{
m_AspectRatio = aspectRatio;
m_3DCamera.SetProjection(m_FovY, m_AspectRatio, m_PerspectiveNearDepth, m_PerspectiveFarDepth);
m_2DCamera.SetProjection(-m_ZoomLevel * m_AspectRatio, m_ZoomLevel * m_AspectRatio, -m_ZoomLevel, m_ZoomLevel);
}
Matrix4x4 ViewportCameraController::GetTransformMatrix()
{
if (m_Is3DCamera)
return Matrix4x4::Translate(m_3DCameraPosition) * Matrix4x4::Rotate({ m_3DCameraRotation });
else
return Matrix4x4::Translate(m_2DCameraPosition);
}
void ViewportCameraController::OnMouseMotion(Vector2f mousePosition)
{
m_MouseRelativeVelocity = (mousePosition - m_MouseLastPosition);
if (Input::IsMouseButtonPressed(MOUSE_BUTTON_MIDDLE))
{
Application::GetWindow().SetCursor(Cursors::ResizeAll);
if (m_Is3DCamera)
{
Strafe(-m_MouseRelativeVelocity.x * 5.0f / (m_ViewPortSize.x * 0.5f / m_AspectRatio));
Raise(m_MouseRelativeVelocity.y * 5.0f / (m_ViewPortSize.y * 0.5f), m_Up);
}
else
{
m_2DCameraPosition.x -= m_MouseRelativeVelocity.x * (m_ZoomLevel / (m_ViewPortSize.x * 0.5f / m_AspectRatio));
m_2DCameraPosition.y += m_MouseRelativeVelocity.y * (m_ZoomLevel / (m_ViewPortSize.y * 0.5f));
}
}
m_MouseLastPosition = mousePosition;
}
void ViewportCameraController::OnMouseWheel(float mouseWheel)
{
if (m_Is3DCamera)
{
if (Input::IsMouseButtonPressed(MOUSE_BUTTON_RIGHT))
{
float ln = 10.0f * log(m_TranslationSpeed);
m_TranslationSpeed = std::clamp((float)exp(0.1f * (ln + mouseWheel)), FLT_MIN, 1000.0f);
if (m_TranslationSpeed < 0.0f)
m_TranslationSpeed = FLT_MIN;
}
else
{
Walk(mouseWheel * m_TranslationSpeed);
}
}
else
{
m_ZoomLevel -= mouseWheel / 4.0f;
m_ZoomLevel = std::clamp(m_ZoomLevel, 0.25f, 1000.0f);
m_2DCamera.SetProjection(-m_AspectRatio * m_ZoomLevel, m_AspectRatio * m_ZoomLevel, -m_ZoomLevel, m_ZoomLevel);
m_TranslationSpeed = m_ZoomLevel;
}
}
void ViewportCameraController::SwitchCamera(bool is3D)
{
if (!is3D)
{
m_CurrentCamera = &m_2DCamera;
m_Is3DCamera = false;
}
else
{
m_CurrentCamera = &m_3DCamera;
m_Is3DCamera = true;
}
}
void ViewportCameraController::LookAt(Vector3f focalPoint, float distance)
{
if(m_Is3DCamera)
m_3DCameraPosition = focalPoint - (distance * m_Forward);
else
{
m_2DCameraPosition = focalPoint;
m_2DCameraPosition.z = 0.0f;
}
}
void ViewportCameraController::Walk(float d)
{
m_3DCameraPosition = (d * m_Forward) + m_3DCameraPosition;
}
void ViewportCameraController::Strafe(float d)
{
m_3DCameraPosition = (d * m_Right) + m_3DCameraPosition;
}
void ViewportCameraController::Raise(float d, const Vector3f& up)
{
m_3DCameraPosition = (d * up) + m_3DCameraPosition;
}
void ViewportCameraController::Pitch(float angle)
{
m_3DCameraRotation.x += angle;
if (m_3DCameraRotation.x > PI * 0.5)
m_3DCameraRotation.x = (float)(PI * 0.5);
else if (m_3DCameraRotation.x < -(PI * 0.5))
m_3DCameraRotation.x = -(float)(PI * 0.5);
else
{
Matrix4x4 rotation = Matrix4x4::Rotate(Quaternion(m_Right, angle));
m_Forward = rotation * m_Forward;
m_Forward.Normalize();
m_Up = Vector3f::Cross(m_Right, m_Forward);
m_Up.Normalize();
}
}
void ViewportCameraController::Yaw(float angle)
{
m_3DCameraRotation.y += angle;
if (m_3DCameraRotation.y > PI)
m_3DCameraRotation.y -= (float)(PI * 2);
else if (m_3DCameraRotation.y < -PI)
m_3DCameraRotation.y += (float)(PI * 2);
Matrix4x4 rotation = Matrix4x4::Rotate(Quaternion(Vector3f(0.0f, 1.0f, 0.0f), angle));
m_Right = rotation * m_Right;
m_Right.Normalize();
m_Forward = Vector3f::Cross(m_Up, m_Right);
m_Forward.Normalize();
m_Up = Vector3f::Cross(m_Right, m_Forward);
m_Up.Normalize();
} | c++ | 17 | 0.70299 | 113 | 23.13913 | 230 | starcoderdata |
public static String getDeviceIdWithPhoneType(Context context) {
TelephonyManager manager = (TelephonyManager) context
.getSystemService(Context.TELEPHONY_SERVICE);
String id = manager.getDeviceId();
if (id == null) {
id = "NotAvailable";
}
switch (manager.getPhoneType()) {
case TelephonyManager.PHONE_TYPE_NONE:
return "NONE:" + id;
case TelephonyManager.PHONE_TYPE_GSM:
return "GSM:IMEI=" + id;
case TelephonyManager.PHONE_TYPE_CDMA:
return "CDMA:MEID/ESN=" + id;
// for API Level 11 or above
// case TelephonyManager.PHONE_TYPE_SIP:
// return "SIP";
default:
return "UNKNOWN:ID=" + id;
}
} | java | 9 | 0.538275 | 64 | 34.826087 | 23 | inline |
def test_broker_db_fully_setup(self):
"""Simple 'integration test' that checks a Broker DB had its schema setup"""
connection = connections["data_broker"]
with connection.cursor() as cursor:
cursor.execute("select * from pg_tables where tablename = 'alembic_version'")
results = cursor.fetchall()
assert results is not None
assert len(results) > 0
assert len(str(results[0][0])) > 0 | python | 11 | 0.629956 | 89 | 49.555556 | 9 | inline |
public class Horse : Piece
{
public Horse(Board board, PieceColor color) : base(board, color)
{
points = 3;
}
protected override bool AttackAvailable(int y, int x)
{
if (!EnemySquare(y, x)) return false;
if (y == Y + 1 || y == Y - 1)
{
if (x == X + 2)
return true;
if (x == X - 2)
return true;
}
else if (y == Y + 2 || y == Y - 2)
{
if (x == X + 1)
return true;
if (x == X - 1)
return true;
}
return false;
}
protected override bool LegalMove(int y, int x)
{
if (!EmptySpot(y, x)) return false;
if (y == Y + 1 || y == Y - 1)
{
if (x == X + 2)
return true;
if (x == X - 2)
return true;
}
else if (y == Y + 2 || y == Y - 2)
{
if (x == X + 1)
return true;
if (x == X - 1)
return true;
}
return false;
}
protected override void ShowAvailableMoves()
{
SetAvailableMoveIfNoAlliesNotUnderAttack(Y + 1, X + 2);
SetAvailableMoveIfNoAlliesNotUnderAttack(Y + 1, X - 2);
SetAvailableMoveIfNoAlliesNotUnderAttack(Y + 2, X + 1);
SetAvailableMoveIfNoAlliesNotUnderAttack(Y + 2, X - 1);
SetAvailableMoveIfNoAlliesNotUnderAttack(Y - 1, X + 2);
SetAvailableMoveIfNoAlliesNotUnderAttack(Y - 1, X - 2);
SetAvailableMoveIfNoAlliesNotUnderAttack(Y - 2, X + 1);
SetAvailableMoveIfNoAlliesNotUnderAttack(Y - 2, X - 1);
}
public override bool NoMoves()
{
if (MoveLegal(Y + 1, X + 2)) return false;
if (MoveLegal(Y + 1, X - 2)) return false;
if (MoveLegal(Y + 2, X + 1)) return false;
if (MoveLegal(Y + 2, X - 1)) return false;
if (MoveLegal(Y - 1, X + 2)) return false;
if (MoveLegal(Y - 1, X - 2)) return false;
if (MoveLegal(Y - 2, X + 1)) return false;
if (MoveLegal(Y - 2, X - 1)) return false;
return true;
}
} | c# | 11 | 0.477209 | 68 | 29.295775 | 71 | starcoderdata |
package controllers;
import static java.util.Arrays.asList;
import java.util.Queue;
import javax.inject.Named;
import org.apache.commons.lang.StringUtils;
import play.mvc.Controller;
public class Application extends Controller {
@Named("MyQueue")
private static Queue queue;
public static void index() {
if(queue == null){
error("Queue is NULL");
}
queue.addAll(asList("A","B","C","D"));
renderText(StringUtils.join(queue.toArray(), ", "));
}
} | java | 12 | 0.655642 | 60 | 17.392857 | 28 | starcoderdata |
package org.hisp.dhis.audit;
/*
* Copyright (c) 2004-2020, University of Oslo
* 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 HISP project 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.
*/
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonRawValue;
import lombok.Builder;
import lombok.Data;
import java.io.Serializable;
import java.time.LocalDateTime;
/**
* Class for Audit message persistence, meant to be a complete replacement for
* our existing audit hibernate classes.
*
* @author
*/
@Data
@Builder
public class Audit implements Serializable
{
private Long id;
/**
* Type of audit.
*/
@JsonProperty
private final AuditType auditType;
/**
* Scope of audit.
*/
@JsonProperty
private final AuditScope auditScope;
/**
* When audit was done. Necessary since there might be delayed from when the Audit
* is put on the queue, to when its actually persisted.
*/
@JsonProperty
private final LocalDateTime createdAt;
/**
* Who initiated the audit action.
*/
@JsonProperty
private final String createdBy;
/**
* Name of klass being audited. Only required if linked directly to an object.
*/
@JsonProperty
private String klass;
/**
* UID of object being audited, implies required for klass.
*/
@JsonProperty
private String uid;
/**
* Code of object being audited, implies required for klass.
*/
@JsonProperty
private String code;
/**
* Additional attributes attached to Audit. Stored as JSONB in the database.
*/
@JsonProperty
@Builder.Default
private AuditAttributes attributes = new AuditAttributes();
/**
* GZipped payload. Exposed as raw json, make sure that the payload is decompressed first.
*/
@JsonRawValue
private final String data;
} | java | 7 | 0.720252 | 94 | 30.396226 | 106 | starcoderdata |
def generate_slicer_files():
"""
Generate the files for the message slicer.
"""
check_builddir()
inputfiles = ['message_slicer.v']
outputfiles = []
for f in inputfiles:
outputfiles.append(copyfile('message', f))
return outputfiles | python | 11 | 0.633333 | 50 | 26.1 | 10 | inline |
"""ThreatConnect HMAC Authorization"""
# standard library
import time
from typing import Callable, Union
# third-party
from requests import auth, request
# first-party
from tcex.input.field_types.sensitive import Sensitive
class TokenAuth(auth.AuthBase):
"""ThreatConnect HMAC Authorization"""
def __init__(self, tc_token: Union[Callable, str, 'Sensitive']) -> None:
"""Initialize the Class properties."""
# super().__init__()
auth.AuthBase.__init__(self)
self.tc_token = tc_token
def _token_header(self):
"""Return HMAC Authorization header value."""
_token = None
if hasattr(self.tc_token, 'token'):
# Token Module - The token module is provided that will handle authentication.
_token = self.tc_token.token.value
elif callable(self.tc_token):
# Callabe - A callable method is provided that will return the token as a plain
# string. The callable will have to handle token renewal.
_token = self.tc_token()
elif isinstance(self.tc_token, Sensitive):
# Sensitive - A sensitive string type was passed. Likely no support for renewal.
_token = self.tc_token.value
else:
# String - A string type was passed. Likely no support for renewal.
_token = self.tc_token
# Return formatted token
return f'TC-Token {_token}'
def __call__(self, r: request) -> request:
"""Add the authorization headers to the request."""
timestamp = int(time.time())
# Add required headers to auth.
r.headers['Authorization'] = self._token_header()
r.headers['Timestamp'] = timestamp
return r | python | 12 | 0.625424 | 92 | 34.4 | 50 | starcoderdata |
static void lupb_cacheinit(lua_State *L) {
/* Create our object cache. */
lua_newtable(L);
/* Cache metatable gives the cache weak values */
lua_createtable(L, 0, 1);
lua_pushstring(L, "v");
lua_setfield(L, -2, "__mode");
lua_setmetatable(L, -2);
/* Set cache in the registry. */
lua_rawsetp(L, LUA_REGISTRYINDEX, &cache_key);
} | c | 7 | 0.640805 | 51 | 25.846154 | 13 | inline |
void RCRun::registerVertexStream(const std::string& stream_name,
bool points_to_data,
const RegisterMode& mode) {
uint32_t stream_index;
if (hasVertexStream(stream_name)) {
// in create mode, read/write streams must have been set if stream name
// exists, so we can simply return.
if (mode == RegisterMode::Create) return;
// stream assumed exist
stream_index = vertexStreamNames_->locked().get().at(stream_name);
} else {
// in existing mode, we assume the stream_name exists but the read stream
// have not been created
if (mode == RegisterMode::Existing) {
std::string err{"Trying to load an non-existing stream."};
CLOG(ERROR, "pose_graph") << err;
throw std::runtime_error{err};
}
{
auto locked_vertex_stream_names = vertexStreamNames_->locked();
stream_index = uint32_t(locked_vertex_stream_names.get().size());
locked_vertex_stream_names.get().emplace(stream_name, stream_index);
}
(void)rosbag_streams_->locked().get()[stream_index];
}
bool write = (mode == RegisterMode::Create);
// Only create streams if this is not an ephemeral run and we request it
if (points_to_data && !isEphemeral()) {
auto data_directory = fs::path{filePath_}.parent_path() / "sensor_data";
auto& data_stream = rosbag_streams_->locked().get().at(stream_index);
// create write stream if not exist
if (write && !data_stream.second)
data_stream.second.reset(new storage::DataStreamWriter<MessageType>(
data_directory, stream_name));
// create read stream if not exist
if (!data_stream.first)
data_stream.first.reset(new storage::DataStreamReader<MessageType>(
data_directory, stream_name));
} else {
LOG(DEBUG) << "Run is ephemeral or does not point to data; not "
"initializing streams for "
<< stream_name;
}
} | c++ | 15 | 0.632653 | 77 | 39.020408 | 49 | inline |
from rest_framework.generics import (
ListAPIView,
CreateAPIView,
RetrieveAPIView
)
from form import models
from api import models as APIModels
from api import serializer
# Create your views here.
class CentreList(ListAPIView):
queryset = models.Centre.objects.all()
serializer_class = serializer.CenterSerializer
class CreateContactQuery(CreateAPIView):
serializer_class = serializer.ContactQuerySerializer
class ExamsList(ListAPIView):
queryset = APIModels.Exams.objects.all()
serializer_class = serializer.ExamSerializer
class ExamsDetail(RetrieveAPIView):
queryset = APIModels.Exams.objects.all()
serializer_class = serializer.ExamSerializer
lookup_field = 'slug' | python | 9 | 0.772981 | 56 | 25.592593 | 27 | starcoderdata |
public void testRecordsDontChange() throws IOException {
writeData(filename, new ByteBufferGenerator(1000));
GoogleCloudStorageLevelDbInputReader reader =
new GoogleCloudStorageLevelDbInputReader(filename, inputOptions());
reader.beginShard();
ByteBufferGenerator expected = new ByteBufferGenerator(1000);
reader.beginSlice();
ArrayList<ByteBuffer> recordsRead = new ArrayList<>();
try {
while (true) {
recordsRead.add(reader.next());
}
} catch (NoSuchElementException e) {
// used a break
}
for (int i = 0; i < recordsRead.size(); i++) {
assertTrue(expected.hasNext());
ByteBuffer read = recordsRead.get(i);
assertEquals(expected.next(), read);
}
verifyEmpty(reader);
reader.endSlice();
} | java | 12 | 0.667925 | 75 | 33.608696 | 23 | inline |
import pymongo
import pandas as pd
import json
from app.services.model import Prediction_Model, model
class Song_Database:
def __init__(self):
self.connection = "mongodb+srv://joe_maulin:
self.create_database()
def create_database(self):
self.client = pymongo.MongoClient(self.connection)
self.database = self.client.song_database
collections = self.database.list_collection_names()
if "songs" not in collections:
self.collection = self.database.songs
self.collection.insert_one({"_id":"init" ,"songid":"placeholder"})
else:
self.collection = self.database.songs
def get_track(self, songid):
track = self.collection.find_one({"songid" : songid})
if track:
return track
def get_tracks(self, songids):
tracks = []
for id in songids:
track = self.get_track(id)
tracks.append(track)
return tracks
def add_track(self, track):
self.collection.insert_one(track)
def update_track(self, track):
self.collection.replace_one({"songid": track['songid']}, track, upsert=True)
def get_predictions(self):
tracks = self.collection.find({"prediction": {"$exists" : True}})
return tracks
def add_prediction(self, track, prediction):
self.collection.update_one({"songid": track['songid']}, {"$set": {"prediction":prediction}})
def import_song_data(self):
df = pd.read_csv("app/services/song_lists/song_list5.csv", sep=",")
records = json.loads(df.to_json(orient="records"))
self.collection.insert_many(records)
self.set_initial_predictions()
def set_initial_predictions(self):
tracks = self.collection.find({"prediction": {"$exists" : False}})
i = 0
for x in tracks:
try:
print(i, "predicted..")
prediction = model.predict(x)
self.add_prediction(x, [float(prediction[0][0]),float(prediction[0][1])])
except:
continue
i+=1
if __name__ == "__main__":
import pandas as pd
import json
# db = Song_Database()
# search_tracks = json.dumps(list(db.get_predictions()))
#
# df = pd.read_json(search_tracks)
#
# print(df.head())
song_database = Song_Database()
# #
# # song_database.set_initial_predictions()
#
#
# for x in song_database.get_predictions():
# print(x)
track = song_database.get_track("2MLHyLy5z5l5YRp7momlgw")
print(f"track: {track}")
# track['prediction'] = [2,32]
#
# song_database.add_prediction(track, [.4,.1])
# # song_database.update_track(track)
#
# track = song_database.get_track("6t9dKp7Nf1t4HpYXOdeVNl")
# print(track)
# features = ['songid','artist','track','danceability','energy','key','loudness','mode','speechiness','acousticness','instrumentalness','liveness','valence','tempo','duration_ms','time_signature']
# data = ['5X4Qm0rVLcZeeO4tSDmBg3',' Thro' Our Hands",0.456,0.255,9.0,-15.805,1.0,0.048,0.946,0.17,0.951,0.0532,116.424,253067.0,4.0]
#
# track = {}
# for i in range(len(features)):
# track[features[i]] = data[i]
#
# print(f"track:{track}")
#
# song_database.add_track(track)
# query = song_database.collection.find({"songid":"5X4Qm0rVLcZeeO4tSDmBg3"})
# for x in query:
# print(x)
# print(song_database.database.list_collection_names())
# print(song_database.client.list_database_names())
# print(song_database.client.list_collection_names())
# song_database.import_song_data() | python | 17 | 0.601793 | 200 | 25.893617 | 141 | starcoderdata |
func (r *BoltEmployeeRepo) FindByID(employeeID string) (*core.Employee, error) {
// map to internal representation
key := []byte(employeeID)
value, err := r.Database.GetEntity("employee", key)
if err != nil {
return nil, err
}
var employee dbEmployee
err = json.Unmarshal(value, &employee)
if err != nil {
return nil, err
}
return dbToCore(employeeID, &employee), nil
} | go | 8 | 0.699739 | 80 | 26.428571 | 14 | inline |
private static Set<Byte> makeCharacterSet( String chars ) {
byte[] bytes;
try {
bytes = chars.getBytes( "US-ASCII" );
}
catch ( UnsupportedEncodingException ex ) {
throw new RuntimeException( ex ); // should never happen with US-ASCII
}
Set<Byte> ret = new HashSet<Byte>();
for ( byte b : bytes ) {
ret.add( b );
}
return Collections.unmodifiableSet( ret );
} | java | 10 | 0.607229 | 76 | 28.714286 | 14 | inline |
define(['dojo/_base/lang', 'dojo/_base/declare'],
function (lang, declare) {
// module:
// gform/schema/Transformer
return declare('RemoveFirstGroupTransformer', [], {
constructor: function (kwArgs) {
lang.mixin(this, kwArgs);
},
execute: function (attributes) {
var newArray = [];
attributes.forEach(function (e) {
if (e.groups && e.code && !e.code.match(/(object|array|map)/)) {
var newE = {};
lang.mixin(newE, e);
var newGroups = [];
e.groups.forEach(function (group, idx) {
if (idx > 0) {
newGroups.push(group);
}
});
newE.groups = newGroups;
newArray.push(newE);
}
});
return newArray;
}
});
})
; | javascript | 30 | 0.379867 | 84 | 31.9375 | 32 | starcoderdata |
# Conditional imports for GDAL
import importlib
import warnings
import sys
try:
gdal = importlib.util.find_spec('gdal')
ogr = importlib.util.find_spec('osgeo.ogr')
osr = importlib.util.find_spec('osr')
gdal = gdal.loader.load_module()
ogr = ogr.loader.load_module()
osr = osr.loader.load_module()
gdal.UseExceptions()
except:
try:
gdal = importlib.util.find_spec('osgeo.gdal')
gdal = gdal.loader.load_module()
except:
gdal = None
ogr = None
osr = None
def conditional_gdal(func):
def has_gdal(*args, **kwargs):
if gdal:
return func(*args, **kwargs)
else:
warnings.warn('Trying to call a GDAL method, but GDAL is not installed.')
return None
return has_gdal
from . import io_autocnetgraph
from . import io_controlnetwork
from . import io_db
from . import io_gdal
from . import io_hdf
from . import io_json
from . import io_krc
from . import io_pvl
from . import io_spectral_profiler
from . import io_tes
from . import io_yaml
from . import isis_serial_number | python | 12 | 0.655014 | 85 | 23.704545 | 44 | starcoderdata |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.