hexsha
stringlengths 40
40
| size
int64 5
1.05M
| ext
stringclasses 98
values | lang
stringclasses 21
values | max_stars_repo_path
stringlengths 3
945
| max_stars_repo_name
stringlengths 4
118
| max_stars_repo_head_hexsha
stringlengths 40
78
| max_stars_repo_licenses
listlengths 1
10
| max_stars_count
int64 1
368k
⌀ | max_stars_repo_stars_event_min_datetime
stringlengths 24
24
⌀ | max_stars_repo_stars_event_max_datetime
stringlengths 24
24
⌀ | max_issues_repo_path
stringlengths 3
945
| max_issues_repo_name
stringlengths 4
118
| max_issues_repo_head_hexsha
stringlengths 40
78
| max_issues_repo_licenses
listlengths 1
10
| max_issues_count
int64 1
134k
⌀ | max_issues_repo_issues_event_min_datetime
stringlengths 24
24
⌀ | max_issues_repo_issues_event_max_datetime
stringlengths 24
24
⌀ | max_forks_repo_path
stringlengths 3
945
| max_forks_repo_name
stringlengths 4
135
| max_forks_repo_head_hexsha
stringlengths 40
78
| max_forks_repo_licenses
listlengths 1
10
| max_forks_count
int64 1
105k
⌀ | max_forks_repo_forks_event_min_datetime
stringlengths 24
24
⌀ | max_forks_repo_forks_event_max_datetime
stringlengths 24
24
⌀ | content
stringlengths 5
1.05M
| avg_line_length
float64 1
1.03M
| max_line_length
int64 2
1.03M
| alphanum_fraction
float64 0
1
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
406a7f02a821260845fe6c5197506f0250a04413
| 1,354
|
rb
|
Ruby
|
test/unchained/client_test.rb
|
andrewpthorp/unchained
|
54db3bfdb41f141de95df9bb620cbd86de675d07
|
[
"MIT"
] | null | null | null |
test/unchained/client_test.rb
|
andrewpthorp/unchained
|
54db3bfdb41f141de95df9bb620cbd86de675d07
|
[
"MIT"
] | null | null | null |
test/unchained/client_test.rb
|
andrewpthorp/unchained
|
54db3bfdb41f141de95df9bb620cbd86de675d07
|
[
"MIT"
] | null | null | null |
require_relative '../test_helper'
describe Unchained::Client do
before do
@client = Unchained::Client.new
end
Unchained::Configuration::KEYS.each do |k|
it "should set up an accessor for #{k}" do
assert(
@client.respond_to?(k),
"Expected `@client` to respond to `#{k}`.",
)
assert(
@client.respond_to?("#{k}="),
"Expected `@client` to respond to `#{k}=`.",
)
end
end
describe 'initialization' do
it 'should initialize the cache' do
refute_nil(@client.cache)
assert(@client.cache.is_a?(Hash))
end
it 'should initialize from the configuration' do
Unchained.configure {|c| c.login_token = 'init_token'}
client = Unchained::Client.new
assert_equal('init_token', client.login_token)
Unchained.reset!
client = Unchained::Client.new
assert_nil(client.login_token)
end
end
describe '#base_url' do
it 'should be set correctly' do
assert_equal(
'http://api.camelotunchained.com/v1',
@client.base_url,
)
end
end
describe '#clear_cache!' do
it 'clears the cache' do
cache = {foo: 'bar'}
@client.instance_variable_set("@cache", cache)
assert_equal(cache, @client.cache)
@client.clear_cache!
assert_empty(@client.cache)
end
end
end
| 22.566667
| 60
| 0.616691
|
3552efb63a3a6a7c7858099d51eb384c85008d9e
| 464
|
lua
|
Lua
|
Blizzlike/ArcEmu/Scripts/Zones/Outland/Shadowmoon Valley/Bron.lua
|
499453466/Lua-Other
|
43fd2b72405faf3f2074fd2a2706ef115d16faa6
|
[
"Unlicense"
] | 2
|
2015-06-23T16:26:32.000Z
|
2019-06-27T07:45:59.000Z
|
Blizzlike/ArcEmu/Scripts/Zones/Outland/Shadowmoon Valley/Bron.lua
|
Eduardo-Silla/Lua-Other
|
db610f946dbcaf81b3de9801f758e11a7bf2753f
|
[
"Unlicense"
] | null | null | null |
Blizzlike/ArcEmu/Scripts/Zones/Outland/Shadowmoon Valley/Bron.lua
|
Eduardo-Silla/Lua-Other
|
db610f946dbcaf81b3de9801f758e11a7bf2753f
|
[
"Unlicense"
] | 3
|
2015-01-10T18:22:59.000Z
|
2021-04-27T21:28:28.000Z
|
function Bron_OnEnterCombat(Unit,Event)
Unit:RegisterEvent("Bron_ThrowHammer", 15000, 0)
end
function Bron_ThrowHammer(Unit,Event)
Unit:FullCastSpellOnTarget(33822,Unit:GetClosestPlayer())
end
function Bron_OnLeaveCombat(Unit,Event)
Unit:RemoveEvents()
end
function Bron_OnDied(Unit,Event)
Unit:RemoveEvents()
end
RegisterUnitEvent(19395, 1, "Bron_OnEnterCombat")
RegisterUnitEvent(19395, 2, "Bron_OnLeaveCombat")
RegisterUnitEvent(19395, 4, "Bron_OnDied")
| 24.421053
| 58
| 0.818966
|
540e8860ce3f7b7b1db4e3fe2c1494ed497313e7
| 147
|
rb
|
Ruby
|
test/riel/hash_test.rb
|
jpace/riel
|
fa6e8265a6759e0311cab2ea2a7d54211d2f317e
|
[
"MIT"
] | null | null | null |
test/riel/hash_test.rb
|
jpace/riel
|
fa6e8265a6759e0311cab2ea2a7d54211d2f317e
|
[
"MIT"
] | null | null | null |
test/riel/hash_test.rb
|
jpace/riel
|
fa6e8265a6759e0311cab2ea2a7d54211d2f317e
|
[
"MIT"
] | null | null | null |
#!/usr/bin/ruby -w
# -*- ruby -*-
require 'test/unit'
require 'riel/hash'
class HashTestCase < Test::Unit::TestCase
def test_nothing
end
end
| 13.363636
| 41
| 0.673469
|
a311c63a55cdb232fba3d4d57d34f742b9fdb498
| 661
|
c
|
C
|
src/C/Applications/Exam_Score_Table/source.c
|
Ahmopasa/TheCodes
|
560ed94190fd0da8cc12285e9b4b5e27b19010a5
|
[
"MIT"
] | null | null | null |
src/C/Applications/Exam_Score_Table/source.c
|
Ahmopasa/TheCodes
|
560ed94190fd0da8cc12285e9b4b5e27b19010a5
|
[
"MIT"
] | null | null | null |
src/C/Applications/Exam_Score_Table/source.c
|
Ahmopasa/TheCodes
|
560ed94190fd0da8cc12285e9b4b5e27b19010a5
|
[
"MIT"
] | null | null | null |
#define _CRT_SECURE_NO_WARNINGS
#include "Data.h"
int main() {
//int total_students;
//check_total_students: printf("Welcome to the system.\nPlease, enter the total size of students: ");
//if (!(scanf("%d", &total_students) && total_students >= 0))
// goto check_total_students;
//student* personelInfo = (student*)malloc(3 * sizeof(student));
//if (!personelInfo)
//{
// puts("List, could not be created. Exiting...");
// exit(EXIT_FAILURE);
//}
student personelInfo[3] = { 0 };
system("cls");
printf("List have been created, but it is empty.\n\n");
CreateList(personelInfo, 3);
ShowList(personelInfo, 3);
WriteToFile(personelInfo, 3);
}
| 24.481481
| 102
| 0.679274
|
43d5ed5d0c40dad623462a22bb5071bb88770749
| 226
|
tsx
|
TypeScript
|
src/badges/Octave.tsx
|
NWylynko/react-clean-badges
|
930212d5aac90afc9a72b211cea07b42aee92f11
|
[
"MIT"
] | null | null | null |
src/badges/Octave.tsx
|
NWylynko/react-clean-badges
|
930212d5aac90afc9a72b211cea07b42aee92f11
|
[
"MIT"
] | null | null | null |
src/badges/Octave.tsx
|
NWylynko/react-clean-badges
|
930212d5aac90afc9a72b211cea07b42aee92f11
|
[
"MIT"
] | null | null | null |
import React from "react"
import { Badge } from "../badge"
import type { BadgeProps } from "../badge"
const Octave = (props: BadgeProps) => <Badge name="Octave" {...props} backgroundColor="#0790C0" />
export default Octave
| 25.111111
| 98
| 0.685841
|
5d44db651758063958bd93c9ed68644739749498
| 3,307
|
cc
|
C++
|
persistence/leveldb_sparql.cc
|
wastl/cmarmotta
|
b2c36f357b5336dd4da31259cec490762ed6e996
|
[
"Apache-2.0"
] | 14
|
2015-11-16T06:43:28.000Z
|
2020-01-12T11:55:06.000Z
|
persistence/leveldb_sparql.cc
|
wastl/cmarmotta
|
b2c36f357b5336dd4da31259cec490762ed6e996
|
[
"Apache-2.0"
] | null | null | null |
persistence/leveldb_sparql.cc
|
wastl/cmarmotta
|
b2c36f357b5336dd4da31259cec490762ed6e996
|
[
"Apache-2.0"
] | 13
|
2016-01-19T19:39:36.000Z
|
2021-09-03T07:46:19.000Z
|
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not 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.
*/
#include "leveldb_sparql.h"
namespace marmotta {
namespace persistence {
namespace sparql {
using ::marmotta::sparql::StatementIterator;
class WrapProtoStatementIterator : public StatementIterator {
public:
WrapProtoStatementIterator(std::unique_ptr<persistence::LevelDBPersistence::StatementIterator> it)
: it(std::move(it)) { }
util::CloseableIterator<rdf::Statement> &operator++() override {
++(*it);
parsed = false;
return *this;
};
rdf::Statement &operator*() override {
if (!parsed) {
current = std::move(**it);
parsed = true;
}
return current;
};
rdf::Statement *operator->() override {
if (!parsed) {
current = std::move(**it);
parsed = true;
}
return ¤t;
};
bool hasNext() override {
return it->hasNext();
}
private:
std::unique_ptr<persistence::LevelDBPersistence::StatementIterator> it;
rdf::Statement current;
bool parsed;
};
bool LevelDBTripleSource::HasStatement(
const rdf::Resource *s, const rdf::URI *p, const rdf::Value *o, const rdf::Resource *c) {
rdf::proto::Statement pattern;
if (s != nullptr) {
*pattern.mutable_subject() = s->getMessage();
}
if (p != nullptr) {
*pattern.mutable_predicate() = p->getMessage();
}
if (o != nullptr) {
*pattern.mutable_object() = o->getMessage();
}
if (c != nullptr) {
*pattern.mutable_context() = c->getMessage();
}
bool found = false;
persistence->GetStatements(pattern, [&found](rdf::proto::Statement) -> bool {
found = true;
return false;
});
return found;
}
std::unique_ptr<sparql::StatementIterator> LevelDBTripleSource::GetStatements(
const rdf::Resource *s, const rdf::URI *p, const rdf::Value *o, const rdf::Resource *c) {
rdf::proto::Statement pattern;
if (s != nullptr) {
*pattern.mutable_subject() = s->getMessage();
}
if (p != nullptr) {
*pattern.mutable_predicate() = p->getMessage();
}
if (o != nullptr) {
*pattern.mutable_object() = o->getMessage();
}
if (c != nullptr) {
*pattern.mutable_context() = c->getMessage();
}
return std::unique_ptr<sparql::StatementIterator>(
new WrapProtoStatementIterator(persistence->GetStatements(pattern)));
}
} // namespace sparql
} // namespace persistence
} // namespace marmotta
| 29.008772
| 102
| 0.635319
|
7b76db9d932889292fbe4332e8b86636c6802856
| 1,801
|
sql
|
SQL
|
sql/db_init.sql
|
koceilam/projet_test
|
36097ece278e382f5d726dbb914bb8f61679ec71
|
[
"MIT"
] | null | null | null |
sql/db_init.sql
|
koceilam/projet_test
|
36097ece278e382f5d726dbb914bb8f61679ec71
|
[
"MIT"
] | null | null | null |
sql/db_init.sql
|
koceilam/projet_test
|
36097ece278e382f5d726dbb914bb8f61679ec71
|
[
"MIT"
] | null | null | null |
--
-- Base de données: `db_holidays`
--
-- --------------------------------------------------------
--
-- Contenu de la table `employees`
--
INSERT INTO `employees` (`id`, `name`, `status`, `date_c`) VALUES
(1, 'Jean claude', 0, '2016-12-13 17:04:21'),
(2, 'Alexendre ', 1, '2016-12-13 17:04:21'),
(3, 'Valerie ', 1, '2016-12-13 17:04:21');
--
-- Contenu de la table `holidays`
--
INSERT INTO `holidays` (`id`, `employee_id`, `date_begin`, `date_end`, `status`, `comment`, `date_c`) VALUES
(1, 1, '2016-12-14 00:00:00', '2016-12-16 23:59:59', 1, 'Congés sans solde', '2016-12-14 18:11:16'),
(2, 1, '2016-12-14 00:00:00', '2016-12-16 23:59:59', 1, 'RAS', '2016-12-14 18:11:16'),
(3, 2, '2016-12-14 00:00:00', '2016-12-16 23:59:59', 2, 'Congés maladies', '2016-12-14 18:11:42'),
(4, 2, '2016-12-14 00:00:00', '2016-12-16 23:59:59', 1, '', '2016-12-14 18:11:42'),
(5, 1, '2016-12-14 00:00:00', '2016-12-16 23:59:59', 1, '', '2016-12-14 18:28:33'),
(6, 1, '2016-12-14 00:00:00', '2016-12-16 23:59:59', 2, '', '2016-12-14 18:28:33'),
(7, 1, '2016-12-14 00:00:00', '2016-12-16 23:59:59', 1, '', '2016-12-14 18:33:13'),
(8, 1, '2016-12-14 00:00:00', '2016-12-16 23:59:59', 2, '', '2016-12-14 18:33:13'),
(9, 3, '2016-12-14 00:00:00', '2016-12-16 23:59:59', 2, 'RAS', '2016-12-14 18:33:13'),
(10, 3, '2016-12-16 00:00:00', '2016-12-16 23:59:59', 1, '', '2016-12-14 18:33:13'),
(11, 3, '2016-12-11 00:00:00', '2016-12-16 23:59:59', 1, '', '2016-12-14 18:33:13'),
(12, 3, '2016-11-14 00:00:00', '2016-12-16 23:59:59', 1, '', '2016-12-14 18:33:13'),
(13, 3, '2016-12-14 00:00:00', '2016-12-16 23:59:59', 0, '', '2016-12-14 18:33:13'),
(14, 3, '2016-12-14 00:00:00', '2016-12-16 23:59:59', 0, '', '2016-12-14 18:33:13'),
(15, 3, '2016-12-14 00:00:00', '2016-12-16 23:59:59', 0, '', '2016-12-14 18:33:13');
| 48.675676
| 108
| 0.544142
|
383fe8f5c30ccd6eeab9fb967ff389924e228b55
| 2,344
|
php
|
PHP
|
src/PhpNuts/Database/Sql/SqlStatement/InsertStatement.php
|
gwillings/phpnuts-basics
|
6e9abee6ca7d3915400e36a2a2fe666c27df225a
|
[
"MIT"
] | 5
|
2019-07-14T03:50:51.000Z
|
2019-10-29T01:57:39.000Z
|
src/PhpNuts/Database/Sql/SqlStatement/InsertStatement.php
|
gwillings/phpnuts-basics
|
6e9abee6ca7d3915400e36a2a2fe666c27df225a
|
[
"MIT"
] | null | null | null |
src/PhpNuts/Database/Sql/SqlStatement/InsertStatement.php
|
gwillings/phpnuts-basics
|
6e9abee6ca7d3915400e36a2a2fe666c27df225a
|
[
"MIT"
] | null | null | null |
<?php
namespace PhpNuts\Database\Sql\SqlStatement;
use PhpNuts\Database\Sql\SqlBlock\InsertBlock;
use PhpNuts\Database\Sql\SqlBlock\IntoBlock;
use PhpNuts\Database\Sql\SqlBlock\SetBlock;
use PhpNuts\Database\Sql\SqlFragment;
use PhpNuts\Database\Sql\SqlKeyword;
use PhpNuts\Database\Sql\SqlStatement\Traits\SetTrait;
/**
* Class InsertStatement
* @package PhpNuts\Database\Sql\SqlStatement
*/
class InsertStatement extends AbstractStatement
{
use SetTrait;
/**
* InsertStatement constructor.
*/
public function __construct()
{
parent::__construct([
SqlKeyword::INSERT => new InsertBlock(),
SqlKeyword::INTO => new IntoBlock(),
SqlKeyword::SET => new SetBlock()
]);
$this->insert('');
}
/**
* Executes the Insert Statement and return the number of rows inserted.
* @return int
*/
public function execute(): int
{
$statement = $this->createStatement();
$statement->execute();
return $statement->rowCount();
}
/**
* Returns an array containing the names of the blocks in
* order of priority/sequence.
* @return string[]
*/
protected function getBlockSequence(): array
{
return [
SqlKeyword::INSERT,
SqlKeyword::INTO,
SqlKeyword::SET
];
}
/**
* @param string $sql
* @param array|string|int|float|bool|null $parameters A single or array of scalar parameters
* @return $this
*/
public function insert(string $sql, $parameters = []): InsertStatement
{
$this->setBlock(SqlKeyword::INSERT, new InsertBlock());
return $this->addFragment(SqlKeyword::INSERT, new SqlFragment($sql, $parameters));
}
/**
* @param string $tableName
* @return $this
*/
public function into(string $tableName)
{
$this->setBlock(SqlKeyword::INTO, new IntoBlock());
return $this->addFragment(SqlKeyword::INTO, new SqlFragment($tableName));
}
/**
* Returns the ID of the last inserted row or sequence value.
* @param string|null $name
* @return string
*/
public function lastInsertId(string $name = null): string
{
return $this->getDatabase()->getConnection()->lastInsertId($name);
}
}
| 26.636364
| 97
| 0.619881
|
afaf61e1b49a121208dcb4a1afc7232b3a697af3
| 2,994
|
lua
|
Lua
|
riven/Riven.lua
|
brenoln/Lactea
|
30e1c76a4ed9f696516d75e64ae9e2eb8ee68346
|
[
"Apache-2.0"
] | null | null | null |
riven/Riven.lua
|
brenoln/Lactea
|
30e1c76a4ed9f696516d75e64ae9e2eb8ee68346
|
[
"Apache-2.0"
] | null | null | null |
riven/Riven.lua
|
brenoln/Lactea
|
30e1c76a4ed9f696516d75e64ae9e2eb8ee68346
|
[
"Apache-2.0"
] | null | null | null |
require('Inspired')
require('IWalk')
--Version RivenKiller v1.0.0.0
--Credits Lactea TheWelder Inspired
-- Script for Gaming on steroids
local myHero = nil
local champName = nil
local target = nil
AddInfo("Riven", "RivenKiller:")
AddButton("Q", "Use Q", true)
AddButton("W", "Use W", true)
AddButton("E", "Use E", true)
AddButton("R", "Use R Kill", true)
AddInfo("util", "Utilities")
AddButton("Gank","GankAlert",true)
OnLoop(function(myHero)
myHero = GetMyHero()
myHeroPos = GetOrigin(GetMyHero())
champName = GetObjectName(myHero)
target = GetCurrentTarget()
local targetPos = GetOrigin(target)
local Obj_Type = GetObjectType(target)
local allDMG = GetBonusDmg(myHero)+GetBaseDamage(myHero)
local perc90 = (allDMG*90)/100
local Qdmg = (GetCastLevel(myHero,_Q)*60)+27+perc90
local Wdmg = (GetCastLevel(myHero,_W)*35)+30+perc90
local Edmg =(GetCastLevel(myHero,_E)*0)+0+allDMG
local Rdmg = (GetCastLevel(myHero,_R)*200)+(allDMG*2)
if GetButtonValue("Gank") then
if EnemiesAround(myHeroPos, 5000) > 0 then
local hero_origin = myHeroPos
local myscreenpos = WorldToScreen(1,hero_origin.x,hero_origin.y,hero_origin.z)
if myscreenpos.flag then
if EnemiesAround(myHeroPos, 5000) < 3 then
DrawText(string.format("ENEMIES = %s", EnemiesAround(myHeroPos, 5000)),24,myscreenpos.x-100,myscreenpos.y,0xff00ff00)
else
DrawText(string.format("CAREFULL = %s", EnemiesAround(myHeroPos, 5000)),24,myscreenpos.x-100,myscreenpos.y,0xffff0000)
end
end
end
end
if champName == "Riven" then
if KeyIsDown(0x20) then
if GetButtonValue("Q") then
if ValidTarget(target,1000) then
local FQpred = GetPredictionForPlayer(myHeroPos,target,GetMoveSpeed(target),2000,250,900,50,true,true)
if CanUseSpell(myHero,_Q) == READY and FQpred.HitChance == 1 then
CastSkillShot(_Q,FQpred.PredPos.x,FQpred.PredPos.y,FQpred.PredPos.z)
CastTargetSpell(target,GetItemSlot(myHero,3153))
CastTargetSpell(target,GetItemSlot(myHero,3144))
end
end
end
if GetButtonValue("W") then
if ValidTarget(target,290) then
if CanUseSpell(myHero,_W) == READY then
CastTargetSpell(target,_W)
end
end
end
if GetButtonValue("E") then
if ValidTarget(target,350) then
local FQpred = GetPredictionForPlayer(myHeroPos,target,GetMoveSpeed(target),2000,250,350,50,true,true)
if CanUseSpell(myHero,_E) == READY then
CastSkillShot(_E,FQpred.PredPos.x,FQpred.PredPos.y,FQpred.PredPos.z)
CastSkillShot(GetItemSlot(myHero,3077),FQpred.PredPos.x,FQpred.PredPos.y,FQpred.PredPos.z)
CastSkillShot(GetItemSlot(myHero,3074),FQpred.PredPos.x,FQpred.PredPos.y,FQpred.PredPos.z)
end
end
end
if GetButtonValue("R") then
if ValidTarget(target,600) then
if CalcDamage(myHero, target, Rdmg) > GetCurrentHP(target) + GetHPRegen(target) then
if CanUseSpell(myHero,_R) == READY then
CastTargetSpell(target,_R)
end
end
end
end
end
end
end)
| 32.193548
| 123
| 0.716433
|
54e377b69f44c5d6c4d52ae143c0604e654fb272
| 2,380
|
rb
|
Ruby
|
actividades/web/rails2-examples/clases/app/controllers/centros_controller.rb
|
oritelad/libro-de-actividades
|
d6cd3a1f7e45947d4ad9c9084d36482f1986545e
|
[
"CC0-1.0"
] | null | null | null |
actividades/web/rails2-examples/clases/app/controllers/centros_controller.rb
|
oritelad/libro-de-actividades
|
d6cd3a1f7e45947d4ad9c9084d36482f1986545e
|
[
"CC0-1.0"
] | null | null | null |
actividades/web/rails2-examples/clases/app/controllers/centros_controller.rb
|
oritelad/libro-de-actividades
|
d6cd3a1f7e45947d4ad9c9084d36482f1986545e
|
[
"CC0-1.0"
] | null | null | null |
class CentrosController < ApplicationController
layout 'default'
# GET /centros
# GET /centros.xml
def index
@centros = Centro.find(:all)
@nav = :centros
@tab = :recursos
respond_to do |format|
format.html # index.html.erb
format.xml { render :xml => @centros }
end
end
# GET /centros/1
# GET /centros/1.xml
def show
@centro = Centro.find(params[:id])
@nav = @centro
@tab = :recursos
respond_to do |format|
format.html # show.html.erb
format.xml { render :xml => @centro }
end
end
# GET /centros/new
# GET /centros/new.xml
def new
@municipios = Municipio.find(:all)
@centro = Centro.new
@nav = :centros
@tab = :recursos
@centro.horario='h1=08:00, h2=09:00, h3=10:00, d3=11:00, h4=11:30, h5=12:30, h6=13:30'
@centro.activo=true
respond_to do |format|
format.html # new.html.erb
format.xml { render :xml => @centro }
end
end
# GET /centros/1/edit
def edit
@municipios = Municipio.find(:all)
@centro = Centro.find(params[:id])
@nav = @centro
@tab = :recursos
end
# POST /centros
# POST /centros.xml
def create
@centro = Centro.new(params[:centro])
respond_to do |format|
if @centro.save
flash[:notice] = 'El Centro se creó correctamente.'
format.html { redirect_to(@centro) }
format.xml { render :xml => @centro, :status => :created, :location => @centro }
else
format.html { render :action => "new" }
format.xml { render :xml => @centro.errors, :status => :unprocessable_entity }
end
end
end
# PUT /centros/1
# PUT /centros/1.xml
def update
@centro = Centro.find(params[:id])
respond_to do |format|
if @centro.update_attributes(params[:centro])
flash[:notice] = 'El Centro se modificó correctamente.'
format.html { redirect_to(@centro) }
format.xml { head :ok }
else
format.html { render :action => "edit" }
format.xml { render :xml => @centro.errors, :status => :unprocessable_entity }
end
end
end
# DELETE /centros/1
# DELETE /centros/1.xml
def destroy
@centro = Centro.find(params[:id])
@centro.destroy
respond_to do |format|
format.html { redirect_to(centros_url) }
format.xml { head :ok }
end
end
end
| 23.564356
| 90
| 0.596639
|
e83ead5112851c6e57e1cad866ce4ee5edcc3ec2
| 76
|
css
|
CSS
|
app/client/templates/users/user_rent.css
|
cfpg/mate
|
edb70792953dd7ef547156ab21916590c83af1ea
|
[
"Apache-2.0"
] | null | null | null |
app/client/templates/users/user_rent.css
|
cfpg/mate
|
edb70792953dd7ef547156ab21916590c83af1ea
|
[
"Apache-2.0"
] | null | null | null |
app/client/templates/users/user_rent.css
|
cfpg/mate
|
edb70792953dd7ef547156ab21916590c83af1ea
|
[
"Apache-2.0"
] | null | null | null |
.aligncenter {
text-align: center;
}
.aligncenter h3 {
margin-top: 43px;
}
| 12.666667
| 20
| 0.684211
|
13cf9440adbf4a426129faa13bec9a9248174cbe
| 292
|
lua
|
Lua
|
easy/roller_coaster.lua
|
IlkhamGaysin/ce-challenges
|
ac6b8c1fc4b6c098e380b9d694e93e614f6c969b
|
[
"BSD-3-Clause"
] | 2
|
2018-06-24T17:09:16.000Z
|
2020-08-03T11:44:54.000Z
|
easy/roller_coaster.lua
|
IlkhamGaysin/ce-challenges
|
ac6b8c1fc4b6c098e380b9d694e93e614f6c969b
|
[
"BSD-3-Clause"
] | null | null | null |
easy/roller_coaster.lua
|
IlkhamGaysin/ce-challenges
|
ac6b8c1fc4b6c098e380b9d694e93e614f6c969b
|
[
"BSD-3-Clause"
] | null | null | null |
for line in io.lines(arg[1]) do
local up = true
for i in line:gmatch(".") do
if i:find("%a") then
if up then
io.write(i:upper())
up = false
else
io.write(i:lower())
up = true
end
else
io.write(i)
end
end
print()
end
| 16.222222
| 31
| 0.489726
|
5dbad53a80bd6f0cecb0edce527bdf09c0216a96
| 29,959
|
cxx
|
C++
|
Hekateros/sw/apps/hek_stalemate/SMCalib.cxx
|
roadnarrows-robotics/rnr-sdk
|
aee20c65b49fb3eedf924c5c2ec9f19f4f1a1b29
|
[
"MIT"
] | null | null | null |
Hekateros/sw/apps/hek_stalemate/SMCalib.cxx
|
roadnarrows-robotics/rnr-sdk
|
aee20c65b49fb3eedf924c5c2ec9f19f4f1a1b29
|
[
"MIT"
] | null | null | null |
Hekateros/sw/apps/hek_stalemate/SMCalib.cxx
|
roadnarrows-robotics/rnr-sdk
|
aee20c65b49fb3eedf924c5c2ec9f19f4f1a1b29
|
[
"MIT"
] | null | null | null |
////////////////////////////////////////////////////////////////////////////////
//
// Package: Hekateros
//
// Program: StaleMate
//
// File: SMCalib.cxx
//
/*! \file
*
* $LastChangedDate: 2012-06-05 15:17:26 -0600 (Tue, 05 Jun 2012) $
* $Rev: 2028 $
*
* \brief StaleMate calibration.
*
* \author Robin Knight (robin.knight@roadnarrows.com)
* \author Daniel Packard (daniel@roadnarrows.com)
*
* \copyright
* \h_copy 2011-2017. RoadNarrows LLC.\n
* http://www.roadnarrows.com\n
* All Rights Reserved
*/
// Unless otherwise noted, all materials contained are copyrighted and may not
// be used except as provided in these terms and conditions or in the copyright
// notice (documents and software ) or other proprietary notice provided with
// the relevant materials.
//
//
// IN NO EVENT SHALL THE AUTHOR, ROADNARROWS, OR ANY MEMBERS/EMPLOYEES/
// CONTRACTORS OF ROADNARROWS OR DISTRIBUTORS OF THIS SOFTWARE BE LIABLE TO ANY
// PARTY FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL
// DAMAGES ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION,
// EVEN IF THE AUTHORS OR ANY OF THE ABOVE PARTIES HAVE BEEN ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
// THE AUTHORS AND ROADNARROWS SPECIFICALLY DISCLAIM ANY WARRANTIES,
// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
// FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS ON AN
// "AS IS" BASIS, AND THE AUTHORS AND DISTRIBUTORS HAVE NO OBLIGATION TO
// PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
//
////////////////////////////////////////////////////////////////////////////////
#include <sys/types.h>
#include <stdarg.h>
#include <libgen.h>
#include <cstring>
#include <iostream>
#include <fstream>
#include <cmath>
#include "rnr/rnrconfig.h"
#include "rnr/log.h"
#include "rnr/rnrWin.h"
#include "StaleMate.h"
#include "StaleMateTune.h"
using namespace std;
using namespace cv;
using namespace rnrWin;
// ---------------------------------------------------------------------------
// Public Interface
// ---------------------------------------------------------------------------
static bool SMCalibBoardSquares(StaleMateSession &session, int nChessBoardDim)
{
IplImage *pImg;
IplImage *pImgGray = NULL;
int nVertDim = nChessBoardDim - 1;
int nVertTot = nVertDim * nVertDim;
CvSize sizeChessBoard = cvSize(nVertDim, nVertDim);
CvPoint2D32f ptCorners[nVertTot];
int nCornerCnt;
CvPoint ptImg[nVertDim][nVertDim];
Rot eRot;
int i, j, k, m, n;
int w1, w2, w3, h1, h2, h3;
double dx1, dy1, dx2, dy2;
int delta, ddelta;
double x, y;
double x11, y11, x12, y12, x21, y21, x22, y22;
CvScalar colorPoly = CV_RGB(192, 0, 255);
CvScalar colorText = CV_RGB(0, 192, 64);
CvFont font;
char bufText[32];
CvPoint *pPolyLines[nChessBoardDim];
int nPolyPts[nChessBoardDim];
int rc = 0;
// - - - -
// Run chess calibration
// - - - -
while( (rc == 0) &&
(session.m_gui.pMenu->GetCurrentAction() == StaleMateActionCalib) )
{
pImg = StaleMateVideoCreateSnapShot(session);
if( pImg == NULL )
{
break;
}
if( pImgGray != NULL )
{
cvReleaseImage(&pImgGray);
}
pImgGray = StaleMateCreateRgbChannel(pImg, CHANNEL_GRAY);
rc = cvFindChessboardCorners(pImgGray, sizeChessBoard, ptCorners,
&nCornerCnt, CV_CALIB_CB_ADAPTIVE_THRESH);
cvCvtColor(pImgGray, pImg, CV_GRAY2RGB);
//cvDrawChessboardCorners(pImg, sizeChessBoard, ptCorners,
// nCornerCnt, rc);
StaleMateIoIShow(session, pImg, session.m_vid.uImgIndex1);
cvReleaseImage(&pImg);
session.m_gui.pWin->WaitKey(5);
}
// - - - -
// Calibration aborted or failed.
// - - - -
if( rc == 0 )
{
if( pImgGray != NULL )
{
cvReleaseImage(&pImgGray);
}
LOGERROR("Failed to calibrate board squares.");
return false;
}
cvInitFont(&font, CV_FONT_HERSHEY_DUPLEX, 0.50, 0.50, 0, 1);
// - - - -
// Determine how the corners are rotated clockwise relative to the chess board
// 1h position ([0][0] square).
// - - - -
m = nVertDim + 1; // catty-corner index
if( (ptCorners[0].x < ptCorners[m].x) &&
(ptCorners[0].y < ptCorners[m].y) )
{
eRot = Rot0;
cerr << "DBG: corners are not rotated." << endl;
}
else if( (ptCorners[0].x > ptCorners[m].x) &&
(ptCorners[0].y < ptCorners[m].y))
{
eRot = Rot90;
cerr << "DBG: corners are 90 degrees cw rotated." << endl;
}
else if( (ptCorners[0].x > ptCorners[m].x) &&
(ptCorners[0].y > ptCorners[m].y))
{
eRot = Rot180;
cerr << "DBG: corners are 180 degrees cw rotated." << endl;
}
else if( (ptCorners[0].x < ptCorners[m].x) &&
(ptCorners[0].y > ptCorners[m].y))
{
eRot = Rot270;
cerr << "DBG: corners are 270 degrees cw rotated." << endl;
}
else
{
eRot = Rot0;
cerr << "DBG: cannot determine corners rotation - assuming 0 degrees."
<< endl;
}
// - - - -
// Convert corners to image points normalizing to 0 degree rotation.
// - - - -
for(i=0; i<nVertTot; ++i)
{
switch( eRot )
{
default:
case Rot0:
m = i / nVertDim;
n = i % nVertDim;
break;
case Rot90:
m = i % nVertDim;
n = (nVertTot - i - 1) / nVertDim;
break;
case Rot180:
m = (nVertTot - i - 1) / nVertDim;
n = (nVertTot - i - 1) % nVertDim;
break;
case Rot270:
m = (nVertTot - i - 1) % nVertDim;
n = i / nVertDim;
break;
}
ptImg[m][n].x = cvRound(ptCorners[i].x);
ptImg[m][n].y = cvRound(ptCorners[i].y);
sprintf(bufText, "%d", m*nVertDim+n);
cvPutText(pImg, bufText, ptImg[m][n], &font, colorText);
}
cerr << "DBG: corners[]={";
for(m=0; m<nVertDim; ++m)
{
cerr << endl;
for(n=0; n<nVertDim; ++n)
{
cerr << "(" << ptImg[m][n].x << "," << ptImg[m][n].y << ") ";
}
}
cerr << "}" << endl;
memset(session.m_calib.ptBoard, 0, sizeof(session.m_calib.ptBoard));
// - - - -
// Central Board Area
// - - - -
for(i=1, m=0; i<nVertDim; ++i, ++m)
{
for(j=1, n=0; j<nVertDim; ++j, ++n)
{
session.m_calib.ptBoard[i][j][0].x = ptImg[m][n].x;
session.m_calib.ptBoard[i][j][0].y = ptImg[m][n].y;
session.m_calib.ptBoard[i][j][1].x = ptImg[m][n+1].x;
session.m_calib.ptBoard[i][j][1].y = ptImg[m][n+1].y;
session.m_calib.ptBoard[i][j][2].x = ptImg[m+1][n+1].x;
session.m_calib.ptBoard[i][j][2].y = ptImg[m+1][n+1].y;
session.m_calib.ptBoard[i][j][3].x = ptImg[m+1][n].x;
session.m_calib.ptBoard[i][j][3].y = ptImg[m+1][n].y;
}
}
// - - - -
// Outer Left Column
// - - - -
for(i=1, j=0, k=1, m=2, n=3; i<nChessBoardDim-1; ++i)
{
// shared points
session.m_calib.ptBoard[i][j][1].x = session.m_calib.ptBoard[i][k][0].x;
session.m_calib.ptBoard[i][j][1].y = session.m_calib.ptBoard[i][k][0].y;
session.m_calib.ptBoard[i][j][2].x = session.m_calib.ptBoard[i][k][3].x;
session.m_calib.ptBoard[i][j][2].y = session.m_calib.ptBoard[i][k][3].y;
// find the top widths of the 3 right neighbors
w1 = iabs(session.m_calib.ptBoard[i][k][1].x -
session.m_calib.ptBoard[i][k][0].x);
w2 = iabs(session.m_calib.ptBoard[i][m][1].x -
session.m_calib.ptBoard[i][m][0].x);
w3 = iabs(session.m_calib.ptBoard[i][n][1].x -
session.m_calib.ptBoard[i][n][0].x);
// calculate the delta widths and the delta deltas
delta = w1 - w2;
ddelta = 0; //delta - (w2 - w3);
// estimate top left x position
x = (double)(session.m_calib.ptBoard[i][j][1].x - (w1 + delta + ddelta));
//
// y = (y2 - y1)/(x2 - x1) * (x - x1) + y1
//
// delta x and y of the top points of the right neighbor
dx1 = (double)(session.m_calib.ptBoard[i][k][1].x -
session.m_calib.ptBoard[i][k][0].x);
dy1 = (double)(session.m_calib.ptBoard[i][k][1].y -
session.m_calib.ptBoard[i][k][0].y);
// calculate top left y, given the x, by the two-point line formula:
y = dy1/dx1 * (double)(x - session.m_calib.ptBoard[i][k][0].x) +
(double)(session.m_calib.ptBoard[i][k][0].y);
// set top-left point
session.m_calib.ptBoard[i][j][0].x = cvRound(x);
session.m_calib.ptBoard[i][j][0].y = cvRound(y);
// find the bottom widths of the 3 right neighbors
w1 = iabs(session.m_calib.ptBoard[i][k][3].x -
session.m_calib.ptBoard[i][k][2].x);
w2 = iabs(session.m_calib.ptBoard[i][m][3].x -
session.m_calib.ptBoard[i][m][2].x);
w3 = iabs(session.m_calib.ptBoard[i][n][3].x -
session.m_calib.ptBoard[i][n][2].x);
// calculate the delta widths and the delta deltas
delta = w1 - w2;
ddelta = 0; //delta - (w2 - w3);
// estimate bottom left x position
x = (double)(session.m_calib.ptBoard[i][j][2].x - (w1 + delta + ddelta));
//
// y = (y2 - y1)/(x2 - x1) * (x - x1) + y1
//
// delta x and y of the bottom points of the right neighbor
dx1 = (double)(session.m_calib.ptBoard[i][k][3].x -
session.m_calib.ptBoard[i][k][2].x);
dy1 = (double)(session.m_calib.ptBoard[i][k][3].y -
session.m_calib.ptBoard[i][k][2].y);
// calculate bottom left y, given the x, by the two-point line formula:
y = dy1/dx1 * (double)(x - session.m_calib.ptBoard[i][k][2].x) +
(double)(session.m_calib.ptBoard[i][k][2].y);
// set bottom-left point
session.m_calib.ptBoard[i][j][3].x = cvRound(x);
session.m_calib.ptBoard[i][j][3].y = cvRound(y);
}
// - - - -
// Outer Right Column
// - - - -
for(i=1, j=nChessBoardDim-1, k=j-1, m=j-2, n=j-3; i<nChessBoardDim-1; ++i)
{
// shared points
session.m_calib.ptBoard[i][j][0].x = session.m_calib.ptBoard[i][k][1].x;
session.m_calib.ptBoard[i][j][0].y = session.m_calib.ptBoard[i][k][1].y;
session.m_calib.ptBoard[i][j][3].x = session.m_calib.ptBoard[i][k][2].x;
session.m_calib.ptBoard[i][j][3].y = session.m_calib.ptBoard[i][k][2].y;
// find the top widths of the 3 left neighbors
w1 = iabs(session.m_calib.ptBoard[i][k][1].x -
session.m_calib.ptBoard[i][k][0].x);
w2 = iabs(session.m_calib.ptBoard[i][m][1].x -
session.m_calib.ptBoard[i][m][0].x);
w3 = iabs(session.m_calib.ptBoard[i][n][1].x -
session.m_calib.ptBoard[i][n][0].x);
// calculate the delta widths and the delta deltas
delta = w1 - w2;
ddelta = 0; //delta - (w2 - w3);
// estimate top right x position
x = (double)(session.m_calib.ptBoard[i][j][0].x + (w1 + delta + ddelta));
//
// y = (y2 - y1)/(x2 - x1) * (x - x1) + y1
//
// delta x and y of the top points of the left neighbor
dx1 = (double)(session.m_calib.ptBoard[i][k][0].x -
session.m_calib.ptBoard[i][k][1].x);
dy1 = (double)(session.m_calib.ptBoard[i][k][0].y -
session.m_calib.ptBoard[i][k][1].y);
// calculate top left y, given the x, by the two-point line formula:
y = dy1/dx1 * (double)(x - session.m_calib.ptBoard[i][k][1].x) +
(double)(session.m_calib.ptBoard[i][k][1].y);
// set top-right point
session.m_calib.ptBoard[i][j][1].x = cvRound(x);
session.m_calib.ptBoard[i][j][1].y = cvRound(y);
// find the bottom widths of the 3 left neighbors
w1 = iabs(session.m_calib.ptBoard[i][k][3].x -
session.m_calib.ptBoard[i][k][2].x);
w2 = iabs(session.m_calib.ptBoard[i][m][3].x -
session.m_calib.ptBoard[i][m][2].x);
w3 = iabs(session.m_calib.ptBoard[i][n][3].x -
session.m_calib.ptBoard[i][n][2].x);
// calculate the delta widths and the delta deltas
delta = w1 - w2;
ddelta = 0; //delta - (w2 - w3);
// estimate bottom right x position
x = (double)(session.m_calib.ptBoard[i][j][3].x + (w1 + delta + ddelta));
//
// y = (y2 - y1)/(x2 - x1) * (x - x1) + y1
//
// delta x and y of the bottom points of the left neighbor
dx1 = (double)(session.m_calib.ptBoard[i][k][3].x -
session.m_calib.ptBoard[i][k][2].x);
dy1 = (double)(session.m_calib.ptBoard[i][k][3].y -
session.m_calib.ptBoard[i][k][2].y);
// calculate bottom left y, given the x, by the two-point line formula:
y = dy1/dx1 * (double)(x - session.m_calib.ptBoard[i][k][2].x) +
(double)(session.m_calib.ptBoard[i][k][2].y);
// set bottom-right point
session.m_calib.ptBoard[i][j][2].x = cvRound(x);
session.m_calib.ptBoard[i][j][2].y = cvRound(y);
}
// - - - -
// Outer Top Row
// - - - -
for(j=1, i=0, k=1, m=2, n=3; j<nChessBoardDim-1; ++j)
{
// shared points
session.m_calib.ptBoard[i][j][2].x = session.m_calib.ptBoard[k][j][1].x;
session.m_calib.ptBoard[i][j][2].y = session.m_calib.ptBoard[k][j][1].y;
session.m_calib.ptBoard[i][j][3].x = session.m_calib.ptBoard[k][j][0].x;
session.m_calib.ptBoard[i][j][3].y = session.m_calib.ptBoard[k][j][0].y;
// find the left heights of the 3 bottom neighbors
h1 = iabs(session.m_calib.ptBoard[k][j][3].y -
session.m_calib.ptBoard[k][j][0].y);
h2 = iabs(session.m_calib.ptBoard[m][j][3].y -
session.m_calib.ptBoard[m][j][0].y);
h3 = iabs(session.m_calib.ptBoard[n][j][3].y -
session.m_calib.ptBoard[n][j][0].y);
// calculate the delta heights and the delta deltas
delta = h1 - h2;
ddelta = 0; //delta - (h2 - h3);
// estimate top left y position
y = (double)(session.m_calib.ptBoard[i][j][3].y - (h1 + delta + ddelta));
//
// x = (x2 - x1)/(y2 - y1) * (y - y1) + x1
//
// delta x and y of the left points of bottom neighbor
dx1 = (double)(session.m_calib.ptBoard[k][j][3].x -
session.m_calib.ptBoard[k][j][0].x);
dy1 = (double)(session.m_calib.ptBoard[k][j][3].y -
session.m_calib.ptBoard[k][j][0].y);
// calculate top left x, given the y, by the two-point line formula:
x = dx1/dy1 * (double)(y - session.m_calib.ptBoard[k][j][0].y) +
(double)(session.m_calib.ptBoard[k][j][0].x);
// set top-left point
session.m_calib.ptBoard[i][j][0].x = cvRound(x);
session.m_calib.ptBoard[i][j][0].y = cvRound(y);
// find the right heights of the 3 bottom neighbors
h1 = iabs(session.m_calib.ptBoard[k][j][2].y -
session.m_calib.ptBoard[k][j][1].y);
h2 = iabs(session.m_calib.ptBoard[m][j][2].y -
session.m_calib.ptBoard[m][j][1].y);
h3 = iabs(session.m_calib.ptBoard[n][j][2].y -
session.m_calib.ptBoard[n][j][1].y);
// calculate the delta heights and the delta deltas
delta = h1 - h2;
ddelta = 0; //delta - (h2 - h3);
// estimate top right y position
y = (double)(session.m_calib.ptBoard[i][j][2].y - (h1 + delta + ddelta));
//
// x = (x2 - x1)/(y2 - y1) * (y - y1) + x1
//
// delta x and y of the right points of bottom neighbor
dx1 = (double)(session.m_calib.ptBoard[k][j][2].x -
session.m_calib.ptBoard[k][j][1].x);
dy1 = (double)(session.m_calib.ptBoard[k][j][2].y -
session.m_calib.ptBoard[k][j][1].y);
// calculate top right x, given the y, by the two-point line formula:
// x = (x2 - x1)/(y2 - y1) * (y - y1) + x1
x = dx1/dy1 * (double)(y - session.m_calib.ptBoard[k][j][1].y) +
(double)(session.m_calib.ptBoard[k][j][1].x);
// set top-right point
session.m_calib.ptBoard[i][j][1].x = cvRound(x);
session.m_calib.ptBoard[i][j][1].y = cvRound(y);
}
// - - - -
// Outer Bottom Row
// - - - -
for(j=1, i=nChessBoardDim-1, k=i-1, m=i-2, n=i-3; j<nChessBoardDim-1; ++j)
{
// shared points
session.m_calib.ptBoard[i][j][0].x = session.m_calib.ptBoard[k][j][3].x;
session.m_calib.ptBoard[i][j][0].y = session.m_calib.ptBoard[k][j][3].y;
session.m_calib.ptBoard[i][j][1].x = session.m_calib.ptBoard[k][j][2].x;
session.m_calib.ptBoard[i][j][1].y = session.m_calib.ptBoard[k][j][2].y;
// find the left heights of the 3 top neighbors
h1 = iabs(session.m_calib.ptBoard[k][j][3].y -
session.m_calib.ptBoard[k][j][0].y);
h2 = iabs(session.m_calib.ptBoard[m][j][3].y -
session.m_calib.ptBoard[m][j][0].y);
h3 = iabs(session.m_calib.ptBoard[n][j][3].y -
session.m_calib.ptBoard[n][j][0].y);
// calculate the delta heights and the delta deltas
delta = h1 - h2;
ddelta = 0; //delta - (h2 - h3);
// estimate bottom left y position
y = (double)(session.m_calib.ptBoard[i][j][0].y + (h1 + delta + ddelta));
//
// x = (x2 - x1)/(y2 - y1) * (y - y1) + x1
//
// delta x and y of the left points of top neighbor
dx1 = (double)(session.m_calib.ptBoard[k][j][3].x -
session.m_calib.ptBoard[k][j][0].x);
dy1 = (double)(session.m_calib.ptBoard[k][j][3].y -
session.m_calib.ptBoard[k][j][0].y);
// calculate bottom left x, given the y, by the two-point line formula:
x = dx1/dy1 * (double)(y - session.m_calib.ptBoard[k][j][0].y) +
(double)(session.m_calib.ptBoard[k][j][0].x);
// set top-left point
session.m_calib.ptBoard[i][j][3].x = cvRound(x);
session.m_calib.ptBoard[i][j][3].y = cvRound(y);
// find the right heights of the 3 top neighbors
h1 = iabs(session.m_calib.ptBoard[k][j][2].y -
session.m_calib.ptBoard[k][j][1].y);
h2 = iabs(session.m_calib.ptBoard[m][j][2].y -
session.m_calib.ptBoard[m][j][1].y);
h3 = iabs(session.m_calib.ptBoard[n][j][2].y -
session.m_calib.ptBoard[n][j][1].y);
// calculate the delta heights and the delta deltas
delta = h1 - h2;
ddelta = 0; //delta - (h2 - h3);
// estimate bottom right y position
y = (double)(session.m_calib.ptBoard[i][j][1].y + (h1 + delta + ddelta));
//
// x = (x2 - x1)/(y2 - y1) * (y - y1) + x1
//
// delta x and y of the right points of top neighbor
dx1 = (double)(session.m_calib.ptBoard[k][j][2].x -
session.m_calib.ptBoard[k][j][1].x);
dy1 = (double)(session.m_calib.ptBoard[k][j][2].y -
session.m_calib.ptBoard[k][j][1].y);
// calculate bottom right x, given the y, by the two-point line formula:
// x = (x2 - x1)/(y2 - y1) * (y - y1) + x1
x = dx1/dy1 * (double)(y - session.m_calib.ptBoard[k][j][1].y) +
(double)(session.m_calib.ptBoard[k][j][1].x);
// set top-right point
session.m_calib.ptBoard[i][j][2].x = cvRound(x);
session.m_calib.ptBoard[i][j][2].y = cvRound(y);
}
// - - - -
// Top Left Corner
// - - - -
i = 0; j = 0; m = 1; n = 1;
// shared points
session.m_calib.ptBoard[i][j][1].x = session.m_calib.ptBoard[i][n][0].x;
session.m_calib.ptBoard[i][j][1].y = session.m_calib.ptBoard[i][n][0].y;
session.m_calib.ptBoard[i][j][2].x = session.m_calib.ptBoard[i][n][3].x;
session.m_calib.ptBoard[i][j][2].y = session.m_calib.ptBoard[i][n][3].y;
session.m_calib.ptBoard[i][j][3].x = session.m_calib.ptBoard[m][j][0].x;
session.m_calib.ptBoard[i][j][3].y = session.m_calib.ptBoard[m][j][0].y;
// line 1
x11 = (double)session.m_calib.ptBoard[i][n][0].x;
y11 = (double)session.m_calib.ptBoard[i][n][0].y;
x12 = (double)session.m_calib.ptBoard[i][n][1].x;
y12 = (double)session.m_calib.ptBoard[i][n][1].y;
dx1 = x12 - x11;
dy1 = y12 - y11;
// line 2
x21 = (double)session.m_calib.ptBoard[m][j][0].x;
y21 = (double)session.m_calib.ptBoard[m][j][0].y;
x22 = (double)session.m_calib.ptBoard[m][j][3].x;
y22 = (double)session.m_calib.ptBoard[m][j][3].y;
dx2 = x22 - x21;
dy2 = y22 - y21;
// calculate intersection
x = (y21 - y11 + dy1/dx1 * x11 - dy2/dx2 * x21) / (dy1/dx1 - dy2/dx2);
y = dy1/dx1 * (x - x11) + y11;
// set top-left point
session.m_calib.ptBoard[i][j][0].x = cvRound(x);
session.m_calib.ptBoard[i][j][0].y = cvRound(y);
// - - - -
// Top Right Corner
// - - - -
i = 0; j = nChessBoardDim-1; m = 1; n = j - 1;
// shared points
session.m_calib.ptBoard[i][j][0].x = session.m_calib.ptBoard[i][n][1].x;
session.m_calib.ptBoard[i][j][0].y = session.m_calib.ptBoard[i][n][1].y;
session.m_calib.ptBoard[i][j][2].x = session.m_calib.ptBoard[m][j][1].x;
session.m_calib.ptBoard[i][j][2].y = session.m_calib.ptBoard[m][j][1].y;
session.m_calib.ptBoard[i][j][3].x = session.m_calib.ptBoard[m][j][0].x;
session.m_calib.ptBoard[i][j][3].y = session.m_calib.ptBoard[m][j][0].y;
// line 1
x11 = (double)session.m_calib.ptBoard[i][n][0].x;
y11 = (double)session.m_calib.ptBoard[i][n][0].y;
x12 = (double)session.m_calib.ptBoard[i][n][1].x;
y12 = (double)session.m_calib.ptBoard[i][n][1].y;
dx1 = x12 - x11;
dy1 = y12 - y11;
// line 2
x21 = (double)session.m_calib.ptBoard[m][j][1].x;
y21 = (double)session.m_calib.ptBoard[m][j][1].y;
x22 = (double)session.m_calib.ptBoard[m][j][2].x;
y22 = (double)session.m_calib.ptBoard[m][j][2].y;
dx2 = x22 - x21;
dy2 = y22 - y21;
// calculate intersection
x = (y21 - y11 + dy1/dx1 * x11 - dy2/dx2 * x21) / (dy1/dx1 - dy2/dx2);
y = dy1/dx1 * (x - x11) + y11;
// set top-left point
session.m_calib.ptBoard[i][j][1].x = cvRound(x);
session.m_calib.ptBoard[i][j][1].y = cvRound(y);
// - - - -
// Bottom Right Corner
// - - - -
i = nChessBoardDim-1; j = nChessBoardDim-1; m = i - 1; n = j - 1;
// shared points
session.m_calib.ptBoard[i][j][0].x = session.m_calib.ptBoard[i][n][1].x;
session.m_calib.ptBoard[i][j][0].y = session.m_calib.ptBoard[i][n][1].y;
session.m_calib.ptBoard[i][j][1].x = session.m_calib.ptBoard[m][j][2].x;
session.m_calib.ptBoard[i][j][1].y = session.m_calib.ptBoard[m][j][2].y;
session.m_calib.ptBoard[i][j][3].x = session.m_calib.ptBoard[i][n][2].x;
session.m_calib.ptBoard[i][j][3].y = session.m_calib.ptBoard[i][n][2].y;
// line 1
x11 = (double)session.m_calib.ptBoard[i][n][2].x;
y11 = (double)session.m_calib.ptBoard[i][n][2].y;
x12 = (double)session.m_calib.ptBoard[i][n][3].x;
y12 = (double)session.m_calib.ptBoard[i][n][3].y;
dx1 = x12 - x11;
dy1 = y12 - y11;
// line 2
x21 = (double)session.m_calib.ptBoard[m][j][1].x;
y21 = (double)session.m_calib.ptBoard[m][j][1].y;
x22 = (double)session.m_calib.ptBoard[m][j][2].x;
y22 = (double)session.m_calib.ptBoard[m][j][2].y;
dx2 = x22 - x21;
dy2 = y22 - y21;
// calculate intersection
x = (y21 - y11 + dy1/dx1 * x11 - dy2/dx2 * x21) / (dy1/dx1 - dy2/dx2);
y = dy1/dx1 * (x - x11) + y11;
// set top-left point
session.m_calib.ptBoard[i][j][2].x = cvRound(x);
session.m_calib.ptBoard[i][j][2].y = cvRound(y);
// - - - -
// Bottom Left Corner
// - - - -
i = nChessBoardDim-1; j = 0; m = i - 1; n = 1;
// shared points
session.m_calib.ptBoard[i][j][0].x = session.m_calib.ptBoard[m][j][3].x;
session.m_calib.ptBoard[i][j][0].y = session.m_calib.ptBoard[m][j][3].y;
session.m_calib.ptBoard[i][j][1].x = session.m_calib.ptBoard[m][j][2].x;
session.m_calib.ptBoard[i][j][1].y = session.m_calib.ptBoard[m][j][2].y;
session.m_calib.ptBoard[i][j][2].x = session.m_calib.ptBoard[i][n][3].x;
session.m_calib.ptBoard[i][j][2].y = session.m_calib.ptBoard[i][n][3].y;
// line 1
x11 = (double)session.m_calib.ptBoard[i][n][2].x;
y11 = (double)session.m_calib.ptBoard[i][n][2].y;
x12 = (double)session.m_calib.ptBoard[i][n][3].x;
y12 = (double)session.m_calib.ptBoard[i][n][3].y;
dx1 = x12 - x11;
dy1 = y12 - y11;
// line 2
x21 = (double)session.m_calib.ptBoard[m][j][0].x;
y21 = (double)session.m_calib.ptBoard[m][j][0].y;
x22 = (double)session.m_calib.ptBoard[m][j][3].x;
y22 = (double)session.m_calib.ptBoard[m][j][3].y;
dx2 = x22 - x21;
dy2 = y22 - y21;
// calculate intersection
x = (y21 - y11 + dy1/dx1 * x11 - dy2/dx2 * x21) / (dy1/dx1 - dy2/dx2);
y = dy1/dx1 * (x - x11) + y11;
// set top-left point
session.m_calib.ptBoard[i][j][3].x = cvRound(x);
session.m_calib.ptBoard[i][j][3].y = cvRound(y);
// - - - -
// Draw calibration
// - - - -
cvInitFont(&font, CV_FONT_HERSHEY_DUPLEX, 0.75, 0.75, 0, 1);
for(i=0; i<nChessBoardDim; ++i)
{
for(j=0, n=0; j<nChessBoardDim; ++j)
{
if( (session.m_calib.ptBoard[i][j][0].x == 0) &&
(session.m_calib.ptBoard[i][j][1].y == 0) )
{
continue;
}
cvPutText(pImg, StaleMateChessBoardCoordStr(i, j),
session.m_calib.ptBoard[i][j][3], &font, colorText);
pPolyLines[n] = session.m_calib.ptBoard[i][j];
nPolyPts[n] = 4;
n++;
}
if( n > 0 )
{
cvPolyLine(pImg, pPolyLines, nPolyPts, n, 2, colorPoly,
1, 8);
}
}
StaleMateIoIShow(session, pImg, session.m_vid.uImgIndex1);
cvReleaseImage(&pImgGray);
return true;
}
static bool SMCalibVideo(StaleMateSession &session)
{
IplImage *pImg;
if( (pImg = StaleMateVideoCreateSnapShot(session)) == NULL )
{
return false;
}
if( session.m_calib.pImgEmptyRed != NULL )
{
cvReleaseImage(&session.m_calib.pImgEmptyRed);
}
session.m_calib.pImgEmptyRed = StaleMateCreateRgbChannel(pImg, CHANNEL_RED);
if( session.m_calib.pImgEmptyBlue != NULL )
{
cvReleaseImage(&session.m_calib.pImgEmptyBlue);
}
session.m_calib.pImgEmptyBlue = StaleMateCreateRgbChannel(pImg, CHANNEL_BLUE);
cvReleaseImage(&pImg);
return true;
}
static bool SMCalibRoi(StaleMateSession &session, int nChessBoardDim)
{
int k;
int w1, w2;
int h1, h2;
k = nChessBoardDim - 1;
if( session.m_calib.ptBoard[0][0][0].x < session.m_calib.ptBoard[k][0][3].x )
{
session.m_calib.rectRoiBoard.x = session.m_calib.ptBoard[0][0][0].x;
}
else
{
session.m_calib.rectRoiBoard.x = session.m_calib.ptBoard[k][0][3].x;
}
if( session.m_calib.ptBoard[0][0][0].y < session.m_calib.ptBoard[0][k][1].y )
{
session.m_calib.rectRoiBoard.y = session.m_calib.ptBoard[0][0][0].y;
}
else
{
session.m_calib.rectRoiBoard.y = session.m_calib.ptBoard[0][k][1].y;
}
w1 = session.m_calib.ptBoard[0][k][1].x - session.m_calib.ptBoard[0][0][0].x;
w2 = session.m_calib.ptBoard[k][k][2].x - session.m_calib.ptBoard[k][0][3].x;
session.m_calib.rectRoiBoard.width = w1 >= w2? w1: w2;
h1 = session.m_calib.ptBoard[k][0][3].y - session.m_calib.ptBoard[0][0][0].y;
h2 = session.m_calib.ptBoard[k][k][2].y - session.m_calib.ptBoard[0][k][1].y;
session.m_calib.rectRoiBoard.height = h1 >= h2? h1: h2;
return true;
}
// positive x is forward, positive y is left
static bool SMCalibDist(StaleMateSession &session,
int nChessBoardDim,
CvPoint2D32f &ptDEBottom)
{
CvPoint2D32f ptOrig;
double x, y;
int i, j;
// origin is the center of upper left corner chess square
ptOrig.x = ptDEBottom.x + (double)nChessBoardDim * TuneChessSquareDim -
TuneChessSquareDim / 2.0;
ptOrig.y = ptDEBottom.y + (double)(nChessBoardDim)/2.0 * TuneChessSquareDim -
TuneChessSquareDim / 2.0;
for(i=0, x = ptOrig.x; i<nChessBoardDim; ++i, x -= TuneChessSquareDim)
{
for(j=0, y = ptOrig.y; j<nChessBoardDim; ++j, y -= TuneChessSquareDim)
{
session.m_calib.ptHekDist[i][j].x = x;
session.m_calib.ptHekDist[i][j].y = y;
}
}
session.m_calib.ptDEBottom = ptDEBottom;
return true;
}
static void SMCalibShowAnnotated(StaleMateSession &session)
{
int nDim = session.m_game.nChessBoardDim;
IplImage *pImg;
CvScalar colorText = CV_RGB(0, 64, 64);
CvScalar colorPoly = CV_RGB(64, 32, 255);
CvScalar colorRoi = CV_RGB(0, 32, 64);
CvFont font;
char bufText[32];
CvPoint *pPolyLines[nDim];
int nPolyPts[nDim];
CvPoint pt1, pt2;
int i, j, k;
if( (pImg = StaleMateVideoCreateSnapShot(session)) == NULL )
{
return;
}
cvInitFont(&font, CV_FONT_HERSHEY_DUPLEX, 0.75, 0.75, 0, 1);
pt1.x = 5;
pt1.y = 25;
cvPutText(pImg, "Calibration", pt1, &font, colorText);
for(i=0; i<nDim; ++i)
{
for(j=0, k=0; j<nDim; ++j)
{
pt1 = session.m_calib.ptBoard[i][j][3];
pt1.x += 3;
pt1.y -= 3;
cvPutText(pImg, StaleMateChessBoardCoordStr(i, j), pt1, &font, colorText);
pPolyLines[k] = session.m_calib.ptBoard[i][j];
nPolyPts[k] = 4;
k++;
}
cvPolyLine(pImg, pPolyLines, nPolyPts, nDim, 2, colorPoly, 2, 8);
}
pt1.x = session.m_calib.rectRoiBoard.x;
pt1.y = session.m_calib.rectRoiBoard.y;
pt2.x = pt1.x + session.m_calib.rectRoiBoard.width - 1;
pt2.y = pt1.y + session.m_calib.rectRoiBoard.height - 1;
cvRectangle(pImg, pt1, pt2, colorRoi, 1);
StaleMateIoIShow(session, pImg, session.m_vid.uImgIndex1);
cvReleaseImage(&pImg);
}
// ---------------------------------------------------------------------------
// Public Interface
// ---------------------------------------------------------------------------
void StaleMateCalib(StaleMateSession &session)
{
session.m_calib.bCalibrated = false;
if( !SMCalibBoardSquares(session, session.m_game.nChessBoardDim) )
{
return;
}
if( !SMCalibVideo(session) )
{
return;
}
if( !SMCalibRoi(session, session.m_game.nChessBoardDim) )
{
return;
}
if( !SMCalibDist(session, session.m_game.nChessBoardDim,
session.m_calib.ptDEBottom) )
{
return;
}
SMCalibShowAnnotated(session);
LOGDIAG1("Calibration complete.");
session.m_calib.bCalibrated = true;
}
| 32.248654
| 80
| 0.580326
|
b28231caa353634e4f4fad520577693621d574ae
| 856
|
dart
|
Dart
|
lib/animated_segment.dart
|
saitbnzl/digital_glass_clock
|
ac4111a9146a0e9843dfd68cc4e93fe18378b8e4
|
[
"MIT"
] | null | null | null |
lib/animated_segment.dart
|
saitbnzl/digital_glass_clock
|
ac4111a9146a0e9843dfd68cc4e93fe18378b8e4
|
[
"MIT"
] | null | null | null |
lib/animated_segment.dart
|
saitbnzl/digital_glass_clock
|
ac4111a9146a0e9843dfd68cc4e93fe18378b8e4
|
[
"MIT"
] | null | null | null |
import 'package:digital_glass_clock/segment.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
class AnimatedSegment extends StatelessWidget {
const AnimatedSegment({
Key key,
@required this.size,
@required this.axis,
this.offOpacity: 0.2,
this.onOpacity: 1.0,
this.color: Colors.white,
this.isOn: false,
Curve curve = Curves.linear,
@required this.duration,
});
final Size size;
final Axis axis;
final bool isOn;
final double offOpacity;
final double onOpacity;
final Duration duration;
final Color color;
@override
Widget build(BuildContext context) {
return AnimatedOpacity(
duration: duration,
opacity: isOn ? onOpacity : offOpacity,
child: Segment(
color: color,
size: size,
axis: axis,
),
);
}
}
| 21.948718
| 50
| 0.667056
|
0decba7baeb6820ac7cafab4d2703fa5bc9bd7e0
| 3,669
|
cs
|
C#
|
Components/Index/Rows.cs
|
olegbruev/OrderMakerServer
|
64089373452e06b499711affd29eca126e4bdb5c
|
[
"MIT"
] | null | null | null |
Components/Index/Rows.cs
|
olegbruev/OrderMakerServer
|
64089373452e06b499711affd29eca126e4bdb5c
|
[
"MIT"
] | null | null | null |
Components/Index/Rows.cs
|
olegbruev/OrderMakerServer
|
64089373452e06b499711affd29eca126e4bdb5c
|
[
"MIT"
] | null | null | null |
/*
MTD OrderMaker - http://ordermaker.org
Copyright (c) 2019 Oleg Bruev <job4bruev@gmail.com>. All rights reserved.
*/
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Mtd.OrderMaker.Server.Areas.Identity.Data;
using Mtd.OrderMaker.Server.Entity;
using Mtd.OrderMaker.Server.EntityHandler.Approval;
using Mtd.OrderMaker.Server.EntityHandler.Filter;
using Mtd.OrderMaker.Server.EntityHandler.Stack;
using Mtd.OrderMaker.Server.Models.Index;
using Mtd.OrderMaker.Server.Services;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
namespace Mtd.OrderMaker.Server.Components.Index
{
[ViewComponent(Name = "IndexRows")]
public class Rows : ViewComponent
{
private readonly OrderMakerContext _context;
private readonly UserHandler _userHandler;
public int pageCount = 0;
public Rows(OrderMakerContext orderMakerContext, UserHandler userHandler)
{
_context = orderMakerContext;
_userHandler = userHandler;
}
public async Task<IViewComponentResult> InvokeAsync(string formId)
{
var user = await _userHandler.GetUserAsync(HttpContext.User);
FilterHandler handlerFilter = new FilterHandler(_context, formId, user, _userHandler);
Incomer incomer = await handlerFilter.GetIncomerDataAsync();
TypeQuery typeQuery = await handlerFilter.GetTypeQueryAsync(user);
OutFlow outFlow = await handlerFilter.GetStackFlowAsync(incomer, typeQuery);
IList<MtdStore> mtdStores = outFlow.MtdStores;
IList<string> storeIds = mtdStores.Select(s => s.Id).ToList();
StackHandler handlerStack = new StackHandler(_context);
IList<MtdStoreStack> mtdStoreStack = await handlerStack.GetStackAsync(storeIds, incomer.FieldIds);
IList<MtdStoreApproval> mtdStoreApprovals = await _context.MtdStoreApproval.Where(x => storeIds.Contains(x.Id)).ToListAsync();
List<ApprovalStore> approvalStores = await ApprovalHandler.GetStoreStatusAsync(_context, storeIds, user);
MtdApproval mtdApproval = await _context.MtdApproval.Where(x => x.MtdForm == formId).FirstOrDefaultAsync();
MtdFilter filter = await _context.MtdFilter.FirstOrDefaultAsync(x => x.IdUser == user.Id && x.MtdForm == formId);
var mtdFormList = await ApprovalHandler.GetWaitStoreIds(_context, user, formId);
int pending = mtdFormList.Count();
RowsModelView rowsModel = new RowsModelView
{
FormId = formId,
SearchNumber = incomer.SearchNumber,
PageCount = outFlow.PageCount,
MtdFormPartFields = incomer.FieldForColumn,
MtdStores = mtdStores,
MtdStoreStack = mtdStoreStack,
WaitList = incomer.WaitList == 1,
ShowDate = await handlerFilter.IsShowDate(),
ShowNumber = await handlerFilter.IsShowNumber(),
ApprovalStores = approvalStores,
MtdApproval = mtdApproval,
StoreIds = string.Join("&", storeIds),
SearchText = filter == null ? string.Empty : filter.SearchText,
Pending = pending,
IsCreator = await _userHandler.IsCreator(user, formId),
PageSize = filter.PageSize,
PageCurrent = filter.Page,
};
return View("Default", rowsModel);
}
}
}
| 41.693182
| 138
| 0.659853
|
7bda7b8671161a60717056e8b9f149dda12325a8
| 495
|
cpp
|
C++
|
DisjoinSetUnion/CPP/DSU.cpp
|
riship99/codeWith-hacktoberfest
|
f16fa9dc9a2af0009dea3dea3220e3eaa43d3d2b
|
[
"MIT"
] | 29
|
2020-10-03T17:41:46.000Z
|
2021-10-04T17:59:22.000Z
|
DisjoinSetUnion/CPP/DSU.cpp
|
riship99/codeWith-hacktoberfest
|
f16fa9dc9a2af0009dea3dea3220e3eaa43d3d2b
|
[
"MIT"
] | 117
|
2020-10-03T15:39:39.000Z
|
2021-10-06T08:21:37.000Z
|
DisjoinSetUnion/CPP/DSU.cpp
|
riship99/codeWith-hacktoberfest
|
f16fa9dc9a2af0009dea3dea3220e3eaa43d3d2b
|
[
"MIT"
] | 160
|
2020-10-03T15:39:23.000Z
|
2021-10-13T09:07:05.000Z
|
#include <bits/stdc++.h>
using namespace std;
#define rank rnk
const int N = 1e5 + 5;
int rank[N], p[N];
void init() {
for (int i = 0; i < N; i++)
rank[i] = 0, p[i] = i;
}
int findp(int n) {
return n == p[n] ? n : p[n] = findp(p[n]);
}
bool merge(int u, int v) {
u = findp(u);
v = findp(v);
if (u == v)
return false;
if (rank[u] < rank[v])
swap(u, v);
if (rank[u] == rank[v])
rank[u]++;
p[v]=u;
return true;
}
bool isSameSet(int u,int v){
return findp(u)==findp(v);
}
| 13.378378
| 43
| 0.527273
|
a8d9a00701573182fcbe46ee72747be5bb2560ad
| 361
|
dart
|
Dart
|
lib/constants.dart
|
monkey-underground-coders/reschedule-tsu-native
|
b8c83346803348a8d03b38ac4bb0db8c1ed0d0a5
|
[
"MIT"
] | null | null | null |
lib/constants.dart
|
monkey-underground-coders/reschedule-tsu-native
|
b8c83346803348a8d03b38ac4bb0db8c1ed0d0a5
|
[
"MIT"
] | null | null | null |
lib/constants.dart
|
monkey-underground-coders/reschedule-tsu-native
|
b8c83346803348a8d03b38ac4bb0db8c1ed0d0a5
|
[
"MIT"
] | null | null | null |
import 'package:flutter/material.dart';
final Color backgroundColor = Color(0xFF2A3DAD);
final Color backgroundColorTransient = backgroundColor.withOpacity(0.88);
final Color headlineColor = Color(0xFF1C2456);
final Color secondaryColor = Color(0xFF9D9D9D);
final Color secondaryBGColor = Color(0xFFF1F1F1);
final Color secondaryBGColor2 = Color(0xFFE9E9E9);
| 36.1
| 73
| 0.817175
|
e29e5cc9850231eaf0630eb80ff738820b80de6a
| 7,309
|
py
|
Python
|
data_processing/pm25_contour/pm2.5_transfer_to_contour_geojson.py
|
tasi788/pm2.5-idw-map
|
59135705ce61d25f5f0a066dff00ed3a817675f6
|
[
"BSD-2-Clause"
] | 26
|
2018-08-16T06:46:22.000Z
|
2022-03-17T09:51:31.000Z
|
data_processing/pm25_contour/pm2.5_transfer_to_contour_geojson.py
|
tasi788/pm2.5-idw-map
|
59135705ce61d25f5f0a066dff00ed3a817675f6
|
[
"BSD-2-Clause"
] | 1
|
2021-11-23T08:36:31.000Z
|
2021-12-16T15:56:08.000Z
|
data_processing/pm25_contour/pm2.5_transfer_to_contour_geojson.py
|
tasi788/pm2.5-idw-map
|
59135705ce61d25f5f0a066dff00ed3a817675f6
|
[
"BSD-2-Clause"
] | 7
|
2018-08-16T06:46:32.000Z
|
2022-02-28T15:47:55.000Z
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on 2018 Apr.
@author: huanglipang
Discription:
converting pm2.5 data to contour geojosn using IDW
Dependencies:
python 3.6.4
numpy 1.14.0
matplotlib 2.1.2
geojsoncontour 0.3.0
"""
import numpy
import matplotlib
# use("Agg") for console execution
matplotlib.use("Agg")
import matplotlib.pyplot as plt
import geojsoncontour
import json
import time
from math import sqrt, pow, log
import config
import logging
import logging.config
import logging_config
from logging_config import RotatingFileNameHandler
# parameters & settings ------------------------------
# all path are absolute path
DIR = config.DIR
DATA_PATH = config.CONTOUR["DATA_PATH"]
LOG_PATH = config.CONTOUR["LOG_PATH"]
# lat lon boundary
BOUNDARY = config.CONTOUR["BOUNDARY"]
"""
BOUNDARY = {
"lat": {"min": 21.0, "max": 26.0},
"lon": {"min": 119.0, "max": 123.0}
}
"""
# PRIECISE of how many division in lenth, e.g. 10, 100, 1000 etc.
PRECISE = config.CONTOUR["PRECISE"]
LOG_PRECISE = int(log(PRECISE, 10)) + 1
# grid size
# a cell of 1 lat * 1 lon
# length of 1 degree lon = 111.320 km
# length of 1 degree lat = 110.574 km
GRID_SIZE = 1.0 / PRECISE
# effective range in KM
EFFECTIVE_RANGE = config.CONTOUR["EFFECTIVE_RANGE"]
# exponential factor for calculating idw value
EXP_FACTOR = config.CONTOUR["EXP_FACTOR"]
# ------------------------------ parameters & settings
# Inverse Distance Weighting (IDW)
# Σ (1 / (di ^ p)) * vi
# V = -------------------------
# Σ (1 / (di ^ p))
# Reference:
# http://www.gitta.info/ContiSpatVar/de/html/Interpolatio_learningObject2.xhtml
# load config file
logging.config.dictConfig(logging_config.LOGGING)
# create logger
logger = logging.getLogger()
# RotatingFileNameHandler(filename, logPath)
logger.addHandler(RotatingFileNameHandler(__file__, LOG_PATH))
start = time.time()
logger.info("pm2.5 data to contour geojson conversion starts")
### Create lat and lon vectors and grid data
try:
# loading data points [lat, lon, value]
data = json.load(open(DATA_PATH), parse_float = float)
except Exception as err:
logger.error("load data.json error.")
logger.error(err)
# numpy.arange(start, stop, step)
# numpy.arange(3, 7, 2) > [3, 5]
lonRange = numpy.arange(BOUNDARY["lon"]["min"],\
BOUNDARY["lon"]["max"], GRID_SIZE)
latRange = numpy.arange(BOUNDARY["lat"]["min"],\
BOUNDARY["lat"]["max"], GRID_SIZE)
latDiff = int(BOUNDARY["lat"]["max"] - BOUNDARY["lat"]["min"])
lonDiff = int(BOUNDARY["lon"]["max"] - BOUNDARY["lon"]["min"])
lonCellLength = lonDiff * PRECISE
latCellLength = latDiff * PRECISE
# numpy.zeros returns a new array of given shape and type, filled with zeros.
# cell[lat][lon]
# cell summation numerator
cellSN = numpy.zeros((latCellLength, lonCellLength),\
dtype=float, order='C')
# cell summation denominator
cellSD = numpy.zeros((latCellLength, lonCellLength),\
dtype=float, order='C')
pm25Value = numpy.zeros((latCellLength, lonCellLength),\
dtype=float, order='C')
temp = time.time()
logger.info("idw calculation starts: %f" % (temp - start))
for point in data["points"]:
# point[lat][lon][value]
# point is the center of the cell
lat = round(point[0], LOG_PRECISE)
lon = round(point[1], LOG_PRECISE)
value = float(point[2])
if(lat >= BOUNDARY["lat"]["min"] and lat < BOUNDARY["lat"]["max"] and \
lon >= BOUNDARY["lon"]["min"] and lon < BOUNDARY["lon"]["max"]):
# calculate boundary coordinate in cellSN and cellSD
# boundary of cell in lat lon
x1 = lon - EFFECTIVE_RANGE / 111.320
x2 = lon + EFFECTIVE_RANGE / 111.320
y1 = lat - EFFECTIVE_RANGE / 110.574
y2 = lat + EFFECTIVE_RANGE / 110.574
# boundary of cell in cellSN cellSD index
x1 = int(round(x1 - BOUNDARY["lon"]["min"], LOG_PRECISE) * PRECISE)
x2 = int(round(x2 - BOUNDARY["lon"]["min"], LOG_PRECISE) * PRECISE)
y1 = int(round(y1 - BOUNDARY["lat"]["min"], LOG_PRECISE) * PRECISE)
y2 = int(round(y2 - BOUNDARY["lat"]["min"], LOG_PRECISE) * PRECISE)
# check x1, x2, y1, y2 in the index boundary
if(x2 < 0):
continue
if(x1 >= lonCellLength):
continue
if(y2 < 0):
continue
if(y1 >= latCellLength):
continue
if(x1 < 0):
x1 = 0
if(x2 >= lonCellLength):
x2 = lonDiff * PRECISE - 1
if(y1 < 0):
y1 = 0
if(y2 >= latCellLength):
y2 = latDiff * PRECISE - 1
# transfer lat lon into index
lat = int((lat - BOUNDARY["lat"]["min"]) * PRECISE)
lon = int((lon - BOUNDARY["lon"]["min"]) * PRECISE)
# set cell center values
cellSN[lat][lon] = value
cellSD[lat][lon] = -1
# calculate idw
# y represents latitude
# x represents longitude
for y in range(y1, y2):
for x in range(x1, x2):
if(cellSD[y][x] < 0.0):
# center of the cell
# which has real pm2.5 value
# cellSD = -1
continue
# calculate distance
distance = sqrt(pow(((x - lon) / PRECISE * 111.320), 2) +\
pow(((y - lat) / PRECISE * 110.574), 2))
if(distance > EFFECTIVE_RANGE):
continue
if distance > 0:
distanceExp = pow(distance, EXP_FACTOR)
cellSN[y][x] += value / distanceExp
cellSD[y][x] += 1 / distanceExp
temp = time.time()
logger.info("idw calculation completes: %f" % (temp - start))
for y in range(0, latCellLength):
for x in range(0, lonCellLength):
if(cellSD[y][x] < 0):
cellSD[y][x] = 1
interpolateValue = 0
if(cellSN[y][x] != 0):
interpolateValue = cellSN[y][x] / cellSD[y][x]
# calculate pm2.5 value
pm25Value[y][x] = interpolateValue
temp = time.time()
logger.info("pm2.5 interpolation value calculation completes: %f" % (temp - start))
### Create a contour plot from grid (lat, lon) data ###
# Create a new figure
figure = plt.figure()
# only one figure show on console
ax = figure.add_subplot(111)
n_contours = {
# "1": 150,
# "2": 75,
# "3": 50,
"5": 30,
"10": 15
}
# numpy.linspace(start, stop, num=50, endpoint=True, retstep=False, dtype=None)
# Return evenly spaced numbers over a specified interval.
# num = number of samples to generate
contourIntervals = {
# "1": numpy.linspace(start = 0, stop = 150, num = n_contours["1"]),
# "2": numpy.linspace(start = 0, stop = 150, num = n_contours["2"]),
# "3": numpy.linspace(start = 0, stop = 150, num = n_contours["3"]),
# "5": numpy.linspace(start = 0, stop = 150, num = n_contours["5"]),
"10": numpy.linspace(start = 0, stop = 150, num = n_contours["10"])
}
# plot contour
for interval in contourIntervals:
contour_grey = ax.contour(lonRange, latRange, pm25Value,\
levels = contourIntervals[interval],\
cmap = None,\
colors = "black"\
)
### Convert matplotlib contour to geojson
geojsoncontour.contour_to_geojson(
contour = contour_grey,
geojson_filepath = DIR + 'data/pm25Contour_grey_' + interval + '.geojson',
min_angle_deg = 10.0,
ndigits = 3,
stroke_width = 2,
unit = "μg/m^3"
)
end = time.time()
logger.info("pm2.5 contour geojson completes: %f" % (end - start))
| 29.591093
| 83
| 0.624162
|
2394ba42c6be35b8bd31686c0a5e444ec92a5e5e
| 224
|
swift
|
Swift
|
Sources/SherlockHUD/UncheckedSendable.swift
|
inamiy/SherlockForms
|
9e995e2350102c8249443a734e3a4471a9d56c91
|
[
"MIT"
] | 71
|
2022-02-14T13:42:10.000Z
|
2022-03-30T01:59:35.000Z
|
Sources/SherlockHUD/UncheckedSendable.swift
|
inamiy/SherlockForms
|
9e995e2350102c8249443a734e3a4471a9d56c91
|
[
"MIT"
] | null | null | null |
Sources/SherlockHUD/UncheckedSendable.swift
|
inamiy/SherlockForms
|
9e995e2350102c8249443a734e3a4471a9d56c91
|
[
"MIT"
] | null | null | null |
// TODO: Remove `@unchecked Sendable` when `Sendable` is supported by each module.
import SwiftUI
extension AnyView: @unchecked Sendable {}
extension Binding: @unchecked Sendable {}
extension UUID: @unchecked Sendable {}
| 24.888889
| 82
| 0.763393
|
2f2ae035540e8568cfc1932c30647488af821b41
| 540
|
js
|
JavaScript
|
node_modules/postcss-less/dist/tokenizer/tokenize-inline-comment.js
|
priyanka-ucreate/reactappnew
|
affc05d4c8b1cfac84d410213f24df81ce9d9493
|
[
"MIT"
] | 25
|
2017-12-12T14:02:54.000Z
|
2021-12-03T14:00:49.000Z
|
assets/manage/node_modules/postcss-less/dist/tokenizer/tokenize-inline-comment.js
|
nuridincs/bimbel_gama
|
be2d0d83d9579c52cda9649777552db9983e3d7b
|
[
"MIT"
] | 34
|
2020-09-28T07:24:42.000Z
|
2022-02-26T14:29:57.000Z
|
assets/manage/node_modules/postcss-less/dist/tokenizer/tokenize-inline-comment.js
|
nuridincs/bimbel_gama
|
be2d0d83d9579c52cda9649777552db9983e3d7b
|
[
"MIT"
] | 7
|
2018-02-11T22:47:02.000Z
|
2021-12-01T10:16:52.000Z
|
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = tokenizeInlineComment;
function tokenizeInlineComment(state) {
state.nextPos = state.css.indexOf('\n', state.pos + 2) - 1;
if (state.nextPos === -2) {
state.nextPos = state.css.length - 1;
}
state.tokens.push(['comment', state.css.slice(state.pos, state.nextPos + 1), state.line, state.pos - state.offset, state.line, state.nextPos - state.offset, 'inline']);
state.pos = state.nextPos;
}
module.exports = exports['default'];
| 30
| 170
| 0.690741
|
14db743c86bba1d1138692a8cda022947cc35637
| 2,410
|
ts
|
TypeScript
|
src/utils/template.ts
|
atEaE/resource-manager
|
f08a589cf1c8357aa2a45e11f611285d37c8f9e0
|
[
"MIT"
] | null | null | null |
src/utils/template.ts
|
atEaE/resource-manager
|
f08a589cf1c8357aa2a45e11f611285d37c8f9e0
|
[
"MIT"
] | null | null | null |
src/utils/template.ts
|
atEaE/resource-manager
|
f08a589cf1c8357aa2a45e11f611285d37c8f9e0
|
[
"MIT"
] | null | null | null |
'use strict';
import * as fs from 'fs';
import * as path from 'path';
/**
* WebviewPanel template engine
*/
export class TemplateEngine {
/**
* dummy template.
*/
public dummy: Template = new Template("dummy", notFoundTemplate);
/**
* Template folder to inspect.
*/
private templateFolder: string;
/**
* Template instances.
*/
private templates: Array<Template> = [];
/**
* Create new TemplateEngine instance.
* @param templateFolder Template folder to inspect.
*/
constructor (templateFolder: string) {
this.templateFolder = templateFolder;
}
/**
* Load .html templates from the specified template folder.
*/
public load(): TemplateEngine {
const files = fs.readdirSync(this.templateFolder).filter(fn => fn.endsWith('.html'));
files.forEach(fn => {
this.templates.push(new Template(fn, fs.readFileSync(path.join(this.templateFolder, fn), 'utf8')));
});
return this;
}
/**
* Gets file template with the specified name.
* @param name Template name.
*/
public find(name: string): Template | undefined {
return this.templates.find(t => t.name === name);
}
}
/**
* Template class for loading the contents of a template file.
*/
export class Template {
/**
* Template name.
*/
public name: string;
/**
* Template file content.
*/
private content: string;
/**
* Create new Template instance.
* @param name Template name.
* @param content Template file content.
*/
constructor(name: string, content: string) {
this.name = name;
this.content = content;
}
/**
* Binds template content params by replacing {} tokens with regex.
* @param bindParams Template key/value pair params.
*/
public bind(bindParams: any): string {
let cnts = this.content;
Object.keys(bindParams).map(bKey => {
cnts = cnts.replace(RegExp(`{${bKey}}`, 'g'), bindParams[bKey]);
});
return cnts;
}
}
/**
* notfound template.
*/
const notFoundTemplate = `<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Resource Manager</title>
</head>
<body>
<h1>Sorry. NotFound Template.</h1>
</body>
</html>`;
| 23.627451
| 111
| 0.59834
|
4141334d33b204c938235dd00a744687022a01c9
| 13,524
|
rs
|
Rust
|
ftp_server/src/main_commands.rs
|
pachev/pachev_ftp
|
84896281d0568a02ecb8d73f764d836506615331
|
[
"MIT"
] | 9
|
2017-03-11T21:48:46.000Z
|
2021-12-24T03:51:38.000Z
|
ftp_server/src/main_commands.rs
|
pachev/pachev_ftp
|
84896281d0568a02ecb8d73f764d836506615331
|
[
"MIT"
] | 3
|
2017-08-20T11:02:07.000Z
|
2021-04-14T12:03:39.000Z
|
ftp_server/src/main_commands.rs
|
pachev/pachev_ftp
|
84896281d0568a02ecb8d73f764d836506615331
|
[
"MIT"
] | 5
|
2017-08-19T17:19:23.000Z
|
2021-04-01T21:45:50.000Z
|
use rand::Rng;
use rand;
use std::fs::OpenOptions;
use std::io::BufReader;
use std::string::String;
use std::net::{TcpStream, TcpListener, Shutdown};
use std::path::Path;
use std::fs;
use std::fs::File;
use user::User;
use server::FtpMode;
use server;
/// # The FTP List command
/// This function implements the list command server side
///
/// # Arguements
///
/// - client
/// - user
/// - mode
/// - args
/// - data_port
/// - listener
pub fn list(client: &mut BufReader<TcpStream>,
user: &User,
mode: FtpMode,
args: &str,
data_port: &i32,
listener: &TcpListener) {
match mode {
FtpMode::Passive => {
info!("{} in passive mode requesting LIST command", user.name);
//getting a head start here in order to prvent slow connection
let (stream, _) = listener.accept().expect("Could not accept connection");
server::write_response(client,
&format!("{} Openning ASCII mode data for file list\r\n",
server::OPENNING_DATA_CONNECTION));
let mut data_stream = stream;
server::ftp_ls(&user, &mut data_stream, args);
server::write_response(client,
&format!("{} Transfer Complete\r\n",
server::CLOSING_DATA_CONNECTION));
data_stream.shutdown(Shutdown::Both).expect("Could not shutdownd data stram");
}
FtpMode::Active(addr) => {
info!("{} in passive mode requesting LIST command", user.name);
server::write_response(client,
&format!("{} Openning ASCII mode data for file list\r\n",
server::OPENNING_DATA_CONNECTION));
let mut stream = TcpStream::connect(addr).expect("Could not connect to addr");
server::ftp_ls(&user, &mut stream, args);
server::write_response(client,
&format!("{} Transfer Complete\r\n",
server::CLOSING_DATA_CONNECTION));
}
}
}
pub fn stor(mut client: &mut BufReader<TcpStream>,
user: &User,
mode: FtpMode,
args: &str,
listener: &TcpListener) {
match mode {
FtpMode::Passive => {
info!("{} in passive mode requesting STOR command", user.name);
let (stream, _) = listener.accept().expect("Could not accept connection");
let mut data_stream = stream;
stor_file(&mut client, user, &mut data_stream, args);
data_stream.shutdown(Shutdown::Both).expect("Could not shutdownd data stram");
}
FtpMode::Active(addr) => {
info!("{} in active mode requesting STOR command", user.name);
let mut data_stream = TcpStream::connect(addr).expect("Could not connect to addr");
stor_file(&mut client, user, &mut data_stream, args);
data_stream.shutdown(Shutdown::Both).expect("Could not shutdownd data stram");
}
}
}
pub fn retr(mut client: &mut BufReader<TcpStream>,
user: &User,
mode: FtpMode,
args: &str,
listener: &TcpListener) {
//getting a head start here in order to prvent slow connection
match mode {
FtpMode::Passive => {
info!("{} in passive mode requesting RETR command", user.name);
let (stream, _) = listener.accept().expect("Could not accept connection");
let mut data_stream = stream;
retr_file(&mut client, user, &mut data_stream, args);
data_stream.shutdown(Shutdown::Both).expect("Could not shutdownd data stram");
}
FtpMode::Active(addr) => {
info!("{} in active mode requesting RETR command", user.name);
let mut data_stream = TcpStream::connect(addr).expect("Could not connect to addr");
retr_file(&mut client, user, &mut data_stream, args);
data_stream.shutdown(Shutdown::Both).expect("Could not shutdownd data stram");
}
}
}
pub fn stou(mut client: &mut BufReader<TcpStream>,
user: &User,
mode: FtpMode,
args: &str,
listener: &TcpListener) {
//This is in case the file name is not unique
let mut rng = rand::thread_rng();
let full_path = format!("{}/{}", user.cur_dir, args);
let s = rng.gen_ascii_chars().take(8).collect::<String>();
let remote = Path::new(&full_path);
match mode {
FtpMode::Passive => {
info!("{} in passive mode requesting STOU command", user.name);
let (stream, _) = listener.accept().expect("Could not accept connection");
let mut data_stream = stream;
if remote.exists() {
stor_file(&mut client, user, &mut data_stream, &s);
} else {
stor_file(&mut client, user, &mut data_stream, args);
}
data_stream.shutdown(Shutdown::Both).expect("Could not shutdownd data stream");
}
FtpMode::Active(addr) => {
info!("{} in active mode requesting STOU command", user.name);
let mut data_stream = TcpStream::connect(addr).expect("Could not connect to addr");
if remote.exists() {
stor_file(&mut client, user, &mut data_stream, &s);
} else {
stor_file(&mut client, user, &mut data_stream, args);
}
data_stream.shutdown(Shutdown::Both).expect("Could not shutdownd data stream");
}
}
}
pub fn appe(client: &mut BufReader<TcpStream>,
user: &User,
mode: FtpMode,
args: &str,
listener: &TcpListener) {
match mode {
FtpMode::Passive => {
//Waits for clinet to connect to data port
let (stream, _) = listener.accept().expect("Could not accept connection");
let mut data_stream = stream;
let full_path = format!("{}/{}", user.cur_dir, args);
let remote = Path::new(&full_path);
if !remote.is_dir() {
let mut file = match OpenOptions::new().append(true).open(remote) {
Ok(file) => file,
Err(_) => {
let file = File::create(remote)
.expect("Could not create remote file for append");
file
}
};
server::write_to_file(&mut file, &mut data_stream);
//TODO: Add how long it took to transfer file
server::write_response(client,
&format!("{} Transfer Complete\r\n",
server::CLOSING_DATA_CONNECTION));
} else {
server::write_response(client,
&format!("{} No Such File or Dir\r\n", server::NO_ACCESS));
}
data_stream.shutdown(Shutdown::Both).expect("Could not shutdownd data stram");
}
FtpMode::Active(_) => {
println!("mode not yet implemented");
}
}
}
pub fn rnfr(mut client: &mut BufReader<TcpStream>, user: &User, args: &str) {
let full_path = format!("{}/{}", user.cur_dir, args);
let remote = Path::new(&full_path);
if remote.exists() {
server::write_response(client,
&format!("{} File or Directory Exists, Ready for Desitination\r\n",
server::ITEM_EXISTS));
//REFRACTOR: Consider adding a function that reads a message and parses cmd/args
let response = server::read_message(&mut client);
let line = response.trim();
let (cmd, new_name) = match line.find(' ') {
Some(pos) => (&line[0..pos], &line[pos + 1..]),
None => (line, "".as_ref()),
};
match cmd.to_lowercase().as_ref() {
"rnto" => {
let from_path = format!("{}/{}", user.cur_dir, args);
let to_path = format!("{}/{}", user.cur_dir, new_name);
let from = Path::new(&from_path);
let to = Path::new(&to_path);
println!("Curr {}\nTo: {}", from_path, to_path);
match fs::rename(from, to) {
Ok(_) => {
server::write_response(client,
&format!("{} Success Renaming\r\n",
server::CWD_CONFIRMED));
}
Err(_) => {
server::write_response(client,
&format!("{} Could Not Rename File\r\n",
server::BAD_SEQUENCE));
}
}
}
_ => {
server::write_response(client,
&format!("{} {} Bad Sequence of Commands \r\n",
server::BAD_SEQUENCE,
cmd));
}
}
} else {
server::write_response(client,
&format!("{} No Such File or Dir\r\n", server::NO_ACCESS));
}
}
pub fn dele(mut client: &mut BufReader<TcpStream>, user: &User, args: &str) {
let full_path = format!("{}/{}", user.cur_dir, args);
let remote = Path::new(&full_path);
info!("{} being deleted form serve", args);
if remote.exists() && !remote.is_dir() {
match fs::remove_file(remote) {
Ok(_) => {
server::write_response(client,
&format!("{} Success Deleting Filer\n",
server::OPERATION_SUCCESS));
}
Err(_) => {
server::write_response(client,
&format!("{} File could not be deleted\r\n",
server::NO_ACCESS));
}
}
} else {
server::write_response(client,
&format!("{} No Such File or Dir\r\n", server::NO_ACCESS));
}
}
pub fn rmd(mut client: &mut BufReader<TcpStream>, user: &User, args: &str) {
let full_path = format!("{}/{}", user.cur_dir, args);
let mut remote = Path::new(&full_path);
if remote.exists() && remote.is_dir() {
match fs::remove_dir(remote) {
Ok(_) => {
server::write_response(client,
&format!("{} Success Deleting Directory\r\n",
server::CWD_CONFIRMED));
}
Err(_) => {
server::write_response(client,
&format!("{} Directory is not empty\r\n",
server::NO_ACCESS));
}
}
} else {
server::write_response(client,
&format!("{} No Such File or Dir\r\n", server::NO_ACCESS));
}
}
fn stor_file(client: &mut BufReader<TcpStream>, user: &User, stream: &mut TcpStream, args: &str) {
server::write_response(client,
&format!("{} Opening binary mode to receive {}\r\n",
server::OPENNING_DATA_CONNECTION,
args));
let mut data_stream = stream;
let full_path = format!("{}/{}", user.cur_dir, args);
let remote = Path::new(&full_path);
if !remote.is_dir() {
let mut file = File::create(remote).expect("Could not create file to store");
server::write_to_file(&mut file, &mut data_stream);
//TODO: Add how long it took to transfer file
server::write_response(client,
&format!("{} Transfer Complete\r\n",
server::CLOSING_DATA_CONNECTION));
} else {
server::write_response(client,
&format!("{} No Such File or Dir\r\n", server::NO_ACCESS));
}
}
fn retr_file(client: &mut BufReader<TcpStream>, user: &User, stream: &mut TcpStream, args: &str) {
server::write_response(client,
&format!("{} Openning binary mode to transfer {}\r\n",
server::OPENNING_DATA_CONNECTION,
args));
let full_path = format!("{}/{}", user.cur_dir, args);
println!("{} requested file", full_path);
let mut data_stream = stream;
let local = Path::new(&full_path);
if !local.is_dir() && local.exists() {
let mut file = File::open(local).expect("Could not create file to store");
server::write_to_stream(&mut file, &mut data_stream);
server::write_response(client,
&format!("{} Transfer Complete\r\n",
server::CLOSING_DATA_CONNECTION));
} else {
server::write_response(client,
&format!("{} No Such File or Dir\r\n", server::NO_ACCESS));
}
}
| 33.066015
| 98
| 0.493641
|
1b5fb449a487eada2b96cce49becceaa5305bcb3
| 576
|
js
|
JavaScript
|
js/main.js
|
karma-git/example-web-services
|
c6e44ed394d3ea90ca8f91dbceb28bc49cce5068
|
[
"WTFPL"
] | null | null | null |
js/main.js
|
karma-git/example-web-services
|
c6e44ed394d3ea90ca8f91dbceb28bc49cce5068
|
[
"WTFPL"
] | null | null | null |
js/main.js
|
karma-git/example-web-services
|
c6e44ed394d3ea90ca8f91dbceb28bc49cce5068
|
[
"WTFPL"
] | null | null | null |
const { response } = require('express');
const express = require('express')
const app = express()
const port = portFromEnv()
var os = require("os");
var uuid = require('uuid');
var jsresponse = {
"language": "javascript",
"hostname": os.hostname(),
"timestamp": new Date(),
"uuid": uuid.v4()
}
function portFromEnv() {
if (process.env.PORT) {
return process.env.PORT
} else {
return 8082
}
}
app.get('/', (req, res) => {
res.send(jsresponse)
})
app.listen(port, () => {
console.log(`js app listening at 0.0.0.0:${port}`)
})
| 19.2
| 52
| 0.590278
|
031ab92b2a63340782ac149ba3fa22f6041b054a
| 4,571
|
rb
|
Ruby
|
spec/helpers/application_helper_spec.rb
|
BathHacked/school-power
|
94651767cae02cea40131eb76c990859447263f9
|
[
"MIT"
] | 10
|
2016-09-12T18:52:58.000Z
|
2020-05-21T12:23:45.000Z
|
spec/helpers/application_helper_spec.rb
|
BathHacked/energy-sparks
|
b7d9a6622be6abbe59a6542f93b0fc18e66b2ace
|
[
"MIT"
] | 233
|
2016-09-05T11:27:54.000Z
|
2020-03-04T00:02:11.000Z
|
spec/helpers/application_helper_spec.rb
|
BathHacked/school-power
|
94651767cae02cea40131eb76c990859447263f9
|
[
"MIT"
] | 2
|
2018-04-04T10:07:57.000Z
|
2019-08-05T20:58:03.000Z
|
require 'rails_helper'
describe ApplicationHelper do
describe '.up_downify' do
it 'adds an up arrow icon for positive starts' do
expect(helper.up_downify('+10%')).to include('<i')
expect(helper.up_downify('+10%')).to include('up')
end
it 'adds an up arrow icon for increased' do
expect(helper.up_downify('increased')).to include('<i')
expect(helper.up_downify('increased')).to include('up')
end
it 'adds a down arrow icon for negative starts' do
expect(helper.up_downify('-10%')).to include('<i')
expect(helper.up_downify('-10%')).to include('down')
end
it 'adds a down arrow icon for decreased' do
expect(helper.up_downify('decreased')).to include('<i')
expect(helper.up_downify('decreased')).to include('down')
end
it 'does not add other strings' do
expect(helper.up_downify('hello')).to_not include('<i')
expect(helper.up_downify('hello + goodbye')).to_not include('<i')
end
end
describe 'last signed in helper' do
it 'shows a message if a user has never signed in' do
expect(display_last_signed_in_as(build(:user))).to eq 'Never signed in'
end
it 'shows the last time as user signed in' do
last_sign_in_at = DateTime.new(2001,2,3,4,5,6)
expect(display_last_signed_in_as(build(:user, last_sign_in_at: last_sign_in_at))).to eq nice_date_times(last_sign_in_at)
end
end
describe 'other_field_name' do
it 'makes a name from wordy category title' do
expect(helper.other_field_name('Local authority')).to eq('OTHER_LA')
end
it 'makes a name from abbreviated category title' do
expect(helper.other_field_name('MAT')).to eq('OTHER_MAT')
end
end
describe 'human_counts' do
it 'shows 0 as once' do
expect(helper.human_counts([])).to eq('no times')
end
it 'shows 1 as once' do
expect(helper.human_counts([1])).to eq('once')
end
it 'shows 2 as twice' do
expect(helper.human_counts([1,2])).to eq('twice')
end
it 'shows more than 2 as several times' do
expect(helper.human_counts([1,2,3])).to eq('several times')
end
end
describe 'progress_as_percent' do
it 'formats as percent' do
expect(helper.progress_as_percent(10, 100)).to eq('10 %')
end
it 'to 0 dp' do
expect(helper.progress_as_percent(1, 3)).to eq('33 %')
end
it 'handles overachievment' do
expect(helper.progress_as_percent(110, 100)).to eq('100 %')
end
it 'handles non-numbers' do
expect(helper.progress_as_percent('foo', 'bar')).to eq(nil)
end
it 'handles divide by zero' do
expect(helper.progress_as_percent(10, 0)).to eq(nil)
end
end
describe 'add_or_remove' do
it 'adds item when empty' do
expect(helper.add_or_remove(nil, 'KS1')).to eq('KS1')
end
it 'adds item to list' do
expect(helper.add_or_remove('KS1,KS2', 'KS3')).to eq('KS1,KS2,KS3')
end
it 'handles whitespace' do
expect(helper.add_or_remove(' KS1 , KS2', 'KS3')).to eq('KS1,KS2,KS3')
end
it 'removes item from list' do
expect(helper.add_or_remove('KS1,KS2,KS3', 'KS2')).to eq('KS1,KS3')
end
end
describe 'activity_types_badge_class' do
it 'has the non-selected class' do
expect(helper.activity_types_badge_class('KS1, KS2', 'KS3', 'info')).to include('badge-light')
end
it 'has the selected class' do
expect(helper.activity_types_badge_class('KS1, KS2', 'KS1', 'info')).to include('badge-info')
end
end
describe '.file_type_icon' do
it 'renders a spreadsheet icon' do
expect(helper.file_type_icon('application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')).to include('<i')
expect(helper.file_type_icon('application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')).to include('file-excel')
end
it 'renders a doc icon' do
expect(helper.file_type_icon('application/vnd.openxmlformats-officedocument.wordprocessingml.document')).to include('<i')
expect(helper.file_type_icon('application/vnd.openxmlformats-officedocument.wordprocessingml.document')).to include('file-word')
end
it 'renders a download icon' do
expect(helper.file_type_icon('image/vnd.dwg')).to include('<i')
expect(helper.file_type_icon('image/vnd.dwg')).to include('file-download')
end
end
describe '.spinner_icon' do
it 'renders a spinner icon' do
expect(helper.spinner_icon).to include('<i')
expect(helper.spinner_icon).to include('fa-spinner fa-spin')
end
end
end
| 34.368421
| 134
| 0.673594
|
23e9a7c75317f97d13bb62b67c539752aabf29e5
| 630
|
js
|
JavaScript
|
packages/strapi-admin/admin/src/containers/Onboarding/constants.js
|
tonxxd/strapi
|
d623346637af28d9e3ec3c7a0bcde22fae4ca6f7
|
[
"MIT"
] | 1,256
|
2018-01-19T11:05:45.000Z
|
2022-03-28T21:37:15.000Z
|
packages/strapi-admin/admin/src/containers/Onboarding/constants.js
|
tonxxd/strapi
|
d623346637af28d9e3ec3c7a0bcde22fae4ca6f7
|
[
"MIT"
] | 138
|
2018-01-16T10:15:21.000Z
|
2022-03-24T22:31:31.000Z
|
packages/strapi-admin/admin/src/containers/Onboarding/constants.js
|
tonxxd/strapi
|
d623346637af28d9e3ec3c7a0bcde22fae4ca6f7
|
[
"MIT"
] | 834
|
2018-02-05T06:30:37.000Z
|
2022-03-30T14:30:31.000Z
|
/*
*
* Onboarding constants
*
*/
export const GET_VIDEOS = 'StrapiAdmin/Onboarding/GET_VIDEOS';
export const GET_VIDEOS_SUCCEEDED =
'StrapiAdmin/Onboarding/GET_VIDEOS_SUCCEEDED';
export const SHOULD_OPEN_MODAL = 'StrapiAdmin/Onboarding/SHOULD_OPEN_MODAL';
export const ON_CLICK = 'StrapiAdmin/Onboarding/ON_CLICK';
export const SET_VIDEOS_DURATION = 'StrapiAdmin/Onboarding/SET_VIDEOS_DURATION';
export const UPDATE_VIDEO_START_TIME = 'StrapiAdmin/Onboarding/UPDATE_VIDEO_START_TIME';
export const SET_VIDEO_END = 'StrapiAdmin/Onboarding/SET_VIDEO_END';
export const REMOVE_VIDEOS = 'StrapiAdmin/Onboarding/REMOVE_VIDEOS';
| 39.375
| 88
| 0.826984
|
3e8c4e4d211509ee967a56169e664589d237843e
| 511
|
html
|
HTML
|
src/solutions/common/templates/settings/app_user_admins.html
|
goubertbrent/oca-backend
|
b9f59cc02568aecb55d4b54aec05245790ea25fd
|
[
"Apache-2.0"
] | null | null | null |
src/solutions/common/templates/settings/app_user_admins.html
|
goubertbrent/oca-backend
|
b9f59cc02568aecb55d4b54aec05245790ea25fd
|
[
"Apache-2.0"
] | null | null | null |
src/solutions/common/templates/settings/app_user_admins.html
|
goubertbrent/oca-backend
|
b9f59cc02568aecb55d4b54aec05245790ea25fd
|
[
"Apache-2.0"
] | null | null | null |
{% raw %}
<h3>${T('Admins')}
<sup id="admins_count" class="badge">${admins.length}</sup>
<button id="add_admin" class="btn btn-success"><i class="fa fa-plus"></i></button>
</h3>
<table id="admins" class="table table-striped table-bordered">
<thead>
<tr>
<th>${ T('Email') }</th>
</tr>
</thead>
<tbody>
{{each(i, user_email) admins}}
<tr>
<td><b>${user_email}</b></td>
</tr>
{{/each}}
</tbody>
</table>
{% endraw %}
| 24.333333
| 86
| 0.489237
|
1389ca4cf309f395253aa4af68b78904bd9f7e22
| 986
|
sh
|
Shell
|
legacy/tools/build.sh
|
Tiamat-Tech/docker-nsolid
|
aa905a5ac81b70a41c24fd62b9eb545445f59c30
|
[
"MIT"
] | 64
|
2016-02-21T08:53:56.000Z
|
2022-02-02T21:52:30.000Z
|
legacy/tools/build.sh
|
Tiamat-Tech/docker-nsolid
|
aa905a5ac81b70a41c24fd62b9eb545445f59c30
|
[
"MIT"
] | 20
|
2016-02-15T21:07:50.000Z
|
2022-03-03T17:48:50.000Z
|
legacy/tools/build.sh
|
Tiamat-Tech/docker-nsolid
|
aa905a5ac81b70a41c24fd62b9eb545445f59c30
|
[
"MIT"
] | 25
|
2016-02-15T17:51:57.000Z
|
2022-02-02T21:52:34.000Z
|
#!/usr/bin/env bash
# Crash on error
set -e
# Get Working Directory
SOURCE="${BASH_SOURCE[0]}"
while [ -h "$SOURCE" ]; do # resolve $SOURCE until the file is no longer a symlink
DIR="$( cd -P "$( dirname "$SOURCE" )" && pwd )"
SOURCE="$(readlink "$SOURCE")"
[[ $SOURCE != /* ]] && SOURCE="$DIR/$SOURCE"
done
DIR="$( cd -P "$( dirname "$SOURCE" )" && pwd )"
# Create a directory to store the logs
LOGS="$DIR/../logs/$(date +'%Y_%m_%d_%H:%M')"
mkdir -p "$LOGS"
echo "Starting with a clean directory"
rm -rf $DIR/../{nsolid,nsolid-console,nsolid-hub}
echo "Generating image file..."
$DIR/gen-images.sh > $DIR/../templates/images.js
echo "Running npm install..."
cd $DIR
npm install
echo "Generating Dockerfiles..."
$DIR/gen-dockerfiles.js
echo "Building etcd-ports tests..."
cd $DIR/../tests/etcd-ports
make
cd $DIR
# Build images and push them to the registry
echo "Running dante..."
cd $DIR/../
dante test -r 2 > "$LOGS/output.md"
dante push -r 2 > "$LOGS/push.md"
cd $DIR
| 23.47619
| 82
| 0.646045
|
84e3940a3afb8052da1f3d6484d2fbf1a1d48815
| 331
|
cs
|
C#
|
Olympic.RazorConverter/WebForms/Filters/IWebFormsNodeFilter.cs
|
olympicsoftware/razor-converter
|
842c82a51d79f1ee6ec69f3a3a1845125f8dc40b
|
[
"MIT"
] | null | null | null |
Olympic.RazorConverter/WebForms/Filters/IWebFormsNodeFilter.cs
|
olympicsoftware/razor-converter
|
842c82a51d79f1ee6ec69f3a3a1845125f8dc40b
|
[
"MIT"
] | null | null | null |
Olympic.RazorConverter/WebForms/Filters/IWebFormsNodeFilter.cs
|
olympicsoftware/razor-converter
|
842c82a51d79f1ee6ec69f3a3a1845125f8dc40b
|
[
"MIT"
] | null | null | null |
using Olympic.RazorConverter.WebForms.DOM;
namespace Olympic.RazorConverter.WebForms.Filters
{
using System.Collections.Generic;
using Olympic.RazorConverter.WebForms.DOM;
public interface IWebFormsNodeFilter
{
IList<IWebFormsNode> Filter(IWebFormsNode node, IWebFormsNode previousFilteredNode);
}
}
| 25.461538
| 92
| 0.773414
|
624f7157070d817f7042f78f05250a7231218d19
| 1,174
|
dart
|
Dart
|
packages/flame/test/image_composition_test.dart
|
Sproute777/flame
|
2058b05b3e88b6d055f066245225a810ac34d9a0
|
[
"MIT"
] | 3
|
2022-02-01T07:37:37.000Z
|
2022-02-02T11:37:13.000Z
|
packages/flame/test/image_composition_test.dart
|
Sproute777/flame
|
2058b05b3e88b6d055f066245225a810ac34d9a0
|
[
"MIT"
] | null | null | null |
packages/flame/test/image_composition_test.dart
|
Sproute777/flame
|
2058b05b3e88b6d055f066245225a810ac34d9a0
|
[
"MIT"
] | null | null | null |
import 'package:flame/image_composition.dart';
import 'package:mocktail/mocktail.dart';
import 'package:test/test.dart';
class MockImage extends Mock implements Image {}
void main() {
group('ImageComposition', () {
group('add', () {
test('breaks assertion when adding an invalid portion', () {
final image = MockImage();
final composition = ImageComposition();
when(() => image.width).thenReturn(100);
when(() => image.height).thenReturn(100);
final invalidRects = [
const Rect.fromLTWH(-10, 10, 10, 10),
const Rect.fromLTWH(10, -10, 10, 10),
const Rect.fromLTWH(110, 10, 10, 10),
const Rect.fromLTWH(0, 110, 10, 10),
const Rect.fromLTWH(0, 0, 110, 110),
const Rect.fromLTWH(20, 0, 90, 10),
const Rect.fromLTWH(0, 20, 90, 90),
const Rect.fromLTWH(0, 0, 190, 90),
const Rect.fromLTWH(0, 0, 90, 190),
];
invalidRects.forEach((r) {
expect(
() => composition.add(image, Vector2.zero(), source: r),
throwsA(isA<AssertionError>()),
);
});
});
});
});
}
| 30.102564
| 68
| 0.554514
|
141c318d6f158af04905368692b49a091bd7f03a
| 153
|
ts
|
TypeScript
|
lib/api/Cart/utils.d.ts
|
cruushmedia/wholesale-sdk
|
0896c71107f28afff09c90d60618b5aca3b081c6
|
[
"BSD-3-Clause"
] | null | null | null |
lib/api/Cart/utils.d.ts
|
cruushmedia/wholesale-sdk
|
0896c71107f28afff09c90d60618b5aca3b081c6
|
[
"BSD-3-Clause"
] | null | null | null |
lib/api/Cart/utils.d.ts
|
cruushmedia/wholesale-sdk
|
0896c71107f28afff09c90d60618b5aca3b081c6
|
[
"BSD-3-Clause"
] | 1
|
2021-02-03T09:33:31.000Z
|
2021-02-03T09:33:31.000Z
|
import { ICheckoutModelLine } from "../../helpers";
export declare function sortCheckoutLines(a: ICheckoutModelLine, b: ICheckoutModelLine): 1 | -1 | 0;
| 51
| 100
| 0.745098
|
4479068e6993ffaee57841db8ee112460f7809d1
| 1,773
|
py
|
Python
|
src/blockchain/block.py
|
slawiko/blockchain_practice
|
24a06d59cc2e0d9674edcaba5ea8c358f3feedd7
|
[
"Apache-2.0"
] | null | null | null |
src/blockchain/block.py
|
slawiko/blockchain_practice
|
24a06d59cc2e0d9674edcaba5ea8c358f3feedd7
|
[
"Apache-2.0"
] | 1
|
2019-10-21T16:28:08.000Z
|
2019-10-21T16:28:08.000Z
|
src/blockchain/block.py
|
slawiko/digital_image
|
24a06d59cc2e0d9674edcaba5ea8c358f3feedd7
|
[
"Apache-2.0"
] | null | null | null |
import hashlib
import logging
from blockchain.transaction import Transaction
complexity = 5
log = logging.getLogger(__name__)
class Block:
def __init__(self, previous_hash, transactions, nonce=None, block_hash=None):
self.previousHash = previous_hash
# TODO: merkle tree?
self.transactions = transactions
self.nonce = nonce or 0
self.hash = block_hash or self.calculate_hash()
def calculate_hash(self):
# TODO: merkle tree root?
data = f"{self.previousHash}\n{','.join(self.transactions.keys())}\n"
prefix = '0' * complexity
with_nonce = f'{data}{self.nonce}'.encode('utf-8')
digest = hashlib.sha256(with_nonce).hexdigest()
while digest[:complexity] != prefix:
self.nonce += 1
with_nonce = f'{data}{self.nonce}'.encode('utf-8')
digest = hashlib.sha256(with_nonce).hexdigest()
log.info('Hash found!')
return digest
def sign(self, private):
return private.sign(self.digest)
@property
def digest(self):
h = self.__hash()
return h.digest()
def hexdigest(self):
return self.__hash().hexdigest()
def __hash(self):
data = f"{self.previousHash}\n{','.join(self.transactions.keys())}\n{self.nonce}".encode('utf-8')
return hashlib.sha256(data)
@staticmethod
def dumps(block):
return {
"transactions": list(map(Transaction.dumps, block.transactions.values())),
"previousHash": block.previousHash,
"nonce": block.nonce,
"hash": block.hash
}
@staticmethod
def genesis():
return Block('', {}, 523782, '000004c41d6eccd35e6bb5f8220cc8f22d68d911af276a060d80fbaf6c647df6')
| 29.065574
| 105
| 0.619853
|
dd57e0396681097fd8616941d0cb254390e4a6b1
| 10,263
|
java
|
Java
|
fulltext/src/main/java/com/github/vantonov1/basalt/fulltext/impl/LuceneDAO.java
|
vantonov1/basalt
|
073bf145c4406425e3fe8278c03d02949708211d
|
[
"Apache-2.0"
] | null | null | null |
fulltext/src/main/java/com/github/vantonov1/basalt/fulltext/impl/LuceneDAO.java
|
vantonov1/basalt
|
073bf145c4406425e3fe8278c03d02949708211d
|
[
"Apache-2.0"
] | null | null | null |
fulltext/src/main/java/com/github/vantonov1/basalt/fulltext/impl/LuceneDAO.java
|
vantonov1/basalt
|
073bf145c4406425e3fe8278c03d02949708211d
|
[
"Apache-2.0"
] | null | null | null |
package com.github.vantonov1.basalt.fulltext.impl;
import com.github.vantonov1.basalt.repo.Pair;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.StringField;
import org.apache.lucene.document.TextField;
import org.apache.lucene.index.CheckIndex;
import org.apache.lucene.index.IndexNotFoundException;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.index.Term;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.SearcherManager;
import org.apache.lucene.search.TermQuery;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.security.InvalidParameterException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Timer;
import java.util.TimerTask;
public class LuceneDAO extends AbstractLuceneDAO {
private final Timer timer = new Timer("update lucene indexes");
private final Log logger = LogFactory.getLog(getClass());
protected Directory directory;
private String luceneRoot;
private IndexWriter writer;
private SearcherManager searcherManager;
@PostConstruct
private void postConstruct() {
timer.schedule(new TimerTask() {
@Override
public void run() {
flush();
}
}, 10000, 10000);
}
@PreDestroy
private void preDestroy() {
timer.cancel();
try {
searcherManager.close();
} catch (IOException e) {
logger.error("while closing Lucene search manager", e);
}
try {
writer.close();
} catch (IOException e) {
logger.error("while closing Lucene writer", e);
}
try {
directory.close();
} catch (IOException e) {
logger.error("while closing Lucene directory", e);
}
}
public void setLuceneRoot(String luceneRoot) {
this.luceneRoot = luceneRoot;
}
@Override
public List<String> search(List<String> mustHave, List<String> shouldHave, int limit) {
try {
final SearcherManager manager = getIndexSearcher();
final IndexSearcher searcher = manager.acquire();
try {
final TopDocs docs = searcher.search(new LuceneQueryBuilder(getAnalyzer(), getTokenized()).build(mustHave, shouldHave), limit > 0 ? limit : 100000);
if (docs != null && docs.totalHits > 0) {
final List<String> result = new ArrayList<>((int) docs.totalHits);
for (ScoreDoc d : docs.scoreDocs) {
final String id = searcher.doc(d.doc).get("id");
assert id != null;
result.add(id);
}
return result;
}
} catch (IndexNotFoundException e) {
logger.error("search on empty index", e);
} finally {
manager.release(searcher);
}
return Collections.emptyList();
} catch (IOException e) {
throw new RuntimeException("while searching lucene index", e);
}
}
public boolean check() {
try {
final Path path = getLuceneDir();
if (path.toFile().exists()) {
try (FSDirectory result = FSDirectory.open(path); CheckIndex checker = new CheckIndex(result)) {
checker.setChecksumsOnly(true);
final CheckIndex.Status status = checker.checkIndex();
return status.clean;
}
} else {
return false;
}
} catch (IOException e) {
return false;
}
}
public boolean clean() {
final Path path = getLuceneDir();
if (path.toFile().exists()) {
for (Path f : path) {
if (!f.toFile().delete()) {
return false;
}
}
}
return true;
}
public void create(String id, List<Pair<String, String>> values) {
if (!values.isEmpty()) {
final Document doc = createLuceneDoc(id, values);
try {
getIndexWriter().addDocument(doc);
} catch (IOException e) {
throw new RuntimeException("while creating lucene index", e);
}
}
}
public void create(Map<String, List<Pair<String, String>>> values) {
final Collection<Document> documents = new ArrayList<>();
for (Map.Entry<String, List<Pair<String, String>>> entry : values.entrySet()) {
documents.add(createLuceneDoc(entry.getKey(), entry.getValue()));
}
try {
getIndexWriter().addDocuments(documents);
} catch (IOException e) {
throw new RuntimeException("while creating lucene index", e);
}
}
public void updateFields(String id, List<Pair<String, String>> values) {
if (!values.isEmpty()) {
try {
final Term docTerm = new Term("id", id);
Document doc = getLuceneDoc(docTerm);
if (doc == null) {
flush();
doc = getLuceneDoc(docTerm);
}
if (doc != null) {
assert Objects.equals(doc.get("id"), id);
doc.removeField(id);
doc.add(new StringField("id", id, Field.Store.YES));
for (Pair<String, String> entry : values) {
final String name = entry.getFirst();
doc.removeField(name);
if (entry.getSecond() != null) {
doc.add(new TextField(name, entry.getSecond(), Field.Store.YES));
}
}
getIndexWriter().updateDocument(docTerm, doc);
} else {
create(id, values);
}
} catch (IOException e) {
throw new RuntimeException("while updating lucene index", e);
}
}
}
public void updateFields(Map<String, List<Pair<String, String>>> values) {
if (!values.isEmpty()) {
try {
getIndexWriter().deleteDocuments(values.keySet().stream().map(id -> new Term("id", id)).toArray(Term[]::new));
create(values);
} catch (IOException e) {
throw new RuntimeException("while updating lucene index", e);
}
}
}
public void remove(String id) {
try {
getIndexWriter().deleteDocuments(new Term("id", id));
} catch (IOException e) {
throw new RuntimeException("while deleting lucene index", e);
}
}
public void flush() {
try {
if (writer != null && writer.hasUncommittedChanges()) {
writer.commit();
}
} catch (IOException e) {
logger.error("while committing", e);
}
try {
if (searcherManager != null) {
searcherManager.maybeRefresh();
}
} catch (IOException e) {
logger.error("while updating searchers", e);
}
}
private static Document createLuceneDoc(String id, List<Pair<String, String>> props) {
final Document doc = new Document();
doc.add(new StringField("id", id, Field.Store.YES));
for (Pair<String, String> nameAndValue : props) {
if (nameAndValue.getSecond() != null) {
doc.add(new TextField(nameAndValue.getFirst(), nameAndValue.getSecond(), Field.Store.YES));
}
}
return doc;
}
private Document getLuceneDoc(Term docTerm) throws IOException {
final SearcherManager manager = getIndexSearcher();
final IndexSearcher searcher = manager.acquire();
try {
final TopDocs topdocs = searcher.search(new TermQuery(docTerm), 1);
return topdocs != null && topdocs.scoreDocs.length > 0 ? searcher.doc(topdocs.scoreDocs[0].doc) : null;
} finally {
manager.release(searcher);
}
}
private synchronized SearcherManager getIndexSearcher() throws IOException {
if (searcherManager == null) {
searcherManager = new SearcherManager(getIndexWriter(), false, false, null);
}
return searcherManager;
}
private synchronized IndexWriter getIndexWriter() throws IOException {
if (writer == null || !writer.isOpen()) {
if (writer != null) {
try {
writer.close();
} catch (Exception ignored) {
}
}
final IndexWriterConfig iwc = new IndexWriterConfig(getAnalyzer());
iwc.setOpenMode(IndexWriterConfig.OpenMode.CREATE_OR_APPEND);
writer = new IndexWriter(getDirectory(), iwc);
}
return writer;
}
protected Directory getDirectory() {
if (directory == null) {
try {
final Path path = getLuceneDir();
Files.createDirectories(path);
directory = FSDirectory.open(path);
} catch (IOException e) {
throw new RuntimeException("unable to init Lucene directory", e);
}
}
return directory;
}
private Path getLuceneDir() {
if (luceneRoot == null) {
throw new InvalidParameterException("lucene root not set");
}
return Paths.get(luceneRoot);
}
}
| 34.789831
| 164
| 0.561921
|
cd33d0b2d5d2712d7fe839aefe7b1eb4f385e83d
| 757
|
cs
|
C#
|
src/ImageSharp.Web/DependencyInjection/ImageSharpConfiguration.cs
|
brhinescot/ImageSharp.Web
|
408801ae831f8134bbf75220f643e827dc82cb1c
|
[
"Apache-2.0"
] | 2
|
2021-05-02T11:17:20.000Z
|
2022-03-28T05:34:52.000Z
|
src/ImageSharp.Web/DependencyInjection/ImageSharpConfiguration.cs
|
brhinescot/ImageSharp.Web
|
408801ae831f8134bbf75220f643e827dc82cb1c
|
[
"Apache-2.0"
] | null | null | null |
src/ImageSharp.Web/DependencyInjection/ImageSharpConfiguration.cs
|
brhinescot/ImageSharp.Web
|
408801ae831f8134bbf75220f643e827dc82cb1c
|
[
"Apache-2.0"
] | null | null | null |
// Copyright (c) Six Labors and contributors.
// Licensed under the Apache License, Version 2.0.
using Microsoft.Extensions.Options;
using SixLabors.ImageSharp.Web.Middleware;
namespace SixLabors.ImageSharp.Web.DependencyInjection
{
/// <summary>
/// Provides default configuration settings to be consumed by the middleware
/// </summary>
public class ImageSharpConfiguration : IConfigureOptions<ImageSharpMiddlewareOptions>
{
/// <inheritdoc/>
public void Configure(ImageSharpMiddlewareOptions options)
{
options.Configuration = Configuration.Default;
options.MaxCacheDays = 365;
options.MaxBrowserCacheDays = 7;
options.CachedNameLength = 12;
}
}
}
| 32.913043
| 89
| 0.689564
|
1a65484f58829b95d4722537a9c9406a1d7b7751
| 1,313
|
cs
|
C#
|
ConvNetSharp/ConvNetSharp.Flow/Ops/Log.cs
|
NSqda/XCoinTrader
|
5f985e7ec4a4fac489032b500ef56c24b487bf1e
|
[
"MIT"
] | 460
|
2015-06-23T03:14:20.000Z
|
2022-03-29T10:55:42.000Z
|
ConvNetSharp/ConvNetSharp.Flow/Ops/Log.cs
|
NSqda/XCoinTrader
|
5f985e7ec4a4fac489032b500ef56c24b487bf1e
|
[
"MIT"
] | 109
|
2015-06-03T03:05:47.000Z
|
2020-12-07T05:26:46.000Z
|
ConvNetSharp/ConvNetSharp.Flow/Ops/Log.cs
|
NSqda/XCoinTrader
|
5f985e7ec4a4fac489032b500ef56c24b487bf1e
|
[
"MIT"
] | 142
|
2016-02-04T09:47:41.000Z
|
2021-10-09T10:26:26.000Z
|
using System;
using System.Collections.Generic;
using ConvNetSharp.Volume;
namespace ConvNetSharp.Flow.Ops
{
public class Log<T> : Op<T> where T : struct, IEquatable<T>, IFormattable
{
public Log(ConvNetSharp<T> graph, Dictionary<string, object> data) : base(graph)
{
}
public Log(ConvNetSharp<T> graph, Op<T> x) : base(graph)
{
this.AddParent(x);
}
public override string Representation => "Log";
public override void Differentiate()
{
this.Parents[0].RegisterDerivate(this.Derivate / this.Parents[0]);
}
public override Volume<T> Evaluate(Session<T> session)
{
if (!this.IsDirty)
{
return base.Evaluate(session);
}
this.IsDirty = false;
var x = this.Parents[0].Evaluate(session);
if (this.Result == null || !Equals(this.Result.Shape, x.Shape))
{
this.Result?.Dispose();
this.Result = BuilderInstance<T>.Volume.SameAs(x.Shape);
}
x.Log(this.Result);
return base.Evaluate(session);
}
public override string ToString()
{
return $"Log({this.Parents[0]})";
}
}
}
| 25.745098
| 88
| 0.533892
|
f8d0bda961d02d2374d131296a662f2e1335f74b
| 437
|
kt
|
Kotlin
|
src/jvmMain/kotlin/choliver/nespot/ui/Event.kt
|
oliver-charlesworth/nespot
|
e5d251b82e11f2986e8a732d55298c2ab0de3191
|
[
"MIT"
] | 1
|
2020-05-29T15:15:19.000Z
|
2020-05-29T15:15:19.000Z
|
src/jvmMain/kotlin/choliver/nespot/ui/Event.kt
|
oliver-charlesworth/nespot
|
e5d251b82e11f2986e8a732d55298c2ab0de3191
|
[
"MIT"
] | 48
|
2020-05-01T15:52:36.000Z
|
2020-06-07T19:59:25.000Z
|
src/jvmMain/kotlin/choliver/nespot/ui/Event.kt
|
oliver-charlesworth/nespot
|
e5d251b82e11f2986e8a732d55298c2ab0de3191
|
[
"MIT"
] | null | null | null |
package choliver.nespot.ui
import choliver.nespot.nes.Joypads
import javafx.scene.input.KeyCode
sealed class Event {
data class ControllerButtonDown(val button: Joypads.Button) : Event()
data class ControllerButtonUp(val button: Joypads.Button) : Event()
data class KeyDown(val code: KeyCode) : Event()
data class KeyUp(val code: KeyCode) : Event()
object Close : Event()
data class Error(val cause: Exception) : Event()
}
| 31.214286
| 71
| 0.750572
|
1a903c418b08f0b81067deae6cd963f7d8db215a
| 299
|
py
|
Python
|
python/search/largest_continuous_sum.py
|
amitsaha/playground
|
82cb5ac02ac90d3fa858a5153b0a5705187c14ce
|
[
"Unlicense"
] | 4
|
2018-04-14T16:28:39.000Z
|
2021-11-14T12:08:02.000Z
|
python/search/largest_continuous_sum.py
|
amitsaha/playground
|
82cb5ac02ac90d3fa858a5153b0a5705187c14ce
|
[
"Unlicense"
] | 3
|
2022-02-14T10:38:51.000Z
|
2022-02-27T16:01:16.000Z
|
python/search/largest_continuous_sum.py
|
amitsaha/playground
|
82cb5ac02ac90d3fa858a5153b0a5705187c14ce
|
[
"Unlicense"
] | 4
|
2015-07-07T01:01:27.000Z
|
2019-04-12T05:38:26.000Z
|
'''
Find the largest continuous sum
'''
def largest_cont_sum(arr):
if len(arr) == 0:
return 0
cur_sum = arr[0]
max_sum = arr[0]
for item in arr[1:]:
cur_sum = max(cur_sum+item, item)
if cur_sum >= max_sum:
max_sum = cur_sum
return max_sum
| 18.6875
| 41
| 0.561873
|
b03992e2193f2551da86bfb640cba3cd09cb558b
| 4,095
|
py
|
Python
|
sdk/python/pulumi_aws/s3/__init__.py
|
sibuthomasmathew/pulumi-aws
|
6351f2182eb6f693d4e09e4136c385adfa0ab674
|
[
"ECL-2.0",
"Apache-2.0"
] | null | null | null |
sdk/python/pulumi_aws/s3/__init__.py
|
sibuthomasmathew/pulumi-aws
|
6351f2182eb6f693d4e09e4136c385adfa0ab674
|
[
"ECL-2.0",
"Apache-2.0"
] | null | null | null |
sdk/python/pulumi_aws/s3/__init__.py
|
sibuthomasmathew/pulumi-aws
|
6351f2182eb6f693d4e09e4136c385adfa0ab674
|
[
"ECL-2.0",
"Apache-2.0"
] | null | null | null |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
# Export this package's modules as members:
from ._enums import *
from .access_point import *
from .account_public_access_block import *
from .analytics_configuration import *
from .bucket import *
from .bucket_metric import *
from .bucket_notification import *
from .bucket_object import *
from .bucket_ownership_controls import *
from .bucket_policy import *
from .bucket_public_access_block import *
from .get_bucket import *
from .get_bucket_object import *
from .get_bucket_objects import *
from .get_canonical_user_id import *
from .inventory import *
from .object_copy import *
from ._inputs import *
from . import outputs
def _register_module():
import pulumi
from .. import _utilities
class Module(pulumi.runtime.ResourceModule):
_version = _utilities.get_semver_version()
def version(self):
return Module._version
def construct(self, name: str, typ: str, urn: str) -> pulumi.Resource:
if typ == "aws:s3/accessPoint:AccessPoint":
return AccessPoint(name, pulumi.ResourceOptions(urn=urn))
elif typ == "aws:s3/accountPublicAccessBlock:AccountPublicAccessBlock":
return AccountPublicAccessBlock(name, pulumi.ResourceOptions(urn=urn))
elif typ == "aws:s3/analyticsConfiguration:AnalyticsConfiguration":
return AnalyticsConfiguration(name, pulumi.ResourceOptions(urn=urn))
elif typ == "aws:s3/bucket:Bucket":
return Bucket(name, pulumi.ResourceOptions(urn=urn))
elif typ == "aws:s3/bucketMetric:BucketMetric":
return BucketMetric(name, pulumi.ResourceOptions(urn=urn))
elif typ == "aws:s3/bucketNotification:BucketNotification":
return BucketNotification(name, pulumi.ResourceOptions(urn=urn))
elif typ == "aws:s3/bucketObject:BucketObject":
return BucketObject(name, pulumi.ResourceOptions(urn=urn))
elif typ == "aws:s3/bucketOwnershipControls:BucketOwnershipControls":
return BucketOwnershipControls(name, pulumi.ResourceOptions(urn=urn))
elif typ == "aws:s3/bucketPolicy:BucketPolicy":
return BucketPolicy(name, pulumi.ResourceOptions(urn=urn))
elif typ == "aws:s3/bucketPublicAccessBlock:BucketPublicAccessBlock":
return BucketPublicAccessBlock(name, pulumi.ResourceOptions(urn=urn))
elif typ == "aws:s3/inventory:Inventory":
return Inventory(name, pulumi.ResourceOptions(urn=urn))
elif typ == "aws:s3/objectCopy:ObjectCopy":
return ObjectCopy(name, pulumi.ResourceOptions(urn=urn))
else:
raise Exception(f"unknown resource type {typ}")
_module_instance = Module()
pulumi.runtime.register_resource_module("aws", "s3/accessPoint", _module_instance)
pulumi.runtime.register_resource_module("aws", "s3/accountPublicAccessBlock", _module_instance)
pulumi.runtime.register_resource_module("aws", "s3/analyticsConfiguration", _module_instance)
pulumi.runtime.register_resource_module("aws", "s3/bucket", _module_instance)
pulumi.runtime.register_resource_module("aws", "s3/bucketMetric", _module_instance)
pulumi.runtime.register_resource_module("aws", "s3/bucketNotification", _module_instance)
pulumi.runtime.register_resource_module("aws", "s3/bucketObject", _module_instance)
pulumi.runtime.register_resource_module("aws", "s3/bucketOwnershipControls", _module_instance)
pulumi.runtime.register_resource_module("aws", "s3/bucketPolicy", _module_instance)
pulumi.runtime.register_resource_module("aws", "s3/bucketPublicAccessBlock", _module_instance)
pulumi.runtime.register_resource_module("aws", "s3/inventory", _module_instance)
pulumi.runtime.register_resource_module("aws", "s3/objectCopy", _module_instance)
_register_module()
| 50.555556
| 99
| 0.715751
|
689722b91bfbe2bde8988d5e5478c2fdaa68ec38
| 253
|
php
|
PHP
|
app/Models/Api/Mahasiswa.php
|
viky1sr/api-laravel-flluter
|
31c7e0f56628268a8171a269b8fe33168be892c6
|
[
"MIT"
] | null | null | null |
app/Models/Api/Mahasiswa.php
|
viky1sr/api-laravel-flluter
|
31c7e0f56628268a8171a269b8fe33168be892c6
|
[
"MIT"
] | 5
|
2021-02-02T20:15:16.000Z
|
2022-02-27T07:30:22.000Z
|
app/Models/Api/Mahasiswa.php
|
viky1sr/api-laravel-flluter
|
31c7e0f56628268a8171a269b8fe33168be892c6
|
[
"MIT"
] | null | null | null |
<?php
namespace App\Models\Api;
use Illuminate\Database\Eloquent\Model;
class Mahasiswa extends Model
{
protected $table = 'mahasiswas';
protected $fillable = ['name','nim','no_tlpn','jenis_kelamin','tgl_lahir','jurusan','alamat','agama'];
}
| 21.083333
| 106
| 0.70751
|
93eb53a47eeb85eeec95eb29f51d780ce570dfc2
| 545
|
cs
|
C#
|
Source/Clarity.Engine/Media/Models/Flexible/IFlexibleModelVertexSet.cs
|
Zulkir/ClarityWorlds
|
2cbc91a2dfdee495428963de397e0eeca6661e7a
|
[
"MIT"
] | 1
|
2020-05-01T15:41:47.000Z
|
2020-05-01T15:41:47.000Z
|
Source/Clarity.Engine/Media/Models/Flexible/IFlexibleModelVertexSet.cs
|
Zulkir/ClarityWorlds
|
2cbc91a2dfdee495428963de397e0eeca6661e7a
|
[
"MIT"
] | null | null | null |
Source/Clarity.Engine/Media/Models/Flexible/IFlexibleModelVertexSet.cs
|
Zulkir/ClarityWorlds
|
2cbc91a2dfdee495428963de397e0eeca6661e7a
|
[
"MIT"
] | null | null | null |
using System.Collections.Generic;
using Clarity.Common.GraphicalGeometry;
using Clarity.Engine.Resources;
using Clarity.Engine.Resources.RawData;
using JetBrains.Annotations;
namespace Clarity.Engine.Media.Models.Flexible
{
public interface IFlexibleModelVertexSet : IResource
{
[NotNull]
IReadOnlyList<RawDataResSubrange> ArraySubranges { get; }
[NotNull, ItemNotNull]
IReadOnlyList<IVertexElementInfo> ElementInfos { get; }
[CanBeNull]
IVertexIndicesInfo IndicesInfo { get; }
}
}
| 27.25
| 65
| 0.730275
|
c28a8a511875a51a3bac1914f8ec39007e4e4311
| 10,304
|
c
|
C
|
target/linux/ar71xx/files/arch/mips/ath79/mach-nbg6716.c
|
opensag/microsemi-openwrt
|
f2e0e0e90801bb7cd87d1b82872cd9942c6e8df6
|
[
"Apache-2.0"
] | 1,144
|
2018-12-18T09:46:47.000Z
|
2022-03-07T14:51:46.000Z
|
target/linux/ar71xx/files/arch/mips/ath79/mach-nbg6716.c
|
opensag/microsemi-openwrt
|
f2e0e0e90801bb7cd87d1b82872cd9942c6e8df6
|
[
"Apache-2.0"
] | 16
|
2019-01-28T06:08:40.000Z
|
2019-12-04T10:26:41.000Z
|
target/linux/ar71xx/files/arch/mips/ath79/mach-nbg6716.c
|
opensag/microsemi-openwrt
|
f2e0e0e90801bb7cd87d1b82872cd9942c6e8df6
|
[
"Apache-2.0"
] | 129
|
2018-12-18T09:46:50.000Z
|
2022-03-30T07:30:13.000Z
|
/*
* ZyXEL NBG6716/NBG6616 board support
*
* Based on the Qualcomm Atheros AP135/AP136 reference board support code
* Copyright (c) 2012 Qualcomm Atheros
* Copyright (c) 2012-2013 Gabor Juhos <juhosg@openwrt.org>
* Copyright (c) 2013 Andre Valentin <avalentin@marcant.net>
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*
*/
#include <linux/platform_device.h>
#include <linux/ar8216_platform.h>
#include <linux/gpio.h>
#include <linux/mtd/mtd.h>
#include <linux/mtd/nand.h>
#include <linux/platform/ar934x_nfc.h>
#include <asm/mach-ath79/ar71xx_regs.h>
#include "common.h"
#include "pci.h"
#include "dev-ap9x-pci.h"
#include "dev-gpio-buttons.h"
#include "dev-eth.h"
#include "dev-leds-gpio.h"
#include "dev-nfc.h"
#include "dev-m25p80.h"
#include "dev-usb.h"
#include "dev-wmac.h"
#include "machtypes.h"
#include "nvram.h"
#define NBG6716_GPIO_LED_INTERNET 18
#define NBG6716_GPIO_LED_POWER 15
#define NBG6716_GPIO_LED_USB1 4
#define NBG6716_GPIO_LED_USB2 13
#define NBG6716_GPIO_LED_WIFI2G 19
#define NBG6716_GPIO_LED_WIFI5G 17
#define NBG6716_GPIO_LED_WPS 21
#define NBG6716_GPIO_BTN_RESET 23
#define NBG6716_GPIO_BTN_RFKILL 1
#define NBG6716_GPIO_BTN_USB1 0
#define NBG6716_GPIO_BTN_USB2 14
#define NBG6716_GPIO_BTN_WPS 22
#define NBG6716_GPIO_USB_POWER 16
#define NBG6716_KEYS_POLL_INTERVAL 20 /* msecs */
#define NBG6716_KEYS_DEBOUNCE_INTERVAL (3 * NBG6716_KEYS_POLL_INTERVAL)
#define NBG6716_MAC0_OFFSET 0
#define NBG6716_MAC1_OFFSET 6
#define NBG6716_WMAC_CALDATA_OFFSET 0x1000
#define NBG6716_PCIE_CALDATA_OFFSET 0x5000
/* NBG6616 has a different GPIO usage as it does not have USB Buttons */
#define NBG6616_GPIO_LED_USB0 14
#define NBG6616_GPIO_LED_USB1 21
#define NBG6616_GPIO_LED_WPS 0
static struct gpio_led nbg6716_leds_gpio[] __initdata = {
{
.name = "nbg6716:white:internet",
.gpio = NBG6716_GPIO_LED_INTERNET,
.active_low = 1,
},
{
.name = "nbg6716:white:power",
.gpio = NBG6716_GPIO_LED_POWER,
.active_low = 1,
},
{
.name = "nbg6716:white:usb1",
.gpio = NBG6716_GPIO_LED_USB1,
.active_low = 1,
},
{
.name = "nbg6716:white:usb2",
.gpio = NBG6716_GPIO_LED_USB2,
.active_low = 1,
},
{
.name = "nbg6716:white:wifi2g",
.gpio = NBG6716_GPIO_LED_WIFI2G,
.active_low = 1,
},
{
.name = "nbg6716:white:wifi5g",
.gpio = NBG6716_GPIO_LED_WIFI5G,
.active_low = 1,
},
{
.name = "nbg6716:white:wps",
.gpio = NBG6716_GPIO_LED_WPS,
.active_low = 1,
}
};
static struct gpio_keys_button nbg6716_gpio_keys[] __initdata = {
{
.desc = "RESET button",
.type = EV_KEY,
.code = KEY_RESTART,
.debounce_interval = NBG6716_KEYS_DEBOUNCE_INTERVAL,
.gpio = NBG6716_GPIO_BTN_RESET,
.active_low = 1,
},
{
.desc = "RFKILL button",
.type = EV_SW,
.code = KEY_RFKILL,
.debounce_interval = NBG6716_KEYS_DEBOUNCE_INTERVAL,
.gpio = NBG6716_GPIO_BTN_RFKILL,
.active_low = 0,
},
{
.desc = "USB1 eject button",
.type = EV_KEY,
.code = BTN_1,
.debounce_interval = NBG6716_KEYS_DEBOUNCE_INTERVAL,
.gpio = NBG6716_GPIO_BTN_USB1,
.active_low = 1,
},
{
.desc = "USB2 eject button",
.type = EV_KEY,
.code = BTN_2,
.debounce_interval = NBG6716_KEYS_DEBOUNCE_INTERVAL,
.gpio = NBG6716_GPIO_BTN_USB2,
.active_low = 1,
},
{
.desc = "WPS button",
.type = EV_KEY,
.code = KEY_WPS_BUTTON,
.debounce_interval = NBG6716_KEYS_DEBOUNCE_INTERVAL,
.gpio = NBG6716_GPIO_BTN_WPS,
.active_low = 1,
},
};
static struct gpio_led nbg6616_leds_gpio[] __initdata = {
{
.name = "nbg6616:green:power",
.gpio = NBG6716_GPIO_LED_POWER,
.active_low = 1,
},
{
.name = "nbg6616:green:usb2",
.gpio = NBG6616_GPIO_LED_USB0,
.active_low = 1,
},
{
.name = "nbg6616:green:usb1",
.gpio = NBG6616_GPIO_LED_USB1,
.active_low = 1,
},
{
.name = "nbg6616:green:wifi2g",
.gpio = NBG6716_GPIO_LED_WIFI2G,
.active_low = 1,
},
{
.name = "nbg6616:green:wifi5g",
.gpio = NBG6716_GPIO_LED_WIFI5G,
.active_low = 1,
},
{
.name = "nbg6616:green:wps",
.gpio = NBG6616_GPIO_LED_WPS,
.active_low = 1,
}
};
static struct gpio_keys_button nbg6616_gpio_keys[] __initdata = {
{
.desc = "RESET button",
.type = EV_KEY,
.code = KEY_RESTART,
.debounce_interval = NBG6716_KEYS_DEBOUNCE_INTERVAL,
.gpio = NBG6716_GPIO_BTN_RESET,
.active_low = 1,
},
{
.desc = "RFKILL button",
.type = EV_KEY,
.code = KEY_RFKILL,
.debounce_interval = NBG6716_KEYS_DEBOUNCE_INTERVAL,
.gpio = NBG6716_GPIO_BTN_RFKILL,
.active_low = 1,
},
{
.desc = "WPS button",
.type = EV_KEY,
.code = KEY_WPS_BUTTON,
.debounce_interval = NBG6716_KEYS_DEBOUNCE_INTERVAL,
.gpio = NBG6716_GPIO_BTN_WPS,
.active_low = 1,
},
};
static struct ar8327_pad_cfg nbg6716_ar8327_pad0_cfg;
static struct ar8327_pad_cfg nbg6716_ar8327_pad6_cfg;
static struct ar8327_led_cfg nbg6716_ar8327_led_cfg;
static struct ar8327_platform_data nbg6716_ar8327_data = {
.pad0_cfg = &nbg6716_ar8327_pad0_cfg,
.pad6_cfg = &nbg6716_ar8327_pad6_cfg,
.port0_cfg = {
.force_link = 1,
.speed = AR8327_PORT_SPEED_1000,
.duplex = 1,
.txpause = 1,
.rxpause = 1,
},
.port6_cfg = {
.force_link = 1,
.speed = AR8327_PORT_SPEED_1000,
.duplex = 1,
.txpause = 1,
.rxpause = 1,
},
.led_cfg = &nbg6716_ar8327_led_cfg
};
static struct mdio_board_info nbg6716_mdio0_info[] = {
{
.bus_id = "ag71xx-mdio.0",
.phy_addr = 0,
.platform_data = &nbg6716_ar8327_data,
},
};
static void nbg6716_get_mac(void* nvram_addr, const char *name, char *mac)
{
u8 *nvram = (u8 *) KSEG1ADDR(nvram_addr);
int err;
err = ath79_nvram_parse_mac_addr(nvram, 0x10000,
name, mac);
if (err)
pr_err("no MAC address found for %s\n", name);
}
static void __init nbg6716_common_setup(u32 leds_num, struct gpio_led* leds,
u32 keys_num,
struct gpio_keys_button* keys,
void* art_addr, void* nvram)
{
u8 *art = (u8 *) KSEG1ADDR(art_addr);
u8 tmpmac[ETH_ALEN];
ath79_register_m25p80(NULL);
ath79_register_leds_gpio(-1, leds_num, leds);
ath79_register_gpio_keys_polled(-1, NBG6716_KEYS_POLL_INTERVAL,
keys_num, keys);
ath79_nfc_set_ecc_mode(AR934X_NFC_ECC_HW);
ath79_register_nfc();
gpio_request_one(NBG6716_GPIO_USB_POWER,
GPIOF_OUT_INIT_HIGH | GPIOF_EXPORT_DIR_FIXED,
"USB power");
ath79_register_usb();
nbg6716_get_mac(nvram, "ethaddr=", tmpmac);
ath79_register_pci();
ath79_register_wmac(art + NBG6716_WMAC_CALDATA_OFFSET, tmpmac);
ath79_setup_qca955x_eth_cfg(QCA955X_ETH_CFG_RGMII_EN);
ath79_register_mdio(0, 0x0);
ath79_init_mac(ath79_eth0_data.mac_addr, tmpmac, 2);
ath79_init_mac(ath79_eth1_data.mac_addr, tmpmac, 3);
mdiobus_register_board_info(nbg6716_mdio0_info,
ARRAY_SIZE(nbg6716_mdio0_info));
/* GMAC0 is connected to the RMGII interface */
ath79_eth0_data.phy_if_mode = PHY_INTERFACE_MODE_RGMII;
ath79_eth0_data.phy_mask = BIT(0);
ath79_eth0_data.mii_bus_dev = &ath79_mdio0_device.dev;
ath79_register_eth(0);
/* GMAC1 is connected to the SGMII interface */
ath79_eth1_data.phy_if_mode = PHY_INTERFACE_MODE_SGMII;
ath79_eth1_data.speed = SPEED_1000;
ath79_eth1_data.duplex = DUPLEX_FULL;
ath79_register_eth(1);
}
static void __init nbg6716_010_setup(void)
{
/* GMAC0 of the AR8337 switch is connected to GMAC0 via RGMII */
nbg6716_ar8327_pad0_cfg.mode = AR8327_PAD_MAC_RGMII;
nbg6716_ar8327_pad0_cfg.txclk_delay_en = true;
nbg6716_ar8327_pad0_cfg.rxclk_delay_en = true;
nbg6716_ar8327_pad0_cfg.txclk_delay_sel = AR8327_CLK_DELAY_SEL1;
nbg6716_ar8327_pad0_cfg.rxclk_delay_sel = AR8327_CLK_DELAY_SEL2;
/* GMAC6 of the AR8337 switch is connected to GMAC1 via SGMII */
nbg6716_ar8327_pad6_cfg.mode = AR8327_PAD_MAC_SGMII;
nbg6716_ar8327_pad6_cfg.rxclk_delay_en = true;
nbg6716_ar8327_pad6_cfg.rxclk_delay_sel = AR8327_CLK_DELAY_SEL0;
ath79_eth0_pll_data.pll_1000 = 0xa6000000;
ath79_eth1_pll_data.pll_1000 = 0x03000101;
nbg6716_ar8327_led_cfg.open_drain = 0;
nbg6716_ar8327_led_cfg.led_ctrl0 = 0xffb7ffb7;
nbg6716_ar8327_led_cfg.led_ctrl1 = 0xffb7ffb7;
nbg6716_ar8327_led_cfg.led_ctrl2 = 0xffb7ffb7;
nbg6716_ar8327_led_cfg.led_ctrl3 = 0x03ffff00;
nbg6716_common_setup(ARRAY_SIZE(nbg6716_leds_gpio), nbg6716_leds_gpio,
ARRAY_SIZE(nbg6716_gpio_keys), nbg6716_gpio_keys,
(void*) 0x1f050000, (void*) 0x1f040000);
}
static void __init nbg6616_010_setup(void)
{
/* GMAC0 of the AR8337 switch is connected to GMAC0 via RGMII */
nbg6716_ar8327_pad0_cfg.mode = AR8327_PAD_MAC_RGMII;
nbg6716_ar8327_pad0_cfg.txclk_delay_en = true;
nbg6716_ar8327_pad0_cfg.rxclk_delay_en = true;
nbg6716_ar8327_pad0_cfg.txclk_delay_sel = AR8327_CLK_DELAY_SEL1;
nbg6716_ar8327_pad0_cfg.rxclk_delay_sel = AR8327_CLK_DELAY_SEL2;
/* GMAC6 of the AR8337 switch is connected to GMAC1 via SGMII */
nbg6716_ar8327_pad6_cfg.mode = AR8327_PAD_MAC_SGMII;
nbg6716_ar8327_pad6_cfg.rxclk_delay_en = true;
nbg6716_ar8327_pad6_cfg.rxclk_delay_sel = AR8327_CLK_DELAY_SEL0;
ath79_eth0_pll_data.pll_1000 = 0xa6000000;
ath79_eth1_pll_data.pll_1000 = 0x03000101;
nbg6716_ar8327_led_cfg.open_drain = 0;
nbg6716_ar8327_led_cfg.led_ctrl0 = 0xffb7ffb7;
nbg6716_ar8327_led_cfg.led_ctrl1 = 0xffb7ffb7;
nbg6716_ar8327_led_cfg.led_ctrl2 = 0xffb7ffb7;
nbg6716_ar8327_led_cfg.led_ctrl3 = 0x03ffff00;
nbg6716_common_setup(ARRAY_SIZE(nbg6616_leds_gpio), nbg6616_leds_gpio,
ARRAY_SIZE(nbg6616_gpio_keys), nbg6616_gpio_keys,
(void*) 0x1f040000, (void*) 0x1f030000);
}
MIPS_MACHINE(ATH79_MACH_NBG6716, "NBG6716",
"Zyxel NBG6716",
nbg6716_010_setup);
MIPS_MACHINE(ATH79_MACH_NBG6616, "NBG6616",
"Zyxel NBG6616",
nbg6616_010_setup);
| 27.044619
| 76
| 0.746118
|
a453afaf60c69152c87a53a6bac055fb92b3c3d2
| 3,374
|
php
|
PHP
|
app/views/users/register.php
|
Eduar2TC/Shareposts
|
f3a6920407c5f6e16e3b13bccd8dd88153456848
|
[
"MIT"
] | null | null | null |
app/views/users/register.php
|
Eduar2TC/Shareposts
|
f3a6920407c5f6e16e3b13bccd8dd88153456848
|
[
"MIT"
] | null | null | null |
app/views/users/register.php
|
Eduar2TC/Shareposts
|
f3a6920407c5f6e16e3b13bccd8dd88153456848
|
[
"MIT"
] | null | null | null |
<?php require_once APP_ROOT . '/views/inc/header.php'; ?>
<main class="d-flex align-items-center min-vh-100 py-2 py-md-0">
<div class="row container-fluid mx-auto mt-4 mb-3">
<div class="col-md-4 offset-md-2 d-flex justify-content-end px-0 img-container">
<img class="img-fluid align-self-end shadow" src="<?php echo URL_ROOT; ?>/img/backgrond-register.jpg" alt="" srcset="">
</div>
<div class="col-md-4 ps-0">
<div class="card card-body bg-light p-3 shadow-lg">
<h2 class="text-center text-primary fira">Create an Accont</h2>
<p class="fw-bold fira">Please fill out this form to register to Website</p>
<form class="formulary" action="<?php echo URL_ROOT; ?>/users/register" method="POST">
<div class="form-group">
<label for="name">Name:<sup>*</sup></label>
<input type="text" name="name" class="form-control form-control-md <?php echo (!empty($data['name_error'])) ? 'is-invalid' : ''; ?>" value="<?php echo $data['name']; ?>" placeholder="<?php echo $data['name_error']; ?>">
</div>
<!-- <span class="invalid-feedback d-block"><?php echo $data['name_error']; ?></span> -->
<div class="form-group">
<label for="email">Email:<sup>*</sup></label>
<input type="email" name="email" class="form-control form-control-md <?php echo (!empty($data['email_error'])) ? 'is-invalid' : ''; ?>" value="<?php echo $data['email']; ?>" placeholder="<?php echo $data['email_error']; ?>">
</div>
<!-- <span class="invalid-feedback d-block"><?php echo $data['email_error']; ?></span> -->
<div class="form-group">
<label for="password">Password:<sup>*</sup></label>
<input type="password" name="password" class="form-control form-control-md <?php echo (!empty($data['password_error'])) ? 'is-invalid' : ''; ?>" value="<?php echo $data['password']; ?>" placeholder="<?php echo $data['password_error']; ?>">
</div>
<!-- <span class="invalid-feedback d-block"><?php echo $data['password_error']; ?></span> -->
<div class="form-group">
<label for="confirm_password">Comfirm:<sup>*</sup></label>
<input type="password" name="confirm_password" class="form-control form-control-md <?php echo (!empty($data['confirm_password_error'])) ? 'is-invalid' : ''; ?>" value="<?php echo $data['confirm_password']; ?>" placeholder="<?php echo $data['confirm_password_error']; ?>">
</div>
<!-- <span class="invalid-feedback d-block"><?php echo $data['confirm_password_error']; ?></span> -->
<div class="d-grid gap-2 col-12 mx-auto mt-4">
<input type="submit" value="Register" class="btn btn-success btn-block">
<a href="<?php echo URL_ROOT; ?>/users/login" class="btn btn-outline-secondary btn-block float-end">Have an account? Login</a>
</div>
</form>
</div>
</div>
</div>
</main>
<?php require_once APP_ROOT . '/views/inc/footer.php'; ?>
| 68.857143
| 296
| 0.534381
|
57fe74b15c47db0ec6a45757184bdde701cf32e8
| 2,994
|
php
|
PHP
|
tests/Dplr/Tests/TaskReportTest.php
|
muxx/dplr
|
98d649c83904a2ea7b339d31e5f009f2ab06bcf8
|
[
"MIT"
] | 11
|
2015-02-19T02:05:58.000Z
|
2019-10-23T12:41:52.000Z
|
tests/Dplr/Tests/TaskReportTest.php
|
muxx/dplr
|
98d649c83904a2ea7b339d31e5f009f2ab06bcf8
|
[
"MIT"
] | null | null | null |
tests/Dplr/Tests/TaskReportTest.php
|
muxx/dplr
|
98d649c83904a2ea7b339d31e5f009f2ab06bcf8
|
[
"MIT"
] | 1
|
2021-05-13T15:42:18.000Z
|
2021-05-13T15:42:18.000Z
|
<?php
namespace Dplr\Tests;
use Dplr\Task;
use Dplr\TaskReport;
use InvalidArgumentException;
use PHPUnit\Framework\TestCase;
class TaskReportTest extends TestCase
{
public function testNoType(): void
{
$this->expectException(InvalidArgumentException::class);
$this->expectExceptionMessage('Not found `Type` parameter.');
new TaskReport([]);
}
public function testInvalidType(): void
{
$this->expectException(InvalidArgumentException::class);
$this->expectExceptionMessage('Type "aaa" not allowed. Allowed types: UserError, Reply, Timeout.');
new TaskReport(['Type' => 'aaa']);
}
public function testNotSuccessfulSystem()
{
$taskReport = new TaskReport(['Type' => TaskReport::TYPE_TIMEOUT]);
$this->assertFalse($taskReport->isSuccessful());
$taskReport = new TaskReport(['Type' => TaskReport::TYPE_USER_ERROR]);
$this->assertFalse($taskReport->isSuccessful());
}
public function testNotSuccessful()
{
$taskReport = new TaskReport(
[
'Type' => TaskReport::TYPE_REPLY,
'Success' => false,
'Stdout' => 'output',
'Stderr' => 'error',
],
new Task(['Action' => 'ssh', 'Cmd' => 'ls -al'])
);
$this->assertFalse($taskReport->isSuccessful());
$this->assertEquals('error', $taskReport->getErrorOutput());
$this->assertEquals('output', $taskReport->getOutput());
}
public function testSuccessful()
{
$taskReport = new TaskReport(
[
'Type' => TaskReport::TYPE_REPLY,
'Success' => true,
'Stdout' => 'output',
],
new Task(['Action' => 'ssh', 'Cmd' => 'ls -al'])
);
$this->assertTrue($taskReport->isSuccessful());
$this->assertNull($taskReport->getErrorOutput());
$this->assertEquals('output', $taskReport->getOutput());
}
public function testNotSuccessfulWithoutStdout()
{
$taskReport = new TaskReport(
[
'Type' => TaskReport::TYPE_REPLY,
'Success' => false,
'Stderr' => 'error',
],
new Task(['Action' => 'ssh', 'Cmd' => 'ls -al'])
);
$this->assertFalse($taskReport->isSuccessful());
$this->assertEquals('error', $taskReport->getErrorOutput());
$this->assertNull($taskReport->getOutput());
}
public function testNotSuccessfulWithoutStderr()
{
$taskReport = new TaskReport(
[
'Type' => TaskReport::TYPE_REPLY,
'Success' => false,
],
new Task(['Action' => 'ssh', 'Cmd' => 'ls -al'])
);
$this->assertFalse($taskReport->isSuccessful());
$this->assertNull($taskReport->getErrorOutput());
$this->assertNull($taskReport->getOutput());
}
}
| 29.643564
| 107
| 0.548764
|
1a8a519104046f74dbcfea99b93c4ebb7df6122d
| 3,477
|
py
|
Python
|
src/main/python/programmingtheiot/cda/connection/RedisPersistenceAdapter.py
|
Taowyoo/-constrained-device-app
|
c858f786dfa7fc82006068d405a04dc21f2fcda5
|
[
"MIT"
] | null | null | null |
src/main/python/programmingtheiot/cda/connection/RedisPersistenceAdapter.py
|
Taowyoo/-constrained-device-app
|
c858f786dfa7fc82006068d405a04dc21f2fcda5
|
[
"MIT"
] | 2
|
2020-10-31T06:33:20.000Z
|
2020-11-05T06:36:44.000Z
|
src/main/python/programmingtheiot/cda/connection/RedisPersistenceAdapter.py
|
Taowyoo/-constrained-device-app
|
c858f786dfa7fc82006068d405a04dc21f2fcda5
|
[
"MIT"
] | 1
|
2020-12-13T03:41:57.000Z
|
2020-12-13T03:41:57.000Z
|
import logging
from programmingtheiot.common import ConfigConst
from programmingtheiot.common.ConfigUtil import ConfigUtil
from programmingtheiot.common.ResourceNameEnum import ResourceNameEnum
from programmingtheiot.data.DataUtil import DataUtil
from programmingtheiot.data.SensorData import SensorData
import redis
class RedisPersistenceAdapter:
def __init__(self)
"""
Constructor, do some basic configrations
"""
self.dataUtil = DataUtil()
self.configUtil = ConfigUtil()
self.host = self.configUtil.getProperty(ConfigConst.DATA_GATEWAY_SERVICE, ConfigConst.HOST_KEY)
self.port = self.configUtil.getInteger(ConfigConst.DATA_GATEWAY_SERVICE, ConfigConst.PORT_KEY)
self.enableCrypt = self.configUtil.getBoolean(ConfigConst.DATA_GATEWAY_SERVICE, ConfigConst.ENABLE_CRYPT_KEY)
if self.enableCrypt:
self.credFilePath = self.configUtil.getProperty(ConfigConst.DATA_GATEWAY_SERVICE, ConfigConst.CRED_FILE_KEY)
# TODO: init redis with encryption
logging.info("Redis client setting: host = {0}, port = {1}.".format(self.host, self.port))
# Init with no connection established
self.curConnection: redis.client.Redis = None
def connectClient(self) -> bool:
"""
Connect to redis
:return: whether success
"""
if self.curConnection is None:
logging.info("Redis client connecting to server...")
try:
self.curConnection = redis.client.Redis(host=self.host, port=self.port)
logging.info("Redis client successfully connect to server.")
except BaseException as be:
self.curConnection = None
logging.error("Cannot connect to Redis server, meet exception: " + be.__str__())
return False
return True
else:
logging.warning("Redis client has already connected!")
return True
def disconnectClient(self) -> bool:
"""
Disconnect to redis
:return: whether success
"""
if self.curConnection is None:
logging.warning("Redis client has already disconnected!")
return True
else:
logging.info("Redis client disconnecting...!")
self.curConnection.close()
self.curConnection = None
logging.info("Redis client disconnect successfully.")
return True
def storeData(self, data: SensorData, resource: ResourceNameEnum = ResourceNameEnum.CDA_SENSOR_MSG_RESOURCE) -> bool:
"""
Store a SensorData to the key which defined by given ResourceNameEnum
:param data: SensorData instance to store which will be convert to json string
:param resource: ResourceNameEnum instance which will be convert to string, defaults to ResourceNameEnum.CDA_SENSOR_MSG_RESOURCE
:return: whether success
"""
topicName: str = resource.value
jsonStr = self.dataUtil.sensorDataToJson(data)
if self.curConnection:
subNums = self.curConnection.publish(channel=topicName, message=jsonStr)
logging.debug("Published msg:\n{0}\nto {1} with {2} subscribers.".format(jsonStr, topicName, subNums))
return True
else:
logging.error("Cannot store data to Redis, because client has not connected to server yet!")
return False
pass
| 41.891566
| 136
| 0.663503
|
ef305782b19d3fb0107bdf10da178d2880d8ffec
| 1,624
|
h
|
C
|
include/libnodes/ValueNode.h
|
heisters/libnodes
|
f0699a2912b03f161c856e4ed14986a81921cd18
|
[
"Unlicense"
] | 9
|
2017-09-09T06:36:36.000Z
|
2022-01-02T20:04:16.000Z
|
include/libnodes/ValueNode.h
|
heisters/libnodes
|
f0699a2912b03f161c856e4ed14986a81921cd18
|
[
"Unlicense"
] | null | null | null |
include/libnodes/ValueNode.h
|
heisters/libnodes
|
f0699a2912b03f161c856e4ed14986a81921cd18
|
[
"Unlicense"
] | 1
|
2017-11-01T03:57:27.000Z
|
2017-11-01T03:57:27.000Z
|
#pragma once
#include "libnodes/Node.h"
namespace nodes {
//! A simple node that holds a primitive value and emits it when the value
//! changes.
template< typename T, typename ...Ts >
class ValueNode : public Node< Inlets< T, Ts... >, Outlets< T, Ts... > >
{
public:
typedef Node< Inlets< T, Ts... >, Outlets< T, Ts... > > node_type;
ValueNode( const std::string &label, const T & v ) :
node_type( label ),
mValue( v )
{
mOldValue = mValue;
listen();
}
ValueNode( const T & v ) :
node_type(),
mValue( v )
{
mOldValue = mValue;
listen();
}
ValueNode() :
node_type()
{
mOldValue = mValue;
listen();
}
void update()
{
if ( mOldValue != mValue ) this->template out< 0 >().update( mValue );
mOldValue = mValue;
}
void set( const T & v ) { mValue = v; update(); }
ValueNode< T > & operator=( const T & v ) { set( v ); return *this; }
T & get() { return mValue; }
const T & get() const { return mValue; }
T operator()() const { return mValue; }
bool operator==( const T & rhs ) const { return mValue == rhs; }
protected:
virtual void listen()
{
this->template in< 0 >().onReceive( [&] ( const T & newv ) {
mValue = newv;
this->template out< 0 >().update( newv );
});
}
private:
T mValue, mOldValue;
};
typedef ValueNode< float > ValueNodef;
typedef ValueNode< int > ValueNodei;
typedef ValueNode< bool > ValueNodeb;
typedef ValueNode< double > ValueNoded;
}
| 21.945946
| 78
| 0.54064
|
e288c29ecb728d69118fc9f8242931e744fe1262
| 6,694
|
py
|
Python
|
plaso/storage/redis/reader.py
|
kiddinn/plaso
|
c7d955724cfeeea09ce6166609fd4d3c77a99fc6
|
[
"Apache-2.0"
] | null | null | null |
plaso/storage/redis/reader.py
|
kiddinn/plaso
|
c7d955724cfeeea09ce6166609fd4d3c77a99fc6
|
[
"Apache-2.0"
] | null | null | null |
plaso/storage/redis/reader.py
|
kiddinn/plaso
|
c7d955724cfeeea09ce6166609fd4d3c77a99fc6
|
[
"Apache-2.0"
] | null | null | null |
# -*- coding: utf-8 -*-
"""Redis reader."""
from plaso.lib import definitions
from plaso.storage.redis import redis_store
from plaso.storage import interface
class RedisStorageReader(interface.StorageReader):
"""Redis storage file reader."""
def __init__(self, task):
"""Initializes a Redis Storage Reader.
Args:
task (Task): the task whose results the store contains.
"""
super(RedisStorageReader, self).__init__()
self._store = redis_store.RedisStore(
storage_type=definitions.STORAGE_TYPE_TASK,
session_identifier=task.session_identifier,
task_identifier=task.identifier)
def IsFinalized(self):
"""Checks if the store has been finalized.
Returns:
bool: True if the store has been finalized.
"""
return self._store.IsFinalized()
def Open(self):
"""Opens the storage reader."""
self._store.Open()
def Close(self):
"""Closes the storage reader."""
self._store.Close()
def GetAnalysisReports(self):
"""Retrieves the analysis reports.
Returns:
generator(AnalysisReport): analysis report generator.
"""
return self._store.GetAnalysisReports()
def GetEventData(self):
"""Retrieves the event data.
Returns:
generator(EventData): event data generator.
"""
return self._store.GetEventData()
def GetEventDataByIdentifier(self, identifier):
"""Retrieves specific event data.
Args:
identifier (AttributeContainerIdentifier): event data identifier.
Returns:
EventData: event data or None if not available.
"""
return self._store.GetEventDataByIdentifier(identifier)
def GetEventDataStreams(self):
"""Retrieves the event data streams.
Returns:
generator(EventDataStream): event data stream generator.
"""
return self._store.GetEventDataStreams()
def GetEventDataStreamByIdentifier(self, identifier):
"""Retrieves a specific event data stream.
Args:
identifier (AttributeContainerIdentifier): event data stream identifier.
Returns:
EventDataStream: event data stream or None if not available.
"""
return self._store.GetEventDataStreamByIdentifier(identifier)
def GetEvents(self):
"""Retrieves the events.
Returns:
generator(EventObject): event generator.
"""
return self._store.GetEvents()
def GetEventSources(self):
"""Retrieves event sources.
Returns:
generator(EventSource): event source generator.
"""
return self._store.GetEventSources()
def GetEventTagByIdentifier(self, identifier):
"""Retrieves a specific event tag.
Args:
identifier (AttributeContainerIdentifier): event tag identifier.
Returns:
EventTag: event tag or None if not available.
"""
return self._store.GetEventTagByIdentifier(identifier)
def GetEventTags(self):
"""Retrieves the event tags.
Returns:
generator(EventSource): event tag generator.
"""
return self._store.GetEventTags()
def GetExtractionWarnings(self):
"""Retrieves the extraction warnings.
Returns:
generator(ExtractionWarning): extraction warning generator.
"""
return self._store.GetExtractionWarnings()
def GetNumberOfAnalysisReports(self):
"""Retrieves the number analysis reports.
Returns:
int: number of analysis reports.
"""
return self._store.GetNumberOfAnalysisReports()
def GetNumberOfEventSources(self):
"""Retrieves the number of event sources.
Returns:
int: number of event sources.
"""
return self._store.GetNumberOfEventSources()
def GetPreprocessingWarnings(self):
"""Retrieves the preprocessing warnings.
Returns:
generator(RecoveryWarning): preprocessing warning generator.
"""
return self._store.GetPreprocessingWarnings()
def GetRecoveryWarnings(self):
"""Retrieves the recovery warnings.
Returns:
generator(RecoveryWarning): recovery warning generator.
"""
return self._store.GetRecoveryWarnings()
def GetSortedEvents(self, time_range=None):
"""Retrieves the events in increasing chronological order.
This includes all events written to the storage including those pending
being flushed (written) to the storage.
Args:
time_range (Optional[TimeRange]): time range used to filter events
that fall in a specific period.
Returns:
generator(EventObject): event generator.
"""
return self._store.GetSortedEvents(time_range)
def GetSessions(self):
"""Retrieves the sessions.
Returns:
generator(Session): session generator.
"""
return self._store.GetSessions()
def HasAnalysisReports(self):
"""Determines if a store contains analysis reports.
Returns:
bool: True if the store contains analysis reports.
"""
return self._store.HasAnalysisReports()
def HasEventTags(self):
"""Determines if a store contains event tags.
Returns:
bool: True if the store contains event tags.
"""
return self._store.HasEventTags()
def HasExtractionWarnings(self):
"""Determines if a store contains extraction warnings.
Returns:
bool: True if the store contains extraction warnings.
"""
return self._store.HasExtractionWarnings()
def HasPreprocessingWarnings(self):
"""Determines if a store contains preprocessing warnings.
Returns:
bool: True if the store contains preprocessing warnings.
"""
return self._store.HasPreprocessingWarnings()
def HasRecoveryWarnings(self):
"""Determines if a store contains recovery warnings.
Returns:
bool: True if the store contains recovery warnings.
"""
return self._store.HasRecoveryWarnings()
# pylint: disable=unused-argument
def ReadSystemConfiguration(self, knowledge_base):
"""Reads system configuration information.
The system configuration contains information about various system specific
configuration data, for example the user accounts.
Args:
knowledge_base (KnowledgeBase): is used to store the preprocessing
information.
"""
# Not implemented by the Redis store, as it is a task store only.
return
def SetSerializersProfiler(self, serializers_profiler):
"""Sets the serializers profiler.
Args:
serializers_profiler (SerializersProfiler): serializers profiler.
"""
self._store.SetSerializersProfiler(serializers_profiler)
def SetStorageProfiler(self, storage_profiler):
"""Sets the storage profiler.
Args:
storage_profiler (StorageProfiler): storage profile.
"""
self._store.SetStorageProfiler(storage_profiler)
| 26.458498
| 79
| 0.70496
|
79ed552caa695864c0ac8e43f87453694a5af9eb
| 191
|
php
|
PHP
|
resources/views/child_category.blade.php
|
Kaleemullah007/events
|
bedb49a0517bf769a4431e02afe1e63ec7b78a36
|
[
"MIT"
] | null | null | null |
resources/views/child_category.blade.php
|
Kaleemullah007/events
|
bedb49a0517bf769a4431e02afe1e63ec7b78a36
|
[
"MIT"
] | null | null | null |
resources/views/child_category.blade.php
|
Kaleemullah007/events
|
bedb49a0517bf769a4431e02afe1e63ec7b78a36
|
[
"MIT"
] | null | null | null |
<tr style="display: none" class="<?=$id?>" >
<td><a href="/search?category={{ str_replace(' ', '_', str_replace('&', '$', $child_category->name))}}">{{$child_category->name}}</a>
</td></tr>
| 63.666667
| 134
| 0.575916
|
1b035b8aa13b22acf87b7a467c6aa7644aa09946
| 618
|
dart
|
Dart
|
system_metrics_widget/lib/src/environment/android.dart
|
DisDis/dslideshow
|
58e9b2afbcd43c7c7f99a2382dd109bcef5c4185
|
[
"MIT"
] | 1
|
2021-04-29T14:49:00.000Z
|
2021-04-29T14:49:00.000Z
|
system_metrics_widget/lib/src/environment/android.dart
|
DisDis/dslideshow
|
58e9b2afbcd43c7c7f99a2382dd109bcef5c4185
|
[
"MIT"
] | null | null | null |
system_metrics_widget/lib/src/environment/android.dart
|
DisDis/dslideshow
|
58e9b2afbcd43c7c7f99a2382dd109bcef5c4185
|
[
"MIT"
] | 1
|
2021-07-15T18:34:22.000Z
|
2021-07-15T18:34:22.000Z
|
import 'dart:io';
// import 'package:permission_handler/permission_handler.dart';
// import 'package:path_provider/path_provider.dart' as path_prov;
final bool isLinuxEmbedded = false;
// Future<Directory> getApplicationDocumentsDirectory() async{
// return path_prov.getApplicationDocumentsDirectory();
// }
//
// Future<bool> checkPermissionReadExternalStorage() async{
// var status = await Permission.storage.status;
// if (status.isUndetermined) {
// // We didn't ask for permission yet.
// status = await Permission.storage.request();
// }
// return status == PermissionStatus.granted;
// }
| 30.9
| 66
| 0.729773
|
4c1cf1c895a0bc6e9aa296d4e54e603ba624d534
| 122
|
lua
|
Lua
|
Source Code/conf.lua
|
siddnikh/pong
|
2d595f0b9ac9afb2289f4c4251bac657be489504
|
[
"MIT"
] | null | null | null |
Source Code/conf.lua
|
siddnikh/pong
|
2d595f0b9ac9afb2289f4c4251bac657be489504
|
[
"MIT"
] | null | null | null |
Source Code/conf.lua
|
siddnikh/pong
|
2d595f0b9ac9afb2289f4c4251bac657be489504
|
[
"MIT"
] | null | null | null |
function love.conf(t)
t.window.icon = 'icon.png'
t.window.borderless = false
t.window.resizable = true
end
| 24.4
| 32
| 0.655738
|
e2a9cf9e0cae4c7e687ca418ba23e3dd66b07d95
| 5,339
|
py
|
Python
|
grand/backends/networkx.py
|
aplbrain/grand
|
d85669df17a40834a13478ae200e984e13b41650
|
[
"Apache-2.0"
] | 31
|
2020-10-16T16:46:02.000Z
|
2022-03-04T20:45:05.000Z
|
grand/backends/networkx.py
|
aplbrain/grand
|
d85669df17a40834a13478ae200e984e13b41650
|
[
"Apache-2.0"
] | 15
|
2020-10-15T16:28:49.000Z
|
2022-02-10T16:41:32.000Z
|
grand/backends/networkx.py
|
aplbrain/grand
|
d85669df17a40834a13478ae200e984e13b41650
|
[
"Apache-2.0"
] | null | null | null |
from typing import Hashable, Generator, Iterable
import time
import pandas as pd
import networkx as nx
from .backend import Backend
class NetworkXBackend(Backend):
def __init__(self, directed: bool = False):
"""
Create a new Backend instance.
Arguments:
directed (bool: False): Whether to make the backend graph directed
Returns:
None
"""
self._nx_graph = nx.DiGraph() if directed else nx.Graph()
self._directed = directed
def is_directed(self) -> bool:
"""
Return True if the backend graph is directed.
Arguments:
None
Returns:
bool: True if the backend graph is directed.
"""
return self._directed
def add_node(self, node_name: Hashable, metadata: dict):
"""
Add a new node to the graph.
Arguments:
node_name (Hashable): The ID of the node
metadata (dict: None): An optional dictionary of metadata
Returns:
Hashable: The ID of this node, as inserted
"""
self._nx_graph.add_node(node_name, **metadata)
def get_node_by_id(self, node_name: Hashable):
"""
Return the data associated with a node.
Arguments:
node_name (Hashable): The node ID to look up
Returns:
dict: The metadata associated with this node
"""
return self._nx_graph.nodes[node_name]
def all_nodes_as_iterable(self, include_metadata: bool = False) -> Generator:
"""
Get a generator of all of the nodes in this graph.
Arguments:
include_metadata (bool: False): Whether to include node metadata in
the response
Returns:
Generator: A generator of all nodes (arbitrary sort)
"""
return self._nx_graph.nodes(data=include_metadata)
def add_edge(self, u: Hashable, v: Hashable, metadata: dict):
"""
Add a new edge to the graph between two nodes.
If the graph is directed, this edge will start (source) at the `u` node
and end (target) at the `v` node.
Arguments:
u (Hashable): The source node ID
v (Hashable): The target node ID
metadata (dict): Optional metadata to associate with the edge
Returns:
Hashable: The edge ID, as inserted.
"""
self._nx_graph.add_edge(u, v, **metadata)
def all_edges_as_iterable(self, include_metadata: bool = False) -> Generator:
"""
Get a list of all edges in this graph, arbitrary sort.
Arguments:
include_metadata (bool: False): Whether to include edge metadata
Returns:
Generator: A generator of all edges (arbitrary sort)
"""
return self._nx_graph.edges(data=include_metadata)
def get_edge_by_id(self, u: Hashable, v: Hashable):
"""
Get an edge by its source and target IDs.
Arguments:
u (Hashable): The source node ID
v (Hashable): The target node ID
Returns:
dict: Metadata associated with this edge
"""
return self._nx_graph.edges[u, v]
def get_node_neighbors(
self, u: Hashable, include_metadata: bool = False
) -> Generator:
"""
Get a generator of all downstream nodes from this node.
Arguments:
u (Hashable): The source node ID
Returns:
Generator
"""
if include_metadata:
return self._nx_graph[u]
return self._nx_graph.neighbors(u)
def get_node_predecessors(
self, u: Hashable, include_metadata: bool = False
) -> Generator:
"""
Get a generator of all downstream nodes from this node.
Arguments:
u (Hashable): The source node ID
Returns:
Generator
"""
if include_metadata:
return self._nx_graph.pred[u]
return self._nx_graph.predecessors(u)
def get_node_count(self) -> Iterable:
"""
Get an integer count of the number of nodes in this graph.
Arguments:
None
Returns:
int: The count of nodes
"""
return len(self._nx_graph)
def ingest_from_edgelist_dataframe(
self, edgelist: pd.DataFrame, source_column: str, target_column: str
) -> None:
"""
Ingest an edgelist from a Pandas DataFrame.
"""
tic = time.time()
self._nx_graph.add_edges_from(
[
(
e[source_column],
e[target_column],
{
k: v
for k, v in dict(e).items()
if k not in [source_column, target_column]
},
)
for _, e in edgelist.iterrows()
]
)
nodes = edgelist[source_column].append(edgelist[target_column]).unique()
return {
"node_count": len(nodes),
"node_duration": 0,
"edge_count": len(edgelist),
"edge_duration": time.time() - tic,
}
def teardown(self) -> None:
return
| 25.917476
| 81
| 0.556846
|
ff22f9b93f9ce4b0fcc06b4dadf84a7ade5ca1f0
| 3,363
|
py
|
Python
|
utils.py
|
vjg28/Lunar-Lander-RL
|
5307f9b9843a16b943ec044dbd3239b77d518bdc
|
[
"MIT"
] | null | null | null |
utils.py
|
vjg28/Lunar-Lander-RL
|
5307f9b9843a16b943ec044dbd3239b77d518bdc
|
[
"MIT"
] | null | null | null |
utils.py
|
vjg28/Lunar-Lander-RL
|
5307f9b9843a16b943ec044dbd3239b77d518bdc
|
[
"MIT"
] | null | null | null |
'''
Common code blocks.
'''
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import shutil,os
def agent_action(p_model, observation):
prob = p_model.sess.run(p_model.action_probs, feed_dict = {p_model.tf_observations: [observation]})
action = np.random.choice(np.arange(len(prob[0])), p = prob[0])
return action
def test_action(p_model, observation):
prob = p_model.sess.run(p_model.action_probs, feed_dict = {p_model.tf_observations: [observation]})
action = np.argmax(prob[0])
return action
def agent_value(v_model, observations):
pred_value = v_model.sess.run(v_model.value, feed_dict = {v_model.tf_observations: observations})
return pred_value
def oc_stateValues(reward, GAMMA):
l = len(reward)
for i in range(l-1):
reward[l-i-2] += (GAMMA * reward[l-i-1])
reward = np.array(reward)
# reward -= np.mean(reward)
# reward /= np.std(reward)
return reward
def restore_model(model, MODEL_DIR):
model.saver.restore(model.sess, MODEL_DIR + 'agent.ckpt')
def introduction_print_file(file_name, args):
with open(file_name, 'w') as f:
print('Test Results of Agent on ', args.env_id,' with 100 episodes of each seed', file =f)
def avg_100_reward(episode_reward_vec):
l = len(episode_reward_vec)
if l<=100:
return np.mean(np.array(episode_reward_vec))
vec_100 = episode_reward_vec[l-100:l]
avg_value = np.mean(np.array(vec_100))
return avg_value
def move(src, dest):
shutil.move(src,dest)
def make_log_file(args, v_model, p_model):
with open('logfile.txt', 'w') as f:
print("Monte Carlo REINFORCE Policy Gradient with Baseline algorithm \nAuthor: Varshil Gandhi \nDate: 16th December, 2018 \nAlgo Source: David Silver Lectures & Rich Sutton RL Book", file = f)
print('\nThe variables used in the experiment:', file = f)
print('-----------------------------------------------', file = f)
for keys, values in vars(args).items():
print('| ',keys, ' : ' , values, ' |', file= f)
print('\nValue Model Parameters', file = f)
print('_____________________________________________', file= f)
print('| Neurons in the First Hidden Layer | ', v_model.n_hidden_1,' |', file = f)
print('| Neurons in the Second Hidden Layer| ', v_model.n_hidden_2,' |', file = f)
print('| Std Deviation in weights of Layers| ', v_model.std_dev, '|', file = f)
print('| Constant in bias vectors of Layers| ', v_model.bias_constant, ' |', file = f)
print('| Regularization Constant | ', v_model.reg, ' |', file = f)
print('_____________________________________________', file = f)
print('\nPolicy Model Parameters', file = f)
print('_____________________________________________', file= f)
print('| Neurons in the First Hidden Layer | ', p_model.n_hidden_1,' |', file = f)
print('| Neurons in the Second Hidden Layer| ', p_model.n_hidden_2,' |', file = f)
print('| Std Deviation in weights of Layers| ', p_model.std_dev, '|', file = f)
print('| Constant in bias vectors of Layers| ', p_model.bias_constant, ' |', file = f)
print('_____________________________________________', file = f)
| 41.518519
| 200
| 0.644068
|
7987434cbebe09b1e1c9c745be0566df14cda324
| 5,262
|
php
|
PHP
|
application/controllers/Order.php
|
dulkith/pizza_duka
|
d759be6075b4600bbbaa45741d7e81bb2383043c
|
[
"MIT"
] | null | null | null |
application/controllers/Order.php
|
dulkith/pizza_duka
|
d759be6075b4600bbbaa45741d7e81bb2383043c
|
[
"MIT"
] | null | null | null |
application/controllers/Order.php
|
dulkith/pizza_duka
|
d759be6075b4600bbbaa45741d7e81bb2383043c
|
[
"MIT"
] | null | null | null |
<?php
/**
* Class Order
* Pizza NoW! online order system order controller class
*/
class Order extends CI_Controller
{
public function __construct()
{
parent::__construct();
// set local time zone
date_default_timezone_set('Asia/Colombo');
}
public function index()
{
// get cart data
$cartDataArray = $this->session->userdata('cartData');
// get cart item count
$itemCount = 0;
// check cart item data
if ($cartDataArray != []) {
// get cart item count
$itemCount = count($cartDataArray);
$headerData['pizzaPageTitle'] = 'Cart[' . $itemCount . ']';
$headerData['cartCount'] = $itemCount;
// calculate subtotal
$subTotal = 0;
foreach ($cartDataArray as $cartItem)
$subTotal += $cartItem->total;
$data['cartDataArray'] = $cartDataArray;
$data['cartCount'] = $itemCount;
$data['subTotal'] = $subTotal;
$data['deliverCharge'] = 200;
$data['total'] = $subTotal + $data['deliverCharge'];
// process views
$this->load->view('templates/header', $headerData);
$this->load->view('pages/order', $data);
$this->load->view('templates/shopInformation');
$this->load->view('templates/footer');
return;
}
$headerData['pizzaPageTitle'] = 'Cart-[' . $itemCount . ']';
$headerData['cartCount'] = $itemCount;
// process views
$this->load->view('templates/header', $headerData);
$this->load->view('pages/cartempty');
$this->load->view('templates/shopInformation');
$this->load->view('templates/footer');
}
public function checkout()
{
$customerData = $data = array();
// Form field validation rules
$this->form_validation->set_rules('first-name', 'First Name', 'required');
$this->form_validation->set_rules('last-name', 'Last Name', 'required');
$this->form_validation->set_rules('mobile', 'Phone', 'required');
$this->form_validation->set_rules('address-line-one', 'Address Line One', 'required');
$this->form_validation->set_rules('city', 'City', 'required');
$this->form_validation->set_rules('region', 'Region', 'required');
// create customer data object with form data
$customerData = array(
'first_name' => strip_tags($this->input->post('first-name')),
'last_name' => strip_tags($this->input->post('last-name')),
'mobile' => strip_tags($this->input->post('mobile')),
'address' => strip_tags($this->input->post('address-line-one'))
. ' ' . strip_tags($this->input->post('address-line-two'))
. ' ' . strip_tags($this->input->post('city'))
. ' ' . strip_tags($this->input->post('region')),
'created' => date("Y-m-d H:i:s")
);
// order detail form validation process
if ($this->form_validation->run() == FALSE) {
$this->index();
} else {
// save customer data
$customerSaveResponse = $this->CustomerModel->saveCustomer($customerData);
// save response validate and save order data
if ($customerSaveResponse) {
// get cart data
$cartDataArray = $this->session->userdata('cartData');
// get cart item count
$itemCount = count($cartDataArray);
// check cart item data
// calculate subtotal and total
$subTotal = 0;
foreach ($cartDataArray as $cartItem) {
$subTotal += $cartItem->total;
}
$deliverCharge = 200;
$total = $subTotal + $deliverCharge;
// create order data object
$newOrdData = array(
'customer_id' => $customerSaveResponse,
'item_count' => $itemCount,
'sub_total' => $subTotal,
'deliver_charge' => $deliverCharge,
'total' => $total,
'created' => date("Y-m-d H:i:s")
);
$orderSaveResponse = $this->OrderModel->saveOrder($newOrdData);
// save response validate and save order item data
if ($orderSaveResponse) {
$newOrderDetailsData = array();
foreach ($cartDataArray as $cartItem) {
// create new item object
$newOrdItemData = array(
'order_id' => $orderSaveResponse,
'product_id' => $cartItem->id,
'title' => $cartItem->title,
'image' => $cartItem->image,
'cart_description' => $cartItem->cartDescription,
'quantity' => $cartItem->qty,
'price' => $cartItem->price,
'total' => $cartItem->total
);
// add new item data to list
array_push($newOrderDetailsData, $newOrdItemData);
}
// save new order items
$insertOrderItems = $this->OrderModel->saveOrderItemsBatch($newOrderDetailsData);
// reset user cart
$this->session->unset_userdata('cartData');
// set order id as new deliver
$this->session->set_userdata('deliverId', $orderSaveResponse);
// display deliver count down
redirect('delivery/' . $orderSaveResponse);
}
}
}
}
}
/*
$this->id = $id;
$this->image = $image;
$this->title = $title;
$this->cartDescription = $cartDescription;
$this->qty = $qty;
$this->price = $price;
$this->total = $total;
*/
class CartItem
{
public $id;
public $image;
public $title;
public $cartDescription;
public $qty;
public $price;
public $total;
public function __construct($id, $image, $title, $cartDescription, $qty, $price, $total)
{
$this->id = $id;
$this->image = $image;
$this->title = $title;
$this->cartDescription = $cartDescription;
$this->qty = $qty;
$this->price = $price;
$this->total = $total;
}
}
| 30.593023
| 89
| 0.63569
|
8752452a61f99c29967ae4e660a684ce1713099c
| 218
|
rb
|
Ruby
|
app/models/posts/paragraphs/comment.rb
|
harman28/parablogger
|
efead66943973daa411e8a6f94d8ffb883b7bf1c
|
[
"MIT"
] | null | null | null |
app/models/posts/paragraphs/comment.rb
|
harman28/parablogger
|
efead66943973daa411e8a6f94d8ffb883b7bf1c
|
[
"MIT"
] | null | null | null |
app/models/posts/paragraphs/comment.rb
|
harman28/parablogger
|
efead66943973daa411e8a6f94d8ffb883b7bf1c
|
[
"MIT"
] | null | null | null |
class Posts::Paragraphs::Comment < ActiveRecord::Base
belongs_to :paragraph, class_name: '::Posts::Paragraph', foreign_key: 'posts_paragraph_id', primary_key: 'id'
validates :posts_paragraph_id, presence: true
end
| 43.6
| 111
| 0.779817
|
f46ad946c4e21c3353cc7e2471e174370d606cc9
| 1,684
|
ts
|
TypeScript
|
src/index.ts
|
DIPSAS/ehrcraft-form-api
|
78b2e9bce061dfa33b5cbdfff2a3fac178a706dc
|
[
"MIT"
] | null | null | null |
src/index.ts
|
DIPSAS/ehrcraft-form-api
|
78b2e9bce061dfa33b5cbdfff2a3fac178a706dc
|
[
"MIT"
] | 1
|
2021-01-28T04:33:56.000Z
|
2021-01-28T04:36:37.000Z
|
src/index.ts
|
DIPSAS/ehrcraft-form-api
|
78b2e9bce061dfa33b5cbdfff2a3fac178a706dc
|
[
"MIT"
] | null | null | null |
import {openEHR} from './rm/rm-model';
import {API} from './api';
import {CTX} from './ctx';
import {HTTP} from './http';
import DvOrdinal = openEHR.RM.QuantityPackage.DvOrdinal;
import DvText = openEHR.RM.TextPackage.DvText;
import DvCodedText = openEHR.RM.TextPackage.DvCodedText;
import DvCodePhrase = openEHR.RM.TextPackage.DvCodePhrase;
import DvQuantity = openEHR.RM.QuantityPackage.DvQuantity;
import DvCount = openEHR.RM.QuantityPackage.DvCount;
import DvDate = openEHR.RM.DateTimePackage.DvDate;
import DvDateTime = openEHR.RM.DateTimePackage.DvDateTime;
import DvBoolean = openEHR.RM.BasicPackage.DvBoolean;
import DvDuration = openEHR.RM.DateTimePackage.DvDuration;
import DvInterval = openEHR.RM.QuantityPackage.DvInterval;
import DvEhrUri = openEHR.RM.UriPackage.DvEhrUri;
import DvUri = openEHR.RM.UriPackage.DvUri;
import DvParsable = openEHR.RM.EncapsulatedPackage.DvParsable;
import DvMultimedia = openEHR.RM.EncapsulatedPackage.DvMultimedia;
import DvTime = openEHR.RM.DateTimePackage.DvTime;
import DvProportion = openEHR.RM.QuantityPackage.DvProportion;
export {DvOrdinal as DvOrdinal}
export {DvText as DvText}
export {DvCodedText as DvCodedText}
export {DvCodePhrase as DvCodePhrase}
export {DvQuantity as DvQuantity}
export {DvBoolean as DvBoolean}
export {DvDate as DvDate}
export {DvDateTime as DvDateTime}
export {DvCount as DvCount}
export {DvDuration as DvDuration}
export {DvEhrUri as DvEhrUri}
export {DvInterval as DvInterval}
export {DvMultimedia as DvMultimedia}
export {DvParsable as DvParsable}
export {DvProportion as DvProportion}
export {DvTime as DvTime}
export {DvUri as DvUri}
export {API as API}
export {CTX as CTX}
export {HTTP as HTTP}
| 36.608696
| 66
| 0.808195
|
32d33d121c50136f5a5a606fe14bb4c5fd3426d1
| 2,201
|
sql
|
SQL
|
Funserver/Trinity Core/SQL/Crystal Bow-100007.sql
|
499453466/Lua-Other
|
43fd2b72405faf3f2074fd2a2706ef115d16faa6
|
[
"Unlicense"
] | 2
|
2015-06-23T16:26:32.000Z
|
2019-06-27T07:45:59.000Z
|
Funserver/Trinity Core/SQL/Crystal Bow-100007.sql
|
Eduardo-Silla/Lua-Other
|
db610f946dbcaf81b3de9801f758e11a7bf2753f
|
[
"Unlicense"
] | null | null | null |
Funserver/Trinity Core/SQL/Crystal Bow-100007.sql
|
Eduardo-Silla/Lua-Other
|
db610f946dbcaf81b3de9801f758e11a7bf2753f
|
[
"Unlicense"
] | 3
|
2015-01-10T18:22:59.000Z
|
2021-04-27T21:28:28.000Z
|
INSERT INTO item_template (entry, `class`, subclass, unk0, `name`, displayid, Quality, Flags, BuyCount, BuyPrice, SellPrice, InventoryType, AllowableClass, AllowableRace, ItemLevel, RequiredLevel, RequiredSkill, RequiredSkillRank, requiredspell, requiredhonorrank, RequiredCityRank, RequiredReputationFaction, RequiredReputationRank, maxcount, stackable, ContainerSlots, stat_type1, stat_value1, stat_type2, stat_value2, stat_type3, stat_value3, stat_type4, stat_value4, stat_type5, stat_value5, stat_type6, stat_value6, stat_type7, stat_value7, stat_type8, stat_value8, stat_type9, stat_value9, stat_type10, stat_value10, dmg_min1, dmg_max1, dmg_type1, dmg_min2, dmg_max2, dmg_type2, armor, holy_res, fire_res, nature_res, frost_res, shadow_res, arcane_res, delay, ammo_type, RangedModRange, spellid_1, spelltrigger_1, spellcharges_1, spellcooldown_1, spellcategory_1, spellcategorycooldown_1, spellid_2, spelltrigger_2, spellcharges_2, spellcooldown_2, spellcategory_2, spellcategorycooldown_2, spellid_3, spelltrigger_3, spellcharges_3, spellcooldown_3, spellcategory_3, spellcategorycooldown_3, spellid_4, spelltrigger_4, spellcharges_4, spellcooldown_4, spellcategory_4, spellcategorycooldown_4, spellid_5, spelltrigger_5, spellcharges_5, spellcooldown_5, spellcategory_5, spellcategorycooldown_5, bonding, description, PageText, LanguageID, PageMaterial, startquest, lockid, Material, sheath, RandomProperty, RandomSuffix, block, itemset, MaxDurability, area, Map, BagFamily, TotemCategory, socketColor_1, socketContent_1, socketColor_2, socketContent_2, socketColor_3, socketContent_3, socketBonus, GemProperties, RequiredDisenchantSkill, ArmorDamageModifier, ScriptName, DisenchantID, StatsCount)
VALUES (100007, 2, 2, -1, "Crystal Bow", 37524, 4, 0, 1, 2557342, 546365, 15, 4, -1, 145, 68, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 5, 5, 17, 41, 4, 45, 17, 46, 7, 35, 3, 38, 7, 15, 21, 14, 3, 47, 1, 980, 6486, 0, 654, 5748, 4, 100, 0, 46, 0, 62, 0, 0, 35, 0, 100, 17713, 1, 0, 0, 0, 0, 24585, 2, 0, 0, 0, 0, 14056, 1, 0, 0, 0, 0, 35898, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, "", 0, 0, 0, 0, 0, 1, 0, 0, 0, 100, 0, 78, 0, 0, 0, 0, 8, 0, 8, 0, 1, 0, 3303, 0, 0, 0, 'internalitemhanler', 0, 10);
| 1,100.5
| 1,704
| 0.763289
|
6317d509732020163ea2d55706f0e7d186aeb24d
| 269
|
lua
|
Lua
|
MMOCoreORB/bin/scripts/object/tangible/deed/city_deed/cityhall_naboo_03_deed.lua
|
V-Fib/FlurryClone
|
40e0ca7245ec31b3815eb6459329fd9e70f88936
|
[
"Zlib",
"OpenSSL"
] | 18
|
2017-02-09T15:36:05.000Z
|
2021-12-21T04:22:15.000Z
|
MMOCoreORB/bin/scripts/object/tangible/deed/city_deed/cityhall_naboo_03_deed.lua
|
V-Fib/FlurryClone
|
40e0ca7245ec31b3815eb6459329fd9e70f88936
|
[
"Zlib",
"OpenSSL"
] | 61
|
2016-12-30T21:51:10.000Z
|
2021-12-10T20:25:56.000Z
|
MMOCoreORB/bin/scripts/object/tangible/deed/city_deed/cityhall_naboo_03_deed.lua
|
V-Fib/FlurryClone
|
40e0ca7245ec31b3815eb6459329fd9e70f88936
|
[
"Zlib",
"OpenSSL"
] | 71
|
2017-01-01T05:34:38.000Z
|
2022-03-29T01:04:00.000Z
|
object_tangible_deed_city_deed_cityhall_naboo_03_deed = object_tangible_deed_city_deed_shared_cityhall_naboo_03_deed:new {
}
ObjectTemplates:addTemplate(object_tangible_deed_city_deed_cityhall_naboo_03_deed, "object/tangible/deed/city_deed/cityhall_naboo_03_deed.iff")
| 67.25
| 143
| 0.918216
|
3db8f5b3e6c3274c5e3a2cf7648fec21ee4a3f6c
| 1,029
|
dart
|
Dart
|
lib/view/bruteforce.dart
|
Manohar007/assignment
|
bffeacc22d4359f24407f215c41596fead58cc61
|
[
"MIT"
] | null | null | null |
lib/view/bruteforce.dart
|
Manohar007/assignment
|
bffeacc22d4359f24407f215c41596fead58cc61
|
[
"MIT"
] | null | null | null |
lib/view/bruteforce.dart
|
Manohar007/assignment
|
bffeacc22d4359f24407f215c41596fead58cc61
|
[
"MIT"
] | null | null | null |
import 'dart:math';
/// Estimates the strength of a password against a brute force attack.
/// The passwords length as well as the characters use are taken into
/// consideration.
double estimateBruteforceStrength(String password) {
if (password.isEmpty) return 0.0;
// Check which types of characters are used and create an opinionated bonus.
double charsetBonus;
if (RegExp(r'^[a-z]*$').hasMatch(password)) {
charsetBonus = 1.0;
} else if (RegExp(r'^[a-z0-9]*$').hasMatch(password)) {
charsetBonus = 1.2;
} else if (RegExp(r'^[a-zA-Z]*$').hasMatch(password)) {
charsetBonus = 1.3;
} else if (RegExp(r'^[a-z\-_!?]*$').hasMatch(password)) {
charsetBonus = 1.3;
} else if (RegExp(r'^[a-zA-Z0-9]*$').hasMatch(password)) {
charsetBonus = 1.5;
} else {
charsetBonus = 1.8;
}
final logisticFunction = (double x) {
return 1.0 / (1.0 + exp(-x));
};
final curve = (double x) {
return logisticFunction((x / 3.0) - 4.0);
};
return curve(password.length * charsetBonus);
}
| 29.4
| 78
| 0.638484
|
8c3423991ffa95f654ba13d43d5afc872a4ba158
| 1,018
|
dart
|
Dart
|
lib/main.dart
|
HYFRAK/SPS_ble
|
28e0335ddef22413d3d373506d8647bc4b9f476d
|
[
"MIT"
] | null | null | null |
lib/main.dart
|
HYFRAK/SPS_ble
|
28e0335ddef22413d3d373506d8647bc4b9f476d
|
[
"MIT"
] | null | null | null |
lib/main.dart
|
HYFRAK/SPS_ble
|
28e0335ddef22413d3d373506d8647bc4b9f476d
|
[
"MIT"
] | null | null | null |
import 'package:firebase_auth/firebase_auth.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:sps_ble/LANDING/login.dart';
import 'package:sps_ble/LANDING/profile.dart';
import 'package:sps_ble/LANDING/sports_select.dart';
import 'BLE/blehome.dart';
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
SystemChrome.setEnabledSystemUIMode(SystemUiMode.edgeToEdge);
SystemChrome.setSystemUIOverlayStyle(SystemUiOverlayStyle(
statusBarColor: Colors.transparent,
));
runApp(MyApp());
}
class MyApp extends StatelessWidget {
final auth1 = FirebaseAuth.instance;
MyApp({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: auth1.currentUser == null ? LoginPage() : SportSelect(),
);
}
}
| 29.941176
| 68
| 0.740668
|
f4abab5cc24d732d701a8f673add0a7abd312f28
| 232
|
tsx
|
TypeScript
|
src/components/utility/safe.area.component.tsx
|
islandhuynh/WhatsForLinner
|
6e26a414e1c09aa1feca6f04805e9834d6c9c450
|
[
"MIT"
] | 1
|
2021-04-06T02:52:23.000Z
|
2021-04-06T02:52:23.000Z
|
src/components/utility/safe.area.component.tsx
|
islandhuynh/WhatsForLinner
|
6e26a414e1c09aa1feca6f04805e9834d6c9c450
|
[
"MIT"
] | 1
|
2021-05-24T00:07:42.000Z
|
2021-05-24T00:07:42.000Z
|
src/components/utility/safe.area.component.tsx
|
islandhuynh/WhatsForLinner
|
6e26a414e1c09aa1feca6f04805e9834d6c9c450
|
[
"MIT"
] | null | null | null |
import { SafeAreaView, StatusBar } from "react-native";
import styled from 'styled-components';
export const SafeArea = styled(SafeAreaView)`
flex: 1;
${StatusBar.currentHeight && `margin-top: ${StatusBar.currentHeight}px;`}
`;
| 33.142857
| 75
| 0.737069
|
06eed773166c195e6fef5822c122e9bbd71d88e9
| 1,207
|
py
|
Python
|
purbeurre_project/settings/dev.py
|
etiennody/purbeurre-v2
|
cee10b5ad3ccee6535f197070cd4ee80f2bad5d0
|
[
"MIT"
] | null | null | null |
purbeurre_project/settings/dev.py
|
etiennody/purbeurre-v2
|
cee10b5ad3ccee6535f197070cd4ee80f2bad5d0
|
[
"MIT"
] | 3
|
2020-10-12T13:58:38.000Z
|
2020-11-12T01:02:14.000Z
|
purbeurre_project/settings/dev.py
|
etiennody/purbeurre-v2
|
cee10b5ad3ccee6535f197070cd4ee80f2bad5d0
|
[
"MIT"
] | 1
|
2021-02-03T18:49:31.000Z
|
2021-02-03T18:49:31.000Z
|
"""
Django settings for purbeurre_project project.
Generated by 'django-admin startproject' using Django 3.0.8.
For more information on this file, see
https://docs.djangoproject.com/en/3.0/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.0/ref/settings/
"""
import os
from .base import *
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = os.environ.get("PURBEURRE_SECRET_KEY", "idsqn%qsm!dfihzq@zml-fpvn9s_qdf")
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = ["localhost", "127.0.0.1"]
# Database
# https://docs.djangoproject.com/en/3.0/ref/settings/#databases
DATABASES = {
"default": {
"ENGINE": "django.db.backends.postgresql",
"NAME": os.environ.get("PURBEURRE_DBNAME", "purbeurre_dbname"),
"USER": os.environ.get("PURBEURRE_DBUSER", "purbeurre_dbuser"),
"PASSWORD": os.environ.get("PURBEURRE_DBPASSWD", "purbeurre_dbpasswd"),
"HOST": "localhost",
"PORT": 5432,
}
}
| 28.738095
| 86
| 0.714167
|
41f7372b427be2c002ba96989820c365320e6c2d
| 6,713
|
swift
|
Swift
|
ttt.swift
|
davidly/ttt
|
a1ae7327f587be752d92dbf32ba9aeaac793f584
|
[
"CC0-1.0"
] | null | null | null |
ttt.swift
|
davidly/ttt
|
a1ae7327f587be752d92dbf32ba9aeaac793f584
|
[
"CC0-1.0"
] | null | null | null |
ttt.swift
|
davidly/ttt
|
a1ae7327f587be752d92dbf32ba9aeaac793f584
|
[
"CC0-1.0"
] | null | null | null |
//
// main.swift
// sttt
//
// Created by David Lee on 1/30/21.
//
import Foundation
let SCORE_WIN = 6
let SCORE_TIE = 5
let SCORE_LOSE = 4
let SCORE_MAX = 9
let SCORE_MIN = 2
var g_moves = 0
enum Piece : UInt8 { case blank=0, X, O }
func winner_proc0(b : Board) -> Piece
{
let x = b.board[0];
if ( ( x == b.board[1] && x == b.board[2] ) ||
( x == b.board[3] && x == b.board[6] ) ||
( x == b.board[4] && x == b.board[8] ) )
{ return x }
return Piece.blank
}
func winner_proc1(b : Board) -> Piece
{
let x = b.board[1];
if ( ( x == b.board[0] && x == b.board[2] ) ||
( x == b.board[4] && x == b.board[7] ) )
{ return x }
return Piece.blank
}
func winner_proc2(b : Board) -> Piece
{
let x = b.board[2];
if ( ( x == b.board[0] && x == b.board[1] ) ||
( x == b.board[4] && x == b.board[6] ) ||
( x == b.board[5] && x == b.board[8] ) )
{ return x }
return Piece.blank
}
func winner_proc3(b : Board) -> Piece
{
let x = b.board[3];
if ( ( x == b.board[0] && x == b.board[6] ) ||
( x == b.board[4] && x == b.board[5] ) )
{ return x }
return Piece.blank
}
func winner_proc4(b : Board) -> Piece
{
let x = b.board[4];
if ( ( x == b.board[0] && x == b.board[8] ) ||
( x == b.board[2] && x == b.board[6] ) ||
( x == b.board[1] && x == b.board[7] ) ||
( x == b.board[3] && x == b.board[5] ) )
{ return x }
return Piece.blank
}
func winner_proc5(b : Board) -> Piece
{
let x = b.board[5];
if ( ( x == b.board[2] && x == b.board[8] ) ||
( x == b.board[3] && x == b.board[4] ) )
{ return x }
return Piece.blank
}
func winner_proc6(b : Board) -> Piece
{
let x = b.board[6];
if ( ( x == b.board[0] && x == b.board[3] ) ||
( x == b.board[2] && x == b.board[4] ) ||
( x == b.board[7] && x == b.board[8] ) )
{ return x }
return Piece.blank
}
func winner_proc7(b : Board) -> Piece
{
let x = b.board[7];
if ( ( x == b.board[1] && x == b.board[4] ) ||
( x == b.board[6] && x == b.board[8] ) )
{ return x }
return Piece.blank
}
func winner_proc8(b : Board) -> Piece
{
let x = b.board[8];
if ( ( x == b.board[2] && x == b.board[5] ) ||
( x == b.board[6] && x == b.board[7] ) ||
( x == b.board[0] && x == b.board[4] ) )
{ return x }
return Piece.blank
}
var winner_funcs: Array<(Board) -> Piece> =
[
winner_proc0,
winner_proc1,
winner_proc2,
winner_proc3,
winner_proc4,
winner_proc5,
winner_proc6,
winner_proc7,
winner_proc8
]
class Board
{
var board: [Piece] = [ Piece.blank, Piece.blank, Piece.blank,
Piece.blank, Piece.blank, Piece.blank,
Piece.blank, Piece.blank, Piece.blank ]
func Print() -> Void
{
print( board[0], board[1], board[2],
board[3], board[4], board[5],
board[6], board[7], board[8] )
}
func LookForWinner() -> Piece
{
var p = board[0]
if ( Piece.blank != p)
{
if ( p == board[1] && p == board[2] ) { return p }
if ( p == board[3] && p == board[6] ) { return p }
}
p = board[3]
if ( Piece.blank != p && p == board[4] && p == board[5]) { return p }
p = board[6]
if ( Piece.blank != p && p == board[7] && p == board[8]) { return p }
p = board[1]
if ( Piece.blank != p && p == board[4] && p == board[7]) { return p }
p = board[2]
if ( Piece.blank != p && p == board[5] && p == board[8]) { return p }
p = board[4]
if ( Piece.blank != p)
{
if ( p == board[0] && p == board[8] ) { return p }
if ( p == board[2] && p == board[6] ) { return p }
}
return Piece.blank
}
}
func Max( x : Int, y : Int) -> Int
{
if ( x > y) { return x }
return y
}
func Min( x: Int, y : Int) -> Int
{
if ( x < y ) { return x }
return y
}
func MinMax( b : Board, alpha : Int, beta : Int, depth : Int, pos : Int) -> Int
{
//print( " alpha ", alpha, " beta ", beta, " depth ", depth )
//b.Print()
g_moves += 1
if ( depth >= 4 )
{
// The function table is SLOWER in Swift (2.7 vs 2.2 seconds); significantly faster in C++
//let p2 : Piece = winner_funcs[ pos ](b)
let p : Piece = b.LookForWinner()
/*
if ( p2 != p)
{
print( "p ", p, " p2 ", p2, " pos ", pos)
b.Print()
exit(1)
}
*/
if ( Piece.X == p) { return SCORE_WIN }
if ( Piece.O == p) { return SCORE_LOSE }
if ( 8 == depth ) { return SCORE_TIE }
}
var localAlpha = alpha
var localBeta = beta
var value : Int
var pieceMove : Piece
if ( 0 != ( depth & 1 ) )
{
value = SCORE_MIN
pieceMove = Piece.X
}
else
{
value = SCORE_MAX
pieceMove = Piece.O
}
for x in 0...8
{
if ( Piece.blank == b.board[x])
{
b.board[x] = pieceMove
let score = MinMax( b: b, alpha: localAlpha, beta: localBeta, depth: depth + 1, pos: x )
b.board[x] = Piece.blank
if ( 0 != ( depth & 1 ) )
{
value = Max( x: value, y: score )
localAlpha = Max( x: localAlpha, y: value )
if ( localAlpha >= localBeta ) { return value } // alpha pruning
if ( SCORE_WIN == value) { return SCORE_WIN }
}
else
{
value = Min( x: value, y: score )
localBeta = Min( x: value, y: localBeta )
if ( localBeta <= localAlpha ) { return value } // beta pruning
if ( SCORE_LOSE == value) { return SCORE_LOSE }
}
}
}
return value
}
func main()
{
let b1 = Board()
b1.board[0] = Piece.X
let b2 = Board()
b2.board[1] = Piece.X
let b3 = Board()
b3.board[4] = Piece.X
var score1 = 0
var score2 = 0
var score3 = 0
for _ in 1...10000
{
score1 = MinMax( b: b1, alpha: SCORE_MIN, beta: SCORE_MAX, depth: 0, pos: 0)
score2 = MinMax( b: b2, alpha: SCORE_MIN, beta: SCORE_MAX, depth: 0, pos: 1)
score3 = MinMax( b: b3, alpha: SCORE_MIN, beta: SCORE_MAX, depth: 0, pos: 4)
}
print("moves: ", g_moves, " scores: ", score1, score2, score3)
}
main()
| 23.720848
| 100
| 0.448384
|
02442b85e4333538bb47ec156a3b13b5b764ea96
| 4,625
|
h
|
C
|
dali/internal/graphics/gles-impl/gles-framebuffer-state-cache.h
|
dalihub/dali-adaptor
|
b7943ae5aeb7ddd069be7496a1c1cee186b740c5
|
[
"Apache-2.0",
"BSD-3-Clause"
] | 6
|
2016-11-18T10:26:46.000Z
|
2021-11-01T12:29:05.000Z
|
dali/internal/graphics/gles-impl/gles-framebuffer-state-cache.h
|
dalihub/dali-adaptor
|
b7943ae5aeb7ddd069be7496a1c1cee186b740c5
|
[
"Apache-2.0",
"BSD-3-Clause"
] | 5
|
2020-07-15T11:30:49.000Z
|
2020-12-11T19:13:46.000Z
|
dali/internal/graphics/gles-impl/gles-framebuffer-state-cache.h
|
dalihub/dali-adaptor
|
b7943ae5aeb7ddd069be7496a1c1cee186b740c5
|
[
"Apache-2.0",
"BSD-3-Clause"
] | 7
|
2019-05-17T07:14:40.000Z
|
2021-05-24T07:25:26.000Z
|
#ifndef DALI_GRAPHICS_GLES_CONTEXT_FRAMEBUFFER_STATE_CACHE_H
#define DALI_GRAPHICS_GLES_CONTEXT_FRAMEBUFFER_STATE_CACHE_H
/*
* Copyright (c) 2021 Samsung Electronics Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
// INTERNAL INCLUDES
#include <dali/integration-api/gl-abstraction.h>
#include <dali/public-api/common/dali-vector.h>
namespace Dali::Graphics
{
namespace GLES
{
/**
* @brief Keeps track of color, depth and stencil buffer state within each frame buffer.
* Used to avoid redundant glClear calls.
*
*/
class FrameBufferStateCache
{
public:
/**
* @brief Constructor
*/
FrameBufferStateCache();
/**
* @brief non-virtual destructor
*/
~FrameBufferStateCache();
/**
* @brief Get the bitmask to pass to glClear based on the mask requested
* and the current state of the frame buffer
* @param[in] mask glClear bit mask
* @param[in] forceClear whether to force the clear ( ignore cached state)
* @param[in] scissorTestEnabled whether scissor test is enabled
* @return new bitmask to pass to glClear
*/
GLbitfield GetClearMask(GLbitfield mask, bool forceClear, bool scissorTestEnabled);
/**
* @brief Set the current bound frame buffer
* @param[in] frameBufferId frame buffer id
*/
void SetCurrentFrameBuffer(GLuint frameBufferId);
/**
* @brief Called when frame buffers are deleted
* @param[in] count number of frame buffers
* @param[in] framebuffers array of frame buffer ids
*/
void FrameBuffersDeleted(GLsizei count, const GLuint* const frameBuffers);
/**
* @brief Called when frame buffers are created
* @param[in] count number of frame buffers
* @param[in] framebuffers array of frame buffer ids
*/
void FrameBuffersCreated(GLsizei count, const GLuint* const frameBuffers);
/**
* @brief Draw operation performed on the current frame buffer
* @param[in] colorBufferUsed whether the color buffer is being written to (glColorMask )
* @param[in] depthBufferUsed whether the depth buffer is being written to (glDepthMask )
* @param[in] stencilBufferUsed whether the stencil buffer is being written to (glStencilMask )
*/
void DrawOperation(bool colorBufferUsed, bool depthBufferUsed, bool stencilBufferUsed);
/**
* Reset the cache
*/
void Reset();
private:
/**
* Current status of the frame buffer
*/
enum FrameBufferStatus
{
COLOR_BUFFER_CLEAN = 1 << 0, ///< color buffer clean
DEPTH_BUFFER_CLEAN = 1 << 1, ///< depth buffer clean
STENCIL_BUFFER_CLEAN = 1 << 2, ///< stencil buffer clean
};
/**
* POD to store the status of frame buffer regarding color,depth and stencil buffers
*/
struct FrameBufferState
{
/**
* Constructor
*/
FrameBufferState(GLuint id)
: mId(id),
mState(0)
{
}
GLuint mId; ///< Frame buffer id
unsigned int mState; ///< State, bitmask of FrameBufferStatus flags
};
using FrameBufferStateVector = Dali::Vector<FrameBufferState>;
/**
* @brief Set the clear state
* @param[in] pointer to frame buffer state object
* @param[in] mask clear mask
*/
void SetClearState(FrameBufferState* state, GLbitfield mask);
/**
* @brief Helper
* @param[in] frameBufferId frame buffer id
* @return pointer to frame buffer state object ( NULL if it doesn't exist)
*/
FrameBufferState* GetFrameBufferState(GLuint frameBufferId);
/**
* @brief Helper to delete a frame buffer state object
* @param[in] frameBufferId frame buffer id
*/
void DeleteFrameBuffer(GLuint frameBufferId);
FrameBufferStateCache(const FrameBufferStateCache&); ///< undefined copy constructor
FrameBufferStateCache& operator=(const FrameBufferStateCache&); ///< undefined assignment operator
private: // data
FrameBufferStateVector mFrameBufferStates{}; ///< state of the frame buffers
GLuint mCurrentFrameBufferId{0}; ///< currently bound frame buffer
};
} // namespace GLES
} // namespace Dali::Graphics
#endif // DALI_GRAPHICS_GLES_CONTEXT_FRAMEBUFFER_STATE_CACHE_H
| 30.032468
| 100
| 0.704865
|
63aa6815f5bf91b0ba275cc91bef28eb7362dfe1
| 27,679
|
rs
|
Rust
|
src/row.rs
|
tachiniererin/duckdb-rs
|
3e78ad46d8a949b55291536c55ae484af82c8392
|
[
"MIT"
] | null | null | null |
src/row.rs
|
tachiniererin/duckdb-rs
|
3e78ad46d8a949b55291536c55ae484af82c8392
|
[
"MIT"
] | null | null | null |
src/row.rs
|
tachiniererin/duckdb-rs
|
3e78ad46d8a949b55291536c55ae484af82c8392
|
[
"MIT"
] | null | null | null |
use std::convert;
use std::sync::Arc;
use super::{Error, Result, Statement};
use crate::types::{self, FromSql, FromSqlError, ValueRef};
use arrow::array::{self, Array, StructArray};
use arrow::datatypes::*;
use fallible_iterator::FallibleIterator;
use fallible_streaming_iterator::FallibleStreamingIterator;
use rust_decimal::prelude::*;
/// An handle for the resulting rows of a query.
#[must_use = "Rows is lazy and will do nothing unless consumed"]
pub struct Rows<'stmt> {
pub(crate) stmt: Option<&'stmt Statement<'stmt>>,
arr: Arc<Option<StructArray>>,
row: Option<Row<'stmt>>,
current_row: usize,
current_batch_row: usize,
}
impl<'stmt> Rows<'stmt> {
#[inline]
fn reset(&mut self) {
self.current_row = 0;
self.current_batch_row = 0;
self.arr = Arc::new(None);
}
/// Attempt to get the next row from the query. Returns `Ok(Some(Row))` if
/// there is another row, `Err(...)` if there was an error
/// getting the next row, and `Ok(None)` if all rows have been retrieved.
///
/// ## Note
///
/// This interface is not compatible with Rust's `Iterator` trait, because
/// the lifetime of the returned row is tied to the lifetime of `self`.
/// This is a fallible "streaming iterator". For a more natural interface,
/// consider using [`query_map`](crate::Statement::query_map) or
/// [`query_and_then`](crate::Statement::query_and_then) instead, which
/// return types that implement `Iterator`.
#[allow(clippy::should_implement_trait)] // cannot implement Iterator
#[inline]
pub fn next(&mut self) -> Result<Option<&Row<'stmt>>> {
self.advance()?;
Ok((*self).get())
}
#[inline]
fn batch_row_count(&self) -> usize {
if self.arr.is_none() {
return 0;
}
self.arr.as_ref().as_ref().unwrap().len()
}
/// Map over this `Rows`, converting it to a [`Map`], which
/// implements `FallibleIterator`.
/// ```rust,no_run
/// use fallible_iterator::FallibleIterator;
/// # use duckdb::{Result, Statement};
/// fn query(stmt: &mut Statement) -> Result<Vec<i64>> {
/// let rows = stmt.query([])?;
/// rows.map(|r| r.get(0)).collect()
/// }
/// ```
// FIXME Hide FallibleStreamingIterator::map
#[inline]
pub fn map<F, B>(self, f: F) -> Map<'stmt, F>
where
F: FnMut(&Row<'_>) -> Result<B>,
{
Map { rows: self, f }
}
/// Map over this `Rows`, converting it to a [`MappedRows`], which
/// implements `Iterator`.
#[inline]
pub fn mapped<F, B>(self, f: F) -> MappedRows<'stmt, F>
where
F: FnMut(&Row<'_>) -> Result<B>,
{
MappedRows { rows: self, map: f }
}
/// Map over this `Rows` with a fallible function, converting it to a
/// [`AndThenRows`], which implements `Iterator` (instead of
/// `FallibleStreamingIterator`).
#[inline]
pub fn and_then<F, T, E>(self, f: F) -> AndThenRows<'stmt, F>
where
F: FnMut(&Row<'_>) -> Result<T, E>,
{
AndThenRows { rows: self, map: f }
}
/// Give access to the underlying statement
pub fn as_ref(&self) -> Option<&Statement<'stmt>> {
self.stmt
}
}
impl<'stmt> Rows<'stmt> {
#[inline]
pub(crate) fn new(stmt: &'stmt Statement<'stmt>) -> Rows<'stmt> {
Rows {
stmt: Some(stmt),
arr: Arc::new(None),
row: None,
current_row: 0,
current_batch_row: 0,
}
}
#[inline]
pub(crate) fn get_expected_row(&mut self) -> Result<&Row<'stmt>> {
match self.next()? {
Some(row) => Ok(row),
None => Err(Error::QueryReturnedNoRows),
}
}
}
/// `F` is used to transform the _streaming_ iterator into a _fallible_
/// iterator.
#[must_use = "iterators are lazy and do nothing unless consumed"]
pub struct Map<'stmt, F> {
rows: Rows<'stmt>,
f: F,
}
impl<F, B> FallibleIterator for Map<'_, F>
where
F: FnMut(&Row<'_>) -> Result<B>,
{
type Error = Error;
type Item = B;
#[inline]
fn next(&mut self) -> Result<Option<B>> {
match self.rows.next()? {
Some(v) => Ok(Some((self.f)(v)?)),
None => Ok(None),
}
}
}
/// An iterator over the mapped resulting rows of a query.
///
/// `F` is used to transform the _streaming_ iterator into a _standard_
/// iterator.
#[must_use = "iterators are lazy and do nothing unless consumed"]
pub struct MappedRows<'stmt, F> {
rows: Rows<'stmt>,
map: F,
}
impl<T, F> Iterator for MappedRows<'_, F>
where
F: FnMut(&Row<'_>) -> Result<T>,
{
type Item = Result<T>;
#[inline]
fn next(&mut self) -> Option<Result<T>> {
let map = &mut self.map;
self.rows
.next()
.transpose()
.map(|row_result| row_result.and_then(|row| (map)(row)))
}
}
/// An iterator over the mapped resulting rows of a query, with an Error type
/// unifying with Error.
#[must_use = "iterators are lazy and do nothing unless consumed"]
pub struct AndThenRows<'stmt, F> {
rows: Rows<'stmt>,
map: F,
}
impl<T, E, F> Iterator for AndThenRows<'_, F>
where
E: convert::From<Error>,
F: FnMut(&Row<'_>) -> Result<T, E>,
{
type Item = Result<T, E>;
#[inline]
fn next(&mut self) -> Option<Self::Item> {
let map = &mut self.map;
self.rows
.next()
.transpose()
.map(|row_result| row_result.map_err(E::from).and_then(|row| (map)(row)))
}
}
/// `FallibleStreamingIterator` differs from the standard library's `Iterator`
/// in two ways:
/// * each call to `next` (sqlite3_step) can fail.
/// * returned `Row` is valid until `next` is called again or `Statement` is
/// reset or finalized.
///
/// While these iterators cannot be used with Rust `for` loops, `while let`
/// loops offer a similar level of ergonomics:
/// ```rust,no_run
/// # use duckdb::{Result, Statement};
/// fn query(stmt: &mut Statement) -> Result<()> {
/// let mut rows = stmt.query([])?;
/// while let Some(row) = rows.next()? {
/// // scan columns value
/// }
/// Ok(())
/// }
/// ```
impl<'stmt> FallibleStreamingIterator for Rows<'stmt> {
type Error = Error;
type Item = Row<'stmt>;
#[inline]
fn advance(&mut self) -> Result<()> {
match self.stmt {
Some(stmt) => {
if self.current_row < stmt.row_count() {
if self.current_batch_row >= self.batch_row_count() {
self.arr = Arc::new(stmt.step());
if self.arr.is_none() {
self.row = None;
return Ok(());
}
self.current_batch_row = 0;
}
self.row = Some(Row {
stmt,
arr: self.arr.clone(),
current_row: self.current_batch_row,
});
self.current_row += 1;
self.current_batch_row += 1;
Ok(())
} else {
self.reset();
self.row = None;
Ok(())
}
}
None => {
self.row = None;
Ok(())
}
}
}
#[inline]
fn get(&self) -> Option<&Row<'stmt>> {
self.row.as_ref()
}
}
/// A single result row of a query.
pub struct Row<'stmt> {
pub(crate) stmt: &'stmt Statement<'stmt>,
arr: Arc<Option<StructArray>>,
current_row: usize,
}
impl<'stmt> Row<'stmt> {
/// Get the value of a particular column of the result row.
///
/// ## Failure
///
/// Panics if calling [`row.get(idx)`](Row::get) would return an error,
/// including:
///
/// * If the underlying DuckDB column type is not a valid type as a source
/// for `T`
/// * If the underlying DuckDB integral value is outside the range
/// representable by `T`
/// * If `idx` is outside the range of columns in the returned query
pub fn get_unwrap<I: RowIndex, T: FromSql>(&self, idx: I) -> T {
self.get(idx).unwrap()
}
/// Get the value of a particular column of the result row.
///
/// ## Failure
///
/// Returns an `Error::InvalidColumnType` if the underlying DuckDB column
/// type is not a valid type as a source for `T`.
///
/// Returns an `Error::InvalidColumnIndex` if `idx` is outside the valid
/// column range for this row.
///
/// Returns an `Error::InvalidColumnName` if `idx` is not a valid column
/// name for this row.
///
/// If the result type is i128 (which requires the `i128_blob` feature to be
/// enabled), and the underlying DuckDB column is a blob whose size is not
/// 16 bytes, `Error::InvalidColumnType` will also be returned.
pub fn get<I: RowIndex, T: FromSql>(&self, idx: I) -> Result<T> {
let idx = idx.idx(self.stmt)?;
let value = self.value_ref(self.current_row, idx);
FromSql::column_result(value).map_err(|err| match err {
FromSqlError::InvalidType => {
Error::InvalidColumnType(idx, self.stmt.column_name_unwrap(idx).into(), value.data_type())
}
FromSqlError::OutOfRange(i) => Error::IntegralValueOutOfRange(idx, i),
FromSqlError::Other(err) => Error::FromSqlConversionFailure(idx as usize, value.data_type(), err),
#[cfg(feature = "uuid")]
FromSqlError::InvalidUuidSize(_) => {
Error::InvalidColumnType(idx, self.stmt.column_name_unwrap(idx).into(), value.data_type())
}
})
}
/// Get the value of a particular column of the result row as a `ValueRef`,
/// allowing data to be read out of a row without copying.
///
/// This `ValueRef` is valid only as long as this Row, which is enforced by
/// it's lifetime. This means that while this method is completely safe,
/// it can be somewhat difficult to use, and most callers will be better
/// served by [`get`](Row::get) or [`get_unwrap`](Row::get_unwrap).
///
/// ## Failure
///
/// Returns an `Error::InvalidColumnIndex` if `idx` is outside the valid
/// column range for this row.
///
/// Returns an `Error::InvalidColumnName` if `idx` is not a valid column
/// name for this row.
pub fn get_ref<I: RowIndex>(&self, idx: I) -> Result<ValueRef<'_>> {
let idx = idx.idx(self.stmt)?;
// Narrowing from `ValueRef<'stmt>` (which `self.stmt.value_ref(idx)`
// returns) to `ValueRef<'a>` is needed because it's only valid until
// the next call to sqlite3_step.
let val_ref = self.value_ref(self.current_row, idx);
Ok(val_ref)
}
fn value_ref(&self, row: usize, col: usize) -> ValueRef<'_> {
let column = self.arr.as_ref().as_ref().unwrap().column(col);
if column.is_null(row) {
return ValueRef::Null;
}
// duckdb.cpp SetArrowFormat
// https://github.com/duckdb/duckdb/blob/71f1c7a7e4b8737cff5e78d1f090c54f5e78e17b/src/main/query_result.cpp#L148
match column.data_type() {
DataType::Utf8 => {
let array = column.as_any().downcast_ref::<array::StringArray>().unwrap();
if array.is_null(row) {
return ValueRef::Null;
}
ValueRef::from(array.value(row))
}
DataType::LargeUtf8 => {
let array = column.as_any().downcast_ref::<array::LargeStringArray>().unwrap();
if array.is_null(row) {
return ValueRef::Null;
}
ValueRef::from(array.value(row))
}
DataType::Binary => {
let array = column.as_any().downcast_ref::<array::BinaryArray>().unwrap();
if array.is_null(row) {
return ValueRef::Null;
}
ValueRef::Blob(array.value(row))
}
DataType::LargeBinary => {
let array = column.as_any().downcast_ref::<array::LargeBinaryArray>().unwrap();
if array.is_null(row) {
return ValueRef::Null;
}
ValueRef::Blob(array.value(row))
}
DataType::Boolean => {
let array = column.as_any().downcast_ref::<array::BooleanArray>().unwrap();
if array.is_null(row) {
return ValueRef::Null;
}
ValueRef::Boolean(array.value(row))
}
DataType::Int8 => {
let array = column.as_any().downcast_ref::<array::Int8Array>().unwrap();
if array.is_null(row) {
return ValueRef::Null;
}
ValueRef::TinyInt(array.value(row))
}
DataType::Int16 => {
let array = column.as_any().downcast_ref::<array::Int16Array>().unwrap();
if array.is_null(row) {
return ValueRef::Null;
}
ValueRef::SmallInt(array.value(row))
}
DataType::Int32 => {
let array = column.as_any().downcast_ref::<array::Int32Array>().unwrap();
if array.is_null(row) {
return ValueRef::Null;
}
ValueRef::Int(array.value(row))
}
DataType::Int64 => {
let array = column.as_any().downcast_ref::<array::Int64Array>().unwrap();
if array.is_null(row) {
return ValueRef::Null;
}
ValueRef::BigInt(array.value(row))
}
DataType::UInt8 => {
let array = column.as_any().downcast_ref::<array::UInt8Array>().unwrap();
if array.is_null(row) {
return ValueRef::Null;
}
ValueRef::UTinyInt(array.value(row))
}
DataType::UInt16 => {
let array = column.as_any().downcast_ref::<array::UInt16Array>().unwrap();
if array.is_null(row) {
return ValueRef::Null;
}
ValueRef::USmallInt(array.value(row))
}
DataType::UInt32 => {
let array = column.as_any().downcast_ref::<array::UInt32Array>().unwrap();
if array.is_null(row) {
return ValueRef::Null;
}
ValueRef::UInt(array.value(row))
}
DataType::UInt64 => {
let array = column.as_any().downcast_ref::<array::UInt64Array>().unwrap();
if array.is_null(row) {
return ValueRef::Null;
}
ValueRef::UBigInt(array.value(row))
}
DataType::Float16 => {
let array = column.as_any().downcast_ref::<array::Float32Array>().unwrap();
if array.is_null(row) {
return ValueRef::Null;
}
ValueRef::Float(array.value(row))
}
DataType::Float32 => {
let array = column.as_any().downcast_ref::<array::Float32Array>().unwrap();
if array.is_null(row) {
return ValueRef::Null;
}
ValueRef::Float(array.value(row))
}
DataType::Float64 => {
let array = column.as_any().downcast_ref::<array::Float64Array>().unwrap();
if array.is_null(row) {
return ValueRef::Null;
}
ValueRef::Double(array.value(row))
}
DataType::Decimal(..) => {
let array = column.as_any().downcast_ref::<array::DecimalArray>().unwrap();
if array.is_null(row) {
return ValueRef::Null;
}
// hugeint: d:38,0
if array.scale() == 0 {
return ValueRef::HugeInt(array.value(row));
}
ValueRef::Decimal(Decimal::from_i128_with_scale(array.value(row), array.scale() as u32))
}
DataType::Timestamp(unit, _) if *unit == TimeUnit::Second => {
let array = column.as_any().downcast_ref::<array::TimestampSecondArray>().unwrap();
if array.is_null(row) {
return ValueRef::Null;
}
ValueRef::Timestamp(types::TimeUnit::Second, array.value(row))
}
DataType::Timestamp(unit, _) if *unit == TimeUnit::Millisecond => {
let array = column
.as_any()
.downcast_ref::<array::TimestampMillisecondArray>()
.unwrap();
if array.is_null(row) {
return ValueRef::Null;
}
ValueRef::Timestamp(types::TimeUnit::Millisecond, array.value(row))
}
DataType::Timestamp(unit, _) if *unit == TimeUnit::Microsecond => {
let array = column
.as_any()
.downcast_ref::<array::TimestampMicrosecondArray>()
.unwrap();
if array.is_null(row) {
return ValueRef::Null;
}
ValueRef::Timestamp(types::TimeUnit::Microsecond, array.value(row))
}
DataType::Timestamp(unit, _) if *unit == TimeUnit::Nanosecond => {
let array = column
.as_any()
.downcast_ref::<array::TimestampNanosecondArray>()
.unwrap();
if array.is_null(row) {
return ValueRef::Null;
}
ValueRef::Timestamp(types::TimeUnit::Nanosecond, array.value(row))
}
DataType::Date32 => {
let array = column.as_any().downcast_ref::<array::Date32Array>().unwrap();
if array.is_null(row) {
return ValueRef::Null;
}
ValueRef::Date32(array.value(row))
}
DataType::Time64(TimeUnit::Microsecond) => {
let array = column.as_any().downcast_ref::<array::Time64MicrosecondArray>().unwrap();
if array.is_null(row) {
return ValueRef::Null;
}
ValueRef::Time64(types::TimeUnit::Microsecond, array.value(row))
}
// TODO: support more data types
// DataType::Interval(unit) => match unit {
// IntervalUnit::DayTime => {
// make_string_interval_day_time!(column, row)
// }
// IntervalUnit::YearMonth => {
// make_string_interval_year_month!(column, row)
// }
// },
// DataType::List(_) => make_string_from_list!(column, row),
// DataType::Dictionary(index_type, _value_type) => match **index_type {
// DataType::Int8 => dict_array_value_to_string::<Int8Type>(column, row),
// DataType::Int16 => dict_array_value_to_string::<Int16Type>(column, row),
// DataType::Int32 => dict_array_value_to_string::<Int32Type>(column, row),
// DataType::Int64 => dict_array_value_to_string::<Int64Type>(column, row),
// DataType::UInt8 => dict_array_value_to_string::<UInt8Type>(column, row),
// DataType::UInt16 => dict_array_value_to_string::<UInt16Type>(column, row),
// DataType::UInt32 => dict_array_value_to_string::<UInt32Type>(column, row),
// DataType::UInt64 => dict_array_value_to_string::<UInt64Type>(column, row),
// _ => Err(ArrowError::InvalidArgumentError(format!(
// "Pretty printing not supported for {:?} due to index type",
// column.data_type()
// ))),
// },
// NOTE: DataTypes not supported by duckdb
// DataType::Date64 => make_string_date!(array::Date64Array, column, row),
// DataType::Time32(unit) if *unit == TimeUnit::Second => {
// make_string_time!(array::Time32SecondArray, column, row)
// }
// DataType::Time32(unit) if *unit == TimeUnit::Millisecond => {
// make_string_time!(array::Time32MillisecondArray, column, row)
// }
// DataType::Time64(unit) if *unit == TimeUnit::Nanosecond => {
// make_string_time!(array::Time64NanosecondArray, column, row)
// }
_ => unreachable!("invalid value: {}, {}", col, self.stmt.column_type(col)),
}
}
/// Get the value of a particular column of the result row as a `ValueRef`,
/// allowing data to be read out of a row without copying.
///
/// This `ValueRef` is valid only as long as this Row, which is enforced by
/// it's lifetime. This means that while this method is completely safe,
/// it can be difficult to use, and most callers will be better served by
/// [`get`](Row::get) or [`get_unwrap`](Row::get_unwrap).
///
/// ## Failure
///
/// Panics if calling [`row.get_ref(idx)`](Row::get_ref) would return an
/// error, including:
///
/// * If `idx` is outside the range of columns in the returned query.
/// * If `idx` is not a valid column name for this row.
pub fn get_ref_unwrap<I: RowIndex>(&self, idx: I) -> ValueRef<'_> {
self.get_ref(idx).unwrap()
}
}
impl<'stmt> AsRef<Statement<'stmt>> for Row<'stmt> {
fn as_ref(&self) -> &Statement<'stmt> {
self.stmt
}
}
mod sealed {
/// This trait exists just to ensure that the only impls of `trait Params`
/// that are allowed are ones in this crate.
pub trait Sealed {}
impl Sealed for usize {}
impl Sealed for &str {}
}
/// A trait implemented by types that can index into columns of a row.
///
/// It is only implemented for `usize` and `&str`.
pub trait RowIndex: sealed::Sealed {
/// Returns the index of the appropriate column, or `None` if no such
/// column exists.
fn idx(&self, stmt: &Statement<'_>) -> Result<usize>;
}
impl RowIndex for usize {
#[inline]
fn idx(&self, stmt: &Statement<'_>) -> Result<usize> {
if *self >= stmt.column_count() {
Err(Error::InvalidColumnIndex(*self))
} else {
Ok(*self)
}
}
}
impl RowIndex for &'_ str {
#[inline]
fn idx(&self, stmt: &Statement<'_>) -> Result<usize> {
stmt.column_index(*self)
}
}
macro_rules! tuple_try_from_row {
($($field:ident),*) => {
impl<'a, $($field,)*> convert::TryFrom<&'a Row<'a>> for ($($field,)*) where $($field: FromSql,)* {
type Error = crate::Error;
// we end with index += 1, which rustc warns about
// unused_variables and unused_mut are allowed for ()
#[allow(unused_assignments, unused_variables, unused_mut)]
fn try_from(row: &'a Row<'a>) -> Result<Self> {
let mut index = 0;
$(
#[allow(non_snake_case)]
let $field = row.get::<_, $field>(index)?;
index += 1;
)*
Ok(($($field,)*))
}
}
}
}
macro_rules! tuples_try_from_row {
() => {
// not very useful, but maybe some other macro users will find this helpful
tuple_try_from_row!();
};
($first:ident $(, $remaining:ident)*) => {
tuple_try_from_row!($first $(, $remaining)*);
tuples_try_from_row!($($remaining),*);
};
}
tuples_try_from_row!(A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P);
#[cfg(test)]
mod tests {
#![allow(clippy::redundant_closure)] // false positives due to lifetime issues; clippy issue #5594
use crate::{Connection, Result};
#[test]
fn test_try_from_row_for_tuple_1() -> Result<()> {
use crate::ToSql;
use std::convert::TryFrom;
let conn = Connection::open_in_memory()?;
conn.execute(
"CREATE TABLE test (a INTEGER)",
crate::params_from_iter(std::iter::empty::<&dyn ToSql>()),
)?;
conn.execute("INSERT INTO test VALUES (42)", [])?;
let val = conn.query_row("SELECT a FROM test", [], |row| <(u32,)>::try_from(row))?;
assert_eq!(val, (42,));
let fail = conn.query_row("SELECT a FROM test", [], |row| <(u32, u32)>::try_from(row));
assert!(fail.is_err());
Ok(())
}
#[test]
fn test_try_from_row_for_tuple_2() -> Result<()> {
use std::convert::TryFrom;
let conn = Connection::open_in_memory()?;
conn.execute("CREATE TABLE test (a INTEGER, b INTEGER)", [])?;
conn.execute("INSERT INTO test VALUES (42, 47)", [])?;
let val = conn.query_row("SELECT a, b FROM test", [], |row| <(u32, u32)>::try_from(row))?;
assert_eq!(val, (42, 47));
let fail = conn.query_row("SELECT a, b FROM test", [], |row| <(u32, u32, u32)>::try_from(row));
assert!(fail.is_err());
Ok(())
}
#[test]
fn test_try_from_row_for_tuple_16() -> Result<()> {
use std::convert::TryFrom;
let create_table = "CREATE TABLE test (
a INTEGER,
b INTEGER,
c INTEGER,
d INTEGER,
e INTEGER,
f INTEGER,
g INTEGER,
h INTEGER,
i INTEGER,
j INTEGER,
k INTEGER,
l INTEGER,
m INTEGER,
n INTEGER,
o INTEGER,
p INTEGER
)";
let insert_values = "INSERT INTO test VALUES (
0,
1,
2,
3,
4,
5,
6,
7,
8,
9,
10,
11,
12,
13,
14,
15
)";
type BigTuple = (
u32,
u32,
u32,
u32,
u32,
u32,
u32,
u32,
u32,
u32,
u32,
u32,
u32,
u32,
u32,
u32,
);
let conn = Connection::open_in_memory()?;
conn.execute(create_table, [])?;
conn.execute(insert_values, [])?;
let val = conn.query_row("SELECT * FROM test", [], |row| BigTuple::try_from(row))?;
// Debug is not implemented for tuples of 16
assert_eq!(val.0, 0);
assert_eq!(val.1, 1);
assert_eq!(val.2, 2);
assert_eq!(val.3, 3);
assert_eq!(val.4, 4);
assert_eq!(val.5, 5);
assert_eq!(val.6, 6);
assert_eq!(val.7, 7);
assert_eq!(val.8, 8);
assert_eq!(val.9, 9);
assert_eq!(val.10, 10);
assert_eq!(val.11, 11);
assert_eq!(val.12, 12);
assert_eq!(val.13, 13);
assert_eq!(val.14, 14);
assert_eq!(val.15, 15);
// We don't test one bigger because it's unimplemented
Ok(())
}
}
| 34.341191
| 120
| 0.518624
|
9039718abbf57b8f3ef5e7ba6f656f2c9c52ed07
| 93
|
sql
|
SQL
|
net.solarnetwork.node.reactor.dao.jdbc/src/net/solarnetwork/node/dao/jdbc/reactor/derby-instruction-insert-status.sql
|
Tsvetelin98/Solar
|
350341d4f6a32d53efd48778ee7a8ba89a591978
|
[
"Apache-2.0"
] | null | null | null |
net.solarnetwork.node.reactor.dao.jdbc/src/net/solarnetwork/node/dao/jdbc/reactor/derby-instruction-insert-status.sql
|
Tsvetelin98/Solar
|
350341d4f6a32d53efd48778ee7a8ba89a591978
|
[
"Apache-2.0"
] | null | null | null |
net.solarnetwork.node.reactor.dao.jdbc/src/net/solarnetwork/node/dao/jdbc/reactor/derby-instruction-insert-status.sql
|
Tsvetelin98/Solar
|
350341d4f6a32d53efd48778ee7a8ba89a591978
|
[
"Apache-2.0"
] | null | null | null |
INSERT INTO solarnode.sn_instruction_status (instruction_id, modified, state)
VALUES (?,?,?)
| 31
| 77
| 0.784946
|
4015ca8a1bd9ef9b570541a6a381bcddcfd25dfc
| 2,671
|
sql
|
SQL
|
MailProxy/account.sql
|
glorycloud/GloryMail
|
f5250bd53f0b45e4dd25adc3940902d20f5597c2
|
[
"Apache-2.0"
] | 2
|
2019-10-06T11:07:51.000Z
|
2021-04-14T01:25:54.000Z
|
MailProxy/account.sql
|
glorycloud/GloryMail
|
f5250bd53f0b45e4dd25adc3940902d20f5597c2
|
[
"Apache-2.0"
] | null | null | null |
MailProxy/account.sql
|
glorycloud/GloryMail
|
f5250bd53f0b45e4dd25adc3940902d20f5597c2
|
[
"Apache-2.0"
] | 3
|
2018-12-23T15:56:47.000Z
|
2022-01-31T14:36:43.000Z
|
/*
SQLyog Enterprise - MySQL GUI v8.14
MySQL - 5.1.44-community : Database - test
*********************************************************************
*/
/*!40101 SET NAMES utf8 */;
/*!40101 SET SQL_MODE=''*/;
/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;
/*Table structure for table `account` */
DROP TABLE IF EXISTS `account`;
CREATE TABLE `account` (
`name` varchar(100) DEFAULT NULL COMMENT 'complete email address',
`loginName` varchar(50) DEFAULT NULL COMMENT 'login name of this account',
`smtpServer` varchar(100) DEFAULT NULL COMMENT 'domain name or IP of smtp server',
`mailServer` varchar(100) DEFAULT NULL,
`serverType` enum('pop3','imap') DEFAULT NULL COMMENT '1 for pop3, 2 for imap',
`ID` int(11) unsigned NOT NULL AUTO_INCREMENT COMMENT 'ID for this account, reference by other tables',
`password` varchar(50) DEFAULT NULL COMMENT 'user''s password',
`mailPort` smallint(5) unsigned DEFAULT '110' COMMENT 'port number of recive server, i.e. pop3, imap, or pop3 SSL',
`smtpPort` smallint(5) unsigned DEFAULT '25' COMMENT 'port number of send server, i.e. smtp port',
`useSSL` tinyint(1) DEFAULT '0',
`createTime` timestamp NULL DEFAULT CURRENT_TIMESTAMP,
`lastActive` timestamp NULL DEFAULT CURRENT_TIMESTAMP,
`mailIndexCounter` int(10) unsigned DEFAULT '1',
PRIMARY KEY (`ID`),
UNIQUE KEY `indexByEmallName` (`name`)
) ENGINE=InnoDB AUTO_INCREMENT=10 DEFAULT CHARSET=latin1;
/*Data for the table `account` */
insert into `account`(`name`,`loginName`,`smtpServer`,`mailServer`,`serverType`,`ID`,`password`,`mailPort`,`smtpPort`,`useSSL`,`createDate`,`mailIndexCounter`) values ('liu_lele@126.com','liu_lele','smtp.126.com','pop3.126.com','pop3',7,NULL,110,25,0,'2010-04-25 23:31:42',8436);
insert into `account`(`name`,`loginName`,`smtpServer`,`mailServer`,`serverType`,`ID`,`password`,`mailPort`,`smtpPort`,`useSSL`,`createDate`,`mailIndexCounter`) values ('liulele@ee.buaa.edu.cn','cocalele@gmail.com','smtp.gmail.com','pop.gmail.com','pop3',8,NULL,143,465,1,'2010-07-16 22:57:31',1);
insert into `account`(`name`,`loginName`,`smtpServer`,`mailServer`,`serverType`,`ID`,`password`,`mailPort`,`smtpPort`,`useSSL`,`createDate`,`mailIndexCounter`) values ('cocalele@gmail.com','cocalele@gmail.com','smtp.gmail.com','pop.gmail.com','pop3',9,NULL,995,465,1,'2010-08-30 22:20:43',1);
/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;
/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;
/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;
| 59.355556
| 298
| 0.688881
|
9531a04f555e7a48dcb14c39682c2686d52baf56
| 9,780
|
asm
|
Assembly
|
PORTS/buzz2.asm
|
bushy555/ZX-Spectrum-1-Bit-Routines
|
4d336dec9d7abc979a97af76d515104a9263f127
|
[
"BSD-3-Clause"
] | null | null | null |
PORTS/buzz2.asm
|
bushy555/ZX-Spectrum-1-Bit-Routines
|
4d336dec9d7abc979a97af76d515104a9263f127
|
[
"BSD-3-Clause"
] | null | null | null |
PORTS/buzz2.asm
|
bushy555/ZX-Spectrum-1-Bit-Routines
|
4d336dec9d7abc979a97af76d515104a9263f127
|
[
"BSD-3-Clause"
] | null | null | null |
;
;--------------------------------
; BUZZKICK
; ------------------------------
;#define defb db
;#define defw dw
;#define db db
;#define dw dw
;#define end end
;#define org org
;#define DEFB db
;#define DEFW dw
;#define DB db
;#define DW dw
;#define END end
;#define ORG org
;#define equ equ
;#define EQU equ
ORG $8000
;test code
begin
ld hl,musicdata1
ld hl,musicdata2
call play
ret
;engine code
play
di
ld (drumList+1),hl
ld a,(hl)
inc hl
ld h,(hl)
ld l,a
xor a
ld (songSpeedComp+1),a
ld (ch1out+1),a
ld (ch2out+1),a
ld a,128
ld (ch1freq+1),a
ld (ch2freq+1),a
ld a,1
ld (ch1delay1+1),a
ld (ch2delay1+1),a
ld a,16
ld (ch1delay2+1),a
ld (ch2delay2+1),a
exx
ld d,a
ld e,a
ld b,a
ld c,a
push hl
exx
readRow
ld c,(hl)
inc hl
bit 7,c
jr z,noSpeed
ld a,(hl)
inc hl
or a
jr nz,noLoop
ld a,(hl)
inc hl
ld h,(hl)
ld l,a
jr readRow
noLoop
ld (songSpeed+1),a
noSpeed
bit 6,c
jr z,noSustain1
ld a,(hl)
inc hl
exx
ld d,a
ld e,a
exx
noSustain1
bit 5,c
jr z,noSustain2
ld a,(hl)
inc hl
exx
ld b,a
ld c,a
exx
noSustain2
bit 4,c
jr z,noNote1
ld a,(hl)
ld d,a
inc hl
or a
jr z,$+4
; ld a,$18
ld a, 33
ld (ch1out+1),a
jr z,noNote1
ld a,d
ld (ch1freq+1),a
srl a
srl a
ld (ch1delay2+1),a
ld a,1
ld (ch1delay1+1),a
exx
ld e,d
exx
noNote1
bit 3,c
jr z,noNote2
ld a,(hl)
ld e,a
inc hl
or a
jr z,$+4
; ld a,$18
ld a, 33
ld (ch2out+1),a
jr z,noNote2
ld a,e
ld (ch2freq+1),a
srl a
srl a
srl a
ld (ch2delay2+1),a
ld a,1
ld (ch2delay1+1),a
exx
ld c,b
exx
noNote2
ld a,c
and 7
jr z,noDrum
playDrum
push hl
add a,a
add a,a
ld c,a
ld b,0
drumList:
ld hl,0
add hl,bc
ld a,(hl) ;length in 256-sample blocks
ld b,a
inc hl
inc hl
add a,a
add a,a
ld (songSpeedComp+1),a
ld a,(hl)
inc hl
ld h,(hl) ;sample data
ld l,a
ld a,1
ld (mask+1),a
ld c,0
loop0
ld a,(hl) ;7
mask:
and 0 ;7
sub 1 ;7
sbc a,a ;4
; and $18 ;7
and 33
; out ($fe),a ;11
ld (26624), a
ld a,(mask+1) ;13
rlc a ;8
ld (mask+1),a ;13
jr nc,$+3 ;7/12
inc hl ;6
jr $+2 ;12
jr $+2 ;12
jr $+2 ;12
jr $+2 ;12
nop ;4
nop ;4
ld a,0 ;7
dec c ;4
jr nz,loop0 ;7/12=168t
djnz loop0
pop hl
noDrum
songSpeed:
ld a,0
ld b,a
songSpeedComp:
sub 0
jr nc,$+3
xor a
ld c,a
ld a,(songSpeedComp+1)
sub b
jr nc,$+3
xor a
ld (songSpeedComp+1),a
ld a,c
or a
jp z,readRow
ld c,a
ld b,64
soundLoop
ld a,3 ;7
dec a ;4
jr nz,$-1 ;7/12=50t
jr $+2 ;12
dec d ;4
jp nz,ch2 ;10
ch1freq:
ld d,0 ;7
ch1delay1:
ld a,0 ;7
dec a ;4
jr nz,$-1 ;7/12
ch1out:
ld a,0 ;7
; out ($fe),a ;11
and 33
ld (26624), a
ch1delay2:
ld a,0 ;7
dec a ;4
jr nz,$-1 ;7/12
; out ($fe),a ;11
and 33
ld (26624), a
ch2
ld a,3 ;7
dec a ;4
jr nz,$-1 ;7/12=50t
jr $+2 ;12
dec e ;4
jp nz,loop ;10
ch2freq:
ld e,0 ;7
ch2delay1:
ld a,0 ;7
dec a ;4
jr nz,$-1 ;7/12
ch2out:
ld a,0 ;7
; out ($fe),a ;11
and 33
ld (26624), a
ch2delay2:
ld a,0 ;7
dec a ;4
jr nz,$-1 ;7/12
; out ($fe),a ;11
and 33
ld (26624), a
loop
dec b ;4
jr nz,soundLoop ;7/12=168t
ld b,64
envelopeDown
exx
dec e
jp nz,noEnv1
ld e,d
ld hl,ch1delay2+1
dec (hl)
jr z,$+5
ld hl,ch1delay1+1
inc (hl)
noEnv1
dec c
jp nz,noEnv2
ld c,b
ld hl,ch2delay2+1
dec (hl)
jr z,$+5
ld hl,ch2delay1+1
inc (hl)
noEnv2
exx
dec c
jp nz,soundLoop
xor a
; in a,($fe)
; cpl
; and $1f
; jp z,readRow
jp readRow
pop hl
exx
ei
ret
musicdata1:
speed equ $c00
db $c0
seq
dw ptn0
dw ptn0
dw ptn1
dw ptn2
dw ptn1
dw ptn3
dw ptn4
dw ptn5
dw ptn4
dw ptn6
dw ptn7
dw ptn7
dw ptn8
dw ptn13
dw ptn9
dw ptn10
dw ptn11
dw ptn13
dw ptn9
dw ptn10
dw ptn11
dw ptn12
dw ptn14
dw ptn14
dw 0
ptn0
db $5,$31
db $5,$31
db $11,$31
db $14,$31
db $31,$31
db $31,$31
db $f,$31
db $f,$31
db $5,$31
db $5,$31
db $11,$31
db $14,$31
db $31,$31
db $31,$31
db $f,$31
db $f,$31
db 0
ptn1
db $5,$e4
db $5,$22
db $11,$20
db $14,$df
db $31,$9f
db $31,$1f
db $f,$b1
db $f,$b1
db $5,$f1
db $5,$31
db $11,$31
db $14,$f1
db $31,$b1
db $31,$31
db $f,$18
db $f,$9b
db 0
ptn2
db $5,$dd
db $5,$1b
db $11,$1d
db $14,$e0
db $31,$a0
db $31,$20
db $f,$f1
db $f,$f1
db $5,$f1
db $5,$31
db $11,$31
db $14,$f1
db $31,$b1
db $31,$31
db $f,$f1
db $f,$31
db 0
ptn3
db $5,$dd
db $5,$1b
db $11,$1d
db $14,$dd
db $31,$9d
db $31,$1d
db $f,$f1
db $f,$f1
db $5,$f1
db $5,$31
db $11,$31
db $14,$f1
db $31,$b1
db $31,$31
db $f,$f1
db $f,$31
db 0
ptn4
db $a,$e2
db $a,$20
db $16,$22
db $19,$e5
db $31,$a5
db $31,$25
db $14,$b1
db $14,$b1
db $a,$f1
db $a,$31
db $16,$31
db $19,$e4
db $31,$a7
db $31,$25
db $14,$24
db $14,$a2
db 0
ptn5
db $5,$e4
db $5,$22
db $11,$24
db $14,$dd
db $31,$9d
db $31,$1d
db $f,$f1
db $f,$f1
db $5,$f1
db $5,$31
db $11,$31
db $14,$f1
db $31,$b1
db $31,$31
db $f,$f1
db $f,$31
db 0
ptn6
db $8c,$e4
db $10c,$24
db $18c,$24
db $b1,$31
db $b1,$31
db $b1,$b1
db $a,$e2
db $a,$31
db $8,$e0
db $8,$31
db $7,$df
db $7,$31
db 0
ptn7
db $5,$f1
db $5,$31
db $11,$31
db $14,$f1
db $31,$b1
db $31,$31
db $f,$b1
db $f,$b1
db $5,$f1
db $5,$31
db $11,$31
db $14,$f1
db $31,$b1
db $31,$31
db $f,$31
db $f,$b1
db 0
ptn8
db $7,$f1
db $7,$31
db $13,$31
db $16,$f1
db $31,$b1
db $31,$31
db $11,$b1
db $11,$b1
db $7,$f1
db $7,$31
db $13,$31
db $16,$f1
db $31,$b1
db $31,$31
db $11,$31
db $11,$b1
db 0
ptn9
db $7,$e6
db $7,$24
db $13,$26
db $16,$e9
db $31,$a9
db $31,$29
db $11,$a9
db $11,$a9
db $7,$f1
db $7,$31
db $13,$31
db $16,$e6
db $31,$a9
db $31,$26
db $11,$29
db $11,$a6
db 0
ptn10
db $7,$eb
db $7,$2b
db $13,$2b
db $16,$eb
db $31,$b1
db $31,$31
db $11,$f1
db $11,$f1
db $7,$f1
db $7,$31
db $13,$26
db $16,$f1
db $31,$a4
db $31,$31
db $11,$df
db $11,$31
db 0
ptn11
db $7,$e6
db $7,$27
db $13,$26
db $16,$df
db $31,$9f
db $31,$1f
db $11,$9f
db $11,$9f
db $7,$f1
db $7,$31
db $13,$31
db $16,$f1
db $31,$a6
db $31,$31
db $11,$26
db $11,$a7
db 0
ptn12
db $1a,$e6
db $1a,$26
db $18,$24
db $18,$24
db $16,$22
db $16,$22
db $15,$21
db $15,$21
db $e,$26
db $e,$26
db $c,$24
db $c,$24
db $a,$22
db $a,$22
db $9,$21
db $9,$21
db 0
ptn13
db $7,$f1
db $7,$31
db $13,$31
db $16,$f1
db $31,$b1
db $31,$31
db $11,$f1
db $11,$f1
db $7,$f1
db $7,$31
db $13,$31
db $16,$f1
db $31,$b1
db $31,$31
db $11,$f1
db $11,$31
db 0
ptn14
db $1a,$26
db $18,$24
db $16,$22
db $15,$21
db $e,$26
db $c,$24
db $a,$22
db $9,$21
db 0
musicdata2
dw $0944
dw p2
db $01,$02
db $03,$04
db $05,$06
db $07,$08
db $09,$0a
db $0b,$0c
db $01,$0d
db $0e,$0f
db $01,$02
db $03,$04
db $05,$06
db $07,$10
db $09,$11
db $0b,$12
db $05,$13
db $14,$15
db $16,$17
db $18,$19
db $1a,$17
db $1b,$1c
db $1d,$1e
db $1f,$20
db $1d,$1e
db $21,$20
db $16,$17
db $18,$1c
db $1a,$17
db $1b,$22
db $23,$24
db $25,$24
db $23,$26
db $27,$28
db $16,$17
db $18,$19
db $1a,$17
db $1b,$1c
db $1d,$1e
db $1f,$20
db $1d,$1e
db $21,$20
db $16,$17
db $18,$1c
db $1a,$17
db $1b,$22
db $29
p2: db $28
db $2a,$28
db $29,$2b
db $2c,$2d
db $00
p3: db $e2,$00,$e2,$00,$e2,$00,$e2,$00
db $00,$00,$38,$38,$32,$32,$2c,$2c
db $2c,$00,$e2,$00,$e2,$00,$e2,$00
db $38,$38,$38,$38,$3c,$3c,$38,$38
db $97,$00,$97,$00,$97,$00,$97,$00
db $38,$38,$3c,$3c,$00,$00,$00,$00
db $2c,$00,$97,$00,$97,$00,$97,$00
db $43,$43,$3c,$3c,$00,$00,$4b,$4b
db $a9,$00,$a9,$00,$a9,$00,$a9,$00
db $4b,$4b,$54,$54,$4b,$4b,$43,$43
db $2c,$00,$a9,$00,$a9,$00,$a9,$00
db $4b,$4b,$4b,$4b,$54,$54,$4b,$4b
db $4b,$4b,$59,$00,$59,$00,$59,$00
db $2c,$00,$ca,$00,$b3,$00,$b3,$00
db $54,$00,$54,$00,$4b,$00,$4b,$00
db $38,$38,$32,$32,$00,$00,$3c,$3c
db $3c,$3c,$43,$43,$4b,$4b,$54,$54
db $65,$65,$59,$59,$00,$00,$4b,$4b
db $4b,$4b,$4b,$4b,$4b,$4b,$4b,$4b
db $2c,$00,$97,$00,$2c,$00,$2c,$00
db $4b,$4b,$4b,$4b,$00,$00,$00,$00
db $a9,$00,$a9,$a9,$54,$00,$54,$54
db $43,$43,$38,$38,$32,$32,$43,$43
db $2c,$00,$a9,$a9,$54,$00,$54,$54
db $38,$38,$32,$32,$38,$38,$32,$32
db $97,$00,$97,$97,$4b,$00,$4b,$4b
db $2c,$00,$97,$97,$2c,$00,$2c,$4b
db $38,$38,$32,$32,$43,$43,$38,$38
db $86,$00,$86,$86,$43,$00,$43,$43
db $3c,$3c,$38,$38,$32,$32,$3c,$3c
db $2c,$00,$86,$86,$43,$00,$43,$43
db $38,$38,$32,$32,$3c,$3c,$38,$38
db $2c,$00,$86,$86,$2c,$00,$2c,$43
db $38,$38,$32,$32,$43,$43,$3c,$3c
db $ca,$00,$ca,$ca,$65,$00,$65,$65
db $43,$00,$43,$00,$43,$00,$43,$00
db $2c,$00,$ca,$ca,$65,$00,$65,$65
db $3c,$00,$3c,$00,$3c,$00,$3c,$00
db $2c,$00,$ca,$ca,$65,$00,$65,$00
db $38,$00,$38,$00,$38,$00,$38,$00
db $e2,$00,$e2,$e2,$71,$00,$71,$71
db $2c,$00,$e2,$e2,$71,$00,$71,$71
db $38,$38,$38,$38,$38,$38,$38,$38
db $2c,$e2,$e2,$e2,$e2,$00,$00,$00
db $38,$38,$38,$38,$38,$00,$00,$00
end
| 12.255639
| 43
| 0.478732
|
ff74fdc7b00342cad31d0e39c65d11e6576f8cbf
| 2,190
|
py
|
Python
|
zerosim/data/watchlists.py
|
rahulmkumar/ZeroSim1
|
63eb357c4831b666581df0de4355f85095653d06
|
[
"MIT"
] | 1
|
2020-08-28T16:27:15.000Z
|
2020-08-28T16:27:15.000Z
|
zerosim/data/watchlists.py
|
rahulmkumar/ZeroSim1
|
63eb357c4831b666581df0de4355f85095653d06
|
[
"MIT"
] | null | null | null |
zerosim/data/watchlists.py
|
rahulmkumar/ZeroSim1
|
63eb357c4831b666581df0de4355f85095653d06
|
[
"MIT"
] | 1
|
2021-02-03T12:31:42.000Z
|
2021-02-03T12:31:42.000Z
|
import shelve
import pandas as pd
class Watchlist(object):
def __init__(self, list_name, l_sym):
self.watchlist_name = list_name
self.l_symbols = l_sym
def get_watchlist_name(self):
return self.watchlist_name
def get_watchlist_sym(self):
return self.l_symbols
class WatchlistDb(object):
WATCHLIST_DB_PATH = ''
WATCHLIST_CSV_PATH = '../symbols/'
WATCHLIST_FILE = 'watchlistdb.csv'
WATCHLIST_DB = 'watchlistdb.db'
def get_watchlists_csv(self, file_name=WATCHLIST_CSV_PATH+WATCHLIST_FILE):
wlist = pd.read_csv(file_name)
wlist = wlist.fillna('')
watchlist_dict = {}
for wl_name in wlist.columns:
l_wlist = list(wlist[wl_name])
try:
while 1:
l_wlist.remove('')
except:
pass
watchlist_dict[wl_name] = l_wlist
return watchlist_dict
def open_watchlistdb(self, db_name = WATCHLIST_DB_PATH+WATCHLIST_DB):
db_con = shelve.open(db_name)
return db_con
def insert_one_watchlist(self, connection, wlist):
connection[wlist.get_watchlist_name()] = wlist
connection.close()
def insert_multiple_watchlists(self, connection, l_wlist_dict):
for w_list in l_wlist_dict:
connection[w_list] = l_wlist_dict[w_list]
connection.close()
def get_watchlists(self, db_name):
connection = self.open_watchlistdb(db_name=db_name)
for w_list in connection:
return w_list, connection[w_list]
#print 'Watchlist Name:' + w_list
#print 'Watchlist Symbols:' + str(connection[w_list])
def get_watchlist_by_name(self, db_name, watchlist_name):
conn = self.open_watchlistdb(db_name=db_name)
return conn[watchlist_name]
if __name__ == '__main__':
import symbols
sym = symbols.SymbolDb()
wlist_dict = sym.get_watchlists()
wl = WatchlistDb()
conn = wl.open_watchlistdb()
wl.insert_multiple_watchlists(conn, wlist_dict)
wl.get_watchlists('watchlistdb.db')
ibd50 = wl.get_watchlist_by_name('watchlistdb.db', 'IBD50')
print ibd50
| 28.076923
| 78
| 0.652055
|
8ea1552e5a667b8e4e116e9ddbb6abcf4afc263c
| 394
|
js
|
JavaScript
|
js/app.js
|
hackEns/VelibFxos
|
8e81698cef7902d821fdaae2d0864f1191d7438a
|
[
"MIT"
] | 3
|
2015-01-13T14:53:05.000Z
|
2015-09-30T02:24:41.000Z
|
js/app.js
|
Phyks/VelibFxos
|
8e81698cef7902d821fdaae2d0864f1191d7438a
|
[
"MIT"
] | 97
|
2015-01-14T08:08:22.000Z
|
2015-10-06T20:54:43.000Z
|
js/app.js
|
hackEns/VelibFxos
|
8e81698cef7902d821fdaae2d0864f1191d7438a
|
[
"MIT"
] | 8
|
2015-01-13T14:53:11.000Z
|
2015-10-03T23:03:04.000Z
|
"use strict";
/**********
* Ready()
**********/
// Wait for the localization to be done and loaded, and avoid having problems
// with unloaded localization variables.
document.addEventListener("localized", function() {
$(function() {
Views.init();
Geolocation.init();
Router.route();
});
});
$(window).on('hashchange', function() {
Router.route();
});
| 18.761905
| 77
| 0.581218
|
c680a3dde5e27a5dfede0824bcad1b9b53f59159
| 7,743
|
rs
|
Rust
|
src/api/rcos/meetings/authorization_for.rs
|
gmisail/Telescope
|
ffb0738f78c8eb5358e7b9ce7634e2d212b794ad
|
[
"MIT"
] | null | null | null |
src/api/rcos/meetings/authorization_for.rs
|
gmisail/Telescope
|
ffb0738f78c8eb5358e7b9ce7634e2d212b794ad
|
[
"MIT"
] | null | null | null |
src/api/rcos/meetings/authorization_for.rs
|
gmisail/Telescope
|
ffb0738f78c8eb5358e7b9ce7634e2d212b794ad
|
[
"MIT"
] | null | null | null |
//! GraphQL query to check if a user can view draft meetings.
use crate::api::rcos::meetings::{MeetingType, ALL_MEETING_TYPES};
use crate::api::rcos::prelude::*;
use crate::api::rcos::send_query;
use crate::api::rcos::users::UserRole;
use crate::error::TelescopeError;
use chrono::Local;
/// Type representing GraphQL query to check if a user can view drafts.
#[derive(GraphQLQuery)]
#[graphql(
schema_path = "graphql/rcos/schema.json",
query_path = "graphql/rcos/meetings/authorization_for.graphql"
)]
pub struct AuthorizationFor;
use crate::api::rcos::meetings::get_host::MeetingHost;
use authorization_for::{ResponseData, Variables};
/// Info on the user that dictates their ability to access meeting data.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct UserMeetingAuthorization {
/// The user's username.
pub username: Option<String>,
/// The user's role. Faculty advisors can access just about anything.
role: UserRole,
/// Is this user a coordinator during an ongoing semester?
is_current_coordinator: bool,
/// Is this user a mentor during an ongoing semester?
is_current_mentor: bool,
}
impl Default for UserMeetingAuthorization {
fn default() -> Self {
UserMeetingAuthorization {
username: None,
role: UserRole::External,
is_current_coordinator: false,
is_current_mentor: false,
}
}
}
impl UserMeetingAuthorization {
/// Create an authorization object for a faculty advisor.
fn faculty_advisor(username: String) -> Self {
Self {
username: Some(username),
role: UserRole::FacultyAdvisor,
is_current_mentor: false,
is_current_coordinator: false,
}
}
/// Can the user associated with this authorization view draft meetings?
pub fn can_view_drafts(&self) -> bool {
self.is_current_coordinator
|| self.role == UserRole::FacultyAdvisor
|| self.role == UserRole::Sysadmin
}
/// Can the user associated with this authorization view meetings of a given type?
pub fn can_view(&self, meeting_type: MeetingType) -> bool {
match meeting_type {
// Coordinator meetings can be viewed by just coordinators and faculty advisors
MeetingType::Coordinators => self.can_view_drafts(),
// Mentor and Grading meetings can be viewed by mentors, coordinators,
// and faculty advisors
MeetingType::Mentors | MeetingType::Grading => {
self.is_current_mentor || self.can_view_drafts()
}
// All other meeting types (small groups, large groups, bonus sessions, etc)
// are public.
_ => true,
}
}
/// Can the user associated with this authorization edit meetings with a given type
/// and optionally specified host username?
pub fn can_edit(&self, host_username: Option<&str>) -> bool {
// If there is a host and viewer
if let (Some(host), Some(viewer)) = (host_username, self.username.as_ref()) {
// and they are the same person (or the viewer has coordinator or higher perms)
host == viewer || self.can_view_drafts()
} else {
// of the viewer is a coordinator or faculty advisor
self.can_view_drafts()
}
}
/// Can the user associated with this authorization edit the meeting
pub async fn can_edit_by_id(&self, meeting_id: i64) -> Result<bool, TelescopeError> {
// If the authenticated user is a coordinator or professor, then they can edit this meeting.
if self.can_view_drafts() {
Ok(true)
} else {
// Otherwise lookup the meeting and check if the authenticated username matches the host
// username.
let meeting_host: Option<String> = MeetingHost::get(meeting_id).await?;
match (meeting_host, self.username.as_ref()) {
// If there is both a host and a viewer, and they're the same,
// the meeting can be edited.
(Some(host), Some(viewer)) => Ok(host == *viewer),
// In any other case, the meeting is not to be edited by the viewer.
_ => Ok(false),
}
}
}
/// Can the user associated with this authorization delete meetings?
/// This is currently just coordinators and faculty advisors.
pub fn can_delete_meetings(&self) -> bool {
self.can_view_drafts()
}
/// Can the user associated with this authorization create meetings?
/// This is currently just coordinators and faculty advisors.
pub fn can_create_meetings(&self) -> bool {
self.can_view_drafts()
}
/// Get a list of the types of meetings viewable under this authorization.
pub fn viewable_types(&self) -> Vec<MeetingType> {
// Start with a vector of sufficient capacity to hold a full access list.
let mut visible_types: Vec<MeetingType> = Vec::with_capacity(ALL_MEETING_TYPES.len());
// Add all the types this user is authorized for.
for ty in ALL_MEETING_TYPES.iter() {
if self.can_view(*ty) {
visible_types.push(*ty);
}
}
return visible_types;
}
}
impl AuthorizationFor {
/// Get the meeting access authorization rules for a given user.
pub async fn get(username: Option<String>) -> Result<UserMeetingAuthorization, TelescopeError> {
// If there is no username, then the viewer has default (lowest) authorization.
if username.is_none() {
return Ok(UserMeetingAuthorization::default());
}
// Otherwise unwrap the username.
let username: String = username.unwrap();
// Create variables for an API query.
let query_vars: Variables = Variables {
// Use the current local date.
now: Local::today().naive_local(),
// Clone the username
username: username.clone(),
};
// Call the API.
let api_response: ResponseData = send_query::<Self>(query_vars).await?;
// First check if the user is a faculty advisor.
let user_role: UserRole = api_response
.users_by_pk
.map(|user| user.role)
.unwrap_or(UserRole::External);
if user_role == UserRole::FacultyAdvisor {
return Ok(UserMeetingAuthorization::faculty_advisor(username));
}
// If they are not a faculty advisor, check if they are a current coordinator.
let is_current_coordinator: bool = api_response
// Start by flattening all the current semesters into one list of coordinator flags.
.current_semesters
.iter()
.map(|semester| semester.enrollments.as_slice())
.flatten()
.map(|enrollment| enrollment.is_coordinator)
// And check if any of them are true
.any(|is_coordinator| is_coordinator);
let is_current_mentor: bool = api_response
// Flatten the current semesters' small groups where this user is a mentor.
.current_semesters
.iter()
.map(|semester| semester.small_groups.as_slice())
.flatten()
.map(|small_group| small_group.small_group_id)
// This user must be a mentor for at least one to be considered a current mentor.
.count()
>= 1;
return Ok(UserMeetingAuthorization {
username: Some(username),
role: user_role,
is_current_coordinator,
is_current_mentor,
});
}
}
| 38.331683
| 100
| 0.625597
|
e5aebd565fbb43c5a4bce82ea6ec4b4536ed592a
| 4,595
|
swift
|
Swift
|
Example/SwiftEventBusExample/SwiftEventBusTests/EventBusTests.swift
|
GarethShapiro/SwiftEventBus
|
623876e05b540fa6a3b283e2e55df35af1375c4b
|
[
"MIT"
] | null | null | null |
Example/SwiftEventBusExample/SwiftEventBusTests/EventBusTests.swift
|
GarethShapiro/SwiftEventBus
|
623876e05b540fa6a3b283e2e55df35af1375c4b
|
[
"MIT"
] | null | null | null |
Example/SwiftEventBusExample/SwiftEventBusTests/EventBusTests.swift
|
GarethShapiro/SwiftEventBus
|
623876e05b540fa6a3b283e2e55df35af1375c4b
|
[
"MIT"
] | null | null | null |
//
// EventBusTests.swift
// SwiftEventBusTests
//
// Created by Gareth Shapiro on 30/01/2019.
// Copyright © 2019 Gareth Shapiro. All rights reserved.
//
import XCTest
import SwiftEventBus
class EventBusTests: XCTestCase {
func testConsumeMethodWithCorrectEvent() {
// GIVEN an instance of EventBus
// WHEN an EventConsumer is registered
// AND an Event the EventConsumer will consume (not on excludeList and on willConsume) is dispatched on the EventBus
// THEN the consume method of the EventConsumer will be called with an instance as an argument
let stubEventBus = EventBus()
let stubEventConsumer = StubEventConsumer()
let stubEvent = StubEvent()
stubEventBus.register(stubEventConsumer)
stubEventBus.dispatch(stubEvent)
guard let targetEvent = stubEventConsumer.consumeCalledWith else {
XCTFail("EventConsumer.consume was not called")
return
}
XCTAssertTrue(targetEvent.isEqual(stubEvent), "EventConsumer.consume was not called with the correct Event : \(stubEvent.self)")
}
func testConsumeMethodWithIncorrectEvent() {
// GIVEN an instance of EventBus
// WHEN an EventConsumer is registered
// AND an Event the EventConsumer will not consume (not on willConsume) is dispatched on the EventBus
// THEN the consume method of the EventConsumer will not be called
let stubEventBus = EventBus()
let stubEventConsumer = StubEventConsumer()
let anotherstubEvent = AnotherStubEvent()
stubEventBus.register(stubEventConsumer)
stubEventBus.dispatch(anotherstubEvent)
XCTAssertNil(stubEventConsumer.consumeCalledWith, "EventConsumer.consume was unexpectedly called with an event.")
}
func testUnregisteredConsumerDoesNotConsumeEvents() {
// GIVEN an instance of EventBus
// WHEN an EventConsumer is registered
// AND then subsequentlty deregistered
// AND an Event the EventConsumer will consume is dispatched on the EventBus
// THEN the consume method of the EventConsumer will not be called
let stubEventBus = EventBus()
let stubEventConsumer = StubEventConsumer()
let stubEvent = StubEvent()
stubEventBus.register(stubEventConsumer)
stubEventBus.deregister(stubEventConsumer)
stubEventBus.dispatch(stubEvent)
XCTAssertNil(stubEventConsumer.consumeCalledWith, "EventConsumer.consume was unexpectedly called with an event.")
}
func testDidConsumeIsDispatchedAfterEventConsumedForOneConsumer() {
// GIVEN an instance of EventBus
// WHEN two EventConsumers are registered with it, the first willConsume StubEvents and the second willConsume DidConsumeEvents
// AND the StubEvent is dispatched on the EventBus
// THEN the consume method of the first EventConsumer is called with an instance of StubEvent as an arguement
// AND subsequently the consume method of the second EventConsumer is called with an instance of DidConsumeEvent as an argurment
// AND the DidConsumeEvent has references to the StubEvent and other EventConsumer
let stubEventBus = EventBus()
let stubEventConsumer = StubEventConsumer()
let didConsumeStubEventConsumer = DidConsumeStubEventConsumer()
let stubEvent = StubEvent()
let stubDidConsumeEvent = DidConsumeEvent(sourceConsumer: stubEventConsumer, sourceEvent: stubEvent)
let didConsumeExpectation = XCTestExpectation(description: "DidConsumeEvent not consumed")
let didConsumeEventBlock = {
didConsumeExpectation.fulfill()
guard let didConsumeEvent = didConsumeStubEventConsumer.consumeCalledWith as? DidConsumeEvent else {
XCTFail("EventConsumer.consume was not called with the correct Event : \(stubDidConsumeEvent.self)")
return
}
XCTAssertTrue(didConsumeEvent.sourceEvent.isEqual(stubEvent), "Unexpected DidConsumeEvent.sourceEvent : \(didConsumeEvent.sourceEvent.self)")
}
didConsumeStubEventConsumer.wasConsumedBlock = didConsumeEventBlock
stubEventBus.register(stubEventConsumer)
stubEventBus.register(didConsumeStubEventConsumer)
stubEventBus.dispatch(stubEvent)
XCTAssertTrue(stubEventConsumer.consumeCalledWith is StubEvent, "EventConsumer.consume was not called with the correct Event : \(stubEvent.self)")
wait(for: [didConsumeExpectation], timeout: 0.5)
}
}
| 41.396396
| 154
| 0.718607
|
3da41e8a846a73c60f1c9fbcc52de4c7dc1cf037
| 688
|
swift
|
Swift
|
Canyoneer/Canyoneer/AppDataKit/Services/FavoriteService.swift
|
bricepollock/canyoneer
|
e95fe8577710a8ff0ca008f079951ae5c1b28b7f
|
[
"MIT"
] | null | null | null |
Canyoneer/Canyoneer/AppDataKit/Services/FavoriteService.swift
|
bricepollock/canyoneer
|
e95fe8577710a8ff0ca008f079951ae5c1b28b7f
|
[
"MIT"
] | null | null | null |
Canyoneer/Canyoneer/AppDataKit/Services/FavoriteService.swift
|
bricepollock/canyoneer
|
e95fe8577710a8ff0ca008f079951ae5c1b28b7f
|
[
"MIT"
] | null | null | null |
//
// FavoriteService.swift
// Canyoneer
//
// Created by Brice Pollock on 1/12/22.
//
import Foundation
import RxSwift
import Combine
class FavoriteService {
func allFavorites() -> AnyPublisher<[Canyon], Never> {
return Just(UserPreferencesStorage.allFavorites).eraseToAnyPublisher()
}
func isFavorite(canyon: Canyon) -> Bool {
return UserPreferencesStorage.isFavorite(canyon: canyon)
}
func setFavorite(canyon: Canyon, to isFavorite: Bool) {
if isFavorite {
UserPreferencesStorage.addFavorite(canyon: canyon)
} else {
UserPreferencesStorage.removeFavorite(canyon: canyon)
}
}
}
| 22.933333
| 78
| 0.65843
|
a339d2cbd113955c3ac090cb8dc8c85a9aa066fe
| 29,549
|
java
|
Java
|
examples/BasicGLSurfaceView/deploy/src/haxe/root/Array.java
|
haxorplatform/androidhx
|
6644be77b59e6de5805646a0f47c5c191284bd01
|
[
"MIT"
] | 8
|
2016-10-31T18:12:15.000Z
|
2021-06-29T08:14:38.000Z
|
examples/BasicGLSurfaceView/deploy/src/haxe/root/Array.java
|
haxorplatform/androidhx
|
6644be77b59e6de5805646a0f47c5c191284bd01
|
[
"MIT"
] | null | null | null |
examples/BasicGLSurfaceView/deploy/src/haxe/root/Array.java
|
haxorplatform/androidhx
|
6644be77b59e6de5805646a0f47c5c191284bd01
|
[
"MIT"
] | null | null | null |
package haxe.root;
import haxe.root.*;
@SuppressWarnings(value={"rawtypes", "unchecked"})
public final class Array<T> extends haxe.lang.HxObject
{
public Array(T[] _native)
{
this.__a = _native;
this.length = _native.length;
}
public Array(haxe.lang.EmptyObject empty)
{
{
}
}
public Array()
{
haxe.root.Array.__hx_ctor__Array(this);
}
public static <T_c> void __hx_ctor__Array(haxe.root.Array<T_c> __temp_me3254)
{
__temp_me3254.length = 0;
__temp_me3254.__a = ((T_c[]) (((java.lang.Object) (new java.lang.Object[((int) (0) )]) )) );
}
public static <X> haxe.root.Array<X> ofNative(X[] _native)
{
return new Array<X>(_native);
}
public static <Y> haxe.root.Array<Y> alloc(int size)
{
return new Array<Y>((Y[]) ((java.lang.Object)new java.lang.Object[size]));
}
public static java.lang.Object __hx_createEmpty()
{
return new haxe.root.Array<java.lang.Object>(((haxe.lang.EmptyObject) (haxe.lang.EmptyObject.EMPTY) ));
}
public static java.lang.Object __hx_create(haxe.root.Array arr)
{
return new haxe.root.Array<java.lang.Object>();
}
public int length;
public T[] __a;
public final haxe.root.Array<T> concat(haxe.root.Array<T> a)
{
int length = this.length;
int len = ( length + a.length );
T[] retarr = ((T[]) (((java.lang.Object) (new java.lang.Object[((int) (len) )]) )) );
java.lang.System.arraycopy(((java.lang.Object) (this.__a) ), ((int) (0) ), ((java.lang.Object) (retarr) ), ((int) (0) ), ((int) (length) ));
java.lang.System.arraycopy(((java.lang.Object) (a.__a) ), ((int) (0) ), ((java.lang.Object) (retarr) ), ((int) (length) ), ((int) (a.length) ));
return haxe.root.Array.ofNative(retarr);
}
public final void concatNative(T[] a)
{
T[] __a = this.__a;
int length = this.length;
int len = ( length + a.length );
if (( __a.length >= len ))
{
java.lang.System.arraycopy(((java.lang.Object) (a) ), ((int) (0) ), ((java.lang.Object) (__a) ), ((int) (length) ), ((int) (length) ));
}
else
{
T[] newarr = ((T[]) (((java.lang.Object) (new java.lang.Object[((int) (len) )]) )) );
java.lang.System.arraycopy(((java.lang.Object) (__a) ), ((int) (0) ), ((java.lang.Object) (newarr) ), ((int) (0) ), ((int) (length) ));
java.lang.System.arraycopy(((java.lang.Object) (a) ), ((int) (0) ), ((java.lang.Object) (newarr) ), ((int) (length) ), ((int) (a.length) ));
this.__a = newarr;
}
this.length = len;
}
public final java.lang.String join(java.lang.String sep)
{
haxe.root.StringBuf buf = new haxe.root.StringBuf();
int i = -1;
boolean first = true;
int length = this.length;
while (( ++ i < length ))
{
if (first)
{
first = false;
}
else
{
buf.add(sep);
}
buf.add(this.__a[i]);
}
return buf.toString();
}
public final T pop()
{
T[] __a = this.__a;
int length = this.length;
if (( length > 0 ))
{
T val = __a[ -- length];
__a[length] = null;
this.length = length;
return val;
}
else
{
return null;
}
}
public final int push(T x)
{
int length = this.length;
if (( length >= this.__a.length ))
{
int newLen = ( (( length << 1 )) + 1 );
T[] newarr = ((T[]) (((java.lang.Object) (new java.lang.Object[((int) (newLen) )]) )) );
java.lang.System.arraycopy(((java.lang.Object) (this.__a) ), ((int) (0) ), ((java.lang.Object) (newarr) ), ((int) (0) ), ((int) (this.__a.length) ));
this.__a = newarr;
}
this.__a[length] = x;
return ++ this.length;
}
public final void reverse()
{
int i = 0;
int l = this.length;
T[] a = this.__a;
int half = ( l >> 1 );
l -= 1;
while (( i < half ))
{
T tmp = a[i];
a[i] = a[( l - i )];
a[( l - i )] = tmp;
i += 1;
}
}
public final T shift()
{
int l = this.length;
if (( l == 0 ))
{
return null;
}
T[] a = this.__a;
T x = a[0];
l -= 1;
java.lang.System.arraycopy(((java.lang.Object) (a) ), ((int) (1) ), ((java.lang.Object) (a) ), ((int) (0) ), ((int) (( this.length - 1 )) ));
a[l] = null;
this.length = l;
return x;
}
public final haxe.root.Array<T> slice(int pos, java.lang.Object end)
{
if (( pos < 0 ))
{
pos = ( this.length + pos );
if (( pos < 0 ))
{
pos = 0;
}
}
if (( end == null ))
{
end = this.length;
}
else
{
if (( haxe.lang.Runtime.compare(end, 0) < 0 ))
{
end = ((int) (haxe.lang.Runtime.toInt(haxe.lang.Runtime.plus(this.length, end))) );
}
}
if (( haxe.lang.Runtime.compare(end, this.length) > 0 ))
{
end = this.length;
}
int len = ( ((int) (haxe.lang.Runtime.toInt(end)) ) - ((int) (pos) ) );
if (( len < 0 ))
{
return new haxe.root.Array<T>();
}
T[] newarr = ((T[]) (((java.lang.Object) (new java.lang.Object[((int) (len) )]) )) );
java.lang.System.arraycopy(((java.lang.Object) (this.__a) ), ((int) (pos) ), ((java.lang.Object) (newarr) ), ((int) (0) ), ((int) (len) ));
return haxe.root.Array.ofNative(newarr);
}
public final void sort(haxe.lang.Function f)
{
if (( this.length == 0 ))
{
return ;
}
this.quicksort(0, ( this.length - 1 ), f);
}
public final void quicksort(int lo, int hi, haxe.lang.Function f)
{
T[] buf = this.__a;
int i = lo;
int j = hi;
T p = buf[( ( i + j ) >> 1 )];
while (( i <= j ))
{
while (( ((int) (f.__hx_invoke2_f(0.0, buf[i], 0.0, p)) ) < 0 ))
{
i++;
}
while (( ((int) (f.__hx_invoke2_f(0.0, buf[j], 0.0, p)) ) > 0 ))
{
j--;
}
if (( i <= j ))
{
T t = buf[i];
buf[i++] = buf[j];
buf[j--] = t;
}
}
if (( lo < j ))
{
this.quicksort(lo, j, f);
}
if (( i < hi ))
{
this.quicksort(i, hi, f);
}
}
public final haxe.root.Array<T> splice(int pos, int len)
{
if (( len < 0 ))
{
return new haxe.root.Array<T>();
}
if (( pos < 0 ))
{
pos = ( this.length + pos );
if (( pos < 0 ))
{
pos = 0;
}
}
if (( pos > this.length ))
{
pos = 0;
len = 0;
}
else
{
if (( ( pos + len ) > this.length ))
{
len = ( this.length - pos );
if (( len < 0 ))
{
len = 0;
}
}
}
T[] a = this.__a;
T[] ret = ((T[]) (((java.lang.Object) (new java.lang.Object[((int) (len) )]) )) );
java.lang.System.arraycopy(((java.lang.Object) (a) ), ((int) (pos) ), ((java.lang.Object) (ret) ), ((int) (0) ), ((int) (len) ));
haxe.root.Array<T> ret1 = haxe.root.Array.ofNative(ret);
int end = ( pos + len );
java.lang.System.arraycopy(((java.lang.Object) (a) ), ((int) (end) ), ((java.lang.Object) (a) ), ((int) (pos) ), ((int) (( this.length - end )) ));
this.length -= len;
while (( -- len >= 0 ))
{
a[( this.length + len )] = null;
}
return ret1;
}
public final void spliceVoid(int pos, int len)
{
if (( len < 0 ))
{
return ;
}
if (( pos < 0 ))
{
pos = ( this.length + pos );
if (( pos < 0 ))
{
pos = 0;
}
}
if (( pos > this.length ))
{
pos = 0;
len = 0;
}
else
{
if (( ( pos + len ) > this.length ))
{
len = ( this.length - pos );
if (( len < 0 ))
{
len = 0;
}
}
}
T[] a = this.__a;
int end = ( pos + len );
java.lang.System.arraycopy(((java.lang.Object) (a) ), ((int) (end) ), ((java.lang.Object) (a) ), ((int) (pos) ), ((int) (( this.length - end )) ));
this.length -= len;
while (( -- len >= 0 ))
{
a[( this.length + len )] = null;
}
}
@Override public java.lang.String toString()
{
haxe.root.StringBuf ret = new haxe.root.StringBuf();
T[] a = this.__a;
ret.add("[");
boolean first = true;
{
int _g1 = 0;
int _g = this.length;
while (( _g1 < _g ))
{
int i = _g1++;
if (first)
{
first = false;
}
else
{
ret.add(",");
}
ret.add(a[i]);
}
}
ret.add("]");
return ret.toString();
}
public final void unshift(T x)
{
T[] __a = this.__a;
int length = this.length;
if (( length >= __a.length ))
{
int newLen = ( (( length << 1 )) + 1 );
T[] newarr = ((T[]) (((java.lang.Object) (new java.lang.Object[((int) (newLen) )]) )) );
java.lang.System.arraycopy(((java.lang.Object) (__a) ), ((int) (0) ), ((java.lang.Object) (newarr) ), ((int) (1) ), ((int) (length) ));
this.__a = newarr;
}
else
{
java.lang.System.arraycopy(((java.lang.Object) (__a) ), ((int) (0) ), ((java.lang.Object) (__a) ), ((int) (1) ), ((int) (length) ));
}
this.__a[0] = x;
++ this.length;
}
public final void insert(int pos, T x)
{
int l = this.length;
if (( pos < 0 ))
{
pos = ( l + pos );
if (( pos < 0 ))
{
pos = 0;
}
}
if (( pos >= l ))
{
this.push(x);
return ;
}
else
{
if (( pos == 0 ))
{
this.unshift(x);
return ;
}
}
if (( l >= this.__a.length ))
{
int newLen = ( (( this.length << 1 )) + 1 );
T[] newarr = ((T[]) (((java.lang.Object) (new java.lang.Object[((int) (newLen) )]) )) );
java.lang.System.arraycopy(((java.lang.Object) (this.__a) ), ((int) (0) ), ((java.lang.Object) (newarr) ), ((int) (0) ), ((int) (pos) ));
newarr[pos] = x;
java.lang.System.arraycopy(((java.lang.Object) (this.__a) ), ((int) (pos) ), ((java.lang.Object) (newarr) ), ((int) (( pos + 1 )) ), ((int) (( l - pos )) ));
this.__a = newarr;
++ this.length;
}
else
{
T[] __a = this.__a;
java.lang.System.arraycopy(((java.lang.Object) (__a) ), ((int) (pos) ), ((java.lang.Object) (__a) ), ((int) (( pos + 1 )) ), ((int) (( l - pos )) ));
java.lang.System.arraycopy(((java.lang.Object) (__a) ), ((int) (0) ), ((java.lang.Object) (__a) ), ((int) (0) ), ((int) (pos) ));
__a[pos] = x;
++ this.length;
}
}
public final boolean remove(T x)
{
T[] __a = this.__a;
int i = -1;
int length = this.length;
while (( ++ i < length ))
{
if (haxe.lang.Runtime.eq(__a[i], x))
{
java.lang.System.arraycopy(((java.lang.Object) (__a) ), ((int) (( i + 1 )) ), ((java.lang.Object) (__a) ), ((int) (i) ), ((int) (( ( length - i ) - 1 )) ));
__a[ -- this.length] = null;
return true;
}
}
return false;
}
public final int indexOf(T x, java.lang.Object fromIndex)
{
int len = this.length;
T[] a = this.__a;
int i = 0;
if (( fromIndex == null ))
{
i = 0;
}
else
{
i = ((int) (haxe.lang.Runtime.toInt(fromIndex)) );
}
if (( i < 0 ))
{
i += len;
if (( i < 0 ))
{
i = 0;
}
}
while (( i < len ))
{
if (haxe.lang.Runtime.eq(a[i], x))
{
return i;
}
i++;
}
return -1;
}
public final int lastIndexOf(T x, java.lang.Object fromIndex)
{
int len = this.length;
T[] a = this.__a;
int i = 0;
if (( fromIndex == null ))
{
i = ( len - 1 );
}
else
{
i = ((int) (haxe.lang.Runtime.toInt(fromIndex)) );
}
if (( i >= len ))
{
i = ( len - 1 );
}
else
{
if (( i < 0 ))
{
i += len;
}
}
while (( i >= 0 ))
{
if (haxe.lang.Runtime.eq(a[i], x))
{
return i;
}
i--;
}
return -1;
}
public final haxe.root.Array<T> copy()
{
int len = this.length;
T[] __a = this.__a;
T[] newarr = ((T[]) (((java.lang.Object) (new java.lang.Object[((int) (len) )]) )) );
java.lang.System.arraycopy(((java.lang.Object) (__a) ), ((int) (0) ), ((java.lang.Object) (newarr) ), ((int) (0) ), ((int) (len) ));
return haxe.root.Array.ofNative(newarr);
}
public final java.lang.Object iterator()
{
return new _Array.ArrayIterator<T>(((haxe.root.Array<T>) (this) ));
}
public final <S> haxe.root.Array<S> map(haxe.lang.Function f)
{
haxe.root.Array<S> ret = new haxe.root.Array<S>(( (S[]) (new java.lang.Object[] {}) ));
{
int _g = 0;
haxe.root.Array<T> _g1 = this;
while (( _g < _g1.length ))
{
T elt = _g1.__get(_g);
++ _g;
ret.push(((S) (f.__hx_invoke1_o(0.0, elt)) ));
}
}
return ret;
}
public final haxe.root.Array<T> filter(haxe.lang.Function f)
{
haxe.root.Array<T> ret = new haxe.root.Array<T>(( (T[]) (new java.lang.Object[] {}) ));
{
int _g = 0;
haxe.root.Array<T> _g1 = this;
while (( _g < _g1.length ))
{
T elt = _g1.__get(_g);
++ _g;
if (haxe.lang.Runtime.toBool(f.__hx_invoke1_o(0.0, elt)))
{
ret.push(elt);
}
}
}
return ret;
}
public final T __get(int idx)
{
T[] __a = this.__a;
if (( ( idx >= __a.length ) || ( idx < 0 ) ))
{
return null;
}
return __a[idx];
}
public final T __set(int idx, T v)
{
T[] __a = this.__a;
if (( idx >= __a.length ))
{
int newl = ( idx + 1 );
if (( idx == __a.length ))
{
newl = ( (( idx << 1 )) + 1 );
}
T[] newArr = ((T[]) (((java.lang.Object) (new java.lang.Object[((int) (newl) )]) )) );
if (( this.length > 0 ))
{
java.lang.System.arraycopy(((java.lang.Object) (__a) ), ((int) (0) ), ((java.lang.Object) (newArr) ), ((int) (0) ), ((int) (this.length) ));
}
this.__a = __a = newArr;
}
if (( idx >= this.length ))
{
this.length = ( idx + 1 );
}
return __a[idx] = v;
}
public final T __unsafe_get(int idx)
{
return this.__a[idx];
}
public final T __unsafe_set(int idx, T val)
{
return this.__a[idx] = val;
}
@Override public double __hx_setField_f(java.lang.String field, double value, boolean handleProperties)
{
{
boolean __temp_executeDef3269 = true;
switch (field.hashCode())
{
case -1106363674:
{
if (field.equals("length"))
{
__temp_executeDef3269 = false;
this.length = ((int) (value) );
return value;
}
break;
}
}
if (__temp_executeDef3269)
{
return super.__hx_setField_f(field, value, handleProperties);
}
else
{
throw null;
}
}
}
@Override public java.lang.Object __hx_setField(java.lang.String field, java.lang.Object value, boolean handleProperties)
{
{
boolean __temp_executeDef3270 = true;
switch (field.hashCode())
{
case 94337:
{
if (field.equals("__a"))
{
__temp_executeDef3270 = false;
this.__a = ((T[]) (value) );
return value;
}
break;
}
case -1106363674:
{
if (field.equals("length"))
{
__temp_executeDef3270 = false;
this.length = ((int) (haxe.lang.Runtime.toInt(value)) );
return value;
}
break;
}
}
if (__temp_executeDef3270)
{
return super.__hx_setField(field, value, handleProperties);
}
else
{
throw null;
}
}
}
@Override public java.lang.Object __hx_getField(java.lang.String field, boolean throwErrors, boolean isCheck, boolean handleProperties)
{
{
boolean __temp_executeDef3271 = true;
switch (field.hashCode())
{
case -537840087:
{
if (field.equals("__unsafe_set"))
{
__temp_executeDef3271 = false;
return ((haxe.lang.Function) (new haxe.lang.Closure(((java.lang.Object) (this) ), haxe.lang.Runtime.toString("__unsafe_set"))) );
}
break;
}
case -1106363674:
{
if (field.equals("length"))
{
__temp_executeDef3271 = false;
return this.length;
}
break;
}
case -537851619:
{
if (field.equals("__unsafe_get"))
{
__temp_executeDef3271 = false;
return ((haxe.lang.Function) (new haxe.lang.Closure(((java.lang.Object) (this) ), haxe.lang.Runtime.toString("__unsafe_get"))) );
}
break;
}
case 94337:
{
if (field.equals("__a"))
{
__temp_executeDef3271 = false;
return this.__a;
}
break;
}
case 90678402:
{
if (field.equals("__set"))
{
__temp_executeDef3271 = false;
return ((haxe.lang.Function) (new haxe.lang.Closure(((java.lang.Object) (this) ), haxe.lang.Runtime.toString("__set"))) );
}
break;
}
case -1354795244:
{
if (field.equals("concat"))
{
__temp_executeDef3271 = false;
return ((haxe.lang.Function) (new haxe.lang.Closure(((java.lang.Object) (this) ), haxe.lang.Runtime.toString("concat"))) );
}
break;
}
case 90666870:
{
if (field.equals("__get"))
{
__temp_executeDef3271 = false;
return ((haxe.lang.Function) (new haxe.lang.Closure(((java.lang.Object) (this) ), haxe.lang.Runtime.toString("__get"))) );
}
break;
}
case -1238494133:
{
if (field.equals("concatNative"))
{
__temp_executeDef3271 = false;
return ((haxe.lang.Function) (new haxe.lang.Closure(((java.lang.Object) (this) ), haxe.lang.Runtime.toString("concatNative"))) );
}
break;
}
case -1274492040:
{
if (field.equals("filter"))
{
__temp_executeDef3271 = false;
return ((haxe.lang.Function) (new haxe.lang.Closure(((java.lang.Object) (this) ), haxe.lang.Runtime.toString("filter"))) );
}
break;
}
case 3267882:
{
if (field.equals("join"))
{
__temp_executeDef3271 = false;
return ((haxe.lang.Function) (new haxe.lang.Closure(((java.lang.Object) (this) ), haxe.lang.Runtime.toString("join"))) );
}
break;
}
case 107868:
{
if (field.equals("map"))
{
__temp_executeDef3271 = false;
return ((haxe.lang.Function) (new haxe.lang.Closure(((java.lang.Object) (this) ), haxe.lang.Runtime.toString("map"))) );
}
break;
}
case 111185:
{
if (field.equals("pop"))
{
__temp_executeDef3271 = false;
return ((haxe.lang.Function) (new haxe.lang.Closure(((java.lang.Object) (this) ), haxe.lang.Runtime.toString("pop"))) );
}
break;
}
case 1182533742:
{
if (field.equals("iterator"))
{
__temp_executeDef3271 = false;
return ((haxe.lang.Function) (new haxe.lang.Closure(((java.lang.Object) (this) ), haxe.lang.Runtime.toString("iterator"))) );
}
break;
}
case 3452698:
{
if (field.equals("push"))
{
__temp_executeDef3271 = false;
return ((haxe.lang.Function) (new haxe.lang.Closure(((java.lang.Object) (this) ), haxe.lang.Runtime.toString("push"))) );
}
break;
}
case 3059573:
{
if (field.equals("copy"))
{
__temp_executeDef3271 = false;
return ((haxe.lang.Function) (new haxe.lang.Closure(((java.lang.Object) (this) ), haxe.lang.Runtime.toString("copy"))) );
}
break;
}
case 1099846370:
{
if (field.equals("reverse"))
{
__temp_executeDef3271 = false;
return ((haxe.lang.Function) (new haxe.lang.Closure(((java.lang.Object) (this) ), haxe.lang.Runtime.toString("reverse"))) );
}
break;
}
case -467511597:
{
if (field.equals("lastIndexOf"))
{
__temp_executeDef3271 = false;
return ((haxe.lang.Function) (new haxe.lang.Closure(((java.lang.Object) (this) ), haxe.lang.Runtime.toString("lastIndexOf"))) );
}
break;
}
case 109407362:
{
if (field.equals("shift"))
{
__temp_executeDef3271 = false;
return ((haxe.lang.Function) (new haxe.lang.Closure(((java.lang.Object) (this) ), haxe.lang.Runtime.toString("shift"))) );
}
break;
}
case 1943291465:
{
if (field.equals("indexOf"))
{
__temp_executeDef3271 = false;
return ((haxe.lang.Function) (new haxe.lang.Closure(((java.lang.Object) (this) ), haxe.lang.Runtime.toString("indexOf"))) );
}
break;
}
case 109526418:
{
if (field.equals("slice"))
{
__temp_executeDef3271 = false;
return ((haxe.lang.Function) (new haxe.lang.Closure(((java.lang.Object) (this) ), haxe.lang.Runtime.toString("slice"))) );
}
break;
}
case -934610812:
{
if (field.equals("remove"))
{
__temp_executeDef3271 = false;
return ((haxe.lang.Function) (new haxe.lang.Closure(((java.lang.Object) (this) ), haxe.lang.Runtime.toString("remove"))) );
}
break;
}
case 3536286:
{
if (field.equals("sort"))
{
__temp_executeDef3271 = false;
return ((haxe.lang.Function) (new haxe.lang.Closure(((java.lang.Object) (this) ), haxe.lang.Runtime.toString("sort"))) );
}
break;
}
case -1183792455:
{
if (field.equals("insert"))
{
__temp_executeDef3271 = false;
return ((haxe.lang.Function) (new haxe.lang.Closure(((java.lang.Object) (this) ), haxe.lang.Runtime.toString("insert"))) );
}
break;
}
case 1301699851:
{
if (field.equals("quicksort"))
{
__temp_executeDef3271 = false;
return ((haxe.lang.Function) (new haxe.lang.Closure(((java.lang.Object) (this) ), haxe.lang.Runtime.toString("quicksort"))) );
}
break;
}
case -277637751:
{
if (field.equals("unshift"))
{
__temp_executeDef3271 = false;
return ((haxe.lang.Function) (new haxe.lang.Closure(((java.lang.Object) (this) ), haxe.lang.Runtime.toString("unshift"))) );
}
break;
}
case -895859076:
{
if (field.equals("splice"))
{
__temp_executeDef3271 = false;
return ((haxe.lang.Function) (new haxe.lang.Closure(((java.lang.Object) (this) ), haxe.lang.Runtime.toString("splice"))) );
}
break;
}
case -1776922004:
{
if (field.equals("toString"))
{
__temp_executeDef3271 = false;
return ((haxe.lang.Function) (new haxe.lang.Closure(((java.lang.Object) (this) ), haxe.lang.Runtime.toString("toString"))) );
}
break;
}
case -821858768:
{
if (field.equals("spliceVoid"))
{
__temp_executeDef3271 = false;
return ((haxe.lang.Function) (new haxe.lang.Closure(((java.lang.Object) (this) ), haxe.lang.Runtime.toString("spliceVoid"))) );
}
break;
}
}
if (__temp_executeDef3271)
{
return super.__hx_getField(field, throwErrors, isCheck, handleProperties);
}
else
{
throw null;
}
}
}
@Override public double __hx_getField_f(java.lang.String field, boolean throwErrors, boolean handleProperties)
{
{
boolean __temp_executeDef3272 = true;
switch (field.hashCode())
{
case -1106363674:
{
if (field.equals("length"))
{
__temp_executeDef3272 = false;
return ((double) (this.length) );
}
break;
}
}
if (__temp_executeDef3272)
{
return super.__hx_getField_f(field, throwErrors, handleProperties);
}
else
{
throw null;
}
}
}
@Override public java.lang.Object __hx_invokeField(java.lang.String field, haxe.root.Array dynargs)
{
{
boolean __temp_executeDef3273 = true;
switch (field.hashCode())
{
case -537840087:
{
if (field.equals("__unsafe_set"))
{
__temp_executeDef3273 = false;
return this.__unsafe_set(((int) (haxe.lang.Runtime.toInt(dynargs.__get(0))) ), ((T) (dynargs.__get(1)) ));
}
break;
}
case -1354795244:
{
if (field.equals("concat"))
{
__temp_executeDef3273 = false;
return this.concat(((haxe.root.Array<T>) (dynargs.__get(0)) ));
}
break;
}
case -537851619:
{
if (field.equals("__unsafe_get"))
{
__temp_executeDef3273 = false;
return this.__unsafe_get(((int) (haxe.lang.Runtime.toInt(dynargs.__get(0))) ));
}
break;
}
case -1238494133:
{
if (field.equals("concatNative"))
{
__temp_executeDef3273 = false;
this.concatNative(((T[]) (dynargs.__get(0)) ));
}
break;
}
case 90678402:
{
if (field.equals("__set"))
{
__temp_executeDef3273 = false;
return this.__set(((int) (haxe.lang.Runtime.toInt(dynargs.__get(0))) ), ((T) (dynargs.__get(1)) ));
}
break;
}
case 3267882:
{
if (field.equals("join"))
{
__temp_executeDef3273 = false;
return this.join(haxe.lang.Runtime.toString(dynargs.__get(0)));
}
break;
}
case 90666870:
{
if (field.equals("__get"))
{
__temp_executeDef3273 = false;
return this.__get(((int) (haxe.lang.Runtime.toInt(dynargs.__get(0))) ));
}
break;
}
case 111185:
{
if (field.equals("pop"))
{
__temp_executeDef3273 = false;
return this.pop();
}
break;
}
case -1274492040:
{
if (field.equals("filter"))
{
__temp_executeDef3273 = false;
return this.filter(((haxe.lang.Function) (dynargs.__get(0)) ));
}
break;
}
case 3452698:
{
if (field.equals("push"))
{
__temp_executeDef3273 = false;
return this.push(((T) (dynargs.__get(0)) ));
}
break;
}
case 107868:
{
if (field.equals("map"))
{
__temp_executeDef3273 = false;
return this.map(((haxe.lang.Function) (dynargs.__get(0)) ));
}
break;
}
case 1099846370:
{
if (field.equals("reverse"))
{
__temp_executeDef3273 = false;
this.reverse();
}
break;
}
case 1182533742:
{
if (field.equals("iterator"))
{
__temp_executeDef3273 = false;
return this.iterator();
}
break;
}
case 109407362:
{
if (field.equals("shift"))
{
__temp_executeDef3273 = false;
return this.shift();
}
break;
}
case 3059573:
{
if (field.equals("copy"))
{
__temp_executeDef3273 = false;
return this.copy();
}
break;
}
case 109526418:
{
if (field.equals("slice"))
{
__temp_executeDef3273 = false;
return this.slice(((int) (haxe.lang.Runtime.toInt(dynargs.__get(0))) ), dynargs.__get(1));
}
break;
}
case -467511597:
{
if (field.equals("lastIndexOf"))
{
__temp_executeDef3273 = false;
return this.lastIndexOf(((T) (dynargs.__get(0)) ), dynargs.__get(1));
}
break;
}
case 3536286:
{
if (field.equals("sort"))
{
__temp_executeDef3273 = false;
this.sort(((haxe.lang.Function) (dynargs.__get(0)) ));
}
break;
}
case 1943291465:
{
if (field.equals("indexOf"))
{
__temp_executeDef3273 = false;
return this.indexOf(((T) (dynargs.__get(0)) ), dynargs.__get(1));
}
break;
}
case 1301699851:
{
if (field.equals("quicksort"))
{
__temp_executeDef3273 = false;
this.quicksort(((int) (haxe.lang.Runtime.toInt(dynargs.__get(0))) ), ((int) (haxe.lang.Runtime.toInt(dynargs.__get(1))) ), ((haxe.lang.Function) (dynargs.__get(2)) ));
}
break;
}
case -934610812:
{
if (field.equals("remove"))
{
__temp_executeDef3273 = false;
return this.remove(((T) (dynargs.__get(0)) ));
}
break;
}
case -895859076:
{
if (field.equals("splice"))
{
__temp_executeDef3273 = false;
return this.splice(((int) (haxe.lang.Runtime.toInt(dynargs.__get(0))) ), ((int) (haxe.lang.Runtime.toInt(dynargs.__get(1))) ));
}
break;
}
case -1183792455:
{
if (field.equals("insert"))
{
__temp_executeDef3273 = false;
this.insert(((int) (haxe.lang.Runtime.toInt(dynargs.__get(0))) ), ((T) (dynargs.__get(1)) ));
}
break;
}
case -821858768:
{
if (field.equals("spliceVoid"))
{
__temp_executeDef3273 = false;
this.spliceVoid(((int) (haxe.lang.Runtime.toInt(dynargs.__get(0))) ), ((int) (haxe.lang.Runtime.toInt(dynargs.__get(1))) ));
}
break;
}
case -277637751:
{
if (field.equals("unshift"))
{
__temp_executeDef3273 = false;
this.unshift(((T) (dynargs.__get(0)) ));
}
break;
}
case -1776922004:
{
if (field.equals("toString"))
{
__temp_executeDef3273 = false;
return this.toString();
}
break;
}
}
if (__temp_executeDef3273)
{
return super.__hx_invokeField(field, dynargs);
}
}
return null;
}
@Override public void __hx_getFields(haxe.root.Array<java.lang.String> baseArr)
{
baseArr.push("__a");
baseArr.push("length");
{
super.__hx_getFields(baseArr);
}
}
}
| 19.465744
| 173
| 0.518427
|
33b3f8b1f761c1c6d1b9750ffe8f0436de27cf22
| 5,266
|
c
|
C
|
src/main/sdvxhook2/dllmain.c
|
Soyandroid/bemanitools
|
0fd499266f4d724b8eea7217a6fd4e6a0caba948
|
[
"Unlicense"
] | 5
|
2021-12-20T02:57:07.000Z
|
2022-02-28T20:19:26.000Z
|
src/main/sdvxhook2/dllmain.c
|
Soyandroid/bemanitools
|
0fd499266f4d724b8eea7217a6fd4e6a0caba948
|
[
"Unlicense"
] | null | null | null |
src/main/sdvxhook2/dllmain.c
|
Soyandroid/bemanitools
|
0fd499266f4d724b8eea7217a6fd4e6a0caba948
|
[
"Unlicense"
] | 1
|
2021-12-21T18:49:01.000Z
|
2021-12-21T18:49:01.000Z
|
#include <windows.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include "bemanitools/eamio.h"
#include "bemanitools/sdvxio.h"
#include "cconfig/cconfig-hook.h"
#include "hooklib/acp.h"
#include "hooklib/adapter.h"
#include "hooklib/app.h"
#include "hooklib/config-adapter.h"
#include "hooklib/memfile.h"
#include "hooklib/rs232.h"
#include "bio2emu/emu.h"
#include "sdvxhook2/acio.h"
#include "sdvxhook2/bi2a.h"
#include "sdvxhook2/config-io.h"
#include "camhook/cam.h"
#include "camhook/config-cam.h"
#include "d3d9exhook/config-gfx.h"
#include "d3d9exhook/d3d9ex.h"
#include "imports/avs.h"
#include "util/log.h"
#include "util/str.h"
#include "util/thread.h"
#define SDVXHOOK2_INFO_HEADER \
"sdvxhook for VW" \
", build " __DATE__ " " __TIME__ ", gitrev " STRINGIFY(GITREV) "\n"
#define SDVXHOOK2_CMD_USAGE \
"Usage: launcher.exe -K sdvxhook2.dll <soundvoltex.dll> [options...]"
struct sdvxhook2_config_io config_io;
struct camhook_config_cam config_cam;
struct d3d9exhook_config_gfx config_gfx;
struct hooklib_config_adapter config_adapter;
static struct bio2emu_port bio2_emu = {
.port = "COM4",
.wport = L"\\\\.\\COM4",
.dispatcher = bio2_emu_bi2a_dispatch_request,
};
static void attach_dest_fd_intercept(const char *sidcode)
{
char region = sidcode[3];
if (region == 'X') {
region = 'J';
}
char target_file[8] = "\\x.dest";
target_file[1] = tolower(region);
// can only capture these by ending path due to /dev/raw being mountable
memfile_hook_add_fd(target_file, ENDING_MATCH, NULL, 0);
}
static bool my_dll_entry_init(char *sidcode, struct property_node *param)
{
struct cconfig *config;
log_info("--- Begin sdvxhook dll_entry_init ---");
config = cconfig_init();
sdvxhook2_config_io_init(config);
d3d9exhook_config_gfx_init(config);
camhook_config_cam_init(config, 1);
hooklib_config_adapter_init(config);
if (!cconfig_hook_config_init(
config,
SDVXHOOK2_INFO_HEADER "\n" SDVXHOOK2_CMD_USAGE,
CCONFIG_CMD_USAGE_OUT_STDOUT)) {
cconfig_finit(config);
exit(EXIT_FAILURE);
}
sdvxhook2_config_io_get(&config_io, config);
camhook_config_cam_get(&config_cam, config, 1);
d3d9exhook_config_gfx_get(&config_gfx, config);
hooklib_config_adapter_get(&config_adapter, config);
cconfig_finit(config);
log_info(SDVXHOOK2_INFO_HEADER);
log_info("Initializing sdvxhook2...");
d3d9ex_configure(&config_gfx);
/* Start up sdvxio.DLL */
if (!config_io.disable_bio2_emu) {
log_info("Starting sdvx IO backend");
sdvx_io_set_loggers(
log_impl_misc, log_impl_info, log_impl_warning, log_impl_fatal);
if (!sdvx_io_init(
avs_thread_create, avs_thread_join, avs_thread_destroy)) {
log_fatal("Initializing sdvx IO backend failed");
}
}
/* Start up EAMIO.DLL */
if (!config_io.disable_card_reader_emu) {
log_misc("Initializing card reader backend");
eam_io_set_loggers(
log_impl_misc, log_impl_info, log_impl_warning, log_impl_fatal);
if (!eam_io_init(
avs_thread_create, avs_thread_join, avs_thread_destroy)) {
log_fatal("Initializing card reader backend failed");
}
}
/* iohooks are okay, even if emu is diabled since the fake handlers won't be
* used */
iohook_push_handler(ac_io_port_dispatch_irp);
iohook_push_handler(bio2emu_port_dispatch_irp);
if (!config_io.disable_file_hooks) {
memfile_hook_init();
iohook_push_handler(memfile_hook_dispatch_irp);
attach_dest_fd_intercept(sidcode);
}
rs232_hook_init();
rs232_hook_limit_hooks();
if (!config_io.disable_bio2_emu) {
bio2emu_init();
bio2_emu_bi2a_init(
&bio2_emu,
config_io.disable_poll_limiter,
config_io.force_headphones);
}
if (!config_io.disable_card_reader_emu) {
ac_io_port_init();
}
// camera hooks
if (!config_cam.disable_emu) {
camhook_init(&config_cam);
}
adapter_hook_override(config_adapter.override_ip);
log_info("--- End sdvxhook dll_entry_init ---");
return app_hook_invoke_init(sidcode, param);
}
static bool my_dll_entry_main(void)
{
bool result;
result = app_hook_invoke_main();
if (!config_cam.disable_emu) {
camhook_fini();
}
if (!config_io.disable_card_reader_emu) {
log_misc("Shutting down card reader backend");
eam_io_fini();
}
if (!config_io.disable_bio2_emu) {
log_misc("Shutting down sdvx IO backend");
sdvx_io_fini();
}
if (!config_io.disable_file_hooks) {
memfile_hook_fini();
}
return result;
}
/**
* Hook library SDVX5+
*/
BOOL WINAPI DllMain(HMODULE mod, DWORD reason, void *ctx)
{
if (reason != DLL_PROCESS_ATTACH) {
goto end;
}
log_to_external(
log_body_misc, log_body_info, log_body_warning, log_body_fatal);
app_hook_init(my_dll_entry_init, my_dll_entry_main);
acp_hook_init();
adapter_hook_init();
d3d9ex_hook_init();
end:
return TRUE;
}
| 24.723005
| 80
| 0.675655
|
45a30f07369e97e7d560fcf15976b0f6a7918379
| 4,538
|
py
|
Python
|
xchainpy/xchainpy_litecoin/xchainpy_litecoin/sochain_api.py
|
tirinox/xchainpy-lib
|
e01f146993c45ca0dad3ca40f07e7b45ed65653e
|
[
"MIT"
] | null | null | null |
xchainpy/xchainpy_litecoin/xchainpy_litecoin/sochain_api.py
|
tirinox/xchainpy-lib
|
e01f146993c45ca0dad3ca40f07e7b45ed65653e
|
[
"MIT"
] | null | null | null |
xchainpy/xchainpy_litecoin/xchainpy_litecoin/sochain_api.py
|
tirinox/xchainpy-lib
|
e01f146993c45ca0dad3ca40f07e7b45ed65653e
|
[
"MIT"
] | null | null | null |
import json
import http3
def to_sochain_network(net: str):
return 'LTCTEST' if net == 'testnet' else 'LTC'
async def get_balance(sochain_url:str, net:str, address:str):
"""Get address balance
https://sochain.com/api#get-balance
:param net: mainnet or testnet
:type net: str
:param address: wallet address
:type address: str
:returns: The fees with memo
"""
try:
api_url = f'{sochain_url}/get_address_balance/{to_sochain_network(net)}/{address}'
client = http3.AsyncClient()
response = await client.get(api_url)
if response.status_code == 200:
balance_response = json.loads(response.content.decode('utf-8'))['data']
confirmed = float(balance_response['confirmed_balance'])
unconfirmed = float(balance_response['unconfirmed_balance'])
total = confirmed + unconfirmed
return total
else:
return None
except Exception as err:
raise Exception(str(err))
async def get_transactions(sochain_url:str, net:str, address:str):
"""Get address information
https://sochain.com/api#get-display-data-address
:param net: mainnet or testnet
:type net: str
:param address: wallet address
:type address: str
:returns: The fees with memo
"""
try:
api_url = f'{sochain_url}/address/{to_sochain_network(net)}/{address}'
client = http3.AsyncClient()
response = await client.get(api_url)
if response.status_code == 200:
return json.loads(response.content.decode('utf-8'))['data']
else:
return None
except Exception as err:
raise Exception(str(err))
async def get_tx(sochain_url:str, net: str, hash: str):
"""Get transaction by hash
https://sochain.com/api#get-tx
:param net: mainnet or testnet
:type net: str
:param hash: The transaction hash
:type hash: str
:returns: The fees with memo
"""
try:
api_url = f'{sochain_url}/get_tx/{to_sochain_network(net)}/{hash}'
client = http3.AsyncClient()
response = await client.get(api_url)
if response.status_code == 200:
return json.loads(response.content.decode('utf-8'))['data']
else:
return None
except Exception as err:
raise Exception(str(err))
async def get_suggested_tx_fee():
"""Get Litecoin suggested transaction fee
Note: sochain does not provide fee rate related data
So use Bitgo API for fee estimation
Refer: https://app.bitgo.com/docs/#operation/v2.tx.getfeeestimate
:returns: The Litecoin suggested transaction fee per bytes in sat
"""
try:
api_url = 'https://app.bitgo.com/api/v2/ltc/tx/fee'
client = http3.AsyncClient()
response = await client.get(api_url)
if response.status_code == 200:
return json.loads(response.content.decode('utf-8'))['feePerKb'] / 1000 # feePerKb to feePerByte
else:
return None
except Exception as err:
raise Exception(str(err))
async def get_unspent_txs(sochain_url, network, address):
"""Get address balance
https://sochain.com/api#get-unspent-tx
:param network: testnet or mainnet
:type network: str
:param address: address
:type address: str
:returns: A list of utxo's
"""
try:
api_url = f'{sochain_url}/get_tx_unspent/{to_sochain_network(network)}/{address}'
client = http3.AsyncClient()
response = await client.get(api_url)
if response.status_code == 200:
txs = json.loads(response.content.decode('utf-8'))['data']['txs']
return txs
except Exception as err:
raise Exception(str(err))
async def broadcast_tx(sochain_url, network, tx_hex):
"""Broadcast transaction
https://sochain.com/api#send-transaction
:param network: testnet or mainnet
:type network: str
:param tx_hex: tranaction hex
:type tx_hex: str
:returns: Transaction ID
"""
try:
api_url = f'{sochain_url}/send_tx/{to_sochain_network(network)}'
client = http3.AsyncClient()
response = await client.post(url=api_url, data={'tx_hex': tx_hex})
if response.status_code == 200:
res = json.loads(response.content.decode('utf-8'))['data']
return res['txid']
else:
return json.loads(response.content.decode('utf-8'))['data']
except Exception as err:
raise Exception(str(err))
| 30.456376
| 107
| 0.636844
|
532fa77e7818b412ad6f41d9e107f67e24f51ff7
| 584
|
ps1
|
PowerShell
|
Exchange/Exchange-resource-get-information.ps1
|
badgumby/powershell-scripts
|
24cc5f15543c99e915fe61d03574db31e58aac35
|
[
"MIT"
] | null | null | null |
Exchange/Exchange-resource-get-information.ps1
|
badgumby/powershell-scripts
|
24cc5f15543c99e915fe61d03574db31e58aac35
|
[
"MIT"
] | null | null | null |
Exchange/Exchange-resource-get-information.ps1
|
badgumby/powershell-scripts
|
24cc5f15543c99e915fe61d03574db31e58aac35
|
[
"MIT"
] | null | null | null |
Set-MailboxFolderPermission -AccessRights LimitedDetails somemailbox@domain.com:\Calendar -User default
Set-CalendarProcessing somemailbox@domain.com -AddOrganizerToSubject $true -DeleteSubject $true
$mailboxlist = Get-Mailbox -RecipientTypeDetails RoomMailbox | Get-CalendarProcessing | Select Identity,AddOrganizerToSubject,DeleteSubject
$mailboxlist2 = get-mailbox -RecipientTypeDetails RoomMailbox | Get-MailboxFolderPermission | Select AccessRights
Get-MailboxFolderPermission somemailbox@domain.com | select * | format-list
Get-CalendarProcessing somemailbox@domain.com | FL
| 64.888889
| 139
| 0.851027
|
e0cd095b74c440946dacf2e2f1f67fed0e3d67ee
| 146
|
lua
|
Lua
|
garrysmod/gamemodes/darkrp/plugins/anomalies/sh_plugin.lua
|
Kek1ch/Kek1ch
|
fa545ac1c261c20639ba7a7119ccd7aa4aaacbdc
|
[
"Apache-2.0"
] | 7
|
2019-06-15T09:10:59.000Z
|
2021-11-21T18:15:03.000Z
|
garrysmod/gamemodes/darkrp/plugins/anomalies/sh_plugin.lua
|
Kek1ch/Kek1ch
|
fa545ac1c261c20639ba7a7119ccd7aa4aaacbdc
|
[
"Apache-2.0"
] | null | null | null |
garrysmod/gamemodes/darkrp/plugins/anomalies/sh_plugin.lua
|
Kek1ch/Kek1ch
|
fa545ac1c261c20639ba7a7119ccd7aa4aaacbdc
|
[
"Apache-2.0"
] | 6
|
2019-06-15T08:33:15.000Z
|
2020-10-25T07:50:32.000Z
|
local PLUGIN = PLUGIN
PLUGIN.name = "ANOMS"
PLUGIN.author = "Kek1ch&WickedRabbit"
PLUGIN.desc = "Sample text"
nut.util.include("sv_plugin.lua")
| 18.25
| 37
| 0.739726
|
2c5784109944beece4969dfd149b7e4707b326f3
| 2,598
|
py
|
Python
|
backend/projects/models.py
|
singsaker/intern
|
9376732c6d537f46443ad43afa51e82df2005da8
|
[
"MIT"
] | 4
|
2021-10-06T19:09:12.000Z
|
2022-03-28T12:14:42.000Z
|
backend/projects/models.py
|
singsaker/intern
|
9376732c6d537f46443ad43afa51e82df2005da8
|
[
"MIT"
] | 2
|
2021-11-30T16:07:05.000Z
|
2022-02-17T23:57:00.000Z
|
backend/projects/models.py
|
singsaker/intern
|
9376732c6d537f46443ad43afa51e82df2005da8
|
[
"MIT"
] | null | null | null |
from datetime import timedelta
from django.db import models
from members.models import Member
class ProjectCategory(models.Model):
name = models.CharField(max_length=20)
def __str__(self) -> str:
return self.name
class Meta:
verbose_name_plural = "Project Categories"
class Project(models.Model):
name = models.CharField(max_length=30)
hours = models.IntegerField(default=2964)
description = models.TextField(blank=True, null=True)
project_category = models.ForeignKey(ProjectCategory, on_delete=models.CASCADE)
start_date = models.DateField(blank=True, null=True)
end_date = models.DateField(blank=True, null=True)
members = models.ManyToManyField(Member, related_name="projects", through="ProjectMember", blank=True)
parent_project = models.ForeignKey(
"self",
blank=True,
null=True,
related_name="child_project",
on_delete=models.CASCADE,
)
def __str__(self) -> str:
return self.name
# Gjenstående timer per pers
# Hver bruker får tilegnet en gitt mengde timer på prosjekt
class ProjectMember(models.Model):
member = models.ForeignKey(
Member,
on_delete=models.CASCADE,
)
project = models.ForeignKey(Project, on_delete=models.CASCADE, related_name="project_members")
allocated_time = models.IntegerField(default=0)
def __str__(self) -> str:
return f"{self.member} deltar i {self.project}"
class WorkCategory(models.Model):
name = models.CharField(max_length=20)
def __str__(self) -> str:
return self.name
class Meta:
verbose_name_plural = "Work Categories"
class Work(models.Model):
class Status(models.IntegerChoices):
PENDING = 1
APPROVED = 2
DISAPPROVED = 3
INACTIVE = 4
project = models.ForeignKey(Project, on_delete=models.CASCADE)
task_category = models.ForeignKey(WorkCategory, on_delete=models.CASCADE)
member = models.ForeignKey(Member, on_delete=models.CASCADE)
description = models.TextField(blank=True, null=True)
duration = models.DurationField(default=timedelta(0))
execution_date = models.DateField(blank=True, null=True)
register_date = models.DateField(blank=True, null=True)
status = models.IntegerField(choices=Status.choices, default=Status.PENDING)
def __str__(self) -> str:
return str(self.member) + ": " + str(self.task_category)
class Meta:
verbose_name_plural = "Work"
# class Task(models.Model): -> Dersom det blir aktuelt å lyse ut oppgaver på internsiden
| 29.862069
| 106
| 0.699384
|
3a586cfbe740f420f8067fcdee51d16db65a7a25
| 639
|
dart
|
Dart
|
lib/utils.dart
|
chaangliu/hybrid_stack_manager
|
cad3a18da9e1d5738e6bb7fd0788b73c5a3d52ab
|
[
"MIT"
] | 8
|
2019-02-18T01:31:48.000Z
|
2021-02-23T10:32:08.000Z
|
lib/utils.dart
|
chaangliu/hybrid_stack_manager
|
cad3a18da9e1d5738e6bb7fd0788b73c5a3d52ab
|
[
"MIT"
] | null | null | null |
lib/utils.dart
|
chaangliu/hybrid_stack_manager
|
cad3a18da9e1d5738e6bb7fd0788b73c5a3d52ab
|
[
"MIT"
] | 2
|
2019-03-06T07:45:33.000Z
|
2021-02-23T10:32:09.000Z
|
class Utils extends Object {
static int baseId = 100;
static String pageNameSeperatorToken = "_";
static String lastGeneratedPageName = "";
static int generatePrimaryPageId() {
return baseId++;
}
static Map parseUniquePageName(String pageName) {
List components = pageName.split(pageNameSeperatorToken);
if (components.length != 2) return null;
return {"name": components[0], "id": components[1]};
}
static String generateUniquePageName(String pageName) {
lastGeneratedPageName = (pageName ?? "") + pageNameSeperatorToken + generatePrimaryPageId().toString();
return lastGeneratedPageName;
}
}
| 30.428571
| 107
| 0.719875
|
ba2928c411e1656a3d35fd5494bbbe21665e5cfb
| 647
|
go
|
Go
|
pkg/ast/create_am_stmt_fingerprint.go
|
elliotcourant/melogale
|
113bf14e67ca26912502283546c35ddea1a1a57b
|
[
"Apache-2.0"
] | null | null | null |
pkg/ast/create_am_stmt_fingerprint.go
|
elliotcourant/melogale
|
113bf14e67ca26912502283546c35ddea1a1a57b
|
[
"Apache-2.0"
] | null | null | null |
pkg/ast/create_am_stmt_fingerprint.go
|
elliotcourant/melogale
|
113bf14e67ca26912502283546c35ddea1a1a57b
|
[
"Apache-2.0"
] | null | null | null |
// Auto-generated - DO NOT EDIT
package ast
func (node CreateAmStmt) Fingerprint(ctx FingerprintContext, parentNode Node, parentFieldName string) {
ctx.WriteString("CreateAmStmt")
if node.Amname != nil {
ctx.WriteString("amname")
ctx.WriteString(*node.Amname)
}
if node.Amtype != 0 {
ctx.WriteString("amtype")
ctx.WriteString(string(node.Amtype))
}
if len(node.HandlerName.Items) > 0 {
subCtx := FingerprintSubContext{}
node.HandlerName.Fingerprint(&subCtx, node, "HandlerName")
if len(subCtx.parts) > 0 {
ctx.WriteString("handler_name")
for _, part := range subCtx.parts {
ctx.WriteString(part)
}
}
}
}
| 20.870968
| 103
| 0.698609
|
dbeeab76c79737251daee3ce569fd076fb94dba8
| 1,175
|
php
|
PHP
|
full-testimonial-loop.php
|
TagTheAgency/leadgrowth-wp
|
28b7743033a4083c877a16cbbe02f5c16375c992
|
[
"MIT"
] | null | null | null |
full-testimonial-loop.php
|
TagTheAgency/leadgrowth-wp
|
28b7743033a4083c877a16cbbe02f5c16375c992
|
[
"MIT"
] | null | null | null |
full-testimonial-loop.php
|
TagTheAgency/leadgrowth-wp
|
28b7743033a4083c877a16cbbe02f5c16375c992
|
[
"MIT"
] | null | null | null |
<?php $args = array('post_type' => 'testimonial'); ?>
<?php $loop = new WP_query($args); ?>
<?php if ($loop->have_posts()):?>
<div class="container-fluid py-5">
<div class="container shadow-me">
<div class="row text-primary justify-content-center">
<div class="col-auto mb-3">
<h2>Testimonies</h2>
</div>
</div>
<?php while($loop->have_posts()):$loop->the_post(); ?>
<div class="row justify-content-center align-items-center mb-3">
<a href="<?php the_permalink(); ?>" class="testimony row col-11 py-4 px-3 primary rounded justify-content-center align-items-center testimonial-item">
<div class="col-auto col-md-2 mb-4 mb-md-0">
<div class="img-container testimonial-image-small">
<?php the_post_thumbnail(); ?>
</div>
</div>
<div class="col-12 col-md-9 text-left">
<div class="col-12 mb-3 testiominal-text">
<p><?php the_excerpt(); ?></p>
</div>
<div class="col-12 font-1">
- <strong><?php the_title(); ?>, <?= get_post_meta(get_the_ID(), 'client_company', true ); ?></strong>
</div>
</div>
</a>
</div>
<?php endwhile; ?>
</div>
</div>
<?php endif; ?>
| 34.558824
| 154
| 0.590638
|
b2ca46aa94925d1f7e0bb585a392cfe0793b7c45
| 7,665
|
css
|
CSS
|
public/assets/themes/site/default/css/dev/fans.css
|
253033688/bbs-laravel
|
d88ccee6fb62cd115dd9b788b51afa457cc95f82
|
[
"MIT"
] | null | null | null |
public/assets/themes/site/default/css/dev/fans.css
|
253033688/bbs-laravel
|
d88ccee6fb62cd115dd9b788b51afa457cc95f82
|
[
"MIT"
] | null | null | null |
public/assets/themes/site/default/css/dev/fans.css
|
253033688/bbs-laravel
|
d88ccee6fb62cd115dd9b788b51afa457cc95f82
|
[
"MIT"
] | null | null | null |
/*#
===================
@explain: 关注/粉丝/找人/访问脚印
@copyright: Copyright 2012,phpwind.com
@author: longwenid@gmail.com
$Id: fans.css 24448 2013-01-30 09:31:12Z yanchixia $
===================
#*/
/*
===================
粉丝关注列表
===================
*/
.fans_page{
}
.fans_list{
padding:15px 0;
}
.fans_list dl{
border-bottom:1px dashed #e6e6e6;
padding:0 0 15px;
margin:0 0 17px;
position:relative;
_height:80px;
}
/*
===================
头像
===================
*/
.fans_list dt{
float: left;
width: 64px;
padding:3px 0 6px;
_padding-top:0;
}
.fans_list dt a{
display:block;
}
/*
===================
打招呼
===================
*/
.fans_list .called{
border:1px solid #d8d8d8;
border-radius:2px;
color:#666;
width:48px;
text-align:center;
background:#f7f7f7;
box-shadow:0 1px 1px #ffffff inset;
}
.fans_list .called:hover{
color:#333;
text-decoration:none;
}
/*
===================
内容
===================
*/
.fans_list dd{
overflow:hidden;
}
/*
===================
用户名
===================
*/
.fans_list .name{
font-size:14px;
margin-right:7px;
}
/*
===================
用户名所以栏
===================
*/
.fans_list .title{
margin-bottom:5px;
}
/*
===================
用户数据
===================
*/
.fans_list .num{
color:#666;
margin-bottom:7px;
}
.fans_list .num span{
color:#ccc;
margin:0 9px;
}
.fans_list .num a{
margin-left:4px;
}
/*
===================
用户最新动作
===================
*/
.fans_list .action a{
color:#5697bd;
margin:0 5px;
}
.fans_list .action .time{
color:#999;
}
/*
===================
两者关系
===================
*/
.fans_list .attribute{
position:absolute;
right:0;
top:2px;
width:80px;
}
.fans_list .attribute .mnfollow{
background:url(../../images/fans/mnfollow.png) no-repeat;
width:43px;
height:13px;
overflow:hidden;
text-indent:-2000em;
display:block;
margin-bottom:10px;
float:right;
}
.fans_list .attribute .core_follow,
.fans_list .attribute .core_unfollow{
float:right;
}
/*
===================
分类
===================
*/
.fans_list .sort{
position:absolute;
right:250px;
top:0;
white-space:nowrap;
}
.fans_list .sort a{
color:#666;
display:block;
padding:3px 15px;
}
.fans_list .sort a:hover,
.fans_list .sort a.current{
border:1px solid #c4c4c4;
padding:2px 14px;
text-decoration:none;
border-radius:3px;
background:#f7f7f7;
background-repeat: no-repeat;
background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#f7f7f7), to(#ebebeb));
background-image: -webkit-linear-gradient(#f7f7f7, #ebebeb);
background-image: -moz-linear-gradient(top, #f7f7f7, #ebebeb);
background-image: -ms-linear-gradient(#f7f7f7, #ebebeb);
background-image: -o-linear-gradient(#f7f7f7, #ebebeb);
background-image: linear-gradient(#f7f7f7, #ebebeb);
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#f7f7f7', endColorstr='#ebebeb', GradientType=0);
}
.fans_list .sort em{
_vertical-align:0;
border-top: 4px #a3a3a3 solid;
}
/*
===================
下拉
===================
*/
.sort_down{
position:absolute;
border:1px solid #ccc;
background:#fff;
width:118px;
padding:1px;
margin-top:23px;
margin-left:-372px;
z-index:1;
}
.sort_down ul{
padding:5px;
}
.sort_down li{
padding:3px 0;
color:#666;
}
.sort_down .add{
display:block;
line-height:25px;
background:#eeeeee url(../../images/fans/add.png) 10px center no-repeat;
color:#5697bd;
border-top:1px dotted #ccc;
padding-left:25px;
}
.sort_down .input{
padding:2px 4px;
width:98px;
margin-bottom:5px;
}
.sort_down .ft{
padding:0 5px 5px;
}
.sort_down .btn{
margin:0;
font-family:Simsun;
width:50px;
}
.sort_down .btn_submit{
margin-right:8px;
}
/*
===================
关联关注
===================
*/
.related{
border:1px solid #e1e4e5;
background:#fbfbfb;
border-radius:3px;
padding:10px;
margin-top:10px;
}
.related p{
padding:5px;
}
/*
===================
找人
===================
*/
.friend_page{
padding:15px;
}
.friend_page h2{
background:#f0f0f0;
font-size:12px;
font-weight:100;
color:#666;
line-height:36px;
height:36px;
padding:0 15px;
margin-bottom:15px;
}
.friend_page .input{
margin-right:5px;
padding:3px 4px 2px;
}
.friend_page .btn{
width:70px;
}
/*按用户查找*/
.friend_page .user{
padding:0 15px 30px;
}
/*按缘分查找*/
.friend_page .fate{
padding:0 0 30px;
}
.friend_page .fate li{
float:left;
display:inline;
border:1px solid #eaeaea;
border-radius:3px;
width:148px;
height:68px;
text-align:center;
margin:0 8px 0 15px;
background-repeat: no-repeat;
background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#fbfafa), color-stop(25%, #fbfafa), to(#f3f2f2));
background-image: -webkit-linear-gradient(#fbfafa, #fbfafa 25%, #f3f2f2);
background-image: -moz-linear-gradient(top, #fbfafa, #fbfafa 25%, #f3f2f2);
background-image: -ms-linear-gradient(#fbfafa, #fbfafa 25%, #f3f2f2);
background-image: -o-linear-gradient(#fbfafa, #fbfafa 25%, #f3f2f2);
background-image: linear-gradient(#fbfafa, #fbfafa 25%, #f3f2f2);
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#fbfafa', endColorstr='#v', GradientType=0);
}
.friend_page .fate li a{
display:block;
}
.friend_page .fate li a.in{
height:68px;
}
.friend_page .fate li a.in:hover{
text-decoration:none;
background:#fffef7;
}
.friend_page .fate li span{
display:block;
font-size:14px;
color:#666;
line-height:30px;
padding-top:7px;
}
.friend_page .fate li em{
color:#666;
}
/*按标签查找*/
.friend_page .tags{
padding:0 15px 30px;
}
.friend_page .tags .hd{
margin-bottom:10px;
}
.friend_page .tags .hd a{
margin-right:10px;
}
.friend_page .tags .hd em{
background:#69a9d7;
border-radius:3px;
color:#fff;
display:inline-block;
vertical-align:middle;
padding:3px 5px;
margin-right:5px;
}
/*精确查找*/
.friend_page .fine{
padding:0 15px 30px;
}
.friend_page .fine dl{
margin-bottom:15px;
}
.friend_page .fine select{
padding:1px;
line-height:22px;
height:22px;
margin-right:5px;
width:60px;
}
.friend_page .fine .begin{
width:100px;
}
.friend_page .fine dt{
float:left;
width:60px;
text-align:right;
color:#666;
line-height:22px;
}
/*无关注时*/
.nofollow_list{
padding:10px 0 10px 15px;
}
.nofollow_list .hd{
padding:0 10px 10px 40px;
line-height:32px;
font-size:14px;
font-weight:700;
color:#999;
background:url(../../images/tips/gray_middle.png) 0 0 no-repeat;
}
.nofollow_list li{
float:left;
padding:5px;
margin-right:7px;
height:125px;
width:90px;
}
.nofollow_list li a{
display:block;
float:left;
margin-bottom:5px;
}
.nofollow_list li img{
display:block;
vertical-align:top;
}
.nofollow_list .ft{
text-align:center;
padding:30px;
}
.nofollow_list .ft .btn{
margin-right:15px;
width:83px;
}
.nofollow_list input{
margin-left:0;
}
.nofollow_list li label{
height:18px;
line-height:18px;
overflow:hidden;
display:block;
white-space:nowrap;
text-overflow:ellipsis;
-ms-text-overflow:ellipsis;
width:90px;
}
/*
===================
关注的人分组
===================
*/
.side_cate_list{
padding:10px 15px;
}
.side_cate_list li{
padding:2px 0;
height:20px;
}
.side_cate_list #J_group_edit_wrap{
height:28px;
}
.side_cate_list li .icon_del,
.side_cate_list li .icon_edit{
display:none;
margin:2px 0 0 5px;
}
.side_cate_list li:hover .icon_del,
.side_cate_list li:hover .icon_edit,
.side_cate_list li.hover .icon_del,
.side_cate_list li.hover .icon_edit{
display:block;
}
.side_cate_list li .input{
margin:0 3px 0 0;
width:100px;
padding:2px;
}
.side_cate_list li a{
color:#666;
}
.side_cate_list li .btn{
margin:0 3px 0 0;
}
.side_cate_list li em{
color:#999;
padding-left:5px;
}
.side_cate_list .add{
display:block;
line-height:25px;
background: url(../../images/fans/add.png) 0 center no-repeat;
color:#5697bd;
padding-left:15px;
}
| 16.308511
| 116
| 0.651533
|
d65b82fddc7ad4f9ef255f97fe1ad2d75e33523a
| 301
|
lua
|
Lua
|
examples/Environment/Skybox/main.lua
|
jmiskovic/lovr-docs
|
e16422b8a5f08e4e837c551ff5b648cde43828ec
|
[
"CC0-1.0"
] | 32
|
2017-01-13T23:15:10.000Z
|
2022-02-12T11:36:53.000Z
|
examples/Environment/Skybox/main.lua
|
jmiskovic/lovr-docs
|
e16422b8a5f08e4e837c551ff5b648cde43828ec
|
[
"CC0-1.0"
] | 55
|
2017-11-22T07:34:49.000Z
|
2022-03-14T19:24:51.000Z
|
examples/Environment/Skybox/main.lua
|
jmiskovic/lovr-docs
|
e16422b8a5f08e4e837c551ff5b648cde43828ec
|
[
"CC0-1.0"
] | 25
|
2017-10-06T21:57:27.000Z
|
2022-03-14T19:17:19.000Z
|
-- Texture from Humus (www.humus.name)
function lovr.load()
cube = lovr.graphics.newTexture({
left = 'negx.jpg',
right = 'posx.jpg',
top = 'posy.jpg',
bottom = 'negy.jpg',
front = 'negz.jpg',
back = 'posz.jpg'
})
end
function lovr.draw()
lovr.graphics.skybox(cube)
end
| 17.705882
| 38
| 0.607973
|
7418342eb8b9b0dbe1a7451e3e9660d5ef9ddf30
| 919
|
css
|
CSS
|
Section grid 3/style.css
|
LucasEduardoGoncalves/FlexBox
|
f8919a825d23254ca97abf27b3f2ca64232c51b6
|
[
"MIT"
] | null | null | null |
Section grid 3/style.css
|
LucasEduardoGoncalves/FlexBox
|
f8919a825d23254ca97abf27b3f2ca64232c51b6
|
[
"MIT"
] | null | null | null |
Section grid 3/style.css
|
LucasEduardoGoncalves/FlexBox
|
f8919a825d23254ca97abf27b3f2ca64232c51b6
|
[
"MIT"
] | null | null | null |
body,ul,li,p{
margin: 0px;
padding: 0px;
list-style: none;
font-size: 1.2rem;
font-family: arial;
}
a{
text-decoration: none;
color: white;
}
img{
max-width: 100%;
display: block;
}
header{
background-color: #1d1e20;
display: flex;
justify-content: space-between;
flex-wrap: wrap;
padding: 20px;
align-items: center;
}
#menu{
display: flex;
}
#menu li{
margin-left: 10px;
}
#menu li a{
display: block;
padding: 10px;
}
.grid3{
display: grid;
grid-template-columns: 1fr 1fr;
grid-gap: 20px;
margin: 0 auto;
max-width: 700px;
padding: 10px;
}
.item1:nth-child(1){
grid-row: 1 / 3;
}
.item1{
display: grid;
}
.item1 img {
grid-column: 1;
grid-row: 1/3;
align-self: end;
}
.item1 p{
background: rgba(0, 0, 0, 0.6);
padding: 10px;
color: white;
grid-row: 2/3;
align-self: end;
}
| 14.138462
| 35
| 0.571273
|
1708f057a3406aec0b2018d089dbf51d149e6051
| 14,307
|
cs
|
C#
|
Program.cs
|
dichternebel/recent-followers-for-obs
|
8eaf89378dd05a902d7191c50c6b76cc639a4380
|
[
"MIT"
] | null | null | null |
Program.cs
|
dichternebel/recent-followers-for-obs
|
8eaf89378dd05a902d7191c50c6b76cc639a4380
|
[
"MIT"
] | null | null | null |
Program.cs
|
dichternebel/recent-followers-for-obs
|
8eaf89378dd05a902d7191c50c6b76cc639a4380
|
[
"MIT"
] | null | null | null |
using System;
using System.Configuration;
using System.Diagnostics;
using System.IO;
using System.IO.Compression;
using System.Net;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
using CliWrap;
using CliWrap.Buffered;
using Serilog;
using SixLabors.ImageSharp;
using SixLabors.ImageSharp.Processing;
using SixLabors.ImageSharp.Drawing.Processing;
using SixLabors.Fonts;
namespace RecentFollowers
{
class Program
{
private static int currentFollower = -1;
private static string clientID { get; set; }
private static string clientSecret { get; set; }
private static string displayHeartbeat { get; set; }
private static string displayFollower { get; set; }
private static string displayTotal { get; set; }
private static string displayViewerCount { get; set; }
private static string outputFolder { get; set; }
private static string heartbeatPath { get; set; }
private static string followerPath { get; set; }
private static string totalPath { get; set; }
private static string viewerPath { get; set; }
private static TwitchUser twitchStreamer { get; set; }
private static FollowerListObject RecentFollowers { get; set; }
#pragma warning disable IDE0051 // Remove unused private members
#pragma warning disable IDE0052 // Remove unused private members
// Warning disabled since fields are needed to prevent garbage collection!
private static Timer heartbeatTimer;
private static Timer viewerTimer;
private static Timer followerTimer;
private static Timer displayTimer;
#pragma warning restore IDE0051 // Remove unused private members
#pragma warning restore IDE0052 // Remove unused private members
static int Main(string[] args)
{
// Initialize serilog logger
Log.Logger = new LoggerConfiguration()
.WriteTo.Console(Serilog.Events.LogEventLevel.Debug)
.WriteTo.File(Path.Combine(Directory.GetCurrentDirectory(), "logs", $"log-.txt"), Serilog.Events.LogEventLevel.Information, rollingInterval: RollingInterval.Day)
.MinimumLevel.Debug()
.Enrich.FromLogContext()
.CreateLogger();
try
{
MainAsync(args).Wait();
return 0;
}
catch (Exception ex)
{
Log.Logger.Error(ex.Message);
return 1;
}
}
static async Task MainAsync(string[] args)
{
// Name this thing
Console.Title = "Recent Followers for OBS";
// We need the twitch-cli libary for this
var libPath = Path.Combine(Directory.GetCurrentDirectory(), "lib");
// Get the twitch-cli if not present
if (!File.Exists(Path.Combine(libPath, "twitch.exe")))
{
using (var client = new WebClient())
{
if (!Directory.Exists(libPath)) Directory.CreateDirectory(libPath);
var zipPath = Path.Combine(libPath, "twitch-cli_1.1.5_Windows_x86_64.zip");
Log.Logger.Information($"Downloading Twitch-CLI to {zipPath}...");
client.DownloadFile(@"https://github.com/twitchdev/twitch-cli/releases/download/v1.1.5/twitch-cli_1.1.5_Windows_x86_64.zip", zipPath);
ZipFile.ExtractToDirectory(zipPath, libPath, true);
File.Delete(zipPath);
}
}
// initialize outputFolder
outputFolder = Path.Combine(Directory.GetCurrentDirectory(), "output");
// first argument: custom output path
if (args.Length > 0)
{
outputFolder = Path.GetFullPath(args[0]);
}
if (!Directory.Exists(outputFolder))
{
var di = Directory.CreateDirectory(outputFolder);
if (di.Exists)
{
Log.Logger.Information("Output folder created successfully.");
}
}
clientID = ConfigurationManager.AppSettings["ClientID"];
clientSecret = ConfigurationManager.AppSettings["ClientSecret"];
// Get permission and token
var authProcess = Process.Start("lib/twitch.exe", new string[] { "configure", "-i", clientID, "-s", clientSecret });
authProcess.WaitForExit();
var tokenProcess = Process.Start("lib/twitch.exe", new string[] { "token" });
tokenProcess.WaitForExit();
var userFile = "user.json";
if (File.Exists(userFile))
{
var jsonString = File.ReadAllText(userFile);
twitchStreamer = JsonSerializer.Deserialize<TwitchUser>(jsonString);
// New output folder passed as argument
if (args.Length > 0)
{
twitchStreamer.OutputFolder = outputFolder;
}
else if (!string.IsNullOrWhiteSpace(twitchStreamer.OutputFolder))
{
outputFolder = twitchStreamer.OutputFolder;
}
}
else
{
Console.Write("Enter your Twitch name: ");
var userName = Console.ReadLine();
// Get Twitch user
twitchStreamer = await GetTwitchUserByName(userName);
// Set the given output folder
twitchStreamer.OutputFolder = outputFolder;
}
// Always update user information on application start
using FileStream createStream = File.Create(userFile);
await JsonSerializer.SerializeAsync(createStream, twitchStreamer);
await createStream.DisposeAsync();
// Set file paths
heartbeatPath = Path.Combine(outputFolder, "currentHeartBeat.txt");
followerPath = Path.Combine(outputFolder, "currentFollower.txt");
totalPath = Path.Combine(outputFolder, "totalFollowerCount.txt");
viewerPath = Path.Combine(outputFolder, "currentViewerCount.txt");
Log.Logger.Information($"Gathering information for {twitchStreamer.DisplayName}...");
#if DEBUG
runHeartbeatTask();
#else
heartbeatTimer = new Timer(x => runHeartbeatTask(), null, 0, 5000);
viewerTimer = new Timer(x => runViewerTask(), null, 0, 5000);
followerTimer = new Timer(x => runFollowerTask(), null, 0, 8000);
displayTimer = new Timer(x => OutputToConsole(), null, 5000, 1000);
#endif
Console.Title = $"Recent Followers for OBS - output to {outputFolder}";
// Block this task until the program is closed.
await Task.Delay(-1);
}
private static void runHeartbeatTask()
{
var rnd = new Random();
displayHeartbeat = rnd.Next(147, 222).ToString();
WriteToTextFile(heartbeatPath, displayHeartbeat);
#if DEBUG
runViewerTask();
#endif
}
private static async void runViewerTask()
{
displayViewerCount = await GetViewerCountFromTwitch();
WriteToTextFile(viewerPath, displayViewerCount);
#if DEBUG
runFollowerTask();
#endif
}
private static async Task<string> GetViewerCountFromTwitch()
{
int currentViewerCount = 0;
try
{
var result = await Cli.Wrap("lib/twitch.exe").WithArguments($"api get /streams -q user_id={twitchStreamer.Id}").WithWorkingDirectory(Directory.GetCurrentDirectory()).ExecuteBufferedAsync();
var streamObject = JsonSerializer.Deserialize<StreamObject>(result.StandardOutput);
if (streamObject.Streams.Count > 0)
{
currentViewerCount = streamObject.Streams[0].ViewerCount;
}
}
catch (Exception ex)
{
Log.Logger.Error(ex.Message);
}
return currentViewerCount.ToString();
}
private static async void runFollowerTask()
{
var followerListChanged = false;
var currentFollowers = await GetFollowersFromTwitch();
if (!IsObjectEqual(RecentFollowers,currentFollowers))
{
RecentFollowers = currentFollowers;
followerListChanged = true;
}
currentFollower++;
if (RecentFollowers.Data.Count == 0)
{
displayFollower = "waiting 4 u!";
currentFollower = -1;
}
else if (RecentFollowers.Data.Count >= currentFollower + 1)
{
displayFollower = RecentFollowers.Data[currentFollower].FollowerName;
}
else
{
currentFollower = 0;
displayFollower = RecentFollowers.Data[currentFollower].FollowerName;
}
WriteToTextFile(followerPath, displayFollower);
displayTotal = RecentFollowers.Total.ToString();
WriteToTextFile(totalPath, displayTotal);
// List didn't change so stop processing
if (!followerListChanged) return;
for (int i = 0; i < RecentFollowers.Data.Count; i++)
{
var follower = RecentFollowers.Data[i];
var twitchUser = await GetTwitchUserByName(follower.FollowerName);
if (twitchUser == null) continue;
var fileId = i + 1;
var followerFileName = $"follower{fileId}.txt";
WriteToTextFile(Path.Combine(outputFolder, followerFileName), twitchUser.DisplayName);
var byteArray = GetAvatarFromTwitch(twitchUser);
if (byteArray == null) continue;
var fileName = $"avatar{fileId}.png";
EditAndSaveAvatar(byteArray, twitchUser.DisplayName, Path.Combine(outputFolder, fileName));
}
#if DEBUG
OutputToConsole();
#endif
}
private static async Task<FollowerListObject> GetFollowersFromTwitch()
{
FollowerListObject followerListObject = null;
try
{
// Get the five most recent followers
var result = await Cli.Wrap("lib/twitch.exe").WithArguments($"api get /users/follows -q to_id={twitchStreamer.Id} -q first=5").WithWorkingDirectory(Directory.GetCurrentDirectory()).ExecuteBufferedAsync();
followerListObject = JsonSerializer.Deserialize<FollowerListObject>(result.StandardOutput);
}
catch (Exception ex)
{
Log.Logger.Error(ex.Message);
}
return followerListObject;
}
private static async Task<TwitchUser> GetTwitchUserByName(string userName)
{
TwitchUser twitchUser = null;
try
{
Log.Logger.Information($"Getting Twitch user information from {userName}...");
var userResult = await Cli.Wrap("lib/twitch.exe").WithArguments($"api get /users -q login={userName}").WithWorkingDirectory(Directory.GetCurrentDirectory()).ExecuteBufferedAsync();
twitchUser = JsonSerializer.Deserialize<TwitchUserObject>(userResult.StandardOutput).Data[0];
}
catch (Exception ex)
{
Log.Logger.Error(ex.Message);
}
return twitchUser;
}
private static byte[] GetAvatarFromTwitch(TwitchUser twitchUser)
{
byte[] byteArray = null;
try
{
Log.Logger.Information($"Loading Twitch avatar for user {twitchUser.DisplayName}...");
using (var client = new WebClient())
//This just saves the png but we want more: we add the user name to it
//client.DownloadFile(twitchUser.ProfileImageUrl, Path.Combine(outputFolder, fileName));
byteArray = client.DownloadData(twitchUser.ProfileImageUrl);
}
catch (Exception ex)
{
Log.Logger.Error(ex.Message);
}
return byteArray;
}
private static void EditAndSaveAvatar(byte[] imageByteArray, string nameToBeAdded, string pathtoImage)
{
try
{
Log.Logger.Information($"Processing Twitch avatar for user {nameToBeAdded}...");
var font = SystemFonts.CreateFont("Impact", 24);
using (var image = Image.Load(imageByteArray))
{
image.Mutate(x => x.Resize(180, 180));
image.Mutate(x => x.DrawText(nameToBeAdded, font, Brushes.Solid(Color.White), Pens.Solid(Color.Black, 1), new PointF(3, 150)));
image.Save(pathtoImage); // Automatic encoder selected based on extension.
}
}
catch (Exception ex)
{
Log.Logger.Error(ex.Message);
}
}
private static void WriteToTextFile(string filePath, string line)
{
try
{
using var sw = new StreamWriter(filePath);
sw.WriteLine(line);
sw.Close();
}
catch (Exception ex)
{
Log.Logger.Error(ex.Message);
}
}
private static void OutputToConsole()
{
Console.Clear();
Console.WriteLine("Random BPM : " + displayHeartbeat);
Console.WriteLine("Current follower: " + displayFollower);
Console.WriteLine("Total followers : " + displayTotal);
Console.WriteLine("Current viewers : " + displayViewerCount);
}
public static bool IsObjectEqual(object x, object y)
{
return JsonSerializer.Serialize(x) == JsonSerializer.Serialize(y);
}
}
}
| 37.161039
| 220
| 0.572167
|
a33b081f08dc6d284048281aa7737e054ddacea4
| 519
|
h
|
C
|
extra/logParser/qtWidgetLogParser/startupdialog.h
|
MickaelF/PTTK
|
94683004927ac7127639578dededdca1132ce034
|
[
"MIT"
] | null | null | null |
extra/logParser/qtWidgetLogParser/startupdialog.h
|
MickaelF/PTTK
|
94683004927ac7127639578dededdca1132ce034
|
[
"MIT"
] | null | null | null |
extra/logParser/qtWidgetLogParser/startupdialog.h
|
MickaelF/PTTK
|
94683004927ac7127639578dededdca1132ce034
|
[
"MIT"
] | null | null | null |
#pragma once
#include <QDialog>
#include "ui_StartUpDialog.h"
class StartUpDialog : public QDialog, public Ui_StartUpDialog
{
Q_OBJECT
public:
explicit StartUpDialog(QWidget* parent = nullptr);
const QString& pathOpened() const { return m_pathOpened; }
void updateRecentComboBox(const QStringList& recents);
protected:
void changeEvent(QEvent* event);
private slots:
void onOpenPressed();
void onGeneratePressed();
void onOpenRecentPressed();
private:
QString m_pathOpened;
};
| 20.76
| 62
| 0.736031
|
1f5f8adb8fa0b8821917906013fdb6760beab916
| 11,127
|
cs
|
C#
|
Source/CurrencyCloud.Tests/ReportRequestsTest.cs
|
MrZoidberg/currencycloud-net
|
a12d3ad0e6d88f44cdd1ac05df33eaa382e2d653
|
[
"MIT"
] | null | null | null |
Source/CurrencyCloud.Tests/ReportRequestsTest.cs
|
MrZoidberg/currencycloud-net
|
a12d3ad0e6d88f44cdd1ac05df33eaa382e2d653
|
[
"MIT"
] | null | null | null |
Source/CurrencyCloud.Tests/ReportRequestsTest.cs
|
MrZoidberg/currencycloud-net
|
a12d3ad0e6d88f44cdd1ac05df33eaa382e2d653
|
[
"MIT"
] | null | null | null |
using NUnit.Framework;
using CurrencyCloud.Tests.Mock.Data;
using CurrencyCloud.Entity.Pagination;
using CurrencyCloud.Tests.Mock.Http;
using CurrencyCloud.Environment;
using System.Threading.Tasks;
using CurrencyCloud.Entity;
namespace CurrencyCloud.Tests
{
[TestFixture]
public class ReportRequestsTest
{
Client client = new Client();
Player player = new Player("./Mock/Http/Recordings/ReportRequests.json");
[OneTimeSetUpAttribute]
public void SetUp()
{
player.Start(ApiServer.Mock.Url);
player.Play("SetUp");
var credentials = Authentication.Credentials;
client.InitializeAsync(Authentication.ApiServer, credentials.LoginId, credentials.ApiKey).Wait();
}
[OneTimeTearDownAttribute]
public void TearDown()
{
player.Play("TearDown");
client.CloseAsync().Wait();
player.Close();
}
/// <summary>
/// Successfully creates a conversion report.
/// </summary>
[Test]
public async Task CreateConversionReport()
{
player.Play("CreateConversionReport");
var report = ReportRequests.Report3;
ReportRequest gotten = await client.CreateConversionReportAsync(new ReportParameters
{
Description = "New Conversion test report",
UniqueRequestId = "1b3687dc-c779-4fe7-9515-00a6509632c4"
}
);
Assert.IsNotNull(gotten);
Assert.AreEqual(report.Status, gotten.Status);
Assert.AreEqual(report.Description, gotten.Description);
Assert.AreEqual(report.Id, gotten.Id);
Assert.AreEqual(report.AccountId, gotten.AccountId);
Assert.AreEqual(report.ContactId, gotten.ContactId);
Assert.AreEqual(report.CreatedAt, gotten.CreatedAt);
Assert.AreEqual(report.ExpirationDate, gotten.ExpirationDate);
Assert.AreEqual(report.FailureReason, gotten.FailureReason);
Assert.AreEqual(report.ReportType, gotten.ReportType);
Assert.AreEqual(report.ReportUrl, gotten.ReportUrl);
Assert.AreEqual(report.SearchParams.Description, gotten.SearchParams.Description);
Assert.AreEqual(report.SearchParams.Scope, gotten.SearchParams.Scope);
Assert.AreEqual(report.ShortReference, gotten.ShortReference);
Assert.AreEqual(report.UpdatedAt, gotten.UpdatedAt);
}
/// <summary>
/// Successfully gets a conversion report.
/// </summary>
[Test]
public async Task GetConversionReport()
{
player.Play("GetConversionReport");
var report = ReportRequests.Report1;
ReportRequest gotten = await client.GetReportRequestAsync(report.Id);
Assert.IsNotNull(gotten);
Assert.AreEqual(report.Status, gotten.Status);
Assert.AreEqual(report.Description, gotten.Description);
Assert.AreEqual(report.Id, gotten.Id);
Assert.AreEqual(report.AccountId, gotten.AccountId);
Assert.AreEqual(report.ContactId, gotten.ContactId);
Assert.AreEqual(report.CreatedAt, gotten.CreatedAt);
Assert.AreEqual(report.ExpirationDate, gotten.ExpirationDate);
Assert.AreEqual(report.FailureReason, gotten.FailureReason);
Assert.AreEqual(report.ReportType, gotten.ReportType);
Assert.AreEqual(report.ReportUrl, gotten.ReportUrl);
Assert.AreEqual(report.SearchParams, gotten.SearchParams);
Assert.AreEqual(report.ShortReference, gotten.ShortReference);
Assert.AreEqual(report.UpdatedAt, gotten.UpdatedAt);
}
/// <summary>
/// Successfully creates a payment report.
/// </summary>
[Test]
public async Task CreatePaymentReport()
{
player.Play("CreatePaymentReport");
var report = ReportRequests.Report4;
ReportRequest gotten = await client.CreatePaymentReportAsync(new ReportParameters
{
Description = "New Payment test report",
UniqueRequestId = "2422a1ee-b376-4358-a4f2-560aa953c461"
}
);
Assert.IsNotNull(gotten);
Assert.AreEqual(report.Status, gotten.Status);
Assert.AreEqual(report.Description, gotten.Description);
Assert.AreEqual(report.Id, gotten.Id);
Assert.AreEqual(report.AccountId, gotten.AccountId);
Assert.AreEqual(report.ContactId, gotten.ContactId);
Assert.AreEqual(report.CreatedAt, gotten.CreatedAt);
Assert.AreEqual(report.ExpirationDate, gotten.ExpirationDate);
Assert.AreEqual(report.FailureReason, gotten.FailureReason);
Assert.AreEqual(report.ReportType, gotten.ReportType);
Assert.AreEqual(report.ReportUrl, gotten.ReportUrl);
Assert.AreEqual(report.SearchParams.Description, gotten.SearchParams.Description);
Assert.AreEqual(report.SearchParams.Scope, gotten.SearchParams.Scope);
Assert.AreEqual(report.ShortReference, gotten.ShortReference);
Assert.AreEqual(report.UpdatedAt, gotten.UpdatedAt);
}
/// <summary>
/// Successfully gets a payment report.
/// </summary>
[Test]
public async Task GetPaymentReport()
{
player.Play("GetPaymentReport");
var report = ReportRequests.Report2;
ReportRequest gotten = await client.GetReportRequestAsync(report.Id);
Assert.IsNotNull(gotten);
Assert.AreEqual(report.Status, gotten.Status);
Assert.AreEqual(report.Description, gotten.Description);
Assert.AreEqual(report.Id, gotten.Id);
Assert.AreEqual(report.AccountId, gotten.AccountId);
Assert.AreEqual(report.ContactId, gotten.ContactId);
Assert.AreEqual(report.CreatedAt, gotten.CreatedAt);
Assert.AreEqual(report.ExpirationDate, gotten.ExpirationDate);
Assert.AreEqual(report.FailureReason, gotten.FailureReason);
Assert.AreEqual(report.ReportType, gotten.ReportType);
Assert.AreEqual(report.ReportUrl, gotten.ReportUrl);
Assert.AreEqual(report.SearchParams, gotten.SearchParams);
Assert.AreEqual(report.ShortReference, gotten.ShortReference);
Assert.AreEqual(report.UpdatedAt, gotten.UpdatedAt);
}
/// <summary>
/// Successfully finds report requests without search parameters.
/// </summary>
[Test]
public async Task FindNoParams()
{
player.Play("FindNoParams");
var report1 = ReportRequests.Report1;
var report2 = ReportRequests.Report2;
PaginatedReportRequests found = await client.FindReportRequestsAsync();
Assert.IsNotEmpty(found.ReportRequests);
Assert.AreEqual(found.ReportRequests.Count, found.Pagination.TotalEntries);
Assert.AreEqual(report1.Status, found.ReportRequests[0].Status);
Assert.AreEqual(report1.Description, found.ReportRequests[0].Description);
Assert.AreEqual(report1.Id, found.ReportRequests[0].Id);
Assert.AreEqual(report1.AccountId, found.ReportRequests[0].AccountId);
Assert.AreEqual(report1.ContactId, found.ReportRequests[0].ContactId);
Assert.AreEqual(report1.CreatedAt, found.ReportRequests[0].CreatedAt);
Assert.AreEqual(report1.ExpirationDate, found.ReportRequests[0].ExpirationDate);
Assert.AreEqual(report1.FailureReason, found.ReportRequests[0].FailureReason);
Assert.AreEqual(report1.ReportType, found.ReportRequests[0].ReportType);
Assert.AreEqual(report1.ReportUrl, found.ReportRequests[0].ReportUrl);
Assert.AreEqual(report1.SearchParams, found.ReportRequests[0].SearchParams);
Assert.AreEqual(report1.ShortReference, found.ReportRequests[0].ShortReference);
Assert.AreEqual(report1.UpdatedAt, found.ReportRequests[0].UpdatedAt);
Assert.AreEqual(report2.Status, found.ReportRequests[1].Status);
Assert.AreEqual(report2.Description, found.ReportRequests[1].Description);
Assert.AreEqual(report2.Id, found.ReportRequests[1].Id);
Assert.AreEqual(report2.AccountId, found.ReportRequests[1].AccountId);
Assert.AreEqual(report2.ContactId, found.ReportRequests[1].ContactId);
Assert.AreEqual(report2.CreatedAt, found.ReportRequests[1].CreatedAt);
Assert.AreEqual(report2.ExpirationDate, found.ReportRequests[1].ExpirationDate);
Assert.AreEqual(report2.FailureReason, found.ReportRequests[1].FailureReason);
Assert.AreEqual(report2.ReportType, found.ReportRequests[1].ReportType);
Assert.AreEqual(report2.ReportUrl, found.ReportRequests[1].ReportUrl);
Assert.AreEqual(report2.SearchParams, found.ReportRequests[1].SearchParams);
Assert.AreEqual(report2.ShortReference, found.ReportRequests[1].ShortReference);
Assert.AreEqual(report2.UpdatedAt, found.ReportRequests[1].UpdatedAt);
}
/// <summary>
/// Successfully finds report requests with search parameters.
/// </summary>
[Test]
public async Task FindWithParams()
{
player.Play("FindWithParams");
var report1 = ReportRequests.Report1;
PaginatedReportRequests found = await client.FindReportRequestsAsync(
new ReportRequestFindParameters { ReportType = "conversion"}
);
Assert.IsNotEmpty(found.ReportRequests);
Assert.AreEqual(found.ReportRequests.Count, found.Pagination.TotalEntries);
Assert.AreEqual(report1.Status, found.ReportRequests[0].Status);
Assert.AreEqual(report1.Description, found.ReportRequests[0].Description);
Assert.AreEqual(report1.Id, found.ReportRequests[0].Id);
Assert.AreEqual(report1.AccountId, found.ReportRequests[0].AccountId);
Assert.AreEqual(report1.ContactId, found.ReportRequests[0].ContactId);
Assert.AreEqual(report1.CreatedAt, found.ReportRequests[0].CreatedAt);
Assert.AreEqual(report1.ExpirationDate, found.ReportRequests[0].ExpirationDate);
Assert.AreEqual(report1.FailureReason, found.ReportRequests[0].FailureReason);
Assert.AreEqual(report1.ReportType, found.ReportRequests[0].ReportType);
Assert.AreEqual(report1.ReportUrl, found.ReportRequests[0].ReportUrl);
Assert.AreEqual(report1.SearchParams, found.ReportRequests[0].SearchParams);
Assert.AreEqual(report1.ShortReference, found.ReportRequests[0].ShortReference);
Assert.AreEqual(report1.UpdatedAt, found.ReportRequests[0].UpdatedAt);
}
}
}
| 46.949367
| 109
| 0.65768
|
8d938b4ef54b362c2c4c35e1b56afe4c97326b99
| 172
|
js
|
JavaScript
|
generators/plopfile.js
|
PiperGuy/PiperGuy.github.io
|
50bcdc2aa25db4f11fb1057d598ea336b9d1440a
|
[
"MIT"
] | 1
|
2022-02-02T07:44:54.000Z
|
2022-02-02T07:44:54.000Z
|
generators/plopfile.js
|
PiperGuy/PiperGuy.github.io
|
50bcdc2aa25db4f11fb1057d598ea336b9d1440a
|
[
"MIT"
] | 12
|
2022-01-27T10:41:12.000Z
|
2022-02-02T07:41:24.000Z
|
generators/plopfile.js
|
PiperGuy/PiperGuy.github.io
|
50bcdc2aa25db4f11fb1057d598ea336b9d1440a
|
[
"MIT"
] | null | null | null |
const { component } = require('./settings')
module.exports = function (plop) {
plop.setDefaultInclude({generators: true})
plop.setGenerator('component', component)
}
| 24.571429
| 44
| 0.715116
|
11f6151b5f754854d40c13f52f4115a1f803c660
| 4,914
|
go
|
Go
|
client/architect/delete_architect_prompt_parameters.go
|
freman/genesysapi
|
34903e753622403b4576784f7ea7186443d71c91
|
[
"MIT"
] | null | null | null |
client/architect/delete_architect_prompt_parameters.go
|
freman/genesysapi
|
34903e753622403b4576784f7ea7186443d71c91
|
[
"MIT"
] | null | null | null |
client/architect/delete_architect_prompt_parameters.go
|
freman/genesysapi
|
34903e753622403b4576784f7ea7186443d71c91
|
[
"MIT"
] | null | null | null |
// Code generated by go-swagger; DO NOT EDIT.
package architect
// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command
import (
"context"
"net/http"
"time"
"github.com/go-openapi/errors"
"github.com/go-openapi/runtime"
cr "github.com/go-openapi/runtime/client"
"github.com/go-openapi/strfmt"
"github.com/go-openapi/swag"
)
// NewDeleteArchitectPromptParams creates a new DeleteArchitectPromptParams object
// with the default values initialized.
func NewDeleteArchitectPromptParams() *DeleteArchitectPromptParams {
var ()
return &DeleteArchitectPromptParams{
timeout: cr.DefaultTimeout,
}
}
// NewDeleteArchitectPromptParamsWithTimeout creates a new DeleteArchitectPromptParams object
// with the default values initialized, and the ability to set a timeout on a request
func NewDeleteArchitectPromptParamsWithTimeout(timeout time.Duration) *DeleteArchitectPromptParams {
var ()
return &DeleteArchitectPromptParams{
timeout: timeout,
}
}
// NewDeleteArchitectPromptParamsWithContext creates a new DeleteArchitectPromptParams object
// with the default values initialized, and the ability to set a context for a request
func NewDeleteArchitectPromptParamsWithContext(ctx context.Context) *DeleteArchitectPromptParams {
var ()
return &DeleteArchitectPromptParams{
Context: ctx,
}
}
// NewDeleteArchitectPromptParamsWithHTTPClient creates a new DeleteArchitectPromptParams object
// with the default values initialized, and the ability to set a custom HTTPClient for a request
func NewDeleteArchitectPromptParamsWithHTTPClient(client *http.Client) *DeleteArchitectPromptParams {
var ()
return &DeleteArchitectPromptParams{
HTTPClient: client,
}
}
/*DeleteArchitectPromptParams contains all the parameters to send to the API endpoint
for the delete architect prompt operation typically these are written to a http.Request
*/
type DeleteArchitectPromptParams struct {
/*AllResources
Whether or not to delete all the prompt resources
*/
AllResources *bool
/*PromptID
Prompt ID
*/
PromptID string
timeout time.Duration
Context context.Context
HTTPClient *http.Client
}
// WithTimeout adds the timeout to the delete architect prompt params
func (o *DeleteArchitectPromptParams) WithTimeout(timeout time.Duration) *DeleteArchitectPromptParams {
o.SetTimeout(timeout)
return o
}
// SetTimeout adds the timeout to the delete architect prompt params
func (o *DeleteArchitectPromptParams) SetTimeout(timeout time.Duration) {
o.timeout = timeout
}
// WithContext adds the context to the delete architect prompt params
func (o *DeleteArchitectPromptParams) WithContext(ctx context.Context) *DeleteArchitectPromptParams {
o.SetContext(ctx)
return o
}
// SetContext adds the context to the delete architect prompt params
func (o *DeleteArchitectPromptParams) SetContext(ctx context.Context) {
o.Context = ctx
}
// WithHTTPClient adds the HTTPClient to the delete architect prompt params
func (o *DeleteArchitectPromptParams) WithHTTPClient(client *http.Client) *DeleteArchitectPromptParams {
o.SetHTTPClient(client)
return o
}
// SetHTTPClient adds the HTTPClient to the delete architect prompt params
func (o *DeleteArchitectPromptParams) SetHTTPClient(client *http.Client) {
o.HTTPClient = client
}
// WithAllResources adds the allResources to the delete architect prompt params
func (o *DeleteArchitectPromptParams) WithAllResources(allResources *bool) *DeleteArchitectPromptParams {
o.SetAllResources(allResources)
return o
}
// SetAllResources adds the allResources to the delete architect prompt params
func (o *DeleteArchitectPromptParams) SetAllResources(allResources *bool) {
o.AllResources = allResources
}
// WithPromptID adds the promptID to the delete architect prompt params
func (o *DeleteArchitectPromptParams) WithPromptID(promptID string) *DeleteArchitectPromptParams {
o.SetPromptID(promptID)
return o
}
// SetPromptID adds the promptId to the delete architect prompt params
func (o *DeleteArchitectPromptParams) SetPromptID(promptID string) {
o.PromptID = promptID
}
// WriteToRequest writes these params to a swagger request
func (o *DeleteArchitectPromptParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error {
if err := r.SetTimeout(o.timeout); err != nil {
return err
}
var res []error
if o.AllResources != nil {
// query param allResources
var qrAllResources bool
if o.AllResources != nil {
qrAllResources = *o.AllResources
}
qAllResources := swag.FormatBool(qrAllResources)
if qAllResources != "" {
if err := r.SetQueryParam("allResources", qAllResources); err != nil {
return err
}
}
}
// path param promptId
if err := r.SetPathParam("promptId", o.PromptID); err != nil {
return err
}
if len(res) > 0 {
return errors.CompositeValidationError(res...)
}
return nil
}
| 29.076923
| 106
| 0.7849
|
a3494ab7590b2a866fb297ef32a62c4717d3b97f
| 34,227
|
java
|
Java
|
plugin/src/main/java/com/intellij/spring/model/SpringUtils.java
|
consulo/consulo-spring
|
a9b2663ebf2f5ff6951a5fcce56b61544382080b
|
[
"Apache-2.0"
] | 1
|
2018-03-08T16:14:44.000Z
|
2018-03-08T16:14:44.000Z
|
plugin/src/main/java/com/intellij/spring/model/SpringUtils.java
|
consulo/consulo-spring
|
a9b2663ebf2f5ff6951a5fcce56b61544382080b
|
[
"Apache-2.0"
] | 1
|
2020-11-15T10:06:43.000Z
|
2020-11-15T10:06:43.000Z
|
plugin/src/main/java/com/intellij/spring/model/SpringUtils.java
|
consulo/consulo-spring
|
a9b2663ebf2f5ff6951a5fcce56b61544382080b
|
[
"Apache-2.0"
] | 1
|
2018-03-08T16:15:04.000Z
|
2018-03-08T16:15:04.000Z
|
/*
* Copyright 2000-2009 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.spring.model;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.extensions.Extensions;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.module.ModuleUtil;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.roots.libraries.JarVersionDetectionUtil;
import com.intellij.openapi.util.Comparing;
import com.intellij.openapi.util.Condition;
import com.intellij.openapi.util.Pair;
import com.intellij.openapi.util.Ref;
import com.intellij.openapi.util.text.CharFilter;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.*;
import com.intellij.psi.codeStyle.JavaCodeStyleManager;
import com.intellij.psi.codeStyle.SuggestedNameInfo;
import com.intellij.psi.codeStyle.VariableKind;
import com.intellij.psi.search.GlobalSearchScope;
import com.intellij.psi.util.*;
import com.intellij.psi.xml.XmlFile;
import com.intellij.spring.SpringBundle;
import com.intellij.spring.SpringManager;
import com.intellij.spring.SpringModel;
import com.intellij.spring.constants.SpringConstants;
import com.intellij.spring.factories.SpringFactoryBeansManager;
import com.intellij.spring.impl.DomSpringModelImpl;
import com.intellij.spring.model.converters.SpringConverterUtil;
import com.intellij.spring.model.values.PlaceholderUtils;
import com.intellij.spring.model.values.PropertyValueConverter;
import com.intellij.spring.model.values.converters.PlaceholderPropertiesConverter;
import com.intellij.spring.model.xml.*;
import com.intellij.spring.model.xml.beans.*;
import com.intellij.util.ArrayUtil;
import com.intellij.util.Function;
import com.intellij.util.Processor;
import com.intellij.util.SmartList;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.xml.*;
import com.intellij.util.xml.reflect.AbstractDomChildrenDescription;
import consulo.spring.module.extension.SpringModuleExtension;
import consulo.util.collection.Sets;
import consulo.util.dataholder.Key;
import org.jetbrains.annotations.NonNls;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.util.*;
public class SpringUtils {
public static final String SPRING_DELIMITERS = ",; ";
public static final CharFilter ourFilter = new CharFilter() {
public boolean accept(char ch) {
return SPRING_DELIMITERS.indexOf(ch) >= 0;
}
};
private SpringUtils() {
}
public static List<String> tokenize(@Nonnull String str) {
final ArrayList<String> list = new ArrayList<String>();
tokenize(str, list);
return list;
}
public static void tokenize(@Nonnull String str, Collection<String> tokens) {
StringTokenizer st = new StringTokenizer(str, SPRING_DELIMITERS);
while (st.hasMoreTokens()) {
String token = st.nextToken();
token = token.trim();
if (token.length() > 0) {
tokens.add(token);
}
}
}
@Nullable
public static String getReferencedName(final CommonSpringBean bean) {
final SpringModel model = getSpringModelForBean(bean);
return model != null ? getReferencedName(SpringBeanPointer.createSpringBeanPointer(bean), model.getAllCommonBeans(true)) : null;
}
@Nullable
public static String getReferencedName(final SpringBeanPointer bean, final Collection<? extends SpringBeanPointer> allBeans) {
final String beanName = bean.getName();
if (beanName != null) return beanName;
for (PsiClass psiClass : bean.getEffectiveBeanType()) {
final String className = psiClass.getQualifiedName();
if (className == null) continue;
final List<SpringBeanPointer> list = findBeansByClassName(allBeans, className);
if (list.size() == 1) {
return className;
}
}
return null;
}
@Nonnull
public static List<SpringBeanPointer> findBeansByClassName(@Nonnull final Collection<? extends SpringBeanPointer> beans,
@Nonnull String className) {
List<SpringBeanPointer> result = new ArrayList<SpringBeanPointer>();
for (SpringBeanPointer bean : beans) {
final PsiClass beanClass = bean.getBeanClass();
if (beanClass != null && className.equals(beanClass.getQualifiedName())) result.add(bean);
}
return result;
}
public static List<SpringModel> getNonEmptySpringModelsByFile(final XmlFile file) {
final Module module = ModuleUtil.findModuleForPsiElement(file);
if (module == null) return Collections.singletonList(SpringManager.getInstance(file.getProject()).getSpringModelByFile(file));
final XmlFile originalFile = (XmlFile) file.getOriginalFile();
return ContainerUtil.findAll(getNonEmptySpringModels(module), new Condition<SpringModel>() {
public boolean value(final SpringModel springModel) {
return springModel.getConfigFiles().contains(originalFile);
}
});
}
private static final Key<CachedValue<List<SpringModel>>> NON_EMPTY_SPRING_MODELS_CACHE = Key.create("NON_EMPTY_SPRING_MODELS_CACHE");
public static List<SpringModel> getNonEmptySpringModels(@Nonnull final Module module) {
CachedValue<List<SpringModel>> value = module.getUserData(NON_EMPTY_SPRING_MODELS_CACHE);
if (value == null) {
value = CachedValuesManager.getManager(module.getProject()).createCachedValue(new CachedValueProvider<List<SpringModel>>() {
public Result<List<SpringModel>> compute() {
return Result.create(computeNonEmptyModels(module), PsiModificationTracker.OUT_OF_CODE_BLOCK_MODIFICATION_COUNT);
}
}, false);
module.putUserData(NON_EMPTY_SPRING_MODELS_CACHE, value);
}
return value.getValue();
}
private static List<SpringModel> computeNonEmptyModels(final Module module) {
final Project project = module.getProject();
final SpringManager manager = SpringManager.getInstance(project);
final Ref<Boolean> hasModels = Ref.create(false);
final Ref<Boolean> hasFacets = Ref.create(false);
final List<SpringModel> result = new SmartList<SpringModel>();
ModuleUtil.visitMeAndDependentModules(module, new Processor<Module>() {
public boolean process(final Module module) {
if (!hasFacets.get().booleanValue()) {
hasFacets.set(SpringModuleExtension.getInstance(module) != null);
}
final List<SpringModel> models = manager.getAllModels(module);
for (final SpringModel model : models) {
hasModels.set(true);
result.add(model);
}
return true;
}
});
if (result.isEmpty() && !hasModels.get().booleanValue() && hasFacets.get().booleanValue()) {
List<DomFileElement<Beans>> models = new SmartList<DomFileElement<Beans>>();
Set<XmlFile> modelFiles = new HashSet<XmlFile>();
final GlobalSearchScope scope =
GlobalSearchScope.moduleWithDependentsScope(module).intersectWith(GlobalSearchScope.projectScope(project));
final Collection<VirtualFile> files = DomService.getInstance().getDomFileCandidates(Beans.class, project, scope);
for (final VirtualFile virtualFile : files) {
final Module mod = ModuleUtil.findModuleForFile(virtualFile, project);
if (mod == null || SpringModuleExtension.getInstance(mod) == null) continue;
final PsiFile file1 = PsiManager.getInstance(project).findFile(virtualFile);
if (file1 instanceof XmlFile) {
final XmlFile xmlFile = (XmlFile) file1;
modelFiles.add(xmlFile);
final DomFileElement<Beans> element = DomManager.getDomManager(project).getFileElement(xmlFile, Beans.class);
ContainerUtil.addIfNotNull(element, models);
}
}
if (models.isEmpty()) return Collections.emptyList();
final DomFileElement<Beans> merged = DomService.getInstance().createModelMerger().mergeModels(DomFileElement.class, models);
return Collections.<SpringModel>singletonList(new DomSpringModelImpl(merged, modelFiles, module, null) {
@Override
public String toString() {
return "No fileset mock model";
}
});
}
return result;
}
@Nonnull
public static SpringModel getSpringModel(final SpringModelElement modelElement) {
final Project project = modelElement.getManager().getProject();
final SpringModel model = SpringManager.getInstance(project).getSpringModelByFile(DomUtil.getFile(modelElement));
assert model != null;
return model;
}
@Nullable
private static SpringModel getSpringModelForBean(final CommonSpringBean springBean) {
if (springBean instanceof SpringModelElement) {
return getSpringModel((SpringModelElement) springBean);
}
else {
final Module module = springBean.getModule();
return module == null ? null : SpringManager.getInstance(module.getProject()).getCombinedModel(module);
}
}
@Nullable
public static SpringPropertyDefinition findPropertyByName(@Nonnull final CommonSpringBean bean, @NonNls @Nonnull String propertyName) {
return findPropertyByName(bean, propertyName, true);
}
@Nullable
public static SpringPropertyDefinition findPropertyByName(@Nonnull final CommonSpringBean bean,
@Nonnull final String propertyName,
boolean searchInParentBean) {
for (SpringPropertyDefinition property : getProperties(bean)) {
if (propertyName.equals(property.getPropertyName())) {
return property;
}
}
final Ref<SpringPropertyDefinition> ref = new Ref<SpringPropertyDefinition>();
if (searchInParentBean && bean instanceof SpringBean) {
visitParents((SpringBean) bean, true, new Processor<SpringBean>() {
public boolean process(SpringBean springBean) {
ref.set(findPropertyByName(springBean, propertyName, false));
return ref.get() == null;
}
});
}
return ref.get();
}
@Nullable
public static String getStringPropertyValue(@Nonnull SpringPropertyDefinition property) {
final GenericDomValue<?> element = property.getValueElement();
return element == null ? null : element.getStringValue();
}
@Nonnull
public static Collection<String> getValueVariants(@Nonnull SpringPropertyDefinition property) {
final GenericDomValue value = getPropertyDomValue(property);
if (value == null) return Collections.emptyList();
return getValueVariants(value);
}
@Nonnull
public static Collection<String> getValueVariants(final GenericDomValue value) {
final String stringValue = value.getStringValue();
if (StringUtil.isEmpty(stringValue)) return Collections.emptyList();
final Converter converter = ((PropertyValueConverter) value.getConverter()).getConverter(value);
if (!(converter instanceof PlaceholderPropertiesConverter)) return Collections.singletonList(stringValue);
return PlaceholderUtils.getExpandedVariants(value);
}
@Nullable
public static GenericDomValue<?> getPropertyDomValue(@Nonnull SpringPropertyDefinition property) {
final GenericDomValue<?> valueElement = property.getValueElement();
return valueElement != null && valueElement.getStringValue() == null ? null : valueElement;
}
public static List<SpringValueHolderDefinition> getValueHolders(@Nonnull CommonSpringBean bean) {
return bean instanceof DomSpringBean
? DomUtil.getDefinedChildrenOfType((DomElement) bean, SpringValueHolderDefinition.class)
: Collections.<SpringValueHolderDefinition>emptyList();
}
public static List<CommonSpringBean> getChildBeans(@Nonnull DomElement parent, final boolean includeParsedCustomBeanWrappers) {
final ArrayList<CommonSpringBean> result = new ArrayList<CommonSpringBean>();
for (final DomSpringBean bean : DomUtil.getDefinedChildrenOfType(parent, DomSpringBean.class)) {
if (bean instanceof CustomBeanWrapper) {
if (includeParsedCustomBeanWrappers || !((CustomBeanWrapper) bean).isParsed()) {
result.add(bean);
}
result.addAll(((CustomBeanWrapper) bean).getCustomBeans());
}
else {
result.add(bean);
}
}
return result;
}
public static List<SpringPropertyDefinition> getProperties(@Nonnull CommonSpringBean bean) {
return bean instanceof DomSpringBean
? DomUtil.getDefinedChildrenOfType((DomElement) bean, SpringPropertyDefinition.class)
: Collections.<SpringPropertyDefinition>emptyList();
}
public static List<ConstructorArg> getConstructorArgs(@Nonnull CommonSpringBean bean) {
return bean instanceof SpringBean ? ((SpringBean) bean).getConstructorArgs() : Collections.<ConstructorArg>emptyList();
}
@Nullable
public static Pair<String, PsiElement> getPropertyValue(@Nonnull SpringPropertyDefinition property) {
final GenericDomValue<?> value = getPropertyDomValue(property);
return value == null ? null : Pair.<String, PsiElement>create(value.getStringValue(), DomUtil.getValueElement(value));
}
public static boolean isEffectiveClassType(final SpringInjection injection, final PsiType requiredType) {
PsiType[] types = injection.getTypesByValue();
if (types == null) {
return false;
}
for (PsiType valueType : types) {
if (valueType instanceof PsiClassType) {
final SpringBeanPointer springBean = getReferencedSpringBean(injection);
if (springBean != null && isEffectiveClassType(requiredType, springBean.getSpringBean())) {
return true;
}
}
}
return false;
}
public static boolean isEffectiveClassType(final CommonSpringBean context, final PsiType requiredType, final Module module) {
final PsiClass[] effectiveBeanTypes = getEffectiveBeanTypes(context);
final PsiClass psiClass = resolvePsiClass(requiredType, module);
if (psiClass != null) {
for (PsiClass aClass : effectiveBeanTypes) {
if (InheritanceUtil.isInheritorOrSelf(aClass, psiClass, true)) return true;
}
return isUnusualBeanFactoriesUsed(context);
}
return false;
}
private static boolean isUnusualBeanFactoriesUsed(final CommonSpringBean context) {
final PsiClass beanClass = context.getBeanClass();
if (beanClass != null && SpringFactoryBeansManager.isBeanFactory(beanClass)) {
final SpringFactoryBeansManager manager = SpringFactoryBeansManager.getInstance();
// unregistered factory or unknown product types (for instance, IDEADEV-30892)
return !manager.isFactoryRegistered(beanClass) || manager.getProductTypeClassNames(beanClass, context).size() == 0;
}
return false;
}
public static boolean isEffectiveClassType(final PsiType psiType, @Nonnull final CommonSpringBean context) {
return isEffectiveClassType(context, psiType, context.getModule());
}
@Nullable
private static PsiClass resolvePsiClass(final PsiType psiType, final Module module) {
if (psiType instanceof PsiClassType) {
return ((PsiClassType) psiType).resolve();
}
if (psiType instanceof PsiPrimitiveType) {
if (module != null) {
final GlobalSearchScope scope = GlobalSearchScope.moduleWithDependenciesAndLibrariesScope(module, false);
final PsiManager psiManager = PsiManager.getInstance(module.getProject());
final PsiClassType boxedType = ((PsiPrimitiveType) psiType).getBoxedType(psiManager, scope);
if (boxedType != null) {
return boxedType.resolve();
}
}
}
return null;
}
@Nullable
public static SpringBeanPointer getReferencedSpringBean(SpringPropertyDefinition definition) {
final GenericDomValue<SpringBeanPointer> element = definition.getRefElement();
if (element != null) {
final SpringBeanPointer springBeanPointer = element.getValue();
if (springBeanPointer != null) return springBeanPointer;
}
return definition instanceof SpringInjection ? getReferencedSpringBean((SpringInjection) definition) : null;
}
@Nullable
public static SpringBeanPointer getReferencedSpringBean(SpringInjection injection) {
final SpringBeanPointer refAttrPointer = injection.getRefAttr().getValue();
if (refAttrPointer != null) {
return refAttrPointer;
}
else if (DomUtil.hasXml(injection.getRef())) {
final SpringRef springRef = injection.getRef();
final SpringBeanPointer beanPointer = springRef.getBean().getValue();
if (beanPointer != null) {
return beanPointer;
}
else {
final SpringBeanPointer localPointer = springRef.getLocal().getValue();
if (localPointer != null) {
return localPointer;
}
else {
final SpringBeanPointer parentPointer = springRef.getParentAttr().getValue();
if (parentPointer != null) {
return parentPointer;
}
}
}
}
else if (DomUtil.hasXml(injection.getBean())) {
return SpringBeanPointer.createSpringBeanPointer(injection.getBean());
}
return null;
}
public static String[] suggestBeanNames(@Nullable CommonSpringBean springBean) {
if (springBean != null) {
final PsiClass beanClass = springBean.getBeanClass();
if (beanClass != null) {
final SpringModel model = getSpringModelForBean(springBean);
final JavaCodeStyleManager codeStyleManager = JavaCodeStyleManager.getInstance(beanClass.getProject());
final PsiElementFactory elementFactory = JavaPsiFacade.getInstance(beanClass.getProject()).getElementFactory();
final LinkedHashSet<String> initialNames = new LinkedHashSet<String>();
final PsiClass[] productClasses = getEffectiveBeanTypes(springBean);
if (productClasses.length > 0) {
for (PsiClass productClass : productClasses) {
final PsiClassType classType = elementFactory.createType(productClass);
SuggestedNameInfo nameInfo = codeStyleManager.suggestVariableName(VariableKind.PARAMETER, null, null, classType);
initialNames.addAll(Arrays.asList(nameInfo.names));
}
}
else {
final PsiClassType classType = elementFactory.createType(beanClass);
SuggestedNameInfo nameInfo = codeStyleManager.suggestVariableName(VariableKind.PARAMETER, null, null, classType);
initialNames.addAll(Arrays.asList(nameInfo.names));
}
List<String> uniqueNames = new ArrayList<String>();
for (String name : initialNames) {
String suggestedName = name;
int i = 1;
while (model.findBean(suggestedName) != null || uniqueNames.contains(suggestedName)) {
suggestedName = name + (++i);
}
uniqueNames.add(suggestedName);
}
return ArrayUtil.toStringArray(uniqueNames);
}
}
return new String[0];
}
/**
* @return bean type or product type (for factoryBeans). Multiple values if factory product proxies multiple interfaces
*/
@Nonnull
public static PsiClass[] getEffectiveBeanTypes(@Nonnull final CommonSpringBean bean) {
final PsiClass beanClass = bean.getBeanClass();
Collection<PsiClass> effectiveTypes = new HashSet<PsiClass>();
ContainerUtil.addIfNotNull(beanClass, effectiveTypes);
for (SpringBeanEffectiveTypeProvider provider : Extensions.getExtensions(SpringBeanEffectiveTypeProvider.BEAN_EFFECTIVE_TYPE_PROVIDER_EXTENSION_POINT)) {
provider.processEffectiveTypes(bean, effectiveTypes);
}
return effectiveTypes.toArray(new PsiClass[effectiveTypes.size()]);
}
@Nullable
public static SpringBean getSpringBeanForCurrentCaretPosition(final Editor editor, final PsiFile file) {
int offset = editor.getCaretModel().getOffset();
PsiElement element = file.findElementAt(offset);
return findBeanFromPsiElement(element);
}
@Nullable
public static SpringBean findBeanFromPsiElement(final PsiElement element) {
return DomUtil.findDomElement(element, SpringBean.class);
}
@Nonnull
public static String getPresentationBeanName(final SpringBeanPointer pointer) {
String beanName = pointer.getName();
if (beanName == null) {
final PsiClass psiClass = pointer.getBeanClass();
if (psiClass != null) beanName = psiClass.getName();
final CommonSpringBean springBean = pointer.getSpringBean();
if (springBean instanceof SpringBean) {
final String unresolvedClassName = ((SpringBean) springBean).getClazz().getStringValue();
if (unresolvedClassName != null) beanName = unresolvedClassName;
}
}
return beanName == null ? SpringBundle.message("spring.bean.dependency.graph.node.unknown") : beanName;
}
public static List<SpringBeanPointer> getSetterDependencies(final CommonSpringBean springBean) {
List<SpringBeanPointer> dependencies = new ArrayList<SpringBeanPointer>();
if (springBean instanceof DomSpringBean) {
for (SpringPropertyDefinition property : getProperties((DomSpringBean) springBean)) {
if (property instanceof SpringValueHolder) {
dependencies.addAll(getSpringValueHolderDependencies(property));
}
}
}
return dependencies;
}
public static List<SpringBeanPointer> getConstructorDependencies(final CommonSpringBean springBean) {
List<SpringBeanPointer> dependencies = new ArrayList<SpringBeanPointer>();
if (springBean instanceof DomSpringBean) {
for (ConstructorArg arg : getConstructorArgs((DomSpringBean) springBean)) {
dependencies.addAll(getSpringValueHolderDependencies(arg));
}
}
return dependencies;
}
public static List<SpringBaseBeanPointer> getSpringValueHolderDependencies(final SpringValueHolderDefinition valueHolder) {
Set<SpringBaseBeanPointer> beans = new LinkedHashSet<SpringBaseBeanPointer>();
addValueHolder(valueHolder, beans);
return new ArrayList<SpringBaseBeanPointer>(beans);
}
private static void addValueHolder(final SpringValueHolderDefinition definition, final Set<SpringBaseBeanPointer> beans) {
final GenericDomValue<SpringBeanPointer> element = definition.getRefElement();
if (element != null) {
addBasePointer(element, beans);
}
if (definition instanceof SpringValueHolder) {
final SpringValueHolder valueHolder = (SpringValueHolder) definition;
addSpringRefBeans(valueHolder.getRef(), beans);
addIdrefBeans(valueHolder.getIdref(), beans);
if (DomUtil.hasXml(valueHolder.getList())) {
addCollectionReferences(valueHolder.getList(), beans);
}
if (DomUtil.hasXml(valueHolder.getSet())) {
addCollectionReferences(valueHolder.getSet(), beans);
}
if (DomUtil.hasXml(valueHolder.getMap())) {
addMapReferences(valueHolder.getMap(), beans);
}
if (DomUtil.hasXml(valueHolder.getBean())) {
beans.add(DomSpringBeanPointer.createDomSpringBeanPointer(valueHolder.getBean()));
}
}
}
private static void addBasePointer(final GenericValue<SpringBeanPointer> value, final Collection<SpringBaseBeanPointer> beans) {
ContainerUtil.addIfNotNull(getBasePointer(value.getValue()), beans);
}
private static void addMapReferences(final SpringMap map, final Set<SpringBaseBeanPointer> beans) {
for (SpringEntry entry : map.getEntries()) {
addValueHolder(entry, beans);
}
}
private static void addIdrefBeans(final Idref idref, final Set<SpringBaseBeanPointer> beans) {
addBasePointer(idref.getLocal(), beans);
addBasePointer(idref.getBean(), beans);
}
private static void addSpringRefBeans(final SpringRef springRef, final Set<SpringBaseBeanPointer> beans) {
if (DomUtil.hasXml(springRef)) {
addBasePointer(springRef.getBean(), beans);
addBasePointer(springRef.getLocal(), beans);
}
}
private static void addCollectionReferences(final CollectionElements elements, final Set<SpringBaseBeanPointer> beans) {
for (SpringRef springRef : elements.getRefs()) {
addSpringRefBeans(springRef, beans);
}
for (Idref idref : elements.getIdrefs()) {
addIdrefBeans(idref, beans);
}
for (ListOrSet listOrSet : elements.getLists()) {
addCollectionReferences(listOrSet, beans);
}
for (ListOrSet listOrSet : elements.getSets()) {
addCollectionReferences(listOrSet, beans);
}
for (SpringBean innerBean : elements.getBeans()) {
beans.add(DomSpringBeanPointer.createDomSpringBeanPointer(innerBean));
}
for (SpringMap map : elements.getMaps()) {
addMapReferences(map, beans);
}
}
@Nullable
public static PsiFile getContainingFile(final CommonSpringBean springBean) {
return springBean.getContainingFile();
}
public static boolean isAssignable(final Project project, final PsiClassType type, final String className) {
final PsiClass psiClass = type.resolve();
if (psiClass != null) {
final PsiManager psiManager = PsiManager.getInstance(project);
final PsiClass required = JavaPsiFacade.getInstance(psiManager.getProject()).findClass(className, GlobalSearchScope.allScope(project));
if (required != null && InheritanceUtil.isInheritorOrSelf(psiClass, required, true)) {
return true;
}
}
return false;
}
@Nullable
public static SpringBeanPointer getBeanPointer(final SpringModel model, @NonNls @Nonnull String beanName) {
String beanReferenceName = beanName.startsWith("&") ? beanName.substring(1) : beanName; // IDEADEV-13855
return findBean(model, beanReferenceName);
}
@Nullable
public static SpringBeanPointer findBean(final SpringModel model, String beanName) {
if (StringUtil.isEmptyOrSpaces(beanName)) return null;
return model.findBean(beanName);
}
public static boolean isCompiled(@Nonnull PsiElement element) {
return element instanceof PsiCompiledElement || element.getOriginalElement() instanceof PsiCompiledElement;
}
public static void navigate(@Nullable DomElement domElement) {
if (domElement == null) return;
final DomElementsNavigationManager navigationManager = DomElementsNavigationManager.getManager(domElement.getManager().getProject());
navigationManager.getDomElementsNavigateProvider(DomElementsNavigationManager.DEFAULT_PROVIDER_NAME).navigate(domElement, true);
}
public static List<SpringBaseBeanPointer> getSpringBeans(final PsiClass aClass) {
final List<SpringBaseBeanPointer> beans = new SmartList<SpringBaseBeanPointer>();
final Module module = ModuleUtil.findModuleForPsiElement(aClass);
if (module != null) {
final SpringModel springModel = SpringManager.getInstance(aClass.getProject()).getCombinedModel(module);
if (springModel != null) {
beans.addAll(springModel.findBeansByPsiClass(aClass));
}
}
return beans;
}
public static List<PsiType> resolveGenerics(PsiClassType classType) {
List<PsiType> generics = new ArrayList<PsiType>();
final PsiClassType.ClassResolveResult resolveResult = classType.resolveGenerics();
final PsiClass psiClass = resolveResult.getElement();
final PsiSubstitutor substitutor = resolveResult.getSubstitutor();
if (psiClass != null && substitutor != null) {
for (PsiTypeParameter typeParameter : psiClass.getTypeParameters()) {
generics.add(substitutor.substitute(typeParameter));
}
}
return generics;
}
public static boolean isCollectionType(final PsiType psiType, final Project project) {
final PsiType collectionType = SpringConverterUtil.findType(Collection.class, project);
return collectionType != null && collectionType.isAssignableFrom(psiType);
}
@Nullable
public static PsiType getGenericCollectonType(final PsiType psiType) {
final List<PsiType> psiTypes = resolveGenerics((PsiClassType) psiType);
return psiTypes.size() == 1 ? psiTypes.get(0) : null;
}
@Nullable
public static SpringBaseBeanPointer getBasePointer(final SpringBeanPointer springBeanPointer) {
return springBeanPointer == null ? null : springBeanPointer.getBasePointer();
}
@Nonnull
public static SpringBean getTopLevelBean(@Nonnull SpringBean bean) {
final DomElement parent = bean.getParent();
if (parent instanceof Beans) {
return bean;
}
else {
assert parent != null;
final SpringBean parentBean = bean.getParentOfType(SpringBean.class, true);
return getTopLevelBean(parentBean);
}
}
public static boolean visitParents(final SpringBean springBean, final boolean strict, Processor<SpringBean> processor) {
SpringBeanPointer parent = springBean.getParentBean().getValue();
if (parent == null) {
return true;
}
final HashSet<CommonSpringBean> visited = new HashSet<CommonSpringBean>();
if (!strict) {
visited.add(springBean);
if (!processor.process(springBean)) {
return false;
}
}
CommonSpringBean bean = parent.getSpringBean();
while (bean instanceof SpringBean) {
if (!processor.process((SpringBean) bean)) {
return false;
}
parent = ((SpringBean) bean).getParentBean().getValue();
if (parent == null) {
return true;
}
bean = parent.getSpringBean();
if (visited.contains(bean)) {
return true;
}
visited.add(bean);
}
return true;
}
public static <T extends GenericDomValue<?>> T getMergedValue(SpringBean springBean, T value) {
final AbstractDomChildrenDescription description = value.getChildDescription();
final Ref<T> ref = new Ref<T>(value);
visitParents(springBean, false, new Processor<SpringBean>() {
public boolean process(final SpringBean springBean) {
final List<? extends DomElement> list = description.getValues(springBean);
if (list.size() == 1) {
final T t = (T) list.get(0);
if (DomUtil.hasXml(t)) {
ref.set(t);
return false;
}
}
return true;
}
});
return ref.get();
}
public static <T extends DomElement> Set<T> getMergedSet(final SpringBean springBean, final Function<SpringBean, Collection<T>> getter) {
final Set<T> set = new HashSet<T>(getter.fun(springBean));
visitParents(springBean, false, new Processor<SpringBean>() {
public boolean process(final SpringBean springBean) {
set.addAll(getter.fun(springBean));
return true;
}
});
return set;
}
public static boolean compareQualifiers(SpringQualifier one, final SpringQualifier two) {
if (!Comparing.equal(one.getQualifierType(), two.getQualifierType())) return false;
if (!Comparing.equal(one.getQualifierValue(), two.getQualifierValue())) return false;
final List<? extends QualifierAttribute> list1 = one.getQualifierAttributes();
final int size1 = list1.size();
final List<? extends QualifierAttribute> list2 = two.getQualifierAttributes();
final int size2 = list2.size();
if (size1 != size2) return false;
if (size1 == 0) return true;
final Set<QualifierAttribute> set = Sets.newHashSet(QualifierAttribute.HASHING_STRATEGY);
set.addAll(list1);
return set.containsAll(list2);
}
@Nonnull
public static List<SpringBaseBeanPointer> getBeansByType(final PsiType type, final SpringModel model) {
if (type instanceof PsiClassType) {
final PsiClass psiClass = ((PsiClassType) type).resolve();
if (psiClass != null) {
return model.findBeansByEffectivePsiClassWithInheritance(psiClass);
}
}
return Collections.emptyList();
}
public static boolean isSpring25(@Nonnull final Module module) {
final String s = JarVersionDetectionUtil.detectJarVersion(SpringConstants.SPRING_VERSION_CLASS, module);
final boolean b = s != null && !s.startsWith("1.") && !s.startsWith("2.0") && !s.startsWith("2.1");
return b;
}
@Nonnull
public static Set<String> getListOrSetValues(@Nonnull final SpringPropertyDefinition property) {
if (property instanceof SpringProperty) {
final SpringProperty springProperty = (SpringProperty) property;
if (DomUtil.hasXml(springProperty.getList())) {
return getValues(springProperty.getList());
}
else if (DomUtil.hasXml(springProperty.getSet())) {
return getValues(springProperty.getSet());
}
}
return Collections.emptySet();
}
@Nonnull
public static Set<String> getValues(@Nonnull final ListOrSet listOrSet) {
final Set<String> values = new HashSet<String>();
for (SpringValue value : listOrSet.getValues()) {
if (value.getValue() != null) {
values.add(value.getStringValue());
}
}
return values;
}
public static Set<String> getAllBeanNames(final SpringBean bean) {
final String beanName = bean.getBeanName();
return beanName == null ? Collections.<String>emptySet() : getSpringModel(bean).getAllBeanNames(beanName);
}
public static Set<String> getAllBeanNames(final CommonSpringBean bean) {
final String beanName = bean.getBeanName();
if (beanName == null) {
return Collections.emptySet();
}
final SpringModel model = getSpringModelForBean(bean);
return model == null ? Collections.<String>emptySet() : model.getAllBeanNames(beanName);
}
@Nullable
public static SpringModel getModelByPsiElement(final PsiElement element) {
if (element == null) {
return null;
}
final Module module = ModuleUtil.findModuleForPsiElement(element);
return module == null ? null : SpringManager.getInstance(element.getProject()).getCombinedModel(module);
}
}
| 39.614583
| 157
| 0.71838
|
ca83054f02316881ccb193c2423442f57748a12c
| 2,125
|
cs
|
C#
|
test/Tizen.NUI.Tests/Tizen.NUI.Devel.Tests/testcase/internal/XamlBinding/TSDeviceInfo.cs
|
lavataste/TizenFX
|
3fc9512605edf181efeaabfece170fe97fe51e9e
|
[
"Apache-2.0",
"MIT"
] | 149
|
2018-01-01T19:10:14.000Z
|
2022-03-03T07:38:55.000Z
|
test/Tizen.NUI.Tests/Tizen.NUI.Devel.Tests/testcase/internal/XamlBinding/TSDeviceInfo.cs
|
lavataste/TizenFX
|
3fc9512605edf181efeaabfece170fe97fe51e9e
|
[
"Apache-2.0",
"MIT"
] | 2,078
|
2017-12-27T05:26:36.000Z
|
2022-03-31T10:49:53.000Z
|
test/Tizen.NUI.Tests/Tizen.NUI.Devel.Tests/testcase/internal/XamlBinding/TSDeviceInfo.cs
|
lavataste/TizenFX
|
3fc9512605edf181efeaabfece170fe97fe51e9e
|
[
"Apache-2.0",
"MIT"
] | 394
|
2017-12-26T06:29:51.000Z
|
2022-03-29T03:16:35.000Z
|
using global::System;
using NUnit.Framework;
using NUnit.Framework.TUnit;
using Tizen.NUI.Components;
using Tizen.NUI.BaseComponents;
using System.Reflection;
using System.Collections.Generic;
using Tizen.NUI.Binding;
namespace Tizen.NUI.Devel.Tests
{
using tlog = Tizen.Log;
[TestFixture]
[Description("internal/XamlBinding/DeviceInfo")]
public class InternalDeviceInfoTest
{
private const string tag = "NUITEST";
internal class MyDeviceInfo : DeviceInfo
{
public override Size PixelScreenSize => new Size(100,100);
public override Size ScaledScreenSize => new Size(100, 100);
public override double ScalingFactor => 1.0f;
}
[SetUp]
public void Init()
{
tlog.Info(tag, "Init() is called!");
}
[TearDown]
public void Destroy()
{
tlog.Info(tag, "Destroy() is called!");
}
[Test]
[Category("P1")]
[Description("DeviceInfo constructor")]
[Property("SPEC", "Tizen.NUI.Binding.DeviceInfo.DeviceInfo C")]
[Property("SPEC_URL", "-")]
[Property("CRITERIA", "CONSTR")]
public void DeviceInfoConstructor()
{
tlog.Debug(tag, $"DeviceInfoConstructor START");
var testingTarget = new MyDeviceInfo();
Assert.IsNotNull(testingTarget, "Can't create success object DeviceInfo.");
Assert.IsInstanceOf<MyDeviceInfo>(testingTarget, "Should return DeviceInfo instance.");
Assert.AreEqual(1.0, testingTarget.DisplayRound(1.0), "Should be equal");
var ret = testingTarget.CurrentOrientation;
testingTarget.CurrentOrientation = ret;
Assert.AreEqual(ret, testingTarget.CurrentOrientation, "Should be equal");
testingTarget.CurrentOrientation = DeviceOrientation.Other;
Assert.AreEqual(DeviceOrientation.Other, testingTarget.CurrentOrientation, "Should be equal");
testingTarget.Dispose();
tlog.Debug(tag, $"DeviceInfoConstructor END");
}
}
}
| 31.716418
| 106
| 0.628706
|
dfd8e7214b996aebd843cb90b21367db149deab2
| 2,823
|
cs
|
C#
|
Sonic 2D/Assets/Sprites/PhysicsObject.cs
|
Otterlord/Sonic-Engine-Unity2D
|
33c2fcd49a6412c814c8d89caccc5478b641418a
|
[
"MIT"
] | 1
|
2021-08-06T23:34:25.000Z
|
2021-08-06T23:34:25.000Z
|
Sonic 2D/Assets/Sprites/PhysicsObject.cs
|
Otterlord/Sonic-Engine-Unity2D
|
33c2fcd49a6412c814c8d89caccc5478b641418a
|
[
"MIT"
] | 1
|
2018-08-20T01:35:44.000Z
|
2018-08-20T01:35:44.000Z
|
Sonic 2D/Assets/Sprites/PhysicsObject.cs
|
Otterlord/Sonic-Engine-Unity2D
|
33c2fcd49a6412c814c8d89caccc5478b641418a
|
[
"MIT"
] | null | null | null |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PhysicsObject : MonoBehaviour {
protected Vector2 velocity;
protected Vector2 target;
protected Vector2 targetV;
protected Rigidbody2D rb;
public float grv = 9.8f;
protected bool grounded = false;
protected Vector2 groundNormal;
protected const float minMoveDist = 0.001f;
protected ContactFilter2D contactFilter;
protected RaycastHit2D[] hitBuffer = new RaycastHit2D[16];
public float minGroundNormal = 0.65f;
protected const float shellRadius = 0.01f;
protected List<RaycastHit2D> hitBufferList = new List<RaycastHit2D>(16);
// Use this for initialization
void Start ()
{
rb = GetComponent<Rigidbody2D>();
contactFilter.useTriggers = false;
contactFilter.SetLayerMask(Physics2D.GetLayerCollisionMask(gameObject.layer));
contactFilter.useLayerMask = true;
}
// Update is called once per frame
void FixedUpdate () {
velocity = target;
grounded = false;
Vector2 deltaVelocity = velocity * Time.deltaTime;
Vector2 moveAlongGround = new Vector2(groundNormal.y, -groundNormal.x);
Vector2 move = moveAlongGround * deltaVelocity.x;
Move(move, false);
move = targetV * Time.deltaTime;
Move(move, true);
}
void Move (Vector2 movement, bool yMovement)
{
float distance = movement.magnitude;
if (distance > minMoveDist)
{
print("yey");
int count = rb.Cast(movement, contactFilter, hitBuffer, distance + shellRadius);
hitBufferList.Clear();
for (int i = 0; i < count; i++)
{
hitBufferList.Add(hitBuffer[i]);
}
for (int i = 0; i < hitBufferList.Count; i++)
{
Vector2 currentNormal = hitBufferList[i].normal;
//groundNormal = currentNormal;
grounded = true;
if (true) // currentNormal.y > minGroundNormal
{
grounded = true;
if (yMovement)
{
groundNormal = currentNormal;
currentNormal.x = 0;
}
}
float projection = Vector2.Dot(velocity, currentNormal);
if (projection < 0)
{
velocity = velocity - projection * currentNormal;
}
float modifiedDistance = hitBufferList[i].distance - shellRadius;
distance = modifiedDistance < distance ? modifiedDistance : distance;
}
}
else print("!");
rb.position += movement.normalized * distance;
}
}
| 29.715789
| 92
| 0.57492
|
dc34aa9831dae50d5bc5ba897a9d612c2c983ff1
| 170
|
tsx
|
TypeScript
|
src/pages/index.tsx
|
tsmvision/nextjs-typescript-jest-enzyme-template
|
00a1e46cc46e9168f28ad1f1e83d929f46ccfa83
|
[
"Apache-2.0"
] | null | null | null |
src/pages/index.tsx
|
tsmvision/nextjs-typescript-jest-enzyme-template
|
00a1e46cc46e9168f28ad1f1e83d929f46ccfa83
|
[
"Apache-2.0"
] | null | null | null |
src/pages/index.tsx
|
tsmvision/nextjs-typescript-jest-enzyme-template
|
00a1e46cc46e9168f28ad1f1e83d929f46ccfa83
|
[
"Apache-2.0"
] | null | null | null |
import React from 'react';
const HomePage = () => {
return (
<div>
<h1>Welcome to Next.js</h1>
</div>
);
};
export default HomePage;
| 15.454545
| 39
| 0.5
|
744fbb665aad6895ac6c412ea664df9919159514
| 245
|
h
|
C
|
examples/demo_common/ProcedureLoader.h
|
rafael-radkowski/TrackingExpert-
|
007310637e1582d9623e518510d5d9eccaa23c2c
|
[
"MIT"
] | 26
|
2020-02-28T06:20:36.000Z
|
2021-12-09T09:52:06.000Z
|
examples/demo_common/ProcedureLoader.h
|
rafael-radkowski/TrackingExpert-
|
007310637e1582d9623e518510d5d9eccaa23c2c
|
[
"MIT"
] | 6
|
2020-02-19T15:04:27.000Z
|
2021-08-15T20:32:08.000Z
|
examples/demo_common/ProcedureLoader.h
|
rafael-radkowski/TrackingExpert-
|
007310637e1582d9623e518510d5d9eccaa23c2c
|
[
"MIT"
] | 5
|
2020-07-09T18:58:34.000Z
|
2021-08-16T00:40:06.000Z
|
#pragma once
/*!
*/
#include <string>
#include <stdio.h>
#include <iostream>
#include <opencv2/core.hpp>
#include "Procedure.h"
class ProcedureLoader
{
public:
static bool loadProcedure(const std::string& path, Procedure& _procedure);
};
| 12.894737
| 75
| 0.714286
|
a3b0c1fd4ca4b41ca1e6d0866650784b39e8a4e8
| 248
|
ts
|
TypeScript
|
scripts/fmt.ts
|
littledivy/webview_deno
|
2977bb9abf4bf651cb47b14e7bb291c14bea10d2
|
[
"MIT"
] | 702
|
2020-06-14T15:21:25.000Z
|
2022-03-29T13:12:40.000Z
|
scripts/fmt.ts
|
littledivy/webview_deno
|
2977bb9abf4bf651cb47b14e7bb291c14bea10d2
|
[
"MIT"
] | 72
|
2020-06-16T08:07:31.000Z
|
2022-03-31T15:51:06.000Z
|
scripts/fmt.ts
|
littledivy/webview_deno
|
2977bb9abf4bf651cb47b14e7bb291c14bea10d2
|
[
"MIT"
] | 42
|
2020-06-18T11:30:13.000Z
|
2022-03-25T21:09:58.000Z
|
import { requires, run } from "./_util.ts";
export async function fmt() {
await requires("cargo", "deno");
await run("formatting rust", ["cargo", "fmt"]);
await run("formatting deno", ["deno", "fmt"]);
}
if (import.meta.main) {
fmt();
}
| 19.076923
| 49
| 0.604839
|
beb77647689e48643d125ad391def3f50c311c7d
| 3,038
|
ts
|
TypeScript
|
src/api/types.ts
|
YoungProducer/zno-client
|
5bc752f2523a071fd2ab2036606d688342c92e7a
|
[
"MIT"
] | null | null | null |
src/api/types.ts
|
YoungProducer/zno-client
|
5bc752f2523a071fd2ab2036606d688342c92e7a
|
[
"MIT"
] | 3
|
2021-03-10T19:54:39.000Z
|
2022-02-27T05:30:50.000Z
|
src/api/types.ts
|
YoungProducer/zno-client
|
5bc752f2523a071fd2ab2036606d688342c92e7a
|
[
"MIT"
] | null | null | null |
/**
* Created by: Oleksandr Bezrukov
* Creation date: 26 February 2020
*
* Declare main interfaces related to API.
*/
// External imports
import { AxiosResponse, AxiosInstance } from 'axios';
export interface ISignUpCredentials {
email: string;
password: string;
}
export interface ISignInCredentials {
email: string;
password: string;
}
export interface ISubjectConfigurationCredentials {
id: string;
}
/** Typings for testSuite method */
export interface ITestSuiteCredentials {
subjectId: string;
subSubjectId?: string;
theme?: string;
/**
* If user select exams
* and sessions type of exams
* this value must contain
* the value of selected session
*/
session?: string;
/**
* If user select exams
* and trainings type of exams
* this value must contain
* the value of selected training
*/
training?: string;
}
export type TAnswerType = 'SINGLE' | 'RELATIONS' | 'TEXT';
export interface IAnswerFromResponse {
/**
* Index of task.
*/
taskId: number;
answer: string[];
type: TAnswerType;
}
export interface ITestSuiteResponseData {
/**
* Test suite id.
*/
id: string;
/**
* Theme name.
*/
theme?: string | null;
/**
* Session name.
*/
session?: string | null;
/**
* Training variant name.
*/
training?: string | null;
/**
* Answers.
*/
answers: IAnswerFromResponse[];
}
/** Types for method testSuiteImages */
export interface ITestSuiteImagesCredentials {
/**
* Test suite id.
*/
id: string;
}
export type TTestSuiteImagesResponseData = string[];
/** Auth types */
export type TUserRole = 'DEFAULT_USER' | 'ADMIN';
export interface IUser {
id: string;
email: string;
name: string;
lastName: string;
role: TUserRole;
emailConfirmed: boolean;
}
export type ISignUpResponseData = IUser;
export type ISignInResponseData = IUser;
export type IMeReponseData = IUser;
export interface IApi {
axiosInstance: AxiosInstance;
/** Methods related to auth */
signup(credentials: ISignUpCredentials): Promise<AxiosResponse<ISignUpResponseData>>;
signin(credentials: ISignInCredentials): Promise<AxiosResponse<ISignInResponseData>>;
me(): Promise<AxiosResponse<IMeReponseData>>;
logout(): Promise<AxiosResponse>;
/** Methods related to subjects and subject configuration */
subjects(): Promise<AxiosResponse>;
subjectConfiguration(credentials: ISubjectConfigurationCredentials): Promise<AxiosResponse>;
/** Methods related to test suites */
testSuite(credentials: ITestSuiteCredentials): Promise<AxiosResponse<ITestSuiteResponseData>>;
testSuiteImages(credentials: ITestSuiteImagesCredentials): Promise<AxiosResponse<TTestSuiteImagesResponseData>[]>;
tasksImages(credentials: ITestSuiteImagesCredentials): Promise<AxiosResponse>;
explanationsImages(credentials: ITestSuiteImagesCredentials): Promise<AxiosResponse>;
}
| 24.5
| 118
| 0.683673
|
d16625e6c47e9a275c902c79bc99b20dd073a382
| 3,002
|
rs
|
Rust
|
devtools/src/codegen/m2x4hd/mod.rs
|
jpattWPC/minidsp-rs
|
d10961cb47ee3ca26d0407480c9f5596d529165b
|
[
"Apache-2.0"
] | 43
|
2021-01-05T14:18:01.000Z
|
2022-03-25T11:55:27.000Z
|
devtools/src/codegen/m2x4hd/mod.rs
|
jpattWPC/minidsp-rs
|
d10961cb47ee3ca26d0407480c9f5596d529165b
|
[
"Apache-2.0"
] | 271
|
2021-01-09T15:50:30.000Z
|
2022-03-28T10:10:35.000Z
|
devtools/src/codegen/m2x4hd/mod.rs
|
jpattWPC/minidsp-rs
|
d10961cb47ee3ca26d0407480c9f5596d529165b
|
[
"Apache-2.0"
] | 7
|
2021-04-09T09:48:50.000Z
|
2022-02-25T05:03:09.000Z
|
use bimap::BiHashMap;
use minidsp::formats::xml_config::Setting;
use strong_xml::XmlRead;
use super::spec::*;
pub struct Target {}
impl crate::Target for Target {
fn filename() -> &'static str {
"m2x4hd.rs"
}
fn symbols() -> bimap::BiMap<String, usize> {
symbols()
}
fn device() -> Device {
device()
}
}
pub(crate) fn input(input: usize) -> Input {
Input {
gate: Some(Gate {
enable: format!("DGain_{}_0_status", input + 1),
gain: format!("DGain_{}_0", input + 1),
}),
meter: Some(format!("Meter02_C1_{}", input)),
peq: (0..10usize)
.map(|index| format!("PEQ_{}_{}", input + 1, 10 - index))
.collect(),
routing: (0..4usize)
.map(|output| Gate {
enable: format!("MixerNxMSmoothed1_{}_{}_status", input, output),
gain: format!("MixerNxMSmoothed1_{}_{}", input, output),
})
.collect(),
}
}
pub(crate) fn output(output: usize) -> Output {
Output {
gate: Gate {
enable: format!("DGain_{}_0_status", 3 + output),
gain: format!("DGain_{}_0", 3 + output),
},
meter: format!("Meter10_C1_{}", 4 + output),
delay_addr: format!("Delay_{}_0", 3 + output),
invert_addr: format!("polarity_out_{}_0", 1 + output),
peq: (1..=10usize)
.rev()
.map(|index| format!("PEQ_{}_{}", output + 3, index))
.collect(),
xover: Some(Crossover {
peqs: [1, 5]
.iter()
.map(|group| format!("BPF_{}_{}", output + 3, group))
.collect(),
}),
compressor: Some(Compressor {
bypass: format!("COMP_{}_0_status", output + 3),
threshold: format!("COMP_{}_0_threshold", output + 3),
ratio: format!("COMP_{}_0_ratio", output + 3),
attack: format!("COMP_{}_0_atime", output + 3),
release: format!("COMP_{}_0_rtime", output + 3),
meter: Some(format!("Meter10_C1_{}", output)),
}),
fir: Some(Fir {
index: output as u8,
num_coefficients: format!("FIR_{}_0_Taps", output + 3),
bypass: format!("FIR_{}_0_status", output + 3),
max_coefficients: 4096,
}),
}
}
pub fn device() -> Device {
Device {
product_name: "2x4HD".into(),
sources: vec!["Analog".into(), "Toslink".into(), "Usb".into()],
inputs: (0..2).map(input).collect(),
outputs: (0..4).map(output).collect(),
fir_max_taps: 4096,
internal_sampling_rate: 96000,
}
}
pub fn symbols() -> BiHashMap<String, usize> {
let cfg = include_str!("config.xml");
Setting::from_str(cfg).unwrap().name_map()
}
#[cfg(test)]
#[test]
fn test_codegen() {
let mut symbol_map = symbols();
let spec = device();
super::generate_static_config(&mut symbol_map, &spec).to_string();
}
| 30.02
| 81
| 0.517988
|
b7176c107b4c4c326de6c7ac47392a995897d323
| 9,801
|
hpp
|
C++
|
include/mflib/waveformTemplate.hpp
|
uofuseismo/mflib
|
14695f62082d28d4cc5603bb6edcaf1efe9dd980
|
[
"MIT"
] | 5
|
2019-12-06T21:14:17.000Z
|
2021-09-21T03:36:58.000Z
|
include/mflib/waveformTemplate.hpp
|
uofuseismo/mflib
|
14695f62082d28d4cc5603bb6edcaf1efe9dd980
|
[
"MIT"
] | 5
|
2019-11-27T19:06:06.000Z
|
2020-04-24T19:07:44.000Z
|
include/mflib/waveformTemplate.hpp
|
uofuseismo/mflib
|
14695f62082d28d4cc5603bb6edcaf1efe9dd980
|
[
"MIT"
] | 2
|
2021-09-09T11:15:50.000Z
|
2021-12-04T00:50:53.000Z
|
#ifndef MFLIB_WAVEFORMTEMPLATE_HPP
#define MFLIB_WAVEFORMTEMPLATE_HPP
#include <memory>
#include "mflib/enums.hpp"
namespace MFLib
{
class NetworkStationPhase;
/*!
* @brief Defines a waveform template.
* @copyright Ben Baker (University of Utah) distributed under the MIT license.
*/
class WaveformTemplate
{
public:
/*! @name Constructors
* @{
*/
/*!
* @brief Constructor.
*/
WaveformTemplate();
/*!
* @brief Copy constructor.
* @param[in] tplate The template class from which to initialize this
* template.
*/
WaveformTemplate(const WaveformTemplate &tplate);
/*!
* @brief Move constructor.
* @param[in,out] tplate The template class whose memory will be moved
* to this. On exit, tplate's behavior is undefined.
*/
WaveformTemplate(WaveformTemplate &&tplate) noexcept;
/*! } */
/*!
* @brief Copy assignment operator.
* @param[in] tplate The waveform template class to copy.
* @result A deep copy of the inupt waveform template.
*/
WaveformTemplate& operator=(const WaveformTemplate &tplate);
/*!
* @brief Move assignment operator.
* @param[in,out] tplate The waveform template class whose memory will be
* moved to this class. On exit, tplate's behavior
* is undefined.
* @result The memory from tplate moved to this.
*/
WaveformTemplate& operator=(WaveformTemplate &&tplate) noexcept;
/*! @name Destructors
* @{
*/
/*!
* @brief Destructor.
*/
~WaveformTemplate();
/*!
* @brief Clears and resets the memory of the class.
*/
void clear() noexcept;
/*! @} */
/*! @name Signal (Required)
* @{
*/
/*!
* @brief Sets the template waveform signal.
* @param[in] npts The number of samples in the template.
* @param[in] x The template waveform signal. This is an array whose
* dimension is [npts].
* @throws std::invalid_argument if npts is not positive or x is NULL.
* @note This will invalidate the onset time.
*/
void setSignal(int npts, const double x[]);
/*! @coypdoc setSignal */
void setSignal(int npts, const float x[]);
/*!
* @brief Gets the template waveform signal.
* @param[in] maxx The maximum number of samples that x can hold. This
* must be at least \c getSignalLength().
* @param[out] x The waveform template. This is an array whose dimension
* is [maxx] however only the first \c getSignalLength()
* samples are accessed.
* @throws std::invalid_argument if x is NULL or maxx is too small.
* @throws std::runtime_error if the signal was not set.
*/
void getSignal(int maxx, double *x[]) const;
/*! @copydoc getSignal */
void getSignal(int maxx, float *x[]) const;
/*!
* @result The length of the template waveform signal.
* @throws std::runtime_error if the template waveform was not set.
* @sa \c haveSignal()
*/
int getSignalLength() const;
/*!
* @brief Determines if the template waveform signal was set.
* @result True indicates that the template was set.
*/
bool haveSignal() const noexcept;
/*! @} */
/*! @name Sampling Rate (Required)
* @{
*/
/*!
* @brief Sets the sampling rate.
* @param[in] samplingRate The sampling rate in Hz of the template waveform
* signal.
* @throws std::invalid_argument if this is not positive.
* @note This will invalidate the onset time.
*/
void setSamplingRate(double samplingRate);
/*!
* @brief Gets the sampling rate.
* @result The template's sampling rate.
* @throws std::runtime_error if the sampling rate was not set.
*/
double getSamplingRate() const;
/*!
* @brief Determines if the sampling rate was set.
* @result True indicates that the sampling rate was set.
*/
bool haveSamplingRate() const noexcept;
/*! @} */
/*! @name Shift and Sum Weight
* @{
*/
/*!
* @brief Defines the template's weight in the shift and stack operation.
* @param[in] weight The weight of this template during the shift and sum
* operation.
* @throws std::invalid_argument if weight is not in the range [0,1].
*/
void setShiftAndStackWeight(double weight);
/*!
* @brief Gets the template's weight during the shift and stack operation.
* @result The template's weight during the shift and sum operation.
* @note If \c setShiftStackAndWeight() was not called then this will
* be unity.
*/
double getShiftAndStackWeight() const noexcept;
/*! @} */
/*! @name Onset Time (Required for Shifting)
* @{
*/
/*!
* @brief Sets the time in seconds relative to the trace where the
* phase onset occurs.
* @param[in] onsetTime The onset time in seconds where the pick occurs.
* For example, if the pick is 2 seconds into the
* the trace, i.e., there is `noise' 2 seconds prior
* to the pick, then this should be 2.
* @throws std::runtime_error if the waveform template signal was not set
* or the sampling rate was not set.
* @throws std::invalid_argument if the onset time is not in the trace.
* @sa \c haveSignal(), \c haveSamplingRate().
* @note This is invalidated whenever the sampling period or signal is set.
*/
void setPhaseOnsetTime(double onsetTime);
/*!
* @brief Gets the phase onset time.
* @result The time, relative to the trace start, where the pick occurs.
* For example, if 2, then 2 seconds into the trace is where the
* pick was made.
* @throws std::runtime_error if the onset time was not set.
* @sa \c havePhaseOnsetTime()
*/
double getPhaseOnsetTime() const;
/*!
* @brief Determines if the onset time was set.
* @result True indicates that the onset time was set.
*/
bool havePhaseOnsetTime() const noexcept;
/*!@ } */
/*! @brief Travel Time (Required for Shifting)
* @{
*/
/*!
* @brief Sets the observed travel time for the pick.
* @param[in] travelTime The observed travel time in seconds for the pick.
* For example, if this is 7, then it took 7 seconds
* for the wave to travel from the source to the
* receiver.
* @throws std::invalid_argument if travelTime is negative
* @note The trace commences travelTime - onsetTime seconds after the origin
* time.
*/
void setTravelTime(double travelTime);
/*!
* @brief Gets the observed travel time for the pick.
* @result The observed travel time for this pick in seconds.
* For example, if this is 7, then it took 7 seconds for the
* wave to travel from the source to the receiver.
* @throws std::runtime_error if the travel time was not set.
* @sa \c haveTravelTime()
*/
double getTravelTime() const;
/*!
* @brief Determines if the travel time was set set.
* @result True indicates that the travel time was set.
*/
bool haveTravelTime() const noexcept;
/*! @} */
/*! @brief Identifier
* @{
*/
/*!
* @brief This is used to give the waveform template an identifier.
* The identifier defines the network, station, and phase
* as well as the event identifier to which the phase was associated
* in the catalog.
* @param[in] id The waveform identifier.
*/
void setIdentifier(const std::pair<NetworkStationPhase, uint64_t> &id) noexcept;
/*!
* @brief Gets the waveform template identifier.
* @result The waveform identifier where result.first is the network,
* station, and phase while result.second is the event identifier.
* @throws std::runtime_error if the waveform identifier was not set.
* @sa \c haveIdentifier()
*/
std::pair<NetworkStationPhase, uint64_t> getIdentifier() const;
/*!
* @brief Determines whether or not the waveform identifier was set.
* @result True indicates that the waveform identifier was set.
*/
bool haveIdentifier() const noexcept;
/*! @} */
/*! @brief Magnitude
* @{
*/
/*!
* @brief Sets the event magnitude associated with this template.
* @param[in] magnitude The magnitude.
*/
void setMagnitude(double magnitude) noexcept;
/*!
* @brief Gets the magnitude associated with this template.
* @result The magnitude associated with this template.
* @throws std::runtime_error if the magnitude was not set.
* @sa \c haveMagnitude()
*/
double getMagnitude() const;
/*!
* @brief Determines whether or not the magnitude was set.
* @result True indicates that the magnitude was set.
*/
bool haveMagnitude() const noexcept;
/*! @} */
/*! @brief Polarity
* @{
*/
/*!
* @brief Sets the onset's polarity.
* @param[in] polarity The arrival's polarity.
*/
void setPolarity(MFLib::Polarity polarity) noexcept;
/*!
* @brief Gets the onset's polarity.
* @result The onset's polarity. By default this is unknown.
*/
MFLib::Polarity getPolarity() const noexcept;
/*! @} */
private:
class WaveformTemplateImpl;
std::unique_ptr<WaveformTemplateImpl> pImpl;
};
}
#endif
| 35.255396
| 84
| 0.605755
|
6510c23e2fa1df889de4f68f508c805421170861
| 1,402
|
rb
|
Ruby
|
lib/fog/openstack/requests/compute/list_volumes.rb
|
madebymany/fog
|
fedd31d89594e96f0617dfbd9cb819a014b45821
|
[
"Unlicense",
"MIT"
] | 2
|
2015-06-02T17:14:30.000Z
|
2015-11-05T01:29:06.000Z
|
lib/fog/openstack/requests/compute/list_volumes.rb
|
madebymany/fog
|
fedd31d89594e96f0617dfbd9cb819a014b45821
|
[
"Unlicense",
"MIT"
] | null | null | null |
lib/fog/openstack/requests/compute/list_volumes.rb
|
madebymany/fog
|
fedd31d89594e96f0617dfbd9cb819a014b45821
|
[
"Unlicense",
"MIT"
] | null | null | null |
module Fog
module Compute
class OpenStack
class Real
def list_volumes(detailed=true)
path = detailed ? 'os-volumes/detail' : 'os-volumes'
request(
:expects => 200,
:method => 'GET',
:path => path
)
end
end
class Mock
def list_volumes(detailed=true)
response = Excon::Response.new
response.status = 200
self.data[:volumes] ||= [
{ "status" => "available",
"displayDescription" => "",
"availabilityZone" => "nova",
"displayName" => "test 1",
"attachments" => [{}],
"volumeType" => nil,
"snapshotId" => Fog::Mock.random_numbers(2),
"size" => 1,
"id" => "6",
"createdAt" => Time.now },
{ "status" => "available",
"displayDescription" => "",
"availabilityZone" => "nova",
"displayName" => "test 2",
"attachments" => [{}],
"volumeType" => nil,
"snapshotId" => Fog::Mock.random_numbers(2),
"size" => 1,
"id" => "8",
"createdAt" => Time.now}
]
response.body = { 'volumes' => self.data[:volumes] }
response
end
end
end
end
end
| 26.961538
| 62
| 0.424394
|
a352138d4a2edc695c04ea6cee16e71c57ce305f
| 2,180
|
ts
|
TypeScript
|
packages/commons/interfaces/models/content/media/Media.ts
|
nicoanders/shopware-pwa
|
6b4ed692c5682e69ce039b8b585cd223955b2184
|
[
"MIT"
] | 163
|
2019-09-26T10:59:51.000Z
|
2020-12-12T09:58:06.000Z
|
packages/commons/interfaces/models/content/media/Media.ts
|
nicoanders/shopware-pwa
|
6b4ed692c5682e69ce039b8b585cd223955b2184
|
[
"MIT"
] | 1,242
|
2019-09-26T10:51:42.000Z
|
2020-12-14T20:53:56.000Z
|
packages/commons/interfaces/models/content/media/Media.ts
|
nicoanders/shopware-pwa
|
6b4ed692c5682e69ce039b8b585cd223955b2184
|
[
"MIT"
] | 55
|
2021-01-10T22:32:18.000Z
|
2022-03-26T18:09:12.000Z
|
import { MediaType } from "./MediaType";
import { MediaTranslation } from "./MediaTranslation";
import { Category } from "../category/Category";
import { ProductMedia } from "../product/ProductMedia";
import { MediaThumbnail } from "./MediaThumbnail";
import { MediaFolder } from "./MediaFolder";
import { PropertyGroupOption } from "../property/PropertyGroupOption";
import { MailTemplateMedia } from "../mail-template/MailTemplateMedia";
import { Tag } from "../../system/tag/Tag";
import { DocumentBaseConfig } from "../../checkout/document/DocumentBaseConfig";
import { ShippingMethod } from "../../checkout/shipping/ShippingMethod";
import { PaymentMethod } from "../../checkout/payment/PaymentMethod";
import { CmsBlock } from "../cms/CmsBlock";
import { Document } from "../../checkout/document/Document";
import { ProductManufacturer } from "../product/ProductManufacturer";
import { OrderLineItem } from "../../checkout/order/OrderLineItem";
import { CustomField } from "../../common/CustomField";
import { User } from "../../system/user/User";
/**
* @public
*/
export interface Media {
userId: string | null;
mimeType: string | null;
fileExtension: string | null;
fileSize: number | null;
title: string | null;
metaDataRaw: string | null;
metaData: [] | null;
mediaType: MediaType;
uploadedAt: Date | null;
alt: string | null;
url: string;
fileName: string;
user: User;
translations: MediaTranslation[] | null;
categories: Category[] | null;
productManufacturers: ProductManufacturer[] | null;
productMedia: ProductMedia | null;
avatarUser: User | null;
thumbnails: MediaThumbnail[] | null;
mediaFolderId: string | null;
mediaFolder: MediaFolder | null;
hasFile: boolean;
private: boolean;
propertyGroupOptions: PropertyGroupOption[] | null;
mailTemplateMedia: MailTemplateMedia[] | null;
customFields: CustomField[];
tags: Tag | null;
thumbnailsRo: string | null;
documentBaseConfigs: DocumentBaseConfig[] | null;
shippingMethods: ShippingMethod[] | null;
paymentMethods: PaymentMethod[] | null;
orderLineItems: OrderLineItem[] | null;
cmsBlocks: CmsBlock[] | null;
documents: Document[] | null;
}
| 36.949153
| 80
| 0.711927
|
7d739f7fba5efcee35e735ca7c2267dc2dc64d3b
| 1,931
|
rs
|
Rust
|
parse-macros/src/parse_type_item.rs
|
yvt/rust-parse-generics
|
48248a2de844772c0fd76cbaa24492e4dfc146af
|
[
"MIT"
] | 15
|
2016-04-30T08:52:29.000Z
|
2020-12-30T18:36:54.000Z
|
parse-macros/src/parse_type_item.rs
|
yvt/rust-parse-generics
|
48248a2de844772c0fd76cbaa24492e4dfc146af
|
[
"MIT"
] | 3
|
2016-07-30T09:57:32.000Z
|
2018-05-02T17:11:50.000Z
|
parse-macros/src/parse_type_item.rs
|
yvt/rust-parse-generics
|
48248a2de844772c0fd76cbaa24492e4dfc146af
|
[
"MIT"
] | 3
|
2017-04-05T16:51:50.000Z
|
2021-03-28T18:21:59.000Z
|
/*
Copyright ⓒ 2016 rust-custom-derive contributors.
Licensed under the MIT license (see LICENSE or <http://opensource.org
/licenses/MIT>) or the Apache License, Version 2.0 (see LICENSE of
<http://www.apache.org/licenses/LICENSE-2.0>), at your option. All
files in the project carrying such notice may not be copied, modified,
or distributed except according to those terms.
*/
#[doc(hidden)]
#[macro_export]
macro_rules! parse_type_item {
(
then $cb:ident!$cb_arg:tt,
$(#[$($attrs:tt)*])* pub type $name:ident $($tail:tt)*
) => {
parse_generics_shim! {
{ constr, params, ltimes, tnames },
then parse_type_item! {
@with_generics
(($cb!$cb_arg), [$(#[$($attrs)*])*], (pub), $name),
},
$($tail)*
}
};
(
then $cb:ident!$cb_arg:tt,
$(#[$($attrs:tt)*])* type $name:ident $($tail:tt)*
) => {
parse_generics_shim! {
{ constr, params, ltimes, tnames },
then parse_type_item! {
@with_generics
(($cb!$cb_arg), [$(#[$($attrs)*])*], (), $name),
},
$($tail)*
}
};
(
@with_generics
$prefix:tt,
$generics:tt,
$($tail:tt)*
) => {
parse_where_shim! {
{ preds }, then parse_type_item! {
@with_where
$prefix, $generics,
},
$($tail)*
}
};
(
@with_where
($cb:tt, $attrs:tt, $vis:tt, $name:ident),
$generics:tt,
$preds:tt,
= $t:ty;
) => {
parse_macros_util! {
@call $cb,
type {
attrs: $attrs,
vis: $vis,
name: $name,
generics: $generics,
where: $preds,
type: $t,
}
}
};
}
| 25.407895
| 70
| 0.449508
|
bc2cacbec3ea14cd83ca3ddb86c2ef24c0ce9107
| 2,537
|
lua
|
Lua
|
rayyy.lua
|
xVoid-xyz/Roblox-Scripts
|
7eb176fa654f2ea5fbc6bcccced1b15df7ed82c2
|
[
"BSD-3-Clause"
] | 70
|
2021-02-09T17:21:32.000Z
|
2022-03-28T12:41:42.000Z
|
rayyy.lua
|
xVoid-xyz/Roblox-Scripts
|
7eb176fa654f2ea5fbc6bcccced1b15df7ed82c2
|
[
"BSD-3-Clause"
] | 4
|
2021-08-19T22:05:58.000Z
|
2022-03-19T18:58:01.000Z
|
rayyy.lua
|
xVoid-xyz/Roblox-Scripts
|
7eb176fa654f2ea5fbc6bcccced1b15df7ed82c2
|
[
"BSD-3-Clause"
] | 325
|
2021-02-26T22:23:41.000Z
|
2022-03-31T19:36:12.000Z
|
me = game.Players.xSoulStealerx
if script.Parent.className ~= "HopperBin" then
h = Instance.new("HopperBin")
h.Parent = me.Backpack
h.Name = "RayCast"
script.Parent = h
end
bin = script.Parent
function GetPhysicsChildren(path)
local objects = {}
for _, children in pairs(path:GetChildren()) do
if children.className == "Part" or children.className == "Seat" or children.className == "WedgePart" or children.className == "TrussPart" or children.className == "VehicleSeat" or children.className == "SkateboardPlatform" then
table.insert(objects, children)
end
if #children:GetChildren() > 0 then
local objects2 = GetPhysicsChildren(children)
for i = 1, #objects2 do
table.insert(objects, objects2[i])
end
end
end
return objects
end
function RayCast(pos1, pos2, maxDistance)
local pos0 = pos1
local objects = GetPhysicsChildren(game:GetService("Workspace"))
for distance = 1, maxDistance, 1 do
pos0 = (CFrame.new(pos1, pos2) * CFrame.new(0, 0, -distance)).p
for _, children in pairs(objects) do
if children.Name ~= "Bullet Trail" then
--if (children.CanCollide and children.Transparency > 0) or (game:GetService("Players"):getPlayerFromCharacter(children.Parent)) then
local pos3 = children.CFrame:pointToObjectSpace(pos0)
if pos3.x > -(children.Size.x / 2) and pos3.x < (children.Size.x / 2) and pos3.y > -(children.Size.y / 2) and pos3.y < (children.Size.y / 2) and pos3.z > -(children.Size.z / 2) and pos3.z < (children.Size.z / 2) then
return pos0, children
end
end
end
end
return pos0, nil
end
function fire(startPoint, endPoint)
if startPoint == nil then return end
if endPoint == nil then return end
local pos, hit = RayCast(startPoint, endPoint, 60)
local tr = Instance.new("Part")
tr.Name = "Bullet Trail"
tr.Anchored = true
tr.formFactor = 0
tr.TopSurface = 0
tr.BottomSurface = 0
tr.Size = Vector3.new(1,1,1)
tr.BrickColor = BrickColor.new("Bright yellow")
tr.CanCollide = false
tr.CFrame = CFrame.new((startPoint + pos)/2, pos)
tr.Parent = workspace
local mesh = Instance.new("BlockMesh",tr)
mesh.Scale = Vector3.new(0.1,0.1,(startPoint - pos).magnitude)
if hit ~= nil then
local hum = hit.Parent:findFirstChild("Humanoid")
if hum ~= nil then
hum.Health = hum.Health - 13
end
end
coroutine.resume(coroutine.create(function()
for i=0,1,0.15 do
wait()
tr.Transparency = i
end
tr:remove()
end))
end
function select(mouse)
mouse.Button1Down:connect(function()
fire(me.Character.Torso.Position, mouse.Hit.p)
end)
end
bin.Selected:connect(select)
| 28.829545
| 228
| 0.717383
|