hexsha
stringlengths 40
40
| size
int64 5
1.05M
| ext
stringclasses 98
values | lang
stringclasses 21
values | max_stars_repo_path
stringlengths 3
945
| max_stars_repo_name
stringlengths 4
118
| max_stars_repo_head_hexsha
stringlengths 40
78
| max_stars_repo_licenses
listlengths 1
10
| max_stars_count
int64 1
368k
⌀ | max_stars_repo_stars_event_min_datetime
stringlengths 24
24
⌀ | max_stars_repo_stars_event_max_datetime
stringlengths 24
24
⌀ | max_issues_repo_path
stringlengths 3
945
| max_issues_repo_name
stringlengths 4
118
| max_issues_repo_head_hexsha
stringlengths 40
78
| max_issues_repo_licenses
listlengths 1
10
| max_issues_count
int64 1
134k
⌀ | max_issues_repo_issues_event_min_datetime
stringlengths 24
24
⌀ | max_issues_repo_issues_event_max_datetime
stringlengths 24
24
⌀ | max_forks_repo_path
stringlengths 3
945
| max_forks_repo_name
stringlengths 4
135
| max_forks_repo_head_hexsha
stringlengths 40
78
| max_forks_repo_licenses
listlengths 1
10
| max_forks_count
int64 1
105k
⌀ | max_forks_repo_forks_event_min_datetime
stringlengths 24
24
⌀ | max_forks_repo_forks_event_max_datetime
stringlengths 24
24
⌀ | content
stringlengths 5
1.05M
| avg_line_length
float64 1
1.03M
| max_line_length
int64 2
1.03M
| alphanum_fraction
float64 0
1
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
79b47548b7b876e7ac68c81e6cbe35506f63c70e
| 685
|
php
|
PHP
|
admin/feedback_del.php
|
7jx/e-commerce
|
b225596b967d9725fafd4ff6c70ea442c6cdcce8
|
[
"MIT"
] | null | null | null |
admin/feedback_del.php
|
7jx/e-commerce
|
b225596b967d9725fafd4ff6c70ea442c6cdcce8
|
[
"MIT"
] | null | null | null |
admin/feedback_del.php
|
7jx/e-commerce
|
b225596b967d9725fafd4ff6c70ea442c6cdcce8
|
[
"MIT"
] | null | null | null |
<?php
require_once 'islogin.php';
require_once '../plus/DbMysql.php';
$id=@$_GET["id"];
if($id=="")
{
echo "<script>alert('Required parameter missingID');location.href='feedback.php';</script>";
exit();
}
$db = new DbMysql();
$db->sql("select * from feedback where id=$id");
if($db->affected()!=1)
{
echo "<script>alert('IDlose');location.href='feedback.php';</script>";
exit();
}
$db->sql("delete from feedback where id =$id");
if($db->affected()==1)
{
echo "<script>alert('Feedback deleted successfully');location.href='feedback.php'</script>";
}
else
{
echo "<script>alert('Feedback deleted failed');location.href='feedback.php'</script>";
}
?>
| 17.125
| 96
| 0.632117
|
dd7fd88f9da9048e329fff09f21e14e4644a1b28
| 3,138
|
java
|
Java
|
ReflexMechanism/ReflectAndAgentDemo.java
|
tewentong/JavaHub
|
021e9a2366f0f8a842d7af970c1432e9099bbc1c
|
[
"MIT"
] | null | null | null |
ReflexMechanism/ReflectAndAgentDemo.java
|
tewentong/JavaHub
|
021e9a2366f0f8a842d7af970c1432e9099bbc1c
|
[
"MIT"
] | null | null | null |
ReflexMechanism/ReflectAndAgentDemo.java
|
tewentong/JavaHub
|
021e9a2366f0f8a842d7af970c1432e9099bbc1c
|
[
"MIT"
] | null | null | null |
/*
Java反射编程
反射与代理设计模式
代理设计模式是在程序开发之中使用最多的设计模式,代理设计模式的核心是:有真实业务实现类,与代理业务实现类
并且代理类要完成比真实业务更多的处理操作
传统代理设计模式的弊端:
所有的代理设计模式如果按照设计要求来讲,必须是基于接口的设计,也就是说需要首先定义出核心接口的组成
下面模拟一个消息发送的代理操作结构
范例:传统代理设计
interface IMessage0315 { // 传统代理设计必须有接口
public void send(); // 业务方法
}
class MessageReal implements IMessage0315 {
@Override
public void send() {
System.out.println("【发送消息】www.mldn.cn");
}
}
class MessageProxy implements IMessage0315 { // 代理类
private IMessage0315 message; // 代理对象,一定是业务接口实例
public MessageProxy(IMessage0315 message) {
this.message = message;
}
public boolean connect() {
System.out.println("【消息代理】进行消息发送通道的连接");
return true;
}
public void close() {
System.out.println("【消息代理】关闭消息通道");
}
@Override
public void send() {
if (this.connect()) {
this.message.send(); // 消息的发送处理
this.close();
}
}
}
public class ReflectAndAgentDemo {
public static void main(String[] args) throws Exception {
IMessage0315 msg = new MessageProxy(new MessageReal());
msg.send();
}
}
以上的操作代码是一个最为标准的代理设计,但是如果要进一步的去思考会发现,
客户端的接口与具体的子类产生耦合问题
所以这样的操作如果从实际的开发来讲最好再引入工厂设计模式进行代理对象的获取
以上的代理设计模式为静态代理设计,这种静态代理设计的特点在于:
一个代理类只为一个接口服务
那么说如果现在准备出了3000个业务接口,那么按照此种做法就意味着需要编写3000个代理类,
并且这3000个代理类的操作形式类似
现在需要解决的问题在于:如何可以让一个代理类满足于所有的业务接口操作要求
*/
interface IMessage0315 { // 传统代理设计必须有接口
public void send(); // 业务方法
}
class MessageReal implements IMessage0315 {
@Override
public void send() {
System.out.println("【发送消息】www.mldn.cn");
}
}
class MessageProxy implements IMessage0315 { // 代理类
private IMessage0315 message; // 代理对象,一定是业务接口实例
public MessageProxy(IMessage0315 message) {
this.message = message;
}
public boolean connect() {
System.out.println("【消息代理】进行消息发送通道的连接");
return true;
}
public void close() {
System.out.println("【消息代理】关闭消息通道");
}
@Override
public void send() {
if (this.connect()) {
this.message.send(); // 消息的发送处理
this.close();
}
}
}
public class ReflectAndAgentDemo {
public static void main(String[] args) throws Exception {
IMessage0315 msg = new MessageProxy(new MessageReal());
msg.send();
}
}
| 32.020408
| 79
| 0.489165
|
7bfc9c9692accf77ebdcced6a2db22ba8979b873
| 5,356
|
cpp
|
C++
|
Cpp/SDK/W_Marker_Request_functions.cpp
|
MrManiak/Squad-SDK
|
742feb5991ae43d6f0cedd2d6b32b949923ca4f9
|
[
"Apache-2.0"
] | 1
|
2020-08-15T08:31:55.000Z
|
2020-08-15T08:31:55.000Z
|
Cpp/SDK/W_Marker_Request_functions.cpp
|
MrManiak/Squad-SDK
|
742feb5991ae43d6f0cedd2d6b32b949923ca4f9
|
[
"Apache-2.0"
] | 2
|
2020-08-15T08:43:56.000Z
|
2021-01-15T05:04:48.000Z
|
Cpp/SDK/W_Marker_Request_functions.cpp
|
MrManiak/Squad-SDK
|
742feb5991ae43d6f0cedd2d6b32b949923ca4f9
|
[
"Apache-2.0"
] | 2
|
2020-08-10T12:05:42.000Z
|
2021-02-12T19:56:10.000Z
|
// Name: S, Version: b
#include "../SDK.h"
#ifdef _MSC_VER
#pragma pack(push, 0x01)
#endif
/*!!HELPER_DEF!!*/
/*!!DEFINE!!*/
namespace UFT
{
//---------------------------------------------------------------------------
// Functions
//---------------------------------------------------------------------------
// Function W_Marker_Request.W_Marker_Request_C.OnPreviewMouseButtonDown
// (BlueprintCosmetic, Event, Public, HasOutParms, HasDefaults, BlueprintCallable, BlueprintEvent)
// Parameters:
// struct FGeometry MyGeometry (BlueprintVisible, BlueprintReadOnly, Parm, IsPlainOldData, NoDestructor)
// struct FPointerEvent MouseEvent (ConstParm, BlueprintVisible, BlueprintReadOnly, Parm, OutParm, ReferenceParm)
// struct FEventReply ReturnValue (Parm, OutParm, ReturnParm)
struct FEventReply UW_Marker_Request_C::OnPreviewMouseButtonDown(const struct FGeometry& MyGeometry, const struct FPointerEvent& MouseEvent)
{
static auto fn = UObject::FindObject<UFunction>("Function W_Marker_Request.W_Marker_Request_C.OnPreviewMouseButtonDown");
UW_Marker_Request_C_OnPreviewMouseButtonDown_Params params;
params.MyGeometry = MyGeometry;
params.MouseEvent = MouseEvent;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
return params.ReturnValue;
}
// Function W_Marker_Request.W_Marker_Request_C.OnScaleChanged
// (Event, Public, BlueprintEvent)
// Parameters:
// float UniformScale (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash)
void UW_Marker_Request_C::OnScaleChanged(float UniformScale)
{
static auto fn = UObject::FindObject<UFunction>("Function W_Marker_Request.W_Marker_Request_C.OnScaleChanged");
UW_Marker_Request_C_OnScaleChanged_Params params;
params.UniformScale = UniformScale;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function W_Marker_Request.W_Marker_Request_C.Construct
// (BlueprintCosmetic, Event, Public, BlueprintEvent)
void UW_Marker_Request_C::Construct()
{
static auto fn = UObject::FindObject<UFunction>("Function W_Marker_Request.W_Marker_Request_C.Construct");
UW_Marker_Request_C_Construct_Params params;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function W_Marker_Request.W_Marker_Request_C.Find Map Icon
// (BlueprintCallable, BlueprintEvent)
void UW_Marker_Request_C::Find_Map_Icon()
{
static auto fn = UObject::FindObject<UFunction>("Function W_Marker_Request.W_Marker_Request_C.Find Map Icon");
UW_Marker_Request_C_Find_Map_Icon_Params params;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function W_Marker_Request.W_Marker_Request_C.OnRightClicked
// (Event, Protected, BlueprintEvent)
void UW_Marker_Request_C::OnRightClicked()
{
static auto fn = UObject::FindObject<UFunction>("Function W_Marker_Request.W_Marker_Request_C.OnRightClicked");
UW_Marker_Request_C_OnRightClicked_Params params;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function W_Marker_Request.W_Marker_Request_C.Set Vis to Commander
// (BlueprintCallable, BlueprintEvent)
void UW_Marker_Request_C::Set_Vis_to_Commander()
{
static auto fn = UObject::FindObject<UFunction>("Function W_Marker_Request.W_Marker_Request_C.Set Vis to Commander");
UW_Marker_Request_C_Set_Vis_to_Commander_Params params;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function W_Marker_Request.W_Marker_Request_C.Tick
// (BlueprintCosmetic, Event, Public, BlueprintEvent)
// Parameters:
// struct FGeometry MyGeometry (BlueprintVisible, BlueprintReadOnly, Parm, IsPlainOldData, NoDestructor)
// float InDeltaTime (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash)
void UW_Marker_Request_C::Tick(const struct FGeometry& MyGeometry, float InDeltaTime)
{
static auto fn = UObject::FindObject<UFunction>("Function W_Marker_Request.W_Marker_Request_C.Tick");
UW_Marker_Request_C_Tick_Params params;
params.MyGeometry = MyGeometry;
params.InDeltaTime = InDeltaTime;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function W_Marker_Request.W_Marker_Request_C.ExecuteUbergraph_W_Marker_Request
// (Final, HasDefaults)
// Parameters:
// int EntryPoint (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash)
void UW_Marker_Request_C::ExecuteUbergraph_W_Marker_Request(int EntryPoint)
{
static auto fn = UObject::FindObject<UFunction>("Function W_Marker_Request.W_Marker_Request_C.ExecuteUbergraph_W_Marker_Request");
UW_Marker_Request_C_ExecuteUbergraph_W_Marker_Request_Params params;
params.EntryPoint = EntryPoint;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| 31.321637
| 176
| 0.740291
|
68d860325bc86be946ac6831b07973de6a0c7d43
| 1,326
|
rb
|
Ruby
|
standalone/pruntime/client/console.rb
|
Soptq/phala-blockchain
|
f2fbd1e62b1b8c2567bfed993ae85a56f227a880
|
[
"Apache-2.0"
] | 279
|
2020-02-04T17:09:57.000Z
|
2022-03-30T19:13:51.000Z
|
standalone/pruntime/client/console.rb
|
Soptq/phala-blockchain
|
f2fbd1e62b1b8c2567bfed993ae85a56f227a880
|
[
"Apache-2.0"
] | 317
|
2020-01-21T18:12:12.000Z
|
2022-03-29T13:25:51.000Z
|
standalone/pruntime/client/console.rb
|
Soptq/phala-blockchain
|
f2fbd1e62b1b8c2567bfed993ae85a56f227a880
|
[
"Apache-2.0"
] | 119
|
2020-02-03T06:05:16.000Z
|
2022-03-30T21:41:27.000Z
|
#!/usr/bin/env ruby
# frozen_string_literal: true
ENV["BUNDLE_GEMFILE"] ||= File.expand_path("Gemfile", __dir__)
require "bundler/setup" # Set up gems listed in the Gemfile.
require 'active_support'
require 'active_support/core_ext'
require "pry"
require "faraday"
require "faraday_middleware"
HOST = "http://localhost:8000/"
class APIClient
class APIError < StandardError; end
attr_reader :client
def initialize(host:)
@client = Faraday.new(HOST) do |faraday|
faraday.request :json
faraday.options[:open_timeout] = 2
faraday.options[:timeout] = 5
# faraday.response :logger
# faraday.response :json
faraday.adapter Faraday.default_adapter
end
end
def get_info
response = client.post("get_info", {input: {}, nonce: {}})
if response.status == 500
raise APIError, "Unexpected return code 500"
end
body =
begin
JSON.parse(response.body)
rescue
raise APIError, "Parse body error -- #{response.body}"
end
if body["payload"].present?
begin
body["payload"] = JSON.parse(body["payload"])
rescue
raise APIError, "Parse payload error -- #{body["payload"]}"
end
end
body
end
end
client = APIClient.new host: HOST
# start a REPL session
binding.pry
| 20.090909
| 67
| 0.648567
|
e0084f9baf00be943a97b97490458ffa409b664c
| 10,210
|
c
|
C
|
softuart/softuart.c
|
d51x/esp-iot-home-components
|
f2fe397efab7238177d806f523f51cd3b8bba666
|
[
"MIT"
] | 1
|
2020-12-23T20:48:04.000Z
|
2020-12-23T20:48:04.000Z
|
softuart/softuart.c
|
d51x/esp-iot-home-components
|
f2fe397efab7238177d806f523f51cd3b8bba666
|
[
"MIT"
] | null | null | null |
softuart/softuart.c
|
d51x/esp-iot-home-components
|
f2fe397efab7238177d806f523f51cd3b8bba666
|
[
"MIT"
] | null | null | null |
/*
* Softuart
* Copyright (C) 2020 d51x <dimonich110@@gmail.com>
* Copyright (C) 2020 Ivan Belokobylskiy <belokobylskij@gmail.com>
* Copyright (C) 2017 Ruslan V. Uss <unclerus@gmail.com>
* Copyright (C) 2016 Bernhard Guillon <Bernhard.Guillon@web.de>
*
* The code is slightly modified to use ESP8266_RTOS SDK
* from Esspressif. The original code [2] is based on Softuart
* from here [1] and reworked to fit into esp-open-rtos.
*
* it fits my needs to read the GY-GPS6MV2 module with 9600 8n1
*
* Original Copyright:
* Copyright (c) 2015 plieningerweb
*
* MIT Licensed as described in the file LICENSE
*
* 1 https://github.com/plieningerweb/esp8266-software-uart
* 2 https://github.com/SuperHouse/esp-open-rtos/tree/master/extras/softuart
*/
#include "softuart.h"
#include <stdint.h>
#include "driver/gpio.h"
#include <stdio.h>
#include <string.h>
#include "rom/ets_sys.h"
#include "esp_log.h"
#include "utils.h"
#define SOFTUART_DEBUG
static const char *TAG = "SOFTUART";
#ifdef SOFTUART_DEBUG
#define debug(fmt, ...) printf("%s: " fmt "\n", "SOFTUART", ## __VA_ARGS__)
#else
#define debug(fmt, ...)
#endif
extern uint32_t esp_get_time(void);
typedef struct
{
char receive_buffer[SOFTUART_MAX_RX_BUFF];
uint8_t receive_buffer_tail;
uint8_t receive_buffer_head;
uint8_t buffer_overflow;
} softuart_buffer_t;
typedef struct
{
uint32_t rx_pin, tx_pin;
uint32_t baudrate;
volatile softuart_buffer_t buffer;
uint16_t bit_time;
uint16_t timeout;
} softuart_t;
static softuart_t uarts[SOFTUART_MAX_UARTS] = { { 0 } };
inline static int8_t find_uart_by_rx(uint8_t rx_pin)
{
for (uint8_t i = 0; i < SOFTUART_MAX_UARTS; i++)
if (uarts[i].baudrate && uarts[i].rx_pin == rx_pin) return i;
return -1;
}
static void IRAM_ATTR read_rx(softuart_t *uart)
{
// Now sample bits
uint8_t d = 0;
uint32_t start_time = 0x7FFFFFFF & esp_get_time();
for (uint8_t i = 0; i < 8; i++)
{
while ((0x7FFFFFFF & esp_get_time()) < (start_time + (uart->bit_time * (i + 1))))
{
// If system timer overflow, escape from while loop
if ((0x7FFFFFFF & esp_get_time()) < start_time)
break;
}
// Shift d to the right
d >>= 1;
// Read bit
if (gpio_get_level(uart->rx_pin))
{
// If high, set msb of 8bit to 1
d |= 0x80;
}
}
// Store byte in buffer
// If buffer full, set the overflow flag and return
uint8_t next = (uart->buffer.receive_buffer_tail + 1) % SOFTUART_MAX_RX_BUFF;
if (next != uart->buffer.receive_buffer_tail)
{
// save new data in buffer: tail points to where byte goes
uart->buffer.receive_buffer[uart->buffer.receive_buffer_tail] = d; // save new byte
uart->buffer.receive_buffer_tail = next;
}
else
{
uart->buffer.buffer_overflow = 1;
}
// Wait for stop bit
ets_delay_us(uart->bit_time);
//*!!!!!!!!!
/* from arduino esp8266 software serial */
/*
unsigned long wait = uart->bit_time;
while ((0x7FFFFFFF & esp_get_time()) - start_time > wait )
{
wait += uart->bit_time;
pauseTask(1);
}
*/
}
// GPIO interrupt handler
static void IRAM_ATTR handle_rx(void *arg)
{
if ( arg == NULL ) return;
portBASE_TYPE HPTaskAwoken = pdFALSE;
//BaseType_t xHigherPriorityTaskWoken;
softuart_t *uart = (softuart_t *)arg;
// Disable interrupt
gpio_set_intr_type(uart->rx_pin, GPIO_INTR_DISABLE);
// Wait till start bit is half over so we can sample the next one in the center
ets_delay_us(uart->bit_time / 2);
read_rx(uart);
// Done, reenable interrupt
gpio_set_intr_type(uart->rx_pin, GPIO_INTR_NEGEDGE);
portEND_SWITCHING_ISR( HPTaskAwoken == pdTRUE );
}
static bool check_uart_no(uint8_t uart_no)
{
if (uart_no >= SOFTUART_MAX_UARTS)
{
debug("Invalid uart number %d, %d max", uart_no, SOFTUART_MAX_UARTS);
return false;
}
return true;
}
static bool check_uart_enabled(uint8_t uart_no)
{
if (!uarts[uart_no].baudrate)
{
debug("Uart %d is disabled", uart_no);
return false;
}
return true;
}
///////////////////////////////////////////////////////////////////////////////
/// Public
///////////////////////////////////////////////////////////////////////////////
bool softuart_open(uint8_t uart_no, uint32_t baudrate, uint32_t rx_pin, uint32_t tx_pin, uint16_t timeout)
{
// do some checks
if (!check_uart_no(uart_no)) return false;
if (baudrate == 0)
{
debug("Invalid baudrate");
return false;
}
for (uint8_t i = 0; i < SOFTUART_MAX_UARTS; i++)
if (uarts[i].baudrate && i != uart_no
&& (uarts[i].rx_pin == rx_pin || uarts[i].tx_pin == tx_pin || uarts[i].rx_pin == tx_pin || uarts[i].tx_pin == rx_pin))
{
debug("Cannot share pins between uarts");
return false;
}
softuart_close(uart_no);
softuart_t *uart = uarts + uart_no;
uart->baudrate = baudrate;
uart->rx_pin = rx_pin;
uart->tx_pin = tx_pin;
uart->timeout = timeout;
// Calculate bit_time
uart->bit_time = (1000000 / baudrate);
if (((100000000 / baudrate) - (100 * uart->bit_time)) > 50) uart->bit_time++;
// Setup Rx
gpio_config_t io_conf;
io_conf.intr_type = GPIO_INTR_DISABLE;
io_conf.mode = GPIO_MODE_INPUT;
io_conf.pin_bit_mask = 1ULL<<rx_pin;
io_conf.pull_down_en = 0;
io_conf.pull_up_en = 1;
gpio_config(&io_conf);
// gpio_enable(rx_pin, GPIO_MODE_INPUT);
// gpio_pullup_en(rx_pin);
// Setup Tx
io_conf.intr_type = GPIO_INTR_DISABLE;
io_conf.mode = GPIO_MODE_OUTPUT;
io_conf.pin_bit_mask = 1ULL<<tx_pin;
io_conf.pull_down_en = 0;
io_conf.pull_up_en = 1;
gpio_config(&io_conf);
// gpio_enable(tx_pin, GPIO_MODE_OUTPUT);
// gpio_pullup_en(tx_pin);
gpio_set_level(tx_pin, 1);
//install gpio isr service
gpio_install_isr_service(0);
// Setup the interrupt handler to get the start bit
gpio_set_intr_type(rx_pin, GPIO_INTR_NEGEDGE);
//gpio_isr_handler_add(rx_pin, handle_rx, (void *)rx_pin);
gpio_isr_handler_add(rx_pin, handle_rx, (void *)uart);
ets_delay_us(1000); // TODO: not sure if it really needed
return true;
}
bool softuart_close(uint8_t uart_no)
{
if (!check_uart_no(uart_no)) return false;
softuart_t *uart = uarts + uart_no;
if (!uart->baudrate) return true;
// Remove interrupt
gpio_set_intr_type(uart->rx_pin, GPIO_INTR_DISABLE);
// Mark as unused
uart->baudrate = 0;
gpio_uninstall_isr_service();
return true;
}
bool softuart_put(uint8_t uart_no, char c)
{
if (!check_uart_no(uart_no)) return false;
if (!check_uart_enabled(uart_no)) return false;
softuart_t *uart = uarts + uart_no;
uint32_t start_time = 0x7FFFFFFF & esp_get_time();
gpio_set_level(uart->tx_pin, 0);
for (uint8_t i = 0; i < 8; i++)
{
while ((0x7FFFFFFF & esp_get_time()) < (start_time + (uart->bit_time * (i + 1))))
{
if ((0x7FFFFFFF & esp_get_time()) < start_time)
break;
}
gpio_set_level(uart->tx_pin, c & (1 << i));
}
while ((0x7FFFFFFF & esp_get_time()) < (start_time + (uart->bit_time * 9)))
{
if ((0x7FFFFFFF & esp_get_time()) < start_time)
break;
}
gpio_set_level(uart->tx_pin, 1);
ets_delay_us(uart->bit_time * 6);
return true;
}
bool softuart_puts(uint8_t uart_no, const char *s)
{
while (*s)
{
if (!softuart_put(uart_no, *s++)) {
ESP_LOGE(TAG, "error char put");
return false;
}
}
return true;
}
bool softuart_write_bytes(uint8_t uart_no, const uint8_t *buf, uint8_t sz)
{
for ( uint8_t i=0; i < sz; i++)
{
if (!softuart_put(uart_no, buf[i])) {
ESP_LOGE(TAG, "error char put");
return false;
}
}
return true;
}
uint8_t softuart_available(uint8_t uart_no)
{
if (!check_uart_no(uart_no)) return false;
if (!check_uart_enabled(uart_no)) return false;
softuart_t *uart = uarts + uart_no;
unsigned long t = millis();
int avail = 0;
while ( millis() - t < uart->timeout )
{
avail = uart->buffer.receive_buffer_tail - uart->buffer.receive_buffer_head;
if (avail < 0) avail += SOFTUART_MAX_RX_BUFF;
if ( avail > 0) break;
pauseTask(10);
}
return avail > 0;
}
uint8_t softuart_read(uint8_t uart_no)
{
if (!check_uart_no(uart_no)) return 0;
if (!check_uart_enabled(uart_no)) return 0;
softuart_t *uart = uarts + uart_no;
if (uart->buffer.receive_buffer_head == uart->buffer.receive_buffer_tail) return 0;
// Read from "head"
uint8_t d = uart->buffer.receive_buffer[uart->buffer.receive_buffer_head]; // grab next byte
uart->buffer.receive_buffer_head = (uart->buffer.receive_buffer_head + 1) % SOFTUART_MAX_RX_BUFF;
return d;
}
uint8_t softuart_read_buf(uint8_t uart_no, char *buf, uint8_t max_len)
{
uint8_t next_char;
uint8_t len = 0;
//WDT_FEED();
while ( softuart_available(uart_no) > 0)
{
next_char = softuart_read(uart_no);
/// if ( next_char == '\r') {
/// continue;
/// } else if ( next_char == '\n' ) {
/// if ( len > 0 ) {
/// break;
/// }
/// //} else if ( len < max_len - 1 ) {
/// } else
if ( len < max_len ) {
*buf++ = next_char;
len++;
} else {
break;
}
}
/// softuart_t *uart = uarts + uart_no;
/// memset(&uart->buffer, 0, sizeof(softuart_buffer_t));
return len;
}
| 27.299465
| 131
| 0.589716
|
88b10ac8b62c62f70b9af7a8094fae5774659d5a
| 469
|
rb
|
Ruby
|
lib/mechanize/form/check_box.rb
|
ucusita/mechanize
|
ff22ae0dd9908d73c3fad73b8e6f7c90d18650b1
|
[
"MIT"
] | 2,331
|
2015-01-01T11:30:26.000Z
|
2022-03-30T20:51:38.000Z
|
lib/mechanize/form/check_box.rb
|
ucusita/mechanize
|
ff22ae0dd9908d73c3fad73b8e6f7c90d18650b1
|
[
"MIT"
] | 183
|
2015-01-14T22:25:15.000Z
|
2022-03-30T08:12:51.000Z
|
lib/mechanize/form/check_box.rb
|
ucusita/mechanize
|
ff22ae0dd9908d73c3fad73b8e6f7c90d18650b1
|
[
"MIT"
] | 290
|
2015-01-01T17:04:01.000Z
|
2022-03-25T05:20:29.000Z
|
# frozen_string_literal: true
##
# This class represents a check box found in a Form. To activate the CheckBox
# in the Form, set the checked method to true.
class Mechanize::Form::CheckBox < Mechanize::Form::RadioButton
def query_value
[[@name, @value || "on"]]
end
def inspect # :nodoc:
"[%s:0x%x type: %s name: %s value: %s]" % [
self.class.name.sub(/Mechanize::Form::/, '').downcase,
object_id, type, name, checked
]
end
end
| 22.333333
| 78
| 0.639659
|
eb05446d189265b84204ebb0b570f74fd72aebce
| 3,052
|
css
|
CSS
|
src/theme/dialog.css
|
hudhudhud/wjxt-formGenerator
|
3bfbfbcf75178b5060ea3399182a159627575e4b
|
[
"Apache-2.0"
] | null | null | null |
src/theme/dialog.css
|
hudhudhud/wjxt-formGenerator
|
3bfbfbcf75178b5060ea3399182a159627575e4b
|
[
"Apache-2.0"
] | null | null | null |
src/theme/dialog.css
|
hudhudhud/wjxt-formGenerator
|
3bfbfbcf75178b5060ea3399182a159627575e4b
|
[
"Apache-2.0"
] | null | null | null |
.v-modal-enter { -webkit-animation: v-modal-in 0.2s ease; animation: v-modal-in 0.2s ease; }
.v-modal-leave { -webkit-animation: v-modal-out 0.2s ease forwards; animation: v-modal-out 0.2s ease forwards; }
@-webkit-keyframes v-modal-in { 0% { opacity: 0; } }
@keyframes v-modal-in { 0% { opacity: 0; } }
@-webkit-keyframes v-modal-out { 100% { opacity: 0; } }
@keyframes v-modal-out { 100% { opacity: 0; } }
.v-modal { position: fixed; left: 0; top: 0; width: 100%; height: 100%; opacity: 0.5; background: #000; }
.el-popup-parent--hidden { overflow: hidden; }
.el-dialog { position: relative; margin: 0 auto 50px; background: #fff; border-radius: 2px; -webkit-box-shadow: 0 1px 3px rgba(0, 0, 0, 0.3); box-shadow: 0 1px 3px rgba(0, 0, 0, 0.3); -webkit-box-sizing: border-box; box-sizing: border-box; width: 50%; }
.el-dialog.is-fullscreen { width: 100%; margin-top: 0; margin-bottom: 0; height: 100%; overflow: auto; }
.el-dialog__wrapper { position: fixed; top: 0; right: 0; bottom: 0; left: 0; overflow: auto; margin: 0; }
.el-dialog__header { padding: 20px 20px 10px; }
.el-dialog__headerbtn { position: absolute; top: 20px; right: 20px; padding: 0; background: 0 0; border: none; outline: 0; cursor: pointer; font-size: 16px; }
.el-dialog__headerbtn .el-dialog__close { color: #909399; }
.el-dialog__headerbtn:focus .el-dialog__close,
.el-dialog__headerbtn:hover .el-dialog__close { color: #205bb5; }
.el-dialog__title { line-height: 24px; font-size: 18px; color: #303133; }
.el-dialog__body { padding: 30px 20px; color: #606266; font-size: 14px; word-break: break-all; }
.el-dialog__footer { padding: 10px 20px 20px; text-align: right; -webkit-box-sizing: border-box; box-sizing: border-box; }
.el-dialog--center { text-align: center; }
.el-dialog--center .el-dialog__body { text-align: initial; padding: 25px 25px 30px; }
.el-dialog--center .el-dialog__footer { text-align: inherit; }
.dialog-fade-enter-active { -webkit-animation: dialog-fade-in 0.3s; animation: dialog-fade-in 0.3s; }
.dialog-fade-leave-active { -webkit-animation: dialog-fade-out 0.3s; animation: dialog-fade-out 0.3s; }
@-webkit-keyframes dialog-fade-in {
0% { -webkit-transform: translate3d(0, -20px, 0); transform: translate3d(0, -20px, 0); opacity: 0; }
100% { -webkit-transform: translate3d(0, 0, 0); transform: translate3d(0, 0, 0); opacity: 1; }
}
@keyframes dialog-fade-in {
0% { -webkit-transform: translate3d(0, -20px, 0); transform: translate3d(0, -20px, 0); opacity: 0; }
100% { -webkit-transform: translate3d(0, 0, 0); transform: translate3d(0, 0, 0); opacity: 1; }
}
@-webkit-keyframes dialog-fade-out {
0% { -webkit-transform: translate3d(0, 0, 0); transform: translate3d(0, 0, 0); opacity: 1; }
100% { -webkit-transform: translate3d(0, -20px, 0); transform: translate3d(0, -20px, 0); opacity: 0; }
}
@keyframes dialog-fade-out {
0% { -webkit-transform: translate3d(0, 0, 0); transform: translate3d(0, 0, 0); opacity: 1; }
100% { -webkit-transform: translate3d(0, -20px, 0); transform: translate3d(0, -20px, 0); opacity: 0; }
}
| 74.439024
| 253
| 0.684142
|
dd7bd71ac6f7809e516e0bf1a31b2ef9aba18c28
| 971
|
java
|
Java
|
plugins/org.eclipse.tm.terminal.view.ui/src/org/eclipse/tm/terminal/view/ui/listeners/WorkbenchWindowListener.java
|
hernad/dbeaver
|
c870417912fa712d3e96388c8c8ad33e4d962031
|
[
"Apache-2.0"
] | null | null | null |
plugins/org.eclipse.tm.terminal.view.ui/src/org/eclipse/tm/terminal/view/ui/listeners/WorkbenchWindowListener.java
|
hernad/dbeaver
|
c870417912fa712d3e96388c8c8ad33e4d962031
|
[
"Apache-2.0"
] | null | null | null |
plugins/org.eclipse.tm.terminal.view.ui/src/org/eclipse/tm/terminal/view/ui/listeners/WorkbenchWindowListener.java
|
hernad/dbeaver
|
c870417912fa712d3e96388c8c8ad33e4d962031
|
[
"Apache-2.0"
] | null | null | null |
/*******************************************************************************
* Copyright (c) 2014, 2018 Wind River Systems, Inc. and others. All rights reserved.
* This program and the accompanying materials are made available under the terms
* of the Eclipse Public License 2.0 which accompanies this distribution, and is
* available at https://www.eclipse.org/legal/epl-2.0/
*
* SPDX-License-Identifier: EPL-2.0
*
* Contributors:
* Wind River Systems - initial API and implementation
*******************************************************************************/
package org.eclipse.tm.terminal.view.ui.listeners;
import org.eclipse.ui.IPartListener2;
/**
* The window listener implementation. Takes care of the
* management of the global listeners per workbench window.
*/
public class WorkbenchWindowListener extends AbstractWindowListener {
@Override
protected IPartListener2 createPartListener() {
return new WorkbenchPartListener();
}
}
| 35.962963
| 85
| 0.641607
|
652df25b26f23304d64962894f32d680bdc31e24
| 125
|
dart
|
Dart
|
lib/src/app_mode.dart
|
dafesimonek/koronac-na-akci
|
4881e8973bf8d92a92628001ad3cff4451095460
|
[
"Apache-2.0"
] | null | null | null |
lib/src/app_mode.dart
|
dafesimonek/koronac-na-akci
|
4881e8973bf8d92a92628001ad3cff4451095460
|
[
"Apache-2.0"
] | null | null | null |
lib/src/app_mode.dart
|
dafesimonek/koronac-na-akci
|
4881e8973bf8d92a92628001ad3cff4451095460
|
[
"Apache-2.0"
] | null | null | null |
///
/// Environment - production or test?
///
/// See:
/// main_prod.dart
/// main_test.dart
///
enum AppMode { PROD, TEST }
| 13.888889
| 37
| 0.6
|
c3f772db5941d7fa063422e99d5435223a314415
| 787
|
cs
|
C#
|
src/E01D.Base.Api/Coding/Code/Api/E01D/Core/Primitives/SingleApi.cs
|
E01D/Base
|
17ae4a28cb0b4347a19ebb2c06b19a6c080ad47e
|
[
"Apache-2.0"
] | null | null | null |
src/E01D.Base.Api/Coding/Code/Api/E01D/Core/Primitives/SingleApi.cs
|
E01D/Base
|
17ae4a28cb0b4347a19ebb2c06b19a6c080ad47e
|
[
"Apache-2.0"
] | null | null | null |
src/E01D.Base.Api/Coding/Code/Api/E01D/Core/Primitives/SingleApi.cs
|
E01D/Base
|
17ae4a28cb0b4347a19ebb2c06b19a6c080ad47e
|
[
"Apache-2.0"
] | null | null | null |
using System.Globalization;
namespace Root.Coding.Code.Api.E01D.Core.Primitives
{
public class SingleApi
{
/// <summary>
/// Reads the single value from the json node
/// </summary>
/// <param name="node"></param>
/// <returns></returns>
public float Read(string stringValue)
{
if (float.TryParse(stringValue, out float result)) return result;
return 0;
}
/// <summary>
/// Writes the single value to the json node
/// </summary>
/// <param name="node"></param>
/// <param name="doubleValue"></param>
public string Write(float singleValue)
{
return singleValue.ToString(CultureInfo.InvariantCulture);
}
}
}
| 26.233333
| 77
| 0.551461
|
038a037401ada803a689279a86d1d05acf7e89aa
| 75,278
|
lua
|
Lua
|
opencl/init.lua
|
LuaDist-testing/opencl
|
447c01353d81844e6a469275e57a563dfdb63697
|
[
"MIT"
] | null | null | null |
opencl/init.lua
|
LuaDist-testing/opencl
|
447c01353d81844e6a469275e57a563dfdb63697
|
[
"MIT"
] | null | null | null |
opencl/init.lua
|
LuaDist-testing/opencl
|
447c01353d81844e6a469275e57a563dfdb63697
|
[
"MIT"
] | null | null | null |
------------------------------------------------------------------------------
-- OpenCL for Lua.
-- Copyright © 2013–2015 Peter Colberg.
-- Distributed under the MIT license. (See accompanying file LICENSE.)
------------------------------------------------------------------------------
local C = require("opencl.C")
local bit = require("bit")
local ffi = require("ffi")
local _M = {}
-- C types.
local char_n = ffi.typeof("char[?]")
local cl_bool = ffi.typeof("cl_bool")
local cl_bool_1 = ffi.typeof("cl_bool[1]")
local cl_buffer_region = ffi.typeof("cl_buffer_region")
local cl_build_status = ffi.typeof("cl_build_status")
local cl_build_status_1 = ffi.typeof("cl_build_status[1]")
local cl_command_queue = ffi.typeof("cl_command_queue")
local cl_command_queue_1 = ffi.typeof("cl_command_queue[1]")
local cl_command_queue_properties = ffi.typeof("cl_command_queue_properties")
local cl_command_queue_properties_1 = ffi.typeof("cl_command_queue_properties[1]")
local cl_command_type = ffi.typeof("cl_command_type")
local cl_command_type_1 = ffi.typeof("cl_command_type[1]")
local cl_context = ffi.typeof("cl_context")
local cl_context_1 = ffi.typeof("cl_context[1]")
local cl_device_affinity_domain = ffi.typeof("cl_device_affinity_domain")
local cl_device_affinity_domain_1 = ffi.typeof("cl_device_affinity_domain[1]")
local cl_device_exec_capabilities = ffi.typeof("cl_device_exec_capabilities")
local cl_device_exec_capabilities_1 = ffi.typeof("cl_device_exec_capabilities[1]")
local cl_device_fp_config = ffi.typeof("cl_device_fp_config")
local cl_device_fp_config_1 = ffi.typeof("cl_device_fp_config[1]")
local cl_device_id = ffi.typeof("cl_device_id")
local cl_device_id_1 = ffi.typeof("cl_device_id[1]")
local cl_device_id_n = ffi.typeof("cl_device_id[?]")
local cl_device_local_mem_type = ffi.typeof("cl_device_local_mem_type")
local cl_device_local_mem_type_1 = ffi.typeof("cl_device_local_mem_type[1]")
local cl_device_mem_cache_type = ffi.typeof("cl_device_mem_cache_type")
local cl_device_mem_cache_type_1 = ffi.typeof("cl_device_mem_cache_type[1]")
local cl_device_partition_property = ffi.typeof("cl_device_partition_property")
local cl_device_partition_property_3 = ffi.typeof("cl_device_partition_property[3]")
local cl_device_partition_property_n = ffi.typeof("cl_device_partition_property[?]")
local cl_device_type = ffi.typeof("cl_device_type")
local cl_device_type_1 = ffi.typeof("cl_device_type[1]")
local cl_event_1 = ffi.typeof("cl_event[1]")
local cl_event_n = ffi.typeof("cl_event[?]")
local cl_int = ffi.typeof("cl_int")
local cl_int_1 = ffi.typeof("cl_int[1]")
local cl_kernel_n = ffi.typeof("cl_kernel[?]")
local cl_kernel_arg_access_qualifier = ffi.typeof("cl_kernel_arg_access_qualifier")
local cl_kernel_arg_access_qualifier_1 = ffi.typeof("cl_kernel_arg_access_qualifier[1]")
local cl_kernel_arg_address_qualifier = ffi.typeof("cl_kernel_arg_address_qualifier")
local cl_kernel_arg_address_qualifier_1 = ffi.typeof("cl_kernel_arg_address_qualifier[1]")
local cl_kernel_arg_type_qualifier = ffi.typeof("cl_kernel_arg_type_qualifier")
local cl_kernel_arg_type_qualifier_1 = ffi.typeof("cl_kernel_arg_type_qualifier[1]")
local cl_mem = ffi.typeof("cl_mem")
local cl_mem_1 = ffi.typeof("cl_mem[1]")
local cl_mem_flags = ffi.typeof("cl_mem_flags")
local cl_mem_flags_1 = ffi.typeof("cl_mem_flags[1]")
local cl_mem_object_type = ffi.typeof("cl_mem_object_type")
local cl_mem_object_type_1 = ffi.typeof("cl_mem_object_type[1]")
local cl_platform_id = ffi.typeof("cl_platform_id")
local cl_platform_id_1 = ffi.typeof("cl_platform_id[1]")
local cl_platform_id_n = ffi.typeof("cl_platform_id[?]")
local cl_program = ffi.typeof("cl_program")
local cl_program_1 = ffi.typeof("cl_program[1]")
local cl_program_binary_type = ffi.typeof("cl_program_binary_type")
local cl_program_binary_type_1 = ffi.typeof("cl_program_binary_type[1]")
local cl_sampler = ffi.typeof("cl_sampler")
local cl_sampler_1 = ffi.typeof("cl_sampler[1]")
local cl_uint = ffi.typeof("cl_uint")
local cl_uint_1 = ffi.typeof("cl_uint[1]")
local cl_ulong = ffi.typeof("cl_ulong")
local cl_ulong_1 = ffi.typeof("cl_ulong[1]")
local const_char_ptr = ffi.typeof("const char *")
local const_char_ptr_1 = ffi.typeof("const char *[1]")
local size_t = ffi.typeof("size_t")
local size_t_1 = ffi.typeof("size_t[1]")
local size_t_n = ffi.typeof("size_t[?]")
local unsigned_char_n = ffi.typeof("unsigned char[?]")
local unsigned_char_ptr = ffi.typeof("unsigned char *")
local unsigned_char_ptr_n = ffi.typeof("unsigned char *[?]")
local void_ptr = ffi.typeof("void *")
local void_ptr_1 = ffi.typeof("void *[1]")
-- Object methods.
local platform = {}
local device = {}
local context = {}
local mem = {}
local queue = {}
local program = {}
local kernel = {}
local event = {}
-- Cache library functions.
local band, bor = bit.band, bit.bor
-- Converts a bit-field to a table of boolean values.
local function bittobool(b, map)
local t = {}
for k, v in pairs(map) do
if band(b, k) ~= 0 then t[v] = true end
end
return t
end
-- Converts a sequence of strings to a bit-field.
local function strtobit(t, map)
if type(t) == "string" then return map[t] end
local b = 0
for _, v in ipairs(t) do
b = bor(b, map[v])
end
return b
end
-- OpenCL error messages.
local errors = {
[C.CL_SUCCESS] = "Success",
[C.CL_DEVICE_NOT_FOUND] = "Device not found",
[C.CL_DEVICE_NOT_AVAILABLE] = "Device not available",
[C.CL_COMPILER_NOT_AVAILABLE] = "Compiler not available",
[C.CL_MEM_OBJECT_ALLOCATION_FAILURE] = "Memory object allocation failure",
[C.CL_OUT_OF_RESOURCES] = "Out of resources",
[C.CL_OUT_OF_HOST_MEMORY] = "Out of host memory",
[C.CL_PROFILING_INFO_NOT_AVAILABLE] = "Profiling information not available",
[C.CL_MEM_COPY_OVERLAP] = "Memory copy overlap",
[C.CL_IMAGE_FORMAT_MISMATCH] = "Image format mismatch",
[C.CL_IMAGE_FORMAT_NOT_SUPPORTED] = "Image format not supported",
[C.CL_BUILD_PROGRAM_FAILURE] = "Build program failure",
[C.CL_MAP_FAILURE] = "Map failure",
[C.CL_MISALIGNED_SUB_BUFFER_OFFSET] = "Misaligned sub-buffer offset",
[C.CL_EXEC_STATUS_ERROR_FOR_EVENTS_IN_WAIT_LIST] = "Execution status error for events in wait list",
[C.CL_COMPILE_PROGRAM_FAILURE] = "Compile program failure",
[C.CL_LINKER_NOT_AVAILABLE] = "Linker not available",
[C.CL_LINK_PROGRAM_FAILURE] = "Link program failure",
[C.CL_DEVICE_PARTITION_FAILED] = "Device partition failed",
[C.CL_KERNEL_ARG_INFO_NOT_AVAILABLE] = "Kernel argument information not available",
[C.CL_INVALID_VALUE] = "Invalid value",
[C.CL_INVALID_DEVICE_TYPE] = "Invalid device type",
[C.CL_INVALID_PLATFORM] = "Invalid platform",
[C.CL_INVALID_DEVICE] = "Invalid device",
[C.CL_INVALID_CONTEXT] = "Invalid context",
[C.CL_INVALID_QUEUE_PROPERTIES] = "Invalid queue properties",
[C.CL_INVALID_COMMAND_QUEUE] = "Invalid command-queue",
[C.CL_INVALID_HOST_PTR] = "Invalid host pointer",
[C.CL_INVALID_MEM_OBJECT] = "Invalid memory object",
[C.CL_INVALID_IMAGE_FORMAT_DESCRIPTOR] = "Invalid image format descriptor",
[C.CL_INVALID_IMAGE_SIZE] = "Invalid image size",
[C.CL_INVALID_SAMPLER] = "Invalid sampler",
[C.CL_INVALID_BINARY] = "Invalid binary",
[C.CL_INVALID_BUILD_OPTIONS] = "Invalid build options",
[C.CL_INVALID_PROGRAM] = "Invalid program",
[C.CL_INVALID_PROGRAM_EXECUTABLE] = "Invalid program executable",
[C.CL_INVALID_KERNEL_NAME] = "Invalid kernel name",
[C.CL_INVALID_KERNEL_DEFINITION] = "Invalid kernel definition",
[C.CL_INVALID_KERNEL] = "Invalid kernel",
[C.CL_INVALID_ARG_INDEX] = "Invalid argument index",
[C.CL_INVALID_ARG_VALUE] = "Invalid argument value",
[C.CL_INVALID_ARG_SIZE] = "Invalid argument size",
[C.CL_INVALID_KERNEL_ARGS] = "Invalid kernel arguments",
[C.CL_INVALID_WORK_DIMENSION] = "Invalid work dimension",
[C.CL_INVALID_WORK_GROUP_SIZE] = "Invalid work group size",
[C.CL_INVALID_WORK_ITEM_SIZE] = "Invalid work item size",
[C.CL_INVALID_GLOBAL_OFFSET] = "Invalid global offset",
[C.CL_INVALID_EVENT_WAIT_LIST] = "Invalid event wait list",
[C.CL_INVALID_EVENT] = "Invalid event",
[C.CL_INVALID_OPERATION] = "Invalid operation",
[C.CL_INVALID_GL_OBJECT] = "Invalid GL object",
[C.CL_INVALID_BUFFER_SIZE] = "Invalid buffer size",
[C.CL_INVALID_MIP_LEVEL] = "Invalid mipmap level",
[C.CL_INVALID_GLOBAL_WORK_SIZE] = "Invalid global work size",
[C.CL_INVALID_PROPERTY] = "Invalid property",
[C.CL_INVALID_IMAGE_DESCRIPTOR] = "Invalid image descriptor",
[C.CL_INVALID_COMPILER_OPTIONS] = "Invalid compiler options",
[C.CL_INVALID_LINKER_OPTIONS] = "Invalid linker options",
[C.CL_INVALID_DEVICE_PARTITION_COUNT] = "Invalid device partition count",
}
setmetatable(errors, {__index = function() return "Unknown error code" end})
function _M.get_platforms()
local num_platforms = cl_uint_1()
local status = C.clGetPlatformIDs(0, nil, num_platforms)
if status ~= C.CL_SUCCESS then return error(errors[status]) end
if num_platforms[0] == 0 then return end
local platforms_buf = cl_platform_id_n(num_platforms[0])
local status = C.clGetPlatformIDs(num_platforms[0], platforms_buf, nil)
if status ~= C.CL_SUCCESS then return error(errors[status]) end
local platforms = {}
for i = 0, num_platforms[0] - 1 do platforms[i + 1] = platforms_buf[i] end
return platforms
end
do
local function get_platform_info_string(name)
return function(platform)
local size = size_t_1()
local status = C.clGetPlatformInfo(platform, name, 0, nil, size)
if status == C.CL_INVALID_VALUE or status == C.CL_INVALID_OPERATION then return end
if status ~= C.CL_SUCCESS then return error(errors[status]) end
if size[0] == 0 then return end
local value = char_n(size[0])
local status = C.clGetPlatformInfo(platform, name, size[0], value, nil)
if status ~= C.CL_SUCCESS then return error(errors[status]) end
return ffi.string(value, size[0] - 1)
end
end
local platform_info = {
profile = get_platform_info_string(C.CL_PLATFORM_PROFILE),
version = get_platform_info_string(C.CL_PLATFORM_VERSION),
name = get_platform_info_string(C.CL_PLATFORM_NAME),
vendor = get_platform_info_string(C.CL_PLATFORM_VENDOR),
extensions = get_platform_info_string(C.CL_PLATFORM_EXTENSIONS),
}
function platform.get_info(platform, name)
return platform_info[name](platform)
end
end
do
local device_types = {
cpu = C.CL_DEVICE_TYPE_CPU,
gpu = C.CL_DEVICE_TYPE_GPU,
accelerator = C.CL_DEVICE_TYPE_ACCELERATOR,
custom = C.CL_DEVICE_TYPE_CUSTOM,
default = C.CL_DEVICE_TYPE_DEFAULT,
}
function platform.get_devices(platform, device_type)
if device_type ~= nil then device_type = strtobit(device_type, device_types) else device_type = C.CL_DEVICE_TYPE_ALL end
local num_devices = cl_uint_1()
local status = C.clGetDeviceIDs(platform, device_type, 0, nil, num_devices)
if status == C.CL_DEVICE_NOT_FOUND then return end
if status ~= C.CL_SUCCESS then return error(errors[status]) end
if num_devices[0] == 0 then return end
local devices_buf = cl_device_id_n(num_devices[0])
local status = C.clGetDeviceIDs(platform, device_type, num_devices[0], devices_buf, nil)
if status ~= C.CL_SUCCESS then return error(errors[status]) end
local devices = {}
for i = 0, num_devices[0] - 1 do devices[i + 1] = devices_buf[i] end
return devices
end
end
do
local function get_device_info_size(name)
return function(device)
local value = size_t_1()
local status = C.clGetDeviceInfo(device, name, ffi.sizeof(size_t), value, nil)
if status == C.CL_INVALID_VALUE or status == C.CL_INVALID_OPERATION then return end
if status ~= C.CL_SUCCESS then return error(errors[status]) end
if value[0] == 0 then return nil end
return tonumber(value[0])
end
end
local function get_device_info_uint(name)
return function(device)
local value = cl_uint_1()
local status = C.clGetDeviceInfo(device, name, ffi.sizeof(cl_uint), value, nil)
if status == C.CL_INVALID_VALUE or status == C.CL_INVALID_OPERATION then return end
if status ~= C.CL_SUCCESS then return error(errors[status]) end
if value[0] == 0 then return nil end
return tonumber(value[0])
end
end
local function get_device_info_ulong(name)
return function(device)
local value = cl_ulong_1()
local status = C.clGetDeviceInfo(device, name, ffi.sizeof(cl_ulong), value, nil)
if status == C.CL_INVALID_VALUE or status == C.CL_INVALID_OPERATION then return end
if status ~= C.CL_SUCCESS then return error(errors[status]) end
if value[0] == 0 then return nil end
return tonumber(value[0])
end
end
local function get_device_info_bool(name)
return function(device)
local value = cl_bool_1()
local status = C.clGetDeviceInfo(device, name, ffi.sizeof(cl_bool), value, nil)
if status == C.CL_INVALID_VALUE or status == C.CL_INVALID_OPERATION then return end
if status ~= C.CL_SUCCESS then return error(errors[status]) end
return value[0] == C.CL_TRUE
end
end
local function get_device_info_string(name)
return function(device)
local size = size_t_1()
local status = C.clGetDeviceInfo(device, name, 0, nil, size)
if status == C.CL_INVALID_VALUE or status == C.CL_INVALID_OPERATION then return end
if status ~= C.CL_SUCCESS then return error(errors[status]) end
if size[0] == 0 then return end
local value = char_n(size[0])
local status = C.clGetDeviceInfo(device, name, size[0], value, nil)
if status ~= C.CL_SUCCESS then return error(errors[status]) end
return ffi.string(value, size[0] - 1)
end
end
local device_fp_config = {
[C.CL_FP_DENORM] = "denorm",
[C.CL_FP_INF_NAN] = "inf_nan",
[C.CL_FP_ROUND_TO_NEAREST] = "round_to_nearest",
[C.CL_FP_ROUND_TO_ZERO] = "round_to_zero",
[C.CL_FP_ROUND_TO_INF] = "round_to_inf",
[C.CL_FP_FMA] = "fma",
[C.CL_FP_SOFT_FLOAT] = "soft_float",
}
local function get_device_info_fp_config(name)
return function(device)
local value = cl_device_fp_config_1()
local status = C.clGetDeviceInfo(device, name, ffi.sizeof(cl_device_fp_config), value, nil)
if status == C.CL_INVALID_VALUE or status == C.CL_INVALID_OPERATION then return end
if status ~= C.CL_SUCCESS then return error(errors[status]) end
if value[0] == 0 then return nil end
return bittobool(tonumber(value[0]), device_fp_config)
end
end
local device_exec_capabilities = {
[C.CL_EXEC_KERNEL] = "kernel",
[C.CL_EXEC_NATIVE_KERNEL] = "native_kernel",
}
local function get_device_info_execution_capabilities(device)
local value = cl_device_exec_capabilities_1()
local status = C.clGetDeviceInfo(device, C.CL_DEVICE_EXECUTION_CAPABILITIES, ffi.sizeof(cl_device_exec_capabilities), value, nil)
if status == C.CL_INVALID_VALUE or status == C.CL_INVALID_OPERATION then return end
if status ~= C.CL_SUCCESS then return error(errors[status]) end
if value[0] == 0 then return nil end
return bittobool(tonumber(value[0]), device_exec_capabilities)
end
local device_mem_cache_type = {
[C.CL_READ_ONLY_CACHE] = "read_only",
[C.CL_READ_WRITE_CACHE] = "read_write",
}
local function get_device_info_global_mem_cache_type(device)
local value = cl_device_mem_cache_type_1()
local status = C.clGetDeviceInfo(device, C.CL_DEVICE_GLOBAL_MEM_CACHE_TYPE, ffi.sizeof(cl_device_mem_cache_type), value, nil)
if status == C.CL_INVALID_VALUE or status == C.CL_INVALID_OPERATION then return end
if status ~= C.CL_SUCCESS then return error(errors[status]) end
if value[0] == C.CL_NONE then return nil end
return device_mem_cache_type[value[0]]
end
local device_local_mem_type = {
[C.CL_LOCAL] = "local",
[C.CL_GLOBAL] = "global",
}
local function get_device_info_local_mem_type(device)
local value = cl_device_local_mem_type_1()
local status = C.clGetDeviceInfo(device, C.CL_DEVICE_LOCAL_MEM_TYPE, ffi.sizeof(cl_device_local_mem_type), value, nil)
if status == C.CL_INVALID_VALUE or status == C.CL_INVALID_OPERATION then return end
if status ~= C.CL_SUCCESS then return error(errors[status]) end
if value[0] == C.CL_NONE then return nil end
return device_local_mem_type[value[0]]
end
local function get_device_info_sizes(name)
return function(device)
local size = size_t_1()
local status = C.clGetDeviceInfo(device, name, 0, nil, size)
if status == C.CL_INVALID_VALUE or status == C.CL_INVALID_OPERATION then return end
if status ~= C.CL_SUCCESS then return error(errors[status]) end
local num_sizes = tonumber(size[0]) / ffi.sizeof(size_t)
local value = size_t_n(num_sizes)
local status = C.clGetDeviceInfo(device, name, size[0], value, nil)
if status ~= C.CL_SUCCESS then return error(errors[status]) end
local sizes = {}
for i = 0, num_sizes - 1 do sizes[i + 1] = tonumber(value[i]) end
return sizes
end
end
local function get_device_info_parent_device(device)
local value = cl_device_id_1()
local status = C.clGetDeviceInfo(device, C.CL_DEVICE_PARENT_DEVICE, ffi.sizeof(cl_device_id), value, nil)
if status == C.CL_INVALID_VALUE or status == C.CL_INVALID_OPERATION then return end
if status ~= C.CL_SUCCESS then return error(errors[status]) end
if value[0] ~= nil then return cl_device_id(value[0]) end
end
local function get_device_info_platform(device)
local value = cl_platform_id_1()
local status = C.clGetDeviceInfo(device, C.CL_DEVICE_PLATFORM, ffi.sizeof(cl_platform_id), value, nil)
if status == C.CL_INVALID_VALUE or status == C.CL_INVALID_OPERATION then return end
if status ~= C.CL_SUCCESS then return error(errors[status]) end
if value[0] ~= nil then return cl_platform_id(value[0]) end
end
local device_type = {
[C.CL_DEVICE_TYPE_CPU] = "cpu",
[C.CL_DEVICE_TYPE_GPU] = "gpu",
[C.CL_DEVICE_TYPE_ACCELERATOR] = "accelerator",
[C.CL_DEVICE_TYPE_DEFAULT] = "default",
[C.CL_DEVICE_TYPE_CUSTOM] = "custom",
}
local function get_device_info_type(device)
local value = cl_device_type_1()
local status = C.clGetDeviceInfo(device, C.CL_DEVICE_TYPE, ffi.sizeof(cl_device_type), value, nil)
if status == C.CL_INVALID_VALUE or status == C.CL_INVALID_OPERATION then return end
if status ~= C.CL_SUCCESS then return error(errors[status]) end
if value[0] == 0 then return nil end
return bittobool(tonumber(value[0]), device_type)
end
local command_queue_properties = {
[C.CL_QUEUE_OUT_OF_ORDER_EXEC_MODE_ENABLE] = "out_of_order_exec_mode",
[C.CL_QUEUE_PROFILING_ENABLE] = "profiling",
}
local function get_device_info_queue_properties(device)
local value = cl_command_queue_properties_1()
local status = C.clGetDeviceInfo(device, C.CL_DEVICE_QUEUE_PROPERTIES, ffi.sizeof(cl_command_queue_properties), value, nil)
if status == C.CL_INVALID_VALUE or status == C.CL_INVALID_OPERATION then return end
if status ~= C.CL_SUCCESS then return error(errors[status]) end
if value[0] == 0 then return nil end
return bittobool(tonumber(value[0]), command_queue_properties)
end
local partition_property = {
[C.CL_DEVICE_PARTITION_EQUALLY] = "equally",
[C.CL_DEVICE_PARTITION_BY_COUNTS] = "by_counts",
[C.CL_DEVICE_PARTITION_BY_AFFINITY_DOMAIN] = "by_affinity_domain",
}
local function get_device_info_partition_properties(device)
local size = size_t_1()
local status = C.clGetDeviceInfo(device, C.CL_DEVICE_PARTITION_PROPERTIES, 0, nil, size)
if status == C.CL_INVALID_VALUE or status == C.CL_INVALID_OPERATION then return end
if status ~= C.CL_SUCCESS then return error(errors[status]) end
local num_properties = tonumber(size[0]) / ffi.sizeof(cl_device_partition_property)
local value = cl_device_partition_property_n(num_properties)
local status = C.clGetDeviceInfo(device, C.CL_DEVICE_PARTITION_PROPERTIES, size[0], value, nil)
if status ~= C.CL_SUCCESS then return error(errors[status]) end
local properties = {}
for i = 0, num_properties - 1 do
if value[i] == 0 then break end
local partition_property = partition_property[tonumber(value[i])]
if partition_property ~= nil then properties[partition_property] = true end
end
return properties
end
local partition_affinity_domain = {
[C.CL_DEVICE_AFFINITY_DOMAIN_NUMA] = "numa",
[C.CL_DEVICE_AFFINITY_DOMAIN_L4_CACHE] = "l4_cache",
[C.CL_DEVICE_AFFINITY_DOMAIN_L3_CACHE] = "l3_cache",
[C.CL_DEVICE_AFFINITY_DOMAIN_L2_CACHE] = "l2_cache",
[C.CL_DEVICE_AFFINITY_DOMAIN_L1_CACHE] = "l1_cache",
[C.CL_DEVICE_AFFINITY_DOMAIN_NEXT_PARTITIONABLE] = "next_partitionable",
}
local function get_device_info_partition_affinity_domain(device)
local value = cl_device_affinity_domain_1()
local status = C.clGetDeviceInfo(device, C.CL_DEVICE_PARTITION_AFFINITY_DOMAIN, ffi.sizeof(cl_device_affinity_domain), value, nil)
if status == C.CL_INVALID_VALUE or status == C.CL_INVALID_OPERATION then return end
if status ~= C.CL_SUCCESS then return error(errors[status]) end
if value[0] == 0 then return end
return bittobool(tonumber(value[0]), partition_affinity_domain)
end
local partition_property_value = {
[C.CL_DEVICE_PARTITION_EQUALLY] = function(value)
return "equally", tonumber(value[1])
end,
[C.CL_DEVICE_PARTITION_BY_COUNTS] = function(value)
local counts = {}
while value[1] ~= C.CL_DEVICE_PARTITION_BY_COUNTS_LIST_END do
counts[#counts + 1] = tonumber(value[1])
value = value + 1
end
return "by_counts", counts
end,
[C.CL_DEVICE_PARTITION_BY_AFFINITY_DOMAIN] = function(value)
return "by_affinity_domain", partition_affinity_domain[tonumber(value[1])]
end,
}
local function get_device_info_partition_type(device)
local size = size_t_1()
local status = C.clGetDeviceInfo(device, C.CL_DEVICE_PARTITION_TYPE, 0, nil, size)
if status == C.CL_INVALID_VALUE or status == C.CL_INVALID_OPERATION then return end
if status ~= C.CL_SUCCESS then return error(errors[status]) end
local num_properties = tonumber(size[0]) / ffi.sizeof(cl_device_partition_property)
local value = cl_device_partition_property_n(num_properties + 1)
local status = C.clGetDeviceInfo(device, C.CL_DEVICE_PARTITION_TYPE, size[0], value, nil)
if status ~= C.CL_SUCCESS then return error(errors[status]) end
if value[0] == 0 then return end
return partition_property_value[tonumber(value[0])](value)
end
local device_info = {
address_bits = get_device_info_uint(C.CL_DEVICE_ADDRESS_BITS),
available = get_device_info_bool(C.CL_DEVICE_AVAILABLE),
built_in_kernels = get_device_info_string(C.CL_DEVICE_BUILT_IN_KERNELS),
compiler_available = get_device_info_bool(C.CL_DEVICE_COMPILER_AVAILABLE),
double_fp_config = get_device_info_fp_config(C.CL_DEVICE_DOUBLE_FP_CONFIG),
endian_little = get_device_info_bool(C.CL_DEVICE_ENDIAN_LITTLE),
error_correction_support = get_device_info_bool(C.CL_DEVICE_ERROR_CORRECTION_SUPPORT),
execution_capabilities = get_device_info_execution_capabilities,
extensions = get_device_info_string(C.CL_DEVICE_EXTENSIONS),
global_mem_cache_size = get_device_info_ulong(C.CL_DEVICE_GLOBAL_MEM_CACHE_SIZE),
global_mem_cache_type = get_device_info_global_mem_cache_type,
global_mem_cacheline_size = get_device_info_uint(C.CL_DEVICE_GLOBAL_MEM_CACHELINE_SIZE),
global_mem_size = get_device_info_ulong(C.CL_DEVICE_GLOBAL_MEM_SIZE),
half_fp_config = get_device_info_fp_config(C.CL_DEVICE_HALF_FP_CONFIG),
host_unified_memory = get_device_info_bool(C.CL_DEVICE_HOST_UNIFIED_MEMORY),
image_support = get_device_info_bool(C.CL_DEVICE_IMAGE_SUPPORT),
image2d_max_height = get_device_info_size(C.CL_DEVICE_IMAGE2D_MAX_HEIGHT),
image2d_max_width = get_device_info_size(C.CL_DEVICE_IMAGE2D_MAX_WIDTH),
image3d_max_depth = get_device_info_size(C.CL_DEVICE_IMAGE3D_MAX_DEPTH),
image3d_max_height = get_device_info_size(C.CL_DEVICE_IMAGE3D_MAX_HEIGHT),
image3d_max_width = get_device_info_size(C.CL_DEVICE_IMAGE3D_MAX_WIDTH),
image_max_buffer_size = get_device_info_size(C.CL_DEVICE_IMAGE_MAX_BUFFER_SIZE),
image_max_array_size = get_device_info_size(C.CL_DEVICE_IMAGE_MAX_ARRAY_SIZE),
linker_available = get_device_info_bool(C.CL_DEVICE_LINKER_AVAILABLE),
local_mem_size = get_device_info_ulong(C.CL_DEVICE_LOCAL_MEM_SIZE),
local_mem_type = get_device_info_local_mem_type,
max_clock_frequency = get_device_info_uint(C.CL_DEVICE_MAX_CLOCK_FREQUENCY),
max_compute_units = get_device_info_uint(C.CL_DEVICE_MAX_COMPUTE_UNITS),
max_constant_args = get_device_info_uint(C.CL_DEVICE_MAX_CONSTANT_ARGS),
max_constant_buffer_size = get_device_info_ulong(C.CL_DEVICE_MAX_CONSTANT_BUFFER_SIZE),
max_mem_alloc_size = get_device_info_ulong(C.CL_DEVICE_MAX_MEM_ALLOC_SIZE),
max_parameter_size = get_device_info_size(C.CL_DEVICE_MAX_PARAMETER_SIZE),
max_read_image_args = get_device_info_uint(C.CL_DEVICE_MAX_READ_IMAGE_ARGS),
max_samplers = get_device_info_uint(C.CL_DEVICE_MAX_SAMPLERS),
max_work_group_size = get_device_info_size(C.CL_DEVICE_MAX_WORK_GROUP_SIZE),
max_work_item_dimensions = get_device_info_uint(C.CL_DEVICE_MAX_WORK_ITEM_DIMENSIONS),
max_work_item_sizes = get_device_info_sizes(C.CL_DEVICE_MAX_WORK_ITEM_SIZES),
max_write_image_args = get_device_info_uint(C.CL_DEVICE_MAX_WRITE_IMAGE_ARGS),
mem_base_addr_align = get_device_info_uint(C.CL_DEVICE_MEM_BASE_ADDR_ALIGN),
min_data_type_align_size = get_device_info_uint(C.CL_DEVICE_MIN_DATA_TYPE_ALIGN_SIZE),
name = get_device_info_string(C.CL_DEVICE_NAME),
native_vector_width_char = get_device_info_uint(C.CL_DEVICE_NATIVE_VECTOR_WIDTH_CHAR),
native_vector_width_short = get_device_info_uint(C.CL_DEVICE_NATIVE_VECTOR_WIDTH_SHORT),
native_vector_width_int = get_device_info_uint(C.CL_DEVICE_NATIVE_VECTOR_WIDTH_INT),
native_vector_width_long = get_device_info_uint(C.CL_DEVICE_NATIVE_VECTOR_WIDTH_LONG),
native_vector_width_float = get_device_info_uint(C.CL_DEVICE_NATIVE_VECTOR_WIDTH_FLOAT),
native_vector_width_double = get_device_info_uint(C.CL_DEVICE_NATIVE_VECTOR_WIDTH_DOUBLE),
native_vector_width_half = get_device_info_uint(C.CL_DEVICE_NATIVE_VECTOR_WIDTH_HALF),
opencl_c_version = get_device_info_string(C.CL_DEVICE_OPENCL_C_VERSION),
parent_device = get_device_info_parent_device,
partition_max_sub_devices = get_device_info_uint(C.CL_DEVICE_PARTITION_MAX_SUB_DEVICES),
partition_properties = get_device_info_partition_properties,
partition_affinity_domain = get_device_info_partition_affinity_domain,
partition_type = get_device_info_partition_type,
platform = get_device_info_platform,
preferred_vector_width_char = get_device_info_uint(C.CL_DEVICE_PREFERRED_VECTOR_WIDTH_CHAR),
preferred_vector_width_short = get_device_info_uint(C.CL_DEVICE_PREFERRED_VECTOR_WIDTH_SHORT),
preferred_vector_width_int = get_device_info_uint(C.CL_DEVICE_PREFERRED_VECTOR_WIDTH_INT),
preferred_vector_width_long = get_device_info_uint(C.CL_DEVICE_PREFERRED_VECTOR_WIDTH_LONG),
preferred_vector_width_float = get_device_info_uint(C.CL_DEVICE_PREFERRED_VECTOR_WIDTH_FLOAT),
preferred_vector_width_double = get_device_info_uint(C.CL_DEVICE_PREFERRED_VECTOR_WIDTH_DOUBLE),
preferred_vector_width_half = get_device_info_uint(C.CL_DEVICE_PREFERRED_VECTOR_WIDTH_HALF),
printf_buffer_size = get_device_info_size(C.CL_DEVICE_PRINTF_BUFFER_SIZE),
preferred_interop_user_sync = get_device_info_bool(C.CL_DEVICE_PREFERRED_INTEROP_USER_SYNC),
profile = get_device_info_string(C.CL_DEVICE_PROFILE),
profiling_timer_resolution = get_device_info_size(C.CL_DEVICE_PROFILING_TIMER_RESOLUTION),
queue_properties = get_device_info_queue_properties,
single_fp_config = get_device_info_fp_config(C.CL_DEVICE_SINGLE_FP_CONFIG),
type = get_device_info_type,
vendor = get_device_info_string(C.CL_DEVICE_VENDOR),
vendor_id = get_device_info_uint(C.CL_DEVICE_VENDOR_ID),
version = get_device_info_string(C.CL_DEVICE_VERSION),
driver_version = get_device_info_string(C.CL_DRIVER_VERSION),
}
function device.get_info(device, name)
return device_info[name](device)
end
end
local function release_device(device)
local status = C.clReleaseDevice(device)
if status ~= C.CL_SUCCESS then return error(errors[status]) end
end
local function retain_device(device)
local value = cl_device_id_1()
local status = C.clGetDeviceInfo(device, C.CL_DEVICE_PARENT_DEVICE, ffi.sizeof(cl_device_id), value, nil)
if status == C.CL_INVALID_VALUE or status == C.CL_INVALID_OPERATION then return device end
if status ~= C.CL_SUCCESS then return error(errors[status]) end
if value[0] == nil then return device end
local status = C.clRetainDevice(device)
if status ~= C.CL_SUCCESS then return error(errors[status]) end
return ffi.gc(device, release_device)
end
do
local partition_affinity_domain = {
numa = C.CL_DEVICE_AFFINITY_DOMAIN_NUMA,
l4_cache = C.CL_DEVICE_AFFINITY_DOMAIN_L4_CACHE,
l3_cache = C.CL_DEVICE_AFFINITY_DOMAIN_L3_CACHE,
l2_cache = C.CL_DEVICE_AFFINITY_DOMAIN_L2_CACHE,
l1_cache = C.CL_DEVICE_AFFINITY_DOMAIN_L1_CACHE,
next_partitionable = C.CL_DEVICE_AFFINITY_DOMAIN_NEXT_PARTITIONABLE,
}
local partition_property_value = {
equally = function(value)
return cl_device_partition_property_3(C.CL_DEVICE_PARTITION_EQUALLY, value)
end,
by_counts = function(value)
local num_properties = #value
local properties = cl_device_partition_property_n(num_properties + 3)
properties[0] = C.CL_DEVICE_PARTITION_BY_COUNTS
for i = 1, num_properties do properties[i] = value[i] end
properties[num_properties + 1] = C.CL_DEVICE_PARTITION_BY_COUNTS_LIST_END
return properties
end,
by_affinity_domain = function(value)
value = partition_affinity_domain[value]
return cl_device_partition_property_3(C.CL_DEVICE_PARTITION_BY_AFFINITY_DOMAIN, value)
end,
}
function device.create_sub_devices(in_device, name, value)
local properties = partition_property_value[name](value)
local num_devices = cl_uint_1()
local status = C.clCreateSubDevices(in_device, properties, 0, nil, num_devices)
if status ~= C.CL_SUCCESS then return error(errors[status]) end
local out_devices_ptr = cl_device_id_n(num_devices[0])
local status = C.clCreateSubDevices(in_device, properties, num_devices[0], out_devices_ptr, nil)
if status ~= C.CL_SUCCESS then return error(errors[status]) end
local out_devices = {}
for i = 1, num_devices[0] do out_devices[i] = ffi.gc(out_devices_ptr[i - 1], release_device) end
return out_devices
end
end
local function release_context(context)
local status = C.clReleaseContext(context)
if status ~= C.CL_SUCCESS then return error(errors[status]) end
end
local function retain_context(context)
local status = C.clRetainContext(context)
if status ~= C.CL_SUCCESS then return error(errors[status]) end
return ffi.gc(context, release_context)
end
function _M.create_context(devices)
local num_devices = #devices
local devices = cl_device_id_n(num_devices, devices)
local status = cl_int_1()
local context = C.clCreateContext(nil, num_devices, devices, nil, nil, status)
if status[0] ~= C.CL_SUCCESS then return error(errors[status[0]]) end
return ffi.gc(context, release_context)
end
do
local function get_context_object_info_uint(name)
return function(context)
local value = cl_uint_1()
local status = C.clGetContextInfo(context, name, ffi.sizeof(cl_uint), value, nil)
if status == C.CL_INVALID_VALUE or status == C.CL_INVALID_OPERATION then return end
if status ~= C.CL_SUCCESS then return error(errors[status]) end
return value[0]
end
end
local function get_context_info_devices(context)
local size = size_t_1()
local status = C.clGetContextInfo(context, C.CL_CONTEXT_DEVICES, 0, nil, size)
if status == C.CL_INVALID_VALUE or status == C.CL_INVALID_OPERATION then return end
if status ~= C.CL_SUCCESS then return error(errors[status]) end
local num_devices = tonumber(size[0]) / ffi.sizeof(cl_device_id)
local value = cl_device_id_n(num_devices)
local status = C.clGetContextInfo(context, C.CL_CONTEXT_DEVICES, num_devices * ffi.sizeof(cl_device_id), value, nil)
if status ~= C.CL_SUCCESS then return error(errors[status]) end
local devices = {}
for i = 1, num_devices do devices[i] = retain_device(value[i - 1]) end
return devices
end
local context_info = {
num_devices = get_context_object_info_uint(C.CL_CONTEXT_NUM_DEVICES),
devices = get_context_info_devices,
}
function context.get_info(context, name)
return context_info[name](context)
end
end
local function release_mem_object(mem)
local status = C.clReleaseMemObject(mem)
if status ~= C.CL_SUCCESS then return error(errors[status]) end
end
local function retain_mem_object(mem)
local status = C.clRetainMemObject(mem)
if status ~= C.CL_SUCCESS then return error(errors[status]) end
return ffi.gc(mem, release_mem_object)
end
do
local create_buffer_flags = {
read_write = C.CL_MEM_READ_WRITE,
write_only = C.CL_MEM_WRITE_ONLY,
read_only = C.CL_MEM_READ_ONLY,
use_host_ptr = C.CL_MEM_USE_HOST_PTR,
alloc_host_ptr = C.CL_MEM_ALLOC_HOST_PTR,
copy_host_ptr = C.CL_MEM_COPY_HOST_PTR,
host_write_only = C.CL_MEM_HOST_WRITE_ONLY,
host_read_only = C.CL_MEM_HOST_READ_ONLY,
host_no_access = C.CL_MEM_HOST_NO_ACCESS,
}
function context.create_buffer(context, flags, size, host_ptr)
if tonumber(flags) ~= nil then flags, size, host_ptr = nil, flags, size end
if flags ~= nil then flags = strtobit(flags, create_buffer_flags) else flags = 0 end
local status = cl_int_1()
local mem = C.clCreateBuffer(context, flags, size, host_ptr, status)
if status[0] ~= C.CL_SUCCESS then return error(errors[status[0]]) end
return ffi.gc(mem, release_mem_object)
end
local create_sub_buffer_flags = {
region = C.CL_BUFFER_CREATE_TYPE_REGION,
}
function mem.create_sub_buffer(buffer, flags, create_type, create_info)
if create_info == nil then flags, create_type, create_info = nil, flags, create_type end
if flags ~= nil then flags = strtobit(flags, create_buffer_flags) else flags = 0 end
create_type = create_sub_buffer_flags[create_type]
create_info = cl_buffer_region(create_info)
local status = cl_int_1()
local mem = C.clCreateSubBuffer(buffer, flags, create_type, create_info, status)
if status[0] ~= C.CL_SUCCESS then return error(errors[status[0]]) end
return ffi.gc(mem, release_mem_object)
end
end
do
local mem_type = {
[C.CL_MEM_OBJECT_BUFFER] = "buffer",
[C.CL_MEM_OBJECT_IMAGE1D] = "image1d",
[C.CL_MEM_OBJECT_IMAGE1D_BUFFER] = "image1d_buffer",
[C.CL_MEM_OBJECT_IMAGE1D_ARRAY] = "image1d_array",
[C.CL_MEM_OBJECT_IMAGE2D] = "image2d",
[C.CL_MEM_OBJECT_IMAGE2D_ARRAY] = "image2d_array",
[C.CL_MEM_OBJECT_IMAGE3D] = "image3d",
}
local function get_mem_object_info_type(mem)
local value = cl_mem_object_type_1()
local status = C.clGetMemObjectInfo(mem, C.CL_MEM_TYPE, ffi.sizeof(cl_mem_object_type), value, nil)
if status == C.CL_INVALID_VALUE or status == C.CL_INVALID_OPERATION then return end
if status ~= C.CL_SUCCESS then return error(errors[status]) end
return mem_type[value[0]]
end
local mem_flags = {
[C.CL_MEM_READ_WRITE] = "read_write",
[C.CL_MEM_WRITE_ONLY] = "write_only",
[C.CL_MEM_READ_ONLY] = "read_only",
[C.CL_MEM_USE_HOST_PTR] = "use_host_ptr",
[C.CL_MEM_ALLOC_HOST_PTR] = "alloc_host_ptr",
[C.CL_MEM_COPY_HOST_PTR] = "copy_host_ptr",
[C.CL_MEM_HOST_WRITE_ONLY] = "host_write_only",
[C.CL_MEM_HOST_READ_ONLY] = "host_read_only",
[C.CL_MEM_HOST_NO_ACCESS] = "host_no_access",
}
local function get_mem_object_info_flags(mem)
local value = cl_mem_flags_1()
local status = C.clGetMemObjectInfo(mem, C.CL_MEM_FLAGS, ffi.sizeof(cl_mem_flags), value, nil)
if status == C.CL_INVALID_VALUE or status == C.CL_INVALID_OPERATION then return end
if status ~= C.CL_SUCCESS then return error(errors[status]) end
return bittobool(tonumber(value[0]), mem_flags)
end
local function get_mem_object_info_size(mem)
local value = size_t_1()
local status = C.clGetMemObjectInfo(mem, C.CL_MEM_SIZE, ffi.sizeof(size_t), value, nil)
if status == C.CL_INVALID_VALUE or status == C.CL_INVALID_OPERATION then return end
if status ~= C.CL_SUCCESS then return error(errors[status]) end
return tonumber(value[0])
end
local function get_mem_object_info_host_ptr(mem)
local value = void_ptr_1()
local status = C.clGetMemObjectInfo(mem, C.CL_MEM_HOST_PTR, ffi.sizeof(void_ptr), value, nil)
if status == C.CL_INVALID_VALUE or status == C.CL_INVALID_OPERATION then return end
if status ~= C.CL_SUCCESS then return error(errors[status]) end
if value[0] == nil then return end
return value[0]
end
local function get_mem_object_info_uint(name)
return function(mem)
local value = cl_uint_1()
local status = C.clGetMemObjectInfo(mem, name, ffi.sizeof(cl_uint), value, nil)
if status == C.CL_INVALID_VALUE or status == C.CL_INVALID_OPERATION then return end
if status ~= C.CL_SUCCESS then return error(errors[status]) end
return value[0]
end
end
local function get_mem_object_info_context(mem)
local value = cl_context_1()
local status = C.clGetMemObjectInfo(mem, C.CL_MEM_CONTEXT, ffi.sizeof(cl_context), value, nil)
if status == C.CL_INVALID_VALUE or status == C.CL_INVALID_OPERATION then return end
if status ~= C.CL_SUCCESS then return error(errors[status]) end
return retain_context(value[0])
end
local function get_mem_object_info_associated_memobject(mem)
local value = cl_mem_1()
local status = C.clGetMemObjectInfo(mem, C.CL_MEM_ASSOCIATED_MEMOBJECT, ffi.sizeof(cl_mem), value, nil)
if status == C.CL_INVALID_VALUE or status == C.CL_INVALID_OPERATION then return end
if status ~= C.CL_SUCCESS then return error(errors[status]) end
if value[0] == nil then return end
return retain_mem_object(value[0])
end
local function get_mem_object_info_offset(mem)
local value = cl_mem_1()
local status = C.clGetMemObjectInfo(mem, C.CL_MEM_ASSOCIATED_MEMOBJECT, ffi.sizeof(cl_mem), value, nil)
if status == C.CL_INVALID_VALUE or status == C.CL_INVALID_OPERATION then return end
if status ~= C.CL_SUCCESS then return error(errors[status]) end
if value[0] == nil then return end
local value = size_t_1()
local status = C.clGetMemObjectInfo(mem, C.CL_MEM_OFFSET, ffi.sizeof(size_t), value, nil)
if status ~= C.CL_SUCCESS then return error(errors[status]) end
return tonumber(value[0])
end
local mem_info = {
type = get_mem_object_info_type,
flags = get_mem_object_info_flags,
size = get_mem_object_info_size,
host_ptr = get_mem_object_info_host_ptr,
map_count = get_mem_object_info_uint(C.CL_MEM_MAP_COUNT),
context = get_mem_object_info_context,
associated_memobject = get_mem_object_info_associated_memobject,
offset = get_mem_object_info_offset,
}
function mem.get_info(mem, name)
return mem_info[name](mem)
end
end
local function release_program(program)
local status = C.clReleaseProgram(program)
if status ~= C.CL_SUCCESS then return error(errors[status]) end
end
local function retain_program(program)
local status = C.clRetainProgram(program)
if status ~= C.CL_SUCCESS then return error(errors[status]) end
return ffi.gc(program, release_program)
end
function context.create_program_with_source(context, source)
local sizes = ffi.new(size_t_1, #source)
local strings = const_char_ptr_1(ffi.cast(const_char_ptr, source))
local status = cl_int_1()
local program = C.clCreateProgramWithSource(context, 1, strings, sizes, status)
if status[0] ~= C.CL_SUCCESS then return error(errors[status[0]]) end
return ffi.gc(program, release_program)
end
function program.build(program, devices, options)
if type(devices) == "string" then devices, options = nil, devices end
local num_devices = devices ~= nil and #devices or 0
if devices ~= nil then devices = cl_device_id_n(num_devices, devices) end
local status = C.clBuildProgram(program, num_devices, devices, options, nil, nil)
if status ~= C.CL_SUCCESS then return error(errors[status]) end
end
do
local function get_program_info_uint(name)
return function(program)
local value = cl_uint_1()
local status = C.clGetProgramInfo(program, name, ffi.sizeof(cl_uint), value, nil)
if status == C.CL_INVALID_VALUE or status == C.CL_INVALID_OPERATION then return end
if status ~= C.CL_SUCCESS then return error(errors[status]) end
return value[0]
end
end
local function get_program_info_context(program)
local value = cl_context_1()
local status = C.clGetProgramInfo(program, C.CL_PROGRAM_CONTEXT, ffi.sizeof(cl_context), value, nil)
if status == C.CL_INVALID_VALUE or status == C.CL_INVALID_OPERATION then return end
if status ~= C.CL_SUCCESS then return error(errors[status]) end
return retain_context(value[0])
end
local function get_program_info_devices(program)
local size = size_t_1()
local status = C.clGetProgramInfo(program, C.CL_PROGRAM_DEVICES, 0, nil, size)
if status == C.CL_INVALID_VALUE or status == C.CL_INVALID_OPERATION then return end
if status ~= C.CL_SUCCESS then return error(errors[status]) end
local num_devices = tonumber(size[0]) / ffi.sizeof(cl_device_id)
local value = cl_device_id_n(num_devices)
local status = C.clGetProgramInfo(program, C.CL_PROGRAM_DEVICES, size[0], value, nil)
if status ~= C.CL_SUCCESS then return error(errors[status]) end
local devices = {}
for i = 1, num_devices do devices[i] = retain_device(value[i - 1]) end
return devices
end
local function get_program_info_string(name)
return function(program)
local size = size_t_1()
local status = C.clGetProgramInfo(program, name, 0, nil, size)
if status == C.CL_INVALID_VALUE or status == C.CL_INVALID_OPERATION then return end
if status ~= C.CL_SUCCESS then return error(errors[status]) end
if size[0] == 0 then return end
local value = char_n(size[0])
local status = C.clGetProgramInfo(program, name, size[0], value, nil)
if status ~= C.CL_SUCCESS then return error(errors[status]) end
return ffi.string(value, size[0] - 1)
end
end
local function get_program_info_binary_sizes(program)
local size = size_t_1()
local status = C.clGetProgramInfo(program, C.CL_PROGRAM_BINARY_SIZES, 0, nil, size)
if status == C.CL_INVALID_VALUE or status == C.CL_INVALID_OPERATION then return end
if status ~= C.CL_SUCCESS then return error(errors[status]) end
local num_binaries = tonumber(size[0]) / ffi.sizeof(size_t)
local value = size_t_n(num_binaries)
local status = C.clGetProgramInfo(program, C.CL_PROGRAM_BINARY_SIZES, size[0], value, nil)
if status ~= C.CL_SUCCESS then return error(errors[status]) end
local sizes = {}
for i = 0, num_binaries - 1 do sizes[i + 1] = tonumber(value[i]) end
return sizes
end
local function get_program_info_binaries(program)
local size = size_t_1()
local status = C.clGetProgramInfo(program, C.CL_PROGRAM_BINARY_SIZES, 0, nil, size)
if status == C.CL_INVALID_VALUE or status == C.CL_INVALID_OPERATION then return end
if status ~= C.CL_SUCCESS then return error(errors[status]) end
local num_binaries = tonumber(size[0]) / ffi.sizeof(size_t)
local binary_sizes = size_t_n(num_binaries)
local status = C.clGetProgramInfo(program, C.CL_PROGRAM_BINARY_SIZES, num_binaries * ffi.sizeof(size_t), binary_sizes, nil)
if status ~= C.CL_SUCCESS then return error(errors[status]) end
local size = 0
for i = 0, num_binaries - 1 do size = size + binary_sizes[i] end
local binary = unsigned_char_n(size)
local binaries_buf = unsigned_char_ptr_n(num_binaries)
local offset = binary
for i = 0, num_binaries - 1 do binaries_buf[i], offset = offset, offset + binary_sizes[i] end
local status = C.clGetProgramInfo(program, C.CL_PROGRAM_BINARIES, num_binaries * ffi.sizeof(unsigned_char_ptr), binaries_buf, nil)
if status ~= C.CL_SUCCESS then return error(errors[status]) end
local binaries = {}
for i = 0, num_binaries - 1 do
if binary_sizes[i] > 0 then binaries[i + 1] = ffi.string(binaries_buf[i], binary_sizes[i]) end
end
return binaries
end
local function get_program_info_num_kernels(program)
local value = size_t_1()
local status = C.clGetProgramInfo(program, C.CL_PROGRAM_NUM_KERNELS, ffi.sizeof(size_t), value, nil)
if status == C.CL_INVALID_VALUE or status == C.CL_INVALID_OPERATION then return end
if status ~= C.CL_SUCCESS then return error(errors[status]) end
return tonumber(value[0])
end
local program_info = {
context = get_program_info_context,
num_devices = get_program_info_uint(C.CL_PROGRAM_NUM_DEVICES),
devices = get_program_info_devices,
source = get_program_info_string(C.CL_PROGRAM_SOURCE),
binary_sizes = get_program_info_binary_sizes,
binaries = get_program_info_binaries,
num_kernels = get_program_info_num_kernels,
kernel_names = get_program_info_string(C.CL_PROGRAM_KERNEL_NAMES),
}
function program.get_info(program, name)
return program_info[name](program)
end
end
do
local function get_program_build_info_string(name)
return function(program, device)
local size = size_t_1()
local status = C.clGetProgramBuildInfo(program, device, name, 0, nil, size)
if status == C.CL_INVALID_VALUE or status == C.CL_INVALID_OPERATION then return end
if status ~= C.CL_SUCCESS then return error(errors[status]) end
if size[0] == 0 then return end
local value = char_n(size[0])
local status = C.clGetProgramBuildInfo(program, device, name, size[0], value, nil)
if status ~= C.CL_SUCCESS then return error(errors[status]) end
return ffi.string(value, size[0] - 1)
end
end
local build_status = {
[C.CL_BUILD_ERROR] = "error",
[C.CL_BUILD_SUCCESS] = "success",
[C.CL_BUILD_IN_PROGRESS] = "in_progress",
}
local function get_program_build_info_status(program, device)
local value = cl_build_status_1()
local status = C.clGetProgramBuildInfo(program, device, C.CL_PROGRAM_BUILD_STATUS, ffi.sizeof(cl_build_status), value, nil)
if status == C.CL_INVALID_VALUE or status == C.CL_INVALID_OPERATION then return end
if status ~= C.CL_SUCCESS then return error(errors[status]) end
if value[0] == C.CL_BUILD_NONE then return nil end
return build_status[value[0]]
end
local binary_type = {
[C.CL_PROGRAM_BINARY_TYPE_COMPILED_OBJECT] = "compiled_object",
[C.CL_PROGRAM_BINARY_TYPE_LIBRARY] = "library",
[C.CL_PROGRAM_BINARY_TYPE_EXECUTABLE] = "executable",
}
local function get_program_build_info_binary_type(program, device)
local value = cl_program_binary_type_1()
local status = C.clGetProgramBuildInfo(program, device, C.CL_PROGRAM_BINARY_TYPE, ffi.sizeof(cl_program_binary_type), value, nil)
if status == C.CL_INVALID_VALUE or status == C.CL_INVALID_OPERATION then return end
if status ~= C.CL_SUCCESS then return error(errors[status]) end
if value[0] == C.CL_PROGRAM_BINARY_TYPE_NONE then return nil end
return binary_type[value[0]]
end
local program_build_info = {
status = get_program_build_info_status,
log = get_program_build_info_string(C.CL_PROGRAM_BUILD_LOG),
options = get_program_build_info_string(C.CL_PROGRAM_BUILD_OPTIONS),
binary_type = get_program_build_info_binary_type,
}
function program.get_build_info(program, device, name)
return program_build_info[name](program, device)
end
end
local function release_kernel(kernel)
local status = C.clReleaseKernel(kernel)
if status ~= C.CL_SUCCESS then return error(errors[status]) end
end
function program.create_kernel(program, name)
local status = cl_int_1()
local kernel = C.clCreateKernel(program, name, status)
if status[0] ~= C.CL_SUCCESS then return error(errors[status[0]]) end
return ffi.gc(kernel, release_kernel)
end
function program.create_kernels_in_program(program)
local num_kernels = cl_int_1()
local status = C.clCreateKernelsInProgram(program, 0, nil, num_kernels)
if status ~= C.CL_SUCCESS then return error(errors[status]) end
local kernels_buf = cl_kernel_n(num_kernels[0])
local status = C.clCreateKernelsInProgram(program, num_kernels[0], kernels_buf, nil)
if status ~= C.CL_SUCCESS then return error(errors[status]) end
local kernels = {}
for i = 1, num_kernels[0] do kernels[i] = ffi.gc(kernels_buf[i - 1], release_kernel) end
return kernels
end
function kernel.set_arg(kernel, index, size, value)
if ffi.istype(cl_mem, size) then size, value = ffi.sizeof(cl_mem), cl_mem_1(size) end
if ffi.istype(cl_sampler, size) then size, value = ffi.sizeof(cl_sampler), cl_sampler_1(size) end
if type(size) == "cdata" then size, value = ffi.sizeof(size), size end
if size == nil then size = ffi.sizeof(cl_mem) end
local status = C.clSetKernelArg(kernel, index, size, value)
if status ~= C.CL_SUCCESS then return error(errors[status]) end
end
do
local function get_kernel_arg_info_string(name)
return function(kernel, index)
local size = size_t_1()
local status = C.clGetKernelArgInfo(kernel, index, name, 0, nil, size)
if status == C.CL_INVALID_VALUE or status == C.CL_INVALID_OPERATION then return end
if status ~= C.CL_SUCCESS then return error(errors[status]) end
if size[0] == 0 then return end
local value = char_n(size[0])
local status = C.clGetKernelArgInfo(kernel, index, name, size[0], value, nil)
if status ~= C.CL_SUCCESS then return error(errors[status]) end
return ffi.string(value, size[0] - 1)
end
end
local address_qualifier = {
[C.CL_KERNEL_ARG_ADDRESS_GLOBAL] = "global",
[C.CL_KERNEL_ARG_ADDRESS_LOCAL] = "local",
[C.CL_KERNEL_ARG_ADDRESS_CONSTANT] = "constant",
[C.CL_KERNEL_ARG_ADDRESS_PRIVATE] = "private",
}
local function get_kernel_arg_info_address_qualifier(kernel, index)
local value = cl_kernel_arg_address_qualifier_1()
local status = C.clGetKernelArgInfo(kernel, index, C.CL_KERNEL_ARG_ADDRESS_QUALIFIER, ffi.sizeof(cl_kernel_arg_address_qualifier), value, nil)
if status == C.CL_INVALID_VALUE or status == C.CL_INVALID_OPERATION then return end
if status ~= C.CL_SUCCESS then return error(errors[status]) end
return address_qualifier[value[0]]
end
local access_qualifier = {
[C.CL_KERNEL_ARG_ACCESS_READ_ONLY] = "read_only",
[C.CL_KERNEL_ARG_ACCESS_WRITE_ONLY] = "write_only",
[C.CL_KERNEL_ARG_ACCESS_READ_WRITE] = "read_write",
}
local function get_kernel_arg_info_access_qualifier(kernel, index)
local value = cl_kernel_arg_access_qualifier_1()
local status = C.clGetKernelArgInfo(kernel, index, C.CL_KERNEL_ARG_ACCESS_QUALIFIER, ffi.sizeof(cl_kernel_arg_access_qualifier), value, nil)
if status == C.CL_INVALID_VALUE or status == C.CL_INVALID_OPERATION then return end
if status ~= C.CL_SUCCESS then return error(errors[status]) end
return access_qualifier[value[0]]
end
local type_qualifier = {
[C.CL_KERNEL_ARG_TYPE_CONST] = "const",
[C.CL_KERNEL_ARG_TYPE_RESTRICT] = "restrict",
[C.CL_KERNEL_ARG_TYPE_VOLATILE] = "volatile",
}
local function get_kernel_arg_info_arg_type_qualifier(kernel, index)
local value = cl_kernel_arg_type_qualifier_1()
local status = C.clGetKernelArgInfo(kernel, index, C.CL_KERNEL_ARG_TYPE_QUALIFIER, ffi.sizeof(cl_kernel_arg_type_qualifier), value, nil)
if status == C.CL_INVALID_VALUE or status == C.CL_INVALID_OPERATION then return end
if status ~= C.CL_SUCCESS then return error(errors[status]) end
return bittobool(tonumber(value[0]), type_qualifier)
end
local kernel_arg_info = {
address_qualifier = get_kernel_arg_info_address_qualifier,
access_qualifier = get_kernel_arg_info_access_qualifier,
type_name = get_kernel_arg_info_string(C.CL_KERNEL_ARG_TYPE_NAME),
type_qualifier = get_kernel_arg_info_arg_type_qualifier,
name = get_kernel_arg_info_string(C.CL_KERNEL_ARG_NAME),
}
function kernel.get_arg_info(kernel, index, name)
return kernel_arg_info[name](kernel, index)
end
end
do
local function get_kernel_work_group_info_size(name)
return function(kernel, device)
local value = size_t_1()
local status = C.clGetKernelWorkGroupInfo(kernel, device, name, ffi.sizeof(size_t), value, nil)
if status == C.CL_INVALID_VALUE or status == C.CL_INVALID_OPERATION then return end
if status ~= C.CL_SUCCESS then return error(errors[status]) end
return tonumber(value[0])
end
end
local function get_kernel_work_group_info_sizes(name)
return function(kernel, device)
local size = size_t_1()
local status = C.clGetKernelWorkGroupInfo(kernel, device, name, 0, nil, size)
if status == C.CL_INVALID_VALUE or status == C.CL_INVALID_OPERATION then return end
if status ~= C.CL_SUCCESS then return error(errors[status]) end
local num_sizes = tonumber(size[0]) / ffi.sizeof(size_t)
local value = size_t_n(num_sizes)
local status = C.clGetKernelWorkGroupInfo(kernel, device, name, size[0], value, nil)
if status ~= C.CL_SUCCESS then return error(errors[status]) end
local sizes = {}
for i = 0, num_sizes - 1 do sizes[i + 1] = tonumber(value[i]) end
return sizes
end
end
local function get_kernel_work_group_info_ulong(name)
return function(kernel, device)
local value = cl_ulong_1()
local status = C.clGetKernelWorkGroupInfo(kernel, device, name, ffi.sizeof(cl_ulong), value, nil)
if status == C.CL_INVALID_VALUE or status == C.CL_INVALID_OPERATION then return end
if status ~= C.CL_SUCCESS then return error(errors[status]) end
return tonumber(value[0])
end
end
local kernel_work_group_info = {
global_work_size = get_kernel_work_group_info_sizes(C.CL_KERNEL_GLOBAL_WORK_SIZE),
work_group_size = get_kernel_work_group_info_size(C.CL_KERNEL_WORK_GROUP_SIZE),
compile_work_group_size = get_kernel_work_group_info_sizes(C.CL_KERNEL_COMPILE_WORK_GROUP_SIZE),
local_mem_size = get_kernel_work_group_info_ulong(C.CL_KERNEL_LOCAL_MEM_SIZE),
preferred_work_group_size_multiple = get_kernel_work_group_info_size(C.CL_KERNEL_PREFERRED_WORK_GROUP_SIZE_MULTIPLE),
private_mem_size = get_kernel_work_group_info_ulong(C.CL_KERNEL_PRIVATE_MEM_SIZE),
}
function kernel.get_work_group_info(kernel, device, name)
if name == nil then device, name = nil, device end
return kernel_work_group_info[name](kernel, device)
end
end
do
local function get_kernel_info_string(name)
return function(kernel)
local size = size_t_1()
local status = C.clGetKernelInfo(kernel, name, 0, nil, size)
if status == C.CL_INVALID_VALUE or status == C.CL_INVALID_OPERATION then return end
if status ~= C.CL_SUCCESS then return error(errors[status]) end
if size[0] == 0 then return end
local value = char_n(size[0])
local status = C.clGetKernelInfo(kernel, name, size[0], value, nil)
if status ~= C.CL_SUCCESS then return error(errors[status]) end
return ffi.string(value, size[0] - 1)
end
end
local function get_kernel_info_uint(name)
return function(kernel)
local value = cl_uint_1()
local status = C.clGetKernelInfo(kernel, name, ffi.sizeof(cl_uint), value, nil)
if status == C.CL_INVALID_VALUE or status == C.CL_INVALID_OPERATION then return end
if status ~= C.CL_SUCCESS then return error(errors[status]) end
return value[0]
end
end
local function get_kernel_info_context(kernel)
local value = cl_context_1()
local status = C.clGetKernelInfo(kernel, C.CL_KERNEL_CONTEXT, ffi.sizeof(cl_context), value, nil)
if status == C.CL_INVALID_VALUE or status == C.CL_INVALID_OPERATION then return end
if status ~= C.CL_SUCCESS then return error(errors[status]) end
return retain_context(value[0])
end
local function get_kernel_info_program(kernel)
local value = cl_program_1()
local status = C.clGetKernelInfo(kernel, C.CL_KERNEL_PROGRAM, ffi.sizeof(cl_program), value, nil)
if status == C.CL_INVALID_VALUE or status == C.CL_INVALID_OPERATION then return end
if status ~= C.CL_SUCCESS then return error(errors[status]) end
return retain_program(value[0])
end
local kernel_info = {
function_name = get_kernel_info_string(C.CL_KERNEL_FUNCTION_NAME),
num_args = get_kernel_info_uint(C.CL_KERNEL_NUM_ARGS),
context = get_kernel_info_context,
program = get_kernel_info_program,
attributes = get_kernel_info_string(C.CL_KERNEL_ATTRIBUTES),
}
function kernel.get_info(kernel, name)
return kernel_info[name](kernel)
end
end
local function release_command_queue(queue)
local status = C.clReleaseCommandQueue(queue)
if status ~= C.CL_SUCCESS then return error(errors[status]) end
end
local function retain_command_queue(queue)
local status = C.clRetainCommandQueue(queue)
if status ~= C.CL_SUCCESS then return error(errors[status]) end
return ffi.gc(queue, release_command_queue)
end
do
local command_queue_properties = {
out_of_order_exec_mode = C.CL_QUEUE_OUT_OF_ORDER_EXEC_MODE_ENABLE,
profiling = C.CL_QUEUE_PROFILING_ENABLE,
}
function context.create_command_queue(context, device, properties)
if properties ~= nil then properties = strtobit(properties, command_queue_properties) else properties = 0 end
local status = cl_int_1()
local queue = C.clCreateCommandQueue(context, device, properties, status)
if status[0] ~= C.CL_SUCCESS then return error(errors[status[0]]) end
return ffi.gc(queue, release_command_queue)
end
end
do
local function get_command_queue_info_context(queue)
local value = cl_context_1()
local status = C.clGetCommandQueueInfo(queue, C.CL_QUEUE_CONTEXT, ffi.sizeof(cl_context), value, nil)
if status == C.CL_INVALID_VALUE or status == C.CL_INVALID_OPERATION then return end
if status ~= C.CL_SUCCESS then return error(errors[status]) end
return retain_context(value[0])
end
local function get_command_queue_info_device(queue)
local value = cl_device_id_1()
local status = C.clGetCommandQueueInfo(queue, C.CL_QUEUE_DEVICE, ffi.sizeof(cl_device_id), value, nil)
if status == C.CL_INVALID_VALUE or status == C.CL_INVALID_OPERATION then return end
if status ~= C.CL_SUCCESS then return error(errors[status]) end
return retain_device(value[0])
end
local command_queue_properties = {
[C.CL_QUEUE_OUT_OF_ORDER_EXEC_MODE_ENABLE] = "out_of_order_exec_mode",
[C.CL_QUEUE_PROFILING_ENABLE] = "profiling",
}
local function get_command_queue_info_properties(queue)
local value = cl_command_queue_properties_1()
local status = C.clGetCommandQueueInfo(queue, C.CL_QUEUE_PROPERTIES, ffi.sizeof(cl_command_queue_properties), value, nil)
if status == C.CL_INVALID_VALUE or status == C.CL_INVALID_OPERATION then return end
if status ~= C.CL_SUCCESS then return error(errors[status]) end
return bittobool(tonumber(value[0]), command_queue_properties)
end
local queue_info = {
context = get_command_queue_info_context,
device = get_command_queue_info_device,
properties = get_command_queue_info_properties,
}
function queue.get_info(queue, name)
return queue_info[name](queue)
end
end
local function release_event(event)
local status = C.clReleaseEvent(event)
if status ~= C.CL_SUCCESS then return error(errors[status]) end
end
function queue.enqueue_ndrange_kernel(queue, kernel, global_offset, global_size, local_size, events)
local work_dim = #global_size
global_size = size_t_n(work_dim, global_size)
if global_offset ~= nil then global_offset = size_t_n(work_dim, global_offset) end
if local_size ~= nil then local_size = size_t_n(work_dim, local_size) end
local num_events = events ~= nil and #events or 0
if events ~= nil then events = cl_event_n(num_events, events) end
local event = cl_event_1()
local status = C.clEnqueueNDRangeKernel(queue, kernel, work_dim, global_offset, global_size, local_size, num_events, events, event)
if status ~= C.CL_SUCCESS then return error(errors[status]) end
return ffi.gc(event[0], release_event)
end
do
local map_buffer_flags = {
read = C.CL_MAP_READ,
write = C.CL_MAP_WRITE,
write_invalidate_region = C.CL_MAP_WRITE_INVALIDATE_REGION,
}
function queue.enqueue_map_buffer(queue, buffer, blocking, flags, offset, size, events)
if offset == nil and size == nil then offset, size = 0, buffer:get_info("size") end
flags = strtobit(flags, map_buffer_flags)
local num_events = events ~= nil and #events or 0
if events ~= nil then events = cl_event_n(num_events, events) end
local event = cl_event_1()
local status = cl_int_1()
local ptr = C.clEnqueueMapBuffer(queue, buffer, blocking, flags, offset, size, num_events, events, event, status)
if status[0] ~= C.CL_SUCCESS then return error(errors[status[0]]) end
return ptr, ffi.gc(event[0], release_event)
end
end
function queue.enqueue_unmap_mem_object(queue, mem, ptr, events)
local num_events = events ~= nil and #events or 0
if events ~= nil then events = cl_event_n(num_events, events) end
local event = cl_event_1()
local status = C.clEnqueueUnmapMemObject(queue, mem, ptr, num_events, events, event)
if status ~= C.CL_SUCCESS then return error(errors[status]) end
return ffi.gc(event[0], release_event)
end
function queue.enqueue_read_buffer(queue, buffer, blocking, offset, size, ptr, events)
if ptr == nil then offset, size, ptr, events = nil, nil, offset, size end
if offset == nil and size == nil then offset, size = 0, buffer:get_info("size") end
local num_events = events ~= nil and #events or 0
if events ~= nil then events = cl_event_n(num_events, events) end
local event = cl_event_1()
local status = C.clEnqueueReadBuffer(queue, buffer, blocking, offset, size, ptr, num_events, events, event)
if status ~= C.CL_SUCCESS then return error(errors[status]) end
return ffi.gc(event[0], release_event)
end
function queue.enqueue_write_buffer(queue, buffer, blocking, offset, size, ptr, events)
if ptr == nil then offset, size, ptr, events = nil, nil, offset, size end
if offset == nil and size == nil then offset, size = 0, buffer:get_info("size") end
local num_events = events ~= nil and #events or 0
if events ~= nil then events = cl_event_n(num_events, events) end
local event = cl_event_1()
local status = C.clEnqueueWriteBuffer(queue, buffer, blocking, offset, size, ptr, num_events, events, event)
if status ~= C.CL_SUCCESS then return error(errors[status]) end
return ffi.gc(event[0], release_event)
end
function queue.enqueue_copy_buffer(queue, src_buffer, dst_buffer, src_offset, dst_offset, size, events)
if src_offset == nil and dst_offset == nil and size == nil then src_offset, dst_offset, size = 0, 0, src_buffer:get_info("size") end
local num_events = events ~= nil and #events or 0
if events ~= nil then events = cl_event_n(num_events, events) end
local event = cl_event_1()
local status = C.clEnqueueCopyBuffer(queue, src_buffer, dst_buffer, src_offset, dst_offset, size, num_events, events, event)
if status ~= C.CL_SUCCESS then return error(errors[status]) end
return ffi.gc(event[0], release_event)
end
function queue.enqueue_fill_buffer(queue, buffer, pattern, pattern_size, offset, size, events)
if offset == nil and size == nil then offset, size = 0, buffer:get_info("size") end
local num_events = events ~= nil and #events or 0
if events ~= nil then events = cl_event_n(num_events, events) end
local event = cl_event_1()
local status = C.clEnqueueFillBuffer(queue, buffer, pattern, pattern_size, offset, size, num_events, events, event)
if status ~= C.CL_SUCCESS then return error(errors[status]) end
return ffi.gc(event[0], release_event)
end
function queue.enqueue_marker_with_wait_list(queue, events)
local num_events = events ~= nil and #events or 0
if events ~= nil then events = cl_event_n(num_events, events) end
local event = cl_event_1()
local status = C.clEnqueueMarkerWithWaitList(queue, num_events, events, event)
if status ~= C.CL_SUCCESS then return error(errors[status]) end
return ffi.gc(event[0], release_event)
end
function queue.enqueue_marker(queue)
local event = cl_event_1()
local status = C.clEnqueueMarker(queue, event)
if status ~= C.CL_SUCCESS then return error(errors[status]) end
return ffi.gc(event[0], release_event)
end
function queue.enqueue_barrier_with_wait_list(queue, events)
local num_events = events ~= nil and #events or 0
if events ~= nil then events = cl_event_n(num_events, events) end
local event = cl_event_1()
local status = C.clEnqueueBarrierWithWaitList(queue, num_events, events, event)
if status ~= C.CL_SUCCESS then return error(errors[status]) end
return ffi.gc(event[0], release_event)
end
function queue.enqueue_barrier(queue)
local status = C.clEnqueueBarrier(queue)
if status ~= C.CL_SUCCESS then return error(errors[status]) end
end
function queue.enqueue_wait_for_events(queue, events)
local num_events = #events
events = cl_event_n(num_events, events)
local status = C.clEnqueueWaitForEvents(queue, num_events, events)
if status ~= C.CL_SUCCESS then return error(errors[status]) end
end
function queue.flush(queue)
local status = C.clFlush(queue)
if status ~= C.CL_SUCCESS then return error(errors[status]) end
end
function queue.finish(queue)
local status = C.clFinish(queue)
if status ~= C.CL_SUCCESS then return error(errors[status]) end
end
function _M.wait_for_events(events)
local num_events = #events
events = cl_event_n(num_events, events)
local status = C.clWaitForEvents(num_events, events)
if status ~= C.CL_SUCCESS then return error(errors[status]) end
end
do
local function get_event_info_command_queue(event)
local value = cl_command_queue_1()
local status = C.clGetEventInfo(event, C.CL_EVENT_COMMAND_QUEUE, ffi.sizeof(cl_command_queue), value, nil)
if status == C.CL_INVALID_VALUE or status == C.CL_INVALID_OPERATION then return end
if status ~= C.CL_SUCCESS then return error(errors[status]) end
return retain_command_queue(value[0])
end
local function get_event_info_context(event)
local value = cl_context_1()
local status = C.clGetEventInfo(event, C.CL_EVENT_CONTEXT, ffi.sizeof(cl_context), value, nil)
if status == C.CL_INVALID_VALUE or status == C.CL_INVALID_OPERATION then return end
if status ~= C.CL_SUCCESS then return error(errors[status]) end
return retain_context(value[0])
end
local command_type = {
[C.CL_COMMAND_NDRANGE_KERNEL] = "ndrange_kernel",
[C.CL_COMMAND_TASK] = "task",
[C.CL_COMMAND_NATIVE_KERNEL] = "native_kernel",
[C.CL_COMMAND_READ_BUFFER] = "read_buffer",
[C.CL_COMMAND_WRITE_BUFFER] = "write_buffer",
[C.CL_COMMAND_COPY_BUFFER] = "copy_buffer",
[C.CL_COMMAND_READ_IMAGE] = "read_image",
[C.CL_COMMAND_WRITE_IMAGE] = "write_image",
[C.CL_COMMAND_COPY_IMAGE] = "copy_image",
[C.CL_COMMAND_COPY_BUFFER_TO_IMAGE] = "copy_buffer_to_image",
[C.CL_COMMAND_COPY_IMAGE_TO_BUFFER] = "copy_image_to_buffer",
[C.CL_COMMAND_MAP_BUFFER] = "map_buffer",
[C.CL_COMMAND_MAP_IMAGE] = "map_image",
[C.CL_COMMAND_UNMAP_MEM_OBJECT] = "unmap_mem_object",
[C.CL_COMMAND_MARKER] = "marker",
[C.CL_COMMAND_ACQUIRE_GL_OBJECTS] = "acquire_gl_objects",
[C.CL_COMMAND_RELEASE_GL_OBJECTS] = "release_gl_objects",
[C.CL_COMMAND_READ_BUFFER_RECT] = "read_buffer_rect",
[C.CL_COMMAND_WRITE_BUFFER_RECT] = "write_buffer_rect",
[C.CL_COMMAND_COPY_BUFFER_RECT] = "copy_buffer_rect",
[C.CL_COMMAND_USER] = "user",
}
local function get_event_info_command_type(event)
local value = cl_command_type_1()
local status = C.clGetEventInfo(event, C.CL_EVENT_COMMAND_TYPE, ffi.sizeof(cl_command_type), value, nil)
if status == C.CL_INVALID_VALUE or status == C.CL_INVALID_OPERATION then return end
if status ~= C.CL_SUCCESS then return error(errors[status]) end
return command_type[value[0]]
end
local command_execution_status = {
[C.CL_QUEUED] = "queued",
[C.CL_SUBMITTED] = "submitted",
[C.CL_RUNNING] = "running",
[C.CL_COMPLETE] = "complete",
}
local function get_event_info_command_execution_status(event)
local value = cl_int_1()
local status = C.clGetEventInfo(event, C.CL_EVENT_COMMAND_EXECUTION_STATUS, ffi.sizeof(cl_int), value, nil)
if status == C.CL_INVALID_VALUE or status == C.CL_INVALID_OPERATION then return end
if status ~= C.CL_SUCCESS then return error(errors[status]) end
return command_execution_status[value[0]]
end
local event_info = {
command_queue = get_event_info_command_queue,
context = get_event_info_context,
command_type = get_event_info_command_type,
command_execution_status = get_event_info_command_execution_status,
}
function event.get_info(event, name)
return event_info[name](event)
end
end
do
local function get_event_profiling_info(name)
return function(event)
local value = cl_ulong_1()
local status = C.clGetEventProfilingInfo(event, name, ffi.sizeof(cl_ulong), value, nil)
if status == C.CL_INVALID_VALUE or status == C.CL_INVALID_OPERATION then return end
if status ~= C.CL_SUCCESS then return error(errors[status]) end
return value[0]
end
end
local event_profiling_info = {
queued = get_event_profiling_info(C.CL_PROFILING_COMMAND_QUEUED),
submit = get_event_profiling_info(C.CL_PROFILING_COMMAND_SUBMIT),
start = get_event_profiling_info(C.CL_PROFILING_COMMAND_START),
["end"] = get_event_profiling_info(C.CL_PROFILING_COMMAND_END),
}
function event.get_profiling_info(event, name)
return event_profiling_info[name](event)
end
end
ffi.metatype("struct _cl_platform_id", {__index = platform})
ffi.metatype("struct _cl_device_id", {__index = device })
ffi.metatype("struct _cl_context", {__index = context })
ffi.metatype("struct _cl_mem", {__index = mem })
ffi.metatype("struct _cl_command_queue", {__index = queue })
ffi.metatype("struct _cl_program", {__index = program })
ffi.metatype("struct _cl_kernel", {__index = kernel })
ffi.metatype("struct _cl_event", {__index = event })
return _M
| 47.434152
| 146
| 0.706661
|
b26104365f1e5ddb43fb380af7d319ffc4c79676
| 1,553
|
kt
|
Kotlin
|
nodecore-miners-pop/src/main/java/nodecore/miners/pop/BootstrapModule.kt
|
dimitryB/nodecore
|
5df4ac5f48a598dde94d57d5810882a548d4d23d
|
[
"MIT"
] | null | null | null |
nodecore-miners-pop/src/main/java/nodecore/miners/pop/BootstrapModule.kt
|
dimitryB/nodecore
|
5df4ac5f48a598dde94d57d5810882a548d4d23d
|
[
"MIT"
] | null | null | null |
nodecore-miners-pop/src/main/java/nodecore/miners/pop/BootstrapModule.kt
|
dimitryB/nodecore
|
5df4ac5f48a598dde94d57d5810882a548d4d23d
|
[
"MIT"
] | null | null | null |
package nodecore.miners.pop
import nodecore.miners.pop.common.BitcoinNetwork
import nodecore.miners.pop.contracts.BlockStore
import nodecore.miners.pop.services.*
import nodecore.miners.pop.shell.PopShell
import nodecore.miners.pop.tasks.ProcessManager
import org.bitcoinj.core.Context
import org.bitcoinj.core.NetworkParameters
import org.bitcoinj.params.MainNetParams
import org.bitcoinj.params.RegTestParams
import org.bitcoinj.params.TestNet3Params
import org.koin.dsl.module
@JvmField
val bootstrapModule = module {
single { ProgramOptions() }
single { Configuration(get()) }
single {
val configuration: Configuration = get()
val params: NetworkParameters
params = when (configuration.bitcoinNetwork) {
BitcoinNetwork.MainNet -> MainNetParams.get()
BitcoinNetwork.TestNet -> TestNet3Params.get()
BitcoinNetwork.RegTest -> RegTestParams.get()
else -> RegTestParams.get()
}
Context(params)
}
single { BlockStore() }
single { PoPEventEngine(get(), get()) }
single { ProcessManager(get(), get()) }
single { BitcoinBlockCache() }
single { ChannelBuilder(get()) }
single { MessageService() }
single { PoPMiner(get(), get(), get(), get(), get(), get(), get(), get()) }
single { PoPStateService(get()) }
single { NodeCoreService(get(), get(), get()) }
single { BitcoinService(get(), get(), get()) }
single { PoPMiningScheduler(get(), get(), get()) }
single { PopShell(get(), get(), get(), get()) }
}
| 34.511111
| 79
| 0.675467
|
c26528e86a12ceca9cf151495ff66bff62a22822
| 2,663
|
h
|
C
|
distributed/include/work.h
|
jangmys/pbb
|
b53111ff3016cbf6885e99537ff80528e602bff6
|
[
"BSD-3-Clause"
] | 1
|
2022-03-22T17:14:21.000Z
|
2022-03-22T17:14:21.000Z
|
distributed/include/work.h
|
jangmys/pbb
|
b53111ff3016cbf6885e99537ff80528e602bff6
|
[
"BSD-3-Clause"
] | null | null | null |
distributed/include/work.h
|
jangmys/pbb
|
b53111ff3016cbf6885e99537ff80528e602bff6
|
[
"BSD-3-Clause"
] | null | null | null |
#ifndef WORK_H
#define WORK_H
//=====================================================
#include <pthread.h>
#include <iostream>
#include <vector>
#include <queue>
#include <memory>
#include "interval.h"
#include "gmp.h"
#include "gmpxx.h"
// class pbab;
class interval;
typedef std::shared_ptr<interval> INTERVAL_PTR;
typedef std::vector<std::shared_ptr<interval>> INTERVAL_VEC;
typedef std::vector<std::shared_ptr<interval>>::iterator INTERVAL_IT;
class work
{
public:
INTERVAL_VEC Uinterval; //...as decimals
//the meta-data
int id;//work ID
int nb_intervals;
int max_intervals;
int exploredNodes;
int nbLeaves;
int end_updated;//flag : was end modified?
int nb_updates;
mpz_class size;//, begin-end;
// time_t timeSinceLastUpdate; // Dernière date de mise à jour, utilisé par le coordinateur et le processus B&B
//Constructeurs
work();
work(const work &w);
work(std::istream& stream);
~work();
size_t writeToFile(FILE*);
size_t readFromFile(FILE*);
void readFromBuffer(int* buffer);
void sortIntervals();
void sortBest();
void displayUinterval();
void clear();
mpz_class wsize();
//work operators
void unionn(work* w);
// void intersection(const std::shared_ptr<work>& w, bool&);
bool intersection(const std::shared_ptr<work>& w);
void subtractFromAll(std::shared_ptr<work> w);
work* subtraction(work* w);
std::shared_ptr<work> divide(int max);
std::shared_ptr<work> divide2(int max);
std::shared_ptr<work> take(int max);
void streamToWork(std::string s);
void readHeader(std::istream& stream);
int readIntervals(std::istream& stream);
void writeHeader(std::ostream& stream)const;
void writeIntervals(std::ostream& stream)const;
//Gestion des variables membres
void set_size();
void set_time();
// void set_peer(peer& p);
void set_finished();
void set_null();
void set_id();
//checking
// bool big();
// bool big2();
// bool finished();
bool isEmpty();
bool fault();
bool update();
bool disjoint(work* w);
bool contain(work* w);
//operators
void operator=(work& w);
bool equal(work& w);
bool differ(std::shared_ptr<work>& w);
void VectToBigint(const int *posV,const int *endV, mpz_class &begin, mpz_class &end);
void BigintToVect(mpz_class begin,mpz_class end, int *posV, int *endV);
//new...
int renumber();
void split(size_t n);
void split2(size_t n);
};
std::ostream& operator<<(std::ostream& stream,const work& w);
std::istream& operator>>(std::istream& stream, work& w);
void work_free(work*);
#endif
| 22.760684
| 115
| 0.651896
|
b01c04404aef4086cf534109b8de74aa4cb5ab99
| 5,083
|
py
|
Python
|
ccontrol/utils/run.py
|
PierreMsy/DRL_continuous_control
|
40a443ea2c7415a5dd7185114da0f06902122c4b
|
[
"MIT"
] | null | null | null |
ccontrol/utils/run.py
|
PierreMsy/DRL_continuous_control
|
40a443ea2c7415a5dd7185114da0f06902122c4b
|
[
"MIT"
] | null | null | null |
ccontrol/utils/run.py
|
PierreMsy/DRL_continuous_control
|
40a443ea2c7415a5dd7185114da0f06902122c4b
|
[
"MIT"
] | null | null | null |
import os
import numpy as np
from collections import deque
from ccontrol.utils import save_scores, save_AC_models, save_configuration
class Runner:
def __init__(self) -> None:
file_location = os.path.dirname(__file__)
self.path_score = os.path.join(file_location, r'./../../output/score')
self.path_model = os.path.join(file_location, r'./../../output/model')
self.path_config = os.path.join(file_location, r'./../../output/configuration')
def run(self, agent, env, brain_name, nb_episodes, key,
average_on=10, target_score=None, target_over=100,
save_score=True, save_config=True, save_weights=False, save_interaction=False):
scores = deque()
scores_target = deque(maxlen=target_over)
scores_window = deque(maxlen=average_on)
is_solved = ''
for episode in range(1, nb_episodes+1):
env_info = env.reset(train_mode=True)[brain_name]
states = env_info.vector_observations
score = 0
while True:
actions = agent.act(states, noise=True)
env_info = env.step(actions)[brain_name]
next_states = env_info.vector_observations
rewards = env_info.rewards
dones = env_info.local_done
for state, action, reward, next_state, done in zip(states, actions, rewards, next_states, dones):
agent.step(state, action, reward, next_state, done)
states = next_states
score += np.mean(rewards)
if np.any(dones):
scores.append(score)
scores_target.append(score)
scores_window.append(score)
score_averaged = np.mean(list(scores_window))
print(f"\rEpisode {episode} Score: {score_averaged}{is_solved}",
end='\r')
if target_score:
if (len(is_solved) == 0) & (np.mean(list(scores_target)) > target_score):
is_solved = f' -> Solved in {episode} episodes'
break
print(f"\nLast score: {round(score_averaged,5)} {is_solved}")
if save_score:
save_scores(scores, key, self.path_score)
if save_config:
save_configuration(agent, key, self.path_config)
if save_weights:
save_AC_models(agent, key, self.path_model)
if save_interaction:
raise Exception('not implemented yet')
def run_single_agent(self, agent, env, brain_name, nb_episodes, key,
average_on=10, target_score=None, target_over=100,
save_score=True, save_config=True, save_weights=False, save_interaction=False):
scores = deque()
scores_target = deque(maxlen=target_over)
scores_window = deque(maxlen=average_on)
is_solved = ''
for episode in range(1, nb_episodes+1):
env_info = env.reset(train_mode=True)[brain_name]
state = env_info.vector_observations[0]
score = 0
while True:
action = agent.act(state, noise=True)
env_info = env.step(action)[brain_name]
next_state = env_info.vector_observations[0]
reward = env_info.rewards[0]
done = env_info.local_done[0]
agent.step(state, action, reward, next_state, done)
state = next_state
score += reward
if done:
scores.append(score)
scores_target.append(score)
scores_window.append(score)
score_averaged = np.mean(list(scores_window))
print(f"\rEpisode {episode} Score: {score_averaged}{is_solved}",
end='\r')
if target_score:
if (len(is_solved) == 0) & (np.mean(list(scores_target)) > target_score):
is_solved = f' -> Solved in {episode} episodes'
break
print(f"\rLast score: {round(score_averaged,5)} {is_solved}")
if save_score:
save_scores(scores, key, self.path_score)
if save_config:
save_configuration(agent, key, self.path_config)
if save_weights:
save_AC_models(agent, key, self.path_model)
if save_interaction:
raise Exception('not implemented yet')
| 40.664
| 117
| 0.508951
|
3ff37b9d80a9f83b1ed294c9111fb0ded4bd371f
| 523
|
rb
|
Ruby
|
app/policies/name_card_apply_policy.rb
|
jasl-lab/cybros_portal
|
fe85e5d217450e1bae916aade38878302cea5e09
|
[
"MIT"
] | 1
|
2021-07-08T07:14:01.000Z
|
2021-07-08T07:14:01.000Z
|
app/policies/name_card_apply_policy.rb
|
jasl-lab/cybros_portal
|
fe85e5d217450e1bae916aade38878302cea5e09
|
[
"MIT"
] | null | null | null |
app/policies/name_card_apply_policy.rb
|
jasl-lab/cybros_portal
|
fe85e5d217450e1bae916aade38878302cea5e09
|
[
"MIT"
] | null | null | null |
# frozen_string_literal: true
class NameCardApplyPolicy < ApplicationPolicy
class Scope < Scope
def resolve
if user.admin? || user.roles.pluck(:role_name).any? { |r| r.in?(%w[管理名片]) }
scope.all
else
scope.where(user_id: user.id).or(scope.where(email: user.email))
end
end
end
def report?
user.admin? || user.roles.pluck(:role_name).any? { |r| r.in?(%w[管理名片]) }
end
def upload?
user.admin? || user.roles.pluck(:role_name).any? { |r| r.in?(%w[管理名片]) }
end
end
| 23.772727
| 81
| 0.615679
|
e6dc92824a9899ad49b923854516fc466a0efd63
| 2,271
|
sh
|
Shell
|
courses/machine_learning/deepdive/09_sequence/setup_kubeflow.sh
|
Glairly/introduction_to_tensorflow
|
aa0a44d9c428a6eb86d1f79d73f54c0861b6358d
|
[
"Apache-2.0"
] | 2
|
2022-01-06T11:52:57.000Z
|
2022-01-09T01:53:56.000Z
|
courses/machine_learning/deepdive/09_sequence_keras/setup_kubeflow.sh
|
Glairly/introduction_to_tensorflow
|
aa0a44d9c428a6eb86d1f79d73f54c0861b6358d
|
[
"Apache-2.0"
] | null | null | null |
courses/machine_learning/deepdive/09_sequence_keras/setup_kubeflow.sh
|
Glairly/introduction_to_tensorflow
|
aa0a44d9c428a6eb86d1f79d73f54c0861b6358d
|
[
"Apache-2.0"
] | null | null | null |
#!/bin/sh
install_ksonnet() {
wget https://github.com/ksonnet/ksonnet/releases/download/v0.8.0/ks_0.8.0_linux_amd64.tar.gz
tar xvfz ks_0.8.0_linux_amd64.tar.gz
}
install_kubeflow() {
rm -rf kubeflow-app
ks init kubeflow-app
cd kubeflow-app
ks registry add kubeflow github.com/kubeflow/kubeflow/tree/master/kubeflow
ks pkg install kubeflow/core
ks pkg install kubeflow/tf-serving
ks pkg install kubeflow/tf-job
cd ..
}
create_kubeflow_core() {
cd kubeflow-app
kubectl create namespace ${KF_NAMESPACE}
ks generate core kubeflow-core --name=kubeflow-core --namespace=${KF_NAMESPACE}
ks env add nocloud
ks env add cloud
ks param set kubeflow-core cloud gke --env=cloud
ks apply ${KF_ENV} -c kubeflow-core
cd ..
}
deploy_model() {
cd kubeflow-app
MODEL_COMPONENT="servePoetry"
MODEL_NAME="poetry"
MODEL_PATH=gs://cloud-training-demos-ml/poetry/model_full/export/poetry
echo "Deploying $MODEL_NAME from $MODEL_PATH"
#ks generate tf-serving ${MODEL_COMPONENT} --name=${MODEL_NAME} --namespace=${KF_NAMESPACE} --model_path=${MODEL_PATH}
ks apply ${KF_ENV} -c ${MODEL_COMPONENT}
cd ..
}
setup_ingress() {
cd kubeflow-app
kubectl expose deployment poetry --type NodePort
#gcloud compute addresses create mlpoetry-ingress --global
cat > /tmp/tfserving.yaml << EOF
apiVersion: extensions/v1beta1
kind: Ingress
metadata:
name: tfservingIngress
annotations:
kubernetes.io/ingress.global-static-ip-name: "mlpoetry-ingress"
spec:
backend:
serviceName: poetry.poetry
servicePort: 8000
EOF
#kubectl create -f /tmp/tfserving.yaml
}
send_request() {
echo "Sending request to $CLUSTER_IP"
curl -i -X POST -H 'Content-Type: application/json' -d '{"input": "all day long my heart trembles like a leaf"}' https://${CLUSTER_IP}:9000/
}
if [ -z "$GITHUB_TOKEN" ]; then
echo "Please get a personal authorization token form GitHub. Otherwise, you'll run into rate limiting"
echo "export GITHUB_TOKEN=<token>"
exit -1
fi
export PATH=${PATH}:${PWD}/ks_0.8.0_linux_amd64/
export KF_NAMESPACE=poetry
export KF_ENV=cloud
#install_ksonnet
#install_kubeflow
#create_kubeflow_core
deploy_model
#setup_ingress
#send_request
| 28.037037
| 143
| 0.715544
|
8687b286bd8bbeb11762e4a0fc0ce93d5ff991e6
| 2,205
|
dart
|
Dart
|
1111_example_flutter/flutter_dadi/example/demo06.dart
|
seerwo/computer_science
|
7b0075d7a6d8b25bae1e32bf43f597cccaded61a
|
[
"MIT"
] | null | null | null |
1111_example_flutter/flutter_dadi/example/demo06.dart
|
seerwo/computer_science
|
7b0075d7a6d8b25bae1e32bf43f597cccaded61a
|
[
"MIT"
] | null | null | null |
1111_example_flutter/flutter_dadi/example/demo06.dart
|
seerwo/computer_science
|
7b0075d7a6d8b25bae1e32bf43f597cccaded61a
|
[
"MIT"
] | null | null | null |
void main(){
var list = <String>['香蕉','苹果','西瓜'];
print(list);
list.add("草莓");
print(list);
print(list.length); //4
print(list.isEmpty); //false
print(list.isNotEmpty);
print(list.reversed); //翻转 队列表倒叙排序
var newMyList = list.reversed.toList();
print(newMyList);
list.add('桃子'); //增加一个数据 增加一个
list.addAll(['桃子','葡萄']); //拼接数组
print(list.indexOf('苹果')); //indexOf查找数据 查找不到返回-1 查找到返回
list.remove('西瓜');
list.removeAt(2);
print(list);
list.fillRange(1, 2, 'aaa'); //修改
print(list);
list.insert(1,'aaa1'); // 插入 一个
print(list);
list.insertAll(1, ['aaa1','bbb1']); //插入 多个
print(list);
var str = list.join('-'); //list转换成字符串
print(str);
print(str is String); //true
var list1 = str.split('-');
print(list1);
var s = new Set(); //集合去重
s.add('香蕉');
s.add('苹果');
print(s);
print(s.toList());
//数组去重
var s1 = Set();
s1.addAll(list1);
print(s1);
print(s1.toList());
Map person = {
"name":"张三",
"age":20,
"sex": "男",
};
var m1 = Map();
m1["name"] = "李四";
print(person);
print(m1);
print(person.keys.toList());
print(person.values.toList());
print(person.isEmpty);
print(person.isNotEmpty);
person.addAll({
"work":['敲代码','送外卖'],
"height": 160
});
person.remove("sex");
print(person);
person.containsValue('张三');
for(var i=0; i< list.length; i++){
//print(list[i]);
}
//item
for (var item in list){
//print(item);
}
//foreach
list.forEach((value) {
print("$value");
});
List list2 = [1,3,4];
List newList = [];
for(var i=0; i< list2.length; i++){
newList.add(list2[i]*2);
}
print(newList);
//map 修改集合里数据
var newList3 = list2.map((value){
return value * 2;
});
print(newList3.toList());
//where 返回条件
var newList4 = newList3.where((value){
return value > 5;
});
print(newList4.toList());
var f = newList3.any((value){ //只要集合里面有满足条件的就返回true
return value > 5;
});
print(f);
var f1 = newList3.every((value){ //每一个都满足条件返回true 否则返回false
return value > 5;
});
print(f1);
//set
var s2 = Set();
s2.addAll([1,222, 333]);
s2.forEach((value) => print(value)); //循环set map
print(s2);
}
| 17.782258
| 61
| 0.569615
|
ff29e1b18d804b039630e12a55317f9a30c8e4c2
| 3,539
|
py
|
Python
|
helper/f2g_omim_analyze.py
|
PEDIA-Charite/PEDIA-workflow
|
f0ab0c7ed3833edb01ad0772ad294978b71feb64
|
[
"MIT"
] | 9
|
2017-10-16T17:04:48.000Z
|
2021-11-03T13:09:11.000Z
|
helper/f2g_omim_analyze.py
|
PEDIA-Charite/PEDIA-workflow
|
f0ab0c7ed3833edb01ad0772ad294978b71feb64
|
[
"MIT"
] | 60
|
2017-05-22T15:43:06.000Z
|
2022-02-07T22:16:48.000Z
|
helper/f2g_omim_analyze.py
|
PEDIA-Charite/PEDIA-workflow
|
f0ab0c7ed3833edb01ad0772ad294978b71feb64
|
[
"MIT"
] | 9
|
2017-11-27T16:19:11.000Z
|
2021-01-24T03:48:08.000Z
|
import os
import json
import csv
from pprint import pprint
from collections import defaultdict
with open("f2g_library_dump.json", "r") as f2g_lib:
syndromes = json.load(f2g_lib)
ps_dict = {}
mim_to_ps = {}
with open("data/phenotypicSeries.txt", "r") as ps_data:
for raw_entry in csv.DictReader(
(r for r in ps_data if not r.startswith("#")),
delimiter="\t",
fieldnames=["ps_number", "mim_number", "phenotype"]
):
if raw_entry["ps_number"] not in ps_dict:
ps_dict[raw_entry["ps_number"]] = {
"name": raw_entry["mim_number"],
"syndromes": []
}
else:
ps_dict[raw_entry["ps_number"]]["syndromes"].append(
{
"mim_number": raw_entry["mim_number"],
"name": raw_entry["phenotype"]
}
)
if raw_entry["mim_number"] in mim_to_ps:
mim_to_ps[raw_entry["mim_number"]].append(
raw_entry["ps_number"]
)
else:
mim_to_ps[raw_entry["mim_number"]] = [raw_entry["ps_number"]]
f2g_only_series = [
"PS104300",
"PS143465",
"PS612863",
"PS121700",
"PS125853",
"PS601551",
"PS164210",
"PS235000",
"PS145500",
"PS608516",
"PS166710",
]
f2g_names = {}
name_to_sid = {}
errors = []
name_to_entry = {}
json_files = [v for v in os.listdir("process/aws_dir/cases")
if v.endswith(".json")]
for syndrome in syndromes:
sid = syndrome["syndrome_id"]
oid = syndrome["omim_id"]
psid = syndrome["omim_ps_id"]
if psid and not psid.startswith("PS"):
psid = "PS" + psid
sname = syndrome["syndrome_name"]
salt = [s["synonym"] for s in syndrome["synonyms"]]
salt += [sname]
nbk_id = syndrome["nbk_id"]
orphanet = syndrome["orphanet"]
if sname not in name_to_entry:
name_to_entry[sname.lower()] = syndrome
# else:
# print(sname)
# print(name_to_entry[sname])
# print(syndrome)
if oid == "0" or oid is None:
# should be names of phenotypic series
# if psid is None:
# print(oid, sname, nbk_id, orphanet)
continue
trans = {
"614132": "213980"
}
def match_syndrome(name: str, oid) -> str:
try:
sname = name.lower()
except AttributeError as e:
print(name, e)
oid = [oid] if not isinstance(oid, list) else oid
oid = [str(o) for o in oid]
oid = [trans[o] if o in trans else o for o in oid]
if len(oid) < 2:
return None
if sname in name_to_entry:
return name_to_entry[sname]
splits = sname.split(";")
for s in splits:
s = s.strip()
for k in name_to_entry:
if s in k:
soid = name_to_entry[k]["omim_id"]
if soid in oid:
return name_to_entry[k]
else:
print("{} not in {}".format(soid, oid))
print(sname, "no match")
matched = 0
for js_file in json_files:
js_path = "process/aws_dir/cases/" + js_file
with open(js_path, "r") as jfp:
js_data = json.load(jfp)
print(js_data["case_id"])
selected = js_data["selected_syndromes"]
detected = js_data["detected_syndromes"]
for d in detected:
sname = d["syndrome_name"]
oid = d["omim_id"]
r = match_syndrome(sname, oid)
if not None:
matched += 1
print("Matched", matched)
| 25.278571
| 77
| 0.552981
|
a41392640d1724f5759d7b8741b12a6a04c9ead8
| 2,012
|
php
|
PHP
|
app/Http/Controllers/WebhookController.php
|
CODevR3IT/avaluosNew_backend
|
8257795051cd4791f8751d390d401e077d7c0bfc
|
[
"MIT"
] | null | null | null |
app/Http/Controllers/WebhookController.php
|
CODevR3IT/avaluosNew_backend
|
8257795051cd4791f8751d390d401e077d7c0bfc
|
[
"MIT"
] | null | null | null |
app/Http/Controllers/WebhookController.php
|
CODevR3IT/avaluosNew_backend
|
8257795051cd4791f8751d390d401e077d7c0bfc
|
[
"MIT"
] | 1
|
2021-03-10T21:20:33.000Z
|
2021-03-10T21:20:33.000Z
|
<?php
namespace App\Http\Controllers;
use Illuminate\Support\Facades\Crypt;
use App\Http\ThirdParty\SolucionIdeas;
use Illuminate\Support\Facades\Storage;
use Illuminate\Http\Request;
use Carbon\Carbon;
use Hamcrest\Arrays\IsArray;
use Log;
class WebhookController extends Controller
{
/**
* Create a new controller instance.
*
* @return void
*/
//protected $modelReimpresionNuevo;
private $errors;
private $file;
public function __construct()
{
//
}
public function recibeToken(Request $request)
{
try{
// Log::info($request);
//echo $request;
$arrayRes['id'] = $request->input('id');
$arrayRes['folio_avaluo'] = $request->input('folio_avaluo');
$arrayRes['token'] = $request->input('token');
/*$arrayRes['idq'] = $request->query('id');
$arrayRes['folio_avaluoq'] = $request->query('folio_avaluo');
$arrayRes['tokenq'] = $request->query('token');*/
/*foreach($request as $id => $req){
if($id == "query" || $id == "input"){
foreach($req as $idInput => $elementoInput){
$arrayRes[$idInput] = $elementoInput;
}
}
} */
//echo json_encode($arrayRes); exit();
$nombreArchivo = "Token".date('Ymd').".txt";
// $rutaArchivos = getcwd()."/Tokens/";
$path = storage_path();
$rutaArchivos = $path."/Tokens/";
$file = fopen($rutaArchivos."/".$nombreArchivo, "a+");
fwrite($file,json_encode($arrayRes)."\n");
fclose($file);
return response()->json(['Estado' => 'Correcto'], 200);
}catch (\Throwable $th){
Log::info($th);
error_log($th);
return response()->json(['mensaje' => 'Error en la recepción'], 500);
}
}
}
| 30.484848
| 81
| 0.50994
|
8dcbede585ff05926d77e7c5cb10689839f0b3d8
| 1,318
|
js
|
JavaScript
|
models/user.js
|
Ejiro-Edwin/Invoice-App
|
05e8c1cd1592db45bb15b39118136a21e2dc7ee7
|
[
"MIT"
] | null | null | null |
models/user.js
|
Ejiro-Edwin/Invoice-App
|
05e8c1cd1592db45bb15b39118136a21e2dc7ee7
|
[
"MIT"
] | null | null | null |
models/user.js
|
Ejiro-Edwin/Invoice-App
|
05e8c1cd1592db45bb15b39118136a21e2dc7ee7
|
[
"MIT"
] | null | null | null |
const Joi = require('joi');
const mongoose = require('mongoose');
const jwt = require('jsonwebtoken');
const config =require('config');
const userSchema = new mongoose.Schema({
firstname: {
type: String,
required: true,
minlength: 5,
maxlength: 50
},
lastname: {
type: String,
required: true,
minlength: 5,
maxlength: 50
},
email: {
type: String,
required: true,
unique:true,
minlength: 5,
maxlength: 255
},
password: {
type: String,
required: true,
minlength: 5,
maxlength: 1024
}
});
userSchema.methods.generateUserAuthToken = function() {
const token = jwt.sign({ _id : this._id},config.get('JwtPrivateKey'));
return token;
}
const User = mongoose.model('User', userSchema);
function validateUser(user) {
const schema = {
firstname: Joi.string().min(5).max(50).required(), //validate
lastname: Joi.string().min(5).max(50).required(),
email: Joi.string().min(5).max(255).required().email(),
password: Joi.string().min(5).max(255).required()
};
return Joi.validate(user, schema);
}
module.exports.userSchema = userSchema;
module.exports.User = User;
module.exports.validate = validateUser;
| 24.867925
| 74
| 0.594841
|
fe3d7d50241a185d564c1da962cdf79c70ce7588
| 218
|
dart
|
Dart
|
lib/src/model/scan_session.dart
|
EstefaniaRealcore/flutter_reactive_ble
|
ea29bd23152c4257294bb9e468950247cf98a63f
|
[
"BSD-3-Clause"
] | 1
|
2021-09-03T09:29:31.000Z
|
2021-09-03T09:29:31.000Z
|
lib/src/model/scan_session.dart
|
jonahwilliams/flutter_reactive_ble
|
6e0597449a7faf49f97548832a5fbb33b6ddb9ce
|
[
"BSD-3-Clause"
] | null | null | null |
lib/src/model/scan_session.dart
|
jonahwilliams/flutter_reactive_ble
|
6e0597449a7faf49f97548832a5fbb33b6ddb9ce
|
[
"BSD-3-Clause"
] | null | null | null |
import 'package:flutter_reactive_ble/src/model/uuid.dart';
class ScanSession {
final List<Uuid> withServices;
final Future<void> future;
const ScanSession({required this.withServices, required this.future});
}
| 24.222222
| 72
| 0.775229
|
56a108a65d39a802d9291f9d924e0c5000b9cc5d
| 32,502
|
lua
|
Lua
|
HUD/.HUD.lua
|
Zavian/Tabletop-Simulator-Scripts
|
42dabbf1a18d920383c290218b1a00898f0b00b8
|
[
"MIT"
] | 6
|
2020-04-27T23:05:32.000Z
|
2021-09-19T13:30:25.000Z
|
HUD/.HUD.lua
|
Zavian/Tabletop-Simulator-Scripts
|
42dabbf1a18d920383c290218b1a00898f0b00b8
|
[
"MIT"
] | null | null | null |
HUD/.HUD.lua
|
Zavian/Tabletop-Simulator-Scripts
|
42dabbf1a18d920383c290218b1a00898f0b00b8
|
[
"MIT"
] | null | null | null |
--#region initiative-hud
local _defaults = {
color = {
ally = "#66ba6b",
neutral = "#d5d165",
player = "#7e7dbb",
enemy = "#BD5365",
lair = "#D2D186",
epic = "#B38CFF"
},
players = {
"Zora",
"Amber",
"Edwin",
"Gilkan",
"Marcus",
"Kottur"
},
playersColors = {
zora = "Red",
amber = "Teal",
edwin = "Blue",
gilkan = "Green",
marcus = "White",
kottur = "Purple"
},
offsets = {
nr = "-35 255",
toggle = "0 255"
},
insets = {
nr = "-35 0",
toggle = "0 0"
},
xt = 5,
xc = 1,
timeToken = {
tToken = "2f363b",
turnPos = {x = 101.87, y = 4.00, z = -33.55},
turnOffset = 0.77,
rToken = "0e4e22",
roundPos = {x = 101.65, y = 4.00, z = -28.57},
roundOffset = 0.38
},
static = {
"Lair",
"Epic Die"
},
textColor = "#f0f0f0ff",
initiative_mat = nil
}
-- ITEMS LEGEND:
-- id .. a = button, aka Activator for the overlay
-- id .. c = Closing button, aka while panel is open
-- id .. i = text, aka Initiative
-- id .. n = text, aka the Name of the initiative
-- id .. o = Opening button, aka while panel is close
-- id .. p = Panel, aka the panel that comes while open
-- id .. r = Toggle, aka Reaction used
-- id .. t = button, aka iniTiative button
-- id .. x = Toggle, aka Concentration used
-- id .. y = image, aka overlaY for the item to be active
local debug = false
local activated = ""
local id = 1
local elements = {}
local xmlElements = {}
local statusCache = {}
local initiatives = {}
local sound = nil
function onFixedUpdate()
local h = #xmlElements * 50
self.UI.setAttribute("layout", "height", h)
self.UI.setAttribute("nm", "text", #xmlElements)
if #xmlElements <= 5 then
self.UI.setAttribute("widget", "noScrollbars", "true")
else
self.UI.setAttribute("widget", "noScrollbars", "false")
end
end
function onLoad()
HideHud()
end
function ReorderMat()
if _defaults.initiative_mat then
local mat = getObjectFromGUID(_defaults.initiative_mat)
mat.call("order_initiative")
end
end
function setElements(params)
local t = params.t
if not _defaults.initiative_mat then
_defaults.initiative_mat = params.mat
end
resetTable()
xmlElements = {}
elements = {}
if t ~= nil then
ShowHud()
for i = 1, #t do
local tempE = {
id = id,
initiative = t[i].ini,
name = t[i].name,
side = t[i].side,
pawn = t[i].pawn
}
table.insert(elements, tempE)
id = id + 1
end
xmlElements = {}
startLuaCoroutine(self, "BuildElements")
Wait.condition(
function()
BuildWidget(xmlElements)
ShowHud()
end,
function()
if xmlElements and elements then
return #xmlElements == #elements and #xmlElements > 0 and #elements > 0
else
return false
end
end
)
end
end
function BuildElements()
table.sort(
elements,
function(k1, k2)
return k1.initiative > k2.initiative
end
)
if elements then
for i = 1, #elements do
local xmlElement = ElementBuilder(elements[i])
table.insert(xmlElements, xmlElement)
coroutine.yield(0)
end
end
return 1
end
function ElementBuilder(element)
if debug and false then
print("-------------------")
print("To Add:")
print("\t" .. element.initiative)
print("\t" .. element.name)
print("color = " .. parseColor(element.side))
element.name = element.name .. "." .. element.id
end
local toAdd = {
tag = "Image",
attributes = {
id = element.id,
image = "Widget",
class = "closed",
color = parseColor(element.side)
},
children = {
{
tag = "Image",
attributes = {
id = element.id .. "y",
image = "Widget-overlay",
active = false
}
},
{
tag = "Panel",
children = {
{
tag = "Button",
attributes = {
id = element.id .. "o",
class = "closed",
onClick = "widgetExpand(id)"
}
},
{
tag = "Text",
attributes = {
id = element.id .. "i",
class = "initiative",
text = element.initiative
}
},
{
tag = "Button",
attributes = {
id = element.id .. "t",
class = "finder",
onclick = "findPawn(id)",
pawn = element.pawn,
active = element.pawn ~= nil and "true" or "false"
}
},
{
tag = "Text",
attributes = {
id = element.id .. "n",
class = "name",
text = element.name
}
},
{
tag = "Button",
attributes = {
id = element.id .. "a",
class = "activator",
onClick = "widgetActivate(id)"
}
},
{
tag = "Panel",
attributes = {
id = element.id .. "p",
active = "false"
},
children = {
{
tag = "Toggle",
attributes = {
id = element.id .. "r",
class = "react",
isOn = seeCache(element.name, element.initiative, element.pawn, "react"),
onValueChanged = "toggleChange"
}
},
{
tag = "Toggle",
attributes = {
id = element.id .. "x",
class = "conc",
isOn = seeCache(element.name, element.initiative, element.pawn, "conc"),
onValueChanged = "toggleChange"
}
},
{
tag = "Button",
attributes = {
id = element.id .. "c",
class = "opened",
onClick = "widgetReduce(id)"
}
}
}
}
}
}
}
}
return toAdd
end
function BuildWidget(xmlEle)
local xmlTable = UI.getXmlTable()
local t = xmlTable[_defaults.xt].children[_defaults.xc].children
for i = 1, #xmlEle do
table.insert(t, xmlEle[i])
end
--xmlTable[3].children[1].children = panel
updateTable(xmlTable)
end
function NextTurn()
if activated == "" then
UI.setAttribute(elements[1].id .. "y", "active", "true")
activated = elements[1].name .. "|" .. elements[1].id
else
local myId = mysplit(activated, "|")[2]
local myPos = findMe(myId)
local nextPos = myPos + 1 > #elements and 1 or myPos + 1
if nextPos == 1 then
NextRound()
end
UI.setAttribute(myId .. "y", "active", "false")
UI.setAttribute(elements[nextPos].id .. "y", "active", "true")
activated = elements[nextPos].name .. "|" .. elements[nextPos].id
notify()
end
end
function ToggleHud()
if UI.getAttribute("widget", "active") == "true" then
HideHud()
roundCPos = nil
roundToken = getObjectFromGUID(_defaults.timeToken.rToken)
turnToken = getObjectFromGUID(_defaults.timeToken.tToken)
roundToken.setPositionSmooth(_defaults.timeToken.roundPos)
turnToken.setPositionSmooth(_defaults.timeToken.turnPos)
statusCache = {}
resetEpicBoons()
else
ShowHud()
end
end
local roundCPos = nil
function NextRound()
if roundCPos == nil then
roundCPos = {x = 101.65, y = 4.00, z = -28.57}
end
roundToken = getObjectFromGUID(_defaults.timeToken.rToken)
roundCPos.x = roundCPos.x + _defaults.timeToken.roundOffset
roundToken.setPositionSmooth(roundCPos, false, false)
roundToken.setRotationSmooth({0, 90, 0}, false, false)
for i = 1, #elements do
if not isPlayer(elements[i].name) then
UI.setAttribute(elements[i].id .. "r", "isOn", "False")
if statusCache[elements[i].name .. "." .. elements[i].initiative .. "." .. elements[i].pawn] then
statusCache[name .. "." .. initiative .. "." .. pawn]["react"] = false
end
end
end
end
function ShowHud()
UI.setAttribute("widget", "active", "true")
UI.setAttribute("nt", "offsetXY", _defaults.offsets.nr)
UI.setAttribute("toggle", "offsetXY", _defaults.offsets.toggle)
UI.setAttribute("reorder", "active", "true")
UI.setAttribute("nt", "textColor", _defaults.textColor)
UI.setAttribute("toggle", "textColor", _defaults.textColor)
UI.setAttribute("reorder", "textColor", _defaults.textColor)
textColor = ""
TogglePlayer(true)
end
function HideHud()
UI.setAttribute("widget", "active", "false")
UI.setAttribute("nt", "offsetXY", _defaults.insets.nr)
UI.setAttribute("toggle", "offsetXY", _defaults.insets.toggle)
UI.setAttribute("reorder", "active", "false")
UI.setAttribute("nt", "textColor", _defaults.textColor)
UI.setAttribute("toggle", "textColor", _defaults.textColor)
UI.setAttribute("reorder", "textColor", _defaults.textColor)
TogglePlayer(false)
end
function TogglePlayer(toggle)
UI.setAttribute("green", "color", toggle and "#ffffffff" or "#ffffff00")
UI.setAttribute("purple", "color", toggle and "#ffffffff" or "#ffffff00")
UI.setAttribute("red", "color", toggle and "#ffffffff" or "#ffffff00")
UI.setAttribute("blue", "color", toggle and "#ffffffff" or "#ffffff00")
UI.setAttribute("yellow", "color", toggle and "#ffffffff" or "#ffffff00")
UI.setAttribute("brown", "color", toggle and "#ffffffff" or "#ffffff00")
UI.setAttribute("white", "color", toggle and "#ffffffff" or "#ffffff00")
UI.setAttribute("teal", "color", toggle and "#ffffffff" or "#ffffff00")
UI.setAttribute("orange", "color", toggle and "#ffffffff" or "#ffffff00")
UI.setAttribute("pink", "color", toggle and "#ffffffff" or "#ffffff00")
end
function toggleChange(player, option, v)
UI.setAttribute(v, "isOn", option)
local id = tonumber(string.sub(v, 1, -2))
local name = UI.getAttribute(id .. "n", "text")
local initiative = UI.getAttribute(id .. "i", "text")
local pawn = UI.getAttribute(id .. "t", "pawn")
local thing = UI.getAttribute(v, "class")
local status = option == "True" and true or false
if not isPlayer(name) then
if not statusCache[name .. "." .. initiative .. "." .. pawn] then
statusCache[name .. "." .. initiative .. "." .. pawn] = {
conc = false,
react = false
}
end
statusCache[name .. "." .. initiative .. "." .. pawn][thing] = status
end
end
function findPawn(player, request, v)
local guid = UI.getAttribute(v, "pawn")
local pawn = getObjectFromGUID(guid)
pawn.call("toggleVisualize", {input = "true", color = "Black"})
--Player["Black"].lookAt(
-- {
-- position = pawn.getPosition(),
-- distance = 60,
-- pitch = 60,
-- yaw = 270
-- }
--)
end
function seeCache(name, initiative, pawn, thing)
if not isPlayer(name) and not isStatic(name) then
if statusCache[name .. "." .. initiative .. "." .. pawn] then
status = statusCache[name .. "." .. initiative .. "." .. pawn][thing]
return status and "True" or "False"
end
end
return false
end
function widgetExpand(player, request, v)
-- request is the requested variable (in this case ID)
-- v is the value of said variable. in this case we are in the button
-- meaning that the id will be id + o (to signify opening button)
-- this will be removed
local id = tonumber(string.sub(v, 1, -2))
UI.setAttribute(id, "image", "Widget-open")
UI.setAttribute(id .. "p", "active", "true")
UI.setAttribute(v, "active", "false")
end
function widgetReduce(player, request, v)
local id = tonumber(string.sub(v, 1, -2))
UI.setAttribute(id, "image", "Widget")
UI.setAttribute(id .. "p", "active", "false")
UI.setAttribute(id .. "o", "active", "true")
end
function widgetActivate(player, request, v)
local id = tonumber(string.sub(v, 1, -2))
if activated ~= "" then
local currentId = mysplit(activated, "|")[2]
UI.setAttribute(currentId .. "y", "active", "false")
end
local name = UI.getAttribute(id .. "n", "text")
activated = name .. "|" .. id
notify()
UI.setAttribute(id .. "y", "active", "true")
end
function notify()
local myId = mysplit(activated, "|")[2]
local myPos = findMe(myId)
if myPos then
local nextPos = myPos + 1
if nextPos > #elements then
nextPos = 1
end
-- this will manage the card notification for the next
-- in the initiative counter
if isPlayer(elements[nextPos].name) then
local name = string.lower(elements[nextPos].name)
if (Player[_defaults.playersColors[name]].seated) then
broadcastToColor(
"You're next in initiative! Prepare yourself.",
_defaults.playersColors[name],
{1, 1, 1}
)
UI.setAttribute(_defaults.playersColors[name], "active", "true")
end
end
if isPlayer(elements[myPos].name) then
local name = string.lower(elements[myPos].name)
if (Player[_defaults.playersColors[name]].seated) then
broadcastToColor("It's your turn!", _defaults.playersColors[name], {1, 1, 1})
UI.setAttribute(_defaults.playersColors[name], "active", "false")
end
end
end
end
function isPlayer(name)
for i = 1, #_defaults.players do
if string.lower(name) == string.lower(_defaults.players[i]) then
return true
end
end
end
function isStatic(name)
for i = 1, #_defaults.static do
if string.lower(name) == string.lower(_defaults.static[i]) then
return true
end
end
end
function findMe(tofind)
for i = 1, #elements do
if tonumber(tofind) == tonumber(elements[i].id) then
return i
end
end
return nil
end
function nextTurn()
-- here goes the movement of the turn counter
if activated == "" then
end
end
function addElement(params)
-- params is from someone else
-- params will be:
-- ini : int
-- name : string
-- side : string
-- owner : guid
---------------------------------
-- the add element will create a new
-- element in the HUD
--if params then
-- local element = {
-- id = id,
-- initiative = params.ini,
-- name = params.name,
-- side = params.side,
-- owner = getObjectFromGUID(params.owner),
-- visible = true
-- }
-- table.insert(elements, element)
-- id = id + 1
-- RenderElements()
--end
end
function SyncTable()
RenderElements()
end
function RenderElements()
table.sort(
elements,
function(k1, k2)
return k1.initiative > k2.initiative
end
)
local xmlTable = self.UI.getXmlTable()
resetTable()
local t = xmlTable[3].children[1].children
for i = 1, #elements do
if debug then
print("-------------------")
print("To Add:")
print("\t" .. elements[i].initiative)
print("\t" .. elements[i].name)
print("color = " .. parseColor(elements[i].side))
elements[i].name = elements[i].name .. "." .. elements[i].id
end
local toAdd = {
tag = "Image",
attributes = {
id = elements[i].id,
image = "Widget",
class = "closed",
color = parseColor(elements[i].side)
},
children = {
{
tag = "Panel",
children = {
{
tag = "Button",
attributes = {
id = elements[i].id .. "o",
class = "closed",
onClick = "widgetExpand(id)"
}
},
{
tag = "Text",
attributes = {
class = "initiative",
text = elements[i].initiative
}
},
{
tag = "Text",
attributes = {
class = "name",
text = elements[i].name
}
},
{
tag = "Panel",
attributes = {
id = elements[i].id .. "p",
active = "false"
},
children = {
{
tag = "Toggle",
attributes = {
class = "react"
}
},
{
tag = "Toggle",
attributes = {
class = "conc"
}
},
{
tag = "Button",
attributes = {
id = elements[i].id .. "c",
class = "opened",
onClick = "widgetReduce(id)"
}
}
}
}
}
}
}
}
--printTable(toAdd)
table.insert(t, toAdd)
toAdd = nil
end
updateTable(xmlTable)
end
function parseColor(side)
return _defaults.color[side]
end
function updateTable(xmlTable)
local h = getHeightMultiplier()
UI.setXmlTable(xmlTable)
UI.setAttribute("layout", "height", h)
end
function resetTable()
local xmlTable = UI.getXmlTable()
xmlTable[_defaults.xt].children[_defaults.xc].children = {}
UI.setXmlTable(xmlTable)
--printTable(xmlTable)
end
function getHeightMultiplier()
local counter = 0
for i = 1, #elements do
if elements[i].visible then
counter = counter + 1
end
end
return counter * 50
end
function setSeated(players)
Wait.time(
function()
local mat = getObjectFromGUID(_defaults.initiative_mat)
for i = 1, #players.input do
log(Player[_defaults.playersColors[players.input[i]]].seated and "true" or "false", players.input[i])
mat.UI.setAttribute(
players.input[i],
"active",
Player[_defaults.playersColors[players.input[i]]].seated and "true" or "false"
)
if debug then
mat.UI.setAttribute(players.input[i], "active", "true")
end
end
end,
1
)
end
function requestPlayer(player)
if not _defaults.initiative_mat then
_defaults.initiative_mat = player.call
end
log(Player[_defaults.playersColors[player.p]].seated, player.p .. " seated")
if Player[_defaults.playersColors[player.p]].seated then
UI.setAttribute(_defaults.playersColors[player.p] .. "_box", "active", "true")
initiatives[_defaults.playersColors[player.p]] = {t = player.t, i = ""}
end
if debug then
UI.setAttribute(_defaults.playersColors[player.p] .. "_box", "active", "true")
initiatives[_defaults.playersColors[player.p]] = {t = player.t, i = ""}
end
end
function submitRequest(player)
-- this activates on the submit button
if initiatives[player.color].i ~= "" then
UI.setAttribute(player.color .. "_box", "active", "false")
local playerName = getPlayerByColor(player.color)
playerName = playerName:sub(1, 1):upper() .. playerName:sub(2) -- capitalize name
printToAll(
"[" .. Color[player.color]:toHex(false) .. "]" .. playerName .. ":[-] " .. initiatives[player.color].i,
"White"
) -- print initiative in the chat
local mat = getObjectFromGUID(_defaults.initiative_mat)
mat.UI.setAttribute(playerName:lower(), "text", playerName .. "|" .. initiatives[player.color].i)
mat.UI.setAttribute(playerName:lower(), "textColor", "#ff7f27") -- setting ui to tell DM that player has written
if debug then
log(playerName:lower(), "setting class to done, " .. initiatives[player.color].i)
end
local obj = getObjectFromGUID(initiatives[player.color].t)
obj.editInput({index = 0, value = playerName .. "\n" .. initiatives[player.color].i})
initiatives[player.color].d = true
end
end
function submitChange(player, value, obj)
-- this activates while the player is writing on its little box
initiatives[player.color].i = value
end
function isInCombat()
return self.UI.getAttribute("widget", "active") == "true"
end
function getPlayerByColor(color)
for k, v in pairs(_defaults.playersColors) do
if v == color then
return k
end
end
return nil
end
--#endregion
-- #region breaker
function UI_SideToggle()
local offset = self.UI.getAttribute("TopButton", "offsetXY")
local closed = offset == "75 5"
if closed then
-- to open
-- button stuff
self.UI.setAttribute("TopButton", "offsetXY", "75 -182")
self.UI.setAttribute("TopButton", "text", "▲")
self.UI.setAttribute("TopButton", "textColor", "#f0f0f0") -- dno why i gotta do this, but alas, shitty program
-- panel stuff
self.UI.setAttribute("TopPanel", "active", "true")
else
-- to close
-- button stuff
self.UI.setAttribute("TopButton", "offsetXY", "75 5")
self.UI.setAttribute("TopButton", "text", "▼")
self.UI.setAttribute("TopButton", "textColor", "#f0f0f0") -- dno why i gotta do this, but alas, shitty program
-- panel stuff
self.UI.setAttribute("TopPanel", "active", "false")
end
end
local _MassField = ""
function UI_MassCalculate(player, request, id)
local half = string.find(id, "Half") ~= nil
local text = tonumber(_MassField)
if half then
text = math.floor(text / 2)
end
local objs = Player[player.color].getSelectedObjects()
for i = 1, #objs do
local gm = objs[i].getGMNotes()
if gm == "monster_token" or gm == "boss_token" then
local val = (id == "MassDamage" or id == "MassDamageHalf") and text * -1 or text
local t = string.gsub(id, "Mass", "")
t = string.gsub(t, "Half", "")
objs[i].call(
"GlobalCalculate",
{
input = val,
t = t
}
)
end
end
end
function UI_UpdateMassHp(player, value)
_MassField = value
end
local _MassModifier = ""
function UI_MassRoll(player, request, id)
local mode = ""
if id == "MassRollAdv" then
mode = "adv"
elseif id == "MassRollDis" then
mode = "dis"
else
mode = nil
end
local text = tonumber(_MassModifier)
if not text then
text = 0
end
local objs = Player[player.color].getSelectedObjects()
for i = 1, #objs do
local gm = objs[i].getGMNotes()
if gm == "monster_token" or gm == "boss_token" then
Wait.time(
function()
objs[i].call("GlobalRoll", {input = text, mode = mode})
end,
math.random(0.2, 0.8)
)
end
end
end
function UI_UpdateMassMod(player, value)
_MassModifier = value
end
-- #endregion
--#region average hud
local _average_notecard = nil
local averages = {}
function showHuds(params)
-- i'll receive params which is all the colors that i have to show the huds of
_average_notecard = params.notecard
for i = 1, #params.players do
self.UI.setAttribute(params.players[i]:lower() .. "_average_box", "active", "true")
averages = {}
end
end
function submitAverage(player, request)
if not averages[player.color] or averages[player.color] == "" then
broadcastToColor("You need to insert a number in the box!", player.color, Color.Red)
return
end
-- i'll receive the info for the notecard to read
self.UI.setAttribute(player.color:lower() .. "_average_box", "active", "false")
self.UI.setAttribute(player.color:lower() .. "_average", "text", "")
local notecard = getObjectFromGUID(_average_notecard)
if notecard then
local crit = nil
if request ~= "-1" then
crit = request == "crit" and 20 or 1
end
log(crit)
notecard.call(
"setData",
{
color = player.color,
avg = averages[player.color],
crit = crit
}
)
end
end
function updateAverage(player, value, obj)
averages[player.color] = value
end
--#endregion
--#region epic-reminder
local _epicBoons = 0
local _initialized = false
function initEpicBoons()
_epicBoons = 0
ShowAllReminders()
_initialized = true
end
function resetEpicBoons()
local colors = {"White", "Teal", "Brown", "Blue", "Red", "Purple", "Orange", "Pink", "Yellow", "Green"}
for _, color in ipairs(colors) do
self.UI.setAttribute(color .. "_Epic_Reminder", "active", false)
self.UI.setAttribute(color .. "_Epic_Boon_1", "active", false)
self.UI.setAttribute(color .. "_Epic_Boon_2", "active", false)
self.UI.setAttribute(color .. "_Epic_Boon_3", "active", false)
self.UI.setAttribute(color .. "_Epic_Boon_4", "active", false)
self.UI.setAttribute(color .. "_Epic_Boon_5", "active", false)
self.UI.setAttribute(color .. "_Epic_Boon_6", "active", false)
end
self.UI.setAttribute("Epic_Glow", "active", false)
_initialized = false
end
function UIEpicReminderOpen(player)
EpicReminderBreaker(true, player.color)
end
function UIEpicReminderClose(player)
EpicReminderBreaker(false, player.color)
end
function ShowAllReminders()
local colors = {"White", "Teal", "Brown", "Blue", "Red", "Purple", "Orange", "Pink", "Yellow", "Green"}
for _, color in ipairs(colors) do
self.UI.setAttribute(color .. "_Epic_Reminder", "active", true)
EpicReminderBreaker(false, color)
end
self.UI.setAttribute("Epic_Glow", "active", true)
end
function EpicReminderBreaker(open, color)
if open then
self.UI.setAttribute(color .. "_Closed_Reminder", "active", false)
self.UI.setAttribute(color .. "_Opened_Reminder", "active", true)
else
self.UI.setAttribute(color .. "_Closed_Reminder", "active", true)
self.UI.setAttribute(color .. "_Opened_Reminder", "active", false)
end
end
function EpicReminderHighlight(color)
for i = 1, 6, 1 do
if i % 2 == 1 then
Wait.time(
function()
self.UI.setAttribute("Epic_Glow", "color", "#B349FD")
end,
0.1 * i
)
else
Wait.time(
function()
self.UI.setAttribute("Epic_Glow", "color", "#A52CFA")
end,
0.1 * i
)
end
end
end
function AddBoon(params)
if not _initialized then
initEpicBoons()
end
local boon = params.boon
local tooltip = params.tooltip
_epicBoons = _epicBoons + 1
if tooltip ~= nil and tooltip ~= "" then
boon = boon .. " ⓘ"
end
local colors = {"White", "Teal", "Brown", "Blue", "Red", "Purple", "Orange", "Pink", "Yellow", "Green"}
for _, color in ipairs(colors) do
local height = 80 * _epicBoons
if height > 320 then
height = 320
end
self.UI.setAttribute(color .. "_Epic_Boons", "height", height)
self.UI.setAttribute(color .. "_Epic_Boon_" .. _epicBoons, "active", true)
if tooltip ~= nil then
self.UI.setAttribute(color .. "_Epic_Boon_" .. _epicBoons, "tooltip", tooltip)
end
self.UI.setAttribute(color .. "_Epic_Boon_" .. _epicBoons, "text", boon)
EpicReminderBreaker(true, color)
EpicReminderHighlight(color)
end
end
--#endregion
function printTable(t)
local printTable_cache = {}
local function sub_printTable(t, indent)
if (printTable_cache[tostring(t)]) then
print(indent .. "*" .. tostring(t))
else
printTable_cache[tostring(t)] = true
if (type(t) == "table") then
for pos, val in pairs(t) do
if (type(val) == "table") then
print(indent .. "[" .. pos .. "] => " .. tostring(t) .. " {")
sub_printTable(val, indent .. string.rep(" ", string.len(pos) + 8))
print(indent .. string.rep(" ", string.len(pos) + 6) .. "}")
elseif (type(val) == "string") then
print(indent .. "[" .. pos .. '] => "' .. val .. '"')
else
print(indent .. "[" .. pos .. "] => " .. tostring(val))
end
end
else
print(indent .. tostring(t))
end
end
end
if (type(t) == "table") then
print(tostring(t) .. " {")
sub_printTable(t, " ")
print("}")
else
sub_printTable(t, " ")
end
end
function mysplit(inputstr, sep)
if sep == nil then
sep = "%s"
end
local t = {}
i = 1
for str in string.gmatch(inputstr, "([^" .. sep .. "]+)") do
t[i] = str
i = i + 1
end
return t
end
| 31.132184
| 120
| 0.499323
|
da6173c414ce2c90dfb0bbbddd62e418d75c7fbb
| 778
|
php
|
PHP
|
src/Providers/RetrieverServiceProvider.php
|
nineoclocksomewhere/laravel-retriever
|
f733ebc11cee377e6b039d2fde23579b427f3a3c
|
[
"MIT"
] | 2
|
2021-09-23T07:39:08.000Z
|
2021-09-23T07:39:11.000Z
|
src/Providers/RetrieverServiceProvider.php
|
nineoclocksomewhere/laravel-retriever
|
f733ebc11cee377e6b039d2fde23579b427f3a3c
|
[
"MIT"
] | null | null | null |
src/Providers/RetrieverServiceProvider.php
|
nineoclocksomewhere/laravel-retriever
|
f733ebc11cee377e6b039d2fde23579b427f3a3c
|
[
"MIT"
] | null | null | null |
<?php
namespace Nocs\Retriever\Providers;
use Illuminate\Support\ServiceProvider;
use Nocs\Retriever\Support\RetrieverManager;
use Nocs\Retriever\Support\Facades\Retriever;
/**
* BackpackServiceProvider class
*/
class RetrieverServiceProvider extends ServiceProvider
{
/**
* Register the service provider.
*
* @return void
*/
public function register()
{
$this->app->singleton('retriever', function ($app) {
return new RetrieverManager($app);
});
}
/**
* [boot description]
* @return [type] [description]
*/
public function boot()
{
Retriever::loadRetrieversFrom(app_path('Retrievers'), 'app');
Retriever::loadRetrieversFrom(app_path('Cache'), 'app');
}
}
| 18.97561
| 69
| 0.633676
|
078331678b6dd263dcf5c30c38712654e757402a
| 1,223
|
rb
|
Ruby
|
lib/fastlane/plugin/veepio/actions/vpo_copy_files.rb
|
veepionyc/fastlane-plugin-veepio
|
33579745942a1d72fcceb5784d1f2a7e3ac896d4
|
[
"MIT"
] | null | null | null |
lib/fastlane/plugin/veepio/actions/vpo_copy_files.rb
|
veepionyc/fastlane-plugin-veepio
|
33579745942a1d72fcceb5784d1f2a7e3ac896d4
|
[
"MIT"
] | null | null | null |
lib/fastlane/plugin/veepio/actions/vpo_copy_files.rb
|
veepionyc/fastlane-plugin-veepio
|
33579745942a1d72fcceb5784d1f2a7e3ac896d4
|
[
"MIT"
] | null | null | null |
require "java-properties"
module Fastlane
module Actions
class VpoCopyFilesAction < Action
def self.run(params)
_from = params[:from]
_to = params[:to]
_preserve = false
_dereference_root = false
_remove_destination = true
FileUtils.copy_entry _from, _to, _preserve, _dereference_root, _remove_destination
UI.message("copied: #{_from} to: #{_to}")
end
def self.description
"get Android project version code in version.properties file for gradle project"
end
def self.available_options
[
FastlaneCore::ConfigItem.new(key: :from,
description: "source file or directory",
is_string: true),
FastlaneCore::ConfigItem.new(key: :to,
description: "destination file or directory",
is_string: true)
]
end
def self.authors
# So no one will ever forget your contribution to fastlane :) You are awesome btw!
["foundry"]
end
def self.is_supported?(platform)
true
end
end
end
end
| 27.177778
| 90
| 0.55601
|
7fa8b4d63f62a068e9ad5055ece39006dd61e51f
| 8,599
|
dart
|
Dart
|
flutter_shop/lib/User/login_page.dart
|
zhaxling/flutter_shop
|
b6e96af3f8e7b24148b13a65e0be858ff41b1123
|
[
"MIT"
] | null | null | null |
flutter_shop/lib/User/login_page.dart
|
zhaxling/flutter_shop
|
b6e96af3f8e7b24148b13a65e0be858ff41b1123
|
[
"MIT"
] | null | null | null |
flutter_shop/lib/User/login_page.dart
|
zhaxling/flutter_shop
|
b6e96af3f8e7b24148b13a65e0be858ff41b1123
|
[
"MIT"
] | null | null | null |
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_shop/Router/app.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:toast/toast.dart';
import 'UserManager.dart';
import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
class LoginPage extends StatefulWidget {
@override
_LoginPageState createState() {
return _LoginPageState();
}
}
class _LoginPageState extends State<LoginPage> {
TextEditingController _pwdEditController;
TextEditingController _userNameEditController;
final FocusNode _userNameFocusNode = FocusNode();
final FocusNode _pwdFocusNode = FocusNode();
@override
void initState() {
super.initState();
_pwdEditController = TextEditingController();
_userNameEditController = TextEditingController();
_pwdEditController.addListener(() => setState(() => {}));
_userNameEditController.addListener(() => setState(() => {}));
}
@override
Widget build(BuildContext context) {
// TODO: implement build
return Scaffold(
appBar: AppBar(
backgroundColor: Colors.blue[400],
elevation: 0,
),
body: SingleChildScrollView(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
buildTopWidget(context),
SizedBox(
height: 80,
),
buildEditWidget(context),
buildLoginButton()
],
),
),
);
}
/// 头部
Widget buildTopWidget(BuildContext context) {
double height = 200.0;
double width = MediaQuery.of(context).size.width;
return Container(
width: width,
height: height,
color: Colors.blue[400],
child: Stack(
overflow: Overflow.visible, // 超出部分显示
children: <Widget>[
Positioned(
left: (width - 90) / 2.0,
top: height - 45,
child: Container(
width: 90.0,
height: 90.0,
decoration: BoxDecoration(
///阴影
boxShadow: [
BoxShadow(color: Theme.of(context).cardColor, blurRadius: 4.0)
],
///形状
shape: BoxShape.circle,
///图片
image: DecorationImage(
fit: BoxFit.cover,
image: NetworkImage(
'https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1569298229946&di=ea4ffb2b140ef40035772bbcee7bbdd5&imgtype=0&src=http%3A%2F%2Fcimg2.163.com%2Fcatchimg%2F20090909%2F8112139_3.jpg'),
),
),
),
)
],
),
);
}
Widget buildEditWidget(BuildContext context) {
return Container(
margin: EdgeInsets.only(left: 15, right: 15),
child: Column(
children: <Widget>[
buildLoginNameTextField(),
SizedBox(height: 20.0),
buildPwdTextField(),
],
),
);
}
Widget buildLoginNameTextField() {
return Container(
height: 40,
decoration: BoxDecoration(
color: Colors.grey[200],
borderRadius: BorderRadius.all(Radius.circular(20.0)),
),
child: Stack(
children: <Widget>[
Positioned(
left: 16,
top: 11,
width: 18,
height: 18,
child: Image.asset('images/login_user.png'),
),
Positioned(
left: 45,
top: 10,
bottom: 10,
width: 1,
child: Container(
color: Colors.black,
),
),
Positioned(
left: 55,
right: 10,
top: 10,
height: 30,
child: TextField(
controller: _userNameEditController,
focusNode: _userNameFocusNode,
decoration: InputDecoration(
hintText: "请输入用户名",
border: InputBorder.none,
),
style: TextStyle(fontSize: 14),
),
)
],
),
);
}
Widget buildPwdTextField() {
return Container(
height: 40,
decoration: BoxDecoration(
color: Colors.grey[200],
borderRadius: BorderRadius.all(Radius.circular(20.0)),
),
child: Stack(
children: <Widget>[
Positioned(
left: 16,
top: 11,
width: 18,
height: 18,
child: Image.asset('images/login_pwd.png'),
),
Positioned(
left: 45,
top: 10,
bottom: 10,
width: 1,
child: Container(
color: Colors.black,
),
),
Positioned(
left: 55,
right: 10,
top: 10,
height: 30,
child: TextField(
controller: _pwdEditController,
focusNode: _pwdFocusNode,
decoration: InputDecoration(
hintText: "请输入密码",
border: InputBorder.none,
),
style: TextStyle(fontSize: 14),
obscureText: true, /// 设置密码
),
)
],
));
}
Widget buildLoginButton(){
return Container(
margin: EdgeInsets.only(top: 40,left: 10,right: 10),
padding: EdgeInsets.all(0),
width: MediaQuery.of(context).size.width-20,
height: 40,
child: RaisedButton(
onPressed: () {
if(checkInput()){
UserManager.loginSuccess();
Fluttertoast.showToast(
msg: "登录成功",
gravity: ToastGravity.CENTER,
timeInSecForIosWeb: 2,
textColor: Colors.white,
fontSize: 14.0
);
}
},
child: Text("登录"),
color: Colors.blue[400],
textColor: Colors.white,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.all(Radius.circular(20.0)),
),
),
);
}
bool checkInput(){
if(_userNameEditController.text.length == 0){
Fluttertoast.showToast(
msg: "请输入用户名",
gravity: ToastGravity.CENTER,
timeInSecForIosWeb: 2,
textColor: Colors.white,
fontSize: 14.0
);
// Toast.show('请输入用户名', context);
return false;
}
else if (_pwdEditController.text.length == 0){
Fluttertoast.showToast(
msg: "请输入密码",
gravity: ToastGravity.CENTER,
timeInSecForIosWeb: 2,
textColor: Colors.white,
fontSize: 14.0
);
// Toast.show('请输入密码', context);
return false;
}
return true;
}
}
//class LoginPage extends StatelessWidget {
// @override
// Widget build(BuildContext context) {
// return Container(
// width: ScreenUtil.screenWidth,
// height: ScreenUtil.screenHeight,
// color: Colors.white,
// child: Column(
// children: <Widget>[
// GestureDetector(
// onTap: (){
// print("登录");
// UserManager.loginSuccess();
// },
// child: Container(
// width: ScreenUtil.screenWidth,
// height: 38,
// margin: EdgeInsets.only(top: 500),
// color: Colors.orange,
// child: Center(child: Text('登录',style: TextStyle(fontSize: 20),),),
// ),
// ),
// GestureDetector(
// onTap: (){
// UserManager.logoutSuccess();
// },
// child: Container(
// width: ScreenUtil.screenWidth,
// height: 38,
// margin: EdgeInsets.only(top: 20),
// color: Colors.orange,
// child: Center(child: Text('退出登录',style: TextStyle(fontSize: 20),),),
// ),
// ),
// GestureDetector(
// onTap: (){
// Application.router.pop(context);
// },
// child: Container(
// width: ScreenUtil.screenWidth,
// height: 38,
// margin: EdgeInsets.only(top: 20),
// color: Colors.orange,
// child: Center(child: Text('关闭',style: TextStyle(fontSize: 20),),),
// ),
// ),
// ],
// ),
// );
// }
//}
| 26.956113
| 222
| 0.505175
|
2ccd9591a0c7138f058867bb37ca85d4c091edf6
| 842
|
py
|
Python
|
day1/day1.py
|
chrisb87/advent_of_code_2016
|
668a7c5e3f2aac036dcf0091ca62a47cb0c54ba8
|
[
"Unlicense"
] | 1
|
2016-12-07T20:28:12.000Z
|
2016-12-07T20:28:12.000Z
|
day1/day1.py
|
chrisb87/advent_of_code_2016
|
668a7c5e3f2aac036dcf0091ca62a47cb0c54ba8
|
[
"Unlicense"
] | null | null | null |
day1/day1.py
|
chrisb87/advent_of_code_2016
|
668a7c5e3f2aac036dcf0091ca62a47cb0c54ba8
|
[
"Unlicense"
] | null | null | null |
def solve(moves, stop_on_second_visit = False):
location = [0,0]
visited = set(tuple(location))
facing = 0
turns = {0: (0, 1), 1: (1, 0), 2: (0, -1), 3: (-1, 0)}
for move in moves:
if move[0] == 'R':
facing = (facing + 1) % 4
elif move[0] == 'L':
facing = (facing - 1) % 4
for step in xrange(int(move[1:])):
location[0] += turns[facing][0]
location[1] += turns[facing][1]
if stop_on_second_visit:
location_key = tuple(location)
if location_key in visited:
return sum(map(abs, location))
else:
visited.add(location_key)
return sum(map(abs, location))
def get_moves():
return open('day1/input.txt').read().replace('\n', '').split(', ')
def solve_part_1():
return solve(get_moves())
def solve_part_2():
return solve(get_moves(), True)
if __name__ == '__main__':
print solve_part_2()
| 22.157895
| 67
| 0.619952
|
5db2c6544db63edb6f90ac06ac4cdcc4bd2e6add
| 2,796
|
cpp
|
C++
|
src/vm/systemCalls.optionals.cpp
|
DosWorld/tmbasic
|
99bd593bb074df6af83d952259b5eb81588f1e3f
|
[
"MIT"
] | 1
|
2022-01-29T05:45:46.000Z
|
2022-01-29T05:45:46.000Z
|
src/vm/systemCalls.optionals.cpp
|
DosWorld/tmbasic
|
99bd593bb074df6af83d952259b5eb81588f1e3f
|
[
"MIT"
] | null | null | null |
src/vm/systemCalls.optionals.cpp
|
DosWorld/tmbasic
|
99bd593bb074df6af83d952259b5eb81588f1e3f
|
[
"MIT"
] | null | null | null |
#include "systemCall.h"
#include "Error.h"
#include "Optional.h"
namespace vm {
static std::pair<const ValueOptional*, const ObjectOptional*> valueOrObjectOptional(const Object& object) {
const auto* valueOptional = dynamic_cast<const ValueOptional*>(&object);
if (valueOptional != nullptr) {
return { valueOptional, nullptr };
}
const auto* objectOptional = dynamic_cast<const ObjectOptional*>(&object);
if (objectOptional != nullptr) {
return { nullptr, objectOptional };
}
throw Error(
ErrorCode::kInternalTypeConfusion,
fmt::format(
"Internal type confusion error. Target is neither {} nor {}.", NAMEOF_TYPE(ValueOptional),
NAMEOF_TYPE(ObjectOptional)));
}
void initSystemCallsOptionals() {
initSystemCall(SystemCall::kHasValue, [](const auto& input, auto* result) {
const auto valueOrObject = valueOrObjectOptional(input.getObject(-1));
const auto* valueOptional = valueOrObject.first;
const auto* objectOptional = valueOrObject.second;
result->returnedValue.setBoolean(
valueOptional != nullptr ? valueOptional->item.has_value() : objectOptional->item.has_value());
});
initSystemCall(SystemCall::kObjectOptionalNewMissing, [](const auto& /*input*/, auto* result) {
result->returnedObject = boost::make_local_shared<ObjectOptional>();
});
initSystemCall(SystemCall::kObjectOptionalNewPresent, [](const auto& input, auto* result) {
result->returnedObject = boost::make_local_shared<ObjectOptional>(input.getObjectPtr(-1));
});
initSystemCall(SystemCall::kValueOptionalNewMissing, [](const auto& /*input*/, auto* result) {
result->returnedObject = boost::make_local_shared<ValueOptional>();
});
initSystemCall(SystemCall::kValueOptionalNewPresent, [](const auto& input, auto* result) {
result->returnedObject = boost::make_local_shared<ValueOptional>(input.getValue(-1));
});
initSystemCall(SystemCall::kValue, [](const auto& input, auto* result) {
const auto valueOrObject = valueOrObjectOptional(input.getObject(-1));
const auto* valueOptional = valueOrObject.first;
const auto* objectOptional = valueOrObject.second;
if (valueOptional != nullptr) {
if (!valueOptional->item.has_value()) {
throw Error(ErrorCode::kValueNotPresent, "Optional value is not present.");
}
result->returnedValue = *valueOptional->item;
} else {
if (!objectOptional->item.has_value()) {
throw Error(ErrorCode::kValueNotPresent, "Optional value is not present.");
}
result->returnedObject = *objectOptional->item;
}
});
}
} // namespace vm
| 39.380282
| 107
| 0.664521
|
f4e9b18e35046e5a71ab16d22584a29544ce7fc7
| 61
|
ts
|
TypeScript
|
src/dtos/bonus/redeemVoucher.request.dto.ts
|
Zweer/BigBangEmpireBot
|
d0fd04118822bf0eb6fffd271ce944f0475c5998
|
[
"MIT"
] | 1
|
2019-10-31T13:49:58.000Z
|
2019-10-31T13:49:58.000Z
|
src/dtos/bonus/redeemVoucher.request.dto.ts
|
Zweer/BigBangEmpireBot
|
d0fd04118822bf0eb6fffd271ce944f0475c5998
|
[
"MIT"
] | 11
|
2018-09-30T15:17:00.000Z
|
2022-02-13T11:52:26.000Z
|
src/dtos/bonus/redeemVoucher.request.dto.ts
|
Zweer/BigBangEmpireBot
|
d0fd04118822bf0eb6fffd271ce944f0475c5998
|
[
"MIT"
] | 6
|
2018-06-18T18:43:46.000Z
|
2021-03-03T21:48:43.000Z
|
export interface RedeemVoucherRequestDto {
code: string;
}
| 15.25
| 42
| 0.786885
|
eb626f05c988b25352421667faca979b2315cc0c
| 20,985
|
css
|
CSS
|
gaf-cloud/gaf-ops/gaf-storage/src/main/frontend/assets/css/common.css
|
SuperMap/GAF
|
cd9564ef554f3dd589c94319092611171ff2395f
|
[
"Apache-2.0"
] | 17
|
2021-04-26T01:07:34.000Z
|
2022-03-31T08:21:26.000Z
|
gaf-cloud/gaf-ops/gaf-storage/src/main/frontend/assets/css/common.css
|
SuperMap/GAF
|
cd9564ef554f3dd589c94319092611171ff2395f
|
[
"Apache-2.0"
] | 7
|
2021-04-26T07:32:12.000Z
|
2021-05-13T03:04:10.000Z
|
gaf-cloud/gaf-ops/gaf-storage/src/main/frontend/assets/css/common.css
|
SuperMap/GAF
|
cd9564ef554f3dd589c94319092611171ff2395f
|
[
"Apache-2.0"
] | 21
|
2021-01-05T05:42:49.000Z
|
2021-08-06T08:53:32.000Z
|
* {
padding: 0;
margin: 0;
}
/* ----布局---- */
/* 页面 背景 */
.app-container {
height: 100%;
border: none;
background-color: rgb(234, 239, 245);
}
.ant-tabs-nav .ant-tabs-tab-active {
color: #329DFF;
}
/* 页面 左侧栏 树组件 */
.page-left {
height: 88vh;
width: 16%;
float: left;
margin: 12px 8px 10px 15px;
padding: 12px 8px 8px 8px;
background-color: #fff;
/* border-top-right-radius: 10px;
border-bottom-right-radius: 10px; */
overflow: auto;
}
/* 同一页面 内容隐藏 达到跳转效果 */
.resource-left {
height: 97vh;
width: 16%;
float: left;
margin: 0 8px 0 0;
padding: 12px 8px 8px 8px;
background-color: #fff;
/* border-top-right-radius: 10px;
border-bottom-right-radius: 10px; */
overflow: auto;
}
/* 页面 右侧 主体内容 */
.page-right {
margin: 12px 0 0 0;
padding: 15px;
height: 88vh;
width: 81%;
float: left;
/* border-top-left-radius: 10px;
border-bottom-left-radius: 10px; */
background-color: #fff;
}
/* 单页面 无左右栏 */
.page-single {
float: left;
background-color: #fff;
margin: 10px 0 1% 1%;
/* border-radius: 5px; */
height: 86vh;
width: 98%;
}
.ant-layout {
height: 100vh;
}
/* 右侧 主体 置顶功能键 */
.btn-fun {
border: 1px solid rgb(24, 144, 255);
/* border-radius: 3px; */
background-color: white;
margin-top: 16px;
height: 36px;
width: 116px;
cursor: pointer;
font-size: 16px;
}
.btn-8 {
margin-right: 8px;
}
.btn-16 {
margin-right: 16px;
/* margin-left: 3%; */
}
.blue {
background-color: rgb(24, 144, 255);
color: white;
}
.seaBlue {
background-color: rgb(38, 188, 213);
}
.lightYellow {
background-color: rgb(214, 200, 75);
}
.lightYellow:hover {
background-color: rgb(192, 180, 69);
}
.seaBlue:hover {
background-color: rgb(36, 161, 184);
}
.red {
border: none;
background-color: rgb(196, 47, 85);
}
.gray {
background-color: rgba(84, 92, 100, .8);
}
.gray:hover {
background-color: rgb(84, 92, 100);
}
/* .red:hover {
border: none;
background-color: rgb(191, 46, 74) !important;
}
.blue:hover {
border: none;
background-color: rgb(30, 108, 253) !important;
}
.btn-fun:hover {
border: none;
transform: translateY(2px);
color: white;
box-shadow: 0 0 0 rgba(128, 128, 128, 0.3);
} */
/*for IE*/
:focus {
outline: none;
}
/*for mozilla*/
::-moz-focus-inner {
border-color: transparent;
}
.margin-15 {
margin: 15px 0 15px 15px;
}
.btn-margin {
text-align: center;
margin: 15px 0;
}
/* 模态框 主体内容 位置调整 */
.page-modal-box {
margin-top: 10px;
padding-left: 70px;
}
/* 搜索框 */
.search-position {
margin-top: 16px;
/* margin-right: 3%; */
width: 210px;
height: 40px;
float: right;
}
.ant-input-affix-wrapper .ant-input:not(:last-child) {
/* padding-right: 65px; */
text-align: left;
}
.ant-pagination-item-active:focus a,
.ant-pagination-item-active:hover a {
color: #329DFF;
}
/* .ant-input {
margin-top: 16px;
margin-right: 3%;
width: 210px;
height: 40px;
float: right;
} */
/* .btn-search {
cursor: pointer;
border-top-right-radius: 5px;
border-bottom-right-radius: 5px;
width: 66px;
height: 40px;
background-color: rgb(47, 117, 249);
color: white;
border: none;
box-shadow: 3px 3px 0 rgba(128, 128, 128, 0.2);
}
.btn-search:hover {
color: white;
transform: translateY(2px);
background-color: rgb(30, 108, 253);
border: none;
box-shadow: 0 0 0 transparent;
} */
/* 模态框中的搜索 size=small */
.model-search {
cursor: pointer;
border-top-right-radius: 5px;
border-bottom-right-radius: 5px;
width: 60px;
height: 32px;
background-color: rgb(47, 117, 249);
color: white;
border: none;
box-shadow: 3px 3px 0 rgba(128, 128, 128, 0.2);
}
.model-search:hover {
color: white;
transform: translateY(2px);
background-color: rgb(30, 108, 253);
border: none;
box-shadow: 0 0 0 transparent;
}
/* 搜索框 */
.ant-input-group .ant-input {
text-align: center;
/* margin-left: 410px; */
/* width: 250px; */
border: 1px solid rgb(217, 217, 217);
/* border-radius: 5px; */
box-shadow: 3px 3px 0 rgba(128, 128, 128, 0.1);
}
.main-top {
margin-left: 16px;
}
/* 表格样式 */
/* .table tr:nth-child(n) {
background: rgb(249, 249, 249);
}
.table tr td {
word-wrap: break-word;
}
.table tr:nth-child(2n+1) {
background: white;
}
.ant-table-thead tr {
background-color: rgb(240, 240, 240) !important;
}
.ant-table-thead tr th {
text-align: center;
font-weight: bolder;
font-size: 16px;
color: rgb(85, 85, 85);
}
.ant-table-body {
margin: 0 !important;
overflow: auto;
}
table {
white-space: nowrap;
} */
/* 详情按钮 */
.btn-view {
border: 1px solid transparent;
padding: 2px 5px;
/* border-radius: 5px; */
color: #fff;
background-color: rgb(94, 192, 94);
}
.btn-view:hover {
background-color: rgb(160, 191, 124);
color: rgb(254, 254, 254);
}
/* 编辑按钮 */
.btn-edit {
border: 1px solid transparent;
padding: 2px 5px;
/* border-radius: 5px; */
color: #fff;
background-color: rgb(74, 175, 205);
}
.btn-edit:hover {
background-color: rgb(95, 192, 221);
color: white;
}
/* 删除按钮 */
.btn-del {
background-color: rgb(216, 77, 72);
border: 1px solid transparent;
padding: 2px 5px;
/* border-radius: 5px; */
color: #fff;
}
.btn-del:hover {
background-color: rgb(250, 101, 95);
color: white;
}
/* 配置按钮 */
.btn-configure {
background-color: rgb(146, 146, 146);
border: 1px solid transparent;
padding: 2px 5px;
/* border-radius: 5px; */
color: #fff;
}
.btn-configure:hover {
background-color: rgba(146, 146, 146, 0.7);
color: white;
}
/* 编码按钮 */
.btn-code {
background-color: rgb(221, 171, 92);
border: 1px solid transparent;
padding: 2px 5px;
/* border-radius: 5px; */
color: #fff;
}
.btn-code:hover {
background-color: rgba(221, 171, 92, 0.7);
color: white;
}
/* 预览按钮 */
.btn-preview {
background-color: rgb(152, 184, 63);
border: 1px solid transparent;
padding: 2px 5px;
/* border-radius: 5px; */
color: #fff;
}
.btn-preview:hover {
background-color: rgba(174, 209, 77, 0.7);
color: white;
}
/* 发布按钮 */
.btn-release {
background-color: rgb(254, 242, 166);
border: 1px solid transparent;
padding: 2px 5px;
/* border-radius: 5px; */
color: #fff;
}
.btn-release:hover {
background-color: rgba(254, 242, 166, 0.5);
color: white;
}
/* 成员按钮 */
.btn-human {
background-color: rgb(0, 188, 213);
border: 1px solid transparent;
padding: 2px 5px;
/* border-radius: 5px; */
color: #fff;
}
.btn-human:hover {
background-color: rgba(0, 188, 213, 0.7);
color: white;
}
/* 项目按钮 */
.btn-project {
background-color: rgb(255, 171, 65);
border: 1px solid transparent;
padding: 2px 5px;
/* border-radius: 5px; */
color: #fff;
}
.btn-project:hover {
background-color: rgba(255, 171, 65, 0.7);
color: white;
}
/* 启用按钮 */
.btn-restart {
background-color: rgb(160, 212, 123);
border: 1px solid transparent;
padding: 2px 5px;
/* border-radius: 5px; */
color: #fff;
}
.btn-restart:hover {
background-color: rgb(110, 159, 91);
color: white;
}
/* 同步按钮 */
.btn-sync {
background-color: rgb(245, 166, 77);
border: 1px solid transparent;
padding: 2px 5px;
/* border-radius: 5px; */
color: #fff;
}
.btn-sync:hover {
background-color: rgb(196, 137, 70);
color: white;
}
/* 全部管理员按钮 */
.btn-admin {
background-color: rgb(66, 210, 134);
border: 1px solid transparent;
padding: 2px 5px;
/* border-radius: 5px; */
color: #fff;
}
.btn-admin:hover {
background-color: rgb(57, 173, 112);
color: white;
}
/* 单页面 表单 */
.web-form {
padding: 5% 0 0 15%;
}
/* |样式 */
.vertical-line {
color: rgb(47, 117, 249);
font-weight: bolder;
font-size: 17px;
}
.text-bolder {
font-weight: 1000;
font-size: 16px;
}
.btn-style {
margin: 0 auto;
width: 200px;
padding: 15px;
}
/* 保存 */
.btn-ok {
cursor: pointer;
width: 100px;
height: 32px;
/* border-radius: 5px; */
box-shadow: 3px 3px 0 rgba(47, 117, 249, 0.3);
border: none;
color: white;
background-color: rgb(47, 117, 249);
}
.btn-ok:hover {
background-color: rgb(38, 107, 236);
color: white;
box-shadow: 0 0 0 transparent;
transform: translateY(2px);
}
/* 抽屉 确认 */
.draws-ok {
cursor: pointer;
width: 66px;
height: 32px;
/* border-radius: 5px; */
box-shadow: 3px 3px 0 rgba(217, 217, 217, 0.3);
border: none;
color: white;
background-color: rgb(84, 92, 100);
}
.draws-ok:hover {
background-color: rgba(84, 92, 100, 0.8);
color: white;
box-shadow: 0 0 0 transparent;
transform: translateY(2px);
}
/* 抽屉 取消 */
.draws-cancel {
cursor: pointer;
width: 66px;
height: 32px;
/* border-radius: 5px; */
box-shadow: 3px 3px 0 rgba(217, 217, 217, 0.3);
border: none;
color: white;
background-color: rgb(132, 133, 135);
}
.draws-cancel:hover {
background-color: rgba(132, 133, 135, 0.8);
color: white;
box-shadow: 0 0 0 transparent;
transform: translateY(2px);
}
/* 删除 */
.btn-cancel {
cursor: pointer;
width: 100px;
height: 32px;
/* border-radius: 5px; */
box-shadow: 3px 3px 0 rgba(47, 117, 249, 0.3);
color: rgb(47, 117, 249);
border: 1px solid rgb(47, 117, 249);
}
.btn-cancel:hover {
border: 1px solid rgb(38, 107, 236);
color: rgb(38, 107, 236);
box-shadow: 0 0 0 transparent;
transform: translateY(2px);
}
.float-left {
float: left;
}
.float-right {
float: right;
}
/* 确认 模态框*/
.submit-gray {
cursor: pointer;
color: white;
border: none;
width: 80px;
height: 32px;
background: #329DFF;
border-radius: 4px;
}
.submit-gray:hover {
background-color: rgba(10, 126, 241, 0.9);
color: white;
box-shadow: 0 0 0 transparent;
transform: translateY(2px);
}
/* 取消 模态框*/
.cancel-modal {
cursor: pointer;
color: #000;
width: 80px;
height: 32px;
background: #FFFFFF;
border: 1px solid #A0A0A0;
border-radius: 4px;
}
.cancel-modal:hover {
background-color: rgb(133, 131, 131);
color: white;
box-shadow: 0 0 0 transparent;
transform: translateY(2px);
}
.margin410 {
margin: 15px 0 0 410px;
}
/* 模态框 title下线 */
.modal-line {
/* border-bottom: 1px solid #E5E5E5;
padding: 15px 10px; */
display: table-cell;
vertical-align: middle;
}
/* 模态框 关闭按钮 */
button.ant-modal-close {
/* margin-top: 16px; */
color: #fff;
font-weight: bolder;
}
button.ant-modal-close:hover {
color: #ccc;
}
/* 模态框头部样式*/
.ant-modal-header {
background: #20252E;
}
.ant-modal-title {
color: #fff;
}
/* 目录树 标题 */
.tree-catalog {
border-bottom: 1px solid rgb(232, 232, 232);
margin-bottom: 10px;
height: 50px;
line-height: 50px;
font-size: 16px;
font-weight: bolder;
background-color: rgb(249, 249, 249);
border-top-left-radius: 8px;
border-top-right-radius: 8px;
}
/* tabs 标签页样式 tab-bar-style */
/* .ant-tabs-tab {
background-color: rgb(249, 249, 249);
border-top-left-radius: 8px;
border-top-right-radius: 8px;
font-weight: 500;
} */
/* ----------------------- */
/*定义滚动条高宽及背景 高宽分别对应横竖滚动条的尺寸*/
::-webkit-scrollbar {
width: 4px;
height: 2px;
background-color: #F5F5F5;
}
/*定义滚动条轨道 内阴影+圆角*/
::-webkit-scrollbar-track {
box-shadow: inset 0 0 3px rgba(0, 0, 0, 0.1);
border-radius: 8px;
background-color: #F5F5F5;
}
/*定义滑块 内阴影+圆角*/
::-webkit-scrollbar-thumb {
border-radius: 8px;
box-shadow: inset 0 0 6px rgba(0, 0, 0, 0.2);
background-color: rgba(232, 232, 232, 0.2);
}
/* 模态框 组件 背景样式 */
.ant-radio-group-solid .ant-radio-button-wrapper-checked:not(.ant-radio-button-wrapper-disabled) {
background-color: #329DFF;
color: white;
border: 1px solid #ccc;
}
.ant-radio-group-solid .ant-radio-button-wrapper-checked:not(.ant-radio-button-wrapper-disabled):hover {
background-color: #329DFF;
border: 1px solid #ccc;
}
.ant-radio-button-wrapper {
height: 31px;
}
/* tabs 下划线 去掉 */
.ant-tabs-ink-bar {
background-color: rgb(24, 144, 255);
}
/* .ant-tabs-tab-active {
background-color: #fff;
border: 1px solid rgb(232, 232, 232);
color: rgb(47, 117, 249) !important;
} */
/* .ant-table-body-inner {
margin-right: 0 !important;
}
.ant-table-tbody tr td {
text-align: center;
} */
table {
table-layout: fixed;
}
.ant-table-tbody tr td {
overflow: hidden;
white-space: nowrap;
text-overflow: ellipsis;
}
.ant-pagination-total-text {
position: absolute;
left: 0;
}
/* 操作键 */
.btn-margin {
padding-right: 28px;
}
/* 表格大小 */
.table-style {
width: 100%;
height: 80%;
margin: 0 auto;
}
/* 选中的背景色 */
.ant-tree li .ant-tree-node-content-wrapper.ant-tree-node-selected {
background-color: rgb(240, 240, 240);
}
/* 选择框 */
.choose-box {
border: 1px dashed #5CB1FF;
width: 100%;
height: 36px;
background-color: #EEF5FB;
margin: 0 auto;
margin-bottom: 20px;
font-size: 14px;
line-height: 36px;
}
.choose-box b {
color: #329DFF;
}
.choose-box a {
margin-left: 49px;
}
.exclamation {
color: #329DFF;
width: 20px;
height: 21px;
margin: 0 20px 0 16px;
}
/* 拖动条样式 */
::-webkit-scrollbar:horizontal {
width: 16px;
height: 5px;
background-color: #f5f5f5;
}
/* grid三明治布局 */
.grid-container {
/* display: grid;
grid-template-rows: auto 1fr auto; */
height: 100%;
}
.ant-drawer-body .Drawer .footer, .ant-drawer-body .Drawer .content {
padding: 0;
}
/* 抽屉头部样式 */
.drawer-header {
width: 100%;
/* position: absolute;
right: 0;
top: 0; */
display: table;
background: #fff;
z-index: 100;
height: 8%;
padding: 0 15px;
border-bottom: 1px solid #E5E5E5;
}
/* 抽屉内容样式 */
.drawer-content {
height: 82%;
padding: 15px 10px;
overflow: auto;
}
/* 抽屉底部样式 */
.drawer-footer {
text-align: center;
padding: 15px 0;
width: 100%;
/* position: absolute;
right: 0;
bottom: 0; */
border-top: 1px solid #E5E5E5;
background: #fff;
z-index: 100;
height: 10%;
display: table;
}
.drawer-footer-div {
display: table-cell;
vertical-align: middle;
}
.special-container {
height: 72vh;
position: relative;
}
.ant-drawer-body {
padding: 0px;
height: 100%;
}
.page-container {
height: 100%;
width: 100%
}
.select-box {
margin: 15px 0 0 65%;
position: absolute;
}
.ant-tree.ant-tree-show-line li:not(:last-child)::before {
border-left: 1px #d9d9d9 dashed;
}
.ant-tree li .ant-tree-node-content-wrapper:hover {
background-color: #e6f7ff;
}
.ant-modal-footer .ant-btn-primary {
background-color: #1890ff;
border-color: #1890ff;
}
/* 勾选样式 */
.ant-checkbox-checked .ant-checkbox-inner {
background-color: #329DFF;
border: 1px solid #329DFF;
}
.ant-checkbox-indeterminate .ant-checkbox-inner::after {
background-color: #329DFF;
}
.ant-pagination.mini .ant-pagination-prev .ant-pagination-item-link,
.ant-pagination.mini .ant-pagination-next .ant-pagination-item-link {
background: #329DFF;
border-color: #329DFF;
color: white;
margin: 0 8px;
padding: 0px 5px;
}
.ant-pagination-item-active {
border-color: #329DFF;
color: #329DFF;
}
.ant-pagination-item-active:focus,
.ant-pagination-item-active:hover {
border-color: #329DFF;
}
.ant-pagination-item-active:focus a,
.ant-pagination-item-active:hover a {
color: #329DFF;
}
.btn-16 span {
margin-left: 8px;
}
/* .sider li.ant-menu-item {
border-left: 5px solid transparent;
margin: 0;
} */
.sider li.ant-menu-item.clicked .nuxt-link-active{
background-color: #21262F;
color: #fff;
border-left: 5px solid #1890FF;
border-radius: 0;
}
.sider .wrap-slide li.ant-menu-item > a{
border-left: 5px solid transparent;
}
.sider .wrap-slide li.ant-menu-item > a > span {
margin-left: 30px;
}
li.ant-menu-item.clicked .nuxt-link-active {
color: #fff;
background: none;
}
.sider .wrap-slide li.ant-menu-item {
padding: 0px !important;
border: none;
margin: 0;
}
.ant-menu-dark .ant-menu-inline.ant-menu-sub {
background-color: var(--theme-color);
}
.ant-menu-dark .ant-menu-item-selected > a, .ant-menu-dark .ant-menu-item-selected > a:hover {
color: rgba(255, 255, 255, 0.65);
}
.ant-menu-dark .ant-menu-item:hover > .ant-menu-submenu-title > .ant-menu-submenu-arrow::after, .ant-menu-dark .ant-menu-item-active > .ant-menu-submenu-title > .ant-menu-submenu-arrow::after, .ant-menu-dark .ant-menu-submenu-active > .ant-menu-submenu-title > .ant-menu-submenu-arrow::after, .ant-menu-dark .ant-menu-submenu-open > .ant-menu-submenu-title > .ant-menu-submenu-arrow::after, .ant-menu-dark .ant-menu-submenu-selected > .ant-menu-submenu-title > .ant-menu-submenu-arrow::after, .ant-menu-dark .ant-menu-submenu-title:hover > .ant-menu-submenu-title > .ant-menu-submenu-arrow::after, .ant-menu-dark .ant-menu-item:hover > .ant-menu-submenu-title:hover > .ant-menu-submenu-arrow::after, .ant-menu-dark .ant-menu-item-active > .ant-menu-submenu-title:hover > .ant-menu-submenu-arrow::after, .ant-menu-dark .ant-menu-submenu-active > .ant-menu-submenu-title:hover > .ant-menu-submenu-arrow::after, .ant-menu-dark .ant-menu-submenu-open > .ant-menu-submenu-title:hover > .ant-menu-submenu-arrow::after, .ant-menu-dark .ant-menu-submenu-selected > .ant-menu-submenu-title:hover > .ant-menu-submenu-arrow::after, .ant-menu-dark .ant-menu-submenu-title:hover > .ant-menu-submenu-title:hover > .ant-menu-submenu-arrow::after, .ant-menu-dark .ant-menu-item:hover > .ant-menu-submenu-title > .ant-menu-submenu-arrow::before, .ant-menu-dark .ant-menu-item-active > .ant-menu-submenu-title > .ant-menu-submenu-arrow::before, .ant-menu-dark .ant-menu-submenu-active > .ant-menu-submenu-title > .ant-menu-submenu-arrow::before, .ant-menu-dark .ant-menu-submenu-open > .ant-menu-submenu-title > .ant-menu-submenu-arrow::before, .ant-menu-dark .ant-menu-submenu-selected > .ant-menu-submenu-title > .ant-menu-submenu-arrow::before, .ant-menu-dark .ant-menu-submenu-title:hover > .ant-menu-submenu-title > .ant-menu-submenu-arrow::before, .ant-menu-dark .ant-menu-item:hover > .ant-menu-submenu-title:hover > .ant-menu-submenu-arrow::before, .ant-menu-dark .ant-menu-item-active > .ant-menu-submenu-title:hover > .ant-menu-submenu-arrow::before, .ant-menu-dark .ant-menu-submenu-active > .ant-menu-submenu-title:hover > .ant-menu-submenu-arrow::before, .ant-menu-dark .ant-menu-submenu-open > .ant-menu-submenu-title:hover > .ant-menu-submenu-arrow::before, .ant-menu-dark .ant-menu-submenu-selected > .ant-menu-submenu-title:hover > .ant-menu-submenu-arrow::before, .ant-menu-dark .ant-menu-submenu-title:hover > .ant-menu-submenu-title:hover > .ant-menu-submenu-arrow::before {
background: #fff;
}
.ant-menu-dark .ant-menu-item:hover, .ant-menu-dark .ant-menu-item-active, .ant-menu-dark .ant-menu-submenu-active, .ant-menu-dark .ant-menu-submenu-open, .ant-menu-dark .ant-menu-submenu-selected, .ant-menu-dark .ant-menu-submenu-title:hover {
color: #fff;
}
.ant-menu-dark .ant-menu-item:hover > a, .ant-menu-dark .ant-menu-item-active > a, .ant-menu-dark .ant-menu-submenu-active > a, .ant-menu-dark .ant-menu-submenu-open > a, .ant-menu-dark .ant-menu-submenu-selected > a, .ant-menu-dark .ant-menu-submenu-title:hover > a {
color: #fff;
}
.ant-menu-item .hight-light{
color: #fff !important;
}
.nav-title {
color: #fff;
font-size: 18px;
border: none !important;
}
.nav-title>span::before {
content: '';
margin-right: 10px;
border-right: 5px solid #1890ff;
height: 19px;
display: inline-block;
vertical-align: sub;
}
.ant-layout>.header {
background-color: #20252E !important;
}
.ant-menu-dark:nth-child(1) {
background-color: #20252E;
}
.ant-menu.ant-menu-dark:nth-child(1) .ant-menu-item-selected {
background-color: #20252E;
}
.AttachmentManagement .btn-upload .ant-upload button {
background-color: #2196f3;
margin-top: 16px;
height: 39px;
width: 116px;
cursor: pointer;
font-size: 16px;
border-radius: 0;
color: #fff;
}
.AttachmentManagement .btn-upload .ant-upload button:hover, .AttachmentManagement .btn-upload .ant-upload button:focus{
border-color: transparent
}
.inputNumber .ant-input-number-input {
text-align: center;
}
.ant-switch-checked {
background-color: #1890FF;
}
.ant-calendar-range .ant-calendar-selected-start-date .ant-calendar-date, .ant-calendar-range .ant-calendar-selected-end-date .ant-calendar-date {
background-color: #329DFF;
}
.ant-calendar .ant-calendar-ok-btn {
background-color: #329DFF;
border: #329DFF;
}
.header .logo img {
background: none;
}
| 19.04265
| 2,476
| 0.626019
|
c8cdb38693a54741de66afd7e326a4efb93b0ba5
| 12,272
|
css
|
CSS
|
build/_mermit-grid-col.min.css
|
mermit/mermit-grid
|
3342a2c2eecefe66dde7d258ab42311d4353cf9f
|
[
"MIT"
] | null | null | null |
build/_mermit-grid-col.min.css
|
mermit/mermit-grid
|
3342a2c2eecefe66dde7d258ab42311d4353cf9f
|
[
"MIT"
] | null | null | null |
build/_mermit-grid-col.min.css
|
mermit/mermit-grid
|
3342a2c2eecefe66dde7d258ab42311d4353cf9f
|
[
"MIT"
] | null | null | null |
[class^="mg-col"]>[class^="mg-sec"],[class^="mg-col"]>[class^="mg-sec"]>[class^="mg-sec"],[class^="mg-col"]>[class^="mg-sec"]>[class^="mg-sec"]>[class^="mg-sec"]{flex-direction:row}[class^="mg-col"]>[class^="mg-sec-0"],[class^="mg-col"]>[class^="mg-sec"]>[class^="mg-sec-0"],[class^="mg-col"]>[class^="mg-sec"]>[class^="mg-sec"]>[class^="mg-sec-0"]{display:none}[class^="mg-col"]>[class^="mg-sec-1"],[class^="mg-col"]>[class^="mg-sec"]>[class^="mg-sec-1"],[class^="mg-col"]>[class^="mg-sec"]>[class^="mg-sec"]>[class^="mg-sec-1"]{width:1.66667%;flex-shrink:0}[class^="mg-col"]>[class^="mg-sec-2"],[class^="mg-col"]>[class^="mg-sec"]>[class^="mg-sec-2"],[class^="mg-col"]>[class^="mg-sec"]>[class^="mg-sec"]>[class^="mg-sec-2"]{width:3.33333%;flex-shrink:0}[class^="mg-col"]>[class^="mg-sec-3"],[class^="mg-col"]>[class^="mg-sec"]>[class^="mg-sec-3"],[class^="mg-col"]>[class^="mg-sec"]>[class^="mg-sec"]>[class^="mg-sec-3"]{width:5%;flex-shrink:0}[class^="mg-col"]>[class^="mg-sec-4"],[class^="mg-col"]>[class^="mg-sec"]>[class^="mg-sec-4"],[class^="mg-col"]>[class^="mg-sec"]>[class^="mg-sec"]>[class^="mg-sec-4"]{width:6.66667%;flex-shrink:0}[class^="mg-col"]>[class^="mg-sec-5"],[class^="mg-col"]>[class^="mg-sec"]>[class^="mg-sec-5"],[class^="mg-col"]>[class^="mg-sec"]>[class^="mg-sec"]>[class^="mg-sec-5"]{width:8.33333%;flex-shrink:0}[class^="mg-col"]>[class^="mg-sec-6"],[class^="mg-col"]>[class^="mg-sec"]>[class^="mg-sec-6"],[class^="mg-col"]>[class^="mg-sec"]>[class^="mg-sec"]>[class^="mg-sec-6"]{width:10%;flex-shrink:0}[class^="mg-col"]>[class^="mg-sec-7"],[class^="mg-col"]>[class^="mg-sec"]>[class^="mg-sec-7"],[class^="mg-col"]>[class^="mg-sec"]>[class^="mg-sec"]>[class^="mg-sec-7"]{width:11.66667%;flex-shrink:0}[class^="mg-col"]>[class^="mg-sec-8"],[class^="mg-col"]>[class^="mg-sec"]>[class^="mg-sec-8"],[class^="mg-col"]>[class^="mg-sec"]>[class^="mg-sec"]>[class^="mg-sec-8"]{width:13.33333%;flex-shrink:0}[class^="mg-col"]>[class^="mg-sec-9"],[class^="mg-col"]>[class^="mg-sec"]>[class^="mg-sec-9"],[class^="mg-col"]>[class^="mg-sec"]>[class^="mg-sec"]>[class^="mg-sec-9"]{width:15%;flex-shrink:0}[class^="mg-col"]>[class^="mg-sec-10"],[class^="mg-col"]>[class^="mg-sec"]>[class^="mg-sec-10"],[class^="mg-col"]>[class^="mg-sec"]>[class^="mg-sec"]>[class^="mg-sec-10"]{width:16.66667%;flex-shrink:0}[class^="mg-col"]>[class^="mg-sec-11"],[class^="mg-col"]>[class^="mg-sec"]>[class^="mg-sec-11"],[class^="mg-col"]>[class^="mg-sec"]>[class^="mg-sec"]>[class^="mg-sec-11"]{width:18.33333%;flex-shrink:0}[class^="mg-col"]>[class^="mg-sec-12"],[class^="mg-col"]>[class^="mg-sec"]>[class^="mg-sec-12"],[class^="mg-col"]>[class^="mg-sec"]>[class^="mg-sec"]>[class^="mg-sec-12"]{width:20%;flex-shrink:0}[class^="mg-col"]>[class^="mg-sec-13"],[class^="mg-col"]>[class^="mg-sec"]>[class^="mg-sec-13"],[class^="mg-col"]>[class^="mg-sec"]>[class^="mg-sec"]>[class^="mg-sec-13"]{width:21.66667%;flex-shrink:0}[class^="mg-col"]>[class^="mg-sec-14"],[class^="mg-col"]>[class^="mg-sec"]>[class^="mg-sec-14"],[class^="mg-col"]>[class^="mg-sec"]>[class^="mg-sec"]>[class^="mg-sec-14"]{width:23.33333%;flex-shrink:0}[class^="mg-col"]>[class^="mg-sec-15"],[class^="mg-col"]>[class^="mg-sec"]>[class^="mg-sec-15"],[class^="mg-col"]>[class^="mg-sec"]>[class^="mg-sec"]>[class^="mg-sec-15"]{width:25%;flex-shrink:0}[class^="mg-col"]>[class^="mg-sec-16"],[class^="mg-col"]>[class^="mg-sec"]>[class^="mg-sec-16"],[class^="mg-col"]>[class^="mg-sec"]>[class^="mg-sec"]>[class^="mg-sec-16"]{width:26.66667%;flex-shrink:0}[class^="mg-col"]>[class^="mg-sec-17"],[class^="mg-col"]>[class^="mg-sec"]>[class^="mg-sec-17"],[class^="mg-col"]>[class^="mg-sec"]>[class^="mg-sec"]>[class^="mg-sec-17"]{width:28.33333%;flex-shrink:0}[class^="mg-col"]>[class^="mg-sec-18"],[class^="mg-col"]>[class^="mg-sec"]>[class^="mg-sec-18"],[class^="mg-col"]>[class^="mg-sec"]>[class^="mg-sec"]>[class^="mg-sec-18"]{width:30%;flex-shrink:0}[class^="mg-col"]>[class^="mg-sec-19"],[class^="mg-col"]>[class^="mg-sec"]>[class^="mg-sec-19"],[class^="mg-col"]>[class^="mg-sec"]>[class^="mg-sec"]>[class^="mg-sec-19"]{width:31.66667%;flex-shrink:0}[class^="mg-col"]>[class^="mg-sec-20"],[class^="mg-col"]>[class^="mg-sec"]>[class^="mg-sec-20"],[class^="mg-col"]>[class^="mg-sec"]>[class^="mg-sec"]>[class^="mg-sec-20"]{width:33.33333%;flex-shrink:0}[class^="mg-col"]>[class^="mg-sec-21"],[class^="mg-col"]>[class^="mg-sec"]>[class^="mg-sec-21"],[class^="mg-col"]>[class^="mg-sec"]>[class^="mg-sec"]>[class^="mg-sec-21"]{width:35%;flex-shrink:0}[class^="mg-col"]>[class^="mg-sec-22"],[class^="mg-col"]>[class^="mg-sec"]>[class^="mg-sec-22"],[class^="mg-col"]>[class^="mg-sec"]>[class^="mg-sec"]>[class^="mg-sec-22"]{width:36.66667%;flex-shrink:0}[class^="mg-col"]>[class^="mg-sec-23"],[class^="mg-col"]>[class^="mg-sec"]>[class^="mg-sec-23"],[class^="mg-col"]>[class^="mg-sec"]>[class^="mg-sec"]>[class^="mg-sec-23"]{width:38.33333%;flex-shrink:0}[class^="mg-col"]>[class^="mg-sec-24"],[class^="mg-col"]>[class^="mg-sec"]>[class^="mg-sec-24"],[class^="mg-col"]>[class^="mg-sec"]>[class^="mg-sec"]>[class^="mg-sec-24"]{width:40%;flex-shrink:0}[class^="mg-col"]>[class^="mg-sec-25"],[class^="mg-col"]>[class^="mg-sec"]>[class^="mg-sec-25"],[class^="mg-col"]>[class^="mg-sec"]>[class^="mg-sec"]>[class^="mg-sec-25"]{width:41.66667%;flex-shrink:0}[class^="mg-col"]>[class^="mg-sec-26"],[class^="mg-col"]>[class^="mg-sec"]>[class^="mg-sec-26"],[class^="mg-col"]>[class^="mg-sec"]>[class^="mg-sec"]>[class^="mg-sec-26"]{width:43.33333%;flex-shrink:0}[class^="mg-col"]>[class^="mg-sec-27"],[class^="mg-col"]>[class^="mg-sec"]>[class^="mg-sec-27"],[class^="mg-col"]>[class^="mg-sec"]>[class^="mg-sec"]>[class^="mg-sec-27"]{width:45%;flex-shrink:0}[class^="mg-col"]>[class^="mg-sec-28"],[class^="mg-col"]>[class^="mg-sec"]>[class^="mg-sec-28"],[class^="mg-col"]>[class^="mg-sec"]>[class^="mg-sec"]>[class^="mg-sec-28"]{width:46.66667%;flex-shrink:0}[class^="mg-col"]>[class^="mg-sec-29"],[class^="mg-col"]>[class^="mg-sec"]>[class^="mg-sec-29"],[class^="mg-col"]>[class^="mg-sec"]>[class^="mg-sec"]>[class^="mg-sec-29"]{width:48.33333%;flex-shrink:0}[class^="mg-col"]>[class^="mg-sec-30"],[class^="mg-col"]>[class^="mg-sec"]>[class^="mg-sec-30"],[class^="mg-col"]>[class^="mg-sec"]>[class^="mg-sec"]>[class^="mg-sec-30"]{width:50%;flex-shrink:0}[class^="mg-col"]>[class^="mg-sec-31"],[class^="mg-col"]>[class^="mg-sec"]>[class^="mg-sec-31"],[class^="mg-col"]>[class^="mg-sec"]>[class^="mg-sec"]>[class^="mg-sec-31"]{width:51.66667%;flex-shrink:0}[class^="mg-col"]>[class^="mg-sec-32"],[class^="mg-col"]>[class^="mg-sec"]>[class^="mg-sec-32"],[class^="mg-col"]>[class^="mg-sec"]>[class^="mg-sec"]>[class^="mg-sec-32"]{width:53.33333%;flex-shrink:0}[class^="mg-col"]>[class^="mg-sec-33"],[class^="mg-col"]>[class^="mg-sec"]>[class^="mg-sec-33"],[class^="mg-col"]>[class^="mg-sec"]>[class^="mg-sec"]>[class^="mg-sec-33"]{width:55%;flex-shrink:0}[class^="mg-col"]>[class^="mg-sec-34"],[class^="mg-col"]>[class^="mg-sec"]>[class^="mg-sec-34"],[class^="mg-col"]>[class^="mg-sec"]>[class^="mg-sec"]>[class^="mg-sec-34"]{width:56.66667%;flex-shrink:0}[class^="mg-col"]>[class^="mg-sec-35"],[class^="mg-col"]>[class^="mg-sec"]>[class^="mg-sec-35"],[class^="mg-col"]>[class^="mg-sec"]>[class^="mg-sec"]>[class^="mg-sec-35"]{width:58.33333%;flex-shrink:0}[class^="mg-col"]>[class^="mg-sec-36"],[class^="mg-col"]>[class^="mg-sec"]>[class^="mg-sec-36"],[class^="mg-col"]>[class^="mg-sec"]>[class^="mg-sec"]>[class^="mg-sec-36"]{width:60%;flex-shrink:0}[class^="mg-col"]>[class^="mg-sec-37"],[class^="mg-col"]>[class^="mg-sec"]>[class^="mg-sec-37"],[class^="mg-col"]>[class^="mg-sec"]>[class^="mg-sec"]>[class^="mg-sec-37"]{width:61.66667%;flex-shrink:0}[class^="mg-col"]>[class^="mg-sec-38"],[class^="mg-col"]>[class^="mg-sec"]>[class^="mg-sec-38"],[class^="mg-col"]>[class^="mg-sec"]>[class^="mg-sec"]>[class^="mg-sec-38"]{width:63.33333%;flex-shrink:0}[class^="mg-col"]>[class^="mg-sec-39"],[class^="mg-col"]>[class^="mg-sec"]>[class^="mg-sec-39"],[class^="mg-col"]>[class^="mg-sec"]>[class^="mg-sec"]>[class^="mg-sec-39"]{width:65%;flex-shrink:0}[class^="mg-col"]>[class^="mg-sec-40"],[class^="mg-col"]>[class^="mg-sec"]>[class^="mg-sec-40"],[class^="mg-col"]>[class^="mg-sec"]>[class^="mg-sec"]>[class^="mg-sec-40"]{width:66.66667%;flex-shrink:0}[class^="mg-col"]>[class^="mg-sec-41"],[class^="mg-col"]>[class^="mg-sec"]>[class^="mg-sec-41"],[class^="mg-col"]>[class^="mg-sec"]>[class^="mg-sec"]>[class^="mg-sec-41"]{width:68.33333%;flex-shrink:0}[class^="mg-col"]>[class^="mg-sec-42"],[class^="mg-col"]>[class^="mg-sec"]>[class^="mg-sec-42"],[class^="mg-col"]>[class^="mg-sec"]>[class^="mg-sec"]>[class^="mg-sec-42"]{width:70%;flex-shrink:0}[class^="mg-col"]>[class^="mg-sec-43"],[class^="mg-col"]>[class^="mg-sec"]>[class^="mg-sec-43"],[class^="mg-col"]>[class^="mg-sec"]>[class^="mg-sec"]>[class^="mg-sec-43"]{width:71.66667%;flex-shrink:0}[class^="mg-col"]>[class^="mg-sec-44"],[class^="mg-col"]>[class^="mg-sec"]>[class^="mg-sec-44"],[class^="mg-col"]>[class^="mg-sec"]>[class^="mg-sec"]>[class^="mg-sec-44"]{width:73.33333%;flex-shrink:0}[class^="mg-col"]>[class^="mg-sec-45"],[class^="mg-col"]>[class^="mg-sec"]>[class^="mg-sec-45"],[class^="mg-col"]>[class^="mg-sec"]>[class^="mg-sec"]>[class^="mg-sec-45"]{width:75%;flex-shrink:0}[class^="mg-col"]>[class^="mg-sec-46"],[class^="mg-col"]>[class^="mg-sec"]>[class^="mg-sec-46"],[class^="mg-col"]>[class^="mg-sec"]>[class^="mg-sec"]>[class^="mg-sec-46"]{width:76.66667%;flex-shrink:0}[class^="mg-col"]>[class^="mg-sec-47"],[class^="mg-col"]>[class^="mg-sec"]>[class^="mg-sec-47"],[class^="mg-col"]>[class^="mg-sec"]>[class^="mg-sec"]>[class^="mg-sec-47"]{width:78.33333%;flex-shrink:0}[class^="mg-col"]>[class^="mg-sec-48"],[class^="mg-col"]>[class^="mg-sec"]>[class^="mg-sec-48"],[class^="mg-col"]>[class^="mg-sec"]>[class^="mg-sec"]>[class^="mg-sec-48"]{width:80%;flex-shrink:0}[class^="mg-col"]>[class^="mg-sec-49"],[class^="mg-col"]>[class^="mg-sec"]>[class^="mg-sec-49"],[class^="mg-col"]>[class^="mg-sec"]>[class^="mg-sec"]>[class^="mg-sec-49"]{width:81.66667%;flex-shrink:0}[class^="mg-col"]>[class^="mg-sec-50"],[class^="mg-col"]>[class^="mg-sec"]>[class^="mg-sec-50"],[class^="mg-col"]>[class^="mg-sec"]>[class^="mg-sec"]>[class^="mg-sec-50"]{width:83.33333%;flex-shrink:0}[class^="mg-col"]>[class^="mg-sec-51"],[class^="mg-col"]>[class^="mg-sec"]>[class^="mg-sec-51"],[class^="mg-col"]>[class^="mg-sec"]>[class^="mg-sec"]>[class^="mg-sec-51"]{width:85%;flex-shrink:0}[class^="mg-col"]>[class^="mg-sec-52"],[class^="mg-col"]>[class^="mg-sec"]>[class^="mg-sec-52"],[class^="mg-col"]>[class^="mg-sec"]>[class^="mg-sec"]>[class^="mg-sec-52"]{width:86.66667%;flex-shrink:0}[class^="mg-col"]>[class^="mg-sec-53"],[class^="mg-col"]>[class^="mg-sec"]>[class^="mg-sec-53"],[class^="mg-col"]>[class^="mg-sec"]>[class^="mg-sec"]>[class^="mg-sec-53"]{width:88.33333%;flex-shrink:0}[class^="mg-col"]>[class^="mg-sec-54"],[class^="mg-col"]>[class^="mg-sec"]>[class^="mg-sec-54"],[class^="mg-col"]>[class^="mg-sec"]>[class^="mg-sec"]>[class^="mg-sec-54"]{width:90%;flex-shrink:0}[class^="mg-col"]>[class^="mg-sec-55"],[class^="mg-col"]>[class^="mg-sec"]>[class^="mg-sec-55"],[class^="mg-col"]>[class^="mg-sec"]>[class^="mg-sec"]>[class^="mg-sec-55"]{width:91.66667%;flex-shrink:0}[class^="mg-col"]>[class^="mg-sec-56"],[class^="mg-col"]>[class^="mg-sec"]>[class^="mg-sec-56"],[class^="mg-col"]>[class^="mg-sec"]>[class^="mg-sec"]>[class^="mg-sec-56"]{width:93.33333%;flex-shrink:0}[class^="mg-col"]>[class^="mg-sec-57"],[class^="mg-col"]>[class^="mg-sec"]>[class^="mg-sec-57"],[class^="mg-col"]>[class^="mg-sec"]>[class^="mg-sec"]>[class^="mg-sec-57"]{width:95%;flex-shrink:0}[class^="mg-col"]>[class^="mg-sec-58"],[class^="mg-col"]>[class^="mg-sec"]>[class^="mg-sec-58"],[class^="mg-col"]>[class^="mg-sec"]>[class^="mg-sec"]>[class^="mg-sec-58"]{width:96.66667%;flex-shrink:0}[class^="mg-col"]>[class^="mg-sec-59"],[class^="mg-col"]>[class^="mg-sec"]>[class^="mg-sec-59"],[class^="mg-col"]>[class^="mg-sec"]>[class^="mg-sec"]>[class^="mg-sec-59"]{width:98.33333%;flex-shrink:0}[class^="mg-col"]>[class^="mg-sec-60"],[class^="mg-col"]>[class^="mg-sec"]>[class^="mg-sec-60"],[class^="mg-col"]>[class^="mg-sec"]>[class^="mg-sec"]>[class^="mg-sec-60"]{width:100%;flex-shrink:0}
| 6,136
| 12,271
| 0.58825
|
e44933219199a01138fe919492bf47437cd49518
| 354
|
hxx
|
C++
|
src/fbc/fbcExchangeReactionFilter.hxx
|
Cosmo-Tech/libfbc
|
eb923f235645c2890009d7cd60347d331adbeb5b
|
[
"BSD-3-Clause",
"Unlicense"
] | null | null | null |
src/fbc/fbcExchangeReactionFilter.hxx
|
Cosmo-Tech/libfbc
|
eb923f235645c2890009d7cd60347d331adbeb5b
|
[
"BSD-3-Clause",
"Unlicense"
] | 2
|
2015-01-07T16:09:44.000Z
|
2015-01-07T16:10:15.000Z
|
src/fbc/fbcExchangeReactionFilter.hxx
|
Cosmo-Tech/libfbc
|
eb923f235645c2890009d7cd60347d331adbeb5b
|
[
"BSD-3-Clause",
"Unlicense"
] | null | null | null |
#ifndef __fbcExchangeReactionFilter_hxx
#define __fbcExchangeReactionFilter_hxx
#include "sbml/util/ElementFilter.h"
class SBase;
class List;
namespace fbc
{
class ExchangeReactionFilter: public ElementFilter
{
private:
List* speciesList;
public:
ExchangeReactionFilter(List* sp_lst);
bool filter(const SBase* element);
};
}
#endif
| 14.75
| 50
| 0.768362
|
d4ea8a5abc30cd849597b8b2213c04ab32e9c051
| 7,654
|
dart
|
Dart
|
lib/components/drawer.dart
|
prijindal/kuzzle_flutter_admin
|
0c6e2a11928e34b6544e9437ba83ea8f26f371c5
|
[
"MIT"
] | 3
|
2019-01-12T02:50:13.000Z
|
2022-01-22T12:29:17.000Z
|
lib/components/drawer.dart
|
prijindal/kuzzle_flutter_admin
|
0c6e2a11928e34b6544e9437ba83ea8f26f371c5
|
[
"MIT"
] | null | null | null |
lib/components/drawer.dart
|
prijindal/kuzzle_flutter_admin
|
0c6e2a11928e34b6544e9437ba83ea8f26f371c5
|
[
"MIT"
] | 1
|
2019-05-01T15:27:50.000Z
|
2019-05-01T15:27:50.000Z
|
import 'package:flutter/material.dart';
import 'package:flutter_redux/flutter_redux.dart';
import 'package:kuzzleflutteradmin/components/expansiontile.dart';
import 'package:kuzzleflutteradmin/models/environment.dart';
import 'package:kuzzleflutteradmin/models/environments.dart';
import 'package:kuzzleflutteradmin/models/kuzzleindexes.dart';
import 'package:kuzzleflutteradmin/models/kuzzlestate.dart';
import 'package:kuzzleflutteradmin/pages/addenvironment.dart';
import 'package:kuzzleflutteradmin/pages/collection.dart';
import 'package:kuzzleflutteradmin/pages/collections.dart';
import 'package:kuzzleflutteradmin/pages/environments.dart';
import 'package:kuzzleflutteradmin/pages/indexes.dart';
import 'package:kuzzleflutteradmin/pages/newcollection.dart';
import 'package:kuzzleflutteradmin/pages/newindex.dart';
import 'package:kuzzleflutteradmin/redux/kuzzleindex/actions.dart';
import 'package:kuzzleflutteradmin/redux/state.dart';
import 'package:redux/redux.dart';
class KuzzleDrawer extends StatelessWidget {
const KuzzleDrawer();
void _chooseEnvironmentConfirm(Environment environment) {}
@override
Widget build(BuildContext context) => Drawer(
child: SingleChildScrollView(
child: Column(
children: [
Container(
color: Theme.of(context).primaryColor,
child: SafeArea(
child: Container(
height: 64,
child: Center(
child: Image.asset(
'images/logo.png',
height: 48,
),
),
),
),
),
const ListTile(
dense: true,
title: Text('Data'),
),
StoreConnector<AppState, List<String>>(
onInit: (store) {
if (store.state.kuzzleindexes.loadingState ==
KuzzleState.INIT) {
store.dispatch(getKuzzleIndexes);
}
},
converter: (store) => store.state.kuzzleindexes.getIndexes(),
builder: (context, indexes) => BaseExpansionTile<String>(
addRoute: MaterialPageRoute(
builder: (context) => const NewIndexPage(),
),
manageRoute: MaterialPageRoute(
builder: (context) => const IndexesPage(),
),
items: indexes,
title: 'Indexes',
icon: const Icon(Icons.dns),
buildChild: (index) => _IndexExpansionTile(
index: index,
),
),
),
const ListTile(
dense: true,
title: Text('Security'),
),
ListTile(
leading: const Icon(Icons.person),
title: const Text('Users'),
onTap: () {
Navigator.of(context).pushReplacementNamed('users');
},
),
ListTile(
leading: const Icon(Icons.people),
title: const Text('Profiles'),
onTap: () {
Navigator.of(context).pushReplacementNamed('profiles');
},
),
ListTile(
leading: const Icon(Icons.lock_open),
title: const Text('Roles'),
onTap: () {
Navigator.of(context).pushReplacementNamed('roles');
},
),
const ListTile(
dense: true,
title: Text('Settings'),
),
StoreConnector<AppState, Environments>(
converter: (store) => store.state.environments,
builder: (context, environments) =>
BaseExpansionTile<Environment>(
addRoute: MaterialPageRoute(
builder: (context) => const AddEnvironmentPage(),
),
manageRoute: MaterialPageRoute(
builder: (context) => const EnvironmentsPage(),
),
items: environments.environments.values.toList(),
title: 'Environments',
icon: const Icon(Icons.kitchen),
buildChild: (environment) => ListTile(
dense: true,
enabled:
environment.name != environments.defaultEnvironment,
leading: const Icon(
Icons.list,
),
title: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Container(
constraints: const BoxConstraints(
maxWidth: 200, maxHeight: 40),
child: Text(environment.name),
),
],
),
onTap: () => _chooseEnvironmentConfirm(environment),
),
),
),
],
),
),
);
}
class _IndexExpansionTile extends StatelessWidget {
const _IndexExpansionTile({@required this.index});
final String index;
void _goToCollectionPage(KuzzleCollection collection, BuildContext context) {
Navigator.of(context).pushReplacement(
MaterialPageRoute(
builder: (context) => CollectionPage(
index: index,
collection: collection,
),
),
);
}
KuzzleCollection get _selectedCollection => null;
void _onValueChange(bool newvalue, Store<AppState> store) {
if (newvalue == true &&
store.state.kuzzleindexes.indexMap[index].loadingState ==
KuzzleState.INIT) {
store.dispatch(getKuzzleCollections(index));
}
}
@override
Widget build(BuildContext context) =>
StoreConnector<AppState, List<KuzzleCollection>>(
converter: (store) =>
store.state.kuzzleindexes.indexMap[index].collections,
builder: (context, collections) => BaseExpansionTile<KuzzleCollection>(
icon: const Icon(Icons.dns),
title: index,
onValueChange: (newvalue) =>
_onValueChange(newvalue, StoreProvider.of(context)),
addRoute: MaterialPageRoute(
builder: (context) => NewCollectionPage(
index: index,
),
),
manageRoute: MaterialPageRoute(
builder: (context) => CollectionsPage(
index: index,
),
),
items: collections,
buildChild: (collection) => ListTile(
dense: true,
enabled: _selectedCollection == null ||
_selectedCollection != collection,
selected: _selectedCollection != null &&
_selectedCollection == collection,
leading: const Icon(
Icons.list,
),
title: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Container(
constraints:
const BoxConstraints(maxWidth: 200, maxHeight: 40),
child: Text(collection.name),
),
],
),
onTap: () => _goToCollectionPage(collection, context),
),
),
);
}
| 36.798077
| 79
| 0.512673
|
e6410b5f38a41c49552a8d14bcf0ee89e36a7c99
| 434
|
sql
|
SQL
|
sql/_04_operator_function/_08_click_counter/_003_complex/cases/1009.sql
|
Zhaojia2019/cubrid-testcases
|
475a828e4d7cf74aaf2611fcf791a6028ddd107d
|
[
"BSD-3-Clause"
] | 9
|
2016-03-24T09:51:52.000Z
|
2022-03-23T10:49:47.000Z
|
sql/_04_operator_function/_08_click_counter/_003_complex/cases/1009.sql
|
Zhaojia2019/cubrid-testcases
|
475a828e4d7cf74aaf2611fcf791a6028ddd107d
|
[
"BSD-3-Clause"
] | 173
|
2016-04-13T01:16:54.000Z
|
2022-03-16T07:50:58.000Z
|
sql/_04_operator_function/_08_click_counter/_003_complex/cases/1009.sql
|
Zhaojia2019/cubrid-testcases
|
475a828e4d7cf74aaf2611fcf791a6028ddd107d
|
[
"BSD-3-Clause"
] | 38
|
2016-03-24T17:10:31.000Z
|
2021-10-30T22:55:45.000Z
|
--[er]test incr, decr with group by clause
CREATE CLASS board (
id INT, title VARCHAR(100), content VARCHAR(4000), read_count INT ,edit_count INT);
INSERT INTO board VALUES (1, 'aaa', 'text...', 0,10);
INSERT INTO board VALUES (2, 'bbb', 'text...', 0,0);
INSERT INTO board VALUES (3, 'ccc', 'text...', 0,0);
select incr(read_count) from board group by title;
select decr(read_count) from board group by title;
drop class board;
| 36.166667
| 87
| 0.693548
|
c8ead31867af4738caef339304f432d57068a801
| 1,261
|
css
|
CSS
|
resources/css/utilities/form.css
|
flekking/erista-chms
|
10d626852b8009faca56936fa41d98371158adad
|
[
"MIT"
] | null | null | null |
resources/css/utilities/form.css
|
flekking/erista-chms
|
10d626852b8009faca56936fa41d98371158adad
|
[
"MIT"
] | null | null | null |
resources/css/utilities/form.css
|
flekking/erista-chms
|
10d626852b8009faca56936fa41d98371158adad
|
[
"MIT"
] | null | null | null |
[type='text'],
[type='email'],
[type='url'],
[type='password'],
[type='number'],
[type='date'],
[type='datetime-local'],
[type='month'],
[type='search'],
[type='tel'],
[type='time'],
[type='week'],
[multiple],
textarea,
select {
&.form-control {
@apply
rounded-lg
focus:outline-none
focus:border-primary-500
bg-white
dark:bg-gray-800
border
border-gray-300
dark:border-gray-700
text-gray-900
dark:text-gray-100
placeholder-gray-300
dark:placeholder-gray-500
shadow-sm
block
w-full
p-2.5;
}
&.form-control-sm {
@apply text-sm;
}
&.form-control-md {
@apply text-base;
}
&.form-control-lg {
@apply text-lg;
}
&.form-control-error {
@apply bg-red-50 border-red-500 focus:border-red-600 text-red-900 placeholder-red-300;
}
}
[type='checkbox'].form-control {
@apply
bg-white
dark:bg-gray-900
border-gray-300
dark:border-gray-600
focus:ring-purple-300
h-4
w-4
rounded
text-purple-500;
}
label.form-label {
@apply text-sm font-medium text-gray-900 block mb-2;
}
label.form-control-checkbox-label {
@apply text-xs font-medium text-gray-900;
}
small.form-error {
@apply text-red-500;
}
| 17.040541
| 90
| 0.604282
|
ac26f076fac794cd6a7f15ace547fca57bee04e9
| 697
|
kt
|
Kotlin
|
app/src/main/java/com/joegruff/decredaddressscanner/types/Daos.kt
|
fossdd/dcraddrscanner
|
213a8987874173b8a5354f97e7669b7af05c15ce
|
[
"BlueOak-1.0.0"
] | null | null | null |
app/src/main/java/com/joegruff/decredaddressscanner/types/Daos.kt
|
fossdd/dcraddrscanner
|
213a8987874173b8a5354f97e7669b7af05c15ce
|
[
"BlueOak-1.0.0"
] | null | null | null |
app/src/main/java/com/joegruff/decredaddressscanner/types/Daos.kt
|
fossdd/dcraddrscanner
|
213a8987874173b8a5354f97e7669b7af05c15ce
|
[
"BlueOak-1.0.0"
] | null | null | null |
package com.joegruff.decredaddressscanner.types
import androidx.room.*
@Dao
interface AddressDao {
@Query("SELECT * FROM address_table ORDER BY timestamp_create ASC")
suspend fun getAll(): List<Address>
@Insert(onConflict = OnConflictStrategy.IGNORE)
suspend fun insert(addr: Address)
@Delete
suspend fun delete(addr: Address)
@Update
suspend fun update(addr:Address)
}
@Dao
interface SettingsDao {
@Query("SELECT * FROM settings_table where user=:user")
suspend fun get(user: String): Settings?
@Insert(onConflict = OnConflictStrategy.IGNORE)
suspend fun insert(settings: Settings)
@Update
suspend fun update(settings: Settings);
}
| 22.483871
| 71
| 0.721664
|
31d64c3e9455c74de999dd2826ff52904690d99c
| 426
|
rb
|
Ruby
|
lib/redcord/migration/ttl.rb
|
chanzuckerberg/redcord
|
dd553229d89f377d86937f75f88fc91431bea6e5
|
[
"MIT"
] | 9
|
2020-07-23T05:10:39.000Z
|
2022-01-10T08:03:23.000Z
|
lib/redcord/migration/ttl.rb
|
chanzuckerberg/redcord
|
dd553229d89f377d86937f75f88fc91431bea6e5
|
[
"MIT"
] | 69
|
2020-07-09T13:36:07.000Z
|
2022-03-17T00:41:07.000Z
|
lib/redcord/migration/ttl.rb
|
chanzuckerberg/redis-record
|
f216b22365395c37552ed8a015a98b36afa0803f
|
[
"MIT"
] | 1
|
2020-09-28T21:34:29.000Z
|
2020-09-28T21:34:29.000Z
|
# typed: strict
module Redcord::Migration::TTL
extend T::Sig
sig { params(model: T.class_of(Redcord::Base)).returns(T.untyped) }
def _get_ttl(model)
model.class_variable_get(:@@ttl) || -1
end
sig { params(model: T.class_of(Redcord::Base)).void }
def change_ttl_active(model)
model.redis.scan_each_shard("#{model.model_key}:id:*") do |key|
model.redis.expire(key, _get_ttl(model))
end
end
end
| 25.058824
| 69
| 0.683099
|
cb77415551a0e79b68b34b063b3bac752e5d802a
| 512
|
dart
|
Dart
|
test/redux/increment_store.dart
|
shindakioku/incredux
|
63cf8fe393406939ad32c5f2fd11a45c9015d0ba
|
[
"BSD-3-Clause"
] | null | null | null |
test/redux/increment_store.dart
|
shindakioku/incredux
|
63cf8fe393406939ad32c5f2fd11a45c9015d0ba
|
[
"BSD-3-Clause"
] | null | null | null |
test/redux/increment_store.dart
|
shindakioku/incredux
|
63cf8fe393406939ad32c5f2fd11a45c9015d0ba
|
[
"BSD-3-Clause"
] | null | null | null |
import 'package:redux/redux.dart';
import 'package:incredux/incredux.dart';
enum Actions { increment, decrement }
int counterReducer(int state, dynamic action) {
if (action == Actions.increment) {
return state + 1;
} else if (action == Actions.decrement) {
return state - 1;
}
return state;
}
Store buildStore(incrs, {whenFn}) => Store<int>(
counterReducer,
initialState: 0,
middleware: <Middleware<int>>[
incredux<int>(incrs: incrs, whenFn: whenFn)
],
);
| 22.26087
| 51
| 0.646484
|
704d9d978eff03dcb2fe6faf282e37bb79a0da7f
| 3,270
|
lua
|
Lua
|
Player/ArmFSM/DRCFinal/armDrillRight.lua
|
ToyotaResearchInstitute/rad-robot
|
9a47e4d88382719ab9bf142932fbcc83dcbcd665
|
[
"MIT"
] | null | null | null |
Player/ArmFSM/DRCFinal/armDrillRight.lua
|
ToyotaResearchInstitute/rad-robot
|
9a47e4d88382719ab9bf142932fbcc83dcbcd665
|
[
"MIT"
] | null | null | null |
Player/ArmFSM/DRCFinal/armDrillRight.lua
|
ToyotaResearchInstitute/rad-robot
|
9a47e4d88382719ab9bf142932fbcc83dcbcd665
|
[
"MIT"
] | 2
|
2018-06-04T12:38:54.000Z
|
2018-09-22T10:31:27.000Z
|
--------------------------------
-- Humanoid arm state
-- (c) 2013 Stephen McGill, Seung-Joon Yi
--------------------------------
local state = {}
state._NAME = ...
local Body = require'Body'
local vector = require'vector'
local movearm = require'movearm'
local t_entry, t_update, t_finish
local timeout = 30.0
-- left and right will both request waist positions potentially
local lco, rco
local okL, qLWaypoint, qLWaist
local okR, qRWaypoint, qRWaist
local sequence, s, stage
function state.entry()
io.write(state._NAME, ' Entry\n')
local t_entry_prev = t_entry
t_entry = Body.get_time()
t_update = t_entry
sequence = {unpack(Config.arm.drillright)}
s = 1
stage = sequence[s]
lco, rco = movearm.goto(stage.left, stage.right)
-- Check for no motion
okL = type(lco)=='thread' or lco==false
okR = type(rco)=='thread' or rco==false
qLWaypoint = nil
qRWaypoint = nil
qLWaistpoint = nil
qRWaistpoint = nil
end
function state.update()
-- io.write(state._NAME,' Update\n')
local t = Body.get_time()
local dt = t - t_update
t_update = t
--if t-t_entry > timeout then return'timeout' end
if not stage then return'done' end
local lStatus = type(lco)=='thread' and coroutine.status(lco) or 'dead'
local rStatus = type(rco)=='thread' and coroutine.status(rco) or 'dead'
local qLArm = Body.get_larm_position()
local qRArm = Body.get_rarm_position()
local qWaist = Body.get_safe_waist_position()
if lStatus=='suspended' then
okL, qLWaypoint, qLWaistpoint = coroutine.resume(lco, qLArm, qWaist)
end
if rStatus=='suspended' then
okR, qRWaypoint, qRWaistpoint = coroutine.resume(rco, qRArm, qWaist)
end
-- Check if errors in either
if not okL or not okR then
print(state._NAME, 'L', okL, qLWaypoint, lco, lStatus)
print(state._NAME, 'R', okR, qRWaypoint, rco, rStatus)
-- Safety
local qcLArm = Body.get_larm_command_position()
local qcRArm = Body.get_rarm_command_position()
local qcWaist = Body.get_safe_waist_command_position()
--
Body.set_larm_command_position(qcLArm)
Body.set_rarm_command_position(qcRArm)
Body.set_safe_waist_command_position(qcWaist)
--
return'teleopraw'
end
if type(qLWaypoint)=='table' then
Body.set_larm_command_position(qLWaypoint)
end
if type(qRWaypoint)=='table' then
Body.set_rarm_command_position(qRWaypoint)
end
--[[
if qLWaistpoint and qRWaistpoint then
print('Conflicting Waist')
elseif qLWaist then
Body.set_safe_waist_command_position(qLWaistpoint)
elseif qRWaist then
Body.set_safe_waist_command_position(qRWaistpoint)
end
--]]
-- Zero the waist
local qWaist = Body.get_safe_waist_command_position()
local qWaist_approach, doneWaist = util.approachTol(qWaist, {0,0}, {2 * DEG_TO_RAD, 2 * DEG_TO_RAD}, dt, {1*DEG_TO_RAD, 1*DEG_TO_RAD})
Body.set_safe_waist_command_position(qWaist_approach)
-- Check if done
if lStatus=='dead' and rStatus=='dead' then
-- Goto the nextitem in the sequnce
s = s + 1
stage = sequence[s]
if stage then
print('Next sequence:', s, stage)
lco, rco = movearm.goto(stage.left, stage.right)
okL = type(lco)=='thread' or lco==false
okR = type(rco)=='thread' or rco==false
else
return doneWaist and 'done'
end
end
end
function state.exit()
print(state._NAME..' Exit')
end
return state
| 26.16
| 136
| 0.713456
|
544c903f0051914dd6a3084d224b4ba4cb68b686
| 77
|
css
|
CSS
|
src/components/Related/Related.module.css
|
themmyloluwaa/sewb_blog
|
5a5ba8703563eaf3e70e87bb8c42367eb815ddef
|
[
"MIT"
] | null | null | null |
src/components/Related/Related.module.css
|
themmyloluwaa/sewb_blog
|
5a5ba8703563eaf3e70e87bb8c42367eb815ddef
|
[
"MIT"
] | 3
|
2022-03-13T02:12:52.000Z
|
2022-03-27T15:18:35.000Z
|
src/components/Related/Related.module.css
|
themmyloluwaa/sewb_blog
|
5a5ba8703563eaf3e70e87bb8c42367eb815ddef
|
[
"MIT"
] | null | null | null |
.container {
@apply my-5;
}
.title {
@apply font-bold mb-6 text-2xl ;
}
| 9.625
| 34
| 0.584416
|
66d73f6c6b8d720f13be4a8a02911aff8823c8f8
| 591
|
dart
|
Dart
|
lib/res/palette.dart
|
goldipatel12/YogApp
|
8aa584421af02fc57b664173d2fc382dfca8ab08
|
[
"MIT"
] | 1
|
2021-08-20T21:25:11.000Z
|
2021-08-20T21:25:11.000Z
|
lib/res/palette.dart
|
goldipatel12/YogApp
|
8aa584421af02fc57b664173d2fc382dfca8ab08
|
[
"MIT"
] | null | null | null |
lib/res/palette.dart
|
goldipatel12/YogApp
|
8aa584421af02fc57b664173d2fc382dfca8ab08
|
[
"MIT"
] | 1
|
2022-03-14T23:41:08.000Z
|
2022-03-14T23:41:08.000Z
|
import 'package:flutter/material.dart';
class Palette {
static const someColor = Colors.white;
static const darkShade = Color(0xFF640226);
static const lightDarkShade = Color(0xFFcd3871);
static const mediumShade = Color(0xFFfbe1e0);
static const lightShade = Color(0xFFFCE0DF);
static const black = Color(0xFF230107);
static const loginBackground = Color(0xFFffead7);
static const nameBackground = Color(0xFFffe6e1);
static const genderBackground = Color(0xFF5cb798);
static const ageBackground = Color(0xFFfeafb6);
static const accentDarkPink = Color(0xFFed576a);
}
| 36.9375
| 52
| 0.771574
|
dc010ea101937b8dfc796899e9238663499e69b3
| 53
|
rb
|
Ruby
|
config/initializers/pusher.rb
|
phuphighter/pusher_app_example
|
de7b3bc99a3dbfe380492b9a6c7e7dece6ad54ed
|
[
"MIT"
] | 1
|
2015-11-05T15:09:13.000Z
|
2015-11-05T15:09:13.000Z
|
config/initializers/pusher.rb
|
phuphighter/pusher_app_example
|
de7b3bc99a3dbfe380492b9a6c7e7dece6ad54ed
|
[
"MIT"
] | null | null | null |
config/initializers/pusher.rb
|
phuphighter/pusher_app_example
|
de7b3bc99a3dbfe380492b9a6c7e7dece6ad54ed
|
[
"MIT"
] | null | null | null |
Pusher.app_id = ''
Pusher.key = ''
Pusher.secret = ''
| 17.666667
| 18
| 0.622642
|
e017a0e260d2a0789455430d2a42c5aa20a37381
| 1,312
|
h
|
C
|
Frameworks/MapKit.framework/MKMapItemMetadataRequester.h
|
shaojiankui/iOS10-Runtime-Headers
|
6b0d842bed0c52c2a7c1464087b3081af7e10c43
|
[
"MIT"
] | 36
|
2016-04-20T04:19:04.000Z
|
2018-10-08T04:12:25.000Z
|
Frameworks/MapKit.framework/MKMapItemMetadataRequester.h
|
shaojiankui/iOS10-Runtime-Headers
|
6b0d842bed0c52c2a7c1464087b3081af7e10c43
|
[
"MIT"
] | null | null | null |
Frameworks/MapKit.framework/MKMapItemMetadataRequester.h
|
shaojiankui/iOS10-Runtime-Headers
|
6b0d842bed0c52c2a7c1464087b3081af7e10c43
|
[
"MIT"
] | 10
|
2016-06-16T02:40:44.000Z
|
2019-01-15T03:31:45.000Z
|
/* Generated by RuntimeBrowser
Image: /System/Library/Frameworks/MapKit.framework/MapKit
*/
@interface MKMapItemMetadataRequester : NSObject <NSURLSessionDataDelegate, NSURLSessionDelegate, NSURLSessionTaskDelegate> {
ACAccountStore * _accountStore;
NSMapTable * _dataForTasks;
bool _hasCheckedYelpAccountCredentials;
NSMapTable * _requestsForURLs;
NSURLSession * _session;
OAURLRequestSigner * _signer;
NSMapTable * _tasksForURLs;
ACAccountCredential * _yelpAccountCredentials;
}
@property (readonly, copy) NSString *debugDescription;
@property (readonly, copy) NSString *description;
@property (readonly) unsigned long long hash;
@property (nonatomic, readonly) OAURLRequestSigner *signer;
@property (readonly) Class superclass;
@property (nonatomic, readonly) ACAccountCredential *yelpAccountCredentials;
+ (id)sharedInstance;
- (void).cxx_destruct;
- (void)URLSession:(id)arg1 dataTask:(id)arg2 didReceiveData:(id)arg3;
- (void)URLSession:(id)arg1 task:(id)arg2 didCompleteWithError:(id)arg3;
- (id)accountStore;
- (void)accountStoreDidChange:(id)arg1;
- (void)cancelRequestsForMapItem:(id)arg1;
- (void)dealloc;
- (void)handleTask:(id)arg1 withData:(id)arg2 error:(id)arg3;
- (id)init;
- (void)sendRequest:(id)arg1;
- (id)signer;
- (id)yelpAccountCredentials;
@end
| 33.641026
| 125
| 0.771341
|
d2fd28b9c6bc5691e3edad3c0e438315f1cea946
| 8,018
|
rs
|
Rust
|
pod/src/link_svc.rs
|
trilloop-software/openlink
|
dd0491892f92cb7c84fe5c39c62bcc6eceabeb1d
|
[
"MIT"
] | null | null | null |
pod/src/link_svc.rs
|
trilloop-software/openlink
|
dd0491892f92cb7c84fe5c39c62bcc6eceabeb1d
|
[
"MIT"
] | null | null | null |
pod/src/link_svc.rs
|
trilloop-software/openlink
|
dd0491892f92cb7c84fe5c39c62bcc6eceabeb1d
|
[
"MIT"
] | null | null | null |
use anyhow::Result;
use serde_json;
use std::sync::Arc;
use tokio::sync::{mpsc::Receiver, mpsc::Sender, Mutex};
use shared::{remote_conn_packet::*, device::*};
use super::{pod_packet::*, pod_packet_payload::*, pod_conn_svc::PodState};
pub struct LinkSvc {
pub device_list: Arc<Mutex<Vec<Device>>>,
pub pod_state: Arc<Mutex<PodState>>,
pub rx_auth: Receiver<RemotePacket>,
pub tx_auth: Sender<RemotePacket>,
pub rx_pod: Receiver<PodPacket>,
pub tx_pod: Sender<PodPacket>,
}
/// link_svc adds/removes/modifies devices to/from the pod
///
impl LinkSvc {
/// Main service task for link service
pub async fn run(mut self) -> Result<()> {
println!("link_svc: service running");
//self.populate_temp_data().await;
while let Some(mut pkt) = self.rx_auth.recv().await {
// process response based on cmd_type variable
let res = match pkt.cmd_type {
//32 is the beginning of the command space for link_svc
32 => self.get_device_list().await.unwrap(),
33 => self.add_device(pkt.payload[0].clone()).await.unwrap(),
34 => self.update_device(pkt.payload[0].clone()).await.unwrap(),
35 => self.remove_device(pkt.payload[0].clone()).await.unwrap(),
36 => self.send_device_cmd(pkt.target_cmd_code, pkt.payload[0].clone()).await.unwrap(),
62 => self.unlock_pod().await.unwrap(),
63 => self.lock_pod().await.unwrap(),
//63 is the end of the command space for link_svc
_ => s!["Command not implemented"]
};
// clear packet payload and add the response to payload vector
pkt.payload.clear();
pkt.payload.push(res);
// send modified packet to auth_svc
if let Err(e) = self.tx_auth.send(pkt).await {
eprintln!("link->auth failed: {}", e);
break;
}
}
println!("link_svc: service down");
Ok(())
}
async fn pod_is_unlocked(&mut self) -> bool {
match *self.pod_state.lock().await{
//return true if pod is in Unlocked state
PodState::Unlocked =>{
println!("Checking Pod State: Unlocked");
true
}
//otherwise, return false
_ => {
println!("Checking Pod State: NOT Unlocked");
false
}
}
}
/// Add new device to device list
///
/// Return success message to client
async fn add_device(&mut self, req: String) -> Result<String, serde_json::Error> {
//only follow through with the command if pod is in Unlocked state
if self.pod_is_unlocked().await {
println!("link_svc: add_device command received");
let dev: Device = serde_json::from_str(&req)?;
self.device_list.lock().await.push(dev);
println!("link_svc: device added");
Ok(s!["Device added"])
}
//otherwise, return a failure message
else{
Ok(s!["Pod must be unlocked first"])
}
}
async fn get_device_list(&self) -> Result<String, serde_json::Error> {
println!("link_svc: get_device_list command received");
serde_json::to_string(&self.device_list.lock().await.clone())
}
/// Lock device_list to start TCP connections to embedded devices in pod_conn_svc
/// Once locked, devices cannot be edited in "Configure" page until the pod is unlocked
async fn lock_pod(&mut self) -> Result<String, serde_json::Error> {
println!("link_svc: lock_devices command received");
//send lock command to pod_conn_svc
if let Err(e) = self.tx_pod.send(PodPacket::new(1,encode_payload(PodPacketPayload::new()))).await {
//if unsuccessful
//return error message
println!("link->pod failed: {}", e);
}
// if lock command was successful
match self.rx_pod.recv().await.unwrap().cmd_type{
0 =>{
// return new device_list
self.get_device_list().await
}
_=>{
// return new device_list
self.get_device_list().await
}
}
}
// Unlock device_list to stop TCP connections to embedded devices in pod_conn_svc
// Once unlocked, devices can be re-configured in the "Configure page" until pod is locked again
async fn unlock_pod(&mut self)-> Result<String, serde_json::Error>{
println!("link_svc: unlock_devices command received");
//send unlock command to pod_conn_svc
if let Err(e) = self.tx_pod.send(PodPacket::new(2,encode_payload(PodPacketPayload::new()))).await {
//if unsuccessful
//return error message
println!("link->pod failed: {}", e);
}
// if lock command was successful
match self.rx_pod.recv().await.unwrap().cmd_type{
0 =>{
println!("Unlock failed");
Ok(s!["unlock unsuccessful"])
}
_=>{
//return success message
Ok(s!["unlock successful"])
}
}
}
/// Find device received from client in device list and remove from vector
///
/// Return success message to client
async fn remove_device(&mut self, req: String) -> Result<String, serde_json::Error> {
//only follow through with the command if pod is in Unlocked state
if self.pod_is_unlocked().await {
println!("link_svc: remove_device command received");
let dev: Device = serde_json::from_str(&req)?;
let index = self.device_list.lock().await.iter().position(|d| d.id == dev.id).unwrap();
self.device_list.lock().await.remove(index);
println!("link_svc: device removed");
Ok(s!["Device removed"])
}
//otherwise, return a failure message
else{
Ok(s!["Pod must be unlocked first"])
}
}
/// Find device received from client in device list and update where id matches
///
/// Return success message to the client
async fn update_device(&mut self, req: String) -> Result<String, serde_json::Error> {
//only follow through with the command if pod is in Unlocked state
if self.pod_is_unlocked().await {
println!("link_svc: update_device command received");
let dev: Device = serde_json::from_str(&req)?;
let index = self.device_list.lock().await.iter().position(|d| d.id == dev.id).unwrap();
self.device_list.lock().await[index] = dev;
println!("link_svc: device updated");
Ok(s!["Device updated"])
}
//otherwise, return a failure message
else{
Ok(s!["Pod must be unlocked first"])
}
}
/// Get device and command code from client
/// Send the command to the corresponding device in device list
async fn send_device_cmd(&mut self, cmd_code: u8, req: String) -> Result<String, serde_json::Error> {
println!("link_svc: send_device_cmd command received");
//recontruct the Device instance from the payload
let dev: Device = serde_json::from_str(&req)?;
//construct a payload that specifies the target device and target cmd code
let mut payload = PodPacketPayload::new();
payload.target_id = dev.id;
payload.target_cmd_code = cmd_code;
//tell pod_conn_svc to send the command to the appropriate device
if let Err(e) = self.tx_pod.send(PodPacket::new(3,encode_payload(payload))).await {
//if unsuccessful
//return error message
println!("link->pod failed: {}", e);
}
//return success message
Ok(s!["Cmd sent to device"])
}
}
| 35.794643
| 107
| 0.581317
|
256f17eea7ecd39ff55755973ff6fc5f5b00a6d1
| 10,535
|
js
|
JavaScript
|
maker.js
|
kalen-oyphanith/Muzic-Room
|
c47826e8c0692ef6fc5f53edb35cbae4922e0f4f
|
[
"Apache-2.0"
] | null | null | null |
maker.js
|
kalen-oyphanith/Muzic-Room
|
c47826e8c0692ef6fc5f53edb35cbae4922e0f4f
|
[
"Apache-2.0"
] | null | null | null |
maker.js
|
kalen-oyphanith/Muzic-Room
|
c47826e8c0692ef6fc5f53edb35cbae4922e0f4f
|
[
"Apache-2.0"
] | null | null | null |
newer version
const handlePost = (e) => {
e.preventDefault();
$("#postMessage").animate({width: 'hide'}, 350);
if($("#postHeading").val() == '' || $("#postBlogPost").val() == '') {
handleError("A heading and your post are required!");
return false;
}
sendAjax('POST', $("#postForm").attr("action"), $("#postForm").serialize(), function() {
loadPostsFromServer();
});
alert("You made a new post!");
return false;
};
const handleUpdate = (e) => {
e.preventDefault();
$("#postMessage").animate({width:'hide'}, 350);
if($("#pass").val() == '' || $("#pass2").val() == '') {
handleError("All fields are required to change password");
return false;
}
if($("#pass").val() !== $("#pass2").val()){
handleError("Passwords do not match");
return false;
}
alert("You have changed your password");
sendAjax('POST', $("#settingsForm").attr("action"), $("#settingsForm").serialize(), redirect);
return false;
};
const PostForm = (props) => {
return (
<form id="postForm"
onSubmit={handlePost}
name="postForm"
action="/maker"
method="POST"
className="postForm"
>
<label htmlFor="heading">Heading: </label>
<input id="postHeading" type="text" name="heading" placeholder="Heading" />
<br></br>
<label htmlFor="nickName">Name: </label>
<input id="nickName" type="text" name="nickName" placeholder="Nick name (optional)" />
<br></br>
<label htmlFor="blogPost">Post: </label>
<textarea rows="5" cols="40" id="postBlogPost" type="text" name="blogPost" placeholder="write a post!"></textarea>
<input type="hidden" name="_csrf" value={props.csrf} />
<input id="postButton" className="makePostSubmit" type="submit" value="Make Post" />
</form>
);
};
const SettingsForm = (props) => {
return (
<form id="settingsForm"
onSubmit={handleUpdate}
name="settingsForm"
action="/passUpdate"
method="POST"
className="settingsForm"
>
<label htmlFor="passwordChange">Password change:</label>
<br></br>
<input id="pass" type="text" name="pass" placeholder="New password" />
<br></br>
<input id="pass2" type="text" name="pass2" placeholder="Confirm new password" />
<br></br>
<input type="hidden" name="_csrf" value={props.csrf} />
<input className="formSubmit" type="submit" value="Update" />
</form>
);
};
const DeleteForm = (props) => {
return (
<form id="deleteForm"
name="deleteForm"
action="/deletePosts"
method="POST"
className="deleteForm"
>
<input type="hidden" name="_csrf" value={props.csrf} />
<input id="deleteBtn" type="button" name="deleteBtn" value="Delete All Posts" onClick={deleteAll} />
</form>
);
};
const PostList = function(props) {
if(props.posts.length === 0) {
return(
<div>
<h3 className="emptyPost">No Posts yet</h3>
</div>
);
}
const postNodes = props.posts.map(function(post) {
// https://www.freecodecamp.org/news/javascript-date-now-how-to-get-the-current-date-in-javascript/
let today = new Date(post.createdDate);
let dayCreated = today.toLocaleDateString();
return (
<div key={post._id} className="post">
<h2> <img src="/assets/img/userFace.png" alt="pfp" /> {post.username} </h2>
<p> {dayCreated} </p>
<h3 id="postHead"> {post.heading.replace(/'|"/gi, "'")} </h3>
<p> {post.blogPost.replace(/'|"/gi, "'")} </p>
<p> {post.nickName} </p>
</div>
);
});
return (
<div>
{postNodes}
</div>
);
};
const FeedWindow = () => {
return(
<div>
<h1>The Muzic Room</h1>
<p>Here's what other people are saying!</p>
</div>
);
};
const ClearWindow = () => {
return(
<p></p>
);
};
const ProfileWindow = () => {
return (
<div>
<h1>My Profile</h1>
</div>
);
};
const SettingsHeadingWindow = function(props) {
return (
<div>
<h1>My Account</h1>
</div>
);
};
class PremButton extends React.Component {
constructor(){
super();
this.state = {
hidden: true
}
}
changeVis(){
this.setState({hidden: !this.state.hidden})
}
render(){
let grid = this.state.hidden ? "hidden" : "show";
return(
<div>
<input id="subscribeButton" type="submit" onClick={this.changeVis.bind(this)} value="Subscribe"/>
<span id="gridContainer" className={grid}>
<img src="/assets/img/sheet_1.png" alt="Sheet Music" />
<img src="/assets/img/sheet_2.jpg" alt="Sheet Music" />
<img src="/assets/img/sheet_3.png" alt="Sheet Music" />
<img src="/assets/img/sheet_4.jpg" alt="Sheet Music" />
<img src="/assets/img/sheet_5.jpg" alt="Sheet Music" />
<img src="/assets/img/sheet_6.jpg" alt="Sheet Music" />
</span>
</div>
);
};
}
const PremiumWindow = () => {
return (
<div>
<h1>Get Your Sheet Music!</h1>
<p>Learn more songs quickly with our sheet music provided!</p>
</div>
);
};
const PremiumBodyWindow = () => {
return(
<div id="gridContainer">
<img src="/assets/img/sheet_1.png" alt="Sheet Music" />
<img src="/assets/img/sheet_2.jpg" alt="Sheet Music" />
<img src="/assets/img/sheet_3.png" alt="Sheet Music" />
<img src="/assets/img/sheet_4.jpg" alt="Sheet Music" />
<img src="/assets/img/sheet_5.jpg" alt="Sheet Music" />
<img src="/assets/img/sheet_6.jpg" alt="Sheet Music" />
</div>
);
};
const createFeedWindow = (csrf) => {
ReactDOM.render(
<FeedWindow csrf={csrf} />,
document.querySelector("#header")
);
ReactDOM.render(
<ClearWindow csrf={csrf} />,
document.querySelector("#deleteAllPosts")
);
ReactDOM.render(
<ClearWindow csrf={csrf} />,
document.querySelector("#makePost")
);
ReactDOM.render(
<PostList posts={[]} />,
document.querySelector("#posts")
);
};
const createProfileWindow = (csrf) => {
ReactDOM.render(
<ProfileWindow csrf={csrf} />,
document.querySelector("#header")
);
ReactDOM.render(
<PostForm csrf={csrf} />, document.querySelector("#makePost")
);
ReactDOM.render(
<PostList posts={[]} />, document.querySelector("#posts")
);
ReactDOM.render(
<DeleteForm csrf={csrf} />, document.querySelector("#deleteAllPosts")
);
};
const createSettingsWindow = (csrf) => {
ReactDOM.render(
<SettingsHeadingWindow />, document.querySelector("#header")
);
ReactDOM.render(
<ClearWindow csrf={csrf} />,
document.querySelector("#deleteAllPosts")
);
ReactDOM.render(
<ClearWindow csrf={csrf} />,
document.querySelector("#makePost")
);
ReactDOM.render(
<SettingsForm csrf={csrf} />,
document.querySelector("#posts")
);
};
const createPremiumWindow = (csrf) => {
ReactDOM.render(
<PremiumWindow csrf={csrf} />,
document.querySelector("#header")
);
ReactDOM.render(
<ClearWindow csrf={csrf} />,
document.querySelector("#makePost")
);
ReactDOM.render(
<ClearWindow csrf={csrf} />,
document.querySelector("#deleteAllPosts")
);
ReactDOM.render(
<PremiumBodyWindow csrf={csrf} />,
document.querySelector("#posts")
);
ReactDOM.render(
<PremButton />, document.querySelector("#gridContainer")
);
// after subsribe button is clicked, disable it
document.querySelector('#subscribeButton').onclick = function() {
this.disabled = true;
}
};
const deleteAll = (e) => {
sendAjax('POST', $("#deleteForm").attr("action"), $("#deleteForm").serialize(), loadPostsFromServer());
};
const loadAllPostsFromServer = () => {
sendAjax('GET', '/getAllPosts', null, (data) => {
ReactDOM.render(
<PostList posts={data.posts} />, document.querySelector("#posts")
);
});
};
const loadPostsFromServer = () => {
sendAjax('GET', '/getPosts', null, (data) => {
ReactDOM.render(
<PostList posts={data.posts} />, document.querySelector("#posts")
);
});
};
const setup = function(csrf) {
const feedButton = document.querySelector("#allPostsButton");
const profileButton = document.querySelector("#profileButton");
const premiumButton = document.querySelector("#premiumButton");
const settingsButton = document.querySelector("#settingsButton");
feedButton.addEventListener("click", (e) => {
e.preventDefault();
createFeedWindow(csrf);
loadAllPostsFromServer();
return false;
});
profileButton.addEventListener("click", (e) => {
e.preventDefault();
createProfileWindow(csrf);
loadPostsFromServer();
return false;
});
premiumButton.addEventListener("click", (e) => {
e.preventDefault();
createPremiumWindow(csrf);
return false;
});
settingsButton.addEventListener("click", (e) => {
e.preventDefault();
createSettingsWindow(csrf);
return false;
});
loadAllPostsFromServer();
createFeedWindow(csrf);
};
const getToken = () => {
sendAjax("GET", '/getToken', null, (result) => {
setup(result.csrfToken);
});
};
$(document).ready(function() {
getToken();
});
| 27.650919
| 126
| 0.525771
|
875b5c4a980a12e2998b39f9fda4bdf0d8eb71b1
| 672
|
rb
|
Ruby
|
test/controllers/tasks_controller_test.rb
|
Scthe/RoR-test
|
b9b18f3f89ca02c438d72a2b0c7de6a2f45a3a75
|
[
"MIT"
] | null | null | null |
test/controllers/tasks_controller_test.rb
|
Scthe/RoR-test
|
b9b18f3f89ca02c438d72a2b0c7de6a2f45a3a75
|
[
"MIT"
] | null | null | null |
test/controllers/tasks_controller_test.rb
|
Scthe/RoR-test
|
b9b18f3f89ca02c438d72a2b0c7de6a2f45a3a75
|
[
"MIT"
] | null | null | null |
require 'test_helper'
class TasksControllerTest < ActionController::TestCase
test "should get index" do
get :index
assert_response :success
assert_template :index
assert_template layout: "layouts/application"
end
test "should get show" do
get :show, id: 1
assert_response :success
assert_template :show
assert_template layout: "layouts/application"
end
test "should get edit" do
get :edit, id: 1
assert_response :success
assert_template :edit
assert_template layout: "layouts/application"
end
test "should get new" do
get :new
assert_response :success
assert_template :new
assert_template layout: "layouts/application"
end
end
| 20.363636
| 54
| 0.760417
|
e28384551c439286bfc28c089a0ea7abc504fe62
| 16,227
|
py
|
Python
|
main.py
|
MartinDolenc/OPB-Ne_se_ena_spletna_trgovina
|
a4c158724100e0facf03777ca70b343e37963b80
|
[
"MIT"
] | null | null | null |
main.py
|
MartinDolenc/OPB-Ne_se_ena_spletna_trgovina
|
a4c158724100e0facf03777ca70b343e37963b80
|
[
"MIT"
] | 1
|
2021-09-04T17:01:58.000Z
|
2021-09-07T08:54:50.000Z
|
main.py
|
MartinDolenc/OPB-Ne_se_ena_spletna_trgovina
|
a4c158724100e0facf03777ca70b343e37963b80
|
[
"MIT"
] | null | null | null |
#!/usr/bin/python
# -*- encoding: utf-8 -*-
# uvozimo bottle.py
from bottle import *
# uvozimo ustrezne podatke za povezavo
import auth_public as auth
#uvozimo paket, za datume
import datetime
# uvozimo psycopg2
import psycopg2, psycopg2.extensions, psycopg2.extras
psycopg2.extensions.register_type(psycopg2.extensions.UNICODE) # se znebimo problemov s šumniki
import hashlib # računanje MD5 kriptografski hash za gesla
import json # za shranjevanje košare
# odkomentiraj, če želiš sporočila o napakah
debug(True)
secret = "to skrivnost je zelo tezko uganiti 1094107c907cw982982c42"
adminGeslo = "1234"
######################################################################
# seznami in slovarji za pomoč
kategorije = ["Filmi", "Glasba", "Igre", "Knjige", "TV serije"]
slovar_kategorij = {"Filmi": "Film", "Glasba": "Glasba", "Igre": "Igra", "Knjige": "Knjiga", "TV serije": "TV serija"}
######################################################################
# Pomožne funkcije
def password_md5(s):
"""Vrni MD5 hash danega UTF-8 niza. Gesla vedno spravimo v bazo
kodirana s to funkcijo."""
h = hashlib.md5()
h.update(s.encode('utf-8'))
return h.hexdigest()
def get_user():
"""Poglej cookie in ugotovi, kdo je prijavljeni uporabnik,
vrni njegov username in ime. Če ni prijavljen, presumeri
na stran za prijavo ali vrni None (advisno od auto_login).
"""
# Dobimo username iz piškotka
username = request.get_cookie('username', secret=secret)
# Preverimo, ali ta uporabnik obstaja
if username is not None:
cur.execute("SELECT username FROM uporabnik WHERE username=%s", [username])
r = cur.fetchone()
if r is not None:
# uporabnik obstaja, vrnemo njegove podatke
return username
# Če pridemo do sem, uporabnik ni prijavljen, naredimo redirect
else:
return None
def is_admin(username):
if username is not None:
cur.execute("SELECT isadmin FROM uporabnik WHERE username=%s", [username])
return cur.fetchone()[0]
else:
return False
def postani_admin():
username = get_user()
adminPassword = request.forms.adminPassword
password = request.forms.password
cur.execute("SELECT * FROM izdelek ORDER BY ocena DESC")
izdelki = cur.fetchall()
cur.execute("SELECT id, ime FROM izdelek ORDER BY RANDOM() LIMIT 1")
randIzdelek = cur.fetchone()
if password == "":
if adminPassword == adminGeslo:
cur.execute("UPDATE uporabnik SET isadmin = True WHERE username=%s", [username])
admin = is_admin(username)
return template('zacetna_stran.html', kategorije=kategorije, napakaO=None, username=username, admin=admin, izdelki=izdelki, idRandIzdelek=randIzdelek[0], imeRandIzdelek=randIzdelek[1])
else:
admin = is_admin(username)
return template('zacetna_stran.html', kategorije=kategorije, napakaO="Vnesili ste napačno admin geslo.", username=username,
admin=admin, izdelki=izdelki, idRandIzdelek=randIzdelek[0], imeRandIzdelek=randIzdelek[1])
else:
cur.execute("SELECT password FROM uporabnik WHERE username=%s", [username])
if cur.fetchone()[0] == password_md5(password):
cur.execute("DELETE FROM uporabnik WHERE username=%s", [username])
response.delete_cookie('username')
return template('zacetna_stran.html', kategorije=kategorije, napakaO=None, username=None, admin=None, izdelki=izdelki, idRandIzdelek=randIzdelek[0], imeRandIzdelek=randIzdelek[1])
else:
admin = is_admin(username)
return template('zacetna_stran.html', kategorije=kategorije, napakaO="Vnesili ste napačno geslo.", username=username, admin=admin, izdelki=izdelki, idRandIzdelek=randIzdelek[0], imeRandIzdelek=randIzdelek[1])
def vsebina_kosare():
"""Funkcija za pridobivanje vsebine košarice kot množice."""
kosara = request.get_cookie('kosara', secret=secret)
if kosara is None:
return set()
try:
return set(json.loads(kosara))
except json.JSONDecodeError:
return set()
# Pomožne funkcije
######################################################################
@get('/static/<filename:path>')
def static(filename):
return static_file(filename, root='static')
@get('/')
def index():
username = get_user()
admin = is_admin(username)
cur.execute("SELECT * FROM izdelek ORDER BY ocena DESC")
izdelki = cur.fetchall()
cur.execute("SELECT id, ime FROM izdelek ORDER BY RANDOM() LIMIT 1")
randIzdelek = cur.fetchone()
return template('zacetna_stran.html', kategorije=kategorije, napakaO=None, username=username,
admin=admin, izdelki=izdelki, idRandIzdelek=randIzdelek[0], imeRandIzdelek=randIzdelek[1])
@post('/postani_admin')
def postani_admin_post():
postani_admin()
redirect('/')
@get('/Login')
def login():
return template('Login.html', napaka=None)
@post('/Login')
def login_post():
"""Obdelaj izpolnjeno formo za prijavo"""
# Uporabniško ime, ki ga je uporabnik vpisal v formo
username = request.forms.username
# Izračunamo MD5 has gesla, ki ga bomo spravili
password = password_md5(request.forms.password)
# Preverimo, ali se je uporabnik pravilno prijavil
cur.execute("SELECT * FROM uporabnik WHERE username=%s AND password=%s", [username, password])
if cur.fetchone() is None:
# Username in geslo se ne ujemata
return template("Login.html", napaka="Uporabnik ne obstaja", username=username)
else:
# Vse je v redu, nastavimo cookie in preusmerimo na glavno stran
response.set_cookie('username', username, path='/', secret=secret)
redirect('/')
@get("/Logout")
def logout():
"""Pobriši cookie in preusmeri na login."""
response.delete_cookie('username')
redirect('/')
@get('/Register')
def register():
return template('Register.html', username=None, napaka=None)
@post("/Register")
def register_post():
print('trying to register')
"""Registriraj novega uporabnika."""
username = request.forms.username
password1 = request.forms.password1
password2 = request.forms.password2
adminPassword = request.forms.adminPassword
adminCheck = request.forms.adminCheckbox
# Ali uporabnik že obstaja?
cur.execute("SELECT * FROM uporabnik WHERE username=%s", [username])
if cur.fetchone():
print('ime že zasedeno')
# Uporabnik že obstaja
return template("Register.html", username=username, napaka='To uporabniško ime je že zasedeno.')
elif not password1 == password2:
print('gesli se ne ujemata')
# Geslo se ne ujemata
return template("Register.html", username=username, napaka='Gesli se ne ujemata.')
else:
# Vse je v redu, vstavi novega uporabnika v bazo
print('ustvarjamo novega uporabnika')
if adminCheck == "kot admin":
if adminPassword == adminGeslo:
print('dodaj admina')
password = password_md5(password1)
cur.execute("INSERT INTO uporabnik (username, password, isadmin) VALUES (%s, %s, %s)",
(username, password, True))
# Daj uporabniku cookie
response.set_cookie('username', username, path='/', secret=secret)
redirect("/")
else:
return template("Register.html", username=username, napaka='Admin geslo ni pravilno.')
else:
print('ustvarimo navadnega uporabnika')
password = password_md5(password1)
cur.execute("INSERT INTO uporabnik (username, password, isadmin) VALUES (%s, %s, %s)",
(username, password, False))
# Daj uporabniku cookie
response.set_cookie('username', username, path='/', secret=secret)
redirect("/")
@post('/')
def iskanje():
username = get_user()
admin = is_admin(username)
search = request.forms.search
cur.execute("SELECT * FROM izdelek WHERE lower(ime) Like %s OR lower(proizvajalec) Like %s OR lower(kategorija) Like %s",
['%' + search + '%', '%' + search + '%', '%' + search + '%'])
izdelki = cur.fetchall()
return template('Iskanje.html', napakaO=None, kategorije=kategorije, napaka=None,
username=username, admin=admin, izdelki=izdelki)
@get('/kategorije/:x/')
def kategorija(x):
username = get_user()
admin = is_admin(username)
cur.execute("SELECT * FROM izdelek WHERE kategorija=%s", [slovar_kategorij[x]])
izdelki = cur.fetchall()
return template('Kategorija.html', x=x, napakaO=None, kategorije=kategorije, napaka=None,
username=username, admin=admin, izdelki=izdelki)
@get('/izdelek/:x/')
def izdelek(x):
username = get_user()
admin = is_admin(username)
if username is not None:
cur.execute("SELECT id FROM uporabnik WHERE username=%s", [username])
userid = cur.fetchone()[0]
else:
userid = -1
cur.execute("SELECT * FROM izdelek WHERE id = %s", [int(x)])
izdelek = cur.fetchall()
cur.execute("SELECT * FROM izdelek WHERE proizvajalec=%s AND id!=%s", [izdelek[0][2], int(x)])
izdelki = cur.fetchall()
if not izdelki:
cur.execute("SELECT * FROM izdelek WHERE kategorija=%s AND id!=%s", [izdelek[0][3], int(x)])
izdelki = cur.fetchall()
cur.execute("SELECT * FROM zazeljeni WHERE uporabnik = %s AND izdelek = %s", [userid, int(x)])
najljubsi = cur.fetchall()
najljubsi = len(najljubsi) == 1
vKosari = x in vsebina_kosare()
return template('Izdelek.html', x=x, napakaO=None, kategorije=kategorije, napaka=None, username=username,
admin=admin, izdelek=izdelek, izdelki=izdelki, najljubsi=najljubsi, vKosari=vKosari)
@post('/dodaj_med_zazeljene/:x/')
def dodaj_med_zazeljene(x):
username = get_user()
cur.execute("SELECT id FROM uporabnik WHERE username=%s", [username])
userid = cur.fetchone()[0]
dodaj = request.forms.dodaj
if dodaj == "ne":
cur.execute("DELETE FROM zazeljeni WHERE uporabnik=%s AND izdelek=%s", [userid, int(x)])
else:
cur.execute("INSERT INTO zazeljeni (uporabnik, izdelek) VALUES (%s, %s)", [userid, int(x)])
redirect("/izdelek/{}/".format(x))
@post('/dodaj_v_kosaro/:x/')
def dodaj_v_kosaro(x):
kosara = vsebina_kosare()
kosara.symmetric_difference_update({x}) # doda v košaro, če ga še ni, sicer ga odstrani
response.set_cookie('kosara', json.dumps(list(kosara)), path='/', secret=secret)
redirect("/izdelek/{}/".format(x))
@get('/kosara')
def kosara():
username = get_user()
admin = is_admin(username)
kosara = vsebina_kosare()
izdelki = []
if len(kosara) == 0:
napaka = 'Vaša košarica je prazna.'
izrisi = False
else:
napaka = None
izrisi = True
cur.execute("SELECT * FROM izdelek WHERE id IN ({})".format(", ".join("%s" for _ in kosara)), tuple(kosara))
izdelki = cur.fetchall()
brez_popusta = 0
z_popustom = 0
for i in izdelki:
brez_popusta += i[6]
z_popustom += i[6]*(100-i[5])/100
return template('kosara.html', izrisi=izrisi, napakaO=None, napaka=napaka, username=username, kategorije=kategorije,
izdelki=izdelki, admin=admin, stevilo_izdelkov=len(izdelki), brez_popusta=brez_popusta, z_popustom=z_popustom)
@get('/nakup')
def nakup():
username = get_user()
admin = is_admin(username)
kosara = vsebina_kosare()
cur.execute("SELECT * FROM izdelek WHERE id IN ({})".format(", ".join("%s" for _ in kosara)), tuple(kosara))
izdelki = cur.fetchall()
brez_popusta = 0
z_popustom = 0
for i in izdelki:
brez_popusta += i[6]
z_popustom += i[6] * (100 - i[5]) / 100
return template('nakup.html', napakaO=None, napaka=None, username=username, kategorije=kategorije,
izdelki=izdelki, admin=admin, stevilo_izdelkov=len(izdelki), brez_popusta=brez_popusta, z_popustom=z_popustom)
@post('/nakup')
def nakup_post():
username = get_user()
cur.execute("SELECT id FROM uporabnik WHERE username=%s", [username])
userid = cur.fetchone()[0]
cur.execute("INSERT INTO nakup (nacin_placila, uporabnik_id) VALUES (%s, %s)", [request.forms.nacin_placila, userid])
cur.execute("SELECT * FROM nakup WHERE uporabnik_id=%s ORDER BY stevilka_racuna DESC", [userid])
stevilka_racuna = cur.fetchone()[0]
kosara = vsebina_kosare()
for str in kosara: # to se pomoje da optimizirat da nimamo toliko sql poizvedb
id_izdelka = str.strip(' ')
cur.execute("SELECT cena, popust FROM izdelek WHERE id=%s", [id_izdelka])
cena_in_popust = cur.fetchone()
trenutna_cena_izdelka = cena_in_popust[0] * (100-cena_in_popust[1])/100
cur.execute("INSERT INTO kupljeni_izdelki (stevilka_racuna, id_izdelka, cena_ob_nakupu) VALUES (%s, %s, %s)",
[stevilka_racuna, id_izdelka, trenutna_cena_izdelka])
response.delete_cookie('kosara', path='/', secret=secret)
redirect("/")
@get('/zazeljeni')
def zazeljeni_get():
username = get_user()
admin = is_admin(username)
cur.execute("SELECT id FROM uporabnik WHERE username=%s", [username])
userid = cur.fetchone()[0]
cur.execute("SELECT * FROM zazeljeni WHERE uporabnik=%s", [userid])
zazelj = cur.fetchall()
izdelki = []
if not zazelj:
napaka = 'Nimate še dodanih zaželjenih izdelkov.'
izrisi = False
else:
napaka = None
izrisi = True
cur.execute("SELECT t.id, t.ime, t.proizvajalec, t.kategorija, t.ocena, t.popust, t.cena FROM izdelek AS t JOIN zazeljeni AS n ON (t.id = n.izdelek) WHERE n.uporabnik=%s", [userid])
izdelki = cur.fetchall()
return template('zazeljeni.html', izrisi=izrisi, napakaO=None, napaka=napaka, username=username, kategorije=kategorije,
izdelki=izdelki, admin=admin)
@get('/uredi_izdelek/:x/')
def uredi_izdelek(x):
username = get_user()
admin = is_admin(username)
cur.execute("SELECT * FROM izdelek WHERE id = %s", [int(x)])
podatki = cur.fetchall()
return template('uredi_izdelek.html', id=int(x), ime=podatki[0][1], proizvajalec=podatki[0][2], kategorija=podatki[0][3],
ocena=podatki[0][4], popust=podatki[0][5], cena=podatki[0][6], kategorije=kategorije, x=x,
napakaO=None, napaka=None, username=username, admin=admin)
@post('/uredi_izdelek/:x/')
def uredi_izdelek_post(x):
username = get_user()
admin = is_admin(username)
ime = request.forms.ime
proizvajalec = request.forms.proizvajalec
kategorija = request.forms.kategorija
ocena = request.forms.ocena
popust = request.forms.popust
cena = request.forms.cena
try:
cur.execute("UPDATE izdelek SET ime=%s, proizvajalec=%s, kategorija=%s, ocena=%s, popust=%s, cena=%s WHERE id=%s",
[ime, proizvajalec, kategorija, ocena, popust, cena, int(x)])
conn.commit()
except Exception as ex:
cur.execute("SELECT * FROM izdelek WHERE id = %s", [int(x)])
podatki = cur.fetchall()
return template('uredi_izdelek.html', id=int(x), ime=podatki[0][1], proizvajalec=podatki[0][2],
kategorija=podatki[0][3],
ocena=podatki[0][4], popust=podatki[0][5], cena=podatki[0][6], kategorije=kategorije, x=x,
napakaO=None, napaka='Zgodila se je napaka: %s' % ex, username=username, admin=admin)
redirect("/izdelek/{}/".format(x))
######################################################################
# Glavni program
# priklopimo se na bazo
conn = psycopg2.connect(database=auth.db, host=auth.host, user=auth.user, password=auth.password)
conn.set_isolation_level(psycopg2.extensions.ISOLATION_LEVEL_AUTOCOMMIT) # onemogočimo transakcije
cur = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)
# poženemo strežnik na portu 8080, glej http://localhost:8000/
run(host='localhost', port=8000, reloader=True)
| 38.181176
| 220
| 0.644543
|
06bbe9d86636c71b5ca39e7856774d2cb91442b0
| 3,351
|
py
|
Python
|
Main.py
|
KemenczkyP/Neural-Net-Visualization-Guided_Grad_CAM
|
a10d99d53a245540a7df1e9fb9046a6ea2a81118
|
[
"Apache-2.0"
] | null | null | null |
Main.py
|
KemenczkyP/Neural-Net-Visualization-Guided_Grad_CAM
|
a10d99d53a245540a7df1e9fb9046a6ea2a81118
|
[
"Apache-2.0"
] | null | null | null |
Main.py
|
KemenczkyP/Neural-Net-Visualization-Guided_Grad_CAM
|
a10d99d53a245540a7df1e9fb9046a6ea2a81118
|
[
"Apache-2.0"
] | null | null | null |
# -*- coding: utf-8 -*-
"""
Created on Fri Jul 19 13:46:40 2019
@author: KemenczkyP
"""
from __future__ import absolute_import, division, print_function, unicode_literals
# TensorFlow and tf.keras
import tensorflow as tf
from tensorflow import keras
# Helper libraries
import numpy as np
import matplotlib.pyplot as plt
import cv2 as cv
print(tf.__version__)
from kerasmodel import MyModel
from heatmap import HeatMap
#register Guided ReLU function
@tf.RegisterGradient("GuidedRelu")
def _GuidedReluGrad(op, grad):
gate_f = tf.cast(op.outputs[0] > 0, "float32") #for f^l > 0
gate_R = tf.cast(grad > 0, "float32") #for R^l+1 > 0
return gate_f * gate_R * grad
#%%
# Load dataset
fashion_mnist = keras.datasets.fashion_mnist
(train_images, train_labels), (test_images, test_labels) = fashion_mnist.load_data()
class_names = ['T-shirt/top',
'Trouser',
'Pullover',
'Dress',
'Coat',
'Sandal',
'Shirt',
'Sneaker',
'Bag',
'Ankle boot']
# scale data to [0,1]
train_images = (train_images / 255.0).astype(np.float32)
test_images = (test_images / 255.0).astype(np.float32)
#%%
#TRAIN
with tf.compat.v1.get_default_graph().gradient_override_map({'Relu': 'GuidedRelu'}): #use Guided ReLU
model = MyModel()
loss_fn = keras.losses.SparseCategoricalCrossentropy()
model.compile(optimizer='adam',
loss=loss_fn,
metrics=['accuracy'])
model.fit(train_images, train_labels, epochs=1,
batch_size = 100)
test_loss, test_acc = model.evaluate(test_images, test_labels)
#%%
#COMPUTE GRADIENTS AND VISUALIZE
#source:
# Grad-CAM: Visual Explanations from Deep Networks via Gradient-based Localization
# doi: 10.1109/iccv.2017.74
random_sample = np.random.randint(0, test_images.shape[0], 1)[0]
image = test_images[random_sample:random_sample+1,:,:] #
image = tf.convert_to_tensor(image)
label = test_labels[random_sample:random_sample+1]
im = tf.convert_to_tensor(np.reshape(image,(-1,image.shape[1], image.shape[2],1)), tf.float32)
with tf.GradientTape() as logits_tape, tf.GradientTape() as loss_tape:
loss_tape.watch(image)
logits = model(image)
loss_value = loss_fn(label, logits)
lastc = model.last_conv_value
guide = loss_tape.gradient(loss_value, image)
grads = logits_tape.gradient(logits, lastc)
GAP_pool = tf.keras.layers.AveragePooling2D((lastc.shape[1], lastc.shape[2]),
padding= 'valid',
strides = (1,1))(grads)
grad_c=tf.zeros(lastc.shape[1:3], tf.float32)
for idx in range(0,GAP_pool.shape[3]):
grad_c=tf.nn.relu(grad_c+lastc[0,:,:,idx]*GAP_pool[0,:,:,idx])
grad_cam, heatmap = HeatMap(grad_c,guide, dims = 2)
#show with heatmap
image = image.numpy() * 255 #rescale to original
image = np.squeeze(np.uint8(image))
RGB_img = cv.cvtColor(image, cv.COLOR_GRAY2BGR) #convert to "RGB" (size)
heatmap_img = cv.applyColorMap(np.uint8(heatmap), cv.COLORMAP_JET)
fin = cv.addWeighted(heatmap_img, 0.7, RGB_img, 0.3, 0)
plt.imshow(fin)
#cv.imshow('image_w_heatmap', fin)
| 28.887931
| 101
| 0.638615
|
b814ca4bb9e247a6f6ccdd43487eb6e1b35ccb5d
| 208
|
dart
|
Dart
|
bloc_example/lib/DataLayer/location.dart
|
KadriyeMacit/Flutter-BLoC-Pattern-with-Zomato
|
824237f4e3a586650ad8d7f9425fad425e726af3
|
[
"MIT"
] | null | null | null |
bloc_example/lib/DataLayer/location.dart
|
KadriyeMacit/Flutter-BLoC-Pattern-with-Zomato
|
824237f4e3a586650ad8d7f9425fad425e726af3
|
[
"MIT"
] | null | null | null |
bloc_example/lib/DataLayer/location.dart
|
KadriyeMacit/Flutter-BLoC-Pattern-with-Zomato
|
824237f4e3a586650ad8d7f9425fad425e726af3
|
[
"MIT"
] | null | null | null |
class Location {
final int id;
final String type;
final String title;
Location.fromJson(Map json)
: id = json['entity_id'],
type = json['entity_type'],
title = json['title'];
}
| 18.909091
| 35
| 0.600962
|
efc15e9cd70a7037d882f308b14ce11d789a412a
| 2,562
|
swift
|
Swift
|
FlexibleCollectionViewLayouts/FlexibleCollectionViewLayouts/Views/Cells/TextCell.swift
|
fahlout/FlexibleCollectionViewLayouts
|
1f72f2fc382798fac3963fb7beb39f516cde4e41
|
[
"MIT"
] | null | null | null |
FlexibleCollectionViewLayouts/FlexibleCollectionViewLayouts/Views/Cells/TextCell.swift
|
fahlout/FlexibleCollectionViewLayouts
|
1f72f2fc382798fac3963fb7beb39f516cde4e41
|
[
"MIT"
] | null | null | null |
FlexibleCollectionViewLayouts/FlexibleCollectionViewLayouts/Views/Cells/TextCell.swift
|
fahlout/FlexibleCollectionViewLayouts
|
1f72f2fc382798fac3963fb7beb39f516cde4e41
|
[
"MIT"
] | null | null | null |
import UIKit
let imageCache = NSCache<NSString, UIImage>()
public class TextCell: UICollectionViewCell {
/// The `UUID` for the data this cell is presenting.
var representedId: UUID?
public let label = UILabel()
public let imageView = UIImageView()
var sessionTask: URLSessionTask?
override public init(frame: CGRect) {
super.init(frame: frame)
setUp()
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setUp()
}
private func setUp() {
clipsToBounds = true
contentView.addSubview(label)
label.translatesAutoresizingMaskIntoConstraints = false
label.numberOfLines = 0
label.lineBreakMode = .byWordWrapping
label.textAlignment = .center
NSLayoutConstraint.activate([
label.leadingAnchor.constraint(equalTo: contentView.layoutMarginsGuide.leadingAnchor),
label.trailingAnchor.constraint(equalTo: contentView.layoutMarginsGuide.trailingAnchor),
label.topAnchor.constraint(equalTo: contentView.layoutMarginsGuide.topAnchor),
label.bottomAnchor.constraint(equalTo: contentView.layoutMarginsGuide.bottomAnchor)
])
contentView.addSubview(imageView)
imageView.translatesAutoresizingMaskIntoConstraints = false
imageView.contentMode = .scaleAspectFill
imageView.isHidden = true
NSLayoutConstraint.activate([
imageView.leadingAnchor.constraint(equalTo: contentView.leadingAnchor),
imageView.trailingAnchor.constraint(equalTo: contentView.trailingAnchor),
imageView.topAnchor.constraint(equalTo: contentView.topAnchor),
imageView.bottomAnchor.constraint(equalTo: contentView.bottomAnchor)
])
}
func configure(with data: DisplayData?) {
guard let image = data?.image else {
imageView.isHidden = true
return
}
imageView.isHidden = false
imageView.image = image
}
}
public class AutoSizeLoggingTextCell: TextCell {
public override func preferredLayoutAttributesFitting(_ layoutAttributes: UICollectionViewLayoutAttributes) -> UICollectionViewLayoutAttributes {
print(#function)
return super.preferredLayoutAttributesFitting(layoutAttributes)
}
public override func apply(_ layoutAttributes: UICollectionViewLayoutAttributes) {
print(#function)
super.apply(layoutAttributes)
}
}
| 34.621622
| 149
| 0.679938
|
a174ebf5b2ceb60084697b975604870be89b5620
| 789
|
ts
|
TypeScript
|
resources/assets/ts/utilities/form_watcher/form_watcher.ts
|
hung-nv/booking
|
88d19d0171822e4e2c066c3e7b272eb2a8714123
|
[
"MIT"
] | null | null | null |
resources/assets/ts/utilities/form_watcher/form_watcher.ts
|
hung-nv/booking
|
88d19d0171822e4e2c066c3e7b272eb2a8714123
|
[
"MIT"
] | null | null | null |
resources/assets/ts/utilities/form_watcher/form_watcher.ts
|
hung-nv/booking
|
88d19d0171822e4e2c066c3e7b272eb2a8714123
|
[
"MIT"
] | null | null | null |
export {
watchForm
}
declare var $, _;
// Store all origin values.
let old = [];
/**
* Watch change of form.
* @param className
* @param color
*/
function watchForm (className, color) {
$(() => {
let $form = $(className);
$form.find('input, select, textarea').each(function (index) {
let $this = $(this);
old[index] = {
value: $this.val(),
css: $this.css('background'),
};
$this.on('change', _.debounce(() => {
if ($this.val() == old[index]['value']) {
$this.css('background', old[index]['css']);
} else {
$this.css('background', color);
}
}, 300));
});
});
}
| 20.230769
| 69
| 0.424588
|
a859a3976341c1dbb203677c0eb15e2d1062676d
| 1,157
|
rs
|
Rust
|
src/commands/package/install.rs
|
ethankhall/cli-management
|
375a8248760a0f4dd956fe483b36fd8848779951
|
[
"BSD-3-Clause"
] | null | null | null |
src/commands/package/install.rs
|
ethankhall/cli-management
|
375a8248760a0f4dd956fe483b36fd8848779951
|
[
"BSD-3-Clause"
] | null | null | null |
src/commands/package/install.rs
|
ethankhall/cli-management
|
375a8248760a0f4dd956fe483b36fd8848779951
|
[
"BSD-3-Clause"
] | null | null | null |
use async_trait::async_trait;
use std::path::*;
use thiserror::Error;
use crate::cli::*;
use crate::commands::SubCommandExec;
use crate::package::{install_package, PackageError};
use crate::remote::DownloadedArtifact;
use crate::state::{get_current_state, update_links};
use crate::util::GlobalFolders;
#[derive(Error, Debug)]
pub enum InstallPackageError {
#[error(transparent)]
State(#[from] crate::state::StateError),
#[error(transparent)]
Package(#[from] PackageError),
#[error(transparent)]
Uknown(#[from] anyhow::Error),
}
#[async_trait]
impl SubCommandExec<InstallPackageError> for InstallToolSubCommand {
async fn execute(self, global_folder: &GlobalFolders) -> Result<(), InstallPackageError> {
let archive_path = DownloadedArtifact {
path: PathBuf::from(&self.archive_path),
etag: None,
};
install_package(&archive_path, self.overwrite, global_folder).await?;
let global_state = global_folder.global_state_file();
let container = get_current_state(&global_state).await?;
update_links(&container, global_folder).await?;
Ok(())
}
}
| 30.447368
| 94
| 0.691443
|
b0d60bd09d584f4888681f0f7267cee8f9b4bf0f
| 390
|
py
|
Python
|
A/KefaAndFirstSteps.py
|
shukkkur/hello-world
|
c6388c2bda387e850fdb928a8d40f769c5684fec
|
[
"CC0-1.0"
] | 11
|
2021-05-26T11:47:50.000Z
|
2022-03-08T14:31:02.000Z
|
A/KefaAndFirstSteps.py
|
shukkkur/hello-world
|
c6388c2bda387e850fdb928a8d40f769c5684fec
|
[
"CC0-1.0"
] | null | null | null |
A/KefaAndFirstSteps.py
|
shukkkur/hello-world
|
c6388c2bda387e850fdb928a8d40f769c5684fec
|
[
"CC0-1.0"
] | 4
|
2021-08-06T05:27:12.000Z
|
2022-03-22T14:05:41.000Z
|
__author__ = 'shukkkur'
'''
https://codeforces.com/problemset/problem/580/A
'''
n = int(input())
values = list(map(int, input().split()))
records = []
count = 1
for i in range(len(values)-1):
if values[i] <= values[i+1]:
count += 1
else:
records.append(count)
count = 1
records.append(count)
print(max(records))
| 16.25
| 48
| 0.538462
|
4bbc8f61d89f0e0364178dcd0abd5c9f08ad33d6
| 1,261
|
h
|
C
|
Include/gtGRBaseToolsDLLBuild.h
|
GPUOpen-Tools/common-src-AMDTBaseTools
|
eeac5a71882f74a7c216758f22d6b6cc9638ae98
|
[
"MIT"
] | 3
|
2016-12-07T17:22:19.000Z
|
2018-04-03T12:44:41.000Z
|
Include/gtGRBaseToolsDLLBuild.h
|
GPUOpen-Tools/common_src_amdtbasetools
|
eeac5a71882f74a7c216758f22d6b6cc9638ae98
|
[
"MIT"
] | null | null | null |
Include/gtGRBaseToolsDLLBuild.h
|
GPUOpen-Tools/common_src_amdtbasetools
|
eeac5a71882f74a7c216758f22d6b6cc9638ae98
|
[
"MIT"
] | 1
|
2020-10-28T22:19:14.000Z
|
2020-10-28T22:19:14.000Z
|
//=====================================================================
// Copyright 2016 (c), Advanced Micro Devices, Inc. All rights reserved.
//
/// \author AMD Developer Tools Team
/// \file gtGRBaseToolsDLLBuild.h
///
//=====================================================================
//------------------------------ gtGRBaseToolsDLLBuild.h ------------------------------
#ifndef __GTGRBASETOOLSDLLBUILD_H
#define __GTGRBASETOOLSDLLBUILD_H
// Under Win32 builds - define: GT_API to be:
// - When building BaseTools.lib: default
// - When building GRBaseTools.dll: __declspec(dllexport).
// - When building other projects: __declspec(dllimport).
// Also add -D "AMDTBASETOOLS_EXTERN" for Linux and HSA build infrastructure
#if defined(_WIN32)
#if defined(AMDTBASETOOLS_EXPORTS)
#define GT_API __declspec(dllexport)
#define GT_API_EXTERN __declspec(dllexport)
#elif defined(AMDTBASETOOLS_STATIC)
#define GT_API
#define GT_API_EXTERN
#else
#define GT_API __declspec(dllimport)
#define GT_API_EXTERN __declspec(dllimport)
#endif
#else
#define GT_API
#endif
#if defined(AMDTBASETOOLS_EXTERN)
#define GT_API_EXTERN extern
#endif
#endif //__GTGRBASETOOLSDLLBUILD_H
| 31.525
| 87
| 0.60904
|
bd0ba24258e1427d87eebe73e820c78b3600e527
| 3,603
|
html
|
HTML
|
index.html
|
rpalakkal/defund12-image-api
|
c3f4c43e6909565862aa40e71cb0a71ca2908ff1
|
[
"MIT"
] | 2
|
2020-06-22T13:34:17.000Z
|
2020-06-25T18:28:07.000Z
|
index.html
|
rpalakkal/defund12-image-api
|
c3f4c43e6909565862aa40e71cb0a71ca2908ff1
|
[
"MIT"
] | 2
|
2020-06-17T17:25:49.000Z
|
2020-06-18T15:03:36.000Z
|
index.html
|
rpalakkal/defund12-image-api
|
c3f4c43e6909565862aa40e71cb0a71ca2908ff1
|
[
"MIT"
] | 3
|
2020-06-17T16:43:10.000Z
|
2021-02-05T13:54:53.000Z
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Defund12 image</title>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link
href="https://unpkg.com/tailwindcss@^1.0/dist/tailwind.min.css"
rel="stylesheet"
/>
</head>
<body>
<div id="root"></div>
<script
crossorigin
src="https://unpkg.com/react@16/umd/react.production.min.js"
></script>
<script
crossorigin
src="https://unpkg.com/react-dom@16/umd/react-dom.production.min.js"
></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/6.26.0/babel.min.js"></script>
<script type="text/babel">
const App = () => {
const [city, setCity] = React.useState("City");
const [path, setPath] = React.useState("path");
const [color, setColor] = React.useState("blue");
const [titleSize, setTitleSize] = React.useState("120");
const [url, setUrl] = React.useState(null);
const handleSubmit = (e) => {
e.preventDefault();
const params = `path=${encodeURIComponent(
path.toLowerCase()
)}&city=${encodeURIComponent(city)}&color=${encodeURIComponent(
color
)}&titleSize=${encodeURIComponent(titleSize)}`;
const url = `https://defund12.vercel.app/api/insta?${params}`;
setUrl(url);
};
const colors = [
"yellow",
"magenta",
"green",
"blue",
"turquoise",
"orange",
"purple",
"pink",
"red",
];
return (
<div className="p-4">
<form onSubmit={handleSubmit} className="mb-10">
<textarea
onChange={(e) => setCity(e.target.value)}
value={city}
class="border block mb-3 rounded p-2"
placeholder="edit me"
></textarea>
<input
onChange={(e) => setPath(e.target.value)}
value={path}
class="border block mb-3 rounded p-2"
placeholder="path"
/>
<input
onChange={(e) => setTitleSize(e.target.value)}
value={titleSize}
class="border block mb-3 rounded p-2"
placeholder="120"
/>
<div className="mb-3">
{colors.map((colorItem) => (
<div>
<input
type="radio"
id={colorItem}
name={colorItem}
value={colorItem}
className="mr-2"
checked={color === colorItem}
onClick={() => setColor(colorItem)}
/>
<label for={colorItem}>{colorItem}</label>
</div>
))}
</div>
<button
type="submit"
className="bg-blue-500 p-2 px-3 rounded text-white"
>
Generate
</button>
</form>
{url && (
<div className="">
<a className="text-blue-500" href={url}>
{url}
</a>
<img src={url} className="mt-3 max-w-xl" />
</div>
)}
</div>
);
};
ReactDOM.render(<App />, document.getElementById("root"));
</script>
</body>
</html>
| 29.292683
| 103
| 0.452678
|
4993f6406a9a73a3ef0b60cd7b6145884beaf326
| 16,925
|
py
|
Python
|
koko/lib/dottext.py
|
TheBeachLab/kokopelli
|
529b8149a951363d2a027946464ea0bb22346428
|
[
"MIT"
] | null | null | null |
koko/lib/dottext.py
|
TheBeachLab/kokopelli
|
529b8149a951363d2a027946464ea0bb22346428
|
[
"MIT"
] | 1
|
2018-11-23T11:52:41.000Z
|
2018-11-23T11:52:41.000Z
|
koko/lib/dottext.py
|
TheBeachLab/kokopelli
|
529b8149a951363d2a027946464ea0bb22346428
|
[
"MIT"
] | null | null | null |
# koko.lib.dottext.py
# Simple dot matrix math-string based font.
# Modified by Francisco Sanchez
# original code by Matt Keeter
# matt.keeter@cba.mit.edu
# kokompe.cba.mit.edu
################################################################################
from koko.lib.shapes2d import *
def text(text, x, y, height = 1, align = 'CC'):
dx, dy = 0, -1
text_shape = None
for line in text.split('\n'):
line_shape = None
for c in line:
if not c in _glyphs.keys():
print 'Warning: Unknown character "%s" in koko.lib.text' % c
else:
chr_math = move(_glyphs[c], dx, dy)
if line_shape is None: line_shape = chr_math
else: line_shape += chr_math
dx += _glyphs[c].width + 0.1
dx -= 0.1
if line_shape is not None:
if align[0] == 'L':
pass
elif align[0] == 'C':
line_shape = move(line_shape, -dx / 2, 0)
elif align[0] == 'R':
line_shape = move(line_shape, -dx, 0)
text_shape += line_shape
dy -= 1.55
dx = 0
dy += 1.55
if text_shape is None: return None
if align[1] == 'T':
pass
elif align[1] == 'B':
text_shape = move(text_shape, 0, -dy,)
elif align[1] == 'C':
text_shape = move(text_shape, 0, -dy/2)
if height != 1:
text_shape = scale_xy(text_shape, 0, 0, height)
dx *= height
dy *= height
return move(text_shape, x, y)
_glyphs = {}
shape = triangle(0, 0, 0.35, 1, 0.1, 0)
shape += triangle(0.1, 0, 0.35, 1, 0.45, 1)
shape += triangle(0.35, 1, 0.45, 1, 0.8, 0)
shape += triangle(0.7, 0, 0.35, 1, 0.8, 0)
shape += rectangle(0.2, 0.6, 0.3, 0.4)
shape.width = 0.8
_glyphs['A'] = shape
shape = circle(0.25, 0.275, 0.275)
shape -= circle(0.25, 0.275, 0.175)
shape = shear_x_y(shape, 0, 0.35, 0, 0.1)
shape += rectangle(0.51, 0.61, 0, 0.35)
shape = move(shape, -0.05, 0)
shape.width = 0.58
_glyphs['a'] = shape
shape = circle(0.3, 0.725, 0.275)
shape -= circle(0.3, 0.725, 0.175)
shape += circle(0.3, 0.275, 0.275)
shape -= circle(0.3, 0.275, 0.175)
shape &= rectangle(0.3, 1, 0, 1)
shape += rectangle(0, 0.1, 0, 1)
shape += rectangle(0.1, 0.3, 0, 0.1)
shape += rectangle(0.1, 0.3, 0.45, 0.55)
shape += rectangle(0.1, 0.3, 0.9, 1)
shape.width = 0.575
_glyphs['B'] = shape
shape = circle(0.25, 0.275, 0.275)
shape -= circle(0.25, 0.275, 0.175)
shape &= rectangle(0.25, 1, 0, 0.275) + rectangle(0, 1, 0.275, 1)
shape += rectangle(0, 0.1, 0, 1)
shape += rectangle(0.1, 0.25, 0, 0.1)
shape.width = 0.525
_glyphs['b'] = shape
shape = circle(0.3, 0.7, 0.3) - circle(0.3, 0.7, 0.2)
shape += circle(0.3, 0.3, 0.3) - circle(0.3, 0.3, 0.2)
shape -= rectangle(0, 0.6, 0.3, 0.7)
shape -= triangle(0.3, 0.5, 1, 1.5, 1, -0.5)
shape -= rectangle(0.3, 0.6, 0.2, 0.8)
shape += rectangle(0, 0.1, 0.3, 0.7)
shape.width = 0.57
_glyphs['C'] = shape
shape = circle(0.275, 0.275, 0.275)
shape -= circle(0.275, 0.275, 0.175)
shape -= triangle(0.275, 0.275, 0.55, 0.55, 0.55, 0)
shape.width = 0.48
_glyphs['c'] = shape
shape = circle(0.1, 0.5, 0.5) - circle(0.1, 0.5, 0.4)
shape &= rectangle(0, 1, 0, 1)
shape += rectangle(0, 0.1, 0, 1)
shape.width = 0.6
_glyphs['D'] = shape
shape = reflect_x(_glyphs['b'], _glyphs['b'].width/2)
shape.width = _glyphs['b'].width
_glyphs['d'] = shape
shape = rectangle(0, 0.1, 0, 1)
shape += rectangle(0.1, 0.6, 0.9, 1)
shape += rectangle(0.1, 0.6, 0, 0.1)
shape += rectangle(0.1, 0.5, 0.45, 0.55)
shape.width = 0.6
_glyphs['E'] = shape
shape = circle(0.275, 0.275, 0.275)
shape -= circle(0.275, 0.275, 0.175)
shape -= triangle(0.1, 0.275, 0.75, 0.275, 0.6, 0)
shape += rectangle(0.05, 0.55, 0.225, 0.315)
shape &= circle(0.275, 0.275, 0.275)
shape.width = 0.55
_glyphs['e'] = shape
shape = rectangle(0, 0.1, 0, 1)
shape += rectangle(0.1, 0.6, 0.9, 1)
shape += rectangle(0.1, 0.5, 0.45, 0.55)
shape.width = 0.6
_glyphs['F'] = shape
shape = circle(0.4, 0.75, 0.25) - circle(0.4, 0.75, 0.15)
shape &= rectangle(0, 0.4, 0.75, 1)
shape += rectangle(0, 0.4, 0.45, 0.55)
shape += rectangle(0.15, 0.25, 0, 0.75)
shape.width = 0.4
_glyphs['f'] = shape
shape = circle(0.275, -0.1, 0.275)
shape -= circle(0.275, -0.1, 0.175)
shape &= rectangle(0, 0.55, -0.375, -0.1)
shape += circle(0.275, 0.275, 0.275) - circle(0.275, 0.275, 0.175)
shape += rectangle(0.45, 0.55, -0.1, 0.55)
shape.width = 0.55
_glyphs['g'] = shape
shape = circle(0.3, 0.7, 0.3) - circle(0.3, 0.7, 0.2)
shape += circle(0.3, 0.3, 0.3) - circle(0.3, 0.3, 0.2)
shape -= rectangle(0, 0.6, 0.3, 0.7)
shape += rectangle(0, 0.1, 0.3, 0.7)
shape += rectangle(0.5, 0.6, 0.3, 0.4)
shape += rectangle(0.3, 0.6, 0.4, 0.5)
shape.width = 0.6
_glyphs['G'] = shape
shape = rectangle(0, 0.1, 0, 1)
shape += rectangle(0.5, 0.6, 0, 1)
shape += rectangle(0.1, 0.5, 0.45, 0.55)
shape.width = 0.6
_glyphs['H'] = shape
shape = circle(0.275, 0.275, 0.275)
shape -= circle(0.275, 0.275, 0.175)
shape &= rectangle(0, 0.55, 0.275, 0.55)
shape += rectangle(0, 0.1, 0, 1)
shape += rectangle(0.45, 0.55, 0, 0.275)
shape.width = 0.55
_glyphs['h'] = shape
shape = rectangle(0, 0.5, 0, 0.1)
shape += rectangle(0, 0.5, 0.9, 1)
shape += rectangle(0.2, 0.3, 0.1, 0.9)
shape.width = 0.5
_glyphs['I'] = shape
shape = rectangle(0.025, 0.125, 0, 0.55)
shape += circle(0.075, 0.7, 0.075)
shape.width = 0.15
_glyphs['i'] = shape
shape = circle(0.275, 0.275, 0.275)
shape -= circle(0.275, 0.275, 0.175)
shape &= rectangle(0, 0.55, 0, 0.275)
shape += rectangle(0.45, 0.55, 0.275, 1)
shape.width = 0.55
_glyphs['J'] = shape
shape = circle(0.0, -0.1, 0.275)
shape -= circle(0.0, -0.1, 0.175)
shape &= rectangle(0, 0.55, -0.375, -0.1)
shape += rectangle(0.175, 0.275, -0.1, 0.55)
shape += circle(0.225, 0.7, 0.075)
shape.width = 0.3
_glyphs['j'] = shape
shape = rectangle(0, 0.6, 0, 1)
shape -= triangle(0.1, 1, 0.5, 1, 0.1, 0.6)
shape -= triangle(0.5, 0, 0.1, 0, 0.1, 0.4)
shape -= triangle(0.6, 0.95, 0.6, 0.05, 0.18, 0.5)
shape.width = 0.6
_glyphs['K'] = shape
shape = rectangle(0, 0.5, 0, 1)
shape -= triangle(0.1, 1, 0.5, 1, 0.1, 0.45)
shape -= triangle(0.36, 0, 0.1, 0, 0.1, 0.25)
shape -= triangle(0.6, 1, 0.5, 0.0, 0.18, 0.35)
shape -= triangle(0.1, 1, 0.6, 1, 0.6, 0.5)
shape.width = 0.5
_glyphs['k'] = shape
shape = rectangle(0, 0.6, 0, 0.1)
shape += rectangle(0, 0.1, 0, 1)
shape.width = 0.6
_glyphs['L'] = shape
shape = rectangle(0.025, 0.125, 0, 1)
shape.width = 0.15
_glyphs['l'] = shape
shape = rectangle(0, 0.1, 0, 1)
shape += rectangle(0.7, 0.8, 0, 1)
shape += triangle(0, 1, 0.1, 1, 0.45, 0)
shape += triangle(0.45, 0, 0.35, 0, 0, 1)
shape += triangle(0.7, 1, 0.8, 1, 0.35, 0)
shape += triangle(0.35, 0, 0.8, 1, 0.45, 0)
shape.width = 0.8
_glyphs['M'] = shape
shape = circle(0.175, 0.35, 0.175) - circle(0.175, 0.35, 0.075)
shape += circle(0.425, 0.35, 0.175) - circle(0.425, 0.35, 0.075)
shape &= rectangle(0, 0.65, 0.35, 0.65)
shape += rectangle(0, 0.1, 0, 0.525)
shape += rectangle(0.25, 0.35, 0, 0.35)
shape += rectangle(0.5, 0.6, 0, 0.35)
shape.width = 0.6
_glyphs['m'] = shape
shape = rectangle(0, 0.1, 0, 1)
shape += rectangle(0.5, 0.6, 0, 1)
shape += triangle(0, 1, 0.1, 1, 0.6, 0)
shape += triangle(0.6, 0, 0.5, 0, 0, 1)
shape.width = 0.6
_glyphs['N'] = shape
shape = circle(0.275, 0.275, 0.275)
shape -= circle(0.275, 0.275, 0.175)
shape &= rectangle(0, 0.55, 0.325, 0.55)
shape += rectangle(0, 0.1, 0, 0.55)
shape += rectangle(0.45, 0.55, 0, 0.325)
shape.width = 0.55
_glyphs['n'] = shape
shape = circle(0.3, 0.7, 0.3) - circle(0.3, 0.7, 0.2)
shape += circle(0.3, 0.3, 0.3) - circle(0.3, 0.3, 0.2)
shape -= rectangle(0, 0.6, 0.3, 0.7)
shape += rectangle(0, 0.1, 0.3, 0.7)
shape += rectangle(0.5, 0.6, 0.3, 0.7)
shape.width = 0.6
_glyphs['O'] = shape
shape = circle(0.275, 0.275, 0.275)
shape -= circle(0.275, 0.275, 0.175)
shape.width = 0.55
_glyphs['o'] = shape
shape = circle(0.3, 0.725, 0.275)
shape -= circle(0.3, 0.725, 0.175)
shape &= rectangle(0.3, 1, 0, 1)
shape += rectangle(0, 0.1, 0, 1)
shape += rectangle(0.1, 0.3, 0.45, 0.55)
shape += rectangle(0.1, 0.3, 0.9, 1)
shape.width = 0.575
_glyphs['P'] = shape
shape = circle(0.275, 0.275, 0.275)
shape -= circle(0.275, 0.275, 0.175)
shape += rectangle(0, 0.1, -0.375, 0.55)
shape.width = 0.55
_glyphs['p'] = shape
shape = circle(0.3, 0.7, 0.3) - circle(0.3, 0.7, 0.2)
shape += circle(0.3, 0.3, 0.3) - circle(0.3, 0.3, 0.2)
shape -= rectangle(0, 0.6, 0.3, 0.7)
shape += rectangle(0, 0.1, 0.3, 0.7)
shape += rectangle(0.5, 0.6, 0.3, 0.7)
shape += triangle(0.5, 0.1, 0.6, 0.1, 0.6, 0)
shape += triangle(0.5, 0.1, 0.5, 0.3, 0.6, 0.1)
shape.width = 0.6
_glyphs['Q'] = shape
shape = circle(0.275, 0.275, 0.275) - circle(0.275, 0.275, 0.175)
shape += rectangle(0.45, 0.55, -0.375, 0.55)
shape.width = 0.55
_glyphs['q'] = shape
shape = circle(0.3, 0.725, 0.275)
shape -= circle(0.3, 0.725, 0.175)
shape &= rectangle(0.3, 1, 0, 1)
shape += rectangle(0, 0.1, 0, 1)
shape += rectangle(0.1, 0.3, 0.45, 0.55)
shape += rectangle(0.1, 0.3, 0.9, 1)
shape += triangle(0.3, 0.5, 0.4, 0.5, 0.575, 0)
shape += triangle(0.475, 0.0, 0.3, 0.5, 0.575, 0)
shape.width = 0.575
_glyphs['R'] = shape
shape = circle(0.55, 0, 0.55) - scale_x(circle(0.55, 0, 0.45), 0.55, 0.8)
shape &= rectangle(0, 0.55, 0, 0.55)
shape = scale_x(shape, 0, 0.7)
shape += rectangle(0, 0.1, 0, 0.55)
shape.width = 0.385
_glyphs['r'] = shape
shape = circle(0.275, 0.725, 0.275)
shape -= circle(0.275, 0.725, 0.175)
shape -= rectangle(0.275, 0.55, 0.45, 0.725)
shape += reflect_x(reflect_y(shape, 0.5), .275)
shape.width = 0.55
_glyphs['S'] = shape
shape = circle(0.1625, 0.1625, 0.1625)
shape -= scale_x(circle(0.165, 0.165, 0.0625), 0.165, 1.5)
shape -= rectangle(0, 0.1625, 0.1625, 0.325)
shape += reflect_x(reflect_y(shape, 0.275), 0.1625)
shape = scale_x(shape, 0, 1.5)
shape.width = 0.4875
_glyphs['s'] = shape
shape = rectangle(0, 0.6, 0.9, 1) + rectangle(0.25, 0.35, 0, 0.9)
shape.width = 0.6
_glyphs['T'] = shape
shape = circle(0.4, 0.25, 0.25) - circle(0.4, 0.25, 0.15)
shape &= rectangle(0, 0.4, 0, 0.25)
shape += rectangle(0, 0.4, 0.55, 0.65)
shape += rectangle(0.15, 0.25, 0.25, 1)
shape.width = 0.4
_glyphs['t'] = shape
shape = circle(0.3, 0.3, 0.3) - circle(0.3, 0.3, 0.2)
shape &= rectangle(0, 0.6, 0, 0.3)
shape += rectangle(0, 0.1, 0.3, 1)
shape += rectangle(0.5, 0.6, 0.3, 1)
shape.width = 0.6
_glyphs['U'] = shape
shape = circle(0.275, 0.275, 0.275) - circle(0.275, 0.275, 0.175)
shape &= rectangle(0, 0.55, 0, 0.275)
shape += rectangle(0, 0.1, 0.275, 0.55)
shape += rectangle(0.45, 0.55, 0, 0.55)
shape.width = 0.55
_glyphs['u'] = shape
shape = triangle(0, 1, 0.1, 1, 0.35, 0)
shape += triangle(0.35, 0, 0.25, 0, 0, 1)
shape += reflect_x(shape, 0.3)
shape.width = 0.6
_glyphs['V'] = shape
shape = triangle(0, 0.55, 0.1, 0.55, 0.35, 0)
shape += triangle(0.35, 0, 0.25, 0, 0, 0.55)
shape += reflect_x(shape, 0.3)
shape.width = 0.6
_glyphs['v'] = shape
shape = triangle(0, 1, 0.1, 1, 0.25, 0)
shape += triangle(0.25, 0, 0.15, 0, 0, 1)
shape += triangle(0.15, 0, 0.35, 1, 0.45, 1)
shape += triangle(0.45, 1, 0.25, 0, 0.15, 0)
shape += reflect_x(shape, 0.4)
shape.width = 0.8
_glyphs['W'] = shape
shape = triangle(0, 0.55, 0.1, 0.55, 0.25, 0)
shape += triangle(0.25, 0, 0.15, 0, 0, 0.55)
shape += triangle(0.15, 0, 0.35, 0.5, 0.45, 0.5)
shape += triangle(0.45, 0.5, 0.25, 0, 0.15, 0)
shape += reflect_x(shape, 0.4)
shape.width = 0.8
_glyphs['w'] = shape
shape = triangle(0, 1, 0.125, 1, 0.8, 0)
shape += triangle(0.8, 0, 0.675, 0, 0, 1)
shape += reflect_x(shape, 0.4)
shape.width = 0.8
_glyphs['X'] = shape
shape = triangle(0, 0.55, 0.125, 0.55, 0.55, 0)
shape += triangle(0.55, 0, 0.425, 0, 0, 0.55)
shape += reflect_x(shape, 0.275)
shape.width = 0.55
_glyphs['x'] = shape
shape = triangle(0, 1, 0.1, 1, 0.45, 0.5)
shape += triangle(0.45, 0.5, 0.35, 0.5, 0, 1)
shape += reflect_x(shape, 0.4)
shape += rectangle(0.35, 0.45, 0, 0.5)
shape.width = 0.8
_glyphs['Y'] = shape
shape = triangle(0, 0.55, 0.1, 0.55, 0.325, 0)
shape += triangle(0.325, 0, 0.225, 0, 0, 0.55)
shape += reflect_x(shape, 0.275) + move(reflect_x(shape, 0.275), -0.225, -0.55)
shape &= rectangle(0, 0.55, -0.375, 0.55)
shape.width = 0.55
_glyphs['y'] = shape
shape = rectangle(0, 0.6, 0, 1)
shape -= triangle(0, 0.1, 0, 0.9, 0.45, 0.9)
shape -= triangle(0.6, 0.1, 0.15, 0.1, 0.6, 0.9)
shape.width = 0.6
_glyphs['Z'] = shape
shape = rectangle(0, 0.6, 0, 0.55)
shape -= triangle(0, 0.1, 0, 0.45, 0.45, 0.45)
shape -= triangle(0.6, 0.1, 0.15, 0.1, 0.6, 0.45)
shape.width = 0.6
_glyphs['z'] = shape
shape = MathTree.Constant(1)
shape.bounds = [0,0,0,0,None,None,None]
shape.shape = True
shape.width = 0.55
shape.xmin, shape.xmax = 0, 0.55
shape.ymin, shape.ymax = 0, 1
_glyphs[' '] = shape
shape = circle(0.075, 0.075, 0.075)
shape = scale_y(shape, 0.075, 3)
shape &= rectangle(0.0, 0.15, -0.15, 0.075)
shape -= triangle(0.075, 0.075, 0.0, -0.15, -0.5, 0.075)
shape += circle(0.1, 0.075, 0.075)
shape.width = 0.175
_glyphs[','] = shape
shape = circle(0.075, 0.075, 0.075)
shape.width = 0.15
_glyphs['.'] = shape
shape = rectangle(0, 0.1, 0.55, 0.8)
shape.width = 0.1
_glyphs["'"] = shape
shape = rectangle(0, 0.1, 0.55, 0.8) + rectangle(0.2, 0.3, 0.55, 0.8)
shape.width = 0.3
_glyphs['"'] = shape
shape = circle(0.075, 0.15, 0.075) + circle(0.075, 0.45, 0.075)
shape.width = 0.15
_glyphs[':'] = shape
shape = circle(0.075, 0.15, 0.075)
shape = scale_y(shape, 0.15, 3)
shape &= rectangle(0.0, 0.15, -0.075, 0.15)
shape -= triangle(0.075, 0.15, 0.0, -0.075, -0.5, 0.15)
shape += circle(0.075, 0.45, 0.075)
shape += circle(0.1, 0.15, 0.075)
shape.width = 0.15
_glyphs[';'] = shape
shape = rectangle(0.025, 0.125, 0.3, 1)
shape += circle(0.075, 0.075, 0.075)
shape.width = 0.1
_glyphs['!'] = shape
shape = rectangle(0.05, 0.4, 0.35, 0.45)
shape.width = 0.45
_glyphs['-'] = shape
shape = circle(0, 0.4, 0.6) - scale_x(circle(0, 0.4, 0.5), 0, 0.7)
shape &= rectangle(0, 0.6, -0.2, 1)
shape = scale_x(shape, 0, 1/2.)
shape.width = 0.3
_glyphs[')'] = shape
shape = circle(0.6, 0.4, 0.6) - scale_x(circle(0.6, 0.4, 0.5), 0.6, 0.7)
shape &= rectangle(0, 0.6, -0.2, 1)
shape = scale_x(shape, 0, 1/2.)
shape.width = 0.3
_glyphs['('] = shape
shape = rectangle(0, 0.3, 0, 1)
shape -= circle(0, 1, 0.2)
shape -= rectangle(0, 0.2, 0, 0.7)
shape.width = 0.3
_glyphs['1'] = shape
shape = circle(0.275, .725, .275)
shape -= circle(0.275, 0.725, 0.175)
shape -= rectangle(0, 0.55, 0, 0.725)
shape += rectangle(0, 0.55, 0, 0.1)
shape += triangle(0, 0.1, 0.45, 0.775, 0.55, 0.725)
shape += triangle(0, 0.1, 0.55, 0.725, 0.125, 0.1)
shape.width = 0.55
_glyphs['2'] = shape
shape = circle(0.3, 0.725, 0.275)
shape -= circle(0.3, 0.725, 0.175)
shape += circle(0.3, 0.275, 0.275)
shape -= circle(0.3, 0.275, 0.175)
shape -= rectangle(0, 0.275, 0.275, 0.725)
shape.width = 0.55
_glyphs['3'] = shape
shape = triangle(-0.10, 0.45, 0.4, 1, 0.4, 0.45)
shape += rectangle(0.4, 0.5, 0, 1)
shape -= triangle(0.4, 0.85, 0.4, 0.55, 0.1, 0.55)
shape &= rectangle(0, 0.5, 0, 1)
shape.width = 0.5
_glyphs['4'] = shape
shape = circle(0.325, 0.325, 0.325) - circle(0.325, 0.325, 0.225)
shape -= rectangle(0, 0.325, 0.325, 0.65)
shape += rectangle(0, 0.325, 0.55, 0.65)
shape += rectangle(0, 0.1, 0.55, 1)
shape += rectangle(0.1, 0.65, 0.9, 1)
shape.width = 0.65
_glyphs['5'] = shape
shape = circle(0.275, 0.725, 0.275) - scale_y(circle(0.275, 0.725, 0.175), .725, 1.2)
shape &= rectangle(0, 0.55, 0.725, 1)
shape -= triangle(0.275, 0.925, 0.55, 0.9, 0.55, 0.725)
shape = scale_y(shape, 1, 2)
shape = scale_x(shape, 0, 1.1)
shape -= rectangle(0.275, 0.65, 0., 0.7)
shape += rectangle(0, 0.1, 0.275, 0.45)
shape += circle(0.275, 0.275, 0.275) - circle(0.275, 0.275, 0.175)
shape.width = 0.55
_glyphs['6'] = shape
shape = rectangle(0, 0.6, 0.9, 1)
shape += triangle(0, 0, 0.475, 0.9, 0.6, 0.9)
shape += triangle(0, 0, 0.6, 0.9, 0.125, 0)
shape.width = 0.6
_glyphs['7'] = shape
shape = circle(0.3, 0.725, 0.275)
shape -= circle(0.3, 0.725, 0.175)
shape += circle(0.3, 0.275, 0.275)
shape -= circle(0.3, 0.275, 0.175)
shape.width = 0.55
_glyphs['8'] = shape
shape = reflect_x(reflect_y(_glyphs['6'], 0.5), _glyphs['6'].width/2)
shape.width = _glyphs['6'].width
_glyphs['9'] = shape
shape = circle(0.5, 0.5, 0.5) - scale_x(circle(0.5, 0.5, 0.4), 0.5, 0.7**0.5)
shape = scale_x(shape, 0, 0.7)
shape.width = 0.7
_glyphs['0'] = shape
shape = rectangle(0., 0.5, 0.45, 0.55)
shape += rectangle(0.2, 0.3, 0.25, 0.75)
shape.width = 0.55
_glyphs['+'] = shape
shape = triangle(0, 0, 0.425, 1, 0.55, 1)
shape += triangle(0, 0, 0.55, 1, 0.125, 0)
shape.width = 0.55
_glyphs['/'] = shape
shape = circle(0.275, 0.725, 0.275) - circle(0.275, 0.725, 0.175)
shape -= rectangle(0, 0.275, 0.45, 0.725)
shape += rectangle(0.225, 0.325, 0.3, 0.55)
shape += circle(0.275, 0.075, 0.075)
shape.width = 0.55
_glyphs['?'] = shape
del shape
| 25.643939
| 85
| 0.58257
|
a16ed003514e3d82a0bf7fde4d4a3473a0c1974b
| 2,226
|
ts
|
TypeScript
|
src/configs/index.ts
|
dannysofftie/express-api
|
94b1e7d7fbf5143806a0b4dc869052972f462cea
|
[
"MIT"
] | 2
|
2019-03-06T10:24:01.000Z
|
2019-03-19T02:36:25.000Z
|
src/configs/index.ts
|
dannysofftie/node-ts-app-scaffold
|
94b1e7d7fbf5143806a0b4dc869052972f462cea
|
[
"MIT"
] | 1
|
2020-08-21T08:58:42.000Z
|
2020-08-21T08:58:42.000Z
|
src/configs/index.ts
|
dannysofftie/express-api
|
94b1e7d7fbf5143806a0b4dc869052972f462cea
|
[
"MIT"
] | null | null | null |
import { config } from 'dotenv';
import { join } from 'path';
import { IEmailConfigs } from '../libraries/Email';
import { Application } from 'express';
export const uploadDirectories = {
png: join(__dirname, '..', '..', 'uploads', 'images'),
jpg: join(__dirname, '..', '..', 'uploads', 'images'),
jpeg: join(__dirname, '..', '..', 'uploads', 'images'),
gif: join(__dirname, '..', '..', 'uploads', 'gifs'),
doc: join(__dirname, '..', '..', 'uploads', 'documents'),
docx: join(__dirname, '..', '..', 'uploads', 'documents'),
csv: join(__dirname, '..', '..', 'uploads', 'documents'),
txt: join(__dirname, '..', '..', 'uploads', 'documents'),
other: join(__dirname, '..', '..', 'uploads', 'other'),
};
config();
export interface IConfig {
firebaseAccountJsonFile: string;
apiurl: string;
mongouri: string;
apikey?: string;
jwtsecret: string;
mail: IEmailConfigs;
appname: string;
rootPath: string;
}
const production = process.env.NODE_ENV === `production`;
const gsuite = true;
const serviceKey = /** require('../../config/sample-service-3fe9c0354d05.json') */ {};
export const configs: IConfig = {
apiurl: (() => {
if (production) {
return process.env.API_PROD_URL;
}
return process.env.API_LOCAL_URL;
})(),
mongouri: process.env.MONGO_PROD_URL,
jwtsecret: process.env.JWT_SECRET_KEY,
mail: {
host: process.env.APP_EMAIL_HOST,
port: process.env.APP_EMAIL_HOST.includes('gmail') || process.env.APP_EMAIL_HOST.includes('zoho') ? 465 : 25,
auth: {
user: process.env.APP_EMAIL_ADDRESS,
...(!gsuite && { pass: process.env.APP_EMAIL_PASSWORD }),
...(gsuite && {
type: 'OAuth2',
privateKey: serviceKey['private_key'],
serviceClient: serviceKey['client_id'],
}),
},
},
appname: process.env.APPLICATION_NAME,
rootPath: '/fht61s',
firebaseAccountJsonFile: join(__dirname, '..', '..', 'config', 'isample-adminsdk-adgra-26b5699c31.json'),
};
export default (app: Application, opts: any, done: (err?: Error) => void) => {
app.decorate('configs', configs);
};
| 32.735294
| 117
| 0.586253
|
975dab51cb03e46987799390c82394a9b488d84b
| 150
|
dart
|
Dart
|
lib/src/ui/f_widget/sublevel/hangman_ui_sublevel_exporter.dart
|
Root-101/citmatel_strawberry_hangman
|
1cf1a8c508f2b961ca96bc1d81243509b1826334
|
[
"Apache-2.0"
] | 2
|
2021-12-03T03:12:52.000Z
|
2021-12-05T02:34:08.000Z
|
lib/src/ui/f_widget/sublevel/hangman_ui_sublevel_exporter.dart
|
Root-101/citmatel_strawberry_hangman
|
1cf1a8c508f2b961ca96bc1d81243509b1826334
|
[
"Apache-2.0"
] | 26
|
2021-12-17T19:14:14.000Z
|
2022-02-27T17:15:31.000Z
|
lib/src/ui/f_widget/sublevel/hangman_ui_sublevel_exporter.dart
|
Root-101/citmatel_strawberry_hangman
|
1cf1a8c508f2b961ca96bc1d81243509b1826334
|
[
"Apache-2.0"
] | null | null | null |
library hangman_ui_sublevel_exporter;
//export all the levels widgets
export 'hangman_sublevel_loading.dart';
export 'hangman_sublevel_screen.dart';
| 25
| 39
| 0.846667
|
138c972f3b7b66ce5fa1bf065371d83b2d0db31b
| 1,069
|
rb
|
Ruby
|
app/controllers/application_controller.rb
|
bens640/Ask-a-Cuban
|
b7c130374f015950f0fa4f9fdb983c0a465f0431
|
[
"MIT"
] | 1
|
2016-03-06T18:22:25.000Z
|
2016-03-06T18:22:25.000Z
|
app/controllers/application_controller.rb
|
bens640/Ask-a-Cuban
|
b7c130374f015950f0fa4f9fdb983c0a465f0431
|
[
"MIT"
] | null | null | null |
app/controllers/application_controller.rb
|
bens640/Ask-a-Cuban
|
b7c130374f015950f0fa4f9fdb983c0a465f0431
|
[
"MIT"
] | null | null | null |
class ApplicationController < ActionController::Base
# Prevent CSRF attacks by raising an exception.
# For APIs, you may want to use :null_session instead.
protect_from_forgery with: :null_session
before_filter :mobile_login, :upvote_mobile, :downvote_mobile
private
def not_authenticated
redirect_to login_path, alert: "Please login first"
end
# Lets mobile app use params to pass in username
def mobile_login
if params[:username].present?
u = User.find_or_create_by(username: params[:username])
auto_login u
end
end
# Used by API to upvote an article by adding upvote=true to URL
def upvote_mobile
if params[:upvote]
current_user.votes.build(vote_params).save
end
end
# Used by API to downvote an article by adding downvote=true to URL
def downvote_mobile
if params[:downvote]
Vote.where(user_id:current_user.id).where(votable_id:params[:id]).destroy_all
end
end
def vote_params
{
votable_id: params[:id],
votable_type: "Item"
}
end
end
| 26.073171
| 84
| 0.707203
|
d07022082e37b48f77f637b644b8a76809b71b91
| 5,284
|
hpp
|
C++
|
libahafront/aha/front/lexer.hpp
|
dlarudgus20/newly-aha
|
4d80bf992af3d8e7a6ddcca3c38d5959059ec66f
|
[
"MIT"
] | 2
|
2017-08-12T11:23:37.000Z
|
2017-08-12T17:11:52.000Z
|
libahafront/aha/front/lexer.hpp
|
dlarudgus20/newly-aha
|
4d80bf992af3d8e7a6ddcca3c38d5959059ec66f
|
[
"MIT"
] | null | null | null |
libahafront/aha/front/lexer.hpp
|
dlarudgus20/newly-aha
|
4d80bf992af3d8e7a6ddcca3c38d5959059ec66f
|
[
"MIT"
] | null | null | null |
// The MIT License (MIT)
//
// Copyright (c) 2016 Im Kyeong-Hyeon (dlarudgus20@naver.com)
//
// 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.
#pragma once
#include <string>
#include <string_view>
#include <vector>
#include <deque>
#include <optional>
#include <variant>
#include <utility>
#include "source.hpp"
namespace aha::front
{
class lexer_error : public source_positional_error
{
public:
lexer_error(source& src, source_position pos, const std::string& msg)
: source_positional_error(src, pos, "lexer error: " + msg)
{
}
};
enum class lex_result
{
done, exhausted, eof, error
};
struct token_indent
{
unsigned level;
};
struct token_newline
{
};
struct token_punct
{
std::u32string str;
};
struct token_keyword
{
std::u32string str;
};
struct token_contextual_keyword
{
std::u32string str;
};
struct token_identifier
{
std::u32string str;
};
struct token_normal_string
{
char32_t delimiter;
std::u32string str;
};
struct token_raw_string
{
char32_t delimiter;
std::u32string str;
};
struct token_interpol_string_start
{
std::u32string str;
};
struct token_interpol_string_mid
{
std::u32string str;
};
struct token_interpol_string_end
{
std::u32string str;
};
struct token_number
{
unsigned radix;
std::string integer, fraction, exponent, postfix;
bool is_float;
};
struct token
{
source* ptr_src;
source_position beg;
source_position end;
std::variant<
token_indent,
token_newline,
token_punct,
token_keyword,
token_contextual_keyword,
token_identifier,
token_normal_string,
token_raw_string,
token_interpol_string_start,
token_interpol_string_mid,
token_interpol_string_end,
token_number
> data;
};
class lexer final
{
public:
lexer(const lexer&) = delete;
lexer& operator =(const lexer&) = delete;
lexer();
~lexer();
void clearBuffer();
void clearAll();
std::optional<token> lex(source& src);
lex_result getLastResult() const;
void enableInterpolatedBlockEnd(bool enable);
void setContextualKeyword(std::vector<std::u32string> keywords);
private:
void init();
enum class state
{
indent,
any,
after_comment,
error
};
std::deque<char32_t> m_buf;
source_position m_buf_beg;
std::u32string m_str_token;
source_position m_tok_beg;
state m_state;
std::u32string m_indent_str;
std::vector<std::size_t> m_indent_pos;
struct
{
bool identifier : 1;
bool unknown_number : 1;
bool binary : 1;
bool octal : 1;
bool heximal : 1;
bool decimal : 1;
bool punct : 1;
bool normal_string : 1;
bool raw_string : 1;
bool interpol_string : 1;
bool comment_line : 1;
bool comment_block : 1;
bool comment_block_contains_newline : 1;
bool comment_block_might_closing : 1;
bool commented_out : 1;
bool interpol_string_after : 1;
bool enable_interpol_block_end : 1;
} m_flags;
int m_idx_float_sep;
int m_idx_float_exp;
int m_idx_num_postfix;
lex_result m_last_result;
std::vector<std::u32string> m_contextual_keywords;
static bool isSeperator(char32_t ch);
static bool isIdentifierFirstChar(char32_t ch);
static bool isIdentifierChar(char32_t ch);
template <typename Exception>
void throwError(Exception&& ex)
{
m_state = state::error;
m_last_result = lex_result::error;
throw std::forward<Exception>(ex);
}
};
}
| 25.282297
| 81
| 0.603331
|
408676b44b7d8582496d97c7ef8d48ea746b3209
| 645
|
rb
|
Ruby
|
parser/lib/snt_utils.rb
|
kopylovvlad/lite_scss
|
88f6910e195adfde85153939cf903a7f387413d1
|
[
"MIT"
] | 7
|
2018-10-22T11:18:19.000Z
|
2022-03-26T10:42:58.000Z
|
parser/lib/snt_utils.rb
|
kopylovvlad/lite_scss
|
88f6910e195adfde85153939cf903a7f387413d1
|
[
"MIT"
] | null | null | null |
parser/lib/snt_utils.rb
|
kopylovvlad/lite_scss
|
88f6910e195adfde85153939cf903a7f387413d1
|
[
"MIT"
] | null | null | null |
###
# some utils for SpliterNodesTransformer
module SntUtils
private
def any_start?(node)
node.mixin_start? || node.selector_start?
end
def check_property?(node)
node.property? or node.property_with_variable?
end
def children_last_recursive(item, sub_level)
if sub_level.zero?
item
else
children_last_recursive(item.children.last, sub_level - 1)
end
end
def valid_node?(node)
(any_start?(node) || check_property?(node) ||
node.mixin_using? || any_close?(node) ||
node.variable_assinment?)
end
def any_close?(node)
close_selector?(node) || close_mixin?(node)
end
end
| 20.15625
| 64
| 0.689922
|
3952b842268b65d2abb63e5b8cdf8e0a4b5a2adc
| 5,101
|
py
|
Python
|
logparsing/sentinel-log-agent.py
|
piyush82/sentinel-agents
|
926649b6f258e2143b07f75995993edd9e2c4227
|
[
"Apache-2.0"
] | null | null | null |
logparsing/sentinel-log-agent.py
|
piyush82/sentinel-agents
|
926649b6f258e2143b07f75995993edd9e2c4227
|
[
"Apache-2.0"
] | null | null | null |
logparsing/sentinel-log-agent.py
|
piyush82/sentinel-agents
|
926649b6f258e2143b07f75995993edd9e2c4227
|
[
"Apache-2.0"
] | null | null | null |
# -----------------------------------------------------------------------------
# Copyright (c) 2017. ZHAW - ICCLab
# All Rights Reserved.
#
# 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.
#
#
#
# Author: Piyush Harsh,
# URL: piyush-harsh.info
# ------------------------------------------------------------------------------
import configparser
import time
from datetime import datetime
from kafka import KafkaProducer
from pygtail import Pygtail
config = configparser.RawConfigParser()
config.read("sentinel-agent.conf")
def get_section():
return config.sections()
def get_elements(section_name):
return config[section_name]
def get_element_value(section_name, element_name):
return config[section_name][element_name]
def get_kafka_producer(endpoint, key_serializer, value_serializer):
if key_serializer == "StringSerializer" and value_serializer == "StringSerializer":
return KafkaProducer(linger_ms=1, acks='all', retries=0, key_serializer=str.encode,
value_serializer=str.encode, bootstrap_servers=[endpoint])
kafka_producer = get_kafka_producer(get_element_value("kafka-endpoint", "endpoint"),
get_element_value("kafka-endpoint", "keySerializer"),
get_element_value("kafka-endpoint", "valueSerializer"))
def send_msg(target_key, msg):
kafka_producer.send(get_element_value("sentinel", "topic"), key=target_key, value=msg)
def parse_elements(log_pattern, line):
values = dict()
map_keys = get_elements("mapping")
for key in map_keys:
values[key] = []
pattern_elements = str.split(log_pattern)
line_elements = str.split(line)
pos = 0;
for pattern in pattern_elements:
if pos < len(line_elements):
for key in map_keys:
conf_value = get_element_value("mapping", key)
if conf_value in pattern or pattern in conf_value:
if "msg" in pattern:
# go till end of the line
temp = str(line_elements[pos]).strip()
if len(temp) > 0:
values[key].append(temp)
while pos < len(line_elements) - 1 :
pos += 1
temp = str(line_elements[pos]).strip()
if len(temp) > 0:
values[key].append(temp)
else:
temp = str(line_elements[pos]).strip()
if len(temp) > 0:
values[key].append(temp)
pos += 1
return values
if __name__ == '__main__':
log_pattern = get_element_value("target-file", "logpattern")
while True:
for line in Pygtail(get_element_value("target-file", "filepath")):
values = parse_elements(log_pattern, line)
aggregated_values = dict()
map_keys = get_elements("mapping")
for key in map_keys:
aggregated_values[key] = ""
for element in values[key]:
if key == "unixtime":
if element != "-":
aggregated_values[key] += element + " "
else:
aggregated_values[key] += element + " "
unix_timestamp = datetime.strptime(str.rstrip(aggregated_values["unixtime"]), '%Y-%m-%d %H:%M:%S')
msg_to_send = ""
if "unixtime:ms" in get_element_value("target-file", "seriesPattern"):
msg_to_send += "unixtime:" + str(unix_timestamp.timestamp() * 1000)
elif "unixtime:s" in get_element_value("target-file", "seriesPattern"):
msg_to_send += "unixtime:" + str(unix_timestamp.timestamp())
elif "unixtime:ns" in get_element_value("target-file", "seriesPattern"):
msg_to_send += "unixtime:" + str(unix_timestamp.timestamp() * 1000000)
elif "unixtime:us" in get_element_value("target-file", "seriesPattern"):
msg_to_send += "unixtime:" + str(unix_timestamp.timestamp() * 1000000000)
for key in map_keys:
if key == "unixtime":
continue
msg_to_send += " " + key + ":" + str(aggregated_values[key]).strip().replace(" ", "_").replace(":", "@")
send_msg(get_element_value("target-file", "seriesName"), msg_to_send)
# print(aggregated_values)
time.sleep(1)
| 40.808
| 120
| 0.568908
|
a3b797d95b500a37ebe26458143d324d814901ec
| 889
|
java
|
Java
|
AllAvailable/app/src/main/java/com/cmu/smartphone/allavailable/ws/remote/DataReceiver.java
|
swen2014/AllAvailable
|
1149503f266d36fea2abf2da94b78c56bcd6f4b1
|
[
"Apache-2.0"
] | null | null | null |
AllAvailable/app/src/main/java/com/cmu/smartphone/allavailable/ws/remote/DataReceiver.java
|
swen2014/AllAvailable
|
1149503f266d36fea2abf2da94b78c56bcd6f4b1
|
[
"Apache-2.0"
] | null | null | null |
AllAvailable/app/src/main/java/com/cmu/smartphone/allavailable/ws/remote/DataReceiver.java
|
swen2014/AllAvailable
|
1149503f266d36fea2abf2da94b78c56bcd6f4b1
|
[
"Apache-2.0"
] | null | null | null |
package com.cmu.smartphone.allavailable.ws.remote;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
/**
* Receive the data to String
*
* @author Xi Wang
* @version 1.0
*/
public class DataReceiver {
/**
* Get json string
*
* @param inputStream
* @return
*/
public static String ChangeInputStream(InputStream inputStream) {
String jsonString = "";
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
int len = 0;
byte[] data = new byte[1024];
try {
while ((len = inputStream.read(data)) != -1) {
outputStream.write(data, 0, len);
}
jsonString = new String(outputStream.toByteArray());
} catch (IOException e) {
e.printStackTrace();
}
return jsonString;
}
}
| 23.394737
| 73
| 0.591676
|
1a750df49929bd7f73ea6f4b92a2c604b39c4f7c
| 6,044
|
py
|
Python
|
examples/custom_action/example_server/swagger_server/models/entity.py
|
ritvikshrivastava/mindmeld
|
48eccac059439ea0f32fa3ac9079415bb006233b
|
[
"Apache-2.0"
] | 580
|
2019-03-24T20:59:09.000Z
|
2022-03-23T17:06:43.000Z
|
examples/custom_action/example_server/swagger_server/models/entity.py
|
ritvikshrivastava/mindmeld
|
48eccac059439ea0f32fa3ac9079415bb006233b
|
[
"Apache-2.0"
] | 199
|
2019-04-30T18:15:46.000Z
|
2022-03-22T17:11:33.000Z
|
examples/custom_action/example_server/swagger_server/models/entity.py
|
Embodimentgeniuslm3/mindmeld
|
042d4ed5400cd1cf8ea1f025eea732359ef68720
|
[
"Apache-2.0"
] | 164
|
2019-04-25T08:27:28.000Z
|
2022-03-23T12:44:33.000Z
|
# coding: utf-8
from __future__ import absolute_import
from .base_model_ import Model
from .. import util
class Entity(Model):
"""NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
"""
def __init__(
self,
text: str = None,
type: str = None,
role: str = None,
value: object = None,
display_text: str = None,
confidence: float = None,
is_system_entity: bool = None,
):
"""Entity - a model defined in Swagger
:param text: The text of this Entity.
:type text: str
:param type: The type of this Entity.
:type type: str
:param role: The role of this Entity.
:type role: str
:param value: The value of this Entity.
:type value: object
:param display_text: The display_text of this Entity.
:type display_text: str
:param confidence: The confidence of this Entity.
:type confidence: float
:param is_system_entity: The is_system_entity of this Entity.
:type is_system_entity: bool
"""
self.swagger_types = {
"text": str,
"type": str,
"role": str,
"value": object,
"display_text": str,
"confidence": float,
"is_system_entity": bool,
}
self.attribute_map = {
"text": "text",
"type": "type",
"role": "role",
"value": "value",
"display_text": "display_text",
"confidence": "confidence",
"is_system_entity": "is_system_entity",
}
self._text = text
self._type = type
self._role = role
self._value = value
self._display_text = display_text
self._confidence = confidence
self._is_system_entity = is_system_entity
@classmethod
def from_dict(cls, dikt) -> "Entity":
"""Returns the dict as a model
:param dikt: A dict.
:type: dict
:return: The Entity of this Entity.
:rtype: Entity
"""
return util.deserialize_model(dikt, cls)
@property
def text(self) -> str:
"""Gets the text of this Entity.
The text contents that span the entity
:return: The text of this Entity.
:rtype: str
"""
return self._text
@text.setter
def text(self, text: str):
"""Sets the text of this Entity.
The text contents that span the entity
:param text: The text of this Entity.
:type text: str
"""
self._text = text
@property
def type(self) -> str:
"""Gets the type of this Entity.
Entity type
:return: The type of this Entity.
:rtype: str
"""
return self._type
@type.setter
def type(self, type: str):
"""Sets the type of this Entity.
Entity type
:param type: The type of this Entity.
:type type: str
"""
self._type = type
@property
def role(self) -> str:
"""Gets the role of this Entity.
Role type
:return: The role of this Entity.
:rtype: str
"""
return self._role
@role.setter
def role(self, role: str):
"""Sets the role of this Entity.
Role type
:param role: The role of this Entity.
:type role: str
"""
self._role = role
@property
def value(self) -> object:
"""Gets the value of this Entity.
The resolved value of the entity
:return: The value of this Entity.
:rtype: object
"""
return self._value
@value.setter
def value(self, value: object):
"""Sets the value of this Entity.
The resolved value of the entity
:param value: The value of this Entity.
:type value: object
"""
self._value = value
@property
def display_text(self) -> str:
"""Gets the display_text of this Entity.
A human readable text representation of the entity for use in natural language responses.
:return: The display_text of this Entity.
:rtype: str
"""
return self._display_text
@display_text.setter
def display_text(self, display_text: str):
"""Sets the display_text of this Entity.
A human readable text representation of the entity for use in natural language responses.
:param display_text: The display_text of this Entity.
:type display_text: str
"""
self._display_text = display_text
@property
def confidence(self) -> float:
"""Gets the confidence of this Entity.
A confidence value from 0 to 1 about how confident the entity recognizer was for the given class label.
:return: The confidence of this Entity.
:rtype: float
"""
return self._confidence
@confidence.setter
def confidence(self, confidence: float):
"""Sets the confidence of this Entity.
A confidence value from 0 to 1 about how confident the entity recognizer was for the given class label.
:param confidence: The confidence of this Entity.
:type confidence: float
"""
self._confidence = confidence
@property
def is_system_entity(self) -> bool:
"""Gets the is_system_entity of this Entity.
True if the entity is a system entity
:return: The is_system_entity of this Entity.
:rtype: bool
"""
return self._is_system_entity
@is_system_entity.setter
def is_system_entity(self, is_system_entity: bool):
"""Sets the is_system_entity of this Entity.
True if the entity is a system entity
:param is_system_entity: The is_system_entity of this Entity.
:type is_system_entity: bool
"""
self._is_system_entity = is_system_entity
| 25.183333
| 111
| 0.579252
|
aff492eb1089f85f487450357f19a324395a9ab9
| 3,875
|
py
|
Python
|
examples/locomotion/talos_warm_start.py
|
iit-DLSLab/crocoddyl
|
2b8b731fae036916ff9b4ce3969e2c96c009593c
|
[
"BSD-3-Clause"
] | null | null | null |
examples/locomotion/talos_warm_start.py
|
iit-DLSLab/crocoddyl
|
2b8b731fae036916ff9b4ce3969e2c96c009593c
|
[
"BSD-3-Clause"
] | null | null | null |
examples/locomotion/talos_warm_start.py
|
iit-DLSLab/crocoddyl
|
2b8b731fae036916ff9b4ce3969e2c96c009593c
|
[
"BSD-3-Clause"
] | null | null | null |
import conf_talos_warm_start as conf
import numpy as np
import pinocchio
from crocoddyl import (ActionModelImpact, CallbackDDPVerbose, CallbackSolverDisplay, ShootingProblem, SolverDDP,
StatePinocchio, a2m, m2a)
from crocoddyl.locomotion import ContactSequenceWrapper, createMultiphaseShootingProblem
from multicontact_api import ContactSequenceHumanoid, CubicHermiteSpline
np.set_printoptions(linewidth=400, suppress=True)
robot = conf.robot
rmodel = robot.model
rdata = robot.data
rmodel.defaultState = np.concatenate([m2a(robot.q0), np.zeros(rmodel.nv)])
# ----------------Load Contact Phases and PostProcess-----------------------
cs = ContactSequenceHumanoid(0)
cs.loadFromXML(conf.MUSCOD_CS_OUTPUT_FILENAME, conf.CONTACT_SEQUENCE_XML_TAG)
csw = ContactSequenceWrapper(cs, conf.contact_patches)
csw.createCentroidalPhi(rmodel, rdata)
csw.createEESplines(rmodel, rdata, conf.X_init, 0.005)
# ----------------Define Problem----------------------------
models = createMultiphaseShootingProblem(rmodel, rdata, csw, conf.DT)
# disp = lambda xs: disptraj(robot, xs)
problem = ShootingProblem(m2a(conf.X_init[0]), models[:-1], models[-1])
# Set contacts in the data elements. Ugly.
# This is defined for IAMEuler. If using IAMRK4, differential is a list. so we need to change.
for d in problem.runningDatas:
if hasattr(d, "differential"): # Because we also have the impact models without differntial.
for (patchname, contactData) in d.differential.contact.contacts.iteritems():
if "forces_" + patchname in d.differential.costs.costs:
d.differential.costs["forces_" + patchname].contact = contactData
# ---------Ugliness over------------------------
# -----------Create inital trajectory---------------
class Init:
X = []
U = []
init = Init()
x_tsid = np.matrix(conf.X_init).T
conf.ddq_init.append(np.zeros(rmodel.nv))
dx_tsid = np.vstack([x_tsid[rmodel.nv:, :], np.matrix(conf.ddq_init).T])
t_tsid = np.linspace(0., cs.contact_phases[-1].time_trajectory[-1], len(conf.ddq_init) + 1)
x_spl = CubicHermiteSpline(a2m(t_tsid), x_tsid, dx_tsid)
state = StatePinocchio(rmodel)
dt = conf.DT
def x_eval(t):
return m2a(x_spl.eval(t)[0])
for i, (m, d) in enumerate(zip(problem.runningModels, problem.runningDatas)):
# Impact models have zero timestep, thus they are copying the same state as the beginning of the next action model
# State and control are defined at the beginning of the time step.
if isinstance(m, ActionModelImpact):
init.X.append(x_eval((i + 1) * dt))
init.U.append(np.zeros(m.nu))
# print "impact at ",i
else:
xp = x_eval(i * dt)
xn = x_eval((i + 1) * dt)
init.X.append(xp)
dx = state.diff(xp, xn)
acc = dx[rmodel.nv:] / dt
u = pinocchio.rnea(rmodel, rdata, a2m(xp[:rmodel.nq]), a2m(xp[rmodel.nq:]), a2m(acc))
m.differential.calc(d.differential, init.X[-1])
contactJ = d.differential.contact.J
f = np.dot(np.linalg.pinv(contactJ.T[:6, :]), u[:6])
u -= (np.dot(contactJ.transpose(), f))
init.U.append(np.array(u[6:]).squeeze().copy())
init.X.append(conf.X_init[-1])
# ---------------Display Initial Trajectory--------------
if conf.DISPLAY:
robot.initDisplay(loadModel=True)
if conf.DISPLAY:
for x in init.X:
robot.display(a2m(x[:robot.nq]))
# sleep(0.005)
# ----------------------
ddp = SolverDDP(problem)
ddp.callback = [CallbackDDPVerbose()] # CallbackSolverTimer()]
if conf.RUNTIME_DISPLAY:
ddp.callback.append(CallbackSolverDisplay(robot, 4))
ddp.th_stop = 1e-9
ddp.solve(maxiter=1000, regInit=0.1, init_xs=init.X, init_us=init.U)
# ---------------Display Final Trajectory--------------
if conf.DISPLAY:
for x in init.X:
robot.display(a2m(x[:robot.nq]))
# sleep(0.005)
# ----------------------
| 38.366337
| 118
| 0.65729
|
be2f5c816061ab72cec783ac5ff6467be7bad43c
| 1,329
|
tsx
|
TypeScript
|
src/components/Sidebar/Sidebar.tsx
|
meowWhat/ReDark
|
293e6662fea3138e89fd83b4d32565f54c43ff88
|
[
"MIT"
] | 2
|
2020-03-27T14:07:56.000Z
|
2020-05-11T13:09:00.000Z
|
src/components/Sidebar/Sidebar.tsx
|
meowWhat/ReDark
|
293e6662fea3138e89fd83b4d32565f54c43ff88
|
[
"MIT"
] | 6
|
2020-12-04T20:06:24.000Z
|
2022-02-27T01:58:08.000Z
|
src/components/Sidebar/Sidebar.tsx
|
meowWhat/ReDark
|
293e6662fea3138e89fd83b4d32565f54c43ff88
|
[
"MIT"
] | null | null | null |
/**
* @Sidebar 侧边栏
*/
import React, { useState } from 'react'
import './Sidebar.less'
import SidebarGroup from './SidebarGroup/SidebarGroup'
import { Sidebar } from '..'
/**
* @groupArr 侧边栏数组
*/
interface Group {
url: string
text: string
chineseText: string
}
interface Sidebar {
groupArr: Array<{ group: Array<Group>; title: string }>
}
export default function (props: Sidebar) {
const { groupArr = [] } = props
const [active, setActive] = useState(false)
const initIconClass = () => {
let className = 'iconfont icon-xiangyou sidebar-icon-default'
if (active) {
className = `${className} sidebar-icon-active`
}
return className
}
const initSiderbarClass = () => {
let className = 'sidebar'
if (active) {
className = `${className} sidebar-active`
}
return className
}
return (
<>
<span
className={initIconClass()}
onClick={() => setActive((pre) => !pre)}
/>
<aside className={initSiderbarClass()}>
<ul className="sidebar-links">
{groupArr.map((arr) => {
const { group, title } = arr
return (
<li key={title}>
<SidebarGroup group={group} title={title} />
</li>
)
})}
</ul>
</aside>
</>
)
}
| 22.525424
| 65
| 0.555305
|
546467096f1441bcdf7a6127c896a10e44e84373
| 916
|
h
|
C
|
release/src/router/libsodium/src/libsodium/include/sodium/crypto_scalarmult_curve25519.h
|
ghsecuritylab/bcwifi
|
4cd7a6989921930f39816583014728b9f07a09a3
|
[
"FSFAP"
] | 34
|
2015-05-04T23:37:14.000Z
|
2021-12-09T04:15:25.000Z
|
release/src/router/libsodium/src/libsodium/include/sodium/crypto_scalarmult_curve25519.h
|
ghsecuritylab/bcwifi
|
4cd7a6989921930f39816583014728b9f07a09a3
|
[
"FSFAP"
] | 1
|
2022-03-15T20:59:22.000Z
|
2022-03-15T21:04:14.000Z
|
release/src/router/libsodium/src/libsodium/include/sodium/crypto_scalarmult_curve25519.h
|
ghsecuritylab/bcwifi
|
4cd7a6989921930f39816583014728b9f07a09a3
|
[
"FSFAP"
] | 6
|
2015-04-16T19:08:46.000Z
|
2021-07-07T06:23:13.000Z
|
#ifndef crypto_scalarmult_curve25519_H
#define crypto_scalarmult_curve25519_H
#if 0
# ifndef SODIUM_HAVE_TI_MODE
# define SODIUM_HAVE_TI_MODE
# endif
#endif
#include "export.h"
#define crypto_scalarmult_curve25519_BYTES 32
#define crypto_scalarmult_curve25519_SCALARBYTES 32
#ifdef __cplusplus
extern "C" {
#endif
SODIUM_EXPORT
int crypto_scalarmult_curve25519(unsigned char *,const unsigned char *,const unsigned char *);
SODIUM_EXPORT
int crypto_scalarmult_curve25519_base(unsigned char *,const unsigned char *);
#ifdef SODIUM_HAVE_TI_MODE
# define crypto_scalarmult_curve25519_donna_c64 crypto_scalarmult_curve25519
# define crypto_scalarmult_curve25519_donna_c64_base crypto_scalarmult_curve25519_base
#else
# define crypto_scalarmult_curve25519_ref crypto_scalarmult_curve25519
# define crypto_scalarmult_curve25519_ref_base crypto_scalarmult_curve25519_base
#endif
#ifdef __cplusplus
}
#endif
#endif
| 24.105263
| 94
| 0.862445
|
7bc8bccc726799aef0eb510ce56b2b8c7dc4c7b0
| 651
|
rb
|
Ruby
|
app/controllers/activities_controller.rb
|
thekevinhuang/specialty_review_v002
|
5e916f1044ccfd2af6d14e174db93cbbec3b101e
|
[
"MIT"
] | null | null | null |
app/controllers/activities_controller.rb
|
thekevinhuang/specialty_review_v002
|
5e916f1044ccfd2af6d14e174db93cbbec3b101e
|
[
"MIT"
] | null | null | null |
app/controllers/activities_controller.rb
|
thekevinhuang/specialty_review_v002
|
5e916f1044ccfd2af6d14e174db93cbbec3b101e
|
[
"MIT"
] | null | null | null |
class ActivitiesController < ApplicationController
before_action :require_log_in
def show
@activity = Activity.find_by(id: params[:id])
end
def new
if !@activity
@activity = Activity.new
end
end
def create
@activity = Activity.new(activity_params)
if @activity.save
redirect_to activity_path(@activity)
else
render :new
end
end
def destroy
end
def index
@activities = Activity.all
end
private
def activity_params
params.require(:activity).permit(:name, :description)
end
end
| 17.594595
| 61
| 0.588326
|
454beedcf2f22f33f3261dc7900fe902a9748697
| 2,516
|
py
|
Python
|
semi-empirical mass formula.py
|
Vworri/Computational-Physics-Review
|
e665b62596b1d521f3e89b8f7a0840999b4d7002
|
[
"MIT"
] | 1
|
2019-02-24T19:00:30.000Z
|
2019-02-24T19:00:30.000Z
|
semi-empirical mass formula.py
|
Vworri/Computational-Physics-Review
|
e665b62596b1d521f3e89b8f7a0840999b4d7002
|
[
"MIT"
] | 1
|
2018-03-11T19:06:50.000Z
|
2018-03-11T19:06:50.000Z
|
semi-empirical mass formula.py
|
Vworri/Computational-Physics-Review
|
e665b62596b1d521f3e89b8f7a0840999b4d7002
|
[
"MIT"
] | null | null | null |
import pandas as pd
import plotly
import plotly.graph_objs as go
def I_have_both():
A = float(input("What is your A value?: "))
Z = float(input("What is your Z value?: "))
B= find_binding_energy(A, Z)
print("Your binding energy per nucleon is: " + str(B / A) + "MeV \n" + "Your binding energy is: " + str(B) + "MeV")
def I_have_z():
Z = int(input("Please put in your Z: "))
find_the_largest_B_for_Z(Z)
def find_binding_energy(A, Z):
a_1 = 15.67
a_2 = 17.23
a_3 = 0.75
a_4 = 93.2
if (A % 2 != 0):
a_5 = 0
elif (A % 2 == 0 and Z % 2 == 0):
a_5 = 12.0
elif (Z % 2 != 0):
a_5 = -12.0
first = a_1 * A
second = a_2 * (A ** (2 / 3))
third = a_3 * ((Z ** 2) / A ** (1 / 3))
fourth = a_4 * (((A - 2 * Z) ** 2) / A)
fifth = a_5 / (A ** (1 / 2))
B = first - second - third - fourth + fifth
print()
print()
return B
def find_the_largest_B_for_Z(Z):
answer = [0.0, 0.0]
for A in range(Z, (3 * Z + 1)):
B = find_binding_energy(A, Z)
if B > answer[0]:
answer[0] = B
answer[1] = A
print("The largest binding energy for Z is " + str(answer[0])+ " MeV at A = "+str(answer[1]))
return answer
def find__B_for_all_Z():
output = []
for Z in range(1,101):
answer = [0.0, 0.0,0.0,0.0]
for A in range(Z, (3 * Z + 1)):
B = find_binding_energy(A, Z)
if B > answer[0]:
answer[0] = B
answer[1] = A
answer[2] = Z
answer[3] = B/A
output.append(answer)
output_df = pd.DataFrame(output, columns=["B","A","Z","B/A"])
trace = go.Scatter(
x = output_df['Z'],
y = output_df["B/A"]
)
layout = dict(title = "The Semi-Empirical Mass Formula",
xaxis = dict(title = "Atomic Number: Z"),
yaxis = dict(title = "Binding Energy per Nucleon"))
fig = dict(data=[trace], layout=layout)
plotly.offline.plot(fig)
return
choose = input("Part A: find binding energy of A,Z pair \n Part B: find largest binding energy for Z? \n or C for "
"highest B from Z= 0-100: ")
if choose == "A":
I_have_both()
elif choose == "B":
I_have_z()
elif choose == "C":
print(find__B_for_all_Z())
else:
print("you must choose A or B")
choose = input("Part A: find binding energy of A,Z pair or Part B: find largest binding energy for Z? ")
| 27.053763
| 119
| 0.517886
|
fc0c2e8dbcee0f6cf360d9bfc303000b6bc81e9e
| 440
|
asm
|
Assembly
|
Relatorio9/programa12.asm
|
GustavoLR548/ACII-GLR
|
135690945f5e29938ef640a3d5475f8a12dbd76c
|
[
"MIT"
] | 1
|
2021-11-03T17:22:02.000Z
|
2021-11-03T17:22:02.000Z
|
Relatorio9/programa12.asm
|
GustavoLR548/ACII-GLR
|
135690945f5e29938ef640a3d5475f8a12dbd76c
|
[
"MIT"
] | null | null | null |
Relatorio9/programa12.asm
|
GustavoLR548/ACII-GLR
|
135690945f5e29938ef640a3d5475f8a12dbd76c
|
[
"MIT"
] | null | null | null |
.data
k: .word 5
x: .word
.text
main:
la $t0, k # pointeiro 1
la $t1, 4($t0) # pointeiro 2
la $t2, 4($t1) # pointeiro , t2 = x
sw $t2, x # armazenando em x o ponteiro
la $s0, -8($t2) # pegando o ponteiro original
lw $s1,($s0) # pegar o conteudo do ponteiro
sll $s1,$s1,1 # multiplicar por 2 ( 1 shift logical left)
sw $s1,($s0) # salvar o resultado da multiplicacao no conteudo do ponteiro
| 29.333333
| 78
| 0.590909
|
a68415ace8fece8a934c232df8380ed3cd9fbee8
| 148
|
sql
|
SQL
|
src/test/resources/test-cases/RMLTC0002j-MySQL/resource.sql
|
kasper-piskorski/rmlmapper-java
|
da75e1a073b07c347addafad28c3a0191e8ba54a
|
[
"MIT"
] | 96
|
2018-08-29T08:52:24.000Z
|
2022-03-31T22:12:20.000Z
|
src/test/resources/test-cases/RMLTC0002j-MySQL/resource.sql
|
vemonet/rmlmapper-java
|
2987b78647d4b4580cb76e89cb85ece1ba317e54
|
[
"MIT"
] | 148
|
2018-08-06T09:36:10.000Z
|
2022-03-31T10:17:19.000Z
|
src/test/resources/test-cases/RMLTC0002j-MySQL/resource.sql
|
vemonet/rmlmapper-java
|
2987b78647d4b4580cb76e89cb85ece1ba317e54
|
[
"MIT"
] | 51
|
2018-07-16T08:56:15.000Z
|
2022-03-07T21:26:23.000Z
|
USE test;
DROP TABLE IF EXISTS test.student;
CREATE TABLE student (
ID INTEGER,
Name VARCHAR(50)
);
INSERT INTO student values ('10', 'Venus');
| 18.5
| 43
| 0.709459
|
b0fb038b828cfd0b8b9c378eaf747209a2e65bbc
| 3,379
|
py
|
Python
|
src/main.py
|
RysisLiang/TimestampConversion
|
f52f333b62cdc80d0ed419f2ca75f2e3749b1def
|
[
"MIT"
] | 1
|
2019-11-17T06:06:57.000Z
|
2019-11-17T06:06:57.000Z
|
src/main.py
|
RysisLiang/TimestampConversion
|
f52f333b62cdc80d0ed419f2ca75f2e3749b1def
|
[
"MIT"
] | null | null | null |
src/main.py
|
RysisLiang/TimestampConversion
|
f52f333b62cdc80d0ed419f2ca75f2e3749b1def
|
[
"MIT"
] | null | null | null |
# -*- coding: utf-8 -*-
import sys
import alfred
import time
import re
from datetime import datetime
_pattern1 = "%Y-%m-%d %H:%M:%S"
_pattern2 = "%Y%m%d %H:%M:%S"
_pattern3 = "%Y/%m/%d %H:%M:%S"
_pattern4 = "%Y.%m.%d %H:%M:%S"
_pattern5 = "%Y-%m-%d"
_pattern6 = "%Y%m%d"
_pattern7 = "%Y/%m/%d"
_pattern8 = "%Y.%m.%d"
_patterns = [_pattern1, _pattern2, _pattern3, _pattern4, _pattern5, _pattern6, _pattern7, _pattern8]
# 时间戳格式化
def _format_by_pattern(time_num, pattern):
time_stamp = float(time_num / 1000)
time_array = time.localtime(time_stamp)
return str(time.strftime(pattern, time_array))
# 解析时间字符串
def _parse_by_pattern(timestr, pattern):
datetime_obj = datetime.strptime(timestr, pattern)
return str(int(time.mktime(datetime_obj.timetuple()) * 1000 + datetime_obj.microsecond / 1000))
# 多格式匹配解析
def _parses(timestr, index=0):
try:
return _parse_by_pattern(timestr, _patterns[index])
except Exception:
if index < len(_patterns):
index += 1
return _parses(timestr, index)
else:
return None
# 获取指定时间或时间戳
def _getOnce(query):
result = []
title = "{}".format(query)
subtitle = "未匹配到指定格式"
# 设置alfred-xml item
def setItem(uid, arg, title, subtitle):
result.append(alfred.Item(
{"uid": uid, "arg": arg},
title,
subtitle,
None
))
# 匹配时间戳
r_res = re.search(r'(^\d{13}$)|(^\d{10}$)', query)
# 匹配日期的格式
r2_res = re.search(r'^((\d{4}([-\./]\d{2}){2})|2\d{7})\s*(\d{2}(:\d{2}){2})?', query)
if r_res and r_res.group():
time_num = int(query)
# 处理秒时间戳
if len(query) == 10:
time_num = time_num * 1000
res1 = _format_by_pattern(time_num, _pattern1)
res2 = _format_by_pattern(time_num, _pattern2)
subtitle = "[{}]-格式化".format(query)
setItem(1, res1, res1, subtitle)
setItem(2, res2, res2, subtitle)
elif r2_res and r2_res.group():
res = _parses(query)
subtitle = "[{}]-解析".format(query)
setItem(1, res, res, subtitle)
else:
setItem(1, title, title, subtitle)
_out(result)
# 获取当前时间和时间戳
def _getNow():
nowTime = time.time()
nowDate = datetime.now()
t1 = nowDate.strftime(_pattern1)
t2 = nowDate.strftime(_pattern2)
t3 = int(nowTime * 1000)
t4 = int(nowTime)
result = [
alfred.Item(
{"uid": 1, "arg": t1},
"{}".format(t1),
"当前时间1",
None
),
alfred.Item(
{"uid": 2, "arg": t2},
"{}".format(t2),
"当前时间2",
None
),
alfred.Item(
{"uid": 3, "arg": t3},
"{}".format(t3),
"时间戳(毫秒)",
None
),
alfred.Item(
{"uid": 4, "arg": t4},
"{}".format(t4),
"时间戳(秒)",
None
)
]
_out(result)
# 输出xml
def _out(result):
alfred.write(alfred.xml(result))
# 引入程序入口
def main(param):
if param:
_getOnce(param)
else:
_getNow()
# 脚本程序入口
if __name__ == "__main__":
args = sys.argv
if len(args) > 1 and args[1]:
main(args[1])
else:
main(None)
# test
# main('2019-05-08 10:10:10')
# main('2019-05-08 10:10:1')
# main('155731466900')
| 22.831081
| 100
| 0.534182
|
05f195e5ec62e0e27198a5b50b234ebd35d1fbe5
| 3,742
|
py
|
Python
|
stats/adjustscore.py
|
spiffcode/hostile-takeover
|
363c8f7f02c25f90255b28a5e2eaea784b2a502f
|
[
"BSD-2-Clause-FreeBSD"
] | 113
|
2015-01-07T00:37:37.000Z
|
2022-03-08T17:58:24.000Z
|
stats/adjustscore.py
|
ptitSeb/hostile-takeover
|
db70254a966ca3223178e669594f3b704b5471a2
|
[
"BSD-2-Clause-FreeBSD"
] | 6
|
2015-04-13T16:16:00.000Z
|
2021-06-08T04:49:09.000Z
|
stats/adjustscore.py
|
spiffcode/hostile-takeover
|
363c8f7f02c25f90255b28a5e2eaea784b2a502f
|
[
"BSD-2-Clause-FreeBSD"
] | 49
|
2015-01-08T04:27:35.000Z
|
2022-03-08T04:55:08.000Z
|
import os
import config
import basehandler
import models
import accounts
import urllib
import admin
from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
from google.appengine.ext import db
class AdjustScore(basehandler.BaseHandler):
def get(self):
account = self.has_access()
if not account:
self.redirect(users.create_login_url(self.request.uri))
return
type = self.request.get('t').lower()
u = self.request.get('u').lower()
player_name = self.request.get('p').lower()
message = ''
# if no type specified, there is no query
rating = 0
next_type = ''
if not type:
# The next request will be a query for a player name's score
next_type = 'q'
# Validate the user. Is this a query or set score request?
p = None
if type == 'q' or type == 's':
# This is a query for a user. Make sure the user is valid
if not u:
message = 'No player name entered!'
type = ''
next_type = 'q'
else:
p = models.PlayerModel.get(models.playermodel_key(u))
if not p:
message = 'Could not find player %s! Please try again:' % u
u = ''
type = ''
next_type = 'q'
# Step through the states
rating = 0
reason = ''
if type == 'q':
# The next request will be for changing a score
next_type = 's'
rating = p.rating
if type == 's':
# Is the new rating valid?
rating = self.request.get('s')
reason = self.request.get('r')
success = True
try:
rating = int(rating)
except:
success = False
if not success or rating >= 3000 or rating < 0:
message = '"%s" is an invalid score. Please try again:' % rating
rating = p.rating
type = 'q'
next_type = 's'
elif not reason:
message = 'Must enter a reason. Please try again:'
rating = p.rating
type = 'q'
next_type = 's'
else:
# Record this action
d = dict(action='adjust_score', player_name=u, old_rating=p.rating, new_rating=rating, reason=reason)
admin.save_action(account.name, self.request.remote_addr, d)
p.rating = rating
p.put()
message = 'Successfully set the score of player %s to %s, reason: %s.' % (u, rating, reason)
type = ''
next_type = 'q'
template_values = {
'tabs': config.get_tabs(player_name, account),
'selected_tab': config.TAB_NONE,
'form_url': config.ADJUSTSCORE_URL,
'message': message,
'player_name': player_name,
'u': u,
'rating': rating,
'type': type,
'reason': reason,
'next_type': next_type
}
self.response.headers['Content-Type'] = 'application/xhtml+xml'
path = os.path.join(os.path.dirname(__file__), 'adjustscore.xhtml')
self.response.out.write(template.render(path, template_values))
def has_access(self):
# Requires an authenticated user with proper access rights
account = accounts.account()
if account and account.ADJUST_SCORE_ACCESS_RIGHT:
return account
return None
| 33.410714
| 117
| 0.522982
|
0a5c1a1ed8119104ee7a3e980c036f65951a54f5
| 19,039
|
cs
|
C#
|
Kudu.Core/Jobs/BaseJobRunner.cs
|
Acidburn0zzz/kudu
|
617711e2f25834ba211e4f6ce002d2b7aae776d9
|
[
"Apache-2.0"
] | null | null | null |
Kudu.Core/Jobs/BaseJobRunner.cs
|
Acidburn0zzz/kudu
|
617711e2f25834ba211e4f6ce002d2b7aae776d9
|
[
"Apache-2.0"
] | null | null | null |
Kudu.Core/Jobs/BaseJobRunner.cs
|
Acidburn0zzz/kudu
|
617711e2f25834ba211e4f6ce002d2b7aae776d9
|
[
"Apache-2.0"
] | null | null | null |
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Configuration;
using System.Diagnostics;
using System.IO;
using System.IO.Abstractions;
using System.Linq;
using System.Text;
using System.Threading;
using System.Xml.Linq;
using System.Xml.XPath;
using Kudu.Contracts.Jobs;
using Kudu.Contracts.Settings;
using Kudu.Contracts.Tracing;
using Kudu.Core.Deployment;
using Kudu.Core.Deployment.Generator;
using Kudu.Core.Infrastructure;
using Kudu.Core.Tracing;
namespace Kudu.Core.Jobs
{
public abstract class BaseJobRunner
{
private static readonly string[] AppConfigFilesLookupList = new string[] { "*.exe.config" };
private readonly ExternalCommandFactory _externalCommandFactory;
private readonly IAnalytics _analytics;
private string _shutdownNotificationFilePath;
protected BaseJobRunner(string jobName, string jobsTypePath, IEnvironment environment,
IDeploymentSettingsManager settings, ITraceFactory traceFactory, IAnalytics analytics)
{
TraceFactory = traceFactory;
Environment = environment;
Settings = settings;
JobName = jobName;
_analytics = analytics;
JobBinariesPath = Path.Combine(Environment.JobsBinariesPath, jobsTypePath, jobName);
JobTempPath = Path.Combine(Environment.TempPath, Constants.JobsPath, jobsTypePath, jobName);
JobDataPath = Path.Combine(Environment.DataPath, Constants.JobsPath, jobsTypePath, jobName);
_externalCommandFactory = new ExternalCommandFactory(Environment, Settings, Environment.RepositoryPath);
}
protected IEnvironment Environment { get; private set; }
protected IDeploymentSettingsManager Settings { get; private set; }
protected ITraceFactory TraceFactory { get; private set; }
public string JobName { get; private set; }
protected string JobBinariesPath { get; private set; }
protected string JobTempPath { get; private set; }
protected string JobDataPath { get; private set; }
protected string WorkingDirectory { get; private set; }
protected abstract string JobEnvironmentKeyPrefix { get; }
protected abstract TimeSpan IdleTimeout { get; }
protected abstract void UpdateStatus(IJobLogger logger, string status);
private static int CalculateHashForJob(string jobBinariesPath)
{
var updateDatesString = new StringBuilder();
DirectoryInfoBase jobBinariesDirectory = FileSystemHelpers.DirectoryInfoFromDirectoryName(jobBinariesPath);
FileInfoBase[] files = jobBinariesDirectory.GetFiles("*.*", SearchOption.AllDirectories);
foreach (FileInfoBase file in files)
{
updateDatesString.Append(file.LastWriteTimeUtc.Ticks);
}
return updateDatesString.ToString().GetHashCode();
}
private void CacheJobBinaries(IJobLogger logger)
{
if (WorkingDirectory != null)
{
try
{
int currentHash = CalculateHashForJob(JobBinariesPath);
int lastHash = CalculateHashForJob(WorkingDirectory);
if (lastHash == currentHash)
{
return;
}
}
catch (Exception ex)
{
// Log error and ignore it as it's not critical to cache job binaries
logger.LogError("Failed to calculate hash for WebJob: " + ex);
_analytics.UnexpectedException(ex);
}
}
SafeKillAllRunningJobInstances(logger);
if (FileSystemHelpers.DirectoryExists(JobTempPath))
{
FileSystemHelpers.DeleteDirectorySafe(JobTempPath, ignoreErrors: true);
}
if (FileSystemHelpers.DirectoryExists(JobTempPath))
{
logger.LogWarning("Failed to delete temporary directory");
}
try
{
var tempJobInstancePath = Path.Combine(JobTempPath, Path.GetRandomFileName());
FileSystemHelpers.CopyDirectoryRecursive(JobBinariesPath, tempJobInstancePath);
UpdateAppConfigs(tempJobInstancePath);
WorkingDirectory = tempJobInstancePath;
}
catch (Exception ex)
{
//Status = "Worker is not running due to an error";
//TraceError("Failed to copy bin directory: " + ex);
logger.LogError("Failed to copy job files: " + ex);
_analytics.UnexpectedException(ex);
// job disabled
WorkingDirectory = null;
}
}
public string GetJobEnvironmentKey()
{
return JobEnvironmentKeyPrefix + JobName;
}
protected void InitializeJobInstance(JobBase job, IJobLogger logger)
{
if (!String.Equals(JobName, job.Name, StringComparison.OrdinalIgnoreCase))
{
throw new InvalidOperationException(
"The job runner can only run jobs with the same name it was configured, configured - {0}, trying to run - {1}".FormatInvariant(
JobName, job.Name));
}
if (!FileSystemHelpers.FileExists(job.ScriptFilePath))
{
throw new InvalidOperationException("Missing job script to run - {0}".FormatInvariant(job.ScriptFilePath));
}
CacheJobBinaries(logger);
if (WorkingDirectory == null)
{
throw new InvalidOperationException("Missing working directory");
}
}
protected void RunJobInstance(JobBase job, IJobLogger logger, string runId)
{
string scriptFileName = Path.GetFileName(job.ScriptFilePath);
string scriptFileFullPath = Path.Combine(WorkingDirectory, job.RunCommand);
string workingDirectoryForScript = Path.GetDirectoryName(scriptFileFullPath);
logger.LogInformation("Run script '{0}' with script host - '{1}'".FormatCurrentCulture(scriptFileName, job.ScriptHost.GetType().Name));
using (var jobStartedReporter = new JobStartedReporter(_analytics, job, Settings.GetWebSitePolicy(), JobDataPath))
{
try
{
var exe = _externalCommandFactory.BuildCommandExecutable(job.ScriptHost.HostPath, workingDirectoryForScript, IdleTimeout, NullLogger.Instance);
_shutdownNotificationFilePath = RefreshShutdownNotificationFilePath(job.Name, job.JobType);
// Set environment variable to be able to identify all processes spawned for this job
exe.EnvironmentVariables[GetJobEnvironmentKey()] = "true";
exe.EnvironmentVariables[WellKnownEnvironmentVariables.WebJobsRootPath] = WorkingDirectory;
exe.EnvironmentVariables[WellKnownEnvironmentVariables.WebJobsName] = job.Name;
exe.EnvironmentVariables[WellKnownEnvironmentVariables.WebJobsType] = job.JobType;
exe.EnvironmentVariables[WellKnownEnvironmentVariables.WebJobsDataPath] = JobDataPath;
exe.EnvironmentVariables[WellKnownEnvironmentVariables.WebJobsRunId] = runId;
exe.EnvironmentVariables[WellKnownEnvironmentVariables.WebJobsShutdownNotificationFile] = _shutdownNotificationFilePath;
exe.EnvironmentVariables[WellKnownEnvironmentVariables.WebJobsCommandArguments] = job.CommandArguments;
UpdateStatus(logger, "Running");
int exitCode =
exe.ExecuteReturnExitCode(
TraceFactory.GetTracer(),
logger.LogStandardOutput,
logger.LogStandardError,
job.ScriptHost.ArgumentsFormat,
scriptFileName,
job.CommandArguments != null ? " " + job.CommandArguments : String.Empty);
if (exitCode != 0)
{
string errorMessage = "Job failed due to exit code " + exitCode;
logger.LogError(errorMessage);
jobStartedReporter.Error = errorMessage;
}
else
{
UpdateStatus(logger, "Success");
}
}
catch (Exception ex)
{
if (ex is ThreadAbortException)
{
// We kill the process when refreshing the job
logger.LogInformation("Job aborted");
UpdateStatus(logger, "Aborted");
return;
}
logger.LogError(ex.ToString());
jobStartedReporter.Error = ex.Message;
}
}
}
public void SafeKillAllRunningJobInstances(IJobLogger logger)
{
try
{
Process[] processes = Process.GetProcesses();
foreach (Process process in processes)
{
StringDictionary processEnvironment;
bool success = ProcessEnvironment.TryGetEnvironmentVariables(process, out processEnvironment);
if (success && processEnvironment.ContainsKey(GetJobEnvironmentKey()))
{
try
{
process.Kill(true, TraceFactory.GetTracer());
}
catch (Exception ex)
{
if (!process.HasExited)
{
logger.LogWarning("Failed to kill process - {0} for job - {1}\n{2}".FormatInvariant(process.ProcessName, JobName, ex));
}
}
}
}
}
catch (Exception ex)
{
logger.LogWarning(ex.ToString());
}
}
protected void NotifyShutdownJob()
{
try
{
if (_shutdownNotificationFilePath != null)
{
FileSystemHelpers.EnsureDirectory(Path.GetDirectoryName(_shutdownNotificationFilePath));
OperationManager.Attempt(() => FileSystemHelpers.WriteAllText(_shutdownNotificationFilePath, DateTime.UtcNow.ToString()));
}
}
catch (Exception ex)
{
TraceFactory.GetTracer().TraceError(ex);
_analytics.UnexpectedException(ex);
}
}
private string RefreshShutdownNotificationFilePath(string jobName, string jobsTypePath)
{
string shutdownFilesDirectory = Path.Combine(Environment.TempPath, "JobsShutdown", jobsTypePath, jobName);
FileSystemHelpers.DeleteDirectoryContentsSafe(shutdownFilesDirectory, ignoreErrors: true);
return Path.Combine(shutdownFilesDirectory, Path.GetRandomFileName());
}
private void UpdateAppConfigs(string tempJobInstancePath)
{
IEnumerable<string> configFilePaths = FileSystemHelpers.ListFiles(tempJobInstancePath, SearchOption.AllDirectories, AppConfigFilesLookupList);
foreach (string configFilePath in configFilePaths)
{
UpdateAppConfig(configFilePath);
UpdateAppConfigAddTraceListeners(configFilePath);
}
}
/// <summary>
/// Updates the app.config using XML directly for injecting trace providers.
/// </summary>
private void UpdateAppConfigAddTraceListeners(string configFilePath)
{
try
{
var xmlConfig = XDocument.Load(configFilePath);
// Make sure the trace listeners section available otherwise create it
var configurationElement = GetOrCreateElement(xmlConfig, "configuration");
var systemDiagnosticsElement = GetOrCreateElement(configurationElement, "system.diagnostics");
var traceElement = GetOrCreateElement(systemDiagnosticsElement, "trace");
var listenersElement = GetOrCreateElement(traceElement, "listeners");
// Inject existing trace providers to the target app.config
foreach (TraceListener listener in Trace.Listeners)
{
// Ignore the default trace provider
if (String.Equals(listener.Name, "default", StringComparison.OrdinalIgnoreCase))
{
continue;
}
// Do not add a trace provider if it already exists (by name)
XElement listenerElement = listenersElement.Elements().FirstOrDefault(xElement =>
{
XAttribute nameAttribute = xElement.Attribute("name");
return nameAttribute != null && String.Equals(nameAttribute.Value, listener.Name, StringComparison.OrdinalIgnoreCase);
});
if (listenerElement == null)
{
var addElement = new XElement("add");
addElement.Add(new XAttribute("name", listener.Name));
addElement.Add(new XAttribute("type", listener.GetType().AssemblyQualifiedName));
listenersElement.AddFirst(addElement);
}
}
FileSystemHelpers.WriteAllText(configFilePath, xmlConfig.ToString());
}
catch (Exception ex)
{
TraceFactory.GetTracer().TraceError(ex);
_analytics.UnexpectedException(ex);
}
}
private static XElement GetOrCreateElement(XContainer root, string name)
{
var element = root.XPathSelectElement(name);
if (element == null)
{
element = new XElement(name);
root.Add(element);
}
return element;
}
private void UpdateAppConfig(string configFilePath)
{
try
{
var settings = SettingsProcessor.Instance;
bool updateXml = false;
// Read app.config
string exeFilePath = configFilePath.Substring(0, configFilePath.Length - ".config".Length);
Configuration config = ConfigurationManager.OpenExeConfiguration(exeFilePath);
foreach (var appSetting in settings.AppSettings)
{
config.AppSettings.Settings.Remove(appSetting.Key);
config.AppSettings.Settings.Add(appSetting.Key, appSetting.Value);
updateXml = true;
}
foreach (ConnectionStringSettings connectionString in settings.ConnectionStrings)
{
ConnectionStringSettings currentConnectionString = config.ConnectionStrings.ConnectionStrings[connectionString.Name];
if (currentConnectionString != null)
{
// Update provider name if connection string already exists and provider name is null (custom type)
connectionString.ProviderName = connectionString.ProviderName ?? currentConnectionString.ProviderName;
}
config.ConnectionStrings.ConnectionStrings.Remove(connectionString.Name);
config.ConnectionStrings.ConnectionStrings.Add(connectionString);
updateXml = true;
}
if (updateXml)
{
// Write updated app.config
config.Save();
}
}
catch (Exception ex)
{
TraceFactory.GetTracer().TraceError(ex);
_analytics.UnexpectedException(ex);
}
}
/// <summary>
/// This class will make sure the "JobStarted" analytics event is invoked after 5 seconds or when disposed.
/// </summary>
private sealed class JobStartedReporter : IDisposable
{
private static readonly int ReportTimeoutInMilliseconds = (int)TimeSpan.FromSeconds(5).TotalMilliseconds;
private readonly IAnalytics _analytics;
private readonly JobBase _job;
private readonly string _siteMode;
private readonly string _jobDataPath;
private Timer _timer;
private int _reported;
public JobStartedReporter(IAnalytics analytics, JobBase job, string siteMode, string jobDataPath)
{
_analytics = analytics;
_job = job;
_siteMode = siteMode;
_jobDataPath = jobDataPath;
_timer = new Timer(Report, null, ReportTimeoutInMilliseconds, Timeout.Infinite);
}
public string Error { get; set; }
private void Report(object state = null)
{
// Make sure this code is only called once.
if (Interlocked.Exchange(ref _reported, 1) == 0)
{
string scriptFileExtension = Path.GetExtension(_job.ScriptFilePath);
string jobType = _job.JobType;
// Recheck whether the job is marked as "using sdk" here since the SDK will create the marker file
// on the fly so it requires a "first run" first.
bool isUsingSdk = JobsManagerBase.IsUsingSdk(_jobDataPath);
if (isUsingSdk)
{
jobType += "/SDK";
}
_analytics.JobStarted(_job.Name.Fuzz(), scriptFileExtension, jobType, _siteMode, Error);
}
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
private void Dispose(bool disposing)
{
if (disposing)
{
if (_timer != null)
{
_timer.Dispose();
_timer = null;
}
Report();
}
}
}
}
}
| 40.166667
| 163
| 0.56295
|
e73525f4380b71059bd9b89ce391b525b6e18893
| 1,195
|
php
|
PHP
|
api/migrations/Version20211217135037.php
|
antoinechab/ws-hesias
|
0cea203f6a7581bfcc100132041649d8fdb5ebdf
|
[
"MIT"
] | null | null | null |
api/migrations/Version20211217135037.php
|
antoinechab/ws-hesias
|
0cea203f6a7581bfcc100132041649d8fdb5ebdf
|
[
"MIT"
] | 9
|
2021-12-08T14:23:12.000Z
|
2021-12-08T15:41:50.000Z
|
api/migrations/Version20211217135037.php
|
antoinechab/ws-hesias
|
0cea203f6a7581bfcc100132041649d8fdb5ebdf
|
[
"MIT"
] | null | null | null |
<?php
declare(strict_types=1);
namespace DoctrineMigrations;
use Doctrine\DBAL\Schema\Schema;
use Doctrine\Migrations\AbstractMigration;
/**
* Auto-generated Migration: Please modify to your needs!
*/
final class Version20211217135037 extends AbstractMigration
{
public function getDescription(): string
{
return '';
}
public function up(Schema $schema): void
{
// this up() migration is auto-generated, please modify it to your needs
$this->addSql('ALTER TABLE "user" ADD follow_id INT DEFAULT NULL');
$this->addSql('ALTER TABLE "user" ADD CONSTRAINT FK_8D93D6498711D3BC FOREIGN KEY (follow_id) REFERENCES "user" (id) NOT DEFERRABLE INITIALLY IMMEDIATE');
$this->addSql('CREATE INDEX IDX_8D93D6498711D3BC ON "user" (follow_id)');
}
public function down(Schema $schema): void
{
// this down() migration is auto-generated, please modify it to your needs
$this->addSql('CREATE SCHEMA public');
$this->addSql('ALTER TABLE "user" DROP CONSTRAINT FK_8D93D6498711D3BC');
$this->addSql('DROP INDEX IDX_8D93D6498711D3BC');
$this->addSql('ALTER TABLE "user" DROP follow_id');
}
}
| 32.297297
| 161
| 0.687866
|
e2be71cd352b207ba4991138ccb8f00e95d56b63
| 16,812
|
py
|
Python
|
cumm/gemm/outputs/__init__.py
|
FindDefinition/cumm
|
3d58e85b660afa05c20514afe65b8aa3a4995953
|
[
"Apache-2.0"
] | 20
|
2021-10-13T03:41:59.000Z
|
2022-03-31T07:23:14.000Z
|
cumm/gemm/outputs/__init__.py
|
FindDefinition/cumm
|
3d58e85b660afa05c20514afe65b8aa3a4995953
|
[
"Apache-2.0"
] | 3
|
2021-11-21T11:25:55.000Z
|
2022-03-08T06:12:35.000Z
|
cumm/gemm/outputs/__init__.py
|
FindDefinition/cumm
|
3d58e85b660afa05c20514afe65b8aa3a4995953
|
[
"Apache-2.0"
] | 4
|
2021-10-13T03:42:01.000Z
|
2022-03-21T13:07:56.000Z
|
# Copyright 2021 Yan Yan
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from typing import Dict, List, Optional, Tuple, Type, Union
import numpy as np
import pccm
from cumm import cudasim, dtypes
from cumm import tensorview as tv
from cumm.common import (GemmBasic, GemmBasicKernel, TensorViewKernel,
TensorViewNVRTC)
from cumm.constants import CUTLASS_MODE
from cumm.core_cc.csrc.arrayref import ArrayPtr
from cumm.gemm import (constants, layout, mask_iters, out_iters, thread_map,
volta_iters, volta_out_iters)
from cumm.gemm.algospec import bases
from cumm.gemm.bases import (GemmInputIterator, GemmOutputIterator,
GemmOutputOp, GemmOutSmemLoader,
GemmOutWarpIterator, GemmSmemIterator,
GemmWarpIterator)
from cumm.gemm.core import MetaArray, array_type, metaseq, seq
def div_up(a, b):
return (a + b - 1) // b
class OutputSmemStorage(pccm.ParameterizedClass):
def __init__(self, shape: MetaArray[int], smem_padding_mn: MetaArray[int],
dtype_acc: dtypes.DType, frag_per_iter: int):
super().__init__()
self.add_dependency(TensorViewNVRTC)
self.shape = shape
self.smem_padding_mn = smem_padding_mn
self.dtype_acc = dtype_acc
self.frag_per_iter = frag_per_iter
self.storage_shape = seq(
(shape[0] + smem_padding_mn[0]) * frag_per_iter,
shape[1] + smem_padding_mn[1])
self.smem_alignment = 16
self.smem_size = self.storage_shape.prod() * dtype_acc.itemsize()
self.smem_size = div_up(self.smem_size,
self.smem_alignment) * self.smem_alignment
self.add_member(
"smem",
f"tv::alignedarray<{dtype_acc}, {self.storage_shape.prod()}, 16>")
class Output(pccm.ParameterizedClass):
def __init__(self, dtype_acc: dtypes.DType,
warp_count_shape: MetaArray[int], partk: int,
spec: bases.Output, smem_storage: OutputSmemStorage):
super().__init__()
self.spec = spec
self.dtype_acc = dtype_acc
self.smem_storage = smem_storage
self.warp_count_shape = warp_count_shape
self.add_param_class("out_ns_frag", spec.frag_iter, "FragIter")
self.add_param_class("out_ns_warp", spec.warp_store_iter,
"OutWarpIter")
self.add_param_class("out_ns_smem", spec.smem_loader, "SmemLoader")
self.add_param_class("out_ns_out", spec.out_iter, "OutIter")
self.add_param_class("out_ns_out_const", spec.const_out_iter,
"ConstOutIter")
self.add_param_class("out_ns_sto", smem_storage, "OutputStorage")
self.add_param_class("out_ns_op", spec.output_op, "OutputOp")
self.add_param_class("out_ns_apply", spec.apply_op, "ApplyOp")
self.accumulator_fragment = array_type(dtype_acc,
spec.mma_spec.accumulator_size)
self.partk = partk
self.out_num_tile = self.spec.frag_per_iter if self.spec.frag_per_iter > 1 else partk
self.out_tile_size = smem_storage.smem_size // dtype_acc.itemsize(
) // self.out_num_tile
# print(smem_storage.smem_size, self.out_tile_size, self.out_num_tile)
# raise NotImplementedError
self.add_member("warp_iter", "OutWarpIter")
self.add_member("smem_loader", "SmemLoader")
# cudasim
self.warp_iter: Optional[GemmOutWarpIterator] = None
self.smem_loader: Optional[GemmOutSmemLoader] = None
self.smem_ptr: Optional[ArrayPtr] = None
@pccm.cuda.constructor(device=True, forceinline=True)
def ctor(self):
code = pccm.code()
code.arg("smem_storage", "OutputStorage*")
code.arg("thread_idx,warp_idx_k,warp_m,warp_n,lane_idx", "int")
code.ctor_init(
"warp_iter",
f"smem_storage->smem.data(), warp_idx_k * {self.warp_count_shape[0]} + warp_m, warp_n, lane_idx"
)
code.ctor_init("smem_loader", f"smem_storage->smem.data(), thread_idx")
return code
def python_ctor(self, smem_ptr: ArrayPtr, thread_idx: int, warp_idx_k: int,
warp_m: int, warp_n: int, lane_idx: int):
new_obj = Output(self.dtype_acc, self.warp_count_shape, self.partk,
self.spec, self.smem_storage)
new_obj.warp_iter = self.spec.warp_store_iter.python_ctor(
smem_ptr, warp_idx_k * self.warp_count_shape[0] + warp_m, warp_n,
lane_idx)
new_obj.smem_loader = self.spec.smem_loader.python_ctor(
smem_ptr, thread_idx)
new_obj.smem_ptr = smem_ptr
return new_obj
def call_template(self, have_source: bool, self_reduce: bool):
code = pccm.code()
code.arg("output_op", f"OutputOp const&")
code.arg("accumulators", f"{self.accumulator_fragment} const&")
code.arg("out_iter", f"OutIter&")
if have_source:
code.arg("source_iter", f"ConstOutIter&")
# TODO why frag_per_iter > 1?
frag_per_iter = self.spec.frag_per_iter
if have_source is not None:
frag_per_iter = 1
if CUTLASS_MODE:
platform_math = "cutlass"
else:
platform_math = "tv::math"
if have_source:
code.raw(f"""
if (!output_op.is_source_needed()){{
return run(output_op, accumulators, out_iter);
}}
{self.spec.out_iter.fragment_t} source_frag;
source_frag.clear();
""")
elif self_reduce:
code.raw(f"""
{self.spec.out_iter.fragment_t} source_frag;
source_frag.clear();
""")
code.raw(f"FragIter out_acc_iter(accumulators.data());")
with code.for_(
f"int iter = 0; iter < {self.spec.num_out_iters}; iter += {frag_per_iter}",
"TV_PRAGMA_UNROLL"):
if have_source:
code.raw(f"""
source_iter.load(source_frag);
++source_iter;
""")
elif self_reduce:
code.raw(f"""
out_iter.load(source_frag);
""")
code.raw(f"__syncthreads();")
with code.range_("p", frag_per_iter, "TV_PRAGMA_UNROLL"):
code.raw(f"""
{self.spec.frag_iter.fragment_t} acc_frag;
out_acc_iter.load(acc_frag);
++out_acc_iter;
warp_iter.store(acc_frag);
if (p < {frag_per_iter} - 1){{
warp_iter.add_pointer_offset({self.out_tile_size});
}}
""")
if cudasim.enable_debug():
code.raw(
f"tv::print_fragment_meta_once<float, {cudasim.debug_tx()}>(acc_frag, iter, \"AccFrag\");"
)
code.raw(f"""
if ({frag_per_iter} > 1){{
warp_iter.add_pointer_offset({self.out_tile_size * (1 - frag_per_iter)});
}}
__syncthreads();
""")
with code.range_("p", frag_per_iter, "TV_PRAGMA_UNROLL"):
code.raw(f"""
{self.spec.smem_loader.fragment_t} smem_frags[{self.partk}];
smem_loader.load(smem_frags[0]);
if (p < {frag_per_iter} - 1){{
smem_loader.add_pointer_offset({self.out_tile_size});
}}
else if ({self.partk} > 1){{
TV_PRAGMA_UNROLL
for (int partk_idx = 1; partk_idx < {self.partk}; ++partk_idx){{
smem_loader.add_pointer_offset({self.out_tile_size});
smem_loader.load(smem_frags[partk_idx]);
{platform_math}::plus<{self.spec.smem_loader.fragment_t}> accer;
smem_frags[0] = accer(smem_frags[0], smem_frags[partk_idx]);
}}
smem_loader.add_pointer_offset({self.out_tile_size * (1 - self.partk)});
}}
{self.spec.out_iter.fragment_t} out_frag;
""")
if cudasim.enable_debug():
code.raw(
f"tv::print_fragment_meta_once<float, {cudasim.debug_tx()}>(smem_frags[0], iter, \"SmemFrag\");"
)
# code.raw(f"tv::print_ptr_once<int, 137, 151, {cudasim.debug_tx()}>(warp_iter.smem_pointer_);")
# code.raw(f"tv::print_fragment_once<float, 0, 8, {cudasim.debug_tx()}>(smem_frags[0]);")
if have_source or self_reduce:
code.raw(f"""
ApplyOp::apply_output_operator(out_frag, output_op, smem_frags[0], source_frag);
""")
else:
code.raw(f"""
ApplyOp::apply_output_operator_no_source(out_frag, output_op, smem_frags[0]);
""")
# if cudasim.enable_debug():
# # code.raw(f"tv::print_fragment_meta_once<float, {cudasim.debug_tx()}>(out_frag, iter, \"OutFrag\");")
# code.raw(f"tv::print_fragment_once<float, 0, 8, {cudasim.debug_tx()}>(smem_frags[0]);")
# code.raw(f"tv::print_fragment_once<float, 0, 8, {cudasim.debug_tx()}>(out_frag);")
code.raw(f"""
out_iter.store(out_frag);
++out_iter;
""")
code.raw(f"""
if ({frag_per_iter} > 1){{
smem_loader.add_pointer_offset({self.out_tile_size * (1 - frag_per_iter)});
}}
""")
return code
@pccm.cuda.member_function(device=True, forceinline=True, name="run")
def run_source(self):
return self.call_template(True, False)
@pccm.cuda.member_function(device=True, forceinline=True, name="run")
def run_no_source(self):
return self.call_template(False, False)
@pccm.cuda.member_function(device=True,
forceinline=True,
name="run_self_reduce")
def run_self_reduce(self):
return self.call_template(False, True)
async def __call__(self,
output_op: GemmOutputOp,
accumulators: ArrayPtr,
out_iter: GemmOutputIterator,
source_iter: Optional[GemmOutputIterator] = None,
self_reduce: bool = False):
out_warp_iter = self.warp_iter
out_smem_loader = self.smem_loader
frag_per_iter = self.spec.frag_per_iter
if source_iter is not None:
frag_per_iter = 1
assert out_warp_iter is not None
assert out_smem_loader is not None
source_frag = ArrayPtr(out_iter.dtype.tv_dtype, out_iter.element_count)
if source_iter is not None:
source_frag.clear()
elif self_reduce:
source_frag.clear()
# if cudasim.debug_once():
# print(source_iter, self_reduce)
out_acc_iter = self.spec.frag_iter.python_ctor(accumulators)
smem_save_list = []
smem_load_list = []
for out_idx in range(0, self.spec.num_out_iters, frag_per_iter):
if source_iter is not None:
source_iter.load_python(source_frag)
source_iter.increment_python()
elif self_reduce:
out_iter.load_python(source_frag)
await cudasim.syncthreads()
for p in range(frag_per_iter):
acc_frag = ArrayPtr(self.dtype_acc.tv_dtype,
self.spec.frag_iter.element_count)
out_acc_iter.load_python(acc_frag)
if cudasim.debug_once():
acc = acc_frag.data.numpy_view()
cudasim.debug_print(
f"{out_idx} AccFrag main: {acc.mean()} , max: {acc.max()} , min: {acc.min()}"
)
out_acc_iter.increment_python()
ptrs = await out_warp_iter.store_python(acc_frag)
if out_idx == 0:
smem_save_list.append(ptrs)
if p < frag_per_iter - 1:
out_warp_iter.add_pointer_offset_python(self.out_tile_size)
if frag_per_iter > 1:
out_warp_iter.add_pointer_offset_python(self.out_tile_size *
(1 - frag_per_iter))
await cudasim.syncthreads()
# if cudasim.threadIdx().x == 0:
# smem_data = smem_out_ptr.data.numpy_view()[:64]
# print("SMEMM", smem_data[:16])
# print("SMEM", smem_data.mean(), smem_data.max(), smem_data.min())
for p in range(frag_per_iter):
smem_frags = [
ArrayPtr(self.dtype_acc.tv_dtype,
out_smem_loader.element_count)
for _ in range(self.partk)
]
ptrs = await out_smem_loader.load_python(smem_frags[0])
if cudasim.debug_once():
acc = smem_frags[0].data.numpy_view()
cudasim.debug_print(
f"{out_idx} SmemFrag main: {acc.mean()} , max: {acc.max()} , min: {acc.min()}"
)
# smem_data = self.smem_ptr.data.numpy_view()[137:151]
# print(self.smem_storage.shape)
# cudasim.debug_print(smem_data)
# cudasim.debug_print(acc)
await cudasim.syncthreads()
if out_idx == 0:
smem_load_list.append(ptrs)
if p != frag_per_iter - 1:
out_smem_loader.add_pointer_offset_python(
self.out_tile_size)
elif self.partk > 1:
for partk_idx in range(1, self.partk):
out_smem_loader.add_pointer_offset_python(
self.out_tile_size)
ptrs = await out_smem_loader.load_python(
smem_frags[partk_idx])
if out_idx == 0:
smem_load_list.append(ptrs)
data_i = smem_frags[partk_idx].data.numpy_view()
smem_frags[0].data.numpy_view()[:] += data_i
out_smem_loader.add_pointer_offset_python(
self.out_tile_size * (1 - self.partk))
out_frag = ArrayPtr(out_iter.dtype.tv_dtype,
out_iter.element_count)
if source_iter is not None or self_reduce:
self.spec.apply_op.apply_output_operator_python(
out_frag, output_op, smem_frags[0], source_frag)
else:
self.spec.apply_op.apply_output_operator_no_source_python(
out_frag, output_op, smem_frags[0])
# if cudasim.debug_once():
# acc = out_frag.data.numpy_view()
# acc2 = smem_frags[0].data.numpy_view()
# cudasim.debug_print(acc)
# # cudasim.debug_print(f"{out_idx} OutFrag main: {acc.mean()} , max: {acc.max()} , min: {acc.min()}")
# cudasim.debug_print(acc)
out_iter.store_python(out_frag)
out_iter.increment_python()
if frag_per_iter > 1:
out_smem_loader.add_pointer_offset_python(self.out_tile_size *
(1 - frag_per_iter))
res = {
"Output": {
"smem_save_coords": smem_save_list,
"smem_load_coords": smem_load_list,
"smem_save_epa": out_warp_iter.element_per_acc,
"smem_load_epa": out_smem_loader.element_per_acc,
"smem_shape": self.smem_storage.storage_shape,
}
}
return res
| 44.47619
| 124
| 0.557102
|
a3af5634a303a9347a0729a4df73e3cd8d4f2b39
| 4,642
|
ts
|
TypeScript
|
src/clang.ts
|
KritantaDev/vscode-clang
|
8246240f71ea94d612312b08e621b0024c177e82
|
[
"MIT"
] | 136
|
2016-01-19T20:39:51.000Z
|
2021-12-28T20:05:19.000Z
|
src/clang.ts
|
KritantaDev/vscode-clang
|
8246240f71ea94d612312b08e621b0024c177e82
|
[
"MIT"
] | 90
|
2016-01-15T16:53:53.000Z
|
2022-03-06T15:09:52.000Z
|
src/clang.ts
|
KritantaDev/vscode-clang
|
8246240f71ea94d612312b08e621b0024c177e82
|
[
"MIT"
] | 41
|
2016-01-28T23:08:47.000Z
|
2021-06-30T16:29:50.000Z
|
import * as vscode from "vscode";
import * as variable from "./variable";
import * as state from "./state";
const renamedKeyMap: Map<string, string> = new Map<string, string>(
new Array<[string, string]>(
["diagnostic.delay", "diagnosticDelay"],
["diagnostic.enable", "enableDiagnostic"],
["completion.enable", "enableCompletion"]
)
);
const insecureKeys: Set<string> = new Set<string>([
'executable',
'cflags',
'cxxflags',
'objcflags',
]);
export function checkInsecureKeys(): Thenable<void> {
if (state.getWorkspaceState().getWorkspaceIsTrusted() !== undefined) {
return Promise.resolve();
}
const customInsecureSettings = [];
for (const key of insecureKeys) {
if (getConf(key) !== undefined && JSON.stringify(getConf(key)) !== JSON.stringify(vscode.workspace.getConfiguration("clang").get(key))) {
customInsecureSettings.push(key);
}
}
if (customInsecureSettings.length > 0) {
return vscode.window.showWarningMessage(
"Some of workspace-level setting (" + customInsecureSettings.map((s) => "`clang." + s + "`").join(", ") + ") is disabled by default. "
+ "These settings may cause security issue, if you are opening a malicious workspece. "
+ "Do you trust the current workspace and enable these settings? ",
{modal: false},
{title: "Yes"}, {title: "No"}, {title: "More Info"},
).then((answer) => {
switch (answer?.title) {
case "Yes": {
state.getWorkspaceState().updateWorkspaceIsTrusted(true);
break;
}
case "No": {
state.getWorkspaceState().updateWorkspaceIsTrusted(false);
break;
}
case "More Info":
vscode.env.openExternal(
vscode.Uri.parse(`https://github.com/mitaki28/vscode-clang/blob/master/README.md#Security`)
);
return checkInsecureKeys();
default:
// do nothing (keep unanswerd state)
}
});
} else {
return Promise.resolve();
}
}
export function getConf<T>(name: string): T {
const conf = vscode.workspace.getConfiguration("clang");
if (renamedKeyMap.has(name)) {
let deprecatedName = renamedKeyMap.get(name)!;
if (conf.has(deprecatedName)) {
vscode.window.showWarningMessage(
`clang.${deprecatedName} is deprecated. Please use ${name} instead.`
);
name = deprecatedName;
}
}
if (!conf.has(name)) {
throw new Error(`implementation error: ${name} is not defined`);
}
if (insecureKeys.has(name) && state.getWorkspaceState().getWorkspaceIsTrusted() !== true) {
const inspection = conf.inspect<T>(name)!;
return (inspection.globalLanguageValue ?? inspection.globalValue ?? inspection.defaultValue)!;
} else {
return conf.get<T>(name)!;
}
}
export function command(language: string, ...options: string[]): [string, string[]] {
let cmd = variable.resolve(getConf<string>("executable"));
let args: string[] = [];
if (language === "cpp") {
args.push("-x", "c++");
args.push(...getConf<string[]>("cxxflags").map(variable.resolve));
} else if (language === "c") {
args.push("-x", "c");
args.push(...getConf<string[]>("cflags").map(variable.resolve));
} else if (language === "objective-c") {
args.push("-x", "objective-c");
args.push(...getConf<string[]>("objcflags").map(variable.resolve));
}
args.push(...options);
return [cmd, args];
}
export function complete(language: string, line: number, char: number): [string, string[]] {
let args = [];
args.push("-fsyntax-only");
args.push("-fparse-all-comments");
if (getConf<boolean>("completion.completeMacros")) {
args.push("-Xclang", "-code-completion-macros");
}
args.push("-Xclang", "-code-completion-brief-comments");
args.push("-Xclang", `-code-completion-at=<stdin>:${line}:${char}`);
args.push("-");
return command(language, ...args);
}
export function check(language: string): [string, string[]] {
return command(language,
"-fsyntax-only",
"-fno-caret-diagnostics",
"-fdiagnostics-print-source-range-info",
"-fno-color-diagnostics",
"-");
}
export function version(language: string): [string, string[]] {
return command(language, "--version");
}
| 36.84127
| 146
| 0.576907
|
9375b4add29145393bd5457bf56b8b12e1b0e9c7
| 3,866
|
cs
|
C#
|
OpenSim/Region/Framework/StorageManager.cs
|
Ideia-Boa/diva-distribution
|
900ea516c1e57e2976a008ca6089afe1a64231f5
|
[
"BSD-3-Clause"
] | 1
|
2016-07-23T23:18:20.000Z
|
2016-07-23T23:18:20.000Z
|
OpenSim/Region/Framework/StorageManager.cs
|
mcortez/opensim
|
6dc971b104cf29cef1f9f3890af13cd5a10dc3e4
|
[
"BSD-3-Clause"
] | null | null | null |
OpenSim/Region/Framework/StorageManager.cs
|
mcortez/opensim
|
6dc971b104cf29cef1f9f3890af13cd5a10dc3e4
|
[
"BSD-3-Clause"
] | 1
|
2020-07-10T06:42:56.000Z
|
2020-07-10T06:42:56.000Z
|
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Reflection;
using log4net;
using OpenSim.Region.Framework.Interfaces;
namespace OpenSim.Region.Framework
{
public class StorageManager
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
protected IRegionDataStore m_dataStore;
public IRegionDataStore DataStore
{
get { return m_dataStore; }
}
private IEstateDataStore m_estateDataStore;
public IEstateDataStore EstateDataStore
{
get { return m_estateDataStore; }
}
public StorageManager(IRegionDataStore storage)
{
m_dataStore = storage;
}
public StorageManager(string dllName, string connectionstring, string estateconnectionstring)
{
m_log.Info("[DATASTORE]: Attempting to load " + dllName);
Assembly pluginAssembly = Assembly.LoadFrom(dllName);
foreach (Type pluginType in pluginAssembly.GetTypes())
{
if (pluginType.IsPublic)
{
Type typeInterface = pluginType.GetInterface("IRegionDataStore", true);
if (typeInterface != null)
{
IRegionDataStore plug =
(IRegionDataStore) Activator.CreateInstance(pluginAssembly.GetType(pluginType.ToString()));
plug.Initialise(connectionstring);
m_dataStore = plug;
m_log.Info("[DATASTORE]: Added IRegionDataStore Interface");
}
typeInterface = pluginType.GetInterface("IEstateDataStore", true);
if (typeInterface != null)
{
IEstateDataStore estPlug =
(IEstateDataStore) Activator.CreateInstance(pluginAssembly.GetType(pluginType.ToString()));
estPlug.Initialise(estateconnectionstring);
m_estateDataStore = estPlug;
}
}
}
//TODO: Add checking and warning to make sure it initialised.
}
}
}
| 39.85567
| 119
| 0.643818
|
e08c9ac38a89402fe6c2f5b7abc0ff905bcbe400
| 1,311
|
c
|
C
|
17_estruturas_genericas/exercicio_02.c
|
mariosoares/Estrut-Dados-Celes-Respostas
|
56931c18f08b7d1edbf35f762d6d604aad635914
|
[
"Apache-2.0"
] | 14
|
2018-10-09T06:53:31.000Z
|
2022-03-21T10:16:08.000Z
|
17_estruturas_genericas/exercicio_02.c
|
mariosoares/Estrut-Dados-Celes-Respostas
|
56931c18f08b7d1edbf35f762d6d604aad635914
|
[
"Apache-2.0"
] | null | null | null |
17_estruturas_genericas/exercicio_02.c
|
mariosoares/Estrut-Dados-Celes-Respostas
|
56931c18f08b7d1edbf35f762d6d604aad635914
|
[
"Apache-2.0"
] | 5
|
2020-01-18T12:08:21.000Z
|
2022-03-31T23:48:37.000Z
|
/*
* Use o TAD do item anterior para armazenar dados de alunos:
*
* typedef struct aluno Aluno;
* struct aluno {
* char nome[81];
* float nota;
* };
*
* Implemente o código necessário para calcular a média das notas dos alunos arma-
* zenados no vetor.
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "vetgen.h"
typedef struct aluno Aluno;
struct aluno {
char nome[81];
float nota;
};
static int imprime_soma(void *info, void *dado)
{
Aluno *a = (Aluno *) info;
float *s = (float *)dado;
printf("%s: %.1f\n", a->nome, a->nota);
*s += a->nota;
return 0;
}
static void insere(VetorGen * vg, char *nome, float nota)
{
Aluno *a = (Aluno *) malloc(sizeof(Aluno));
if (!a) {
perror("");
exit(EXIT_FAILURE);
}
strcpy(a->nome, nome);
a->nota = nota;
vgen_insere(vg, a);
}
int main(void)
{
float m = 0;
float nota;
char nome[81];
VetorGen *vg = vgen_cria();
puts("Informe nome e nota do aluno (Ctrl+D para encerrar)");
while (1) {
printf("\nNome: ");
if (1 == scanf(" %80[^\n]", nome)) {
printf("Nota: ");
if (1 == scanf("%f", ¬a)) {
insere(vg, nome, nota);
continue;
}
}
break;
}
vgen_percorre(vg, imprime_soma, &m);
m /= vgen_tam(vg);
printf("Media dos alunos: %.1f\n", m);
vgen_libera(vg, free);
return 0;
}
| 18.464789
| 82
| 0.604882
|
a41d48a13e15d5574d59afbb344804994283da7b
| 2,483
|
php
|
PHP
|
www/TestsDiv.php
|
Vladimir-Trufanov/TPhpTools
|
2a6f28f0ca5b2113791db8d30a17e32e53693957
|
[
"MIT"
] | null | null | null |
www/TestsDiv.php
|
Vladimir-Trufanov/TPhpTools
|
2a6f28f0ca5b2113791db8d30a17e32e53693957
|
[
"MIT"
] | null | null | null |
www/TestsDiv.php
|
Vladimir-Trufanov/TPhpTools
|
2a6f28f0ca5b2113791db8d30a17e32e53693957
|
[
"MIT"
] | null | null | null |
<?php
// PHP7/HTML5, EDGE/CHROME *** TestsDiv.php ***
// ****************************************************************************
// * TPhpTools-test Развернуть правую часть экрана - *
// * выполнить заданный тест *
// ****************************************************************************
// Автор: Труфанов В.Е.
// Дата создания: 13.01.2019
// Copyright © 2019 tve Посл.изменение: 25.08.2021
// Определяем каталог тестов библиотеки прикладных классов
$TPhpToolsTests=$SiteHost.'/TPhpTools/TPhpToolsTests';
// Строим разметку для проведения тестов
echo '<div class="container">';
// Принимаем команду на запуск тестов
$classTT=prown\getComRequest('test');
if ($classTT===NULL)
{
$classTT='NULL';
echo 'Класс для тестирования не выбран!<br>';
}
else
{
require_once $TPhpToolsTests."/T_ToolsTestCommon.php";
// Определяем главный модуль тестирования класса и подключаем вспомогательные
define ("ScenName",$TPhpToolsTests."/T".$classTT."__test.php");
if ($classTT=='BaseMaker')
{
require_once $TPhpToolsTests."/TBaseMaker_CreateBaseTest.php";
require_once $TPhpToolsTests."/TBaseMaker_PragmaTest.php";
require_once $TPhpToolsTests."/TBaseMaker_ValueRow.php";
require_once $TPhpToolsTests."/TBaseMaker_Query.php";
require_once $TPhpToolsTests."/TBaseMaker_UpdateInsert.php";
}
else if ($classTT=='UploadToServer')
{
require_once $TPhpToolsTests."/TUploadToServer_Construct.php";
}
// Подключаем и вызываем тестовую оболочку
require_once($SiteHost.'/TSimpleTest/autorun.php');
class test_TTools extends UnitTestCase
{
function test_TPhpTools()
{
echo '<div id="TestsDiv">';
$shellTest=$this; require_once (ScenName); // запустили главный модуль тестов класса
echo '</div>';
}
}
// Выводим меню для возврата в контрольное меню тестов
echo '<ul>';
echo
'<li id=li'.$classTT.' class="dropdown">'.
'<input type="checkbox" name="test" value="'.$classTT.'">'.
'<a href="'.$SpecSite.'/?control='.$classTT.'" data-toggle="dropdown">T'.$classTT.'</a>'.
'</li>';
echo '</ul>';
}
echo '</div>';
// <!-- --> ************************************************** TestsDiv.php ***
| 39.412698
| 95
| 0.548933
|
4409f7c7e409a18b2b31582c5ad096cfb87dfef8
| 4,394
|
py
|
Python
|
src/remotia/deployers/common.py
|
hivesolutions/remotia
|
cb7f3f1c8993af28991fdae36cf2000c1423ddc4
|
[
"Apache-1.1"
] | 1
|
2015-11-12T16:31:03.000Z
|
2015-11-12T16:31:03.000Z
|
src/remotia/deployers/common.py
|
hivesolutions/remotia
|
cb7f3f1c8993af28991fdae36cf2000c1423ddc4
|
[
"Apache-1.1"
] | null | null | null |
src/remotia/deployers/common.py
|
hivesolutions/remotia
|
cb7f3f1c8993af28991fdae36cf2000c1423ddc4
|
[
"Apache-1.1"
] | null | null | null |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Hive Remotia System
# Copyright (c) 2008-2020 Hive Solutions Lda.
#
# This file is part of Hive Remotia System.
#
# Hive Remotia System is free software: you can redistribute it and/or modify
# it under the terms of the Apache License as published by the Apache
# Foundation, either version 2.0 of the License, or (at your option) any
# later version.
#
# Hive Remotia System 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
# Apache License for more details.
#
# You should have received a copy of the Apache License along with
# Hive Remotia System. If not, see <http://www.apache.org/licenses/>.
__author__ = "João Magalhães <joamag@hive.pt>"
""" The author(s) of the module """
__version__ = "1.0.0"
""" The version of the module """
__revision__ = "$LastChangedRevision$"
""" The revision number of the module """
__date__ = "$LastChangedDate$"
""" The last change date of the module """
__copyright__ = "Copyright (c) 2008-2020 Hive Solutions Lda."
""" The copyright for the module """
__license__ = "Apache License, Version 2.0"
""" The license for the module """
import os
import sys
import legacy
import paramiko
import datetime
DEBUG = False
SSH_INSTANCES = {}
base_dir = os.path.dirname(__file__)
base_dir = os.path.normpath(base_dir)
root_dir = os.path.join(base_dir, "..")
root_dir = os.path.normpath(root_dir)
templates_home = os.path.join(root_dir, "templates")
user_home = os.path.expanduser("~")
dropbox_base = os.path.join(user_home, "Dropbox")
dropbox_home = os.path.join(dropbox_base, "Home")
ssh_home = os.path.join(dropbox_home, "ssh")
if not user_home in sys.path: sys.path.append(user_home)
if not dropbox_base in sys.path: sys.path.append(dropbox_base)
if not dropbox_home in sys.path: sys.path.append(dropbox_home)
rconfig = __import__("rconfig")
config = rconfig
def get_ssh(hostname, force = False):
ssh = SSH_INSTANCES.get(hostname, None)
if ssh and not force: return ssh
username, password = config.SERVERS_MAP.get(hostname, ("root", "root"))
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
print_host(hostname, "connecting...")
home_path = os.path.expanduser("~")
id_rsa_path = os.path.join(home_path, ".ssh", "id_rsa")
id_rsa_exists = os.path.exists(id_rsa_path)
id_rsa_exists and ssh.connect(
hostname,
username = username,
password = password,
key_filename = id_rsa_path
) or ssh.connect(
hostname,
username = username,
password = password
)
print_host(hostname, "connected")
SSH_INSTANCES[hostname] = ssh
return ssh
def command(ssh, command, shell = False):
if shell: return command_shell(ssh, command)
else: return command_single(ssh, command)
def command_single(ssh, command):
stdin, stdout, stderr = ssh.exec_command(command)
data_out = stdout.readlines()
data_err = stderr.readlines()
stream_out = legacy.StringIO()
stream_err = legacy.StringIO()
for line in data_out: stream_out.write(line + "\n")
for line in data_err: stream_err.write(line + "\n")
stream_out.seek(0)
stream_err.seek(0)
if DEBUG:
for line in data_out: print(line)
for line in data_err: print(line)
return stdin, stream_out, stream_err
def command_shell(ssh, command):
channel = ssh.invoke_shell()
stdin = channel.makefile("wb")
stdout = channel.makefile("rb")
stdin.write(command + "\r\n" + "exit\r\n")
data_out = stdout.readlines()
stream_out = legacy.StringIO()
for line in data_out: stream_out.write(line + "\n")
stream_out.seek(0)
if DEBUG:
for line in data_out: print(line)
stdout.close()
stdin.close()
def print_host(hostname, message):
print("[" + hostname + "] " + message)
def get_date_s():
date_time = datetime.datetime.now()
date_s = date_time.strftime("%Y%m%d")
return date_s
def get_date_time_s():
date_time = datetime.datetime.now()
date_time_s = date_time.strftime("%Y%m%d%H%M")
return date_time_s
cmd = command
| 28.718954
| 78
| 0.672053
|
57ec47a546ccdb3016997adeacd4b31a452044d2
| 1,021
|
php
|
PHP
|
booking_complete.php
|
dat1041988/rezgo-parser
|
7464b20521c27292c63ba6f755d5e49ec38ae361
|
[
"Apache-2.0"
] | 1
|
2020-01-08T12:48:16.000Z
|
2020-01-08T12:48:16.000Z
|
booking_complete.php
|
arinno/rezgo-parser
|
1ff56a49f41e7ad601a4da4152a6791210655e79
|
[
"Apache-2.0"
] | null | null | null |
booking_complete.php
|
arinno/rezgo-parser
|
1ff56a49f41e7ad601a4da4152a6791210655e79
|
[
"Apache-2.0"
] | null | null | null |
<?php
// This is the booking receipt page
require('rezgo/include/page_header.php');
// start a new instance of RezgoSite
$site = new RezgoSite();
// grab and decode the trans_num if it was set
$trans_num = $site->decode($_REQUEST['trans_num']);
// send the user home if they shoulden't be here
if(!$trans_num) $site->sendTo($site->base."/booking-not-found");
// start a session so we can grab the analytics code
session_start();
// empty the cart
$site->clearCart();
$site->setMetaTags('<meta name="robots" content="noindex, nofollow">');
?>
<?=$site->getTemplate('frame_header')?>
<? if(strlen($trans_num) == 16) { ?>
<?=$site->getTemplate('booking_order')?>
<?
$ga_add_transacton = "
ga('ecommerce:addTransaction', {
'id': '$trans_num',
'affiliation': '$c',
'revenue': '$cart_total',
'currency': '".$site->getBookingCurrency()."'
});
";
?>
<? } else { ?>
<?=$site->getTemplate('booking_complete')?>
<? } ?>
<?=$site->getTemplate('frame_footer')?>
| 21.270833
| 72
| 0.621939
|
43f6acb2d55b6d66d97b71e9ac8489557247477f
| 265
|
ts
|
TypeScript
|
src/wait-for-dom-content-loaded.ts
|
BlackGlory/wait-for
|
7f4ac58dc4f72eae8c93f99bc133d6c00207a461
|
[
"MIT"
] | null | null | null |
src/wait-for-dom-content-loaded.ts
|
BlackGlory/wait-for
|
7f4ac58dc4f72eae8c93f99bc133d6c00207a461
|
[
"MIT"
] | 6
|
2021-01-04T14:27:00.000Z
|
2021-12-24T06:39:29.000Z
|
src/wait-for-dom-content-loaded.ts
|
BlackGlory/wait-for
|
7f4ac58dc4f72eae8c93f99bc133d6c00207a461
|
[
"MIT"
] | 1
|
2021-10-16T08:06:36.000Z
|
2021-10-16T08:06:36.000Z
|
export function waitForDOMContentLoaded(): Promise<void> {
return new Promise(resolve => {
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', () => resolve(), { once: true })
} else {
resolve()
}
})
}
| 26.5
| 84
| 0.618868
|
2c98f1c092b65ce2ec69568fe50df4ea9368d181
| 4,378
|
py
|
Python
|
main/passwordValidator.py
|
FredHappyface/Python.PasswordValidator
|
7ab48a073456e3431489fd476f46428bd09cbf1f
|
[
"MIT"
] | null | null | null |
main/passwordValidator.py
|
FredHappyface/Python.PasswordValidator
|
7ab48a073456e3431489fd476f46428bd09cbf1f
|
[
"MIT"
] | null | null | null |
main/passwordValidator.py
|
FredHappyface/Python.PasswordValidator
|
7ab48a073456e3431489fd476f46428bd09cbf1f
|
[
"MIT"
] | null | null | null |
'''
Author FredHappyface
Date 2019/07/22
passwordValidator.py is a more intelligent password validator that fails early
and suggests changes to your passwords
'''
import os, sys, inspect
THISDIR = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))
# Add ../lib to the import path
sys.path.insert(0, os.path.dirname(THISDIR) + "/lib")
import fileIO
import math
CONFIG = "config.json"
RES = "res/"
PASSWORDS = "validatePasswords.txt"
MIN_LENGTH, WEAK_SYMBOLS, WEAK_NUMBERS, SUGGESTIONS, MIN_LENGTH_RES, MAX_LENGTH_RES, ENTROPY_THRESHOLD = "", "", "", "", "", "", 0
def readConfig():
data = fileIO.readJSON(fileIO.genFileName([THISDIR, CONFIG]))
return data["minLength"], data["weakSymbols"], data["weakNumbers"], data["suggestions"], data["minLengthRes"], data["maxLengthRes"], data["entropy"]
def passwordValidator(password):
score = 0
# Too Short
if len(password) < MIN_LENGTH:
return score, SUGGESTIONS["underMinLength"], str(len(password))
# Letters Only
score += 1
if onlyCharsInPassword(password, [('A', 'Z'), ('a', 'z')]):
return score, SUGGESTIONS["lettersOnly"], ""
# Letters and Numbers Only
score += 1
if onlyCharsInPassword(password, [('0', '9'), ('A', 'Z'), ('a', 'z')]):
return score, SUGGESTIONS["lettersAndNumbersOnly"], ""
# Common Numbers
score += 1
for number in WEAK_NUMBERS:
pos = password.find(str(number))
adjacentNumber = False
if pos != -1:
if (pos + 1) < len(password) and charInPassword(password[pos + 1], [('0', '9')]):
adjacentNumber = True
if (pos -1) > -1 and charInPassword(password[pos - 1], [('0', '9')]):
adjacentNumber = True
if not adjacentNumber:
return score, SUGGESTIONS["weakNumbers"], str(number)
# Common Symbols
score += 1
asciiRange = []
for symbol in WEAK_SYMBOLS:
asciiRange.append((symbol, symbol))
if charInPassword(password, asciiRange):
return score, SUGGESTIONS["weakSymbols"], ""
# Shannon entropy below threshold
score += 1
if shannonEntropy(password) < ENTROPY_THRESHOLD:
return score, SUGGESTIONS["lowEntropy"], ""
# Common Passwords in Password
score += 1
for length in range(MIN_LENGTH_RES, min(len(password), MAX_LENGTH_RES)):
commonFileName = fileIO.genFileName([THISDIR, RES, "passwords" + str(length) + ".txt"])
if os.path.isfile(commonFileName):
commonFile = open(commonFileName, "r")
for commonPassword in commonFile:
if password.lower().find(commonPassword.rstrip().lower()) > -1:
return score, SUGGESTIONS["commonPasswordInPassword"], commonPassword[:-1]
score += 1
return score, "Max Score", ""
def charInPassword(password, asciiRange):
for char in password:
for asciiChars in asciiRange:
if ord(char) >= ord(asciiChars[0]) and ord(char) <= ord(asciiChars[1]):
return True
return False
def onlyCharsInPassword(password, asciiRange):
pointer = 0
notAsciiRange = []
for asciiChars in asciiRange:
notAsciiRange.append((chr(pointer), chr(ord(asciiChars[0]) -1)))
pointer = ord(asciiChars[1]) + 1
notAsciiRange.append((chr(pointer), chr(128)))
return not charInPassword(password, notAsciiRange)
'''
Calculates the shannon entropy. Better passwords will have a better
shannon entropy
'''
def shannonEntropy(string):
probChars = [float(string.count(char)) / len(string) for char in dict.fromkeys(list(string))]
return - sum([probChar * math.log(probChar) / math.log(2.0) for probChar in probChars])
'''
Global variables are either block caps eg MIN_LENGTH or preceded with g_ eg
g_score
'''
if __name__ == "__main__": # pragma: no cover
MIN_LENGTH, WEAK_SYMBOLS, WEAK_NUMBERS, SUGGESTIONS, MIN_LENGTH_RES, MAX_LENGTH_RES, ENTROPY_THRESHOLD = readConfig()
g_passwordTokens = fileIO.fileToTokens(fileIO.genFileName([THISDIR, PASSWORDS]))
for g_password in g_passwordTokens:
pskClean = g_password.rstrip()
g_score, g_suggestion, g_offense = passwordValidator(pskClean)
print("password:", pskClean)
print("\tscore:", g_score)
print("\tsuggestion:", g_suggestion)
print("\toffense:", g_offense)
| 36.181818
| 152
| 0.656693
|
fddddaed4b316747db990cddc356ef5047622fb5
| 25
|
css
|
CSS
|
src/css/components/po-info/index.css
|
leonardosimoura/po-style
|
6ea2dcfe7c7f54cddda55e693771a34290b85234
|
[
"MIT"
] | 25
|
2020-05-09T18:08:02.000Z
|
2022-03-18T02:57:04.000Z
|
src/css/components/po-info/index.css
|
leonardosimoura/po-style
|
6ea2dcfe7c7f54cddda55e693771a34290b85234
|
[
"MIT"
] | 14
|
2020-04-15T20:55:28.000Z
|
2022-01-30T15:43:29.000Z
|
src/css/components/po-info/index.css
|
leonardosimoura/po-style
|
6ea2dcfe7c7f54cddda55e693771a34290b85234
|
[
"MIT"
] | 33
|
2020-03-25T14:00:29.000Z
|
2022-03-12T09:52:36.000Z
|
@import './po-info.css';
| 12.5
| 24
| 0.6
|
8ea0d8f0a305b28674d6347ea2c9e9c541103642
| 829
|
rb
|
Ruby
|
spec/services/pipeline_service/serializers_spec.rb
|
FeatureToggleStudy/canvas_shim
|
07f4a811fab7f58b0b77c6f76cde0e2fe5d272cf
|
[
"MIT"
] | null | null | null |
spec/services/pipeline_service/serializers_spec.rb
|
FeatureToggleStudy/canvas_shim
|
07f4a811fab7f58b0b77c6f76cde0e2fe5d272cf
|
[
"MIT"
] | 41
|
2019-01-29T20:32:12.000Z
|
2021-07-12T19:00:17.000Z
|
spec/services/pipeline_service/serializers_spec.rb
|
FeatureToggleStudy/canvas_shim
|
07f4a811fab7f58b0b77c6f76cde0e2fe5d272cf
|
[
"MIT"
] | 2
|
2019-11-03T19:35:41.000Z
|
2020-12-16T00:20:18.000Z
|
describe PipelineService::Serializers do
include_context 'stubbed_network'
describe '#names' do
it 'list the names of the serializers' do
expect(described_class.names).to include(:Assignment)
end
it 'does not include base methods' do
expect(described_class.names).to_not include(:BaseMethods)
end
end
describe '#repositories' do
it 'returns repositories' do
expect(described_class.repositories).to include(::Assignment)
end
it 'does not include serializers that do not use repos' do
expect(described_class.repositories).to_not include(PipelineService::Serializers::CanvasAPIEnrollment)
end
end
describe '#list' do
it 'returns the serializers' do
expect(described_class.list).to include(PipelineService::Serializers::Assignment)
end
end
end
| 29.607143
| 108
| 0.732207
|
70e9c3a2d18e7cb2a5c8b2de54676a1734286186
| 162
|
sql
|
SQL
|
web/db/DBScripts/DBScripts/AttacheToDB.sql
|
benchuk/PicAround
|
5ddc3bd59e0bf6d13a1eaf1050c66426798aefca
|
[
"MIT"
] | null | null | null |
web/db/DBScripts/DBScripts/AttacheToDB.sql
|
benchuk/PicAround
|
5ddc3bd59e0bf6d13a1eaf1050c66426798aefca
|
[
"MIT"
] | null | null | null |
web/db/DBScripts/DBScripts/AttacheToDB.sql
|
benchuk/PicAround
|
5ddc3bd59e0bf6d13a1eaf1050c66426798aefca
|
[
"MIT"
] | null | null | null |
EXEC sp_attach_db
@dbname = N'Picup',
@filename1 = N'C:\Android\WebSite\PicUpMvc3\PicApp1\App_Data\PicUpDB.mdf'
EXEC sp_detach_db
@dbname = N'Picup'
| 18
| 74
| 0.709877
|
9ff20de4069c7434facc95ac4771da5d600af92b
| 2,293
|
py
|
Python
|
runner.py
|
Pgmbru/wowhead_scraper
|
b4bf3e71bf88abac707d1d1f8c93a30f7c7d0164
|
[
"MIT"
] | null | null | null |
runner.py
|
Pgmbru/wowhead_scraper
|
b4bf3e71bf88abac707d1d1f8c93a30f7c7d0164
|
[
"MIT"
] | null | null | null |
runner.py
|
Pgmbru/wowhead_scraper
|
b4bf3e71bf88abac707d1d1f8c93a30f7c7d0164
|
[
"MIT"
] | null | null | null |
from argparse import ArgumentParser
from logging import getLogger
from pathlib import Path
from typing import Union
from scrapy.crawler import CrawlerProcess
from spiders import NPCSpider, QuestSpider
class Runner:
lang: str = ""
target: str = ""
output_dir: Path = None
def __init__(self, lang: str, target: str) -> None:
self.lang = lang
self.target = target
self.logger = getLogger(__name__)
self.output_dir = self.__create_output_dir()
@staticmethod
def __create_output_dir() -> Path:
out = Path("output")
if not out.exists():
out.mkdir()
return out
def run(self) -> None:
feed_uri = self.__build_feed_uri()
if feed_uri is None:
return None
process = CrawlerProcess(settings={
"LOG_LEVEL": "INFO",
"FEED_EXPORT_ENCODING": "utf-8",
"FEED_FORMAT": "json",
"CONCURRENT_REQUESTS": 32,
"FEED_URI": str(feed_uri),
"COOKIES_ENABLED": False
})
self.logger.info("Starting {} crawler".format(self.target))
if self.target == "npc":
process.crawl(NPCSpider, lang=self.lang)
elif self.target == "quest":
process.crawl(QuestSpider, lang=self.lang)
process.start()
def __build_feed_uri(self) -> Union[Path, None]:
if self.target == "npc":
feed_uri = self.output_dir / "{}_npc_data.json".format(self.lang)
elif self.target == "quest":
feed_uri = self.output_dir / "{}_quest_data.json".format(self.lang)
else:
self.logger.error("Unknown target '{}'".format(self.target))
return None
return feed_uri
if __name__ == '__main__':
parser = ArgumentParser()
parser.add_argument("-l", "--lang", help="The language you want to scrape. Default: 'en'",
type=str)
parser.add_argument("-t", "--target", help="The target you want to scrape. Either 'npc' or 'quest'. Default: 'npc'",
type=str)
args = parser.parse_args()
if args.lang is None:
args.lang = "en"
if args.target is None:
args.target = "npc"
runner = Runner(args.lang, args.target)
runner.run()
| 29.779221
| 120
| 0.58744
|
eb8d1e21846361e5be544c512782b7b721064757
| 2,931
|
css
|
CSS
|
css/antsand--forms.css
|
antsand/styles
|
de5e42d64ad74c5b517b195bf01caf7c286cafe7
|
[
"MIT"
] | 2
|
2019-01-24T23:17:13.000Z
|
2019-01-28T23:35:56.000Z
|
css/antsand--forms.css
|
antsand/styles
|
de5e42d64ad74c5b517b195bf01caf7c286cafe7
|
[
"MIT"
] | null | null | null |
css/antsand--forms.css
|
antsand/styles
|
de5e42d64ad74c5b517b195bf01caf7c286cafe7
|
[
"MIT"
] | null | null | null |
*,*:before,*:after{-moz-box-sizing:border-box;-webkit-box-sizing:border-box;box-sizing:border-box}.color-red{color:#d52b1e}.form-padding{padding:45px 0px}.form-default .form-elements{margin:15px 0px}.form-default input[type="text"],.form-default input[type="email"],.form-default input[type="tel"],.form-default input[type="number"],.form-default select,.form-default textarea,.form-default .input{padding:.6em .7em .5em .7em;font-size:.9em;color:#666;box-shadow:none;-moz-box-shadow:none;-webkit-box-shadow:none;border:1px solid #ccc;border-color:#c4c4c4 #d8d8d8 #e2e2e2;outline:none;margin:0;line-height:1.5em;width:100%;border-radius:4px;-moz-border-radius:4px;-webkit-border-radius:4px;box-sizing:border-box;-moz-box-sizing:border-box;-webkit-box-sizing:border-box;font-family:Helvetica,Arial;vertical-align:top}.form-default input[type="text"] a,.form-default input[type="email"] a,.form-default input[type="tel"] a,.form-default input[type="number"] a,.form-default select a,.form-default textarea a,.form-default .input a{list-style:none;text-decoration:none;text-decoration-line:none;text-decoration-style:solid;list-style-type:none;list-style-image:none;list-style-position:outside;border:0px solid #000;outline:none;color:inherit;text-decoration:underline;color:#007AB8;outline:none}.form-default input[type="text"] a li,.form-default input[type="email"] a li,.form-default input[type="tel"] a li,.form-default input[type="number"] a li,.form-default select a li,.form-default textarea a li,.form-default .input a li{list-style-image:none;list-style-type:none;margin-left:0}.form-default input[type="text"] hr,.form-default input[type="email"] hr,.form-default input[type="tel"] hr,.form-default input[type="number"] hr,.form-default select hr,.form-default textarea hr,.form-default .input hr{margin-top:16px;margin-bottom:16px;border:0;border-top:1px solid rgba(0,0,0,0.1)}.form-default .error{border:#ff8181 2px solid !important}.form-default .input-container{position:relative;margin:6px 0 9px 0}.form-default .error-notification{position:absolute;z-index:100;width:auto;line-height:1;top:-10%;font-size:11px;right:32px;display:block;margin:auto auto;text-align:center;background:white;color:#ec2222}.form-default .form-text{display:block;margin-top:.25rem}.form-default .label-container{margin-bottom:6px}.form-default .label{line-height:1.42857143;color:#333;font-weight:bold;font-size:15.6px;display:block;flex:none;max-width:none;margin:0;padding:0 0 3px 0;border:none;display:block;white-space:normal;width:100%;min-height:20px}.form-default .sub-label{color:rgba(15,15,15,0.7);line-height:1.2;min-height:15px;font-size:12px}.form-default .required{position:relative}.form-default .required:after{content:'*';color:red;position:absolute;top:-0.32em;z-index:10;left:-0.17em;right:-0.15em;font-size:1.6em;font-family:Helvetica;font-weight:bold;width:10px}.popup-form-white{background-color:rgba(255,255,255,0.98)}
| 1,465.5
| 2,930
| 0.778915
|
6d412c24e70e84f1031972383c3f7b1d1675ac06
| 8,493
|
ts
|
TypeScript
|
src/provider/controller/ToastManager.ts
|
TheoOttahOF/notifications-service
|
d848b89e27519ba6985c3ff7f0eb44479087b1e9
|
[
"Apache-2.0"
] | null | null | null |
src/provider/controller/ToastManager.ts
|
TheoOttahOF/notifications-service
|
d848b89e27519ba6985c3ff7f0eb44479087b1e9
|
[
"Apache-2.0"
] | null | null | null |
src/provider/controller/ToastManager.ts
|
TheoOttahOF/notifications-service
|
d848b89e27519ba6985c3ff7f0eb44479087b1e9
|
[
"Apache-2.0"
] | null | null | null |
import {injectable, inject} from 'inversify';
import {Inject} from '../common/Injectables';
import {StoredNotification} from '../model/StoredNotification';
import {Toast, ToastState} from '../model/Toast';
import {CreateNotification, RemoveNotifications, ToggleCenterVisibility, MinimizeToast, ToggleCenterMuted} from '../store/Actions';
import {ServiceStore} from '../store/ServiceStore';
import {Action} from '../store/Store';
import {RootState} from '../store/State';
import {MonitorModel} from '../model/MonitorModel';
import {WebWindowFactory} from '../model/WebWindow';
import {Layouter} from './Layouter';
import {LayoutStack} from './LayoutStack';
import {AsyncInit} from './AsyncInit';
@injectable()
export class ToastManager extends AsyncInit {
private readonly _layouter: Layouter;
private readonly _store: ServiceStore;
private readonly _monitorModel: MonitorModel;
private readonly _webWindowFactory: WebWindowFactory;
private readonly _stack: LayoutStack = new LayoutStack();
constructor(
@inject(Inject.STORE) store: ServiceStore,
@inject(Inject.LAYOUTER) layouter: Layouter,
@inject(Inject.MONITOR_MODEL) monitorModel: MonitorModel,
@inject(Inject.WEB_WINDOW_FACTORY) webWindowFactory: WebWindowFactory
) {
super();
this._store = store;
this._store.onAction.add(this.onAction, this);
this._layouter = layouter;
this._layouter.onLayoutRequired.add(this.onLayoutRequired, this);
this._monitorModel = monitorModel;
this._webWindowFactory = webWindowFactory;
}
protected async init() {
await this._store.initialized;
await this._monitorModel.initialized;
}
/**
* Signal callback for layout required event. This signal is emitted by Layouter in events like
* monitor info is changed, etc.
*/
private onLayoutRequired(): void {
this._layouter.layout(this._stack);
}
private async onAction(action: Action<RootState>): Promise<void> {
const retireToast = (toast: Toast) => toast.setState(toast.state >= ToastState.ACTIVE ? ToastState.TRANSITION_OUT : ToastState.CLOSED);
if (action instanceof CreateNotification) {
if (!this._store.state.centerMuted) {
this.create(action.notification);
}
} else if (action instanceof RemoveNotifications) {
action.notifications.forEach((notification: StoredNotification) => {
const toast: Toast | null = this._stack.getToast(notification.id);
if (toast) {
retireToast(toast);
}
});
} else if (action instanceof ToggleCenterMuted) {
if (this._store.state.centerMuted) {
this._stack.items.forEach((toast: Toast) => retireToast(toast));
}
} else if (action instanceof ToggleCenterVisibility) {
this.closeAll();
} else if (action instanceof MinimizeToast) {
const toast: Toast | null = this._stack.getToast(action.notification.id);
if (toast) {
retireToast(toast);
}
}
}
/**
* Instantly closes all toasts (without transition animation) and resets the stack.
*/
private async closeAll(): Promise<void> {
const toasts = this._stack.items.slice();
await Promise.all(toasts.map((toast) => this.closeToast(toast)));
this._stack.clear();
}
/**
* Create a new toast.
*
* Returned promise captures the creation and initialisation of the window that will be used to display the toast,
* but not anything to do with the presentation of the toast to the user.
*
* If the notification re-uses the ID of an existing notification, that window will be closed (including 'close'
* animation) and re-created as part of the returned promise.
*
* @param notification The notification to display in the created toast.
*/
private async create(notification: StoredNotification): Promise<void> {
const state = this._store.state;
if (state.centerVisible) {
return;
}
// Check for existing toast with same ID
// Toast may still exist even after notification is deleted, due to toast animations.
const {id} = notification;
const existing = this._stack.getToast(id);
if (existing) {
// Need to wait for the existing toast to close, so that we can re-use that window identity for a new toast
await existing.setState(existing.state >= ToastState.ACTIVE ? ToastState.TRANSITION_OUT : ToastState.CLOSED);
if (this._stack.items.includes(existing) || this._stack.queue.includes(existing)) {
console.warn('Toast should have been removed from queue by now');
}
await existing.close();
}
// Create toast and immediately add to queue
const toast: Toast = new Toast(this._store, this._monitorModel, this._webWindowFactory, notification);
this._stack.addToQueue(toast);
// Handle state changes
toast.onStateChange.add(this.handleToastStateChange, this);
}
private async handleToastStateChange(toast: Toast, state: ToastState): Promise<void> {
// Handle state-specific toast updates
if (state === ToastState.QUEUED) {
if (this._stack.getToast(toast.id) === toast) {
toast.setState(ToastState.QUEUED);
// Move toast to stack if it'll fit on screen. Otherwise, leave in queue.
this.checkQueue();
} else {
// Notification was deleted whilst window/toast was initialising
console.info(`Toast created but no longer required (init) ${toast.id}`);
toast.close();
}
} else if (state === ToastState.ACTIVE) {
await toast.show();
} else if (state === ToastState.TRANSITION_OUT) {
// Queue-up a CLOSED transition once animation completes
toast.currentTransition!.then(() => {
toast.setState(ToastState.CLOSED);
});
} else if (state === ToastState.CLOSED) {
// Keep toast in stack until window has fully closed
// This ensures we won't attempt to create a new window with the same identity
await toast.close();
this._stack.remove(toast);
// There is extra space now, check the queue.
this.checkQueue();
}
// Refresh toast positions
if (state >= ToastState.ACTIVE) {
this._layouter.layout(this._stack);
}
}
/**
* Instantly closes a toast. Will immediately destroy the toast and its window, use removeToasts to "animate out"
* the toast.
*
* @param toast Toast to delete.
*/
private async closeToast(toast: Toast): Promise<void> {
if (this._stack.existsWithinStack(toast.id) && this._stack.remove(toast)) {
if (toast.state < ToastState.CLOSED) {
toast.setState(ToastState.CLOSED);
} else {
console.warn('Stack contained a toast that was in CLOSED state', toast.id);
// Sanity check, to ensure toast window is removed
toast.close();
}
} else {
console.warn('Trying to delete a toast that is not in the stack', toast && toast.id);
// Toast is likely already closed, but should make sure
await toast.close();
}
}
/**
* Adds a toast from awaiting toasts queue to the layout stack if it would fit.
*/
private async checkQueue(): Promise<void> {
const items = this._layouter.getFittingItems(this._stack, this._stack.queue) as Toast[];
await Promise.all(items.map(async (toast: Toast) => {
if (this._stack.moveToStack(toast)) {
// Snap toast into starting position, and start transition-in animation
await this._layouter.setInitialTransform(toast);
toast.setState(ToastState.ACTIVE);
} else {
// Notification was deleted whilst toast was being measured and positioned
console.info(`Toast created but no longer required (measure) ${toast.id}`);
toast.close();
}
}));
}
}
| 39.873239
| 143
| 0.621688
|
c3677e0f3a0c810123f79efb2a05a710d5761842
| 5,104
|
cs
|
C#
|
Assets/DataBindings/Editor/Lib/gendarme/framework/Gendarme.Framework.Rocks/MethodRocks.cs
|
laicasaane/unity-data-binding
|
b5b2c86e20c1e2087aaaae1f4959de64718fcdd4
|
[
"MIT"
] | 6
|
2019-05-28T14:11:02.000Z
|
2020-05-25T23:10:10.000Z
|
Assets/DataBindings/Editor/Lib/gendarme/framework/Gendarme.Framework.Rocks/MethodRocks.cs
|
laicasaane/unity-data-binding
|
b5b2c86e20c1e2087aaaae1f4959de64718fcdd4
|
[
"MIT"
] | null | null | null |
Assets/DataBindings/Editor/Lib/gendarme/framework/Gendarme.Framework.Rocks/MethodRocks.cs
|
laicasaane/unity-data-binding
|
b5b2c86e20c1e2087aaaae1f4959de64718fcdd4
|
[
"MIT"
] | 1
|
2020-03-15T13:20:31.000Z
|
2020-03-15T13:20:31.000Z
|
//
// Gendarme.Framework.Rocks.MethodRocks
//
// Authors:
// Sebastien Pouliot <sebastien@ximian.com>
// Adrian Tsai <adrian_tsai@hotmail.com>
// Daniel Abramov <ex@vingrad.ru>
// Andreas Noever <andreas.noever@gmail.com>
// Cedric Vivier <cedricv@neonux.com>
//
// Copyright (C) 2007-2008 Novell, Inc (http://www.novell.com)
// Copyright (c) 2007 Adrian Tsai
// Copyright (C) 2008 Daniel Abramov
// (C) 2008 Andreas Noever
// Copyright (C) 2008 Cedric Vivier
//
// 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.
using System.Collections.Generic;
using Mono.Cecil;
namespace Gendarme.Framework.Rocks {
// add Method[Reference|Definition][Collection] extensions methods here
// only if:
// * you supply minimal documentation for them (xml)
// * you supply unit tests for them
// * they are required somewhere to simplify, even indirectly, the rules
// (i.e. don't bloat the framework in case of x, y or z in the future)
/// <summary>
/// MethodRocks contains extensions methods for Method[Definition|Reference]
/// and the related collection classes.
///
/// Note: whenever possible try to use MethodReference since it's extend the
/// reach/usability of the code.
/// </summary>
public static class MethodRocks {
/// <summary>
/// Check if the MethodReference is defined as the entry point of it's assembly.
/// </summary>
/// <param name="self">The MethodReference on which the extension method can be called.</param>
/// <returns>True if the method is defined as the entry point of it's assembly, False otherwise</returns>
public static bool IsEntryPoint (this MethodReference self)
{
return ((self != null) && (self == self.Module.Assembly.EntryPoint));
}
/// <summary>
/// Check if the signature of a method is consitent for it's use as a Main method.
/// Note: it doesn't check that the method is the EntryPoint of it's assembly.
/// <code>
/// static [void|int] Main ()
/// static [void|int] Main (string[] args)
/// </code>
/// </summary>gre
/// <param name="self">The MethodReference on which the extension method can be called.</param>
/// <returns>True if the method is a valid Main, False otherwise.</returns>
public static bool IsMain (this MethodReference self)
{
if (self == null)
return false;
MethodDefinition method = self.Resolve ();
// Main must be static
if (!method.IsStatic)
return false;
if (method.Name != "Main")
return false;
// Main must return void or int
switch (method.ReturnType.Name) {
case "Void":
case "Int32":
// ok, continue checks
break;
default:
return false;
}
// Main (void)
if (!method.HasParameters)
return true;
IList<ParameterDefinition> pdc = method.Parameters;
if (pdc.Count != 1)
return false;
// Main (string[] args)
return (pdc [0].ParameterType.Name == "String[]");
}
/// <summary>
/// Check if the method corresponds to the get or set operation on a property.
/// </summary>
/// <param name="self">The MethodReference on which the extension method can be called.</param>
/// <returns>True if the method is a getter or a setter, False otherwise</returns>
public static bool IsProperty (this MethodReference self)
{
if (self == null)
return false;
MethodDefinition method = self.Resolve ();
if (method == null)
return false;
return ((method.SemanticsAttributes & (MethodSemanticsAttributes.Getter | MethodSemanticsAttributes.Setter)) != 0);
}
/// <summary>
/// Check if the method is visible outside of the assembly.
/// </summary>
/// <param name="self">The MethodReference on which the extension method can be called.</param>
/// <returns>True if the method can be used from outside of the assembly, false otherwise.</returns>
public static bool IsVisible (this MethodReference self)
{
if (self == null)
return false;
MethodDefinition method = self.Resolve ();
if ((method == null) || method.IsPrivate || method.IsAssembly)
return false;
return self.DeclaringType.Resolve ().IsVisible ();
}
}
}
| 35.444444
| 118
| 0.700235
|
38c9d0fa083dd97ee87c14c546a3edd8694c3fd5
| 56,044
|
php
|
PHP
|
application/controllers/dosen/Pengabdian.php
|
irzanurf/siTediTa
|
eea9fc8be4fc20f3fc895884fd84d775de4ce8b7
|
[
"MIT"
] | null | null | null |
application/controllers/dosen/Pengabdian.php
|
irzanurf/siTediTa
|
eea9fc8be4fc20f3fc895884fd84d775de4ce8b7
|
[
"MIT"
] | null | null | null |
application/controllers/dosen/Pengabdian.php
|
irzanurf/siTediTa
|
eea9fc8be4fc20f3fc895884fd84d775de4ce8b7
|
[
"MIT"
] | null | null | null |
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Pengabdian extends CI_Controller {
public function __construct()
{
parent::__construct();
//load model admin
$this->load->model('Admin');
//cek session dan level user
if($this->Admin->is_role() == "1" || $this->Admin->is_role()=='4'){
redirect("login/");
}
$this->load->model('M_PropPengabdian');
$this->load->model('M_Mitra');
$this->load->model('M_User');
$this->load->model('M_Profile');
$this->load->model('M_SumberDana');
$this->load->model('M_Dosen');
$this->load->model('M_Mahasiswa');
$this->load->model('M_SkemaPengabdian');
$this->load->model('M_Admin');
$this->load->model('M_LaporanAkhirPengabdian');
$this->load->model('M_JadwalPengabdian');
$this->load->model('M_Luaran');
$this->load->model('M_KomponenNilaiPengabdian');
$this->load->model('M_NilaiPropPengabdian');
$this->load->model('M_Publikasi_Pribadi');
}
public function index()
{
$user = $this->session->userdata('user_name');
$data['nama'] = $this->M_Dosen->getwhere_dosen(array('nip'=>$user))->result();
$data['berita'] = $this->M_Admin->get_berita(array('id'=>2))->result();
$nama['cek']= $this->M_Profile->cekRevPengabdian(array('nip'=>$user))->result();
$data['view']= $this->M_PropPengabdian->get_viewpengajuan($user)->result();
$data['anggota']= $this->M_PropPengabdian->get_viewanggota($user)->result();
$nama['hitungovr'] = $this->M_Publikasi_Pribadi->hitungovrview();
$this->load->view('pengabdian/header',$nama);
$this->load->view("dosen/dashboardpengabdian",$data);
$this->load->view("pengabdian/footer");
}
public function detail()
{
$id = $this->input->post('id',true);
if($id==NULL){
redirect("dosen/pengabdian/submitpermohonan");
}
// $id_jenis = $this->input->post('id_skema');
$nip = $this->session->userdata('user_name');
$proposal = $data['proposal'] = $this->M_PropPengabdian->getwhere_proposal(array('id'=>$id))->row();
$id_jenis = $proposal->id_skema;
$data['jenis'] = $this->M_KomponenNilaiPengabdian->getwhere_komponen(array('id_skema_pengabdian'=>$id_jenis))->result();
$reviewer = $this->M_PropPengabdian->getwhere_rev(array('id_proposal'=>$id))->row()->reviewer;
$reviewer2 = $this->M_PropPengabdian->getwhere_rev(array('id_proposal'=>$id))->row()->reviewer2;
$data['komponen'] = $this->M_KomponenNilaiPengabdian->get_nilaikomponenProp($id, $reviewer)->result();
$data['komponen2'] = $this->M_KomponenNilaiPengabdian->get_nilaikomponenProp($id,$reviewer2)->result();
$nama['cek']= $this->M_Profile->cekRevPengabdian(array('nip'=>$nip))->result();
$nama['hitungovr'] = $this->M_Publikasi_Pribadi->hitungovrview();
$data['nilai'] = $this->M_NilaiPropPengabdian->getwhere_nilai(array('id_proposal'=>$id))->row()->nilai;
$data['komentar'] = $this->M_NilaiPropPengabdian->getwhere_nilai(array('id_proposal'=>$id))->row()->komentar;
$data['nilai2'] = $this->M_NilaiPropPengabdian->getwhere_nilai(array('id_proposal'=>$id))->row()->nilai2;
$data['komentar2'] = $this->M_NilaiPropPengabdian->getwhere_nilai(array('id_proposal'=>$id))->row()->komentar2;
$this->load->view('pengabdian/header', $nama);
$this->load->view('dosen/detail', $data);
$this->load->view("pengabdian/footer");
}
function checkUsername(){
$userName = $this->input->post('username');
$if_exists = $this->M_User->checkUserexist($userName);
$if_exists_mitra = $this->M_Mitra->checkUserexist($userName);
if ($if_exists > 0 || $if_exists_mitra > 0) {
echo json_encode('Username tidak tersedia');
} else {
echo json_encode('Username tersedia');
}
}
function checkJudul(){
$judul = $this->input->post('judul');
$if_exists = $this->M_PropPengabdian->checkJudulExist($judul);
if ($if_exists > 0) {
echo json_encode('Judul sudah diajukan');
} else {
echo json_encode('Judul belum diajukan');
}
}
public function addformProposalTanpaMitra()
{
$this->form_validation->set_rules('judul','Judul Pengabdian', 'required');
$this->form_validation->set_rules('abstrak','Abstrak', 'required');
if($this->form_validation->run()==false){
redirect("dosen/pengabdian/pengisianformtanpamitra");
} else {
$prop_file = $_FILES['file_prop'];
if($prop_file=''){}else{
$config['upload_path'] = './assets/prop_pengabdian';
$config['allowed_types'] = 'pdf';
$config['encrypt_name'] = TRUE;
$this->load->library('upload',$config);
if(!$this->upload->do_upload('file_prop')){
echo "Upload Gagal"; die();
} else {
$prop_file=$this->upload->data('file_name');
}
}
$nip = $this->session->userdata('user_name');
$date = date('Y-m-d');
$bulan = $this->input->post('bulan',true);
$jadwal = $this->M_JadwalPengabdian->get_last_jadwal()->row()->id;
$biaya = str_replace('.','',$this->input->post('biaya',true));
$prop = [
"nip"=>$nip,
"judul"=>$this->input->post('judul',true),
"abstrak"=>$this->input->post('abstrak',true),
"tgl_upload"=>$date,
"id_jadwal" => $jadwal,
"lokasi"=>$this->input->post('lokasi',true),
"lama_pelaksanaan"=>$bulan,
"id_sumberdana"=>$this->input->post('sumberdana',true),
"biaya"=>$biaya,
"id_skema"=>$this->input->post('skema_pengabdian'),
"file" => $prop_file
];
$proposal=$this->M_PropPengabdian->insert_proposal($prop);
/**
* upload file proposal
*/
$nip= $this->input->post('dosen[]');
$data_dosen = array();
for($i=0; $i<count($nip)-1; $i++)
{
if($nip[$i]==""||$nip[$i]==null||$nip[$i]==0){
}
else{
$data_dosen[$i] = array(
'nip' => $nip[$i],
"id_proposal"=>$proposal,
);
}
}
$this->M_PropPengabdian->dosen($data_dosen);
$id_luaran= $this->input->post('luaran[]');
$data_luaran = array();
for($i=0; $i<count($id_luaran)-1; $i++)
{
if($id_luaran[$i]==""||$id_luaran[$i]==null||$id_luaran[$i]==0){
}
else{
$data_luaran[$i] = array(
'id_luaran' =>$id_luaran[$i],
"id_proposal"=>$proposal,
);
}
}
$this->M_PropPengabdian->luaran($data_luaran);
$nim= $this->input->post('nim_mahasiswa[]');
$nama_mhs = $this->input->post('nama_mahasiswa[]');
$data_mahasiswa = array();
for($i=0; $i<count($nim)-1; $i++)
{
if($nim[$i]==""||$nim[$i]==null||$nim[$i]==0){
}
else{
$data_mahasiswa[$i] = array(
'nim' => $nim[$i],
'nama' => $nama_mhs[$i],
"id_proposal"=>$proposal,
);
}}
$this->M_PropPengabdian->mahasiswa($data_mahasiswa);
$this->session->set_flashdata('pesan', '<p>Terimakasih Anda berhasil melakukan permohonan proposal <br> Proposal dapat dirubah selama jadwal pengumpulan belum berakhir <br> Pastikan Anda telah mengecek kembali proposal Anda sebelum jadwal pengumpulan berakhir </p>');
$this->session->set_flashdata('button', 'dosen/pengabdian/submitpermohonan');
redirect("dosen/pengabdian/success");
}
}
public function addformProposal()
{
$this->form_validation->set_rules('judul','Judul Pengabdian', 'required');
$this->form_validation->set_rules('abstrak','Abstrak', 'required');
$this->form_validation->set_rules('instansi','Nama Instansi', 'required');
$this->form_validation->set_rules('username','Username', 'required');
$this->form_validation->set_rules('password','Password', 'required');
if($this->form_validation->run()==false){
redirect("dosen/pengabdian/pengisianform");
} else {
$prop_file = $_FILES['file_prop'];
if($prop_file=''){}else{
$config['upload_path'] = './assets/prop_pengabdian';
$config['allowed_types'] = 'pdf';
$config['encrypt_name'] = TRUE;
$this->load->library('upload',$config);
if(!$this->upload->do_upload('file_prop')){
echo "Upload Gagal"; die();
} else {
$prop_file=$this->upload->data('file_name');
}
}
$nip = $this->session->userdata('user_name');
$data = [
"nama_instansi"=> $this->input->post('instansi',true),
"penanggung_jwb"=>$this->input->post('pj',true),
"no_telp"=> $this->input->post('no_telp',true),
"alamat"=>$this->input->post('alamat',true),
"email"=>$this->input->post('email',true),
"username"=>$this->input->post('username',true),
"status"=>"0"
];
$data_check = [
"nama_instansi"=> $this->input->post('instansi',true),
"username"=>$this->input->post('username',true),
"status"=>"0"
];
$checkMitra = $this->M_Mitra->getwhere_mitra($data_check);
if($checkMitra->num_rows() > 0){
$mitra = $checkMitra->row()->id;
} else{
$mitra=$this->M_Mitra->insert_mitra($data);
}
$date = date('Y-m-d');
$bulan = $this->input->post('bulan',true);
$jadwal = $this->M_JadwalPengabdian->get_last_jadwal()->row()->id;
$biaya = str_replace('.','',$this->input->post('biaya',true));
$prop = [
"id_mitra"=>$mitra,
"nip"=>$nip,
"judul"=>$this->input->post('judul',true),
"abstrak"=>$this->input->post('abstrak',true),
"tgl_upload"=>$date,
"id_jadwal" => $jadwal,
"lokasi"=>$this->input->post('lokasi',true),
"lama_pelaksanaan"=>$bulan,
"id_sumberdana"=>$this->input->post('sumberdana',true),
"biaya"=>$biaya,
"id_skema"=>$this->input->post('skema_pengabdian')
];
$proposal=$this->M_PropPengabdian->insert_proposal($prop);
/**
* upload file proposal
*/
$data_file = array('file'=>$prop_file);
$this->M_PropPengabdian->update_prop($proposal,$data_file);
$nip= $this->input->post('dosen[]');
$data_dosen = array();
for($i=0; $i<count($nip)-1; $i++)
{
if($nip[$i]==""||$nip[$i]==null||$nip[$i]==0){
}
else{
$data_dosen[$i] = array(
'nip' => $nip[$i],
"id_proposal"=>$proposal,
);
}
}
$this->M_PropPengabdian->dosen($data_dosen);
$id_luaran= $this->input->post('luaran[]');
$data_luaran = array();
for($i=0; $i<count($id_luaran)-1; $i++)
{
if($id_luaran[$i]==""||$id_luaran[$i]==null||$id_luaran[$i]==0){
}
else{
$data_luaran[$i] = array(
'id_luaran' =>$id_luaran[$i],
"id_proposal"=>$proposal,
);
}
}
$this->M_PropPengabdian->luaran($data_luaran);
$nim= $this->input->post('nim_mahasiswa[]');
$nama_mhs = $this->input->post('nama_mahasiswa[]');
$data_mahasiswa = array();
for($i=0; $i<count($nim)-1; $i++)
{
$data_mahasiswa[$i] = array(
'nim' => $nim[$i],
'nama' => $nama_mhs[$i],
"id_proposal"=>$proposal,
);
}
$this->M_PropPengabdian->mahasiswa($data_mahasiswa);
$role_mitra='4';
$password= md5($this->input->post('password',true));
$user_mitra = [
"username"=>$this->input->post('username',true),
"password"=>$password,
"role"=>$role_mitra
];
$this->M_User->insert_user($user_mitra);
$this->session->set_flashdata('pesan', '<p>Terimakasih Anda berhasil melakukan permohonan proposal <br> Proposal dapat diedit selama Anda belum melakukan "Submit" di menu selanjutnya<br> Pastikan Anda telah mengecek kembali proposal Anda sebelum melakukan finalisasi <br> Proposal akan otomatis terfinalisasi apabila batas pengumpulan telah berakhir</p>');
$this->session->set_flashdata('button', 'dosen/pengabdian/submitpermohonan');
redirect("dosen/pengabdian/success");
}
}
public function success(){
$this->load->view("pengabdian/header");
$this->load->view("dosen/success");
$this->load->view("pengabdian/footer");
}
public function PengisianForm()
{
$data['sumberdana']= $this->M_SumberDana->get_sumberdana()->result();
$nip = $this->session->userdata('user_name');
$data['dosen']= $this->M_Dosen->get_dosen()->result();
$data['mahasiswa']= $this->M_Mahasiswa->get_mahasiswa()->result();
$data['skema'] = $this->M_SkemaPengabdian->get_skemapengabdian()->result();
$data['luaran']= $this->M_Luaran->get_luaran_pengabdian()->result();
$data['jadwal'] = $this->M_JadwalPengabdian->get_last_jadwal()->row();
$now = date('Y-m-d', strtotime(date('Y-m-d')));
$awal = date('Y-m-d', strtotime($data['jadwal']->tgl_mulai));
$akhir = date('Y-m-d', strtotime($data['jadwal']->tgl_selesai));
$nama['cek']= $this->M_Profile->cekRevPengabdian(array('nip'=>$nip))->result();
$nama['hitungovr'] = $this->M_Publikasi_Pribadi->hitungovrview();
$this->load->view('pengabdian/header',$nama);
if(($now >= $awal) && ($now<=$akhir)){
$this->load->view('dosen/form_permohonan_pengabdian_mitra',$data);
} else {
$this->load->view('dosen/closed_form', $data);
}
$this->load->view('pengabdian/footer');
}
public function formTambahMitra($id)
{
$data['prop'] = $this->M_PropPengabdian->getwhere_proposal(array('id'=>$id))->row();
$id_mitra = $data['prop']->id_mitra;
$nip = $data['prop']->nip;
$data['dosen'] = $this->M_Dosen->getwhere_dosen(array('nip'=>$nip))->row();
$nip = $this->session->userdata('user_name');
$nama['cek']= $this->M_Profile->cekRevPengabdian(array('nip'=>$nip))->result();
$nama['hitungovr'] = $this->M_Publikasi_Pribadi->hitungovrview();
$this->load->view('pengabdian/header',$nama);
$this->load->view('dosen/form_tambah_mitra',$data);
$this->load->view('pengabdian/footer');
}
public function addFormMitra()
{
$data = [
"nama_instansi"=> $this->input->post('instansi',true),
"penanggung_jwb"=>$this->input->post('pj',true),
"no_telp"=> $this->input->post('no_telp',true),
"alamat"=>$this->input->post('alamat',true),
"email"=>$this->input->post('email',true),
"username"=>$this->input->post('username',true),
"status"=>"0"
];
$data_check = [
"nama_instansi"=> $this->input->post('instansi',true),
"username"=>$this->input->post('username',true),
"status"=>"0"
];
$checkMitra = $this->M_Mitra->getwhere_mitra($data_check);
if($checkMitra->num_rows() > 0){
$mitra = $checkMitra->row()->id;
} else{
$mitra=$this->M_Mitra->insert_mitra($data);
}
$id_prop = $this->input->post('id');
$data_prop = [
'id_mitra' => $mitra,
];
$role_mitra='4';
$password= md5($this->input->post('password',true));
$user_mitra = [
"username"=>$this->input->post('username',true),
"password"=>$password,
"role"=>$role_mitra
];
$this->M_User->insert_user($user_mitra);
$this->M_PropPengabdian->update_prop($id_prop,$data_prop);
$this->session->set_flashdata('pesan', '<p>Terimakasih Anda berhasil melakukan penambahan mitra <br> Detail mitra dapat diedit selama Mitra belum menyetujui kerjasama<br> Pastikan Anda telah mengecek kembali detail mitra pengabdian Anda<br></p>');
$this->session->set_flashdata('button', 'dosen/pengabdian/submitpermohonan');
redirect("dosen/pengabdian/success");
}
public function PengisianFormTanpaMitra()
{
$data['sumberdana']= $this->M_SumberDana->get_sumberdana()->result();
$nip = $this->session->userdata('user_name');
$data['dosen']= $this->M_Dosen->get_dosen()->result();
$data['mahasiswa']= $this->M_Mahasiswa->get_mahasiswa()->result();
$data['skema'] = $this->M_SkemaPengabdian->get_skemapengabdian()->result();
$data['luaran']= $this->M_Luaran->get_luaran_pengabdian()->result();
$data['jadwal'] = $this->M_JadwalPengabdian->get_last_jadwal()->row();
$now = date('Y-m-d', strtotime(date('Y-m-d')));
$awal = date('Y-m-d', strtotime($data['jadwal']->tgl_mulai));
$akhir = date('Y-m-d', strtotime($data['jadwal']->tgl_selesai));
$nama['cek']= $this->M_Profile->cekRevPengabdian(array('nip'=>$nip))->result();
$nama['hitungovr'] = $this->M_Publikasi_Pribadi->hitungovrview();
$this->load->view('pengabdian/header',$nama);
if(($now >= $awal) && ($now<=$akhir)){
$this->load->view('dosen/form_permohonan_pengabdian',$data);
} else {
$this->load->view('dosen/closed_form', $data);
}
$this->load->view('pengabdian/footer');
}
public function UploadSuratMitra()
{
$nip = $this->session->userdata('user_name');
$data['view']= $this->M_PropPengabdian->get_viewpengajuan($nip)->result();
$nama['cek']= $this->M_Profile->cekRevPengabdian(array('nip'=>$nip))->result();
$nama['hitungovr'] = $this->M_Publikasi_Pribadi->hitungovrview();
$this->load->view('pengabdian/header',$nama);
$this->load->view('dosen/upload_surat_mitra',$data);
$this->load->view('pengabdian/footer');
}
public function hapusProposal($id)
{
$data = array('id' => $id);
$mitra_id = $this->M_PropPengabdian->getwhere_proposal($data)->row();
$data_mitra = array('id' => $mitra_id->id_mitra);
$mitra = $this->M_Mitra->getwhere_mitra($data_mitra)->row();
$data_user = array(
'username' => $mitra->username
);
$this->M_User->delete_user($data_user);
$data_foreign = array('id_proposal'=>$id);
$this->M_Mitra->delete_mitra($data_mitra);
$this->M_PropPengabdian->delete_proposal($data);
$this->M_Dosen->delete_dosenpengabdian($data_foreign);
$this->M_Mahasiswa->delete_mahasiswapengabdian($data_foreign);
redirect('dosen/pengabdian/submitpermohonan');
}
public function hapusProposalTanpaMitra($id)
{
$data = array('id' => $id);
$data_foreign = array('id_proposal'=>$id);
$this->M_PropPengabdian->delete_proposal($data);
$this->M_Dosen->delete_dosenpengabdian($data_foreign);
$this->M_Mahasiswa->delete_mahasiswapengabdian($data_foreign);
$this->M_Luaran->delete_luaranpengabdian($data);
redirect('dosen/pengabdian/submitpermohonan');
}
public function SubmitPermohonan()
{
$nip = $this->session->userdata('user_name');
$username = $this->session->userdata('user_name');
$data['view']= $this->M_PropPengabdian->get_viewpengajuan($username)->result();
$data['anggota']= $this->M_PropPengabdian->get_viewanggota($username)->result();
$data['sumberdana']= $this->M_SumberDana->get_sumberdana()->result();
$data['dosen']= $this->M_Dosen->get_dosen()->result();
$data['mahasiswa']= $this->M_Mahasiswa->get_mahasiswa()->result();
// $data = array(
// 'sumberdana' => $this->M_SumberDana->get_sumberdana(),
// 'sumberdana_selected' => '',
// );
$nama['cek']= $this->M_Profile->cekRevPengabdian(array('nip'=>$nip))->result();
$nama['hitungovr'] = $this->M_Publikasi_Pribadi->hitungovrview();
$this->load->view('pengabdian/header',$nama);
$this->load->view('dosen/formpengabdian', $data);
$this->load->view('pengabdian/footer');
}
public function mitra()
{
$nip = $this->session->userdata('user_name');
$username = $this->session->userdata('user_name');
$data['view']= $this->M_PropPengabdian->get_viewpengajuan($username)->result();
$data['anggota']= $this->M_PropPengabdian->get_viewanggota($username)->result();
$data['sumberdana']= $this->M_SumberDana->get_sumberdana()->result();
$data['dosen']= $this->M_Dosen->get_dosen()->result();
$data['mahasiswa']= $this->M_Mahasiswa->get_mahasiswa()->result();
// $data = array(
// 'sumberdana' => $this->M_SumberDana->get_sumberdana(),
// 'sumberdana_selected' => '',
// );
$nama['cek']= $this->M_Profile->cekRevPengabdian(array('nip'=>$nip))->result();
$nama['hitungovr'] = $this->M_Publikasi_Pribadi->hitungovrview();
$this->load->view('pengabdian/header',$nama);
$this->load->view('dosen/penambahanmitra', $data);
$this->load->view('pengabdian/footer');
}
public function updateSurat()
{
$surat = $_FILES['file_persetujuan'];
if(!empty($surat['name'])){
$config['upload_path'] = './assets/suratmitra';
$config['allowed_types'] = 'pdf';
$config['encrypt_name'] = TRUE;
$this->load->library('upload',$config);
if(!$this->upload->do_upload('file_persetujuan')){
echo "Upload Gagal"; die();
} else {
$surat=$this->upload->data('file_name');
}
}
$id = $this->input->post('id');
$data = array('file_persetujuan'=>$surat);
$this->M_Mitra->update_mitra($id,$data);
redirect('dosen/pengabdian/submitpermohonan');
}
public function uploadLaporanAkhir()
{
$surat = $_FILES['laporan_akhir'];
if($surat=''){}else{
$config['upload_path'] = './assets/laporan_akhir';
$config['allowed_types'] = 'pdf';
$config['encrypt_name'] = TRUE;
$this->load->library('upload',$config);
if(!$this->upload->do_upload('laporan_akhir')){
echo "Upload Gagal"; die();
} else {
$surat=$this->upload->data('file_name');
}
}
$id = $this->input->post('id');
$data = array('laporan_akhir'=>$surat);
$this->M_LaporanAkhirPengabdian->update_laporan($id,$data);
redirect('dosen/pengabdian/laporanakhir');
}
public function uploadLogbook()
{
$surat = $_FILES['logbook'];
if($surat=''){}else{
$config['upload_path'] = './assets/logbook';
$config['allowed_types'] = 'pdf';
$config['encrypt_name'] = TRUE;
$this->load->library('upload',$config);
if(!$this->upload->do_upload('logbook')){
echo "Upload Gagal"; die();
} else {
$surat=$this->upload->data('file_name');
}
}
$id = $this->input->post('id');
$data = array('logbook'=>$surat);
$this->M_LaporanAkhirPengabdian->update_laporan($id,$data);
redirect('dosen/pengabdian/laporanakhir');
}
public function uploadBelanja()
{
$surat = $_FILES['belanja'];
if($surat=''){}else{
$config['upload_path'] = './assets/belanja';
$config['allowed_types'] = 'pdf';
$config['encrypt_name'] = TRUE;
$this->load->library('upload',$config);
if(!$this->upload->do_upload('belanja')){
echo "Upload Gagal"; die();
} else {
$surat=$this->upload->data('file_name');
}
}
$id = $this->input->post('id');
$data = array('belanja'=>$surat);
$this->M_LaporanAkhirPengabdian->update_laporan($id,$data);
redirect('dosen/pengabdian/laporanakhir');
}
public function uploadLuaran()
{
$surat = $_FILES['luaran'];
if($surat=''){}else{
$config['upload_path'] = './assets/luaran';
$config['allowed_types'] = 'pdf';
$config['encrypt_name'] = TRUE;
$this->load->library('upload',$config);
if(!$this->upload->do_upload('luaran')){
echo "Upload Gagal"; die();
} else {
$surat=$this->upload->data('file_name');
}
}
$id = $this->input->post('id');
$data = array('luaran'=>$surat);
$this->M_LaporanAkhirPengabdian->update_laporan($id,$data);
redirect('dosen/pengabdian/laporanakhir');
}
public function editMitra($id){
$data['prop'] = $this->M_PropPengabdian->getwhere_proposal(array('id'=>$id))->row();
$id_mitra = $data['prop']->id_mitra;
$nip = $data['prop']->nip;
$data['dosen'] = $this->M_Dosen->getwhere_dosen(array('nip'=>$nip))->row();
$id_mitra = $data['prop']->id_mitra;
$data['luaran']= $this->M_Luaran->get_luaran_pengabdian()->result();
$data['mitra'] = $this->M_Mitra->getwhere_mitra(array('id'=>$id_mitra))->row();
$nip = $this->session->userdata('user_name');
$nama['cek']= $this->M_Profile->cekRevPengabdian(array('nip'=>$nip))->result();
$nama['hitungovr'] = $this->M_Publikasi_Pribadi->hitungovrview();
$this->load->view('pengabdian/header',$nama);
$this->load->view('dosen/edit_mitra',$data);
$this->load->view('pengabdian/footer');
}
public function editProposal($id){
$data['sumberdana']= $this->M_SumberDana->get_sumberdana()->result();
$data['proposal'] = $this->M_PropPengabdian->getwhere_proposal(array('id'=>$id))->row();
$id_mitra = $data['proposal']->id_mitra;
$data['dosen']= $this->M_Dosen->get_dosen()->result();
$data['luaran']= $this->M_Luaran->get_luaran_pengabdian()->result();
$data['mahasiswa']= $this->M_Mahasiswa->get_mahasiswa()->result();
$data['skema'] = $this->M_SkemaPengabdian->get_skemapengabdian()->result();
$data['anggota_dosen'] = $this->M_PropPengabdian->dosen_update_prop($id)->result();
$data['anggota_mhs'] = $this->M_PropPengabdian->mhs_update_prop($id)->result();
$data['nilai_luaran'] = $this->M_PropPengabdian->luaran_update_prop($id)->result();
$data['mitra'] = $this->M_Mitra->getwhere_mitra(array('id'=>$id_mitra))->row();
$nip = $this->session->userdata('user_name');
$nama['cek']= $this->M_Profile->cekRevPengabdian(array('nip'=>$nip))->result();
$nama['hitungovr'] = $this->M_Publikasi_Pribadi->hitungovrview();
$this->load->view('pengabdian/header',$nama);
$this->load->view('dosen/upproppengabdian_mitra',$data);
$this->load->view('pengabdian/footer');
}
public function editProposalTanpaMitra($id){
$data['sumberdana']= $this->M_SumberDana->get_sumberdana()->result();
$data['proposal'] = $this->M_PropPengabdian->getwhere_proposal(array('id'=>$id))->row();
$data['dosen']= $this->M_Dosen->get_dosen()->result();
$data['luaran']= $this->M_Luaran->get_luaran_pengabdian()->result();
$data['mahasiswa']= $this->M_Mahasiswa->get_mahasiswa()->result();
$data['skema'] = $this->M_SkemaPengabdian->get_skemapengabdian()->result();
$data['anggota_dosen'] = $this->M_PropPengabdian->dosen_update_prop($id)->result();
$data['anggota_mhs'] = $this->M_PropPengabdian->mhs_update_prop($id)->result();
$data['nilai_luaran'] = $this->M_PropPengabdian->luaran_update_prop($id)->result();
$nip = $this->session->userdata('user_name');
$nama['cek']= $this->M_Profile->cekRevPengabdian(array('nip'=>$nip))->result();
$nama['hitungovr'] = $this->M_Publikasi_Pribadi->hitungovrview();
$this->load->view('pengabdian/header',$nama);
$this->load->view('dosen/upproppengabdian',$data);
$this->load->view('pengabdian/footer');
}
public function updateProposalTanpaMitra(){
$this->form_validation->set_rules('judul','Judul Pengabdian', 'required');
$this->form_validation->set_rules('abstrak','Abstrak', 'required');
if($this->form_validation->run()==false){
redirect("dosen/pengabdian/editproposaltanpamitra/".$this->input->post('id'));
} else {
$id = $this->input->post('id');
$nip = $this->session->userdata('user_name');
$data_proposal = $this->M_PropPengabdian->getwhere_proposal(array('id'=> $id))->row();
$date = date('Y-m-d');
$old_username_mitra = $this->M_Mitra->getwhere_mitra(array('id'=>$data_proposal->id_mitra))->row()->username;
$biaya = str_replace('.','',$this->input->post('biaya',true));
$prop = array (
"judul"=>$this->input->post('judul',true),
"abstrak"=>$this->input->post('abstrak',true),
"tgl_upload"=>$date,
"lokasi"=>$this->input->post('lokasi',true),
"biaya"=>$biaya,
);
$proposal=$this->M_PropPengabdian->update_prop($id,$prop);
/**
* upload file proposal
*/
$prop_file = $_FILES['file_prop'];
if(!empty($prop_file['name'])){
$config['upload_path'] = './assets/prop_pengabdian';
$config['allowed_types'] = 'pdf';
$config['encrypt_name'] = TRUE;
$this->load->library('upload',$config);
if(!$this->upload->do_upload('file_prop')){
echo "Upload Gagal"; die();
} else {
$prop_file=$this->upload->data('file_name');
}
$data_file = array('file'=>$prop_file);
$this->M_PropPengabdian->update_prop($id,$data_file);
}
/* update anggota dosen */
$dsn_update = $this->input->post('dosen[]');
$id_dsn_anggota = $this->input->post('id_dsn_anggota[]');
$dsn_new = $this->input->post('dosen_new[]');
$data_dsn_anggota = $this->M_PropPengabdian->dosen_update_prop($id)->result();
$luaran_update = $this->input->post('luaran[]');
$id_nilai_luaran = $this->input->post('id_nilai_luaran[]');
$luaran_new = $this->input->post('luaran_new[]');
$data_nilai_luaran = $this->M_PropPengabdian->luaran_update_prop($id)->result();
// print_r($dsn_update);
if(!empty($dsn_update)){
foreach($data_dsn_anggota as $k){
for($i=0;$i<count($dsn_update);$i++){
if($k->id == $id_dsn_anggota[$i]){
$dsn=$dsn_update[$i];
$data_dosen =[
'nip' => $dsn,
];
$this->M_PropPengabdian->update_dosen_anggota($data_dosen, $id_dsn_anggota[$i]);
continue 2;
}
}
$this->M_PropPengabdian->hapus_dosen_anggota(array('id'=>$k->id));
}
if(!empty($dsn_new)){
for($j=0; $j<count($dsn_new)-1;$j++)
{
if($dsn_new[$j]==""||$dsn_new[$j]==null){
}
else{
$dosen_new=$dsn_new[$j];
$data_dosen_new =[
'nip' => $dosen_new,
'id_proposal' => $id
];
$this->M_PropPengabdian->insert_dsn_anggota($data_dosen_new);
}
}
}
}
if(!empty($luaran_update)){
foreach($data_nilai_luaran as $k){
for($i=0;$i<count($luaran_update);$i++){
if($k->id == $id_nilai_luaran[$i]){
$luaran=$luaran_update[$i];
$data_luaran =[
'id_luaran' => $luaran,
];
$this->M_PropPengabdian->update_nilai_luaran($data_luaran, $id_nilai_luaran[$i]);
continue 2;
}
}
$this->M_PropPengabdian->hapus_nilai_luaran(array('id'=>$k->id));
}
if(!empty($luaran_new)){
for($j=0; $j<count($luaran_new)-1;$j++)
{
if($luaran_new[$j]==""||$luaran_new[$j]==null||$luaran_new[$j]==0){
}
else{
$l_new=$luaran_new[$j];
$data_luaran_new =[
'id_luaran' => $l_new,
'id_proposal' => $id
];
$this->M_PropPengabdian->insert_nilai_luaran($data_luaran_new);
}
}
}
}
if(empty($dsn_update)){
$this->M_PropPengabdian->hapus_dosen_anggota(array('id_proposal'=>$id));
for($j=0; $j<count($dsn_new)-1;$j++)
{
if($dsn_new[$j]==""||$dsn_new[$j]==null||$dsn_new[$j]==0){
}
else{
$dosen_new=$dsn_new[$j];
$data_dosen_new =[
'nip' => $dosen_new,
'id_proposal' => $id
];
$this->M_PropPengabdian->insert_dsn_anggota($data_dosen_new);
}
}
}
if(empty($luaran_update)){
$this->M_PropPengabdian->hapus_nilai_luaran(array('id_proposal'=>$id));
for($j=0; $j<count($luaran_new)-1;$j++)
{
if($luaran_new[$j]==""||$luaran_new[$j]==null||$luaran_new[$j]==0){
}
else{
$l_new=$luaran_new[$j];
$data_luaran_new =[
'id_luaran' => $l_new,
'id_proposal' => $id
];
$this->M_PropPengabdian->insert_nilai_luaran($data_luaran_new);
}
}
}
/* update anggota mahasiswa */
$mhs_update = $this->input->post('nim_mahasiswa[]');
$mhs_nama_update = $this->input->post('nama_mahasiswa[]');
$id_mhs_anggota = $this->input->post('id_mhs_anggota[]');
$mhs_new = $this->input->post('nim_mahasiswa_new[]');
$mhs_nama_new = $this->input->post('nama_mahasiswa_new[]');
$data_mhs_anggota = $this->M_PropPengabdian->mhs_update_prop($id)->result();
foreach($data_mhs_anggota as $k){
for($i=0;$i<count($mhs_update);$i++){
if($k->id == $id_mhs_anggota[$i]){
$mhs=$mhs_update[$i];
$data_mhs =[
'nim' => $mhs,
'nama'=> $mhs_nama_update[$i],
];
$this->M_PropPengabdian->update_mhs_anggota($data_mhs, $id_mhs_anggota[$i]);
continue 2;
}
}
$this->M_PropPengabdian->hapus_mhs_anggota(array('id'=>$k->id));
}
for($j=0; $j<count($mhs_new)-1;$j++)
{
$mahasiswa_new=$mhs_new[$j];
$data_mhs_new =[
'nim' => $mahasiswa_new,
'nama' => $mhs_nama_new[$j],
'id_proposal' => $id
];
$this->M_PropPengabdian->insert_mhs_anggota($data_mhs_new);
}
$this->session->set_flashdata('pesan', '<p>Terimakasih Anda berhasil melakukan perubahan proposal <br> Proposal dapat dirubah selama jadwal pengumpulan belum berakhir <br> Pastikan Anda telah mengecek kembali proposal Anda sebelum jadwal pengumpulan berakhir </p>');
$this->session->set_flashdata('button', 'dosen/pengabdian/submitpermohonan');
redirect("dosen/pengabdian/success");
}
}
public function updateProposal(){
$this->form_validation->set_rules('judul','Judul Pengabdian', 'required');
$this->form_validation->set_rules('abstrak','Abstrak', 'required');
if($this->form_validation->run()==false){
redirect("dosen/pengabdian/editproposal/".$this->input->post('id'));
} else {
$id = $this->input->post('id');
$nip = $this->session->userdata('user_name');
$data_proposal = $this->M_PropPengabdian->getwhere_proposal(array('id'=> $id))->row();
$date = date('Y-m-d');
$old_username_mitra = $this->M_Mitra->getwhere_mitra(array('id'=>$data_proposal->id_mitra))->row()->username;
$biaya = str_replace('.','',$this->input->post('biaya',true));
$prop = array (
"judul"=>$this->input->post('judul',true),
"abstrak"=>$this->input->post('abstrak',true),
"tgl_upload"=>$date,
"lokasi"=>$this->input->post('lokasi',true),
"biaya"=>$biaya,
);
$proposal=$this->M_PropPengabdian->update_prop($id,$prop);
/**
* upload file proposal
*/
$prop_file = $_FILES['file_prop'];
if(!empty($prop_file['name'])){
$config['upload_path'] = './assets/prop_pengabdian';
$config['allowed_types'] = 'pdf';
$config['encrypt_name'] = TRUE;
$this->load->library('upload',$config);
if(!$this->upload->do_upload('file_prop')){
echo "Upload Gagal"; die();
} else {
$prop_file=$this->upload->data('file_name');
}
$data_file = array('file'=>$prop_file);
$this->M_PropPengabdian->update_prop($id,$data_file);
}
/* update anggota dosen */
$dsn_update = $this->input->post('dosen[]');
$id_dsn_anggota = $this->input->post('id_dsn_anggota[]');
$dsn_new = $this->input->post('dosen_new[]');
$data_dsn_anggota = $this->M_PropPengabdian->dosen_update_prop($id)->result();
$luaran_update = $this->input->post('luaran[]');
$id_nilai_luaran = $this->input->post('id_nilai_luaran[]');
$luaran_new = $this->input->post('luaran_new[]');
$data_nilai_luaran = $this->M_PropPengabdian->luaran_update_prop($id)->result();
// print_r($dsn_update);
if(!empty($dsn_update)){
foreach($data_dsn_anggota as $k){
for($i=0;$i<count($dsn_update);$i++){
if($k->id == $id_dsn_anggota[$i]){
$dsn=$dsn_update[$i];
$data_dosen =[
'nip' => $dsn,
];
$this->M_PropPengabdian->update_dosen_anggota($data_dosen, $id_dsn_anggota[$i]);
continue 2;
}
}
$this->M_PropPengabdian->hapus_dosen_anggota(array('id'=>$k->id));
}
if(!empty($dsn_new)){
for($j=0; $j<count($dsn_new)-1;$j++)
{
if($dsn_new[$j]==""||$dsn_new[$j]==null||$dsn_new[$j]==0){
}
else{
$dosen_new=$dsn_new[$j];
$data_dosen_new =[
'nip' => $dosen_new,
'id_proposal' => $id
];
$this->M_PropPengabdian->insert_dsn_anggota($data_dosen_new);
}
}
}
}
if(!empty($luaran_update)){
foreach($data_nilai_luaran as $k){
for($i=0;$i<count($luaran_update);$i++){
if($k->id == $id_nilai_luaran[$i]){
$luaran=$luaran_update[$i];
$data_luaran =[
'id_luaran' => $luaran,
];
$this->M_PropPengabdian->update_nilai_luaran($data_luaran, $id_nilai_luaran[$i]);
continue 2;
}
}
$this->M_PropPengabdian->hapus_nilai_luaran(array('id'=>$k->id));
}
if(!empty($luaran_new)){
for($j=0; $j<count($luaran_new)-1;$j++)
{
if($luaran_new[$j]==""||$luaran_new[$j]==null||$luaran_new[$j]==0){
}
else{
$l_new=$luaran_new[$j];
$data_luaran_new =[
'id_luaran' => $l_new,
'id_proposal' => $id
];
$this->M_PropPengabdian->insert_nilai_luaran($data_luaran_new);
}
}
}
}
if(empty($dsn_update)){
$this->M_PropPengabdian->hapus_dosen_anggota(array('id_proposal'=>$id));
for($j=0; $j<count($dsn_new)-1;$j++)
{
if($dsn_new[$j]==""||$dsn_new[$j]==null||$dsn_new[$j]==0){
}
else{
$dosen_new=$dsn_new[$j];
$data_dosen_new =[
'nip' => $dosen_new,
'id_proposal' => $id
];
$this->M_PropPengabdian->insert_dsn_anggota($data_dosen_new);
}
}
}
if(empty($luaran_update)){
$this->M_PropPengabdian->hapus_nilai_luaran(array('id_proposal'=>$id));
for($j=0; $j<count($luaran_new)-1;$j++)
{
if($luaran_new[$j]==""||$luaran_new[$j]==null||$luaran_new[$j]==0){
}
else{
$l_new=$luaran_new[$j];
$data_luaran_new =[
'id_luaran' => $l_new,
'id_proposal' => $id
];
$this->M_PropPengabdian->insert_nilai_luaran($data_luaran_new);
}
}
}
/* update anggota mahasiswa */
$mhs_update = $this->input->post('nim_mahasiswa[]');
$mhs_nama_update = $this->input->post('nama_mahasiswa[]');
$id_mhs_anggota = $this->input->post('id_mhs_anggota[]');
$mhs_new = $this->input->post('nim_mahasiswa_new[]');
$mhs_nama_new = $this->input->post('nama_mahasiswa_new[]');
$data_mhs_anggota = $this->M_PropPengabdian->mhs_update_prop($id)->result();
foreach($data_mhs_anggota as $k){
for($i=0;$i<count($mhs_update);$i++){
if($k->id == $id_mhs_anggota[$i]){
$mhs=$mhs_update[$i];
$data_mhs =[
'nim' => $mhs,
'nama'=> $mhs_nama_update[$i],
];
$this->M_PropPengabdian->update_mhs_anggota($data_mhs, $id_mhs_anggota[$i]);
continue 2;
}
}
$this->M_PropPengabdian->hapus_mhs_anggota(array('id'=>$k->id));
}
for($j=0; $j<count($mhs_new)-1;$j++)
{
$mahasiswa_new=$mhs_new[$j];
$data_mhs_new =[
'nim' => $mahasiswa_new,
'nama' => $mhs_nama_new[$j],
'id_proposal' => $id
];
$this->M_PropPengabdian->insert_mhs_anggota($data_mhs_new);
}
/* edit mitra */
$id_mitra = $this->input->post('id_mitra');
$data_mitra = [
"nama_instansi"=> $this->input->post('instansi',true),
"penanggung_jwb"=>$this->input->post('pj',true),
"no_telp"=> $this->input->post('no_telp',true),
"alamat"=>$this->input->post('alamat',true),
"email"=>$this->input->post('email',true),
"username"=>$this->input->post('username',true),
];
$this->M_Mitra->update_mitra($id_mitra, $data_mitra);
$pass = $this->input->post('password');
$username_mitra = $this->input->post('username');
if($pass != null){
$if_exists = $this->M_User->checkUserexist($username_mitra);
if($if_exists>0){
$data_user_mitra = [
'username' =>$username_mitra,
'password' =>md5($pass)
];
$this->M_User->update_user($old_username_mitra, $data_user_mitra);
} else {
$data_user_mitra = [
"username"=>$username_mitra,
"password"=>md5($pass),
"role"=>4
];
$this->M_User->insert_user($data_user_mitra);
}
} else{
$data_user_mitra = [
'username' => $this->input->post('username')
];
$this->M_User->update_user($old_username_mitra, $data_user_mitra);
}
$this->session->set_flashdata('pesan', '<p>Terimakasih Anda berhasil melakukan perubahan proposal <br> Proposal dapat dirubah selama jadwal pengumpulan belum berakhir <br> Pastikan Anda telah mengecek kembali proposal Anda sebelum jadwal pengumpulan berakhir </p>');
$this->session->set_flashdata('button', 'dosen/pengabdian/submitpermohonan');
redirect("dosen/pengabdian/success");
}
}
public function finalSubmitProp($id){
$data = array('status'=>'SUBMITTED');
$this->M_PropPengabdian->update_prop($id,$data);
redirect('dosen/pengabdian/submitpermohonan');
}
public function DaftarPermohonan()
{
$nip = $this->session->userdata('user_name');
$data['view']= $this->M_PropPengabdian->get_viewpengajuan($nip)->result();
$nama['cek']= $this->M_Profile->cekRevPengabdian(array('nip'=>$nip))->result();
$nama['hitungovr'] = $this->M_Publikasi_Pribadi->hitungovrview();
$this->load->view('pengabdian/header',$nama);
$this->load->view('dosen/daftar_permohonan_pengabdian', $data);
$this->load->view('pengabdian/footer');
}
public function updateMitra()
{
$id = $this->input->post('id');
$data_proposal = $this->M_PropPengabdian->getwhere_proposal(array('id'=> $id))->row();
$old_username_mitra = $this->M_Mitra->getwhere_mitra(array('id'=>$data_proposal->id_mitra))->row()->username;
$id_mitra = $this->input->post('id_mitra');
$data_mitra = [
"nama_instansi"=> $this->input->post('instansi',true),
"penanggung_jwb"=>$this->input->post('pj',true),
"no_telp"=> $this->input->post('no_telp',true),
"alamat"=>$this->input->post('alamat',true),
"email"=>$this->input->post('email',true),
"username"=>$this->input->post('username',true),
];
$this->M_Mitra->update_mitra($id_mitra, $data_mitra);
$pass = $this->input->post('password');
$username_mitra = $this->input->post('username');
if($pass != null){
$data_user_mitra = [
'username' =>$username_mitra,
'password' =>md5($pass)
];
$this->M_User->update_user($old_username_mitra, $data_user_mitra);
} else{
$data_user_mitra = [
'username' => $this->input->post('username')
];
$this->M_User->update_user($old_username_mitra, $data_user_mitra);
}
$this->session->set_flashdata('pesan', '<p>Terimakasih Anda berhasil melakukan pengubahan data mitra <br> Data mitra dapat diedit selama mitra belum menyetujui kerjasama <br> Pastikan Anda telah mengecek kembali data mitra Anda<br></p>');
$this->session->set_flashdata('button', 'dosen/pengabdian/submitpermohonan');
redirect("dosen/pengabdian/success");
}
public function deleteMitra($id)
{
$data_proposal = $this->M_PropPengabdian->getwhere_proposal(array('id'=> $id))->row();
$id_mitra = $data_proposal->id_mitra;
$data = [
'id_mitra' => 0,
];
$this->M_PropPengabdian->update_prop($id, $data);
$this->M_Mitra->delete_mitra($id_mitra);
redirect('dosen/pengabdian/submitpermohonan');
}
public function luaran(){
$id = $this->input->post('id');
$data['proposal'] = $this->M_PropPengabdian->getwhere_proposal(array('id'=>$id))->row();
if($id==NULL){
redirect("dosen/pengabdian/laporanAkhir");
}
$nip = $this->session->userdata('user_name');
$data['luaran'] = $this->M_PropPengabdian->get_luaran(array('id_proposal'=>$id))->result();
$nama['nama']= $this->M_Profile->getwhere_profile(array('nip'=>$nip))->result();
$nama['cek']= $this->M_Profile->cekRevPenelitian(array('nip'=>$nip))->result();
$nama['hitungovr'] = $this->M_Publikasi_Pribadi->hitungovrview();
$this->load->view('pengabdian/header', $nama);
$this->load->view('dosen/uploadluaran',$data);
$this->load->view("pengabdian/footer");
}
public function upLuaran(){
$id=$this->input->post('id');
$cekLuaran = $this->M_PropPengabdian->get_luaran(array('id_proposal'=>$id))->result();
$nip = $this->session->userdata('user_name');
for($i=0, $count = count($cekLuaran);$i<$count;$i++) {
$id_luaran = $this->input->post("id_luaran$i");
$jenis_luaran = $this->input->post("jenis$i");
$judul = $this->input->post("judul$i");
$nama = $this->input->post("nama$i");
$author = $this->input->post("author$i");
$tahun = $this->input->post("tahun$i");
$link = $this->input->post("link$i");
$file_luaran = $_FILES["file_luaran$i"];
if(empty($file_luaran['name'])){
$datafile = [
"pengusul"=>$nip,
"judul"=>$judul,
"jenis_luaran"=>$jenis_luaran,
"nama"=>$nama,
"author"=>$author,
"tahun"=>$tahun,
"link"=>$link,];
$proposal=$this->M_PropPengabdian->update_luaran($datafile,$id,$id_luaran);
}
else{
$config['upload_path'] = './assets/luaran';
$config['allowed_types'] = 'pdf';
$config['encrypt_name'] = TRUE;
$this->load->library('upload',$config);
if(!$this->upload->do_upload("file_luaran$i")){
echo "Upload Gagal"; die();
} else {
$file_luaran=$this->upload->data('file_name');
}
$datafile = [
"pengusul"=>$nip,
"judul"=>$judul,
"jenis_luaran"=>$jenis_luaran,
"nama"=>$nama,
"author"=>$author,
"tahun"=>$tahun,
"link"=>$link,
"file"=>$file_luaran,];
$this->M_PropPengabdian->update_luaran($datafile,$id,$id_luaran);
}
};
$data = [
"luaran"=>"done",
];
$this->M_LaporanAkhirPengabdian->update_laporan($id,$data);
$this->session->set_flashdata('pesan', '<p>Terimakasih Anda berhasil melakukan pengumpulan luaran laporan akhir <br> Laporan akhir dapat dirubah selama jadwal pengumpulan belum berakhir <br> Pastikan Anda telah mengecek kembali laporan akhir Anda sebelum jadwal pengumpulan berakhir </p>');
$this->session->set_flashdata('button', 'dosen/pengabdian/laporanAkhir');
redirect("dosen/pengabdian/success");
}
public function laporanAkhir()
{
$id = $this->input->post('id');
$data['view']= $this->M_PropPengabdian->get_viewlaporanakhir()->result();
$nip = $this->session->userdata('user_name');
$nama['cek']= $this->M_Profile->cekRevPengabdian(array('nip'=>$nip))->result();
$data['luaran'] = $this->M_PropPengabdian->get_luaran(array('id_proposal'=>$id))->result();
$nama['hitungovr'] = $this->M_Publikasi_Pribadi->hitungovrview();
$this->load->view('pengabdian/header',$nama);
$cekjad=$data['jadwal'] = $this->M_JadwalPengabdian->get_last_jadwal()->row();
if (empty($cekjad)){
$this->load->view('dosen/closed_form_akhir', $data);
}
else{
$now = date('Y-m-d', strtotime(date('Y-m-d')));
$awal = date('Y-m-d', strtotime($data['jadwal']->tgl_mulai));
$akhir = date('Y-m-d', strtotime($data['jadwal']->tgl_akhir));
if(($now>= $awal) && ($now<=$akhir)){
$this->load->view('dosen/laporan_akhir_pengabdian', $data);
}
else {
$this->load->view('dosen/closed_form_akhir', $data);
}
}
$this->load->view('pengabdian/footer');
}
public function logout()
{
$this->session->sess_destroy();
redirect('login');
}
}
| 42.3613
| 364
| 0.507316
|
dab8dd1066851f4cc35f829b19b68d36a6013ecf
| 144
|
ts
|
TypeScript
|
src/Todo/create-todo.dto.ts
|
eudesenv/todo-app
|
e2cb9b5780e8d0cc8d31d128c06a87ce070232b4
|
[
"MIT"
] | null | null | null |
src/Todo/create-todo.dto.ts
|
eudesenv/todo-app
|
e2cb9b5780e8d0cc8d31d128c06a87ce070232b4
|
[
"MIT"
] | null | null | null |
src/Todo/create-todo.dto.ts
|
eudesenv/todo-app
|
e2cb9b5780e8d0cc8d31d128c06a87ce070232b4
|
[
"MIT"
] | null | null | null |
export class Todo {
constructor(
public id: string,
public todoTitle: string,
public todoDescription: string,
) {}
}
| 20.571429
| 37
| 0.611111
|
4b6c9e2d2865f26739898f527eb513ebf0d5a6ee
| 4,681
|
cpp
|
C++
|
core/jitk/codegen_util.cpp
|
bh107/bohrium
|
5b83e7117285fefc7779ed0e9acb0f8e74c7e068
|
[
"Apache-2.0"
] | 236
|
2015-03-31T15:39:30.000Z
|
2022-03-24T01:43:14.000Z
|
core/jitk/codegen_util.cpp
|
bh107/bohrium
|
5b83e7117285fefc7779ed0e9acb0f8e74c7e068
|
[
"Apache-2.0"
] | 324
|
2015-05-27T10:35:38.000Z
|
2021-12-10T07:34:10.000Z
|
core/jitk/codegen_util.cpp
|
bh107/bohrium
|
5b83e7117285fefc7779ed0e9acb0f8e74c7e068
|
[
"Apache-2.0"
] | 41
|
2015-05-26T12:38:42.000Z
|
2022-01-10T15:16:37.000Z
|
/*
This file is part of Bohrium and copyright (c) 2012 the Bohrium
team <http://www.bh107.org>.
Bohrium is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as
published by the Free Software Foundation, either version 3
of the License, or (at your option) any later version.
Bohrium is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the
GNU Lesser General Public License along with Bohrium.
If not, see <http://www.gnu.org/licenses/>.
*/
#include <limits>
#include <iomanip>
#include <thread> // std::this_thread::sleep_for
#include <chrono> // std::chrono::seconds
#include <unistd.h>
#include <sstream>
#include <boost/filesystem/operations.hpp>
#include <bohrium/jitk/codegen_util.hpp>
#include <bohrium/jitk/view.hpp>
#include <bohrium/jitk/instruction.hpp>
using namespace std;
namespace bohrium {
namespace jitk {
string hash_filename(uint64_t compilation_hash, size_t source_hash, string extension) {
stringstream ss;
ss << setfill ('0') << setw(sizeof(size_t)*2) << hex << compilation_hash << "_"<< source_hash << extension;
return ss.str();
}
boost::filesystem::path write_source2file(const std::string &src,
const boost::filesystem::path &dir,
const std::string &filename,
bool verbose) {
boost::filesystem::path srcfile = dir;
srcfile /= filename;
ofstream ofs(srcfile.string());
ofs << src;
ofs.flush();
ofs.close();
if (verbose) {
cout << "Write source " << srcfile << endl;
}
return srcfile;
}
boost::filesystem::path get_tmp_path(const ConfigParser &config) {
boost::filesystem::path tmp_path, unique_path;
const boost::filesystem::path tmp_dir = config.defaultGet<boost::filesystem::path>("tmp_dir", "NONE");
if (tmp_dir.empty()) {
tmp_path = boost::filesystem::temp_directory_path();
} else {
tmp_path = boost::filesystem::path(tmp_dir);
}
// We add the process id to the unique template
stringstream unique_template;
unique_template << "bh_" << std::hex << getpid() << "_%%%%%";
// On some systems `boost::filesystem::unique_path()` throws a runtime error
// when `LC_ALL` is undefined (or invalid). In this case, we set `LC_ALL=C` and try again.
try {
unique_path = boost::filesystem::unique_path(unique_template.str());
} catch(std::runtime_error &e) {
setenv("LC_ALL", "C", 1); // Force C locale
unique_path = boost::filesystem::unique_path(unique_template.str());
}
return tmp_path / unique_path;
}
void create_directories(const boost::filesystem::path &path) {
constexpr int tries = 5;
for (int i = 1; i <= tries; ++i) {
try {
boost::filesystem::create_directories(path);
return;
} catch (boost::filesystem::filesystem_error &e) {
if (i == tries) {
throw;
}
this_thread::sleep_for(chrono::seconds(3));
cerr << e.what() << endl;
cout << "Warning: " << e.what() << " (" << i << " attempt)" << endl;
}
}
}
std::vector<InstrPtr> order_sweep_set(const std::set<InstrPtr> &sweep_set, const SymbolTable &symbols) {
vector<InstrPtr> ret;
ret.reserve(sweep_set.size());
std::copy(sweep_set.begin(), sweep_set.end(), std::back_inserter(ret));
std::sort(ret.begin(), ret.end(),
[symbols](const InstrPtr & a, const InstrPtr & b) -> bool
{
return symbols.viewID(a->operand[0]) > symbols.viewID(b->operand[0]);
});
return ret;
}
bool row_major_access(const bh_view &view) {
if(not view.isConstant()) {
assert(view.ndim > 0);
for(int64_t i = 1; i < view.ndim; ++ i) {
if (view.stride[i] > view.stride[i-1]) {
return false;
}
}
}
return true;
}
bool row_major_access(const bh_instruction &instr) {
for (const bh_view &view: instr.operand) {
if (not row_major_access(view)) {
return false;
}
}
return true;
}
void to_column_major(std::vector<bh_instruction> &instr_list) {
for(bh_instruction &instr: instr_list) {
if (instr.opcode < BH_MAX_OPCODE_ID and row_major_access(instr)) {
instr.transpose();
}
}
}
} // jitk
} // bohrium
| 32.734266
| 111
| 0.618885
|
4d1473ccf39e9a751975902f40216f3c24b8f04f
| 216
|
cs
|
C#
|
src/System/Diagnostics/SR.cs
|
Polystream/System.Diagnostics.PerformanceCounters
|
f0e69bc366c97a05bf5e05c5c81c1156457f0380
|
[
"Apache-2.0"
] | 7
|
2018-01-16T14:17:40.000Z
|
2019-07-27T05:11:15.000Z
|
src/System/Diagnostics/SR.cs
|
Polystream/System.Diagnostics.PerformanceCounters
|
f0e69bc366c97a05bf5e05c5c81c1156457f0380
|
[
"Apache-2.0"
] | 2
|
2019-05-21T06:02:24.000Z
|
2020-06-10T07:52:42.000Z
|
src/System/Diagnostics/SR.cs
|
Polystream/System.Diagnostics.PerformanceCounters
|
f0e69bc366c97a05bf5e05c5c81c1156457f0380
|
[
"Apache-2.0"
] | null | null | null |
namespace PerformanceCounters
{
public static class SR
{
public static string GetString(string format, params object[] args)
{
return string.Format(format, args);
}
}
}
| 21.6
| 75
| 0.601852
|
38d5c655e2fca7777438841967f470062e7a681e
| 969
|
php
|
PHP
|
tests/Api/SuppressionTest.php
|
rutek/mailgun-php
|
3c18d84dba86161185924ab764bf0bf4c1703034
|
[
"MIT"
] | null | null | null |
tests/Api/SuppressionTest.php
|
rutek/mailgun-php
|
3c18d84dba86161185924ab764bf0bf4c1703034
|
[
"MIT"
] | null | null | null |
tests/Api/SuppressionTest.php
|
rutek/mailgun-php
|
3c18d84dba86161185924ab764bf0bf4c1703034
|
[
"MIT"
] | null | null | null |
<?php
/*
* Copyright (C) 2013 Mailgun
*
* This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE file for details.
*/
namespace Mailgun\Tests\Api;
use Mailgun\Api\Suppression;
/**
* @author Tobias Nyholm <tobias.nyholm@gmail.com>
*/
class SuppressionTest extends TestCase
{
public function testBounces()
{
$api = $this->getApiInstance();
$this->assertInstanceOf(Suppression\Bounce::class, $api->bounces());
}
public function testComplaints()
{
$api = $this->getApiInstance();
$this->assertInstanceOf(Suppression\Complaint::class, $api->complaints());
}
public function testUnsubscribes()
{
$api = $this->getApiInstance();
$this->assertInstanceOf(Suppression\Unsubscribe::class, $api->unsubscribes());
}
/**
* {@inheritdoc}
*/
protected function getApiClass()
{
return Suppression::class;
}
}
| 21.533333
| 86
| 0.636739
|
7712bea8a5466c59e23f22f1997b489414053997
| 550
|
py
|
Python
|
app/main/models/pedido.py
|
amandapersampa/Franguinho
|
940b6601a821ab4857de7f0a5a0ac53f6f54a564
|
[
"MIT"
] | null | null | null |
app/main/models/pedido.py
|
amandapersampa/Franguinho
|
940b6601a821ab4857de7f0a5a0ac53f6f54a564
|
[
"MIT"
] | 8
|
2017-03-14T11:55:07.000Z
|
2017-04-03T00:53:32.000Z
|
app/main/models/pedido.py
|
amandapersampa/MicroGerencia
|
940b6601a821ab4857de7f0a5a0ac53f6f54a564
|
[
"MIT"
] | null | null | null |
# coding=utf-8
from app import db
from sqlalchemy.orm import relationship
class pedido_dao:
__tablename__ = "pedido"
# id_pedido = db.Column(db.Integer, primary_key=True)
# nome = db.Column(db.String)
# valor = db.Column(db.Float)
# qtd_ingrediente = db.Column(db.Integer)
# qtd_item_extra = db.Column(db.Integer)
# tipo_item = db.Column(db.String)
# item_extra = db.Column(db.String)
# id_produto = db.Column(db.Integer, db.ForeignKey('produto.id_produto'))
# produto = relationship("Produto_dao", back_populates="")
| 34.375
| 76
| 0.707273
|
ddcbcee38fb9fa5dd831a3c28ebca1910ae6693c
| 1,895
|
java
|
Java
|
drools-benchmarks/src/main/java/org/drools/benchmarks/common/AbstractBenchmark.java
|
hellowdan/kie-benchmarks
|
1cfce530cc3d374f3884b60d954bae9a038b7b5c
|
[
"Apache-2.0"
] | 4
|
2020-05-12T08:57:00.000Z
|
2020-12-02T20:26:43.000Z
|
drools-benchmarks/src/main/java/org/drools/benchmarks/common/AbstractBenchmark.java
|
hellowdan/kie-benchmarks
|
1cfce530cc3d374f3884b60d954bae9a038b7b5c
|
[
"Apache-2.0"
] | 41
|
2017-08-28T12:11:00.000Z
|
2022-03-31T16:14:34.000Z
|
drools-benchmarks/src/main/java/org/drools/benchmarks/common/AbstractBenchmark.java
|
hellowdan/kie-benchmarks
|
1cfce530cc3d374f3884b60d954bae9a038b7b5c
|
[
"Apache-2.0"
] | 26
|
2017-08-22T09:08:48.000Z
|
2021-11-09T11:51:23.000Z
|
/*
* Copyright 2015 Red Hat, Inc. and/or its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
*
* 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.drools.benchmarks.common;
import java.util.Collection;
import java.util.concurrent.TimeUnit;
import org.kie.api.KieBase;
import org.kie.api.runtime.KieSession;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Level;
import org.openjdk.jmh.annotations.Measurement;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.annotations.TearDown;
import org.openjdk.jmh.annotations.Warmup;
import org.openjdk.jmh.infra.Blackhole;
@BenchmarkMode(Mode.SingleShotTime)
@State(Scope.Thread)
@Warmup(iterations = 30)
@Measurement(iterations = 20)
@OutputTimeUnit(TimeUnit.MILLISECONDS)
public abstract class AbstractBenchmark {
protected KieBase kieBase;
protected KieSession kieSession;
public abstract void setup() throws ProviderException;
@TearDown(Level.Iteration)
public void tearDown() {
if (kieSession != null) {
kieSession.halt();
kieSession.dispose();
kieSession = null;
}
}
protected void insertFacts(final Collection<Object> facts, final Blackhole eater) {
facts.forEach(fact -> eater.consume(kieSession.insert(fact)));
}
}
| 32.118644
| 87
| 0.746702
|
fae9017601477a5c103e5cf5cd15da3cbc34805f
| 738
|
sql
|
SQL
|
database.sql
|
gruessung/meaju
|
2060c4afa113e9dd5744b160373f8eea6af34503
|
[
"WTFPL"
] | 18
|
2019-09-23T13:07:20.000Z
|
2021-11-21T13:59:04.000Z
|
database.sql
|
gruessung/meaju
|
2060c4afa113e9dd5744b160373f8eea6af34503
|
[
"WTFPL"
] | 1
|
2020-03-02T13:52:07.000Z
|
2020-12-19T14:16:29.000Z
|
database.sql
|
gruessung/meaju
|
2060c4afa113e9dd5744b160373f8eea6af34503
|
[
"WTFPL"
] | 3
|
2019-09-23T13:28:01.000Z
|
2020-04-29T18:58:15.000Z
|
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET AUTOCOMMIT = 0;
START TRANSACTION;
SET time_zone = "+00:00";
CREATE TABLE `stat` (
`id` int(11) NOT NULL,
`url` int(20) NOT NULL,
`time` varchar(50) NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
CREATE TABLE `urls` (
`id` int(11) NOT NULL,
`short` varchar(255) NOT NULL,
`long` varchar(999) NOT NULL,
`pw` varchar(255) DEFAULT NULL,
`userid` int(5) NOT NULL,
`abuse` int(1) NOT NULL DEFAULT '0'
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
ALTER TABLE `stat`
ADD PRIMARY KEY (`id`);
ALTER TABLE `urls`
ADD PRIMARY KEY (`id`);
ALTER TABLE `stat`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;
ALTER TABLE `urls`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;
COMMIT;
| 21.085714
| 46
| 0.680217
|
e2cd45da03be911624abea4e2d780a36759787cb
| 9,695
|
py
|
Python
|
ebi_eva_common_pyutils/nextflow/nextflow_pipeline.py
|
itsroops/eva-common-pyutils
|
4226e3800a95e8a50ff2735792382fe1a6ca4efc
|
[
"Apache-2.0"
] | null | null | null |
ebi_eva_common_pyutils/nextflow/nextflow_pipeline.py
|
itsroops/eva-common-pyutils
|
4226e3800a95e8a50ff2735792382fe1a6ca4efc
|
[
"Apache-2.0"
] | 4
|
2020-09-11T12:02:49.000Z
|
2021-06-23T14:44:36.000Z
|
ebi_eva_common_pyutils/nextflow/nextflow_pipeline.py
|
itsroops/eva-common-pyutils
|
4226e3800a95e8a50ff2735792382fe1a6ca4efc
|
[
"Apache-2.0"
] | 6
|
2020-07-18T21:06:10.000Z
|
2022-01-11T08:00:26.000Z
|
# Copyright 2021 EMBL - European Bioinformatics Institute
#
# 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.
# Rationale for a Nextflow pipeline abstraction
# ---------------------------------------------
# Dynamic pipeline generation
# Abstraction to represent process dependencies
# Unit testability of individual steps without scattering logic between Python and Nextflow
# Ability to combine pipelines
import networkx as nx
import os
from typing import List, Dict, Union
from ebi_eva_common_pyutils.logger import AppLogger
from ebi_eva_common_pyutils.command_utils import run_command_with_output
class NextFlowProcess:
def __init__(self, process_name: str, command_to_run: str, process_directives: Dict[str, str] = None) -> None:
"""
Create a Nextflow process
:rtype: None
:param process_name: Name of the process - should be a valid identifier - ex: p1_merge
:type process_name: str
:param command_to_run: Command to be run - ex: bash -c "echo p1"
:type command_to_run: str
:param process_directives: Additional process directives - ex: {"memory": "4GB", "executor": "lsf"}
:type process_directives: dict
"""
if not process_name.isidentifier():
raise ValueError(f"{process_name} is not a valid Nextflow process name")
self.process_name = process_name
self.success_flag = f"{self.process_name}_success"
self.command_to_run = command_to_run
self.process_directives = process_directives if process_directives else dict()
class NextFlowPipeline(AppLogger):
def __init__(self, process_dependency_map: Dict[NextFlowProcess, List[NextFlowProcess]] = None) -> None:
"""
Create a Nextflow pipeline with a process dependency map
:param process_dependency_map: Map of Nextflow processes and their corresponding dependencies
- ex: {p3 : [p2], p2: [p1]} where p1, p2 and p3 are Nextflow processes that should be executed sequentially
"""
# Modeling the dependency map as a DiGraph (Directed graph) is advantageous
# in ordering/combining flows and detecting cycles
self.process_dependency_map = nx.ordered.DiGraph()
if process_dependency_map:
self.add_dependencies(process_dependency_map)
def add_dependencies(self, process_dependency_map: Dict[NextFlowProcess, List[NextFlowProcess]]):
for process, dependencies in process_dependency_map.items():
if dependencies:
for dependency in dependencies:
self.add_process_dependency(process, dependency)
else:
self.add_process_dependency(process, None)
def add_process_dependency(self, process: NextFlowProcess, dependency: Union[NextFlowProcess, None]):
if dependency:
self.process_dependency_map.add_edge(process, dependency)
if not nx.dag.is_directed_acyclic_graph(self.process_dependency_map):
raise ValueError(f"Cycles found in pipeline when adding process {process.process_name} "
f"and its dependency {dependency.process_name}")
else:
# If no dependency is specified, the process will just be a single node in the DAG
self.process_dependency_map.add_node(process)
def _write_to_pipeline_file(self, workflow_file_path: str):
with open(workflow_file_path, "a") as pipeline_file_handle:
pipeline_file_handle.write(self.__str__() + "\n")
def run_pipeline(self, workflow_file_path: str, nextflow_binary_path: str = 'nextflow',
nextflow_config_path: str = None, working_dir: str = ".", resume: bool = False,
other_args: dict = None):
# Remove pipeline file if it already exists
if os.path.exists(workflow_file_path):
os.remove(workflow_file_path)
self._write_to_pipeline_file(workflow_file_path)
workflow_command = f"cd {working_dir} && {nextflow_binary_path} run {workflow_file_path}"
workflow_command += f" -c {nextflow_config_path}" if nextflow_config_path else ""
workflow_command += f" -with-report {workflow_file_path}.report.html"
workflow_command += f" -with-dag {workflow_file_path}.dag.png"
workflow_command += " -resume" if resume else ""
workflow_command += " ".join([f" -{arg} {val}" for arg, val in other_args.items()]) if other_args else ""
run_command_with_output(f"Running pipeline {workflow_file_path}...", workflow_command)
@staticmethod
def join_pipelines(main_pipeline: 'NextFlowPipeline', dependent_pipeline: 'NextFlowPipeline') -> 'NextFlowPipeline':
"""
Join two pipelines.
Returns a new pipeline where:
1) root processes are those of the main pipeline.
2) final processes are those of the dependent pipeline and
3) every root process of the dependent pipeline depends on the final processes of the main pipeline.
"""
joined_pipeline = NextFlowPipeline()
# Aggregate dependency maps of both pipelines
joined_pipeline.process_dependency_map = nx.compose(main_pipeline.process_dependency_map,
dependent_pipeline.process_dependency_map)
for final_process_in_main_pipeline in main_pipeline._get_final_processes():
for root_process_in_dependent_pipeline in dependent_pipeline._get_root_processes():
joined_pipeline.add_process_dependency(root_process_in_dependent_pipeline,
final_process_in_main_pipeline)
return joined_pipeline
def _get_root_processes(self) -> List[NextFlowProcess]:
# Root processes are those which have no dependencies
# See https://stackoverflow.com/a/62948641
roots = []
for component in nx.weakly_connected_components(self.process_dependency_map):
subgraph = self.process_dependency_map.subgraph(component)
roots.extend([n for n, d in subgraph.out_degree() if d == 0])
return roots
def _get_final_processes(self) -> List[NextFlowProcess]:
# Final processes are those which have no other processes depending on them
# See https://stackoverflow.com/a/62948641
roots = []
for component in nx.weakly_connected_components(self.process_dependency_map):
subgraph = self.process_dependency_map.subgraph(component)
roots.extend([n for n, d in subgraph.in_degree() if d == 0])
return roots
@staticmethod
def _get_process_repr(process: NextFlowProcess, dependencies: List[NextFlowProcess]) -> str:
process_directives_str = "\n".join([f"{key}='{value}'" for key, value in process.process_directives.items()])
input_dependencies = "val flag from true"
if dependencies:
input_dependencies = "\n".join([f"val {dependency.success_flag} from {dependency.success_flag}"
for dependency in dependencies])
return "\n".join(map(str.strip, f"""
process {process.process_name} {{
{process_directives_str}
input:
{input_dependencies}
output:
val true into {process.success_flag}
script:
\"\"\"
{process.command_to_run}
\"\"\"
}}""".split("\n")))
def __str__(self):
# Order the list of nodes based on the dependency
# See https://networkx.org/documentation/stable/reference/algorithms/generated/networkx.algorithms.traversal.depth_first_search.dfs_postorder_nodes.html?highlight=dfs_postorder_nodes#networkx.algorithms.traversal.depth_first_search.dfs_postorder_nodes
ordered_list_of_processes_to_run = list(nx.dfs_postorder_nodes(self.process_dependency_map))
# Get a Nextflow pipeline representation of each process and its dependencies
return "\n\n".join([NextFlowPipeline._get_process_repr(process, list(self.process_dependency_map[process]))
for process in ordered_list_of_processes_to_run])
class LinearNextFlowPipeline(NextFlowPipeline):
"""
Simple linear pipeline that supports resumption
"""
previous_process: NextFlowProcess = None
def __init__(self, process_list: List[NextFlowProcess] = None):
dependency_map = {}
if process_list:
for index, process in enumerate(process_list):
dependency_map[process] = [] if index == 0 else [process_list[index - 1]]
super().__init__(dependency_map)
def add_process(self, process_name, command_to_run):
current_process = NextFlowProcess(process_name=process_name, command_to_run=command_to_run)
self._add_new_process(current_process)
def _add_new_process(self, current_process):
super().add_process_dependency(current_process, self.previous_process)
self.previous_process = current_process
| 51.296296
| 259
| 0.678185
|
7fb67f9bbe9900061f8971f5cfcdde3492cbbe6f
| 1,540
|
php
|
PHP
|
public/lib/Kendo/UI/AppBar.php
|
ductm-it/codeignterdev
|
f5baa5aff686442fd94b7c920ca9ae2539bf0969
|
[
"MIT"
] | null | null | null |
public/lib/Kendo/UI/AppBar.php
|
ductm-it/codeignterdev
|
f5baa5aff686442fd94b7c920ca9ae2539bf0969
|
[
"MIT"
] | null | null | null |
public/lib/Kendo/UI/AppBar.php
|
ductm-it/codeignterdev
|
f5baa5aff686442fd94b7c920ca9ae2539bf0969
|
[
"MIT"
] | null | null | null |
<?php
namespace Kendo\UI;
class AppBar extends \Kendo\UI\Widget {
public function name() {
return 'AppBar';
}
//>> Properties
/**
* Adds AppBarItem to the AppBar.
* @param \Kendo\UI\AppBarItem|array,... $value one or more AppBarItem to add.
* @return \Kendo\UI\AppBar
*/
public function addItem($value) {
return $this->add('items', func_get_args());
}
/**
* Defines where in the page the AppBar will be positioned
* @param string $value
* @return \Kendo\UI\AppBar
*/
public function position($value) {
return $this->setProperty('position', $value);
}
/**
* Defines the type of positioning
* @param string $value
* @return \Kendo\UI\AppBar
*/
public function positionMode($value) {
return $this->setProperty('positionMode', $value);
}
/**
* Specifies the color of the component
* @param string $value
* @return \Kendo\UI\AppBar
*/
public function themeColor($value) {
return $this->setProperty('themeColor', $value);
}
/**
* Sets the resize event of the AppBar.
* Fired when the window is resized.
* @param string|\Kendo\JavaScriptFunction $value Can be a JavaScript function definition or name.
* @return \Kendo\UI\AppBar
*/
public function resize($value) {
if (is_string($value)) {
$value = new \Kendo\JavaScriptFunction($value);
}
return $this->setProperty('resize', $value);
}
//<< Properties
}
?>
| 23.333333
| 101
| 0.6
|