identifier
stringlengths 42
383
| collection
stringclasses 1
value | open_type
stringclasses 1
value | license
stringlengths 0
1.81k
| date
float64 1.99k
2.02k
⌀ | title
stringlengths 0
100
| creator
stringlengths 1
39
| language
stringclasses 157
values | language_type
stringclasses 2
values | word_count
int64 1
20k
| token_count
int64 4
1.32M
| text
stringlengths 5
1.53M
| __index_level_0__
int64 0
57.5k
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|
https://github.com/werminghoff/Provenance/blob/master/Cores/Gambatte/GB/common/resample/src/chainresampler.cpp
|
Github Open Source
|
Open Source
|
BSD-3-Clause
| 2,022
|
Provenance
|
werminghoff
|
C++
|
Code
| 936
| 2,769
|
/***************************************************************************
* Copyright (C) 2008 by Sindre Aamås *
* sinamas@users.sourceforge.net *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License version 2 as *
* published by the Free Software Foundation. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License version 2 for more details. *
* *
* You should have received a copy of the GNU General Public License *
* version 2 along with this program; if not, write to the *
* Free Software Foundation, Inc., *
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
***************************************************************************/
#include "chainresampler.h"
#include <cassert>
#include <cmath>
static float get1ChainCost(float ratio, float finalRollOffLen) {
return ratio / finalRollOffLen;
}
static float get2ChainMidRatio(float ratio, float finalRollOffLen, float midRollOffStartPlusEnd) {
return 0.5f * ( std::sqrt(ratio * midRollOffStartPlusEnd * finalRollOffLen)
+ midRollOffStartPlusEnd);
}
static float get2ChainCost(float ratio, float finalRollOffLen, float midRatio,
float midRollOffStartPlusEnd)
{
float midRollOffLen = midRatio * 2 - midRollOffStartPlusEnd;
return midRatio * ratio / midRollOffLen
+ get1ChainCost(midRatio, finalRollOffLen);
}
static float get3ChainRatio2(float ratio1,
float finalRollOffLen,
float midRollOffStartPlusEnd) {
return get2ChainMidRatio(ratio1, finalRollOffLen, midRollOffStartPlusEnd);
}
static float get3ChainRatio1(float ratio1, float const finalRollOffLen, float const ratio,
float const midRollOffStartPlusEnd)
{
for (int n = 8; n--;) {
float ratio2 = get3ChainRatio2(ratio1, finalRollOffLen, midRollOffStartPlusEnd);
ratio1 = ( std::sqrt(ratio * midRollOffStartPlusEnd * (2 - midRollOffStartPlusEnd / ratio2))
+ midRollOffStartPlusEnd) * 0.5f;
}
return ratio1;
}
static float get3ChainCost(float ratio, float finalRollOffLen,
float ratio1, float ratio2, float midRollOffStartPlusEnd)
{
float firstRollOffLen = ratio1 * 2 - midRollOffStartPlusEnd;
return ratio1 * ratio / firstRollOffLen
+ get2ChainCost(ratio1, finalRollOffLen, ratio2, midRollOffStartPlusEnd);
}
ChainResampler::ChainResampler(long inRate, long outRate, std::size_t periodSize)
: Resampler(inRate, outRate)
, bigSinc_(0)
, buffer2_(0)
, periodSize_(periodSize)
, maxOut_(0)
{
}
void ChainResampler::downinitAddSincResamplers(double ratio,
float const outRate,
CreateSinc const createBigSinc,
CreateSinc const createSmallSinc,
double gain)
{
// For high outRate: Start roll-off at 36 kHz continue until outRate Hz,
// then wrap around back down to 40 kHz.
float const outPeriod = 1.0f / outRate;
float const finalRollOffLen =
std::max((outRate - 36000.0f + outRate - 40000.0f) * outPeriod,
0.2f);
{
float const midRollOffStart = std::min(36000.0f * outPeriod, 1.0f);
float const midRollOffEnd = std::min(40000.0f * outPeriod, 1.0f); // after wrap at folding freq.
float const midRollOffStartPlusEnd = midRollOffStart + midRollOffEnd;
float const ideal2ChainMidRatio = get2ChainMidRatio(ratio, finalRollOffLen,
midRollOffStartPlusEnd);
int div_2c = int(ratio * small_sinc_mul / ideal2ChainMidRatio + 0.5f);
double ratio_2c = ratio * small_sinc_mul / div_2c;
float cost_2c = get2ChainCost(ratio, finalRollOffLen, ratio_2c, midRollOffStartPlusEnd);
if (cost_2c < get1ChainCost(ratio, finalRollOffLen)) {
float const ideal3ChainRatio1 = get3ChainRatio1(ratio_2c, finalRollOffLen,
ratio, midRollOffStartPlusEnd);
int const div1_3c = int(ratio * small_sinc_mul / ideal3ChainRatio1 + 0.5f);
double const ratio1_3c = ratio * small_sinc_mul / div1_3c;
float const ideal3ChainRatio2 = get3ChainRatio2(ratio1_3c, finalRollOffLen,
midRollOffStartPlusEnd);
int const div2_3c = int(ratio1_3c * small_sinc_mul / ideal3ChainRatio2 + 0.5f);
double const ratio2_3c = ratio1_3c * small_sinc_mul / div2_3c;
if (get3ChainCost(ratio, finalRollOffLen, ratio1_3c,
ratio2_3c, midRollOffStartPlusEnd) < cost_2c) {
list_.push_back(createSmallSinc(div1_3c,
0.5f * midRollOffStart / ratio,
(ratio1_3c - 0.5f * midRollOffStartPlusEnd) / ratio,
gain));
ratio = ratio1_3c;
div_2c = div2_3c;
ratio_2c = ratio2_3c;
gain = 1.0;
}
list_.push_back(createSmallSinc(div_2c,
0.5f * midRollOffStart / ratio,
(ratio_2c - 0.5f * midRollOffStartPlusEnd) / ratio,
gain));
ratio = ratio_2c;
gain = 1.0;
}
}
float rollOffStart = 0.5f * (1.0f
+ std::max((outRate - 40000.0f) * outPeriod, 0.0f)
- finalRollOffLen) / ratio;
bigSinc_ = createBigSinc(static_cast<int>(big_sinc_mul * ratio + 0.5),
rollOffStart,
0.5f * finalRollOffLen / ratio,
gain);
list_.push_back(bigSinc_);
}
void ChainResampler::upinit(long const inRate,
long const outRate,
CreateSinc const createSinc) {
double ratio = static_cast<double>(outRate) / inRate;
// Spectral images above 20 kHz assumed inaudible
// this post-polyphase zero stuffing causes some power loss though.
{
int const div = outRate / std::max(inRate, 40000l);
if (div >= 2) {
list_.push_front(new Upsampler<channels>(div));
ratio /= div;
}
}
float const rollOffLen = std::max((inRate - 36000.0f) / inRate, 0.2f);
bigSinc_ = createSinc(static_cast<int>(big_sinc_mul / ratio + 0.5),
0.5f * (1 - rollOffLen),
0.5f * rollOffLen,
1.0);
list_.push_front(bigSinc_); // note: inserted at the front
reallocateBuffer();
}
void ChainResampler::reallocateBuffer() {
std::size_t bufSize[2] = { 0, 0 };
std::size_t inSize = periodSize_;
int i = -1;
for (List::iterator it = list_.begin(); it != list_.end(); ++it) {
inSize = (inSize * (*it)->mul() - 1) / (*it)->div() + 1;
++i;
if (inSize > bufSize[i & 1])
bufSize[i & 1] = inSize;
}
if (inSize >= bufSize[i & 1])
bufSize[i & 1] = 0;
if (buffer_.size() < (bufSize[0] + bufSize[1]) * channels)
buffer_.reset((bufSize[0] + bufSize[1]) * channels);
buffer2_ = bufSize[1] ? buffer_ + bufSize[0] * channels : 0;
maxOut_ = inSize;
}
void ChainResampler::adjustRate(long const inRate, long const outRate) {
unsigned long mul, div;
exactRatio(mul, div);
double newDiv = double( inRate) * mul
/ (double(outRate) * (div / bigSinc_->div()));
bigSinc_->adjustDiv(int(newDiv + 0.5));
reallocateBuffer();
setRate(inRate, outRate);
}
void ChainResampler::exactRatio(unsigned long &mul, unsigned long &div) const {
mul = 1;
div = 1;
for (List::const_iterator it = list_.begin(); it != list_.end(); ++it) {
mul *= (*it)->mul();
div *= (*it)->div();
}
}
std::size_t ChainResampler::resample(short *const out, short const *const in, std::size_t inlen) {
assert(inlen <= periodSize_);
short *const buf = buffer_ != buffer2_ ? buffer_ : out;
short *const buf2 = buffer2_ ? buffer2_ : out;
short const *inbuf = in;
short *outbuf = 0;
for (List::iterator it = list_.begin(); it != list_.end(); ++it) {
outbuf = ++List::iterator(it) == list_.end()
? out
: (inbuf == buf ? buf2 : buf);
inlen = (*it)->resample(outbuf, inbuf, inlen);
inbuf = outbuf;
}
return inlen;
}
ChainResampler::~ChainResampler() {
std::for_each(list_.begin(), list_.end(), defined_delete<SubResampler>);
}
| 3,942
|
https://github.com/austkao/VOOGASalad/blob/master/src/main/java/com.yeet.messenger/src/messenger/external/MenuStartEvent.java
|
Github Open Source
|
Open Source
|
MIT
| null |
VOOGASalad
|
austkao
|
Java
|
Code
| 19
| 42
|
package messenger.external;
public class MenuStartEvent extends Event {
@Override
public String getName() {
return "Menu Start Event";
}
}
| 29,977
|
https://github.com/mandy8055/dataStructuresAndAlgoJava/blob/master/src/coding_bat_problems/recursion1/Problem22.java
|
Github Open Source
|
Open Source
|
MIT
| 2,021
|
dataStructuresAndAlgoJava
|
mandy8055
|
Java
|
Code
| 46
| 150
|
package coding_bat_problems.recursion1;
// problem link: https://codingbat.com/prob/p161124
public class Problem22 {
public int countAbc(String str) {
// base case
if(str.length() <= 2)return 0;
// Main case
if(str.startsWith("abc") || str.startsWith("aba")){
String ros = str.substring(2);
return 1 + countAbc(ros);
}else{
String ros = str.substring(1);
return countAbc(ros);
}
}
}
| 37,760
|
https://github.com/xWriteCoder/Bozkurt/blob/master/src/main/java/tr/bozkurt/lang/LanguageManager.java
|
Github Open Source
|
Open Source
|
MIT
| 2,019
|
Bozkurt
|
xWriteCoder
|
Java
|
Code
| 172
| 639
|
package tr.bozkurt.lang;
import tr.bozkurt.Logger;
import tr.bozkurt.util.Utils;
import java.io.IOException;
import java.io.InputStream;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
public final class LanguageManager{
public static final String FALLBACK_LANGUAGE = "eng";
private final String langName;
private final ConcurrentMap<String, String> lang;
private ConcurrentMap<String, String> fallbackLang = new ConcurrentHashMap<>();
private final Translator translator;
public LanguageManager(String lang){
this(lang, FALLBACK_LANGUAGE);
}
public LanguageManager(String lang, String fallback){
langName = lang.toLowerCase();
boolean useFallback = !lang.equals(fallback);
this.lang = loadLang(Utils.loadFromStream("languages/bedrock/" + langName + ".ini"));
if(useFallback)
fallbackLang = loadLang(Utils.loadFromStream("languages/bedrock/" + fallback + ".ini"));
if(fallbackLang == null) fallbackLang = this.lang;
translator = new Translator(fallback, lang);
translator.start();
}
private ConcurrentMap<String, String> loadLang(InputStream stream){
try{
String content = Utils.readFile(stream);
ConcurrentMap<String, String> d = new ConcurrentHashMap<>();
for(String line : content.split("\n")){
line = line.trim();
if(line.isEmpty() || line.charAt(0) == '#'){
continue;
}
String[] t = line.split("=");
if(t.length < 2){
continue;
}
String key = t[0];
StringBuilder value = new StringBuilder();
for(int i = 1; i < t.length - 1; i++){
value.append(t[i]).append("=");
}
value.append(t[t.length - 1]);
if(value.length() == 0){
continue;
}
d.put(key, value.toString());
}
return d;
}catch(IOException e){
Logger.logException(e);
return null;
}
}
}
| 12,366
|
https://github.com/BoldijarPaul/ubb/blob/master/app/src/test/java/com/ubb/app/XmlUnitTests.java
|
Github Open Source
|
Open Source
|
Apache-2.0
| null |
ubb
|
BoldijarPaul
|
Java
|
Code
| 200
| 1,065
|
package com.ubb.app;
import com.shirwa.simplistic_rss.RssItem;
import com.ubb.app.xml.XmlRssParser;
import org.junit.Test;
import java.util.List;
import static org.junit.Assert.*;
/**
* To work on unit tests, switch the Test Artifact in the Build Variants view.
*/
public class XmlUnitTests {
@Test
public void addition_isCorrect() throws Exception {
assertEquals(4, 2 + 2);
}
String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
"<rss xmlns:sy=\"http://purl.org/rss/1.0/modules/syndication/\" xmlns:slash=\"http://purl.org/rss/1.0/modules/slash/\">\n" +
" <channel>\n" +
" <item>\n" +
" <title>title</title>\n" +
" <link><![CDATA[url]]></link>\n" +
" <comments>comments</comments>\n" +
" <pubDate>pubDate</pubDate>\n" +
" <dc:creator></dc:creator>\n" +
" <category>category</category>\n" +
" <guid isPermaLink=\"false\">http://www.cs.ubbcluj.ro/?p=22185</guid>\n" +
" <description>des</description>\n" +
" <content:encoded>content:encoded</content:encoded>\n" +
" <wfw:commentRss></wfw:commentRss>\n" +
" <slash:comments>0</slash:comments>\n" +
" </item>\n" +
" <item>\n" +
" <title>Deschiderea festivă a Programului de Conversie Profesională Matematică</title>\n" +
" <link>http://www.cs.ubbcluj.ro/deschiderea-festiva-a-programului-de-conversie-profesionala-matematica/</link>\n" +
" <comments>http://www.cs.ubbcluj.ro/deschiderea-festiva-a-programului-de-conversie-profesionala-matematica/#comments</comments>\n" +
" <pubDate>Thu, 01 Oct 2015 15:00:27 +0000</pubDate>\n" +
" <dc:creator></dc:creator>\n" +
" <category><![CDATA[Anunţuri burse Erasmus & CEEPUS]]></category>\n" +
" <guid isPermaLink=\"false\">http://www.cs.ubbcluj.ro/?p=22022</guid>\n" +
" <description></description>\n" +
" <content:encoded></content:encoded>\n" +
" <wfw:commentRss>http://www.cs.ubbcluj.ro/deschiderea-festiva-a-programului-de-conversie-profesionala-matematica/feed/</wfw:commentRss>\n" +
" <slash:comments>0</slash:comments>\n" +
" </item>\n" +
" </channel>\n" +
" </rss>";
@Test
public void xmlParseLengthWorks() {
List<RssItem> items = XmlRssParser.getRssItemsFromXml(xml);
assertEquals(items.size(), 2);
}
@Test
public void xmlTestVariables() {
RssItem item = XmlRssParser.getRssItemsFromXml(xml).get(0);
assertEquals(item.getTitle(), "title");
assertEquals(item.getDescription(), "des");
assertEquals("url", item.getLink());
RssItem item2 = XmlRssParser.getRssItemsFromXml(xml).get(1);
assertEquals("Anunţuri burse Erasmus & CEEPUS", item2.getCategory());
}
}
| 43,530
|
https://github.com/dkiltyhc/appian-locust-hc-fork/blob/master/tests/test_ui_reconciler.py
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,021
|
appian-locust-hc-fork
|
dkiltyhc
|
Python
|
Code
| 185
| 794
|
from appian_locust._ui_reconciler import UiReconciler
import unittest
class TestUiReconciler(unittest.TestCase):
def setUp(self) -> None:
self.reconciler: UiReconciler = UiReconciler()
def test_reconcile_new_state_replace(self) -> None:
# Given
old_state = {"ui": {'#t': 'abc'}}
new_state = {"ui": {'#t': '123'}}
# When
reconciled_state = self.reconciler.reconcile_ui(old_state, new_state)
# Then
self.assertEqual(reconciled_state, new_state)
def test_reconcile_reconcile_one_level_deep_replace(self) -> None:
# Given
old_component = {'_cId': '12345', 'value': "This is what it used to be"}
new_component = {'_cId': '12345', 'value': "This is what it is now"}
old_state = {'context': 'abc', "ui": {'#t': 'abc', 'contents': [old_component]}}
new_state = {'context': '123', "ui": {'#t': UiReconciler.COMPONENT_DELTA_TYPE, 'modifiedComponents': [new_component]}}
# When
reconciled_state = self.reconciler.reconcile_ui(old_state, new_state)
# Then
self.assertNotEqual(reconciled_state, new_state)
self.assertEqual('123', reconciled_state['context'])
self.assertEqual(new_component, reconciled_state['ui']['contents'][0])
def test_reconcile_reconcile_two_levels_deep_replace(self) -> None:
# Given
old_component = {'_cId': '12345', 'value': "This is what it used to be"}
old_unchanged_component = {'_cId': '55555', 'value': "This is what it used to be"}
new_component = {'_cId': '12345', 'value': "This is what it is now"}
old_state = {'context': 'abc', "ui": {'#t': 'abc', 'contents': [{'contents': [old_component, old_unchanged_component]}]}}
new_state = {'context': '123', "ui": {'#t': UiReconciler.COMPONENT_DELTA_TYPE, 'modifiedComponents': [new_component]}}
# When
reconciled_state = self.reconciler.reconcile_ui(old_state, new_state)
# Then
self.assertNotEqual(reconciled_state, new_state)
self.assertEqual('123', reconciled_state['context'])
self.assertEqual(new_component, reconciled_state['ui']['contents'][0]['contents'][0])
self.assertEqual(old_unchanged_component, reconciled_state['ui']['contents'][0]['contents'][1])
if __name__ == '__main__':
unittest.main()
| 45,597
|
https://github.com/chrsjwilliams/DreamTeam/blob/master/DreamTeam/Assets/Scripts/Utils/GameEvent.cs
|
Github Open Source
|
Open Source
|
Unlicense
| 2,017
|
DreamTeam
|
chrsjwilliams
|
C#
|
Code
| 106
| 339
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityStandardAssets.Characters.FirstPerson;
namespace GameEvents
{
public abstract class GameEvent
{
public delegate void Handler(GameEvent e);
}
public class TopicSelectedEvent : GameEvent
{
public readonly HARTOTuningv3Script hartoTopic;
public readonly FirstPersonController player;
public TopicSelectedEvent(HARTOTuningv3Script hartoTopic, FirstPersonController player)
{
this.hartoTopic = hartoTopic;
this.player = player;
}
}
public class ToggleHARTOEvent : GameEvent
{
public ToggleHARTOEvent ()
{
}
}
public class BeginDialogueEvent : GameEvent
{
public BeginDialogueEvent ()
{
}
}
public class EndDialogueEvent : GameEvent
{
public EndDialogueEvent ()
{
}
}
public class EmotionSelectedEvent : GameEvent
{
public readonly HARTOTuningv3Script hartoEmotion;
public EmotionSelectedEvent(HARTOTuningv3Script hartoEmotion)
{
this.hartoEmotion = hartoEmotion;
}
}
}
| 37,875
|
https://github.com/vikingz9065/vikingzgit/blob/master/myci.sql
|
Github Open Source
|
Open Source
|
MIT
| null |
vikingzgit
|
vikingz9065
|
SQL
|
Code
| 58
| 170
|
CREATE TABLE `ci_sessions`(
`id` varchar(128) NOT NULL,
`ip_address` varchar(45) NOT NULL,
`timestamp` int(10) unsigned NOT NULL DEFAULT '0',
`data` blob NOT NULL,
PRIMARY KEY(`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE IF NOT EXISTS `ci_sessions` (
`id` varchar(128) NOT NULL,
`ip_address` varchar(45) NOT NULL,
`timestamp` int(10) unsigned DEFAULT 0 NOT NULL,
`data` blob NOT NULL,
KEY `ci_sessions_timestamp` (`timestamp`)
);
| 49,843
|
https://github.com/gonzodepedro/silkopter/blob/master/q/src/video/Dynamic_Image.cpp
|
Github Open Source
|
Open Source
|
BSD-3-Clause
| 2,019
|
silkopter
|
gonzodepedro
|
C++
|
Code
| 3,958
| 12,271
|
#include "QStdAfx.h"
#include "video/Dynamic_Image.h"
using namespace q;
using namespace video;
Dynamic_Image::Dynamic_Image(Path const& path)
: Resource(path)
, m_format(Format::RGBA_8)
, m_owns_data(true)
, m_data_ptr(0)
, m_pitch(0)
{
}
void Dynamic_Image::allocate(Format format, math::vec2u32 const& size, uint8_t const* data)
{
deallocate();
QASSERT(size.x > 0 && size.y > 0);
m_size = math::max(size, math::vec2u32(1, 1));
m_format = format;
size_t data_size = get_data_size();
m_data.resize(data_size);
m_data_ptr = m_data.data();
m_owns_data = true;
m_pitch = get_line_size();
if (data)
{
memcpy(m_data_ptr, data, data_size);
}
else
{
memset(m_data_ptr, 0, data_size);
}
}
void Dynamic_Image::adopt(Format format, math::vec2u32 const& size, size_t pitch, uint8_t* data)
{
QASSERT(data);
QASSERT(pitch > 0 && size.x > 0 && size.y > 0);
deallocate();
m_size = math::max(size, math::vec2u32(1, 1));
m_format = format;
m_data_ptr = data;
m_owns_data = false;
m_pitch = pitch;
}
Dynamic_Image::~Dynamic_Image()
{
deallocate();
}
void Dynamic_Image::deallocate()
{
std::vector<uint8_t> t;
std::swap(t, m_data);
m_data_ptr = 0;
}
Dynamic_Image_uptr Dynamic_Image::clone() const
{
auto mi = std::unique_ptr<Dynamic_Image>(new Dynamic_Image);
if (is_compact())
{
mi->allocate(get_format(), get_size(), get_data());
}
else
{
mi->allocate(get_format(), get_size(), nullptr);
for (uint32_t i = 0; i < m_size.y; i++)
{
memcpy(mi->get_mutable_line_data(i), get_line_data(i), get_line_size());
}
}
return mi;
}
void Dynamic_Image::save_as_tga(data::Sink& sink) const
{
auto const* src = this;
Dynamic_Image_uptr tempImg;
if (m_format != Format::RGBA_8 && m_format != Format::RGB_8)
{
tempImg = clone();
tempImg->convert_to_rgba8();
src = tempImg.get();
}
save_as_tga(sink, src->m_format == Format::RGBA_8, src->m_size, src->m_pitch, src->m_data_ptr);
}
void Dynamic_Image::save_as_tga(data::Sink& sink, bool has_alpha, math::vec2u32 const& size, size_t pitch, uint8_t const* data)
{
QASSERT(data);
QASSERT(size.x > 0 && size.y > 0);
QASSERT(size.x < 65536 && size.y < 65536);
sink << (uint8_t)0; //idlength
sink << (uint8_t)0; //colourmaptype
sink << (uint8_t)2; //datatypecode
sink << (uint16_t)0; //colourmaporigin
sink << (uint16_t)0; //colourmaplength
sink << (uint8_t)0; //colourmapdepth
sink << (uint16_t)0; //x_origin
sink << (uint16_t)0; //y_origin
sink << (uint16_t)size.x; //width
sink << (uint16_t)size.y; //height
sink << (uint8_t)(has_alpha ? 32 : 24); //bitsperpixel
sink << (uint8_t)0; //descriptor
size_t line_size = size.x * (has_alpha ? 4 : 3);
boost::auto_buffer<uint8_t, boost::store_n_bytes<8192>> temp;
temp.uninitialized_resize(line_size);
if (has_alpha)
{
for (int i = size.y - 1; i >= 0; i--)
{
uint32_t const* src = (uint32_t const*)(data + pitch * i);
uint32_t* dst = (uint32_t*)temp.data();
for (uint32_t x = 0; x < size.x; x++)
{
uint32_t c = *src++;
c = math::color::swap_rb(c);
*dst++ = c;
}
sink.write(temp.data(), line_size);
}
}
else
{
for (int i = size.y - 1; i >= 0; i--)
{
uint8_t const* src = data + pitch * i;
uint8_t* dst = temp.data();
for (uint32_t x = 0; x < size.x; x++)
{
dst[2] = *src++;
dst[1] = *src++;
dst[0] = *src++;
dst += 3;
}
sink.write(temp.data(), line_size);
}
}
}
void Dynamic_Image::unload()
{
deallocate();
}
bool Dynamic_Image::is_valid() const
{
return m_data_ptr != nullptr;
}
Dynamic_Image& Dynamic_Image::clear()
{
if (is_compact())
{
memset(m_data_ptr, 0, get_data_size());
}
else
{
size_t line_size = get_line_size();
uint8_t* data = m_data_ptr;
for (size_t i = 0; i < m_size.y; i++)
{
memset(data, 0, line_size);
data += m_pitch;
}
}
return *this;
}
static uint32_t mixColorsRgba8(uint32_t a, uint32_t b, uint32_t c, uint32_t d)
{
uint32_t ab = 0;
{
uint32_t al = (a & 0x00ff00ff);
uint32_t ah = (a & 0xff00ff00) >> 8;
uint32_t bl = (b & 0x00ff00ff);
uint32_t bh = (b & 0xff00ff00) >> 8;
uint32_t ml = ((al << 7) + (bl << 7));
uint32_t mh = ((ah << 7) + (bh << 7));
ab = (mh & 0xff00ff00) | ((ml & 0xff00ff00) >> 8);
}
uint32_t cd = 0;
{
uint32_t al = (c & 0x00ff00ff);
uint32_t ah = (c & 0xff00ff00) >> 8;
uint32_t bl = (d & 0x00ff00ff);
uint32_t bh = (d & 0xff00ff00) >> 8;
uint32_t ml = ((al << 7) + (bl << 7));
uint32_t mh = ((ah << 7) + (bh << 7));
cd = (mh & 0xff00ff00) | ((ml & 0xff00ff00) >> 8);
}
uint32_t al = (ab & 0x00ff00ff);
uint32_t ah = (ab & 0xff00ff00) >> 8;
uint32_t bl = (cd & 0x00ff00ff);
uint32_t bh = (cd & 0xff00ff00) >> 8;
uint32_t ml = ((al << 7) + (bl << 7));
uint32_t mh = ((ah << 7) + (bh << 7));
uint32_t result = (mh & 0xff00ff00) | ((ml & 0xff00ff00) >> 8);
return result;
}
static uint8_t mixColorsA8(uint8_t a, uint8_t b, uint8_t c, uint8_t d)
{
uint8_t ab = (a + b) >> 1;
uint8_t cd = (c + d) >> 1;
uint8_t result = (ab + cd) >> 1;
return result;
}
static uint16_t mixColorsAI8(uint16_t a, uint16_t b, uint16_t c, uint16_t d)
{
uint32_t ax = (a & 0xff) | ((a & 0xff00) << 8);
uint32_t bx = (b & 0xff) | ((b & 0xff00) << 8);
uint32_t abx = ((ax + bx) >> 1) & 0x00ff00ff;
uint32_t cx = (c & 0xff) | ((c & 0xff00) << 8);
uint32_t dx = (d & 0xff) | ((d & 0xff00) << 8);
uint32_t cdx = ((cx + dx) >> 1) & 0x00ff00ff;
uint32_t abcdx = ((abx + cdx) >> 1) & 0x00ff00ff;
return static_cast<uint16_t>(abcdx | (abcdx >> 8));
}
static uint16_t mixColorsRgb565(uint16_t a, uint16_t b, uint16_t c, uint16_t d)
{
uint32_t ax = (a & 0xf81f) | ((a & 0x07e0) << 16);
uint32_t bx = (b & 0xf81f) | ((b & 0x07e0) << 16);
uint32_t abx = ((ax + bx) >> 1) & 0x07e0f81f;
uint32_t cx = (c & 0xf81f) | ((c & 0x07e0) << 16);
uint32_t dx = (d & 0xf81f) | ((d & 0x07e0) << 16);
uint32_t cdx = ((cx + dx) >> 1) & 0x07e0f81f;
uint32_t abcdx = ((abx + cdx) >> 1) & 0x07e0f81f;
return static_cast<uint16_t>(abcdx | (abcdx >> 16));
}
static uint16_t mixColorsRgba4(uint16_t a, uint16_t b, uint16_t c, uint16_t d)
{
uint32_t ax = (a & 0x0f0f) | ((a & 0xf0f0) << 12);
uint32_t bx = (b & 0x0f0f) | ((b & 0xf0f0) << 12);
uint32_t abx = ((ax + bx) >> 1) & 0x0f0f0f0f;
uint32_t cx = (c & 0x0f0f) | ((c & 0xf0f0) << 12);
uint32_t dx = (d & 0x0f0f) | ((d & 0xf0f0) << 12);
uint32_t cdx = ((cx + dx) >> 1) & 0x0f0f0f0f;
uint32_t abcdx = ((abx + cdx) >> 1) & 0x0f0f0f0f;
return static_cast<uint16_t>(abcdx | (abcdx >> 12));
}
static uint16_t mixColorsRgba5551(uint16_t a, uint16_t b, uint16_t c, uint16_t d)
{
uint32_t ax = (a & 0x7c1f) | ((a & 0x8e30) << 15);
uint32_t bx = (b & 0x7c1f) | ((b & 0x8e30) << 15);
uint32_t abx = ((ax + bx) >> 1) & 0x41f07c1f;
uint32_t cx = (c & 0x7c1f) | ((c & 0x8e30) << 15);
uint32_t dx = (d & 0x7c1f) | ((d & 0x8e30) << 15);
uint32_t cdx = ((cx + dx) >> 1) & 0x41f07c1f;
uint32_t abcdx = ((abx + cdx) >> 1) & 0x41f07c1f;
return static_cast<uint16_t>(abcdx | (abcdx >> 15));
}
static math::vec4f mixColorsRgba32(math::vec4f const& a, math::vec4f const& b, math::vec4f const& c, math::vec4f const& d)
{
return (a + b + c + d) * 0.25f;
}
static math::vec3f mixColorsRgb32(math::vec3f const& a, math::vec3f const& b, math::vec3f const& c, math::vec3f const& d)
{
return (a + b + c + d) * 0.25f;
}
Dynamic_Image& Dynamic_Image::downscale(bool smooth)
{
if (m_size == math::vec2u32(1, 1) || !is_compact())
{
return *this;
}
math::vec2u32 newSize(math::max(m_size.x >> 1, 1u), math::max(m_size.y >> 1, 1u));
auto img = std::make_shared<Dynamic_Image>();
img->allocate(m_format, newSize, nullptr);
uint32_t factorX = m_size.x / newSize.x;
uint32_t factorY = (m_size.y / newSize.y) * m_size.x;
uint32_t deltaX = factorX - 1;
uint32_t deltaY = factorY - m_size.x;
//uint32_t count = newSize.x * newSize.y;
if (smooth)
{
switch (m_format)
{
case Format::I_32:
{
float* dst = (float*)img->m_data_ptr;
for (uint32_t y = 0; y < newSize.y; y++)
{
float const* src0 = (float const*)m_data_ptr + y * factorY;
float const* src1 = src0 + deltaX;
float const* src2 = src0 + deltaY;
float const* src3 = src1 + deltaY;
for (uint32_t i = 0; i < newSize.x; i++, src0 += factorX, src1 += factorX, src2 += factorX, src3 += factorX, dst++)
{
float a = *src0, b = *src1, c = *src2, d = *src3;
*dst = (a + b + c + d) * 0.25f;
}
}
}
break;
case Format::RGBA_8:
{
uint32_t* dst = (uint32_t*)img->m_data_ptr;
for (uint32_t y = 0; y < newSize.y; y++)
{
uint32_t const* src0 = (uint32_t const*)m_data_ptr + y * factorY;
uint32_t const* src1 = src0 + deltaX;
uint32_t const* src2 = src0 + deltaY;
uint32_t const* src3 = src1 + deltaY;
for (uint32_t i = 0; i < newSize.x; i++, src0 += factorX, src1 += factorX, src2 += factorX, src3 += factorX, dst++)
{
uint32_t a = *src0, b = *src1, c = *src2, d = *src3;
*dst = mixColorsRgba8(a, b, c, d);
}
}
}
break;
case Format::RGBA_32:
{
QASSERT(sizeof(math::vec4f) == 16);
auto* dst = (math::vec4f*)img->m_data_ptr;
for (uint32_t y = 0; y < newSize.y; y++)
{
auto const* src0 = (math::vec4f const*)m_data_ptr + y * factorY;
auto const* src1 = src0 + deltaX;
auto const* src2 = src0 + deltaY;
auto const* src3 = src1 + deltaY;
for (uint32_t i = 0; i < newSize.x; i++, src0 += factorX, src1 += factorX, src2 += factorX, src3 += factorX, dst++)
{
auto a = *src0, b = *src1, c = *src2, d = *src3;
*dst = mixColorsRgba32(a, b, c, d);
}
}
}
break;
case Format::RGB_32:
{
auto* dst = (math::vec3f*)img->m_data_ptr;
for (uint32_t y = 0; y < newSize.y; y++)
{
auto const* src0 = (math::vec3f const*)m_data_ptr + y * factorY;
auto const* src1 = src0 + deltaX;
auto const* src2 = src0 + deltaY;
auto const* src3 = src1 + deltaY;
for (uint32_t i = 0; i < newSize.x; i++, src0 += factorX, src1 += factorX, src2 += factorX, src3 += factorX, dst++)
{
//do the math in vec3 to get some simd love
math::vec3f a(*src0), b(*src1), c(*src2), d(*src3);
*dst = mixColorsRgb32(a, b, c, d);
}
}
}
break;
case Format::I_8:
case Format::A_8:
{
uint8_t* dst = img->m_data_ptr;
for (uint32_t y = 0; y < newSize.y; y++)
{
uint8_t const* src0 = m_data_ptr + y * factorY;
uint8_t const* src1 = src0 + deltaX;
uint8_t const* src2 = src0 + deltaY;
uint8_t const* src3 = src1 + deltaY;
for (uint32_t i = 0; i < newSize.x; i++, src0 += factorX, src1 += factorX, src2 += factorX, src3 += factorX, dst++)
{
uint8_t a = *src0, b = *src1, c = *src2, d = *src3;
*dst = mixColorsA8(a, b, c, d);
}
}
}
break;
case Format::AI_8:
{
uint16_t* dst = (uint16_t*)img->m_data_ptr;
for (uint32_t y = 0; y < newSize.y; y++)
{
uint16_t const* src0 = (uint16_t const*)m_data_ptr + y * factorY;
uint16_t const* src1 = src0 + deltaX;
uint16_t const* src2 = src0 + deltaY;
uint16_t const* src3 = src1 + deltaY;
for (uint32_t i = 0; i < newSize.x; i++, src0 += factorX, src1 += factorX, src2 += factorX, src3 += factorX, dst++)
{
uint16_t a = *src0, b = *src1, c = *src2, d = *src3;
*dst = mixColorsAI8(a, b, c, d);
}
}
}
break;
case Format::RGB_565:
{
uint16_t* dst = (uint16_t*)img->m_data_ptr;
for (uint32_t y = 0; y < newSize.y; y++)
{
uint16_t const* src0 = (uint16_t const*)m_data_ptr + y * factorY;
uint16_t const* src1 = src0 + deltaX;
uint16_t const* src2 = src0 + deltaY;
uint16_t const* src3 = src1 + deltaY;
for (uint32_t i = 0; i < newSize.x; i++, src0 += factorX, src1 += factorX, src2 += factorX, src3 += factorX, dst++)
{
uint16_t a = *src0, b = *src1, c = *src2, d = *src3;
*dst = mixColorsRgb565(a, b, c, d);
}
}
}
break;
case Format::RGBA_4:
{
uint16_t* dst = (uint16_t*)img->m_data_ptr;
for (uint32_t y = 0; y < newSize.y; y++)
{
uint16_t const* src0 = (uint16_t const*)m_data_ptr + y * factorY;
uint16_t const* src1 = src0 + deltaX;
uint16_t const* src2 = src0 + deltaY;
uint16_t const* src3 = src1 + deltaY;
for (uint32_t i = 0; i < newSize.x; i++, src0 += factorX, src1 += factorX, src2 += factorX, src3 += factorX, dst++)
{
uint16_t a = *src0, b = *src1, c = *src2, d = *src3;
*dst = mixColorsRgba4(a, b, c, d);
}
}
}
break;
case Format::RGBA_5551:
{
uint16_t* dst = (uint16_t*)img->m_data_ptr;
for (uint32_t y = 0; y < newSize.y; y++)
{
uint16_t const* src0 = (uint16_t const*)m_data_ptr + y * factorY;
uint16_t const* src1 = src0 + deltaX;
uint16_t const* src2 = src0 + deltaY;
uint16_t const* src3 = src1 + deltaY;
for (uint32_t i = 0; i < newSize.x; i++, src0 += factorX, src1 += factorX, src2 += factorX, src3 += factorX, dst++)
{
uint16_t a = *src0, b = *src1, c = *src2, d = *src3;
*dst = mixColorsRgba5551(a, b, c, d);
}
}
}
break;
case Format::RGB_8:
{
factorX *= 3;
factorY *= 3;
deltaX *= 3;
deltaY *= 3;
uint8_t* dst = img->m_data_ptr;
for (uint32_t y = 0; y < newSize.y; y++)
{
uint8_t const* src0 = m_data_ptr + y * factorY;
uint8_t const* src1 = src0 + deltaX;
uint8_t const* src2 = src0 + deltaY;
uint8_t const* src3 = src1 + deltaY;
for (uint32_t i = 0; i < newSize.x; i++, src0 += factorX, src1 += factorX, src2 += factorX, src3 += factorX)
{
uint32_t a = (*(src0) << 16) | (*(src0 + 1) << 8) | *(src0 + 2);
uint32_t b = (*(src1) << 16) | (*(src1 + 1) << 8) | *(src1 + 2);
uint32_t c = (*(src2) << 16) | (*(src2 + 1) << 8) | *(src2 + 2);
uint32_t d = (*(src3) << 16) | (*(src3 + 1) << 8) | *(src3 + 2);
uint32_t x = mixColorsRgba8(a, b, c, d);
*dst++ = (x >> 16) & 0xFF;
*dst++ = (x >> 8) & 0xFF;
*dst++ = x & 0xFF;
}
}
}
break;
default: QASSERT(0); break;
}
}
else
{
switch (m_format)
{
case Format::RGBA_32:
{
QASSERT(sizeof(math::vec4f) == 16);
auto* dst = (math::vec4f*)img->m_data_ptr;
for (uint32_t y = 0; y < newSize.y; y++)
{
auto const* src = (math::vec4f const*)m_data_ptr + y * factorY;
for (uint32_t i = 0; i < newSize.x; i++, src += factorX, dst++)
{
*dst = *src;
}
}
}
break;
case Format::RGB_32:
{
auto* dst = (math::vec3f*)img->m_data_ptr;
for (uint32_t y = 0; y < newSize.y; y++)
{
auto const* src = (math::vec3f const*)m_data_ptr + y * factorY;
for (uint32_t i = 0; i < newSize.x; i++, src += factorX, dst++)
{
*dst = *src;
}
}
}
break;
case Format::I_32:
case Format::RGBA_8:
{
QASSERT(sizeof(float) == sizeof(uint32_t));
uint32_t* dst = (uint32_t*)img->m_data_ptr;
for (uint32_t y = 0; y < newSize.y; y++)
{
uint32_t const* src = (uint32_t const*)m_data_ptr + y * factorY;
for (uint32_t i = 0; i < newSize.x; i++, src += factorX, dst++)
{
*dst = *src;
}
}
}
break;
case Format::I_8:
case Format::A_8:
{
uint8_t* dst = img->m_data_ptr;
for (uint32_t y = 0; y < newSize.y; y++)
{
uint8_t const* src = m_data_ptr + y * factorY;
for (uint32_t i = 0; i < newSize.x; i++, src += factorX, dst++)
{
*dst = *src;
}
}
}
break;
case Format::AI_8:
case Format::RGB_565:
case Format::RGBA_4:
case Format::RGBA_5551:
{
uint16_t* dst = (uint16_t*)img->m_data_ptr;
for (uint32_t y = 0; y < newSize.y; y++)
{
uint16_t const* src = (uint16_t const*)m_data_ptr + y * factorY;
for (uint32_t i = 0; i < newSize.x; i++, src += factorX, dst++)
{
*dst = *src;
}
}
}
break;
case Format::RGB_8:
{
factorX *= 3;
factorY *= 3;
uint8_t* dst = img->m_data_ptr;
for (uint32_t y = 0; y < newSize.y; y++)
{
uint8_t const* src = m_data_ptr + y * factorY;
for (uint32_t i = 0; i < newSize.x; i++, src += factorX)
{
*dst++ = *src;
*dst++ = *(src + 1);
*dst++ = *(src + 2);
}
}
}
break;
default: QASSERT(0); break;
}
}
swap(*img);
return *this;
}
Dynamic_Image& Dynamic_Image::flip_h()
{
switch (m_format)
{
case Format::A_8:
case Format::I_8:
{
for (uint32_t j = 0; j < m_size.y; j++)
{
auto* a = get_mutable_line_data(j);
auto* b = a + m_size.x - 1;
for (uint32_t i = 0, szi = m_size.x / 2; i < szi; i++)
{
std::swap(*a, *b);
a++;
b--;
}
}
}
break;
case Format::AI_8:
case Format::RGBA_4:
case Format::RGBA_5551:
case Format::RGB_565:
{
for (uint32_t j = 0; j < m_size.y; j++)
{
auto* a = (uint16_t*)get_mutable_line_data(j);
auto* b = a + m_size.x - 1;
for (uint32_t i = 0, szi = m_size.x / 2; i < szi; i++)
{
std::swap(*a, *b);
a++;
b--;
}
}
}
break;
case Format::RGB_8:
{
uint32_t line_size = get_line_size();
for (uint32_t j = 0; j < m_size.y; j++)
{
auto* a = get_mutable_line_data(j);
auto* b = a + line_size - 3;
for (uint32_t i = 0, szi = m_size.x / 2; i < szi; i++)
{
std::swap(a[0], b[0]);
std::swap(a[1], b[1]);
std::swap(a[2], b[2]);
a += 3;
b -= 3;
}
}
}
break;
case Format::I_32:
case Format::RGBA_8:
{
QASSERT(sizeof(float) == sizeof(uint32_t));
for (uint32_t j = 0; j < m_size.y; j++)
{
auto* a = (uint32_t*)get_mutable_line_data(j);
auto* b = a + m_size.x - 1;
for (uint32_t i = 0, szi = m_size.x / 2; i < szi; i++)
{
std::swap(*a, *b);
a++;
b--;
}
}
}
break;
case Format::RGBA_32:
{
QASSERT(sizeof(math::vec4f) == 16);
for (uint32_t j = 0; j < m_size.y; j++)
{
auto* a = (math::vec4f*)get_mutable_line_data(j);
auto* b = a + m_size.x - 1;
for (uint32_t i = 0, szi = m_size.x / 2; i < szi; i++)
{
std::swap(*a, *b);
a++;
b--;
}
}
}
break;
case Format::RGB_32:
{
for (uint32_t j = 0; j < m_size.y; j++)
{
auto* a = (math::vec3f*)get_mutable_line_data(j);
auto* b = a + m_size.x - 1;
for (uint32_t i = 0, szi = m_size.x / 2; i < szi; i++)
{
std::swap(*a, *b);
a++;
b--;
}
}
}
break;
default:
QLOGE("Image format not handled: {}", m_format);
break;
}
return *this;
}
Dynamic_Image& Dynamic_Image::flip_v()
{
boost::auto_buffer<uint8_t, boost::store_n_bytes<8192>> buffer;
size_t line_size = get_line_size();
buffer.uninitialized_resize(line_size);
uint8_t* a = get_mutable_line_data(0);
uint8_t* b = get_mutable_line_data(m_size.y - 1);
for (size_t i = 0, sz = m_size.y / 2; i < sz; i++)
{
memcpy(buffer.data(), a, line_size);
memcpy(a, b, line_size);
memcpy(b, buffer.data(), line_size);
a += m_pitch;
b -= m_pitch;
}
return *this;
}
Dynamic_Image& Dynamic_Image::flip(bool horizontal, bool vertical)
{
if (horizontal & vertical)
{
flip_v();
flip_h();
}
else if (horizontal)
{
flip_v();
}
else if (vertical)
{
flip_h();
}
return *this;
}
Dynamic_Image& Dynamic_Image::rotate_90_cw()
{
QASSERT(m_owns_data);
return *this;
}
Dynamic_Image& Dynamic_Image::rotate_90_ccw()
{
QASSERT(m_owns_data);
return *this;
}
Dynamic_Image& Dynamic_Image::convert_to_rgba8()
{
if (!is_compact())
{
return *this;
}
if (m_format == Format::RGBA_8)
{
return *this;
}
uint32_t count = m_size.x * m_size.y;
//since the float and uint32_t have the same storage, we can do this in place
if (m_format == Format::I_32)
{
QASSERT(sizeof(float) == sizeof(uint32_t));
float const* src = (float const*)m_data_ptr;
uint32_t* dst = (uint32_t*)m_data_ptr;
for (uint32_t i = 0; i < count; i++)
{
float d = *src++;
uint8_t dq = (uint8_t)(d * 255.f);
*dst++ = 0xFF000000 | (dq << 16) | (dq << 8) | dq;
}
m_format = Format::RGBA_8;
return *this;
}
auto img = std::make_shared<Dynamic_Image>();
img->allocate(Format::RGBA_8, m_size, nullptr);
QASSERT(m_data_ptr && img->m_data_ptr);
uint32_t* dst = (uint32_t*)img->m_data_ptr;
switch (m_format)
{
case Format::A_8:
{
uint8_t const* src = m_data_ptr;
for (uint32_t i = 0; i < count; i++)
{
uint8_t c = *src++;
*dst++ = c << 24;
}
}
break;
case Format::I_8:
{
uint8_t const* src = m_data_ptr;
for (uint32_t i = 0; i < count; i++)
{
uint8_t c = *src++;
*dst++ = 0xFF000000 | (c << 16) | (c << 8) | c;
}
}
break;
case Format::AI_8:
{
uint16_t const* src = (uint16_t const*)m_data_ptr;
for (uint32_t i = 0; i < count; i++)
{
uint16_t c = *src++;
uint32_t a = c >> 8;
uint32_t x = c & 0xFF;
*dst++ = (a << 24) | (x << 16) | (x << 8) | x;
}
}
break;
case Format::RGBA_4:
{
uint16_t const* src = (uint16_t const*)m_data_ptr;
for (uint32_t i = 0; i < count; i++)
{
uint16_t c = *src++;
uint32_t a = ((c >> 12) & 0xF) << 28;
uint32_t b = ((c >> 8) & 0xF) << 20;
uint32_t g = ((c >> 4) & 0xF) << 12;
uint32_t r = ((c ) & 0xF) << 4;
*dst++ = a | b | g | r;
}
}
break;
case Format::RGBA_5551:
{
uint16_t const* src = (uint16_t const*)m_data_ptr;
for (uint32_t i = 0; i < count; i++)
{
uint16_t c = *src++;
uint32_t a = ((c >> 15) & 1) << 31;
uint32_t b = ((c >> 10) & 31) << 19;
uint32_t g = ((c >> 5) & 31) << 11;
uint32_t r = ((c ) & 31) << 3;
*dst++ = a | b | g | r;
}
}
break;
case Format::RGB_565:
{
uint16_t const* src = (uint16_t const*)m_data_ptr;
for (uint32_t i = 0; i < count; i++)
{
uint16_t c = *src++;
uint32_t b = ((c >> 11) & 31) << 19;
uint32_t g = ((c >> 5) & 63) << 10;
uint32_t r = ((c ) & 31) << 3;
*dst++ = 0xFF000000 | b | g | r;
}
}
break;
case Format::RGB_8:
{
uint8_t const* src = m_data_ptr;
for (uint32_t i = 0; i < count; i++)
{
//rgb rgb rgb
//uint8_t layout: rgba rgba rgba -> uint32_t layout: abgr abgr abgr
uint32_t r = *src++;
uint32_t g = *src++;
uint32_t b = *src++;
*dst++ = 0xFF000000 | (b << 16) | (g << 8) | r;
}
}
break;
default:
QASSERT(0);
break;
}
return swap(*img);
}
Dynamic_Image& Dynamic_Image::convert_to_rgb8()
{
if (!is_compact())
{
return *this;
}
if (m_format == Format::RGB_8)
{
return *this;
}
uint32_t count = m_size.x * m_size.y;
auto img = std::make_shared<Dynamic_Image>();
img->allocate(Format::RGB_8, m_size, nullptr);
QASSERT(m_data_ptr && img->m_data_ptr);
uint8_t* dst = (uint8_t*)img->m_data_ptr;
switch (m_format)
{
case Format::I_32:
{
float const* src = (float const*)m_data_ptr;
for (uint32_t i = 0; i < count; i++)
{
float d = *src++;
uint8_t dq = (uint8_t)(d * 255.f);
*dst++ = dq;
*dst++ = dq;
*dst++ = dq;
}
}
case Format::A_8:
{
memset(dst, 0, count * 3);
}
break;
case Format::I_8:
{
uint8_t const* src = m_data_ptr;
for (uint32_t i = 0; i < count; i++)
{
uint8_t c = *src++;
*dst++ = c;
*dst++ = c;
*dst++ = c;
}
}
break;
case Format::AI_8:
{
uint16_t const* src = (uint16_t const*)m_data_ptr;
for (uint32_t i = 0; i < count; i++)
{
uint16_t c = *src++;
uint8_t x = static_cast<uint8_t>(c & 0xFF);
*dst++ = x;
*dst++ = x;
*dst++ = x;
}
}
break;
case Format::RGBA_4:
{
uint16_t const* src = (uint16_t const*)m_data_ptr;
for (uint32_t i = 0; i < count; i++)
{
uint16_t c = *src++;
uint8_t b = static_cast<uint8_t>(((c >> 8) & 0xF) << 20);
uint8_t g = static_cast<uint8_t>(((c >> 4) & 0xF) << 12);
uint8_t r = static_cast<uint8_t>(((c ) & 0xF) << 4);
*dst++ = r;
*dst++ = g;
*dst++ = b;
}
}
break;
case Format::RGBA_5551:
{
uint16_t const* src = (uint16_t const*)m_data_ptr;
for (uint32_t i = 0; i < count; i++)
{
uint16_t c = *src++;
uint8_t b = static_cast<uint8_t>(((c >> 10) & 31) << 19);
uint8_t g = static_cast<uint8_t>(((c >> 5) & 31) << 11);
uint8_t r = static_cast<uint8_t>(((c ) & 31) << 3);
*dst++ = r;
*dst++ = g;
*dst++ = b;
}
}
break;
case Format::RGB_565:
{
uint16_t const* src = (uint16_t const*)m_data_ptr;
for (uint32_t i = 0; i < count; i++)
{
uint16_t c = *src++;
uint8_t b = static_cast<uint8_t>(((c >> 11) & 31) << 19);
uint8_t g = static_cast<uint8_t>(((c >> 5) & 63) << 10);
uint8_t r = static_cast<uint8_t>(((c ) & 31) << 3);
*dst++ = r;
*dst++ = g;
*dst++ = b;
}
}
break;
case Format::RGBA_8:
{
uint8_t const* src = m_data_ptr;
for (uint32_t i = 0; i < count; i++)
{
src++; //alpha
uint8_t r = static_cast<uint8_t>(*src++);
uint8_t g = static_cast<uint8_t>(*src++);
uint8_t b = static_cast<uint8_t>(*src++);
*dst++ = r;
*dst++ = g;
*dst++ = b;
}
}
break;
default:
QASSERT(0);
break;
}
return swap(*img);
}
Dynamic_Image& Dynamic_Image::swap(Dynamic_Image& img)
{
std::swap(m_format, img.m_format);
std::swap(m_data_ptr, img.m_data_ptr);
std::swap(m_data, img.m_data);
std::swap(m_owns_data, img.m_owns_data);
std::swap(m_pitch, img.m_pitch);
std::swap(m_size, img.m_size);
return *this;
}
| 36,100
|
https://github.com/kemditkb/tutorial_shopping_cart/blob/master/src/containers/Home/components/Content.js
|
Github Open Source
|
Open Source
|
WTFPL
| 2,017
|
tutorial_shopping_cart
|
kemditkb
|
JavaScript
|
Code
| 233
| 1,030
|
import React, { Component } from 'react';
import { Container, Row, Col, Jumbotron, Button, Modal, ModalHeader, ModalBody, ModalFooter } from 'reactstrap';
import AlbumJson from './Album.json';
import Product from './Product';
import Cart from './Cart';
export default class Content extends Component {
state = {
modal: false,
album: AlbumJson,
cart: [],
}
// 呼叫API
// componentDidMount = async () => {
// const data = await fetch('https://demojson.herokuapp.com/cart').then(response => response.json());
// this.setState({
// album: data,
// });
// }
toggle = () => {
this.setState({
modal: !this.state.modal,
});
}
addToCart = (product) => {
const cart = this.state.cart;
cart.push(product);
this.setState({
cart
});
}
deleteCartItem = (index) => {
const cart = this.state.cart;
cart.splice(index, 1);
this.setState({
cart
});
}
checkout = (totalPrice) => {
alert(`已從您的信用卡中扣除${totalPrice}元!`);
}
render() {
const { album, cart, modal } = this.state;
const totalPrice = cart.reduce((acc, item) => (acc += item.price), 0);
return (
<div className="content">
<Container>
<Row>
<Col md={12}>
<Jumbotron>
<h1 className="display-3">美客唱片</h1>
<p className="lead">
美客唱片成立以來,結合實體唱片通路、唱片公司、網站,因而擁有豐富、完整的音樂資源
</p>
<p className="lead">
並與電視、廣播等媒體進行策略聯盟,已迅速打響知名度,並廣受各界好評
</p>
<p className="lead">
不僅如此,美客唱片將跨足大中華地區,透過舉辦跨國、跨區域的大型頒獎典禮、演唱會以及音樂活動
</p>
<p className="lead">
進一步擴大影響力,提昇流行音樂產業的動能
</p>
<hr className="my-2" />
<p className="lead">
<Button color="primary" onClick={this.toggle}>購物車({cart.length})</Button>
</p>
</Jumbotron>
</Col>
</Row>
<Row>
{
album.map(product => (
<Col sm={6} md={4} className="mb-3">
<Product
product={product}
cart={cart}
addToCart={this.addToCart}
/>
</Col>
))
}
</Row>
<Modal isOpen={modal} toggle={this.toggle}>
<ModalHeader toggle={this.toggle}>購物車</ModalHeader>
<ModalBody>
<Cart
cart={cart}
deleteCartItem={this.deleteCartItem}
/>
</ModalBody>
<ModalFooter>
<Button
disabled={cart.length === 0}
color="primary"
onClick={() => this.checkout(totalPrice)}
>
結帳
</Button>{' '}
<Button color="secondary" onClick={this.toggle}>取消</Button>
</ModalFooter>
</Modal>
</Container>
</div>
);
}
}
| 22,957
|
https://github.com/akabii/RazorPagesSample/blob/master/RazorPagesSample/Customers/InlinePageModels/_PageImports.cshtml
|
Github Open Source
|
Open Source
|
MIT
| 2,017
|
RazorPagesSample
|
akabii
|
HTML+Razor
|
Code
| 6
| 31
|
@using RazorPages
@using Microsoft.EntityFrameworkCore
@using Microsoft.AspNetCore.Mvc.RazorPages
| 38,228
|
https://github.com/milesaturpin/raft-baselines/blob/master/src/raft_baselines/classifiers/transformers_causal_lm_classifier.py
|
Github Open Source
|
Open Source
|
MIT
| null |
raft-baselines
|
milesaturpin
|
Python
|
Code
| 207
| 897
|
from typing import List, Mapping
import datasets
import torch
from transformers import AutoModelForCausalLM
from sentence_transformers import util
from raft_baselines.classifiers.in_context_classifier import InContextClassifier
from raft_baselines.utils.tokenizers import TransformersTokenizer
from raft_baselines.utils.embedders import SentenceTransformersEmbedder
class TransformersCausalLMClassifier(InContextClassifier):
def __init__(
self,
*args,
model_type: str = "distilgpt2",
**kwargs,
) -> None:
tokenizer = TransformersTokenizer(model_type)
self.device = "cuda" if torch.cuda.is_available() else "cpu"
self.model = AutoModelForCausalLM.from_pretrained(model_type).to(self.device)
self.similarity_embedder = SentenceTransformersEmbedder()
super().__init__(
*args,
tokenizer=tokenizer,
max_tokens=self.model.config.max_position_embeddings,
**kwargs,
)
def semantically_select_training_examples(
self, target: Mapping[str, str]
) -> datasets.Dataset:
formatted_examples_without_labels = tuple(
self.format_dict(
{col: row[col] for col in self.input_cols if col in row},
)
for row in self.training_data
)
formatted_target = self.format_dict(target)
# adapted from https://towardsdatascience.com/semantic-similarity-using-transformers-8f3cb5bf66d6
target_embedding = self.similarity_embedder(tuple([formatted_target]))
example_embeddings = self.similarity_embedder(formatted_examples_without_labels)
similarity_scores = util.pytorch_cos_sim(target_embedding, example_embeddings)[
0
]
sorted_indices = torch.argsort(-similarity_scores.to(self.device))
return self.training_data.select(
list(reversed(sorted_indices[: self.num_prompt_training_examples]))
)
def _get_raw_probabilities(
self,
prompt: str,
) -> List[float]:
# import ipdb; ipdb.set_trace()
inputs = self.tokenizer(prompt, return_tensors="pt").to(self.device)
# inputs is dict with input_ids and attention mask
with torch.no_grad():
output = self.model(**inputs)
# torch.Size([1, 961, 50257]), softmax of next token probs, vector
next_token_probs = torch.softmax(output.logits[0][-1], dim=0)
def get_prob_for_class(clas):
# import ipdb; ipdb.set_trace()
clas_str = (
f" {clas}"
if not self.add_prefixes
else f" {self.classes.index(clas) + 1}"
)
# tokenize answer then check prob of first toekn
return next_token_probs[self.tokenizer(clas_str)["input_ids"][0]]
return (
torch.stack([get_prob_for_class(clas) for clas in self.classes])
.cpu()
.detach()
.numpy()
)
| 5,794
|
https://github.com/JeanMaximilienCadic/deepspeech2paddle-docker/blob/master/data/librispeech/librispeech.py
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,021
|
deepspeech2paddle-docker
|
JeanMaximilienCadic
|
Python
|
Code
| 408
| 1,897
|
"""Prepare Librispeech ASR datasets.
Download, unpack and create manifest files.
Manifest file is a json-format file with each line containing the
meta data (i.e. audio filepath, transcript and audio duration)
of each audio file in the data set.
"""
import distutils.util
import os
import sys
import argparse
import soundfile
import json
import codecs
import io
from data_utils.utility import download, unpack
URL_ROOT = "http://www.openslr.org/resources/12"
URL_ROOT = "https://openslr.magicdatatech.com/resources/12"
URL_TEST_CLEAN = URL_ROOT + "/test-clean.tar.gz"
URL_TEST_OTHER = URL_ROOT + "/test-other.tar.gz"
URL_DEV_CLEAN = URL_ROOT + "/dev-clean.tar.gz"
URL_DEV_OTHER = URL_ROOT + "/dev-other.tar.gz"
URL_TRAIN_CLEAN_100 = URL_ROOT + "/train-clean-100.tar.gz"
URL_TRAIN_CLEAN_360 = URL_ROOT + "/train-clean-360.tar.gz"
URL_TRAIN_OTHER_500 = URL_ROOT + "/train-other-500.tar.gz"
MD5_TEST_CLEAN = "32fa31d27d2e1cad72775fee3f4849a9"
MD5_TEST_OTHER = "fb5a50374b501bb3bac4815ee91d3135"
MD5_DEV_CLEAN = "42e2234ba48799c1f50f24a7926300a1"
MD5_DEV_OTHER = "c8d0bcc9cca99d4f8b62fcc847357931"
MD5_TRAIN_CLEAN_100 = "2a93770f6d5c6c964bc36631d331a522"
MD5_TRAIN_CLEAN_360 = "c0e676e450a7ff2f54aeade5171606fa"
MD5_TRAIN_OTHER_500 = "d1a0fd59409feb2c614ce4d30c387708"
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument(
"--target_dir",
default='~/.cache/paddle/dataset/speech/libri',
type=str,
help="Directory to save the dataset. (default: %(default)s)")
parser.add_argument(
"--manifest_prefix",
default="manifest",
type=str,
help="Filepath prefix for output manifests. (default: %(default)s)")
parser.add_argument(
"--full_download",
default="True",
type=distutils.util.strtobool,
help="Download all datasets for Librispeech."
" If False, only download a minimal requirement (test-clean, dev-clean"
" train-clean-100). (default: %(default)s)")
args = parser.parse_args()
def create_manifest(data_dir, manifest_path):
"""Create a manifest json file summarizing the data set, with each line
containing the meta data (i.e. audio filepath, transcription text, audio
duration) of each audio file within the data set.
"""
print("Creating manifest %s ..." % manifest_path)
json_lines = []
for subfolder, _, filelist in sorted(os.walk(data_dir)):
text_filelist = [
filename for filename in filelist if filename.endswith('trans.txt')
]
if len(text_filelist) > 0:
text_filepath = os.path.join(subfolder, text_filelist[0])
for line in io.open(text_filepath, encoding="utf8"):
segments = line.strip().split()
text = ' '.join(segments[1:]).lower()
audio_filepath = os.path.join(subfolder, segments[0] + '.flac')
audio_data, samplerate = soundfile.read(audio_filepath)
duration = float(len(audio_data)) / samplerate
json_lines.append(
json.dumps({
'audio_filepath': audio_filepath,
'duration': duration,
'text': text
}))
with codecs.open(manifest_path, 'w', 'utf-8') as out_file:
for line in json_lines:
out_file.write(line + '\n')
def prepare_dataset(url, md5sum, target_dir, manifest_path):
"""Download, unpack and create summmary manifest file.
"""
if not os.path.exists(os.path.join(target_dir, "LibriSpeech")):
# download
filepath = download(url, md5sum, target_dir)
# unpack
unpack(filepath, target_dir)
else:
print("Skip downloading and unpacking. Data already exists in %s." %
target_dir)
# create manifest json file
create_manifest(target_dir, manifest_path)
def main():
if args.target_dir.startswith('~'):
args.target_dir = os.path.expanduser(args.target_dir)
prepare_dataset(
url=URL_TEST_CLEAN,
md5sum=MD5_TEST_CLEAN,
target_dir=os.path.join(args.target_dir, "test-clean"),
manifest_path=args.manifest_prefix + ".test-clean")
prepare_dataset(
url=URL_DEV_CLEAN,
md5sum=MD5_DEV_CLEAN,
target_dir=os.path.join(args.target_dir, "dev-clean"),
manifest_path=args.manifest_prefix + ".dev-clean")
if args.full_download:
prepare_dataset(
url=URL_TRAIN_CLEAN_100,
md5sum=MD5_TRAIN_CLEAN_100,
target_dir=os.path.join(args.target_dir, "train-clean-100"),
manifest_path=args.manifest_prefix + ".train-clean-100")
prepare_dataset(
url=URL_TEST_OTHER,
md5sum=MD5_TEST_OTHER,
target_dir=os.path.join(args.target_dir, "test-other"),
manifest_path=args.manifest_prefix + ".test-other")
prepare_dataset(
url=URL_DEV_OTHER,
md5sum=MD5_DEV_OTHER,
target_dir=os.path.join(args.target_dir, "dev-other"),
manifest_path=args.manifest_prefix + ".dev-other")
prepare_dataset(
url=URL_TRAIN_CLEAN_360,
md5sum=MD5_TRAIN_CLEAN_360,
target_dir=os.path.join(args.target_dir, "train-clean-360"),
manifest_path=args.manifest_prefix + ".train-clean-360")
prepare_dataset(
url=URL_TRAIN_OTHER_500,
md5sum=MD5_TRAIN_OTHER_500,
target_dir=os.path.join(args.target_dir, "train-other-500"),
manifest_path=args.manifest_prefix + ".train-other-500")
if __name__ == '__main__':
main()
| 2,021
|
https://github.com/juxd/nusmods/blob/master/www/src/js/selectors/moduleBank.js
|
Github Open Source
|
Open Source
|
MIT
| null |
nusmods
|
juxd
|
JavaScript
|
Code
| 127
| 401
|
// @flow
import type { ModuleCode, ModuleCondensed, Semester } from 'types/modules';
import type { ModuleBank } from 'reducers/moduleBank';
import type { State } from 'reducers';
import type { SemTimetableConfig } from 'types/timetables';
import type { ModuleSelectListItem } from 'types/reducers';
import { getRequestModuleCode } from 'actions/moduleBank';
import { isOngoing } from './requests';
export function getModuleCondensed(
moduleBank: ModuleBank,
): (moduleCode: ModuleCode) => ?ModuleCondensed {
return (moduleCode) => moduleBank.moduleCodes[moduleCode];
}
export function getAllPendingModules(state: State): ModuleCode[] {
return Object.keys(state.requests)
.filter((key) => isOngoing(state, key))
.map(getRequestModuleCode)
.filter(Boolean);
}
export function getSemModuleSelectList(
state: State,
semester: Semester,
semTimetableConfig: SemTimetableConfig,
): ModuleSelectListItem[] {
const pendingModules = new Set(getAllPendingModules(state));
return (
state.moduleBank.moduleList
// In specified semester and not within the timetable.
.filter((item) => item.Semesters.includes(semester))
.map((module) => ({
...module,
isAdded: module.ModuleCode in semTimetableConfig,
isAdding: pendingModules.has(module.ModuleCode),
}))
);
}
| 11,671
|
https://github.com/quantum-defence/MicroQiskit/blob/master/versions/MicroPython/microqiskit.py
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,021
|
MicroQiskit
|
quantum-defence
|
Python
|
Code
| 389
| 2,081
|
import random
from math import cos,sin,pi
r2=0.70710678118
class QuantumCircuit:
def __init__(self,n,m=0):
self.num_qubits=n
self.num_clbits=m
self.name = ''
self.data=[]
def __add__(self,self2):
self3=QuantumCircuit(max(self.num_qubits,self2.num_qubits),max(self.num_clbits,self2.num_clbits))
self3.data=self.data+self2.data
self3.name = self.name
return self3
def initialize(self,k):
self.data[:] = []
self.data.append(('init',[e for e in k]))
def x(self,q):
self.data.append(('x',q))
def rx(self,theta,q):
self.data.append(('rx',theta,q))
def rz(self,theta,q):
self.data.append(('rz',theta,q))
def h(self,q):
self.data.append(('h',q))
def cx(self,s,t):
self.data.append(('cx',s,t))
def crx(self,theta,s,t):
self.data.append(('crx',theta,s,t))
def measure(self,q,b):
assert b<self.num_clbits, 'Index for output bit out of range.'
assert q<self.num_qubits, 'Index for qubit out of range.'
self.data.append(('m',q,b))
def ry(self,theta,q):
self.rx(pi/2,q)
self.rz(theta,q)
self.rx(-pi/2,q)
def z(self,q):
self.rz(pi,q)
def y(self,q):
self.rz(pi,q)
self.x(q)
def simulate(qc,shots=1024,get='counts',noise_model=[]):
def superpose(x,y):
return [r2*(x[j]+y[j])for j in range(2)],[r2*(x[j]-y[j])for j in range(2)]
def turn(x,y,theta):
theta = float(theta)
return [x[0]*cos(theta/2)+y[1]*sin(theta/2),x[1]*cos(theta/2)-y[0]*sin(theta/2)],[y[0]*cos(theta/2)+x[1]*sin(theta/2),y[1]*cos(theta/2)-x[0]*sin(theta/2)]
def phaseturn(x,y,theta):
theta = float(theta)
return [[x[0]*cos(theta/2) - x[1]*sin(-theta/2),x[1]*cos(theta/2) + x[0]*sin(-theta/2)],[y[0]*cos(theta/2) - y[1]*sin(+theta/2),y[1]*cos(theta/2) + y[0]*sin(+theta/2)]]
k = [[0,0] for _ in range(2**qc.num_qubits)]
k[0] = [1.0,0.0]
if noise_model:
if type(noise_model)==float:
noise_model = [noise_model]*qc.num_qubits
outputnum_clbitsap = {}
for gate in qc.data:
if gate[0]=='init':
if type(gate[1][0])==list:
k = [e for e in gate[1]]
else:
k = [[e,0] for e in gate[1]]
elif gate[0]=='m':
outputnum_clbitsap[gate[2]] = gate[1]
elif gate[0] in ['x','h','rx','rz']:
j = gate[-1]
for i0 in range(2**j):
for i1 in range(2**(qc.num_qubits-j-1)):
b0=i0+2**(j+1)*i1
b1=b0+2**j
if gate[0]=='x':
k[b0],k[b1]=k[b1],k[b0]
elif gate[0]=='h':
k[b0],k[b1]=superpose(k[b0],k[b1])
elif gate[0]=='rx':
theta = gate[1]
k[b0],k[b1]=turn(k[b0],k[b1],theta)
elif gate[0]=='rz':
theta = gate[1]
k[b0],k[b1]=phaseturn(k[b0],k[b1],theta)
elif gate[0] in ['cx','crx']:
if gate[0]=='cx':
[s,t] = gate[1:]
else:
theta = gate[1]
[s,t] = gate[2:]
[l,h] = sorted([s,t])
for i0 in range(2**l):
for i1 in range(2**(h-l-1)):
for i2 in range(2**(qc.num_qubits-h-1)):
b0=i0+2**(l+1)*i1+2**(h+1)*i2+2**s
b1=b0+2**t
if gate[0]=='cx':
k[b0],k[b1]=k[b1],k[b0]
else:
k[b0],k[b1]=turn(k[b0],k[b1],theta)
if get=='statevector':
return k
else:
probs = [e[0]**2+e[1]**2 for e in k]
if noise_model:
for j in range(qc.num_qubits):
p_meas = noise_model[j]
for i0 in range(2**j):
for i1 in range(2**(qc.num_qubits-j-1)):
b0=i0+2**(j+1)*i1
b1=b0+2**j
p0 = probs[b0]
p1 = probs[b1]
probs[b0] = (1-p_meas)*p0 + p_meas*p1
probs[b1] = (1-p_meas)*p1 + p_meas*p0
if get=='probabilities_dict':
return {('{0:0'+str(qc.num_qubits)+'b}').format(j):p for j,p in enumerate(probs)}
elif get in ['counts', 'memory']:
m = [False for _ in range(qc.num_qubits)]
for gate in qc.data:
for j in range(qc.num_qubits):
assert not ((gate[-1]==j) and m[j]), 'Incorrect or missing measure command.'
m[j] = (gate==('m',j,j))
m=[]
for _ in range(shots):
cumu=0
un=True
r=random.random()
for j,p in enumerate(probs):
cumu += p
if r<cumu and un:
raw_out=('{0:0'+str(qc.num_qubits)+'b}').format(j)
out_list = ['0']*qc.num_clbits
for bit in outputnum_clbitsap:
out_list[qc.num_clbits-1-bit] = raw_out[qc.num_qubits-1-outputnum_clbitsap[bit]]
out = ''.join(out_list)
m.append(out)
un=False
if get=='memory':
return m
else:
counts = {}
for out in m:
if out in counts:
counts[out] += 1
else:
counts[out] = 1
return counts
| 42,625
|
https://github.com/leidelosreyes/swappee/blob/master/resources/views/messages/mail.blade.php
|
Github Open Source
|
Open Source
|
MIT
| null |
swappee
|
leidelosreyes
|
PHP
|
Code
| 43
| 213
|
<div class="container mb-5 d-flex justify-content-around">
<div class="card" style="width:80%;">
<h3 class="card-header">Message</h3>
<div class="card-body">
<div class="row">
<div class="col-12 text-center">
<h4 class="card-title">Hi <strong>{{ $name}}</strong>,</h4>
</div>
<div class="col-12 text-center">
<p class="card-text">{{$body}}</p>
</div>
<div class="col-12 text-center mt-3">
<a href="https://swappee.online" class="btn btn-primary">Redirect to Swappee</a>
</div>
</div>
</div>
</div>
</div>
| 32,127
|
https://github.com/sailfishos-flatpak/flatpak-runner/blob/master/fpk/__init__.py
|
Github Open Source
|
Open Source
|
BSD-3-Clause
| 2,021
|
flatpak-runner
|
sailfishos-flatpak
|
Python
|
Code
| 44
| 151
|
from .apps import refresh_apps as refresh_apps_impl
from .extension import has_extension as has_extension_impl
from .extension import remove_extension as remove_extension_impl
from .extension import sync_extension as sync_extension_impl
# externally available functions
def has_extension(arch):
return has_extension_impl(arch)
def refresh_apps(just_delete = False):
return refresh_apps_impl(just_delete=just_delete)
def remove_extension(arch):
remove_extension_impl(arch)
def sync_extension(arch):
sync_extension_impl(arch)
| 37,412
|
https://github.com/Liuyuting5/AiyinYue/blob/master/爱悦台/resource/C/SearchViewController.m
|
Github Open Source
|
Open Source
|
MIT
| 2,015
|
AiyinYue
|
Liuyuting5
|
Objective-C
|
Code
| 963
| 4,673
|
//
// SearchViewController.m
// AiYueTai
//
// Created by qianfeng on 15/6/18.
// Copyright (c) 2015年 qianfeng. All rights reserved.
//
#import "SearchViewController.h"
#import "SearchModel.h"
#import "searchCell.h"
#import "DetailViewController.h"
#import "LiveModel.h"
@interface SearchViewController ()<UITableViewDelegate,UITableViewDataSource>
{
UISearchBar *searchBar;
UIButton *searchBnt;
UIView *_noDataView;
NSMutableArray *models;
UITableView *_tableView;
NSInteger _offset;
}
- (IBAction)biaoQianbuttonClicked:(id)sender;
@property (weak, nonatomic) IBOutlet UIView *searchBiaoQianView;
@property (weak, nonatomic) IBOutlet UIButton *button1;
@property (weak, nonatomic) IBOutlet UIButton *button2;
@property (weak, nonatomic) IBOutlet UIButton *button3;
@property (weak, nonatomic) IBOutlet UIButton *button4;
@property (weak, nonatomic) IBOutlet UIButton *button5;
@property (weak, nonatomic) IBOutlet UIButton *button6;
@property (weak, nonatomic) IBOutlet UIButton *button7;
@property (weak, nonatomic) IBOutlet UIButton *button8;
@property (weak, nonatomic) IBOutlet UIButton *button9;
@property (weak, nonatomic) IBOutlet UIButton *button10;
@property (weak, nonatomic) IBOutlet UIButton *button11;
@property (weak, nonatomic) IBOutlet UIButton *button12;
@property (weak, nonatomic) IBOutlet UIButton *button13;
@property (weak, nonatomic) IBOutlet UIButton *button14;
@property (weak, nonatomic) IBOutlet UIButton *button15;
@property (weak, nonatomic) IBOutlet UIButton *button16;
@property (weak, nonatomic) IBOutlet UIButton *button17;
@property (weak, nonatomic) IBOutlet UIButton *button18;
@property (weak, nonatomic) IBOutlet UIButton *button19;
@property (weak, nonatomic) IBOutlet UIButton *button20;
@property (nonatomic)DetailViewController *detailVC;
@end
@implementation SearchViewController
- (void)viewDidLoad {
[super viewDidLoad];
models = [[NSMutableArray alloc] init];
// Do any additional setup after loading the view from its nib.
self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"backgroundView"]];
self.view.userInteractionEnabled = YES;
[self createView];
[self setButtonRadius];
[self createNavView];
[self createTableView];
_tableView.hidden = YES;
}
#pragma mark-创建顶部的搜索栏
-(void)createView{
self.automaticallyAdjustsScrollViewInsets = NO;
UIView *searchBarBg = [[UIView alloc]initWithFrame:CGRectMake(0, 64, SCREEN_WIDTH, 40)];
searchBarBg.backgroundColor = [UIColor colorWithRed:26/(CGFloat)0x100 green:26/(CGFloat)0x100 blue:26/(CGFloat)0x100 alpha:1];
[self.view addSubview:searchBarBg];
searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 64, SCREEN_WIDTH-60, 40)];
searchBar.tintColor = [UIColor blueColor];
searchBar.layer.cornerRadius = 10;
searchBar.layer.masksToBounds = YES;
// searchBar.placeholder = @"//";
[self.view addSubview:searchBar];
//搜素按钮
searchBnt = [[UIButton alloc] initWithFrame:CGRectMake(SCREEN_WIDTH-60+10, 64, 40, 40)];
[searchBnt setTitle:@"搜索" forState:UIControlStateNormal];
searchBnt.backgroundColor =[UIColor grayColor];
[searchBnt addTarget:self action:@selector(searchBntClicked:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:searchBnt];
}
//搜索按钮点击事件
-(void)searchBntClicked:(UIButton*)button{
[searchBar resignFirstResponder];
if (searchBar.text.length==0) {
_searchBiaoQianView.hidden = YES;
[self createNoDataView];
}
#pragma mark-请求数据
NSString *urlstring = [NSString stringWithFormat:@"%@%@&%@",SEARCH_URL,[searchBar.text stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding],DEVICE_URL];
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager] ;
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", nil];
if (models) {
[models removeAllObjects];
}
[manager GET:urlstring parameters:nil success:^(NSURLSessionDataTask *task, NSDictionary* dic) {
NSArray *array = dic[@"videos"];
[array enumerateObjectsUsingBlock:^(NSDictionary* dic, NSUInteger idx, BOOL *stop) {
SearchModel *searchModel = [SearchModel SearchModelWithDic:dic];
[models addObject:searchModel];
[_tableView reloadData];
}];
} failure:^(NSURLSessionDataTask *task, NSError *error) {
NSLog(@"error");
}];
_searchBiaoQianView.hidden = YES;
_tableView.hidden = NO ;
}
//创建TabeView
-(void)createTableView{
_tableView =[[UITableView alloc] initWithFrame:CGRectMake(0, 64+40, SCREEN_WIDTH, SCREEN_HEIGHT-104) style:UITableViewStylePlain];
_tableView.delegate = self;
_tableView.dataSource = self;
[self setUpRefresh];
UINib *nibName = [UINib nibWithNibName:@"searchCell" bundle:nil];
[_tableView registerNib:nibName forCellReuseIdentifier:@"searchCell"];
[self.view addSubview:_tableView];
}
#pragma mark-tableView的代理方法
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
return models.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
searchCell *cell = [tableView dequeueReusableCellWithIdentifier:@"searchCell"];
SearchModel *searchModel = models[indexPath.row];
[cell refreshCell:searchModel];
return cell;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
return 150;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
_detailVC = [[DetailViewController alloc] init];
// LiveModel *liveModel =models[indexPath.row];
// detailVC.url=liveModel.hdUrl;
// detailVC.title = liveModel.title;
// detailVC.uid = liveModel.uid;
SearchModel *seacrMldel = models[indexPath.row];
_detailVC.url =seacrMldel.hdUrl;
_detailVC.title = seacrMldel.title;
_detailVC.uid = seacrMldel.uid;
UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:_detailVC];
UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 60, 30)];
[button setTitle:@"返回" forState:UIControlStateNormal];
button.titleLabel.textColor = [UIColor whiteColor];
UIBarButtonItem *leftButton = [[UIBarButtonItem alloc]initWithCustomView:button];
_detailVC.navigationItem.leftBarButtonItem = leftButton;
[button addTarget:self action:@selector(dismissDetailVC) forControlEvents:UIControlEventTouchUpInside];
[self presentViewController:nav animated:YES completion:nil];
}
- (void)dismissDetailVC {
[_detailVC dismissSelf];
}
#pragma mark -tableView添加刷新
-(void)setUpRefresh{
[_tableView.header setTitle:@"下拉刷新" forState:MJRefreshHeaderStateIdle];
[_tableView.header setTitle:@"松开刷新" forState:MJRefreshHeaderStatePulling];
[_tableView.header setTitle:@"正在刷新" forState:MJRefreshHeaderStateRefreshing];
[_tableView.footer setTitle:@"上拉加载" forState:MJRefreshFooterStateIdle];
[_tableView.footer setTitle:@"正在加载" forState:MJRefreshFooterStateRefreshing];
[_tableView.footer setTitle:@"没有更多数据了" forState:MJRefreshFooterStateNoMoreData];
_tableView.header.textColor = [UIColor grayColor];
_tableView.header.font = [UIFont systemFontOfSize:12];
_tableView.footer.textColor = [UIColor grayColor];
_tableView.footer.font = [UIFont systemFontOfSize:12];
[_tableView addLegendHeaderWithRefreshingTarget:self refreshingAction:@selector(headerRefresh)];
[_tableView addLegendFooterWithRefreshingTarget:self refreshingAction:@selector(footerRefresh)];
}
#pragma mark-上拉刷新
-(void)footerRefresh{
if (models) {
[models removeAllObjects];
}
#pragma mark-请求数据
NSString *urlstring = [NSString stringWithFormat:@"%@%@&%@",SEARCH_URL,[searchBar.text stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding],DEVICE_URL];
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager] ;
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", nil];
if (models) {
[models removeAllObjects];
}
[manager GET:urlstring parameters:nil success:^(NSURLSessionDataTask *task, NSDictionary* dic) {
NSArray *array = dic[@"videos"];
[array enumerateObjectsUsingBlock:^(NSDictionary* dic, NSUInteger idx, BOOL *stop) {
SearchModel *searchModel = [SearchModel SearchModelWithDic:dic];
[models addObject:searchModel];
[_tableView reloadData];
[_tableView.footer endRefreshing];
}];
} failure:^(NSURLSessionDataTask *task, NSError *error) {
NSLog(@"error");
}];
}
#pragma mark-下拉刷新
-(void)headerRefresh{
_offset += 21;
NSString *urlstring = [NSString stringWithFormat:@"%@%@&%@",SEARCH_URL,[searchBar.text stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding],DEVICE_URL];
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager] ;
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", nil];
if (models) {
[models removeAllObjects];
}
[manager GET:urlstring parameters:nil success:^(NSURLSessionDataTask *task, NSDictionary* dic) {
NSArray *array = dic[@"videos"];
[array enumerateObjectsUsingBlock:^(NSDictionary* dic, NSUInteger idx, BOOL *stop) {
SearchModel *searchModel = [SearchModel SearchModelWithDic:dic];
[models addObject:searchModel];
[_tableView reloadData];
[_tableView.header endRefreshing ];
}];
} failure:^(NSURLSessionDataTask *task, NSError *error) {
NSLog(@"error");
}];
}
//点击键盘退出
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
[searchBar resignFirstResponder];
// [searchBar endEditing:YES];
}
//创建没有数据的View
-(void)createNoDataView{
_noDataView = [[UIView alloc] initWithFrame:CGRectMake(0, 114, SCREEN_WIDTH, SCREEN_HEIGHT-114)];
_noDataView.backgroundColor = [UIColor whiteColor];
[self.view addSubview:_noDataView];
UILabel *lable = [[UILabel alloc] initWithFrame:CGRectMake(0, 200, SCREEN_WIDTH, 200)];
lable.text = @"您没有输入歌手名字,请重新输入";
lable.textColor = [UIColor magentaColor];
lable.textAlignment = NSTextAlignmentCenter;
lable.font = [UIFont systemFontOfSize:13];
lable.numberOfLines = 0;
[_noDataView addSubview:lable];
}
//定制上面的导航条
-(void)createNavView{
UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(10, 24, 36, 36)];
[button setImage:[UIImage imageNamed:@"yyt_return"] forState:UIControlStateNormal];
[button setImage:[UIImage imageNamed:@"yyt_return_Sel"] forState:UIControlStateHighlighted];
[button addTarget:self action:@selector(backClicked:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:button];
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(SCREEN_WIDTH/2-100, 22, 200, 40)];
label.text = @"搜索";
label.textColor = [UIColor whiteColor];
label.font = [UIFont systemFontOfSize:20];
label.textAlignment = NSTextAlignmentCenter;
[self.view addSubview:label];
}
-(void)backClicked:(UIButton*)button{
[self dismissViewControllerAnimated:YES completion:nil];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
}
- (IBAction)biaoQianbuttonClicked:(UIButton*)sender {
searchBar.text =sender.titleLabel.text;
}
// 设置button标签的外观
-(void)setButtonRadius{
self.button1.layer.cornerRadius = 3;
self.button1.layer.masksToBounds = YES;
self.button2.layer.cornerRadius = 3;
self.button2.layer.masksToBounds = YES;
self.button3.layer.cornerRadius = 3;
self.button3.layer.masksToBounds = YES;
self.button4.layer.cornerRadius = 3;
self.button4.layer.masksToBounds = YES;
self.button5.layer.cornerRadius = 3;
self.button5.layer.masksToBounds = YES;
self.button6.layer.cornerRadius = 3;
self.button6.layer.masksToBounds = YES;
self.button7.layer.cornerRadius = 3;
self.button7.layer.masksToBounds = YES;
self.button8.layer.cornerRadius = 3;
self.button8.layer.masksToBounds = YES;
self.button9.layer.cornerRadius = 3;
self.button9.layer.masksToBounds = YES;
self.button10.layer.cornerRadius = 3;
self.button10.layer.masksToBounds = YES;
self.button11.layer.cornerRadius = 3;
self.button11.layer.masksToBounds = YES;
self.button12.layer.cornerRadius = 3;
self.button12.layer.masksToBounds = YES;
self.button13.layer.cornerRadius = 3;
self.button13.layer.masksToBounds = YES;
self.button14.layer.cornerRadius = 3;
self.button14.layer.masksToBounds = YES;
self.button15.layer.cornerRadius = 3;
self.button15.layer.masksToBounds = YES;
self.button16.layer.cornerRadius = 3;
self.button16.layer.masksToBounds = YES;
self.button17.layer.cornerRadius = 3;
self.button17.layer.masksToBounds = YES;
self.button18.layer.cornerRadius = 3;
self.button18.layer.masksToBounds = YES;
self.button19.layer.cornerRadius = 3;
self.button19.layer.masksToBounds = YES;
self.button20.layer.cornerRadius = 3;
self.button20.layer.masksToBounds = YES;
}
@end
| 26,157
|
https://github.com/tslothorst/hangman-cpp/blob/master/game.cpp
|
Github Open Source
|
Open Source
|
MIT
| null |
hangman-cpp
|
tslothorst
|
C++
|
Code
| 175
| 547
|
#include "game.h"
#include "iostream"
#include "word.h"
#include "gallow.h"
game::game() {
}
game::~game() {
}
void game::play_game() {
word w;
gallow g;
std::string word = w.word_to_guess();
std::cout << "Let's play hangman!\n Guess the word I picked:\n";
int wrong_count = -1;
int word_length = word.length();
std::string board = draw_positions(word_length, word);
std::cout << board;
do {
char guess_letter {};
std::cout << board << "\n";
std::cout << "Enter a letter:";
std::cin >> guess_letter;
if (!check_letter(word,guess_letter)){
++wrong_count;
}
board = draw_positions(word_length, word, guess_letter);
if (wrong_count>=0){
std::cout << g.gallow_drawing(wrong_count);
}
std::cout << board;
} while (wrong_count<11);
}
std::string game::draw_positions(int length, std::string word, char guess) {
std::string temp {};
for (int i = 0; i < length; ++i) {
temp += ".";
}
int position = 0;
for (int i = 0; i < length; ++i) {
if(tolower(guess) == tolower(word.at(i))){
temp.at(i) = toupper(guess);
}
}
return std::string();
}
bool game::check_letter(std::string word, char guess) {
int correct_count = 0;
for (int i = 0; i < word.length(); ++i) {
if(tolower(guess) == tolower(word.at(i))){
++correct_count;
}
}
if (correct_count>0){
return true;
}
return false;
}
| 46,995
|
https://github.com/pstrikos/Pintos/blob/master/src/devices/batch-scheduler.c
|
Github Open Source
|
Open Source
|
MIT-Modern-Variant, LicenseRef-scancode-unknown-license-reference, MIT
| 2,020
|
Pintos
|
pstrikos
|
C
|
Code
| 585
| 1,525
|
/* Tests cetegorical mutual exclusion with different numbers of threads.
* Automatic checks only catch severe problems like crashes.
*/
#include <stdio.h>
#include "tests/threads/tests.h"
#include "threads/malloc.h"
#include "threads/synch.h"
#include "threads/thread.h"
#include "lib/random.h" //generate random numbers
#include "devices/timer.h"
#define BUS_CAPACITY 3
#define SENDER 0
#define RECEIVER 1
#define NORMAL 0
#define HIGH 1
/*
* initialize task with direction and priority
* call o
* */
typedef struct {
int direction;
int priority;
} task_t;
//Global Variables
int TasksOnBus;
int waitersH[2];
int CurrentDirection;
//Condition Variables and Lock
struct condition waitingToGO[2];
struct lock mutex;
void batchScheduler(unsigned int num_tasks_send, unsigned int num_task_receive, unsigned int num_priority_send, unsigned int num_priority_receive);
void senderTask(void *);
void receiverTask(void *);
void senderPriorityTask(void *);
void receiverPriorityTask(void *);
void oneTask(task_t task);/*Task requires to use the bus and executes methods below*/
void getSlot(task_t task); /* task tries to use slot on the bus */
void transferData(task_t task); /* task processes data on the bus either sending or receiving based on the direction*/
void leaveSlot(task_t task); /* task release the slot */
/* initializes semaphores */
void init_bus(void)
{
random_init((unsigned int)123456789);
TasksOnBus = 0;
waitersH[0] = 0;
waitersH[1] = 0;
waitersH[1] = 0;
CurrentDirection = SENDER;
cond_init(&waitingToGO[SENDER]);
cond_init(&waitingToGO[RECEIVER]);
lock_init(&mutex);
}
/*
* Creates a memory bus sub-system with num_tasks_send + num_priority_send
* sending data to the accelerator and num_task_receive + num_priority_receive tasks
* reading data/results from the accelerator.
*
* Every task is represented by its own thread.
* Task requires and gets slot on bus system (1)
* process data and the bus (2)
* Leave the bus (3).
*/
void batchScheduler(unsigned int num_tasks_send, unsigned int num_task_receive,
unsigned int num_priority_send, unsigned int num_priority_receive)
{
unsigned int i;
/* create sender threads */
for(i = 0; i < num_tasks_send; i++)
thread_create("sender_task", 1, senderTask, NULL);
/* create receiver threads */
for(i = 0; i < num_task_receive; i++)
thread_create("receiver_task", 1, receiverTask, NULL);
/* create high priority sender threads */
for(i = 0; i < num_priority_send; i++)
thread_create("prio_sender_task", 1, senderPriorityTask, NULL);
/* create high priority receiver threads */
for(i = 0; i < num_priority_receive; i++)
thread_create("prio_receiver_task", 1, receiverPriorityTask, NULL);
}
/* Normal task, sending data to the accelerator */
void senderTask(void *aux UNUSED){
task_t task = {SENDER, NORMAL};
oneTask(task);
}
/* High priority task, sending data to the accelerator */
void senderPriorityTask(void *aux UNUSED){
task_t task = {SENDER, HIGH};
oneTask(task);
}
/* Normal task, reading data from the accelerator */
void receiverTask(void *aux UNUSED){
task_t task = {RECEIVER, NORMAL};
oneTask(task);
}
/* High priority task, reading data from the accelerator */
void receiverPriorityTask(void *aux UNUSED){
task_t task = {RECEIVER, HIGH};
oneTask(task);
}
/* abstract task execution*/
void oneTask(task_t task) {
getSlot(task);
transferData(task);
leaveSlot(task);
}
/* task tries to get slot on the bus subsystem */
void getSlot(task_t task)
{
lock_acquire(&mutex);
/* wait if cannot go on bridge */
while ((TasksOnBus == BUS_CAPACITY) || (TasksOnBus > 0 && task.direction != CurrentDirection))
{
if (task.priority == HIGH)
{
waitersH[task.direction]++;
}
cond_wait(&waitingToGO[task.direction], &mutex);
if (task.priority == HIGH)
{
waitersH[task.direction]--;
}
}
/* get on the bridge */
TasksOnBus++;
CurrentDirection = task.direction;
lock_release(&mutex);
//thread_yield();
}
/* task processes data on the bus send/receive */
void transferData(task_t task)
{
/* sleep the thread for random amount of time*/
int64_t randomTicks = ((int64_t) random_ulong() % 5) + 1;
timer_sleep(randomTicks);
}
/* task releases the slot */
void leaveSlot(task_t task)
{
lock_acquire(&mutex);
TasksOnBus--;
/* wake the tasks in current direction*/
if (waitersH[CurrentDirection] > 0)
{
cond_signal(&waitingToGO[CurrentDirection], &mutex);
}
/* wake the tasks in current direction*/
else if (TasksOnBus == 0)
{
cond_broadcast(&waitingToGO[1 - CurrentDirection], &mutex);
}
lock_release(&mutex);
}
| 7,866
|
https://github.com/kenshinthebattosai/DotNetAnalytics.Google/blob/master/src/LinqAn.Google/Dimensions/CountryISOCode.cs
|
Github Open Source
|
Open Source
|
MIT
| null |
DotNetAnalytics.Google
|
kenshinthebattosai
|
C#
|
Code
| 76
| 199
|
using System.ComponentModel;
namespace LinqAn.Google.Dimensions
{
/// <summary>
/// The country ISO code of users, derived from IP addresses or Geographical IDs. Values are given as an ISO-3166-1 alpha-2 code.
/// </summary>
[Description("The country ISO code of users, derived from IP addresses or Geographical IDs. Values are given as an ISO-3166-1 alpha-2 code.")]
public class CountryIsoCode: Dimension
{
/// <summary>
/// Instantiates a <seealso cref="CountryIsoCode" />.
/// </summary>
public CountryIsoCode(): base("Country ISO Code",false,"ga:countryIsoCode")
{
}
}
}
| 32,004
|
https://github.com/MironovVadim/vmironov/blob/master/chapter_004/src/test/java/ru/job4j/storage/TrashDecoratorTest.java
|
Github Open Source
|
Open Source
|
Apache-2.0
| null |
vmironov
|
MironovVadim
|
Java
|
Code
| 111
| 400
|
package ru.job4j.storage;
import org.junit.Test;
import ru.job4j.storage.food.Food;
import ru.job4j.storage.food.Fruit;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;
/**
* Test class.
* @author Vadim Moronov (Mironov6292@gmail.ru/Multik6292@mail.ru)
* @version $Id$
* @since 0.1
*/
public class TrashDecoratorTest {
/**
* Test addFood() method.
*/
@Test
public void whenAddReproductedFoodThenGetZeroSizeOfStorage() {
Storage storage = new Trash();
Storage trashDecorator = new TrashDecorator(storage);
long currentTime = System.currentTimeMillis();
long oneDay = 86400000;
Fruit fruit = new Fruit("SomeFruit",
new Date(currentTime - oneDay * 7),
new Date(currentTime - oneDay), 30, 20, true, false);
List<Food> foodList = new ArrayList<>();
foodList.add(fruit);
List<Food> trashFood = trashDecorator.getFoodForStorage(foodList);
trashDecorator.addFood(trashFood);
int result = trashDecorator.getFoodFromStorage().size();
int expected = 0;
assertThat(result, is(expected));
}
}
| 38,268
|
https://github.com/haterzlin/character-sheet/blob/master/src/components/VitalStat.vue
|
Github Open Source
|
Open Source
|
MIT
| 2,021
|
character-sheet
|
haterzlin
|
Vue
|
Code
| 345
| 1,036
|
<script>
/**
* Displays one stat with @param stat.id as a name of stat
* Then @param scale number of points with css style @param stat.style
* And init and fill css style depending on computed @param value while looking
* at @param stat.defaultValue and @param stat.defaultModifier
* @param stat {JSON} displayed object
* @param scale {Number} total number of points, split into groups of five
* @param value {Number} sum of dependency values
*/
export default {
props: { stat: Object, scale: Number, value: Number },
data() {
return {
initialValue: this.stat.value ? this.stat.value : this.finalValue()
};
},
methods: {
/**
* checks if default modifier exists, if not it is zero
* @returns computed modifier(value) + default modifier
*/
finalValue() {
let mod = (this.stat.defaultModifier) ? this.stat.defaultModifier : 0;
return mod + this.value
},
/**
* @returns keyed array of class for a point with value @param valueOfPoint
*/
classOfPoint(valueOfPoint) {
let classOfPoint = {};
classOfPoint[this.stat.style] = true;
classOfPoint['fill'] =
valueOfPoint > this.initialValue && valueOfPoint <= this.finalValue();
classOfPoint['init'] = valueOfPoint <= this.initialValue;
return classOfPoint;
},
},
};
</script>
<template>
<div class="vitalStatBox">
<div class="vitalStatName">{{ stat.id }}:</div>
<div class="vitalStatPoints">
<span v-for="i in scale" :key="i" :class="classOfPoint(i)"> </span>
</div>
</div>
</template>
<style scoped>
.point {
cursor: default;
}
.vitalStatPoints > :nth-child(5n + 0) {
margin-right: 10px;
}
.healthPt,
.willPt {
width: 16px;
height: 20px;
display: inline-block;
vertical-align: middle;
text-align: center;
margin: 1px;
border: 1px;
border-style: solid;
border-color: transparent;
}
.hungerPt,
.humanityPt {
width: 14px;
height: 14px;
border: 1px;
border-style: outset;
display: inline-block;
vertical-align: middle;
text-align: center;
margin: 1px;
}
.healthPt.fill {
background-color: #ff6666;
}
.healthPt.init {
background-color: #cc0000;
color: #999999;
border: 1px;
border-style: outset;
}
.willPt.fill {
background-color: #6666ff;
}
.willPt.init {
background-color: blue;
color: #999999;
border: 1px;
border-style: outset;
}
.humanityPt {
color: #666666;
}
.humanityPt.fill {
background-color: blue;
}
.humanityPt.init {
background-color: black;
color: white;
}
.humanityPt:hover:after,
.healthPt.init:hover:after,
.willPt.init:hover:after {
content: '/';
}
.humanityPt.init:hover:after,
.hungerPt.init:after,
.hungerPt:hover:after {
content: 'X';
}
.hungerPt:hover:after {
color: #666666;
}
.hungerPt.init:hover:after {
color: #999999;
}
.vitalStatBox {
margin: auto;
display: display-block;
margin-bottom: 1ch;
}
.vitalStatName {
font-weight: 600;
}
</style>
| 37,224
|
https://github.com/dev-senior-com-br/senior-sam-node/blob/master/lib/model/lobby/IncidentTypeReactionEmail.ts
|
Github Open Source
|
Open Source
|
MIT
| null |
senior-sam-node
|
dev-senior-com-br
|
TypeScript
|
Code
| 59
| 148
|
import { BaseModel } from '../BaseModel';
export = class IncidentTypeReactionEmail extends BaseModel {
/**
* ID
*/
private _id: number;
private set id(value: number) {
this._id = value;
}
private get id() {
return this._id;
}
/**
* Email
*/
private _email:string;
private set email(value: string) {
this._email = value;
}
private get email() {
return this._email;
}
}
| 24,465
|
https://github.com/sontx/bottle-app/blob/master/app/src/main/java/com/blogspot/sontx/bottle/system/event/ChatChannelChangedEvent.java
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,017
|
bottle-app
|
sontx
|
Java
|
Code
| 15
| 70
|
package com.blogspot.sontx.bottle.system.event;
import com.blogspot.sontx.bottle.model.bean.chat.Channel;
import lombok.Data;
@Data
public class ChatChannelChangedEvent {
private Channel channel;
}
| 26,773
|
https://github.com/maze/go-gtfs-api/blob/master/shapes.go
|
Github Open Source
|
Open Source
|
MIT
| 2,013
|
go-gtfs-api
|
maze
|
Go
|
Code
| 117
| 376
|
package main
import (
"menteslibres.net/gosexy/db"
)
type Shape struct {
ShapeId string `field:"shape_id"`
PtSequence int `field:"shape_pt_sequence"`
DistTraveled float64 `field:"shape_dist_traleved"`
PtLat float64 `field:"shape_pt_lat"`
PtLon float64 `field:"shape_pt_lon"`
}
const ShapeCollection = `shapes`
type ShapeApi struct {
C db.Collection
DB db.Database
}
func (self *ShapeApi) List(ShapeId string) ([]Shape, error) {
return self.query(db.Cond{"shape_id": ShapeId})
}
func (self *ShapeApi) query(conds db.Cond) ([]Shape, error) {
var shapes []Shape
count, err := self.C.Count(conds)
shapes = make([]Shape, 0, count)
q, err := self.C.Query(conds)
if err != nil {
return nil, err
}
for {
shape := Shape{}
err := q.Next(&shape)
if err != nil {
if err != db.ErrNoMoreRows {
return nil, err
}
break
}
shapes = append(shapes, shape)
}
return shapes, nil
}
| 26,817
|
https://github.com/y-spreen/NativeScript-Status-Bar/blob/master/sample/StatusBarSample/typings/tns-core-modules/ui/styling/stylers.d.ts
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,020
|
NativeScript-Status-Bar
|
y-spreen
|
TypeScript
|
Code
| 8
| 27
|
declare module "ui/styling/stylers" {
export function _registerDefaultStylers();
}
| 23,767
|
https://github.com/cancervariants/variation-normalization/blob/master/variation/validators/single_nucleotide_variation_base.py
|
Github Open Source
|
Open Source
|
MIT
| 2,023
|
variation-normalization
|
cancervariants
|
Python
|
Code
| 830
| 2,363
|
"""The module for Single Nucleotide Variation Validation."""
from typing import List, Dict, Optional
import logging
from ga4gh.vrsatile.pydantic.vrs_models import CopyChange
from variation.schemas.app_schemas import Endpoint
from variation.schemas.classification_response_schema import Classification, \
ClassificationType
from variation.schemas.token_response_schema import Token, GeneToken
from variation.schemas.normalize_response_schema\
import HGVSDupDelMode as HGVSDupDelModeEnum
from .validator import Validator
logger = logging.getLogger("variation")
logger.setLevel(logging.DEBUG)
class SingleNucleotideVariationBase(Validator):
"""The Single Nucleotide Variation Validator Base class."""
def is_token_instance(self, t: Token) -> bool:
"""Check to see if token is instance of a token type.
:param Token t: Classification token to find type of
:return: `True` if token is instance of class token. `False` otherwise.
"""
raise NotImplementedError
def variation_name(self) -> str:
"""Return the variation name.
:return: variation class name
"""
raise NotImplementedError
def get_gene_tokens(
self, classification: Classification) -> List[GeneToken]:
"""Return a list of gene tokens for a classification.
:param Classification classification: Classification for a list of
tokens
:return: A list of gene tokens for the classification
"""
raise NotImplementedError
async def get_transcripts(self, gene_tokens: List, classification: Classification,
errors: List) -> Optional[List[str]]:
"""Get transcript accessions for a given classification.
:param List gene_tokens: A list of gene tokens
:param Classification classification: A classification for a list of
tokens
:param List errors: List of errors
:return: List of transcript accessions
"""
raise NotImplementedError
def validates_classification_type(
self, classification_type: ClassificationType) -> bool:
"""Check that classification type can be validated by validator.
:param ClassificationType classification_type: The type of variation
:return: `True` if classification_type matches validator's
classification type. `False` otherwise.
"""
raise NotImplementedError
async def get_valid_invalid_results(
self, classification_tokens: List, transcripts: List,
classification: Classification, results: List, gene_tokens: List,
mane_data_found: Dict, is_identifier: bool,
hgvs_dup_del_mode: HGVSDupDelModeEnum,
endpoint_name: Optional[Endpoint] = None,
baseline_copies: Optional[int] = None,
copy_change: Optional[CopyChange] = None,
do_liftover: bool = False
) -> None:
"""Add validation result objects to a list of results.
:param List classification_tokens: A list of classification Tokens
:param List transcripts: A list of transcript accessions
:param Classification classification: A classification for a list of
tokens
:param List results: Stores validation result objects
:param List gene_tokens: List of GeneMatchTokens for a classification
:param Dict mane_data_found: MANE Transcript information found
:param bool is_identifier: `True` if identifier is given for exact
location. `False` otherwise.
:param HGVSDupDelModeEnum hgvs_dup_del_mode: Must be: `default`,
`copy_number_count`, `copy_number_change`, `repeated_seq_expr`,
`literal_seq_expr`. This parameter determines how to represent HGVS dup/del
expressions as VRS objects.
:param Optional[Endpoint] endpoint_name: Then name of the endpoint being used
:param Optional[int] baseline_copies: Baseline copies number
:param Optional[CopyChange] copy_change: The copy change
:param bool do_liftover: Whether or not to liftover to GRCh38 assembly
"""
raise NotImplementedError
async def silent_mutation_valid_invalid_results(
self, classification_tokens: List, transcripts: List,
classification: Classification, results: List, gene_tokens: List,
endpoint_name: Optional[Endpoint], mane_data_found: Dict,
is_identifier: bool, do_liftover: bool = False) -> None:
"""Add validation result objects to a list of results for
Silent Mutations.
:param List classification_tokens: A list of classification Tokens
:param List transcripts: A list of transcript accessions
:param Classification classification: A classification for a list of
tokens
:param List results: Stores validation result objects
:param List gene_tokens: List of GeneMatchTokens for a classification
:param Optional[Endpoint] endpoint_name: Then name of the endpoint being used
:param Dict mane_data_found: MANE Transcript information found
:param bool is_identifier: `True` if identifier is given for exact
location. `False` otherwise.
:param bool do_liftover: Whether or not to liftover to GRCh38 assembly
"""
valid_alleles = list()
for s in classification_tokens:
for t in transcripts:
errors = list()
t = self.get_accession(t, classification)
allele = None
if s.coordinate_type == "c":
cds_start_end = await self.uta.get_cds_start_end(t)
if not cds_start_end:
cds_start = None
errors.append(
f"Unable to find CDS start for accession : {t}"
)
else:
cds_start = cds_start_end[0]
else:
cds_start = None
if not errors:
allele = self.vrs.to_vrs_allele(
t, s.position, s.position, s.coordinate_type,
s.alt_type, errors, cds_start=cds_start,
alt=s.new_nucleotide
)
if not errors:
sequence, w = self.seqrepo_access.get_reference_sequence(
t, s.position)
if sequence is None:
errors.append(w)
else:
if s.ref_nucleotide:
if sequence != s.ref_nucleotide:
errors.append(
f"Expected {s.coordinate_type} but "
f"found {sequence}")
if not errors:
if endpoint_name == Endpoint.NORMALIZE:
mane = await self.mane_transcript.get_mane_transcript(
t, s.position, s.coordinate_type, end_pos=s.position,
gene=gene_tokens[0].token if gene_tokens else None,
try_longest_compatible=True)
self.add_mane_data(mane, mane_data_found, s.coordinate_type,
s.alt_type, s)
elif endpoint_name == Endpoint.TO_CANONICAL and do_liftover:
await self._liftover_genomic_data(
gene_tokens, t, s, errors, valid_alleles, results,
classification)
self.add_validation_result(allele, valid_alleles, results,
classification, s, t, gene_tokens, errors)
if is_identifier:
break
if endpoint_name == Endpoint.NORMALIZE:
self.add_mane_to_validation_results(mane_data_found, valid_alleles, results,
classification, gene_tokens)
async def _liftover_genomic_data(
self, gene_tokens: List, t: str, s: Token, errors: List, valid_alleles: List,
results: List, classification: Classification
) -> None:
"""Add liftover data to validation results
Currently only works for HGVS expressions.
:param List gene_tokens: List of GeneMatchTokens for a classification
:param str t: Accession
:param Token s: Classification token
:param List errors: List of errors
:param List valid_alleles: List of valid alleles
:param List results: List of results data
:param Classification classification: A classification for a list of tokens
"""
if not gene_tokens:
if not self._is_grch38_assembly(t):
grch38 = await self.mane_transcript.g_to_grch38(t, s.position,
s.position)
else:
grch38 = dict(ac=t, pos=(s.position, s.position))
await self.add_genomic_liftover_to_results(
grch38, errors, s.new_nucleotide, valid_alleles, results,
classification, s, t, gene_tokens)
def check_ref_nucleotide(self, actual_ref_nuc: str, expected_ref_nuc: str,
position: int, t: str, errors: List) -> None:
"""Assert that ref_nuc matches s.ref_nucleotide."""
if actual_ref_nuc != expected_ref_nuc:
errors.append(f"Needed to find {expected_ref_nuc} at position {position} "
f"on {t} but found {actual_ref_nuc}")
| 7,288
|
https://github.com/JCCR/readium-js-viewer/blob/master/lib/versioning/UnpackagedVersioning.js
|
Github Open Source
|
Open Source
|
BSD-3-Clause
| 2,016
|
readium-js-viewer
|
JCCR
|
JavaScript
|
Code
| 86
| 336
|
define(['jquery', 'Readium'], function($, Readium){
var UnpackagedVersioning = {
getVersioningInfo: function(callback){
var obj = {
release: false,
clean: false,
devMode: true
}
var readiumVersion = Readium.version,
versionInfo = {};
versionInfo.viewer = obj;
versionInfo.readiumJs = readiumVersion.readiumJs;
versionInfo.readiumSharedJs = readiumVersion.readiumSharedJs;
$.get('package.json', function(data){
obj.version = data.version;
obj.chromeVersion = '2.' + data.version.substring(2);
if (obj.sha){
callback(versionInfo);
}
})
$.get('.git/HEAD', function(data){
var ref = data.substring(5, data.length - 1);
$.get('.git/' + ref, function(data){
var sha = data.substring(0, data.length - 1);
obj.sha = sha;
if (obj.version){
callback(versionInfo)
}
})
});
}
}
return UnpackagedVersioning;
});
| 29,627
|
https://github.com/ali5ter/vmware_scripts/blob/master/tmc/terraform/standup/.gitignore
|
Github Open Source
|
Open Source
|
MIT
| 2,023
|
vmware_scripts
|
ali5ter
|
Ignore List
|
Code
| 4
| 14
|
.terraform*
variables*
plan
terraform*
| 23,020
|
https://github.com/Horpey/diabPredict-timi/blob/master/src/pages/dashboard/Diagnose.vue
|
Github Open Source
|
Open Source
|
MIT
| null |
diabPredict-timi
|
Horpey
|
Vue
|
Code
| 700
| 3,182
|
<template>
<div class>
<div class="mt-2">
<div class="row">
<div class="col-md-7">
<div class="card" style="min-height: 494px;">
<div class="card-body mx-3">
<router-link to="/dashboard/patients" class="text-dark">
<span class="fa fa-arrow-left mr-2" style="font-size: 14px;"></span>
<span class="pt-1">Back</span>
</router-link>
<h3 class="text-capitalize font-weight-bold mb-3">Diagnosis</h3>
<hr />
<form @submit.prevent="makeDiagnose">
<div class="row">
<div class="col-md-6">
<div class="form-group cardform">
<label for="bs_fast">
Blood Sugar (Before Meal)
<span class="fa fa-info-circle ml-2"></span>
</label>
<input required v-model="bs_fast" id="bs_fast" value class="form-control" />
</div>
</div>
<div class="col-md-6">
<div class="form-group cardform">
<label for="afterMeal">
Blood Sugar (After Meal)
<span class="fa fa-info-circle ml-2"></span>
</label>
<input required v-model="bs_pp" id="afterMeal" value class="form-control" />
</div>
</div>
<div class="col-md-6">
<div class="form-group cardform">
<label for="plasma">
Plasma Glucose
<span class="fa fa-info-circle ml-2"></span>
</label>
<input required v-model="plasma_r" id="plasma" value class="form-control" />
</div>
</div>
<div class="col-md-6">
<div class="form-group cardform">
<label for="plasmam">
Plasma Glucose (Morning)
<span class="fa fa-info-circle ml-2"></span>
</label>
<input required v-model="plasma_f" id="plasmam" value class="form-control" />
</div>
</div>
<div class="col-md-6">
<div class="form-group cardform">
<label for="HbA1c">
HbA1c
<span class="fa fa-info-circle ml-2"></span>
</label>
<input required v-model="hbA1c" id="HbA1c" value class="form-control" />
</div>
</div>
</div>
<div class="form-group mt-3">
<button :disabled="btndisable" type="submit" class="btn btn-dark btn-lg">
Make
Diagnosis
<img
v-if="rloading"
class="ml-2"
src="/img/loaderlight.svg"
alt="logo"
height="20"
/>
</button>
</div>
</form>
</div>
</div>
</div>
<div class="col-md-5">
<div class="card">
<div class="card-body" style="min-height: 495px;">
<h3 class="text-capitalize text-center font-weight-bold mb-3">Report</h3>
<div class="ml-loading" v-if="mlloading">
<div class="w-100 text-center text-light">
<svg
class="gear"
style="width:64px"
xmlns="http://www.w3.org/2000/svg"
viewBox="0 0 100 100"
>
<path
id="p"
fill="#064dc8"
d="M94.1 58.8c.6-2.8.9-5.8.9-8.8s-.3-6-.9-8.8l-11.7-.4c-.7-2.6-1.7-5-3-7.3l8-8.5c-3.3-4.9-7.5-9.2-12.5-12.5l-8.5 8c-2.3-1.3-4.7-2.3-7.3-3l-.3-11.6C56 5.3 53 5 50 5s-6 .3-8.8.9l-.4 11.7c-2.6.7-5 1.7-7.3 3l-8.5-8c-4.9 3.3-9.2 7.5-12.5 12.5l8 8.5c-1.3 2.3-2.3 4.7-3 7.3l-11.6.3C5.3 44 5 47 5 50s.3 6 .9 8.8l11.7.4c.7 2.6 1.7 5 3 7.3l-8 8.5c3.3 4.9 7.5 9.2 12.5 12.5l8.5-8c2.3 1.3 4.7 2.3 7.3 3l.4 11.7c2.7.5 5.7.8 8.7.8s6-.3 8.8-.9l.4-11.7c2.6-.7 5-1.7 7.3-3l8.5 8c4.9-3.3 9.2-7.5 12.5-12.5l-8-8.5c1.3-2.3 2.3-4.7 3-7.3l11.6-.3zM50 66.9c-9.3 0-16.9-7.6-16.9-16.9S40.7 33.1 50 33.1 66.9 40.7 66.9 50 59.3 66.9 50 66.9z"
/>
</svg>
<svg
class="gear"
style="width:64px;margin:64px 0 0 -12px;animation-direction:reverse"
xmlns="http://www.w3.org/2000/svg"
viewBox="0 0 100 100"
>
<use href="#p" />
</svg>
<h5 class="font-weight-bold mt-2 mb-0 text-black">Please wait..</h5>
<div class="text-muted">Our ML Engine is processing the data.</div>
</div>
</div>
<div class v-else>
<table class="table">
<tbody>
<tr>
<th>Time of check</th>
<th>Blood sugar level</th>
</tr>
<tr>
<td>Fasting or before breakfast</td>
<td class="text-info">{{reportData.bl1}} mg/dl</td>
</tr>
<tr>
<td>2 hours after meal</td>
<td class="text-danger">{{reportData.bl2}} mg/dl</td>
</tr>
<tr>
<td>Plasma Glucose (any Time)</td>
<td class="text-info">{{reportData.pl1}} mmol/L</td>
</tr>
<tr>
<td>Plasma Glucose (Morning)</td>
<td class="text-danger">{{reportData.bl2}} mmol/L</td>
</tr>
</tbody>
</table>
<table class="table">
<tbody>
<tr>
<th class="text-info">Diabetic Status</th>
<th>{{reportData.ds}}</th>
</tr>
<tr>
<th class="text-info">Diabetic Type</th>
<th>{{reportData.dt}}</th>
</tr>
</tbody>
</table>
<div class="text-right">
<p
v-if="sendingdb"
class="font-weight-bold d-inline-block mr-3"
>Sending Data to Database...</p>
<a href="#" class="btn btn-outline-primary text-dark">
<span class="fa fa-file-download mr-2"></span>
Download Report
</a>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</template>
<script>
export default {
name: "diagnose",
bodyClass: "",
components: {},
data() {
return {
rloading: false,
mlloading: false,
btndisable: false,
patientID: "",
age: "",
bs_fast: "",
bs_pp: "",
plasma_r: "",
plasma_f: "",
hbA1c: "",
sendingdb: false,
reportData: {
patientID: "",
bl1: "",
bl2: "",
pl1: "",
pl2: "",
hba1c: "",
ds: "",
dt: ""
}
};
},
methods: {
makeDiagnose() {
let patientID = this.patientID;
let age = this.age;
let bs_fast = this.bs_fast;
let bs_pp = this.bs_pp;
let plasma_r = this.plasma_r;
let plasma_f = this.plasma_f;
let hbA1c = this.hbA1c;
this.mlloading = true;
this.btndisable = true;
this.rloading = true;
this.$store
.dispatch("makeDiagnosis", {
age,
bs_fast,
bs_pp,
plasma_r,
plasma_f,
hbA1c
})
.then(resp => {
this.rloading = false;
this.btndisable = false;
this.mlloading = false;
this.reportData.bl1 = this.bs_fast;
this.reportData.bl2 = this.bs_pp;
this.reportData.pl1 = this.plasma_r;
this.reportData.pl2 = this.plasma_f;
this.reportData.hba1c = this.hbA1c;
this.reportData.patientID = this.$route.params.id;
if (resp.data.prediction == "Normal") {
this.reportData.ds = "negative";
this.reportData.dt = "";
} else {
this.reportData.ds = "positive";
this.reportData.dt = resp.data.prediction;
}
console.log(this.reportData);
this.sendtoDB();
})
.catch(err => {
this.rloading = false;
this.mlloading = false;
this.btndisable = false;
this.$toast.error("Unable to make diagnosis, Please try again");
});
},
sendtoDB() {
console.log(this.reportData);
this.sendingdb = true;
let reportdat = this.reportData;
this.$store
.dispatch("senttoDB", reportdat)
.then(resp => {
console.log(resp);
this.sendingdb = false;
})
.catch(err => {
this.sendingdb = false;
});
}
},
mounted() {
let patientId = this.$route.params.id;
let patientDob = this.$route.query.dob;
var moment = require("moment");
this.age = moment(patientDob)
.fromNow(true)
.replace(" years", "");
// console.log(this.age);
}
};
</script>
<style>
@keyframes r {
0% {
transform: rotate(0deg);
}
100% {
transform: rotate(45deg);
}
}
#splash {
transition: all 0.3s linear;
}
#splash.hidden {
opacity: 0;
z-index: -1;
visibility: hidden;
}
svg.gear {
animation: r 0.5s infinite linear;
}
</style>
<style lang="scss" scoped>
@import "../../assets/scss/dashboard/index.scss";
</style>
| 49,555
|
https://github.com/hasinilmalik/ANITA/blob/master/application/models/M_kategori.php
|
Github Open Source
|
Open Source
|
MIT
| 2,020
|
ANITA
|
hasinilmalik
|
PHP
|
Code
| 53
| 217
|
<?php
class M_kategori extends CI_Model{
function get_kategori(){
$hasil=$this->db->query("SELECT * FROM kelas");
return $hasil;
}
function get_subkategori($id){
$hasil=$this->db->query("SELECT * FROM siswa WHERE id_kelas='$id'");
return $hasil->result();
}
function get_kategorievaluasi(){
$hasil=$this->db->query("SELECT * FROM kategori");
return $hasil;
}
function get_juz(){
$hasil=$this->db->query("SELECT * FROM juz");
return $hasil;
}
function get_surat(){
$hasil=$this->db->query("SELECT * FROM surat");
return $hasil;
}
}
| 2,938
|
https://github.com/jamesjefferies/energy-sparks_analytics/blob/master/lib/dashboard/aggregation/amr_data.rb
|
Github Open Source
|
Open Source
|
MIT
| null |
energy-sparks_analytics
|
jamesjefferies
|
Ruby
|
Code
| 1,094
| 4,097
|
require_relative '../half_hourly_data'
require_relative '../half_hourly_loader'
class AMRData < HalfHourlyData
attr_reader :economic_tariff, :accounting_tariff, :grid_carbon, :carbon_emissions
def initialize(type)
super(type)
@lock_updates = false
end
def set_economic_tariff(meter_id, fuel_type, default_energy_purchaser)
@economic_tariff = EconomicCosts.create_costs(meter_id, self, fuel_type, default_energy_purchaser)
end
def set_accounting_tariff(meter_id, fuel_type, default_energy_purchaser)
@accounting_tariff = AccountingCosts.create_costs(meter_id, self, fuel_type, default_energy_purchaser)
end
def set_economic_tariff_schedule(tariff)
@economic_tariff = tariff
end
def set_accounting_tariff_schedule(tariff)
@accounting_tariff = tariff
end
# only accessed for combined meters, where calculation is the summation of 'sub' meters
def set_carbon_schedule(co2)
@carbon_emissions = co2
end
# access point for single meters, not combined meters
def set_carbon_emissions(meter_id_for_debug, flat_rate, grid_carbon)
@grid_carbon = grid_carbon # needed for updates
@carbon_emissions = CarbonEmissions.create_carbon_emissions(meter_id_for_debug, self, flat_rate, grid_carbon)
@lock_updates = true
end
def add(date, one_days_data)
throw EnergySparksUnexpectedStateException.new('Updates locked - no updates allowed') if @lock_updates
throw EnergySparksUnexpectedStateException.new('AMR Data must not be nil') if one_days_data.nil?
throw EnergySparksUnexpectedStateException.new("AMR Data now held as OneDayAMRReading not #{one_days_data.class.name}") unless one_days_data.is_a?(OneDayAMRReading)
throw EnergySparksUnexpectedStateException.new("AMR Data date mismatch not #{date} v. #{one_days_data.date}") if date != one_days_data.date
set_min_max_date(date)
self[date] = one_days_data
@cache_days_totals.delete(date)
end
def delete(date)
super(date)
@cache_days_totals.delete(date)
end
def data(date, halfhour_index)
throw EnergySparksUnexpectedStateException.new('Deprecated call to amr_data.data()')
end
def days_kwh_x48(date, type = :kwh)
kwhs = self[date].kwh_data_x48
return kwhs if type == :kwh
return @economic_tariff.days_cost_data_x48(date) if type == :£ || type == :economic_cost
return @accounting_tariff.days_cost_data_x48(date) if type == :accounting_cost
return @carbon_emissions.one_days_data_x48(date) if type == :co2
end
def self.fast_multiply_x48_x_x48(a, b)
c = Array.new(48, 0.0)
(0..47).each { |x| c[x] = a[x] * b[x] }
c
end
def self.fast_add_x48_x_x48(a, b)
c = Array.new(48, 0.0)
(0..47).each { |x| c[x] = a[x] + b[x] }
c
end
def self.fast_add_multiple_x48_x_x48(list)
c = Array.new(48, 0.0)
list.each do |data_x48|
c = fast_add_x48_x_x48(c, data_x48)
end
c
end
def self.fast_multiply_x48_x_scalar(a, scalar)
a.map { |v| v * scalar }
end
def set_days_kwh_x48(date, days_kwh_data_x48)
self[date].set_days_kwh_x48(days_kwh_data_x48)
end
def kwh(date, halfhour_index, type = :kwh)
return self[date].kwh_halfhour(halfhour_index) if type == :kwh
return @economic_tariff.cost_data_halfhour(date, halfhour_index) if type == :£ || type == :economic_cost
return @accounting_tariff.cost_data_halfhour(date, halfhour_index) if type == :accounting_cost
return @carbon_emissions.one_days_data_x48(date)[halfhour_index] if type == :co2
end
def set_kwh(date, halfhour_index, kwh)
self[date].set_kwh_halfhour(halfhour_index, kwh)
end
def add_to_kwh(date, halfhour_index, kwh)
self[date].set_kwh_halfhour(halfhour_index, kwh + kwh(date, halfhour_index))
end
def one_day_kwh(date, type = :kwh)
return self[date].one_day_kwh if type == :kwh
return @economic_tariff.one_day_total_cost(date) if type == :£ || type == :economic_cost
return @accounting_tariff.one_day_total_cost(date) if type == :accounting_cost
return @carbon_emissions.one_day_total(date) if type == :co2
end
def clone_one_days_data(date)
self[date].deep_dup
end
# called from inherited half_hourly)data.one_day_total(date), shouldn't use generally
def one_day_total(date, type = :kwh)
one_day_kwh(date, type)
end
def total(type = :kwh)
t = 0.0
(start_date..end_date).each do |date|
t += one_day_kwh(date, type)
end
t
end
def kwh_date_range(date1, date2, type = :kwh)
return one_day_kwh(date1, type) if date1 == date2
total_kwh = 0.0
(date1..date2).each do |date|
total_kwh += one_day_kwh(date, type)
end
total_kwh
end
def kwh_period(period)
kwh_date_range(period.start_date, period.end_date)
end
def average_in_date_range(date1, date2, type = :kwh)
kwh_date_range(date1, date2, type) / (date2 - date1 + 1)
end
def average_in_date_range_ignore_missing(date1, date2, type = :kwh)
kwhs = []
(date1..date2).each do |date|
kwhs.push(one_day_kwh(date, type)) if date_exists?(date)
end
kwhs.empty? ? 0.0 : (kwhs.inject(:+) / kwhs.length)
end
def kwh_date_list(dates, type = :kwh)
total_kwh = 0.0
dates.each do |date|
total_kwh += one_day_kwh(date, type)
end
total_kwh
end
def baseload_kw(date)
statistical_baseload_kw(date)
end
def overnight_baseload_kw(date)
raise EnergySparksNotEnoughDataException.new("Missing electric data (2) for #{date}") if !self.key?(date)
baseload_kw_between_half_hour_indices(date, 41, 47)
end
def average_overnight_baseload_kw_date_range(date1, date2)
overnight_baseload_kwh_date_range(date1, date2) / (date2 - date1 + 1)
end
def overnight_baseload_kwh_date_range(date1, date2)
total = 0.0
(date1..date2).each do |date|
raise EnergySparksNotEnoughDataException.new("Missing electric data for #{date}") if !self.key?(date)
total += overnight_baseload_kw(date)
end
total
end
def baseload_kw_between_half_hour_indices(date, hhi1, hhi2)
total_kwh = 0.0
count = 0
if hhi2 > hhi1 # same day
(hhi1..hhi2).each do |halfhour_index|
total_kwh += kwh(date, halfhour_index)
count += 1
end
else
(hhi1..48).each do |halfhour_index| # before midnight
total_kwh += kwh(date, halfhour_index)
count += 1
end
(0..hhi2).each do |halfhour_index| # after midnight
total_kwh += kwh(date, halfhour_index)
count += 1
end
end
total_kwh * 2.0 / count
end
# alternative heuristic for baseload calculation (for storage heaters)
# find the average of the bottom 8 samples (4 hours) in a day
def statistical_baseload_kw(date)
days_data = days_kwh_x48(date) # 48 x 1/2 hour kWh
sorted_kwh = days_data.clone.sort
lowest_sorted_kwh = sorted_kwh[0..7]
average_kwh = lowest_sorted_kwh.inject { |sum, el| sum + el }.to_f / lowest_sorted_kwh.size
average_kwh * 2.0 # convert to kW
end
def statistical_peak_kw(date)
days_data = days_kwh_x48(date) # 48 x 1/2 hour kWh
sorted_kwh = days_data.clone.sort
highest_sorted_kwh = sorted_kwh[45..47]
average_kwh = highest_sorted_kwh.inject { |sum, el| sum + el }.to_f / highest_sorted_kwh.size
average_kwh * 2.0 # convert to kW
end
def average_baseload_kw_date_range(date1, date2)
baseload_kwh_date_range(date1, date2) / (date2 - date1 + 1)
end
def baseload_kwh_date_range(date1, date2)
total = 0.0
(date1..date2).each do |date|
total += baseload_kw(date)
end
total
end
def self.create_empty_dataset(type, start_date, end_date)
data = AMRData.new(type)
(start_date..end_date).each do |date|
data.add(date, OneDayAMRReading.new('Unknown', date, 'ORIG', nil, DateTime.now, Array.new(48, 0.0)))
end
data
end
# long gaps are demarked by a single LGAP meter reading - the last day of the gap
# data held in the database doesn't store the date as part of its meta data so its
# set here by calling this function after all meter readings are loaded
def set_long_gap_boundary
override_start_date = nil
override_end_date = nil
(start_date..end_date).each do |date|
one_days_data = self[date]
override_start_date = date if !one_days_data.nil? && (one_days_data.type == 'LGAP' || one_days_data.type == 'FIXS')
override_end_date = date if !one_days_data.nil? && one_days_data.type == 'FIXE'
end
unless override_start_date.nil?
logger.info "Overriding start_date of amr data from #{self.start_date} to #{override_start_date}"
set_min_date(override_start_date)
end
unless override_end_date.nil?
logger.info "Overriding end_date of amr data from #{self.end_date} to #{override_end_date}"
set_max_date(override_end_date) unless override_end_date.nil?
end
end
def summarise_bad_data
date, one_days_data = self.first
logger.info '=' * 80
logger.info "Bad data for meter #{one_days_data.meter_id}"
logger.info "Valid data between #{start_date} and #{end_date}"
key, _value = self.first
if key < start_date
logger.info "Ignored data between #{key} and #{start_date} - because of long gaps"
end
bad_data_stats = bad_data_count
percent_bad = 100.0
if bad_data_count.key?('ORIG')
percent_bad = (100.0 * (length - bad_data_count['ORIG'].length)/length).round(1)
end
logger.info "bad data summary: #{percent_bad}% substituted"
bad_data_count.each do |type, dates|
type_description = sprintf('%-60.60s', OneDayAMRReading::AMR_TYPES[type][:name])
logger.info " #{type}: #{type_description} * #{dates.length}"
if type != 'ORIG'
cpdp = CompactDatePrint.new(dates)
cpdp.log
end
end
end
# take one set (dd_data) of half hourly data from self
# - avoiding performance hit of taking a copy
# caller expected to ensure start and end dates reasonable
def minus_self(dd_data, min_value = nil)
sd = start_date > dd_data.start_date ? start_date : dd_data.start_date
ed = end_date < dd_data.end_date ? end_date : dd_data.end_date
(sd..ed).each do |date|
(0..47).each do |halfhour_index|
updated_kwh = kwh(date, halfhour_index) - dd_data.kwh(date, halfhour_index)
if min_value.nil?
set_kwh(date, halfhour_index, updated_kwh)
else
set_kwh(date, halfhour_index, updated_kwh > min_value ? updated_kwh : min_value)
end
end
end
end
private
# go through amr_data creating 'histogram' of type of amr_data by type (original data v. substituted)
# returns {type} = [list of dates of that type]
def bad_data_count
bad_data_type_count = {}
(start_date..end_date).each do |date|
one_days_data = self[date]
unless bad_data_type_count.key?(one_days_data.type)
bad_data_type_count[one_days_data.type] = []
end
bad_data_type_count[one_days_data.type].push(date)
end
bad_data_type_count
end
end
| 42,258
|
https://github.com/sasa27/Domoticz-Heatpump-Thermostat/blob/master/ThermostatRoom.lua
|
Github Open Source
|
Open Source
|
MIT
| null |
Domoticz-Heatpump-Thermostat
|
sasa27
|
Lua
|
Code
| 871
| 2,918
|
--thermostat for heat pump / AC
-- heat only
-- variables to edit ------
--------------------------------
local debugging = false --pour voir les logs dans la console log Dz ou false pour ne pas les voir
local fixedTemp = 'thermostat' --domoticz button thermostat, used with force mode
local mode ='selector' --domoticz button mode choosen
local automode='Room-Auto-Cal' -- selector button with planning allowing to manage the auto mode
-- holidays
local holidaybool=true -- checks if today is a holyday
local automodeH='Room-Auto-Cal-Holidays' -- special Selector for planning management, for holidays (and school holidays), leave blanck if no required
local holivar='holiday' -- domoticz var affected to decimal 1-> true 0-> false no holiday today
--user present
local presentbool=false --special mode if someone is inside and if eco ->change to confort
local presence = '' --Pir check if someone is inside if eco change to confort
local presencefirst='presencefirstRoom' --for starting to count the PIr occurences
local presencecount='presencecountRoom' -- count the pir occurences during 3 minutes
local prestime=30 --time during which user is present after detecttion in minutes
--heatpump
local HeatpumpMode='ACModeRoom' -- dummy selector for changing HT mode
local heatpumpT='ACTempRoom' -- dummy thermostat for setting/ storing its assigned temperature
local HeatPumpTidx='1900'
--temperatures w.r.t. modes
local fixedtemp = {
Eco = 16.0;
Frostfree= 12.0;
Comfort=19;
Auto = 0.0;
Off=0.0;
}
local hysteresis = 0.5 -- theshold value
local triggerHeat=0.5 -- threshold value for starting/stopping heat pump
--sensors
local tsensor='TempHum int'; --for one sensor onlyæ
local tmode=2; -- 1 = 1 temperature sensor; 2= humidity/temperature combined sensor
local CurrentHPMode=otherdevices[HeatpumpMode];
local CurrentHPT = tonumber(string.sub(otherdevices_svalues[heatpumpT],1,5));
function see_logs (s)
if (debugging ) then
s=automode .. ":".. s
print ("<font color='#f3031d'>".. s .."</font>");
end
return
end
function timedifference(s)
local year = string.sub(s, 1, 4)
local month = string.sub(s, 6, 7)
local day = string.sub(s, 9, 10)
local hour = string.sub(s, 12, 13)
local minutes = string.sub(s, 15, 16)
local seconds = string.sub(s, 18, 19)
local t1 = os.time()
local t2 = os.time{year=year, month=month, day=day, hour=hour, min=minutes, sec=seconds}
local di = os.difftime (t1, t2)
return di
end
--change heat pump state, state=on;off;minus,plus, t=temperature;
function heatpump(state,t)
local modes = {
Off=0;
Auto=10;
Heat=20;
Cool=30;
Dry=40;
Fan=50;
Turbo=60;
};
if CurrentHPMode ~=state then
commandArray[HeatpumpMode]='Set Level '..modes[state];
CurrentHPMode=state
see_logs('Thermostat: HeatPump changing state: '..state);
end
if (CurrentHPT ~= t) then
--commandArray['UpdateDevice']=HeatPumpTidx..'|0|'..t;
commandArray['OpenURL'] = 'http://127.0.0.1:8080/json.htm?type=command¶m=udevice&idx='.. HeatPumpTidx .. '&nvalue=0&svalue=' .. tostring(t)
see_logs('Thermostat: HeatPump changing temp: '..t);
CurrentHPT=t
end
return
end
commandArray = {}
--test user Variable
if(uservariables[presencefirst] == nil) then
noBlankDomoticz_Devicename = string.gsub(presencefirst, " ", "+")
commandArray['OpenURL'] = 'http://127.0.0.1:8080/json.htm?type=command¶m=saveuservariable&vname='.. noBlankDomoticz_Devicename..'&vtype=2&vvalue=1';
--json.htm?type=command¶m=saveuservariable&vname=uservariablename&vtype=uservariabletype&vvalue=uservariablevalue
see_logs('add variable '..presencefirst);
end
if(uservariables[presencecount] == nil) then
noBlankDomoticz_Devicename = string.gsub(presencecount, " ", "+")
commandArray['OpenURL'] = 'http://localhost:8080/json.htm?type=command¶m=saveuservariable&vname='..noBlankDomoticz_Devicename..'&vtype=0&vvalue=0';
see_logs('add variable '.. presencecount);
end
--test offline
if (devicechanged[mode]=='Off') and CurrentHPMode ~='Off' then
see_logs("Thermostat: shutdown");
heatpump('Off',CurrentHPT);
return commandArray;
end
local Temp
see_logs('Current Ac mode: '..CurrentHPMode);
--check sensor
difference = timedifference(otherdevices_lastupdate[tsensor])
if (difference > 3600) then
--sensor issue
--commandArray['SendNotification']= 'Error:#Thermostat Sensor issue '.. tsensor;
return commandArray;
else
if tmode==2 then
Temp = tonumber(string.sub(otherdevices_svalues[tsensor],1,4));
else
Temp = otherdevices_svalues[tsensor];
end
end
see_logs('Thermostat: Current mode:'..otherdevices[mode]);
see_logs('Thermostat: Current temperature:'..Temp);
local expectedTemp;--get expected temp
local diff_change; --time delay from last change
if otherdevices[mode]=='Forced' then
expectedTemp = tonumber(string.sub(otherdevices_svalues[fixedTemp],1,5));
elseif otherdevices[mode]=='Auto' then
--check for holidays
if (holidaybool==true and uservariables[holivar]==1) then
expectedTemp= fixedtemp[otherdevices[automodeH]];
--diff_change=timedifference(otherdevices_lastupdate[automodeH]);
see_logs('Thermostat: in auto, current mode:'..otherdevices[automodeH]);
else
expectedTemp= fixedtemp[otherdevices[automode]];
--diff_change=timedifference(otherdevices_lastupdate[automode]);
see_logs('Thermostat: in auto, current mode:'..otherdevices[automode]);
end
else
expectedTemp= fixedtemp[otherdevices[mode]];
--diff_change=timedifference(otherdevices_lastupdate[automode]);
end
diff_change=timedifference(otherdevices_lastupdate[HeatpumpMode]);
see_logs('Time delay since last change: '..diff_change);
see_logs('Thermostat: expected temperature:'.. tostring(expectedTemp));
see_logs('Thermostat: HeatPump temperature:'.. tostring(CurrentHPT));
--Pir
if (devicechanged[presence]=='On') then
difference = timedifference(uservariables_lastupdate[presencefirst]);
difference2 = timedifference(uservariables_lastupdate[presencecount]);
see_logs('pir '.. difference .. ' ' .. difference2);
if (difference < 180 or (difference2 < prestime*60 and uservariables[presencecount]>2) ) then
commandArray['Variable:' .. presencecount] = tostring(tonumber(uservariables[presencecount])+1);
see_logs("Thermostat Pir: " .. tostring(tonumber(uservariables[presencecount])+1));
else
commandArray['Variable:' .. presencecount] = "1";
commandArray['Variable:' .. presencefirst] = "up";
see_logs("Thermostat Pir: 1");
end
end
--presence
if (presentbool==true) then
difference = timedifference(uservariables_lastupdate[presencecount])
time = os.date("*t");
see_logs(time.hour)
if (time.hour>=8 and time.hour<20 and difference < prestime*60 and uservariables[presencecount]>2 and expectedTemp==fixedtemp['Eco']) then
--someone present and eco -> confort
see_logs('Thermostat: mode eco but presence detected since '..(difference/60)..' minutes-> Comfort mode');
expectedTemp=fixedtemp['Comfort'];
-- commandArray['SendNotification']= 'Error:#Thermostat pir min'..(difference/60)..' '.. uservariables[presencecount];
end
end
--normal start HP
if otherdevices[mode]~='Off' and CurrentHPMode=='Off' and (Temp <= expectedTemp - hysteresis) then
see_logs("Thermostat: Heatpump start");
heatpump('Heat',expectedTemp);
return commandArray;
end
-- if real temp > expected + triggerHeat-> shutdown HP
if (Temp >= expectedTemp + triggerHeat) then
if CurrentHPMode=='Heat' then
see_logs("Thermostat: temp difference important, Heatpump shutdown");
heatpump('Off',CurrentHPT);
return commandArray;
end
end
-- if real temp < expected and HP is shutdown-> start HP
if (Temp <= expectedTemp - triggerHeat) then
if CurrentHPMode=='Off' then
see_logs("Thermostat: temp difference less important, Heatpump start");
heatpump('Heat',expectedTemp);
return commandArray;
end
end
--reduce temp heat pump
if CurrentHPMode == 'Heat' and (CurrentHPT > expectedTemp+hysteresis) then
see_logs("Thermostat: reduce temp Heat pump");
heatpump('Heat',expectedTemp);
return commandArray;
end
if CurrentHPMode == 'Heat' and (CurrentHPT < expectedTemp-hysteresis) then
--increase temp heat pump
see_logs("Thermostat: increase temp Heat pump to "..expectedTemp);
heatpump('Heat',expectedTemp);
return commandArray;
end
--turbo mode
if (CurrentHPMode == 'Heat') and (diff_change > 3600) and (diff_change <= 5400) and (Temp < expectedTemp-hysteresis) then
--temp not yet reached -> turbo mode ?
see_logs("Thermostat: Turbo, increase temp Heat pump to "..expectedTemp+1);
heatpump('Turbo',expectedTemp+1);
return commandArray;
end
--turbo mode for 30 min -> stop
if (CurrentHPMode == 'Turbo') and (diff_change > 1800) and (diff_change <= 3600) then
see_logs("Thermostat: Turbo, reduce temp Heat pump to "..expectedTemp);
heatpump('Heat',expectedTemp);
return commandArray;
end
return commandArray;
| 39,937
|
https://github.com/vpavkin/zio-keeper/blob/master/membership/src/main/scala/zio/membership/hyparview/messages.scala
|
Github Open Source
|
Open Source
|
Apache-2.0
| null |
zio-keeper
|
vpavkin
|
Scala
|
Code
| 410
| 1,612
|
package zio.membership.hyparview
import upickle.default._
import zio.Chunk
import zio.keeper.membership.{ ByteCodec, TaggedCodec }
sealed trait ActiveProtocol[+T]
object ActiveProtocol {
implicit def tagged[T](
implicit
c1: ByteCodec[Disconnect[T]],
c2: ByteCodec[ForwardJoin[T]],
c3: ByteCodec[Shuffle[T]],
c4: ByteCodec[UserMessage]
): TaggedCodec[ActiveProtocol[T]] =
TaggedCodec.instance(
{
case _: Disconnect[T] => 10
case _: ForwardJoin[T] => 11
case _: Shuffle[T] => 12
case _: UserMessage => 13
}, {
case 10 => c1.asInstanceOf[ByteCodec[ActiveProtocol[T]]]
case 11 => c2.asInstanceOf[ByteCodec[ActiveProtocol[T]]]
case 12 => c3.asInstanceOf[ByteCodec[ActiveProtocol[T]]]
case 13 => c4.asInstanceOf[ByteCodec[ActiveProtocol[T]]]
}
)
final case class Disconnect[T](
sender: T,
alive: Boolean
) extends ActiveProtocol[T]
object Disconnect {
implicit def codec[T: ReadWriter]: ByteCodec[Disconnect[T]] =
ByteCodec.fromReadWriter(macroRW[Disconnect[T]])
}
final case class ForwardJoin[T](
sender: T,
originalSender: T,
ttl: TimeToLive
) extends ActiveProtocol[T]
object ForwardJoin {
implicit def codec[T: ReadWriter]: ByteCodec[ForwardJoin[T]] =
ByteCodec.fromReadWriter(macroRW[ForwardJoin[T]])
}
final case class Shuffle[T](
sender: T,
originalSender: T,
activeNodes: List[T],
passiveNodes: List[T],
ttl: TimeToLive
) extends ActiveProtocol[T]
object Shuffle {
implicit def codec[T: ReadWriter]: ByteCodec[Shuffle[T]] =
ByteCodec.fromReadWriter(macroRW[Shuffle[T]])
}
final case class UserMessage(
msg: Chunk[Byte]
) extends ActiveProtocol[Nothing]
object UserMessage {
implicit val codec: ByteCodec[UserMessage] =
ByteCodec.fromReadWriter(
implicitly[ReadWriter[Array[Byte]]].bimap[UserMessage](_.msg.toArray, bA => UserMessage(Chunk.fromArray(bA)))
)
}
}
sealed trait InitialProtocol[T]
object InitialProtocol {
implicit def tagged[T](
implicit
c1: ByteCodec[Neighbor[T]],
c2: ByteCodec[InitialMessage.Join[T]],
c3: ByteCodec[InitialMessage.ForwardJoinReply[T]],
c4: ByteCodec[InitialMessage.ShuffleReply[T]]
): TaggedCodec[InitialProtocol[T]] =
TaggedCodec.instance(
{
case _: Neighbor[T] => 0
case _: InitialMessage.Join[T] => 1
case _: InitialMessage.ForwardJoinReply[T] => 2
case _: InitialMessage.ShuffleReply[T] => 3
}, {
case 0 => c1.asInstanceOf[ByteCodec[InitialProtocol[T]]]
case 1 => c2.asInstanceOf[ByteCodec[InitialProtocol[T]]]
case 2 => c3.asInstanceOf[ByteCodec[InitialProtocol[T]]]
case 3 => c4.asInstanceOf[ByteCodec[InitialProtocol[T]]]
}
)
}
final case class Neighbor[T](
sender: T,
isHighPriority: Boolean
) extends InitialProtocol[T]
object Neighbor {
implicit def codec[T: ReadWriter]: ByteCodec[Neighbor[T]] =
ByteCodec.fromReadWriter(macroRW[Neighbor[T]])
}
sealed trait InitialMessage[T] extends InitialProtocol[T]
object InitialMessage {
final case class Join[T](
sender: T
) extends InitialMessage[T]
object Join {
implicit def codec[T: ReadWriter]: ByteCodec[Join[T]] =
ByteCodec.fromReadWriter(macroRW[Join[T]])
}
final case class ForwardJoinReply[T](
sender: T
) extends InitialMessage[T]
object ForwardJoinReply {
implicit def codec[T: ReadWriter]: ByteCodec[ForwardJoinReply[T]] =
ByteCodec.fromReadWriter(macroRW[ForwardJoinReply[T]])
}
final case class ShuffleReply[T](
passiveNodes: List[T],
sentOriginally: List[T]
) extends InitialMessage[T]
object ShuffleReply {
implicit def codec[T: ReadWriter]: ByteCodec[ShuffleReply[T]] =
ByteCodec.fromReadWriter(macroRW[ShuffleReply[T]])
}
}
final case class JoinReply[T](
remote: T
)
object JoinReply {
implicit def codec[T: ReadWriter]: ByteCodec[JoinReply[T]] =
ByteCodec.fromReadWriter(macroRW[JoinReply[T]])
}
sealed trait NeighborReply
object NeighborReply {
implicit val tagged: TaggedCodec[NeighborReply] =
TaggedCodec.instance(
{
case _: Reject.type => 20
case _: Accept.type => 21
}, {
case 20 => ByteCodec[Reject.type].asInstanceOf[ByteCodec[NeighborReply]]
case 21 => ByteCodec[Accept.type].asInstanceOf[ByteCodec[NeighborReply]]
}
)
case object Reject extends NeighborReply {
implicit val codec: ByteCodec[Reject.type] =
ByteCodec.fromReadWriter(macroRW[Reject.type])
}
case object Accept extends NeighborReply {
implicit val codec: ByteCodec[Accept.type] =
ByteCodec.fromReadWriter(macroRW[Accept.type])
}
}
| 9,706
|
https://github.com/rawsonm88/Cowsay/blob/master/Cowsay/RegularExpressions.cs
|
Github Open Source
|
Open Source
|
MIT
| 2,021
|
Cowsay
|
rawsonm88
|
C#
|
Code
| 43
| 162
|
using System.Text.RegularExpressions;
namespace Cowsay
{
internal static class RegularExpressions
{
internal static Regex Cow { get; } = new Regex(@"\$the_cow\s*=\s*<<""*EOC""*;*[\r\n]*(?<cow>[\s\S]+?)[\r\n]*EOC[\r\n]*", RegexOptions.Multiline);
internal static Regex Eye { get; } = new Regex("\\$eye");
internal static Regex LineEndings { get; } = new Regex(@"\r\n?|\n");
}
}
| 31,551
|
https://github.com/dgolant/pence-to-sith/blob/master/Source/content_script.js
|
Github Open Source
|
Open Source
|
WTFPL
| 2,016
|
pence-to-sith
|
dgolant
|
JavaScript
|
Code
| 200
| 634
|
var observeDOM = (function(){
var MutationObserver = window.MutationObserver || window.WebKitMutationObserver,
eventListenerSupported = window.addEventListener;
return function(obj, callback){
if( MutationObserver ){
// define a new observer
var obs = new MutationObserver(function(mutations, observer){
if( mutations[0].addedNodes.length || mutations[0].removedNodes.length )
callback();
});
// have the observer observe foo for changes in children
obs.observe( obj, { childList:true, subtree:true });
}
else if( eventListenerSupported ){
obj.addEventListener('DOMNodeInserted', callback, false);
obj.addEventListener('DOMNodeRemoved', callback, false);
}
}
})();
// Observe a specific DOM element:
observeDOM( document.body ,function(){
walk(document.body);
});
function walk(node)
{
var child, next;
switch ( node.nodeType )
{
case 1: // Element
case 9: // Document
case 11: // Document fragment
child = node.firstChild;
while ( child )
{
next = child.nextSibling;
walk(child);
child = next;
}
break;
case 3: // Text node
handleText(node);
break;
}
}
function handleText(textNode)
{
var v = textNode.nodeValue;
v = v.replace(/\bMike Pence\b/g, "Sith Lord Pence");
v = v.replace(/\bMichael Richard \x22Mike\x22 Pence\b/g, "Michael Richard \x22Water Poisoner\x22 Pence");
v = v.replace(/\bIndiana Governor Mike Pence\b/g, "Corn Imperator Pence");
v = v.replace(/\bGovernor\b/g, "Dark Master");
v = v.replace(/\bGovernor Pence\b/g, "Darth Pence");
v = v.replace(/\bHoosier\b/g, "Corn Person");
v = v.replace(/\bHoosiers\b/g, "Corn People");
v = v.replace(/\bVice Presidential Candidate Mike Pence\b/g, "Sith Apprentice to Donald Trump, ");
textNode.nodeValue = v;
}
| 50,234
|
https://github.com/hejiehui/xUnit/blob/master/com.xrosstools.xunit.editor/src/com/xrosstools/xunit/editor/io/UnitNodeDiagramFactory.java
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,023
|
xUnit
|
hejiehui
|
Java
|
Code
| 161
| 551
|
package com.xrosstools.xunit.editor.io;
import org.w3c.dom.Document;
import com.xrosstools.xunit.editor.model.UnitConstants;
import com.xrosstools.xunit.editor.model.UnitNodeDiagram;
/**
* <xunit packageId name>
* <description>...</description>
* <imports>
* <import packageId, name>
* </imports>
* <units>
* <unit name type class>
* <validator name type class validLabel invalidLabel>
* <locator name type class>
* <chain name type class>
* any unit
* </chain>
* <bi_branch name type class>
* <validator/>
* <validUnit/>
* <invalidUnit/>
* </bi_branch>
* <branch name type class>
* <locator/>
* <branch_unit key/>
* <unit/>
* </branch>
* <parallel_branch name type class>
* <dispatcher/>
* <branch_unit key task_type/>
* <unit/>
* </parallel_branch>
* <while name type class>
* <validator/>
* <loop_unit/>
* </while>
* <do_while name type class>
* <validator/>
* <loop_unit/>
* </do_while>
* </units>
* </xunit>
*
*/
public class UnitNodeDiagramFactory implements UnitConstants{
public UnitNodeDiagram getEmptyDiagram(){
return new UnitNodeDiagram();
}
private UnitNodeDiagramReader reader = new UnitNodeDiagramReader();
private UnitNodeDiagramWriter writer = new UnitNodeDiagramWriter();
public UnitNodeDiagram getFromDocument(Document doc){
return reader.getFromDocument(doc);
}
public Document writeToDocument(UnitNodeDiagram model){
return writer.writeToDocument(model);
}
}
| 3,991
|
https://github.com/hexiaofeng/joyqueue/blob/master/joyqueue-server/joyqueue-broker-core/src/main/java/org/joyqueue/broker/config/Configuration.java
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,020
|
joyqueue
|
hexiaofeng
|
Java
|
Code
| 1,060
| 2,811
|
/**
* Copyright 2019 The JoyQueue Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.joyqueue.broker.config;
import org.joyqueue.toolkit.config.Property;
import org.joyqueue.toolkit.config.PropertySupplier;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
/**
* 配置集
* Created by yangyang115 on 18-7-23.
*/
public class Configuration implements PropertySupplier {
protected static final Logger logger = LoggerFactory.getLogger(Configuration.class);
protected static final int DEFAULT_CONFIGURATION_PRIORITY = 1;
protected static final long DEFAULT_CONFIGURATION_VERSION = 1;
protected static final String DEFAULT_CONFIGURATION_NAME = "_BROKER_CONFIG_";
//名称
protected String name = DEFAULT_CONFIGURATION_NAME;
//数据版本
protected long version = DEFAULT_CONFIGURATION_VERSION;
//优先级
protected int priority = DEFAULT_CONFIGURATION_PRIORITY;
protected Map<String, Property> properties =new HashMap<>();
public Configuration() {
}
public Configuration(String name, Collection<Property> properties, long version, int priority) {
this.name = name;
this.version = version;
this.priority = priority;
addProperties(properties);
}
public Configuration(String name, Map<?, ?> properties, long version, int priority) {
this.name = name;
this.version = version;
this.priority = priority;
if (properties != null) {
List<Property> items = new ArrayList<Property>(properties.size());
for (Map.Entry<?, ?> entry : properties.entrySet()) {
items.add(new Property(name, entry.getKey().toString(), entry.getValue().toString(), version, priority));
}
addProperties(items);
}
}
public Configuration(String name, long version, int priority) {
this.name = name;
this.version = version;
this.priority = priority;
}
public Configuration(String name, List<Configuration> configurations, long version) {
this.name = name;
this.version = version;
List<Property> items = new LinkedList<Property>();
if (configurations != null) {
for (Configuration configuration : configurations) {
if (configuration != null && configuration.size() > 0) {
for (Property property : configuration.properties.values()) {
items.add(property);
}
//获取配置的最大优先级和该优先级的版本
if (this.priority < configuration.priority) {
this.priority = configuration.priority;
}
}
}
}
addProperties(items);
}
/**
* 添加属性集,处理数组配置方式
*
* @param collection
*/
protected void addProperties(final Collection<Property> collection) {
if (collection == null || collection.isEmpty()) {
return;
}
//处理数组的配置方式
//laf.config.manager.parameters[autoListener] = true
//laf.config.resources[0].name=ucc_test
Map<String, Object> context = new HashMap<String, Object>();
for (Property item : collection) {
if (item.getKey() == null || item.getValue() == null) {
return;
}
properties.put(item.getKey(), item);
process(item.getKey(), 0, item.getValue(), context);
}
if (!context.isEmpty()) {
processArray(context, false);
Property property;
for (Map.Entry<String, Object> entry : context.entrySet()) {
if (!properties.containsKey(entry.getKey())) {
//动态创建的属性设置成不存储
property = new Property(name, entry.getKey(), entry.getValue(), version, priority);
properties.put(entry.getKey(), property);
}
}
}
}
/**
* 添加属性
*
* @param key
* @param value
*/
public Property addProperty(final String key, final String value, final String group) {
Property property = new Property(name, key, value, group, 0, priority);
properties.put(key, property);
return property;
}
public Property addProperty(final String key, final String value) {
return addProperty(key, value, null);
}
protected static void process(final String source, final int start, final Object value, final Map<String, Object> context) {
//找到"[xxx]","]"为结尾或后面跟着".xxx"
int from = start;
while (true) {
int left = source.indexOf('[', from);
if (left > 0) {
int right = source.indexOf(']', left + 1);
if (right > 0) {
String key = source.substring(start, left);
String index = source.substring(left + 1, right);
if (index != null && !index.isEmpty()
&& (right == source.length() - 1
|| source.charAt(right + 1) == '.' && right < source.length() - 2)) {
Object v = context.get(key);
if (v == null || !(v instanceof Map)) {
v = new HashMap<String, Object>();
context.put(key, v);
}
if (right == source.length() - 1) {
//']'在最后
((Map<String, Object>) v).put(index, value);
} else {
//"]."
Object child = ((Map) v).get(index);
if (child == null || !(child instanceof Map)) {
child = new HashMap<String, Object>();
((Map) v).put(index, child);
}
process(source, right + 2, value, (Map<String, Object>) child);
}
return;
} else {
//查找下一个"[xxx]"
from = right + 1;
}
} else {
break;
}
} else {
break;
}
}
//剩余字符串
if (start > 0 && start < source.length()) {
//后面作为整个字符串出来
context.put(source.substring(start), value);
}
}
protected static Object[] processArray(final Map<String, Object> context, final boolean flag) {
if (context.isEmpty()) {
return null;
}
//判断值是否可以转换成数组
int v;
int max = 0;
boolean isArray = true;
Object[] array;
for (Map.Entry<String, Object> entry : context.entrySet()) {
if (flag && isArray) {
try {
v = Integer.parseInt(entry.getKey());
if (v >= 0) {
if (max < v) {
max = v;
}
} else {
isArray = false;
}
} catch (NumberFormatException e) {
isArray = false;
}
}
if (entry.getValue() instanceof Map) {
array = processArray((Map<String, Object>) entry.getValue(), true);
if (array != null) {
entry.setValue(array);
}
}
}
if (flag && isArray) {
Object[] result = new Object[max + 1];
for (Map.Entry<String, Object> entry : context.entrySet()) {
result[Integer.parseInt(entry.getKey())] = entry.getValue();
}
return result;
} else {
return null;
}
}
@Override
public Property getProperty(final String key) {
return properties.get(key);
}
@Override
public Property getOrCreateProperty(final String key) {
Property property = getProperty(key);
if (property == null) {
//when key not exists ,the created property should assign low version and low priority
return new Property(this.name, key, null, 0, 0);
}
return property;
}
/**
* 获取配置集下所有属性
*
* @return
* @see Configuration#getProperties()
*/
@Deprecated
public Collection<Property> get() {
return getProperties();
}
@Override
public List<Property> getProperties() {
return properties == null ? new ArrayList<Property>(0) : new ArrayList<Property>(properties.values());
}
@Override
public List<Property> getPrefix(final String prefix) {
List<Property> result = new ArrayList<Property>();
if (prefix == null || prefix.isEmpty() || properties == null) {
return result;
}
for (Map.Entry<String, Property> entry : properties.entrySet()) {
if (entry.getKey().startsWith(prefix)) {
result.add(entry.getValue());
}
}
return result;
}
/**
* 验证是否存在 key
*
* @param key
* @return
*/
public boolean contains(final String key) {
return properties.containsKey(key);
}
public String getName() {
return name;
}
public long getVersion() {
return version;
}
public int getPriority() {
return priority;
}
public boolean isEmpty() {
return properties.isEmpty();
}
public int size() {
return properties == null ? 0 : properties.size();
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Configuration that = (Configuration) o;
return properties.equals(that.properties);
}
@Override
public int hashCode() {
return name.hashCode();
}
@Override
public String toString() {
return "Configuration{" +
"properties=" + properties +
", name='" + name + '\'' +
", version=" + version +
'}';
}
}
| 18,703
|
https://github.com/jxc98728/cmu-tcp/blob/master/Vagrantfile
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,021
|
cmu-tcp
|
jxc98728
|
Ruby
|
Code
| 212
| 722
|
# -*- mode: ruby -*-
# vi: set ft=ruby :
$INSTALL_BASE = <<SCRIPT
sudo apt-get update
sudo DEBIAN_FRONTEND=noninteractive apt-get install -y build-essential vim emacs tree tmux git gdb valgrind python-dev libffi-dev libssl-dev clang-format iperf3 tshark
sudo DEBIAN_FRONTEND=noninteractive apt-get install -y python python3-pip python-tk
pip install --upgrade pip
pip install tcconfig scapy fabric typing cryptography scapy matplotlib pytest fabric
SCRIPT
Vagrant.configure(2) do |config|
config.vm.box = "ubuntu/focal64"
config.ssh.forward_agent = true
config.vm.provision "shell", inline: $INSTALL_BASE
config.vm.synced_folder "15-441-project-2", "/vagrant/15-441-project-2"
# config.vm.provider "virtualbox" do |vb|
# # Display the VirtualBox GUI when booting the machine
# # Username: vagrant
# # Password: vagrant
#
# vb.gui = true
# # Customize the amount of memory on the VM:
# vb.memory = "1024"
# end
config.vm.define :client, primary: true do |host|
host.vm.hostname = "client"
host.vm.network "private_network", ip: "10.0.0.2", netmask: "255.255.255.0", mac: "080027a7feb1",
virtualbox__intnet: "15441"
host.vm.provision "shell", inline: "sudo tcset enp0s8 --rate 100Mbps --delay 20ms"
host.vm.provision "shell", inline: "sudo sed -i 's/PasswordAuthentication no/PasswordAuthentication yes/g' /etc/ssh/sshd_config"
host.vm.provision "shell", inline: "sudo service sshd restart"
end
config.vm.define :server do |host|
host.vm.hostname = "server"
host.vm.network "private_network", ip: "10.0.0.1", netmask: "255.255.255.0", mac: "08002722471c",
virtualbox__intnet: "15441"
host.vm.provision "shell", inline: "sudo tcset enp0s8 --rate 100Mbps --delay 20ms"
host.vm.provision "shell", inline: "sudo sed -i 's/PasswordAuthentication no/PasswordAuthentication yes/g' /etc/ssh/sshd_config"
host.vm.provision "shell", inline: "sudo service sshd restart"
end
end
| 18,999
|
https://github.com/ARGOeu/argo-ams-library/blob/master/pymod/amsmsg.py
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,023
|
argo-ams-library
|
ARGOeu
|
Python
|
Code
| 354
| 978
|
import sys
import json
import inspect
from base64 import b64encode, b64decode
try:
from collections.abc import Callable
except ImportError:
from collections import Callable
from .amsexceptions import AmsMessageException
class AmsMessage(Callable):
"""Abstraction of AMS Message
AMS Message is constituted from mandatory data field
and arbitrary number of attributes. Data is Base64
encoded prior dispatching message to AMS service and
Base64 decoded when it is being pulled from service.
"""
def __init__(self, b64enc=True, attributes='', data=None,
messageId='', publishTime=''):
self._attributes = attributes
self._messageId = messageId
self._publishTime = publishTime
self.set_data(data, b64enc)
def __call__(self, **kwargs):
if 'attributes' not in kwargs:
kwargs.update({'attributes': self._attributes})
self.__init__(b64enc=True, **kwargs)
return self.dict()
def _has_dataattr(self):
if not getattr(self, '_data', False) and not self._attributes:
raise AmsMessageException('At least data field or one attribute needs to be defined')
return True
def set_attr(self, key, value):
"""Set attributes of message
Args:
key (str): Key of the attribute
value (str): Value of the attribute
"""
self._attributes.update({key: value})
def set_data(self, data, b64enc=True):
"""Set data of message
Default behaviour is to Base64 encode data prior sending it by the
publisher. Method is also used internally when pull from subscription
is being made by subscriber and in that case, data is already Base64 encoded
Args:
data (str): Data of the message
Kwargs:
b64enc (bool): Control whether data should be Base64 encoded
"""
if b64enc and data:
try:
if sys.version_info < (3, ):
self._data = b64encode(data)
else:
if isinstance(data, bytes):
self._data = str(b64encode(data), 'utf-8')
else:
self._data = str(b64encode(bytearray(data, 'utf-8')), 'utf-8')
except Exception as e:
raise AmsMessageException('b64encode() {0}'.format(str(e)))
elif data:
self._data = data
def dict(self):
"""Construct python dict from message"""
if self._has_dataattr():
d = dict()
for attr in ['attributes', 'data', 'messageId', 'publishTime']:
if getattr(self, '_{0}'.format(attr), False):
v = eval('self._{0}'.format(attr))
d.update({attr: v})
return d
def get_data(self):
"""Fetch the data of the message and Base64 decode it"""
if self._has_dataattr():
try:
return b64decode(self._data)
except Exception as e:
raise AmsMessageException('b64decode() {0}'.format(str(e)))
def get_msgid(self):
"""Fetch the message id of the message"""
return self._messageId
def get_publishtime(self):
"""Fetch the publish time of the message set by the AMS service"""
return self._publishTime
def get_attr(self):
"""Fetch all attributes of the message"""
if self._has_dataattr():
return self._attributes
def json(self):
"""Return JSON interpretation of the message"""
return json.dumps(self.dict())
def __str__(self):
return str(self.dict())
| 7,498
|
https://github.com/sengeiou/freshDay-Market/blob/master/freshday-ware/src/main/java/com/haoliang/freshday/ware/dao/WareOrderTaskDetailDao.java
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,022
|
freshDay-Market
|
sengeiou
|
Java
|
Code
| 31
| 154
|
package com.haoliang.freshday.ware.dao;
import com.haoliang.freshday.ware.entity.WareOrderTaskDetailEntity;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Mapper;
/**
* 库存工作单
*
* @author zhouhaoliang
* @email 614136484@qq.com
* @date 2021-04-06 15:43:36
*/
@Mapper
public interface WareOrderTaskDetailDao extends BaseMapper<WareOrderTaskDetailEntity> {
}
| 48,037
|
https://github.com/Robscha11/vis_exc1/blob/master/node_modules/.cache/snowpack/build/d3-fetch@2.0.0/d3-fetch.js
|
Github Open Source
|
Open Source
|
MIT
| null |
vis_exc1
|
Robscha11
|
JavaScript
|
Code
| 265
| 709
|
import { dsvFormat, tsvParse, csvParse } from 'd3-dsv';
function responseBlob(response) {
if (!response.ok) throw new Error(response.status + " " + response.statusText);
return response.blob();
}
function blob(input, init) {
return fetch(input, init).then(responseBlob);
}
function responseArrayBuffer(response) {
if (!response.ok) throw new Error(response.status + " " + response.statusText);
return response.arrayBuffer();
}
function buffer(input, init) {
return fetch(input, init).then(responseArrayBuffer);
}
function responseText(response) {
if (!response.ok) throw new Error(response.status + " " + response.statusText);
return response.text();
}
function text(input, init) {
return fetch(input, init).then(responseText);
}
function dsvParse(parse) {
return function(input, init, row) {
if (arguments.length === 2 && typeof init === "function") row = init, init = undefined;
return text(input, init).then(function(response) {
return parse(response, row);
});
};
}
function dsv(delimiter, input, init, row) {
if (arguments.length === 3 && typeof init === "function") row = init, init = undefined;
var format = dsvFormat(delimiter);
return text(input, init).then(function(response) {
return format.parse(response, row);
});
}
var csv = dsvParse(csvParse);
var tsv = dsvParse(tsvParse);
function image(input, init) {
return new Promise(function(resolve, reject) {
var image = new Image;
for (var key in init) image[key] = init[key];
image.onerror = reject;
image.onload = function() { resolve(image); };
image.src = input;
});
}
function responseJson(response) {
if (!response.ok) throw new Error(response.status + " " + response.statusText);
if (response.status === 204 || response.status === 205) return;
return response.json();
}
function json(input, init) {
return fetch(input, init).then(responseJson);
}
function parser(type) {
return (input, init) => text(input, init)
.then(text => (new DOMParser).parseFromString(text, type));
}
var xml = parser("application/xml");
var html = parser("text/html");
var svg = parser("image/svg+xml");
export { blob, buffer, csv, dsv, html, image, json, svg, text, tsv, xml };
| 704
|
https://github.com/TecArt/servicecatalog-development/blob/master/oscm-portal-unittests/javasrc/org/oscm/ui/beans/ReportIssueBeanTest.java
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,021
|
servicecatalog-development
|
TecArt
|
Java
|
Code
| 512
| 2,459
|
/*******************************************************************************
*
* Copyright FUJITSU LIMITED 2017
*
* Creation Date: 2012-4-24
*
*******************************************************************************/
package org.oscm.ui.beans;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyLong;
import static org.mockito.Matchers.anyString;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.doNothing;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import java.util.Locale;
import javax.faces.application.FacesMessage;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Matchers;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import org.oscm.ui.common.UiDelegate;
import org.oscm.ui.stubs.FacesContextStub;
import org.oscm.validator.ADMValidator;
import org.oscm.internal.components.response.Response;
import org.oscm.internal.intf.SubscriptionService;
import org.oscm.internal.subscriptiondetails.POSubscriptionDetails;
import org.oscm.internal.subscriptiondetails.SubscriptionDetailsService;
import org.oscm.internal.types.enumtypes.SubscriptionStatus;
import org.oscm.internal.types.exception.MailOperationException;
import org.oscm.internal.types.exception.ObjectNotFoundException;
import org.oscm.internal.types.exception.OperationNotPermittedException;
import org.oscm.internal.types.exception.ValidationException;
import org.oscm.internal.vo.VOSubscriptionDetails;
/**
* Unit test for testing the ReportIssueBean.
*
* @author yuyin
*/
public class ReportIssueBeanTest {
private static final String OUTCOME_SUBSCRIPTION_NOT_AVAILABLE = "subscriptionNotAccessible";
private SubscriptionService subscriptionServiceMock;
private SubscriptionDetailsService subscriptionDetailsService;
private ReportIssueBean spy;
private Message message = null;
private VOSubscriptionDetails subscription;
private static final long subscriptionKey = 1L;
private class Message {
String SERVERITY;
String KEY;
Message(String severity, String key) {
SERVERITY = severity;
KEY = key;
}
}
@Before
public void setUp() throws Exception {
new FacesContextStub(Locale.ENGLISH);
subscriptionServiceMock = mock(SubscriptionService.class);
subscriptionDetailsService = mock(SubscriptionDetailsService.class);
spy = spy(new ReportIssueBean());
doReturn(subscriptionDetailsService).when(spy)
.getSubscriptionDetailsService();
doReturn(subscriptionServiceMock).when(spy).getSubscriptionService();
doReturn(Long.valueOf(subscriptionKey)).when(spy)
.getSelectedSubscriptionKey();
doAnswer(new Answer<Object>() {
@Override
public Object answer(InvocationOnMock invocation) {
Object[] args = invocation.getArguments();
String severity = args[1].toString();
String key = (String) args[2];
message = new Message(severity, key);
return null;
}
}).when(spy).addMessage(anyString(), any(FacesMessage.Severity.class),
anyString());
spy.ui = mock(UiDelegate.class);
subscription = new VOSubscriptionDetails();
subscription.setSellerName("Supplier 1");
subscription.setSubscriptionId("Subscription 0x234");
subscription.setStatus(SubscriptionStatus.ACTIVE);
POSubscriptionDetails subscriptionDetails = new POSubscriptionDetails();
subscriptionDetails.setSubscription(subscription);
when(spy.ui.getViewLocale()).thenReturn(Locale.GERMAN);
}
private void assertMessage(String severity, String key) {
assertNotNull(message);
assertEquals(severity, message.SERVERITY);
assertEquals(key, message.KEY);
}
@Test
public void init() {
spy.setSupportEmailTitle("previous title");
spy.setSupportEmailContent("previous content");
// when
spy.init();
// then
verify(spy).resetUIInputChildren();
assertEquals(null, spy.getSupportEmailContent());
assertEquals(null, spy.getSupportEmailTitle());
}
@Test
public void testReportIssue_InitialState() {
ReportIssueBean bean = new ReportIssueBean();
assertNull(bean.getSupportEmailContent());
assertNull(bean.getSupportEmailTitle());
}
@Test
public void testReportIssue_Success() throws Exception {
final String supportMailTitle = "Problem sending emails";
final String supportMailContent = "There is a problem when sending a support email.";
when(subscriptionDetailsService.loadSubscriptionStatus(anyLong()))
.thenReturn(new Response(SubscriptionStatus.ACTIVE));
doAnswer(new Answer<Void>() {
@Override
public Void answer(InvocationOnMock invocation) throws Throwable {
Object[] args = invocation.getArguments();
assertNotNull(args);
assertEquals(subscription.getSubscriptionId(), args[0]);
assertEquals(supportMailTitle, args[1]);
assertEquals(supportMailContent, args[2]);
return null;
}
}).when(subscriptionServiceMock).reportIssue(Matchers.anyString(),
Matchers.anyString(), Matchers.anyString());
spy.setSupportEmailTitle(supportMailTitle);
spy.setSupportEmailContent(supportMailContent);
doNothing().when(subscriptionServiceMock).reportIssue(anyString(),
eq(supportMailTitle), eq(supportMailContent));
assertEquals(BaseBean.OUTCOME_SUCCESS, spy.reportIssue("abcdef"));
assertMessage(FacesMessage.SEVERITY_INFO.toString(),
BaseBean.INFO_ORGANIZATION_SUPPORTMAIL_SENT);
verify(subscriptionServiceMock, times(1)).reportIssue(
Matchers.anyString(), Matchers.anyString(),
Matchers.anyString());
}
@Test
public void testReportIssue_ValidationException() throws Exception {
doThrow(new ValidationException()).when(subscriptionServiceMock)
.reportIssue(Matchers.anyString(), Matchers.anyString(),
Matchers.anyString());
assertEquals(BaseBean.OUTCOME_ERROR,
spy.reportIssue(Matchers.anyString()));
}
@Test
public void testReportIssue_ObjectException() throws Exception {
doThrow(new ObjectNotFoundException()).when(subscriptionServiceMock)
.reportIssue(Matchers.anyString(), Matchers.anyString(),
Matchers.anyString());
assertEquals(BaseBean.OUTCOME_ERROR,
spy.reportIssue(Matchers.anyString()));
}
@Test
public void testReportIssue_MailOperationException() throws Exception {
doThrow(new MailOperationException()).when(subscriptionServiceMock)
.reportIssue(Matchers.anyString(), Matchers.anyString(),
Matchers.anyString());
assertEquals(BaseBean.OUTCOME_ERROR,
spy.reportIssue(Matchers.anyString()));
}
@Test
public void testReportIssue_OperationNotPermittedException()
throws Exception {
doThrow(new OperationNotPermittedException()).when(
subscriptionServiceMock).reportIssue(Matchers.anyString(),
Matchers.anyString(), Matchers.anyString());
assertEquals(BaseBean.OUTCOME_ERROR,
spy.reportIssue(Matchers.anyString()));
}
@Test
public void testMaxInputLength() {
assertEquals(ADMValidator.LENGTH_EMAIL_SUBJECT, spy.getSubjectLen());
assertEquals(ADMValidator.LENGTH_EMAIL_CONTENT, spy.getContentLen());
}
@Test
public void refreshSendSuccessMessage() {
assertEquals(BaseBean.OUTCOME_SUCCESS, spy.refreshSendSuccessMessage());
assertMessage(FacesMessage.SEVERITY_INFO.toString(),
BaseBean.INFO_ORGANIZATION_SUPPORTMAIL_SENT);
}
@Test
public void testReportIssue_MissingSelectedSubscriptionId()
throws Exception {
assertEquals(BaseBean.OUTCOME_ERROR, spy.reportIssue(null));
}
@Test
public void testReportIssue_EmptySelectedSubscriptionId() throws Exception {
assertEquals(BaseBean.OUTCOME_ERROR, spy.reportIssue(""));
}
@Test
public void reportIssue_subscriptionInvalid() throws Exception {
// given
when(subscriptionDetailsService.loadSubscriptionStatus(anyLong()))
.thenReturn(new Response(SubscriptionStatus.INVALID));
// when
String result = spy.reportIssue("subscriptionId");
assertEquals(OUTCOME_SUBSCRIPTION_NOT_AVAILABLE, result);
}
@Test
public void reportIssue_subscriptionDeactivated() throws Exception {
// given
when(subscriptionDetailsService.loadSubscriptionStatus(anyLong()))
.thenThrow(new ObjectNotFoundException());
// when
String result = spy.reportIssue("subscriptionId");
assertEquals(OUTCOME_SUBSCRIPTION_NOT_AVAILABLE, result);
}
}
| 16,069
|
https://github.com/yothinn/employee-service/blob/master/src/modules/employee/controllers/controller.js
|
Github Open Source
|
Open Source
|
MIT
| null |
employee-service
|
yothinn
|
JavaScript
|
Code
| 507
| 1,619
|
'use strict';
var mongoose = require('mongoose'),
model = require('../models/model'),
mq = require('../../core/controllers/rabbitmq'),
Employee = mongoose.model('Employee'),
errorHandler = require('../../core/controllers/errors.server.controller'),
_ = require('lodash');
const XLSX = require('xlsx');
const fs = require('fs');
exports.getList = async function (req, res) {
var pageNo = parseInt(req.query.pageNo);
var size = parseInt(req.query.size);
delete req.query.pageNo;
delete req.query.size;
var searchText = req.query.query;
var channel = req.query.channel ? req.query.channel : null;
var startDate = new Date(req.query.startDate);
var endDate = new Date(req.query.endDate);
let query = { $and: [] };
// Query id, customer name
if (searchText) {
query['$and'].push({
$or: [
{ firstName: { $regex: `^${searchText}`, $options: "i" } },
{ lastName: { $regex: `${searchText}`, $options: "i" } },
]
})
}
// Query channel
if (channel) {
query['$and'].push({
channel: channel
})
}
// Reset query when no parameter
if (query['$and'].length === 0) {
query = {};
}
// Query created in start and end date.
if (!isNaN(startDate.valueOf()) && !isNaN(endDate.valueOf())) {
console.log('date valid');
if (!endDate || (startDate > endDate)) {
return res.status(400).send({
status: 400,
message: "End date equal null or start date greate than end date"
});
}
query['$and'].push({
created: { $gte: startDate, $lte: endDate }
})
}
console.log(query);
var sort = { created: -1 };
if (pageNo < 0) {
response = { "error": true, "message": "invalid page number, should start with 1" };
return res.json(response);
}
try {
const [_result, _count] = await Promise.all([
Employee.find(query)
.skip(size * (pageNo - 1))
.limit(size)
.sort(sort)
.exec(),
Employee.countDocuments(query).exec()
]);
//console.log(_result);
res.jsonp({
status: 200,
data: _result,
pageIndex: pageNo,
pageSize: size,
totalRecord: _count,
});
} catch (err) {
console.log(err);
return res.status(400).send({
status: 400,
message: errorHandler.getErrorMessage(err)
});
}
};
exports.create = function (req, res) {
var newEmployee = new Employee(req.body);
newEmployee.createby = req.user;
newEmployee.save(function (err, data) {
if (err) {
return res.status(400).send({
status: 400,
message: errorHandler.getErrorMessage(err)
});
} else {
res.jsonp({
status: 200,
data: data
});
/**
* Message Queue
*/
// mq.publish('exchange', 'keymsg', JSON.stringify(newOrder));
};
});
};
exports.getByID = function (req, res, next, id) {
if (!mongoose.Types.ObjectId.isValid(id)) {
return res.status(400).send({
status: 400,
message: 'Id is invalid'
});
}
Employee.findById(id, function (err, data) {
if (err) {
return res.status(400).send({
status: 400,
message: errorHandler.getErrorMessage(err)
});
} else {
req.data = data ? data : {};
next();
};
});
};
exports.read = function (req, res) {
res.jsonp({
status: 200,
data: req.data ? req.data : []
});
};
exports.update = function (req, res) {
var updEmployee = _.extend(req.data, req.body);
updEmployee.updated = new Date();
updEmployee.updateby = req.user;
updEmployee.save(function (err, data) {
if (err) {
return res.status(400).send({
status: 400,
message: errorHandler.getErrorMessage(err)
});
} else {
res.jsonp({
status: 200,
data: data
});
};
});
};
exports.delete = function (req, res) {
req.data.remove(function (err, data) {
if (err) {
return res.status(400).send({
status: 400,
message: errorHandler.getErrorMessage(err)
});
} else {
res.jsonp({
status: 200,
data: data
});
};
});
};
exports.uploads = function (req, res) {
console.log(req.file.path)
var filePath = req.file.path
const workbook = XLSX.readFile(filePath);
const worksheet = workbook.Sheets[workbook.SheetNames[0]];
let dataEmployee = XLSX.utils.sheet_to_json(worksheet);
try {
dataEmployee.map(res => {
let newEmployee = new Employee(res);
newEmployee.save()
})
res.jsonp({
status: 200
});
} catch (err) {
console.log(err);
return res.status(400).send({
status: 400,
message: errorHandler.getErrorMessage(err)
});
}
fs.unlinkSync(filePath);
}
| 33,509
|
https://github.com/romchesko-pazzi/my-app/blob/master/src/components/EditableSpan/EditableSpan.tsx
|
Github Open Source
|
Open Source
|
MIT
| null |
my-app
|
romchesko-pazzi
|
TypeScript
|
Code
| 80
| 278
|
import React, {ChangeEvent, useState} from 'react';
export type EditableSpanPropsType = {
name: string
callback:(newTitle:string)=>void
}
export const EditableSpan = (props: EditableSpanPropsType) => {
const {name,callback} = props;
const [spanOrInput, setSpanOrInput] = useState(false)
const [value, setValue] = useState(name);
const onDoubleClickHandler = () => {
setSpanOrInput(true);
}
const onChangeHandler = (event: ChangeEvent<HTMLInputElement>) => {
setValue(event.currentTarget.value);
}
const onBlurHandler = () => {
callback(value)
setSpanOrInput(false);
}
return (
<>
{spanOrInput ? <input
onChange={onChangeHandler}
onBlur={onBlurHandler}
value={value}
autoFocus
type="text"/> : <span onDoubleClick={onDoubleClickHandler}>{name}</span>}
</>
);
};
| 27,941
|
https://github.com/egnitionHamburg/mopad/blob/master/client/src/business/auth.ts
|
Github Open Source
|
Open Source
|
MIT
| 2,018
|
mopad
|
egnitionHamburg
|
TypeScript
|
Code
| 123
| 390
|
import { ApolloLink, NextLink, Operation } from "apollo-link";
export class AuthenticationLink extends ApolloLink {
constructor(private tokenStore: ISessionStore) {
super();
}
public request(operation: Operation, forward?: NextLink) {
operation.setContext(({ headers }) => ({
headers: {
...headers,
authorization: `Bearer ${this.tokenStore.token}`
}
}));
return forward(operation);
}
}
export interface ISessionStore {
token: string;
userId: string;
userIsAdmin: boolean;
clearSession();
}
export class LocalSessionStore implements ISessionStore {
public get token(): string {
return localStorage.getItem("token");
}
public set token(value: string) {
localStorage.setItem("token", value);
}
public get userId(): string {
return localStorage.getItem("userId");
}
public set userId(value: string) {
localStorage.setItem("userId", value);
}
public get userIsAdmin(): boolean {
return localStorage.getItem("userIsAdmin") === "true";
}
public set userIsAdmin(value: boolean) {
localStorage.setItem("userIsAdmin", value ? "true" : "false");
}
public clearSession() {
localStorage.removeItem("token");
localStorage.removeItem("userId");
localStorage.removeItem("userIsAdmin");
}
}
| 49,427
|
https://github.com/1619khze/apex/blob/master/src/main/java/org/apex/scheduler/SystemScheduler.java
|
Github Open Source
|
Open Source
|
MIT
| 2,021
|
apex
|
1619khze
|
Java
|
Code
| 313
| 676
|
/*
* MIT License
*
* Copyright (c) 2020 1619kHz
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package org.apex.scheduler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Executor;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import static java.util.Objects.requireNonNull;
/**
* @author WangYi
* @since 2020/6/23
*/
public enum SystemScheduler implements Scheduler {
INSTANCE;
static final Method delayedExecutor = getDelayedExecutorMethod();
static Method getDelayedExecutorMethod() {
try {
return CompletableFuture.class.getMethod(
"delayedExecutor", long.class, TimeUnit.class, Executor.class);
} catch (NoSuchMethodException | SecurityException e) {
return null;
}
}
static boolean isPresent() {
return (delayedExecutor != null);
}
@Override
@SuppressWarnings("NullAway")
public Future<?> schedule(Executor executor, Runnable command, long delay, TimeUnit unit) {
requireNonNull(executor);
requireNonNull(command);
requireNonNull(unit);
try {
Executor scheduler = null;
if (delayedExecutor != null) {
scheduler = (Executor) delayedExecutor.invoke(
CompletableFuture.class, delay, unit, executor);
}
return CompletableFuture.runAsync(command, scheduler);
} catch (IllegalAccessException | InvocationTargetException e) {
throw new RuntimeException(e);
}
}
}
| 18,274
|
https://github.com/joneng2016/simulationmoise/blob/master/app/Models/StatisticSimulation.php
|
Github Open Source
|
Open Source
|
MIT
| 2,018
|
simulationmoise
|
joneng2016
|
PHP
|
Code
| 69
| 379
|
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class StatisticSimulation extends Model
{
public function __construct(){
$this->name_simulation = new \App\Models\NameSimulation;
}
public function insertStatistic($name_simulation,$average){
if($this->name_simulation->verifyIfExist($name_simulation))
$name_id = $this->name_simulation->findId($name_simulation);
else
$this->writeInBank($name_simulation,$name_id);
$this->prepareArg($name_id,$average,$arg_insert);
$this->insert($arg_insert);
return true;
}
public function verifyIfExist($name_id){
return $this->where("name_id",$name_id)->get()->isNotEmpty();
}
public function prepareArg($name_id,$average,&$arg_insert){
$arg_insert =
[
"name_id" => $name_id,
"average" => $average,
"created_at" => new \DateTime,
"updated_at" => new \DateTime
];
}
public function writeInBank($name_simulation,&$name_id){
$this->name_simulation->insertName($name_simulation);
$name_id = $this->findId($name_simulation);
}
}
| 15,914
|
https://github.com/magefree/mage/blob/master/Mage/src/main/java/mage/game/permanent/token/JaceCunningCastawayIllusionToken.java
|
Github Open Source
|
Open Source
|
MIT
| 2,023
|
mage
|
magefree
|
Java
|
Code
| 173
| 643
|
package mage.game.permanent.token;
import mage.constants.CardType;
import mage.constants.SubType;
import mage.MageInt;
import mage.MageObject;
import mage.abilities.TriggeredAbilityImpl;
import mage.abilities.effects.common.SacrificeSourceEffect;
import mage.constants.Zone;
import mage.game.Game;
import mage.game.events.GameEvent;
import mage.game.stack.Spell;
/**
* @author TheElk801
*/
public final class JaceCunningCastawayIllusionToken extends TokenImpl {
public JaceCunningCastawayIllusionToken() {
super("Illusion Token", "2/2 blue Illusion creature token with \"When this creature becomes the target of a spell, sacrifice it.\"");
cardType.add(CardType.CREATURE);
color.setBlue(true);
subtype.add(SubType.ILLUSION);
power = new MageInt(2);
toughness = new MageInt(2);
this.addAbility(new IllusionTokenTriggeredAbility());
}
protected JaceCunningCastawayIllusionToken(final JaceCunningCastawayIllusionToken token) {
super(token);
}
@Override
public JaceCunningCastawayIllusionToken copy() {
return new JaceCunningCastawayIllusionToken(this);
}
}
class IllusionTokenTriggeredAbility extends TriggeredAbilityImpl {
public IllusionTokenTriggeredAbility() {
super(Zone.BATTLEFIELD, new SacrificeSourceEffect(), false);
}
protected IllusionTokenTriggeredAbility(final IllusionTokenTriggeredAbility ability) {
super(ability);
}
@Override
public IllusionTokenTriggeredAbility copy() {
return new IllusionTokenTriggeredAbility(this);
}
@Override
public boolean checkEventType(GameEvent event, Game game) {
return event.getType() == GameEvent.EventType.TARGETED;
}
@Override
public boolean checkTrigger(GameEvent event, Game game) {
MageObject eventSourceObject = game.getObject(event.getSourceId());
if (event.getTargetId().equals(this.getSourceId()) && eventSourceObject instanceof Spell) {
return true;
}
return false;
}
@Override
public String getRule() {
return "When this creature becomes the target of a spell, sacrifice it.";
}
}
| 49,544
|
https://github.com/ms2sato/isheeet/blob/master/fuel/app/classes/controller/introduction.php
|
Github Open Source
|
Open Source
|
MIT
| null |
isheeet
|
ms2sato
|
PHP
|
Code
| 54
| 221
|
<?php
class Controller_Introduction extends Controller_Authenticated
{
public function action_index()
{
$data['introductions'] = Model_Introduction::find('all');
$this->template->title = "Introductions";
$this->template->content = View::forge('introduction/index', $data);
}
public function action_view($id = null)
{
is_null($id) and Response::redirect('introduction');
if ( ! $data['introduction'] = Model_Introduction::find($id))
{
Session::set_flash('error', 'Could not find introduction #'.$id);
Response::redirect('introduction');
}
$this->template->title = "Introduction";
$this->template->content = View::forge('introduction/view', $data);
}
}
| 33,088
|
https://github.com/dlandi/xamarin.exposurenotification/blob/master/Xamarin.ExposureNotification/ExposureNotification.android.cs
|
Github Open Source
|
Open Source
|
MIT
| null |
xamarin.exposurenotification
|
dlandi
|
C#
|
Code
| 645
| 2,876
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
using Android.App;
using Android.Bluetooth;
using Android.Gms.Common.Apis;
using Android.Gms.Nearby.ExposureNotification;
using Android.Runtime;
using AndroidX.Work;
using Java.Nio.FileNio;
using AndroidRiskLevel = Android.Gms.Nearby.ExposureNotification.RiskLevel;
using Nearby = Android.Gms.Nearby.NearbyClass;
[assembly: UsesFeature("android.hardware.bluetooth_le", Required=true)]
[assembly: UsesFeature("android.hardware.bluetooth")]
[assembly: UsesPermission(Android.Manifest.Permission.Bluetooth)]
namespace Xamarin.ExposureNotifications
{
public static partial class ExposureNotification
{
static IExposureNotificationClient instance;
static IExposureNotificationClient Instance
=> instance ??= Nearby.GetExposureNotificationClient(Application.Context);
static async Task<ExposureConfiguration> GetConfigurationAsync()
{
var c = await Handler.GetConfigurationAsync();
return new ExposureConfiguration.ExposureConfigurationBuilder()
.SetAttenuationScores(c.AttenuationScores)
.SetDurationScores(c.DurationScores)
.SetDaysSinceLastExposureScores(c.DaysSinceLastExposureScores)
.SetTransmissionRiskScores(c.TransmissionRiskScores)
.SetAttenuationWeight(c.AttenuationWeight)
.SetDaysSinceLastExposureWeight(c.DaysSinceLastExposureWeight)
.SetDurationWeight(c.DurationWeight)
.SetTransmissionRiskWeight(c.TransmissionWeight)
.SetMinimumRiskScore(c.MinimumRiskScore)
.SetDurationAtAttenuationThresholds(c.DurationAtAttenuationThresholds)
.Build();
}
const int requestCodeStartExposureNotification = 1111;
const int requestCodeGetTempExposureKeyHistory = 2222;
static TaskCompletionSource<object> tcsResolveConnection;
public static void OnActivityResult(int requestCode, Result resultCode, global::Android.Content.Intent data)
{
if (requestCode == requestCodeStartExposureNotification || requestCode == requestCodeGetTempExposureKeyHistory)
{
if (resultCode == Result.Ok)
tcsResolveConnection?.TrySetResult(null);
else
tcsResolveConnection.TrySetException(new AccessDeniedException("Failed to resolve Exposure Notifications API"));
}
}
static PropertyInfo apiExceptionMStatusPropertyInfo = null;
static async Task<T> ResolveApi<T>(int requestCode, Func<Task<T>> apiCall)
{
try
{
return await apiCall();
}
catch (ApiException apiEx)
{
if (apiEx.StatusCode == CommonStatusCodes.ResolutionRequired) // Resolution required
{
tcsResolveConnection = new TaskCompletionSource<object>();
// Look up the property if it's null
apiExceptionMStatusPropertyInfo ??=
apiEx.GetType().GetProperty("MStatus", BindingFlags.Instance | BindingFlags.NonPublic);
// Get the mStatus field from the java object using reflection since it's a protected property
var val = (Java.Lang.Object)apiExceptionMStatusPropertyInfo.GetValue(apiEx);
// Get the actual Statuses object back
var statuses = val.JavaCast<Statuses>();
// Start the resolution
statuses.StartResolutionForResult(Essentials.Platform.CurrentActivity, requestCode);
// Wait for the activity result to be called
await tcsResolveConnection.Task;
// Try the original api call again
return await apiCall();
}
}
return default;
}
static void PlatformInit()
{
_ = ScheduleFetchAsync();
}
static Task PlatformStart()
=> ResolveApi<object>(requestCodeStartExposureNotification, async () =>
{
await Instance.StartAsync();
return default;
});
static Task PlatformStop()
=> ResolveApi<object>(requestCodeStartExposureNotification, async () =>
{
await Instance.StopAsync();
return default;
});
static Task<bool> PlatformIsEnabled()
=> ResolveApi(requestCodeStartExposureNotification, () =>
Instance.IsEnabledAsync());
public static void ConfigureBackgroundWorkRequest(TimeSpan repeatInterval, Action<PeriodicWorkRequest.Builder> requestBuilder)
{
if (requestBuilder == null)
throw new ArgumentNullException(nameof(requestBuilder));
if (repeatInterval == null)
throw new ArgumentNullException(nameof(repeatInterval));
bgRequestBuilder = requestBuilder;
bgRepeatInterval = repeatInterval;
}
static Action<PeriodicWorkRequest.Builder> bgRequestBuilder = b =>
b.SetConstraints(new Constraints.Builder()
.SetRequiresBatteryNotLow(true)
.SetRequiresDeviceIdle(true)
.SetRequiredNetworkType(NetworkType.Connected)
.Build());
static TimeSpan bgRepeatInterval = TimeSpan.FromHours(6);
static Task PlatformScheduleFetch()
{
var workManager = WorkManager.GetInstance(Essentials.Platform.AppContext);
var workRequestBuilder = new PeriodicWorkRequest.Builder(
typeof(BackgroundFetchWorker),
bgRepeatInterval);
bgRequestBuilder.Invoke(workRequestBuilder);
var workRequest = workRequestBuilder.Build();
workManager.EnqueueUniquePeriodicWork("exposurenotification",
ExistingPeriodicWorkPolicy.Replace,
workRequest);
return Task.CompletedTask;
}
// Tells the local API when new diagnosis keys have been obtained from the server
static async Task PlatformDetectExposuresAsync(IEnumerable<string> keyFiles, System.Threading.CancellationToken cancellationToken)
{
var config = await GetConfigurationAsync();
await Instance.ProvideDiagnosisKeysAsync(
keyFiles.Select(f => new Java.IO.File(f)).ToList(),
config,
Guid.NewGuid().ToString());
}
static Task<IEnumerable<TemporaryExposureKey>> PlatformGetTemporaryExposureKeys()
=> ResolveApi(requestCodeGetTempExposureKeyHistory, async () =>
{
var exposureKeyHistory = await Instance.GetTemporaryExposureKeyHistoryAsync();
return exposureKeyHistory.Select(k =>
new TemporaryExposureKey(
k.GetKeyData(),
k.RollingStartIntervalNumber,
TimeSpan.Zero, // TODO: TimeSpan.FromMinutes(k.RollingDuration * 10),
k.TransmissionRiskLevel.FromNative()));
});
internal static async Task<IEnumerable<ExposureInfo>> PlatformGetExposureInformationAsync(string token)
{
var exposures = await Instance.GetExposureInformationAsync(token);
var info = exposures.Select(d => new ExposureInfo(
DateTimeOffset.UnixEpoch.AddMilliseconds(d.DateMillisSinceEpoch).UtcDateTime,
TimeSpan.FromMinutes(d.DurationMinutes),
d.AttenuationValue,
d.TotalRiskScore,
d.TransmissionRiskLevel.FromNative()));
return info;
}
internal static async Task<ExposureDetectionSummary> PlatformGetExposureSummaryAsync(string token)
{
var summary = await Instance.GetExposureSummaryAsync(token);
// TODO: Reevaluate byte usage here
return new ExposureDetectionSummary(
summary.DaysSinceLastExposure,
(ulong)summary.MatchedKeyCount,
summary.MaximumRiskScore,
summary.GetAttenuationDurationsInMinutes()
.Select(a => TimeSpan.FromMinutes(a)).ToArray(),
summary.SummationRiskScore);
}
static async Task<Status> PlatformGetStatusAsync()
{
var bt = BluetoothAdapter.DefaultAdapter;
if (bt == null || !bt.IsEnabled)
return Status.BluetoothOff;
var status = await Instance.IsEnabledAsync();
return status ? Status.Active : Status.Disabled;
}
}
public class BackgroundFetchWorker : Worker
{
public BackgroundFetchWorker(global::Android.Content.Context context, WorkerParameters workerParameters)
: base(context, workerParameters)
{
}
public override Result DoWork()
{
try
{
Task.Run(() => DoAsyncWork()).GetAwaiter().GetResult();
return Result.InvokeSuccess();
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine(ex);
return Result.InvokeRetry();
}
}
async Task DoAsyncWork()
{
if (await ExposureNotification.IsEnabledAsync())
await ExposureNotification.UpdateKeysFromServer();
}
}
static partial class Utils
{
public static RiskLevel FromNative(this int riskLevel) =>
riskLevel switch
{
AndroidRiskLevel.RiskLevelLowest => RiskLevel.Lowest,
AndroidRiskLevel.RiskLevelLow => RiskLevel.Low,
AndroidRiskLevel.RiskLevelLowMedium => RiskLevel.MediumLow,
AndroidRiskLevel.RiskLevelMedium => RiskLevel.Medium,
AndroidRiskLevel.RiskLevelMediumHigh => RiskLevel.MediumHigh,
AndroidRiskLevel.RiskLevelHigh => RiskLevel.High,
AndroidRiskLevel.RiskLevelVeryHigh => RiskLevel.VeryHigh,
AndroidRiskLevel.RiskLevelHighest => RiskLevel.Highest,
_ => AndroidRiskLevel.RiskLevelInvalid,
};
public static int ToNative(this RiskLevel riskLevel) =>
riskLevel switch
{
RiskLevel.Lowest => AndroidRiskLevel.RiskLevelLowest,
RiskLevel.Low => AndroidRiskLevel.RiskLevelLow,
RiskLevel.MediumLow => AndroidRiskLevel.RiskLevelLowMedium,
RiskLevel.Medium => AndroidRiskLevel.RiskLevelMedium,
RiskLevel.MediumHigh => AndroidRiskLevel.RiskLevelMediumHigh,
RiskLevel.High => AndroidRiskLevel.RiskLevelHigh,
RiskLevel.VeryHigh => AndroidRiskLevel.RiskLevelVeryHigh,
RiskLevel.Highest => AndroidRiskLevel.RiskLevelHighest,
_ => AndroidRiskLevel.RiskLevelInvalid,
};
}
}
| 31,828
|
https://github.com/simonscheider/mapmatching/blob/master/setup.py
|
Github Open Source
|
Open Source
|
MIT
| 2,022
|
mapmatching
|
simonscheider
|
Python
|
Code
| 10
| 53
|
from distutils.core import setup
setup(name='mapmatcher',
version='1.0',
packages=['mapmatcher'],
package_dir={'mapmatcher': 'mapmatcher'},
)
| 10,705
|
https://github.com/downplay/create-rogue-app/blob/master/games/hero/src/game/levels/Door.tsx
|
Github Open Source
|
Open Source
|
MIT
| 2,020
|
create-rogue-app
|
downplay
|
TypeScript
|
Code
| 123
| 284
|
import React from "react";
import { text, ContentAST } from "@hero/text";
import { Emoji } from "../../ui/Typography";
import { hasPosition, PositionState } from "../../mechanics/hasPosition";
import { hasTile, TileState } from "../../mechanics/hasTile";
import { entity } from "../../engine/entity";
import { canInteractWith } from "../../mechanics/canInteractWith";
export const DoorTile = () => <Emoji>🚪</Emoji>;
export type DoorState = PositionState &
TileState & {
// TODO: Not 100% sure how this will work, is it events or callbacks?
onEnter: ContentAST;
};
// TODO: Want two slightly different kinds of doors. Plain open/close ones a la DC:SS,
// then one like this with an event to go to different locations
export const Door = entity(text<DoorState>`
${hasTile(DoorTile)}
${hasPosition()}
${canInteractWith}
Type:
Door
onEnter:~
You walk through the door...
onInteract:~
$onEnter
`);
| 48,452
|
https://github.com/daibinhua888/NeuronFramework/blob/master/NNeuronFramework/ConcreteNetwork/Core/GraphNode.cs
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,018
|
NeuronFramework
|
daibinhua888
|
C#
|
Code
| 339
| 1,103
|
using NNeuronFramework.ConcreteNetwork.Core.Operations;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace NNeuronFramework.ConcreteNetwork.Core
{
public class GraphNode
{
public GraphNode()
{
this.Nexts = new List<GraphNodeConnector>();
this.Previouses = new List<GraphNodeConnector>();
this.IsProcessed = false;
this.CopyValueFrom = string.Empty;
this.Name = Guid.NewGuid().ToString("N");
this.IsTempNode = true;
this.IsWalked = false;
//this.IsRandomizeInit = false;
}
public NodeType NodeType { get; set; }
public Operation Operation { get; set; }
public bool IsProcessed { get; set; }
public string CopyValueFrom { get; set; }
public string Name { get; internal set; }
public List<GraphNodeConnector> Nexts { get; set; }
public List<GraphNodeConnector> Previouses { get; set; }
public bool IsWalked { get; set; }
public bool IsSavable { get; internal set; }
//public bool IsRandomizeInit { get; set; }
public bool IsStartable { get; set; }
public bool IsTempNode { get; set; }
public double[] Value { get; set; }
public Dictionary<string, double> Weights { get; set; }
public List<double[]> OutputValue { get; set; }
public int InputsCount { get; internal set; }
public int NeuronsCount { get; internal set; }
public bool IsWeightsNode { get; internal set; }
public bool IsMonitoringNode { get; set; }
public double B;
public static Dictionary<string, bool> processedParses = new Dictionary<string, bool>();
public List<string> ParseDirections()
{
if (this.IsWalked)
return new List<string>();
var lst = new List<string>();
foreach (var connect in Nexts)
{
var key = string.Format("{0}.{1}.{2}", this.Name, connect.Node.Name, connect.Operation.GetType().Name);
if (!processedParses.ContainsKey(key))
{
lst.Add(string.Format("\"{0}\"->\"{1}\"[label=\"{2}\"]", this.Name, connect.Node.Name, connect.Operation.GetType().Name.TrimEnd("Operation".ToCharArray())));
processedParses.Add(key, true);
}
}
foreach (var connect in Previouses)
{
var key = string.Format("{0}.{1}.{2}", connect.Node.Name, this.Name, connect.Operation.GetType().Name);
if (!processedParses.ContainsKey(key))
{
lst.Add(string.Format("\"{1}\"->\"{0}\"[label=\"{2}\"]", this.Name, connect.Node.Name, connect.Operation.GetType().Name.TrimEnd("Operation".ToCharArray())));
processedParses.Add(key, true);
}
}
this.IsWalked = true;
foreach (var connect in Nexts)
lst.AddRange(connect.Node.ParseDirections());
foreach (var connect in Previouses)
lst.AddRange(connect.Node.ParseDirections());
return lst;
}
public void RandomizeWeights()
{
var neuronsCount = this.NeuronsCount;
var inputsCount = this.Previouses.First().Node.InputsCount;
Console.WriteLine(neuronsCount);
Console.WriteLine(inputsCount);
Console.WriteLine("===============");
Dictionary<string, double> weights = new Dictionary<string, double>();
for (var nIndex = 0; nIndex < neuronsCount; nIndex++)
{
for (var inIndex = 0; inIndex < inputsCount; inIndex++)
{
string key = string.Format("{0}, {1}", nIndex, inIndex);
weights.Add(key, Utils.Utils.GenerateRandomValue());
}
}
this.Weights = weights;
}
}
}
| 31,299
|
https://github.com/TimofeyLuk/rs.ios-stage1-task1/blob/master/RSSchool_T1/RSSchool_T1/Exercises/5/PalindromeSolver.m
|
Github Open Source
|
Open Source
|
MIT
| 2,020
|
rs.ios-stage1-task1
|
TimofeyLuk
|
Objective-C
|
Code
| 149
| 433
|
#import "PalindromeSolver.h"
@implementation PalindromeSolver
// Complete the highestValuePalindrome function below.
- (NSString *) highestValuePalindrome:(NSString *)s n:(NSNumber *)n k:(NSNumber *)k {
NSMutableArray *arr = [[NSMutableArray alloc] initWithArray:@[]];
[s enumerateSubstringsInRange:(NSRange){0, [s length]} options: NSStringEnumerationByComposedCharacterSequences usingBlock:^(NSString * _Nullable substring, NSRange substringRange, NSRange enclosingRange, BOOL * _Nonnull stop) {[arr addObject:substring];}];
int chengeCount = 0;
long previouseMax = 0;
for (long i = ([n intValue] / 2); i >= 0; i -= 1) {
NSInteger firstElement = [[arr objectAtIndex: i] integerValue];
NSInteger secondElement = [[arr objectAtIndex: ([n intValue] - i - 1) ] integerValue];
if (firstElement != secondElement) {
long max = MAX(previouseMax,MAX(firstElement, secondElement));
previouseMax = max;
if (firstElement != max) {
chengeCount += 1;
}
if (secondElement != max) {
chengeCount += 1;
}
arr[i] = [NSString stringWithFormat:@"%ld", max];
arr[([n intValue] - i - 1)] = [NSString stringWithFormat:@"%ld", max];
}
}
return chengeCount == [k intValue] ? [arr componentsJoinedByString:@""] : @"-1";
}
@end
| 29,960
|
https://github.com/suhetao/srs.win/blob/master/trunk/win/lib/st/io_win.c
|
Github Open Source
|
Open Source
|
MIT
| 2,014
|
srs.win
|
suhetao
|
C
|
Code
| 1,845
| 6,131
|
/*
* The contents of this file are subject to the Netscape Public
* License Version 1.1 (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.mozilla.org/NPL/
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* The Original Code is Mozilla Communicator client code, released
* March 31, 1998.
*
* The Initial Developer of the Original Code is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1998-1999 Netscape Communications Corporation. All
* Rights Reserved.
*
* Portions created by SGI are Copyright (C) 2000 Silicon Graphics, Inc.
* All Rights Reserved.
*
* Contributor(s): Silicon Graphics, Inc.
*
* Alternatively, the contents of this file may be used under the terms
* of the ____ license (the "[____] License"), in which case the provisions
* of [____] License are applicable instead of those above. If you wish to
* allow use of your version of this file only under the terms of the [____]
* License and not to allow others to use your version of this file under the
* NPL, indicate your decision by deleting the provisions above and replace
* them with the notice and other provisions required by the [____] License.
* If you do not delete the provisions above, a recipient may use your version
* of this file under either the NPL or the [____] License.
*/
/*
* This file is derived directly from Netscape Communications Corporation,
* and consists of extensive modifications made during the year(s) 1999-2000.
*/
#include <stdlib.h>
#ifdef WIN32
#include <io.h>
#include <sys/uio.h>
#else
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/ioctl.h>
#include <sys/uio.h>
#include <sys/time.h>
#include <sys/resource.h>
#endif
#include <fcntl.h>
#include <signal.h>
#include <errno.h>
#include "common.h"
#define open _open
#define close _close
#if EAGAIN != EWOULDBLOCK
#define _IO_NOT_READY_ERROR ((errno == EAGAIN) || (errno == EWOULDBLOCK))
#else
#define _IO_NOT_READY_ERROR (errno == EAGAIN)
#endif
#define _LOCAL_MAXIOV 16
/* Winsock Data */
static WSADATA wsadata;
/* map winsock descriptors to small integers */
int fds[FD_SETSIZE+5];
/* File descriptor object free list */
static _st_netfd_t *_st_netfd_freelist = NULL;
/* Maximum number of file descriptors that the process can open */
static int _st_osfd_limit = -1;
static void _st_netfd_free_aux_data(_st_netfd_t *fd);
APIEXPORT int st_errno(void)
{
return(errno);
}
/* _st_GetError xlate winsock errors to unix */
int _st_GetError(int err)
{
int syserr;
if(err == 0) syserr=GetLastError();
SetLastError(0);
if(syserr < WSABASEERR) return(syserr);
switch(syserr)
{
case WSAEINTR: syserr=EINTR;
break;
case WSAEBADF: syserr=EBADF;
break;
case WSAEACCES: syserr=EACCES;
break;
case WSAEFAULT: syserr=EFAULT;
break;
case WSAEINVAL: syserr=EINVAL;
break;
case WSAEMFILE: syserr=EMFILE;
break;
case WSAEWOULDBLOCK: syserr=EAGAIN;
break;
case WSAEINPROGRESS: syserr=EINTR;
break;
case WSAEALREADY: syserr=EINTR;
break;
case WSAENOTSOCK: syserr=ENOTSOCK;
break;
case WSAEDESTADDRREQ: syserr=EDESTADDRREQ;
break;
case WSAEMSGSIZE: syserr=EMSGSIZE;
break;
case WSAEPROTOTYPE: syserr=EPROTOTYPE;
break;
case WSAENOPROTOOPT: syserr=ENOPROTOOPT;
break;
case WSAEOPNOTSUPP: syserr=EOPNOTSUPP;
break;
case WSAEADDRINUSE: syserr=EADDRINUSE;
break;
case WSAEADDRNOTAVAIL: syserr=EADDRNOTAVAIL;
break;
case WSAECONNABORTED: syserr=ECONNABORTED;
break;
case WSAECONNRESET: syserr=ECONNRESET;
break;
case WSAEISCONN: syserr=EISCONN;
break;
case WSAENOTCONN: syserr=ENOTCONN;
break;
case WSAETIMEDOUT: syserr=ETIMEDOUT;
break;
case WSAECONNREFUSED: syserr=ECONNREFUSED;
break;
case WSAEHOSTUNREACH: syserr=EHOSTUNREACH;
break;
}
return(syserr);
}
/* freefdsslot */
int freefdsslot(void)
{
int i;
for(i=5;i<FD_SETSIZE;i++)
{
if(fds[i] == 0) return(i);
}
return(-1);
}
/* getpagesize */
size_t getpagesize(void)
{
SYSTEM_INFO sysinf;
GetSystemInfo(&sysinf);
return(sysinf.dwPageSize);
}
int _st_io_init(void)
{
int i;
/* Set maximum number of open file descriptors */
_st_osfd_limit = FD_SETSIZE;
WSAStartup(2,&wsadata);
/* setup fds index. start at 5 */
for(i=0;i<5;i++) fds[i]=-1;
for(i=5;i<FD_SETSIZE;i++) fds[i]=0;
/* due to the braindead select implementation we need a dummy socket */
fds[4]=socket(AF_INET,SOCK_STREAM,0);
return 0;
}
APIEXPORT int st_getfdlimit(void)
{
return _st_osfd_limit;
}
void st_netfd_free(_st_netfd_t *fd)
{
if (!fd->inuse)
return;
fd->inuse = 0;
if (fd->aux_data)
_st_netfd_free_aux_data(fd);
if (fd->private_data && fd->destructor)
(*(fd->destructor))(fd->private_data);
fd->private_data = NULL;
fd->destructor = NULL;
fd->next = _st_netfd_freelist;
_st_netfd_freelist = fd;
}
static _st_netfd_t *_st_netfd_new(int osfd, int nonblock, int is_socket)
{
_st_netfd_t *fd;
int flags = 1;
int i;
i=freefdsslot();
if(i < 0)
{
errno=EMFILE;
return(NULL);
}
fds[i]=osfd; /* add osfd to index */
if ((*_st_eventsys->fd_new)(i) < 0)
return NULL;
if (_st_netfd_freelist) {
fd = _st_netfd_freelist;
_st_netfd_freelist = _st_netfd_freelist->next;
} else {
fd = (st_netfd_t)calloc(1, sizeof(_st_netfd_t));
if (!fd)
return NULL;
}
fd->osfd = i;
fd->inuse = 1;
fd->next = NULL;
if(is_socket == FALSE) return(fd);
if(nonblock) ioctlsocket(fds[fd->osfd], FIONBIO, (u_long*)&flags);
return fd;
}
APIEXPORT _st_netfd_t *st_netfd_open(int osfd)
{
return _st_netfd_new(osfd, 1, 0);
}
APIEXPORT _st_netfd_t *st_netfd_open_socket(int osfd)
{
return _st_netfd_new(osfd, 1, 1);
}
APIEXPORT int st_netfd_close(_st_netfd_t *fd)
{
if ((*_st_eventsys->fd_close)(fd->osfd) < 0)
return -1;
st_netfd_free(fd);
closesocket(fds[fd->osfd]);
fds[fd->osfd]=0;
errno=_st_GetError(0);
return(errno);
}
APIEXPORT int st_netfd_fileno(_st_netfd_t *fd)
{
return(fds[fd->osfd]);
}
APIEXPORT void st_netfd_setspecific(_st_netfd_t *fd, void *value,
_st_destructor_t destructor)
{
if (value != fd->private_data) {
/* Free up previously set non-NULL data value */
if (fd->private_data && fd->destructor)
(*(fd->destructor))(fd->private_data);
}
fd->private_data = value;
fd->destructor = destructor;
}
APIEXPORT void *st_netfd_getspecific(_st_netfd_t *fd)
{
return (fd->private_data);
}
/*
* Wait for I/O on a single descriptor.
*/
APIEXPORT int st_netfd_poll(_st_netfd_t *fd, int how, st_utime_t timeout)
{
struct pollfd pd;
int n;
pd.fd = fd->osfd;
pd.events = (short) how;
pd.revents = 0;
if ((n = st_poll(&pd, 1, timeout)) < 0)
return -1;
if (n == 0) {
/* Timed out */
errno = ETIME;
return -1;
}
if(pd.revents == 0) {
errno = EBADF;
return -1;
}
return 0;
}
/* No-op */
int st_netfd_serialize_accept(_st_netfd_t *fd)
{
fd->aux_data = NULL;
return 0;
}
/* No-op */
static void _st_netfd_free_aux_data(_st_netfd_t *fd)
{
fd->aux_data = NULL;
}
APIEXPORT _st_netfd_t *st_accept(_st_netfd_t *fd, struct sockaddr *addr, int *addrlen,
st_utime_t timeout)
{
int osfd;
_st_netfd_t *newfd;
while ((osfd = accept(fds[fd->osfd], addr, (socklen_t *)addrlen)) < 0)
{
errno=_st_GetError(0);
if(errno == EINTR) continue;
if(!_IO_NOT_READY_ERROR) return NULL;
/* Wait until the socket becomes readable */
if (st_netfd_poll(fd, POLLIN, timeout) < 0)
return NULL;
}
/* create newfd */
newfd = _st_netfd_new(osfd, 1, 1);
if(!newfd)
{
closesocket(osfd);
}
return newfd;
}
APIEXPORT int st_connect(_st_netfd_t *fd, const struct sockaddr *addr, int addrlen,
st_utime_t timeout)
{
int n, err = 0;
if(connect(fds[fd->osfd], addr, addrlen) < 0)
{
errno=_st_GetError(0);
if( (errno != EAGAIN) && (errno != EINTR)) return(-1);
/* Wait until the socket becomes writable */
if(st_netfd_poll(fd, POLLOUT, timeout) < 0) return(-1);
/* Try to find out whether the connection setup succeeded or failed */
n = sizeof(int);
if(getsockopt(fds[fd->osfd], SOL_SOCKET, SO_ERROR, (char *)&err,
(socklen_t *)&n) < 0) return(-1);
if(err)
{
errno = _st_GetError(err);
return -1;
}
}
return(0);
}
APIEXPORT ssize_t st_read(_st_netfd_t *fd, void *buf, size_t nbyte, st_utime_t timeout)
{
ssize_t n;
while((n = recv(fds[fd->osfd], (char*)buf, nbyte,0)) < 0)
{
errno=_st_GetError(0);
if(errno == EINTR) continue;
if(!_IO_NOT_READY_ERROR) return(-1);
/* Wait until the socket becomes readable */
if(st_netfd_poll(fd, POLLIN, timeout) < 0) return(-1);
}
return n;
}
APIEXPORT ssize_t st_read_fully(_st_netfd_t *fd, void *buf, size_t nbyte,
st_utime_t timeout)
{
ssize_t n;
size_t nleft = nbyte;
while (nleft > 0) {
if ((n = recv(fds[fd->osfd], (char*)buf, nleft,0)) < 0) {
errno=_st_GetError(0);
if (errno == EINTR)
continue;
if (!_IO_NOT_READY_ERROR)
return -1;
} else {
nleft -= n;
if (nleft == 0 || n == 0)
break;
buf = (void *)((char *)buf + n);
}
/* Wait until the socket becomes readable */
if (st_netfd_poll(fd, POLLIN, timeout) < 0)
return -1;
}
return (ssize_t)(nbyte - nleft);
}
APIEXPORT ssize_t st_write(_st_netfd_t *fd, const void *buf, size_t nbyte,
st_utime_t timeout)
{
ssize_t n;
ssize_t nleft = nbyte;
while (nleft > 0) {
if ((n = send(fds[fd->osfd], (char*)buf, nleft,0)) < 0) {
errno=_st_GetError(0);
if (errno == EINTR)
continue;
if (!_IO_NOT_READY_ERROR)
return -1;
} else {
if (n == nleft)
break;
nleft -= n;
buf = (const void *)((const char *)buf + n);
}
/* Wait until the socket becomes writable */
if (st_netfd_poll(fd, POLLOUT, timeout) < 0)
return -1;
}
return (ssize_t)nbyte;
}
#define _LOCAL_MAXIOV 16
static ssize_t _st_writev(int fd, struct iovec *iov, unsigned int iov_cnt)
{
size_t i;
size_t total;
void* pv = NULL;
ssize_t ret;
for(i = 0, total = 0; i < iov_cnt; ++i)
{
total += iov[i].iov_len;
}
pv = calloc(1, total);
if(NULL == pv){
errno = _st_GetError(0);
ret = -1;
}
else
{
for(i = 0, ret = 0; i < iov_cnt; ++i){
(void)memcpy((char*)pv + ret, iov[i].iov_base, iov[i].iov_len);
ret += (ssize_t)iov[i].iov_len;
}
if(!send(fd, (char*)pv,total,0)){
errno = _st_GetError(0);
ret = -1;
}
else{
ret = total;
}
(void)free(pv);
}
return ret;
}
APIEXPORT ssize_t st_writev(st_netfd_t fd, const struct iovec *iov, int iov_size,
st_utime_t timeout)
{
ssize_t n, rv;
size_t nleft, nbyte;
int index, iov_cnt;
struct iovec *tmp_iov;
struct iovec local_iov[_LOCAL_MAXIOV];
/* Calculate the total number of bytes to be sent */
nbyte = 0;
for (index = 0; index < iov_size; index++)
nbyte += iov[index].iov_len;
rv = (ssize_t)nbyte;
nleft = nbyte;
tmp_iov = (struct iovec *) iov; /* we promise not to modify iov */
iov_cnt = iov_size;
while (nleft > 0) {
if (iov_cnt == 1) {
if (st_write(fd, tmp_iov[0].iov_base, nleft, timeout) != (ssize_t) nleft)
rv = -1;
break;
}
if ((n = _st_writev(fd->osfd, tmp_iov, iov_cnt)) < 0) {
if (errno == EINTR)
continue;
if (!_IO_NOT_READY_ERROR) {
rv = -1;
break;
}
} else {
if ((size_t) n == nleft)
break;
nleft -= n;
/* Find the next unwritten vector */
n = (ssize_t)(nbyte - nleft);
for (index = 0; (size_t) n >= iov[index].iov_len; index++)
n -= iov[index].iov_len;
if (tmp_iov == iov) {
/* Must copy iov's around */
if (iov_size - index <= _LOCAL_MAXIOV) {
tmp_iov = local_iov;
} else {
tmp_iov = (struct iovec*)calloc(1, (iov_size - index) * sizeof(struct iovec));
if (tmp_iov == NULL)
return -1;
}
}
/* Fill in the first partial read */
tmp_iov[0].iov_base = &(((char *)iov[index].iov_base)[n]);
tmp_iov[0].iov_len = iov[index].iov_len - n;
index++;
/* Copy the remaining vectors */
for (iov_cnt = 1; index < iov_size; iov_cnt++, index++) {
tmp_iov[iov_cnt].iov_base = iov[index].iov_base;
tmp_iov[iov_cnt].iov_len = iov[index].iov_len;
}
}
/* Wait until the socket becomes writable */
if (st_netfd_poll(fd, POLLOUT, timeout) < 0) {
rv = -1;
break;
}
}
if (tmp_iov != iov && tmp_iov != local_iov)
free(tmp_iov);
return rv;
}
/*
* Simple I/O functions for UDP.
*/
APIEXPORT int st_recvfrom(_st_netfd_t *fd, void *buf, int len, struct sockaddr *from,
int *fromlen, st_utime_t timeout)
{
int n;
while ((n = recvfrom(fds[fd->osfd], (char*)buf, len, 0, from, (socklen_t *)fromlen))
< 0) {
errno=_st_GetError(0);
if (errno == EINTR)
continue;
if (!_IO_NOT_READY_ERROR)
return -1;
/* Wait until the socket becomes readable */
if (st_netfd_poll(fd, POLLIN, timeout) < 0)
return -1;
}
return n;
}
APIEXPORT int st_sendto(_st_netfd_t *fd, const void *msg, int len, const struct sockaddr *to,
int tolen, st_utime_t timeout)
{
int n;
while ((n = sendto(fds[fd->osfd], (char*)msg, len, 0, to, tolen)) < 0) {
errno=_st_GetError(0);
if (errno == EINTR)
continue;
if (!_IO_NOT_READY_ERROR)
return -1;
/* Wait until the socket becomes writable */
if (st_netfd_poll(fd, POLLOUT, timeout) < 0)
return -1;
}
return n;
}
/*
* To open FIFOs or other special files.
*/
APIEXPORT _st_netfd_t *st_open(const char *path, int oflags, mode_t mode)
{
int osfd, err;
_st_netfd_t *newfd;
while ((osfd = open(path, oflags, mode)) < 0) {
errno=_st_GetError(0);
if (errno != EINTR)
return NULL;
}
newfd = _st_netfd_new(osfd, 0, 0);
if (!newfd) {
errno=_st_GetError(0);
err = errno;
close(osfd);
errno = err;
}
return newfd;
}
| 16,365
|
https://github.com/willsalz/example-bazel-monorepo/blob/master/book_sorting/main.py
|
Github Open Source
|
Open Source
|
MIT
| 2,022
|
example-bazel-monorepo
|
willsalz
|
Python
|
Code
| 38
| 107
|
import click
@click.command()
@click.option("--count", default=1, help="Number of greetings.")
def cli(count):
"""
Stub program. TODO(Jonathon): Implement a more interesting program
Example usage: bazel run //book_sorting:main -- --count 45
"""
print("Hello world " * count)
if __name__ == "__main__":
cli()
| 48,313
|
https://github.com/bobjiangps/python-spider-example/blob/master/scrapy_example/scrapy_gitee/scrapy_gitee/__init__.py
|
Github Open Source
|
Open Source
|
MIT
| null |
python-spider-example
|
bobjiangps
|
Python
|
Code
| 6
| 16
|
# scrapy crawl scrapy_gitee -o repo.csv
| 7,789
|
https://github.com/Azure/azureml-examples/blob/master/sdk/python/foundation-models/huggingface/inference/token-classification/token-classification-online-endpoint.ipynb
|
Github Open Source
|
Open Source
|
MIT
| 2,023
|
azureml-examples
|
Azure
|
Jupyter Notebook
|
Code
| 1,248
| 4,015
|
{
"cells": [
{
"attachments": {},
"cell_type": "markdown",
"metadata": {},
"source": [
"## Deploy token-classification models from HuggingFaceHub to AzureML Online Endpoints\n",
"\n",
"This sample shows how to deploy `token-classification` models from the HuggingFaceHub to an online endpoint for inference. Learn more about `token-classification` task: https://huggingface.co/tasks/token-classification\n",
"\n",
"A large set of models hosted on [Hugging Face Hub](https://huggingface.co/models) are available in the Hugging Face Hub collection in AzureML Model Catalog. This collection is powered by the Hugging Face Hub community registry. Integration with the AzureML Model Catalog enables seamless deployment of Hugging Face Hub models in AzureML. _todo: learn more link_\n",
"\n",
"### Outline\n",
"* Set up pre-requisites.\n",
"* Pick a model to deploy.\n",
"* Deploy the model for real time inference.\n",
"* Try sample inference.\n",
"* Clean up resources."
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {},
"source": [
"### Set up pre-requisites\n",
"* Install dependencies\n",
"* Connect to AzureML Workspace. Learn more at [set up SDK authentication](https://learn.microsoft.com/en-us/azure/machine-learning/how-to-setup-authentication?tabs=sdk). Replace `<WORKSPACE_NAME>`, `<RESOURCE_GROUP>` and `<SUBSCRIPTION_ID>` below.\n",
"* Connect to `HuggingFaceHub` community registry"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from azure.ai.ml import MLClient\n",
"from azure.identity import (\n",
" DefaultAzureCredential,\n",
" InteractiveBrowserCredential,\n",
" ClientSecretCredential,\n",
")\n",
"from azure.ai.ml.entities import AmlCompute\n",
"import time\n",
"\n",
"try:\n",
" credential = DefaultAzureCredential()\n",
" credential.get_token(\"https://management.azure.com/.default\")\n",
"except Exception as ex:\n",
" credential = InteractiveBrowserCredential()\n",
"\n",
"# connect to a workspace\n",
"workspace_ml_client = None\n",
"try:\n",
" workspace_ml_client = MLClient.from_config(credential)\n",
" subscription_id = workspace_ml_client.subscription_id\n",
" workspace = workspace_ml_client.workspace_name\n",
" resource_group = workspace_ml_client.resource_group_name\n",
"except Exception as ex:\n",
" print(ex)\n",
" # Enter details of your workspace\n",
" subscription_id = \"<SUBSCRIPTION_ID>\"\n",
" resource_group = \"<RESOURCE_GROUP>\"\n",
" workspace = \"<AML_WORKSPACE_NAME>\"\n",
" workspace_ml_client = MLClient(\n",
" credential, subscription_id, resource_group, workspace\n",
" )\n",
"# Connect to the HuggingFaceHub registry\n",
"registry_ml_client = MLClient(credential, registry_name=\"HuggingFace\")\n",
"print(registry_ml_client)"
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {},
"source": [
"### Pick a model to deploy\n",
"\n",
"Open the Model Catalog in AzureML Studio and choose the Hugging Face Hub collection. Filter by the `token-classification` task and search any specific models you are interested in. In this example, we use the `dslim-bert-base-ner` model. If you plan to deploy a different model, replace the model name and version accordingly. "
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"model_name = \"dslim-bert-base-ner\"\n",
"foundation_model = registry_ml_client.models.get(model_name, version=\"17\")\n",
"print(\n",
" \"\\n\\nUsing model name: {0}, version: {1}, id: {2} for inferencing\".format(\n",
" foundation_model.name, foundation_model.version, foundation_model.id\n",
" )\n",
")"
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {},
"source": [
"### Deploy the model to an online endpoint\n",
"Online endpoints give a durable REST API that can be used to integrate with applications that need to use the model. Create an online endpoint and then create an online deployment. You need to specify the Virtual Machine instance or SKU when creating the deployment. You can find the optimal CPU or GPU SKU for a model by opening the quick deployment dialog from the model page in the AzureML Model Catalog. Specify the SKU in the `instance_type` input in deployment settings below.\n",
"\n",
"Typically Online Endpoints require you to provide scoring script and a docker container image (through an AzureML environment), in addition to the model. You don't need to worry about them for HuggingFace Hub models available in AzureML Model Catalog because we have enabled 'no code deployments' for these models by packaging scoring script and container image along with the model.\n",
"\n",
"Learn more about Online Endpoints: https://learn.microsoft.com/en-us/azure/machine-learning/how-to-deploy-online-endpoints"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import time, sys\n",
"from azure.ai.ml.entities import (\n",
" ManagedOnlineEndpoint,\n",
" ManagedOnlineDeployment,\n",
" OnlineRequestSettings,\n",
")\n",
"\n",
"# Create online endpoint - endpoint names need to be unique in a region, hence using timestamp to create unique endpoint name\n",
"timestamp = int(time.time())\n",
"online_endpoint_name = \"token-classification-\" + str(timestamp)\n",
"# create an online endpoint\n",
"endpoint = ManagedOnlineEndpoint(\n",
" name=online_endpoint_name,\n",
" description=\"Online endpoint for \"\n",
" + foundation_model.name\n",
" + \", for token-classification task\",\n",
" auth_mode=\"key\",\n",
")\n",
"workspace_ml_client.begin_create_or_update(endpoint).wait()"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# create a deployment\n",
"demo_deployment = ManagedOnlineDeployment(\n",
" name=\"demo\",\n",
" endpoint_name=online_endpoint_name,\n",
" model=foundation_model.id,\n",
" instance_type=\"Standard_DS3_v2\",\n",
" instance_count=1,\n",
")\n",
"workspace_ml_client.online_deployments.begin_create_or_update(demo_deployment).wait()\n",
"# online endpoints can have multiple deployments with traffic split or shadow traffic. Set traffic to 100% for demo deployment\n",
"endpoint.traffic = {\"demo\": 100}\n",
"workspace_ml_client.begin_create_or_update(endpoint).result()"
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {},
"source": [
"### Try sample inference\n",
"\n",
"Online endpoints expose a REST API that can be integrated into your applications. Learn how to fetch the scoring REST API and credentials for online endpoints here: https://learn.microsoft.com/en-us/azure/machine-learning/how-to-authenticate-online-endpoint\n",
"\n",
"In this example, we will use the Python SDK helper method to invoke the endpoint. "
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Get the model object from HuggingFaceHub. We can use it to check for sample test data\n",
"import urllib.request, json\n",
"\n",
"raw_data = urllib.request.urlopen(\n",
" \"https://huggingface.co/api/models/\" + foundation_model.tags[\"modelId\"]\n",
")\n",
"\n",
"print(\"https://huggingface.co/api/models/\" + foundation_model.tags[\"modelId\"])\n",
"data = json.load(raw_data)\n",
"print(data)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# check if there is sample inference data available on HuggingFaceHub for the model, else try with the backup sample data\n",
"scoring_file = \"./sample_score.json\"\n",
"inputs = []\n",
"if \"widgetData\" in data:\n",
" for input in data[\"widgetData\"]:\n",
" inputs.append(input[\"text\"])\n",
" # write the sample_score.json file\n",
" score_dict = {\"inputs\": inputs}\n",
" with open(scoring_file, \"w\") as outfile:\n",
" json.dump(score_dict, outfile)\n",
"else:\n",
" scoring_file = \"./sample_score_backup.json\"\n",
"\n",
"# print the sample scoring file\n",
"print(\"\\n\\nSample scoring file: \")\n",
"with open(scoring_file) as json_file:\n",
" scoring_data = json.load(json_file)\n",
" print(scoring_data)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# score the sample_score.json file using the online endpoint with the azureml endpoint invoke method\n",
"response = workspace_ml_client.online_endpoints.invoke(\n",
" endpoint_name=online_endpoint_name,\n",
" deployment_name=\"demo\",\n",
" request_file=scoring_file,\n",
")\n",
"response_json = json.loads(response)\n",
"print(json.dumps(response_json, indent=2))"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# load the repsonse into a dataframe to better visualize the results\n",
"import pandas as pd\n",
"\n",
"response_df = pd.DataFrame()\n",
"for result in response_json:\n",
" for row in result:\n",
" df = pd.DataFrame(row, index=[0])\n",
" response_df = pd.concat([response_df, df], ignore_index=True)\n",
"\n",
"print(response_df.head(len(response_df)))"
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {},
"source": [
"Let's make the output prettier and print it in below format:\n",
"\n",
"\"My name is Wolfgang [B-PER] and I live in Berlin [B-LOC]\""
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import json\n",
"\n",
"\n",
"def concatenate_entity(input_string, json_data):\n",
" data = json.loads(json_data)\n",
" output_string = input_string\n",
"\n",
" for sublist in data:\n",
" for entity in sublist:\n",
" word = entity.get(\"word\")\n",
" entity_type = entity.get(\"entity\")\n",
" if word and entity_type:\n",
" if word in output_string:\n",
" output_string = output_string.replace(\n",
" word, f\"{word} [{entity_type}]\"\n",
" )\n",
"\n",
" return output_string\n",
"\n",
"\n",
"for input_string in scoring_data[\"inputs\"]:\n",
" output = concatenate_entity(input_string, response)\n",
" print(output)"
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {},
"source": [
"### Delete the online endpoint\n",
"Don't forget to delete the online endpoint, else you will leave the billing meter running for the compute used by the endpoint."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"workspace_ml_client.online_endpoints.begin_delete(name=online_endpoint_name).wait()"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
}
],
"metadata": {
"kernelspec": {
"display_name": "updated",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.11.2"
},
"orig_nbformat": 4
},
"nbformat": 4,
"nbformat_minor": 2
}
| 16,404
|
https://github.com/consta-design-system/uikit/blob/master/src/components/UserSelect/__stand__/examples/UserSelectExampleItems/UserSelectExampleItems.tsx
|
Github Open Source
|
Open Source
|
MIT
| 2,023
|
uikit
|
consta-design-system
|
TSX
|
Code
| 98
| 321
|
import { Example } from '@consta/stand';
import React, { useState } from 'react';
import { UserSelect } from '../../../UserSelect';
type Item = {
label: string;
subLabel?: string;
avatarUrl?: string;
id: string | number;
};
const items: Item[] = [
{
label: 'Андрей Андреев',
subLabel: 'andrey@gmail.com',
id: 1,
},
{
label: 'Иван Иванов',
subLabel: 'ivan@gmail.com',
id: 2,
},
{
label: 'Егор Егоров',
subLabel: 'igor@icloud.com',
avatarUrl: 'https://avatars.githubusercontent.com/u/13190808?v=4',
id: 3,
},
];
export function UserSelectExampleItems() {
const [value, setValue] = useState<Item | null>();
return (
<Example col={1}>
<UserSelect
items={items}
value={value}
onChange={({ value }) => setValue(value)}
placeholder="Выберите пользователя"
/>
</Example>
);
}
| 8,224
|
https://github.com/deciduously/taocp/blob/master/vol1/ch01/euclid.scm
|
Github Open Source
|
Open Source
|
BSD-3-Clause
| null |
taocp
|
deciduously
|
Scheme
|
Code
| 32
| 77
|
(import (rnrs))
(define gcd
(lambda (m n)
(if (and (>= m 0) (>= n 0))
(cond [(= n 0) m]
[else (gcd n (mod m n))])
(- 1))))
(display (gcd 119 544))
| 6,682
|
https://github.com/lnmaurer/pyGSTi/blob/master/test/unit/tools/test_slicetools.py
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,020
|
pyGSTi
|
lnmaurer
|
Python
|
Code
| 142
| 509
|
from ..util import BaseCase
import numpy as np
from pygsti.tools.slicetools import *
N = 100
slices = []
for i in range(1, N):
for j in range(1, N):
for k in [1, 2]:
slices.append(slice(i, j, k))
class SliceToolsTester(BaseCase):
def test_length(self):
for s in slices:
length(s)
self.assertEqual(length(slice(10)), 0)
self.assertEqual(length(slice(1, 10)), 9)
def test_indices(self):
for s in slices:
indices(s)
indices(slice(10))
# TODO assert correctness
def test_intersect(self):
intersect(slice(None, 10, 1), slice(1, 10, 1))
intersect(slice(1, 10, 1), slice(None, 10, 1))
intersect(slice(1, None, 1), slice(1, 10, 1))
intersect(slice(1, 10, 1), slice(1, None, 1))
intersect(slice(10, -10, 1), slice(10, -10, 1))
# TODO assert correctness
def test_list_to_slice(self):
self.assertEqual(list_to_slice([]), slice(0, 0))
self.assertEqual(list_to_slice([1, 2, 3, 4]), slice(1, 5))
self.assertEqual(list_to_slice(slice(0, 4)), slice(0, 4))
with self.assertRaises(ValueError):
list_to_slice([0, 1, 2, 3, 10]) # doesn't correspond to a slice
def test_asarray(self):
self.assertArraysAlmostEqual(as_array(slice(0, 10)), np.arange(10))
self.assertArraysAlmostEqual(as_array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]), np.arange(10))
| 43,022
|
https://github.com/PerfectusInc/zenshoppe-responsive-encart-template/blob/master/Theme/includes/templates/zenshoppe/templates/tpl_modules_listing_display_order.php
|
Github Open Source
|
Open Source
|
MIT
| 2,017
|
zenshoppe-responsive-encart-template
|
PerfectusInc
|
PHP
|
Code
| 254
| 889
|
<?php
/**
* Module Template
*
* @package templateSystem
* @copyright Copyright 2003-2006 Zen Cart Development Team
* @copyright Portions Copyright 2003 osCommerce
* @license http://www.zen-cart.com/license/2_0.txt GNU Public License V2.0
* @version $Id: tpl_modules_listing_display_order.php 3369 2006-04-03 23:09:13Z drbyte $
*/
?>
<?php
// NOTE: to remove a sort order option add an HTML comment around the option to be removed
?>
<div class="sorter">
<?php
echo zen_draw_form('sorter_form', zen_href_link($_GET['main_page']), 'get');
echo zen_draw_hidden_field('main_page', $_GET['main_page']);
// echo zen_draw_hidden_field('disp_order', $_GET['disp_order']);
echo zen_hide_session_id();
?>
<?php
if (PRODUCT_LISTING_GRID_SORT) {
echo '<label for="disp-order-sorter">' . PRODUCT_LISTING_GRID_SORT_TEXT . '</label>';
?>
<select name="disp_order" onchange="this.form.submit();" id="disp-order-sorter">
<?php if ($disp_order != $disp_order_default) { ?>
<option value="<?php echo $disp_order_default; ?>" <?php echo ($disp_order == $disp_order_default ? 'selected="selected"' : ''); ?>><?php echo PULL_DOWN_ALL_RESET; ?></option>
<?php } // reset to store default ?>
<option value="1" <?php echo ($disp_order == '1' ? 'selected="selected"' : ''); ?>><?php echo TEXT_INFO_SORT_BY_PRODUCTS_NAME; ?></option>
<option value="2" <?php echo ($disp_order == '2' ? 'selected="selected"' : ''); ?>><?php echo TEXT_INFO_SORT_BY_PRODUCTS_NAME_DESC; ?></option>
<option value="3" <?php echo ($disp_order == '3' ? 'selected="selected"' : ''); ?>><?php echo TEXT_INFO_SORT_BY_PRODUCTS_PRICE; ?></option>
<option value="4" <?php echo ($disp_order == '4' ? 'selected="selected"' : ''); ?>><?php echo TEXT_INFO_SORT_BY_PRODUCTS_PRICE_DESC; ?></option>
<option value="5" <?php echo ($disp_order == '5' ? 'selected="selected"' : ''); ?>><?php echo TEXT_INFO_SORT_BY_PRODUCTS_MODEL; ?></option>
<option value="6" <?php echo ($disp_order == '6' ? 'selected="selected"' : ''); ?>><?php echo TEXT_INFO_SORT_BY_PRODUCTS_DATE_DESC; ?></option>
<option value="7" <?php echo ($disp_order == '7' ? 'selected="selected"' : ''); ?>><?php echo TEXT_INFO_SORT_BY_PRODUCTS_DATE; ?></option>
</select>
<?php
}
?>
<?php
/* Gridview- Listview tab */
echo $gridlist_tab;
// draw alpha sorter
//require(DIR_WS_MODULES . zen_get_module_directory(FILENAME_PRODUCT_LISTING_ALPHA_SORTER));
?>
</form>
</div>
| 36,881
|
https://github.com/prosolotechnologies/prosolo/blob/master/prosolo-main/src/main/java/org/prosolo/services/nodes/data/resourceAccess/RestrictedAccessResult.java
|
Github Open Source
|
Open Source
|
BSD-3-Clause
| null |
prosolo
|
prosolotechnologies
|
Java
|
Code
| 67
| 207
|
package org.prosolo.services.nodes.data.resourceAccess;
import java.io.Serializable;
public class RestrictedAccessResult<T> implements Serializable {
private static final long serialVersionUID = -3718705470521304506L;
private final T resource;
private final ResourceAccessData access;
private RestrictedAccessResult(T resource, ResourceAccessData access) {
this.resource = resource;
this.access = access;
}
public static <T> RestrictedAccessResult<T> of(T resource, ResourceAccessData access) {
return new RestrictedAccessResult<T>(resource, access);
}
public T getResource() {
return resource;
}
public ResourceAccessData getAccess() {
return access;
}
}
| 12,703
|
https://github.com/sajustsmile/twitter-blockchain/blob/master/studio/node_modules/@sanity/types/parts/part.@sanity/components/build-snapshot/__legacy/@sanity/components/layer/LayerProvider.d.ts
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,021
|
twitter-blockchain
|
sajustsmile
|
TypeScript
|
Code
| 11
| 31
|
import React from 'react'
export declare function LayerProvider({children}: {children: React.ReactNode}): JSX.Element
| 8,290
|
https://github.com/travisll/dotfiles.fish/blob/master/k9s/install.fish
|
Github Open Source
|
Open Source
|
MIT
| 2,021
|
dotfiles.fish
|
travisll
|
Fish
|
Code
| 30
| 183
|
#!/usr/bin/env fish
if command -qs k9s
switch (uname)
case Darwin
mkdir -p ~/Library/Preferences/k9s
curl -sL https://raw.githubusercontent.com/derailed/k9s/master/skins/dracula.yml -o ~/Library/Preferences/k9s/skin.yml
case Linux
mkdir -p $XDG_CONFIG_HOME/k9s
curl -sL https://raw.githubusercontent.com/derailed/k9s/master/skins/dracula.yml -o $XDG_CONFIG_HOME/k9s/skin.yml
end
end
| 38,119
|
https://github.com/jguerin4/Ascenseur-s-creed/blob/master/Assets/Scenes/ComboScene.unity.meta
|
Github Open Source
|
Open Source
|
CC-BY-3.0, CC-BY-4.0
| 2,015
|
Ascenseur-s-creed
|
jguerin4
|
Unity3D Asset
|
Code
| 6
| 39
|
fileFormatVersion: 2
guid: 8b0d8682864db184b961a8226c997ffc
DefaultImporter:
userData:
| 13,598
|
https://github.com/atdavidpark/gloo-mesh/blob/master/pkg/meshctl/commands/describe/destinations/describe_traffictarget.go
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,022
|
gloo-mesh
|
atdavidpark
|
Go
|
Code
| 376
| 1,570
|
package destinations
import (
"bytes"
"context"
"fmt"
"strings"
"github.com/olekukonko/tablewriter"
discoveryv1 "github.com/solo-io/gloo-mesh/pkg/api/discovery.mesh.gloo.solo.io/v1"
"github.com/solo-io/gloo-mesh/pkg/meshctl/commands/describe/printing"
"github.com/solo-io/gloo-mesh/pkg/meshctl/utils"
v1 "github.com/solo-io/skv2/pkg/api/core.skv2.solo.io/v1"
"github.com/spf13/cobra"
"github.com/spf13/pflag"
"sigs.k8s.io/controller-runtime/pkg/client"
)
func Command(ctx context.Context) *cobra.Command {
opts := &options{}
cmd := &cobra.Command{
Use: "destination",
Short: "Description of discovered Destinations",
Aliases: []string{"destinations"},
RunE: func(cmd *cobra.Command, args []string) error {
c, err := utils.BuildClient(opts.kubeconfig, opts.kubecontext)
if err != nil {
return err
}
description, err := describeDestinations(ctx, c, opts.searchTerms)
if err != nil {
return err
}
fmt.Println(description)
return nil
},
}
cmd.SilenceUsage = true
return cmd
}
type options struct {
kubeconfig string
kubecontext string
searchTerms []string
}
func (o *options) addToFlags(flags *pflag.FlagSet) {
utils.AddManagementKubeconfigFlags(&o.kubeconfig, &o.kubecontext, flags)
flags.StringSliceVarP(&o.searchTerms, "search", "s", []string{}, "A list of terms to match traffic target names against")
}
func describeDestinations(ctx context.Context, c client.Client, searchTerms []string) (string, error) {
destinationClient := discoveryv1.NewDestinationClient(c)
destinationList, err := destinationClient.ListDestination(ctx)
if err != nil {
return "", err
}
var destinationDescriptions []destinationDescription
for _, destination := range destinationList.Items {
destination := destination // pike
if matchDestination(destination, searchTerms) {
destinationDescriptions = append(destinationDescriptions, describeDestination(&destination))
}
}
buf := new(bytes.Buffer)
table := tablewriter.NewWriter(buf)
table.SetHeader([]string{"Metadata", "Traffic_Policies", "Access_Policies"})
table.SetRowLine(true)
table.SetAutoWrapText(false)
for _, description := range destinationDescriptions {
table.Append([]string{
description.Metadata.string(),
printing.FormattedObjectRefs(description.TrafficPolicies),
printing.FormattedObjectRefs(description.AccessPolicies),
})
}
table.Render()
return buf.String(), nil
}
func (m destinationMetadata) string() string {
var s strings.Builder
s.WriteString(printing.FormattedField("Name", m.Name))
s.WriteString(printing.FormattedField("Namespace", m.Namespace))
s.WriteString(printing.FormattedField("Cluster", m.Cluster))
s.WriteString(printing.FormattedField("Type", m.Type))
s.WriteString(printing.FormattedField("Federated DNS Name", m.FederatedDnsName))
return s.String()
}
type destinationDescription struct {
Metadata *destinationMetadata
TrafficPolicies []*v1.ObjectRef
AccessPolicies []*v1.ObjectRef
}
type destinationMetadata struct {
Type string
Name string
Namespace string
Cluster string
FederatedDnsName string
FederatedToMeshes []*v1.ObjectRef
}
func matchDestination(destination discoveryv1.Destination, searchTerms []string) bool {
// do not apply matching when there are no search strings
if len(searchTerms) == 0 {
return true
}
for _, s := range searchTerms {
if strings.Contains(destination.Name, s) {
return true
}
}
return false
}
func describeDestination(destination *discoveryv1.Destination) destinationDescription {
meshMeta := getDestinationMetadata(destination)
var trafficPolicies []*v1.ObjectRef
for _, fs := range destination.Status.AppliedTrafficPolicies {
trafficPolicies = append(trafficPolicies, fs.Ref)
}
var accessPolicies []*v1.ObjectRef
for _, vm := range destination.Status.AppliedAccessPolicies {
accessPolicies = append(accessPolicies, vm.Ref)
}
return destinationDescription{
Metadata: &meshMeta,
TrafficPolicies: trafficPolicies,
AccessPolicies: accessPolicies,
}
}
func getDestinationMetadata(destination *discoveryv1.Destination) destinationMetadata {
switch destination.Spec.GetType().(type) {
case *discoveryv1.DestinationSpec_KubeService_:
kubeServiceRef := destination.Spec.GetKubeService().Ref
return destinationMetadata{
Type: "kubernetes service",
Name: kubeServiceRef.Name,
Namespace: kubeServiceRef.Namespace,
Cluster: kubeServiceRef.ClusterName,
FederatedDnsName: destination.Status.GetAppliedFederation().GetFederatedHostname(),
FederatedToMeshes: destination.Status.GetAppliedFederation().GetFederatedToMeshes(),
}
}
return destinationMetadata{}
}
| 9,636
|
https://github.com/r3volutionary/metaplex/blob/master/js/packages/web/src/actions/index.ts
|
Github Open Source
|
Open Source
|
Apache-2.0
| null |
metaplex
|
r3volutionary
|
TypeScript
|
Code
| 24
| 66
|
export * from './nft';
export * from './createVault';
export * from './makeAuction';
export * from './createExternalFractionPriceAccount';
export * from './deprecatedPopulatePrintingTokens';
export * from './addTokensToVault';
| 5,808
|
https://github.com/kimoapp/Jarvis.Framework/blob/master/Jarvis.Framework.Tests/ProjectionsTests/Atomic/LiveAtomicReadModelProcessorTests.cs
|
Github Open Source
|
Open Source
|
MIT
| 2,021
|
Jarvis.Framework
|
kimoapp
|
C#
|
Code
| 344
| 1,778
|
using Jarvis.Framework.Shared.Events;
using Jarvis.Framework.Shared.ReadModel.Atomic;
using Jarvis.Framework.Tests.ProjectionsTests.Atomic.Support;
using NUnit.Framework;
using System;
using System.Threading.Tasks;
namespace Jarvis.Framework.Tests.ProjectionsTests.Atomic
{
[TestFixture]
public class LiveAtomicReadModelProcessorTests : AtomicProjectionEngineTestBase
{
[Test]
public async Task Project_distinct_entities()
{
var c1 = await GenerateSomeChangesetsAndReturnLatestsChangeset().ConfigureAwait(false);
_aggregateIdSeed++;
var c2 = await GenerateSomeChangesetsAndReturnLatestsChangeset().ConfigureAwait(false);
await GenerateTouchedEvent().ConfigureAwait(false);
//ok we need to check that events are not mixed.
var sut = _container.Resolve<ILiveAtomicReadModelProcessor>();
var processed = await sut.ProcessAsync<SimpleTestAtomicReadModel>(((DomainEvent)c1.Events[0]).AggregateId, Int32.MaxValue).ConfigureAwait(false);
Assert.That(processed.TouchCount, Is.EqualTo(2));
processed = await sut.ProcessAsync<SimpleTestAtomicReadModel>(((DomainEvent)c2.Events[0]).AggregateId, Int32.MaxValue).ConfigureAwait(false);
Assert.That(processed.TouchCount, Is.EqualTo(3));
}
[Test]
public async Task Project_up_until_certain_aggregate_version()
{
var c1 = await GenerateSomeChangesetsAndReturnLatestsChangeset().ConfigureAwait(false);
var c2 = await GenerateTouchedEvent().ConfigureAwait(false);
//ok we need to check that events are not mixed.
var sut = _container.Resolve<ILiveAtomicReadModelProcessor>();
var processed = await sut.ProcessAsync<SimpleTestAtomicReadModel>(((DomainEvent)c1.Events[0]).AggregateId, c1.AggregateVersion).ConfigureAwait(false);
Assert.That(processed.TouchCount, Is.EqualTo(2));
processed = await sut.ProcessAsync<SimpleTestAtomicReadModel>(((DomainEvent)c1.Events[0]).AggregateId, c2.AggregateVersion).ConfigureAwait(false);
Assert.That(processed.TouchCount, Is.EqualTo(3));
}
[Test]
public async Task Project_up_until_certain_checkpoint_number()
{
var c1 = await GenerateSomeChangesetsAndReturnLatestsChangeset().ConfigureAwait(false);
var c2 = await GenerateTouchedEvent().ConfigureAwait(false);
//ok we need to check that events are not mixed.
var sut = _container.Resolve<ILiveAtomicReadModelProcessor>();
DomainEvent firstEvent = (DomainEvent)c1.Events[0];
var processed = await sut.ProcessAsyncUntilChunkPosition<SimpleTestAtomicReadModel>(
firstEvent.AggregateId.AsString(),
firstEvent.CheckpointToken).ConfigureAwait(false);
Assert.That(processed.TouchCount, Is.EqualTo(2));
Assert.That(processed.AggregateVersion, Is.EqualTo(3));
firstEvent = (DomainEvent)c2.Events[0];
processed = await sut.ProcessAsyncUntilChunkPosition<SimpleTestAtomicReadModel>(
firstEvent.AggregateId.AsString(),
firstEvent.CheckpointToken).ConfigureAwait(false);
Assert.That(processed.TouchCount, Is.EqualTo(3));
Assert.That(processed.AggregateVersion, Is.EqualTo(4));
}
[Test]
public async Task Capability_of_catchup_events()
{
await GenerateSomeChangesetsAndReturnLatestsChangeset().ConfigureAwait(false);
var c2 = await GenerateSomeChangesetsAndReturnLatestsChangeset().ConfigureAwait(false);
var c3 = await GenerateTouchedEvent().ConfigureAwait(false);
//Arrange: manually process some events in readmodel
var firstEvent = (DomainEvent)c2.Events[0];
var sut = _container.Resolve<ILiveAtomicReadModelProcessor>();
var rm = await sut.ProcessAsync<SimpleTestAtomicReadModel>(
firstEvent.AggregateId.AsString(),
c2.AggregateVersion).ConfigureAwait(false);
Assert.That(rm.AggregateVersion, Is.EqualTo(c2.AggregateVersion));
var touchCount = rm.TouchCount;
//Act, ask to catchup events.
await sut.CatchupAsync(rm).ConfigureAwait(false);
Assert.That(rm.AggregateVersion, Is.EqualTo(c3.AggregateVersion));
Assert.That(rm.TouchCount, Is.EqualTo(touchCount + 1));
}
[Test]
public async Task Cacthup_events_with_no_more_Events_works()
{
await GenerateSomeChangesetsAndReturnLatestsChangeset().ConfigureAwait(false);
var c2 = await GenerateSomeChangesetsAndReturnLatestsChangeset().ConfigureAwait(false);
//Arrange: manually process some events in readmodel
var firstEvent = (DomainEvent)c2.Events[0];
var sut = _container.Resolve<ILiveAtomicReadModelProcessor>();
var rm = await sut.ProcessAsync<SimpleTestAtomicReadModel>(
firstEvent.AggregateId.AsString(),
c2.AggregateVersion).ConfigureAwait(false);
Assert.That(rm.AggregateVersion, Is.EqualTo(c2.AggregateVersion));
var touchCount = rm.TouchCount;
//Act, ask to catchup events.
await sut.CatchupAsync(rm).ConfigureAwait(false);
Assert.That(rm.AggregateVersion, Is.EqualTo(c2.AggregateVersion));
Assert.That(rm.TouchCount, Is.EqualTo(touchCount));
}
[Test]
public async Task Capability_of_catchup_to_project_everything()
{
await GenerateSomeChangesetsAndReturnLatestsChangeset().ConfigureAwait(false);
await GenerateSomeChangesetsAndReturnLatestsChangeset().ConfigureAwait(false);
var c3 = await GenerateTouchedEvent().ConfigureAwait(false);
//Arrange: manually process some events in readmodel
var firstEvent = (DomainEvent) c3.Events[0];
var sut = _container.Resolve<ILiveAtomicReadModelProcessor>();
var rm = new SimpleTestAtomicReadModel(firstEvent.AggregateId);
//Act, ask to catchup events.
await sut.CatchupAsync(rm).ConfigureAwait(false);
Assert.That(rm.AggregateVersion, Is.EqualTo(c3.AggregateVersion));
Assert.That(rm.TouchCount, Is.EqualTo(3)); //we have 3 touch events.
}
}
}
| 43,276
|
https://github.com/liorhson/artifactory-client-java/blob/master/api/src/main/java/org/jfrog/artifactory/client/model/repository/settings/ComposerRepositorySettings.java
|
Github Open Source
|
Open Source
|
Apache-2.0
| null |
artifactory-client-java
|
liorhson
|
Java
|
Code
| 16
| 54
|
package org.jfrog.artifactory.client.model.repository.settings;
public interface ComposerRepositorySettings extends VcsRepositorySettings {
// ** remote ** //
String getComposerRegistryUrl();
}
| 30,379
|
https://github.com/hanson-young/reid-strong-baseline/blob/master/modeling/download.py
|
Github Open Source
|
Open Source
|
MIT
| null |
reid-strong-baseline
|
hanson-young
|
Python
|
Code
| 5
| 63
|
import torch.utils.model_zoo as model_zoo
model_zoo.load_url('http://data.lip6.fr/cadene/pretrainedmodels/se_resnext50_32x4d-a260b3a4.pth')
| 41,328
|
https://github.com/ashkaushik0007/foodtriangle_beta/blob/master/.gitignore
|
Github Open Source
|
Open Source
|
MIT
| 2,017
|
foodtriangle_beta
|
ashkaushik0007
|
Ignore List
|
Code
| 1
| 11
|
/src/app/app.config.ts
| 30,191
|
https://github.com/yosephtesfaye/mof/blob/master/src/main/resources/static/js/file.js
|
Github Open Source
|
Open Source
|
MIT
| 2,021
|
mof
|
yosephtesfaye
|
JavaScript
|
Code
| 91
| 493
|
$(document).ready(function()
{
$('#loader').hide();
$("#signup").on("click",function(){
$("#signup").prop("disabled",true);
var name=$("#name").val();
var file=$("#file").val();
// Get form
var form=$('#register-form')[0];
var data=new formData(form);
data.append("name",name);
$('#loader').show();
if(name == "" || file == ""){
$("#signup").prop("disabled",false);
$('#loader').hide();
$("#name").css("border-color","red");
$("#file").css("border-color","red");
$("#error_name").html("Please fill the required filed.");
$("#error_file").html("Please fill the required filed.");
} else{
$("#name").css("border-color","");
$("#file").css("border-color","");
$("#error_name").css('opacity',0);
$("#error_file").css('opacity',0);
$.ajax({
type:'POST',
enctype:'multipart/form-data',
data:data,
url:"file-upload",
processData:false,//prevent jquery from automatically transforming the data
contentType:false,//tell jquery not to set the conttype
cache:false,
success: function(data,statusText ,xhr){
console.log(xhr.status);
if(xhr.status == "200"){
$('#loader').hide();
$("#register-form")[0].reset();
$("#error").text("");
$("#success").text(data);
$('#success').delay(5000).fadeOut('slow');
$("#signup").prop("disabled",false);
}
},
error:function(e){
$('#loader').hide();
$("#error").text(e.responseText);
$('#error').delay(10000).fadeOut('slow');
$("#signup").prop("disabled",false);
}
});
}
});
});
| 31,124
|
https://github.com/nistefan/cmssw/blob/master/Calibration/HcalCalibAlgos/macros/install_OfflineMain.sh
|
Github Open Source
|
Open Source
|
Apache-2.0
| null |
cmssw
|
nistefan
|
Shell
|
Code
| 11
| 45
|
g++ -Wall -Wno-deprecated -I./ `root-config --cflags` OfflineMain.C -o OfflineMain.exe `root-config --libs`
| 11,109
|
https://github.com/foss-card-games/Solitairey/blob/master/ext/yui-unpack/yui/docs/assets/datatable/datatable-chkboxselect-tests.js
|
Github Open Source
|
Open Source
|
BSD-2-Clause, BSD-2-Clause-Views, BSD-3-Clause, MIT, GPL-1.0-or-later, LicenseRef-scancode-public-domain, LicenseRef-scancode-free-unknown
| 2,023
|
Solitairey
|
foss-card-games
|
JavaScript
|
Code
| 260
| 714
|
YUI.add('datatable-chkboxselect-tests', function(Y) {
var suite = new Y.Test.Suite('datatable-chkboxselect example test suite'),
Assert = Y.Assert;
/** this sets the constrain checkbox to checked or not
* The example code looks for chkbox.on('click')... attr checked == true
* IE doesn't set attr checked with a click
* In non-IE, if you set checked to true then also click it checked == false (it seems)
* @param expectedState Boolean
*/
var clickCheckbox = function(checkbox, expectedState) {
if (Y.UA.ie && Y.UA.ie < 9) {
checkbox.set("checked", expectedState);
} else {
// Just in case it's already at that state, and the test wants to flip it with the click
if (checkbox.get("checked") === expectedState) {
checkbox.set("checked", !expectedState);
}
}
checkbox.simulate("click");
}
var tableSelector = '#dtable ',
th = Y.all(tableSelector + 'th'),
td = Y.all(tableSelector + 'td'),
tr = Y.all(tableSelector + 'tr');
suite.add(new Y.Test.Case({
name: 'Example tests',
'test populating with HTML table': function() {
Assert.areEqual(8, th.size(), ' - Wrong number of th');
Assert.isTrue((td.size() > 20), ' - Wrong number of td');
Assert.isTrue((tr.size() > 10), ' - Wrong number of tr');
Assert.isTrue((tr.item(3).hasClass('yui3-datatable-odd')), ' - Failed to assign odd row class');
Assert.isTrue((td.item(0).getHTML().indexOf('checkbox') > -1), ' - Failed to insert input HTML');
},
'test selecting and processing': function() {
clickCheckbox(td.item(0).one('input'), true);
//clickCheckbox(td.item(4).one('input'), true); // I don't know why this one doesn't work
Y.one('#btnSelected').simulate('click');
Assert.isTrue((Y.one('#processed').getHTML().indexOf('Record index = 0 Data = 20 : FTP_data') > -1), ' - Failed to process checkbox selection');
},
'test clearing selection': function() {
Y.one('#btnClearSelected').simulate('click');
Assert.isTrue((Y.one('#processed').getHTML().indexOf('(None)') > -1), ' - Failed to clear checkbox selection');
}
}));
Y.Test.Runner.add(suite);
}, '', { requires: [ 'node', 'node-event-simulate' ] });
| 38,132
|
https://github.com/ponyatov/replit/blob/master/docs/search/classes_b.js
|
Github Open Source
|
Open Source
|
MIT
| null |
replit
|
ponyatov
|
JavaScript
|
Code
| 6
| 64
|
var searchData=
[
['net',['Net',['../classmetaL_1_1Net.html',1,'metaL']]],
['number',['Number',['../classmetaL_1_1Number.html',1,'metaL']]]
];
| 34,144
|
https://github.com/martin-hughes/project_azalea/blob/master/test/dummy_libs/synch/kernel_mutexes.dummy.cpp
|
Github Open Source
|
Open Source
|
MIT
| 2,022
|
project_azalea
|
martin-hughes
|
C++
|
Code
| 270
| 869
|
// KLIB mutex dummy implementation for test scripts.
// The mutex implementation in the main code relies upon the task scheduling system, which can't easily be emulated in
// the test code. As such, create a dummy implementation here.
//#define ENABLE_TRACING
#include "klib/klib.h"
#include <thread>
#include <mutex>
#include <memory>
#include <map>
std::map<klib_mutex *, std::unique_ptr<std::mutex>> mutex_map;
// Initialize a mutex object. The owner of the mutex object is responsible for managing the memory associated with it.
void klib_synch_mutex_init(klib_mutex &mutex)
{
KL_TRC_ENTRY;
klib_synch_spinlock_init(mutex.access_lock);
klib_synch_spinlock_lock(mutex.access_lock);
mutex.mutex_locked = false;
mutex.owner_thread = nullptr;
klib_list_initialize(&mutex.waiting_threads_list);
klib_synch_spinlock_unlock(mutex.access_lock);
mutex_map[&mutex] = std::make_unique<std::mutex>();
KL_TRC_EXIT;
}
// Acquire the mutex for the currently running thread. It is permissible for a thread to call this function when it
// already owns the mutex - nothing happens. The maximum time to wait is max_wait milliseconds. If max_wait is set to
// MUTEX_MAX_WAIT then the caller waits indefinitely. Threads acquire the mutex in order that they call this function.
//
// The return values should be self-explanatory.
SYNC_ACQ_RESULT klib_synch_mutex_acquire(klib_mutex &mutex, uint64_t max_wait)
{
KL_TRC_ENTRY;
bool locked_ok;
SYNC_ACQ_RESULT our_result;
// This isn't quite right - we don't support timed waits here.
if (max_wait != 0)
{
mutex_map[&mutex]->lock();
locked_ok = true;
}
else
{
locked_ok = mutex_map[&mutex]->try_lock();
}
if (locked_ok)
{
KL_TRC_TRACE(TRC_LVL::FLOW, "Acquired mutex\n");
our_result = SYNC_ACQ_ACQUIRED;
mutex.mutex_locked = true;
}
else
{
KL_TRC_TRACE(TRC_LVL::FLOW, "Already owned mutex\n");
our_result = SYNC_ACQ_TIMEOUT;
mutex.mutex_locked = true;
}
KL_TRC_EXIT;
return our_result;
}
// Release the mutex. If a thread is waiting for it, it will be permitted to run.
void klib_synch_mutex_release(klib_mutex &mutex, const bool disregard_owner)
{
KL_TRC_ENTRY;
ASSERT(mutex.mutex_locked);
mutex.mutex_locked = false;
mutex_map[&mutex]->unlock();
KL_TRC_EXIT;
}
void test_only_free_mutex(klib_mutex &mutex)
{
mutex_map.erase(&mutex);
}
| 29,186
|
https://github.com/git-gd/DarnTheLuck/blob/master/Views/Grant/Delete.cshtml
|
Github Open Source
|
Open Source
|
MIT
| null |
DarnTheLuck
|
git-gd
|
C#
|
Code
| 78
| 340
|
@model List<DarnTheLuck.ViewModels.DeleteGroupViewModel>
@if (Model == null)
{
<h2>No Authorized Users Or Unclaimed Codes</h2>
}
else
{
<form method="post">
<div class="card">
<div class="card-header">
<h2 class="text-danger">Remove User Permissions:</h2>
</div>
<div class="card-body">
@for (int i = 0; i < Model.Count; i++)
{
<div class="form-check m-1">
<input type="hidden" asp-for="@Model[i].GrantEmail" />
<input asp-for="@Model[i].Delete" class="form-check-input checkbox-rnd-dgr" />
<label class="form-check-label" asp-for="@Model[i].Delete">
@Model[i].GrantEmail
</label>
</div>
}
</div>
<div class="card-footer">
<input type="submit" value="Delete" class="btn btn-danger" style="width:auto" />
<a asp-controller="Grant" asp-action="Index"
class="btn btn-dark" style="width:auto">Cancel</a>
</div>
</div>
</form>
}
| 49,614
|
https://github.com/mlgill/mfoutparser/blob/master/mfoutparser/examples/output/mfout_singlefield_tag_header.tsv
|
Github Open Source
|
Open Source
|
BSD-3-Clause
| 2,015
|
mfoutparser
|
mlgill
|
TSV
|
Code
| 64
| 188
|
index tag value
0 modelfree_version 4.20
1 date Tue Jun 2 16:32:50 2015
2 input_file mfinput.3
3 model_file mfmodel.final
4 data_file ubiquitin.MFDATA
5 parameter_file ubiquitin.MFPAR
6 simulation_file none
7 optimization tval
8 seed -1985
9 search grid
10 diffusion isotropic
11 algorithm powell
12 simulations pred
13 iterations 300
14 trim_level 0.000
15 selection none
16 sim_algorithm powell
17 total_spins 65
18 number_of_fields 1
| 28,229
|
https://github.com/shmartel/azure-sdk-for-net/blob/master/sdk/network/Azure.ResourceManager.Network/src/Generated/Models/ApplicationGatewayAutoscaleConfiguration.Serialization.cs
|
Github Open Source
|
Open Source
|
MIT
| 2,021
|
azure-sdk-for-net
|
shmartel
|
C#
|
Code
| 91
| 374
|
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// <auto-generated/>
#nullable disable
using System.Text.Json;
using Azure.Core;
namespace Azure.ResourceManager.Network.Models
{
public partial class ApplicationGatewayAutoscaleConfiguration : IUtf8JsonSerializable
{
void IUtf8JsonSerializable.Write(Utf8JsonWriter writer)
{
writer.WriteStartObject();
writer.WritePropertyName("minCapacity");
writer.WriteNumberValue(MinCapacity);
if (Optional.IsDefined(MaxCapacity))
{
writer.WritePropertyName("maxCapacity");
writer.WriteNumberValue(MaxCapacity.Value);
}
writer.WriteEndObject();
}
internal static ApplicationGatewayAutoscaleConfiguration DeserializeApplicationGatewayAutoscaleConfiguration(JsonElement element)
{
int minCapacity = default;
Optional<int> maxCapacity = default;
foreach (var property in element.EnumerateObject())
{
if (property.NameEquals("minCapacity"))
{
minCapacity = property.Value.GetInt32();
continue;
}
if (property.NameEquals("maxCapacity"))
{
maxCapacity = property.Value.GetInt32();
continue;
}
}
return new ApplicationGatewayAutoscaleConfiguration(minCapacity, Optional.ToNullable(maxCapacity));
}
}
}
| 45,285
|
https://github.com/danylo-dubinin/xcom-zero-k-techrepo/blob/master/TargettingAI_Artemis.lua
|
Github Open Source
|
Open Source
|
MIT
| null |
xcom-zero-k-techrepo
|
danylo-dubinin
|
Lua
|
Code
| 626
| 2,315
|
function widget:GetInfo()
return {
name = "TargettingAI_Artemis",
desc = "attempt to make Artemis not fire cheap aircraft with metal cost less than 270. Meant to be used with hold/return fire state. Version 1,00",
author = "terve886",
date = "2019",
license = "PD", -- should be compatible with Spring
layer = 11,
handler = true, --for adding customCommand into UI
enabled = true
}
end
local UPDATE_FRAME=4
local ArtemisStack = {}
local GetUnitMaxRange = Spring.GetUnitMaxRange
local GetUnitPosition = Spring.GetUnitPosition
local GetMyAllyTeamID = Spring.GetMyAllyTeamID
local GiveOrderToUnit = Spring.GiveOrderToUnit
local GetGroundHeight = Spring.GetGroundHeight
local GetUnitsInSphere = Spring.GetUnitsInSphere
local GetUnitsInCylinder = Spring.GetUnitsInCylinder
local GetUnitAllyTeam = Spring.GetUnitAllyTeam
local GetUnitNearestEnemy = Spring.GetUnitNearestEnemy
local GetUnitIsDead = Spring.GetUnitIsDead
local GetMyTeamID = Spring.GetMyTeamID
local GetUnitDefID = Spring.GetUnitDefID
local GetTeamUnits = Spring.GetTeamUnits
local GetUnitStates = Spring.GetUnitStates
local Echo = Spring.Echo
local Artemis_NAME = "turretaaheavy"
local GetSpecState = Spring.GetSpectatingState
local CMD_STOP = CMD.STOP
local CMD_ATTACK = CMD.ATTACK
local CMD_Change_MetalTarget = 19497
local ArtemisUnitDefID = UnitDefNames["turretaaheavy"].id
local selectedArtemis = nil
local cmdChangeMetalTarget = {
id = CMD_Change_MetalTarget,
type = CMDTYPE.ICON,
tooltip = 'Makes Puppy rocket rush enemies that get close.',
action = 'oneclickwep',
params = { },
texture = 'LuaUI/Images/commands/Bold/dgun.png',
pos = {CMD_ONOFF,CMD_REPEAT,CMD_MOVE_STATE,CMD_FIRE_STATE, CMD_RETREAT},
}
local ArtemisController = {
unitID,
pos,
allyTeamID = GetMyAllyTeamID(),
range,
forceTarget,
metalTarget,
metalTargetValue,
new = function(self, unitID)
--Echo("ArtemisController added:" .. unitID)
self = deepcopy(self)
self.unitID = unitID
self.range = GetUnitMaxRange(self.unitID)
self.pos = {GetUnitPosition(self.unitID)}
self.metalTarget = {220, 300, 700}
self.metalTargetValue = 1
return self
end,
unset = function(self)
--Echo("ArtemisController removed:" .. self.unitID)
GiveOrderToUnit(self.unitID,CMD_STOP, {}, {""},1)
return nil
end,
setForceTarget = function(self, param)
self.forceTarget = param[1]
end,
changeMetalTarget = function(self)
self.metalTargetValue = self.metalTargetValue+1
if (self.metalTargetValue > #self.metalTarget)then
self.metalTargetValue = 1
end
Echo("Minimum metal filter changed to:" .. self.metalTarget[self.metalTargetValue])
end,
isEnemyInRange = function (self)
local units = GetUnitsInCylinder(self.pos[1], self.pos[3], self.range)
local target = nil
for i=1, #units do
if not (GetUnitAllyTeam(units[i]) == self.allyTeamID) then
if (units[i]==self.forceTarget and GetUnitIsDead(units[i]) == false)then
GiveOrderToUnit(self.unitID,CMD_ATTACK, units[i], 0)
return true
end
DefID = GetUnitDefID(units[i])
if not(DefID == nil)then
if (GetUnitIsDead(units[i]) == false and UnitDefs[DefID].isAirUnit == true and UnitDefs[DefID].metalCost >= self.metalTarget[self.metalTargetValue]) then
if (target == nil) then
target = units[i]
end
if (UnitDefs[GetUnitDefID(target)].metalCost < UnitDefs[DefID].metalCost)then
target = units[i]
end
end
end
end
end
if (target == nil) then
GiveOrderToUnit(self.unitID,CMD_STOP, {}, {""},1)
else
GiveOrderToUnit(self.unitID,CMD_ATTACK, target, 0)
end
end,
handle=function(self)
if(GetUnitStates(self.unitID).firestate==1)then
self:isEnemyInRange()
end
end
}
function widget:UnitCommand(unitID, unitDefID, unitTeam, cmdID, cmdParams, cmdOpts, cmdTag)
if (UnitDefs[unitDefID].name == Artemis_NAME and cmdID == CMD_ATTACK and #cmdParams == 1) then
if (ArtemisStack[unitID])then
ArtemisStack[unitID]:setForceTarget(cmdParams)
end
end
end
function widget:UnitFinished(unitID, unitDefID, unitTeam)
if (UnitDefs[unitDefID].name==Artemis_NAME)
and (unitTeam==GetMyTeamID()) then
ArtemisStack[unitID] = ArtemisController:new(unitID);
end
end
function widget:UnitDestroyed(unitID)
if not (ArtemisStack[unitID]==nil) then
ArtemisStack[unitID]=ArtemisStack[unitID]:unset();
end
end
function widget:GameFrame(n)
if (n%UPDATE_FRAME==0) then
for _,Artemis in pairs(ArtemisStack) do
Artemis:handle()
end
end
end
function deepcopy(orig)
local orig_type = type(orig)
local copy
if orig_type == 'table' then
copy = {}
for orig_key, orig_value in next, orig, nil do
copy[deepcopy(orig_key)] = deepcopy(orig_value)
end
setmetatable(copy, deepcopy(getmetatable(orig)))
else
copy = orig
end
return copy
end
--- COMMAND HANDLING
function widget:CommandNotify(cmdID, params, options)
if selectedArtemis ~= nil then
if (cmdID == CMD_Change_MetalTarget)then
for i=1, #selectedArtemis do
if(ArtemisStack[selectedArtemis[i]])then
ArtemisStack[selectedArtemis[i]]:changeMetalTarget()
end
end
end
end
end
function widget:SelectionChanged(selectedUnits)
selectedArtemis = filterArtemis(selectedUnits)
end
function filterArtemis(units)
local filtered = {}
local n = 0
for i = 1, #units do
local unitID = units[i]
if (ArtemisUnitDefID == GetUnitDefID(unitID)) then
n = n + 1
filtered[n] = unitID
end
end
if n == 0 then
return nil
else
return filtered
end
end
function widget:CommandsChanged()
if selectedArtemis then
local customCommands = widgetHandler.customCommands
customCommands[#customCommands+1] = cmdChangeMetalTarget
end
end
-- The rest of the code is there to disable the widget for spectators
local function DisableForSpec()
if GetSpecState() then
widgetHandler:RemoveWidget()
end
end
function widget:Initialize()
DisableForSpec()
local units = GetTeamUnits(Spring.GetMyTeamID())
for i=1, #units do
DefID = GetUnitDefID(units[i])
if (UnitDefs[DefID].name==Artemis_NAME) then
if (ArtemisStack[units[i]]==nil) then
ArtemisStack[units[i]]=ArtemisController:new(units[i])
end
end
end
end
function widget:PlayerChanged (playerID)
DisableForSpec()
end
| 49,035
|
https://github.com/AlexanderStanev/GameDatabase/blob/master/src/Web/GamesDatabase.Web/Areas/Administration/Views/Admin/Index.cshtml
|
Github Open Source
|
Open Source
|
MIT
| 2,022
|
GameDatabase
|
AlexanderStanev
|
C#
|
Code
| 80
| 348
|
@using Services.DataServices.Interfaces
@inject IGenresService GenresService
@inject IGamesService GamesService
@inject IReviewsService ReviewsService
<h2>Administration Panel</h2>
<div class="row py-2">
<div class="col-sm-6">
<div class="py-2">
Currently there are <a asp-area="" asp-action="Browse" asp-controller="Games">@GamesService.GetCount()</a> Games
</div>
<div class="py-2">
Currently there are <a asp-area="Administration" asp-action="All" asp-controller="Genres">@GenresService.GetCount()</a> Genres
</div>
<div class="py-2">
Currently there are <a asp-area="Administration" asp-action="All" asp-controller="Reviews">@ReviewsService.GetCount()</a> Reviews
</div>
</div>
<div class="col-sm-6">
<a asp-area="" asp-action="Create" asp-controller="Games" class="btn btn-dark py-2">
Create a new Game
</a>
<a asp-area="Administration" asp-action="Create" asp-controller="Genres" class="btn btn-dark py-2">
Create a new Genre
</a>
</div>
</div>
| 42,475
|
https://github.com/masmangan/taciturn-octo-kidney/blob/master/aula21/Jogo.cc
|
Github Open Source
|
Open Source
|
CC0-1.0
| 2,015
|
taciturn-octo-kidney
|
masmangan
|
C++
|
Code
| 169
| 412
|
// Jogo.cc
// g++ Circulo.cc Jogo.cc -o Jogo
#include <iostream>
#include <vector>
#include "Circulo.h"
using namespace std;
int main() {
vector<Circulo> cs;
cs.push_back( Circulo() );
cs.push_back( Circulo(100, 150, 30, 1) );
cs.push_back( Circulo(50, 70, 10, 2) );
int x, y;
//bool acerto;
cout << "Jogo dos Círculos." << endl;
while ( ! cs.empty() ) {
cout << "Círculos:" << endl;
for (int i = 0 ; i < cs.size() ; i++)
cout << cs[i] << endl;
cout << "Informe x e y:";
cin >> x >> y;
// acerto = false;
for (int i = 0 ; i < cs.size() ; i++) {
if ( cs[i].acertou(x, y) ) {
//acerto = true;
cs.erase(cs.begin() + i);
}
// cout << "C #" << i << endl;
// cout << cs[i] << " A=" << acerto << endl;
}
//cout << "R=" << acerto << endl;
//if (acerto == 1)
// break;
for (int i = 0 ; i < cs.size() ; i++)
cs[i].mover();
}
cout << "*FIM*" << endl;
}
| 47,959
|
https://github.com/Mythie/prime/blob/master/packages/prime-ui/src/routes/settings/ChangePassword.tsx
|
Github Open Source
|
Open Source
|
MIT
| 2,020
|
prime
|
Mythie
|
TSX
|
Code
| 325
| 983
|
import { Form, Input, message } from 'antd';
import { FormComponentProps } from 'antd/lib/form';
import gql from 'graphql-tag';
import React from 'react';
import { Auth } from '../../stores/auth';
import { accountsPassword } from '../../utils/accounts';
import { client } from '../../utils/client';
type IProps = FormComponentProps & {
forwardRef: any;
visible: boolean;
close(): void;
};
export const ChangePassword = Form.create<IProps>()(
({ form, forwardRef, close, visible }: IProps) => {
const [confirmDirty, setConfirmDirty] = React.useState(false);
// reset form on visible change
React.useEffect(() => form.resetFields(), [visible]);
const onSubmit = (e: React.FormEvent<HTMLElement>) => {
e.preventDefault();
form.validateFieldsAndScroll(async (err, values) => {
if (!err) {
const res = await client.mutate({
mutation: gql`
mutation changePassword($oldpassword: String!, $newpassword: String!) {
changePassword(oldPassword: $oldpassword, newPassword: $newpassword)
}
`,
variables: {
oldpassword: values.oldpassword,
newpassword: values.newpassword,
},
});
if (res.errors) {
const errorMessage = res.errors[0].message || 'Failed to change password';
message.error(errorMessage);
} else {
message.info('Password has been changed');
close();
}
}
});
};
const compareToFirstPassword = (rule: any, value: any, callback: (input?: string) => void) =>
callback(
value && value !== form.getFieldValue('newpassword')
? 'The passwords do not match'
: undefined
);
const validateToNextPassword = (rule: any, value: any, callback: (input?: string) => void) => {
if (value && confirmDirty) {
form.validateFields(['confirm'], { force: true });
}
callback();
};
const onPasswordBlur = (e: React.FocusEvent<HTMLInputElement>) =>
setConfirmDirty(confirmDirty || !!e.target.value);
return (
<Form onSubmit={onSubmit} ref={forwardRef}>
<Form.Item label="Password" required>
{form.getFieldDecorator('oldpassword', {
rules: [
{
required: true,
message: 'Please enter old password',
},
],
})(<Input type="password" size="large" placeholder="Old Password" />)}
</Form.Item>
<Form.Item label="New Password" required>
{form.getFieldDecorator('newpassword', {
rules: [
{
required: true,
message: 'Please enter a password',
},
{
min: 6,
message: 'Enter at least 6 characters',
},
{
validator: validateToNextPassword,
},
],
})(
<Input
autoComplete="off"
type="password"
size="large"
placeholder="Password"
onBlur={onPasswordBlur}
/>
)}
</Form.Item>
<Form.Item label="Confirm password" required>
{form.getFieldDecorator('confirm', {
rules: [
{
required: true,
message: 'Please confirm the password',
},
{
validator: compareToFirstPassword,
},
],
})(
<Input autoComplete="off" type="password" placeholder="Confirm password" size="large" />
)}
</Form.Item>
<input type="submit" hidden />
</Form>
);
}
);
| 15,323
|
https://github.com/pdeoliveira/jhi-dotnetcore-cities/blob/master/src/World.Domain/Entities/AuditedEntityBase.cs
|
Github Open Source
|
Open Source
|
MIT
| null |
jhi-dotnetcore-cities
|
pdeoliveira
|
C#
|
Code
| 44
| 99
|
using System;
using company.world.Domain.Interfaces;
namespace company.world.Domain
{
public abstract class AuditedEntityBase : IAuditedEntityBase
{
public string CreatedBy { get; set; }
public DateTime CreatedDate { get; set; }
public string LastModifiedBy { get; set; }
public DateTime LastModifiedDate { get; set; }
}
}
| 23,074
|
https://github.com/mohwa/emnida/blob/master/tests/unit/type/isNumber.spec.js
|
Github Open Source
|
Open Source
|
MIT
| 2,021
|
emnida
|
mohwa
|
JavaScript
|
Code
| 321
| 792
|
// eslint-disable-next-line
import { isNumber } from '../../../lib/type';
describe('isNumber', () => {
it('should be return true if 0', () => {
// Given
const v = 0;
// When
const result = isNumber(v);
// Then
expect(result).toEqual(true);
});
it('should be return true if 1', () => {
// Given
const v = 1;
// When
const result = isNumber(v);
// Then
expect(result).toEqual(true);
});
it('should be return true if Infinity', () => {
// Given / When
const result = isNumber(Infinity);
// Then
expect(result).toEqual(true);
});
it('should be return true if NaN', () => {
// Given / When
const result = isNumber(NaN);
// Then
expect(result).toEqual(true);
});
it('should be return true if 0xff', () => {
// Given / When
const result = isNumber(0xff);
// Then
expect(result).toEqual(true);
});
it('should be return true if 5e3', () => {
// Given / When
const result = isNumber(5e3);
// Then
expect(result).toEqual(true);
});
it('should be return true if -10.10', () => {
// Given / When
const result = isNumber(-10.1);
// Then
expect(result).toEqual(true);
});
it('should be return false if string type', () => {
// Given / When
const result1 = isNumber('test');
const result2 = isNumber('1.1');
const result3 = isNumber('0xff');
const result4 = isNumber('');
const result5 = isNumber(' ');
// Then
expect(result1).toEqual(false);
expect(result2).toEqual(false);
expect(result3).toEqual(false);
expect(result4).toEqual(false);
expect(result5).toEqual(false);
});
it('should be return false if boolean type', () => {
// Given / When
const result = isNumber(true);
// Then
expect(result).toEqual(false);
});
it('should be return false if null type', () => {
// Given / When
const result = isNumber(null);
// Then
expect(result).toEqual(false);
});
it('should be return false if undefined type', () => {
// Given / When
const result = isNumber(undefined);
// Then
expect(result).toEqual(false);
});
it('should be return false if symbol type', () => {
// Given / When
const result = isNumber(Symbol(1));
// Then
expect(result).toEqual(false);
});
it('should be return false if object type', () => {
// Given / When
const result = isNumber({});
// Then
expect(result).toEqual(false);
});
});
| 19,741
|
https://github.com/lucasmpavelski/elmoead/blob/master/src/surrogate/benchmark/cec09_problems.cpp
|
Github Open Source
|
Open Source
|
MIT
| 2,020
|
elmoead
|
lucasmpavelski
|
C++
|
Code
| 2
| 13
|
#include "cec09_problems.h"
| 13,713
|
https://github.com/sentimentes/base-server/blob/master/src/main/java/com/wwls/modules/application/utils/CacheConfig.java
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,020
|
base-server
|
sentimentes
|
Java
|
Code
| 290
| 1,534
|
package com.wwls.modules.application.utils;
import java.util.List;
import com.wwls.common.utils.JedisUtils;
/****
* @author xudongdong
* @version 2016-07-02
*
* 缓存的主键列表
* **/
public class CacheConfig {
public static final String APP_INFO_MAP ="APP_INFO_MAP";//应用信息列表
public static final String APP_AUTHOR_MAP ="APP_AUTHOR_MAP";//应用权限MAP
public static final String APP_USER_SESSION_MAP="APP_USER_SESSION_MAP";//APP用户会话信息列表
public static final String APP_PAY_INFO="APP_PAY_INFO";//APP支付信息缓存
public static final String INTERFACE_ACCESS_PARATER="INTERFACE_ACCESS_PARATER";//接口参数列表缓存
public static final String MENU_LIST_MAPPING = "MENU_LIST_MAPPING";//接口地址映射列表缓存
public static final String EC_CACHE_DICT_COUNTRY_LIST="EC_CACHE_DICT_COUNTRY_LIST";//国家列表
public static final String APP_INTEGRAL_INFO = "APP_INTEGRAL_INFO";//积分应用列表
public static final String GoodsCategoryCount ="goodsCategoryCount";//商品运营分类数量统计
// private static final CommonPayManageDao commonPayManageDao = SpringContextHolder.getBean(CommonPayManageDao.class);
private static final String productDetail = "productDetail";//商品缓存
//加载用户信息
public static void setAppUserSession(String key,Object object,int cacheSeconds){
JedisUtils.setObject(CacheConfig.APP_USER_SESSION_MAP+key,object,cacheSeconds);
}
//获取用户信息
public static Object getAppUserSession(String key){
return JedisUtils.getObject(CacheConfig.APP_USER_SESSION_MAP+key);
}
//直APP应用信息 接放入redis缓存中
public static void setAppInfo(String key,Object object,int cacheSeconds){
JedisUtils.setObject(CacheConfig.APP_INFO_MAP+key, object, 0);//直APP应用信息 接放入redis缓存中
}
//直APP应用信息 接放入redis缓存中
public static Object getAppInfo(String key){
return JedisUtils.getObject(CacheConfig.APP_INFO_MAP+key);//直APP应用信息 接放入redis缓存中
}
//初始化APP权限列表
public static void setAppAuthorList(String key,Object object,int cacheSeconds){
JedisUtils.setObject(CacheConfig.APP_AUTHOR_MAP+key, object, cacheSeconds);
}
//获取APP权限列表
public static Object getAppAuthorList(String key) {
return JedisUtils.getObject(CacheConfig.APP_AUTHOR_MAP +key);
}
//设置App支付信息缓存
public static void setAppPayInfo(List<String> value,int cacheSeconds){
System.out.println("设置支付信息=="+CacheConfig.APP_PAY_INFO);
JedisUtils.setList(CacheConfig.APP_PAY_INFO, value, cacheSeconds);
}
// //获取APP支付信息
// public static CommonPayManage getAppPayInfo(String type,String clientId){
// CommonPayManage cpm = new CommonPayManage();
// cpm.setPayType(type);
// cpm.setClientId(clientId);
// List<CommonPayManage> commpayList = commonPayManageDao.findList(cpm);
// if(commpayList!=null&&commpayList.size()>0){
// return commpayList.get(0);
// }
// return null;
// }
//初始化积分列表
public static void setAppIntegral(String key,Object object,int cacheSeconds){
JedisUtils.setObject(key, object, cacheSeconds);
}
//初始化积分列表
public static Object getAppIntegral(String key){
return JedisUtils.getObject(key);
}
//将接口参数列表初始化近如缓存
public static void setMenueParam(String key,Object object,int cacheSeconds){
JedisUtils.setObject(CacheConfig.INTERFACE_ACCESS_PARATER+key, object, cacheSeconds);
}
//获取接口参数缓存
public static Object getMenueParamList(String key){
return JedisUtils.getObject(CacheConfig.INTERFACE_ACCESS_PARATER +key);
}
//设置运营分类数量
public static void setGoodsCategoryCount(String key,Object value,int cacheSeconds){
JedisUtils.setObject(CacheConfig.GoodsCategoryCount+key, value, cacheSeconds);//将支付信息设置入缓存
}
//获取商品运营分类数量
public static Object getGoodsCategoryCount(String key){
return JedisUtils.getObject(CacheConfig.GoodsCategoryCount+key);
}
//设置商品数据缓存
public static void setProductDetail(String key,Object value,int cacheSeconds){
JedisUtils.setObject(CacheConfig.productDetail+key, value, cacheSeconds);//将支付信息设置入缓存
}
//设置商品数据缓存
public static Object getProductDetail(String key){
return JedisUtils.getObject(CacheConfig.productDetail+key);//将支付信息设置入缓存
}
}
| 27,613
|
https://github.com/AshishSurgimap/Surgimap_laravel5/blob/master/resources/views/auth/login.blade.php
|
Github Open Source
|
Open Source
|
MIT
| 2,015
|
Surgimap_laravel5
|
AshishSurgimap
|
Blade
|
Code
| 130
| 602
|
@extends('app')
@section('title', 'Login')
@section('content')
<div class="container-fluid">
<div class="row">
<div class= "header-login">
<div class="col-md-11 col-md-offset-1">
<span>Login</span>
<hr>
</div>
</div>
<div class="col-md-4 col-md-offset-1">
<div class="panel">
@if (count($errors) > 0)
<div class="alert alert-danger">
<strong>Whoops!</strong> There were some problems with your input.<br><br>
<ul>
@foreach ($errors->all() as $error)
<li>{{ $error }}</li>
@endforeach
</ul>
</div>
@endif
<form role="form" method="POST" action="{{ url('/auth/login') }}">
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<div class="row">
<div class="col-lg-9">
<div class="form-group">
<label for="inputEmail">Email</label>
<input type="email" class="form-control" name="email" value="{{ old('email') }}" placeholder="Email">
</div>
</div>
</div>
<div class="row">
<div class="col-lg-9">
<div class="form-group">
<label for="inputPassword">Password</label>
<input type="password" class="form-control" name="password" placeholder="Password">
</div>
</div>
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary">Login</button>
<div class= "forgot-pass">
Forgot Passwords?
<a href="{{ url('/auth/recover_password') }}">Click here to recover it!</a>
<!-- TO=DO - Add HREF -->
</div>
</div>
</form>
</div>
</div>
</div>
</div>
@endsection
| 43,714
|
https://github.com/avaje-metric/avaje-metric-core/blob/master/src/main/java/io/avaje/metrics/core/noop/NoopTimedMetric.java
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,016
|
avaje-metric-core
|
avaje-metric
|
Java
|
Code
| 217
| 678
|
package io.avaje.metrics.core.noop;
import io.avaje.metrics.MetricName;
import io.avaje.metrics.TimedEvent;
import io.avaje.metrics.TimedMetric;
import io.avaje.metrics.statistics.MetricStatisticsVisitor;
import java.util.Map;
import java.util.function.Supplier;
public class NoopTimedMetric implements TimedMetric {
private static final NoopTimedEvent NOOP_TIMED_EVENT = new NoopTimedEvent();
private static final NoopValueStatistics NOOP_STATS = NoopValueStatistics.INSTANCE;
private final MetricName metricName;
public NoopTimedMetric(MetricName metricName) {
this.metricName = metricName;
}
@Override
public MetricName getName() {
return metricName;
}
@Override
public boolean isBucket() {
return false;
}
@Override
public String getBucketRange() {
return "";
}
@Override
public void collect(MetricStatisticsVisitor metricStatisticsVisitor) {
// do nothing
}
@Override
public void clear() {
// do nothing
}
@Override
public void setRequestTiming(int collectionCount) {
// do nothing
}
@Override
public int getRequestTiming() {
return 0;
}
@Override
public void decrementRequestTiming() {
// do nothing
}
@Override
public void time(Runnable event) {
event.run();
}
@Override
public <T> T time(Supplier<T> event) {
return event.get();
}
@Override
public TimedEvent startEvent() {
return NOOP_TIMED_EVENT;
}
@Override
public void addEventSince(boolean success, long startNanos) {
// do nothing
}
@Override
public void addEventDuration(boolean success, long durationNanos) {
// do nothing
}
@Override
public boolean isRequestTiming() {
return false;
}
@Override
public void add(long startNanos) {
}
@Override
public void add(long startNanos, boolean activeThreadContext) {
}
@Override
public void addErr(long startNanos) {
}
@Override
public void addErr(long startNanos, boolean activeThreadContext) {
}
@Override
public Map<String, String> attributes() {
return null;
}
}
| 42,060
|
https://github.com/Honey-9/Resume-Builder/blob/master/styles/globals.scss
|
Github Open Source
|
Open Source
|
MIT
| null |
Resume-Builder
|
Honey-9
|
SCSS
|
Code
| 195
| 646
|
@import url('https://fonts.googleapis.com/css2?family=Poppins:wght@100;200;300;400;500;600;700;800&display=swap');
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
html {
font-size: 80%;
@media only screen and (min-width: 640px) {
font-size: 80%;
}
@media only screen and (min-width: 768px) {
font-size: 90%;
}
@media only screen and (min-width: 1024px) {
font-size: 100%;
}
}
div{
word-break: break-word;
}
html,
body {
padding: 0;
margin: 0;
font-family: 'Poppins', sans-serif;
font-weight: 300;
background-color: #f9fafb;
position: relative;
}
a {
color: inherit;
text-decoration: none;
}
* {
box-sizing: border-box;
}
.resume-a4 {
// width: 1240px;
// height: 874px;
// width: 596px;
// height: 842px;
height: 286.2mm;
max-width: 210mm;
// Margin is causing messing up of the printing process (an extra page is coming (blank))
margin: 20px auto;
margin-bottom: 93px;
@media only screen and (min-width: 1024px) {
margin-bottom: 20px;
}
}
.left-sidebar {
@media only screen and (min-width: 1024px) {
height: 297mm;
}
}
img {
height: 100%;
width: 100%;
object-fit: cover;
}
.ReactCrop-opt {
position: relative;
display: inline-block;
cursor: crosshair;
overflow: hidden;
// max-height: 500px;
margin-right: 2.5rem;
// img {
// object-fit: contain;
// height: 500px;
// }
}
.MuiDrawer-paperAnchorTop {
width: 100vw;
height: 100vh;
@media only screen and (min-width: 1024px) {
width: 50vw;
}
}
| 16,099
|
https://github.com/iquipsys-positron/iqs-services-mqttgateway-node/blob/master/src/protocol/StatisticsMessage.ts
|
Github Open Source
|
Open Source
|
MIT
| null |
iqs-services-mqttgateway-node
|
iquipsys-positron
|
TypeScript
|
Code
| 90
| 232
|
import { IStream } from 'iqs-libs-protocols-node';
import { Message } from './Message';
import { CommStatistics } from './CommStatistics';
export class StatisticsMessage extends Message {
public stats: CommStatistics[] = [];
public constructor() {
super(9);
}
public stream(stream: IStream): void {
super.stream(stream);
this.stats = this.streamStats(stream, this.stats);
}
private streamStats(stream: IStream, stats: CommStatistics[]): CommStatistics[] {
stats = stats || [];
let count = stream.streamWord(stats.length);
let result = [];
for (let index = 0; index < count; index++) {
let stat: CommStatistics = stats[index] || new CommStatistics();
stat.stream(stream);
result.push(stat);
}
return result;
}
}
| 44,908
|
https://github.com/tadeokondrak/kiss/blob/master/repo/libelf/build
|
Github Open Source
|
Open Source
|
MIT
| 2,019
|
kiss
|
tadeokondrak
|
Shell
|
Code
| 11
| 42
|
#!/bin/sh -e
./configure \
--prefix=/usr \
--disable-nls
make
make prefix="$1/usr" install
| 2,592
|
https://github.com/waldyrious/cosmopolitan/blob/master/libc/literal.h
|
Github Open Source
|
Open Source
|
0BSD
| 2,021
|
cosmopolitan
|
waldyrious
|
C
|
Code
| 81
| 427
|
#ifndef COSMOPOLITAN_LIBC_LITERAL_H_
#define COSMOPOLITAN_LIBC_LITERAL_H_
#ifdef __INT8_C
#define INT8_C(c) __INT8_C(c)
#define UINT8_C(c) __UINT8_C(c)
#define INT16_C(c) __INT16_C(c)
#define UINT16_C(c) __UINT16_C(c)
#define INT32_C(c) __INT32_C(c)
#define UINT32_C(c) __UINT32_C(c)
#define INT64_C(c) __INT64_C(c)
#define UINT64_C(c) __UINT64_C(c)
#else
#define INT8_C(c) c
#define UINT8_C(c) c
#define INT16_C(c) c
#define UINT16_C(c) c
#define INT32_C(c) c
#define UINT32_C(c) c##U
#define INT64_C(c) c##L
#define UINT64_C(c) c##UL
#endif
#if __SIZEOF_INTMAX__ == 16
#define INT128_C(c) ((intmax_t)(c))
#define UINT128_C(c) ((uintmax_t)(c))
#elif __SIZEOF_INTMAX__ == 8
#define INT128_C(c) __INT64_C(c)
#define UINT128_C(c) __UINT64_C(c)
#endif
#endif /* COSMOPOLITAN_LIBC_LITERAL_H_ */
| 23,106
|
https://github.com/DF-Kyun/kie-docs/blob/master/docs/optaplanner-wb-es-docs/src/main/asciidoc/Workbench/AuthoringPlanningAssets-chapter.adoc
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,017
|
kie-docs
|
DF-Kyun
|
AsciiDoc
|
Code
| 8
| 51
|
[[_planner.authoringplanningassets]]
= Authoring Planning Assets
:imagesdir: ..
include::AuthoringPlanningAssets/SolverEditor-section.adoc[leveloffset=+1]
| 28,173
|
https://github.com/webbestmaster/tangram-2/blob/master/res/tangram-old/ios/js/controllers/timer.js
|
Github Open Source
|
Open Source
|
MIT
| null |
tangram-2
|
webbestmaster
|
JavaScript
|
Code
| 130
| 439
|
(function (win) {
var timer;
timer = {
init: function(){
this.node = $('.js-timer-wrapper', main.wrapper);
this.countValue = 0;
if (this.timeoutID !== undefined) {
clearTimeout(this.timeoutID);
}
if (!info.timerIsActive && this.node) {
this.node.style.display = 'none';
return;
}
this.isActive = true;
this.isPause = false;
this.timeoutID = setTimeout(this.count.bind(this), 1000);
},
count: function(){
this.countValue += this.isPause ? 0 : 1;
var countValue = this.countValue;
var minutes = Math.floor(countValue / 60);
var seconds = countValue % 60;
if (seconds <= 9) {
seconds = '0' + seconds;
}
var timerNode = $('.js-timer-wrapper', main.wrapper);
if (timerNode) {
timerNode.innerHTML = minutes + ':' + seconds;
this.timeoutID = setTimeout(this.count.bind(this), 1000);
} else {
this.stop();
}
},
stop: function(){
this.isActive = false;
clearTimeout(this.timeoutID);
},
pause: function(needPause){
this.isPause = needPause === undefined || needPause === true;
}
};
win.timer = timer;
}(window));
| 31,510
|
https://github.com/arunvc/incubator-pagespeed-mod/blob/master/net/instaweb/http/sync_fetcher_adapter_callback.cc
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,018
|
incubator-pagespeed-mod
|
arunvc
|
C++
|
Code
| 367
| 1,148
|
/*
* 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.
*/
// lsong@google.com (Libo Song)
#include "net/instaweb/http/public/sync_fetcher_adapter_callback.h"
#include "base/logging.h"
#include "pagespeed/kernel/base/abstract_mutex.h"
#include "pagespeed/kernel/base/basictypes.h"
#include "pagespeed/kernel/base/condvar.h"
#include "pagespeed/kernel/base/string_util.h"
#include "pagespeed/kernel/base/thread_system.h"
#include "pagespeed/kernel/base/writer.h"
namespace net_instaweb {
class MessageHandler;
bool SyncFetcherAdapterCallback::ProtectedWriter::Write(
const StringPiece& buf, MessageHandler* handler) {
bool ret = true;
// If the callback has not timed out and been released, then pass
// the data through.
if (callback_->LockIfNotReleased()) {
ret = orig_writer_->Write(buf, handler);
callback_->Unlock();
}
return ret;
}
bool SyncFetcherAdapterCallback::ProtectedWriter::Flush(
MessageHandler* handler) {
bool ret = true;
// If the callback has not timed out and been released, then pass
// the flush through.
if (callback_->LockIfNotReleased()) {
ret = orig_writer_->Flush(handler);
callback_->Unlock();
}
return ret;
}
SyncFetcherAdapterCallback::SyncFetcherAdapterCallback(
ThreadSystem* thread_system, Writer* writer,
const RequestContextPtr& request_context)
: AsyncFetch(request_context),
mutex_(thread_system->NewMutex()),
cond_(mutex_->NewCondvar()),
done_(false),
success_(false),
released_(false),
writer_(new ProtectedWriter(this, writer)) {}
SyncFetcherAdapterCallback::~SyncFetcherAdapterCallback() {}
void SyncFetcherAdapterCallback::HandleDone(bool success) {
mutex_->Lock();
done_ = true;
success_ = success;
if (released_) {
mutex_->Unlock();
delete this;
} else {
cond_->Signal();
mutex_->Unlock();
}
}
void SyncFetcherAdapterCallback::Release() {
mutex_->Lock();
DCHECK(!released_);
released_ = true;
if (done_) {
mutex_->Unlock();
delete this;
} else {
mutex_->Unlock();
}
}
bool SyncFetcherAdapterCallback::IsDone() const {
ScopedMutex hold_lock(mutex_.get());
return done_;
}
bool SyncFetcherAdapterCallback::IsDoneLockHeld() const {
mutex_->DCheckLocked();
return done_;
}
bool SyncFetcherAdapterCallback::success() const {
ScopedMutex hold_lock(mutex_.get());
return success_;
}
bool SyncFetcherAdapterCallback::released() const {
ScopedMutex hold_lock(mutex_.get());
return released_;
}
bool SyncFetcherAdapterCallback::LockIfNotReleased() {
mutex_->Lock();
if (!released_) {
return true;
} else {
mutex_->Unlock();
return false;
}
}
void SyncFetcherAdapterCallback::Unlock() { mutex_->Unlock(); }
void SyncFetcherAdapterCallback::TimedWait(int64 timeout_ms) {
mutex_->DCheckLocked();
DCHECK(!released_);
cond_->TimedWait(timeout_ms);
}
} // namespace net_instaweb
| 27,166
|
https://github.com/Djohnnie/DotNet6-DotNetDeveloperDays-2021/blob/master/4-CSharp10Features/4-CSharp10Features.Records/Program.cs
|
Github Open Source
|
Open Source
|
Unlicense
| 2,021
|
DotNet6-DotNetDeveloperDays-2021
|
Djohnnie
|
C#
|
Code
| 130
| 322
|
var p1 = new Person1
{
Name = "Johnny Hooyberghs",
Age = 36
};
Console.WriteLine(p1);
var p2 = new Person2("Johnny Hooyberghs", 36);
Console.WriteLine(p2);
var p3 = p2 with { Age = 25 };
Console.WriteLine(p3);
var p4 = new Person4("Johnny Hooyberghs", 36);
p4.Age++;
Console.WriteLine(p4);
var p5 = new Person5("Johnny Hooyberghs", 36);
p5.Age++;
Console.WriteLine(p5);
// Record classes
public record Person1
{
public string Name { get; init; }
public byte Age { get; init; }
}
public record Person2(string Name, byte Age);
public record class Person3(string Name, byte Age)
{
public void Birtday()
{
Age++;
}
}
// Record structs
public record struct Person4(string Name, byte Age)
{
public void Birtday()
{
Age++;
}
}
public readonly record struct Person5(string Name, byte Age)
{
public void Birtday()
{
Age++;
}
}
| 41,883
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.