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
sequencelengths 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
sequencelengths 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
sequencelengths 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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
cf1fdb7edf649ccc7a404f0e8b6fc93e1d2baa62 | 5,593 | php | PHP | application/modules/admin/models/Academic_subject_model.php | devsourceexpert/SM1520161 | ea709639d67329d7b1af9eb43341d3aa473cfedd | [
"MIT"
] | null | null | null | application/modules/admin/models/Academic_subject_model.php | devsourceexpert/SM1520161 | ea709639d67329d7b1af9eb43341d3aa473cfedd | [
"MIT"
] | null | null | null | application/modules/admin/models/Academic_subject_model.php | devsourceexpert/SM1520161 | ea709639d67329d7b1af9eb43341d3aa473cfedd | [
"MIT"
] | null | null | null | <?php
/*
* Developer : Saravanan.S
* Date : 26 JAN, 2016
* Description : Manage Academic Subjects
*/
class Academic_subject_model extends CI_Model
{
private $db;
private $table = null;
public $academic_subject_id = 0;
public $subject_name = null;
public $academic_year_id = 0;
public $active = 1; // default is active(1)
public function __construct()
{
parent::__construct();
$this->db = & get_instance()->db_mgr;
$this->load->config('db_constants');
$this->table = TBL_ACADEMIC_SUBJECTS;
}
public function save()
{
$insert_data = array (
'subject_name' => $this->subject_name,
'academic_year_id' => $this->academic_year_id,
'active' => $this->active
);
$this->db->writer()->insert($this->table,$insert_data);
return $this->db->writer()->insert_id();
}
public function update()
{
$update_data = array (
'subject_name' => $this->subject_name,
'academic_year_id' => $this->academic_year_id,
'active' => $this->active
);
$where = array(
'academic_subject_id' => $this->academic_subject_id
);
$this->db->writer()
->where($where)
->update($this->table,$update_data);
return $this->db->writer()->affected_rows();
}
public function delete()
{
$where = array(
'academic_subject_id' => $this->academic_subject_id
);
$this->db->writer()
->where($where)
->delete($this->table);
return $this->db->writer()->affected_rows();
}
public function get_subjects($request_data)
{
$subjects = array();
$columns = array(
// datatable column index => database column name
0 => 'subject_name',
1 => 'active'
);
// get and set the total records count without filter
$count_query = $this->db->reader()
->select('COUNT(academic_subject_id) AS tot_records')
->from($this->table)
->where('academic_year_id', $this->academic_year_id)
->get();
$result_set = $count_query->row();
$subjects['total_data'] = $result_set->tot_records;
$subjects['total_filtered'] = $subjects['total_data'];
// get and set the total filtered record counts after applied filter
if( !empty($request_data['search']['value']) )
{
$query = $this->db->reader()
->select('COUNT(academic_subject_id) AS tot_records')
->from($this->table)
->where('academic_year_id', $this->academic_year_id)
->where(" subject_name LIKE '". $request_data['search']['value'] ."%'")
->get();
$result_set = $count_query->row();
$subjects['total_filtered'] = $result_set->tot_records;
$data_query = $this->db->reader()
->select('*')
->from($this->table)
->where('academic_year_id', $this->academic_year_id)
->where(" subject_name LIKE '". $request_data['search']['value'] ."%'")
->order_by($columns[$request_data['order'][0]['column']], $request_data['order'][0]['dir'])
->limit($request_data['length'],$request_data['start'])
->get();
}
else {
$data_query = $this->db->reader()
->select('*')
->from($this->table)
->where('academic_year_id', $this->academic_year_id)
->order_by($columns[$request_data['order'][0]['column']], $request_data['order'][0]['dir'])
->limit($request_data['length'],$request_data['start'])
->get();
}
$subjects['result'] = $data_query->result();
return $subjects;
}
public function get_active_subjects() {
$subjects = array();
$query = $this->db->reader()
->select('*')
->from($this->table)
->where('active', 1)
->where('academic_year_id', $this->academic_year_id)
->get();
$subjects = $query->result();
return $subjects;
}
public function get_subject()
{
$where = array(
'academic_subject_id' => $this->academic_subject_id
);
$query = $this->db->reader()
->select('*')
->from($this->table)
->where($where)
->get();
return $query->result();
}
public function unique_check()
{
$num_rows = $this->db->reader()
->select('academic_subject_id')
->from($this->table)
->where('subject_name',$this->subject_name)
->where('academic_year_id', $this->academic_year_id)
->where('academic_subject_id !=', $this->academic_subject_id)
->limit(1)->get()->num_rows();
if($num_rows)
{
return false;
}
return true;
}
} | 32.707602 | 107 | 0.474522 |
c6910a1785539e08539553c1566d65ff9f1445c5 | 667 | rb | Ruby | lib/fragmenter/validators/checksum_validator.rb | dscout/fragmenter | 9a87996c3a4067da58be38f6adab62bec5d8696d | [
"MIT"
] | 1 | 2015-03-22T10:13:07.000Z | 2015-03-22T10:13:07.000Z | lib/fragmenter/validators/checksum_validator.rb | dscout/fragmenter | 9a87996c3a4067da58be38f6adab62bec5d8696d | [
"MIT"
] | null | null | null | lib/fragmenter/validators/checksum_validator.rb | dscout/fragmenter | 9a87996c3a4067da58be38f6adab62bec5d8696d | [
"MIT"
] | null | null | null | require 'digest/md5'
module Fragmenter
module Validators
class ChecksumValidator
attr_reader :errors, :request
def initialize(request)
@request = request
@errors = []
end
def part?
true
end
def valid?
matches = expected.nil? || expected == calculated
unless matches
errors << "Expected checksum #{expected} to match #{calculated}"
end
matches
end
private
def expected
request.headers['HTTP_CONTENT_MD5']
end
def calculated
@calculated ||= Digest::MD5.hexdigest(request.body)
end
end
end
end
| 17.102564 | 74 | 0.574213 |
5d401c19452901ae86f32ac359aae3a8a22142fe | 1,489 | hpp | C++ | src/parser/skip-to-sequence.hpp | aaron-michaux/giraffe | 457b55d80f6d21616a5c40232c2f68ee9e2c8335 | [
"MIT"
] | null | null | null | src/parser/skip-to-sequence.hpp | aaron-michaux/giraffe | 457b55d80f6d21616a5c40232c2f68ee9e2c8335 | [
"MIT"
] | null | null | null | src/parser/skip-to-sequence.hpp | aaron-michaux/giraffe | 457b55d80f6d21616a5c40232c2f68ee9e2c8335 | [
"MIT"
] | null | null | null |
#pragma once
#include "scanner/scanner.hpp"
#include "utils/in-list.hpp"
namespace giraffe::detail
{
template<typename T> bool match_worker(Scanner& tokens, T&& id) noexcept
{
if(in_list(tokens.current().id(), id)) {
tokens.consume();
return true;
}
return false;
}
template<typename T, typename... Ts>
bool match_worker(Scanner& tokens, T&& id, Ts&&... rest) noexcept
{
return match_worker(tokens, id) && match_worker(tokens, std::forward<Ts>(rest)...);
}
} // namespace giraffe::detail
namespace giraffe
{
template<typename... Ts> bool skip_to_sequence(Scanner& tokens, Ts&&... ids) noexcept
{
while(tokens.has_next()) {
const auto start_position = tokens.position();
const bool match = detail::match_worker(tokens, std::forward<Ts>(ids)...);
tokens.set_position(start_position);
if(match)
return true;
else
tokens.consume(); // advance one token
}
return false;
}
template<typename O, typename... Ts>
bool skip_to_sequence_omitting(Scanner& tokens, const O& omit, Ts&&... ids) noexcept
{
while(tokens.has_next() && !in_list(tokens.current().id(), omit)) {
const auto start_position = tokens.position();
const bool match = detail::match_worker(tokens, std::forward<Ts>(ids)...);
tokens.set_position(start_position);
if(match)
return true;
else
tokens.consume(); // advance one token
}
return false;
}
} // namespace giraffe
| 26.122807 | 89 | 0.648086 |
0a947c2f4fc40f019d272db0f9531d9c86df02a7 | 3,561 | cs | C# | UltimaOnline.Data/Engines/ConPVP/StakesContainer.cs | netcode-gamer/game.ultimaonline.io | 5be917d62b6232b07c5517f5f0b06bcaf3df93b9 | [
"MIT"
] | null | null | null | UltimaOnline.Data/Engines/ConPVP/StakesContainer.cs | netcode-gamer/game.ultimaonline.io | 5be917d62b6232b07c5517f5f0b06bcaf3df93b9 | [
"MIT"
] | null | null | null | UltimaOnline.Data/Engines/ConPVP/StakesContainer.cs | netcode-gamer/game.ultimaonline.io | 5be917d62b6232b07c5517f5f0b06bcaf3df93b9 | [
"MIT"
] | null | null | null | using System;
using System.Text;
using System.Collections;
using UltimaOnline;
using UltimaOnline.Items;
namespace UltimaOnline.Engines.ConPVP
{
#if false
[Flipable(0x9A8, 0xE80)]
public class StakesContainer : LockableContainer
{
private Mobile m_Initiator;
private Participant m_Participant;
private Hashtable m_Owners;
public override bool CheckItemUse(Mobile from, Item item)
{
Mobile owner = (Mobile)m_Owners[item];
if (owner != null && owner != from)
return false;
return base.CheckItemUse(from, item);
}
public override bool CheckTarget(Mobile from, Server.Targeting.Target targ, object targeted)
{
Mobile owner = (Mobile)m_Owners[targeted];
if (owner != null && owner != from)
return false;
return base.CheckTarget(from, targ, targeted);
}
public override bool CheckLift(Mobile from, Item item)
{
Mobile owner = (Mobile)m_Owners[item];
if (owner != null && owner != from)
return false;
return base.CheckLift(from, item);
}
public void ReturnItems()
{
ArrayList items = new ArrayList(this.Items);
for (int i = 0; i < items.Count; ++i)
{
Item item = (Item)items[i];
Mobile owner = (Mobile)m_Owners[item];
if (owner == null || owner.Deleted)
owner = m_Initiator;
if (owner == null || owner.Deleted)
return;
if (item.LootType != LootType.Blessed || !owner.PlaceInBackpack(item))
owner.BankBox.DropItem(item);
}
}
public override bool TryDropItem(Mobile from, Item dropped, bool sendFullMessage)
{
if (m_Participant == null || !m_Participant.Contains(from))
{
if (sendFullMessage)
from.SendMessage("You are not allowed to place items here.");
return false;
}
if (dropped is Container || dropped.Stackable)
{
if (sendFullMessage)
from.SendMessage("That item cannot be used as stakes.");
return false;
}
if (!base.TryDropItem(from, dropped, sendFullMessage))
return false;
if (from != null)
m_Owners[dropped] = from;
return true;
}
public override void RemoveItem(Item item)
{
base.RemoveItem(item);
m_Owners.Remove(item);
}
public StakesContainer(DuelContext context, Participant participant) : base(0x9A8)
{
Movable = false;
m_Initiator = context.Initiator;
m_Participant = participant;
m_Owners = new Hashtable();
}
public StakesContainer(Serial serial) : base(serial)
{
}
public override void Serialize(GenericWriter writer)
{
base.Serialize(writer);
writer.Write((int)0); // version
}
public override void Deserialize(GenericReader reader)
{
base.Deserialize(reader);
int version = reader.ReadInt();
}
}
#endif
} | 28.03937 | 101 | 0.512496 |
7bca2dbc1ca7552e5f6978fcb64478f85881a998 | 110 | cpp | C++ | src/UIKit/UIEvent.cpp | jjzhang166/uikit-cpp-win32 | 6887cef72334214c00cae95a671415f0e91dd886 | [
"MIT"
] | 4 | 2015-06-05T03:06:21.000Z | 2021-02-13T18:07:58.000Z | src/UIKit/UIEvent.cpp | jjzhang166/uikit-cpp-win32 | 6887cef72334214c00cae95a671415f0e91dd886 | [
"MIT"
] | null | null | null | src/UIKit/UIEvent.cpp | jjzhang166/uikit-cpp-win32 | 6887cef72334214c00cae95a671415f0e91dd886 | [
"MIT"
] | 4 | 2015-06-05T03:06:22.000Z | 2022-03-25T01:03:05.000Z | #include "UIEvent.h"
UIEvent::UIEvent()
: x(0)
, y(0)
, view(NULL) {
}
UIEvent::~UIEvent() {
} | 9.166667 | 21 | 0.5 |
c8cf2f48e7e46261d65d6c0ef13ed4d1a242b6dd | 3,804 | css | CSS | wp-content/plugins/easy-social-share-buttons3/assets/admin/tinymce/pinpro.css | aniskchaou/BLOG-COMET-CMS | c1fbaeaffb4cdb62082049d7e76f0a10fcefe9c1 | [
"MIT"
] | null | null | null | wp-content/plugins/easy-social-share-buttons3/assets/admin/tinymce/pinpro.css | aniskchaou/BLOG-COMET-CMS | c1fbaeaffb4cdb62082049d7e76f0a10fcefe9c1 | [
"MIT"
] | null | null | null | wp-content/plugins/easy-social-share-buttons3/assets/admin/tinymce/pinpro.css | aniskchaou/BLOG-COMET-CMS | c1fbaeaffb4cdb62082049d7e76f0a10fcefe9c1 | [
"MIT"
] | null | null | null | .mce-i-essb-pp-image {
background-image: url(data:image/svg+xml;utf8;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iaXNvLTg4NTktMSI/Pgo8IS0tIEdlbmVyYXRvcjogQWRvYmUgSWxsdXN0cmF0b3IgMTguMC4wLCBTVkcgRXhwb3J0IFBsdWctSW4gLiBTVkcgVmVyc2lvbjogNi4wMCBCdWlsZCAwKSAgLS0+CjwhRE9DVFlQRSBzdmcgUFVCTElDICItLy9XM0MvL0RURCBTVkcgMS4xLy9FTiIgImh0dHA6Ly93d3cudzMub3JnL0dyYXBoaWNzL1NWRy8xLjEvRFREL3N2ZzExLmR0ZCI+CjxzdmcgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIiB4bWxuczp4bGluaz0iaHR0cDovL3d3dy53My5vcmcvMTk5OS94bGluayIgdmVyc2lvbj0iMS4xIiBpZD0iQ2FwYV8xIiB4PSIwcHgiIHk9IjBweCIgdmlld0JveD0iMCAwIDExMi4xOTggMTEyLjE5OCIgc3R5bGU9ImVuYWJsZS1iYWNrZ3JvdW5kOm5ldyAwIDAgMTEyLjE5OCAxMTIuMTk4OyIgeG1sOnNwYWNlPSJwcmVzZXJ2ZSIgd2lkdGg9IjUxMnB4IiBoZWlnaHQ9IjUxMnB4Ij4KPGc+Cgk8Y2lyY2xlIHN0eWxlPSJmaWxsOiNDQjIwMjc7IiBjeD0iNTYuMDk5IiBjeT0iNTYuMSIgcj0iNTYuMDk4Ii8+Cgk8Zz4KCQk8cGF0aCBzdHlsZT0iZmlsbDojRjFGMkYyOyIgZD0iTTYwLjYyNyw3NS4xMjJjLTQuMjQxLTAuMzI4LTYuMDIzLTIuNDMxLTkuMzQ5LTQuNDVjLTEuODI4LDkuNTkxLTQuMDYyLDE4Ljc4NS0xMC42NzksMjMuNTg4ICAgIGMtMi4wNDUtMTQuNDk2LDIuOTk4LTI1LjM4NCw1LjM0LTM2Ljk0MWMtMy45OTItNi43MiwwLjQ4LTIwLjI0Niw4LjktMTYuOTEzYzEwLjM2Myw0LjA5OC04Ljk3MiwyNC45ODcsNC4wMDgsMjcuNTk2ICAgIGMxMy41NTEsMi43MjQsMTkuMDgzLTIzLjUxMywxMC42NzktMzIuMDQ3Yy0xMi4xNDItMTIuMzIxLTM1LjM0My0wLjI4LTMyLjQ5LDE3LjM1OGMwLjY5NSw0LjMxMiw1LjE1MSw1LjYyMSwxLjc4LDExLjU3MSAgICBjLTcuNzcxLTEuNzIxLTEwLjA4OS03Ljg1LTkuNzkxLTE2LjAyMWMwLjQ4MS0xMy4zNzUsMTIuMDE4LTIyLjc0LDIzLjU5LTI0LjAzNmMxNC42MzUtMS42MzgsMjguMzcxLDUuMzc0LDMwLjI2NywxOS4xNCAgICBDODUuMDE1LDU5LjUwNCw3Ni4yNzUsNzYuMzMsNjAuNjI3LDc1LjEyMkw2MC42MjcsNzUuMTIyeiIvPgoJPC9nPgo8L2c+CjxnPgo8L2c+CjxnPgo8L2c+CjxnPgo8L2c+CjxnPgo8L2c+CjxnPgo8L2c+CjxnPgo8L2c+CjxnPgo8L2c+CjxnPgo8L2c+CjxnPgo8L2c+CjxnPgo8L2c+CjxnPgo8L2c+CjxnPgo8L2c+CjxnPgo8L2c+CjxnPgo8L2c+CjxnPgo8L2c+Cjwvc3ZnPgo=) !important;
}
.mce-i-essb-pp-image:before {
display: inline-block;
-webkit-font-smoothing: antialiased;
text-align: center;
font-weight: 400;
font-size: 20px;
line-height: 1;
background-image: url(data:image/svg+xml;utf8;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iaXNvLTg4NTktMSI/Pgo8IS0tIEdlbmVyYXRvcjogQWRvYmUgSWxsdXN0cmF0b3IgMTguMC4wLCBTVkcgRXhwb3J0IFBsdWctSW4gLiBTVkcgVmVyc2lvbjogNi4wMCBCdWlsZCAwKSAgLS0+CjwhRE9DVFlQRSBzdmcgUFVCTElDICItLy9XM0MvL0RURCBTVkcgMS4xLy9FTiIgImh0dHA6Ly93d3cudzMub3JnL0dyYXBoaWNzL1NWRy8xLjEvRFREL3N2ZzExLmR0ZCI+CjxzdmcgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIiB4bWxuczp4bGluaz0iaHR0cDovL3d3dy53My5vcmcvMTk5OS94bGluayIgdmVyc2lvbj0iMS4xIiBpZD0iQ2FwYV8xIiB4PSIwcHgiIHk9IjBweCIgdmlld0JveD0iMCAwIDExMi4xOTggMTEyLjE5OCIgc3R5bGU9ImVuYWJsZS1iYWNrZ3JvdW5kOm5ldyAwIDAgMTEyLjE5OCAxMTIuMTk4OyIgeG1sOnNwYWNlPSJwcmVzZXJ2ZSIgd2lkdGg9IjUxMnB4IiBoZWlnaHQ9IjUxMnB4Ij4KPGc+Cgk8Y2lyY2xlIHN0eWxlPSJmaWxsOiNDQjIwMjc7IiBjeD0iNTYuMDk5IiBjeT0iNTYuMSIgcj0iNTYuMDk4Ii8+Cgk8Zz4KCQk8cGF0aCBzdHlsZT0iZmlsbDojRjFGMkYyOyIgZD0iTTYwLjYyNyw3NS4xMjJjLTQuMjQxLTAuMzI4LTYuMDIzLTIuNDMxLTkuMzQ5LTQuNDVjLTEuODI4LDkuNTkxLTQuMDYyLDE4Ljc4NS0xMC42NzksMjMuNTg4ICAgIGMtMi4wNDUtMTQuNDk2LDIuOTk4LTI1LjM4NCw1LjM0LTM2Ljk0MWMtMy45OTItNi43MiwwLjQ4LTIwLjI0Niw4LjktMTYuOTEzYzEwLjM2Myw0LjA5OC04Ljk3MiwyNC45ODcsNC4wMDgsMjcuNTk2ICAgIGMxMy41NTEsMi43MjQsMTkuMDgzLTIzLjUxMywxMC42NzktMzIuMDQ3Yy0xMi4xNDItMTIuMzIxLTM1LjM0My0wLjI4LTMyLjQ5LDE3LjM1OGMwLjY5NSw0LjMxMiw1LjE1MSw1LjYyMSwxLjc4LDExLjU3MSAgICBjLTcuNzcxLTEuNzIxLTEwLjA4OS03Ljg1LTkuNzkxLTE2LjAyMWMwLjQ4MS0xMy4zNzUsMTIuMDE4LTIyLjc0LDIzLjU5LTI0LjAzNmMxNC42MzUtMS42MzgsMjguMzcxLDUuMzc0LDMwLjI2NywxOS4xNCAgICBDODUuMDE1LDU5LjUwNCw3Ni4yNzUsNzYuMzMsNjAuNjI3LDc1LjEyMkw2MC42MjcsNzUuMTIyeiIvPgoJPC9nPgo8L2c+CjxnPgo8L2c+CjxnPgo8L2c+CjxnPgo8L2c+CjxnPgo8L2c+CjxnPgo8L2c+CjxnPgo8L2c+CjxnPgo8L2c+CjxnPgo8L2c+CjxnPgo8L2c+CjxnPgo8L2c+CjxnPgo8L2c+CjxnPgo8L2c+CjxnPgo8L2c+CjxnPgo8L2c+CjxnPgo8L2c+Cjwvc3ZnPgo=);
content: ' ';
color: #4099ff;
speak: none;
vertical-align: top;
position: relative;
} | 211.333333 | 1,759 | 0.953996 |
6607466a83a7aedb5945640707a5d47caaa76929 | 33,314 | py | Python | hio-yocto-bsp/sources/poky/scripts/lib/mic/utils/partitionedfs.py | qiangzai00001/hio-prj | 060ff97fe21093b1369db78109d5b730b2b181c8 | [
"MIT"
] | null | null | null | hio-yocto-bsp/sources/poky/scripts/lib/mic/utils/partitionedfs.py | qiangzai00001/hio-prj | 060ff97fe21093b1369db78109d5b730b2b181c8 | [
"MIT"
] | null | null | null | hio-yocto-bsp/sources/poky/scripts/lib/mic/utils/partitionedfs.py | qiangzai00001/hio-prj | 060ff97fe21093b1369db78109d5b730b2b181c8 | [
"MIT"
] | null | null | null | #!/usr/bin/python -tt
#
# Copyright (c) 2009, 2010, 2011 Intel, Inc.
# Copyright (c) 2007, 2008 Red Hat, Inc.
# Copyright (c) 2008 Daniel P. Berrange
# Copyright (c) 2008 David P. Huff
#
# This program is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by the Free
# Software Foundation; version 2 of the License
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
# or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
# for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc., 59
# Temple Place - Suite 330, Boston, MA 02111-1307, USA.
import os
from mic import msger
from mic.utils import runner
from mic.utils.errors import MountError
from mic.utils.fs_related import *
from mic.utils.gpt_parser import GptParser
from mic.utils.oe.misc import *
# Overhead of the MBR partitioning scheme (just one sector)
MBR_OVERHEAD = 1
# Overhead of the GPT partitioning scheme
GPT_OVERHEAD = 34
# Size of a sector in bytes
SECTOR_SIZE = 512
class PartitionedMount(Mount):
def __init__(self, mountdir, skipformat = False):
Mount.__init__(self, mountdir)
self.disks = {}
self.partitions = []
self.subvolumes = []
self.mapped = False
self.mountOrder = []
self.unmountOrder = []
self.parted = find_binary_path("parted")
self.btrfscmd=None
self.skipformat = skipformat
self.snapshot_created = self.skipformat
# Size of a sector used in calculations
self.sector_size = SECTOR_SIZE
self._partitions_layed_out = False
def __add_disk(self, disk_name):
""" Add a disk 'disk_name' to the internal list of disks. Note,
'disk_name' is the name of the disk in the target system
(e.g., sdb). """
if disk_name in self.disks:
# We already have this disk
return
assert not self._partitions_layed_out
self.disks[disk_name] = \
{ 'disk': None, # Disk object
'mapped': False, # True if kpartx mapping exists
'numpart': 0, # Number of allocate partitions
'partitions': [], # Indexes to self.partitions
'offset': 0, # Offset of next partition (in sectors)
# Minimum required disk size to fit all partitions (in bytes)
'min_size': 0,
'ptable_format': "msdos" } # Partition table format
def add_disk(self, disk_name, disk_obj):
""" Add a disk object which have to be partitioned. More than one disk
can be added. In case of multiple disks, disk partitions have to be
added for each disk separately with 'add_partition()". """
self.__add_disk(disk_name)
self.disks[disk_name]['disk'] = disk_obj
def __add_partition(self, part):
""" This is a helper function for 'add_partition()' which adds a
partition to the internal list of partitions. """
assert not self._partitions_layed_out
self.partitions.append(part)
self.__add_disk(part['disk_name'])
def add_partition(self, size, disk_name, mountpoint, source_file = None, fstype = None,
label=None, fsopts = None, boot = False, align = None,
part_type = None):
""" Add the next partition. Prtitions have to be added in the
first-to-last order. """
ks_pnum = len(self.partitions)
# Converting MB to sectors for parted
size = size * 1024 * 1024 / self.sector_size
# We need to handle subvolumes for btrfs
if fstype == "btrfs" and fsopts and fsopts.find("subvol=") != -1:
self.btrfscmd=find_binary_path("btrfs")
subvol = None
opts = fsopts.split(",")
for opt in opts:
if opt.find("subvol=") != -1:
subvol = opt.replace("subvol=", "").strip()
break
if not subvol:
raise MountError("No subvolume: %s" % fsopts)
self.subvolumes.append({'size': size, # In sectors
'mountpoint': mountpoint, # Mount relative to chroot
'fstype': fstype, # Filesystem type
'fsopts': fsopts, # Filesystem mount options
'disk_name': disk_name, # physical disk name holding partition
'device': None, # kpartx device node for partition
'mount': None, # Mount object
'subvol': subvol, # Subvolume name
'boot': boot, # Bootable flag
'mounted': False # Mount flag
})
# We still need partition for "/" or non-subvolume
if mountpoint == "/" or not fsopts or fsopts.find("subvol=") == -1:
# Don't need subvolume for "/" because it will be set as default subvolume
if fsopts and fsopts.find("subvol=") != -1:
opts = fsopts.split(",")
for opt in opts:
if opt.strip().startswith("subvol="):
opts.remove(opt)
break
fsopts = ",".join(opts)
part = { 'ks_pnum' : ks_pnum, # Partition number in the KS file
'size': size, # In sectors
'mountpoint': mountpoint, # Mount relative to chroot
'source_file': source_file, # partition contents
'fstype': fstype, # Filesystem type
'fsopts': fsopts, # Filesystem mount options
'label': label, # Partition label
'disk_name': disk_name, # physical disk name holding partition
'device': None, # kpartx device node for partition
'mount': None, # Mount object
'num': None, # Partition number
'boot': boot, # Bootable flag
'align': align, # Partition alignment
'part_type' : part_type, # Partition type
'partuuid': None } # Partition UUID (GPT-only)
self.__add_partition(part)
def layout_partitions(self, ptable_format = "msdos"):
""" Layout the partitions, meaning calculate the position of every
partition on the disk. The 'ptable_format' parameter defines the
partition table format, and may be either "msdos" or "gpt". """
msger.debug("Assigning %s partitions to disks" % ptable_format)
if ptable_format not in ('msdos', 'gpt'):
raise MountError("Unknown partition table format '%s', supported " \
"formats are: 'msdos' and 'gpt'" % ptable_format)
if self._partitions_layed_out:
return
self._partitions_layed_out = True
# Go through partitions in the order they are added in .ks file
for n in range(len(self.partitions)):
p = self.partitions[n]
if not self.disks.has_key(p['disk_name']):
raise MountError("No disk %s for partition %s" \
% (p['disk_name'], p['mountpoint']))
if p['part_type'] and ptable_format != 'gpt':
# The --part-type can also be implemented for MBR partitions,
# in which case it would map to the 1-byte "partition type"
# filed at offset 3 of the partition entry.
raise MountError("setting custom partition type is only " \
"imlemented for GPT partitions")
# Get the disk where the partition is located
d = self.disks[p['disk_name']]
d['numpart'] += 1
d['ptable_format'] = ptable_format
if d['numpart'] == 1:
if ptable_format == "msdos":
overhead = MBR_OVERHEAD
else:
overhead = GPT_OVERHEAD
# Skip one sector required for the partitioning scheme overhead
d['offset'] += overhead
# Steal few sectors from the first partition to offset for the
# partitioning overhead
p['size'] -= overhead
if p['align']:
# If not first partition and we do have alignment set we need
# to align the partition.
# FIXME: This leaves a empty spaces to the disk. To fill the
# gaps we could enlargea the previous partition?
# Calc how much the alignment is off.
align_sectors = d['offset'] % (p['align'] * 1024 / self.sector_size)
# We need to move forward to the next alignment point
align_sectors = (p['align'] * 1024 / self.sector_size) - align_sectors
msger.debug("Realignment for %s%s with %s sectors, original"
" offset %s, target alignment is %sK." %
(p['disk_name'], d['numpart'], align_sectors,
d['offset'], p['align']))
# increase the offset so we actually start the partition on right alignment
d['offset'] += align_sectors
p['start'] = d['offset']
d['offset'] += p['size']
p['type'] = 'primary'
p['num'] = d['numpart']
if d['ptable_format'] == "msdos":
if d['numpart'] > 2:
# Every logical partition requires an additional sector for
# the EBR, so steal the last sector from the end of each
# partition starting from the 3rd one for the EBR. This
# will make sure the logical partitions are aligned
# correctly.
p['size'] -= 1
if d['numpart'] > 3:
p['type'] = 'logical'
p['num'] = d['numpart'] + 1
d['partitions'].append(n)
msger.debug("Assigned %s to %s%d, sectors range %d-%d size %d "
"sectors (%d bytes)." \
% (p['mountpoint'], p['disk_name'], p['num'],
p['start'], p['start'] + p['size'] - 1,
p['size'], p['size'] * self.sector_size))
# Once all the partitions have been layed out, we can calculate the
# minumim disk sizes.
for disk_name, d in self.disks.items():
d['min_size'] = d['offset']
if d['ptable_format'] == 'gpt':
# Account for the backup partition table at the end of the disk
d['min_size'] += GPT_OVERHEAD
d['min_size'] *= self.sector_size
def __run_parted(self, args):
""" Run parted with arguments specified in the 'args' list. """
args.insert(0, self.parted)
msger.debug(args)
rc, out = runner.runtool(args, catch = 3)
out = out.strip()
if out:
msger.debug('"parted" output: %s' % out)
if rc != 0:
# We don't throw exception when return code is not 0, because
# parted always fails to reload part table with loop devices. This
# prevents us from distinguishing real errors based on return
# code.
msger.debug("WARNING: parted returned '%s' instead of 0" % rc)
def __create_partition(self, device, parttype, fstype, start, size):
""" Create a partition on an image described by the 'device' object. """
# Start is included to the size so we need to substract one from the end.
end = start + size - 1
msger.debug("Added '%s' partition, sectors %d-%d, size %d sectors" %
(parttype, start, end, size))
args = ["-s", device, "unit", "s", "mkpart", parttype]
if fstype:
args.extend([fstype])
args.extend(["%d" % start, "%d" % end])
return self.__run_parted(args)
def __format_disks(self):
self.layout_partitions()
if self.skipformat:
msger.debug("Skipping disk format, because skipformat flag is set.")
return
for dev in self.disks.keys():
d = self.disks[dev]
msger.debug("Initializing partition table for %s" % \
(d['disk'].device))
self.__run_parted(["-s", d['disk'].device, "mklabel",
d['ptable_format']])
msger.debug("Creating partitions")
for p in self.partitions:
d = self.disks[p['disk_name']]
if d['ptable_format'] == "msdos" and p['num'] == 5:
# The last sector of the 3rd partition was reserved for the EBR
# of the first _logical_ partition. This is why the extended
# partition should start one sector before the first logical
# partition.
self.__create_partition(d['disk'].device, "extended",
None, p['start'] - 1,
d['offset'] - p['start'])
if p['fstype'] == "swap":
parted_fs_type = "linux-swap"
elif p['fstype'] == "vfat":
parted_fs_type = "fat32"
elif p['fstype'] == "msdos":
parted_fs_type = "fat16"
else:
# Type for ext2/ext3/ext4/btrfs
parted_fs_type = "ext2"
# Boot ROM of OMAP boards require vfat boot partition to have an
# even number of sectors.
if p['mountpoint'] == "/boot" and p['fstype'] in ["vfat", "msdos"] \
and p['size'] % 2:
msger.debug("Substracting one sector from '%s' partition to " \
"get even number of sectors for the partition" % \
p['mountpoint'])
p['size'] -= 1
self.__create_partition(d['disk'].device, p['type'],
parted_fs_type, p['start'], p['size'])
if p['boot']:
if d['ptable_format'] == 'gpt':
flag_name = "legacy_boot"
else:
flag_name = "boot"
msger.debug("Set '%s' flag for partition '%s' on disk '%s'" % \
(flag_name, p['num'], d['disk'].device))
self.__run_parted(["-s", d['disk'].device, "set",
"%d" % p['num'], flag_name, "on"])
# Parted defaults to enabling the lba flag for fat16 partitions,
# which causes compatibility issues with some firmware (and really
# isn't necessary).
if parted_fs_type == "fat16":
if d['ptable_format'] == 'msdos':
msger.debug("Disable 'lba' flag for partition '%s' on disk '%s'" % \
(p['num'], d['disk'].device))
self.__run_parted(["-s", d['disk'].device, "set",
"%d" % p['num'], "lba", "off"])
# If the partition table format is "gpt", find out PARTUUIDs for all
# the partitions. And if users specified custom parition type UUIDs,
# set them.
for disk_name, disk in self.disks.items():
if disk['ptable_format'] != 'gpt':
continue
pnum = 0
gpt_parser = GptParser(d['disk'].device, SECTOR_SIZE)
# Iterate over all GPT partitions on this disk
for entry in gpt_parser.get_partitions():
pnum += 1
# Find the matching partition in the 'self.partitions' list
for n in d['partitions']:
p = self.partitions[n]
if p['num'] == pnum:
# Found, fetch PARTUUID (partition's unique ID)
p['partuuid'] = entry['part_uuid']
msger.debug("PARTUUID for partition %d on disk '%s' " \
"(mount point '%s') is '%s'" % (pnum, \
disk_name, p['mountpoint'], p['partuuid']))
if p['part_type']:
entry['type_uuid'] = p['part_type']
msger.debug("Change type of partition %d on disk " \
"'%s' (mount point '%s') to '%s'" % \
(pnum, disk_name, p['mountpoint'],
p['part_type']))
gpt_parser.change_partition(entry)
del gpt_parser
def __map_partitions(self):
"""Load it if dm_snapshot isn't loaded. """
load_module("dm_snapshot")
for dev in self.disks.keys():
d = self.disks[dev]
if d['mapped']:
continue
msger.debug("Running kpartx on %s" % d['disk'].device )
rc, kpartxOutput = runner.runtool([self.kpartx, "-l", "-v", d['disk'].device])
kpartxOutput = kpartxOutput.splitlines()
if rc != 0:
raise MountError("Failed to query partition mapping for '%s'" %
d['disk'].device)
# Strip trailing blank and mask verbose output
i = 0
while i < len(kpartxOutput) and kpartxOutput[i][0:4] != "loop":
i = i + 1
kpartxOutput = kpartxOutput[i:]
# Make sure kpartx reported the right count of partitions
if len(kpartxOutput) != d['numpart']:
# If this disk has more than 3 partitions, then in case of MBR
# paritions there is an extended parition. Different versions
# of kpartx behave differently WRT the extended partition -
# some map it, some ignore it. This is why we do the below hack
# - if kpartx reported one more partition and the partition
# table type is "msdos" and the amount of partitions is more
# than 3, we just assume kpartx mapped the extended parition
# and we remove it.
if len(kpartxOutput) == d['numpart'] + 1 \
and d['ptable_format'] == 'msdos' and len(kpartxOutput) > 3:
kpartxOutput.pop(3)
else:
raise MountError("Unexpected number of partitions from " \
"kpartx: %d != %d" % \
(len(kpartxOutput), d['numpart']))
for i in range(len(kpartxOutput)):
line = kpartxOutput[i]
newdev = line.split()[0]
mapperdev = "/dev/mapper/" + newdev
loopdev = d['disk'].device + newdev[-1]
msger.debug("Dev %s: %s -> %s" % (newdev, loopdev, mapperdev))
pnum = d['partitions'][i]
self.partitions[pnum]['device'] = loopdev
# grub's install wants partitions to be named
# to match their parent device + partition num
# kpartx doesn't work like this, so we add compat
# symlinks to point to /dev/mapper
if os.path.lexists(loopdev):
os.unlink(loopdev)
os.symlink(mapperdev, loopdev)
msger.debug("Adding partx mapping for %s" % d['disk'].device)
rc = runner.show([self.kpartx, "-v", "-a", d['disk'].device])
if rc != 0:
# Make sure that the device maps are also removed on error case.
# The d['mapped'] isn't set to True if the kpartx fails so
# failed mapping will not be cleaned on cleanup either.
runner.quiet([self.kpartx, "-d", d['disk'].device])
raise MountError("Failed to map partitions for '%s'" %
d['disk'].device)
# FIXME: there is a bit delay for multipath device setup,
# wait 10ms for the setup
import time
time.sleep(10)
d['mapped'] = True
def __unmap_partitions(self):
for dev in self.disks.keys():
d = self.disks[dev]
if not d['mapped']:
continue
msger.debug("Removing compat symlinks")
for pnum in d['partitions']:
if self.partitions[pnum]['device'] != None:
os.unlink(self.partitions[pnum]['device'])
self.partitions[pnum]['device'] = None
msger.debug("Unmapping %s" % d['disk'].device)
rc = runner.quiet([self.kpartx, "-d", d['disk'].device])
if rc != 0:
raise MountError("Failed to unmap partitions for '%s'" %
d['disk'].device)
d['mapped'] = False
def __calculate_mountorder(self):
msger.debug("Calculating mount order")
for p in self.partitions:
if p['mountpoint']:
self.mountOrder.append(p['mountpoint'])
self.unmountOrder.append(p['mountpoint'])
self.mountOrder.sort()
self.unmountOrder.sort()
self.unmountOrder.reverse()
def cleanup(self):
Mount.cleanup(self)
if self.disks:
self.__unmap_partitions()
for dev in self.disks.keys():
d = self.disks[dev]
try:
d['disk'].cleanup()
except:
pass
def unmount(self):
self.__unmount_subvolumes()
for mp in self.unmountOrder:
if mp == 'swap':
continue
p = None
for p1 in self.partitions:
if p1['mountpoint'] == mp:
p = p1
break
if p['mount'] != None:
try:
# Create subvolume snapshot here
if p['fstype'] == "btrfs" and p['mountpoint'] == "/" and not self.snapshot_created:
self.__create_subvolume_snapshots(p, p["mount"])
p['mount'].cleanup()
except:
pass
p['mount'] = None
# Only for btrfs
def __get_subvolume_id(self, rootpath, subvol):
if not self.btrfscmd:
self.btrfscmd=find_binary_path("btrfs")
argv = [ self.btrfscmd, "subvolume", "list", rootpath ]
rc, out = runner.runtool(argv)
msger.debug(out)
if rc != 0:
raise MountError("Failed to get subvolume id from %s', return code: %d." % (rootpath, rc))
subvolid = -1
for line in out.splitlines():
if line.endswith(" path %s" % subvol):
subvolid = line.split()[1]
if not subvolid.isdigit():
raise MountError("Invalid subvolume id: %s" % subvolid)
subvolid = int(subvolid)
break
return subvolid
def __create_subvolume_metadata(self, p, pdisk):
if len(self.subvolumes) == 0:
return
argv = [ self.btrfscmd, "subvolume", "list", pdisk.mountdir ]
rc, out = runner.runtool(argv)
msger.debug(out)
if rc != 0:
raise MountError("Failed to get subvolume id from %s', return code: %d." % (pdisk.mountdir, rc))
subvolid_items = out.splitlines()
subvolume_metadata = ""
for subvol in self.subvolumes:
for line in subvolid_items:
if line.endswith(" path %s" % subvol["subvol"]):
subvolid = line.split()[1]
if not subvolid.isdigit():
raise MountError("Invalid subvolume id: %s" % subvolid)
subvolid = int(subvolid)
opts = subvol["fsopts"].split(",")
for opt in opts:
if opt.strip().startswith("subvol="):
opts.remove(opt)
break
fsopts = ",".join(opts)
subvolume_metadata += "%d\t%s\t%s\t%s\n" % (subvolid, subvol["subvol"], subvol['mountpoint'], fsopts)
if subvolume_metadata:
fd = open("%s/.subvolume_metadata" % pdisk.mountdir, "w")
fd.write(subvolume_metadata)
fd.close()
def __get_subvolume_metadata(self, p, pdisk):
subvolume_metadata_file = "%s/.subvolume_metadata" % pdisk.mountdir
if not os.path.exists(subvolume_metadata_file):
return
fd = open(subvolume_metadata_file, "r")
content = fd.read()
fd.close()
for line in content.splitlines():
items = line.split("\t")
if items and len(items) == 4:
self.subvolumes.append({'size': 0, # In sectors
'mountpoint': items[2], # Mount relative to chroot
'fstype': "btrfs", # Filesystem type
'fsopts': items[3] + ",subvol=%s" % items[1], # Filesystem mount options
'disk_name': p['disk_name'], # physical disk name holding partition
'device': None, # kpartx device node for partition
'mount': None, # Mount object
'subvol': items[1], # Subvolume name
'boot': False, # Bootable flag
'mounted': False # Mount flag
})
def __create_subvolumes(self, p, pdisk):
""" Create all the subvolumes. """
for subvol in self.subvolumes:
argv = [ self.btrfscmd, "subvolume", "create", pdisk.mountdir + "/" + subvol["subvol"]]
rc = runner.show(argv)
if rc != 0:
raise MountError("Failed to create subvolume '%s', return code: %d." % (subvol["subvol"], rc))
# Set default subvolume, subvolume for "/" is default
subvol = None
for subvolume in self.subvolumes:
if subvolume["mountpoint"] == "/" and p['disk_name'] == subvolume['disk_name']:
subvol = subvolume
break
if subvol:
# Get default subvolume id
subvolid = self. __get_subvolume_id(pdisk.mountdir, subvol["subvol"])
# Set default subvolume
if subvolid != -1:
rc = runner.show([ self.btrfscmd, "subvolume", "set-default", "%d" % subvolid, pdisk.mountdir])
if rc != 0:
raise MountError("Failed to set default subvolume id: %d', return code: %d." % (subvolid, rc))
self.__create_subvolume_metadata(p, pdisk)
def __mount_subvolumes(self, p, pdisk):
if self.skipformat:
# Get subvolume info
self.__get_subvolume_metadata(p, pdisk)
# Set default mount options
if len(self.subvolumes) != 0:
for subvol in self.subvolumes:
if subvol["mountpoint"] == p["mountpoint"] == "/":
opts = subvol["fsopts"].split(",")
for opt in opts:
if opt.strip().startswith("subvol="):
opts.remove(opt)
break
pdisk.fsopts = ",".join(opts)
break
if len(self.subvolumes) == 0:
# Return directly if no subvolumes
return
# Remount to make default subvolume mounted
rc = runner.show([self.umountcmd, pdisk.mountdir])
if rc != 0:
raise MountError("Failed to umount %s" % pdisk.mountdir)
rc = runner.show([self.mountcmd, "-o", pdisk.fsopts, pdisk.disk.device, pdisk.mountdir])
if rc != 0:
raise MountError("Failed to umount %s" % pdisk.mountdir)
for subvol in self.subvolumes:
if subvol["mountpoint"] == "/":
continue
subvolid = self. __get_subvolume_id(pdisk.mountdir, subvol["subvol"])
if subvolid == -1:
msger.debug("WARNING: invalid subvolume %s" % subvol["subvol"])
continue
# Replace subvolume name with subvolume ID
opts = subvol["fsopts"].split(",")
for opt in opts:
if opt.strip().startswith("subvol="):
opts.remove(opt)
break
opts.extend(["subvolrootid=0", "subvol=%s" % subvol["subvol"]])
fsopts = ",".join(opts)
subvol['fsopts'] = fsopts
mountpoint = self.mountdir + subvol['mountpoint']
makedirs(mountpoint)
rc = runner.show([self.mountcmd, "-o", fsopts, pdisk.disk.device, mountpoint])
if rc != 0:
raise MountError("Failed to mount subvolume %s to %s" % (subvol["subvol"], mountpoint))
subvol["mounted"] = True
def __unmount_subvolumes(self):
""" It may be called multiple times, so we need to chekc if it is still mounted. """
for subvol in self.subvolumes:
if subvol["mountpoint"] == "/":
continue
if not subvol["mounted"]:
continue
mountpoint = self.mountdir + subvol['mountpoint']
rc = runner.show([self.umountcmd, mountpoint])
if rc != 0:
raise MountError("Failed to unmount subvolume %s from %s" % (subvol["subvol"], mountpoint))
subvol["mounted"] = False
def __create_subvolume_snapshots(self, p, pdisk):
import time
if self.snapshot_created:
return
# Remount with subvolid=0
rc = runner.show([self.umountcmd, pdisk.mountdir])
if rc != 0:
raise MountError("Failed to umount %s" % pdisk.mountdir)
if pdisk.fsopts:
mountopts = pdisk.fsopts + ",subvolid=0"
else:
mountopts = "subvolid=0"
rc = runner.show([self.mountcmd, "-o", mountopts, pdisk.disk.device, pdisk.mountdir])
if rc != 0:
raise MountError("Failed to umount %s" % pdisk.mountdir)
# Create all the subvolume snapshots
snapshotts = time.strftime("%Y%m%d-%H%M")
for subvol in self.subvolumes:
subvolpath = pdisk.mountdir + "/" + subvol["subvol"]
snapshotpath = subvolpath + "_%s-1" % snapshotts
rc = runner.show([ self.btrfscmd, "subvolume", "snapshot", subvolpath, snapshotpath ])
if rc != 0:
raise MountError("Failed to create subvolume snapshot '%s' for '%s', return code: %d." % (snapshotpath, subvolpath, rc))
self.snapshot_created = True
def __install_partition(self, num, source_file, start, size):
"""
Install source_file contents into a partition.
"""
if not source_file: # nothing to install
return
# Start is included in the size so need to substract one from the end.
end = start + size - 1
msger.debug("Installed %s in partition %d, sectors %d-%d, size %d sectors" % (source_file, num, start, end, size))
dd_cmd = "dd if=%s of=%s bs=%d seek=%d count=%d conv=notrunc" % \
(source_file, self.image_file, self.sector_size, start, size)
rc, out = exec_cmd(dd_cmd)
def install(self, image_file):
msger.debug("Installing partitions")
self.image_file = image_file
for p in self.partitions:
d = self.disks[p['disk_name']]
if d['ptable_format'] == "msdos" and p['num'] == 5:
# The last sector of the 3rd partition was reserved for the EBR
# of the first _logical_ partition. This is why the extended
# partition should start one sector before the first logical
# partition.
self.__install_partition(p['num'], p['source_file'],
p['start'] - 1,
d['offset'] - p['start'])
self.__install_partition(p['num'], p['source_file'],
p['start'], p['size'])
def mount(self):
for dev in self.disks.keys():
d = self.disks[dev]
d['disk'].create()
self.__format_disks()
self.__calculate_mountorder()
return
def resparse(self, size = None):
# Can't re-sparse a disk image - too hard
pass
| 42.546616 | 136 | 0.515579 |
8b8c69008d2e854728d2cfc2a6046fc8b9d3cd12 | 6,016 | sql | SQL | bd1/formularios.sql | andreinah/proyecto | 1fca188b50c9b3d5e8837e3b0c84108371715eec | [
"MIT"
] | null | null | null | bd1/formularios.sql | andreinah/proyecto | 1fca188b50c9b3d5e8837e3b0c84108371715eec | [
"MIT"
] | null | null | null | bd1/formularios.sql | andreinah/proyecto | 1fca188b50c9b3d5e8837e3b0c84108371715eec | [
"MIT"
] | null | null | null | -- phpMyAdmin SQL Dump
-- version 4.8.5
-- https://www.phpmyadmin.net/
--
-- Servidor: 127.0.0.1
-- Tiempo de generación: 14-04-2021 a las 23:51:11
-- Versión del servidor: 10.1.38-MariaDB
-- Versión de PHP: 7.3.2
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET AUTOCOMMIT = 0;
START TRANSACTION;
SET time_zone = "+00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;
--
-- Base de datos: `formularios`
--
-- --------------------------------------------------------
--
-- Estructura de tabla para la tabla `aplicaciones`
--
CREATE TABLE `aplicaciones` (
`codigo` int(100) NOT NULL,
`nombre` varchar(30) NOT NULL,
`fpago` varchar(30) NOT NULL,
`ndocumentos` int(10) NOT NULL,
`nalmacenamiento` int(10) NOT NULL,
`nempleados` int(10) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
-- --------------------------------------------------------
--
-- Estructura de tabla para la tabla `ciudades`
--
CREATE TABLE `ciudades` (
`id` int(11) NOT NULL,
`nombre` varchar(30) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
-- --------------------------------------------------------
--
-- Estructura de tabla para la tabla `cliente`
--
CREATE TABLE `cliente` (
`id` int(10) NOT NULL,
`proceso` varchar(30) NOT NULL,
`subproceso` varchar(30) NOT NULL,
`actividad` varchar(30) NOT NULL,
`sedes` varchar(30) NOT NULL,
`maquina` varchar(30) NOT NULL,
`bodega` varchar(30) NOT NULL,
`empleado` varchar(30) NOT NULL,
`cargo` varchar(30) NOT NULL,
`area` varchar(30) NOT NULL,
`procesoempleado` varchar(30) NOT NULL,
`email` varchar(30) NOT NULL,
`telefono` varchar(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
-- --------------------------------------------------------
--
-- Estructura de tabla para la tabla `departamento`
--
CREATE TABLE `departamento` (
`id` int(11) NOT NULL,
`nombre` int(11) NOT NULL,
`idciudad` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
-- --------------------------------------------------------
--
-- Estructura de tabla para la tabla `login`
--
CREATE TABLE `login` (
`id` int(10) NOT NULL,
`nombre` varchar(40) NOT NULL,
`usuario` varchar(20) NOT NULL,
`pass` varchar(20) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
-- --------------------------------------------------------
--
-- Estructura de tabla para la tabla `mclientes`
--
CREATE TABLE `mclientes` (
`id` int(10) NOT NULL,
`fecha` date NOT NULL,
`logo` varchar(100) NOT NULL,
`nit` varchar(20) NOT NULL,
`rsocial` varchar(30) NOT NULL,
`empresa` varchar(30) NOT NULL,
`actividad` varchar(30) NOT NULL,
`direccion` varchar(30) NOT NULL,
`url` varchar(30) NOT NULL,
`telefono` varchar(30) NOT NULL,
`sector` varchar(30) NOT NULL,
`subsector` varchar(30) NOT NULL,
`pais` varchar(30) NOT NULL,
`departamento` varchar(30) NOT NULL,
`ciudad` varchar(30) NOT NULL,
`barrio` varchar(30) NOT NULL,
`nempleados` varchar(30) NOT NULL,
`contacto` varchar(30) NOT NULL,
`tlfcontacto` varchar(30) NOT NULL,
`email` varchar(30) NOT NULL,
`asesor` varchar(30) NOT NULL,
`plazo` varchar(15) NOT NULL,
`cupo` varchar(30) NOT NULL,
`estado` int(1) NOT NULL,
`usuario` varchar(30) NOT NULL,
`pass` varchar(30) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
-- --------------------------------------------------------
--
-- Estructura de tabla para la tabla `sectores`
--
CREATE TABLE `sectores` (
`id` int(11) NOT NULL,
`nombre` int(11) NOT NULL,
`idsubsector` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
-- --------------------------------------------------------
--
-- Estructura de tabla para la tabla `subsectores`
--
CREATE TABLE `subsectores` (
`id` int(11) NOT NULL,
`nombre` varchar(50) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Índices para tablas volcadas
--
--
-- Indices de la tabla `aplicaciones`
--
ALTER TABLE `aplicaciones`
ADD PRIMARY KEY (`codigo`);
--
-- Indices de la tabla `ciudades`
--
ALTER TABLE `ciudades`
ADD PRIMARY KEY (`id`);
--
-- Indices de la tabla `cliente`
--
ALTER TABLE `cliente`
ADD PRIMARY KEY (`id`);
--
-- Indices de la tabla `departamento`
--
ALTER TABLE `departamento`
ADD PRIMARY KEY (`id`);
--
-- Indices de la tabla `login`
--
ALTER TABLE `login`
ADD PRIMARY KEY (`id`);
--
-- Indices de la tabla `mclientes`
--
ALTER TABLE `mclientes`
ADD PRIMARY KEY (`id`);
--
-- Indices de la tabla `sectores`
--
ALTER TABLE `sectores`
ADD PRIMARY KEY (`id`);
--
-- Indices de la tabla `subsectores`
--
ALTER TABLE `subsectores`
ADD PRIMARY KEY (`id`);
--
-- AUTO_INCREMENT de las tablas volcadas
--
--
-- AUTO_INCREMENT de la tabla `aplicaciones`
--
ALTER TABLE `aplicaciones`
MODIFY `codigo` int(100) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=3;
--
-- AUTO_INCREMENT de la tabla `ciudades`
--
ALTER TABLE `ciudades`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;
--
-- AUTO_INCREMENT de la tabla `cliente`
--
ALTER TABLE `cliente`
MODIFY `id` int(10) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=2;
--
-- AUTO_INCREMENT de la tabla `departamento`
--
ALTER TABLE `departamento`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;
--
-- AUTO_INCREMENT de la tabla `login`
--
ALTER TABLE `login`
MODIFY `id` int(10) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=2;
--
-- AUTO_INCREMENT de la tabla `mclientes`
--
ALTER TABLE `mclientes`
MODIFY `id` int(10) NOT NULL AUTO_INCREMENT;
--
-- AUTO_INCREMENT de la tabla `sectores`
--
ALTER TABLE `sectores`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;
--
-- AUTO_INCREMENT de la tabla `subsectores`
--
ALTER TABLE `subsectores`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;
COMMIT;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
| 22.787879 | 69 | 0.634475 |
7adec58ea6ac4d4f2e1843f02d0ca38f534a5358 | 1,081 | cs | C# | tools/InvoiceXpress.Cli/Item/ItemUpdateCommand.cs | filipetoscano/invoicexpress | 6574f229407a28ac699c0b59449e8d374ab08d6e | [
"MIT"
] | null | null | null | tools/InvoiceXpress.Cli/Item/ItemUpdateCommand.cs | filipetoscano/invoicexpress | 6574f229407a28ac699c0b59449e8d374ab08d6e | [
"MIT"
] | 7 | 2022-03-28T18:18:58.000Z | 2022-03-31T13:25:44.000Z | tools/InvoiceXpress.Cli/Item/ItemUpdateCommand.cs | filipetoscano/invoicexpress | 6574f229407a28ac699c0b59449e8d374ab08d6e | [
"MIT"
] | null | null | null | using McMaster.Extensions.CommandLineUtils;
using static InvoiceXpress.Cli.StaticUtils;
namespace InvoiceXpress.Cli;
/// <summary />
[Command( "update", Description = "Updates an item record" )]
public class ItemUpdateCommand
{
/// <summary />
[Argument( 0, Description = "Item record, in JSON file" )]
[FileExists]
public string? FilePath { get; set; }
/// <summary />
[Option( "--id", CommandOptionType.SingleValue, Description = "Set item identifier, overriding value in JSON file" )]
public int? ItemId { get; set; }
/// <summary />
private async Task<int> OnExecuteAsync( InvoiceXpressClient api, Jsonizer jss, IConsole console )
{
if ( TryLoad<Item>( console, this.FilePath, jss, out var item ) == false )
return 599;
if ( this.ItemId.HasValue == true )
item.Id = this.ItemId.Value;
/*
*
*/
var res = await api.ItemUpdateAsync( item );
if ( res.IsSuccessful == false )
return console.WriteError( res );
return 0;
}
}
| 26.365854 | 121 | 0.610546 |
e234388bd8e15d597ff8ba76f14c3e09b73c8156 | 1,338 | js | JavaScript | tasks/startup.js | rlugojr/lightning | d4d2d5fc6971a660df587950852d0384d459128d | [
"MIT"
] | 1,028 | 2015-01-15T05:43:12.000Z | 2022-02-19T19:15:36.000Z | tasks/startup.js | rlugojr/lightning | d4d2d5fc6971a660df587950852d0384d459128d | [
"MIT"
] | 61 | 2015-02-06T21:27:13.000Z | 2020-06-02T21:17:30.000Z | tasks/startup.js | harunpehlivan/lightning | 2c712c444957187f46b2004edb8bcfb5e5e1af75 | [
"MIT"
] | 129 | 2015-01-10T01:46:24.000Z | 2021-09-18T08:37:10.000Z | var models = require('../app/models');
var utils = require('../app/utils');
var env = process.env.NODE_ENV || 'development';
var dbConfig = require(__dirname + '/../config/database')[env];
var _ = require('lodash');
var tasks = require('./index');
var port = process.env.PORT || 3000;
var npm = require('npm');
var debug = require('debug')('lightning:server:startup');
require('colors');
var config = require('../config/config');
var f = function() {
console.log('Lightning started on port: ' + port);
debug(utils.getASCIILogo().magenta);
debug('Running database: ' + dbConfig.dialect);
models.sequelize.sync({force: false})
.then(function() {
return models.VisualizationType.findAll();
})
.then(function(vizTypes) {
debug('Installed visualizations:');
debug('-------------------------');
_.each(vizTypes, function(vt) {
debug('* ' + vt.name);
})
if(vizTypes.length === 0) {
npm.load(utils.getNPMConfig(), function() {
tasks.getDefaultVisualizations();
});
}
})
.catch(function(err) {
debug('Could not connect to the database. Is Postgres running?');
throw err;
});
};
module.exports = f;
| 28.468085 | 77 | 0.54559 |
a43ce687f662b11933b059f007c72f44f5c0d618 | 572 | php | PHP | app/Http/Controllers/api/admin/CustomerController.php | ihsan606/backend-ecommerce-restfull-api | 2bbe45f0f337c5cdfc4498fcab4f701291bd8efa | [
"MIT"
] | null | null | null | app/Http/Controllers/api/admin/CustomerController.php | ihsan606/backend-ecommerce-restfull-api | 2bbe45f0f337c5cdfc4498fcab4f701291bd8efa | [
"MIT"
] | null | null | null | app/Http/Controllers/api/admin/CustomerController.php | ihsan606/backend-ecommerce-restfull-api | 2bbe45f0f337c5cdfc4498fcab4f701291bd8efa | [
"MIT"
] | null | null | null | <?php
namespace App\Http\Controllers\Api\Admin;
use App\Models\Customer;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Http\Resources\CustomerResource;
class CustomerController extends Controller
{
//
public function index()
{
$customers = Customer::when(request()->q, function($customers) {
$customers = $customers->where('name', 'like', '%'. request()->q . '%');
})->latest()->paginate(5);
//return with Api Resource
return new CustomerResource(true, 'List Data Customer', $customers);
}
}
| 24.869565 | 78 | 0.667832 |
dca4deec5ac1d7eb15edc6f7b1a03997538613c1 | 388 | rb | Ruby | app/mailers/projects_mailer.rb | leonardoc2o/nos.vc | ff9780c1fd8697d921ba7e4929c30c80feda1d79 | [
"MIT"
] | 1 | 2021-09-01T14:38:41.000Z | 2021-09-01T14:38:41.000Z | app/mailers/projects_mailer.rb | gomex/nos.vc | d43afca5c24251d1a4e41a3b2fede4a8572b68d8 | [
"MIT"
] | null | null | null | app/mailers/projects_mailer.rb | gomex/nos.vc | d43afca5c24251d1a4e41a3b2fede4a8572b68d8 | [
"MIT"
] | null | null | null | class ProjectsMailer < ActionMailer::Base
include ERB::Util
def new_project(name, link, project, user)
@name = name
@link = link
@project = project
@user = user
mail(:from => "#{I18n.t('site.name')} <#{I18n.t('site.email.system')}>", :to => I18n.t('site.email.projects'), :subject => I18n.t('projects_mailer.new_project.subject', :name => @user.name ))
end
end
| 32.333333 | 195 | 0.639175 |
8e2dd55d228ec16f4f521276a9991f8245c15b5d | 2,700 | kt | Kotlin | app/src/main/java/com/syntia/local_alarm_sample/utils/NotificationUtils.kt | syntialai/local-alarm-sample | 89df13bb0236114892252b6c55f3e429542d3932 | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/syntia/local_alarm_sample/utils/NotificationUtils.kt | syntialai/local-alarm-sample | 89df13bb0236114892252b6c55f3e429542d3932 | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/syntia/local_alarm_sample/utils/NotificationUtils.kt | syntialai/local-alarm-sample | 89df13bb0236114892252b6c55f3e429542d3932 | [
"Apache-2.0"
] | null | null | null | package com.syntia.local_alarm_sample.utils
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.os.Build
import androidx.annotation.RequiresApi
import androidx.core.app.NotificationCompat
import com.syntia.local_alarm_sample.R
import com.syntia.local_alarm_sample.presentation.view.MainActivity
object NotificationUtils {
private const val NOTIFICATION_CHANNEL_ID = "NotificationChannelId"
private const val NOTIFICATION_ID = 12345
private const val CHANNEL_ID = "channel_id"
private const val CHANNEL_NAME = "channel_name"
fun showNotification(
context: Context,
title: String,
notificationId: Int = NOTIFICATION_ID
) {
val notificationManagerCompat = context.getSystemService(
Context.NOTIFICATION_SERVICE
) as NotificationManager
val notificationBuilder = getNotificationBuilder(
context,
title,
NOTIFICATION_CHANNEL_ID
)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
createNotificationChannel(notificationManagerCompat, notificationBuilder)
}
notificationManagerCompat.notify(notificationId, notificationBuilder.build())
}
@RequiresApi(Build.VERSION_CODES.O)
private fun createNotificationChannel(
notificationManager: NotificationManager,
notificationBuilder: NotificationCompat.Builder,
channelId: String = CHANNEL_ID,
channelName: String = CHANNEL_NAME
) {
val channel = NotificationChannel(
channelId,
channelName,
NotificationManager.IMPORTANCE_DEFAULT
)
notificationBuilder.setChannelId(channelId)
notificationManager.createNotificationChannel(channel)
}
private fun getNotificationBuilder(
context: Context,
title: String,
channelId: String
): NotificationCompat.Builder {
return NotificationCompat.Builder(context, channelId)
.setSmallIcon(R.drawable.ic_launcher_foreground)
.setContentTitle(title)
.setContentIntent(getPendingIntentToHome(context))
.setAutoCancel(true)
}
private fun getPendingIntentToHome(context: Context) = PendingIntent.getActivity(
context,
1000,
getHomeIntent(context),
PendingIntent.FLAG_UPDATE_CURRENT
)
private fun getHomeIntent(context: Context) = Intent(context, MainActivity::class.java).apply {
flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK
}
} | 33.333333 | 99 | 0.712593 |
1a5764a28fbba1b1832288eec7f1e52a4f08d966 | 9,178 | py | Python | control3.py | misterhay/VISCA-IP-Controller | 13e433dc825864eaaab9bfb83c0ebf1340a1f6aa | [
"Unlicense"
] | 30 | 2020-08-24T08:57:28.000Z | 2022-03-01T17:59:45.000Z | control3.py | misterhay/VISCA-IP-Controller | 13e433dc825864eaaab9bfb83c0ebf1340a1f6aa | [
"Unlicense"
] | 5 | 2021-06-21T16:43:54.000Z | 2022-01-30T17:26:44.000Z | control3.py | misterhay/VISCA-IP-Controller | 13e433dc825864eaaab9bfb83c0ebf1340a1f6aa | [
"Unlicense"
] | 14 | 2020-09-09T09:55:53.000Z | 2022-03-14T22:44:12.000Z | #!/usr/bin/env python
# sudo apt install python3-tk
from camera import *
c = Camera('192.168.0.100', 52381)
def save_preset_labels():
with open('preset_labels.txt', 'w') as f:
for entry in entry_boxes:
f.write(entry.get())
f.write('\n')
f.close()
# GUI
from tkinter import Tk, StringVar, Button, Label, Scale, Entry, W
root = Tk()
#display_message = StringVar()
root.title('VISCA IP Camera Controller')
root['background'] = 'white'
#Label(root, text='VISCA IP Camera Controller').grid(row=0, column=0, columnspan=100)
store_column = 0
label_column = 1
recall_column = 2
pan_tilt_column = 5
pan_tilt_row = 1
zoom_column = 3
zoom_row = 1
focus_column = 3
focus_row = 8
on_off_column = 3
on_off_row = 13
button_width = 8
store_color = 'red'
recall_color = 'light grey'
pan_tilt_color = 'white'
zoom_color = 'light blue'
focus_color = 'cyan'
on_off_color = 'violet'
# Preset store buttons
Label(root, text='Store', bg=store_color).grid(row=1, column=store_column)
Button(root, text=0, width=3, bg=store_color, command=lambda: c.memory_set(0)).grid(row=2, column=store_column)
Button(root, text=1, width=3, bg=store_color, command=lambda: c.memory_set(1)).grid(row=3, column=store_column)
Button(root, text=2, width=3, bg=store_color, command=lambda: c.memory_set(2)).grid(row=4, column=store_column)
Button(root, text=3, width=3, bg=store_color, command=lambda: c.memory_set(3)).grid(row=5, column=store_column)
Button(root, text=4, width=3, bg=store_color, command=lambda: c.memory_set(4)).grid(row=6, column=store_column)
Button(root, text=5, width=3, bg=store_color, command=lambda: c.memory_set(5)).grid(row=7, column=store_column)
Button(root, text=6, width=3, bg=store_color, command=lambda: c.memory_set(6)).grid(row=8, column=store_column)
Button(root, text=7, width=3, bg=store_color, command=lambda: c.memory_set(7)).grid(row=9, column=store_column)
Button(root, text=8, width=3, bg=store_color, command=lambda: c.memory_set(8)).grid(row=10, column=store_column)
Button(root, text=9, width=3, bg=store_color, command=lambda: c.memory_set(9)).grid(row=11, column=store_column)
Button(root, text='A', width=3, bg=store_color, command=lambda: c.memory_set(10)).grid(row=12, column=store_column)
Button(root, text='B', width=3, bg=store_color, command=lambda: c.memory_set(11)).grid(row=13, column=store_column)
Button(root, text='C', width=3, bg=store_color, command=lambda: c.memory_set(12)).grid(row=14, column=store_column)
Button(root, text='D', width=3, bg=store_color, command=lambda: c.memory_set(13)).grid(row=15, column=store_column)
Button(root, text='E', width=3, bg=store_color, command=lambda: c.memory_set(14)).grid(row=16, column=store_column)
Button(root, text='F', width=3, bg=store_color, command=lambda: c.memory_set(15)).grid(row=17, column=store_column)
# Recall buttons and entries (as labels)
Label(root, text='Recall', bg=recall_color).grid(row=1, column=recall_column)
Button(root, text=0, width=5, bg=recall_color, command=lambda: c.memory_recall(0)).grid(row=2, column=recall_column)
Button(root, text=1, width=5, bg=recall_color, command=lambda: c.memory_recall(1)).grid(row=3, column=recall_column)
Button(root, text=2, width=5, bg=recall_color, command=lambda: c.memory_recall(2)).grid(row=4, column=recall_column)
Button(root, text=3, width=5, bg=recall_color, command=lambda: c.memory_recall(3)).grid(row=5, column=recall_column)
Button(root, text=4, width=5, bg=recall_color, command=lambda: c.memory_recall(4)).grid(row=6, column=recall_column)
Button(root, text=5, width=5, bg=recall_color, command=lambda: c.memory_recall(5)).grid(row=7, column=recall_column)
Button(root, text=6, width=5, bg=recall_color, command=lambda: c.memory_recall(6)).grid(row=8, column=recall_column)
Button(root, text=7, width=5, bg=recall_color, command=lambda: c.memory_recall(7)).grid(row=9, column=recall_column)
Button(root, text=8, width=5, bg=recall_color, command=lambda: c.memory_recall(8)).grid(row=10, column=recall_column)
Button(root, text=9, width=5, bg=recall_color, command=lambda: c.memory_recall(9)).grid(row=11, column=recall_column)
Button(root, text='A', width=5, bg=recall_color, command=lambda: c.memory_recall(10)).grid(row=12, column=recall_column)
Button(root, text='B', width=5, bg=recall_color, command=lambda: c.memory_recall(11)).grid(row=13, column=recall_column)
Button(root, text='C', width=5, bg=recall_color, command=lambda: c.memory_recall(12)).grid(row=14, column=recall_column)
Button(root, text='D', width=5, bg=recall_color, command=lambda: c.memory_recall(13)).grid(row=15, column=recall_column)
Button(root, text='E', width=5, bg=recall_color, command=lambda: c.memory_recall(14)).grid(row=16, column=recall_column)
Button(root, text='F', width=5, bg=recall_color, command=lambda: c.memory_recall(15)).grid(row=17, column=recall_column)
try:
with open('preset_labels.txt', 'r') as f:
labels = f.read().splitlines()
f.close()
except:
pass
entry_boxes = []
for e in range(16):
box = Entry(root, justify='right')
try:
box.insert(-1, labels[e])
except:
pass
box.grid(row=e+2, column=label_column)
entry_boxes.append(box)
Button(root, text='Save preset labels', bg=store_color, command=lambda: save_preset_labels()).grid(row=1, column=label_column)
# Pan speed and Tilt speed sliders
Label(root, text='Pan Speed', bg=pan_tilt_color).grid(row=pan_tilt_row, column=pan_tilt_column)
pan_speed_slider = Scale(root, from_=24, to=0, bg=pan_tilt_color)
pan_speed_slider.set(7)
pan_speed_slider.grid(row=pan_tilt_row+1, column=pan_tilt_column, rowspan=4)
Label(root, text='Tilt Speed', bg=pan_tilt_color).grid(row=pan_tilt_row, column=pan_tilt_column+1)
tilt_speed_slider = Scale(root, from_=24, to=0, bg=pan_tilt_color)
tilt_speed_slider.set(7)
tilt_speed_slider.grid(row=pan_tilt_row+1, column=pan_tilt_column+1, rowspan=4)
#Button(root, text='test', command=lambda: print(pan_speed_slider.get(), tilt_speed_slider.get())).grid(row=0,column=0)
# Pan and tilt buttons
Button(root, text='↑', width=3, bg=pan_tilt_color, command=lambda: c.pantilt('up', pan_speed_slider.get(), tilt_speed_slider.get())).grid(row=pan_tilt_row, column=pan_tilt_column+3)
Button(root, text='←', width=3, bg=pan_tilt_color, command=lambda: c.pantilt('left', pan_speed_slider.get(), tilt_speed_slider.get())).grid(row=pan_tilt_row+1, column=pan_tilt_column+2)
Button(root, text='→', width=3, bg=pan_tilt_color, command=lambda: c.pantilt('right', pan_speed_slider.get(), tilt_speed_slider.get())).grid(row=pan_tilt_row+1, column=pan_tilt_column+4)
Button(root, text='↓', width=3, bg=pan_tilt_color, command=lambda: c.pantilt('down', pan_speed_slider.get(), tilt_speed_slider.get())).grid(row=pan_tilt_row+2, column=pan_tilt_column+3)
Button(root, text='↖', width=3, bg=pan_tilt_color, command=lambda: c.pantilt('upleft', pan_speed_slider.get(), tilt_speed_slider.get())).grid(row=pan_tilt_row, column=pan_tilt_column+2)
Button(root, text='↗', width=3, bg=pan_tilt_color, command=lambda: c.pantilt('upright', pan_speed_slider.get(), tilt_speed_slider.get())).grid(row=pan_tilt_row, column=pan_tilt_column+4)
Button(root, text='↙', width=3, bg=pan_tilt_color, command=lambda: c.pantilt('downleft', pan_speed_slider.get(), tilt_speed_slider.get())).grid(row=pan_tilt_row+2, column=pan_tilt_column+2)
Button(root, text='↘', width=3, bg=pan_tilt_color, command=lambda: c.pantilt('downright', pan_speed_slider.get(), tilt_speed_slider.get())).grid(row=pan_tilt_row+2, column=pan_tilt_column+4)
Button(root, text='■', width=3, bg=pan_tilt_color, command=lambda: c.pantilt_stop()).grid(row=pan_tilt_row+1, column=pan_tilt_column+3)
#Button(root, text='Home', command=lambda: send_message(pan_home)).grid(row=pan_tilt_row+2, column=pan_tilt_column+1)
# Zoom buttons
Label(root, text='Zoom', bg=zoom_color, width=button_width).grid(row=zoom_row, column=zoom_column)
Button(root, text='In', bg=zoom_color, width=button_width, command=lambda: c.zoom_in()).grid(row=zoom_row+1, column=zoom_column)
Button(root, text='Stop', bg=zoom_color, width=button_width, command=lambda: c.zoom_stop()).grid(row=zoom_row+2, column=zoom_column)
Button(root, text='Out', bg=zoom_color, width=button_width, command=lambda: c.zoom_out()).grid(row=zoom_row+3, column=zoom_column)
# On off connect buttons
Label(root, text='Camera', bg=on_off_color, width=button_width).grid(row=on_off_row, column=on_off_column)
Button(root, text='On', bg=on_off_color, width=button_width, command=lambda: c.on()).grid(row=on_off_row+1, column=on_off_column)
Button(root, text='Connect', bg=on_off_color, width=button_width, command=lambda: c.connect()).grid(row=on_off_row+2, column=on_off_column)
Button(root, text='Off', bg=on_off_color, width=button_width, command=lambda: c.off()).grid(row=on_off_row+3, column=on_off_column)
Button(root, text='Info Off', bg=on_off_color, width=button_width, command=lambda: c.info_display_off()).grid(row=on_off_row+4, column=on_off_column)
# IP Label
#Label(root, text=camera_ip+':'+str(camera_port)).grid(row=6, column=0, columnspan=3)
# Connection Label
#Label(root, textvariable=display_message).grid(row=6, column=4, columnspan=3)
root.mainloop()
#'''
| 66.507246 | 190 | 0.753323 |
f4c9d11712f7ac2ae7b9b3611f81008e90e4b086 | 1,885 | ts | TypeScript | src/types/Chart.ts | openmusicgame/omgc-core | 3092ffde203a5b6edf1fb9446bd03068af8716c3 | [
"MIT"
] | null | null | null | src/types/Chart.ts | openmusicgame/omgc-core | 3092ffde203a5b6edf1fb9446bd03068af8716c3 | [
"MIT"
] | null | null | null | src/types/Chart.ts | openmusicgame/omgc-core | 3092ffde203a5b6edf1fb9446bd03068af8716c3 | [
"MIT"
] | null | null | null | import { IUniqueModel } from "./base/model";
import { Dictionary, ExtensiveStringEnum, PredefinedDictionary } from "./base/typeutil";
import ChartData from "./ChartData";
import { ChartRelation } from "./ChartRelation";
import { v4 as uuid} from 'uuid';
export type ChartModes =
"key" |
"slide" |
"piano" |
"taiko" |
"appear" |
"through" |
"combined"|
"other";
export interface PredefinedMetadata {
/** 标记谱面来源(游戏) */
"preserved.source": string;
/** 标记谱面制作工具 */
"preserved.creator": string;
"keyCount": number;
/** 标记推荐玩法 */
"mode": ChartModes;
}
export interface ChartBasic<T = number> extends IUniqueModel<T> {
version: string;
author?: string;
description? :string;
license? :string;
cover? :string;
repository? :string;
keywords? :string[];
level? :string;
rank? :string;
metadata: PredefinedDictionary<any, PredefinedMetadata>;
}
export interface Chart<T = number> extends ChartBasic<T> {
rel?: ChartRelation;
data: ChartData;
}
export class OmgcChart implements Chart {
version: string;
rel?: ChartRelation | undefined;
author?: string | undefined;
description?: string | undefined;
license?: string | undefined;
cover?: string | undefined;
repository?: string | undefined;
keywords?: string[] | undefined;
level?: string | undefined;
rank?: string | undefined;
metadata: PredefinedDictionary<any, PredefinedMetadata>;
id?: number | undefined;
uid: string;
constructor(public name: string, public data: ChartData, metadata: PredefinedDictionary<any, PredefinedMetadata> = {}) {
this.uid = uuid();
this.version = "0.1.0";
this.metadata = metadata;
if (!this.metadata["preserved.creator"]) {
this.metadata["preserved.creator"] = "omgc";
}
}
} | 26.549296 | 124 | 0.634483 |
21c92032f89963623342a0a91373ca38e1ea51e6 | 363 | js | JavaScript | tests/data.js | roibh/juntas-server | a00757a289bc29d23e04f4d1e86672ab9aa99608 | [
"Apache-2.0"
] | null | null | null | tests/data.js | roibh/juntas-server | a00757a289bc29d23e04f4d1e86672ab9aa99608 | [
"Apache-2.0"
] | null | null | null | tests/data.js | roibh/juntas-server | a00757a289bc29d23e04f4d1e86672ab9aa99608 | [
"Apache-2.0"
] | null | null | null | "use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.newUser = {
FirstName: 'Roi',
LastName: 'Ben haim',
Email: '[email protected]',
Password: '1234'
};
exports.newUserNew = {
FirstName: 'Roi',
LastName: 'Ben haim',
Email: '[email protected]',
Password: '1234'
};
//# sourceMappingURL=data.js.map | 24.2 | 62 | 0.636364 |
464447a61d4ac50966a030f4e9b93a311e3acb10 | 3,369 | php | PHP | src/Permissions/Permission.php | jadu/meteor | 8215f6e6450f38cd98222c1f74eff65e7f622639 | [
"MIT"
] | 11 | 2016-08-17T12:54:27.000Z | 2021-03-04T17:12:52.000Z | src/Permissions/Permission.php | jadu/meteor | 8215f6e6450f38cd98222c1f74eff65e7f622639 | [
"MIT"
] | 55 | 2016-08-17T14:05:53.000Z | 2021-09-27T21:25:49.000Z | src/Permissions/Permission.php | jadu/meteor | 8215f6e6450f38cd98222c1f74eff65e7f622639 | [
"MIT"
] | null | null | null | <?php
namespace Meteor\Permissions;
use Symfony\Component\Finder\Glob;
class Permission
{
/**
* @var string
*/
protected $pattern;
/**
* @var bool
*/
protected $read;
/**
* @var bool
*/
protected $write;
/**
* @var bool
*/
protected $execute;
/**
* @var bool
*/
protected $recursive;
/**
* @param string $pattern
*/
public function __construct($pattern, $read = false, $write = false, $execute = false, $recursive = false)
{
$this->pattern = trim($pattern);
$this->read = (bool) $read;
$this->write = (bool) $write;
$this->execute = (bool) $execute;
$this->recursive = (bool) $recursive;
}
/**
* @param string $pattern
* @param array $modes
*
* @return Permission
*/
public static function create($pattern, array $modes)
{
$read = false;
$write = false;
$execute = false;
$recursive = false;
$permission = new self($pattern);
foreach ($modes as $mode) {
switch ($mode) {
case 'r':
$read = true;
break;
case 'w':
$write = true;
break;
case 'x':
$execute = true;
break;
case 'R':
$recursive = true;
break;
}
}
return new self($pattern, $read, $write, $execute, $recursive);
}
/**
* @return string
*/
public function getPattern()
{
return $this->pattern;
}
/**
* @return bool
*/
public function canRead()
{
return $this->read;
}
/**
* @param bool $read
*/
public function setRead($read)
{
$this->read = (bool) $read;
}
/**
* @return bool
*/
public function canWrite()
{
return $this->write;
}
/**
* @param bool $write
*/
public function setWrite($write)
{
$this->write = (bool) $write;
}
/**
* @return bool
*/
public function canExecute()
{
return $this->execute;
}
/**
* @param bool $execute
*/
public function setExecute($execute)
{
$this->execute = (bool) $execute;
}
/**
* @return bool
*/
public function isRecursive()
{
return $this->recursive;
}
/**
* @param bool $recursive
*/
public function setRecursive($recursive)
{
$this->recursive = (bool) $recursive;
}
/**
* Whether the path matches the pattern.
*
* @param string $path
*
* @return bool
*/
public function matches($path)
{
return preg_match(Glob::toRegex($this->pattern), $path) === 1;
}
/**
* @return string
*/
public function getModeString()
{
$string = '';
if ($this->canRead()) {
$string .= 'r';
}
if ($this->canWrite()) {
$string .= 'w';
}
if ($this->canExecute()) {
$string .= 'x';
}
if ($this->isRecursive()) {
$string .= 'R';
}
return $string;
}
}
| 17.638743 | 110 | 0.439596 |
52503634dbf970f1085a2161f0c998d672626c35 | 543 | sh | Shell | engines/morph-rdb/evaluate_warm.sh | jatoledo/gtfs-bench | 5b3fa0fd0bdb169c9a7436820392b68bcc9d9808 | [
"Apache-2.0"
] | null | null | null | engines/morph-rdb/evaluate_warm.sh | jatoledo/gtfs-bench | 5b3fa0fd0bdb169c9a7436820392b68bcc9d9808 | [
"Apache-2.0"
] | null | null | null | engines/morph-rdb/evaluate_warm.sh | jatoledo/gtfs-bench | 5b3fa0fd0bdb169c9a7436820392b68bcc9d9808 | [
"Apache-2.0"
] | null | null | null | #!/bin/bash
for i in 1 5 10 50 100 500
do
for j in 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
do
for t in 1 2 3 4 5 6
do
#properties, mapping, querypath, size,query,time
# Load properties configuration
./pre_update_config.sh gtfs.morph-rdb.properties $i q${j}.rq 'warm'
# Run engine
timeout -s SIGKILL 60m ./run.sh $i q${j}.rq $t 'warm' ||echo "$i, q${j}.rq, $t, warm, TimeOut">> ../results/results-times.csv
# Delete properties configuration
./post_update_config.sh gtfs.morph-rdb.properties
done
done
done
| 25.857143 | 128 | 0.662983 |
663a78ecd8a06bd71aa337a4064e146ea0fb9f86 | 611 | py | Python | get_seek_chains.py | gkovacs/invideo-quizzes-analysis-las2016 | 6ec8686ef0d3ffa5e994f8dec41590fea87e9539 | [
"MIT"
] | null | null | null | get_seek_chains.py | gkovacs/invideo-quizzes-analysis-las2016 | 6ec8686ef0d3ffa5e994f8dec41590fea87e9539 | [
"MIT"
] | null | null | null | get_seek_chains.py | gkovacs/invideo-quizzes-analysis-las2016 | 6ec8686ef0d3ffa5e994f8dec41590fea87e9539 | [
"MIT"
] | null | null | null | #!/usr/bin/env python
# md5: 737667fea08e49f39f1ae66bfe5a2ccd
# coding: utf-8
from memoized import memoized
import cPickle as pickle
import os
import json
@memoized
def getSeekChainsFast(lecture_id):
pfile = '/lfs/local/0/geza/seek_chains_' + str(lecture_id) + '.pickle'
if not os.path.exists(pfile):
raise 'file does not exist: ' + pfile
return pickle.load(open(pfile))
@memoized
def getPartsPlayedFast(lecture_id):
jfile = '/lfs/local/0/geza/video_to_parts_played.json'
if not os.path.exists(jfile):
raise 'file does not exist: ' + jfile
return json.load(open(jfile))[str(lecture_id)]
| 25.458333 | 72 | 0.738134 |
860f48c705e8958e97c8dfa3a708ab2ab42b5819 | 4,188 | rb | Ruby | RUBY/language/language_other_file.rb | lemming-life/Snippets | 796d34f3d33cb0e38d38197938bc36397ce8a27b | [
"Unlicense"
] | null | null | null | RUBY/language/language_other_file.rb | lemming-life/Snippets | 796d34f3d33cb0e38d38197938bc36397ce8a27b | [
"Unlicense"
] | null | null | null | RUBY/language/language_other_file.rb | lemming-life/Snippets | 796d34f3d33cb0e38d38197938bc36397ce8a27b | [
"Unlicense"
] | null | null | null | puts "Executing language_other_file.rb"
# A class
class Shape
def initialize
@x = 0 # member variable
@y = 0 # member variable
end
def set_x(new_x)
@x = new_x
end
def get_x()
return @x # Explicit return
end
def set_y(new_y)
@y = new_y
end
def get_y # No need for ()
@y # Implicit return
end
# Setter (can be used to verify that data compatible)
def x=(new_x)
@x = new_x if new_x.is_a?(Numeric)
end
# Getter
def x
@x # implicit return
end
def y=(new_y)
@y = new_y if new_y.is_a?(Numeric)
end
def y
@y
end
def get_area
return 0
end
end
# Create an object
shape = Shape.new
shape.set_x(1) # Use a method, pass a value
shape.get_x # Use a method to get
shape.x = 5 # Use the setter
shape.x # Use the getter
# Class using inheritance
class Circle < Shape
#attr_reader :radius, :area # Getters
#attr_writer :radius :area # Setters
attr_accessor :radius, :color # Both getter and setter
def initialize
radius = 1
end
# Override get_area of Shape
def get_area
return 3.14 * radius.to_f
end
end
class Rectangle < Shape
attr_accessor :height, :width
def initialize
height = 1
width = 1
end
def get_area
return width.to_f * height.to_f
end
end
circle = Circle.new
circle.x = 1 # Uses the x setter from Shape
circle.y = -1
circle.radius = 2
circle.get_area # 6.28
# Allows us to use the StopWatch module
require_relative "stopwatch"
module Phone
def play_ringtone
puts "ring, ring..."
end
def vibrate
puts "brrr"
end
end
class FancyPhone
include Phone
# Include StopWatch methods in the Phone
include StopWatch
end
fancyPhone = FancyPhone.new
fancyPhone.play_ringtone
fancyPhone.start_stop_watch
fancyPhone.output_stop_watch
fancyPhone.stop_stop_watch
class NotFancyPhone
prepend Phone
# Note how vibrate is a method in both Phone and NotFancyPhone
# the preprend Phone means that the Phone one will be used instead of the NotFancyPhone
def vibrate
puts "no vibrate"
end
end
noFancyPhone = NotFancyPhone.new
noFancyPhone.vibrate # brrr
# Symbols (no value given)
:a_symbol
# Enumeration
class Colors
include Enumerable
def each
yield "red"
yield "green"
yield "blue"
end
end
colors = Colors.new
colors.each do |color|
aColor = color
end
colors.first # red
colors.find{ |color| color = "red" }.to_s # "red"
colors.select { |color| color.size <=4 } # ["red", "blue"]
colors.reject { |color| color.size >=4 } # ["red"]
colors.min # blue
colors.max # red
colors.sort #["blue", "green", "red"]
colors.reverse_each { |color| aColor = color} # blue, green, red
# Open classes allow us to
# have more class instance member additions
# even though class Colors was already defined.
# You can do this with any class, and you could
# modify some very essential classes, this is called "moneky patching"
class Colors
def some_other_method
end
end
# Duck Typing
# if it behaves like a duck then it is a duck
# all of Ruby is done this way, which is quite different
# from static typed languages...
class Animal
def do_quack(maybe_a_duck)
# as long as whatever is passed has a quack method
# it is ok to have here
maybe_a_duck.quack()
end
end
class Duck
def quack
puts "quack from Duck"
end
end
class Person
#Notice how Person has a quack method
def quack
puts "quack from Person"
end
end
Animal.new.do_quack(Duck.new) # ok
Animal.new.do_quack(Person.new) # also ok
# Here's an example of using methodName=
class Something
def setter=(x)
@x = x
end
end
# We can now do this:
something = Something.new
something.setter=(5)
something.setter = 5 # Same as above
# Classes are "open" so we can add more
# methods and variables to a class.
# The additions can be in any file.
class Something
def more_stuff
end
end | 18.780269 | 91 | 0.644222 |
5baa6413f907f043c816d5e15fcad40b1f16ee1e | 2,390 | css | CSS | style.css | Ciph3r007/Resume-with-HTML-CSS | bc35785515dd3d4d7580bbc74bc0ff78f4bbe72e | [
"MIT"
] | null | null | null | style.css | Ciph3r007/Resume-with-HTML-CSS | bc35785515dd3d4d7580bbc74bc0ff78f4bbe72e | [
"MIT"
] | null | null | null | style.css | Ciph3r007/Resume-with-HTML-CSS | bc35785515dd3d4d7580bbc74bc0ff78f4bbe72e | [
"MIT"
] | null | null | null | html {
font-size: 62.5%;
}
body {
background-color: whitesmoke;
}
* {
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen,
Ubuntu, Cantarell, "Open Sans", "Helvetica Neue", sans-serif;
margin: 0;
padding: 0;
}
main {
background-color: white;
width: 70vh;
margin: auto;
box-shadow: 0px 0px 100px grey;
padding: 3rem;
margin-top: 1rem;
margin-bottom: 1rem;
}
.header {
display: flex;
justify-content: space-between;
}
#name {
font-weight: bold;
font-size: 265%;
margin-bottom: 0.8rem;
}
#job {
color: grey;
font-style: italic;
font-weight: 700;
margin-bottom: 1.5em;
}
.info {
display: flex;
margin-left: 0px;
}
.info-icon {
margin-right: 1rem;
}
.info-item {
margin-top: 0.5rem;
margin-right: 4rem;
line-height: 0.5rem;
}
figure {
margin-left: auto;
}
img {
width: 13rem;
max-width: 100%;
height: auto;
border-radius: 100%;
}
a {
color: black;
text-decoration: none;
}
a:visited {
color: navy;
}
a:hover,
a:focus,
#no-link:hover {
color: dodgerblue;
}
.segment-wrapper {
margin-top: 1rem;
display: grid;
grid-template-columns: 2fr 1fr;
}
.seg-header {
margin-top: 2rem;
font-size: 200%;
font-weight: bold;
text-transform: uppercase;
}
hr {
border: 2px solid black;
border-radius: 1px;
}
.segment-col-left {
flex: auto;
margin-right: 3rem;
}
.title {
margin-top: 1.5rem;
margin-bottom: 0.5rem;
}
.descr {
color: grey;
font-size: 150%;
margin-bottom: 3rem;
}
#summary {
font-size: 150%;
font-style: italic;
margin-top: 1.5rem;
margin-bottom: 2rem;
}
#qualification {
margin-top: 1.5rem;
font-size: 150%;
margin-bottom: 0.5rem;
}
.entity-name {
font-weight: bold;
font-size: 120%;
}
#location {
margin-top: 0.5rem;
margin-bottom: 2rem;
}
.skill {
margin-top: 5px;
display: flex;
}
.skillbar {
margin-left: auto;
margin-top: 0.4rem;
margin-bottom: 0.4rem;
width: 35%;
height: 5px;
border-radius: 1rem;
display: flex;
}
.skill-ratio {
margin-right: auto;
background-image: linear-gradient(
to right,
#838383,
#616161,
#414141,
#232323,
#000000
);
border-radius: 1rem;
}
#skill-60 {
width: 60%;
}
#skill-80 {
width: 80%;
}
#skill-100 {
width: 100%;
}
.bullets {
margin-bottom: 0.5rem;
margin-left: 1em;
}
.bullets:first-of-type {
margin-top: 1rem;
}
| 12.578947 | 77 | 0.621757 |
2368f45ea0eb267305984b789cf0f979c7ce7e74 | 261 | kt | Kotlin | app/src/main/java/com/cleteci/redsolidaria/models/User.kt | JusticeInternational/RedSol-android | 766168e2c5655f36e0e1898542f8ccb831d7da75 | [
"MIT"
] | 1 | 2020-04-04T00:08:58.000Z | 2020-04-04T00:08:58.000Z | app/src/main/java/com/cleteci/redsolidaria/models/User.kt | JusticeInternational/RedSol-android | 766168e2c5655f36e0e1898542f8ccb831d7da75 | [
"MIT"
] | 4 | 2020-05-25T15:45:28.000Z | 2021-06-21T18:08:09.000Z | app/src/main/java/com/cleteci/redsolidaria/models/User.kt | JusticeInternational/RedSol-android | 766168e2c5655f36e0e1898542f8ccb831d7da75 | [
"MIT"
] | 1 | 2020-04-04T00:09:08.000Z | 2020-04-04T00:09:08.000Z | package com.cleteci.redsolidaria.models
data class User(val id: String,
val name: String,
val role: String,
val email:String,
val password: String? ="",
val lastName:String? =""
)
| 26.1 | 42 | 0.509579 |
a3cfa0bffeb24577d8bd7c0bf2fe95ae3538f524 | 2,389 | java | Java | src/main/java/me/acidviper/viperuhc/command/HelpopReplyCommand.java | AcidicViper/ViperUHC | 01791b208321a16bc4640d8b744c9d77dbcc8063 | [
"Unlicense"
] | null | null | null | src/main/java/me/acidviper/viperuhc/command/HelpopReplyCommand.java | AcidicViper/ViperUHC | 01791b208321a16bc4640d8b744c9d77dbcc8063 | [
"Unlicense"
] | null | null | null | src/main/java/me/acidviper/viperuhc/command/HelpopReplyCommand.java | AcidicViper/ViperUHC | 01791b208321a16bc4640d8b744c9d77dbcc8063 | [
"Unlicense"
] | null | null | null | package me.acidviper.viperuhc.command;
import lombok.Getter;
import me.acidviper.viperuhc.player.UHCPlayer;
import net.md_5.bungee.api.chat.ClickEvent;
import net.md_5.bungee.api.chat.ComponentBuilder;
import net.md_5.bungee.api.chat.HoverEvent;
import net.md_5.bungee.api.chat.TextComponent;
import org.bukkit.ChatColor;
import org.bukkit.Sound;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import java.util.*;
public class HelpopReplyCommand implements CommandExecutor {
public boolean onCommand(CommandSender sender, Command command, String s, String[] args) {
if (!(sender instanceof Player)) {
sender.sendMessage(ChatColor.translateAlternateColorCodes('&', "&f[&6ViperUHC&f] &fYou must be a player to use this command."));
return false;
}
Player p = (Player) sender;
if (!p.hasPermission("uhc.helpop")) {
p.sendMessage(ChatColor.translateAlternateColorCodes('&', "&f[&6ViperUHC&f] &fNo Permission."));
return false;
}
if (args.length < 2) {
sender.sendMessage(ChatColor.translateAlternateColorCodes('&', "&cUsage: /helpopreply <id> <message>"));
return false;
}
int ID = 0;
try { ID = Integer.parseInt(args[0]); } catch (Exception e) {
sender.sendMessage(ChatColor.translateAlternateColorCodes('&', "&cUsage: /helpopreply <id> <message>"));
return false;
}
Player helpoper = HelpopCommand.getHelpopIds().get(ID);
if (!helpoper.isOnline()) {
sender.sendMessage(ChatColor.translateAlternateColorCodes('&', "&cThat player is no longer online!"));
return false;
}
List<String> helpopResponseMessage = new ArrayList<>(Arrays.asList(args));
helpopResponseMessage.remove(0);
String cleanedMessage = helpopResponseMessage.toString().replaceAll(", ", " ").replaceAll("\\[", "").replaceAll("]", "");
helpoper.sendMessage(ChatColor.translateAlternateColorCodes('&', ChatColor.translateAlternateColorCodes('&', "&f[&6HelpOp&f] &6" + ((Player) sender).getDisplayName() + ": &f" + cleanedMessage)));
helpoper.playSound(helpoper.getLocation(), Sound.valueOf("ORB_PICKUP"), .2f, 1);
return false;
}
}
| 39.816667 | 203 | 0.667225 |
bb21d0967719b23e586509318670ab2b537422ca | 841 | asm | Assembly | oeis/142/A142429.asm | neoneye/loda-programs | 84790877f8e6c2e821b183d2e334d612045d29c0 | [
"Apache-2.0"
] | 11 | 2021-08-22T19:44:55.000Z | 2022-03-20T16:47:57.000Z | oeis/142/A142429.asm | neoneye/loda-programs | 84790877f8e6c2e821b183d2e334d612045d29c0 | [
"Apache-2.0"
] | 9 | 2021-08-29T13:15:54.000Z | 2022-03-09T19:52:31.000Z | oeis/142/A142429.asm | neoneye/loda-programs | 84790877f8e6c2e821b183d2e334d612045d29c0 | [
"Apache-2.0"
] | 3 | 2021-08-22T20:56:47.000Z | 2021-09-29T06:26:12.000Z | ; A142429: Primes congruent to 18 mod 49.
; Submitted by Jon Maiga
; 67,263,557,1439,1733,1831,2027,2713,2909,3203,3301,3889,4673,4967,5261,5653,5849,6143,6829,7417,7907,8887,9181,9377,9769,10259,10357,10651,10847,11239,11827,12611,13003,13297,13591,14081,14669,14767,15061,15551,15649,16139,16433,17021,17609,17707,17903,19079,19373,19471,19961,20353,20549,21529,22901,23293,24077,24371,24469,24763,25057,25253,25841,25939,26723,26821,27017,27409,27997,28879,29173,29663,29761,30643,30839,30937,31231,31721,32309,32603,33191,33289,34171,34367,34759,35053,35543,35837
mov $1,33
mov $2,$0
add $2,2
pow $2,2
lpb $2
sub $2,1
mov $3,$1
add $1,13
mul $3,2
seq $3,10051 ; Characteristic function of primes: 1 if n is prime, else 0.
sub $0,$3
add $1,36
mov $4,$0
max $4,0
cmp $4,$0
mul $2,$4
lpe
mov $0,$1
mul $0,2
sub $0,97
| 33.64 | 500 | 0.727705 |
db7b894f2adb86746cff509916600046f8da0a23 | 4,908 | php | PHP | app/Language/sk/HTTP.php | peppers96/InventorySystem | af3f125c88fcc43d1876e563890a711523c0f00b | [
"MIT"
] | 18 | 2020-10-05T12:35:05.000Z | 2022-02-11T11:53:29.000Z | app/Language/sk/HTTP.php | peppers96/InventorySystem | af3f125c88fcc43d1876e563890a711523c0f00b | [
"MIT"
] | 1 | 2022-03-31T20:39:46.000Z | 2022-03-31T20:39:46.000Z | app/Language/sk/HTTP.php | peppers96/InventorySystem | af3f125c88fcc43d1876e563890a711523c0f00b | [
"MIT"
] | 7 | 2021-05-08T15:31:59.000Z | 2022-02-03T15:49:18.000Z | <?php
/**
* HTTP language strings.
*
* This content is released under the MIT License (MIT)
*
* Copyright (c) 2014-2019 British Columbia Institute of Technology
* Copyright (c) 2019-2020 CodeIgniter Foundation
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
* @package CodeIgniter
* @author Jozef Botka - xbotkaj on Github
* @copyright 2019-2020 CodeIgniter Foundation
* @license https://opensource.org/licenses/MIT MIT License
* @link https://codeigniter.com
* @since Version 4.0.0
* @filesource
*
* @codeCoverageIgnore
*/
return [
// CurlRequest
'missingCurl' => 'Aby bolo možné používať triedu CURLRequest, musí byť povolená funkcia CURL.',
'invalidSSLKey' => 'Nie je možné nastaviť kľúč SSL. {0} nie je platný súbor.',
'sslCertNotFound' => 'SSL certifikát nebol nájdený na: {0}',
'curlError' => '{0} : {1}',
// IncomingRequest
'invalidNegotiationType' => '{0} nie je platný typ vyjednávania. Musí to byť: médium, znaková sada, kódovanie alebo jazyk.',
// Message
'invalidHTTPProtocol' => 'Neplatná verzia protokolu HTTP. Musí to byť jedno z: {0}',
// Negotiate
'emptySupportedNegotiations' => 'Musíte poskytnúť pole podporovaných hodnôt pre všetky negotiations.',
// RedirectResponse
'invalidRoute' => '{0} trasu nemožno nájsť pri spätnom smerovaní.',
// DownloadResponse
'cannotSetBinary' => 'Pri nastavovaní filepath nie je možné nastaviť binary.',
'cannotSetFilepath' => 'Pri nastavovaní binary nie je možné nastaviť filepath: {0}',
'notFoundDownloadSource' => 'Not found download body source.',
'cannotSetCache' => 'Nepodporuje ukladanie do vyrovnávacej pamäte pre sťahovanie.',
'cannotSetStatusCode' => 'Nepodporuje stavový kód chnage na stiahnutie. kód: {0}, dôvod: {1}',
// Response
'missingResponseStatus' => 'V odpovedi HTTP chýba stavový kód',
'invalidStatusCode' => '{0} nie je platný návratový stavový kód HTTP',
'unknownStatusCode' => 'Neznámy stavový kód HTTP poskytnutý bez správy: {0}',
// URI
'cannotParseURI' => 'Nemožno analyzovať URI: {0}',
'segmentOutOfRange' => 'Segment URI žiadosti je mimo rozsahu: {0}',
'invalidPort' => 'Porty musia byť medzi 0 a 65535. Zadaný: {0}',
'malformedQueryString' => 'Reťazce dopytov nemusia obsahovať fragmenty URI.',
// Page Not Found
'pageNotFound' => 'Stránka sa nenašla',
'emptyController' => 'Nie je zadaný žiadny Controller.',
'controllerNotFound' => 'Controller alebo jeho metóda sa nenašla: {0}::{1}',
'methodNotFound' => 'Metóda Controller-u sa nenašla: {0}',
// CSRF
'disallowedAction' => 'Požadovaná akcia nie je povolená.',
// Uploaded file moving
'alreadyMoved' => 'Nahraný súbor už bol presunutý.',
'invalidFile' => 'Pôvodný súbor nie je platný.',
'moveFailed' => 'Nepodarilo sa presunúť súbor z {0} do {1} ({2})',
'uploadErrOk' => 'Súbor bol úspešne odovzdaný.',
'uploadErrIniSize' => 'Súbor "%s" prekračuje vašu direktívu upload_max_filesize ini.',
'uploadErrFormSize' => 'Súbor "%s" prekračuje limit pre upload stanovený vo vašom formulári.',
'uploadErrPartial' => 'Súbor "%s" bol nahraný iba čiastočne.',
'uploadErrNoFile' => 'Nebol nahraný žiaden súbor.',
'uploadErrCantWrite' => 'Súbor "%s" sa nedal zapísať na disk.',
'uploadErrNoTmpDir' => 'Súbor sa nepodarilo nahrať: chýba dočasný adresár.',
'uploadErrExtension' => 'Nahrávanie súborov bolo zastavené rozšírením PHP.',
'uploadErrUnknown' => 'Súbor "%s" nebol nahraný kvôli neznámej chybe.',
];
| 48.594059 | 131 | 0.658109 |
b368bf296dbdcc636fab9eb58ef641d1b9f373aa | 5,735 | py | Python | stepperModule.py | nathrun/Stepper-motor-controller | d77aa21691fe441685db429e178c42c1d3195003 | [
"MIT"
] | null | null | null | stepperModule.py | nathrun/Stepper-motor-controller | d77aa21691fe441685db429e178c42c1d3195003 | [
"MIT"
] | null | null | null | stepperModule.py | nathrun/Stepper-motor-controller | d77aa21691fe441685db429e178c42c1d3195003 | [
"MIT"
] | null | null | null | #---Documentation---------------------------------------------------------------
# This module was designed to run with a L298N h-bridge module. I created this
# in my spare time and did not test extensively so there might be bugs
# def __init__:
# params - motorPinsArray is an array that contains the GPIO pins that go to
# these inputs -> [IN1,IN2,IN3,IN4]
# - stepsPerRevolution is the amount of steps your stepper motor
# requires to do a single revolution
# - defaultRPM -> pretty obvious... can be either an integer or float
#
# def setDefaultRPM:
# params -defaultRPM -> new default rpm for object, can be either an
# integer or float
# will return True if operation happened successfully
#
# def spinMotor:
# params - numRevolution is a float that indicates exactly how many
# revolution you would like the stepper motor to turn. If negative,
# the motor will turn in the opposite direction.
# - stepPhase (optional, default='dual'), refers to either 'single'
# phase stepping or 'dual' phase stepping
# (dual phase, both coils will always be engaged)
# - stepType (optional, default='full'), can only be used of stepPhase
# is equal to 'dual'.
# - rpm (optional), if you want to set a temporary rpm,
# either an integer or float
#-------------------------------------------------------------------------------
import time
import RPi.GPIO as GPIO
class stepperController(object):
#array that rearanges the format of the pins to be used on an L298N h-bridge
pinShuffle = [0,3,1,2]
#dualPhaseStepping[0] for half stepping
#dualPhaseStepping[1] for full stepping
#can not do half stepping on singlePhaseStepping
singlePhaseStepping = [
[1,0,0,0],
[0,1,0,0],
[0,0,1,0],
[0,0,0,1]
]
dualPhaseStepping = [
[
[1,1,0,0],
[0,1,1,0],
[0,0,1,1],
[1,0,0,1]
],
[
[1,0,0,0],
[1,1,0,0],
[0,1,0,0],
[0,1,1,0],
[0,0,1,0],
[0,0,1,1],
[0,0,0,1],
[1,0,0,1]
]
]
def __init__(self,motorPinsArray, stepsPerRevolution, defaultRPM): #<-- needs to be tested
self.pins = motorPinsArray
self.stepsInRevolution = stepsPerRevolution
self.d_RPM = defaultRPM
#add some checks for the values entered
if(type(self.pins) != list):
#send exception
print('please enter list')
if (type(self.stepsInRevolution) != int):
print('stepsPerRevolution must be an integer value')
if (type(self.d_RPM) != int and type(self.d_RPM) != float):
print('defaultRPM must be an integer value')
#---end of def __init__-----------------------------------------------------
#Function returns a bool, False if any arguments are not correct
#and True once the stepper motor has completed spinning.
def spinMotor(self, numRevolution, stepPhase="dual", stepType='full', rpm=0): #<-- needs to be tested
if(stepPhase != 'dual' and stepPhase != 'single'):
return 'stepPhase must equal "single" or "dual"'
#should change to throw exception as well for more detail
if(stepType != 'half' and stepType != 'full'):
return 'stepType must equal "half" or "full"'
#should change to throw exception as well for more detail
curSeq = []
steps = self.stepsInRevolution
if(stepPhase == 'single'):
if(stepType == 'half'):
print('can not do half steps on single phase stepping. defualted to full steps')
curSeq = self.singlePhaseStepping
elif(stepType == 'half'):
curSeq = self.dualPhaseStepping[1]
steps = steps*2
else:
curSeq = self.dualPhaseStepping[0]
if (rpm==0):
stepBreak = 60.0/(steps*self.d_RPM)
else:
stepBreak = 60.0/(steps*rpm)
#if numRevolution < 0, reverse curSeq and change numRevolution to possitive
if (numRevolution < 0):
curSeq.reverse()
numRevolution *= -1
print 'DEBUG curSeq'
print curSeq
print 'DEBUG end'
if (numRevolution ==0):
return True #skip irrelavant setup and gpio.cleanup
#assign GPIO pins here
if(GPIO.getmode != GPIO.BCM):
GPIO.setmode(GPIO.BCM)
for pin in self.pins:
GPIO.setup(pin, GPIO.OUT, initial=GPIO.LOW)
#make for loop to run through curSeq to make motor spin the correct amount of times
phase = 0
for x in range(int(round(steps*numRevolution))):
for pin in range(4):
GPIO.output(self.pins[self.pinShuffle[pin]], curSeq[phase][pin])
time.sleep(stepBreak)
phase += 1
if(phase >= len(curSeq)):
phase = 0
#end of turning phase
#set pins to LOW
for pin in self.pins:
GPIO.output(pin,0)
GPIO.cleanup()
return True
#---end of def spinMotor()------------------------------------------------------
def setDefaultRPM(self, defaultRPM):
result = True if(type(defaultRPM)==int or type(defaultRPM)== float) else 'defaultRPM must be an integer or a float'
if result==True:
self.d_RPM = defaultRPM
return result
| 39.280822 | 124 | 0.53932 |
286ae5affe11e7fd941f955ee584d55deb9b672e | 3,845 | sql | SQL | hasura/migrations/1610443601512_create_relevant_indexes/up.sql | LasseWolter/clowdr | 4777fc8386a7cd4f09b7a366ccd01662608c3e01 | [
"BSD-3-Clause"
] | 49 | 2021-01-09T07:09:08.000Z | 2022-03-27T05:16:46.000Z | hasura/migrations/1610443601512_create_relevant_indexes/up.sql | LasseWolter/clowdr | 4777fc8386a7cd4f09b7a366ccd01662608c3e01 | [
"BSD-3-Clause"
] | 333 | 2021-01-17T14:52:22.000Z | 2022-03-10T02:38:53.000Z | hasura/migrations/1610443601512_create_relevant_indexes/up.sql | LasseWolter/clowdr | 4777fc8386a7cd4f09b7a366ccd01662608c3e01 | [
"BSD-3-Clause"
] | 15 | 2021-01-29T14:17:38.000Z | 2022-02-14T22:13:48.000Z | /* Conference by slug */
CREATE INDEX IF NOT EXISTS slug ON "Conference" ("slug") INCLUDE ("id", "name", "shortName");
CREATE INDEX IF NOT EXISTS creator_id ON "Conference" ("createdBy") INCLUDE ("id");
/* Group attendee */
CREATE INDEX IF NOT EXISTS group_id ON "GroupAttendee" ("groupId") INCLUDE ("attendeeId");
CREATE INDEX IF NOT EXISTS attendee_id ON "GroupAttendee" ("attendeeId") INCLUDE ("groupId");
/* Group role */
CREATE INDEX IF NOT EXISTS group_id ON "GroupRole" ("groupId") INCLUDE ("roleId");
CREATE INDEX IF NOT EXISTS role_id ON "GroupRole" ("roleId") INCLUDE ("groupId");
/* Group */
CREATE INDEX IF NOT EXISTS conference_id ON "Group" ("conferenceId", "enabled", "includeUnauthenticated") INCLUDE ("id");
/* Role permission */
CREATE INDEX IF NOT EXISTS group_id ON "RolePermission" ("roleId") INCLUDE ("permissionName");
CREATE INDEX IF NOT EXISTS role_id ON "RolePermission" ("permissionName") INCLUDE ("roleId");
/* "X by conference id" */
CREATE INDEX IF NOT EXISTS conference_id ON "Attendee" ("conferenceId") INCLUDE ("displayName");
CREATE INDEX IF NOT EXISTS conference_id ON "ContentGroup" ("conferenceId");
CREATE INDEX IF NOT EXISTS conference_id ON "Tag" ("conferenceId");
CREATE INDEX IF NOT EXISTS conference_id ON "Room" ("conferenceId");
CREATE INDEX IF NOT EXISTS conference_id ON "RoomParticipant" ("conferenceId");
CREATE INDEX IF NOT EXISTS conference_id ON "ConferencePrepareJob" ("conferenceId");
CREATE INDEX IF NOT EXISTS conference_id ON "Transitions" ("conferenceId");
/* Room by vonage session */
CREATE INDEX IF NOT EXISTS vonage_session_id ON "Room" ("publicVonageSessionId") INCLUDE ("id");
/* Room person by room id */
CREATE INDEX IF NOT EXISTS room_id ON "RoomPerson" ("roomId") INCLUDE ("attendeeId") WITH (fillfactor = 40);
/* Room by privacy */
CREATE INDEX IF NOT EXISTS privacy ON "Room" ("roomPrivacyName");
/* Attendee by user id */
CREATE INDEX IF NOT EXISTS user_id ON "Attendee" ("userId");
/* Content group by type */
CREATE INDEX IF NOT EXISTS type_name ON "ContentGroup" ("contentGroupTypeName");
/* Content group tag by tag */
CREATE INDEX IF NOT EXISTS tag_id ON "ContentGroupTag" ("tagId") INCLUDE ("contentGroupId");
/* Content group tag by group */
CREATE INDEX IF NOT EXISTS group_id ON "ContentGroupTag" ("contentGroupId") INCLUDE ("tagId");
/* Content group hallway by group */
CREATE INDEX IF NOT EXISTS group_id ON "ContentGroupHallway" ("groupId");
/* Content group person by group */
CREATE INDEX IF NOT EXISTS group_id ON "ContentGroupPerson" ("groupId");
/* Content item by group */
CREATE INDEX IF NOT EXISTS group_id ON "ContentItem" ("contentGroupId");
/* Event by content group */
CREATE INDEX IF NOT EXISTS group_id ON "Event" ("contentGroupId");
/* Event by room */
CREATE INDEX IF NOT EXISTS room_id ON "Event" ("roomId");
/* Event person by event */
CREATE INDEX IF NOT EXISTS event_id ON "EventPerson" ("eventId");
/* Event tag by event */
CREATE INDEX IF NOT EXISTS event_id ON "EventTag" ("eventId");
/* Event participant stream by event */
CREATE INDEX IF NOT EXISTS event_id ON "EventParticipantStream" ("eventId") WITH (fillfactor = 40);
/* Event room join request */
CREATE INDEX IF NOT EXISTS all_ids ON "EventRoomJoinRequest" ("conferenceId", "eventId", "attendeeId") INCLUDE ("approved") WITH (fillfactor = 40);
/* Invitation by invite code */
CREATE INDEX IF NOT EXISTS event_id ON "Invitation" ("inviteCode");
/* Transition by room */
CREATE INDEX IF NOT EXISTS room_id ON "Transitions" ("roomId");
/* Event specialisms */
CREATE INDEX IF NOT EXISTS intended_mode ON "Event" ("intendedRoomModeName");
CREATE INDEX IF NOT EXISTS events_in_range ON "Event" ("intendedRoomModeName", "endTime", "startTime");
/* Event vonage session by session id */
CREATE INDEX IF NOT EXISTS session_id ON "EventVonageSession" ("sessionId");
| 44.709302 | 147 | 0.736801 |
93f9b3e440124c17c4520fca3f653efe6ba4bf3e | 262 | cs | C# | Menu/Models/Toppings.cs | 4rgc/TouhenbokuMenu | 59ca51119011a48c68374673991a64b716fbc70c | [
"MIT"
] | null | null | null | Menu/Models/Toppings.cs | 4rgc/TouhenbokuMenu | 59ca51119011a48c68374673991a64b716fbc70c | [
"MIT"
] | null | null | null | Menu/Models/Toppings.cs | 4rgc/TouhenbokuMenu | 59ca51119011a48c68374673991a64b716fbc70c | [
"MIT"
] | null | null | null | using System;
using System.Collections.Generic;
namespace Menu.Models
{
public partial class Toppings
{
public long ToppingId { get; set; }
public string ToppingName { get; set; }
public long? ToppingPrice { get; set; }
}
}
| 20.153846 | 47 | 0.637405 |
23d66b8c3fda4422fa9370a1c986c4f9ccae8ccc | 5,861 | js | JavaScript | public/66.js | rohiabdulloh/tokoonline_react_laravel_inertia | 0eab34177ad98ef963cebf8196561299fb1028a1 | [
"MIT"
] | null | null | null | public/66.js | rohiabdulloh/tokoonline_react_laravel_inertia | 0eab34177ad98ef963cebf8196561299fb1028a1 | [
"MIT"
] | null | null | null | public/66.js | rohiabdulloh/tokoonline_react_laravel_inertia | 0eab34177ad98ef963cebf8196561299fb1028a1 | [
"MIT"
] | null | null | null | (window["webpackJsonp"] = window["webpackJsonp"] || []).push([[66],{
/***/ "./resources/js/Pages/Front/Detail.js":
/*!********************************************!*\
!*** ./resources/js/Pages/Front/Detail.js ***!
\********************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! react */ "./node_modules/react/index.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var react_helmet__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! react-helmet */ "./node_modules/react-helmet/es/Helmet.js");
/* harmony import */ var _inertiajs_inertia_react__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @inertiajs/inertia-react */ "./node_modules/@inertiajs/inertia-react/dist/index.js");
/* harmony import */ var _inertiajs_inertia_react__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_inertiajs_inertia_react__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var _material_ui_core_Grid__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @material-ui/core/Grid */ "./node_modules/@material-ui/core/esm/Grid/index.js");
/* harmony import */ var _material_ui_core_Typography__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! @material-ui/core/Typography */ "./node_modules/@material-ui/core/esm/Typography/index.js");
/* harmony import */ var _material_ui_core_Button__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! @material-ui/core/Button */ "./node_modules/@material-ui/core/esm/Button/index.js");
/* harmony import */ var _material_ui_icons_ShoppingCart__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! @material-ui/icons/ShoppingCart */ "./node_modules/@material-ui/icons/ShoppingCart.js");
/* harmony import */ var _material_ui_icons_ShoppingCart__WEBPACK_IMPORTED_MODULE_6___default = /*#__PURE__*/__webpack_require__.n(_material_ui_icons_ShoppingCart__WEBPACK_IMPORTED_MODULE_6__);
/* harmony import */ var react_currency_format__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! react-currency-format */ "./node_modules/react-currency-format/lib/currency-format.js");
/* harmony import */ var react_currency_format__WEBPACK_IMPORTED_MODULE_7___default = /*#__PURE__*/__webpack_require__.n(react_currency_format__WEBPACK_IMPORTED_MODULE_7__);
/* harmony import */ var _Shared_FrontLayout__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./../../Shared/FrontLayout */ "./resources/js/Shared/FrontLayout.js");
var Detail = function Detail(props) {
var produk = props.produk;
return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(_Shared_FrontLayout__WEBPACK_IMPORTED_MODULE_8__["default"], null, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(react_helmet__WEBPACK_IMPORTED_MODULE_1__["default"], null, produk != null ? /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("title", null, produk.nama_produk) : /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("title", null, "Detail Produk")), produk == null && /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(_material_ui_core_Typography__WEBPACK_IMPORTED_MODULE_4__["default"], {
variant: "h4"
}, "Produk tidak ditemukan"), produk != null && /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(_material_ui_core_Grid__WEBPACK_IMPORTED_MODULE_3__["default"], {
container: true,
spacing: 4
}, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(_material_ui_core_Grid__WEBPACK_IMPORTED_MODULE_3__["default"], {
item: true,
sm: 4,
xs: 12
}, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("img", {
src: "/images/" + produk.foto,
title: produk.nama_produk,
width: "100%"
})), /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(_material_ui_core_Grid__WEBPACK_IMPORTED_MODULE_3__["default"], {
item: true,
sm: 8,
xs: 12
}, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("h4", null, produk.nama_produk), /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("p", null, produk.deskripsi_produk), "Berat ", produk.berat, " Kg", /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("br", null), "Stok ", produk.stok, " ", /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("br", null), /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("h4", null, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(react_currency_format__WEBPACK_IMPORTED_MODULE_7___default.a, {
value: produk.harga,
displayType: 'text',
thousandSeparator: true,
prefix: 'Rp. '
})), produk.stok > 0 ? /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(_material_ui_core_Button__WEBPACK_IMPORTED_MODULE_5__["default"], {
component: _inertiajs_inertia_react__WEBPACK_IMPORTED_MODULE_2__["InertiaLink"],
href: route('keranjang.add', produk.id),
variant: "contained",
color: "primary",
startIcon: /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(_material_ui_icons_ShoppingCart__WEBPACK_IMPORTED_MODULE_6___default.a, null)
}, "Tambah ke keranjang") : /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(_material_ui_core_Button__WEBPACK_IMPORTED_MODULE_5__["default"], {
variant: "contained",
color: "secondary"
}, "Stok habis"))));
};
/* harmony default export */ __webpack_exports__["default"] = (Detail);
/***/ })
}]); | 78.146667 | 673 | 0.773247 |
c972dca30701febf2811f46a57f15bcaa2065b8c | 213 | ts | TypeScript | packages/packer/src/pack.function.ts | blacha/shockr-layout | 62eb155b5af5d71ccaf78de329723d59c85a4b9a | [
"MIT"
] | null | null | null | packages/packer/src/pack.function.ts | blacha/shockr-layout | 62eb155b5af5d71ccaf78de329723d59c85a4b9a | [
"MIT"
] | 125 | 2020-02-12T17:24:06.000Z | 2020-07-16T19:33:46.000Z | packages/packer/src/pack.function.ts | blacha/shockr-layout | 62eb155b5af5d71ccaf78de329723d59c85a4b9a | [
"MIT"
] | null | null | null | import { pack } from './pack';
pack('./packages/st-backend/build/index.js', './functions/lib/index.js', [
'firebase-admin',
'firebase-functions',
'cors',
'express',
]).catch(e => console.log(e));
| 23.666667 | 74 | 0.600939 |
46bc6e014ceff50e1fe3f894d2a908d7857dd78a | 615 | py | Python | kick/device2/series3/actions/dialogs.py | CiscoDevNet/firepower-kickstart | 37a36856fcdc661e8c51edaa694e48f74cc6fcb5 | [
"Apache-2.0"
] | 2 | 2020-02-10T23:36:57.000Z | 2020-03-25T15:46:05.000Z | kick/device2/series3/actions/dialogs.py | CiscoDevNet/firepower-kickstart | 37a36856fcdc661e8c51edaa694e48f74cc6fcb5 | [
"Apache-2.0"
] | 1 | 2020-08-07T13:01:32.000Z | 2020-08-07T13:01:32.000Z | kick/device2/series3/actions/dialogs.py | CiscoDevNet/firepower-kickstart | 37a36856fcdc661e8c51edaa694e48f74cc6fcb5 | [
"Apache-2.0"
] | 1 | 2020-02-19T13:58:35.000Z | 2020-02-19T13:58:35.000Z | from unicon.eal.dialogs import Dialog
class Series3Dialog:
def __init__(self, patterns):
self.patterns = patterns
self.ssh_connect_dialog = Dialog([
['continue connecting (yes/no)?', 'sendline(yes)', None, True, False],
#['Password:', 'sendline_ctx({})'.format(self.patterns.login_password), None, True, False],
['Password:', 'sendline_ctx(password)', None, True, False],
['Password OK', 'sendline()', None, False, False],
['Last login:', None, None, True, False],
# ['(.*Cisco.)*', None, None, False, False],
])
| 41 | 103 | 0.577236 |
0a5a788ebe9e3c5a2fa2e3a9460bf8edfa74df31 | 24,791 | cs | C# | TestSuites/FileServer/src/FSA/TestSuite/Leasing/CompareLeaseKeys.cs | G-arj/WindowsProtocolTestSuites | 58a0c33976804d3a4e9c269da3621bf5047e7be4 | [
"MIT"
] | 332 | 2019-05-14T09:46:46.000Z | 2022-03-23T19:45:34.000Z | TestSuites/FileServer/src/FSA/TestSuite/Leasing/CompareLeaseKeys.cs | xwyangjshb/WindowsProtocolTestSuites | 03b3906b9745be72b1852f7ec6ac28ca838029b6 | [
"MIT"
] | 107 | 2015-11-27T05:44:26.000Z | 2019-02-28T08:37:53.000Z | TestSuites/FileServer/src/FSA/TestSuite/Leasing/CompareLeaseKeys.cs | xwyangjshb/WindowsProtocolTestSuites | 03b3906b9745be72b1852f7ec6ac28ca838029b6 | [
"MIT"
] | 106 | 2019-05-15T02:05:55.000Z | 2022-03-25T00:52:11.000Z | // Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Linq;
using Microsoft.Protocols.TestSuites.FileSharing.Common.Adapter;
using Microsoft.Protocols.TestTools;
using Microsoft.Protocols.TestTools.StackSdk.FileAccessService.Smb2;
using Smb2 = Microsoft.Protocols.TestTools.StackSdk.FileAccessService.Smb2;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Threading.Tasks;
using Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter;
namespace Microsoft.Protocols.TestSuites.FileSharing.FSA.TestSuite.Leasing
{
public partial class LeasingTestCases : PtfTestClassBase
{
#region Variables
private Smb2FunctionalClient client1;
private Smb2FunctionalClient client2;
private string sharePath;
private uint client1TreeId;
private Smb2.FILEID client1FileId;
private uint client2TreeId;
private Smb2.FILEID client2FileId;
#endregion
#region Test Case Initialize and Clean up
protected override void TestInitialize()
{
initializeAdapter();
testConfig = fsaAdapter.TestConfig;
sharePath = Smb2Utility.GetUncPath(testConfig.SutComputerName, fsaAdapter.ShareName);
client1 = new Smb2FunctionalClient(testConfig.Timeout, testConfig, BaseTestSite);
client2 = new Smb2FunctionalClient(testConfig.Timeout, testConfig, BaseTestSite);
client1.ConnectToServer(testConfig.UnderlyingTransport, testConfig.SutComputerName, testConfig.SutIPAddress);
client2.ConnectToServer(testConfig.UnderlyingTransport, testConfig.SutComputerName, testConfig.SutIPAddress);
}
protected override void TestCleanup()
{
#region Tear Down Clients
BaseTestSite.Log.Add(LogEntryKind.TestStep, "Tear down the first client by sending the following requests: 1. CLOSE; 2. TREE_DISCONNECT; 3. LOG_OFF");
TearDownClient(client1, client1TreeId, client1FileId);
BaseTestSite.Log.Add(LogEntryKind.TestStep, "Tear down the second client by sending the following requests: 1. CLOSE; 2. TREE_DISCONNECT; 3. LOG_OFF");
TearDownClient(client2, client2TreeId, client2FileId);
#endregion
if (client1 != null)
{
client1.Disconnect();
}
if (client2 != null)
{
client2.Disconnect();
}
base.TestCleanup();
fsaAdapter.Dispose();
base.TestCleanup();
CleanupTestManager();
}
#endregion
#region Test Cases
[TestMethod]
[TestCategory(TestCategories.Fsa)]
[TestCategory(TestCategories.LeaseV1)]
[TestCategory(TestCategories.Smb21)]
[TestCategory(TestCategories.Smb30)]
[TestCategory(TestCategories.Smb302)]
[TestCategory(TestCategories.Smb311)]
[TestCategory(TestCategories.Positive)]
[Description("Compare the server returned lease keys of two opens of the same file using the same lease key")]
public void Comparing_Same_File_LeaseKeysV1()
{
CheckLeaseApplicability(DialectRevision.Smb21);
Smb2CreateRequestLease leaseRequest = createLeaseRequestContext();
Smb2CreateResponseLease client1ResponseLease;
Smb2CreateResponseLease client2ResponseLease;
InitializeClientsConnections(leaseRequest, leaseRequest, out client1ResponseLease, out client2ResponseLease);
#region Test Cases
BaseTestSite.Log.Add(LogEntryKind.TestStep, "Comparing lease keys");
BaseTestSite.Assert.AreEqual(leaseRequest.LeaseKey, client1ResponseLease.LeaseKey, "Client 1 Request Lease Key MUST be the same its Response Lease key");
BaseTestSite.Assert.AreEqual(leaseRequest.LeaseKey, client2ResponseLease.LeaseKey, "Client 2 Request Lease Key MUST be the same its Response Lease key");
BaseTestSite.Assert.AreEqual(client1ResponseLease.LeaseKey, client2ResponseLease.LeaseKey, "LeaseOpen.leaseKey MUST be the same with OperationOpen.LeaseKey");
#endregion
}
[TestMethod]
[TestCategory(TestCategories.Fsa)]
[TestCategory(TestCategories.LeaseV1)]
[TestCategory(TestCategories.Smb21)]
[TestCategory(TestCategories.Smb30)]
[TestCategory(TestCategories.Smb302)]
[TestCategory(TestCategories.Smb311)]
[TestCategory(TestCategories.Positive)]
[Description("Compare the server returned lease keys of two opens of the same directory file using the same lease key")]
public void Comparing_Same_Directory_LeaseKeysV1()
{
CheckLeaseApplicability(DialectRevision.Smb21, checkFileTypeSupport: false, checkDirectoryTypeSupport: true);
Smb2CreateRequestLease leaseRequest = createLeaseRequestContext(leaseState: LeaseStateValues.SMB2_LEASE_READ_CACHING | LeaseStateValues.SMB2_LEASE_HANDLE_CACHING);
Smb2CreateResponseLease client1ResponseLease;
Smb2CreateResponseLease client2ResponseLease;
InitializeClientsConnections(leaseRequest, leaseRequest, out client1ResponseLease, out client2ResponseLease, isBothClientDirectory: true);
#region Test Cases
BaseTestSite.Log.Add(LogEntryKind.TestStep, "Comparing lease keys");
BaseTestSite.Assert.AreEqual(leaseRequest.LeaseKey, client1ResponseLease.LeaseKey, "Client 1 Request Lease Key MUST be the same with its Response Lease key");
BaseTestSite.Assert.AreEqual(leaseRequest.LeaseKey, client2ResponseLease.LeaseKey, "Client 2 Request Lease Key MUST be the same with its Response Lease key");
BaseTestSite.Assert.AreEqual(client1ResponseLease.LeaseKey, client2ResponseLease.LeaseKey, "LeaseOpen.leaseKey MUST be the same with OperationOpen.LeaseKey");
#endregion
}
[TestMethod]
[TestCategory(TestCategories.Fsa)]
[TestCategory(TestCategories.LeaseV2)]
[TestCategory(TestCategories.Smb30)]
[TestCategory(TestCategories.Smb302)]
[TestCategory(TestCategories.Smb311)]
[TestCategory(TestCategories.Positive)]
[Description("Compare the server returned lease keys of two opens of the same file using the same lease key")]
public void Comparing_Same_LeaseKeysV2()
{
CheckLeaseApplicability();
Smb2CreateRequestLeaseV2 leaseRequest = createLeaseV2RequestContext();
Smb2CreateResponseLeaseV2 client1ResponseLease;
Smb2CreateResponseLeaseV2 client2ResponseLease;
InitializeClientsConnections(leaseRequest, leaseRequest, out client1ResponseLease, out client2ResponseLease);
#region Test Cases
BaseTestSite.Log.Add(LogEntryKind.TestStep, "Comparing lease keys");
BaseTestSite.Assert.AreEqual(leaseRequest.LeaseKey, client1ResponseLease.LeaseKey, "Client 1 Request Lease Key MUST be the same its Response Lease key");
BaseTestSite.Assert.AreEqual(leaseRequest.LeaseKey, client2ResponseLease.LeaseKey, "Client 2 Request Lease Key MUST be the same its Response Lease key");
BaseTestSite.Assert.AreEqual(client1ResponseLease.LeaseKey, client2ResponseLease.LeaseKey, "LeaseOpen.leaseKey MUST be the same with OperationOpen.LeaseKey");
BaseTestSite.Assert.AreNotSame(client1ResponseLease.LeaseKey, Guid.Empty, "LeaseOpen.LeaseKey can not be empty");
BaseTestSite.Assert.IsTrue(client1ResponseLease.LeaseKey != Guid.Empty || client1ResponseLease.ParentLeaseKey != Guid.Empty,
"Both LeaseOpen.LeaseKey and LeaseOpen.ParentLeaseKey can not be empty");
BaseTestSite.Assert.IsTrue(client2ResponseLease.LeaseKey != Guid.Empty || client2ResponseLease.ParentLeaseKey != Guid.Empty,
"Both OperationOpen.LeaseKey and OperationOpen.ParentLeaseKey can not be empty");
BaseTestSite.Assert.IsTrue(client1ResponseLease.LeaseKey != Guid.Empty,
"LeaseOpen.LeaseKey can not be empty");
#endregion
}
[TestMethod]
[TestCategory(TestCategories.Fsa)]
[TestCategory(TestCategories.LeaseV2)]
[TestCategory(TestCategories.Smb30)]
[TestCategory(TestCategories.Smb302)]
[TestCategory(TestCategories.Smb311)]
[TestCategory(TestCategories.Compatibility)]
[Description("The server should return an empty parentLeaseKey when leaseFlag is set to zero")]
public void Compare_Zero_LeaseFlag_ParentLeaseKey()
{
CheckLeaseApplicability();
Smb2CreateRequestLeaseV2 leaseRequest = createLeaseV2RequestContext(leaseFlag: LeaseFlagsValues.NONE);
Smb2CreateResponseLeaseV2 client1ResponseLease;
Smb2CreateResponseLeaseV2 client2ResponseLease;
InitializeClientsConnections(leaseRequest, leaseRequest, out client1ResponseLease, out client2ResponseLease);
#region Test Cases
BaseTestSite.Log.Add(LogEntryKind.TestStep, "Comparing lease keys");
BaseTestSite.Assert.AreNotEqual(leaseRequest.ParentLeaseKey, Guid.Empty,
"LeaseRequest.ParentLeaseKey should not be empty");
BaseTestSite.Assert.AreEqual(client1ResponseLease.ParentLeaseKey, Guid.Empty,
"LeaseOpen.ParentLeaseKey MUST be empty if LeaseFlag is set to Zero");
#endregion
}
[TestMethod]
[TestCategory(TestCategories.Fsa)]
[TestCategory(TestCategories.LeaseV2)]
[TestCategory(TestCategories.Smb30)]
[TestCategory(TestCategories.Smb302)]
[TestCategory(TestCategories.Smb311)]
[TestCategory(TestCategories.Positive)]
[Description("Compare the returned lease keys of two opens to the same directory file")]
public void DirectoryComparing_LeaseKeysV2()
{
CheckLeaseApplicability(checkDirectoryTypeSupport: true);
Guid leaseKey = Guid.NewGuid();
Smb2CreateRequestLeaseV2 client1RequestLease = createLeaseV2RequestContext(leaseKey, leaseState: LeaseStateValues.SMB2_LEASE_READ_CACHING | LeaseStateValues.SMB2_LEASE_HANDLE_CACHING);
Smb2CreateRequestLeaseV2 client2RequestLease = createLeaseV2RequestContext(parentLeaseKey: leaseKey);
Smb2CreateResponseLeaseV2 client1ResponseLease;
Smb2CreateResponseLeaseV2 client2ResponseLease;
InitializeClientsConnections(client1RequestLease, client2RequestLease, out client1ResponseLease, out client2ResponseLease, isBothClientDirectory: true);
#region Test Cases
BaseTestSite.Log.Add(LogEntryKind.TestStep, "Comparing lease keys");
BaseTestSite.Assert.IsTrue(client2ResponseLease.ParentLeaseKey != Guid.Empty, "OperationOpen.ParentLeaseKey CANNOT be empty when SMB2_LEASE_FLAG_PARENT_LEASE_KEY_SET Flags is set");
BaseTestSite.Assert.AreEqual(client1ResponseLease.LeaseKey, client2ResponseLease.ParentLeaseKey, "LeaseOpen.LeaseKey MUST be equal to OperationOpen.ParentLeasekey");
#endregion
}
[TestMethod]
[TestCategory(TestCategories.Fsa)]
[TestCategory(TestCategories.LeaseV2)]
[TestCategory(TestCategories.Smb30)]
[TestCategory(TestCategories.Smb302)]
[TestCategory(TestCategories.Smb311)]
[TestCategory(TestCategories.Positive)]
[Description("Compare the returned lease keys of two opens of a parent directory file and a child file")]
public void DirectoryComparing_ParentLeaseKey_ChildLeaseKey()
{
CheckLeaseApplicability(checkDirectoryTypeSupport: true);
Guid leaseKey = Guid.NewGuid();
Smb2CreateRequestLeaseV2 client1RequestLease = createLeaseV2RequestContext(leaseKey, leaseState: LeaseStateValues.SMB2_LEASE_READ_CACHING | LeaseStateValues.SMB2_LEASE_HANDLE_CACHING);
Smb2CreateRequestLeaseV2 client2RequestLease = createLeaseV2RequestContext(parentLeaseKey: leaseKey);
Smb2CreateResponseLeaseV2 client1ResponseLease;
Smb2CreateResponseLeaseV2 client2ResponseLease;
InitializeClientsConnections(client1RequestLease, client2RequestLease, out client1ResponseLease, out client2ResponseLease, isClient1ParentDirectory: true);
#region Test Cases
BaseTestSite.Log.Add(LogEntryKind.TestStep, "Comparing lease keys");
BaseTestSite.Assert.IsTrue(client2ResponseLease.ParentLeaseKey != Guid.Empty, "OperationOpen.ParentLeaseKey CANNOT be empty when SMB2_LEASE_FLAG_PARENT_LEASE_KEY_SET Flags is set");
BaseTestSite.Assert.AreEqual(client1ResponseLease.LeaseKey, client2ResponseLease.ParentLeaseKey, "LeaseOpen.LeaseKey MUST be equal to OperationOpen.ParentLeasekey");
#endregion
}
[TestMethod]
[TestCategory(TestCategories.Fsa)]
[TestCategory(TestCategories.LeaseV2)]
[TestCategory(TestCategories.Smb30)]
[TestCategory(TestCategories.Smb302)]
[TestCategory(TestCategories.Smb311)]
[TestCategory(TestCategories.Compatibility)]
[Description("Compare lease keys of parent directory file and a child file with an invalid parent lease key")]
public void DirectoryComparing_Child_Invalid_ParentLeaseKeys()
{
CheckLeaseApplicability(checkDirectoryTypeSupport: true);
Guid leaseKey = Guid.NewGuid();
Smb2CreateRequestLeaseV2 client1RequestLease = createLeaseV2RequestContext(leaseKey, leaseState: LeaseStateValues.SMB2_LEASE_READ_CACHING | LeaseStateValues.SMB2_LEASE_HANDLE_CACHING);
Smb2CreateRequestLeaseV2 client2RequestLease = createLeaseV2RequestContext();
client2RequestLease.ParentLeaseKey = new Guid(); // Invalid Key
Smb2CreateResponseLeaseV2 client1ResponseLease;
Smb2CreateResponseLeaseV2 client2ResponseLease;
InitializeClientsConnections(client1RequestLease, client2RequestLease, out client1ResponseLease, out client2ResponseLease, isClient1ParentDirectory: true, expectServerBreakNotification: true);
#region Test Cases
BaseTestSite.Log.Add(LogEntryKind.TestStep, "Comparing lease keys");
BaseTestSite.Assert.AreEqual(client2RequestLease.ParentLeaseKey, Guid.Empty, "request.ParentLeaseKey should be empty");
BaseTestSite.Assert.AreEqual(client2ResponseLease.ParentLeaseKey, Guid.Empty, "open.ParentLeaseKey should be empty");
#endregion
}
#endregion
#region Utility
private void InitializeClientsConnections(Smb2CreateRequestLease client1RequestLease, Smb2CreateRequestLease client2RequestLease, out Smb2CreateResponseLease client1ResponseLease,
out Smb2CreateResponseLease client2ResponseLease, bool isBothClientDirectory = false, bool isClient1ParentDirectory = false, bool expectServerBreakNotification = false)
{
Smb2CreateContextResponse client1ResponseContext;
Smb2CreateContextResponse client2ResponseContext;
SendRequestContext(client1RequestLease, client2RequestLease, out client1ResponseContext, out client2ResponseContext, isBothClientDirectory, isClient1ParentDirectory, expectServerBreakNotification);
client1ResponseLease = client1ResponseContext as Smb2CreateResponseLease;
client2ResponseLease = client2ResponseContext as Smb2CreateResponseLease;
}
private void InitializeClientsConnections(Smb2CreateRequestLeaseV2 client1RequestLease, Smb2CreateRequestLeaseV2 client2RequestLease, out Smb2CreateResponseLeaseV2 client1ResponseLease,
out Smb2CreateResponseLeaseV2 client2ResponseLease, bool isBothClientDirectory = false, bool isClient1ParentDirectory = false, bool expectServerBreakNotification = false)
{
Smb2CreateContextResponse client1ResponseContext;
Smb2CreateContextResponse client2ResponseContext;
SendRequestContext(client1RequestLease, client2RequestLease, out client1ResponseContext, out client2ResponseContext, isBothClientDirectory, isClient1ParentDirectory, expectServerBreakNotification);
client1ResponseLease = client1ResponseContext as Smb2CreateResponseLeaseV2;
client2ResponseLease = client2ResponseContext as Smb2CreateResponseLeaseV2;
}
public void SendRequestContext(Smb2CreateContextRequest client1RequestLease, Smb2CreateContextRequest client2RequestLease, out Smb2CreateContextResponse client1ResponseLease,
out Smb2CreateContextResponse client2ResponseLease, bool isBothClientDirectory = false, bool isClient1ParentDirectory = false, bool expectServerBreakNotification = false)
{
string client1FileName;
string client2FileName;
GenerateFileNames(isBothClientDirectory, isClient1ParentDirectory, out client1FileName, out client2FileName);
#region Add Event Handler
client1.Smb2Client.LeaseBreakNotificationReceived += new Action<Packet_Header, LEASE_BREAK_Notification_Packet>(OnLeaseBreakNotificationReceived);
clientToAckLeaseBreak = client1;
#endregion
#region Client1 (LeaseOpen) Open a File with Lease RWH or Directory with RH
BaseTestSite.Log.Add(LogEntryKind.TestStep,
"Start the first client to create a file by sending the following requests: 1. NEGOTIATE; 2. SESSION_SETUP; 3. TREE_CONNECT; 4. CREATE (with LeaseV2 context)");
SetupClientConnection(client1, out client1TreeId);
Smb2CreateContextResponse[] createContextResponse;
client1.Create(client1TreeId, client1FileName, isBothClientDirectory || isClient1ParentDirectory ? CreateOptions_Values.FILE_DIRECTORY_FILE : CreateOptions_Values.FILE_NON_DIRECTORY_FILE,
out client1FileId, out createContextResponse, RequestedOplockLevel_Values.OPLOCK_LEVEL_LEASE,
new Smb2CreateContextRequest[]
{
client1RequestLease
},
checker: (Packet_Header header, CREATE_Response response) =>
{
if (response.OplockLevel != OplockLevel_Values.OPLOCK_LEVEL_LEASE)
{
BaseTestSite.Assume.Inconclusive("Server OPLOCK Level is: {0}, expected: {1} indicating support for leasing.", response.OplockLevel, OplockLevel_Values.OPLOCK_LEVEL_LEASE);
}
}
);
#endregion
// Get response lease for Client1 (LeaseOpen)
client1ResponseLease = (createContextResponse != null) ? createContextResponse.First() : new Smb2CreateResponseLease();
#region Start a second client (OperationOpen) to request lease by using the same lease key with the first client
BaseTestSite.Log.Add(LogEntryKind.TestStep, "Start a second client to create the same file with the first client by sending the following requests: 1. NEGOTIATE; 2. SESSION_SETUP; 3. TREE_CONNECT; 4. CREATE");
SetupClientConnection(client2, out client2TreeId);
client2.Create(client2TreeId, client2FileName, isBothClientDirectory ? CreateOptions_Values.FILE_DIRECTORY_FILE : CreateOptions_Values.FILE_NON_DIRECTORY_FILE, out client2FileId, out createContextResponse, RequestedOplockLevel_Values.OPLOCK_LEVEL_LEASE,
new Smb2CreateContextRequest[]
{
client2RequestLease
},
checker: (Packet_Header header, CREATE_Response response) =>
{
if (response.OplockLevel != OplockLevel_Values.OPLOCK_LEVEL_LEASE)
{
BaseTestSite.Assume.Inconclusive("Server OPLOCK Level is: {0}, expected: {1} indicating support for leasing.", response.OplockLevel, OplockLevel_Values.OPLOCK_LEVEL_LEASE);
}
}
);
#endregion
// Check whether server will send out lease break notification or not
CheckBreakNotification(expectServerBreakNotification);
// Get response lease for Client2 (OperationOpen)
client2ResponseLease = createContextResponse.First();
}
private Smb2CreateRequestLease createLeaseRequestContext(Guid leaseKey = new Guid(), LeaseStateValues leaseState = LeaseStateValues.SMB2_LEASE_READ_CACHING | LeaseStateValues.SMB2_LEASE_HANDLE_CACHING | LeaseStateValues.SMB2_LEASE_WRITE_CACHING)
{
return new Smb2CreateRequestLease
{
LeaseKey = leaseKey == Guid.Empty ? Guid.NewGuid() : leaseKey,
LeaseState = leaseState
};
}
private Smb2CreateRequestLeaseV2 createLeaseV2RequestContext(Guid leaseKey = new Guid(), LeaseStateValues leaseState = LeaseStateValues.SMB2_LEASE_READ_CACHING | LeaseStateValues.SMB2_LEASE_HANDLE_CACHING | LeaseStateValues.SMB2_LEASE_WRITE_CACHING,
Guid parentLeaseKey = new Guid(), LeaseFlagsValues leaseFlag = LeaseFlagsValues.SMB2_LEASE_FLAG_PARENT_LEASE_KEY_SET)
{
return new Smb2CreateRequestLeaseV2
{
LeaseKey = leaseKey == Guid.Empty ? Guid.NewGuid() : leaseKey,
LeaseState = leaseState,
ParentLeaseKey = parentLeaseKey == Guid.Empty ? Guid.NewGuid() : parentLeaseKey,
LeaseFlags = (uint) leaseFlag
};
}
private void SetupClientConnection(Smb2FunctionalClient client, out uint clientTreeId)
{
client.Negotiate(testConfig.RequestDialects, testConfig.IsSMB1NegotiateEnabled);
client.SessionSetup(testConfig.DefaultSecurityPackage, testConfig.SutComputerName, testConfig.AccountCredential, false);
client.TreeConnect(sharePath, out clientTreeId);
}
private void CheckLeaseApplicability(DialectRevision dialect = DialectRevision.Smb30, bool checkFileTypeSupport = true, bool checkDirectoryTypeSupport = false)
{
testConfig.CheckDialect(dialect);
if (checkFileTypeSupport)
{
testConfig.CheckCapabilities(NEGOTIATE_Response_Capabilities_Values.GLOBAL_CAP_LEASING);
}
if (checkDirectoryTypeSupport)
{
testConfig.CheckCapabilities(NEGOTIATE_Response_Capabilities_Values.GLOBAL_CAP_DIRECTORY_LEASING);
}
if (dialect >= DialectRevision.Smb30)
{
testConfig.CheckCreateContext(CreateContextTypeValue.SMB2_CREATE_REQUEST_LEASE_V2);
} else
{
testConfig.CheckCreateContext(CreateContextTypeValue.SMB2_CREATE_REQUEST_LEASE);
}
}
private void TearDownClient(Smb2FunctionalClient client, uint clientTreeId, FILEID clientFileId)
{
if (ClientTreeConnectSessionExists(clientTreeId))
{
client.Close(clientTreeId, clientFileId);
client.TreeDisconnect(clientTreeId);
client.LogOff();
}
}
// Checks that there's an existing Tree_Connect session
private bool ClientTreeConnectSessionExists(uint clientTreeId)
{
return clientTreeId != 0;
}
private void GenerateFileNames(bool isBothClientDirectory, bool isClient1ParentDirectory, out string client1FileName, out string client2FileName)
{
client1FileName = "";
client2FileName = "";
if (isBothClientDirectory)
{
client1FileName = fsaAdapter.ComposeRandomFileName(10);
client2FileName = client1FileName;
}
if (isClient1ParentDirectory)
{
client1FileName = fsaAdapter.ComposeRandomFileName(10);
client2FileName = fsaAdapter.ComposeRandomFileName(10, opt: isBothClientDirectory ? CreateOptions.DIRECTORY_FILE : CreateOptions.NON_DIRECTORY_FILE, parentDirectoryName: client1FileName);
}
else if (!isBothClientDirectory)
{
client1FileName = fsaAdapter.ComposeRandomFileName(10, opt: CreateOptions.NON_DIRECTORY_FILE);
client2FileName = client1FileName;
}
}
#endregion
}
}
| 51.221074 | 265 | 0.704732 |
c726c52bcb8f14d9e396935e9f0cdee6e48e58d0 | 4,770 | dart | Dart | lib/src/responses/effects/effect_responses.dart | dmitryhryppa/stellar_flutter_sdk | 03fdbfbea36607f58ea58bc975c6ee0d7424e76f | [
"MIT"
] | null | null | null | lib/src/responses/effects/effect_responses.dart | dmitryhryppa/stellar_flutter_sdk | 03fdbfbea36607f58ea58bc975c6ee0d7424e76f | [
"MIT"
] | null | null | null | lib/src/responses/effects/effect_responses.dart | dmitryhryppa/stellar_flutter_sdk | 03fdbfbea36607f58ea58bc975c6ee0d7424e76f | [
"MIT"
] | null | null | null | // Copyright 2020 The Stellar Flutter SDK Authors. All rights reserved.
// Use of this source code is governed by a license that can be
// found in the LICENSE file.
import '../response.dart';
import 'account_effects_responses.dart';
import 'signer_effects_responses.dart';
import 'trustline_effects_responses.dart';
import 'trade_effects_responses.dart';
import 'data_effects_responses.dart';
import 'misc_effects_responses.dart';
///Abstract class for effect responses.
/// See: <a href="https://developers.stellar.org/api/resources/effects/" target="_blank">Effects</a>.
///
///<p>Possible types:</p>
///<ul>
/// <li>account_created</li>
/// <li>account_removed</li>
/// <li>account_credited</li>
/// <li>account_debited</li>
/// <li>account_thresholds_updated</li>
/// <li>account_home_domain_updated</li>
/// <li>account_flags_updated</li>
/// <li>account_inflation_destination_updated</li>
/// <li>signer_created</li>
/// <li>signer_removed</li>
/// <li>signer_updated</li>
/// <li>trustline_created</li>
/// <li>trustline_removed</li>
/// <li>trustline_updated</li>
/// <li>trustline_authorized_to_maintain_liabilities</li>
/// <li>trustline_deauthorized</li>
/// <li>trustline_authorized</li>
/// <li>offer_created</li>
/// <li>offer_removed</li>
/// <li>offer_updated</li>
/// <li>trade</li>
/// <li>data_created</li>
/// <li>data_removed</li>
/// <li>data_updated</li>
/// <li>sequence_bumped</li>
///</ul>
///
abstract class EffectResponse extends Response {
String id;
String account;
String type;
String createdAt;
String pagingToken;
EffectResponseLinks links;
EffectResponse();
factory EffectResponse.fromJson(Map<String, dynamic> json) {
int type = convertInt(json["type_i"]);
switch (type) {
// Account effects
case 0:
return AccountCreatedEffectResponse.fromJson(json);
case 1:
return AccountRemovedEffectResponse.fromJson(json);
case 2:
return AccountCreditedEffectResponse.fromJson(json);
case 3:
return AccountDebitedEffectResponse.fromJson(json);
case 4:
return AccountThresholdsUpdatedEffectResponse.fromJson(json);
case 5:
return AccountHomeDomainUpdatedEffectResponse.fromJson(json);
case 6:
return AccountFlagsUpdatedEffectResponse.fromJson(json);
case 7:
return AccountInflationDestinationUpdatedEffectResponse.fromJson(json);
// Signer effects
case 10:
return SignerCreatedEffectResponse.fromJson(json);
case 11:
return SignerRemovedEffectResponse.fromJson(json);
case 12:
return SignerUpdatedEffectResponse.fromJson(json);
// Trustline effects
case 20:
return TrustlineCreatedEffectResponse.fromJson(json);
case 21:
return TrustlineRemovedEffectResponse.fromJson(json);
case 22:
return TrustlineUpdatedEffectResponse.fromJson(json);
case 23:
return TrustlineAuthorizedEffectResponse.fromJson(json);
case 24:
return TrustlineDeauthorizedEffectResponse.fromJson(json);
case 25:
return TrustlineAuthorizedToMaintainLiabilitiesEffectResponse.fromJson(
json);
// Trading effects
case 30:
return OfferCreatedEffectResponse.fromJson(json);
case 31:
return OfferRemovedEffectResponse.fromJson(json);
case 32:
return OfferUpdatedEffectResponse.fromJson(json);
case 33:
return TradeEffectResponse.fromJson(json);
// Data effects
case 40:
return DataCreatedEffectResponse.fromJson(json);
case 41:
return DataRemovedEffectResponse.fromJson(json);
case 42:
return DataUpdatedEffectResponse.fromJson(json);
// Bump Sequence effects
case 43:
return SequenceBumpedEffectResponse.fromJson(json);
default:
throw new Exception("Invalid operation type");
}
}
}
///Represents effect links.
class EffectResponseLinks {
Link operation;
Link precedes;
Link succeeds;
EffectResponseLinks(this.operation, this.precedes, this.succeeds);
factory EffectResponseLinks.fromJson(Map<String, dynamic> json) {
return new EffectResponseLinks(
json['operation'] == null
? null
: new Link.fromJson(json['operation'] as Map<String, dynamic>),
json['precedes'] == null
? null
: new Link.fromJson(json['precedes'] as Map<String, dynamic>),
json['succeeds'] == null
? null
: new Link.fromJson(json['succeeds'] as Map<String, dynamic>));
}
Map<String, dynamic> toJson() => <String, dynamic>{
'operation': operation,
'precedes': precedes,
'succeeds': succeeds
};
}
| 32.22973 | 101 | 0.677568 |
cd282f8b8a7868a2af065312e42d889ae7f34744 | 1,422 | cs | C# | Bazzigg.Database.Test/TestOptions.cs | bazzi-gg/database | a228dc07577bc772e9dc80893c6111f889487edb | [
"MIT"
] | 1 | 2021-11-29T11:02:56.000Z | 2021-11-29T11:02:56.000Z | Bazzigg.Database.Test/TestOptions.cs | bazzi-gg/database | a228dc07577bc772e9dc80893c6111f889487edb | [
"MIT"
] | 2 | 2022-03-24T09:13:45.000Z | 2022-03-24T21:45:14.000Z | Bazzigg.Database.Test/TestOptions.cs | bazzi-gg/database | a228dc07577bc772e9dc80893c6111f889487edb | [
"MIT"
] | null | null | null |
using Bazzigg.Database.Context;
using Kartrider.Api;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Pomelo.EntityFrameworkCore.MySql.Infrastructure;
namespace Bazzigg.Database.Test
{
[TestClass]
public class TestOptions
{
public static KartriderApi KartriderApi { get; private set; }
public static DbContextOptions<AppDbContext> AppDbContextOptions { get; private set; }
[AssemblyInitialize]
public static void Init(TestContext context)
{
IConfiguration configuration = new ConfigurationBuilder()
.AddJsonFile("appsettings.json")
.AddEnvironmentVariables("TEST_")
.Build();
string appDbConnectionString = configuration["APP_DB_CONNECTION_STRING"];
AppDbContextOptions = new DbContextOptionsBuilder<AppDbContext>()
.UseMySql(appDbConnectionString, ServerVersion.Parse("10.5.6-MariaDB", ServerType.MariaDb), options =>
{
})
.EnableSensitiveDataLogging() // <-- These two calls are optional but help
.EnableDetailedErrors() // <-- with debugging (remove for production).
.Options;
KartriderApi = KartriderApi.GetInstance(configuration["NEXON_OPEN_API_KEY"]);
}
}
}
| 36.461538 | 118 | 0.660338 |
9e0cffe5ceaff4dbc1c13558086a83134ac0b04b | 586 | cs | C# | DotNetVault/Interfaces/IVsIListWrapper.cs | JTOne123/DotNetVault | f8c425739eecfb26e6fe7442d415dd671ff31735 | [
"MIT-0",
"MIT"
] | 5 | 2020-10-14T09:12:34.000Z | 2022-02-24T16:49:27.000Z | DotNetVault/Interfaces/IVsIListWrapper.cs | JTOne123/DotNetVault | f8c425739eecfb26e6fe7442d415dd671ff31735 | [
"MIT-0",
"MIT"
] | 20 | 2020-10-11T19:15:07.000Z | 2021-10-31T15:25:41.000Z | DotNetVault/Interfaces/IVsIListWrapper.cs | JTOne123/DotNetVault | f8c425739eecfb26e6fe7442d415dd671ff31735 | [
"MIT-0",
"MIT"
] | 2 | 2020-06-25T13:31:15.000Z | 2021-04-19T12:18:40.000Z | using System.Collections.Generic;
using System.Collections.Immutable;
using DotNetVault.Attributes;
using DotNetVault.VsWrappers;
using JetBrains.Annotations;
namespace DotNetVault.Interfaces
{
[NotVsProtectable]
internal interface IVsIListWrapper<[VaultSafeTypeParam] T> : IReadOnlyList<T>
{
new StandardEnumerator<T> GetEnumerator();
ImmutableList<T> ToImmutableList();
ImmutableArray<T> ToImmutableArray();
[Pure]
int IndexOf(T item);
[Pure]
bool Contains(T item);
void CopyTo(T[] array, int idx);
}
} | 27.904762 | 81 | 0.691126 |
64e6cea818a18470d0cbff395f8566db75f10d9b | 413 | sql | SQL | db/deploy/users.sql | d3sandoval/tome | bf317ab2c4499bb57a6d937813edea84a0391b6d | [
"MIT"
] | 1 | 2020-02-26T04:40:14.000Z | 2020-02-26T04:40:14.000Z | db/deploy/users.sql | d3sandoval/tome | bf317ab2c4499bb57a6d937813edea84a0391b6d | [
"MIT"
] | 4 | 2020-03-29T21:35:34.000Z | 2022-02-13T09:32:09.000Z | db/deploy/users.sql | d3sandoval/tome | bf317ab2c4499bb57a6d937813edea84a0391b6d | [
"MIT"
] | null | null | null | -- Deploy tome:users to pg
-- requires: appschema
BEGIN;
CREATE TABLE "users" (
"id" serial PRIMARY KEY,
"auth_id" varchar,
"auth_metadata" jsonb NOT NULL,
"created_at" timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updated_at" timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP
);
CREATE TRIGGER "users_bu" BEFORE UPDATE ON "users" FOR EACH ROW
EXECUTE PROCEDURE update_changetimestamp_column();
COMMIT;
| 22.944444 | 63 | 0.762712 |
bd0d6b020082898639f000d7c4d46a244a34048f | 862 | rb | Ruby | lib/animations/happy_birthday_animation.rb | mrstebo/slack-message-animator | a62efc88bd756271772deb1ce7739ee1d6e5fdac | [
"MIT"
] | 2 | 2016-11-08T08:53:19.000Z | 2016-11-14T11:40:14.000Z | lib/animations/happy_birthday_animation.rb | mrstebo/slack-message-animator | a62efc88bd756271772deb1ce7739ee1d6e5fdac | [
"MIT"
] | 6 | 2016-11-13T22:17:24.000Z | 2022-02-26T01:13:32.000Z | lib/animations/happy_birthday_animation.rb | mrstebo/slack-message-animator | a62efc88bd756271772deb1ce7739ee1d6e5fdac | [
"MIT"
] | 1 | 2016-11-10T16:23:56.000Z | 2016-11-10T16:23:56.000Z | class HappyBirthdayAnimation
def ask_questions
@person = ask("Whos birthday is it?") {|q| q.echo = true}
end
def frames
return [] unless @person
[
create_frame(4, "#{birthday_cake} Happy Birthday @#{@person}! #{birthday_cake}"),
create_frame(2, "Happy Birthday to you"),
create_frame(2, "Happy Birthday to you!"),
create_frame(2, "Happy Birthday, dear @#{@person}!"),
create_frame(3, "Happy Birthday to you!"),
create_frame(1, "Have an awesome day, @#{@person}! #{hugging_face}")
]
end
private
def create_frame(delay, content)
AnimationFrame.new(content, {
delay: delay,
override_previous_frame: true
})
end
def birthday_cake
':birthday:'
end
def candle
':candle:'
end
def dancer
':dancer:'
end
def hugging_face
':hugging_face:'
end
end
| 20.046512 | 87 | 0.62529 |
968ab8ad576369a4853649ca1b53902ab62463d8 | 1,954 | lua | Lua | mods/mapgen/aurum_villages/structures/corrupted_temple.lua | tigris-mt/aurum-compiled | d092040304b3583ffb97bf398033501377b8aecc | [
"0BSD"
] | 2 | 2019-07-22T10:22:53.000Z | 2020-04-03T17:50:02.000Z | mods/mapgen/aurum_villages/structures/corrupted_temple.lua | tigris-mt/aurum-compiled | d092040304b3583ffb97bf398033501377b8aecc | [
"0BSD"
] | 52 | 2019-07-12T20:49:52.000Z | 2021-06-24T15:46:36.000Z | mods/mapgen/aurum_villages/structures/corrupted_temple.lua | tigris-mt/aurum-compiled | d092040304b3583ffb97bf398033501377b8aecc | [
"0BSD"
] | null | null | null | local PH_SCROLL_HOLE = 1
local PH_STORAGE = 2
local PH_CONTRABAND = 3
local PH_MOCKING = 4
aurum.villages.register_structure("aurum_villages:corrupted_temple", {
size = vector.new(11, 18, 10),
offset = vector.new(0, -5, 0),
foundation = {"aurum_base:stone_brick"},
schematic = aurum.structures.f"corrupted_temple.mts",
on_generated = function(c)
for _,pos in ipairs(c:ph(PH_SCROLL_HOLE)) do
minetest.set_node(pos, {name = "aurum_storage:scroll_hole"})
c:treasures(pos, "main", c:random(1, 2), {
{
count = c:random(1, 2),
preciousness = {0, 3},
groups = {"scroll", "lore_aurum"},
},
})
end
for _,pos in ipairs(c:ph(PH_STORAGE)) do
minetest.set_node(pos, {name = "aurum_storage:box"})
c:treasures(pos, "main", c:random(1, 2), {
{
count = c:random(1, 2),
preciousness = {0, 2},
groups = {"deco", "minetool", "building_block", "crafting_component", "scroll"},
},
})
end
for _,pos in ipairs(c:ph(PH_CONTRABAND)) do
minetest.set_node(pos, {name = "aurum_storage:shell_box"})
c:treasures(pos, "main", c:random(1, 2), {
{
count = c:random(0, 2),
preciousness = {0, 5},
groups = {"magic", "spell", "worker"},
},
})
end
local village_id = aurum.villages.get_village_id_at(c.base.pos)
local village = village_id and aurum.villages.get_village(village_id)
for _,pos in ipairs(c:ph(PH_MOCKING)) do
if village then
minetest.set_node(pos, {name = "aurum_books:stone_tablet_written", param2 = minetest.dir_to_facedir(c:dir(vector.new(-1, 0, 0)))})
gtextitems.set_node(pos, {
title = village.name,
text = ("Our %s servant %s has brought about the end of %s."):format(aurum.flavor.generate_mocking(c:random(4), c.base.random), aurum.flavor.generate_name(c.base.random), village.name),
author = "a dreadful one",
author_type = "npc",
id = "aurum_villages:corrupted_temple_mocking",
})
end
end
end,
})
| 30.53125 | 190 | 0.651484 |
21c6e55e0ef2abf9a3815dc3272130af83051ea2 | 645 | js | JavaScript | app/components/Header/elements.js | kalyanjyothula/minicart | 8228055371063494c5718b36ac4eed84b5988c5d | [
"MIT"
] | 1 | 2019-11-09T10:56:09.000Z | 2019-11-09T10:56:09.000Z | app/components/Header/elements.js | kalyanjyothula/minicart | 8228055371063494c5718b36ac4eed84b5988c5d | [
"MIT"
] | 3 | 2019-11-05T09:11:26.000Z | 2020-07-18T15:13:27.000Z | app/components/Header/elements.js | kalyanjyothula/minicart | 8228055371063494c5718b36ac4eed84b5988c5d | [
"MIT"
] | null | null | null | import styled from 'styled-components';
import { Link } from 'react-router-dom';
export const MainHeaderContainer = styled.div`
height: 60px;
width: 100%;
background: #fffffe;
transition: box-shadow 0.15s ease;
box-shadow: 0 1px 3px rgba(50, 50, 93, 0.15), 0 1px 0 rgba(0, 0, 0, 0.02);
display: flex;
align-items: center;
padding: 0px 10px;
justify-content: space-between;
`;
export const TitleContainer = styled(Link)`
display: flex;
align-items: center;
text-decoration: none;
`;
export const Title = styled.h1`
margin-left: 0.5rem;
font-weight: 600;
user-select: none;
font-size: 1.88rem;
color: #000;
`;
| 22.241379 | 76 | 0.68062 |
c8e43fd16611224307350dfbcae50407f2ef456b | 2,700 | swift | Swift | XiaoYu_Network/Classes/Network/RJRequset.swift | A-Jun/XiaoYu_Network | 9de1b7a312f87c0eae0546dfa81595a1d6e19b22 | [
"MIT"
] | null | null | null | XiaoYu_Network/Classes/Network/RJRequset.swift | A-Jun/XiaoYu_Network | 9de1b7a312f87c0eae0546dfa81595a1d6e19b22 | [
"MIT"
] | null | null | null | XiaoYu_Network/Classes/Network/RJRequset.swift | A-Jun/XiaoYu_Network | 9de1b7a312f87c0eae0546dfa81595a1d6e19b22 | [
"MIT"
] | null | null | null | //
// RJRequset.swift
// XiaoYu_V3.0_Refactor
//
// Created by RJ on 2018/8/16.
// Copyright © 2018年 coollang. All rights reserved.
//
import UIKit
import YTKNetwork
enum RJAPIType :String{
case none
// ---------------------------------Login---------------------------------
case PhoneRegistered
case RegisterByPhone
case RegisterByEmail
case LoginByAccount
case QuickLoginByPhone
case ThirdPlatformLogin
case GetVerifyCodeByPhone
case ResetPasswordByPhone
case ResetPasswordByEmail
case ModifyPassword
case BindThirdPlatform
case BindPhone
case GetAccountBindInfo
case RelieveBind
}
class RJRequset: YTKBaseRequest {
var apiType : RJAPIType = .none
var arguments : [AnyHashable:Any]?
override func requestMethod() -> YTKRequestMethod {
return .POST
}
override func requestUrl() -> String {
return requestString(apiType)
}
override func requestArgument() -> Any? {
return arguments ?? nil
}
class
func requsetWith(_ apiType:RJAPIType , params:[AnyHashable:Any]?) -> RJRequset {
let request = RJRequset()
request.apiType = apiType
request.arguments = params
return request
}
func requestString(_ apiType:RJAPIType) -> String {
switch apiType {
case .none:
break
case .PhoneRegistered:
return "/BadmintonLoginController/checkPhoneRegistered"
case .RegisterByPhone:
return "/BadmintonLoginController/phoneVerify"
case .RegisterByEmail:
return "/BadmintonLoginController/emailRegister"
case .LoginByAccount:
return "/BadmintonLoginController/accountLogin"
case .QuickLoginByPhone:
return "/BadmintonLoginController/phoneVerify"
case .ThirdPlatformLogin:
return "/BadmintonLoginController/qqLoginCallBack"
case .GetVerifyCodeByPhone:
return "/BadmintonLoginController/getPwdByPhoneCode"
case .ResetPasswordByPhone:
return "/BadmintonLoginController/registerPwd"
case .ResetPasswordByEmail:
return "/BadmintonLoginController/getMyEmailCode"
case .ModifyPassword:
return "/BadmintonLoginController/changePwd"
case .BindThirdPlatform:
return "/BadmintonLoginController/bindQQorWX"
case .BindPhone:
return "/BadmintonLoginController/bindPhone"
case .GetAccountBindInfo:
return "/BadmintonLoginController/getMyAccount"
case .RelieveBind:
return "/BadmintonLoginController/unbind"
}
return "1"
}
}
| 31.395349 | 84 | 0.645556 |
89b6ac473ab8a4f2d3f31b64b5f2f886094daed4 | 6,128 | swift | Swift | martkurly/martkurly/Home/View/ProductView/ProductCell.swift | KasRoid/martkurly-ios | d4c3cc6b4503f8b6756b51ceb21f9dfaffe679ec | [
"MIT"
] | 4 | 2020-09-22T06:37:08.000Z | 2020-10-11T19:59:01.000Z | martkurly/martkurly/Home/View/ProductView/ProductCell.swift | KasRoid/martkurly-ios | d4c3cc6b4503f8b6756b51ceb21f9dfaffe679ec | [
"MIT"
] | 28 | 2020-08-19T17:17:32.000Z | 2020-10-11T19:51:40.000Z | martkurly/martkurly/Home/View/ProductView/ProductCell.swift | KasRoid/martkurly-ios | d4c3cc6b4503f8b6756b51ceb21f9dfaffe679ec | [
"MIT"
] | 5 | 2020-08-17T06:16:35.000Z | 2020-10-11T20:03:37.000Z | //
// ProductCell.swift
// martkurly
//
// Created by 천지운 on 2020/08/24.
// Copyright © 2020 Team3x3. All rights reserved.
//
import UIKit
import Kingfisher
class ProductCell: UICollectionViewCell {
// MARK: - Properties
static let identifier = "ProductCell"
var product: Product? {
didSet { configure() }
}
private let productImageView = UIImageView().then {
$0.image = UIImage(named: "TestImage")
$0.contentMode = .scaleAspectFill
$0.clipsToBounds = true
}
private let saleDisplayLabel = UILabel().then {
let boldAttributes: [NSAttributedString.Key: Any] = [
.font: UIFont.boldSystemFont(ofSize: 20),
.foregroundColor: UIColor.white
]
let attributes: [NSAttributedString.Key: Any] = [
.font: UIFont.systemFont(ofSize: 14),
.foregroundColor: UIColor.white
]
var stringValue = NSMutableAttributedString(string: "SAVE\n", attributes: attributes)
stringValue.append(NSAttributedString(string: "40", attributes: boldAttributes))
stringValue.append(NSAttributedString(string: "%", attributes: attributes))
$0.attributedText = stringValue
$0.textAlignment = .center
$0.numberOfLines = 2
}
private lazy var saleDisplayView = UIView().then {
$0.backgroundColor = UIColor(red: 147/255,
green: 83/255,
blue: 185/255,
alpha: 0.8)
$0.addSubview(saleDisplayLabel)
saleDisplayLabel.snp.makeConstraints {
$0.edges.equalToSuperview()
}
}
private lazy var cartButton = UIButton(type: .system).then {
$0.backgroundColor = UIColor(red: 110/255,
green: 85/255,
blue: 116/255,
alpha: 0.8)
let configuration = UIImage.SymbolConfiguration(
pointSize: 20,
weight: .medium,
scale: .large)
let symbolImage = UIImage(
systemName: "cart",
withConfiguration: configuration)
$0.setImage(symbolImage, for: .normal)
$0.tintColor = .white
$0.addTarget(self, action: #selector(tappedCartButton), for: .touchUpInside)
}
private let productTitleLabel = UILabel().then {
$0.text = "[남향푸드또띠아] 간편 간식 브리또 8종"
$0.textColor = .black
$0.font = UIFont.systemFont(ofSize: 16)
$0.numberOfLines = 2
}
private let productPriceLabel = UILabel().then {
$0.text = "2,800원"
$0.textColor = .black
$0.font = UIFont.boldSystemFont(ofSize: 16)
}
private let productStatsLeftLabel = UILabel().then {
let mainColor = ColorManager.General.mainPurple.rawValue
$0.text = " Kurly only "
$0.textColor = mainColor
$0.font = UIFont.boldSystemFont(ofSize: 12)
$0.layer.borderColor = mainColor.cgColor
$0.layer.borderWidth = 1
}
private let productStatsRightLabel = UILabel().then {
let mainColor = ColorManager.General.mainPurple.rawValue
$0.text = " 한정수량 "
$0.textColor = mainColor
$0.font = UIFont.systemFont(ofSize: 12)
$0.layer.borderColor = mainColor.cgColor
$0.layer.borderWidth = 1
}
private lazy var infoView = UIView().then {
$0.backgroundColor = .white
let stack = UIStackView(arrangedSubviews: [
productTitleLabel, productPriceLabel
])
stack.axis = .vertical
stack.spacing = 4
$0.addSubview(stack)
stack.snp.makeConstraints {
$0.top.leading.trailing.equalToSuperview()
}
let statsStack = UIStackView(arrangedSubviews: [
productStatsLeftLabel, productStatsRightLabel
])
statsStack.spacing = 2
statsStack.axis = .horizontal
$0.addSubview(statsStack)
statsStack.snp.makeConstraints {
$0.leading.bottom.equalToSuperview()
}
}
// MARK: - LifeCycle
override init(frame: CGRect) {
super.init(frame: frame)
configureUI()
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: - Selectors
@objc func tappedCartButton(_ sender: UIButton) {
}
// MARK: - Helpers
func configureUI() {
self.backgroundColor = .white
[productImageView, infoView, cartButton, saleDisplayView].forEach {
self.addSubview($0)
}
productImageView.snp.makeConstraints {
$0.top.leading.trailing.equalToSuperview()
$0.bottom.equalTo(infoView.snp.top).offset(-16)
}
saleDisplayView.snp.makeConstraints {
$0.top.leading.equalToSuperview()
$0.height.equalTo(48)
$0.width.equalTo(56)
}
cartButton.snp.makeConstraints {
$0.width.height.equalTo(52)
$0.bottom.trailing.equalTo(productImageView).offset(-12)
}
cartButton.layer.cornerRadius = 52 / 2
infoView.snp.makeConstraints {
$0.leading.equalToSuperview().offset(16)
$0.bottom.trailing.equalToSuperview().offset(-16)
$0.height.equalTo(88)
}
}
func configure() {
guard let product = product else { return }
let viewModel = ProductViewModel(product: product)
saleDisplayView.isHidden = viewModel.isShowSaleView
saleDisplayLabel.attributedText = viewModel.saleDisplayText
productTitleLabel.text = product.title
productImageView.kf.setImage(with: viewModel.imageURL)
productPriceLabel.attributedText = viewModel.priceDisplayText
productStatsLeftLabel.isHidden = viewModel.isShowleftTag
productStatsLeftLabel.text = viewModel.leftTagText
productStatsRightLabel.isHidden = viewModel.isShowRightTag
productStatsRightLabel.text = viewModel.rightTagText
}
}
| 29.892683 | 93 | 0.597585 |
5bab31b043d8a2ddd9d946ab83655d338e87b464 | 1,943 | css | CSS | ums-mvc-framework/public/css/default.css | d3v4s/ums-framework | 9178cf0ac380be651c8ef340d5e5348619c460ae | [
"MIT"
] | null | null | null | ums-mvc-framework/public/css/default.css | d3v4s/ums-framework | 9178cf0ac380be651c8ef340d5e5348619c460ae | [
"MIT"
] | null | null | null | ums-mvc-framework/public/css/default.css | d3v4s/ums-framework | 9178cf0ac380be651c8ef340d5e5348619c460ae | [
"MIT"
] | null | null | null | @charset "utf-8";
#message-box {
z-index: 10;
}
#close-message-box {
color: white;
}
#close-message-box:hover {
color: black;
text-decoration: none;
transition-duration: .15s;
}
#dropdown-account {
min-width: 250px;
}
#double-login-container {
position: absolute;
width: 100%;
height: 100%;
z-index: 9;
background-color: #000000ac;
top: 0;
}
#double-login-container .message-box {
background-color: #3c3c3c;
}
div.toogle-lang > a {
color: rgba(255,255,255,.5);
}
div.toogle-lang > a:focus,
div.toogle-lang > a:hover {
color: rgba(255,255,255,.75);
}
html, body {
height: 100%;
margin: 0;
overflow-x: hidden;
}
main {
min-height: 100% !important;
}
li.nav-item.active > a.nav-link {
pointer-events: none;
cursor: default;
text-decoration: none;
}
.display-none {
display: none;
}
.text-red {
color: #dc3545;
}
.text-small {
font-size: 0.9em;
}
.link-danger {
color: #dc3545;
}
.link-danger:hover {
color: #c82333;
transition-duration: .15s;
}
a:hover {
text-decoration: none;
}
.btn-link:hover {
text-decoration: none;
}
.footer {
background-color: #343a40;
}
.footer > .container {
padding-right: 15px;
padding-left: 15px;
}
.bg-blue {
background-color: #2081dc;
}
.bg-red {
background-color: #ff1304;
}
.z-index-1 {
z-index: 1;
}
.over-top {
top: -100px;
}
.flag {
width: 2.3em;
}
@media (prefers-color-scheme: dark) {
#dropdown-account {
background-color: #272c31;
color: #fd7e14;
}
body {
background-color: #1c1c1c !important;
color: #17a2b8 !important;
}
h1, h2, h3, h4, h5, h6 {
color: #fd7e14;
}
hr {
display: block;
height: 1px;
border: 0;
border-top: 1px solid #6c757d;
margin: 1em 0;
padding: 0;
}
input, textarea {
background: #6c757d !important;
color: #20c997 !important;
}
input::placeholder {
color: #20c997 !important;
opacity: .8 !important;
}
tbody, thead, tfoot {
color: #fd7e14;
}
} | 12.616883 | 39 | 0.630468 |
568f818cf6b53c9647e4cd3eac609d3b524681d1 | 622 | lua | Lua | Assets/ResourcesAsset/Lua/config/movecurve/Common_Summon/Summon_Yuzuru_Skill_2.lua | lixiaobing/DAL2Client | 612d745fee88ea3fb6abbfd52b668774be483dd5 | [
"BSD-3-Clause"
] | 1 | 2021-03-16T06:10:15.000Z | 2021-03-16T06:10:15.000Z | Assets/ResourcesAsset/Lua/config/movecurve/Common_Summon/Summon_Yuzuru_Skill_2.lua | lixiaobing/DAL2Client | 612d745fee88ea3fb6abbfd52b668774be483dd5 | [
"BSD-3-Clause"
] | null | null | null | Assets/ResourcesAsset/Lua/config/movecurve/Common_Summon/Summon_Yuzuru_Skill_2.lua | lixiaobing/DAL2Client | 612d745fee88ea3fb6abbfd52b668774be483dd5 | [
"BSD-3-Clause"
] | null | null | null | --MoveCurve
--Common_Summon/Summon_Yuzuru_Skill_2 Summon_Yuzuru_Skill_2
return
{
filePath = "Common_Summon/Summon_Yuzuru_Skill_2",
startTime = Fixed64(1048576) --[[1]],
startRealTime = Fixed64(41943) --[[0.04]],
endTime = Fixed64(78643200) --[[75]],
endRealTime = Fixed64(3145728) --[[3]],
isZoom = false,
isCompensate = false,
curve = {
[1] = {
time = 0 --[[0]],
value = 0 --[[0]],
inTangent = 16777216 --[[16]],
outTangent = 16777216 --[[16]],
},
[2] = {
time = 786432 --[[0.75]],
value = 12582912 --[[12]],
inTangent = 16777216 --[[16]],
outTangent = 16777216 --[[16]],
},
},
} | 23.037037 | 59 | 0.59164 |
eb2f55baa23ca1ec165587935edc791a8c802e7f | 7,586 | swift | Swift | DXOSwift/Module/News/Controller/NewsController.swift | ruixingchen/DXOSwift | fdc213354326822e4ba1acaf18966e6d9f59537b | [
"Apache-2.0"
] | 1 | 2018-11-14T02:57:32.000Z | 2018-11-14T02:57:32.000Z | DXOSwift/Module/News/Controller/NewsController.swift | ruixingchen/DXOSwift | fdc213354326822e4ba1acaf18966e6d9f59537b | [
"Apache-2.0"
] | null | null | null | DXOSwift/Module/News/Controller/NewsController.swift | ruixingchen/DXOSwift | fdc213354326822e4ba1acaf18966e6d9f59537b | [
"Apache-2.0"
] | null | null | null | //
// NewsController.swift
// DXOSwift
//
// Created by ruixingchen on 18/10/2017.
// Copyright © 2017 ruixingchen. All rights reserved.
//
import UIKit
import MJRefresh
import SDCycleScrollView
import SnapKit
import Toast_Swift
/// the main controller
class NewsController: GenericReviewListController, SDCycleScrollViewDelegate {
private var cycleScrollView:SDCycleScrollView?
private var cycleScrollViewHeight:CGFloat = 250 //for 375 width(4.7 inch devices)
private var topTopicDataSource:NSMutableArray = [] //one dimension
override func initFunction() {
super.initFunction()
self.title = LocalizedString.title_dxo_mark
self.navigationItem.backBarButtonItem = UIBarButtonItem(title: "", style: .plain, target: nil, action: nil)
}
override func viewDidLoad() {
super.viewDidLoad()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
cycleScrollView?.adjustWhenControllerViewWillAppera()
}
override func setupSubviews(){
let searchButton:UIBarButtonItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.search, target: self, action: #selector(didTapSearchButton))
searchButton.tintColor = UIColor.white
self.navigationItem.rightBarButtonItem = searchButton
// let imageView:UIImageView = UIImageView(image: UIImage(named: "dxo_logo"))
// self.navigationItem.titleView = imageView
}
//MARK: - Action
@objc func didTapSearchButton(){
let next = SearchContainerController()
next.hidesBottomBarWhenPushed = true
next.view.backgroundColor = UIColor.white
self.navigationController?.pushViewController(next, animated: true)
}
//MARK: - Request
override func headerRefresh(){
//when we do header refresh, we overwrite all the data source.
DXOService.mainPage(completion: {[weak self] (inTopTopic, inNews, inError) in
if self == nil {
log.debug("self nil")
return
}
var userInfo:UserInfo = [:]
if inTopTopic != nil {
userInfo.updateValue(inTopTopic!, forKey: "top")
}
self?.headerRefreshHandle(inObject: inNews, inError: inError, userInfo: userInfo)
})
}
override func footerRefresh() {
//we load the next page
DXOService.news(page: page+1) {[weak self] (inReviews, inError) in
if self == nil {
log.debug("self nil")
return
}
self?.footerRefreshHanle(inObject: inReviews, inError: inError)
}
}
override func headerRefreshHandle(inObject: [Review]?, inError: RXError?, userInfo: UserInfo? = nil) {
if inError != nil || inObject == nil{
if inError != nil {
log.debug("error: \(inError!.description)")
}else if inObject == nil {
log.debug("inObject nil")
}else {
log.debug("unknown error")
}
DispatchQueue.main.async {
self.tableView.refreshControl?.endRefreshing()
if self.dataSource.count == 0 {
//show loading failed view
self.retryLoadingView?.removeFromSuperview()
self.retryLoadingView = nil
self.retryLoadingView = RetryLoadingView()
self.retryLoadingView?.delegate = self
self.tableView.addSubview(self.retryLoadingView!)
self.retryLoadingView?.snp.makeConstraints({ (make) in
make.center.equalToSuperview()
make.size.equalToSuperview()
})
}else{
self.view.makeToast(LocalizedString.refresh_failed_try_again_later)
}
}
return
}
DispatchQueue.main.async {
if let inTopTopic = userInfo?["top"] as? [Review] {
if self.cycleScrollView == nil {
self.cycleScrollView = SDCycleScrollView()
self.cycleScrollView?.bannerImageViewContentMode = .scaleAspectFill
self.cycleScrollView?.autoScrollTimeInterval = 3
self.cycleScrollView?.titleLabelHeight = 60
self.cycleScrollView?.delegate = self
}
self.topTopicDataSource = NSMutableArray(array: inTopTopic)
self.cycleScrollViewHeight = self.view.bounds.width/1.75
var imageArray:[String] = []
var titleArray:[String] = []
for i in inTopTopic {
imageArray.append(i.coverImage ?? "")
titleArray.append(i.title)
}
self.cycleScrollView?.imageURLStringsGroup = imageArray
self.cycleScrollView?.titlesGroup = titleArray
self.cycleScrollView?.frame = CGRect(x: 0, y: 0, width: self.tableView.bounds.width, height: self.cycleScrollViewHeight)
self.tableView.tableHeaderView = self.cycleScrollView
}else{
if self.cycleScrollView != nil {
self.tableView.tableHeaderView = nil
self.cycleScrollView?.removeFromSuperview()
self.cycleScrollView = nil
}
}
self.page = 1
self.dataSource = NSMutableArray(array: inObject!)
self.tableView.refreshControl?.endRefreshing()
self.tableView.reloadData()
if self.tableView.refreshControl == nil {
let rc:UIRefreshControl = UIRefreshControl()
rc.addTarget(self, action: #selector(self.headerRefreshAction), for: UIControlEvents.valueChanged)
self.tableView.refreshControl = rc
}
if self.tableView.mj_footer == nil {
self.tableView.mj_footer = MJRefreshAutoNormalFooter(refreshingTarget: self, refreshingAction: #selector(self.footerRefreshAction))
}
}
}
//MARK: - ScrollViewDelegate
func scrollViewDidScroll(_ scrollView: UIScrollView) {
if scrollView != tableView {
return
}
}
//MARK: - SDCycleScrollViewDelegate
func cycleScrollView(_ cycleScrollView: SDCycleScrollView!, didSelectItemAt index: Int) {
guard let review:Review = self.topTopicDataSource.safeGet(at: index) as? Review else {
log.error("can not get top topic for index \(index), data source count:\(self.topTopicDataSource.count)")
return
}
var nextController:UIViewController?
if review.targetUrl.hasSuffix("www.dxomark.com/Cameras/") || review.targetUrl.hasSuffix("www.dxomark.com/Cameras") {
//go to camera DB
nextController = DeviceDatabaseController(deviceType: Device.DeviceType.camera)
}else if review.targetUrl.hasSuffix("www.dxomark.com/Lenses/") || review.targetUrl.hasSuffix("www.dxomark.com/Lenses") {
//go to lenses DB
nextController = DeviceDatabaseController(deviceType: Device.DeviceType.lens)
}else {
nextController = NewsDetailController(review: review)
}
if nextController == nil {
return
}
nextController?.hidesBottomBarWhenPushed = true
self.navigationController?.pushViewController(nextController!, animated: true)
}
}
| 39.717277 | 162 | 0.605062 |
cdbfb2cd74b2c13adb668c8c5ca77bba6afbcc95 | 1,217 | cs | C# | Assets/Scripts/Player.cs | goldenxp/blocks | 880b0ea45a8bf813269802f0ae97aa1859ea9534 | [
"MIT"
] | null | null | null | Assets/Scripts/Player.cs | goldenxp/blocks | 880b0ea45a8bf813269802f0ae97aa1859ea9534 | [
"MIT"
] | null | null | null | Assets/Scripts/Player.cs | goldenxp/blocks | 880b0ea45a8bf813269802f0ae97aa1859ea9534 | [
"MIT"
] | null | null | null | using UnityEngine;
using UnityEngine.InputSystem;
public class Player : Mover
{
public static Player instance;
public static Player Get() { return instance; }
Vector3 direction = Vector3.zero;
public InputActionReference actionMove;
void Awake()
{
instance = this;
}
void OnEnable()
{
actionMove.action.Enable();
}
void OnDisable()
{
actionMove.action.Disable();
}
void Update ()
{
if (CanInput())
CheckInput();
}
public bool CanInput()
{
return !Game.isMoving && !Game.Get().holdingUndo;
}
public void CheckInput()
{
Vector2 axes = actionMove.action.ReadValue<Vector2>();
float hor = axes.x;
float ver = axes.y;
if (hor == 0 && ver == 0)
return;
if (hor != 0 && ver != 0)
{
if (direction == Game.Get().MoveLeft || direction == Game.Get().MoveRight)
hor = 0;
else
ver = 0;
}
if (hor == 1)
direction = Game.Get().MoveRight;
else if (hor == -1)
direction = Game.Get().MoveLeft;
else if (ver == -1)
direction = Game.Get().MoveDown;
else if (ver == 1)
direction = Game.Get().MoveUp;
if (CanMove(direction))
{
MoveIt(direction);
Game.Get().MoveStart(direction);
} else
Game.moversToMove.Clear();
}
}
| 16.671233 | 77 | 0.6212 |
23c683accc8989017b53e094dc35f7dbd6bad4da | 2,543 | js | JavaScript | packages/aws-client/tests/test-SQS.js | lindsleycj/cumulus | 77bfd0f51ce55237febe7da506e137e7f981845a | [
"Apache-2.0"
] | 185 | 2018-07-23T20:31:12.000Z | 2022-03-21T06:29:12.000Z | packages/aws-client/tests/test-SQS.js | lindsleycj/cumulus | 77bfd0f51ce55237febe7da506e137e7f981845a | [
"Apache-2.0"
] | 564 | 2018-07-19T15:46:59.000Z | 2022-03-23T14:53:33.000Z | packages/aws-client/tests/test-SQS.js | lindsleycj/cumulus | 77bfd0f51ce55237febe7da506e137e7f981845a | [
"Apache-2.0"
] | 114 | 2018-08-02T13:33:56.000Z | 2022-03-14T18:58:57.000Z | const test = require('ava');
const cryptoRandomString = require('crypto-random-string');
const { Console } = require('console');
const { Writable } = require('stream');
const Logger = require('@cumulus/logger');
const { sqs } = require('../services');
const {
createQueue,
getQueueNameFromUrl,
parseSQSMessageBody,
sqsQueueExists,
sendSQSMessage,
} = require('../SQS');
const randomString = () => cryptoRandomString({ length: 10 });
class TestStream extends Writable {
constructor(options) {
super(options);
this.output = '';
}
_write(chunk, _encoding, callback) {
this.output += chunk;
callback();
}
}
class TestConsole extends Console {
constructor() {
const stdoutStream = new TestStream();
const stderrStream = new TestStream();
super(stdoutStream, stderrStream);
this.stdoutStream = stdoutStream;
this.stderrStream = stderrStream;
}
get stdoutLogEntries() {
return this.stdoutStream.output
.trim()
.split('\n')
.filter((line) => line.length > 0)
.map(JSON.parse);
}
get stderrLogEntries() {
return this.stderrStream.output
.trim()
.split('\n')
.filter((line) => line.length > 0)
.map(JSON.parse);
}
}
test('parseSQSMessageBody parses messages correctly', (t) => {
const messageBody = { test: 'value' };
const bodyString = JSON.stringify(messageBody);
t.deepEqual(parseSQSMessageBody({ Body: bodyString }), messageBody);
t.deepEqual(parseSQSMessageBody({ body: bodyString }), messageBody);
t.deepEqual(parseSQSMessageBody({}), {});
});
test('sqsQueueExists detects if the queue does not exist or is not accessible', async (t) => {
const queueUrl = await createQueue(randomString());
t.true(await sqsQueueExists(queueUrl));
t.false(await sqsQueueExists(randomString()));
await sqs().deleteQueue({ QueueUrl: queueUrl }).promise();
});
test('getQueueNameFromUrl extracts queue name from a queue URL', (t) => {
const queueName = 'MyQueue';
const queueUrl = `https://sqs.us-east-2.amazonaws.com/123456789012/${queueName}`;
const extractedName = getQueueNameFromUrl(queueUrl);
t.is(extractedName, queueName);
});
test('sendSQSMessage logs errors', async (t) => {
const testConsole = new TestConsole();
const log = new Logger({ console: testConsole });
await t.throwsAsync(
sendSQSMessage('fakequeue', 'Queue message', log),
{ instanceOf: Error }
);
t.is(testConsole.stderrLogEntries.length, 1);
t.regex(testConsole.stderrLogEntries[0].message, /fakequeue/);
});
| 27.641304 | 94 | 0.679119 |
a43d0e832108318216d5f86ed59caa35951f44ac | 9,217 | php | PHP | application/models/MEmployee.php | trisonsystem/api-yotaka | 60c545a253ad338b02e322eb0dec2f0938b1a7a0 | [
"MIT"
] | null | null | null | application/models/MEmployee.php | trisonsystem/api-yotaka | 60c545a253ad338b02e322eb0dec2f0938b1a7a0 | [
"MIT"
] | null | null | null | application/models/MEmployee.php | trisonsystem/api-yotaka | 60c545a253ad338b02e322eb0dec2f0938b1a7a0 | [
"MIT"
] | null | null | null | <?php
class MEmployee extends CI_Model {
public function __construct(){
parent::__construct();
}
public function search_employee( $aData ){
$lm = 15;
if ( !isset($aData["page"]) ) { $aData["page"] = 1;}
if ( !isset($aData["employee_id"]) ) { $aData["employee_id"] = "";}
if ( !isset($aData["employee_code"]) ) { $aData["employee_code"] = "";}
if ( !isset($aData["employee_name"]) ) { $aData["employee_name"] = "";}
if ( !isset($aData["employee_lastname"]) ) { $aData["employee_lastname"] = "";}
if ( !isset($aData["position_id"]) ) { $aData["position_id"] = "";}
if ( !isset($aData["department_id"]) ) { $aData["department_id"] = "";}
if ( !isset($aData["division_id"]) ) { $aData["division_id"] = "";}
if ( !isset($aData["employee_status"]) ){ $aData["employee_status"] = "";}
$LIMIT = ( $aData["page"] == "" ) ? "0, $lm" : (($aData["page"] * $lm) - $lm).",$lm" ;
$WHERE = "";
$WHERE .= ( $aData["employee_id"] == "" ) ? "" : " AND EM.id='".$aData["employee_id"]."'";
$WHERE .= ( $aData["employee_code"] == "" ) ? "" : " AND EM.code LIKE '%".$aData["employee_code"]."%'";
$WHERE .= ( $aData["employee_name"] == "" ) ? "" : " AND EM.name LIKE '%".$aData["employee_name"]."%'";
$WHERE .= ( $aData["employee_lastname"]== "" ) ? "" : " AND EM.last_name LIKE '%".$aData["employee_lastname"]."%'";
$WHERE .= ( $aData["position_id"] == "" ) ? "" : " AND PS.id='".$aData["position_id"]."'";
$WHERE .= ( $aData["department_id"] == "" ) ? "" : " AND DP.id='".$aData["department_id"]."'";
$WHERE .= ( $aData["division_id"] == "" ) ? "" : " AND DV.id='".$aData["division_id"]."'";
$WHERE .= ( $aData["employee_status"] == "" ) ? "" : " AND EM.m_status_employee_id='".$aData["employee_status"]."'";
$WHERE .= " AND EM.hotel_id='".$aData["hotel_id"]."'";
$sql = "SELECT EM.*,
PS.name AS position_name,
DP.name AS department_name,
DV.name AS division_name,
SE.name AS status_name
FROM m_employee AS EM
LEFT JOIN m_position AS PS ON PS.id = EM.m_position_id
LEFT JOIN m_department AS DP ON DP.id = EM.m_department_id
LEFT JOIN m_division AS DV ON DV.id = EM.m_division_id
LEFT JOIN m_status_employee AS SE ON SE.id = EM.m_status_employee_id
WHERE 1 = 1 $WHERE
ORDER BY EM.id DESC
LIMIT $LIMIT";
$query = $this->db->query($sql);
$arr = array();
foreach ($query->result_array() as $key => $value) {
$arr[] = $value;
}
$arr["limit"] = $lm;
// debug($arr);
return $arr;
}
public function search_division( $aData ){
$WHERE = "";
if ($aData != "") {
$WHERE = ( $aData["division_id"] == "" ) ? "" : " AND DV.id='".$aData["division_id"]."'";
$WHERE .= " AND DV.hotel_id='".$aData["hotel_id"]."'";
}
$sql = " SELECT DV.*
FROM m_division AS DV
WHERE 1 = 1 $WHERE
ORDER BY DV.id ASC";
$query = $this->db->query($sql);
$arr = array();
foreach ($query->result_array() as $key => $value) {
$arr[] = $value;
}
// debug($arr);
return $arr;
}
public function search_department( $aData ){
$WHERE = "";
if ($aData != "") {
$WHERE .= ( !isset($aData["department_id"]) ) ? "" : " AND DP.id='".$aData["department_id"]."'";
$WHERE .= ( !isset($aData["division_id"]) ) ? "" : " AND DP.m_division_id='".$aData["division_id"]."'";
$WHERE .= " AND DP.hotel_id='".$aData["hotel_id"]."'";
}
$sql = " SELECT DP.*
FROM m_department AS DP
WHERE 1 = 1 $WHERE
ORDER BY DP.id ASC";
$query = $this->db->query($sql);
$arr = array();
foreach ($query->result_array() as $key => $value) {
$arr[] = $value;
}
// debug($arr);
return $arr;
}
public function search_position( $aData ){
$WHERE = "";
if ($aData != "") {
$WHERE .= ( !isset($aData["position_id"]) ) ? "" : " AND PS.id='".$aData["position_id"]."'";
$WHERE .= ( !isset($aData["division_id"]) ) ? "" : " AND PS.m_division_id='".$aData["division_id"]."'";
$WHERE .= ( !isset($aData["department_id"]) ) ? "" : " AND PS.m_department_id='".$aData["department_id"]."'";
$WHERE .= " AND PS.hotel_id='".$aData["hotel_id"]."'";
}
$sql = " SELECT PS.*
FROM m_position AS PS
WHERE 1 = 1 $WHERE
ORDER BY PS.id ASC";
$query = $this->db->query($sql);
$arr = array();
foreach ($query->result_array() as $key => $value) {
$arr[] = $value;
}
// debug($arr);
return $arr;
}
public function search_status_employee( $aData ){
$WHERE = "";
if ($aData != "") {
$WHERE = ( !isset($aData["status_employee_id"] ) ) ? "" : " AND SE.id='".$aData["status_employee_id"]."'";
}
$sql = " SELECT SE.*
FROM m_status_employee AS SE
WHERE 1 = 1 $WHERE
ORDER BY SE.id ASC";
$query = $this->db->query($sql);
$arr = array();
foreach ($query->result_array() as $key => $value) {
$arr[] = $value;
}
// debug($arr);
return $arr;
}
public function save_data( $aData ){
$aReturn = array();
$arrParam = array('slDivision','slDepartment','slPosition','txtBirthday','txtPrefix','txtName','txtLastName','txtCardNumber','rTypeCard','txtAddress','txtTel','txtEmail','hotel_id','slRights','txtEmployeeProfile','password');
foreach ($arrParam as $key) {
if(!isset($aData[$key])){
return array( "flag"=>false, "msg"=>"Parameter Error ".$key);
exit();
}
}
$code = ($aData["txtEmployee_id"] == "0") ? $this->create_employee_code( $aData["slDivision"], $aData["slDepartment"], $aData["slPosition"] ) : $aData["txtEmployee_code"] ;
$fodel = "assets/upload/employee_profile/";
$aFN = explode(".", $aData["txtEmployeeProfile"]);
$n_name = $aFN[count($aFN)-1];
$n_path = $fodel.$code.".".$n_name;
$aSave = array();
$aSave["m_division_id"] = $aData["slDivision"];
$aSave["m_department_id"] = $aData["slDepartment"];
$aSave["m_position_id"] = $aData["slPosition"];
$aSave["prefix"] = $aData["txtPrefix"];
$aSave["name"] = $aData["txtName"];
$aSave["last_name"] = $aData["txtLastName"];
$aSave["id_card"] = $aData["txtCardNumber"];
$aSave["type_card"] = $aData["rTypeCard"];
$aSave["address"] = $aData["txtAddress"];
$aSave["tel"] = $aData["txtTel"];
$aSave["email"] = $aData["txtEmail"];
$aSave["hotel_id"] = $aData["hotel_id"];
$aSave["rights"] = $aData["slRights"];
$aSave["birthday"] = $this->convert_date_to_base( $aData["txtBirthday"] );
if ($aData["txtEmployeeProfile"] != "0") {
$aSave["profile_img"] = $n_path;
}
if ($aData["txtEmployee_id"] == "0") {
$aSave["code"] = $code;
$aSave["username"] = $code;//$aData["txtUsername"];
$aSave["password"] = md5($aData["txtPassWord"]);
$aSave["m_status_employee_id"] = "1";
$aSave["create_date"] = date("Y-m-d H:i:s");
$aSave["create_by"] = $aData["user"];
$aSave["update_date"] = date("Y-m-d H:i:s");
$aSave["update_by"] = $aData["user"];
if ($this->db->replace('m_employee', $aSave)) {
$aReturn["flag"] = true;
$aReturn["msg"] = "success";
$aReturn["code"] = $code;
}else{
$aReturn["flag"] = false;
$aReturn["msg"] = "Error SQL !!!";
}
}else{
$aSave["update_date"] = date("Y-m-d H:i:s");
$aSave["update_by"] = $aData["user"];
$this->db->where("id", $aData["txtEmployee_id"] );
if ($this->db->update('m_employee', $aSave)) {
$aReturn["flag"] = true;
$aReturn["msg"] = "success";
$aReturn["code"] = $code;
}else{
$aReturn["flag"] = false;
$aReturn["msg"] = "Error SQL !!!";
}
}
// debug($aSave);
return $aReturn;
}
function convert_date_to_base($str_date){
if ($str_date != "") {
$aDate = explode("-", $str_date);
return $aDate["2"]."-".$aDate["1"]."-".$aDate["0"];
}
}
function create_employee_code($division_id, $department, $Position_id){
$time = "-".substr(date("Y") + 543, 2).date("m");
$sql = " SELECT DV.code AS devision_code,
DP.code AS department_code,
PS.code AS position_code,
MAX( EM.code ) AS employee_code
FROM m_division AS DV
LEFT JOIN m_department AS DP ON DV.id = DP.m_division_id
LEFT JOIN m_position AS PS ON DV.id = DP.m_division_id AND DP.id = PS.m_department_id
LEFT JOIN m_employee AS EM ON EM.code LIKE CONCAT(DV.code ,DP.code, PS.code,$time, '%')";
$query = $this->db->query($sql);
$arr = array();
foreach ($query->result_array() as $key => $value) {
$arr[] = $value;
}
if (count($arr) > 0) {
$aCode = explode("-", $arr[0]["employee_code"]);
$code = $aCode[1]+1;
$code = number_format("0.".$code, 7);
$code = $aCode[0]."-".substr($code, 2);
}
return $code;
}
function chang_status( $aData ){
$aSave["update_date"] = date("Y-m-d H:i:s");
$aSave["update_by"] = $aData["user"];
$aSave["m_status_employee_id"] = $aData["status"];
$this->db->where("id", $aData["employee_id"] );
if ($this->db->update('m_employee', $aSave)) {
$aReturn["flag"] = true;
$aReturn["msg"] = "success";
}else{
$aReturn["flag"] = false;
$aReturn["msg"] = "Error SQL !!!";
}
return $aReturn;
}
} | 34.912879 | 227 | 0.552566 |
a456c9367bbc650ab092f487d5deaa00d5974e7d | 2,157 | php | PHP | resources/views/post/category.blade.php | Adtyya/anywalp | 375320303635ef8e49239aa74089df04f9f0440e | [
"MIT"
] | null | null | null | resources/views/post/category.blade.php | Adtyya/anywalp | 375320303635ef8e49239aa74089df04f9f0440e | [
"MIT"
] | null | null | null | resources/views/post/category.blade.php | Adtyya/anywalp | 375320303635ef8e49239aa74089df04f9f0440e | [
"MIT"
] | null | null | null | @extends('default.admin')
@section('content')
<section>
<main class="col-md-9 ms-sm-auto col-lg-10">
<h3>Tambah Kategori Baru</h3>
<div class="row">
<div class="col-lg">
<form action="/storeCategory" method="POST">
@csrf
<div class="col-md-6">
<div class="form-group mt-2">
<label for="nama" class="mb-2">Nama kategori</label>
<input type="text" name="nama" placeholder="Masukan nama kategori" class="form-control" required>
</div>
</div>
<div class="col-md-6">
<div class="form-group mt-2">
<input type="hidden" name="slug" placeholder="Masukan slug" class="form-control" required>
</div>
</div>
<div class="form-gorup mt-2">
<button type="submit" class="btn" style="background-color: #082032;color:white">Tambah kategori</button>
</div>
</form>
</div>
</div>
</main>
<main class="col-md-9 ms-sm-auto col-lg-10">
<div class="table-responsive col-lg-8 mt-3">
<table class="table table-striped table-md">
<thead>
<tr>
<th scope="col">No</th>
<th scope="col">Nama kategori</th>
<th scope="col">Slug</th>
<th scope="col">Action</th>
</tr>
</thead>
<tbody>
@foreach ($data as $no => $item)
<tr>
<td>{{ $data->firstItem()+ $no }}</td>
<td>{{ $item->nama }}</td>
<td>{{ $item->slug }}</td>
<td>
<a href="{{url('/delete/'.$item->id)}}" class="btn btn-danger">Hapus</a>
</td>
</tr>
@endforeach
</tbody>
</table>
</div>
</main>
</section>
@endsection | 38.517857 | 128 | 0.405656 |
094271935d68df7e520bb284098d1f7f212f41f6 | 580 | ps1 | PowerShell | automatic/bsnes-hd/tools/chocolateyInstall.ps1 | Xav83/chocolatey-packages | 717eddf7808c9e55399902cb8ad63b6c50fba0e1 | [
"Apache-2.0"
] | 1 | 2020-09-29T10:56:55.000Z | 2020-09-29T10:56:55.000Z | automatic/bsnes-hd/tools/chocolateyInstall.ps1 | Xav83/chocolatey-packages | 717eddf7808c9e55399902cb8ad63b6c50fba0e1 | [
"Apache-2.0"
] | 6 | 2021-01-18T00:29:17.000Z | 2022-01-13T13:23:52.000Z | automatic/bsnes-hd/tools/chocolateyInstall.ps1 | Xav83/chocolatey-packages | 717eddf7808c9e55399902cb8ad63b6c50fba0e1 | [
"Apache-2.0"
] | 2 | 2020-09-29T10:57:21.000Z | 2021-02-08T07:37:29.000Z | $ErrorActionPreference = 'Stop'
$packageName = $env:ChocolateyPackageName
$url64 = 'https://github.com/DerKoun/bsnes-hd/releases/download/beta_10_6/bsnes_hd_beta_10_6_windows.zip'
$checksum64 = '31c4d27e74ff8d87e9e7da7ca9c64960d5f69e6b6d6c805120145e955067e445'
$packageArgs = @{
packageName = $packageName
fileType = 'ZIP'
url64Bit = $url64
checksum64 = $checksum64
checksumType64 = 'sha256'
unzipLocation = Split-Path $MyInvocation.MyCommand.Definition
validExitCodes = @(0)
}
Install-ChocolateyZipPackage @packageArgs
| 34.117647 | 112 | 0.731034 |
bb5188b82cf4cb3b774f0c688c6391cd364bf941 | 1,177 | cs | C# | src/Anthurium.API/Dtos/AssetUpdateDto.cs | CurlyBytes/Anthurium | c5c80b3ae2e9fbb7dc795863364c54cbeeb76e04 | [
"MIT"
] | 1 | 2021-03-05T14:45:32.000Z | 2021-03-05T14:45:32.000Z | src/Anthurium.API/Dtos/AssetUpdateDto.cs | CurlyBytes/Anthurium | c5c80b3ae2e9fbb7dc795863364c54cbeeb76e04 | [
"MIT"
] | 15 | 2021-02-19T00:26:54.000Z | 2021-04-17T20:48:59.000Z | src/Anthurium.API/Dtos/AssetUpdateDto.cs | CurlyBytes/Anthurium | c5c80b3ae2e9fbb7dc795863364c54cbeeb76e04 | [
"MIT"
] | null | null | null | using Anthurium.API.Helpers;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
namespace Anthurium.API.Dtos {
public class AssetUpdateDto {
[Key]
public int AssetId {
get;
set;
}
[Required]
public int ClientInformationId {
get;
set;
}
public ClientInformationUpdateDto ClientInformation {
get;
set;
}
[Required]
public int VendorId {
get;
set;
}
public VendorUpdateDto Vendor {
get;
set;
}
[Required]
public int ItemId {
get;
set;
}
public ItemUpdateDto Item {
get;
set;
}
[Required]
public DateTime WarrantyDate {
get;
set;
}
[Required]
[MaxLength(200)]
public string SerialNumber {
get;
set;
}
[Required]
public DateTime DateRecieve {
get;
set;
}
[Required]
public DateTime DateUpdated {
get;
set;
}
= DateTime.UtcNow;
[Required]
public bool IsActive {
get;
set;
}
= true;
}
}
| 14.011905 | 57 | 0.557349 |
e720503ce7e287b027908ad51a93d45c63f3564f | 2,386 | php | PHP | application/views/Profile/index.php | keenu1/frameworkwebUAS | 3043faf12f8c4c8e0c0bda0c0dc04ac9dbc261ce | [
"MIT"
] | null | null | null | application/views/Profile/index.php | keenu1/frameworkwebUAS | 3043faf12f8c4c8e0c0bda0c0dc04ac9dbc261ce | [
"MIT"
] | null | null | null | application/views/Profile/index.php | keenu1/frameworkwebUAS | 3043faf12f8c4c8e0c0bda0c0dc04ac9dbc261ce | [
"MIT"
] | null | null | null | <div class="container-fluid">
<div class="col-sm-12">
<div class="clearfix">
<div class="float-left">
<h1 class="h3 mb-4 text-gray-800"><?= $titleHeader ?> </h1>
</div>
</div>
<hr>
</div>
<div class="col-md-4 offset-1 mt-5 mb-auto">
<form action="<?php echo base_url() . 'profile/update'; ?>" method="post">
<input <?= ($titleHeader == 'Detail') ? 'readonly' : null ?> type="hidden" name="id" value="<?= $user['id'] ?>">
<div class="form-group">
<label for="username">Nama</label>
<input <?= ($titleHeader == 'Profile') ? 'readonly' : null ?> type="text" name="username" class="form-control" value="<?= $user['name'] ?>">
</div>
<div class="form-group">
<label for="alamat">Email</label>
<input <?= ($titleHeader == 'Profile') ? 'readonly' : null ?> type="text" name="alamat" class="form-control" value="<?= $user['email'] ?>">
</div>
<div class="form-group">
<label for="phone_number">NO Handphone</label>
<input <?= ($titleHeader == 'Profile') ? 'readonly' : null ?> type="text" name="phone_number" class="form-control" value="<?= $user['phone_number'] ?>">
</div>
<div class="form-group">
<label for="address">Alamat</label>
<input <?= ($titleHeader == 'Profile') ? 'readonly' : null ?> type="text" name="address" class="form-control" value="<?= $user['address'] ?>">
</div>
<?php if ($titleHeader == 'Edit') : ?>
<button type='submit' class="btn btn-sm btn-info"><i class="fa fa-save"></i> Simpan</button>
<a href="<?= base_url('User/akun') ?>" class="btn btn-sm btn-secondary"><i class="fa fa-reply"></i> Kembali</a>
<?php endif ?>
<?php if ($titleHeader == 'Profile') : ?>
<div class="row mt-5 ml-5">
<a href="<?= base_url('profile/edit/') ?>" class="btn btn-info"><i class="fa fa-edit"></i>Edit</a>
</div>
<?php endif ?>
</form>
</div>
</div>
</div> | 55.488372 | 172 | 0.45264 |
759822765d4542419527083216fb330a1b4af9b6 | 526 | css | CSS | ivolunteer/public/images/client/templates/css/notice_messages.css | kds119/eBay-Opportunity-Hack-Blr-2014 | 3bb0d35c88f4001a2fc50dca6349b06bc7f2f33d | [
"MIT"
] | 3 | 2015-05-28T04:30:06.000Z | 2016-12-11T01:19:10.000Z | ivolunteer/client/templates/css/notice_messages.css | ebayohblr2014/eBay-Opportunity-Hack-Blr-2014 | 3bb0d35c88f4001a2fc50dca6349b06bc7f2f33d | [
"MIT"
] | 11 | 2015-02-04T05:06:23.000Z | 2015-02-04T06:24:32.000Z | client/templates/css/notice_messages.css | channikhabra/iVolunteer | f95aa18b3a657ffd4b109873458c2b335f60ee04 | [
"MIT"
] | 2 | 2015-02-05T06:16:58.000Z | 2015-02-05T16:10:46.000Z | .alert {
margin-bottom: 10px;
margin-top: 0;
color: #675100;
border-width: 0;
border-left-width: 5px;
padding: 10px;
border-radius: 0;
-webkit-border-radius: 0;
-moz-border-radius: 0;
}
.alert-success {
border-color: #8ac38b;
color: #356635;
background-color: #cde0c4;
}
.alert-warning {
border-color: #dfb56c;
color: #826430;
background-color: #efe1b3;
}
.alert-info {
border-color: #9cb4c5;
color: #305d8c;
background-color: #d6dde7;
}
.danger {
color: #a94442;
cursor: pointer;
} | 15.470588 | 28 | 0.648289 |
958add6233807b1f57fa7bf555d5d03710c082da | 19,031 | sql | SQL | modules/EmergencyMedicine/sql/demo_fulldata.sql | MohGovIL/Clinical-Vertical-emergency-medicine-backend | 081f60f68be018bc9024878750fb0d47984861a7 | [
"MIT"
] | null | null | null | modules/EmergencyMedicine/sql/demo_fulldata.sql | MohGovIL/Clinical-Vertical-emergency-medicine-backend | 081f60f68be018bc9024878750fb0d47984861a7 | [
"MIT"
] | 1 | 2020-08-27T15:01:43.000Z | 2020-08-27T15:01:43.000Z | modules/EmergencyMedicine/sql/demo_fulldata.sql | MohGovIL/Clinical-Vertical-emergency-medicine-backend | 081f60f68be018bc9024878750fb0d47984861a7 | [
"MIT"
] | 1 | 2020-11-01T11:08:22.000Z | 2020-11-01T11:08:22.000Z |
SET @current_date = '2020-08-27';
SET @current_date_time = '2020-08-27 12:00:00';
SET @bod = '1993-08-02';
SET @fname = 'בדיקה';
SET @lname = 'שניה';
SET @ss = '301190385';
SET @gender = 'Female';
SET @user_id = 1;
SET @pid = (select (MAX(id) + 1) From patient_data);
SET @uuid = '0x91626ecbe35f4b66bb85e5bc795b0991';
SET @facility = 15;
--
-- Dumping data for table `patient_data`
--
INSERT INTO `patient_data` (`pid`, `uuid`, `title`, `language`, `financial`, `fname`, `lname`, `mname`, `DOB`, `street`, `postal_code`, `city`, `state`, `country_code`, `drivers_license`, `ss`, `occupation`, `phone_home`, `phone_biz`, `phone_contact`, `phone_cell`, `pharmacy_id`, `status`, `contact_relationship`, `date`, `sex`, `referrer`, `referrerID`, `providerID`, `ref_providerID`, `email`, `email_direct`, `ethnoracial`, `race`, `ethnicity`, `religion`, `interpretter`, `migrantseasonal`, `family_size`, `monthly_income`, `billing_note`, `homeless`, `financial_review`, `genericname1`, `genericval1`, `genericname2`, `genericval2`, `hipaa_mail`, `hipaa_voice`, `hipaa_notice`, `hipaa_message`, `hipaa_allowsms`, `hipaa_allowemail`, `squad`, `fitness`, `referral_source`, `usertext1`, `usertext2`, `usertext3`, `usertext4`, `usertext5`, `usertext6`, `usertext7`, `usertext8`, `userlist1`, `userlist2`, `userlist3`, `userlist4`, `userlist5`, `userlist6`, `userlist7`, `pricelevel`, `regdate`, `contrastart`, `completed_ad`, `ad_reviewed`, `vfc`, `mothersname`, `guardiansname`, `allow_imm_reg_use`, `allow_imm_info_share`, `allow_health_info_ex`, `allow_patient_portal`, `deceased_date`, `deceased_reason`, `soap_import_status`, `cmsportal_login`, `care_team`, `county`, `industry`, `imm_reg_status`, `imm_reg_stat_effdate`, `publicity_code`, `publ_code_eff_date`, `protect_indicator`, `prot_indi_effdate`, `guardianrelationship`, `guardiansex`, `guardianaddress`, `guardiancity`, `guardianstate`, `guardianpostalcode`, `guardiancountry`, `guardianphone`, `guardianworkphone`, `guardianemail`, `mh_house_no`, `mh_pobox`, `mh_type_id`, `mh_english_name`, `mh_insurance_organiz`) VALUES
(@pid, @uuid, '', '', '', @fname, @lname, '', @bod, '', '', '', '', '', '', @ss, NULL, '', '', '', '0523441345', 0, '', '', NULL, @gender, '', '', NULL, NULL, '', '', '', '', '', '', '', '', '', '', NULL, '', NULL, '', '', '', '', '', '', '', '', 'NO', 'NO', '', 0, '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', 'standard', NULL, NULL, 'NO', NULL, '', '', NULL, '', '', '', '', '0000-00-00 00:00:00', '', NULL, '', NULL, '', NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, '', '', 'teudat_zehut', '', '7');
--
-- Dumping data for table `form_encounter`
--
INSERT INTO `form_encounter` (`date`, `reason`, `facility`, `facility_id`, `pid`, `encounter`, `onset_date`, `sensitivity`, `billing_note`, `pc_catid`, `last_level_billed`, `last_level_closed`, `last_stmt_date`, `stmt_count`, `provider_id`, `supervisor_id`, `invoice_refno`, `referral_source`, `billing_facility`, `external_id`, `pos_code`, `parent_encounter_id`, `status`, `priority`, `service_type`, `escort_id`, `eid`, `arrival_way`, `reason_codes_details`, `secondary_status`, `status_update_date`) VALUES
(@current_date_time, NULL, NULL, @facility, @pid, NULL, NULL, NULL, NULL, 5, 0, 0, NULL, 0, @user_id, 0, '', '', 0, NULL, NULL, NULL, 'in-progress', 211, 1, 1, 0, 'Independent', 'פירוט פירוט פירוט', 'waiting_for_release', @current_date_time);
SET @enc_id = LAST_INSERT_ID();
--
-- Dumping data for table `encounter_reasoncode_map`
--
INSERT INTO `encounter_reasoncode_map` (`eid`, `reason_code`) VALUES(@enc_id, 1);
INSERT INTO `encounter_reasoncode_map` (`eid`, `reason_code`) VALUES(@enc_id, 2);
INSERT INTO `encounter_reasoncode_map` (`eid`, `reason_code`) VALUES(@enc_id, 11);
-- Dumping data for table `fhir_service_request`
--
INSERT INTO `fhir_service_request` (`category`, `encounter`, `reason_code`, `patient`, `instruction_code`, `order_detail_code`, `order_detail_system`, `patient_instruction`, `requester`, `authored_on`, `status`, `intent`, `note`, `performer`, `occurrence_datetime`, `reason_reference_doc_id`) VALUES
('1', @enc_id, '1', @pid, 'providing_medicine', '1000978', 'details_providing_medicine', NULL, @user_id, @current_date_time, 'completed', 'order', NULL, @user_id, @current_date_time, 0);
INSERT INTO `fhir_service_request` (`category`, `encounter`, `reason_code`, `patient`, `instruction_code`, `order_detail_code`, `order_detail_system`, `patient_instruction`, `requester`, `authored_on`, `status`, `intent`, `note`, `performer`, `occurrence_datetime`, `reason_reference_doc_id`) VALUES
('1', @enc_id, '1', @pid, 'inhalation', NULL, 'details_inhalation', 'זהירות רבה', @user_id, @current_date_time, 'active', 'order', 'המטופל לא רגוע', NULL, '0000-00-00 00:00:00', 0);
INSERT INTO `questionnaire_response` (`form_name`, `encounter`, `subject`, `subject_type`, `create_date`, `update_date`, `create_by`, `update_by`, `source`, `source_type`, `status`) VALUES
('commitment_questionnaire', @enc_id, @pid, 'Patient', @current_date_time, @current_date_time, 0, 0, @pid, 'Patient', 'completed');
SET @form_commitment_questionnaire_id = LAST_INSERT_ID();
--
-- Dumping data for table `form_commitment_questionnaire`
--
INSERT INTO `form_commitment_questionnaire` (`encounter`, `form_id`, `question_id`, `answer`) VALUES(@enc_id, @form_commitment_questionnaire_id, 1, NULL);
INSERT INTO `form_commitment_questionnaire` (`encounter`, `form_id`, `question_id`, `answer`) VALUES(@enc_id, @form_commitment_questionnaire_id, 2, NULL);
INSERT INTO `form_commitment_questionnaire` (`encounter`, `form_id`, `question_id`, `answer`) VALUES(@enc_id, @form_commitment_questionnaire_id, 3, NULL);
INSERT INTO `form_commitment_questionnaire` (`encounter`, `form_id`, `question_id`, `answer`) VALUES(@enc_id, @form_commitment_questionnaire_id, 4, '');
INSERT INTO `form_commitment_questionnaire` (`encounter`, `form_id`, `question_id`, `answer`) VALUES(@enc_id, @form_commitment_questionnaire_id, 5, '');
INSERT INTO `form_commitment_questionnaire` (`encounter`, `form_id`, `question_id`, `answer`) VALUES(@enc_id, @form_commitment_questionnaire_id, 6, '');
INSERT INTO `form_commitment_questionnaire` (`encounter`, `form_id`, `question_id`, `answer`) VALUES(@enc_id, @form_commitment_questionnaire_id, 7, '');
INSERT INTO `form_commitment_questionnaire` (`encounter`, `form_id`, `question_id`, `answer`) VALUES(@enc_id, @form_commitment_questionnaire_id, 8, '');
--
-- Dumping data for table `questionnaire_response`
--
INSERT INTO `questionnaire_response` (`form_name`, `encounter`, `subject`, `subject_type`, `create_date`, `update_date`, `create_by`, `update_by`, `source`, `source_type`, `status`) VALUES
('diagnosis_and_recommendations_questionnaire', @enc_id, @pid, 'Patient', @current_date_time, @current_date_time, 0, 0, @pid, 'Patient', 'completed');
SET @diagnosis_and_recommendations_id = LAST_INSERT_ID();
--
-- Dumping data for table `form_diagnosis_and_recommendations_questionnaire`
--
INSERT INTO `form_diagnosis_and_recommendations_questionnaire` (`encounter`, `form_id`, `question_id`, `answer`) VALUES(@enc_id, @diagnosis_and_recommendations_id, 1, ' טקסט 1 לשדה פירוט הממצאים בהתייבשות\nטקסט 2 לשדה פירוט הממצאים בהתייבשות\n');
INSERT INTO `form_diagnosis_and_recommendations_questionnaire` (`encounter`, `form_id`, `question_id`, `answer`) VALUES(@enc_id, @diagnosis_and_recommendations_id, 2, ' \n טקסט 1 לשדה פירוט האבחנה בהתייבשות\n');
INSERT INTO `form_diagnosis_and_recommendations_questionnaire` (`encounter`, `form_id`, `question_id`, `answer`) VALUES(@enc_id, @diagnosis_and_recommendations_id, 3, 'פרטים חשויבם');
INSERT INTO `form_diagnosis_and_recommendations_questionnaire` (`encounter`, `form_id`, `question_id`, `answer`) VALUES(@enc_id, @diagnosis_and_recommendations_id, 4, ' טקסט 1 לשדה הוראות להמשך טיפול בהתייבשות\n');
INSERT INTO `form_diagnosis_and_recommendations_questionnaire` (`encounter`, `form_id`, `question_id`, `answer`) VALUES(@enc_id, @diagnosis_and_recommendations_id, 5, 'Release to home');
INSERT INTO `form_diagnosis_and_recommendations_questionnaire` (`encounter`, `form_id`, `question_id`, `answer`) VALUES(@enc_id, @diagnosis_and_recommendations_id, 6, 'Independent');
INSERT INTO `form_diagnosis_and_recommendations_questionnaire` (`encounter`, `form_id`, `question_id`, `answer`) VALUES(@enc_id, @diagnosis_and_recommendations_id, 7, '7');
INSERT INTO `form_diagnosis_and_recommendations_questionnaire` (`encounter`, `form_id`, `question_id`, `answer`) VALUES(@enc_id, @diagnosis_and_recommendations_id, 1, ' טקסט 1 לשדה פירוט הממצאים בהתייבשות\nטקסט 2 לשדה פירוט הממצאים בהתייבשות\n');
INSERT INTO `form_diagnosis_and_recommendations_questionnaire` (`encounter`, `form_id`, `question_id`, `answer`) VALUES(@enc_id, @diagnosis_and_recommendations_id, 2, ' \n טקסט 1 לשדה פירוט האבחנה בהתייבשות\n');
INSERT INTO `form_diagnosis_and_recommendations_questionnaire` (`encounter`, `form_id`, `question_id`, `answer`) VALUES(@enc_id, @diagnosis_and_recommendations_id, 3, 'פרטים חשויבם');
INSERT INTO `form_diagnosis_and_recommendations_questionnaire` (`encounter`, `form_id`, `question_id`, `answer`) VALUES(@enc_id, @diagnosis_and_recommendations_id, 4, ' טקסט 1 לשדה הוראות להמשך טיפול בהתייבשות\n');
INSERT INTO `form_diagnosis_and_recommendations_questionnaire` (`encounter`, `form_id`, `question_id`, `answer`) VALUES(@enc_id, @diagnosis_and_recommendations_id, 5, 'Release to home');
INSERT INTO `form_diagnosis_and_recommendations_questionnaire` (`encounter`, `form_id`, `question_id`, `answer`) VALUES(@enc_id, @diagnosis_and_recommendations_id, 6, 'Independent');
INSERT INTO `form_diagnosis_and_recommendations_questionnaire` (`encounter`, `form_id`, `question_id`, `answer`) VALUES(@enc_id, @diagnosis_and_recommendations_id, 7, '7');
--
-- Dumping data for table `questionnaire_response`
--
INSERT INTO `questionnaire_response` (`form_name`, `encounter`, `subject`, `subject_type`, `create_date`, `update_date`, `create_by`, `update_by`, `source`, `source_type`, `status`) VALUES
('medical_admission_questionnaire', @enc_id, @pid, 'Patient', @current_date_time, @current_date_time, 0, 0, @pid, 'Patient', 'completed');
SET @medical_admission_id = LAST_INSERT_ID();
--
-- Dumping data for table `form_medical_admission_questionnaire`
--
INSERT INTO `form_medical_admission_questionnaire` (`encounter`, `form_id`, `question_id`, `answer`) VALUES(@enc_id, @medical_admission_id, 1, '1');
INSERT INTO `form_medical_admission_questionnaire` (`encounter`, `form_id`, `question_id`, `answer`) VALUES(@enc_id, @medical_admission_id, 2, 'לא לצאת מהחדר');
INSERT INTO `form_medical_admission_questionnaire` (`encounter`, `form_id`, `question_id`, `answer`) VALUES(@enc_id, @medical_admission_id, 3, ' \n טקסט 1 לשדה אנמנזה סיעודית בהתייבשות\nטקסט 2 לשדה אנמנזה סיעודית בהתייבשות\n');
INSERT INTO `form_medical_admission_questionnaire` (`encounter`, `form_id`, `question_id`, `answer`) VALUES(@enc_id, @medical_admission_id, 4, 'Yes');
INSERT INTO `form_medical_admission_questionnaire` (`encounter`, `form_id`, `question_id`, `answer`) VALUES(@enc_id, @medical_admission_id, 1, '1');
INSERT INTO `form_medical_admission_questionnaire` (`encounter`, `form_id`, `question_id`, `answer`) VALUES(@enc_id, @medical_admission_id, 2, 'לא לצאת מהחדר');
INSERT INTO `form_medical_admission_questionnaire` (`encounter`, `form_id`, `question_id`, `answer`) VALUES(@enc_id, @medical_admission_id, 3, ' \n טקסט 1 לשדה אנמנזה סיעודית בהתייבשות\nטקסט 2 לשדה אנמנזה סיעודית בהתייבשות\n');
INSERT INTO `form_medical_admission_questionnaire` (`encounter`, `form_id`, `question_id`, `answer`) VALUES(@enc_id, @medical_admission_id, 4, 'Yes');
INSERT INTO `form_medical_admission_questionnaire` (`encounter`, `form_id`, `question_id`, `answer`) VALUES(@enc_id, @medical_admission_id, 1, '1');
--
-- Dumping data for table `form_vitals`
--
INSERT INTO `form_vitals` (`date`, `pid`, `user`, `groupname`, `authorized`, `activity`, `bps`, `bpd`, `weight`, `height`, `temperature`, `temp_method`, `pulse`, `respiration`, `note`, `BMI`, `BMI_status`, `waist_circ`, `head_circ`, `oxygen_saturation`, `external_id`, `glucose`, `pain_severity`, `eid`, `category`) VALUES
(@current_date_time, @pid, @user_id, NULL, 0, 0, NULL, NULL, 78.00, 180.00, 0.00, NULL, 0.00, 0.00, NULL, 0.0, NULL, 0.00, 0.00, 0.00, NULL, NULL, NULL, 2, 'exam');
INSERT INTO `form_vitals` (`date`, `pid`, `user`, `groupname`, `authorized`, `activity`, `bps`, `bpd`, `weight`, `height`, `temperature`, `temp_method`, `pulse`, `respiration`, `note`, `BMI`, `BMI_status`, `waist_circ`, `head_circ`, `oxygen_saturation`, `external_id`, `glucose`, `pain_severity`, `eid`, `category`) VALUES
(@current_date_time, @pid, @user_id, NULL, 0, 0, '56_', '78_', 0.00, 0.00, 0.00, NULL, 87.00, 50.00, NULL, 0.0, NULL, 0.00, 0.00, 0.00, NULL, 0, 8, 2, 'vital-signs');
--
-- Dumping data for table `lists`
--
INSERT INTO `lists` (`date`, `type`, `subtype`, `title`, `begdate`, `enddate`, `returndate`, `occurrence`, `classification`, `referredby`, `extrainfo`, `diagnosis`, `diagnosis_valueset`, `activity`, `comments`, `pid`, `user`, `groupname`, `outcome`, `destination`, `reinjury_id`, `injury_part`, `injury_type`, `injury_grade`, `reaction`, `external_allergyid`, `erx_source`, `erx_uploaded`, `modifydate`, `severity_al`, `external_id`, `list_option_id`) VALUES
(@current_date_time, 'sensitive', '', NULL, NULL, NULL, NULL, NULL, 0, NULL, NULL, 'Sensitivities:40', 'sensitivities', NULL, '', @pid, @user_id, NULL, 0, NULL, 0, '', '', '', '', NULL, '0', '0', @current_date_time, NULL, NULL, NULL);
INSERT INTO `lists` (`date`, `type`, `subtype`, `title`, `begdate`, `enddate`, `returndate`, `occurrence`, `classification`, `referredby`, `extrainfo`, `diagnosis`, `diagnosis_valueset`, `activity`, `comments`, `pid`, `user`, `groupname`, `outcome`, `destination`, `reinjury_id`, `injury_part`, `injury_type`, `injury_grade`, `reaction`, `external_allergyid`, `erx_source`, `erx_uploaded`, `modifydate`, `severity_al`, `external_id`, `list_option_id`) VALUES
(@current_date_time, 'medical_problem', '', NULL, NULL, NULL, NULL, NULL, 0, NULL, NULL, 'BK Diseases:10', 'bk_diseases', NULL, '', @pid, @user_id, NULL, 0, NULL, 0, '', '', '', '', NULL, '0', '0', @current_date_time, NULL, NULL, NULL);
INSERT INTO `lists` (`date`, `type`, `subtype`, `title`, `begdate`, `enddate`, `returndate`, `occurrence`, `classification`, `referredby`, `extrainfo`, `diagnosis`, `diagnosis_valueset`, `activity`, `comments`, `pid`, `user`, `groupname`, `outcome`, `destination`, `reinjury_id`, `injury_part`, `injury_type`, `injury_grade`, `reaction`, `external_allergyid`, `erx_source`, `erx_uploaded`, `modifydate`, `severity_al`, `external_id`, `list_option_id`) VALUES
(@current_date_time, 'medical_problem', '', NULL, NULL, NULL, NULL, NULL, 0, NULL, NULL, 'BK Diseases:20', 'bk_diseases', NULL, '', @pid, @user_id, NULL, 0, NULL, 0, '', '', '', '', NULL, '0', '0', @current_date_time, NULL, NULL, NULL);
INSERT INTO `lists` (`date`, `type`, `subtype`, `title`, `begdate`, `enddate`, `returndate`, `occurrence`, `classification`, `referredby`, `extrainfo`, `diagnosis`, `diagnosis_valueset`, `activity`, `comments`, `pid`, `user`, `groupname`, `outcome`, `destination`, `reinjury_id`, `injury_part`, `injury_type`, `injury_grade`, `reaction`, `external_allergyid`, `erx_source`, `erx_uploaded`, `modifydate`, `severity_al`, `external_id`, `list_option_id`) VALUES
(@current_date_time, 'sensitive', '', NULL, NULL, NULL, NULL, NULL, 0, NULL, NULL, 'Sensitivities:30', 'sensitivities', NULL, '', @pid, @user_id, NULL, 0, NULL, 0, '', '', '', '', NULL, '0', '0', @current_date_time, NULL, NULL, NULL);
INSERT INTO `lists` (`date`, `type`, `subtype`, `title`, `begdate`, `enddate`, `returndate`, `occurrence`, `classification`, `referredby`, `extrainfo`, `diagnosis`, `diagnosis_valueset`, `activity`, `comments`, `pid`, `user`, `groupname`, `outcome`, `destination`, `reinjury_id`, `injury_part`, `injury_type`, `injury_grade`, `reaction`, `external_allergyid`, `erx_source`, `erx_uploaded`, `modifydate`, `severity_al`, `external_id`, `list_option_id`) VALUES
(NULL, 'medication', '', NULL, NULL, NULL, NULL, 0, 0, NULL, NULL, 'MOH_DRUGS:1002300', NULL, NULL, '', @pid, '', NULL, 1, NULL, 0, '', '', '', '', NULL, '0', '0', @current_date_time, NULL, NULL, NULL);
INSERT INTO `lists` (`date`, `type`, `subtype`, `title`, `begdate`, `enddate`, `returndate`, `occurrence`, `classification`, `referredby`, `extrainfo`, `diagnosis`, `diagnosis_valueset`, `activity`, `comments`, `pid`, `user`, `groupname`, `outcome`, `destination`, `reinjury_id`, `injury_part`, `injury_type`, `injury_grade`, `reaction`, `external_allergyid`, `erx_source`, `erx_uploaded`, `modifydate`, `severity_al`, `external_id`, `list_option_id`) VALUES
(NULL, 'medication', '', NULL, NULL, NULL, NULL, 0, 0, NULL, NULL, 'MOH_DRUGS:646461', NULL, NULL, '', @pid, '', NULL, 1, NULL, 0, '', '', '', '', NULL, '0', '0', @current_date_time, NULL, NULL, NULL);
--
-- Dumping data for table `related_person`
--
INSERT INTO `related_person` (`identifier`, `identifier_type`, `active`, `pid`, `relationship`, `phone_home`, `phone_cell`, `email`, `gender`, `full_name`) VALUES
(NULL, NULL, 0, @pid, NULL, '', '0524675567', '', NULL, 'משה ');
--
-- Dumping data for table `prescriptions`
--
INSERT INTO `prescriptions` (`patient_id`, `filled_by_id`, `pharmacy_id`, `date_added`, `date_modified`, `provider_id`, `encounter`, `start_date`, `drug`, `drug_id`, `rxnorm_drugcode`, `form`, `dosage`, `quantity`, `size`, `unit`, `route`, `interval`, `substitute`, `refills`, `per_refill`, `filled_date`, `medication`, `note`, `active`, `datetime`, `user`, `site`, `prescriptionguid`, `erx_source`, `erx_uploaded`, `drug_info_erx`, `external_id`, `end_date`, `indication`, `prn`, `ntx`, `rtx`, `txDate`) VALUES
(@pid, NULL, NULL, NULL, NULL, @user_id, @enc_id, @current_date, 'PILOCARPINE HYDROCHLORIDE 10 MG/ML OPHTHALMIC SOLUTION', 1000647, NULL, 5, '6', NULL, NULL, NULL, 3, 2, NULL, NULL, NULL, NULL, NULL, '', 1, @current_date_time, '1', NULL, NULL, 0, 0, NULL, NULL, '2021-11-01', NULL, NULL, NULL, NULL, '0000-00-00');
INSERT INTO `prescriptions` (`patient_id`, `filled_by_id`, `pharmacy_id`, `date_added`, `date_modified`, `provider_id`, `encounter`, `start_date`, `drug`, `drug_id`, `rxnorm_drugcode`, `form`, `dosage`, `quantity`, `size`, `unit`, `route`, `interval`, `substitute`, `refills`, `per_refill`, `filled_date`, `medication`, `note`, `active`, `datetime`, `user`, `site`, `prescriptionguid`, `erx_source`, `erx_uploaded`, `drug_info_erx`, `external_id`, `end_date`, `indication`, `prn`, `ntx`, `rtx`, `txDate`) VALUES
(@pid, NULL, NULL, NULL, NULL, @user_id, @enc_id, @current_date, 'MEDROXYPROGESTERONE ACETATE 5 MG ORAL TABLET', 1000141, NULL, 3, '6', NULL, NULL, NULL, 3, 13, NULL, NULL, NULL, NULL, NULL, '', 1, @current_date_time, '1', NULL, NULL, 0, 0, NULL, NULL, '2021-11-01', NULL, NULL, NULL, NULL, '0000-00-00');
| 119.691824 | 1,689 | 0.707215 |
ce83536089755172e7b2b9479a1fd9c27eaa98bf | 18,594 | rs | Rust | src/hir/hir_maker.rs | yhara/shiika | e8a92cac2a0a819b243cab5711bddbea0a1f802d | [
"MIT"
] | 108 | 2018-06-08T11:07:38.000Z | 2021-04-01T01:19:58.000Z | src/hir/hir_maker.rs | yhara/shiika | e8a92cac2a0a819b243cab5711bddbea0a1f802d | [
"MIT"
] | 158 | 2019-07-26T11:27:54.000Z | 2021-04-02T08:01:33.000Z | src/hir/hir_maker.rs | yhara/shiika | e8a92cac2a0a819b243cab5711bddbea0a1f802d | [
"MIT"
] | 10 | 2019-12-08T01:59:10.000Z | 2021-03-01T01:33:02.000Z | use crate::ast::*;
use crate::code_gen::CodeGen;
use crate::error;
use crate::error::Error;
use crate::hir::class_dict::ClassDict;
use crate::hir::hir_maker_context::*;
use crate::hir::method_dict::MethodDict;
use crate::hir::*;
use crate::library::LibraryExports;
use crate::names;
use crate::type_checking;
use ctx_stack::CtxStack;
#[derive(Debug)]
pub struct HirMaker<'hir_maker> {
/// List of classes found so far
pub(super) class_dict: ClassDict<'hir_maker>,
/// List of methods found so far
pub(super) method_dict: MethodDict,
/// List of constants found so far
pub(super) constants: HashMap<ConstFullname, TermTy>,
/// Constants defined from other library
pub(super) imported_constants: &'hir_maker HashMap<ConstFullname, TermTy>,
/// Expressions that initialize constants
pub(super) const_inits: Vec<HirExpression>,
/// List of string literals found so far
pub(super) str_literals: Vec<String>,
/// Contextual information
pub(super) ctx_stack: CtxStack,
/// Counter to give unique name for lambdas
pub(super) lambda_ct: usize,
/// Counter for unique name
pub(super) gensym_ct: usize,
}
pub fn make_hir(
ast: ast::Program,
corelib: Option<Corelib>,
imports: &LibraryExports,
) -> Result<Hir, Error> {
let (core_classes, core_methods) = if let Some(c) = corelib {
(c.sk_classes, c.sk_methods)
} else {
(Default::default(), Default::default())
};
let class_dict = class_dict::create(&ast, core_classes, &imports.sk_classes)?;
let mut hir_maker = HirMaker::new(class_dict, &imports.constants);
hir_maker.define_class_constants();
let (main_exprs, main_lvars) = hir_maker.convert_toplevel_items(&ast.toplevel_items)?;
let mut hir = hir_maker.extract_hir(main_exprs, main_lvars);
// While corelib classes are included in `class_dict`,
// corelib methods are not. Here we need to add them manually
hir.add_methods(core_methods);
Ok(hir)
}
impl<'hir_maker> HirMaker<'hir_maker> {
fn new(
class_dict: ClassDict<'hir_maker>,
imported_constants: &'hir_maker HashMap<ConstFullname, TermTy>,
) -> HirMaker<'hir_maker> {
HirMaker {
class_dict,
method_dict: MethodDict::new(),
constants: HashMap::new(),
imported_constants,
const_inits: vec![],
str_literals: vec![],
ctx_stack: CtxStack::new(vec![HirMakerContext::toplevel()]),
lambda_ct: 0,
gensym_ct: 0,
}
}
/// Destructively convert self to Hir
fn extract_hir(&mut self, main_exprs: HirExpressions, main_lvars: HirLVars) -> Hir {
// Extract data from self
let sk_classes = std::mem::take(&mut self.class_dict.sk_classes);
let sk_methods = std::mem::take(&mut self.method_dict.sk_methods);
let mut constants = HashMap::new();
std::mem::swap(&mut constants, &mut self.constants);
let mut str_literals = vec![];
std::mem::swap(&mut str_literals, &mut self.str_literals);
let mut const_inits = vec![];
std::mem::swap(&mut const_inits, &mut self.const_inits);
Hir {
sk_classes,
sk_methods,
constants,
str_literals,
const_inits,
main_exprs,
main_lvars,
}
}
/// Register constants which hold class object
/// eg.
/// - ::Int
/// - ::Meta:Int
fn define_class_constants(&mut self) {
for (name, const_is_obj) in self.class_dict.constant_list() {
let resolved = ResolvedConstName::unsafe_create(name);
if const_is_obj {
// Create constant like `Void`, `Maybe::None`.
let str_idx = self.register_string_literal(&resolved.string());
let ty = ty::raw(&resolved.string());
// The class
let cls_obj =
Hir::class_literal(ty.meta_ty(), resolved.to_class_fullname(), str_idx);
// The instance
let expr = Hir::method_call(
ty,
cls_obj,
method_fullname(&metaclass_fullname(&resolved.string()), "new"),
vec![],
);
self.register_const_full(resolved.to_const_fullname(), expr);
} else {
let ty = ty::meta(&resolved.string());
let str_idx = self.register_string_literal(&resolved.string());
let expr = Hir::class_literal(ty.clone(), resolved.to_class_fullname(), str_idx);
self.register_const_full(resolved.to_const_fullname(), expr);
}
}
}
fn convert_toplevel_items(
&mut self,
items: &[ast::TopLevelItem],
) -> Result<(HirExpressions, HirLVars), Error> {
let mut main_exprs = vec![];
for item in items {
match item {
ast::TopLevelItem::Def(def) => {
self.process_toplevel_def(def)?;
}
ast::TopLevelItem::Expr(expr) => {
main_exprs.push(self.convert_expr(expr)?);
}
}
}
debug_assert!(self.ctx_stack.len() == 1);
let mut toplevel_ctx = self.ctx_stack.pop_toplevel_ctx();
Ok((
HirExpressions::new(main_exprs),
extract_lvars(&mut toplevel_ctx.lvars),
))
}
fn process_toplevel_def(&mut self, def: &ast::Definition) -> Result<(), Error> {
let namespace = Namespace::root();
match def {
// Extract instance/class methods
ast::Definition::ClassDefinition {
name,
typarams,
defs,
..
} => {
self.process_class_def(&namespace, name, typarams.clone(), defs)?;
}
ast::Definition::EnumDefinition {
name,
typarams,
cases,
defs,
} => self.process_enum_def(&namespace, name, typarams.clone(), cases, defs)?,
ast::Definition::ConstDefinition { name, expr } => {
self.register_toplevel_const(name, expr)?;
}
_ => panic!("should be checked in hir::class_dict"),
}
Ok(())
}
/// Process a class definition and its inner defs
fn process_class_def(
&mut self,
namespace: &Namespace,
firstname: &ClassFirstname,
typarams: Vec<TyParam>,
defs: &[ast::Definition],
) -> Result<(), Error> {
let fullname = namespace.class_fullname(firstname);
let meta_name = fullname.meta_name();
self.ctx_stack
.push(HirMakerContext::class(namespace.add(firstname), typarams));
// Register constants before processing #initialize
let inner_namespace = namespace.add(firstname);
self._process_const_defs_in_class(&inner_namespace, defs)?;
// Register #initialize and ivars
let own_ivars =
self._process_initialize(&fullname, defs.iter().find(|d| d.is_initializer()))?;
if !own_ivars.is_empty() {
// Be careful not to reset ivars of corelib/* by builtin/*
self.class_dict.define_ivars(&fullname, own_ivars.clone());
self.define_accessors(&fullname, own_ivars, defs);
}
// Register .new
if fullname.0 != "Class" {
self.method_dict
.add_method(&meta_name, self.create_new(&fullname, false)?);
}
// Process inner defs
for def in defs {
match def {
ast::Definition::InstanceMethodDefinition { sig, body_exprs } => {
if def.is_initializer() {
// Already processed above
} else {
log::trace!("method {}#{}", &fullname, &sig.name);
let method = self.convert_method_def(&fullname, &sig.name, body_exprs)?;
self.method_dict.add_method(&fullname, method);
}
}
ast::Definition::ClassMethodDefinition {
sig, body_exprs, ..
} => {
log::trace!("method {}.{}", &fullname, &sig.name);
let method = self.convert_method_def(&meta_name, &sig.name, body_exprs)?;
self.method_dict.add_method(&meta_name, method);
}
ast::Definition::ConstDefinition { .. } => {
// Already processed above
}
ast::Definition::ClassDefinition {
name,
defs,
typarams,
..
} => self.process_class_def(&inner_namespace, name, typarams.clone(), defs)?,
ast::Definition::EnumDefinition {
name,
typarams,
cases,
defs,
} => {
self.process_enum_def(&inner_namespace, name, typarams.clone(), cases, defs)?
}
}
}
self.ctx_stack.pop_class_ctx();
Ok(())
}
/// Add `#initialize` and return defined ivars
fn _process_initialize(
&mut self,
fullname: &ClassFullname,
initialize: Option<&ast::Definition>,
) -> Result<SkIVars, Error> {
let mut own_ivars = HashMap::default();
if let Some(ast::Definition::InstanceMethodDefinition {
sig, body_exprs, ..
}) = initialize
{
log::trace!("method {}#initialize", &fullname);
let (sk_method, found_ivars) =
self.create_initialize(fullname, &sig.name, body_exprs)?;
self.method_dict.add_method(fullname, sk_method);
own_ivars = found_ivars;
}
Ok(own_ivars)
}
/// Register constants defined in a class
fn _process_const_defs_in_class(
&mut self,
namespace: &Namespace,
defs: &[ast::Definition],
) -> Result<(), Error> {
for def in defs {
if let ast::Definition::ConstDefinition { name, expr } = def {
let full = namespace.const_fullname(name);
let hir_expr = self.convert_expr(expr)?;
self.register_const_full(full, hir_expr);
}
}
Ok(())
}
/// Create the `initialize` method
/// Also, define ivars
fn create_initialize(
&mut self,
class_fullname: &ClassFullname,
name: &MethodFirstname,
body_exprs: &[AstExpression],
) -> Result<(SkMethod, SkIVars), Error> {
let super_ivars = self.class_dict.superclass_ivars(class_fullname);
self.convert_method_def_(class_fullname, name, body_exprs, super_ivars)
}
/// Create .new
fn create_new(
&self,
class_fullname: &ClassFullname,
const_is_obj: bool,
) -> Result<SkMethod, Error> {
let (initialize_name, init_cls_name) =
self._find_initialize(&class_fullname.instance_ty())?;
let (signature, _) = self.class_dict.lookup_method(
&class_fullname.class_ty(),
&method_firstname("new"),
Default::default(),
)?;
let arity = signature.params.len();
let classname = class_fullname.clone();
let new_body = move |code_gen: &CodeGen, function: &inkwell::values::FunctionValue| {
code_gen.gen_body_of_new(
function.get_params(),
&classname,
&initialize_name,
&init_cls_name,
arity,
const_is_obj,
);
Ok(())
};
Ok(SkMethod {
signature,
body: SkMethodBody::RustClosureMethodBody {
boxed_gen: Box::new(new_body),
},
lvars: vec![],
})
}
/// Find actual `initialize` func to call from `.new`
fn _find_initialize(&self, class: &TermTy) -> Result<(MethodFullname, ClassFullname), Error> {
let (_, found_cls) = self.class_dict.lookup_method(
class,
&method_firstname("initialize"),
Default::default(),
)?;
Ok((names::method_fullname(&found_cls, "initialize"), found_cls))
}
/// Register a constant defined in the toplevel
pub(super) fn register_toplevel_const(
&mut self,
name: &str,
expr: &AstExpression,
) -> Result<(), Error> {
let hir_expr = self.convert_expr(expr)?;
self.constants
.insert(toplevel_const(name), hir_expr.ty.clone());
let op = Hir::const_assign(toplevel_const(name), hir_expr);
self.const_inits.push(op);
Ok(())
}
/// Register a constant
pub(super) fn register_const_full(&mut self, fullname: ConstFullname, hir_expr: HirExpression) {
debug_assert!(!self.constants.contains_key(&fullname));
self.constants.insert(fullname.clone(), hir_expr.ty.clone());
let op = Hir::const_assign(fullname, hir_expr);
self.const_inits.push(op);
}
fn convert_method_def(
&mut self,
class_fullname: &ClassFullname,
name: &MethodFirstname,
body_exprs: &[AstExpression],
) -> Result<SkMethod, Error> {
let (sk_method, _ivars) =
self.convert_method_def_(class_fullname, name, body_exprs, None)?;
Ok(sk_method)
}
/// Create a SkMethod and return it with ctx.iivars
fn convert_method_def_(
&mut self,
class_fullname: &ClassFullname,
name: &MethodFirstname,
body_exprs: &[AstExpression],
super_ivars: Option<SkIVars>,
) -> Result<(SkMethod, HashMap<String, SkIVar>), Error> {
// MethodSignature is built beforehand by class_dict::new
let err = format!("[BUG] signature not found ({}/{})", class_fullname, name);
let signature = self
.class_dict
.find_method(class_fullname, name)
.expect(&err)
.clone();
self.ctx_stack
.push(HirMakerContext::method(signature.clone(), super_ivars));
let mut hir_exprs = self.convert_exprs(body_exprs)?;
// Insert ::Void so that last expr always matches to ret_ty
if signature.ret_ty.is_void_type() {
hir_exprs.voidify();
}
let mut method_ctx = self.ctx_stack.pop_method_ctx();
let lvars = extract_lvars(&mut method_ctx.lvars);
type_checking::check_return_value(&self.class_dict, &signature, &hir_exprs.ty)?;
let body = SkMethodBody::ShiikaMethodBody { exprs: hir_exprs };
Ok((
SkMethod {
signature,
body,
lvars,
},
method_ctx.iivars,
))
}
/// Process a enum definition
fn process_enum_def(
&mut self,
namespace: &Namespace,
firstname: &ClassFirstname,
typarams: Vec<TyParam>,
cases: &[ast::EnumCase],
defs: &[ast::Definition],
) -> Result<(), Error> {
let fullname = namespace.class_fullname(firstname);
let inner_namespace = namespace.add(firstname);
for case in cases {
self._register_enum_case_class(&inner_namespace, case)?;
}
self.ctx_stack
.push(HirMakerContext::class(namespace.add(firstname), typarams));
for def in defs {
match def {
ast::Definition::InstanceMethodDefinition {
sig, body_exprs, ..
} => {
if def.is_initializer() {
return Err(error::program_error(
"you cannot define #initialize of enum",
));
} else {
log::trace!("method {}#{}", &fullname, &sig.name);
let method = self.convert_method_def(&fullname, &sig.name, body_exprs)?;
self.method_dict.add_method(&fullname, method);
}
}
_ => panic!("[TODO] in enum {:?}", def),
}
}
self.ctx_stack.pop_class_ctx();
Ok(())
}
/// Create a enum case class
fn _register_enum_case_class(
&mut self,
namespace: &Namespace,
case: &EnumCase,
) -> Result<(), Error> {
let fullname = namespace.class_fullname(&case.name);
// Register #initialize
let signature = self
.class_dict
.find_method(&fullname, &method_firstname("initialize"))
.unwrap();
let self_ty = ty::raw(&fullname.0);
let exprs = signature
.params
.iter()
.enumerate()
.map(|(idx, param)| {
let argref = Hir::arg_ref(param.ty.clone(), idx);
Hir::ivar_assign(¶m.name, idx, argref, false, self_ty.clone())
})
.collect();
let body = SkMethodBody::ShiikaMethodBody {
exprs: HirExpressions::new(exprs),
};
let initialize = SkMethod {
signature: signature.clone(),
body,
lvars: Default::default(),
};
self.method_dict.add_method(&fullname, initialize);
// Register accessors
let ivars = self.class_dict.get_class(&fullname).ivars.clone();
self.define_accessors(&fullname, ivars, Default::default());
// Register .new
let const_is_obj = case.params.is_empty();
self.method_dict.add_method(
&fullname.meta_name(),
self.create_new(&fullname, const_is_obj)?,
);
Ok(())
}
/// Generate special lvar name
pub fn generate_lvar_name(&mut self, prefix: &str) -> String {
let n = self.gensym_ct;
self.gensym_ct += 1;
// Suffix `_` because llvm may add numbers after this name
// eg.
// %"expr@0_3" = load %Maybe*, %Maybe** %"expr@0"
format!("{}@{}_", prefix, n)
}
}
/// Destructively extract list of local variables
pub fn extract_lvars(lvars: &mut HashMap<String, CtxLVar>) -> HirLVars {
std::mem::take(lvars)
.into_iter()
.map(|(name, ctx_lvar)| (name, ctx_lvar.ty))
.collect::<Vec<_>>()
}
| 35.62069 | 100 | 0.550823 |
23b153819402625cd790c250a37a71799731e8db | 971 | js | JavaScript | Code/Beskova.Ontology/Beskova.Ontology.Web/AngularApp/Controllers/userOptionsController.js | MikhailApsalikov/Veronika | 808142f3b308449046d3a2e437342fe832408d1c | [
"MIT"
] | null | null | null | Code/Beskova.Ontology/Beskova.Ontology.Web/AngularApp/Controllers/userOptionsController.js | MikhailApsalikov/Veronika | 808142f3b308449046d3a2e437342fe832408d1c | [
"MIT"
] | 34 | 2017-03-05T12:52:55.000Z | 2017-06-26T18:42:46.000Z | Code/Beskova.Ontology/Beskova.Ontology.Web/AngularApp/Controllers/userOptionsController.js | MikhailApsalikov/Veronika | 808142f3b308449046d3a2e437342fe832408d1c | [
"MIT"
] | null | null | null | (function() {
"use strict";
var angular = window.angular;
angular
.module("APP")
.controller("userOptionsController", ["$scope", "loginService", userOptionsController]);
function userOptionsController($scope, loginService) {
$scope.userName = null;
$scope.role = null;
$scope.isLoggedIn = function() {
return !!$scope.userName;
};
$scope.logout = loginService.logout;
$scope.isAdmin = function() {
return $scope.role === loginService.roles[2];
};
$scope.isMinistryAdmin = function() {
return $scope.role === loginService.roles[1];
};
$scope.navigate = function(route) {
window.location = "/" + route;
};
$scope.exportOwl = function() {
window.location = "/api/export";
};
function updateUserInfo() {
var userInfo = loginService.getUserInfo();
$scope.userName = userInfo.Name;
$scope.role = loginService.roles[userInfo.Role];
}
function activate() {
updateUserInfo();
};
activate();
}
})(); | 21.577778 | 90 | 0.651905 |
0348268336626e4ad3ec0610b09f2997d951cbbf | 180 | rb | Ruby | spec/factories/project.rb | MaxiBoether/redmine_diff_email | ee42ea29b4d6f072d9ed08f1b5a5985a106a06a4 | [
"MIT"
] | 1 | 2018-04-18T15:34:35.000Z | 2018-04-18T15:34:35.000Z | spec/factories/project.rb | MaxiBoether/redmine_diff_email | ee42ea29b4d6f072d9ed08f1b5a5985a106a06a4 | [
"MIT"
] | null | null | null | spec/factories/project.rb | MaxiBoether/redmine_diff_email | ee42ea29b4d6f072d9ed08f1b5a5985a106a06a4 | [
"MIT"
] | 2 | 2016-06-05T10:35:59.000Z | 2021-07-01T09:00:40.000Z | FactoryGirl.define do
factory :project do |project|
project.sequence(:identifier) { |n| "project#{n}"}
project.sequence(:name) { |n| "Project#{n}"}
end
end
| 20 | 56 | 0.611111 |
963b6ab3f4a0a07caea1f5ff76925de3c3894ba7 | 7,092 | rb | Ruby | ordering/queue.rb | kmindspark/bud-sandbox | 76d77685ed52abf358deb910fa52fa4e444c432c | [
"BSD-3-Clause"
] | 24 | 2015-02-11T11:31:53.000Z | 2021-10-31T20:25:22.000Z | ordering/queue.rb | bloom-lang/bud-sandbox | 4f654bfa1f20e2e52a574c034c4ec12c3a71875d | [
"BSD-3-Clause"
] | null | null | null | ordering/queue.rb | bloom-lang/bud-sandbox | 4f654bfa1f20e2e52a574c034c4ec12c3a71875d | [
"BSD-3-Clause"
] | 4 | 2016-10-31T19:54:07.000Z | 2020-12-10T02:45:17.000Z | # @abstract PriorityQueueProtocol is the abstract interface for priority queues
# Any implementation of a queue should subclass PriorityQueueProtocol
module PriorityQueueProtocol
state do
# Push items into the queue.
# Useful Mnemonic: push "item" with priority "priority" into queue "queue."
# Note: queue is essentially optional - a single queue can be used without specifying queue because it will automatically be included as nil
# @param [Object] item is the item that will be pushed into the queue
# @param [Number] priority specifies the priority of the item in the queue
# @param [Number] queue specifies which queue to push the item in
interface input, :push, [:item, :priority, :queue]
# Removes items out of the queue, regardless of priority.
# Useful Mnemonic: remove "item" from queue "queue"
# @param [Object] item specifies which item to remove
# @param [Number] queue specifies which queue to remove the item from
# @return [remove_response] upon successful removal.
interface input, :remove, [:item, :queue]
# Pop items out of the queue.
# Removes the top priority item in queue queue: outputs the item into pop_response.
# Useful Mnemonic: pop from queue "queue"
# @param [Number] queue specifies which queue to pop from
# @return [pop_response] when the pop request is successfully processed.
interface input, :pop, [:queue]
# Peek the top item in the queue.
# Like pop, but does not remove the item from the queue.
# Useful Mnemonic: peek from queue "queue"
# @param [Number] queue specifies which queue to peek at
# @return [peek_response] when the peek request is successfully processed.
interface input, :peek, [:queue]
# If there is a remove request, remove and return the item regardless of priority
# @param [Object] item is the item that will be pushed into the queue
# @param [Number] priority specifies the priority of the item in the queue
# @param [Number] queue specifies which queue to push the item in
interface output, :remove_response, push.schema
# If there is a pop request, remove and return the top priority item from the queue
# @param [Object] item is the item that will be pushed into the queue
# @param [Number] priority specifies the priority of the item in the queue
# @param [Number] queue specifies which queue to push the item in
interface output, :pop_response, push.schema
# If there is a peek request, return (but don't remove) the top priority item from the queue
# @param [Object] item is the item that will be pushed into the queue
# @param [Number] priority specifies the priority of the item in the queue
# @param [Number] queue specifies which queue to push the item in
interface output, :peek_response, push.schema
end
end
# @abstract FIFOQueueProtocol is the abstract interface for fifo queues
module FIFOQueueProtocol
state do
# Push items into the queue.
# Note: queue is essentially optional - a single queue can be used without specifying queue because it will automatically be included as nil
# @param [Object] item is the item that will be pushed into the queue
# @param [Number] queue specifies which queue to push the item in
interface input, :push, [:item, :queue]
# Pop items out of the queue.
# Removes the top priority item in queue queue: outputs the item into pop_response.
# @param [Number] queue specifies which queue to pop from
# @return [pop_response] when the pop request is successfully processed.
interface input, :pop, [:queue]
# Peek the top item in the queue.
# Like pop, but does not remove the item from the queue.
# @param [Number] queue specifies which queue to peek at
# @return [peek_response] when the peek request is successfully processed.
interface input, :peek, [:queue]
# If there is a pop request, remove and return the first item that was inserted into the queue
# @param [Object] item is the item that will be pushed into the queue
# @param [Number] queue specifies which queue to push the item in
interface output, :pop_response, [:item, :queue]
# If there is a peek request, return (but don't remove) the first item that was inserted into the queue
# @param [Object] item is the item that will be pushed into the queue
# @param [Number] queue specifies which queue to push the item in
interface output, :peek_response, [:item, :queue]
end
end
# PriorityQueue is the basic implementation of a priority queue.
# The front of the queue is always the lowest priority item.
# @see PriorityQueue implements PriorityQueueProtocol
module PriorityQueue
include PriorityQueueProtocol
state do
# The items that are currently in the queue
table :items, [:item, :priority, :queue]
# The lowest priority item for each queue.
# Does not necessarily contain one item per queue (contains all items with the current lowest priority)
scratch :lowest, [:item, :priority, :queue]
# Temporary collection to contain the pop response.
# Does not necessarily contain one item per queue (contains all items with the current lowest priority)
# An interposition for breaking ties
scratch :lowest_popr, [:item, :priority, :queue]
# Temporary collection to contain the peek response.
# Does not necessarily contain one item per queue (contains all items with the current lowest priority)
# An interposition for breaking ties
scratch :lowest_peekr, [:item, :priority, :queue]
end
bloom :remember do
items <= push
end
bloom :calc_lowest do
# Users can override method of choosing best priority
# By default it is based on the ruby min
lowest <= items.argmin([:queue], :priority)
lowest_popr <= (pop * lowest).rights(:queue => :queue)
lowest_peekr <= (peek * lowest).rights(:queue => :queue)
end
bloom :break_tie do
# Users can override method of breaking ties
# By default it is chosen arbitrarily
pop_response <= lowest_popr.argagg(:choose, [:queue, :priority], :item)
peek_response <= lowest_peekr.argagg(:choose, [:queue, :priority], :item)
end
bloom :remove_item do
remove_response <= (remove * items).rights(:queue => :queue, :item => :item)
end
bloom :drop do
items <- remove_response
items <- pop_response
end
bloom :debug do
# stdio <~ lowest.inspected
# stdio <~ pop_response.inspected
end
end
# FIFOQueue is the basic implementation of a fifo queue.
# The front of the queue is always the earliest item that was inserted out of the items in the queue.
# Uses budtime to order the items.
# @see FIFOQueue implements FIFOQueueProtocol
# @see FIFOQueue imports PriorityQueue
module FIFOQueue
include FIFOQueueProtocol
import PriorityQueue => :pq
bloom do
pq.push <= push {|p| [p.item, budtime, p.queue]}
pq.pop <= pop
pq.peek <= peek
pop_response <= pq.pop_response {|p| [p.item, p.queue]}
peek_response <= pq.peek_response {|p| [p.item, p.queue]}
end
end
| 43.243902 | 144 | 0.715877 |
c50676a1847c49738fe5d3fada055a510b4d4dea | 2,059 | css | CSS | public/css/shortcodes/separator.css | sayeed105236/globalskills_live | 4c9b587f9f639d67a111284cf6a010b9a92437de | [
"MIT"
] | 3 | 2020-08-20T12:11:05.000Z | 2021-07-25T14:45:05.000Z | public/css/shortcodes/separator.css | sayeed105236/globalskills_live | 4c9b587f9f639d67a111284cf6a010b9a92437de | [
"MIT"
] | 2 | 2022-02-19T07:05:48.000Z | 2022-02-27T11:09:16.000Z | public/css/shortcodes/separator.css | sayeed105236/globalskills_live | 4c9b587f9f639d67a111284cf6a010b9a92437de | [
"MIT"
] | 2 | 2020-09-11T09:53:29.000Z | 2020-11-03T17:42:40.000Z | .ttr-separator-outer {
overflow: hidden;
}
.ttr-separator {
display: inline-block;
height: 2px;
width: 80px;
margin-bottom: 10px;
position: relative;
}
.ttr-separator.style-liner {
width: 20px;
}
.ttr-separator.style-icon {
width: 30px;
height: auto;
text-align: center;
font-size: 20px;
}
.ttr-separator[class*="style-"]:after,
.ttr-separator[class*="style-"]:before {
content: "";
position: absolute;
top: 50%;
left: 40px;
width: 70px;
height: 2px;
background: #eee;
-webkit-transform: translateY(-50%);
-ms-transform: translateY(-50%);
transform: translateY(-50%);
}
.ttr-separator[class*="style-"]:before {
left: auto;
right: 40px;
}
.ttr-separator.style-skew {
width: 15px;
height: 10px;
margin-left: 1px;
margin-right: 1px;
-moz-transform: skewX(-10deg);
-webkit-transform: skewX(-10deg);
-o-transform: skewX(-10deg);
-ms-transform: skewX(-10deg);
transform: skewX(-10deg);
}
.ttr-separator.style-skew[class*="style-"]:after,
.ttr-separator.style-skew[class*="style-"]:before {
width: 80px;
height: 4px;
left: 20px;
-moz-transform: translateY(-50%) skewX(-10deg);
-webkit-transform: translateY(-50%) skewX(-10deg);
-o-transform: translateY(-50%) skewX(-10deg);
-ms-transform: translateY(-50%) skewX(-10deg);
transform: translateY(-50%) skewX(-10deg);
}
.ttr-separator.style-skew[class*="style-"]:before {
right: 20px;
left: auto;
}
.ttr-separator.bnr-title{
height:1px;
width: 155px;
opacity: 0.5;
}
.ttr-separator.bnr-title:before {
height: inherit;
right: -80px;
width: 25px;
}
.ttr-separator.bnr-title:after {
height: inherit;
right: -90px;
top: 0;
width: 6px;
}
.ttr-separator.bnr-title:before,
.ttr-separator.bnr-title:after{
position:absolute;
content:"";
background-color:inherit;
}
.ttr-separator.bnr-title i {
background-color: inherit;
display: block;
height: inherit;
position: absolute;
right: -50px;
width: 45px;
} | 22.380435 | 54 | 0.632831 |
da730687955932d4556ccc8bfca5c70f3c9fbbeb | 1,586 | tsx | TypeScript | src/utils/context.tsx | yannbf/braga.dev | c4ba0f4a04ca62ad1147cd3ca7291df419327a6f | [
"MIT"
] | 1 | 2022-02-17T20:16:09.000Z | 2022-02-17T20:16:09.000Z | src/utils/context.tsx | yannbf/braga.dev | c4ba0f4a04ca62ad1147cd3ca7291df419327a6f | [
"MIT"
] | 10 | 2020-07-20T07:15:43.000Z | 2022-03-26T12:29:34.000Z | src/utils/context.tsx | yannbf/braga.dev | c4ba0f4a04ca62ad1147cd3ca7291df419327a6f | [
"MIT"
] | null | null | null | import React, { useState, useEffect } from 'react';
import Cookies from 'js-cookie';
export enum ThemeEnum {
light = 'light',
dark = 'dark',
}
interface ContextValue {
theme: ThemeEnum;
toggleTheme: () => void;
}
export const ThemeContext = React.createContext<ContextValue | undefined>({
theme: ThemeEnum.dark,
toggleTheme: () => null,
});
export const useTheme = (): ContextValue => {
const context = React.useContext<ContextValue | undefined>(ThemeContext);
if (!context) {
throw new Error('useTheme must be within a ThemeProvider');
}
return context;
};
export interface Theme {
color: string;
}
export const ContextThemeProvider: React.FC = ({ children }) => {
// Set the default theme state to the value stored in the user's cookie and fallback
// to 'dark' if no cookie is found
const [theme, setTheme] = useState(ThemeEnum.dark);
/**
* Toggle between light and dark themes and set the current theme
* value as a cookie. Also need to re-initialize the animate on scroll
* module to ensure elements don't disappear.
* @returns {void}
*/
const toggleTheme = () => {
const newThemeValue = theme === ThemeEnum.light ? ThemeEnum.dark : ThemeEnum.light;
Cookies.set('theme', newThemeValue);
setTheme(newThemeValue);
};
useEffect(() => {
if (Cookies.get('theme') !== theme) {
setTheme(Cookies.get('theme') as ThemeEnum);
}
}, [theme]);
return (
<ThemeContext.Provider
value={{
theme,
toggleTheme,
}}
>
{children}
</ThemeContext.Provider>
);
};
| 24.4 | 87 | 0.652585 |
255952a4a8f996ca320ca6337cabb99d227b24d9 | 435 | cs | C# | Data/Approles.cs | sammyach/hrisAPI | 5684dd5c6c2b00b15b16e47b4e15d4e59cfa80a5 | [
"MIT"
] | null | null | null | Data/Approles.cs | sammyach/hrisAPI | 5684dd5c6c2b00b15b16e47b4e15d4e59cfa80a5 | [
"MIT"
] | null | null | null | Data/Approles.cs | sammyach/hrisAPI | 5684dd5c6c2b00b15b16e47b4e15d4e59cfa80a5 | [
"MIT"
] | null | null | null | using System;
using System.Collections.Generic;
namespace WebApi.Data
{
public partial class AppRoles
{
public AppRoles()
{
AppUserRoles = new HashSet<AppUserRoles>();
}
public int RoleId { get; set; }
public string Rolename { get; set; }
public string Description { get; set; }
public virtual ICollection<AppUserRoles> AppUserRoles { get; set; }
}
}
| 21.75 | 75 | 0.604598 |
149192dd7f0047f6c4131b9a24b44e430da93728 | 393 | dart | Dart | lib/myanimelist.dart | MaikuB/myanimelist | d286995676d3d5cfa4b4dbcf33a7f3d1965f2b89 | [
"BSD-3-Clause"
] | 4 | 2018-05-06T01:58:28.000Z | 2020-08-14T21:24:32.000Z | lib/myanimelist.dart | MaikuB/myanimelist | d286995676d3d5cfa4b4dbcf33a7f3d1965f2b89 | [
"BSD-3-Clause"
] | 2 | 2018-04-23T13:18:31.000Z | 2021-12-09T11:48:07.000Z | lib/myanimelist.dart | MaikuB/myanimelist | d286995676d3d5cfa4b4dbcf33a7f3d1965f2b89 | [
"BSD-3-Clause"
] | null | null | null | export 'package:myanimelist/src/mal_client.dart';
export 'package:myanimelist/src/dtos/result_dto.dart';
export 'package:myanimelist/src/models/anime.dart';
export 'package:myanimelist/src/models/entry.dart';
export 'package:myanimelist/src/models/manga.dart';
export 'package:myanimelist/src/models/search_anime_result.dart';
export 'package:myanimelist/src/models/search_manga_result.dart';
| 49.125 | 65 | 0.824427 |
45633f6164c14ac496ea3f9bf257b9bf0362529f | 4,735 | py | Python | Python/TextMining/id3_entropy.py | zhangmianhongni/MyPracticeVarious | db58f5a9e5d99a5d80e8e8bf561f104c1fa4efd5 | [
"Apache-2.0"
] | null | null | null | Python/TextMining/id3_entropy.py | zhangmianhongni/MyPracticeVarious | db58f5a9e5d99a5d80e8e8bf561f104c1fa4efd5 | [
"Apache-2.0"
] | null | null | null | Python/TextMining/id3_entropy.py | zhangmianhongni/MyPracticeVarious | db58f5a9e5d99a5d80e8e8bf561f104c1fa4efd5 | [
"Apache-2.0"
] | 1 | 2021-08-29T10:10:33.000Z | 2021-08-29T10:10:33.000Z | #-- coding: UTF-8 --#
from math import log
import operator
#计算熵
def calcShannonEnt(dataSet):
numEntries = len(dataSet)
labelCounts = {}
for featVec in dataSet:
currentLabel = featVec[-1]
if currentLabel not in labelCounts.keys():
labelCounts[currentLabel] = 0
labelCounts[currentLabel] += 1
shannonEnt = 0.0
for key in labelCounts:
prob = float(labelCounts[key]) / numEntries #当前数据每个分类的比例
shannonEnt -= prob * log(prob, 2)
return shannonEnt
#创建数据集
def createDataSet():
dataSet = [['sunny', 'hot', 'high', 'FALSE', 'no'], ['sunny', 'hot', 'high', 'TRUE', 'no'], ['overcast', 'hot', 'high', 'FALSE', 'yes'],
['rainy', 'mild', 'high', 'FALSE', 'yes'], ['rainy', 'cool', 'normal', 'FALSE', 'yes'], ['rainy', 'cool', 'normal', 'TRUE', 'no'],
['overcast', 'cool', 'normal', 'TRUE', 'yes'], ['sunny', 'mild', 'high', 'FALSE', 'no'], ['sunny', 'cool', 'normal', 'FALSE', 'yes'],
['rainy', 'mild', 'normal', 'FALSE', 'yes'], ['sunny', 'mild', 'normal', 'TRUE', 'yes'], ['overcast', 'mild', 'high', 'TRUE', 'yes'],
['overcast', 'hot', 'normal', 'FALSE', 'yes'], ['rainy', 'mild', 'high', 'TRUE', 'no']]
labels = ['outlook', 'temperature', 'humidity', 'windy']
return dataSet, labels
# 离散特征分割 根据特征值分割数据集,axis是属性索引,value是属性对应的值
def splitDataSet(dataSet, axis, value):
retDataSet = []
for featVec in dataSet:
if featVec[axis] == value:
reducedFeatVec = featVec[:axis]
reducedFeatVec.extend(featVec[axis + 1:])
retDataSet.append(reducedFeatVec)
return retDataSet
#根据信息增益选择最好的属性
def chooseBestFeatureToSplit(dataSet):
numFeatures = len(dataSet[0]) - 1
baseEntropy = calcShannonEnt(dataSet) #信息熵
print("baseEntropy: " + str(baseEntropy))
bestInfoGain = 0.0
bestFeature = -1
for i in range(numFeatures):
featList = [example[i] for example in dataSet]
uniqueVals = set(featList)
print(uniqueVals)
newEntropy = 0.0 #条件熵
#splitEntropy = 0.0 #分裂信息熵
for value in uniqueVals: #计算离散值的条件熵
subDataSet = splitDataSet(dataSet, i, value)
prob = len(subDataSet) / float(len(dataSet))
newEntropy += prob * calcShannonEnt(subDataSet)
#splitEntropy -= prob * log(prob, 2)
print(i)
print("newEntropy: " + str(newEntropy))
#print("splitEntropy: " + str(splitEntropy))
infoGain = baseEntropy - newEntropy #信息增益,使用信息增益有一个缺点,那就是它偏向于具有大量值的特征,所以C4.5选用信息增益率
#infoGainRatio = infoGain / splitEntropy
print("infoGain: " + str(infoGain))
#print("infoGainRatio: " + str(infoGainRatio))
if infoGain > bestInfoGain: #选择最大信息增益率的特征作为树节点
bestInfoGain = infoGain
bestFeature = i
return bestFeature #返回节点的特征索引
'''
如果数据集已经处理了所有属性,但类标签依然不唯一,此时我们需要决定如何定该叶子节点,
这种情况我们通常会采用表决的方法决定该叶子节点的分类 。
'''
def majorityCnt(classList):
classCount={}
for vote in classList:
if vote not in classCount.keys ():classCount[vote] = 0
classCount[vote] += 1
sortedClassCount = sorted(classCount.iteritems(), key=operator.itemgetter(1), reverse=True)
print(sortedClassCount)
return sortedClassCount[0][0]
#创建决策树
def createTree(dataSet, labels):
classList = [example[-1] for example in dataSet]
if classList.count(classList[0]) == len(classList): #如果所有的数据都是同一个分类,返回分类标签
return classList[0]
if len(dataSet[0]) == 1: #如果数据集已经处理了所有属性,但类标签依然不唯一,执行多数表决
return majorityCnt(classList)
bestFeat = chooseBestFeatureToSplit(dataSet)
bestFeatLabel = labels[bestFeat]
myTree = {bestFeatLabel:{}}
del(labels[bestFeat]) #删除已处理的节点名字
featValues = [example[bestFeat] for example in dataSet]
uniqueVals = set(featValues)
subLabels = labels[:]
for value in uniqueVals:
myTree[bestFeatLabel][value] = createTree(splitDataSet(dataSet, bestFeat, value), subLabels) #递归创建树节点
return myTree
#利用决策树进行分类
def classify(inputTree, featLabels, testVec):
firstStr = inputTree.keys()[0]
secondDict = inputTree[firstStr]
featIndex = featLabels.index(firstStr)
classLabel = ''
for key in secondDict.keys():
if testVec[featIndex] == key:
if type(secondDict[key]).__name__ == 'dict':
classLabel = classify(secondDict[key], featLabels, testVec)
else:
classLabel = secondDict[key]
return classLabel
if __name__ == "__main__":
myData, labels = createDataSet()
labelsBackup = labels[:]
tree = createTree(myData, labels)
print(tree)
print(classify(tree, labelsBackup, ['rainy', 'mild', 'high', 'FALSE']))
| 38.185484 | 149 | 0.625977 |
c68a7aa15afc7cb5d068d66870d5f9eef97c7647 | 153 | rs | Rust | frontend/rust/src/lib.rs | saminkhan/rust_life | 01600a357093beb92b7000de0da0407af65306b0 | [
"MIT"
] | null | null | null | frontend/rust/src/lib.rs | saminkhan/rust_life | 01600a357093beb92b7000de0da0407af65306b0 | [
"MIT"
] | null | null | null | frontend/rust/src/lib.rs | saminkhan/rust_life | 01600a357093beb92b7000de0da0407af65306b0 | [
"MIT"
] | null | null | null | use wasm_bindgen::prelude::*;
#[wasm_bindgen]
pub fn fib(n: u32) -> u32 {
if n < 2 {
n
} else {
fib(n - 1) + fib(n - 2)
}
}
| 13.909091 | 31 | 0.444444 |
cd1123e3d4c97d97c13d04157f5e479900e0d8e2 | 2,316 | cs | C# | sample/RSAExtensions.ConsoleApp/Program.cs | redfire168/RSAExtensions | 0a2ff3b96a8d82f6a829caeba643894a0b0b3655 | [
"Apache-2.0"
] | 132 | 2019-12-16T09:31:11.000Z | 2022-03-22T09:00:51.000Z | sample/RSAExtensions.ConsoleApp/Program.cs | redfire168/RSAExtensions | 0a2ff3b96a8d82f6a829caeba643894a0b0b3655 | [
"Apache-2.0"
] | 2 | 2020-04-03T09:44:58.000Z | 2022-02-18T09:59:15.000Z | sample/RSAExtensions.ConsoleApp/Program.cs | redfire168/RSAExtensions | 0a2ff3b96a8d82f6a829caeba643894a0b0b3655 | [
"Apache-2.0"
] | 29 | 2019-12-17T05:46:28.000Z | 2022-03-25T14:24:11.000Z | using System;
using System.Security.Cryptography;
using System.Text;
namespace RSAExtensions.ConsoleApp
{
class Program
{
static void Main(string[] args)
{
var rsa = RSA.Create(512);
Console.WriteLine();
Console.WriteLine(rsa.ExportPublicKey(RSAKeyType.Pkcs8));
Console.WriteLine();
Console.WriteLine(rsa.ExportPrivateKey(RSAKeyType.Pkcs1));
Console.WriteLine("-----------------------------------------");
Console.WriteLine(rsa.ExportPrivateKey(RSAKeyType.Pkcs1, true));
Console.WriteLine("-----------------------------------------");
Console.WriteLine(rsa.ExportPrivateKey(RSAKeyType.Pkcs8));
Console.WriteLine("-----------------------------------------");
Console.WriteLine(rsa.ExportPrivateKey(RSAKeyType.Pkcs8,true));
Console.WriteLine("-----------------------------------------");
Console.WriteLine(rsa.ExportPrivateKey(RSAKeyType.Xml));
Console.WriteLine("-----------------------------------------");
var data = "响应式布局的概念是一个页面适配多个终端及不同分辨率。在针对特定屏幕宽度优化应用 UI 时,我们将此称为创建响应式设计。WPF设计之初响应式设计的概念并不流行,那时候大部分网页设计师都按着宽度960像素的标准设计。到了UWP诞生的时候响应式布局已经很流行了,所以UWP提供了很多响应式布局的技术,这篇文章简单总结了一些响应式布局常用的技术,更完整的内容请看文章最后给出的参考网站。所谓的传统,是指在响应式设计没流行前XAML就已经存在的应对不同分辨率的技术,毕竟桌面客户端常常也调整窗体的大小,有些人还同时使用两个不同分辨率的屏幕。以我的经验来说以下这些做法可以使UI有效应对分辨率改变不同的DPI设定、不同的本地化字符串长度都可能使整个页面布局乱掉。而且和网页不同,WPF窗体默认没有提供ScrollViewer,所以千万不能忘记。在桌面客户端合理使用以上技术可以避免客户投诉。但UWP主打跨平台,它需要更先进(或者说,更激进)的技术。微软的官方文档介绍了UWP中响应式设计常用的6个技术,包括重新定位、调整大小、重新排列、显示/隐藏、替换和重新构建,具体可见以下网站:UWP中部分控件已经实现了响应式行为, 最典型的就是NavigationView。可以使用 PaneDisplayMode 属性配置不同的导航样式或显示模式。默认情况下,PaneDisplayMode 设置为 Auto。在 Auto 模式下,导航视图会进行自适应,在窗口狭窄时为 LeftMinimal,接下来为 LeftCompact,随后在窗口变宽时为 Left。这种时候MVVM的优势就体现出来了,因为VIEW和VIEWMODEL解耦了,VIEW随便换,而且整个UI显示隐藏说不定比多个小模块独自改变性能更好。说到性能,UWP的很多场景都为已经死了多年的WindowsWobile考虑了性能,更不用说现在的桌面平台,所以做UWP不需要太过介意性能,尤其是已经在WPF上培养出小心翼翼的习惯的开发者,UWP的性能问题等真的出现了再说。除了使用显示隐藏,UWP还可以使用限定符名称指定CodeBehind对应的XAML文件,这有点像是自适应应用的话题。使用格式如下";
var encrypt = rsa.EncryptBigData(data, RSAEncryptionPadding.OaepSHA1);
Console.WriteLine(encrypt);
var decrypt = rsa.DecryptBigData(encrypt, RSAEncryptionPadding.OaepSHA1);
Console.WriteLine(decrypt);
}
}
}
| 64.333333 | 944 | 0.68437 |
1446be21c8daddb487eb3b3462bc4f9e104a3844 | 1,058 | ts | TypeScript | src/app.module.ts | Quantumlyy/nftx-rarity-api | 49a5ff1be4cbb93948a3383774d59987ffd509f2 | [
"MIT"
] | null | null | null | src/app.module.ts | Quantumlyy/nftx-rarity-api | 49a5ff1be4cbb93948a3383774d59987ffd509f2 | [
"MIT"
] | null | null | null | src/app.module.ts | Quantumlyy/nftx-rarity-api | 49a5ff1be4cbb93948a3383774d59987ffd509f2 | [
"MIT"
] | null | null | null | import { BullModule } from '@nestjs/bull';
import { Module } from '@nestjs/common';
import { ConfigModule, ConfigService } from '@nestjs/config';
import { EthersModule, MAINNET_NETWORK } from 'nestjs-ethers';
import { AuthModule } from './auth/Auth.module';
import { DatabaseModule } from './database/Database.module';
import { ProvidersModule } from './providers/Providers.module';
@Module({
imports: [
DatabaseModule,
ProvidersModule,
ConfigModule.forRoot(),
BullModule.forRoot({
redis: {
host: 'localhost',
port: 6379,
},
}),
EthersModule.forRootAsync({
imports: [ConfigModule],
inject: [ConfigService],
useFactory: (config: ConfigService) => {
return {
network: MAINNET_NETWORK,
infura: {
projectId: config.get<string>('INFURA_PROJECT_ID'),
projectSecret: config.get<string>('INFURA_PROJECT_SECRET'),
},
useDefaultProvider: false,
};
},
}),
AuthModule,
],
})
export class AppModule {}
| 27.842105 | 71 | 0.619093 |
b92bc81aa19fa3cd08ddc72f1fbfcdd8e880c9ad | 52 | css | CSS | static/css/danmu.css | tonghuashuai/yikuaitouba | a309d397e5d297d201cbe728984ff8e493ba282f | [
"MIT"
] | null | null | null | static/css/danmu.css | tonghuashuai/yikuaitouba | a309d397e5d297d201cbe728984ff8e493ba282f | [
"MIT"
] | null | null | null | static/css/danmu.css | tonghuashuai/yikuaitouba | a309d397e5d297d201cbe728984ff8e493ba282f | [
"MIT"
] | null | null | null | #danmu{
height: 480px;
background-color: #000;
}
| 8.666667 | 24 | 0.653846 |
aecdd8eb8e210d304a4c8c0d86f4ce757cbf91dc | 9,079 | cs | C# | src/Operations.Application.Web/Controllers/NaosOperationsLogTracesController.cs | vip32/Naos.Core | 8c1cd1350e01f0d52dd0553444df226a5b3f2b0a | [
"MIT"
] | 10 | 2018-11-09T11:42:11.000Z | 2019-08-22T14:24:02.000Z | src/Operations.Application.Web/Controllers/NaosOperationsLogTracesController.cs | vip32/Naos.Core | 8c1cd1350e01f0d52dd0553444df226a5b3f2b0a | [
"MIT"
] | 148 | 2018-11-20T10:42:16.000Z | 2019-08-26T22:41:41.000Z | src/Operations.Application.Web/Controllers/NaosOperationsLogTracesController.cs | vip32/Naos.Core | 8c1cd1350e01f0d52dd0553444df226a5b3f2b0a | [
"MIT"
] | 2 | 2019-04-05T09:23:34.000Z | 2019-05-03T23:05:38.000Z | namespace Naos.Operations.Application.Web
{
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using EnsureThat;
using Humanizer;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.ObjectPool;
using Naos.Foundation;
using Naos.Foundation.Application;
using Naos.Foundation.Domain;
using Naos.RequestFiltering.Application;
using Naos.Tracing.Domain;
using NSwag.Annotations;
[Route("naos/operations/logtraces")]
[ApiController]
public class NaosOperationsLogTracesController : ControllerBase
{
private readonly ILogger<NaosOperationsLogTracesController> logger;
private readonly FilterContext filterContext;
private readonly ILogTraceRepository repository;
private readonly ILogEventService service;
private readonly ServiceDescriptor serviceDescriptor;
private readonly ObjectPool<StringBuilder> stringBuilderPool = new DefaultObjectPoolProvider().CreateStringBuilderPool();
public NaosOperationsLogTracesController(
ILoggerFactory loggerFactory,
ILogTraceRepository repository,
ILogEventService service,
IFilterContextAccessor filterContext,
ServiceDescriptor serviceDescriptor = null)
{
EnsureArg.IsNotNull(loggerFactory, nameof(loggerFactory));
EnsureArg.IsNotNull(repository, nameof(repository));
EnsureArg.IsNotNull(service, nameof(service));
this.logger = loggerFactory.CreateLogger<NaosOperationsLogTracesController>();
this.filterContext = filterContext.Context ?? new FilterContext();
this.repository = repository;
this.service = service;
this.serviceDescriptor = serviceDescriptor;
}
[HttpGet]
[ProducesResponseType((int)HttpStatusCode.OK)]
[ProducesResponseType(typeof(ValidationProblemDetails), (int)HttpStatusCode.BadRequest)]
[ProducesResponseType(typeof(ProblemDetails), (int)HttpStatusCode.InternalServerError)]
[OpenApiTag("Naos Operations")]
public async Task<ActionResult<IEnumerable<LogTrace>>> Get()
{
//var acceptHeader = this.HttpContext.Request.Headers.GetValue("Accept");
//if (acceptHeader.ContainsAny(new[] { ContentType.HTML.ToValue(), ContentType.HTM.ToValue() }))
//{
// return await this.GetHtmlAsync().AnyContext();
//}
return this.Ok(await this.GetJsonAsync().AnyContext());
}
[HttpGet]
[Route("{id}")]
[ProducesResponseType((int)HttpStatusCode.OK)]
[ProducesResponseType(typeof(ValidationProblemDetails), (int)HttpStatusCode.BadRequest)]
[ProducesResponseType(typeof(ProblemDetails), (int)HttpStatusCode.InternalServerError)]
[OpenApiTag("Naos Operations")]
public async Task<ActionResult<LogTrace>> Get(string id)
{
return this.Ok(await this.repository.FindOneAsync(id).AnyContext());
}
[HttpGet]
[Route("dashboard")]
[Produces("text/html")]
[ProducesResponseType((int)HttpStatusCode.OK)]
[ProducesResponseType(typeof(ValidationProblemDetails), (int)HttpStatusCode.BadRequest)]
[ProducesResponseType(typeof(ProblemDetails), (int)HttpStatusCode.InternalServerError)]
[OpenApiTag("Naos Operations")]
public Task GetHtml()
{
return this.GetHtmlAsync();
}
private async Task<IEnumerable<LogTrace>> GetJsonAsync()
{
LoggingFilterContext.Prepare(this.filterContext); // add some default criteria
return await this.repository.FindAllAsync(
this.filterContext.GetSpecifications<LogTrace>().Insert(
new Specification<LogTrace>(t => t.TrackType == "trace")),
this.filterContext.GetFindOptions<LogTrace>()).AnyContext();
}
private Task GetHtmlAsync()
{
this.HttpContext.Response.WriteNaosDashboard(
title: this.serviceDescriptor?.ToString(),
tags: this.serviceDescriptor?.Tags,
action: async r =>
{
var entities = this.GetJsonAsync().Result;
var nodes = Node<LogTrace>.ToHierarchy(entities, l => l.SpanId, l => l.ParentSpanId, true).ToList();
try
{
await nodes.RenderAsync(
t => this.WriteTrace(t),
t => this.WriteTraceHeader(t),
orderBy: t => t.Ticks,
options: new HtmlNodeRenderOptions(r.HttpContext) { ChildNodeBreak = string.Empty }).AnyContext();
}
catch
{
// do nothing
}
//foreach (var entity in entities) // .Where(l => !l.TrackType.EqualsAny(new[] { LogTrackTypes.Trace }))
//{
// await this.WriteTraceAsync(entity).AnyContext();
//}
}).Wait();
return Task.CompletedTask;
}
private string WriteTraceHeader(LogTrace entity)
{
var sb = this.stringBuilderPool.Get(); // less allocations
sb.Append("<div style='white-space: nowrap;'>")
.Append("<span style='color: #EB1864; font-size: x-small;'>")
.AppendFormat("{0:u}", entity.Timestamp.ToUniversalTime())
.Append("</span>");
sb.Append(" [<span style='color: ")
.Append(this.GetTraceLevelColor(entity)).Append("'>")
.Append(entity.Kind?.ToUpper().Truncate(6, string.Empty))
.Append("</span>]");
sb.Append(!entity.CorrelationId.IsNullOrEmpty() ? $" <a style='font-size: xx-small;' target=\"blank\" href=\"/naos/operations/logevents/dashboard?q=CorrelationId={entity.CorrelationId}\">{entity.CorrelationId.Truncate(12, string.Empty, Truncator.FixedLength, TruncateFrom.Left)}</a> " : " ");
sb.Append($"<span style='color: #AE81FF; font-size: xx-small;'>{entity.ServiceName.Truncate(15, string.Empty, TruncateFrom.Left)}</span> ");
//sb.Append(!entity.CorrelationId.IsNullOrEmpty() ? $" <a target=\"blank\" href=\"/naos/operations/logtraces/dashboard?q=CorrelationId={entity.CorrelationId}\">{entity.CorrelationId.Truncate(12, string.Empty, Truncator.FixedLength, TruncateFrom.Left)}</a> " : " ");
var result = sb.ToString();
this.stringBuilderPool.Return(sb);
return result;
}
private string WriteTrace(LogTrace entity)
{
var extraStyles = string.Empty;
var sb = this.stringBuilderPool.Get(); // less allocations
sb.Append("<span style='color: ").Append(this.GetTraceLevelColor(entity)).Append("; ").Append(extraStyles).Append("'>");
//.Append(logEvent.TrackType.SafeEquals("journal") ? "*" : " "); // journal prefix
if (entity.Message?.Length > 5 && entity.Message.Take(6).All(char.IsUpper))
{
sb.Append($"<span style='color: #37CAEC;'>{entity.Message.Slice(0, 6)}</span>");
sb.Append(entity.Message.Slice(6)).Append(" (").Append(entity.SpanId).Append('/').Append(entity.ParentSpanId).Append(") ");
}
else
{
sb.Append(entity.Message).Append(" (").Append(entity.SpanId).Append('/').Append(entity.ParentSpanId).Append(") ");
}
sb.Append("<a target='blank' href='/naos/operations/logtraces/").Append(entity.Id).Append("'>*</a> ");
sb.Append("<span style='color: gray;font-size: xx-small'>-> took ");
sb.Append(entity.Duration.Humanize());
sb.Append("</span>");
sb.Append("</span>");
sb.Append("</div>");
var result = sb.ToString();
this.stringBuilderPool.Return(sb);
return result;
}
private string GetTraceLevelColor(LogTrace entity)
{
var levelColor = "#96E228";
if (entity.Status.SafeEquals(nameof(SpanStatus.Transient)))
{
levelColor = "#75715E";
}
else if (entity.Status.SafeEquals(nameof(SpanStatus.Cancelled)))
{
levelColor = "#FF8C00";
}
else if (entity.Status.SafeEquals(nameof(SpanStatus.Failed)))
{
levelColor = "#FF0000";
}
return levelColor;
}
// Application parts? https://docs.microsoft.com/en-us/aspnet/core/mvc/advanced/app-parts?view=aspnetcore-2.1
}
}
| 45.395 | 379 | 0.597753 |
9e2cae89515e11719bd2d9a57751a20945fd7338 | 7,593 | cs | C# | src/Diva.MainMenu/Diva.MainMenu.WelcomeVBox.cs | mdk/diva | f58841d8b539d925a95d78d33427b61a2665ff33 | [
"MIT"
] | 2 | 2015-01-10T16:09:40.000Z | 2016-05-09T01:58:17.000Z | src/Diva.MainMenu/Diva.MainMenu.WelcomeVBox.cs | mdk/diva | f58841d8b539d925a95d78d33427b61a2665ff33 | [
"MIT"
] | null | null | null | src/Diva.MainMenu/Diva.MainMenu.WelcomeVBox.cs | mdk/diva | f58841d8b539d925a95d78d33427b61a2665ff33 | [
"MIT"
] | null | null | null | ////////////////////////////////////////////////////////////////////////////////
// //
// MIT X11 license, Copyright (c) 2005-2006 by: //
// //
// Authors: //
// Michael Dominic K. <[email protected]> //
// //
// 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. //
// //
////////////////////////////////////////////////////////////////////////////////
/* This VBox contains the main menu just after the splash screen
*/
namespace Diva.MainMenu {
using System;
using Mono.Unix;
using Gtk;
using Util;
using Widgets;
public class WelcomeVBox : VBox {
// Fields //////////////////////////////////////////////////////
Button helpButton = null;
Button closeButton = null;
HButtonBox buttonBox = null;
VButtonBox menuBox = null;
Model model = null;
// Translatable ///////////////////////////////////////////////
readonly static string welcomeSS = Catalog.GetString
("<b>Welcome to Diva</b>\n");
readonly static string newSS = Catalog.GetString
("Start editing a new movie");
readonly static string preferencesSS = Catalog.GetString
("Preferences");
readonly static string openSS = Catalog.GetString
("Open a project");
readonly static string captureSS = Catalog.GetString
("Capture media");
readonly static string pruneSS = Catalog.GetString
("Prune projects and media files");
// Public methods //////////////////////////////////////////////
/* CONSTRUCTOR */
public WelcomeVBox (Model model) : base (false, 6)
{
this.model = model;
// Image
Image welcomeLogo = new Gtk.Image (Util.IconFu.MainDivaIcon96);
// Labels
Label welcomeLabel = new Gtk.Label (welcomeSS);
welcomeLabel.UseMarkup = true;
welcomeLabel.Justify = Justification.Center;
// Buttons
helpButton = new Button (Stock.Help);
closeButton = new Button (Stock.Close);
closeButton.Clicked += OnCloseClicked;
// Button box
buttonBox = new HButtonBox ();
buttonBox.Add (helpButton);
buttonBox.Add (closeButton);
buttonBox.Spacing = 6;
// Menu
OffsettedButton newButton = new OffsettedButton (newSS, "gnome-multimedia");
newButton.Clicked += OnNewProjectClicked;
OffsettedButton preferencesButton = new OffsettedButton (preferencesSS, Stock.Preferences);
preferencesButton.Clicked += OnPreferencesClicked;
OffsettedButton openButton = new OffsettedButton (openSS, Stock.Open);
openButton.Clicked += OnOpenProjectClicked;
OffsettedButton captureButton = new OffsettedButton (captureSS, Stock.MediaRecord);
captureButton.Clicked += OnCaptureClicked;
OffsettedButton pruneButton = new OffsettedButton (pruneSS, "gnome-fs-trash-empty");
pruneButton.Clicked += OnPruneClicked;
// Menu button box
menuBox = new VButtonBox ();
menuBox.Layout = ButtonBoxStyle.Start;
menuBox.Spacing = 6;
menuBox.PackStart (newButton);
menuBox.PackStart (openButton);
menuBox.PackStart (captureButton);
menuBox.PackStart (pruneButton);
menuBox.PackStart (preferencesButton);
// Pack it
PackStart (welcomeLogo, false, false, 0);
PackStart (welcomeLabel, false, false, 0);
PackStart (menuBox, true, true, 0);
PackEnd (buttonBox, false, false, 0);
}
// Private methods /////////////////////////////////////////////
void OnNewProjectClicked (object o, EventArgs args)
{
model.SwitchToComponent (MenuComponent.NewProject);
}
void OnOpenProjectClicked (object o, EventArgs args)
{
model.SwitchToComponent (MenuComponent.OpenProject);
}
void OnCloseClicked (object o, EventArgs args)
{
model.QuitApplication (0);
}
void OnCaptureClicked (object o, EventArgs args)
{
FastDialog.InfoOkNotImplemented (null);
}
void OnPruneClicked (object o, EventArgs args)
{
FastDialog.InfoOkNotImplemented (null);
}
void OnPreferencesClicked (object o, EventArgs args)
{
FastDialog.InfoOkNotImplemented (null);
}
}
}
| 47.754717 | 115 | 0.434874 |
dba12455a50e88848f48e20722abb48cd03715e1 | 341 | php | PHP | src/Utils/IconData.php | Barbarossa-42/datagrid | 8ab693161a89c5fd0a58ac85db0b2e965f22ef95 | [
"MIT"
] | null | null | null | src/Utils/IconData.php | Barbarossa-42/datagrid | 8ab693161a89c5fd0a58ac85db0b2e965f22ef95 | [
"MIT"
] | null | null | null | src/Utils/IconData.php | Barbarossa-42/datagrid | 8ab693161a89c5fd0a58ac85db0b2e965f22ef95 | [
"MIT"
] | null | null | null | <?php
namespace Ublaboo\DataGrid\Utils;
class IconData
{
/**
* @var string
*/
public $content;
/**
* @var string
*/
public $iconClass;
/**
* @param string $content
* @param string $iconClass
*/
public function __construct($content, $iconClass)
{
$this->content = $content;
$this->iconClass = $iconClass;
}
}
| 12.178571 | 50 | 0.615836 |
af674f4a0aa5533bd74643e9a5bef25460b19717 | 2,179 | py | Python | scripts/amr2txt/preproces.py | pywirrarika/GPT-too-AMR2text | 82d700cb81bc332bb07221d380cdf2318324109c | [
"Apache-2.0"
] | 37 | 2020-05-20T02:51:43.000Z | 2022-02-23T13:43:47.000Z | scripts/amr2txt/preproces.py | pywirrarika/GPT-too-AMR2text | 82d700cb81bc332bb07221d380cdf2318324109c | [
"Apache-2.0"
] | 4 | 2020-07-18T12:36:20.000Z | 2021-06-05T14:09:21.000Z | scripts/amr2txt/preproces.py | pywirrarika/GPT-too-AMR2text | 82d700cb81bc332bb07221d380cdf2318324109c | [
"Apache-2.0"
] | 8 | 2020-05-22T23:43:37.000Z | 2022-03-09T23:16:25.000Z | import os
import json
import re
import argparse
def argument_parser():
parser = argparse.ArgumentParser(description='Preprocess AMR data')
# Multiple input parameters
parser.add_argument(
"--in-amr",
help="input AMR file",
type=str
)
parser.add_argument(
"--out-amr",
help="output (post-processed) AMR file",
type=str
)
parser.add_argument(
"--out-tokens",
help="tokens from AMR",
type=str
)
parser.add_argument(
"--stog-fix",
action='store_true',
help="Reformat AMR token to be parseable by publict stog"
)
args = parser.parse_args()
return args
def fix_tokens_file(file_path):
"""
Replace each
# ::tok sentence
by json parsable version
# ::token json-parseable-sentence
so that
sentence == json.loads(json-parseable-sentence)
"""
token_line = re.compile('^# ::tok (.*)')
# read and modifiy token lines
new_amr = []
tokens = []
with open(file_path) as fid:
for line in fid:
fetch = token_line.match(line.rstrip())
if fetch:
sentence = fetch.groups()[0]
tokens.append(sentence)
json_str = json.dumps(sentence)
new_amr.append(f'# ::tokens {json_str}\n')
else:
new_amr.append(line)
return new_amr, tokens
if __name__ == '__main__':
# Argument handlig
args = argument_parser()
assert os.path.isfile(args.in_amr), \
f'{args.in_amr} is missing or is not a file'
# create pre-processed AMR and extract tokens
new_amr, tokens = fix_tokens_file(args.in_amr)
assert tokens, "did not find tokens, AMR already formatted?"
# write pre-processed AMR
if args.stog_fix:
print(args.out_amr)
with open(args.out_amr, 'w') as fid:
for line in new_amr:
fid.write(line)
# write tokens
if args.out_tokens:
print(args.out_tokens)
with open(args.out_tokens, 'w') as fid:
for tok_sent in tokens:
fid.write(f'{tok_sent}\n')
| 22.936842 | 71 | 0.580083 |
33c76afd5aaf8bc65cb77f0b422642282618cb3e | 2,209 | h | C | code/engine/xrPhysics/PhysicsCommon.h | InNoHurryToCode/xray-162 | fff9feb9ffb681b3c6ba1dc7c4534fe80006f87e | [
"Apache-2.0"
] | 58 | 2016-11-20T19:14:35.000Z | 2021-12-27T21:03:35.000Z | code/engine/xrPhysics/PhysicsCommon.h | InNoHurryToCode/xray-162 | fff9feb9ffb681b3c6ba1dc7c4534fe80006f87e | [
"Apache-2.0"
] | 59 | 2016-09-10T10:44:20.000Z | 2018-09-03T19:07:30.000Z | code/engine/xrPhysics/PhysicsCommon.h | InNoHurryToCode/xray-162 | fff9feb9ffb681b3c6ba1dc7c4534fe80006f87e | [
"Apache-2.0"
] | 39 | 2017-02-05T13:35:37.000Z | 2022-03-14T11:00:12.000Z | #ifndef PHYSICS_COMMON_H
#define PHYSICS_COMMON_H
#include "DisablingParams.h"
#include "physicsexternalcommon.h"
//#include "ode_include.h"
//#include "../3rd party/ode/include/ode/common.h"
extern XRPHYSICS_API const float default_l_limit;
extern XRPHYSICS_API const float default_w_limit;
extern XRPHYSICS_API const float default_k_l;
extern XRPHYSICS_API const float default_k_w;
extern const float default_l_scale;
extern const float default_w_scale;
extern const float base_fixed_step;
extern const float base_erp;
extern const float base_cfm;
extern XRPHYSICS_API float fixed_step;
extern float world_cfm;
extern float world_erp;
extern float world_spring;
extern float world_damping;
// extern const float mass_limit
// ;
extern const u16 max_joint_allowed_for_exeact_integration;
extern XRPHYSICS_API const float default_world_gravity;
extern XRPHYSICS_API float phTimefactor;
extern XRPHYSICS_API int phIterations;
// extern float phBreakCommonFactor
// ; extern float phRigidBreakWeaponFactor
// ; extern float ph_tri_query_ex_aabb_rate
// ; extern int ph_tri_clear_disable_count
// ;
struct SGameMtl;
#define ERP_S(k_p, k_d, s) ((s * (k_p)) / (((s) * (k_p)) + (k_d)))
#define CFM_S(k_p, k_d, s) (1.f / (((s) * (k_p)) + (k_d)))
#define SPRING_S(cfm, erp, s) ((erp) / (cfm) / s)
//////////////////////////////////////////////////////////////////////////////////
#define DAMPING(cfm, erp) ((1.f - (erp)) / (cfm))
#define ERP(k_p, k_d) ERP_S(k_p, k_d, fixed_step)
#define CFM(k_p, k_d) CFM_S(k_p, k_d, fixed_step)
#define SPRING(cfm, erp) SPRING_S(cfm, erp, fixed_step)
IC float Erp(float k_p, float k_d, float s = fixed_step) {
return ((s * (k_p)) / (((s) * (k_p)) + (k_d)));
}
IC float Cfm(float k_p, float k_d, float s = fixed_step) { return (1.f / (((s) * (k_p)) + (k_d))); }
IC float Spring(float cfm, float erp, float s = fixed_step) { return ((erp) / (cfm) / s); }
IC float Damping(float cfm, float erp) { return ((1.f - (erp)) / (cfm)); }
IC void MulSprDmp(float& cfm, float& erp, float mul_spring, float mul_damping) {
float factor = 1.f / (mul_spring * erp + mul_damping * (1 - erp));
cfm *= factor;
erp *= (factor * mul_spring);
}
#endif // PHYSICS_COMMON_H | 36.213115 | 100 | 0.690358 |
d0a77d01629e931823f41a16007a608fbd3a6a67 | 2,836 | dart | Dart | lib/views/tvshow_detail_page/state.dart | zhengger/Flutter-Movie | 29987360ac47e85f7082f2f8aedc672222b46cc2 | [
"Apache-2.0"
] | 1 | 2020-06-11T16:51:04.000Z | 2020-06-11T16:51:04.000Z | lib/views/tvshow_detail_page/state.dart | zhengger/Flutter-Movie | 29987360ac47e85f7082f2f8aedc672222b46cc2 | [
"Apache-2.0"
] | null | null | null | lib/views/tvshow_detail_page/state.dart | zhengger/Flutter-Movie | 29987360ac47e85f7082f2f8aedc672222b46cc2 | [
"Apache-2.0"
] | null | null | null | import 'package:fish_redux/fish_redux.dart';
import 'package:flutter/material.dart';
import 'package:movie/globalbasestate/store.dart';
import 'package:movie/models/base_api_model/account_state.dart';
import 'package:movie/models/creditsmodel.dart';
import 'package:movie/models/imagemodel.dart';
import 'package:movie/models/keyword.dart';
import 'package:movie/models/review.dart';
import 'package:movie/models/tvdetail.dart';
import 'package:movie/models/videolist.dart';
import 'package:movie/models/videomodel.dart';
class TvShowDetailState implements Cloneable<TvShowDetailState> {
GlobalKey<ScaffoldState> scaffoldkey;
TVDetailModel tvDetailModel;
int tvid;
String name;
String posterPic;
CreditsModel creditsModel;
ImageModel imagesmodel;
ReviewModel reviewModel;
VideoListModel recommendations;
KeyWordModel keywords;
VideoModel videomodel;
String backdropPic;
Color mainColor;
Color tabTintColor;
AccountState accountState;
@override
TvShowDetailState clone() {
return TvShowDetailState()
..scaffoldkey = scaffoldkey
..tvDetailModel = tvDetailModel
..mainColor = mainColor
..tabTintColor = tabTintColor
..creditsModel = creditsModel
..tvid = tvid
..reviewModel = reviewModel
..imagesmodel = imagesmodel
..recommendations = recommendations
..keywords = keywords
..videomodel = videomodel
..backdropPic = backdropPic
..posterPic = posterPic
..name = name
..accountState = accountState;
}
}
TvShowDetailState initState(Map<String, dynamic> args) {
TvShowDetailState state = TvShowDetailState();
state.scaffoldkey =
GlobalKey<ScaffoldState>(debugLabel: '_TvShowDetailPagekey');
state.tvid = args['tvid'];
if (args['bgpic'] != null) state.backdropPic = args['bgpic'];
if (args['posterpic'] != null) state.posterPic = args['posterpic'];
if (args['name'] != null) state.name = args['name'];
state.tvDetailModel = new TVDetailModel.fromParams();
state.creditsModel = new CreditsModel.fromParams(
cast: List<CastData>(), crew: List<CrewData>());
state.imagesmodel = new ImageModel.fromParams(
posters: List<ImageData>(), backdrops: List<ImageData>());
state.reviewModel = new ReviewModel.fromParams(results: List<ReviewResult>());
state.recommendations =
new VideoListModel.fromParams(results: List<VideoListResult>());
state.keywords = new KeyWordModel.fromParams(
keywords: List<KeyWordData>(), results: List<KeyWordData>());
state.videomodel = new VideoModel.fromParams(results: List<VideoResult>());
state.accountState = AccountState.fromParams(
id: 0,
uid: GlobalStore.store.getState().user?.firebaseUser?.uid,
mediaId: state.tvid,
favorite: false,
watchlist: false,
mediaType: 'tv');
return state;
}
| 35.898734 | 80 | 0.724965 |
446e002c8c15a745cda335facc4ab78fcda296e5 | 1,802 | py | Python | tests/test_create.py | tachyondecay/quickpaste | 880de852b45e0b3b2bbfdff93888bf54b19a416e | [
"MIT"
] | null | null | null | tests/test_create.py | tachyondecay/quickpaste | 880de852b45e0b3b2bbfdff93888bf54b19a416e | [
"MIT"
] | null | null | null | tests/test_create.py | tachyondecay/quickpaste | 880de852b45e0b3b2bbfdff93888bf54b19a416e | [
"MIT"
] | null | null | null | from app.create_app import limiter, shortlink
from app.repositories import db
def test_should_return_200(client):
rv = client.get('/')
assert rv.status_code == 200
assert rv.headers['Content-type'] == 'text/html; charset=utf-8'
def test_should_return_redirect_to_home(client):
rv = client.post('/')
assert rv.status_code == 302
assert rv.headers['Location'] == 'http://localhost/'
def test_should_return_413(client):
text = 'aaaaaaaaaaaaaaaaaaaaa'
rv = client.post('/', data={'text': text})
assert rv.status_code == 413
assert rv.headers['Content-type'] == 'text/html; charset=utf-8'
def test_should_return_429(client):
limiter.enabled = True
client.get('/')
client.get('/')
rv = client.get('/')
assert rv.status_code == 429
def test_should_return_400(client):
rv = client.post('/', headers={'X-Respondwith': 'link'})
assert rv.status_code == 400
assert rv.headers['Content-type'] == 'text/plain; charset=utf-8'
def test_should_return_500(app, client):
with app.app_context():
db.engine.execute('DROP TABLE pastes')
# Need to do this to reset migrations history
db.engine.execute('DROP TABLE alembic_version')
rv = client.post('/', data={'text': 'foo'})
assert rv.status_code == 500
def test_should_return_redirect_to_paste(client):
rv = client.post('/', data={'text': 'hello_world'})
assert rv.status_code == 302
assert rv.headers['Location'] == 'http://localhost/{}'.format(
shortlink.encode(1))
def test_should_return_link_to_paste(client):
rv = client.post('/', data={'text': 'hello_world'},
headers={'X-Respondwith': 'link'})
assert rv.status_code == 200
assert rv.headers['Content-type'] == 'text/plain; charset=utf-8'
| 30.542373 | 68 | 0.660932 |
d650ee9be747187eaabaaac97ff655f55d14a4a9 | 604 | cs | C# | src/Essensoft.AspNetCore.Payment.Alipay/Domain/KoubeiCateringPosDeskareaSyncModel.cs | LuohuaRain/payment | e175dd1e2af43c07d01e60c575dc9ec128c2757b | [
"MIT"
] | 1 | 2021-04-21T03:40:05.000Z | 2021-04-21T03:40:05.000Z | src/Essensoft.AspNetCore.Payment.Alipay/Domain/KoubeiCateringPosDeskareaSyncModel.cs | LuohuaRain/payment | e175dd1e2af43c07d01e60c575dc9ec128c2757b | [
"MIT"
] | null | null | null | src/Essensoft.AspNetCore.Payment.Alipay/Domain/KoubeiCateringPosDeskareaSyncModel.cs | LuohuaRain/payment | e175dd1e2af43c07d01e60c575dc9ec128c2757b | [
"MIT"
] | 1 | 2022-02-22T01:16:19.000Z | 2022-02-22T01:16:19.000Z | using System.Text.Json.Serialization;
namespace Essensoft.AspNetCore.Payment.Alipay.Domain
{
/// <summary>
/// KoubeiCateringPosDeskareaSyncModel Data Structure.
/// </summary>
public class KoubeiCateringPosDeskareaSyncModel : AlipayObject
{
/// <summary>
/// 餐区信息
/// </summary>
[JsonPropertyName("desk_area")]
public DeskAreaEntity DeskArea { get; set; }
/// <summary>
/// 标识接口所做操作,add 新增,update 修改,del 删除,其他返回 null
/// </summary>
[JsonPropertyName("type")]
public string Type { get; set; }
}
}
| 26.26087 | 66 | 0.602649 |
0743b9384ab1481076a655e9d9047ea3d8f4f0e2 | 1,395 | sql | SQL | Chapter04/CH05_23_merge_using_checksums.sql | PhilippeBinggeli/Hands-On-Data-Science-with-SQL-Server-2017 | f0af444e190ce7fcaf5e65fc2d5bae4f6f66a73b | [
"MIT"
] | 8 | 2018-07-09T16:08:23.000Z | 2021-11-08T13:10:52.000Z | Chapter04/CH05_23_merge_using_checksums.sql | PhilippeBinggeli/Hands-On-Data-Science-with-SQL-Server-2017 | f0af444e190ce7fcaf5e65fc2d5bae4f6f66a73b | [
"MIT"
] | null | null | null | Chapter04/CH05_23_merge_using_checksums.sql | PhilippeBinggeli/Hands-On-Data-Science-with-SQL-Server-2017 | f0af444e190ce7fcaf5e65fc2d5bae4f6f66a73b | [
"MIT"
] | 9 | 2018-08-07T09:54:39.000Z | 2021-05-21T17:44:23.000Z | DROP TABLE IF EXISTS #res -- temporary table used to catch what was done
CREATE TABLE #res (Id int, Discontinued bit, WhatHappens nvarchar(10))
-- common table expression is added to resolve a state of every record
;WITH cte AS
(
SELECT lp.*
, IIF(sp.ProductKey is null, 'UPDATE', 'NONE') as DesiredAction
FROM Landing.Products AS lp
LEFT JOIN Staging.Products as sp ON lp.ProductKey = sp.ProductKey
AND CHECKSUM(lp.ProductKey, lp.ProductName, lp.ListPrice) =
CHECKSUM(sp.ProductKey, sp.ProductName, sp.ListPrice)
)
MERGE Staging.Products AS sp
USING cte AS lp -- Landing.Products is used no more, instead the CTE is used
ON sp.ProductKey = lp.ProductKey
WHEN MATCHED and DesiredAction = 'UPDATE' THEN -- new condition added
UPDATE SET
ProductName = lp.ProductName
, ListPrice = lp.ListPrice
, Discontinued = 0
WHEN NOT MATCHED BY TARGET THEN -- this node remains without changes
INSERT (ProductKey, ProductName, ListPrice)
VALUES (lp.ProductKey, lp.ProductName, lp.ListPrice)
WHEN NOT MATCHED BY SOURCE and sp.Discontinued = 0 THEN -- new condition added
UPDATE SET Discontinued = 1 -- this is a logical delete
-- when we want actual delete,
-- we'll just write DELETE
OUTPUT inserted.Id, Inserted.Discontinued, $action AS WhatHappens into #res
;
SELECT * FROM #res -- inspecting results | 43.59375 | 78 | 0.712545 |
75b50bc90830d7b1cf55ec2412b44dd85d2e4ac3 | 1,704 | css | CSS | public/stylesheets/common.css | danielvlopes/base_app | 9d17939293cc6ebc8cb5f69a45599a985a34aa16 | [
"MIT"
] | 1 | 2015-11-05T05:49:52.000Z | 2015-11-05T05:49:52.000Z | public/stylesheets/common.css | danielvlopes/base_app | 9d17939293cc6ebc8cb5f69a45599a985a34aa16 | [
"MIT"
] | null | null | null | public/stylesheets/common.css | danielvlopes/base_app | 9d17939293cc6ebc8cb5f69a45599a985a34aa16 | [
"MIT"
] | null | null | null | /* flash messages */
.flash-message {
position: relative;
}
.flash-message .close {
font-weight:bold;
position: absolute;
right: 10px;
top:10px;
cursor: pointer;
}
#notice {
padding: 10px 10px 10px 40px;
color: #264409;
background: #e6efc2 url(/images/notice.png) no-repeat 10px 10px;
border: 1px solid #c6d880;
}
#alert {
padding: 10px 10px 10px 40px;
color: #514721;
background: #fff6bf url(/images/alert.png) no-repeat 10px 10px;
border: 1px solid #ffd324;
}
#error {
margin: 5px 0;
padding: 10px 10px 10px 40px;
color: #8a1f11;
background-color: #fbe3e4;
background-image: url(/images/error.png);
background-position: 10px 10px;
background-repeat: no-repeat;
border: 1px solid #fbc2c4;
}
/* error messages */
.input_error {
display:table;
font-size:10px;
color:#ff0000;
background:#ffffcc;
}
#errorExplanation {
border: 2px solid red;
padding: 7px;
padding-bottom: 12px;
margin-bottom: 20px;
background-color: #f0f0f0;
}
#errorExplanation h2 {
text-align: left;
font-weight: bold;
padding: 5px 5px 5px 15px;
font-size: 12px;
margin: -7px;
background-color: #c00;
color: #fff;
}
#errorExplanation p {
color: #333;
margin-bottom: 0;
padding: 5px;
}
#errorExplanation ul li {
font-size: 12px;
list-style: square;
}
/* misc */
.middle { vertical-align:middle; }
.left { float:left; }
.right { float:right; }
.clear { clear:both; }
.txt-center { text-align:center !important; }
.txt-right { text-align:right !important; }
.txt-left { text-align:left !important; }
.odd { background-color:#F1F5FA; }
.even { background-color:#FFF; }
.highlight { background-color:#FFFFCC; } | 19.813953 | 66 | 0.660798 |
eb8351a7b29dc76cfab30cbc515ee9b87cb048fa | 626 | dart | Dart | lib/controller/helper/theme.dart | wappon-28-dev/majimo_timer | 3bbe49504e55c44c5fb5d8d6336b3a3e31891f9e | [
"MIT"
] | null | null | null | lib/controller/helper/theme.dart | wappon-28-dev/majimo_timer | 3bbe49504e55c44c5fb5d8d6336b3a3e31891f9e | [
"MIT"
] | null | null | null | lib/controller/helper/theme.dart | wappon-28-dev/majimo_timer | 3bbe49504e55c44c5fb5d8d6336b3a3e31891f9e | [
"MIT"
] | 1 | 2022-03-18T12:09:10.000Z | 2022-03-18T12:09:10.000Z | part of '../controller.dart';
class ThemeController extends StateNotifier<ThemeState> {
ThemeController() : super(const ThemeState());
// change_value functions
void updateTheme({required int value}) {
state = state.copyWith(theme: value);
PrefManager().setInt(key: PrefKey.appTheme, value: value);
Logger.s('- from ThemeState \n >> save int theme = ${state.theme}');
}
bool isLight({required BuildContext context}) {
final isLightMode =
MediaQuery.of(context).platformBrightness == Brightness.light;
final pref = state.theme;
return (pref != 0) ? (pref == 1) : isLightMode;
}
}
| 31.3 | 72 | 0.680511 |
796a7c92dd3ef88dcc8edcfca894b9b3dbffa5b1 | 2,422 | php | PHP | resources/views/front/contact.blade.php | nguyencongluat21092001/Project_Fitness_Lifestyle | 90c9043c9a84a569c802ccd32595215e08873729 | [
"MIT"
] | null | null | null | resources/views/front/contact.blade.php | nguyencongluat21092001/Project_Fitness_Lifestyle | 90c9043c9a84a569c802ccd32595215e08873729 | [
"MIT"
] | null | null | null | resources/views/front/contact.blade.php | nguyencongluat21092001/Project_Fitness_Lifestyle | 90c9043c9a84a569c802ccd32595215e08873729 | [
"MIT"
] | null | null | null | @extends('front.Users.Layout.app')
@section('body')
<div id="fh5co-contact">
<div class="container">
<div class="row">
<div class="col-md-5 col-md-push-1 animate-box">
<div class="fh5co-contact-info">
<h3>Thông tin liên lạc</h3>
<ul>
<li class="address">8 Tôn Thất Thuyết,Hà Nội <br>FITNESS_LIFSTYLE - T2009E</li>
<li class="phone"><a href="tel://1234567920">+84 386 358 006</a></li>
<li class="email"><a href="mailto:[email protected]">[email protected]</a></li>
<li class="url"><a href="https://www.facebook.com/profile.php?id=100059688523687">Facebook: Fitness LifeStyle VN</a></li>
<li class="email"><a>Bình luận</a>
</li>
</ul>
</div>
</div>
<div class="col-md-6 animate-box">
<h3>Liên lạc</h3>
<form action="{{ route('store.contact')}}" role="form" method="POST">
@method("POST")
@csrf
<div class="row form-group">
<div class="col-md-6">
<!-- <label for="fname">First Name</label> -->
<input type="text" name="post_name" id="fname" class="form-control" placeholder="Tên của bạn?">
</div>
<div class="col-md-6">
<!-- <label for="lname">Last Name</label> -->
<input type="text" name="post_age"id="lname" class="form-control" placeholder="Tuổi">
</div>
</div>
<div class="row form-group">
<div class="col-md-12">
<!-- <label for="email">Email</label> -->
<input type="text" name="post_adress"id="email" class="form-control" placeholder="Địa chỉ">
</div>
</div>
<div class="row form-group">
<div class="col-md-12">
<!-- <label for="subject">Subject</label> -->
<input type="number" name="post_phone"id="subject" class="form-control" placeholder="Điện thoại">
</div>
</div>
<div class="row form-group">
<div class="col-md-12">
<!-- <label for="message">Message</label> -->
<textarea type="text" name="post_comment"id="message" cols="30" rows="10" class="form-control" placeholder="Hãy nói đôi điều về chúng tôi."></textarea>
</div>
</div>
<div class="form-group">
<button type="submit" name="submit"class="btn btn-success">Gửi</button>
</div>
<?php
$name = Session::get('success');
if($name){
echo $name;
}else {
}
?>
</form>
</div>
</div>
</div>
</div>
@endsection
| 31.868421 | 159 | 0.569777 |
7f742bdda376e9e3b73ada5765b7b1c85a23e2ba | 559 | php | PHP | app/Http/Controllers/PerkenalanController.php | muhamadabduh/demo-crud | ebfdc4ce9fa8cb6ead14a243f13a51605da2856f | [
"MIT"
] | null | null | null | app/Http/Controllers/PerkenalanController.php | muhamadabduh/demo-crud | ebfdc4ce9fa8cb6ead14a243f13a51605da2856f | [
"MIT"
] | null | null | null | app/Http/Controllers/PerkenalanController.php | muhamadabduh/demo-crud | ebfdc4ce9fa8cb6ead14a243f13a51605da2856f | [
"MIT"
] | null | null | null | <?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class PerkenalanController extends Controller
{
//
public function halo($nama_depan, $nama_belakang) {
$nama_lengkap = "$nama_depan $nama_belakang";
return view('perkenalan', compact('nama_lengkap'));
}
public function form () {
return view('form');
}
public function selamat_datang(Request $request) {
// dd($request->all());
$email = $request["email"];
return view('setelah-login', ["surel" => $email]);
}
}
| 21.5 | 59 | 0.618962 |
81beee1eaa3dfd048053f6360bee5a18c752ad35 | 628 | php | PHP | src/MuseumBundle/Repository/ReclamationmRepository.php | Dorra66/Application_Web_Symfony | 5229435eec96b4b91dbb1e25452ced2bf909b574 | [
"MIT"
] | null | null | null | src/MuseumBundle/Repository/ReclamationmRepository.php | Dorra66/Application_Web_Symfony | 5229435eec96b4b91dbb1e25452ced2bf909b574 | [
"MIT"
] | null | null | null | src/MuseumBundle/Repository/ReclamationmRepository.php | Dorra66/Application_Web_Symfony | 5229435eec96b4b91dbb1e25452ced2bf909b574 | [
"MIT"
] | null | null | null | <?php
namespace MuseumBundle\Repository;
use MuseumBundle\Entity\Reclamationm;
use UserBundle\Entity\User;
/**
* ReclamationmRepository
*
* This class was generated by the Doctrine ORM. Add your own custom
* repository methods below.
*/
class ReclamationmRepository extends \Doctrine\ORM\EntityRepository
{
//Chercher mes réclamations (Client) : (*:Utilisateur connecté)
public function findMyClaims($person)
{
$query = $this->getEntityManager()->createQuery(" SELECT r FROM MuseumBundle:Reclamationm r WHERE r.idsource='$person'");
return $query->getResult();
}
} | 27.304348 | 130 | 0.700637 |
0708215d01dd914db2f5d20555d047e70894d338 | 1,626 | h | C | BZRelativeLayout/UltimatePower+UIView.h | CBillZhang/BZRelativeLayout | 10e4c212bdd9cbe29a058303e5f10c5de82b0c04 | [
"MIT"
] | 3 | 2017-03-29T09:06:15.000Z | 2017-08-23T08:23:47.000Z | BZRelativeLayout/UltimatePower+UIView.h | CBillZhang/BZRelativeLayout | 10e4c212bdd9cbe29a058303e5f10c5de82b0c04 | [
"MIT"
] | null | null | null | BZRelativeLayout/UltimatePower+UIView.h | CBillZhang/BZRelativeLayout | 10e4c212bdd9cbe29a058303e5f10c5de82b0c04 | [
"MIT"
] | null | null | null | //
// UltimatePower.h
// BZFramework
//
// Created by Bill.Zhang on 2017/3/25.
// Copyright © 2017年 Bill.Zhang. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface UIView (BZSize)
@property(nonatomic) CGFloat bzLeft;
@property(nonatomic) CGFloat bzTop;
@property(nonatomic) CGFloat bzRight;
@property(nonatomic) CGFloat bzBottom;
@property(nonatomic) CGPoint bzOrigin;
@end
@interface UIView (BZRelativeLayout)
typedef NS_ENUM(NSInteger, BZRelativeRule){
//Must set a view
BZRelativeRuleStartOf,
BZRelativeRuleAboveOf,
BZRelativeRuleEndOf,
BZRelativeRuleBelowOf,
BZRelativeRuleAlignStart,
BZRelativeRuleAlignTop,
BZRelativeRuleAlignEnd,
BZRelativeRuleAlignBottom,
//Ignore view
BZRelativeRuleAlignParentStart,
BZRelativeRuleAlignParentTop,
BZRelativeRuleAlignParentEnd,
BZRelativeRuleAlignParentBottom,
//Ignore view,margin
BZRelativeRuleCenterHorizontalOf,
BZRelativeRuleCenterVerticalOf,
BZRelativeRuleCenterOf,
BZRelativeRuleCenterHorizontalInParent,
BZRelativeRuleCenterVerticalInParent,
BZRelativeRuleCenterInParent,
BZRelativeRuleBaseline//Only works on AutoLayout
};
@property(nonatomic,getter = isEnableAutoLayout) BOOL enableAutoLayout;//Default is YES
@property (nonatomic,nullable) NSArray<NSDictionary*> *rules;
-(void) addRule:(BZRelativeRule)rule;
-(void) addRule:(BZRelativeRule)rule view:(nullable UIView*) view;
-(void) addRule:(BZRelativeRule)rule margin:(CGFloat) margin;
-(void) addRule:(BZRelativeRule)rule view:(nullable UIView*) view margin:(CGFloat) margin;
@end
| 23.911765 | 90 | 0.760763 |
79cfdc247e5f41b287c94cb795da5ea26e774a58 | 8,998 | php | PHP | resources/lang/es/customers.php | aBillander/aBillander | 137d38e3fe3a84176ca33c228d0225078528a380 | [
"MIT"
] | 18 | 2018-09-20T13:28:45.000Z | 2022-03-27T19:51:30.000Z | resources/lang/es/customers.php | aBillander/aBillander | 137d38e3fe3a84176ca33c228d0225078528a380 | [
"MIT"
] | 14 | 2017-09-16T01:55:44.000Z | 2022-03-07T10:51:23.000Z | resources/lang/es/customers.php | aBillander/aBillander | 137d38e3fe3a84176ca33c228d0225078528a380 | [
"MIT"
] | 14 | 2015-05-08T06:11:30.000Z | 2021-05-26T13:42:00.000Z | <?php
return [
/*
|--------------------------------------------------------------------------
| Customers Language Lines :: index
|--------------------------------------------------------------------------
|
| .
|
*/
'Customers' => 'Clientes',
'Name' => 'Nombre',
'Email' => 'Correo Electrónico',
'Phone' => 'Teléfono',
'External Reference' => 'Referencia Externa',
'' => '',
'' => '',
'' => '',
'Invite Customer' => 'Invitar a un Cliente',
'Invite' => 'Invitar',
'Send an Invitation Email' => 'Enviar una Invitación por Email',
' :_> :company invites you to his Customer Center' => ' :_> :company le invita a su Centro de Clientes',
/*
|--------------------------------------------------------------------------
| Customers Language Lines :: create
|--------------------------------------------------------------------------
|
| .
|
*/
'Customers - Create' => 'Clientes - Crear',
'New Customer' => 'Nuevo Cliente',
'Back to Customers' => 'Volver a Clientes',
'Fiscal Name' => 'Nombre Fiscal',
'Commercial Name' => 'Nombre Comercial',
'Identification' => 'NIF / CIF',
'New Customers will take values from the Customer Group, but you can change these values later on.' =>
'El nuevo Cliente tomará valores del Grupo de Clientes, pero podrán cambiarse más adelante.',
'' => '',
'' => '',
'' => '',
'' => '',
'' => '',
'' => '',
/*
|--------------------------------------------------------------------------
| Customers Language Lines :: edit
|--------------------------------------------------------------------------
|
| .
|
*/
'Customers - Edit' => 'Clientes - Modificar',
'Edit Customer' => 'Modificar Cliente',
'This Customer is BLOCKED' => 'Este Cliente está BLOQUEADO',
'Group Shipping Slips' => 'Agrupar Albaranes',
'Group Orders' => 'Agrupar Pedidos',
'Invoice' => 'Factura',
'Main Data' => 'Datos Generales',
'Commercial' => 'Comercial',
'Banks Accounts' => 'Bancos',
'Address Book' => 'Direcciones',
'Special Prices' => 'Precios Especiales',
'Statistics' => 'Estadísticas',
'ABCC Access' => 'Acceso ABCC',
'Web Shop' => 'Tienda Online',
'Website' => 'Web',
'Misc' => 'Otros',
'Sequence for Invoices' => 'Serie de Facturas',
'Template for Invoices' => 'Plantilla para Facturas',
'Template for Orders' => 'Plantilla para Pedidos',
'Template for Shipping Slips' => 'Plantilla para Albaranes',
'Payment Method' => 'Forma de Pago',
'Payment Currency' => 'Divisa de Pago',
'Is Invoiceable?' => '¿Es Facturable?',
'Accept e-Invoice?' => '¿Admite Factura Electrónica?',
'Automatic Invoice?' => '¿Factura Automática?',
'Include this Customer in Automatic Invoice Generation Process.' => 'Incluir este Cliente en el Proceso de Facturación Automática.',
'Outstanding Amount Allowed' => 'Riesgo Máximo Permitido',
'Outstanding Amount' => 'Riesgo Alcanzado',
'Unresolved Amount' => 'Impagado',
'Sales Equalization' => 'Recargo de Equivalencia',
'Customer Group' => 'Grupo de Clientes',
'Price List' => 'Tarifa',
'Sales Representative' => 'Agente Comercial',
'Shipping Address' => 'Dirección de Envío',
'Carrier' => 'Transportista',
'Shipping Method' => 'Método de Envío',
'Webshop ID' => 'Código en la Tienda Web',
'Longitude' => 'Longitud',
'Latitude' => 'Latitud',
'Payment Day(s)' => 'Día(s) de Pago',
'Comma separated list of days, as in: 3,17' => 'Lista separada por comas, como: 3,17',
'No Payment Month' => 'Mes de No Pago',
'Document Discount (%)' => 'Descuento en Documento (%)',
'Prompt Payment Discount (%)' => 'Descuento Pronto Pago (%)',
'Special Addresses' => 'Direcciones especiales',
'Fiscal (main) Address' => 'Dirección Fiscal (principal)',
'This Address will appear on Invoices' => 'Es la Dirección que aparecerá en las Facturas',
'Shipping Address' => 'Dirección de Envío',
'Default Shipping Address' => 'Es la Dirección de Envío por defecto',
'Alias' => 'Alias',
'Address' => 'Dirección',
'Contact' => 'Contacto',
'Fiscal' => 'Fiscal',
'Shipping' => 'Envío',
'You need one Address at list, for Customer (:id) :name' => 'Debe crear al menos una Dirección Postal para el Cliente (:id) :name',
'Shipping Address has been updated for Customer (:id) :name' => 'Se ha actualizado la Dirección de Envío del Cliente (:id) :name',
'Main Address has been updated for Customer (:id) :name' => 'Se ha actualizado la Dirección Principal del Cliente (:id) :name',
'Default Shipping Address has been updated for Customer (:id) :name' => 'Se ha actualizado la Dirección de Envío por defecto para el Cliente (:id) :name',
'You should set the Main Address for Customer (:id) :name' => 'Debe indicar la Dirección Principal para el Cliente (:id) :name',
'No Payment Month' => 'Mes de No Pago',
'Orders' => 'Pedidos',
'View Order' => 'Ir al Pedido',
'Order #' => 'Número',
'Date' => 'Fecha',
'Created via' => 'Creado por',
'Delivery Date' => 'Fecha Entrega',
'Total' => 'Total',
'Products' => 'Productos',
'Product' => 'Producto',
'Document' => 'Documento',
'Price Rules' => 'Reglas de Precio',
'Category' => 'Categoría',
'Discount Percent' => 'Porcentaje de Descuento',
'Discount Amount' => 'Cantidad de Descuento',
'tax inc.' => 'IVA inc.',
'tax exc.' => 'IVA exc.',
'Price' => 'Precio',
'Currency' => 'Divisa',
'From Quantity' => 'Desde Cantidad',
'Date from' => 'Fecha desde',
'Date to' => 'Fecha hasta',
'Create Price Rule' => 'Crear Regla de Precio',
'Product Reference' => 'Referencia de Producto',
'Search by Product Reference or Name' => 'Busque por Nombre o Referencia',
'Customer Center Access' => 'Acceso al Centro de Clientes',
'Allow Customer Center access?' => '¿Permitir acceso al Centro de Clientes?',
'Notify Customer? (by email)' => '¿Informar al Cliente? (por email)',
'Shopping Cart' => 'Contenido del Carrito',
'Cart Items' => 'Productos en el Carrito',
'Reference' => 'Referencia',
'Product Name' => 'Producto',
'Customer Price' => 'Precio',
'Prices are exclusive of Tax' => 'El Precio no incluye Impuestos',
'Quantity' => 'Cantidad',
'Total' => 'Total',
'View Image' => 'Ver Imagen',
'Product Images' => 'Imágenes de Productos',
'EAN Code' => 'Código EAN',
'Manufacturer' => 'Marca',
'Stock' => 'Stock',
'Can not create a User for this Customer:' => 'No es posible crear un Usuario para este Cliente:',
'This Customer has not a valid email address.' => 'Este Cliente no tiene una dirección de correo electrónico válida.',
'' => '',
'' => '',
'Product consumption' => 'Consumo del Producto',
'Customer Final Price' => 'Precio Final',
'Bank Accounts' => 'Cuentas Bancarias',
'Bank Name' => 'Nombre del Banco',
'Bank Account Code' => 'Código Cuenta Cliente',
'Bank code' => 'Entidad',
'Bank Branch code' => 'Oficina',
'Control' => 'Control',
'Account' => 'Cuenta',
'Calculate Iban' => 'Calcular Iban',
'Iban' => 'Iban',
'To make it more readable, you can enter spaces.' => 'Para que sea mas legible, puede introducir espacios.',
'Swift' => 'Swift',
'Mandate (for automatic payment remittances)' => 'Mandato (para Remesas de pago automático)',
'Mandate Reference' => 'Referencia única',
'You can use Customer Identification (only letters and digits) plus space plus Mandate Date.' => 'Puede usar el NIF/CIF del Cliente, más un espacio, más la Fecha del Mandato.',
'Mandate Date' => 'Fecha de Firma',
'View Cart' => 'Ver Carrito',
'Add New User' => 'Nuevo Usuario para este Cliente',
'Create User' => 'Crear Usuario',
'Update User' => 'Modificar Usuario',
'Invoice Shipping Slips' => 'Facturar Albaranes',
'Accounting ID' => 'Código Contabilidad',
'Search by Name or Reference.' => 'Busque por Nombre o Referencia.',
'Reset search: empty field plus press [return].' => 'Reiniciar búsqueda: vacíe el campo y pulse [intro].',
'CustomerOrder' => 'Pedidos',
'CustomerShippingSlip' => 'Albaranes',
'CustomerInvoice' => 'Facturas',
'Description' => 'Descripción',
/*
|--------------------------------------------------------------------------
| Customers Language Lines :: VAT Regime List
|--------------------------------------------------------------------------
|
| .
|
*/
'VAT Regime' => 'Régimen de IVA',
'General' => 'General',
'Intra-Community' => 'Intracomunitario',
'Export' => 'Exportación',
'Exempt' => 'Exento',
'Invoice by Shipping Address?' => '¿Facturar por Dirección de Envío?',
'One Invoice per Shipping Address' => 'Una Factura por Dirección de Envío',
'One Invoice per Shipping Slip and Shipping Address' => 'Una Factura por Albarán y Dirección de Envío',
];
| 35.286275 | 177 | 0.574683 |
5ce3f9fa37e6d794e6e48a04f1c8afe51fb5d2e5 | 579 | swift | Swift | Sources/Classes/BundleLoader.swift | FlaneurApp/FlaneurImagePicker | eb5904ff9ffe435a10a18f1d0dd020cf66beff4e | [
"MIT"
] | 17 | 2017-12-17T17:36:03.000Z | 2019-02-10T17:57:14.000Z | Sources/Classes/BundleLoader.swift | FlaneurApp/FlaneurImagePicker | eb5904ff9ffe435a10a18f1d0dd020cf66beff4e | [
"MIT"
] | 4 | 2017-12-11T16:31:10.000Z | 2018-03-08T10:19:33.000Z | Sources/Classes/BundleLoader.swift | FlaneurApp/FlaneurImagePicker | eb5904ff9ffe435a10a18f1d0dd020cf66beff4e | [
"MIT"
] | null | null | null | /// The Assets bundle inside a pod is hard to reach.
/// This is the gateway.
class BundleLoader {
/// The assets bundle of the pod.
static var assetsBundle: Bundle = {
let podBundle = Bundle(for: BundleLoader.self)
guard let bundleURL = podBundle.url(forResource: "FlaneurImagePicker", withExtension: "bundle") else {
fatalError("Cannot locate assets bundle")
}
guard let assetsBundle = Bundle(url: bundleURL) else {
fatalError("Cannot create a bundle from URL")
}
return assetsBundle
}()
}
| 30.473684 | 110 | 0.637306 |
14a7478b9695821af3d3622fba1a18d3fdf4c58d | 2,466 | asm | Assembly | programs/oeis/092/A092966.asm | karttu/loda | 9c3b0fc57b810302220c044a9d17db733c76a598 | [
"Apache-2.0"
] | null | null | null | programs/oeis/092/A092966.asm | karttu/loda | 9c3b0fc57b810302220c044a9d17db733c76a598 | [
"Apache-2.0"
] | null | null | null | programs/oeis/092/A092966.asm | karttu/loda | 9c3b0fc57b810302220c044a9d17db733c76a598 | [
"Apache-2.0"
] | null | null | null | ; A092966: Number of interior balls in a truncated tetrahedral arrangement.
; 0,10,52,149,324,600,1000,1547,2264,3174,4300,5665,7292,9204,11424,13975,16880,20162,23844,27949,32500,37520,43032,49059,55624,62750,70460,78777,87724,97324,107600,118575,130272,142714,155924,169925,184740,200392,216904,234299,252600,271830,292012,313169,335324,358500,382720,408007,434384,461874,490500,520285,551252,583424,616824,651475,687400,724622,763164,803049,844300,886940,930992,976479,1023424,1071850,1121780,1173237,1226244,1280824,1337000,1394795,1454232,1515334,1578124,1642625,1708860,1776852,1846624,1918199,1991600,2066850,2143972,2222989,2303924,2386800,2471640,2558467,2647304,2738174,2831100,2926105,3023212,3122444,3223824,3327375,3433120,3541082,3651284,3763749,3878500,3995560,4114952,4236699,4360824,4487350,4616300,4747697,4881564,5017924,5156800,5298215,5442192,5588754,5737924,5889725,6044180,6201312,6361144,6523699,6689000,6857070,7027932,7201609,7378124,7557500,7739760,7924927,8113024,8304074,8498100,8695125,8895172,9098264,9304424,9513675,9726040,9941542,10160204,10382049,10607100,10835380,11066912,11301719,11539824,11781250,12026020,12274157,12525684,12780624,13039000,13300835,13566152,13834974,14107324,14383225,14662700,14945772,15232464,15522799,15816800,16114490,16415892,16721029,17029924,17342600,17659080,17979387,18303544,18631574,18963500,19299345,19639132,19982884,20330624,20682375,21038160,21398002,21761924,22129949,22502100,22878400,23258872,23643539,24032424,24425550,24822940,25224617,25630604,26040924,26455600,26874655,27298112,27725994,28158324,28595125,29036420,29482232,29932584,30387499,30847000,31311110,31779852,32253249,32731324,33214100,33701600,34193847,34690864,35192674,35699300,36210765,36727092,37248304,37774424,38305475,38841480,39382462,39928444,40479449,41035500,41596620,42162832,42734159,43310624,43892250,44479060,45071077,45668324,46270824,46878600,47491675,48110072,48733814,49362924,49997425,50637340,51282692,51933504,52589799,53251600,53918930,54591812,55270269,55954324,56644000,57339320,58040307,58746984,59459374
mov $2,$0
mov $3,$0
mov $6,$0
mov $7,$0
lpb $3,1
lpb $6,1
mov $0,$3
add $2,5
trn $3,$2
add $2,$0
add $5,$2
add $1,$5
sub $6,1
lpe
lpe
mov $8,$7
mov $10,$7
lpb $10,1
add $9,$8
sub $10,1
lpe
mov $4,1
mov $8,$9
lpb $4,1
add $1,$8
sub $4,1
lpe
mov $9,0
mov $10,$7
lpb $10,1
add $9,$8
sub $10,1
lpe
mov $4,2
mov $8,$9
lpb $4,1
add $1,$8
sub $4,1
lpe
| 57.348837 | 1,995 | 0.809002 |
d1770e7bd0db22a94663ba21ba9cfe12b40658d7 | 94 | html | HTML | src/main/resources/io/jenkins/plugins/ossarchiver/OSSArchiverConfiguration/help-endPoint_zh.html | JerryLocke/jenkins-oss-archiver | c8ca3c0e186d2f29b82142abf53f6c99b033d602 | [
"MIT"
] | null | null | null | src/main/resources/io/jenkins/plugins/ossarchiver/OSSArchiverConfiguration/help-endPoint_zh.html | JerryLocke/jenkins-oss-archiver | c8ca3c0e186d2f29b82142abf53f6c99b033d602 | [
"MIT"
] | null | null | null | src/main/resources/io/jenkins/plugins/ossarchiver/OSSArchiverConfiguration/help-endPoint_zh.html | JerryLocke/jenkins-oss-archiver | c8ca3c0e186d2f29b82142abf53f6c99b033d602 | [
"MIT"
] | null | null | null | <div>
OSS <a href="https://help.aliyun.com/document_detail/31837.html">访问域名</a>
</div>
| 23.5 | 78 | 0.648936 |
7d94aaf1c196094adac025d9965a28ec2428714f | 425 | rb | Ruby | lib/elasticband/aggregation/filter.rb | LoveMondays/slingband | 76af30bcee3b4f8abd290a88de6fb12f97e5564f | [
"MIT"
] | null | null | null | lib/elasticband/aggregation/filter.rb | LoveMondays/slingband | 76af30bcee3b4f8abd290a88de6fb12f97e5564f | [
"MIT"
] | null | null | null | lib/elasticband/aggregation/filter.rb | LoveMondays/slingband | 76af30bcee3b4f8abd290a88de6fb12f97e5564f | [
"MIT"
] | null | null | null | module Elasticband
class Aggregation
class Filter < Aggregation
attr_accessor :filter, :options
def initialize(name, filter, options = {})
super(name)
self.filter = filter
self.options = options
end
def to_h
super(aggregation_hash)
end
private
def aggregation_hash
{ filter: filter.to_h }.merge!(options)
end
end
end
end
| 17.708333 | 48 | 0.597647 |
b03bf655f5cc98ef3426a900e94c4c6077ff7207 | 905 | py | Python | main.py | cavalcantigor/tweets-ceuma | 4985e3c2241632823e710c039afe7b7f247b51f3 | [
"MIT"
] | null | null | null | main.py | cavalcantigor/tweets-ceuma | 4985e3c2241632823e710c039afe7b7f247b51f3 | [
"MIT"
] | null | null | null | main.py | cavalcantigor/tweets-ceuma | 4985e3c2241632823e710c039afe7b7f247b51f3 | [
"MIT"
] | null | null | null | from tweepy import (
API, Stream, OAuthHandler
)
from tt_keys import consumer_secret, consumer_key, access_token_secret, access_token
from ceuma_stream import StreamListenerCeuma
def timeline():
# get tweets from timeline
timeline_result = api.home_timeline()
return timeline_result
def search_tweets(query):
# get tweets that matches the query search
search_result = api.search(query, text_mode='extended')
return search_result
def print_tweets(tweets):
# print tweets
for tweet in tweets:
print(tweet.text)
# set consumer key and consumer secret key
auth = OAuthHandler(consumer_key, consumer_secret)
# set access token and access token secret
auth.set_access_token(access_token, access_token_secret)
# create api object
api = API(auth)
listener = StreamListenerCeuma()
stream = Stream(auth, listener)
stream.filter(track=['ceuma', 'dino', 'gol'])
| 23.815789 | 84 | 0.755801 |
75620a23998d51873a410079e72484fbe7960458 | 322 | css | CSS | dist/style.css | kvlin/Team-Profile-Generator | fb75e9f39a043e6ce66ffc254e1f177ce5477eb3 | [
"MIT"
] | null | null | null | dist/style.css | kvlin/Team-Profile-Generator | fb75e9f39a043e6ce66ffc254e1f177ce5477eb3 | [
"MIT"
] | null | null | null | dist/style.css | kvlin/Team-Profile-Generator | fb75e9f39a043e6ce66ffc254e1f177ce5477eb3 | [
"MIT"
] | null | null | null | .team {
text-align: center;
padding-top: 0.5em;
padding-bottom: 0.5em;
margin-bottom: 0.5em;
margin: auto;
background-color: rgb(235, 235, 235);
color:rgb(2, 109, 2);
}
.card {
margin: 1em 0em 0em 1em;
display:inline-block
}
.card-body {
background-color:rgb(191, 214, 191)
} | 18.941176 | 41 | 0.593168 |
06b6c59a68adfd7a23ce91086c462482161d71c5 | 1,376 | py | Python | singleview.py | puhachov/Discovering-spammers-from-multiple-views | 0484552af19e68148bd7c29d3a726b4323c00834 | [
"MIT"
] | 1 | 2022-01-23T11:28:53.000Z | 2022-01-23T11:28:53.000Z | singleview.py | puhachov/Discovering-spammers-from-multiple-views | 0484552af19e68148bd7c29d3a726b4323c00834 | [
"MIT"
] | null | null | null | singleview.py | puhachov/Discovering-spammers-from-multiple-views | 0484552af19e68148bd7c29d3a726b4323c00834 | [
"MIT"
] | null | null | null | import numpy as np
from sklearn.svm import SVC
from sklearn.model_selection import train_test_split
from sklearn.metrics import confusion_matrix
import pandas as pd
class singleview():
def __init__(self, data, class_):
self.X = np.copy(np.transpose(data))
self.ground_truth = np.sum(class_, axis = 1)
def evaluate(self, model, training_size):
X_train, X_test, y_train, y_test = train_test_split(self.X, self.ground_truth)
clf = model.fit(X_train, y_train)
y_pred = clf.predict(X_test)
confusion_matrix_ = confusion_matrix(y_test, y_pred)
precision = confusion_matrix_[0,0]/(confusion_matrix_[0,0] + confusion_matrix_[0,1])
recall = confusion_matrix_[0,0]/(confusion_matrix_[0,0] + confusion_matrix_[1,0])
F1_score = 2*precision*recall/(precision + recall)
confusion_matrix_df = pd.DataFrame(data = confusion_matrix_,
columns = ['Actual_Spammer', 'Actual_Legitimate'],
index = ['Predicted_Spammer ','Predicted_Legitimate'])
print("Precision: {}\n".format(precision))
print("Recall: {}\n".format(recall))
print("F1-score: {}\n".format(F1_score))
print("Confusion Matrix:\n {}\n".format(confusion_matrix_))
return precision, recall, F1_score, confusion_matrix_
| 38.222222 | 96 | 0.653343 |
b31581c32a44f3886d55bd3a411651c6d47fea63 | 106 | sql | SQL | app/src/main/assets/migrations/72.sql | DukeMobileTech/AndroidiSEE | bc7b53c3f5a7d4ee9b8a3c2bbaa13c1c0cf50cb6 | [
"MIT"
] | 4 | 2015-08-13T19:02:11.000Z | 2021-12-02T20:38:57.000Z | app/src/main/assets/migrations/72.sql | DukeMobileTech/AndroidiSEE | bc7b53c3f5a7d4ee9b8a3c2bbaa13c1c0cf50cb6 | [
"MIT"
] | null | null | null | app/src/main/assets/migrations/72.sql | DukeMobileTech/AndroidiSEE | bc7b53c3f5a7d4ee9b8a3c2bbaa13c1c0cf50cb6 | [
"MIT"
] | 5 | 2017-06-04T16:14:49.000Z | 2020-12-24T12:49:22.000Z | ALTER TABLE Questions ADD COLUMN RankResponses BOOLEAN;
ALTER TABLE Responses ADD COLUMN RankOrder STRING; | 53 | 55 | 0.858491 |
2f32f85242d50c73be33f2d9d9f0fcc124549265 | 354 | js | JavaScript | website/src/pages/examples.js | dhenson02/react-base-table-dk | c7388775e7e20ae6497baf5ce94106f73426eccf | [
"MIT"
] | null | null | null | website/src/pages/examples.js | dhenson02/react-base-table-dk | c7388775e7e20ae6497baf5ce94106f73426eccf | [
"MIT"
] | null | null | null | website/src/pages/examples.js | dhenson02/react-base-table-dk | c7388775e7e20ae6497baf5ce94106f73426eccf | [
"MIT"
] | null | null | null | import { Redirect } from '@reach/router';
import Page from 'components/Page';
import { withPrefix } from 'gatsby-link';
import React from 'react';
const Examples = () => (
<Page title="Examples">
<Redirect
from={withPrefix('/examples')}
to={withPrefix('/examples/default')}
noThrow
/>
</Page>
);
export default Examples;
| 19.666667 | 42 | 0.638418 |
a5eb5ae4b965d22413a00674c5b8354c054fc978 | 13,854 | h | C | packages/ogdf.js/ogdf/include/ogdf/graphalg/MinSteinerTreeGoemans139.h | ZJUVAI/ogdf.js | 6670d20b6c630a46593ac380d1edf91d2c9aabe8 | [
"MIT"
] | 3 | 2021-09-14T08:11:37.000Z | 2022-03-04T15:42:07.000Z | packages/ogdf.js/ogdf/include/ogdf/graphalg/MinSteinerTreeGoemans139.h | JackieAnxis/ogdf.js | 6670d20b6c630a46593ac380d1edf91d2c9aabe8 | [
"MIT"
] | 2 | 2021-12-04T17:09:53.000Z | 2021-12-16T08:57:25.000Z | packages/ogdf.js/ogdf/include/ogdf/graphalg/MinSteinerTreeGoemans139.h | ZJUVAI/ogdf.js | 6670d20b6c630a46593ac380d1edf91d2c9aabe8 | [
"MIT"
] | 2 | 2021-06-22T08:21:54.000Z | 2021-07-07T06:57:22.000Z | /** \file
* \brief Implementation of an LP-based 1.39+epsilon Steiner tree
* approximation algorithm by Goemans et al.
*
* \author Stephan Beyer
*
* \par License:
* This file is part of the Open Graph Drawing Framework (OGDF).
*
* \par
* Copyright (C)<br>
* See README.md in the OGDF root directory for details.
*
* \par
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* Version 2 or 3 as published by the Free Software Foundation;
* see the file LICENSE.txt included in the packaging of this file
* for details.
*
* \par
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* \par
* You should have received a copy of the GNU General Public
* License along with this program; if not, see
* http://www.gnu.org/copyleft/gpl.html
*/
#pragma once
#include <ogdf/graphalg/steiner_tree/FullComponentGeneratorDreyfusWagner.h>
#include <ogdf/graphalg/steiner_tree/Full2ComponentGenerator.h>
#include <ogdf/graphalg/steiner_tree/Full3ComponentGeneratorVoronoi.h>
#include <ogdf/graphalg/steiner_tree/common_algorithms.h>
#include <ogdf/graphalg/steiner_tree/LPRelaxationSER.h>
#include <ogdf/graphalg/steiner_tree/goemans/Approximation.h>
namespace ogdf {
/*!
* \brief This class implements the (1.39+epsilon)-approximation algorithm
* for the Steiner tree problem by Goemans et. al.
*
* @ingroup ga-steiner
*
* This implementation is based on:
*
* M.X. Goemans, N. Olver, T. Rothvoß, R. Zenklusen:
* Matroids and Integrality Gaps for Hypergraphic Steiner Tree Relaxations.
* STOC 2012, pages 1161-1176, 2012
*
* and
*
* S. Beyer, M. Chimani: Steiner Tree 1.39-Approximation in Practice.
* MEMICS 2014, LNCS 8934, 60-72, Springer, 2014
*/
template<typename T>
class MinSteinerTreeGoemans139 : public MinSteinerTreeModule<T>
{
private:
class Main;
protected:
int m_restricted;
bool m_use2approx;
bool m_forceAPSP;
bool m_separateCycles;
int m_seed;
public:
MinSteinerTreeGoemans139()
: m_restricted(3)
, m_use2approx(false)
, m_forceAPSP(false)
, m_separateCycles(false)
, m_seed(1337)
{
}
virtual ~MinSteinerTreeGoemans139() { }
/*!
* \brief Sets the maximal number of terminals in a full component
* @param k the maximal number of terminals in a full component
*/
void setMaxComponentSize(int k)
{
m_restricted = k;
}
/*!
* \brief Set seed for the random number generation.
* @param seed The seed
*/
void setSeed(int seed)
{
m_seed = seed;
}
/*!
* \brief Use Takahashi-Matsuyama 2-approximation as upper bounds
* \note not recommended to use in general
* @param use2approx True to apply the bound
*/
void use2Approximation(bool use2approx = true)
{
m_use2approx = use2approx;
}
/*! \brief Force full APSP algorithm even if consecutive SSSP algorithms may work
*
* For the 3-restricted case, it is sufficient to compute an SSSP from every terminal
* instead of doing a full APSP. In case a full APSP is faster, use this method.
* @param force True to force APSP instead of SSSP.
*/
void forceAPSP(bool force = true)
{
m_forceAPSP = force;
}
/*!
* \brief Use stronger LP relaxation (not recommended in general)
* @param separateCycles True to turn the stronger LP relaxation on
*/
void separateCycles(bool separateCycles = true)
{
m_separateCycles = separateCycles;
}
protected:
/*!
* \brief Builds a minimum Steiner tree for a given weighted graph with terminals \see MinSteinerTreeModule::computeSteinerTree
* @param G The weighted input graph
* @param terminals The list of terminal nodes
* @param isTerminal A bool array of terminals
* @param finalSteinerTree The final Steiner tree
* @return The objective value (sum of edge costs) of the final Steiner tree
*/
virtual T computeSteinerTree(
const EdgeWeightedGraph<T> &G,
const List<node> &terminals,
const NodeArray<bool> &isTerminal,
EdgeWeightedGraphCopy<T> *&finalSteinerTree) override;
};
template<typename T>
T MinSteinerTreeGoemans139<T>::computeSteinerTree(const EdgeWeightedGraph<T> &G, const List<node> &terminals, const NodeArray<bool> &isTerminal, EdgeWeightedGraphCopy<T> *&finalSteinerTree)
{
std::minstd_rand rng(m_seed);
List<node> sortedTerminals(terminals);
MinSteinerTreeModule<T>::sortTerminals(sortedTerminals);
Main main(G, sortedTerminals, isTerminal, m_restricted, m_use2approx, m_separateCycles, !m_forceAPSP);
return main.getApproximation(finalSteinerTree, rng, true);
}
//! \brief Class managing LP-based approximation
//! \todo should be refactored, done this way for historical reasons
template<typename T>
class MinSteinerTreeGoemans139<T>::Main
{
const EdgeWeightedGraph<T> &m_G;
const NodeArray<bool> &m_isTerminal;
const List<node> &m_terminals; //!< List of terminals
steiner_tree::FullComponentWithExtraStore<T, double> m_fullCompStore; //!< all enumerated full components, with solution
int m_restricted;
enum class Approx2State {
Off,
On,
JustUseIt,
};
Approx2State m_use2approx;
bool m_ssspDistances;
const double m_eps; //!< epsilon for double operations
EdgeWeightedGraphCopy<T> *m_approx2SteinerTree;
T m_approx2Weight;
//! \name Finding full components
//! @{
//! Computes distance and predecessor matrix
void computeDistanceMatrix(NodeArray<NodeArray<T>>& distance, NodeArray<NodeArray<edge>>& pred);
//! Find full components of size 2
void findFull2Components(const NodeArray<NodeArray<T>>& distance, const NodeArray<NodeArray<edge>>& pred);
//! Find full components of size 3
void findFull3Components(const NodeArray<NodeArray<T>>& distance, const NodeArray<NodeArray<edge>>& pred);
//! Find full components
void findFullComponents();
//! @}
//! \name Preliminaries and preprocessing for the approximation algorithm
//! @{
//! Remove inactive components from m_fullCompStore (since we do not need them any longer)
void removeInactiveComponents()
{
// XXX: is it faster to do this backwards? (less copying)
int k = 0;
while (k < m_fullCompStore.size()) {
if (m_fullCompStore.extra(k) > m_eps) {
++k;
} else {
m_fullCompStore.remove(k);
}
}
}
//! Remove the full components with the given ids
void removeComponents(ArrayBuffer<int> &ids)
{
ids.quicksort();
for (int i = ids.size() - 1; i >= 0; --i) {
m_fullCompStore.remove(ids[i]);
}
}
//! Add a full component to the final solution (by changing nonterminals to terminals)
void addComponent(NodeArray<bool> &isNewTerminal, int id)
{
m_fullCompStore.foreachNode(id, [&](node v) {
isNewTerminal[v] = true;
});
}
//! \brief Preprocess LP solution
//! \pre every terminal is covered with >= 1
void preprocess(NodeArray<bool> &isNewTerminal)
{
Graph H; // a graph where each component is a star
NodeArray<int> id(H); // ids each center of the star to the component id
NodeArray<node> copy(m_G, nullptr); // ids orig in m_G -> copy in H
List<node> centers; // all centers
for (int i = 0; i < m_fullCompStore.size(); ++i) {
const node center = H.newNode();
centers.pushBack(center);
id[center] = i;
for (node vG : m_fullCompStore.terminals(i)) {
node vH = copy[vG];
if (!vH) {
vH = H.newNode();
copy[vG] = vH;
}
H.newEdge(vH, center); // target is always center
}
}
// find components to be inserted into the steinerTree and insert them
ArrayBuffer<int> inactive; // ids of components we insert; we have to remove them from the set of active components afterwards
bool changed;
do {
changed = false;
ListIterator<node> it2;
for (ListIterator<node> it = centers.begin(); it.valid(); it = it2) {
it2 = it.succ();
node c = *it;
int innerNodes = 0; // count inner nodes
for (adjEntry adj : c->adjEntries) {
innerNodes += (adj->twinNode()->degree() != 1);
}
if (innerNodes <= 1) { // this center represents a component to add to steinerTree
// insert component into steinerTree
addComponent(isNewTerminal, id[c]);
// remove center from H (adjacent leaves can remain being isolated nodes)
inactive.push(id[c]);
H.delNode(c);
centers.del(it);
changed = true;
}
}
} while (changed);
removeComponents(inactive);
}
//! @}
public:
//! Initialize all attributes, sort the terminal list
Main(const EdgeWeightedGraph<T> &G, const List<node> &terminals, const NodeArray<bool> &isTerminal,
int restricted, bool use2approx, bool separateCycles, bool useSSSPfor3Restricted, double eps = 1e-8)
: m_G(G)
, m_isTerminal(isTerminal)
, m_terminals(terminals)
, m_fullCompStore(G, m_terminals, isTerminal)
, m_restricted(restricted)
, m_use2approx(use2approx ? Approx2State::On : Approx2State::Off)
, m_ssspDistances(useSSSPfor3Restricted)
, m_eps(eps)
, m_approx2SteinerTree(nullptr)
, m_approx2Weight(0)
{
if (m_use2approx == Approx2State::On) { // add upper bound by 2-approximation
MinSteinerTreeTakahashi<T> mstT;
m_approx2Weight = mstT.call(m_G, m_terminals, m_isTerminal, m_approx2SteinerTree);
}
if (m_restricted > m_terminals.size()) {
m_restricted = m_terminals.size();
}
findFullComponents();
steiner_tree::LPRelaxationSER<T> lp(m_G, m_terminals, m_isTerminal, m_fullCompStore, m_approx2Weight, m_restricted + 1, m_eps);
if (!lp.solve()) {
OGDF_ASSERT(m_use2approx == Approx2State::On);
m_use2approx = Approx2State::JustUseIt;
}
}
~Main()
{
}
//! Obtain an (1.39+epsilon)-approximation based on the LP solution
T getApproximation(EdgeWeightedGraphCopy<T> *&finalSteinerTree, const std::minstd_rand &rng, const bool doPreprocessing = true);
};
template<typename T>
void MinSteinerTreeGoemans139<T>::Main::findFull2Components(const NodeArray<NodeArray<T>>& distance, const NodeArray<NodeArray<edge>>& pred)
{
steiner_tree::Full2ComponentGenerator<T> fcg;
fcg.call(m_G, m_terminals, distance, pred,
[&](node s, node t, T cost) {
EdgeWeightedGraphCopy<T> minComp;
minComp.createEmpty(m_G);
minComp.newEdge(minComp.newNode(s), minComp.newNode(t), distance[s][t]);
m_fullCompStore.insert(minComp);
});
}
template<typename T>
void MinSteinerTreeGoemans139<T>::Main::findFull3Components(const NodeArray<NodeArray<T>>& distance, const NodeArray<NodeArray<edge>>& pred)
{
steiner_tree::Full3ComponentGeneratorVoronoi<T> fcg;
fcg.call(m_G, m_terminals, m_isTerminal, distance, pred,
[&](node t0, node t1, node t2, node minCenter, T minCost) {
// create a full 3-component
EdgeWeightedGraphCopy<T> minComp;
minComp.createEmpty(m_G);
node minCenterC = minComp.newNode(minCenter);
minComp.newEdge(minComp.newNode(t0), minCenterC, distance[t0][minCenter]);
minComp.newEdge(minComp.newNode(t1), minCenterC, distance[t1][minCenter]);
minComp.newEdge(minComp.newNode(t2), minCenterC, distance[t2][minCenter]);
m_fullCompStore.insert(minComp);
});
}
template<typename T>
void MinSteinerTreeGoemans139<T>::Main::computeDistanceMatrix(NodeArray<NodeArray<T>>& distance, NodeArray<NodeArray<edge>>& pred)
{
if (m_ssspDistances
&& m_restricted <= 3) {
// for 2- and 3-restricted computations, it is ok to use SSSP from all terminals
#ifndef OGDF_MINSTEINERTREEGOEMANS139_DETOUR
MinSteinerTreeModule<T>::allTerminalShortestPathsStrict
#else
MinSteinerTreeModule<T>::allTerminalShortestPathsDetour
#endif
(m_G, m_terminals, m_isTerminal, distance, pred);
} else {
m_ssspDistances = false;
#ifndef OGDF_MINSTEINERTREEGOEMANS139_DETOUR
MinSteinerTreeModule<T>::allPairShortestPathsStrict
#else
MinSteinerTreeModule<T>::allPairShortestPathsDetour
#endif
(m_G, m_isTerminal, distance, pred);
}
}
template<typename T>
void MinSteinerTreeGoemans139<T>::Main::findFullComponents()
{
NodeArray<NodeArray<T>> distance;
NodeArray<NodeArray<edge>> pred;
computeDistanceMatrix(distance, pred);
if (m_restricted >= 4) { // use Dreyfus-Wagner based full component generation
SubsetEnumerator<node> terminalSubset(m_terminals);
steiner_tree::FullComponentGeneratorDreyfusWagner<T> fcg(m_G, m_terminals, distance);
fcg.call(m_restricted);
for (terminalSubset.begin(2, m_restricted); terminalSubset.valid(); terminalSubset.next()) {
EdgeWeightedGraphCopy<T> component;
List<node> terminals;
terminalSubset.list(terminals);
fcg.getSteinerTreeFor(terminals, component);
if (steiner_tree::FullComponentGeneratorDreyfusWagner<T>::isValidComponent(component, pred, m_isTerminal)) {
m_fullCompStore.insert(component);
}
}
} else {
findFull2Components(distance, pred);
if (m_restricted == 3) {
findFull3Components(distance, pred);
}
}
}
template<typename T>
T
MinSteinerTreeGoemans139<T>::Main::getApproximation(EdgeWeightedGraphCopy<T> *&finalSteinerTree, const std::minstd_rand &rng, const bool doPreprocessing)
{
if (m_use2approx == Approx2State::JustUseIt) {
// no remaining components
finalSteinerTree = m_approx2SteinerTree;
return m_approx2Weight;
}
removeInactiveComponents();
NodeArray<bool> isNewTerminal(m_G, false);
for (node v : m_terminals) {
isNewTerminal[v] = true;
}
if (doPreprocessing) {
preprocess(isNewTerminal);
}
if (!m_fullCompStore.isEmpty()) {
steiner_tree::goemans::Approximation<T> approx(m_G, m_terminals, m_isTerminal, m_fullCompStore, rng, m_eps);
approx.solve(isNewTerminal);
}
T cost = steiner_tree::obtainFinalSteinerTree(m_G, isNewTerminal, m_isTerminal, finalSteinerTree);
if (m_use2approx != Approx2State::Off) {
if (m_approx2Weight < cost) {
delete finalSteinerTree;
finalSteinerTree = m_approx2SteinerTree;
cost = m_approx2Weight;
} else {
delete m_approx2SteinerTree;
}
}
return cost;
}
}
| 30.650442 | 189 | 0.729537 |
cda6937ec0ecdeca86f407b91af0ddb98b6a4ff0 | 1,685 | cs | C# | src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/Server/SmiLink.cs | Xtrimmer/SqlClient | 9e145376933cb8da05eea4949dac783382aec5db | [
"MIT"
] | 590 | 2019-05-06T16:30:57.000Z | 2022-03-30T06:43:00.000Z | src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/Server/SmiLink.cs | Xtrimmer/SqlClient | 9e145376933cb8da05eea4949dac783382aec5db | [
"MIT"
] | 1,060 | 2019-05-06T16:39:40.000Z | 2022-03-31T23:19:48.000Z | src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/Server/SmiLink.cs | Xtrimmer/SqlClient | 9e145376933cb8da05eea4949dac783382aec5db | [
"MIT"
] | 189 | 2019-05-06T15:56:34.000Z | 2022-03-28T14:20:59.000Z | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
[assembly: System.Runtime.CompilerServices.InternalsVisibleTo("SqlAccess, PublicKey=0024000004800000940000000602000000240000525341310004000001000100272736ad6e5f9586bac2d531eabc3acc666c2f8ec879fa94f8f7b0327d2ff2ed523448f83c3d5c5dd2dfc7bc99c5286b2c125117bf5cbe242b9d41750732b2bdffe649c6efb8e5526d526fdd130095ecdb7bf210809c6cdad8824faa9ac0310ac3cba2aa0523567b2dfa7fe250b30facbd62d4ec99b94ac47c7d3b28f1f6e4c8")] // SQLBU 437687
namespace Microsoft.Data.SqlClient.Server
{
internal abstract class SmiLink
{
// NOTE: Except for changing the constant value below, adding new members
// to this class may create versioning issues. We would prefer not
// to add additional items to this if possible.
internal const ulong InterfaceVersion = 210;
// Version negotiation (appdomain-wide negotiation)
// This needs to be the first method called when negotiating with a
// driver back end. Once called, the rest of the back end interface
// needs to conform to the returned version number's interface.
internal abstract ulong NegotiateVersion(ulong requestedVersion);
// Get utility class valid in current thread execution environment
// This returns an object, to allow us to version the context without
// having to version this class. (eg. SmiContext1 vs SmiContext2)
internal abstract object GetCurrentContext(SmiEventSink eventSink);
}
}
| 56.166667 | 423 | 0.760237 |
f47dc31d8521359019803fbd2178add357e5a6e9 | 168 | ts | TypeScript | src/app/components/contact/contact.ts | hanmarkslag/angular2-component-router | c71b698e08edb1e1f70045ea56f00c87af875f9c | [
"MIT"
] | null | null | null | src/app/components/contact/contact.ts | hanmarkslag/angular2-component-router | c71b698e08edb1e1f70045ea56f00c87af875f9c | [
"MIT"
] | null | null | null | src/app/components/contact/contact.ts | hanmarkslag/angular2-component-router | c71b698e08edb1e1f70045ea56f00c87af875f9c | [
"MIT"
] | null | null | null | import {Component} from 'angular2/angular2';
@Component({
selector: 'contact',
templateUrl: './app/components/contact/contact.html'
})
export class Contact {
} | 21 | 56 | 0.708333 |
2d76cdcec6aeacae304787c29ba81670de517460 | 409 | css | CSS | build/css/style-b9be79d798.css | pushpan999/webflow | 242fad190f4e6086c20bfd682ab5d656d551cc4c | [
"MIT"
] | null | null | null | build/css/style-b9be79d798.css | pushpan999/webflow | 242fad190f4e6086c20bfd682ab5d656d551cc4c | [
"MIT"
] | null | null | null | build/css/style-b9be79d798.css | pushpan999/webflow | 242fad190f4e6086c20bfd682ab5d656d551cc4c | [
"MIT"
] | null | null | null | body
{
color: #fff;
background: #000;
}
/*# sourceMappingURL=data:application/json;charset=utf8;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoic3R5bGUuY3NzIiwic291cmNlcyI6WyJzdHlsZS5zY3NzIl0sInNvdXJjZXNDb250ZW50IjpbImJvZHkge1xuICAgIGJhY2tncm91bmQ6ICMwMDA7XG4gICAgY29sb3I6ICNmZmY7XG59Il0sIm1hcHBpbmdzIjoiQUFBQSxBQUFBLElBQUksQ0FBQztFQUNELFVBQVUsRUFBRSxJQUFLO0VBQ2pCLEtBQUssRUFBRSxJQUFLLEdBQ2YiLCJuYW1lcyI6W119 */
| 51.125 | 358 | 0.9022 |
20d9e83355715395d11edcac8cb76a015536c1ce | 328 | cs | C# | src/ScenarioEdit/Entities/TexTargetName.cs | CptCipher/MLTDTools | d91ca92b901fd64816278c6c6afeeb92967126da | [
"BSD-3-Clause-Clear"
] | null | null | null | src/ScenarioEdit/Entities/TexTargetName.cs | CptCipher/MLTDTools | d91ca92b901fd64816278c6c6afeeb92967126da | [
"BSD-3-Clause-Clear"
] | null | null | null | src/ScenarioEdit/Entities/TexTargetName.cs | CptCipher/MLTDTools | d91ca92b901fd64816278c6c6afeeb92967126da | [
"BSD-3-Clause-Clear"
] | null | null | null | using UnityStudio.Serialization;
using UnityStudio.Serialization.Naming;
namespace OpenMLTD.ScenarioEdit.Entities {
[MonoBehaviour(NamingConventionType = typeof(CamelCaseNamingConvention))]
public sealed class TexTargetName {
public int Target { get; set; }
public string Name { get; set; }
}
}
| 23.428571 | 77 | 0.72561 |
29846bd3f440b27e30e883f2c1e1fd266d179028 | 3,083 | kt | Kotlin | reposilite-backend/src/main/kotlin/com/reposilite/shared/extensions/PicocliExtensions.kt | asad-awadia/reposilite | cceff854ded99cc3164551fb373db55af7e759a1 | [
"Apache-2.0"
] | 20 | 2019-06-27T05:20:19.000Z | 2020-05-17T21:51:03.000Z | reposilite-backend/src/main/kotlin/com/reposilite/shared/extensions/PicocliExtensions.kt | asad-awadia/reposilite | cceff854ded99cc3164551fb373db55af7e759a1 | [
"Apache-2.0"
] | 44 | 2019-08-10T19:30:57.000Z | 2020-05-17T23:31:24.000Z | reposilite-backend/src/main/kotlin/com/reposilite/shared/extensions/PicocliExtensions.kt | asad-awadia/reposilite | cceff854ded99cc3164551fb373db55af7e759a1 | [
"Apache-2.0"
] | 6 | 2017-07-12T11:37:23.000Z | 2018-11-14T13:03:24.000Z | /*
* Copyright (c) 2022 dzikoysk
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.reposilite.shared.extensions
import com.reposilite.VERSION
import panda.std.Result
import panda.std.asSuccess
import picocli.CommandLine
import java.util.TreeSet
abstract class Validator : Runnable {
override fun run() { }
}
internal data class CommandConfiguration<VALUE>(
val name: String,
val configuration: VALUE
)
internal fun <CONFIGURATION : Runnable> loadCommandBasedConfiguration(configuration: CONFIGURATION, description: String): CommandConfiguration<CONFIGURATION> =
description.split(" ", limit = 2)
.let { CommandConfiguration(it[0], it.getOrElse(1) { "" }) }
.also { CommandLine(configuration).execute(*splitArguments(it.configuration)) }
.let { CommandConfiguration(it.name, configuration) }
.also { it.configuration.run() }
private fun splitArguments(args: String): Array<String> =
if (args.isEmpty()) arrayOf() else args.split(" ").toTypedArray()
internal fun createCommandHelp(commands: Map<String, CommandLine>, requestedCommand: String): Result<List<String>, String> {
if (requestedCommand.isNotEmpty()) {
return commands[requestedCommand]
?.let { listOf(it.usageMessage).asSuccess() }
?: error("Unknown command '$requestedCommand'")
}
val uniqueCommands: MutableSet<CommandLine> = TreeSet(Comparator.comparing { it.commandName })
uniqueCommands.addAll(commands.values)
val response = mutableListOf("Reposilite $VERSION Commands:")
uniqueCommands
.forEach { command ->
val specification = command.commandSpec
response.add(" " + command.commandName +
(if (specification.args().isEmpty()) "" else " ") +
specification.args().joinToString(separator = " ", transform = {
if (it.isOption) {
var option = ""
if (!it.required()) option += "["
option += "--"
option += if (it.paramLabel().startsWith("<")) it.paramLabel().substring(1).dropLast(1) else it.paramLabel()
if (it.type() != Boolean::class.javaPrimitiveType) option += "=<value>"
if (!it.required()) option += "]"
option
} else it.paramLabel()
}) +
" - ${specification.usageMessage().description().joinToString(". ")}"
)
}
return response.asSuccess()
}
| 39.025316 | 159 | 0.634771 |
21cf7df88eae709ea91512f34b007d01819ff9a7 | 1,597 | js | JavaScript | controller/EventCard.js | huangdgm/bot-framework-service | d7fd8705d9ed3d0bf36bbc78afd31dfd72ef681b | [
"Apache-2.0"
] | null | null | null | controller/EventCard.js | huangdgm/bot-framework-service | d7fd8705d9ed3d0bf36bbc78afd31dfd72ef681b | [
"Apache-2.0"
] | null | null | null | controller/EventCard.js | huangdgm/bot-framework-service | d7fd8705d9ed3d0bf36bbc78afd31dfd72ef681b | [
"Apache-2.0"
] | null | null | null | var rest = require('../API/Restclient');
var builder = require('botbuilder');
//Calls 'getYelpEventData' in RestClient.js with 'displayEventCards' as callback to get list of events information
exports.displayEventCards = function getEventData(location, session){
var url ='https://api.yelp.com/v3/events?location='+location+'&limit=5';
var auth ='BRIcgJBZ7_gG4csSu9e3Yfdyto_2L0xiRL1sG4m6BMTv5QFLX7nNZuVCLSsoWJZ6rRoex4MUrbygnhYh1F_RKTHvbWHYr3OpPflVnK4RDr4hMNLXnvI1pgJNegUeWnYx';
rest.getYelpEventData(url,auth,session,displayEventCards);
}
function displayEventCards(message, session) {
var attachment = [];
var eventsFound = JSON.parse(message);
//For each event, add herocard with name, address, image and url in attachment
for (var index in eventsFound.events) {
var event = eventsFound.events[index];
var name = event.name;
var imageURL = event.image_url;
var url = event.event_site_url;
var address = event.location.address1 + ", " + event.location.city;
var card = new builder.HeroCard(session)
.title(name)
.text(address)
.images([
builder.CardImage.create(session, imageURL)])
.buttons([
builder.CardAction.openUrl(session, url, 'More Information')
]);
attachment.push(card);
}
//Displays event hero card carousel in chat box
var message = new builder.Message(session)
.attachmentLayout(builder.AttachmentLayout.carousel)
.attachments(attachment);
session.send(message);
} | 40.948718 | 145 | 0.681277 |
05990a94ee99e2632bfdfebcdbf5a0acd9ac2fee | 554 | dart | Dart | tests/language/operator/operator6_test.dart | omerlevran46/sdk | b1955d63ad678b651b09db3dd286136c4463f36b | [
"BSD-3-Clause"
] | 8,969 | 2015-05-16T16:49:24.000Z | 2022-03-31T19:54:40.000Z | tests/language/operator/operator6_test.dart | omerlevran46/sdk | b1955d63ad678b651b09db3dd286136c4463f36b | [
"BSD-3-Clause"
] | 30,202 | 2015-05-17T02:27:45.000Z | 2022-03-31T22:54:46.000Z | tests/language/operator/operator6_test.dart | omerlevran46/sdk | b1955d63ad678b651b09db3dd286136c4463f36b | [
"BSD-3-Clause"
] | 1,619 | 2015-05-16T21:36:42.000Z | 2022-03-29T20:36:59.000Z | // Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
import "package:expect/expect.dart";
class OperatorTest {
OperatorTest() {}
static testMain() {
var op1 = new Operator(1);
var op2 = new Operator(2);
Expect.equals(~1, ~op1);
}
}
class Operator {
int value;
Operator(this.value);
operator ~() {
return ~value;
}
}
main() {
OperatorTest.testMain();
}
| 18.466667 | 77 | 0.662455 |
eb21eaae47bd49900e4975d417e81a1cc8f3fe24 | 18,871 | css | CSS | wp-content/uploads/md_cache/68720e.css | abdouabdel/projetAH | 04bca6e264fe3719f6b65bd086dbf35046a9982d | [
"MIT"
] | null | null | null | wp-content/uploads/md_cache/68720e.css | abdouabdel/projetAH | 04bca6e264fe3719f6b65bd086dbf35046a9982d | [
"MIT"
] | null | null | null | wp-content/uploads/md_cache/68720e.css | abdouabdel/projetAH | 04bca6e264fe3719f6b65bd086dbf35046a9982d | [
"MIT"
] | null | null | null | .vc_row.hide-overflow:not(.vc_inner){overflow:hidden}.row-equal-column-height .wrap,.row-equal-column-height .wpb_column,.row-equal-column-height .mBuilder-element.mBuilder-vc_column{display:flex}.row-content-top:not(.row-equal-column-height) .wrap{display:flex;align-items:flex-start}.row-content-middle:not(.row-equal-column-height) .wrap{display:flex;align-items:center}.row-content-bottom:not(.row-equal-column-height) .wrap{display:flex;align-items:flex-end}.row-equal-column-height.row-content-top .wrap .vc_column-inner{display:flex;align-items:flex-start}.row-equal-column-height.row-content-middle .wrap .vc_column-inner{display:flex;align-items:center}.row-equal-column-height.row-content-bottom .wrap .vc_column-inner{display:flex;align-items:flex-end}.row-equal-column-height>.wrap>.vc_column_container>.vc_column-inner>.wpb_wrapper,.row-equal-column-height>.wrap>.mBuilder-element>.vc_column_container>.vc_column-inner>.wpb_wrapper{width:100%}.vc_row.vc_parallax{position:relative;overflow:visible}.vc_parallax>*{position:relative;z-index:1}.vc_row{position:relative;backface-visibility:hidden}.vc_row:not(.vertical-aligned){display:flex;width:100%}.vc_row>.wrap:not(.box_size_container){width:100%}.vc_row.row_video,.vc_row.sloped_row{overflow:hidden}.row-image{background-position:center;background-repeat:no-repeat}.row-image-normal.isParallax{background-attachment:fixed;background-position:center;background-repeat:no-repeat}.row-image-fixed.isParallax:after{content:"";display:block;background-attachment:fixed;width:100%;background-position:center;background-repeat:no-repeat;height:100%;position:absolute;top:0;left:0;background-size:cover}body.one_page_scroll .row-image-fixed.isParallax:after{background-attachment:local}.row-image.repeat{background-repeat:repeat;background-size:inherit!important}.row-image.repeat:after{background-repeat:repeat;background-size:inherit!important}.sectionOverlay:after{width:100%;height:100%;position:absolute;left:0;top:0;display:block!important}.sectionOverlay .row-image,.sectionOverlay .row-image-inner-row{width:100%;position:absolute!important;height:100%;left:0;z-index:0!important;top:0;margin:auto;background-size:cover;overflow:hidden}.sectionOverlay.box_size{margin-left:auto!important;margin-right:auto!important}.sectionOverlay .box_size_container{float:none;margin:0 auto}.sloped-edge{height:105px;position:absolute!important;left:-10%;right:-10%}.sloped-edge.top-edge{top:-55px}.sloped-edge.bottom-edge{bottom:-55px}.vc_row.full_size{margin:0}video.row-videobg{position:absolute;top:50%;left:50%;min-width:100%;min-height:100%;width:auto;height:auto;z-index:-1;-webkit-transform:translateX(-50%) translateY(-50%);transform:translateX(-50%) translateY(-50%);background-repeat:no-repeat;background-size:cover}.vc_column-inner>.wpb_wrapper{position:relative;z-index:1}.shortcode-btn .button-icon{vertical-align:middle;text-align:center}.shortcode-btn{display:inline-block;backface-visibility:hidden;padding:1px;white-space:nowrap}.shortcode-btn .button{display:inline-table}.shortcode-btn .button.fill-oval span,.shortcode-btn .button.fade-oval span{vertical-align:middle;position:relative;top:-1px}.shortcode-btn .button.button-small.slide span{position:relative;top:-2px}.shortcode-btn .animation{overflow:hidden}.shortcode-btn .button-small{font-size:12px;line-height:13px}.shortcode-btn .button-standard .button-icon{font-size:15px;width:15px;height:15px;line-height:15px}.shortcode-btn .button-standard .button-icon{font-size:14px;width:22px;height:22px;line-height:22px}.shortcode-btn .button-standard{font-size:13px;line-height:13px}.shortcode-btn .button.fade-square.button-small .button-icon{font-size:14px}.shortcode-btn .button.fade-oval.button-standard .button-icon,.shortcode-btn .button.fill-oval.button-standard .button-icon{font-size:18px}.shortcode-btn .button.fade-oval.button-small .button-icon,.shortcode-btn .button.fill-oval.button-small .button-icon{font-size:14px}.shortcode-btn .animation span{display:inline-block}.shortcode-btn .button-standard.animation{letter-spacing:6px}body:not(.compose-mode) .shortcode-btn .button-standard.animation{overflow:hidden}.shortcode-btn .button-small.animation{letter-spacing:4px}.shortcode-btn .button-small.animation span,.shortcode-btn .button-standard.animation span{margin-right:9px}.shortcode-btn .button-small.animation .button-icon{font-size:15px}.shortcode-btn .button-standard.slide,.shortcode-btn .button-small.slide{text-align:left}.shortcode-btn .slide.slide-transition{transition:width .4s,background .4s}.shortcode-btn .button-standard.slide{height:52px;width:52px}.shortcode-btn .button-small.slide{height:40px;width:40px}.shortcode-btn .button-standard.slide span{left:25px;opacity:0;padding-right:24px;top:50%;transform:translateY(-50%);bottom:0;font-size:14px}.shortcode-btn .button-small.slide span{opacity:0;left:17px;padding-right:15px;top:0;bottom:0;margin:13px 0}.shortcode-btn .button-standard.slide .button-icon{width:47px;display:table;height:52px;line-height:54px}.shortcode-btn .button-small.slide .button-icon{width:38px;display:inline-block;height:40px;line-height:38px}.shortcode-btn .button-standard.come-in{border:3px solid}.shortcode-btn .button-small.come-in{border:2px solid}.shortcode-btn .button-standard.flash-animate:hover .button-icon{left:5px}.shortcode-btn .button-small.flash-animate:hover .button-icon{left:4px}.shortcode-btn .button-standard.flash-animate:hover{letter-spacing:0}.shortcode-btn .fade-square,.shortcode-btn .fade-oval,.shortcode-btn .fill-oval,.shortcode-btn .slide,.shortcode-btn .come-in,.shortcode-btn .fill-rectangle,.shortcode-btn .animation,.shortcode-btn .flash-animate{opacity:1;border:1px solid;font-weight:400}.shortcode-btn .fade-oval,.shortcode-btn .flash-animate,.shortcode-btn .slide{border:2px solid}.shortcode-btn .fade-square,.shortcode-btn .fade-oval,.shortcode-btn .come-in,.shortcode-btn .animation,.shortcode-btn .flash-animate{-webkit-transition:background-color .3s;-moz-transition:background-color .3s;-ms-transition:background-color .3s;-o-transition:background-color .3s;transition:background-color .3s}.shortcode-btn .fade-square,.shortcode-btn .flash-animate{border-radius:3px}.shortcode-btn .fade-square .button-icon,.shortcode-btn .fade-oval .button-icon,.shortcode-btn .fill-oval .button-icon{padding-right:10px}.shortcode-btn .fade-square .button-icon,.shortcode-btn .fade-square span,.shortcode-btn .fade-oval .button-icon,.shortcode-btn .fade-oval span{-webkit-transition:all 100ms;-moz-transition:all 100ms;-ms-transition:all 100ms;white-space:nowrap;-o-transition:all 100ms;transition:all 100ms}.shortcode-btn .fill-oval{-webkit-transition:all .4s;-moz-transition:all .4s;-ms-transition:all .4s;-o-transition:all .4s;transition:all .4s}.shortcode-btn .fade-oval,.shortcode-btn .fill-oval{border-radius:50px;font-size:14px}.shortcode-btn .fill-oval span{line-height:13px}.shortcode-btn .slide .button-icon{transition:all .8s}.shortcode-btn .slide{border-radius:50px;display:flex;align-items:center;text-align:center;position:relative;overflow:hidden}.shortcode-btn .slide span{white-space:nowrap;-webkit-transition:left .4s,opacity .4s;-moz-transition:left .4s,opacity .4s;-ms-transition:left .4s,opacity .4s;-o-transition:left .4s,opacity .4s;transition:left .4s,opacity .4s}.shortcode-btn .slide:hover{border-radius:50px;background-color:#2d2d2d;width:124px}.shortcode-btn .slide:hover .button-icon{transform:rotate(360deg)}.shortcode-btn .slide .button-icon{font-size:18px}.shortcode-btn .come-in,.shortcode-btn .fill-rectangle{position:relative;overflow:hidden;z-index:9;transition:all .4s}.shortcode-btn .come-in:hover:after{width:100%}.shortcode-btn .come-in:after{content:'';position:absolute;z-index:-1;width:0;height:100%;top:0;right:0;-webkit-transition:all .3s;-moz-transition:all .3s;-ms-transition:all .3s;-o-transition:all .3s;transition:all .3s}.shortcode-btn .come-in .button-icon,.shortcode-btn .come-in span{-webkit-transition:all .3s;-moz-transition:all .3s;-ms-transition:all .3s;-o-transition:all .3s;transition:all .3s}.shortcode-btn .come-in .button-icon,.shortcode-btn .fill-rectangle .button-icon{margin-right:10px}.shortcode-btn .button-standard.come-in span,.shortcode-btn .button-standard.fill-rectangle span{font-size:14px;line-height:1.2em}.shortcode-btn .button-standard.come-in .button-icon,.shortcode-btn .button-standard.fill-rectangle .button-icon{font-size:15px}.shortcode-btn .animation{font-size:13px;line-height:13px;position:relative;border:1px solid;-webkit-transition:opacity .4s,color .4s;-moz-transition:opacity .4s,color .4s;-ms-transition:opacity .4s,color .4s;-o-transition:opacity .4s,color .4s;transition:opacity .4s,color .4s}.shortcode-btn .animation:after{content:"";position:absolute;left:-125px;width:80px;height:100px;top:-25px;-webkit-transition:left .4s,opacity .4s,color .4s,transform .4s;-moz-transition:left .4s,opacity .4s,color .4s,transform .4s;-ms-transition:left .4s,opacity .4s,color .4s,transform .4s;-o-transition:left .4s,opacity .4s,color .4s,transform .4s;transition:left .4s,opacity .4s,color .4s,transform .4s;-webkit-transform:skew(40deg);-moz-transform:skew(40deg);-ms-transform:skew(40deg);-o-transform:skew(40deg);transform:skew(40deg)}.shortcode-btn .animation:hover:after{-webkit-transform:skew(0);-moz-transform:skew(0);-ms-transform:skew(0);-o-transform:skew(0);transform:skew(0);left:101%}.shortcode-btn .animation:hover{opacity:1}.shortcode-btn .animation .button-icon{font-size:15px}.shortcode-btn .flash-animate{-webkit-transition:all .3s;-moz-transition:all .3s;-ms-transition:all .3s;-o-transition:all .3s;transition:all .3s}.shortcode-btn .flash-animate:hover .button-icon{opacity:1;left:5px}.shortcode-btn .flash-animate .button-icon{opacity:0;left:-3px;position:relative;-webkit-transition:all .3s;-moz-transition:all .3s;-ms-transition:all .3s;-o-transition:all .3s;transition:all .3s}.md-text-container{display:flex}.md-text-container.md-align-left{justify-content:flex-start}.md-text-container.md-align-center{justify-content:center}.md-text-container.md-align-right{justify-content:flex-end}.md-text .md-text-title-separator{max-width:96%}.md-text-button .shortcode-btn{float:none!important}.md-text .without-title,.md-text .without-content{display:none}.disable-edit-title,.disable-edit{display:none}@font-face{font-family:'flexslider-icon';src:url(fonts/flexslider-icon.html);src:url(fonts/flexslider-icond41d.html?#iefix) format("embedded-opentype"),url(fonts/flexslider-icon-2.html) format("woff"),url(fonts/flexslider-icon-3.html) format("truetype"),url(fonts/flexslider-icon-4.html#flexslider-icon) format("svg");font-weight:400;font-style:normal}.flex-container a:hover,.flex-slider a:hover,.flex-container a:focus,.flex-slider a:focus{outline:0}.slides,.slides>li,.flex-control-nav,.flex-direction-nav{margin:0;padding:0;list-style:none}.flex-pauseplay span{text-transform:capitalize}.flexslider{margin:0;padding:0}.flexslider .slides>li{display:none;-webkit-backface-visibility:hidden}.flexslider .slides img{width:100%;display:block}.flexslider .slides:after{content:"\0020";display:block;clear:both;visibility:hidden;line-height:0;height:0}html[xmlns] .flexslider .slides{display:block}* html .flexslider .slides{height:1%}.no-js .flexslider .slides>li:first-child{display:block}.flexslider{margin:0 0 60px;background:#fff;border:4px solid #fff;position:relative;zoom:1;-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px;-webkit-box-shadow:0 1px 4px rgba(0,0,0,0.2);-moz-box-shadow:0 1px 4px rgba(0,0,0,0.2);-o-box-shadow:0 1px 4px rgba(0,0,0,0.2);box-shadow:0 1px 4px rgba(0,0,0,0.2)}.flexslider .slides{zoom:1}.flexslider .slides img{height:auto}.flex-viewport{max-height:2000px;-webkit-transition:all 1s ease;-moz-transition:all 1s ease;-ms-transition:all 1s ease;-o-transition:all 1s ease;transition:all 1s ease}.loading .flex-viewport{max-height:300px}.carousel li{margin-right:5px}.flex-direction-nav{*height:0}.flex-direction-nav a{text-decoration:none;display:block;width:40px;height:40px;margin:-20px 0 0;position:absolute;top:50%;z-index:10;overflow:hidden;opacity:0;cursor:pointer;color:rgba(0,0,0,0.8);text-shadow:1px 1px 0 rgba(255,255,255,0.3);-webkit-transition:all .3s ease-in-out;-moz-transition:all .3s ease-in-out;-ms-transition:all .3s ease-in-out;-o-transition:all .3s ease-in-out;transition:all .3s ease-in-out}.flex-direction-nav a:before{font-family:"flexslider-icon";font-size:40px;display:inline-block;content:'\f001';color:rgba(0,0,0,0.8);text-shadow:1px 1px 0 rgba(255,255,255,0.3)}.flex-direction-nav a.flex-next:before{content:'\f002'}.flex-direction-nav .flex-prev{left:-50px}.flex-direction-nav .flex-next{right:-50px;text-align:right}.flexslider:hover .flex-direction-nav .flex-prev{opacity:.7;left:10px}.flexslider:hover .flex-direction-nav .flex-prev:hover{opacity:1}.flexslider:hover .flex-direction-nav .flex-next{opacity:.7;right:10px}.flexslider:hover .flex-direction-nav .flex-next:hover{opacity:1}.flex-direction-nav .flex-disabled{opacity:0!important;filter:alpha(opacity=0);cursor:default}.flex-pauseplay a{display:block;width:20px;height:20px;position:absolute;bottom:5px;left:10px;opacity:.8;z-index:10;overflow:hidden;cursor:pointer;color:#000}.flex-pauseplay a:before{font-family:"flexslider-icon";font-size:20px;display:inline-block;content:'\f004'}.flex-pauseplay a:hover{opacity:1}.flex-pauseplay a .flex-play:before{content:'\f003'}.flex-control-nav{width:100%;position:absolute;bottom:-40px;text-align:center}.flex-control-nav li{margin:0 6px;display:inline-block;zoom:1;*display:inline}.flex-control-paging li a{width:11px;height:11px;display:block;background:#666;background:rgba(0,0,0,0.5);cursor:pointer;text-indent:-9999px;-webkit-box-shadow:inset 0 0 3px rgba(0,0,0,0.3);-moz-box-shadow:inset 0 0 3px rgba(0,0,0,0.3);-o-box-shadow:inset 0 0 3px rgba(0,0,0,0.3);box-shadow:inset 0 0 3px rgba(0,0,0,0.3);-webkit-border-radius:20px;-moz-border-radius:20px;border-radius:20px}.flex-control-paging li a:hover{background:#333;background:rgba(0,0,0,0.7)}.flex-control-paging li a.flex-active{background:#000;background:rgba(0,0,0,0.9);cursor:default}.flex-control-thumbs{margin:5px 0 0;position:static;overflow:hidden}.flex-control-thumbs li{width:25%;float:left;margin:0}.flex-control-thumbs img{width:100%;height:auto;display:block;opacity:.7;cursor:pointer;-webkit-transition:all 1s ease;-moz-transition:all 1s ease;-ms-transition:all 1s ease;-o-transition:all 1s ease;transition:all 1s ease}.flex-control-thumbs img:hover{opacity:1}.flex-control-thumbs .flex-active{opacity:1;cursor:default}@media screen and (max-width:860px){.flex-direction-nav .flex-prev{opacity:1;left:10px}.flex-direction-nav .flex-next{opacity:1;right:10px}}.img-box-slider{overflow:hidden;position:relative}.img-box-slider .imgBox-image{width:100%;height:100%;margin:auto;background-repeat:no-repeat;background-size:auto;display:block}.img-box-slider.md-align-right .imgBox-image{background-position:right}.img-box-slider.md-align-left .imgBox-image{background-position:left}.img-box-slider.md-align-center .imgBox-image{background-position:center}.img-box-slider .image-box-slider-hover{width:100%;height:100%;position:absolute;top:0;z-index:9}.image-box-slider-hover .bg-animate,.image-box-slider-hover .title,.image-box-slider-hover .description{position:relative;left:-100%}.image-box-slider-hover .title,.image-box-slider-hover .description{background-color:transparent!important}.img-box-slider .bg-animate{width:100%;height:100%;position:absolute;top:0;background-color:rgba(0,0,0,0)}.img-box-slider .image-box-slider-hover .title{font-size:20px;font-weight:bold;color:#fff;margin-bottom:30px;padding:56px 56px 0 34px}.img-box-slider .image-box-slider-hover .description{font-size:14px;font-weight:400;color:#fff;padding:0 56px 0 34px}.img-box-slider .image-box-slider-btn{background-color:rgba(15,15,15,0.4);width:35px;height:35px;position:absolute;bottom:0;right:0;color:#fff;backface-visibility:hidden;margin:0 26px 21px 0;border-radius:50px;background-position:center;cursor:pointer;z-index:10;transition:transform .3s,background-color .3s,opacity .2s}@-moz-document url-prefix(){.img-box-slider .image-box-slider-btn{height:37px}}.img-box-slider .image-box-slider-btn:before{display:table-cell;text-align:center;vertical-align:middle;width:35px;height:35px}.img-box-slider .image-box-slider-btn:hover{opacity:.7}.img-box-slider ul,.img-box-slider ul>li{height:100%;position:relative}.img-box-slider .image-box-slider-hover-text{position:absolute;top:50%;padding:0 50px 0 50px;text-align:center;opacity:0;font-size:18px;display:inline-block;width:100%;line-height:25px;left:0;transform:translateY(-50%)}.img-box-slider .imgBox-image-hover{position:absolute;top:0;left:0;transition:opacity .3s}.tablet-slider{min-height:330px}.tablet-slider .flex-control-nav{position:relative;bottom:0;margin-bottom:40px;list-style-type:none;text-align:center}.tablet-slider .flex-control-nav li{display:inline-block;font-size:14px;cursor:pointer;padding-left:17px;opacity:.5}.tablet-slider .flex-control-nav li:last-child:after{content:''}.tablet-slider .flex-control-nav li.flex-active{opacity:1}.tablet-slider .flexslider{max-width:745px;margin:0 auto;position:relative;background:0;border:0;width:90%;height:90%}.tablet-slider .flexslider .slides{list-style-type:none}.tablet-slider .flexslider .tablet-frame{position:absolute;left:0;max-width:100%;background-color:transparent;background-position:left top;background-repeat:no-repeat;background-size:contain;height:593px;right:0;margin:auto;transform:scale(1.009)}.tablet-slider .flexslider .slide-description{margin-bottom:67px;color:#000;text-align:center;font-size:14px;line-height:22px;height:64px;overflow:hidden;padding:0 7%}.tablet-slider .flexslider .slide-image{background-size:cover;background-position:center;border-radius:20px;margin:auto}.tablet-slider .flexslider .flex-direction-nav a{width:13%;height:13%;top:50%;opacity:1}.tablet-slider .flexslider .flex-direction-nav .flex-prev{left:-9%!important}.tablet-slider .flexslider .flex-direction-nav .flex-prev:before{content:"";max-width:100%;background-size:contain;background-color:transparent;background-position:left center;background-repeat:no-repeat;width:100%;height:100%}.tablet-slider .flexslider .flex-direction-nav .flex-next{right:-16%!important}.tablet-slider .flexslider .flex-direction-nav .flex-next:before{content:"";max-width:100%;background-color:transparent;background-position:left center;background-repeat:no-repeat;background-size:contain;width:100%;height:100%}.md-align-left.tablet-slider{float:left;margin-left:25px;display:inline-block}.md-align-center.tablet-slider{margin:0 auto}.md-align-right.tablet-slider{float:right;display:inline-block;margin-right:10px}.vc_md_tablet_slider:after,.vc_md_tablet_slider:before{clear:both;content:' ';display:block} | 18,871 | 18,871 | 0.797997 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.