hexsha
stringlengths
40
40
size
int64
5
1.05M
ext
stringclasses
98 values
lang
stringclasses
21 values
max_stars_repo_path
stringlengths
3
945
max_stars_repo_name
stringlengths
4
118
max_stars_repo_head_hexsha
stringlengths
40
78
max_stars_repo_licenses
listlengths
1
10
max_stars_count
int64
1
368k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
3
945
max_issues_repo_name
stringlengths
4
118
max_issues_repo_head_hexsha
stringlengths
40
78
max_issues_repo_licenses
listlengths
1
10
max_issues_count
int64
1
134k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
3
945
max_forks_repo_name
stringlengths
4
135
max_forks_repo_head_hexsha
stringlengths
40
78
max_forks_repo_licenses
listlengths
1
10
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
5
1.05M
avg_line_length
float64
1
1.03M
max_line_length
int64
2
1.03M
alphanum_fraction
float64
0
1
7b7673c2f6dbb1a4c53785cc377ab707c2d08afc
5,082
css
CSS
scss/themes/okra/fonts/oktaneue/oktaneue.css
edisim/apiscp-bootstrap-sdk
42d5f47e260351226a6342c027104f1363f81e73
[ "MIT" ]
null
null
null
scss/themes/okra/fonts/oktaneue/oktaneue.css
edisim/apiscp-bootstrap-sdk
42d5f47e260351226a6342c027104f1363f81e73
[ "MIT" ]
null
null
null
scss/themes/okra/fonts/oktaneue/oktaneue.css
edisim/apiscp-bootstrap-sdk
42d5f47e260351226a6342c027104f1363f81e73
[ "MIT" ]
null
null
null
@font-face { font-family: 'Okta Neue'; src: url('OktaNeue-BlackItalic.woff2') format('woff2'), url('OktaNeue-BlackItalic.woff') format('woff'); font-weight: 900; font-style: italic; font-display: swap; } @font-face { font-family: 'Okta Neue'; src: url('OktaNeue-Black.woff2') format('woff2'), url('OktaNeue-Black.woff') format('woff'); font-weight: 900; font-style: normal; font-display: swap; } @font-face { font-family: 'Okta Neue'; src: url('OktaNeue-BoldItalic.woff2') format('woff2'), url('OktaNeue-BoldItalic.woff') format('woff'); font-weight: bold; font-style: italic; font-display: swap; } @font-face { font-family: 'Okta Neue'; src: url('OktaNeue-Light.woff2') format('woff2'), url('OktaNeue-Light.woff') format('woff'); font-weight: 300; font-style: normal; font-display: swap; } @font-face { font-family: 'Okta Neue'; src: url('OktaNeue-RegularItalic.woff2') format('woff2'), url('OktaNeue-RegularItalic.woff') format('woff'); font-weight: normal; font-style: italic; font-display: swap; } @font-face { font-family: 'Okta Neue'; src: url('OktaNeue-ExtraLight.woff2') format('woff2'), url('OktaNeue-ExtraLight.woff') format('woff'); font-weight: 200; font-style: normal; font-display: swap; } @font-face { font-family: 'Okta Neue'; src: url('OktaNeue-LightItalic.woff2') format('woff2'), url('OktaNeue-LightItalic.woff') format('woff'); font-weight: 300; font-style: italic; font-display: swap; } @font-face { font-family: 'Okta Neue'; src: url('OktaNeue-Medium.woff2') format('woff2'), url('OktaNeue-Medium.woff') format('woff'); font-weight: 500; font-style: normal; font-display: swap; } @font-face { font-family: 'Okta Neue'; src: url('OktaNeue-Bold.woff2') format('woff2'), url('OktaNeue-Bold.woff') format('woff'); font-weight: bold; font-style: normal; font-display: swap; } @font-face { font-family: 'Okta Neue Normal'; src: url('OktaNeue-NormalItalic.woff2') format('woff2'), url('OktaNeue-NormalItalic.woff') format('woff'); font-weight: normal; font-style: italic; font-display: swap; } @font-face { font-family: 'Okta Neue'; src: url('OktaNeue-ExtraLightItalic.woff2') format('woff2'), url('OktaNeue-ExtraLightItalic.woff') format('woff'); font-weight: 200; font-style: italic; font-display: swap; } @font-face { font-family: 'Okta Neue'; src: url('OktaNeue-HeavyItalic.woff2') format('woff2'), url('OktaNeue-HeavyItalic.woff') format('woff'); font-weight: 900; font-style: italic; font-display: swap; } @font-face { font-family: 'Okta Neue'; src: url('OktaNeue-MediumItalic.woff2') format('woff2'), url('OktaNeue-MediumItalic.woff') format('woff'); font-weight: 500; font-style: italic; font-display: swap; } @font-face { font-family: 'Okta Neue'; src: url('OktaNeue-Heavy.woff2') format('woff2'), url('OktaNeue-Heavy.woff') format('woff'); font-weight: 900; font-style: normal; font-display: swap; } @font-face { font-family: 'Okta Neue Normal'; src: url('OktaNeue-Normal.woff2') format('woff2'), url('OktaNeue-Normal.woff') format('woff'); font-weight: normal; font-style: normal; font-display: swap; } @font-face { font-family: 'Okta Neue'; src: url('OktaNeue-SemiBold.woff2') format('woff2'), url('OktaNeue-SemiBold.woff') format('woff'); font-weight: 600; font-style: normal; font-display: swap; } @font-face { font-family: 'Okta Neue'; src: url('OktaNeue-Regular.woff2') format('woff2'), url('OktaNeue-Regular.woff') format('woff'); font-weight: normal; font-style: normal; font-display: swap; } @font-face { font-family: 'Okta Neue'; src: url('OktaNeue-ThinItalic.woff2') format('woff2'), url('OktaNeue-ThinItalic.woff') format('woff'); font-weight: 100; font-style: italic; font-display: swap; } @font-face { font-family: 'Okta Neue'; src: url('OktaNeue-SemiBoldItalic.woff2') format('woff2'), url('OktaNeue-SemiBoldItalic.woff') format('woff'); font-weight: 600; font-style: italic; font-display: swap; } @font-face { font-family: 'Okta Neue'; src: url('OktaNeue-Thin.woff2') format('woff2'), url('OktaNeue-Thin.woff') format('woff'); font-weight: 100; font-style: normal; font-display: swap; } @font-face { font-family: 'Okta Neue'; src: url('OktaNeue-UltraLightItalic.woff2') format('woff2'), url('OktaNeue-UltraLightItalic.woff') format('woff'); font-weight: 200; font-style: italic; font-display: swap; } @font-face { font-family: 'Okta Neue'; src: url('OktaNeue-UltraLight.woff2') format('woff2'), url('OktaNeue-UltraLight.woff') format('woff'); font-weight: 200; font-style: normal; font-display: swap; }
25.537688
64
0.622983
08986b8543134415c990df2b13e78433f32b9ef9
410
swift
Swift
AppilfTool/Managers/AppilfToolManager.swift
alperengezgin/AppilfTool
c542a7af6fca2e3d812f89457bc0c40a8b85432f
[ "MIT" ]
null
null
null
AppilfTool/Managers/AppilfToolManager.swift
alperengezgin/AppilfTool
c542a7af6fca2e3d812f89457bc0c40a8b85432f
[ "MIT" ]
null
null
null
AppilfTool/Managers/AppilfToolManager.swift
alperengezgin/AppilfTool
c542a7af6fca2e3d812f89457bc0c40a8b85432f
[ "MIT" ]
null
null
null
// // AppilfToolManager.swift // AppilfTool // // Created by Steve Cooper on 2.02.2022. // import Foundation import SVProgressHUD class AppilfToolManager { let sharedInstance = AppilfToolManager() private init() { } func add(number1: Int, number2: Int) { let result = number1 + number2 SVProgressHUD.showInfo(withStatus: String(result)) } }
17.083333
58
0.62439
d1b93711e70ce3c6de6ab7cd387a7081a626b0a4
12,530
rs
Rust
simple-dns/src/dns/mod.rs
Disasm/simple-dns
64248bae1f4a0e075cd1800ab9159cb1370cbff7
[ "MIT" ]
9
2021-06-02T12:33:10.000Z
2021-11-25T20:25:40.000Z
simple-dns/src/dns/mod.rs
Disasm/simple-dns
64248bae1f4a0e075cd1800ab9159cb1370cbff7
[ "MIT" ]
3
2021-07-31T10:33:19.000Z
2022-01-29T22:22:17.000Z
simple-dns/src/dns/mod.rs
Disasm/simple-dns
64248bae1f4a0e075cd1800ab9159cb1370cbff7
[ "MIT" ]
4
2021-09-07T14:51:17.000Z
2022-02-18T06:39:42.000Z
//! Provides parsing and manipulation for DNS packets mod character_string; mod name; mod packet; mod packet_header; mod question; pub mod rdata; mod resource_record; use std::{collections::HashMap, convert::TryFrom}; pub use character_string::CharacterString; pub use name::Name; pub use packet::{Packet, PacketBuf, QuestionsIter}; pub use packet_header::PacketHeader; pub use question::Question; pub use resource_record::ResourceRecord; const MAX_LABEL_LENGTH: usize = 63; const MAX_NAME_LENGTH: usize = 255; const MAX_CHARACTER_STRING_LENGTH: usize = 255; const MAX_NULL_LENGTH: usize = 65535; /// The maximum DNS packet size is 9000 bytes less the maximum /// sizes of the IP (60) and UDP (8) headers. // const MAX_PACKET_SIZE: usize = 9000 - 68; /// Represents anything that can be part of a dns packet (Question, Resource Record, RData) pub(crate) trait DnsPacketContent<'a> { /// Parse the contents of the data buffer begining in the given position /// It is necessary to pass the full buffer to this function, to be able to correctly implement name compression fn parse(data: &'a [u8], position: usize) -> crate::Result<Self> where Self: Sized; /// Append the bytes of this content to a given vector fn append_to_vec(&self, out: &mut Vec<u8>) -> crate::Result<()>; /// Append the bytes of this content to a given vector, compress Names before appending fn compress_append_to_vec( &self, out: &mut Vec<u8>, _name_refs: &mut HashMap<u64, usize>, ) -> crate::Result<()> { self.append_to_vec(out) } /// Returns the length in bytes of this content fn len(&self) -> usize; } /// Possible TYPE values in DNS Resource Records /// Each value is described according to its own RFC #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)] pub enum TYPE { /// Host address, [RFC 1035](https://tools.ietf.org/html/rfc1035) A, /// Host address (IPv6) [rfc3596](https://tools.ietf.org/html/rfc3596) AAAA, /// Authoritative name server, [RFC 1035](https://tools.ietf.org/html/rfc1035) NS, /// Mail destination (Obsolete - use MX), [RFC 1035](https://tools.ietf.org/html/rfc1035) MD, /// Mail forwarder (Obsolete - use MX), [RFC 1035](https://tools.ietf.org/html/rfc1035) MF, /// Canonical name for an alias, [RFC 1035](https://tools.ietf.org/html/rfc1035) CNAME, /// Marks the start of a zone of authority, [RFC 1035](https://tools.ietf.org/html/rfc1035) SOA, /// Mailbox domain name (EXPERIMENTAL), [RFC 1035](https://tools.ietf.org/html/rfc1035) MB, /// Mail group member (EXPERIMENTAL), [RFC 1035](https://tools.ietf.org/html/rfc1035) MG, /// Mail rename domain name (EXPERIMENTAL), [RFC 1035](https://tools.ietf.org/html/rfc1035) MR, /// Null RR (EXPERIMENTAL), [RFC 1035](https://tools.ietf.org/html/rfc1035) NULL, /// Well known service description, [RFC 1035](https://tools.ietf.org/html/rfc1035) WKS, /// Domain name pointer, [RFC 1035](https://tools.ietf.org/html/rfc1035) PTR, /// Host information, [RFC 1035](https://tools.ietf.org/html/rfc1035) HINFO, /// Mailbox or mail list information, [RFC 1035](https://tools.ietf.org/html/rfc1035) MINFO, /// Mail exchange, [RFC 1035](https://tools.ietf.org/html/rfc1035) MX, /// Text strings, [RFC 1035](https://tools.ietf.org/html/rfc1035) TXT, /// SRV specifies the location of the server(s) for a specific protocol and domain. [RFC 2780](https://tools.ietf.org/html/rfc2782) SRV, /// Unknown value, for future (or unimplemented RFC) compatibility Unknown(u16), } impl From<TYPE> for u16 { fn from(value: TYPE) -> Self { match value { TYPE::A => 1, TYPE::AAAA => 28, TYPE::NS => 2, TYPE::MD => 3, TYPE::MF => 4, TYPE::CNAME => 5, TYPE::SOA => 6, TYPE::MB => 7, TYPE::MG => 8, TYPE::MR => 9, TYPE::NULL => 10, TYPE::WKS => 11, TYPE::PTR => 12, TYPE::HINFO => 13, TYPE::MINFO => 14, TYPE::MX => 15, TYPE::TXT => 16, TYPE::SRV => 33, TYPE::Unknown(x) => x, } } } impl From<u16> for TYPE { fn from(value: u16) -> Self { use self::TYPE::*; match value { 1 => A, 2 => NS, 3 => MD, 4 => MF, 5 => CNAME, 6 => SOA, 7 => MB, 8 => MG, 9 => MR, 10 => NULL, 11 => WKS, 12 => PTR, 13 => HINFO, 14 => MINFO, 15 => MX, 16 => TXT, 28 => AAAA, 33 => SRV, v => TYPE::Unknown(v), } } } /// Possible QTYPE values for a Question in a DNS packet /// Each value is described according to its own RFC #[derive(Debug, Copy, Clone, PartialEq)] pub enum QTYPE { /// Host address, [RFC 1035](https://tools.ietf.org/html/rfc1035) A = 1, /// Host address (IPv6) [rfc3596](https://tools.ietf.org/html/rfc3596) AAAA = 28, /// Authoritative name server, [RFC 1035](https://tools.ietf.org/html/rfc1035) NS = 2, /// Mail destination (Obsolete - use MX), [RFC 1035](https://tools.ietf.org/html/rfc1035) MD = 3, /// Mail forwarder (Obsolete - use MX), [RFC 1035](https://tools.ietf.org/html/rfc1035) MF = 4, /// Canonical name for an alias, [RFC 1035](https://tools.ietf.org/html/rfc1035) CNAME = 5, /// Marks the start of a zone of authority, [RFC 1035](https://tools.ietf.org/html/rfc1035) SOA = 6, /// Mailbox domain name (EXPERIMENTAL), [RFC 1035](https://tools.ietf.org/html/rfc1035) MB = 7, /// Mail group member (EXPERIMENTAL), [RFC 1035](https://tools.ietf.org/html/rfc1035) MG = 8, /// Mail rename domain name (EXPERIMENTAL), [RFC 1035](https://tools.ietf.org/html/rfc1035) MR = 9, /// Null RR (EXPERIMENTAL), [RFC 1035](https://tools.ietf.org/html/rfc1035) NULL = 10, /// Well known service description, [RFC 1035](https://tools.ietf.org/html/rfc1035) WKS = 11, /// Domain name pointer, [RFC 1035](https://tools.ietf.org/html/rfc1035) PTR = 12, /// Host Information, [RFC 1035](https://tools.ietf.org/html/rfc1035) HINFO = 13, /// Mailbox or mail list information, [RFC 1035](https://tools.ietf.org/html/rfc1035) MINFO = 14, /// Mail exchange, [RFC 1035](https://tools.ietf.org/html/rfc1035) MX = 15, /// Text strings, [RFC 1035](https://tools.ietf.org/html/rfc1035) TXT = 16, /// SRV specifies the location of the server(s) for a specific protocol and domain. [RFC 2780](https://tools.ietf.org/html/rfc2782) SRV = 33, /// A request for a transfer of an entire zone, [RFC 1035](https://tools.ietf.org/html/rfc1035) AXFR = 252, /// A request for mailbox-related records (MB, MG or MR), [RFC 1035](https://tools.ietf.org/html/rfc1035) MAILB = 253, /// A request for mail agent RRs (Obsolete - see MX), [RFC 1035](https://tools.ietf.org/html/rfc1035) MAILA = 254, /// A request for all records, [RFC 1035](https://tools.ietf.org/html/rfc1035) ANY = 255, } impl TryFrom<u16> for QTYPE { type Error = crate::SimpleDnsError; fn try_from(value: u16) -> Result<Self, Self::Error> { use self::QTYPE::*; match value { 1 => Ok(A), 2 => Ok(NS), 3 => Ok(MD), 4 => Ok(MF), 5 => Ok(CNAME), 6 => Ok(SOA), 7 => Ok(MB), 8 => Ok(MG), 9 => Ok(MR), 10 => Ok(NULL), 11 => Ok(WKS), 12 => Ok(PTR), 13 => Ok(HINFO), 14 => Ok(MINFO), 15 => Ok(MX), 16 => Ok(TXT), 28 => Ok(AAAA), 33 => Ok(SRV), 252 => Ok(AXFR), 253 => Ok(MAILB), 254 => Ok(MAILA), 255 => Ok(ANY), v => Err(Self::Error::InvalidQType(v)), } } } /// Possible CLASS values for a Resource in a DNS packet /// Each value is described according to its own RFC #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)] pub enum CLASS { /// The Internet, [RFC 1035](https://tools.ietf.org/html/rfc1035) IN = 1, /// The CSNET class (Obsolete - used only for examples in some obsolete RFCs), [RFC 1035](https://tools.ietf.org/html/rfc1035) CS = 2, /// The CHAOS class, [RFC 1035](https://tools.ietf.org/html/rfc1035) CH = 3, /// Hesiod [Dyer 87], [RFC 1035](https://tools.ietf.org/html/rfc1035) HS = 4, } impl TryFrom<u16> for CLASS { type Error = crate::SimpleDnsError; fn try_from(value: u16) -> Result<Self, Self::Error> { use self::CLASS::*; match value { 1 => Ok(IN), 2 => Ok(CS), 3 => Ok(CH), 4 => Ok(HS), v => Err(Self::Error::InvalidClass(v)), } } } /// Possible QCLASS values for a Question in a DNS packet /// Each value is described according to its own RFC #[derive(Debug, Copy, Clone, PartialEq)] pub enum QCLASS { /// The Internet, [RFC 1035](https://tools.ietf.org/html/rfc1035) IN = 1, /// The CSNET class (Obsolete - used only for examples in some obsolete RFCs), [RFC 1035](https://tools.ietf.org/html/rfc1035) CS = 2, /// The CHAOS class, [RFC 1035](https://tools.ietf.org/html/rfc1035) CH = 3, /// Hesiod [Dyer 87], [RFC 1035](https://tools.ietf.org/html/rfc1035) HS = 4, /// [RFC 1035](https://tools.ietf.org/html/rfc1035) ANY = 255, } impl TryFrom<u16> for QCLASS { type Error = crate::SimpleDnsError; fn try_from(value: u16) -> Result<Self, Self::Error> { use self::QCLASS::*; match value { 1 => Ok(IN), 2 => Ok(CS), 3 => Ok(CH), 4 => Ok(HS), 255 => Ok(ANY), v => Err(Self::Error::InvalidQClass(v)), } } } /// Possible OPCODE values for a DNS packet, use to specify the type of operation. /// [RFC 1035](https://tools.ietf.org/html/rfc1035): A four bit field that specifies kind of query in this message. /// This value is set by the originator of a query and copied into the response. #[derive(Debug, Copy, Clone, PartialEq)] pub enum OPCODE { /// Normal query StandardQuery = 0, /// Inverse query (query a name by IP) InverseQuery = 1, /// Server status request ServerStatusRequest = 2, /// Reserved opcode for future use Reserved, } impl From<u16> for OPCODE { fn from(code: u16) -> Self { match code { 0 => OPCODE::StandardQuery, 1 => OPCODE::InverseQuery, 2 => OPCODE::ServerStatusRequest, _ => OPCODE::Reserved, } } } /// Possible RCODE values for a DNS packet /// [RFC 1035](https://tools.ietf.org/html/rfc1035) Response code - this 4 bit field is set as part of responses. /// The values have the following interpretation #[derive(Debug, Copy, Clone, PartialEq)] pub enum RCODE { /// No error condition NoError = 0, /// Format error - The name server was unable to interpret the query. FormatError = 1, /// Server failure - The name server was unable to process this query due to a problem with the name server. ServerFailure = 2, /// Name Error - Meaningful only for responses from an authoritative name server, /// this code signifies that the domain name referenced in the query does not exist. NameError = 3, /// Not Implemented - The name server does not support the requested kind of query. NotImplemented = 4, /// Refused - The name server refuses to perform the specified operation for policy reasons. /// For example, a name server may not wish to provide the information to the particular requester, /// or a name server may not wish to perform a particular operation (e.g., zone transfer) for particular data. Refused = 5, /// Reserved for future use. Reserved, } impl From<u16> for RCODE { fn from(code: u16) -> Self { match code { 0 => RCODE::NoError, 1 => RCODE::FormatError, 2 => RCODE::ServerFailure, 3 => RCODE::NameError, 4 => RCODE::NotImplemented, 5 => RCODE::Refused, _ => RCODE::Reserved, } } }
34.902507
135
0.58739
21df9703106d11fd3eca77e52a588924db4ba4a7
30,660
html
HTML
Instructor/views/home.html
jsndc99/Inertia_ByteCamp_2020
8f0edf42847e09d8ba3ca570a35e12e091595f2f
[ "MIT" ]
null
null
null
Instructor/views/home.html
jsndc99/Inertia_ByteCamp_2020
8f0edf42847e09d8ba3ca570a35e12e091595f2f
[ "MIT" ]
2
2020-02-22T15:19:49.000Z
2020-02-23T06:40:33.000Z
Instructor/views/home.html
jsndc99/Inertia_ByteCamp_2020
8f0edf42847e09d8ba3ca570a35e12e091595f2f
[ "MIT" ]
3
2020-03-12T15:51:16.000Z
2020-04-03T15:10:20.000Z
<html lang="en"> <head> <meta charset="UTF-8"> <title>Dashboard</title> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css"> <link href="https://fonts.googleapis.com/css?family=Droid+Sans" rel="stylesheet"> <link rel="stylesheet" href="css/main.css"> <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.2/Chart.bundle.js"></script> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script> <script src="js/makeChart.js"></script> </head> <body> <aside class="side-nav" id="show-side-navigation1"> <i class="fa fa-bars close-aside hidden-sm hidden-md hidden-lg" data-close="show-side-navigation1"></i> <div class="heading"> <img src="https://www.logopeople.in/blog/wp-content/uploads/2013/01/government-of-india.jpg" alt=""> <div class="info"> <h3><a href="#"> Minister for Agriculture and Farmers’ Welfare</a></h3> <p>Growing the Future!!</p> </div> </div> <div class="search"> <input type="text" placeholder="Type here"><i class="fa fa-search"></i> </div> <ul class="categories"> <li><i class="fa fa-home fa-fw" ></i><a href="#welcome">Home</a></li> <li><i class="fa fa-support fa-fw"></i><a href="#charts"> Reports</a> <ul class="side-nav-dropdown"> <li><a href="#">Lorem ipsum</a></li> <li><a href="#">ipsum dolor</a></li> <li><a href="#">dolor ipsum</a></li> <li><a href="#">amet consectetur</a></li> <li><a href="#">ipsum dolor sit</a></li> </ul> </li> <li><i class="fa fa-support fa-fw"></i><a href="#"> Analytics</a> <ul class="side-nav-dropdown"> <li><a href="#">Lorem ipsum</a></li> <li><a href="#">ipsum dolor</a></li> <li><a href="#">dolor ipsum</a></li> <li><a href="#">amet consectetur</a></li> <li><a href="#">ipsum dolor sit</a></li> </ul> </li> <li><i class="fa fa-support fa-fw"></i><a href="#charts"> Pending Approvals</a></li> </ul> </aside> <section id="contents"> <nav class="navbar navbar-default"> <div class="container-fluid"> <div class="navbar-header"> <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false"> <i class="fa fa-align-right"></i> </button> <a class="navbar-brand" href="#">my<span class="main-color">Dashboard</span></a> </div> <div class="collapse navbar-collapse navbar-right" id="bs-example-navbar-collapse-1"> <ul class="nav navbar-nav"> <li class="dropdown"> <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">My profile <span class="caret"></span></a> <ul class="dropdown-menu"> <li><a href="#"><i class="fa fa-user-o fw"></i> My account</a></li> <li><a href="#"><i class="fa fa-envelope-o fw"></i> My inbox</a></li> <li><a href="#"><i class="fa fa-question-circle-o fw"></i> Help</a></li> <li role="separator" class="divider"></li> <li><a href="#"><i class="fa fa-sign-out"></i> Log out</a></li> </ul> </li> <li><a href="#"><i data-show="show-side-navigation1" class="fa fa-bars show-side-btn"></i></a></li> </ul> </div> </div> </nav> <div class="welcome"> <div class="container-fluid"> <div class="row"> <div class="col-md-12"> <div class="content"> <h2>Welcome to Dashboard</h2> <p>Lets us help you solve your queries!!</p> </div> </div> </div> </div> </div> <section class="statistics"> <div class="container-fluid"> <div class="row"> <div class="col-md-4"> <div class="box"> <i class="fa fa-envelope fa-fw bg-primary"></i> <div class="info"> <h3 style="padding-top: 10px;">Chat</h3> </div> </div> </div> <div class="col-md-4"> <div class="box"> <i class="fa fa-file fa-fw danger"></i> <div class="info"> <h3 style="padding-top: 10px;">Chat Guidelines</h3> </div> </div> </div> </div> </div> </section> <section class="charts"> <div class="container-fluid"> <div class="row"> <div class="col-md-6"> <div class="chart-container"> <h3>Chart</h3> <canvas id="myChart"></canvas> </div> </div> <div class="col-md-6"> <div class="chart-container"> <h3>Chart2</h3> <canvas id="myChart2"></canvas> </div> </div> </div> </div> </section> <section class='statis text-center'> <div class="container-fluid"> <div class="row"> <div class="col-md-3"> <div class="box bg-primary"> <i class="fa fa-eye"></i> <h3>89.45%</h3> <p class="lead">Average Online Training Accuracy</p> </div> </div> <div class="col-md-3"> <div class="box danger"> <i class="fa fa-user-o"></i> <h3>12</h3> <p class="lead">Farmers Registered</p> </div> </div> <div class="col-md-3"> <div class="box warning"> <i class="fa fa-shopping-cart"></i> <h3>5,154</h3> <p class="lead">Area Of Land Owned</p> </div> </div> </div> </div> </section> <section class="chrt3"> <div class="container-fluid"> <div class="row"> <div class="col-md-9"> <div class="chart-container"> <canvas id="chart3" width="100%"></canvas> </div> </div> <div class="col-md-4"> <div class="box"> </div> </div> </div> </div> </section> </section> <section id="2"></section> <form action="generate_form" method="POST"> <section id="container1" class="add" style="height: 100%; width:100%;" > <h1 class="col-lg-12" style="text-align: center; color: #b09db9;">FILL THE 7/12 EXTRACT!!</h1> <span class="input col-sm-4"> <input type="text" class="input__field" id="input-1" name="village" required /> <label for="input-1" class="input__label"> <span class="input__label-content">Village</span> </label> </span> <span class="input col-sm-4"> <input type="number" class="input__field" id="input-2" name="survey_no" required /> <label for="input-2" class="input__label"> <span class="input__label-content">Survey no</span> </label> </span> <span class="input col-sm-4"> <input type="text" class="input__field" id="input-3" name="sub_division_of" required /> <label for="input-3" class="input__label"> <span class="input__label-content">Sub division of</span> </label> </span> <span class="input col-sm-4"> <input type="text" class="input__field" id="input-4" name="taluka" required/> <label for="input-4" class="input__label"> <span class="input__label-content">Taluka</span> </label> </span> <span class="input col-sm-4"> <input type="number" class="input__field" id="input-5" name="cut_land" required /> <label for="input-5" class="input__label"> <span class="input__label-content">Cultivated Land (in acres)</span> </label> </span> <span class="input col-sm-4"> <input type="text" class="input__field" id="input-6" name="name_of_occupant" required /> <label for="input-6" class="input__label"> <span class="input__label-content">Name of Occupant</span> </label> </span> <span class="input col-sm-4"> <input type="number" class="input__field" id="input-7" name="khata_no" required /> <label for="input-7" class="input__label"> <span class="input__label-content">Khata no.</span> </label> </span> <span class="input col-sm-4"> <input type="text" class="input__field" id="input-8" name="name_of_the_rent" required /> <label for="input-8" class="input__label"> <span class="input__label-content">Name of the Rent</span> </label> </span> <span class="input col-sm-4"> <input type="number" class="input__field" id="input-9" name="B_s_marks" required></input> <label for="input-9" class="input__label"> <span class="input__label-content">Boundary and Survey marks</span> </label> </span> <span class="col-lg-6" style="padding-left: 220px;"> <button id="send-button" type="submit">Submit</button></span> </section> </form> <style> @import url(https://fonts.googleapis.com/css?family=Raleway:200,500,700,800); .add { background: #111; font-weight: 500; font-size: 1.05em; height: 100%; font-family: 'Raleway', Arial, sans-serif; } #container1 { position: absolute; width: 100%; height: 5em; display: flex; flex-wrap: wrap; background-color: #313348; justify-content: center; align-content: center; } .input { position: relative; margin: 1em; width: calc(50% - 2em); height: 80px; } .message { width: calc(100% - 2em); height: 100px; } textarea { border: none; resize: none; } .input__field { position: absolute; margin: 0.8em 0; padding: 0.4em; width: 100%; height: calc(100% - 1.6em); border: none; border-radius: 0; background: transparent; color: #b09db9; font-size: 1.55em; font-weight: bold; -webkit-appearance: none;/* for box shadows to show on iOS */ } .input__field:focus { outline: none; } .input__label { position: absolute; padding: 0 1em; margin: 1.2em 0; width: 100%; height: calc(100% - 2.4em); color: #b09db9; font-weight: bold; font-size: 70.25%; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; -webkit-touch-callout: none; -webkit-user-select: none; -khtml-user-select: none; -moz-user-select: none; -ms-user-select: none; user-select: none; } .input__label-content { position: relative; display: block; padding: 1.5em 0; width: 100%; -webkit-transition: -webkit-transform 0.3s; transition: transform 0.3s; } .input__label::before, .input__label:after { content: ''; position: absolute; left: 0; width: 100%; height: 2px; background: #6a7989; -webkit-transition: -webkit-transform 0.3s; transition: transform 0.3s; } .input__label::before { top: 0; } .input__label::after { bottom: 0; } .input__field:focus + .input__label .input__label-content, .input--filled .input__label-content { -webkit-transform: translate3d(0, -90%, 0); transform: translate3d(0, -90%, 0); } .input__field:focus + .input__label::before, .input--filled .input__label::before { -webkit-transform: translate3d(0, -0.5em, 0); transform: translate3d(0, -0.5em, 0); } .input__field:focus + .input__label::after, .input--filled .input__label::after { -webkit-transform: translate3d(0, 0.5em, 0); transform: translate3d(0, 0.5em, 0); } #send-button { width: 200px; height: 60px; background-color: #b09db9; color: #000; border: 0; font-weight: bold; font-size: 70.25%; text-transform: uppercase; letter-spacing: 4px; -webkit-transition: -webkit-transform 0.3s; transition: transform 0.3s; } #send-button:hover, #send-button:focus { outline: 0; background-color: #ffcc00; color: #000; -webkit-transition: -webkit-transform 0.3s; transition: transform 0.3s; } </style> <script src='http://code.jquery.com/jquery-latest.js'></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.6.0/Chart.bundle.js"></script> <script src='js/main.js'></script> </body> </html> <style> * { padding: 0; margin: 0; -webkit-box-sizing: border-box; -moz-box-sizing: border-box; box-sizing: border-box; font-family: 'Droid Sans', sans-serif; outline: none; } ::-webkit-scrollbar { background: transparent; width: 5px; height: 5px; } ::-webkit-scrollbar-thumb { background-color: #888; } ::-webkit-scrollbar-thumb:hover { background-color: rgba(0, 0, 0, 0.3); } body {background-color: #2a2b3d} #contents { position: relative; transition: .3s; margin-left: 290px; background-color: #2a2b3d; } .margin { margin-left: 0 !important; } /* Start side navigation bar */ .side-nav { float: left; height: 100%; width: 290px; background-color: #252636; color: #CCC; -webkit-transform: translateX(0); -moz-transform: translateX(0); transform: translateX(0); -webkit-transition: all .3s ease-in-out; -moz-transition: all .3s ease-in-out; transition: .3s; position: fixed; top: 0; left: 0; overflow: auto; z-index: 9999999 } .side-nav .close-aside { position: absolute; top: 7px; right: 7px; cursor: pointer; color: #EEE; } .side-nav .heading { background-color: #252636; padding: 15px 15px 15px 30px; overflow: hidden; border-bottom: 1px solid #2a2b3c } .side-nav .heading > img { border-radius: 50%; float: left; width: 28%; } .side-nav .info { float: left; width: 69%; margin-left: 3%; } .side-nav .heading .info > h3 {margin: 0 0 5px} .side-nav .heading .info > h3 > a { color: #EEE; font-weight: 100; margin-top: 4px; display: block; text-decoration: none; font-size: 18px; } .side-nav .heading .info > h3 > a:hover { color: #FFF; } .side-nav .heading .info > p { color: #BBB; font-size: 13px; } /* End heading */ /* Start search */ .side-nav .search { text-align: center; padding: 15px 30px; margin: 15px 0; position: relative; } .side-nav .search > input { width: 100%; background-color: transparent; border: none; border-bottom: 1px solid #23262d; padding: 7px 0 7px; color: #DDD } .side-nav .search > input ~ i { position: absolute; top: 22px; right: 40px; display: block; color: #2b2f3a; font-size: 19px; } /* End search */ .side-nav .categories > li { padding: 17px 40px 17px 30px; overflow: hidden; border-bottom: 1px solid rgba(255, 255, 255, 0.02); cursor: pointer; } .side-nav .categories > li > a { color: #AAA; text-decoration: none; } /* Start num: there are three options primary, danger and success like Bootstrap */ .side-nav .categories > li > a > .num { line-height: 0; border-radius: 3px; font-size: 14px; color: #FFF; padding: 0px 5px } .dang {background-color: #f35959} .prim {background-color: #0275d8} .succ {background-color: #5cb85c} /* End num */ .side-nav .categories > li > a:hover { color: #FFF } .side-nav .categories > li > i { font-size: 18px; margin-right: 5px } .side-nav .categories > li > a:after { content: "\f053"; font-family: fontAwesome; font-size: 11px; line-height: 1.8; float: right; color: #AAA; -webkit-transition: all .3s ease-in-out; -moz-transition: all .3s ease-in-out; transition: all .3s ease-in-out; } .side-nav .categories .opend > a:after { -webkit-transform: rotate(-90deg); -moz-transform: rotate(-90deg); transform: rotate(-90deg); } /* End categories */ /* Start dropdown menu */ .side-nav .categories .side-nav-dropdown { padding-top: 10px; padding-left: 30px; list-style: none; display: none; } .side-nav .categories .side-nav-dropdown > li > a { color: #AAA; text-decoration: none; padding: 7px 0; display: block; } .side-nav .categories p { margin-left: 30px; color: #535465; margin-top: 10px; } /* End dropdown menu */ .show-side-nav { -webkit-transform: translateX(-290px); -moz-transform: translateX(-290px); transform: translateX(-290px); } /* Start media query */ @media (max-width: 767px) { .side-nav .categories > li { padding-top: 12px; padding-bottom: 12px; } .side-nav .search { padding: 10px 0 10px 30px } } /* End side navigation bar */ /* Start welcome */ .welcome { color: #CCC; } .welcome .content { background-color: #313348; padding: 15px; margin-top: 25px; } .welcome h2 { font-family: Calibri; font-weight: 100; margin-top: 0 } .welcome p { color: #999; } /* Start statistics */ .statistics { margin-top: 25px; color: #CCC; } .statistics .box { background-color: #313348; padding: 15px; overflow: hidden; } .statistics .box > i { float: left; color: #FFF; border-radius: 50%; width: 60px; height: 60px; line-height: 60px; font-size: 22px; } .statistics .box .info { float: left; width: auto; margin-left: 10px; } .statistics .box .info h3 { margin: 5px 0 5px; display: inline-block; } .statistics .box .info p {color:#BBB} /* End statistics */ /* Start charts */ .charts { margin-top: 25px; color: #BBB } .charts .chart-container { background-color: #313348; padding: 15px; } .charts .chart-container h3 { margin: 0 0 10px; font-size: 17px; } /* Start users */ .admins { margin-top: 25px; } .admins .box { } .admins .box > h3 { color: #ccc; font-family: Calibri; font-weight: 300; margin-top: 0; } .admins .box .admin { margin-bottom: 20px; overflow: hidden; background-color: #313348; padding: 10px; } .admins .box .admin .img { width: 20%; margin-right: 5%; float: left; } .admins .box .admin .img img { border-radius: 50%; } .admins .box .info { width: 75%; color: #EEE; float: left; } .admins .box .info h3 {font-size: 19px} .admins .box .info p {color: #BBB} /* End users */ /* Start statis */ .statis { color: #EEE; margin-top: 15px; } .statis .box { position: relative; padding: 15px; overflow: hidden; border-radius: 3px; margin-bottom: 25px; } .statis .box h3:after { content: ""; height: 2px; width: 70%; margin: auto; background-color: rgba(255, 255, 255, 0.12); display: block; margin-top: 10px; } .statis .box i { position: absolute; height: 70px; width: 70px; font-size: 22px; padding: 15px; top: -25px; left: -25px; background-color: rgba(255, 255, 255, 0.15); line-height: 60px; text-align: right; border-radius: 50%; } /*chart*/ .chrt3 { padding-bottom: 50px; } .chrt3 .chart-container { height: 350px; padding: 15px; margin-top: 25px; } .chrt3 .box { padding: 15px; } .main-color { color: #ffc107 } .warning {background-color: #f0ad4e} .danger {background-color: #d9534f} .success {background-color: #5cb85c} .inf {background-color: #5bc0de} /* كمية الإمبورتات دى علشان البوتستراب تبطل غتاته وتسيب العناصر اللى متعدله فى حالها طبعا الكلام ده فى كود بن بس */ /* Start bootstrap */ .navbar-right .dropdown-menu { right: auto !important; left: 0 !important; } .navbar-default { background-color: #6f6486 !important; border: none !important; border-radius: 0 !important; margin: 0 !important } .navbar-default .navbar-nav>li>a { color: #EEE !important; line-height: 55px !important; padding: 0 10px !important; } .navbar-default .navbar-brand {color:#FFF !important} .navbar-default .navbar-nav>li>a:focus, .navbar-default .navbar-nav>li>a:hover {color: #EEE !important} .navbar-default .navbar-nav>.open>a, .navbar-default .navbar-nav>.open>a:focus, .navbar-default .navbar-nav>.open>a:hover {background-color: transparent !important; color: #FFF !important} .navbar-default .navbar-brand {line-height: 55px !important; padding: 0 !important} .navbar-default .navbar-brand:focus, .navbar-default .navbar-brand:hover {color: #FFF !important} .navbar>.container .navbar-brand, .navbar>.container-fluid .navbar-brand {margin: 0 !important} @media (max-width: 767px) { .navbar>.container-fluid .navbar-brand { margin-left: 15px !important; } .navbar-default .navbar-nav>li>a { padding-left: 0 !important; } .navbar-nav { margin: 0 !important; } .navbar-default .navbar-collapse, .navbar-default .navbar-form { border: none !important; } } .navbar-default .navbar-nav>li>a { float: left !important; } .navbar-default .navbar-nav>li>a>span:not(.caret) { background-color: #e74c3c !important; border-radius: 50% !important; height: 25px !important; width: 25px !important; padding: 2px !important; font-size: 11px !important; position: relative !important; top: -10px !important; right: 5px !important } .dropdown-menu>li>a { padding-top: 5px !important; padding-right: 5px !important; } .navbar-default .navbar-nav>li>a>i { font-size: 18px !important; } /* Start media query */ @media (max-width: 767px) { #contents { margin: 0 !important } .statistics .box { margin-bottom: 25px !important; } .navbar-default .navbar-nav .open .dropdown-menu>li>a { color: #CCC !important } .navbar-default .navbar-nav .open .dropdown-menu>li>a:hover { color: #FFF !important } .navbar-default .navbar-toggle{ border:none !important; color: #EEE !important; font-size: 18px !important; } .navbar-default .navbar-toggle:focus, .navbar-default .navbar-toggle:hover {background-color: transparent !important} } </style> <script> /*global $, console*/ /* By Mostafa Omar https://www.facebook.com/MostafaOmarIbrahiem */ $(function () { 'use strict'; (function () { var aside = $('.side-nav'), showAsideBtn = $('.show-side-btn'), contents = $('#contents'); showAsideBtn.on("click", function () { $("#" + $(this).data('show')).toggleClass('show-side-nav'); contents.toggleClass('margin'); }); if ($(window).width() <= 767) { aside.addClass('show-side-nav'); } $(window).on('resize', function () { if ($(window).width() > 767) { aside.removeClass('show-side-nav'); } }); // dropdown menu in the side nav var slideNavDropdown = $('.side-nav-dropdown'); $('.side-nav .categories li').on('click', function () { $(this).toggleClass('opend').siblings().removeClass('opend'); if ($(this).hasClass('opend')) { $(this).find('.side-nav-dropdown').slideToggle('fast'); $(this).siblings().find('.side-nav-dropdown').slideUp('fast'); } else { $(this).find('.side-nav-dropdown').slideUp('fast'); } }); $('.side-nav .close-aside').on('click', function () { $('#' + $(this).data('close')).addClass('show-side-nav'); contents.removeClass('margin'); }); }()); // Start chart // var chart = document.getElementById('myChart'); Chart.defaults.global.animation.duration = 2000; // Animation duration Chart.defaults.global.title.display = false; // Remove title Chart.defaults.global.title.text = "Chart"; // Title Chart.defaults.global.title.position = 'bottom'; // Title position Chart.defaults.global.defaultFontColor = '#999'; // Font color Chart.defaults.global.defaultFontSize = 10; // Font size for every label // Chart.defaults.global.tooltips.backgroundColor = '#FFF'; // Tooltips background color Chart.defaults.global.tooltips.borderColor = 'white'; // Tooltips border color Chart.defaults.global.legend.labels.padding = 0; Chart.defaults.scale.ticks.beginAtZero = true; Chart.defaults.scale.gridLines.zeroLineColor = 'rgba(255, 255, 255, 0.1)'; Chart.defaults.scale.gridLines.color = 'rgba(255, 255, 255, 0.02)'; Chart.defaults.global.legend.display = false; var anger_list = []; var happy_list = []; var disgusted_list = []; var sleeping_list = []; var output_list = []; var time_list =[]; async function getID(){ var response = await fetch('/getids'); var jsondata = await response.json(); return jsondata } var myIDs = [] getID().then( data =>{ myIDs = data.all myIDs.forEach(element => { console.log(element) }); }) async function getJson(){ var response = await fetch('/getDashboardData/1'); var jsondata = await response.json(); return jsondata } getJson().then( data => { time_list = data.time output_list = data.output var chart = document.getElementById('myChart'); var myChart = new Chart(chart, { type: 'bar', data: { labels: time_list, datasets: [{ label: "Attentiveness", fill: false, lineTension: 0, data: output_list, pointBorderColor: "#4bc0c0", borderColor: '#4bc0c0', borderWidth: 2, showLine: true, }] }, }); }) setInterval(()=>{ getJson().then( data => { time_list = data.time output_list = data.output var chart = document.getElementById('myChart'); var myChart = new Chart(chart, { type: 'bar', data: { labels: time_list, datasets: [{ label: "Attentiveness", fill: false, lineTension: 0, data: output_list, pointBorderColor: "#4bc0c0", borderColor: '#4bc0c0', borderWidth: 2, showLine: true, }] }, }); }) },10000) getJson().then( data =>{ time_list = data.time output_list = data.output var Chart2 = document.getElementById('myChart2').getContext('2d'); var chart = new Chart(Chart2, { type: 'line', data: { labels: time_list, datasets: [{ label: "Humidity", backgroundColor: 'rgb(255, 99, 132)', borderColor: 'rgb(255, 79, 116)', borderWidth: 2, pointBorderColor: false, data: output_list, fill: false, lineTension: 0, }] }, // Configuration options options: { title: { display: false } } }); }) setInterval(()=>{ getJson().then( data =>{ time_list = data.time output_list = data.output var Chart2 = document.getElementById('myChart2').getContext('2d'); var chart = new Chart(Chart2, { type: 'line', data: { labels: time_list, datasets: [{ label: "Humidity", backgroundColor: 'rgb(255, 99, 132)', borderColor: 'rgb(255, 79, 116)', borderWidth: 2, pointBorderColor: false, data: output_list, fill: false, lineTension: 0, }] }, // Configuration options options: { title: { display: false } } }); }) },10000) // console.log(Chart.defaults.global); // getJson().then( data => { // min_temp_list = data.min // max_temp_list = data.max // var chart = document.getElementById('chart3'); // var myChart = new Chart(chart, { // type: 'line', // data: { // labels: ["Rice", "Sugarcane","Jowar","Bajra","Cotton","Soyabean","Ragi"], // datasets: [{ // label: "Minimum Temperature", // fill: false, // lineTension: .5, // pointBorderColor: "transparent", // pointColor: "white", // borderColor: '#d9534f', // borderWidth: 0, // showLine: true, // data: min_temp_list, // pointBackgroundColor: 'transparent', // },{ // label: "Maximum Temperature", // fill: false, // lineTension: .5, // pointColor: "white", // borderColor: '#5cb85c', // borderWidth: 0, // showLine: true, // data: max_temp_list, // pointBackgroundColor: 'transparent', // }] // }, // }); // }) // setInterval(()=>{ // getJson().then( data => { // min_temp_list = data.min // max_temp_list = data.max // var chart = document.getElementById('chart3'); // var myChart = new Chart(chart, { // type: 'line', // data: { // labels: ["Rice", "Sugarcane","Jowar","Bajra","Cotton","Soyabean","Ragi"], // datasets: [{ // label: "Minimum Temperature", // fill: false, // lineTension: .5, // pointBorderColor: "transparent", // pointColor: "white", // borderColor: '#d9534f', // borderWidth: 0, // showLine: true, // data: min_temp_list, // pointBackgroundColor: 'transparent', // },{ // label: "Maximum Temperature", // fill: false, // lineTension: .5, // pointColor: "white", // borderColor: '#5cb85c', // borderWidth: 0, // showLine: true, // data: max_temp_list, // pointBackgroundColor: 'transparent', // }] // }, // }); // }) // },10000) }); </script>
26.005089
213
0.565297
55854c051df5091b848b74357ad867dbeb636981
2,054
html
HTML
demo.html
stottle-uk/stottle-social-pocket
eca7afc09a7a54078b59dd3b7f504077c9a7ad5a
[ "MIT" ]
null
null
null
demo.html
stottle-uk/stottle-social-pocket
eca7afc09a7a54078b59dd3b7f504077c9a7ad5a
[ "MIT" ]
null
null
null
demo.html
stottle-uk/stottle-social-pocket
eca7afc09a7a54078b59dd3b7f504077c9a7ad5a
[ "MIT" ]
null
null
null
The demands on business to create a strong powerful presence on social media in todays market in increasingly more and more draining on small to medium size businesses and startups who are put off by the idea of recruiting expensive social media experts to manage their social media presence on line. What if we could put the power of a whole team of social media experts firmly into your hands. Allowing you expand your social reach using the lasted AI machine learning technology to provide you with detailed insights on how to best edit and apply your filters against onto your content Our services will scour over a 100 million existing Instagram photos across 1000 different categories to help your business understand how to create great engaging content against what already works on Instagram. Creating great content is only the tip of the iceberg, there a plethora of great content on Instagram which is completely invisible to their audience which can sometimes leave businesses feeling frustrated. Social pocket have a unique understanding of instagrams algorithms and know what it talks to ensure you content gets into the to 9 posts resulting in an instant expansion in reach and visibility. The unique thing about instagrams top 9 posts is that depending of the activity within that hashtag you could find yourself featured for up to 3 days. Our Unique hash tag suggestion tool will pick the best hashtags for your post based on a few suggested keywords which will be completely tailored to your Social pocket will carry out all the essential tasks your social media expert will typically carry out on a daily basis, from applying hashtags, suggesting photo edits and keeping track of your growth and engagement. Our unique analytics tools will provide you with a deep insights to your current audience, pin pointing your biggest influences and engagers and help you understand whats topics are currently trending across instagram right now. providing you with the knowledge to know what when and how you should post to instagram
146.714286
501
0.824245
3e3041d5214918d9f44fad8b0a436a42c0db525b
934
h
C
Tunnel/SSPacketTunnelProvider.h
iRemark/SSTestKit
f85eb522fd985a6fe300d28e96c9283ea3977499
[ "MIT" ]
2
2019-09-08T13:09:08.000Z
2019-09-10T03:03:39.000Z
Tunnel/SSPacketTunnelProvider.h
iRemark/SSTestKit
f85eb522fd985a6fe300d28e96c9283ea3977499
[ "MIT" ]
null
null
null
Tunnel/SSPacketTunnelProvider.h
iRemark/SSTestKit
f85eb522fd985a6fe300d28e96c9283ea3977499
[ "MIT" ]
3
2020-04-17T08:05:52.000Z
2021-03-24T21:57:37.000Z
// // PacketTunnelProvider.h // tunnel // // Created by xiaoyu on 2018/9/26. // Copyright © 2018年 xiaoyu. All rights reserved. // @import NetworkExtension; @protocol SSPacketTunnelProviderProtocol <NSObject> - (void)customCancelTunnelWithError:(nullable NSError *)error; - (void)customSetTunnelNetworkSettings:(nullable NETunnelNetworkSettings *)tunnelNetworkSettings completionHandler:(nullable void (^)( NSError * __nullable error))completionHandler; @end //NEPacketTunnelProvider @interface SSPacketTunnelProvider: NSObject @property NEPacketTunnelFlow *packetFlow; @property (nullable) NWPath *defaultPath; @property (weak) id<SSPacketTunnelProviderProtocol> delegate; - (void)startTunnelWithOptions:(NSDictionary *)options completionHandler:(void (^)(NSError *))completionHandler; - (void)stopTunnelWithReason:(NEProviderStopReason)reason completionHandler:(void (^)(void))completionHandler; @end
29.1875
181
0.782655
52f4b4809d5b9283d35a309f086892764afc5863
845
kt
Kotlin
src/main/kotlin/com/flaidzeres/hid4kotlin/Example.kt
DmitriyGovorukhin/project-H
29c9c1146cc033d8be942599cbc5df692e11cccc
[ "MIT" ]
null
null
null
src/main/kotlin/com/flaidzeres/hid4kotlin/Example.kt
DmitriyGovorukhin/project-H
29c9c1146cc033d8be942599cbc5df692e11cccc
[ "MIT" ]
null
null
null
src/main/kotlin/com/flaidzeres/hid4kotlin/Example.kt
DmitriyGovorukhin/project-H
29c9c1146cc033d8be942599cbc5df692e11cccc
[ "MIT" ]
null
null
null
package com.flaidzeres.hid4kotlin import java.nio.ByteBuffer import java.util.* fun main(args: Array<String>) { val lsnr = object : HidDeviceListener { override fun onConnect(d: HidDevice) { println("Connected: $d") } override fun onDisconnect(d: HidDevice) { println("Disconnected: $d") } } val mgr = HidDeviceManager(mod = HIDRAW) mgr += lsnr mgr.open { val d = device("/dev/hidraw1") d.open { val buf = ByteBuffer.allocate(64) val arr = buf.array() var cnt = 1000 while (true) { if (cnt <= 0) break read(arr) println(Arrays.toString(arr)) buf.clear() cnt-- } } } }
18.777778
49
0.474556
8816810c381d761cfcd59fbab3e6a5c9fc679c00
492
swift
Swift
Example/EFKeyboardToolBar/UIColor+.swift
EyreFree/EFKeyboardToolBar
f161119a9c06272ddad6519e533c467e403ef8ad
[ "MIT" ]
3
2018-09-12T00:59:22.000Z
2018-09-26T09:27:26.000Z
Example/EFKeyboardToolBar/UIColor+.swift
EyreFree/EFKeyboardToolBar
f161119a9c06272ddad6519e533c467e403ef8ad
[ "MIT" ]
null
null
null
Example/EFKeyboardToolBar/UIColor+.swift
EyreFree/EFKeyboardToolBar
f161119a9c06272ddad6519e533c467e403ef8ad
[ "MIT" ]
null
null
null
// // UIColor+.swift // EFKeyboardToolBar_Example // // Created by EyreFree on 2018/9/11. // Copyright © 2018年 CocoaPods. All rights reserved. // import UIKit extension UIColor { convenience init(valueRGB: UInt, alpha: CGFloat = 1.0) { self.init( red: CGFloat((valueRGB & 0xFF0000) >> 16) / 255.0, green: CGFloat((valueRGB & 0x00FF00) >> 8) / 255.0, blue: CGFloat(valueRGB & 0x0000FF) / 255.0, alpha: alpha ) } }
22.363636
63
0.579268
1e4c4c9dceae483cf6bf304b3983f47812f34a2b
708
css
CSS
assets/public/css/responsive.css
vinhan16sep/thienlocxuan
770e5ff339a71a917d738bc837709675b2d3fb4f
[ "MIT" ]
null
null
null
assets/public/css/responsive.css
vinhan16sep/thienlocxuan
770e5ff339a71a917d738bc837709675b2d3fb4f
[ "MIT" ]
null
null
null
assets/public/css/responsive.css
vinhan16sep/thienlocxuan
770e5ff339a71a917d738bc837709675b2d3fb4f
[ "MIT" ]
null
null
null
@media(max-width:768px){ .logo{ text-align:center; } .nav_bar ul{ } #slide_top{ } #slide_top img{ } #slide_top .carousel-inner{ } .content_title { padding-right: 15px; text-align: left; } .line{ margin-left: 0; } .nav_bar .sub_menu_hover { font-size: 1em; padding: 10px 5px; margin-top: 12px; display: inline-block; } .top_menu{ text-align: left; } .main_content{ margin-top: 180px; } .page_list{ margin-top: 60px; } .page_list ul{ width: 80%; padding-left: 0; margin: 0 auto; } } @media(min-width:768px) and (max-width:992px){ .main_content{ margin-top: 0px; } }
11.419355
47
0.55226
f8703492f913e10dd39278f18d9de20ef7b1a40f
4,388
sql
SQL
src/ecis_extraction/sql/functions/ecis_enrollment_extraction.sql
ctoec/oec-data-tools
775d565bcffd8c090651cf200c401bb6b73460d7
[ "CC0-1.0" ]
null
null
null
src/ecis_extraction/sql/functions/ecis_enrollment_extraction.sql
ctoec/oec-data-tools
775d565bcffd8c090651cf200c401bb6b73460d7
[ "CC0-1.0" ]
17
2020-05-14T15:08:30.000Z
2021-01-15T21:26:06.000Z
src/ecis_extraction/sql/functions/ecis_enrollment_extraction.sql
ctoec/oec-data-tools
775d565bcffd8c090651cf200c401bb6b73460d7
[ "CC0-1.0" ]
null
null
null
select Student.Student.Id as StudentId, Student.Enrollment.Id as EnrollmentId, CAST(Student.Enrollment.EnrollmentDate as DATE) as EnrollmentDate, CAST(Student.Enrollment.FacilityExitDate as DATE) as FacilityExitDate, Universal.Agency.Name, Universal.Agency.Id as FacilityId, Universal.Agency.Code, Universal.Agency.ParentOrganization as OrganizationId, Student.Student.SASID, Student.StudentDetails.FirstName, Student.StudentDetails.MiddleName, Student.StudentDetails.LastName, Student.StudentDetails.Dob, Student.StudentDetails.Gender, RecentDetermination.AnnualFamilyIncome, RecentDetermination.NumberOfPeopleInHousehold, Enrollment.EnrollmentFunding.FundingType, RaceList, AdditionalFunding.AdditionalFundingTypes, trim(concat(RecentAddress.StreetNumber, ' ', RecentAddress.Address1, ' ', RecentAddress.Address2)) as Address, RecentAddress.Town, RecentAddress.Zip, RecentAddress.State, RecentDetermination.IndividualizedIEP, RecentAddress.AddressType, BirthCertificate.Value as BirthCertificateId, StateOfBirth.Value as StateOfBirth, TownOfBirth.Value as TownOfBirth, Enrollment.EnrollmentFunding.SpaceType FROM Enrollment.EnrollmentFunding LEFT JOIN Student.Enrollment ON Enrollment.EnrollmentFunding.EnrollmentId = Student.Enrollment.Id LEFT JOIN Student.Student ON Student.Enrollment.StudentId = Student.Student.Id left join Student.StudentDetails on Student.Student.Id = Student.StudentDetails.StudentId /* 3 duplicate records */ left join (select *, ROW_NUMBER() OVER (PARTITION BY StudentId ORDER BY DateFamilyIncomeDocumented DESC) as RN FROM Enrollment.AdditionalStudentInfo) as RecentDetermination on Student.Student.Id = RecentDetermination.StudentId AND RecentDetermination.RN = 1 left join Universal.Agency on Student.Enrollment.FacilityCode = Universal.Agency.Code LEFT JOIN (select StudentId, string_agg(Student.Race.RaceCode,',') as RaceList From Student.Race GROUP BY StudentId) as StudentRace on Student.Student.Id = StudentRace.StudentId left join (select *, ROW_NUMBER() OVER (PARTITION BY StudentId ORDER BY ModifiedDate DESC) as RN FROM Student.Address) as RecentAddress on Student.Student.Id = RecentAddress.StudentId AND RecentAddress.RN = 1 left join Student.EditableFieldValues as BirthCertificate ON BirthCertificate.StudentId = Student.Student.Id AND BirthCertificate.EditableFieldId = 3 and Enrollment.RegisteringSiteId = BirthCertificate.OrganizationId left join Student.EditableFieldValues as StateOfBirth ON StateOfBirth.StudentId = Student.Student.Id AND StateOfBirth.EditableFieldId = 4 and Enrollment.RegisteringSiteId = StateOfBirth.OrganizationId left join Student.EditableFieldValues as TownOfBirth ON Student.Student.Id = TownOfBirth.StudentId AND TownOfBirth.EditableFieldId = 5 and Enrollment.RegisteringSiteId = TownOfBirth.OrganizationId left join (select EnrollmentId, string_agg(Enrollment.AdditionalFundingSources.AdditionalFundingType,',') as AdditionalFundingTypes from Enrollment.AdditionalFundingSources GROUP BY EnrollmentId) as AdditionalFunding on AdditionalFunding.EnrollmentId = EnrollmentFunding.EnrollmentId WHERE StartDate <= CAST(:start_date AS DATETIME) AND EndDate >= CAST(:end_date AS DATETIME) GROUP BY Student.Student.Id, Student.Enrollment.Id, CAST(Student.Enrollment.EnrollmentDate as DATE), CAST(Student.Enrollment.FacilityExitDate as DATE), Universal.Agency.Name, Universal.Agency.Id, Universal.Agency.Code, Universal.Agency.ParentOrganization, Student.Student.SASID, Student.StudentDetails.FirstName, Student.StudentDetails.MiddleName, Student.StudentDetails.LastName, Student.StudentDetails.Dob, Student.StudentDetails.Gender, RecentDetermination.AnnualFamilyIncome, RecentDetermination.NumberOfPeopleInHousehold, Enrollment.EnrollmentFunding.FundingType, RaceList, AdditionalFunding.AdditionalFundingTypes, trim(concat(RecentAddress.StreetNumber, ' ', RecentAddress.Address1, ' ', RecentAddress.Address2)), RecentAddress.Town, RecentAddress.Zip, RecentAddress.State, RecentDetermination.IndividualizedIEP, RecentAddress.AddressType, BirthCertificate.Value, StateOfBirth.Value, TownOfBirth.Value, Enrollment.EnrollmentFunding.SpaceType;
78.357143
949
0.799681
864ca8cb7eee0cfacc4b0f5596c447d9d519730d
2,591
rs
Rust
src/codegen/method.rs
gaoqiangz/pbni-rs
0809edd7fcc2d7263d21de9e1a05584c6e249e35
[ "BSD-2-Clause" ]
10
2021-06-08T01:15:12.000Z
2022-02-22T09:58:27.000Z
src/codegen/method.rs
yishuixuanyuan/pbni-rs
0809edd7fcc2d7263d21de9e1a05584c6e249e35
[ "BSD-2-Clause" ]
1
2021-06-09T07:31:04.000Z
2021-06-10T12:15:16.000Z
src/codegen/method.rs
yishuixuanyuan/pbni-rs
0809edd7fcc2d7263d21de9e1a05584c6e249e35
[ "BSD-2-Clause" ]
1
2022-02-22T09:57:53.000Z
2022-02-22T09:57:53.000Z
use crate::{callinfo::FromCallInfo, value::ToValue, *}; /// 通用函数调用的抽象工厂 pub trait Factory<CTX, T, R> { fn call(&self, ctx: CTX, param: T) -> R; } /// 通过抽象工厂接口反射调用函数 #[doc(hidden)] pub fn factory_call<'ci, CTX, F, T, R>(f: F, ctx: CTX, ci: &CallInfoRef<'ci>) -> Result<()> where F: Factory<CTX, T, R>, T: FromCallInfo<'ci>, R: ToValue { match T::from_callinfo(ci) { Ok(param) => f.call(ctx, param).to_value(&mut ci.return_value()), Err(e) => { //发生NULL错误说明参数接收者不支持传NULL值,此时自动转义为返回NULL if e == PBXRESULT::E_NULL_ERROR { ci.return_value().set_to_null() } else { Err(e) } } } } #[rustfmt::skip] mod m { use super::*; /// 将函数参数列表反射为tuple类型 macro_rules! factory_tuple { ($(($n:tt, $T:ident)),+) => { #[doc(hidden)] impl<CTX,FUNC,$($T),+,R> Factory<CTX,($($T,)+),R> for FUNC where FUNC: Fn(CTX,$($T),+) -> R { fn call(&self, ctx: CTX, param: ($($T,)+)) -> R { (self)(ctx,$(param.$n),+) } } } } #[doc(hidden)] impl<CTX,F,R> Factory<CTX,(),R> for F where F: Fn(CTX) -> R { fn call(&self, ctx: CTX, _: ()) -> R { (self)(ctx) } } factory_tuple!((0, A)); factory_tuple!((0, A), (1, B)); factory_tuple!((0, A), (1, B), (2, C)); factory_tuple!((0, A), (1, B), (2, C), (3, D)); factory_tuple!((0, A), (1, B), (2, C), (3, D), (4, E)); factory_tuple!((0, A), (1, B), (2, C), (3, D), (4, E), (5, F)); factory_tuple!((0, A), (1, B), (2, C), (3, D), (4, E), (5, F), (6, G)); factory_tuple!((0, A), (1, B), (2, C), (3, D), (4, E), (5, F), (6, G), (7, H)); factory_tuple!((0, A), (1, B), (2, C), (3, D), (4, E), (5, F), (6, G), (7, H), (8, I)); factory_tuple!((0, A), (1, B), (2, C), (3, D), (4, E), (5, F), (6, G), (7, H), (8, I), (9, J)); factory_tuple!((0, A), (1, B), (2, C), (3, D), (4, E), (5, F), (6, G), (7, H), (8, I), (9, J), (10, K)); factory_tuple!((0, A), (1, B), (2, C), (3, D), (4, E), (5, F), (6, G), (7, H), (8, I), (9, J), (10, K), (11, L)); factory_tuple!((0, A), (1, B), (2, C), (3, D), (4, E), (5, F), (6, G), (7, H), (8, I), (9, J), (10, K), (11, L), (12, M)); factory_tuple!((0, A), (1, B), (2, C), (3, D), (4, E), (5, F), (6, G), (7, H), (8, I), (9, J), (10, K), (11, L), (12, M), (13, N)); factory_tuple!((0, A), (1, B), (2, C), (3, D), (4, E), (5, F), (6, G), (7, H), (8, I), (9, J), (10, K), (11, L), (12, M), (13, N), (14, O)); }
36.492958
144
0.40988
992730b2bf5972cc6825703e12f1424c4a7a2cac
5,664
c
C
nitan/inherit/room/demonroom.c
cantona/NT6
073f4d491b3cfe6bfbe02fbad12db8983c1b9201
[ "MIT" ]
1
2019-03-27T07:25:16.000Z
2019-03-27T07:25:16.000Z
nitan/inherit/room/demonroom.c
cantona/NT6
073f4d491b3cfe6bfbe02fbad12db8983c1b9201
[ "MIT" ]
null
null
null
nitan/inherit/room/demonroom.c
cantona/NT6
073f4d491b3cfe6bfbe02fbad12db8983c1b9201
[ "MIT" ]
null
null
null
// demonroom.c // 怪物練級房間 // n_time 怪物刷新時間 // n_npc 怪物刷新數量 // n_max_npc 房間容納最多怪物數量,即一次最多刷新多少個怪物 // s_npc 怪物種類,文件路徑 // n_av_refresh 平均刷新速率 // 一個房間只能定義一種怪物 #include <ansi.h> inherit ROOM; // 計算刷新速率的間隔時間 // 每過一段時間通過一定算法計算刷新速率 #define COUNT_REFRESH_TIME 45 void start_heart_beat() { // 默認為心跳1 set_heart_beat(1); } void setup() { mapping product; string mine; int count; //set("no_clean_up", 1); set("no_roar", 1); //set("no_flyto", 1); // 不能騎馬或MISS到這裏,已經在horse.c做限制 // 設置房間怪物屬性 if (! query("n_time"))set("n_time", 60); // 默認怪物45秒刷新一次 if (! query("n_npc"))set("n_npc", 1); // 默認怪物每次刷新一個 if (! query("n_max_npc"))set("n_max_npc", 1); //默認為1,房間容納最多怪物數量,即一次最多刷新多少個怪物 if (! query("s_npc"))set("s_npc", "/clone/quarry/zhu"); // 默認怪物為野獸—豬 set("n_die", 0); // 單位時間內怪物死亡數量 if (query("last_refresh_time")) // 上次刷新時間 set("last_refresh_time", query("last_refresh_time")); if (query("last_count_refresh_time")) // 上次計算刷新速率的時間 set("last_count_refresh_time", query("last_count_refresh_time")); ::setup(); start_heart_beat(); } void init() { if (random(2))this_player()->start_busy(1); } // 每次心跳執行的操作 // 刷新時間到後刷新怪物,並計算下次刷新時間及怪物數量 void heart_beat() { object ob_npc; object env; object *inv, *obs; int n_left_npc; // 當前怪物數量和最大容納怪物數的差 int n_npc; // 設置怪物的數量 int i; // 計數變量 int refresh_total; // 時間間隔內總共刷新的怪物數量 int new_n_time; // 設置新的刷新時間 int new_n_npc; // 設置怪物刷新數量 //object me; //me = find_player("rcwiz"); env = this_object(); if (new_n_time <= 0)new_n_time = env->query("n_time"); if (new_n_npc <= 0)new_n_time = env->query("n_npc"); // 如果為蓬萊島,則判斷蓬萊島是否開放 if (env->query("penglai") && ! GIFT_D->is_open_pld())return; inv = all_inventory(env); obs = filter_array(inv, (: base_name($1) == query("s_npc") :)); // 過濾掉非本房間怪物的其他文件 // 時間到達則刷新怪物 n_left_npc = query("n_max_npc") - sizeof(obs); if (n_left_npc > 0 && time() - query("last_refresh_time") >= query("n_time")) { n_npc = n_left_npc >= query("n_npc") ? query("n_npc") : n_left_npc; for (i = 0; i < n_npc; i ++ ) { ob_npc = new(query("s_npc")); if (! objectp(ob_npc)) { log_file("mroom", "無法找到npc文件 " + query("s_npc") + "\n"); return; } ob_npc->move(env); } set("last_refresh_time", time()); } // 計算刷新速率的算法 // 每間隔COUNT_REFRESH_TIME秒計算一次,然後根據計算結果重新設置 // 怪物刷新時間和數量 if (time() - query("last_count_refresh_time") >= COUNT_REFRESH_TIME) { // 算法描述 // 通過統計單位時間內怪物死亡數量 // 判定刷新速度,只計算怪物減少或不變的數量,不計算增加的數量 // 時間間隔內總共刷新的怪物數量 refresh_total = COUNT_REFRESH_TIME / query("n_time") * query("n_npc"); if (refresh_total < 1)refresh_total = 1; // 設置刷新時間按照比例計算 new_n_time = query("n_time") * query("n_die") / refresh_total; // 滿刷,即刷出多少怪都全部殺死增加刷新 if (new_n_time >= query("n_time")) { new_n_time = new_n_time - new_n_time / 3; new_n_npc = query("n_npc") + 1; } // 殺死怪物超過刷出的一半增加刷新 else if (new_n_time >= query("n_time") / 2) { new_n_time = new_n_time - new_n_time / 5; new_n_npc = query("n_npc") + 1; } else // 未超過一半刷新速度則降低刷新速度 { new_n_time = new_n_time + new_n_time / 2; new_n_npc = query("n_npc") / 2; } // 溢出判斷 if (new_n_time > query("n_time"))new_n_time = query("n_time"); if (new_n_time <= 0)new_n_time = query("n_time"); // n_die == 0 if (new_n_time < 15)new_n_time = 15; if (new_n_npc < 1)new_n_npc = 1; if (new_n_npc > query("n_max_npc"))new_n_npc = query("n_max_npc"); set("n_time", new_n_time); set("n_npc", new_n_npc); // 計數清0 set("n_die", 0); // 記錄本次計算的時間 set("last_count_refresh_time", time()); } } // 怪物死亡時通知該房間累計怪物死亡熟練,以便計算刷新速率 void npc_die(object ob) { add("n_die", 1); }
33.317647
123
0.413489
24bacb54581bada777c5c7e896b4db9ee14b6d50
798
sql
SQL
ProjektZaliczeniowy/ProjektZaliczeniowy/HR/Tables/Pracownicy_Zespoly.sql
Nitril/ProjektZ_11166
00ae03f81a458a793428725395008a439f859892
[ "MIT" ]
null
null
null
ProjektZaliczeniowy/ProjektZaliczeniowy/HR/Tables/Pracownicy_Zespoly.sql
Nitril/ProjektZ_11166
00ae03f81a458a793428725395008a439f859892
[ "MIT" ]
null
null
null
ProjektZaliczeniowy/ProjektZaliczeniowy/HR/Tables/Pracownicy_Zespoly.sql
Nitril/ProjektZ_11166
00ae03f81a458a793428725395008a439f859892
[ "MIT" ]
null
null
null
CREATE TABLE [HR].[Pracownicy_Zespoly] ( [Przypisanie_Id] INT IDENTITY (1, 1) NOT NULL, [Zespol_Id] INT CONSTRAINT [DF_Zespol_Id_Pracownicy_Zespoly] DEFAULT ((-1)) NOT NULL, [Pracownik_Id] INT CONSTRAINT [DF_Pracownik_Id_Pracownicy_Zespoly] DEFAULT ((-1)) NOT NULL, [Data_Przypisania] SMALLDATETIME NOT NULL, [Data_Wypisania] SMALLDATETIME NULL, PRIMARY KEY CLUSTERED ([Przypisanie_Id] ASC), CONSTRAINT [FK_Pracownik_Id_Pracownicy_Zespoly] FOREIGN KEY ([Pracownik_Id]) REFERENCES [HR].[Pracownik] ([Pracownik_Id]) ON DELETE SET DEFAULT ON UPDATE SET DEFAULT, CONSTRAINT [FK_Zespol_Id_Pracownicy_Zespoly] FOREIGN KEY ([Zespol_Id]) REFERENCES [HR].[Zespoly] ([Zespol_Id]) ON DELETE SET DEFAULT ON UPDATE SET DEFAULT );
57
170
0.713033
22e043a27e132bf5195a00c3620fb0719f65bf10
6,232
kt
Kotlin
frontend/android/app/src/main/java/app/cyla/auth/AndroidEnclave.kt
cyla-app/cyla-app
9ecd8b30e4250946d7ef81cf31b9999d20f2d7dc
[ "MIT" ]
2
2020-12-01T08:25:52.000Z
2021-07-10T15:21:03.000Z
frontend/android/app/src/main/java/app/cyla/auth/AndroidEnclave.kt
cyla-app/cyla-app
9ecd8b30e4250946d7ef81cf31b9999d20f2d7dc
[ "MIT" ]
27
2021-01-02T17:32:16.000Z
2022-02-27T11:29:48.000Z
frontend/android/app/src/main/java/app/cyla/auth/AndroidEnclave.kt
cyla-app/cyla-app
9ecd8b30e4250946d7ef81cf31b9999d20f2d7dc
[ "MIT" ]
null
null
null
package app.cyla.auth import android.app.KeyguardManager import android.content.Context import android.security.keystore.KeyGenParameterSpec import android.security.keystore.KeyProperties import android.security.keystore.UserNotAuthenticatedException import android.util.Log import android.widget.Toast import androidx.biometric.BiometricManager import androidx.biometric.BiometricManager.Authenticators import androidx.biometric.BiometricManager.BIOMETRIC_SUCCESS import androidx.biometric.BiometricPrompt import androidx.core.content.ContextCompat import app.cyla.MainActivity import java.nio.charset.Charset import java.security.KeyStore import javax.crypto.Cipher import javax.crypto.KeyGenerator import javax.crypto.SecretKey import javax.crypto.spec.GCMParameterSpec import kotlin.coroutines.Continuation import kotlin.coroutines.resume import kotlin.coroutines.resumeWithException import kotlin.coroutines.suspendCoroutine class AndroidEnclave(private val context: MainActivity) { companion object { private const val KEYSTORE_ALIAS = "passphrase" private val KEY_SIZE = 256 private val ANDROID_KEYSTORE = "AndroidKeyStore" private val ENCRYPTION_BLOCK_MODE = KeyProperties.BLOCK_MODE_GCM private val ENCRYPTION_PADDING = KeyProperties.ENCRYPTION_PADDING_NONE private val ENCRYPTION_ALGORITHM = KeyProperties.KEY_ALGORITHM_AES } private val promptInfo = BiometricPrompt.PromptInfo.Builder() .setTitle("Passphrase Store") .setDescription("Authenticate to store your credentials securely.") .setAllowedAuthenticators(Authenticators.BIOMETRIC_STRONG) .setNegativeButtonText("Cancel") .build() private fun getCipher(): Cipher { val transformation = "$ENCRYPTION_ALGORITHM/$ENCRYPTION_BLOCK_MODE/$ENCRYPTION_PADDING" return Cipher.getInstance(transformation) } private fun initKeyGenerator(): KeyGenerator { val keyGenerator: KeyGenerator = KeyGenerator .getInstance(ENCRYPTION_ALGORITHM, ANDROID_KEYSTORE) val specBuilder = KeyGenParameterSpec.Builder( KEYSTORE_ALIAS, KeyProperties.PURPOSE_ENCRYPT or KeyProperties.PURPOSE_DECRYPT ) .setBlockModes(ENCRYPTION_BLOCK_MODE) .setEncryptionPaddings(ENCRYPTION_PADDING) .setKeySize(KEY_SIZE) val keyguardManager = context.getSystemService(Context.KEYGUARD_SERVICE) as KeyguardManager if (keyguardManager.isDeviceSecure) { val biometricManager = BiometricManager.from(context) if (biometricManager.canAuthenticate(Authenticators.BIOMETRIC_STRONG) == BIOMETRIC_SUCCESS) { specBuilder.setUserAuthenticationRequired(true) specBuilder.setUserAuthenticationValidityDurationSeconds(10) } else { specBuilder.setUserAuthenticationRequired(false) } } else { specBuilder.setUserAuthenticationRequired(false) } keyGenerator.init(specBuilder.build()); return keyGenerator } private fun authenticate(cipher: Cipher?, callback: BiometricPrompt.AuthenticationCallback) { val executor = ContextCompat.getMainExecutor(context) val biometricPrompt = BiometricPrompt(context, executor, callback) if (cipher != null) { biometricPrompt.authenticate(promptInfo, BiometricPrompt.CryptoObject(cipher)) } else { biometricPrompt.authenticate(promptInfo) } } suspend fun encryptPassphrase(passphrase: String): Pair<ByteArray, ByteArray> { val keyGenerator = initKeyGenerator() val secretKey: SecretKey = keyGenerator.generateKey(); val cipher: Cipher = getCipher(); return suspendCoroutine { cont: Continuation<Pair<ByteArray, ByteArray>> -> try { cipher.init(Cipher.ENCRYPT_MODE, secretKey); cont.resume(Pair(cipher.doFinal(passphrase.encodeToByteArray()), cipher.iv)) } catch (e: UserNotAuthenticatedException) { authenticate(null, object : BiometricPrompt.AuthenticationCallback() { override fun onAuthenticationError(errorCode: Int, errString: CharSequence) { cont.resumeWithException(Exception("Authentication error $errorCode :: $errString")) } override fun onAuthenticationSucceeded(result: BiometricPrompt.AuthenticationResult) { cipher.init(Cipher.ENCRYPT_MODE, secretKey); cont.resume(Pair(cipher.doFinal(passphrase.encodeToByteArray()), cipher.iv)) } }) } } } suspend fun decryptPassphrase(cipherText: ByteArray, iv: ByteArray): String { val keyStore = KeyStore.getInstance(ANDROID_KEYSTORE); keyStore.load(null); val secretKeyEntry = keyStore.getEntry(KEYSTORE_ALIAS, null) as KeyStore.SecretKeyEntry val secretKey = secretKeyEntry.secretKey val cipher: Cipher = getCipher(); return suspendCoroutine { cont: Continuation<String> -> try { cipher.init(Cipher.DECRYPT_MODE, secretKey, GCMParameterSpec(128, iv)) val plainText = cipher.doFinal(cipherText) cont.resume(plainText.toString(Charset.forName("UTF-8"))) } catch (e: UserNotAuthenticatedException) { authenticate(null, object : BiometricPrompt.AuthenticationCallback() { override fun onAuthenticationError(errorCode: Int, errString: CharSequence) { cont.resumeWithException(Exception("Authentication error $errorCode :: $errString")) } override fun onAuthenticationSucceeded(result: BiometricPrompt.AuthenticationResult) { cipher.init(Cipher.DECRYPT_MODE, secretKey, GCMParameterSpec(128, iv)) val plainText = cipher.doFinal(cipherText) cont.resume(plainText.toString(Charset.forName("UTF-8"))) } }) } } } }
41.546667
108
0.68389
0be05d4a2cf8a6a79eafd93aa3b055ae54cbe534
5,435
js
JavaScript
lib/nontree.js
calvinmetcalf/nontree
66b161dfb5c560e7f02366a91a095aacf106e41e
[ "MIT" ]
2
2015-07-02T21:49:36.000Z
2017-12-13T15:24:26.000Z
lib/nontree.js
calvinmetcalf/nontree
66b161dfb5c560e7f02366a91a095aacf106e41e
[ "MIT" ]
null
null
null
lib/nontree.js
calvinmetcalf/nontree
66b161dfb5c560e7f02366a91a095aacf106e41e
[ "MIT" ]
null
null
null
'use strict'; function getMid(box) { var dif = [(box[2]-box[0])/3,(box[3]-box[1])/3]; return [[box[0]+dif[0],box[1]+dif[1]],[box[2]-dif[0],box[3]-dif[1]]]; } var tiles = [ ['a','b','c'], ['f','e','d'], ['g','h','i'] ]; function whichNon(coord, mid, prev) { var x,y; if (coord[0] < mid[0][0]) { x = 0; } else if (coord[0] > mid[1][0]) { x = 2; } else{ x = 1; } if (coord[1] < mid[0][1]) { y = 2; } else if (coord[1] > mid[1][1]) { y = 0; } else{ y = 1; } return normilize(prev, tiles[y][x]); } function normilize(prev, current) { var flipx = 0; var flipy = 0; var i = 0; var len = prev.length; while(i<len) { if (~['b','e','h'].indexOf(prev[i])) { flipy+=1; } if (~['f','e','d'].indexOf(prev[i])) { flipx+=1; } i++; } return normalization[Boolean(flipx % 2)][Boolean(flipy % 2)][current]; } function newBox(non, oldBox, mid, prev) { var out = [0,0,0,0]; var normilizedNon = normilize(prev, non); if (~['a','b','c'].indexOf(normilizedNon)) { out[1]=mid[1][1]; out[3]=oldBox[3]; } else if (~['f','e','d'].indexOf(normilizedNon)) { out[1]=mid[0][1]; out[3]=mid[1][1]; } else{ out[1]=oldBox[1]; out[3]=mid[0][1]; } if (~['a','f','g'].indexOf(normilizedNon)) { out[0]=oldBox[0]; out[2]=mid[0][0]; } else if (~['b','e','h'].indexOf(normilizedNon)) { out[0] = mid[0][0]; out[2] = mid[1][0]; } else{ out[0] = mid[1][0]; out[2] = oldBox[2]; } return out; } exports.toNon = toNon; function toNon(coords, maxDepth, box) { var depth = -1; var out = ''; var current, mid, prev; while (++depth < maxDepth) { mid = getMid(box); prev = current; current = whichNon(coords, mid, out); box = newBox(current, box, mid, out); out += current; } return out; } exports.fromNon = fromNon; function fromNon(non, range) { var depth = non.length; var i = -1; var letter,prev,mid; while (++i < depth) { prev = letter; letter = non[i]; mid = getMid(range); range = newBox(letter, range, mid, non.slice(0, i)); } return range; } exports.next = next; function next(non) { if (!non.length) { return non; } var i = non.length; while (i--) { if (non.charCodeAt(i) < 105) { return non.slice(0,i ) + String.fromCharCode(non.charCodeAt(i) + 1) + non.slice(i + 1); } else if (non.charCodeAt(i)===105) { non = non.slice(0, i); } else{ throw new Error('invalid tile name'); } } } exports.whichChildren = whichChildren; function whichChildren(non, bbox, searchDepth, range) { var children = [ non + 'a', non + 'b', non + 'c', non + 'd', non + 'e', non + 'f', non + 'g', non + 'h', non + 'i' ]; var full = []; var partial = []; children.forEach(function(child) { var childBox = fromNon(child, range); if (contains(bbox, childBox)) { full.push(child); } else if (intersects(childBox, bbox)) { if (child.length === searchDepth) { full.push(child); } else { partial.push(child); } } }); return { full: full, partial: partial, id: non }; } var normalization = { true:{ true:{ c:'g', b:'h', a:'i', f:'d', e:'e', d:'f', i:'a', h:'b', g:'c' }, false:{ c:'a', b:'b', a:'c', f:'d', e:'e', d:'f', i:'g', h:'h', g:'i' } }, false:{ true:{ a:'g', b:'h', c:'i', d:'d', e:'e', f:'f', g:'a', h:'b', i:'c' }, false:{ a:'a', b:'b', c:'c', d:'d', e:'e', f:'f', g:'g', h:'h', i:'i' } } }; function sort(a, b){ return a.num - b.num; } exports.extent = extent; function extent(bbox, range, maxPieces, precision){ var todo = ['']; var done = []; var current, newTodo, tempTodo, len, i, item; while(todo.length){ len = todo.length; i = -1; newTodo = new Array(len); while (++i < len) { newTodo[i] = whichChildren(todo[i], bbox, precision, range); } todo = []; tempTodo = []; len = newTodo.length; i = -1; while (++i < len) { item = newTodo[i]; if(item.full.length ===1 && !item.partial.length){ done.push(item.full[0]); }else if(!item.full.length && item.partial.length ===1){ todo.push(item.partial[0]); }else{ item.num = item.full.length + item.partial.length; tempTodo.push(item); } } if(tempTodo.length){ tempTodo.sort(sort); i = -1; len = tempTodo.length; while(++i < len){ current = tempTodo[i]; if((current.num + todo.length + done.length) > maxPieces){ done.push(current.id); }else{ done = done.concat(current.full); todo = todo.concat(current.partial); } } } } return done; } exports.deA = deA; function deA(a) { while (a.length) { if (a[a.length - 1] === 'a') { a = a.slice(0, -1); } else { return a; } } return a; } //from rbush function contains(a, b) { return a[0] <= b[0] && a[1] <= b[1] && b[2] <= a[2] && b[3] <= a[3]; } function intersects(a, b) { return b[0] < a[2] && b[1] < a[3] && b[2] > a[0] && b[3] > a[1]; }
20.12963
93
0.478013
7e756a0852a1c7306d52450129b5223e7518c97d
562
kt
Kotlin
runtime/runtime-core/jvm/src/aws/smithy/kotlin/runtime/content/FileContent.kt
AlexandreBrown/smithy-kotlin
1a194904d84cc51f3c65836dad3a789879028a9c
[ "Apache-2.0" ]
9
2021-08-31T14:12:27.000Z
2022-03-17T13:36:48.000Z
runtime/runtime-core/jvm/src/aws/smithy/kotlin/runtime/content/FileContent.kt
AlexandreBrown/smithy-kotlin
1a194904d84cc51f3c65836dad3a789879028a9c
[ "Apache-2.0" ]
135
2021-08-30T16:34:03.000Z
2022-03-31T21:26:17.000Z
runtime/runtime-core/jvm/src/aws/smithy/kotlin/runtime/content/FileContent.kt
AlexandreBrown/smithy-kotlin
1a194904d84cc51f3c65836dad3a789879028a9c
[ "Apache-2.0" ]
6
2021-09-05T22:28:25.000Z
2022-02-28T17:15:01.000Z
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ package aws.smithy.kotlin.runtime.content import aws.smithy.kotlin.runtime.io.SdkByteReadChannel import aws.smithy.kotlin.runtime.io.readChannel import java.io.File /** * ByteStream backed by a local [file] */ public class FileContent( public val file: File, ) : ByteStream.ReplayableStream() { override val contentLength: Long get() = file.length() override fun newReader(): SdkByteReadChannel = file.readChannel() }
23.416667
69
0.729537
85f581f375f77ea3e30cf5d65982382d9a7b072d
27,727
c
C
src/main.c
JocelynTissot/Temps_solaire_vrai_Pebble
35b2d84fb59ef5f183ef85bba6c9b2ea40e1fac6
[ "MIT" ]
null
null
null
src/main.c
JocelynTissot/Temps_solaire_vrai_Pebble
35b2d84fb59ef5f183ef85bba6c9b2ea40e1fac6
[ "MIT" ]
null
null
null
src/main.c
JocelynTissot/Temps_solaire_vrai_Pebble
35b2d84fb59ef5f183ef85bba6c9b2ea40e1fac6
[ "MIT" ]
null
null
null
#include <pebble.h> #include "my_math.h" #include "reglages.h" static Window *s_main_window; static TextLayer *s_date_layer; static TextLayer *s_time_layer; static TextLayer *s_text_solar_layer; static TextLayer *s_solar_layer; static TextLayer *s_gmtime_layer; static TextLayer *s_text_eot_layer; static TextLayer *s_eot_layer; static TextLayer *s_text_longitude_difference_layer; static TextLayer *s_longitude_difference_h_layer; static TextLayer *s_longitude_difference_d_layer; static TextLayer *s_text_battery_layer; static TextLayer *s_battery_layer; static TextLayer *s_text_posAJour_layer; static TextLayer *s_posAJour_layer; time_t clock_time_t = 0; time_t lastTime; time_t lastTime2; int posAJour; time_t utc_time_t = 0; time_t solar_time_t = 0; int32_t corr_eotd_received; double corr_eotd = 0; double eotd; int32_t longitude_received; float longitude; float longitude_difference; int long_dif_h; int long_dif_hm; int long_dif_hs; int long_dif_d; int long_dif_dm; int long_dif_ds; struct tm clock_time_tm = { .tm_hour = 0, .tm_min = 0 }; struct tm utc_time_tm = { .tm_hour = 0, .tm_min = 0 }; struct tm solar_time_tm = { .tm_hour = 0, .tm_min = 0 }; int32_t timezoneOffset; int32_t time_zone; int eotMinInt; int eotSecInt; static void update_time(); static void affichage(); static void eot(); static void long_dif(); static void solar_time(); static void handle_battery(BatteryChargeState charge_state) { static char battery_text[] = "charge"; #if defined(PBL_SDK_3) if (charge_state.is_charging) { snprintf(battery_text, sizeof(battery_text), "charge"); text_layer_set_text_color(s_text_battery_layer, GColorGreen); text_layer_set_text_color(s_battery_layer, GColorGreen); } else { if (charge_state.charge_percent < 20){ text_layer_set_text_color(s_text_battery_layer, GColorRed); text_layer_set_text_color(s_battery_layer, GColorRed); } else{ text_layer_set_text_color(s_text_battery_layer, GColorWhite); text_layer_set_text_color(s_battery_layer, GColorWhite); } snprintf(battery_text, sizeof(battery_text), "%d%%", charge_state.charge_percent); } #elif defined(PBL_SDK_2) if (charge_state.is_charging) { snprintf(battery_text, sizeof(battery_text), "charge"); } else { snprintf(battery_text, sizeof(battery_text), "%d%%", charge_state.charge_percent); } text_layer_set_text_color(s_text_battery_layer, GColorWhite); text_layer_set_text_color(s_battery_layer, GColorWhite); #endif text_layer_set_text(s_battery_layer, battery_text); } static void send_request(int command) { Tuplet command_tuple = TupletInteger(0 /*KEY_COMMAND*/ , command); Tuplet index_tuple = TupletInteger(1 /*KEY_INDEX*/, 0 /*entryIndex*/); DictionaryIterator *iter; app_message_outbox_begin(&iter); if (iter == NULL) return; dict_write_tuplet(iter, &command_tuple); dict_write_tuplet(iter, &index_tuple); dict_write_end(iter); app_message_outbox_send(); } static void affichage(){ // Create a long-lived buffer static char buffer_date[] = "jj.mm.aaaa"; static char buffer_t[] = "00:00"; static char buffer_gmt[] = "XXX 00:00"; static char buffer_text_solar[] = "Temps solaire vrai"; static char buffer_solar[] = "XXXXxx 00:00"; static char buffer_text_eot[] = "Equation du temps"; static char buffer_eot[] = "000:000X"; static char buffer_text_longitude_difference[] = "Différence de long."; static char buffer_longitude_difference_h[] = "---h--m--s"; static char buffer_longitude_difference_d[] = "---°--'--"; static char buffer_text_battery[] = "Bat."; static char buffer_text_posAJour[] = "Pos.\nM.àJ."; static char buffer_posAJour[] = "+ -h"; // Write the current hours and minutes into the buffer strftime(buffer_date, sizeof("jj.mm.aaaa"), "%e.%m.%y", &clock_time_tm); strftime(buffer_t, sizeof("00:00"), "%k:%M", &clock_time_tm); strftime(buffer_gmt, sizeof("XXX 00:00"), "UTC %k:%M", &utc_time_tm); snprintf(buffer_text_solar, sizeof("Temps solaire vrai"), "Temps solaire vrai"); strftime(buffer_solar, sizeof("XXXXxx 00:00"), "%k:%M", &solar_time_tm); snprintf(buffer_text_longitude_difference, sizeof("Différence de long."), "Différence de long."); if ((long_dif_h == 0) && (long_dif_hm == 0)){ snprintf(buffer_longitude_difference_h, sizeof("SSs"), "%ds", long_dif_hs); } else if (long_dif_h == 0){ snprintf(buffer_longitude_difference_h, sizeof("MMm SSs"), "%dm %ds", long_dif_hm, long_dif_hs); } else { snprintf(buffer_longitude_difference_h, sizeof("XHHhMMmSSs"), "%dh%dm%ds", long_dif_h, long_dif_hm, long_dif_hs); } if ((long_dif_d == 0) && (long_dif_dm == 0)){ snprintf(buffer_longitude_difference_d, sizeof("SSX"), "%d\"", long_dif_ds); } else if (long_dif_d == 0){ snprintf(buffer_longitude_difference_d, sizeof("MM' SSX"), "%d' %d\"", long_dif_dm, long_dif_ds); } else { snprintf(buffer_longitude_difference_d, sizeof("XDD°MM'SSX"), "%d°%d'%d\"", long_dif_d, long_dif_dm, long_dif_ds); } snprintf(buffer_text_eot, sizeof("Equation du temps"), "Equation du temps"); if ( eotMinInt == 0) { snprintf(buffer_eot, sizeof("000X"), "%ds", eotSecInt); } else { snprintf(buffer_eot, sizeof("000:000X"), "%dm %ds", eotMinInt , eotSecInt); } snprintf(buffer_text_battery, sizeof("Bat."), "Bat."); snprintf(buffer_text_posAJour, sizeof("Pos.\nM.àJ."), "Pos.\nM.àJ."); if (posAJour > 9){ snprintf(buffer_posAJour, sizeof("+ -h"), "+ 9h");} else{ snprintf(buffer_posAJour, sizeof("+ -h"), "+ %dh", posAJour); } // Display this time on the TextLayer text_layer_set_text(s_date_layer, buffer_date); text_layer_set_text(s_time_layer, buffer_t); text_layer_set_text(s_gmtime_layer, buffer_gmt); text_layer_set_text(s_text_solar_layer, buffer_text_solar); text_layer_set_text(s_solar_layer, buffer_solar); text_layer_set_text(s_text_longitude_difference_layer, buffer_text_longitude_difference); text_layer_set_text(s_longitude_difference_h_layer, buffer_longitude_difference_h); text_layer_set_text(s_longitude_difference_d_layer, buffer_longitude_difference_d); text_layer_set_text(s_text_eot_layer, buffer_text_eot); text_layer_set_text(s_eot_layer, buffer_eot); text_layer_set_text(s_text_battery_layer, buffer_text_battery); text_layer_set_text(s_text_posAJour_layer, buffer_text_posAJour); text_layer_set_text(s_posAJour_layer, buffer_posAJour); } static void update_time() { // Get a tm structure clock_time_t = time(NULL); clock_time_tm = *localtime(&clock_time_t); #if defined(PBL_SDK_3) utc_time_t = clock_time_t; #elif defined(PBL_SDK_2) utc_time_t = clock_time_t + timezoneOffset; #endif #if defined(PBL_SDK_3) utc_time_tm = *gmtime(&utc_time_t); #elif defined(PBL_SDK_2) utc_time_tm = *localtime(&utc_time_t); #endif eot(); long_dif(); solar_time(); //solar_time_tm = *localtime(&solar_time_t); solar_time_tm = *gmtime (&solar_time_t); if (solar_time_tm.tm_min >= 60) { solar_time_tm.tm_min -= 60; solar_time_tm.tm_hour += 1; } if (solar_time_tm.tm_hour == 24) { solar_time_tm.tm_hour = 0; } if (solar_time_tm.tm_hour > 24) { solar_time_tm.tm_hour = solar_time_tm.tm_hour - 24; } if (solar_time_tm.tm_hour < 0) { solar_time_tm.tm_hour = solar_time_tm.tm_hour + 24; } posAJour = ((clock_time_t / 3600.0) - (lastTime / 60.0)); //posAJour = ((clock_time_t / 60)-(lastTime)); //posAJour = 2; // test #if defined(PBL_SDK_3) if (posAJour > 4)/*(posAJour > (INTERV_MAJ_DONNEE / 60) - (INTERV_MAJ_DONNEE_APRES_ECHEC / 60))*/ { text_layer_set_text_color(s_text_posAJour_layer, GColorRed); text_layer_set_text_color(s_posAJour_layer, GColorRed);} else{ text_layer_set_text_color(s_text_posAJour_layer, GColorWhite); text_layer_set_text_color(s_posAJour_layer, GColorWhite);} #elif defined(PBL_SDK_2) text_layer_set_text_color(s_text_posAJour_layer, GColorWhite); text_layer_set_text_color(s_posAJour_layer, GColorWhite); #endif /* if (((lastTime + (INTERV_MAJ_DONNEE)) < (clock_time_t / 60)) && ((lastTime2 + (INTERV_MAJ_DONNEE_APRES_ECHEC)) < (clock_time_t / 60))) { //Vibreur //vibes_double_pulse(); lastTime2 = (clock_time_t / 60); send_request(0); // request data refresh from phone JS } */ affichage(); } /****************** APPMESSAGE STUFF *******************/ enum { LONGITUDE = 2, OFFSET_TIMEZONE = 42, TIME_ZONE = 43, CORR_EOT = 45 }; void in_received_handler(DictionaryIterator *received, void *ctx) { APP_LOG(APP_LOG_LEVEL_DEBUG, "in_received_handler()"); Tuple *longitude_tuple = dict_find(received, LONGITUDE); Tuple *timezoneOffset_tuple = dict_find(received, OFFSET_TIMEZONE); Tuple *time_zone_tuple = dict_find(received, TIME_ZONE); Tuple *corr_eot_tuple = dict_find(received, CORR_EOT); //Vibreur //vibes_short_pulse(); APP_LOG(APP_LOG_LEVEL_DEBUG, "Received from phone:"); if (longitude_tuple) { longitude_received = longitude_tuple->value->int32; longitude = longitude_received / 1000000.0; } if (timezoneOffset_tuple) { timezoneOffset = timezoneOffset_tuple->value->int32; } if (time_zone_tuple) { time_zone = time_zone_tuple->value->int32; } if (corr_eot_tuple) { corr_eotd_received = corr_eot_tuple->value->int32; corr_eotd = corr_eotd_received / 1000000.0; } //longitude = 8;//test if (longitude > -181 && longitude < 181 && timezoneOffset > (-15 * 3600) && timezoneOffset < (17 * 3600) && time_zone > (3600 * -12) && time_zone < (3600 * 14) && corr_eotd > -30 && corr_eotd < 30) { lastTime = clock_time_t / 60; } else { // lecture des valeurs sauvegardées si elle existent, sinon: valeur par defaut longitude = persist_exists(AD_MEM_LONGITUDE) ? persist_read_int(AD_MEM_LONGITUDE) : VAL_DEFAUT_LONGITUDE; longitude = longitude / 10000; timezoneOffset = persist_exists(AD_MEM_TIMEZONEOFFSET) ? persist_read_int(AD_MEM_TIMEZONEOFFSET) : VAL_DEFAUT_TIMEZONEOFFSET; time_zone = persist_exists(AD_MEM_TIME_ZONE) ? persist_read_int(AD_MEM_TIME_ZONE) : VAL_DEFAUT_TIME_ZONE; corr_eotd = persist_exists(AD_MEM_CORR_EOTD) ? persist_read_int(AD_MEM_CORR_EOTD) : VAL_DEFAUT_CORR_EOTD; corr_eotd = corr_eotd / 100; lastTime = persist_exists(AD_MEM_LASTTIME) ? persist_read_int(AD_MEM_LASTTIME) : VAL_DEFAUT_LASTTIME; } update_time(); } void in_dropped_handler(AppMessageResult reason, void *context) { APP_LOG(APP_LOG_LEVEL_DEBUG, "Watch dropped data."); } void out_sent_handler(DictionaryIterator *sent, void *ctx) { APP_LOG(APP_LOG_LEVEL_DEBUG, "Message sent to phone."); } void out_failed_handler(DictionaryIterator *failed, AppMessageResult reason, void *ctx) { APP_LOG(APP_LOG_LEVEL_DEBUG, "Message FAILED to send to phone."); } static void eot(){ /* bbb = 367 * The_Year - 730531.5 ccc = int((7 * int(The_Year + (The_Month + 9) / 12)) / 4) ddd = int(275 * The_Month / 9) + The_Day D2000 = bbb - ccc + ddd + (The_Hour + The_Minute / 60 + The_Second / 3600) / 24 Cycle = int(D2000 / 365.25) Theta = 0.0172024 * (D2000 - 365.25 * Cycle) Average = 0.00526 Amp1 = 7.36303 - Cycle * 9e-05 Amp2 = 9.92465 - Cycle * 0.00014 Phi1 = 3.07892 + Cycle * -0.00019 Phi2 = -1.38995 + Cycle * 0.00013 EoT1 = Amp1 * sin(1 * (Theta + Phi1)) EoT2 = Amp2 * sin(2 * (Theta + Phi2)) EoT3 = 0.3173 * sin(3 * (Theta - 0.94686)) EoT4 = 0.21922 * sin(4 * (Theta - 0.60716)) EoT = Average + EoT1 + EoT2 + EoT3 + EoT4 */ //int eotMinInt; double eotSec; double j1970; double d2000; int cycle; double theta; double average; double amp1; double amp2; double phi1; double phi2; double eot1; double eot2; double eot3; double eot4; j1970 = utc_time_t/(3600.0F*24.0F); d2000 = j1970 - 11322.5F; cycle = d2000 / 365.25F; theta = 0.0172024F * (d2000 - 365.25F * cycle); average = 0.00526F; amp1 = 7.36303F - cycle * 9.0e-05; amp2 = 9.92465F - cycle * 0.00014F; phi1 = 3.07892F + cycle * -0.00019F; phi2 = -1.38995F + cycle * 0.00013F; //Calcul de l'équation du temps eot1 = amp1 * my_sin(1.0F * (theta + phi1)); eot2 = amp2 * my_sin(2.0F * (theta + phi2)); eot3 = 0.3173F* my_sin(3.0F * (theta - 0.94686F)); eot4 = 0.21922F * my_sin(4.0F * (theta - 0.60716F)); eotd = average + eot1 + eot2 + eot3 + eot4 + corr_eotd; //eotd = corr_eotd; //inversion du signe eotd = -eotd; //Test des arrondis //eotd = 1.53; eotMinInt = (int)eotd; eotSec = (eotd - eotMinInt) * 60.0; //Arrondi des secondes if (eotd > 0){ if ((eotSec - (int)eotSec) >= 0.5) { eotSec = my_floor((eotd - eotMinInt)*60)+1; if (eotSec >= 60) { eotSec = 0; eotMinInt = eotMinInt + 1; } } else { eotSec = my_floor((eotd - eotMinInt)*60); } if ((eotSec < 0) && eotMinInt != 0) { eotSecInt = -eotSec; } else{ eotSecInt = eotSec; } } else { //Equation du temps en positif pour l'arrondi eotSec = -eotSec; eotMinInt = -eotMinInt; eotd = -eotd; //Arrondi des secondes if ((eotSec - (int)eotSec) >= 0.5) { eotSec = my_floor((eotd - eotMinInt)*60)+1; if (eotSec >= 60) { eotSec = 0; eotMinInt = eotMinInt + 1; } } else { eotSec = my_floor((eotd - eotMinInt)*60); } //Remise de l équation du temps en négatif eotSec = -eotSec; eotMinInt = -eotMinInt; eotd = -eotd; //Si eotSec est négatif et eotMinInt n'est pas null, supprimer le signe - if ((eotSec < 0) && eotMinInt != 0) { eotSecInt = -eotSec; } else{ eotSecInt = eotSec; } } } static void long_dif(){ longitude_difference = (time_zone / 3600.0 * 15.0) - (longitude); //longitude_difference = (longitude) - (time_zone / 3600.0 * 15.0); long_dif_d = my_floor(longitude_difference); long_dif_dm = my_floor((longitude_difference - long_dif_d) * 60.0); long_dif_ds = my_floor((((longitude_difference - long_dif_d) * 60.0) - long_dif_dm)*60.0); if ((long_dif_dm < 0) && (long_dif_d != 0)){ long_dif_dm = -long_dif_dm; } if ((long_dif_ds < 0) && ((long_dif_dm != 0) || (long_dif_d != 0))){ long_dif_ds = -long_dif_ds; } long_dif_h = my_floor(longitude_difference / 15.0); long_dif_hm = my_floor(((longitude_difference / 15.0) - long_dif_h) * 60.0); long_dif_hs = my_floor(((((longitude_difference / 15.0) - long_dif_h) * 60.0) - long_dif_hm)*60.0); if ((long_dif_hm < 0) && (long_dif_h != 0)){ long_dif_hm = -long_dif_hm; } if ((long_dif_hs < 0) && ((long_dif_hm != 0) || (long_dif_h != 0))){ long_dif_hs = -long_dif_hs; } } static void solar_time(){ //solar_time_t = utc_time_t + time_zone + (eotd * 60.0) + (longitude_difference * 4.0 * 60.0); solar_time_t = utc_time_t + time_zone - (eotd * 60.0) - (longitude_difference * 4.0 * 60.0); } static void main_window_load(Window *window) { window_set_background_color(s_main_window, GColorBlack); // Create date TextLayer s_date_layer = text_layer_create(GRect(0, -2, 144, 24)); text_layer_set_background_color(s_date_layer, GColorClear); #if defined(PBL_SDK_3) text_layer_set_text_color(s_date_layer, GColorCadetBlue); #elif defined(PBL_SDK_2) text_layer_set_text_color(s_date_layer, GColorWhite); #endif text_layer_set_text(s_date_layer, "--.--.----"); // Create time TextLayer s_time_layer = text_layer_create(GRect(0, 15, 144, 28)); text_layer_set_background_color(s_time_layer, GColorClear); text_layer_set_text_color(s_time_layer, GColorWhite); text_layer_set_text(s_time_layer, "--:--"); // Create gmtime TextLayer s_gmtime_layer = text_layer_create(GRect(0, 46, 144, 18)); text_layer_set_background_color(s_gmtime_layer, GColorClear); #if defined(PBL_SDK_3) text_layer_set_text_color(s_gmtime_layer, GColorCadetBlue); #elif defined(PBL_SDK_2) text_layer_set_text_color(s_gmtime_layer, GColorWhite); #endif text_layer_set_text(s_gmtime_layer, "GMT --:--"); // Create solar_text TextLayer s_text_solar_layer = text_layer_create(GRect(0, 56, 144, 20)); text_layer_set_background_color(s_text_solar_layer, GColorClear); #if defined(PBL_SDK_3) text_layer_set_text_color(s_text_solar_layer, GColorYellow); #elif defined(PBL_SDK_2) text_layer_set_text_color(s_text_solar_layer, GColorWhite); #endif text_layer_set_text(s_text_solar_layer, "Temps solaire vrai"); // Create solar TextLayer s_solar_layer = text_layer_create(GRect(0, 68, 144, 24)); text_layer_set_background_color(s_solar_layer, GColorClear); #if defined(PBL_SDK_3) text_layer_set_text_color(s_solar_layer, GColorYellow); #elif defined(PBL_SDK_2) text_layer_set_text_color(s_solar_layer, GColorWhite); #endif text_layer_set_text(s_solar_layer, "--:--"); // Create text_longitude_difference TextLayer s_text_longitude_difference_layer = text_layer_create(GRect(0, 90, 144, 21)); text_layer_set_background_color(s_text_longitude_difference_layer, GColorClear); #if defined(PBL_SDK_3) text_layer_set_text_color(s_text_longitude_difference_layer, GColorGreen); #elif defined(PBL_SDK_2) text_layer_set_text_color(s_text_longitude_difference_layer, GColorWhite); #endif text_layer_set_text(s_text_longitude_difference_layer, "Différence de long."); // Create longitude_difference_h TextLayer s_longitude_difference_h_layer = text_layer_create(GRect(-2, 108, 77, 18)); text_layer_set_background_color(s_longitude_difference_h_layer, GColorClear); #if defined(PBL_SDK_3) text_layer_set_text_color(s_longitude_difference_h_layer, GColorGreen); #elif defined(PBL_SDK_2) text_layer_set_text_color(s_longitude_difference_h_layer, GColorWhite); #endif text_layer_set_text(s_longitude_difference_h_layer, "---h --m --s"); // Create longitude_difference_d TextLayer s_longitude_difference_d_layer = text_layer_create(GRect(70, 108, 77, 18)); text_layer_set_background_color(s_longitude_difference_d_layer, GColorClear); #if defined(PBL_SDK_3) text_layer_set_text_color(s_longitude_difference_d_layer, GColorGreen); #elif defined(PBL_SDK_2) text_layer_set_text_color(s_longitude_difference_d_layer, GColorWhite); #endif text_layer_set_text(s_longitude_difference_d_layer, "---° --m --s"); // Create text_eot TextLayer s_text_eot_layer = text_layer_create(GRect(0, 126, 144, 20)); text_layer_set_background_color(s_text_eot_layer, GColorClear); #if defined(PBL_SDK_3) text_layer_set_text_color(s_text_eot_layer, GColorBrilliantRose); #elif defined(PBL_SDK_2) text_layer_set_text_color(s_text_eot_layer, GColorWhite); #endif text_layer_set_text(s_text_eot_layer, "Equation du temps"); // Create eot TextLayer s_eot_layer = text_layer_create(GRect(25, 144, 94, 18)); text_layer_set_background_color(s_eot_layer, GColorClear); #if defined(PBL_SDK_3) text_layer_set_text_color(s_eot_layer, GColorBrilliantRose); #elif defined(PBL_SDK_2) text_layer_set_text_color(s_eot_layer, GColorWhite); #endif text_layer_set_text(s_eot_layer, "---m --s"); // Creat text_battery TextLayer s_text_battery_layer = text_layer_create(GRect(0, 0, 144, 34)); //text_layer_set_text_color(s_text_battery_layer, GColorWhite); text_layer_set_background_color(s_text_battery_layer, GColorClear); text_layer_set_text(s_text_battery_layer, "Bat."); // Creat battery TextLayer s_battery_layer = text_layer_create(GRect(0, 14, 144, 34)); //text_layer_set_text_color(s_battery_layer, GColorWhite); text_layer_set_background_color(s_battery_layer, GColorClear); text_layer_set_text(s_battery_layer, "charge"); // Creat text_posAJour TextLayer s_text_posAJour_layer = text_layer_create(GRect(0, 0, 144, 34)); //text_layer_set_text_color(s_text_posAJour_layer, GColorWhite); text_layer_set_background_color(s_text_posAJour_layer, GColorClear); text_layer_set_text(s_text_posAJour_layer, "Pos.\nM.àJ."); // Creat posAJour TextLayer s_posAJour_layer = text_layer_create(GRect(0, 28, 144, 34)); //text_layer_set_text_color(s_posAJour_layer, GColorWhite); text_layer_set_background_color(s_posAJour_layer, GColorClear); text_layer_set_text(s_posAJour_layer, "+ -h"); // Improve the layout to be more like a watchface text_layer_set_font(s_date_layer, fonts_get_system_font(FONT_KEY_GOTHIC_18_BOLD)); text_layer_set_text_alignment(s_date_layer, GTextAlignmentCenter); text_layer_set_font(s_time_layer, fonts_get_system_font(FONT_KEY_GOTHIC_28_BOLD)); text_layer_set_text_alignment(s_time_layer, GTextAlignmentCenter); text_layer_set_font(s_gmtime_layer, fonts_get_system_font(FONT_KEY_GOTHIC_14_BOLD)); text_layer_set_text_alignment(s_gmtime_layer, GTextAlignmentCenter); text_layer_set_font(s_text_solar_layer, fonts_get_system_font(FONT_KEY_GOTHIC_18_BOLD)); text_layer_set_text_alignment(s_text_solar_layer, GTextAlignmentCenter); text_layer_set_font(s_solar_layer, fonts_get_system_font(FONT_KEY_GOTHIC_24_BOLD)); text_layer_set_text_alignment(s_solar_layer, GTextAlignmentCenter); text_layer_set_font(s_text_longitude_difference_layer, fonts_get_system_font(FONT_KEY_GOTHIC_18_BOLD)); text_layer_set_text_alignment(s_text_longitude_difference_layer, GTextAlignmentCenter); text_layer_set_font(s_longitude_difference_d_layer, fonts_get_system_font(FONT_KEY_GOTHIC_18_BOLD)); text_layer_set_text_alignment(s_longitude_difference_d_layer, GTextAlignmentCenter); text_layer_set_font(s_longitude_difference_h_layer, fonts_get_system_font(FONT_KEY_GOTHIC_18_BOLD)); text_layer_set_text_alignment(s_longitude_difference_h_layer, GTextAlignmentCenter); text_layer_set_font(s_text_eot_layer, fonts_get_system_font(FONT_KEY_GOTHIC_18_BOLD)); text_layer_set_text_alignment(s_text_eot_layer, GTextAlignmentCenter); text_layer_set_font(s_eot_layer, fonts_get_system_font(FONT_KEY_GOTHIC_18_BOLD)); text_layer_set_text_alignment(s_eot_layer, GTextAlignmentCenter); text_layer_set_font(s_text_battery_layer, fonts_get_system_font(FONT_KEY_GOTHIC_14_BOLD)); text_layer_set_text_alignment(s_text_battery_layer, GTextAlignmentLeft); text_layer_set_font(s_battery_layer, fonts_get_system_font(FONT_KEY_GOTHIC_14_BOLD)); text_layer_set_text_alignment(s_battery_layer, GTextAlignmentLeft); text_layer_set_font(s_text_posAJour_layer, fonts_get_system_font(FONT_KEY_GOTHIC_14_BOLD)); text_layer_set_text_alignment(s_text_posAJour_layer, GTextAlignmentRight); text_layer_set_font(s_posAJour_layer, fonts_get_system_font(FONT_KEY_GOTHIC_14_BOLD)); text_layer_set_text_alignment(s_posAJour_layer, GTextAlignmentRight); // Add it as a child layer to the Window's root layer layer_add_child(window_get_root_layer(window), text_layer_get_layer(s_date_layer)); layer_add_child(window_get_root_layer(window), text_layer_get_layer(s_time_layer)); layer_add_child(window_get_root_layer(window), text_layer_get_layer(s_gmtime_layer)); layer_add_child(window_get_root_layer(window), text_layer_get_layer(s_text_solar_layer)); layer_add_child(window_get_root_layer(window), text_layer_get_layer(s_solar_layer)); layer_add_child(window_get_root_layer(window), text_layer_get_layer(s_text_longitude_difference_layer)); layer_add_child(window_get_root_layer(window), text_layer_get_layer(s_longitude_difference_h_layer)); layer_add_child(window_get_root_layer(window), text_layer_get_layer(s_longitude_difference_d_layer)); layer_add_child(window_get_root_layer(window), text_layer_get_layer(s_text_eot_layer)); layer_add_child(window_get_root_layer(window), text_layer_get_layer(s_eot_layer)); layer_add_child(window_get_root_layer(window), text_layer_get_layer(s_text_battery_layer)); layer_add_child(window_get_root_layer(window), text_layer_get_layer(s_battery_layer)); layer_add_child(window_get_root_layer(window), text_layer_get_layer(s_text_posAJour_layer)); layer_add_child(window_get_root_layer(window), text_layer_get_layer(s_posAJour_layer)); // Make sure the time is displayed from the start handle_battery(battery_state_service_peek()); } static void main_window_unload(Window *window) { tick_timer_service_unsubscribe(); battery_state_service_unsubscribe(); // Destroy TextLayer text_layer_destroy(s_date_layer); text_layer_destroy(s_time_layer); text_layer_destroy(s_gmtime_layer); text_layer_destroy(s_text_solar_layer); text_layer_destroy(s_solar_layer); text_layer_destroy(s_text_longitude_difference_layer); text_layer_destroy(s_longitude_difference_d_layer); text_layer_destroy(s_longitude_difference_h_layer); text_layer_destroy(s_text_eot_layer); text_layer_destroy(s_eot_layer); text_layer_destroy(s_text_battery_layer); text_layer_destroy(s_battery_layer); text_layer_destroy(s_text_posAJour_layer); text_layer_destroy(s_posAJour_layer); } static void tick_handler(struct tm *tick_time, TimeUnits units_changed) { update_time(); } static void init() { // lecture des valeurs sauvegardées si elle existent, sinon: valeur par defaut longitude = persist_exists(AD_MEM_LONGITUDE) ? persist_read_int(AD_MEM_LONGITUDE) : VAL_DEFAUT_LONGITUDE; longitude = longitude / 10000; timezoneOffset = persist_exists(AD_MEM_TIMEZONEOFFSET) ? persist_read_int(AD_MEM_TIMEZONEOFFSET) : VAL_DEFAUT_TIMEZONEOFFSET; time_zone = persist_exists(AD_MEM_TIME_ZONE) ? persist_read_int(AD_MEM_TIME_ZONE) : VAL_DEFAUT_TIME_ZONE; corr_eotd = persist_exists(AD_MEM_CORR_EOTD) ? persist_read_int(AD_MEM_CORR_EOTD) : VAL_DEFAUT_CORR_EOTD; corr_eotd = corr_eotd / 100; lastTime = persist_exists(AD_MEM_LASTTIME) ? persist_read_int(AD_MEM_LASTTIME) : VAL_DEFAUT_LASTTIME; app_message_register_inbox_received(in_received_handler); app_message_register_inbox_dropped(in_dropped_handler); app_message_register_outbox_sent(out_sent_handler); app_message_register_outbox_failed(out_failed_handler); app_message_open(app_message_inbox_size_maximum(),app_message_outbox_size_maximum()); // Create main Window element and assign to pointer s_main_window = window_create(); // Set handlers to manage the elements inside the Window window_set_window_handlers(s_main_window, (WindowHandlers) { .load = main_window_load, .unload = main_window_unload }); // Show the Window on the watch, with animated=true window_stack_push(s_main_window, true); // Register with TickTimerService // tick_timer_service_subscribe(SECOND_UNIT, tick_handler); tick_timer_service_subscribe (MINUTE_UNIT, tick_handler); battery_state_service_subscribe(handle_battery); } static void deinit() { //sauvegarde des données if (longitude > -181 && longitude < 181 && timezoneOffset > (-15 * 3600) && timezoneOffset < (17 * 3600) && time_zone > (3600 * -12) && time_zone < (3600 * 14) && corr_eotd > -30 && corr_eotd < 30) { persist_write_int(AD_MEM_LONGITUDE, longitude*10000); persist_write_int(AD_MEM_TIMEZONEOFFSET, timezoneOffset); persist_write_int(AD_MEM_TIME_ZONE, time_zone); persist_write_int(AD_MEM_CORR_EOTD, corr_eotd*100); persist_write_int(AD_MEM_LASTTIME, lastTime); } // Destroy Window window_destroy(s_main_window); } int main(void) { init(); app_event_loop(); deinit(); }
38.034294
199
0.736863
79d08b18ba2473041bc6f209b620bd4349b01f1c
10,941
asm
Assembly
Driver/Task/BNF/bnfClipboard.asm
steakknife/pcgeos
95edd7fad36df400aba9bab1d56e154fc126044a
[ "Apache-2.0" ]
504
2018-11-18T03:35:53.000Z
2022-03-29T01:02:51.000Z
Driver/Task/BNF/bnfClipboard.asm
steakknife/pcgeos
95edd7fad36df400aba9bab1d56e154fc126044a
[ "Apache-2.0" ]
96
2018-11-19T21:06:50.000Z
2022-03-06T10:26:48.000Z
Driver/Task/BNF/bnfClipboard.asm
steakknife/pcgeos
95edd7fad36df400aba9bab1d56e154fc126044a
[ "Apache-2.0" ]
73
2018-11-19T20:46:53.000Z
2022-03-29T00:59:26.000Z
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Copyright (c) GeoWorks 1991 -- All Rights Reserved PROJECT: PC GEOS MODULE: FILE: bnfClipboard.asm AUTHOR: Adam de Boor, Oct 7, 1991 ROUTINES: Name Description ---- ----------- REVISION HISTORY: Name Date Description ---- ---- ----------- Adam 10/7/91 Initial revision DESCRIPTION: Functions to deal with B&F's clipboard file.. Characters are stored out in straight ASCII. I don't know whether lines are \r\n-terminated or just \r-terminated. We'll see. $Id: bnfClipboard.asm,v 1.1 97/04/18 11:58:09 newdeal Exp $ %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ BNF_DEFAULT_CHAR equ '.' udata segment cbEnabled word 0 ; ; Modification time of clipboard when last read in. ; cbLastModified FileDateAndTime udata ends Movable segment resource bnfCat char 'back & forth', 0 clipboardKey char 'clipboard', 0 COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% BNFCBInit %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Initialize our manhandling of the B&F clipboard. CALLED BY: BNFAttach PASS: ds = es = dgroup RETURN: nothing DESTROYED: nothing PSEUDO CODE/STRATEGY: KNOWN BUGS/SIDE EFFECTS/IDEAS: REVISION HISTORY: Name Date Description ---- ---- ----------- ardeb 10/7/91 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ BNFCBInit proc near uses cx, dx, ax, bx, si, bp .enter ; ; See if we've saved a status to the ini file before. We assume ; the user doesn't want the support enabled (principle of least ; surprise) unless we've previously put something in the ini file ; saying it should be on. ; push ds segmov ds, cs, cx ; ds, cx <- cs mov si, offset bnfCat mov dx, offset clipboardKey call InitFileReadBoolean mov cx, FALSE ; assume disabled jc setListState mov_tr cx, ax setListState: pop ds mov ds:[cbEnabled], cx jcxz done ; if disabled, do nothing ; ; If it's actually enabled, hook in the generic clipboard support. ; mov cx, offset BNFCBImport mov dx, offset BNFCBExport call TCBInit done: .leave ret BNFCBInit endp COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% BNFCBExit %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Close down our clipboard support. CALLED BY: BNFDetach PASS: ds = es = dgroup RETURN: nothing DESTROYED: nothing PSEUDO CODE/STRATEGY: KNOWN BUGS/SIDE EFFECTS/IDEAS: REVISION HISTORY: Name Date Description ---- ---- ----------- ardeb 10/7/91 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ BNFCBExit proc near .enter tst ds:[cbEnabled] jz done call TCBExit done: .leave ret BNFCBExit endp COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% BNFCBImport %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Import the current data from tbe B&F clipboard, if it's changed. CALLED BY: TCBImport PASS: nothing RETURN: bx = handle of sharable block holding the text, in the DOS character set. cx = # bytes (0 if nothing imported; excludes null-term) DESTROYED: nothing PSEUDO CODE/STRATEGY: KNOWN BUGS/SIDE EFFECTS/IDEAS: REVISION HISTORY: Name Date Description ---- ---- ----------- ardeb 10/7/91 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ BNFCBImport proc near modified local FileDateAndTime fileSize local dword attrs local 2 dup(FileExtAttrDesc) fileName local PathName uses ax, dx, di, es .enter ; ; Fetch the modification date (so we can decide whether to import ; the text) and the size (so we know how big a buffer to allocate to ; get it) of the current cliboard file. ; mov ss:[attrs][0*FileExtAttrDesc].FEAD_attr, FEA_MODIFICATION lea ax, ss:[modified] mov ss:[attrs][0*FileExtAttrDesc].FEAD_value.offset, ax mov ss:[attrs][0*FileExtAttrDesc].FEAD_value.segment, ss mov ss:[attrs][0*FileExtAttrDesc].FEAD_size, size modified mov ss:[attrs][1*FileExtAttrDesc].FEAD_attr, FEA_SIZE lea ax, ss:[fileSize] mov ss:[attrs][1*FileExtAttrDesc].FEAD_value.offset, ax mov ss:[attrs][1*FileExtAttrDesc].FEAD_value.segment, ss mov ss:[attrs][1*FileExtAttrDesc].FEAD_size, size fileSize lea di, ss:[fileName] segmov es, ss mov bx, BNFAPI_GET_CLIPBOARD_NAME call BNFCall ; dx:ax <- filename mov ds, dx mov_tr dx, ax ; ds:dx <- filename mov ax, FEA_MULTIPLE segmov es, ss lea di, ss:[attrs] ; es:di <- attr array mov cx, length attrs ; cx <- # of attrs call FileGetPathExtAttributes jc returnNothing ; ; Now see if the file's been modified since last we checked. Because ; of how the records are laid out, if we compare the current FDAT_date ; to the last-known and it's greater, or if the current FDAT_time is ; greater than the last-known, the file has been modified. ; segmov ds, dgroup, ax mov ax, ss:[modified].FDAT_date mov bx, ss:[modified].FDAT_time cmp ax, ds:[cbLastModified].FDAT_date ja import cmp bx, ds:[cbLastModified].FDAT_time jbe returnNothing import: ; ; We've decided to import the stuff in the clipboard, so record its ; modification stamp for next time. ; segmov es, dgroup, di mov es:[cbLastModified].FDAT_date, ax mov es:[cbLastModified].FDAT_time, bx ; ; If it's > 64Kb, there's nothing we can do. ; tst ss:[fileSize].high jnz returnNothing ; ; Allocate a sharable block that big. ; mov ax, ss:[fileSize].low inc ax ; room for null-terminator mov cx, ALLOC_DYNAMIC_LOCK or mask HF_SHARABLE call MemAlloc jc returnNothing ; ; Now open the file itself. ; push bx, ax mov al, FileAccessFlags <FE_NONE, FA_READ_ONLY> call FileOpen pop ds jc returnNothingAfterFreeingBuffer ; ; Read the whole file into the buffer. ; mov_tr bx, ax clr dx mov cx, ss:[fileSize].low clr al call FileRead jc returnNothingAfterClosingFileAndFreeingBuffer ; ; Close the beast. ; clr al call FileClose ; ; Null-terminate the buffer and compress its CR-LF pairs to CRs ; mov bx, cx mov {char}ds:[bx], 0 pop bx call TCBConvertCRLFToCR call MemUnlock done: .leave ret ;-------------------- returnNothingAfterClosingFileAndFreeingBuffer: clr al call FileClose returnNothingAfterFreeingBuffer: pop bx call MemFree returnNothing: clr cx jmp done BNFCBImport endp COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% BNFCBExport %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Export the contents of the pc/geos clipboard to B&F CALLED BY: TCBExport PASS: ds = text string to copy to clipboard converted to DOS code page bx = handle of block to which DS points cx = # chars to copy es = dgroup RETURN: nothing DESTROYED: nothing PSEUDO CODE/STRATEGY: KNOWN BUGS/SIDE EFFECTS/IDEAS: REVISION HISTORY: Name Date Description ---- ---- ----------- ardeb 10/7/91 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ BNFCBExport proc near fileName local PathName uses bx, ax, cx, dx, di .enter ; ; Expand CRs to CR-LF pairs. XXX: necessary? ; call TCBConvertCRToCRLF jc done ; ; Fetch the name of the clipboard file we want to modify. ; push ds, es lea di, ss:[fileName] segmov es, ds mov bx, BNFAPI_GET_CLIPBOARD_NAME call BNFCall ; ; Open it and truncate it. ; mov ds, dx mov_tr dx, ax mov ax, (mask FCF_NATIVE or FILE_CREATE_TRUNCATE) shl 8 or \ FileAccessFlags <FE_DENY_WRITE, FA_WRITE_ONLY> call FileCreate jc couldntCreate ; ; Now write all the bytes to it. We don't much care if we run out of ; disk space here. After all, all we can do is truncate the thing, and ; B&F would probably spit-up at that... ; mov bx, ds pop ds, es push bx, dx ; save name for getting FEA_MODIFICATION mov_tr bx, ax clr dx ; ds:dx <- buffer from which to write clr al ; allow errors call FileWrite ; ; Close the file down. Note that some DOSes will actually change the ; modification time during a close, even if we hadn't modified the ; thing, so we always wait until after the close to get the modification ; stamp, which we can usually get w/o opening the darn thing up... ; clr al call FileClose ; ; Now fetch the modification stamp for the file, so we know whether it's ; changed when we come back. ; pop ds, dx mov ax, FEA_MODIFICATION mov di, offset cbLastModified mov cx, size cbLastModified call FileGetPathExtAttributes done: .leave ret couldntCreate: ; ; Just clear the stack and return... ; pop ds jmp done BNFCBExport endp COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% BNFSSetCBSupport %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Take note of a change in the state of the clipboard support list. CALLED BY: MSG_BNF_SET_CB_SUPPORT PASS: ds = es = dgroup cx = TRUE to turn clipboard support on = FALSE to turn clipboard support off. RETURN: nothing DESTROYED: anything PSEUDO CODE/STRATEGY: KNOWN BUGS/SIDE EFFECTS/IDEAS: REVISION HISTORY: Name Date Description ---- ---- ----------- ardeb 10/24/91 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ BNFSetCBSupport method dynamic BNFClass, MSG_BNF_SET_CB_SUPPORT .enter cmp ds:[cbEnabled], cx je done ; just being careful... push ds mov ds:[cbEnabled], cx ; ; Write the state out to the ini file so we remember it next time. ; xchg ax, cx segmov ds, cs, cx ; ds, cx <- code segment mov si, offset bnfCat ; ds:si <- category mov dx, offset clipboardKey ; cx:dx <- key call InitFileWriteBoolean xchg ax, cx ; cx <- enable state again, as this ; is smaller & shorted than testing ; ax... pop ds jcxz disable ; ; User wants to turn the beastie on, so hook in the generic support. ; mov cx, offset BNFCBImport mov dx, offset BNFCBExport call TCBInit done: .leave ret disable: ; ; User wants to turn the beastie off, so unhook the generic support. ; call TCBExit jmp done BNFSetCBSupport endm Movable ends
23.836601
79
0.5898
afa3baeb2b87fa3777b2fad530ff191c22a12488
211
rb
Ruby
db/migrate/20200308003708_add_address_to_vendors.rb
franklee26/appfolio-uber-for-vendors
fe048e8a2a79d48137382504ebd23b1bbccb441c
[ "MIT" ]
2
2021-02-17T03:31:26.000Z
2021-05-18T17:16:23.000Z
db/migrate/20200308003708_add_address_to_vendors.rb
franklee26/appfolio-scheduleme
fe048e8a2a79d48137382504ebd23b1bbccb441c
[ "MIT" ]
13
2020-02-07T06:48:20.000Z
2022-03-30T23:56:41.000Z
db/migrate/20200308003708_add_address_to_vendors.rb
franklee26/appfolio-uber-for-vendors
fe048e8a2a79d48137382504ebd23b1bbccb441c
[ "MIT" ]
null
null
null
class AddAddressToVendors < ActiveRecord::Migration[5.1] def change add_column :vendors, :street_address, :string add_column :vendors, :city, :string add_column :vendors, :state, :string end end
26.375
56
0.729858
0bb8e30ded6e839a96a8ac9f64f609621cb56e4a
2,055
py
Python
S4/S4 Library/simulation/careers/pick_career_by_agent_interaction.py
NeonOcean/Environment
ca658cf66e8fd6866c22a4a0136d415705b36d26
[ "CC-BY-4.0" ]
1
2021-05-20T19:33:37.000Z
2021-05-20T19:33:37.000Z
S4/S4 Library/simulation/careers/pick_career_by_agent_interaction.py
NeonOcean/Environment
ca658cf66e8fd6866c22a4a0136d415705b36d26
[ "CC-BY-4.0" ]
null
null
null
S4/S4 Library/simulation/careers/pick_career_by_agent_interaction.py
NeonOcean/Environment
ca658cf66e8fd6866c22a4a0136d415705b36d26
[ "CC-BY-4.0" ]
null
null
null
from event_testing.resolver import SingleSimResolver from sims4.resources import Types from sims4.tuning.tunable import TunableList, TunableReference from sims4.tuning.tunable_base import GroupNames from traits.trait_tracker import TraitPickerSuperInteraction import services class PickCareerByAgentInteraction(TraitPickerSuperInteraction): INSTANCE_TUNABLES = {'pickable_careers': TunableList(description='\n A list of careers whose available agents will be used to populate\n the picker. When an available agent is selected, the sim actor will\n be placed in the associated career. A career may have multiple\n agents, in which case each will appear and each will correspond to\n that career.\n ', tunable=TunableReference(manager=services.get_instance_manager(Types.CAREER), pack_safe=True), tuning_group=GroupNames.PICKERTUNING, unique_entries=True)} @classmethod def _get_agent_traits_for_career_gen(cls, sim_info, career): career_history = sim_info.career_tracker.career_history (entry_level, _, career_track) = career.get_career_entry_level(career_history, SingleSimResolver(sim_info)) for agent_trait in career_track.career_levels[entry_level].agents_available: yield agent_trait @classmethod def _trait_selection_gen(cls, target): for career in cls.pickable_careers: if target.sim_info.career_tracker.has_career_by_uid(career.guid64): continue yield from cls._get_agent_traits_for_career_gen(target.sim_info, career) def on_choice_selected(self, choice_tag, **kwargs): if choice_tag is None: return sim_info = self.target.sim_info for career in self.pickable_careers: if choice_tag in self._get_agent_traits_for_career_gen(sim_info, career): sim_info.career_tracker.add_career(career(sim_info), post_quit_msg=False) super().on_choice_selected(choice_tag, **kwargs) return
60.441176
583
0.734793
3e60e4f68522e090b96096c93e905b0c7e044bc0
4,873
c
C
test/test-audio.c
Chreece/bluez-alsa
6950e8bb26c471436ba4dc6a2c412a998cffafdf
[ "MIT" ]
null
null
null
test/test-audio.c
Chreece/bluez-alsa
6950e8bb26c471436ba4dc6a2c412a998cffafdf
[ "MIT" ]
null
null
null
test/test-audio.c
Chreece/bluez-alsa
6950e8bb26c471436ba4dc6a2c412a998cffafdf
[ "MIT" ]
null
null
null
/* * test-audio.c * Copyright (c) 2016-2022 Arkadiusz Bokowy * * This file is a part of bluez-alsa. * * This project is licensed under the terms of the MIT license. * */ #include <stdint.h> #include <string.h> #include <check.h> #include "audio.h" #include "shared/defs.h" START_TEST(test_audio_interleave_deinterleave_s16_2le) { const int16_t ch1[] = { 0x0123, 0x1234, 0x2345, 0x3456 }; const int16_t ch2[] = { 0x4567, 0x5678, 0x6789, 0x789A }; int16_t dest[ARRAYSIZE(ch1) + ARRAYSIZE(ch2)]; int16_t dest_ch1[ARRAYSIZE(ch1)]; int16_t dest_ch2[ARRAYSIZE(ch2)]; audio_interleave_s16_2le(ch1, ch2, ARRAYSIZE(ch1), 2, dest); for (size_t i = 0; i < ARRAYSIZE(ch1); i++) { ck_assert_int_eq(dest[i * 2 + 0], ch1[i]); ck_assert_int_eq(dest[i * 2 + 1], ch2[i]); } audio_deinterleave_s16_2le(dest, ARRAYSIZE(ch1), 2, dest_ch1, dest_ch2); ck_assert_int_eq(memcmp(dest_ch1, ch1, sizeof(ch1)), 0); ck_assert_int_eq(memcmp(dest_ch2, ch2, sizeof(ch1)), 0); } END_TEST START_TEST(test_audio_interleave_deinterleave_s32_4le) { const int32_t ch1[] = { 0x01234567, 0x12345678, 0x23456789, 0x3456789A }; const int32_t ch2[] = { 0x456789AB, 0x56789ABC, 0x6789ABCD, 0x789ABCDE }; int32_t dest[ARRAYSIZE(ch1) + ARRAYSIZE(ch2)]; int32_t dest_ch1[ARRAYSIZE(ch1)]; int32_t dest_ch2[ARRAYSIZE(ch2)]; audio_interleave_s32_4le(ch1, ch2, ARRAYSIZE(ch1), 2, dest); for (size_t i = 0; i < ARRAYSIZE(ch1); i++) { ck_assert_int_eq(dest[i * 2 + 0], ch1[i]); ck_assert_int_eq(dest[i * 2 + 1], ch2[i]); } audio_deinterleave_s32_4le(dest, ARRAYSIZE(ch1), 2, dest_ch1, dest_ch2); ck_assert_int_eq(memcmp(dest_ch1, ch1, sizeof(ch1)), 0); ck_assert_int_eq(memcmp(dest_ch2, ch2, sizeof(ch1)), 0); } END_TEST START_TEST(test_audio_scale_s16_2le) { const int16_t mute[] = { 0x0000, 0x0000, 0x0000, 0x0000 }; const int16_t mute_l[] = { 0x0000, 0x2345, 0x0000, (int16_t)0xCDEF }; const int16_t mute_r[] = { 0x1234, 0x0000, (int16_t)0xBCDE, 0x0000 }; const int16_t half[] = { 0x1234 / 2, 0x2345 / 2, (int16_t)0xBCDE / 2, (int16_t)0xCDEF / 2 }; const int16_t half_l[] = { 0x1234 / 2, 0x2345, (int16_t)0xBCDE / 2, (int16_t)0xCDEF }; const int16_t half_r[] = { 0x1234, 0x2345 / 2, (int16_t)0xBCDE, (int16_t)0xCDEF / 2 }; const int16_t in[] = { 0x1234, 0x2345, (int16_t)0xBCDE, (int16_t)0xCDEF }; int16_t tmp[ARRAYSIZE(in)]; memcpy(tmp, in, sizeof(tmp)); audio_scale_s16_2le(tmp, ARRAYSIZE(tmp), 1, 0, 0); ck_assert_int_eq(memcmp(tmp, mute, sizeof(mute)), 0); memcpy(tmp, in, sizeof(tmp)); audio_scale_s16_2le(tmp, ARRAYSIZE(tmp), 1, 1.0, 0); ck_assert_int_eq(memcmp(tmp, in, sizeof(in)), 0); memcpy(tmp, in, sizeof(tmp)); audio_scale_s16_2le(tmp, ARRAYSIZE(tmp), 1, 0.5, 0); ck_assert_int_eq(memcmp(tmp, half, sizeof(half)), 0); memcpy(tmp, in, sizeof(tmp)); audio_scale_s16_2le(tmp, ARRAYSIZE(tmp) / 2, 2, 0, 1.0); ck_assert_int_eq(memcmp(tmp, mute_l, sizeof(mute_l)), 0); memcpy(tmp, in, sizeof(tmp)); audio_scale_s16_2le(tmp, ARRAYSIZE(tmp) / 2, 2, 1.0, 0); ck_assert_int_eq(memcmp(tmp, mute_r, sizeof(mute_r)), 0); memcpy(tmp, in, sizeof(tmp)); audio_scale_s16_2le(tmp, ARRAYSIZE(tmp) / 2, 2, 0.5, 1.0); ck_assert_int_eq(memcmp(tmp, half_l, sizeof(half_l)), 0); memcpy(tmp, in, sizeof(tmp)); audio_scale_s16_2le(tmp, ARRAYSIZE(tmp) / 2, 2, 1.0, 0.5); ck_assert_int_eq(memcmp(tmp, half_r, sizeof(half_r)), 0); } END_TEST START_TEST(test_audio_scale_s32_4le) { const int32_t mute[] = { 0, 0, 0, 0 }; const int32_t mute_l[] = { 0, 0x23456789, 0, 0x00ABCDEF }; const int32_t half[] = { 0x12345678 / 2, 0x23456789 / 2, 0x00123456 / 2, 0x00ABCDEF / 2 }; const int32_t half_r[] = { 0x12345678, 0x23456789 / 2, 0x00123456, 0x00ABCDEF / 2 }; const int32_t in[] = { 0x12345678, 0x23456789, 0x00123456, 0x00ABCDEF }; int32_t tmp[ARRAYSIZE(in)]; memcpy(tmp, in, sizeof(tmp)); audio_scale_s32_4le(tmp, ARRAYSIZE(tmp), 1, 0, 0); ck_assert_int_eq(memcmp(tmp, mute, sizeof(mute)), 0); memcpy(tmp, in, sizeof(tmp)); audio_scale_s32_4le(tmp, ARRAYSIZE(tmp) / 2, 2, 0, 1.0); ck_assert_int_eq(memcmp(tmp, mute_l, sizeof(mute_l)), 0); memcpy(tmp, in, sizeof(tmp)); audio_scale_s32_4le(tmp, ARRAYSIZE(tmp), 1, 0.5, 0); ck_assert_int_eq(memcmp(tmp, half, sizeof(half)), 0); memcpy(tmp, in, sizeof(tmp)); audio_scale_s32_4le(tmp, ARRAYSIZE(tmp) / 2, 2, 1.0, 0.5); ck_assert_int_eq(memcmp(tmp, half_r, sizeof(half_r)), 0); } END_TEST int main(void) { Suite *s = suite_create(__FILE__); TCase *tc = tcase_create(__FILE__); SRunner *sr = srunner_create(s); suite_add_tcase(s, tc); tcase_add_test(tc, test_audio_interleave_deinterleave_s16_2le); tcase_add_test(tc, test_audio_interleave_deinterleave_s32_4le); tcase_add_test(tc, test_audio_scale_s16_2le); tcase_add_test(tc, test_audio_scale_s32_4le); srunner_run_all(sr, CK_ENV); int nf = srunner_ntests_failed(sr); srunner_free(sr); return nf == 0 ? 0 : 1; }
32.925676
93
0.702852
6460ebace85553801a2c132e1939986bd44031d2
571
kt
Kotlin
app/src/main/java/com/github/frapontillo/babylon/list/PostViewHolder.kt
frapontillo/babylon-test
477b8a7735037203dd510d060d440432be49ffc0
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/github/frapontillo/babylon/list/PostViewHolder.kt
frapontillo/babylon-test
477b8a7735037203dd510d060d440432be49ffc0
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/github/frapontillo/babylon/list/PostViewHolder.kt
frapontillo/babylon-test
477b8a7735037203dd510d060d440432be49ffc0
[ "Apache-2.0" ]
null
null
null
package com.github.frapontillo.babylon.list import android.view.View import androidx.recyclerview.widget.RecyclerView import kotlinx.android.extensions.LayoutContainer import kotlinx.android.synthetic.main.post_list_item.* class PostViewHolder(override val containerView: View, private val onPostSelected: OnPostSelected) : RecyclerView.ViewHolder(containerView), LayoutContainer { fun bind(item: PostViewModel) { post_title.text = item.title post_body.text = item.body containerView.setOnClickListener { onPostSelected(item) } } }
33.588235
100
0.782837
22c9b70c40988e963f3e2cc165beefb9b5fe0d16
585
swift
Swift
TwitterDemo/ViewController.swift
JaberJanati/Twitter
54306991991eada9350ee8a2f5a4bfdb1310b292
[ "Apache-2.0" ]
null
null
null
TwitterDemo/ViewController.swift
JaberJanati/Twitter
54306991991eada9350ee8a2f5a4bfdb1310b292
[ "Apache-2.0" ]
3
2016-02-29T02:13:55.000Z
2016-03-23T19:16:02.000Z
TwitterDemo/ViewController.swift
JaberJanati/Twitter
54306991991eada9350ee8a2f5a4bfdb1310b292
[ "Apache-2.0" ]
null
null
null
// // ViewController.swift // TwitterDemo // // Created by The Boss on 2/28/16. // Copyright © 2016 The Boss. All rights reserved. // import UIKit import BDBOAuth1Manager class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func onLoginButton(sender: AnyObject) { } }
20.172414
80
0.675214
b1a92ac07ae8637364b1c8c27c10b2a936429543
4,678
h
C
src/solvers.h
dparo/master-thesis
1580e1566e17ff3103da134b7368de9bf613fcd6
[ "MIT" ]
1
2022-01-07T15:17:35.000Z
2022-01-07T15:17:35.000Z
src/solvers.h
dparo/master-thesis
1580e1566e17ff3103da134b7368de9bf613fcd6
[ "MIT" ]
10
2021-12-22T11:09:06.000Z
2022-01-09T13:17:29.000Z
src/solvers.h
dparo/master-thesis
1580e1566e17ff3103da134b7368de9bf613fcd6
[ "MIT" ]
1
2021-11-04T13:54:04.000Z
2021-11-04T13:54:04.000Z
/* * Copyright (c) 2021 Davide Paro * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #pragma once #if __cplusplus extern "C" { #endif #include "core.h" static const SolverDescriptor MIP_SOLVER_DESCRIPTOR = { "mip", { {"SCRIND", TYPED_PARAM_BOOL, "false", "Enable or disable (default) CPLEX SCRIND and MIPDISPLAY parameters"}, {"NUM_THREADS", TYPED_PARAM_INT32, "0", "Set the number of threads to use. Default 0, means autodetect based " "on the number of cores available"}, {"APPLY_UPPER_CUTOFF", TYPED_PARAM_BOOL, "false", "Apply upper cutoff value (CPX_PARAM_CUTUP) by using the " "zero_reduced_cost_threshold"}, {"APPLY_LOWER_CUTOFF", TYPED_PARAM_BOOL, "true", "Apply lower cutoff value (CPX_PARAM_CUTLO) by using a " "trivially computed lower bound for the objective function"}, {"ENFORCE_STRONG_BRANCHING", TYPED_PARAM_BOOL, "false", "Force CPLEX to opt for strong branching decisions"}, {"APPLY_LB_HEUR", TYPED_PARAM_BOOL, "false", "Apply local branching heuristic (CPX_PARAM_LBHEUR) to try to improve " "new incumbents found during a MIP search."}, {"HEUR_PRICER_MODE", TYPED_PARAM_BOOL, "false", "Behave as an heuristic pricer. Terminate solution process as soon as " "a reduced cost route, without proving its optimality."}, {"INS_HEUR_WARM_START", TYPED_PARAM_BOOL, "true", "Warm start the MIP solver by using an insertion heuristic for " "finding an initial solution"}, {"APPLY_POLISHING_AFTER_WARM_START", TYPED_PARAM_BOOL, "false", "Polish the initial warm start solutions right away before " "beginning " "the Branch&Cut procedure"}, {"AMORTIZED_FRACTIONAL_LABELING", TYPED_PARAM_BOOL, "false", "Amortize the min-cut/max-flow fractional labeling over multiple " "iterations." "Setting this parateter to false essentially enforces exhaustive " "labeling."}, {"GSEC_CUTS", TYPED_PARAM_BOOL, "true", "Enable GSEC cut separation"}, {"GLM_CUTS", TYPED_PARAM_BOOL, "true", "Enable GLM cuts separation"}, {"RCI_CUTS", TYPED_PARAM_BOOL, "true", "Enable RCI cuts separation"}, {"DISABLE_FRACTIONAL_SEPARATION", TYPED_PARAM_BOOL, "false", "Disable any form of labeling and separation for fractional " "solutions. Disables the CPLEX callback entirely."}, {"GSEC_FRAC_CUTS", TYPED_PARAM_BOOL, "true", "Enable GSEC cut separation for fractional solutions. Param " "`GSEC_CUTS` must also be enabled for this to take effect."}, {"GLM_FRAC_CUTS", TYPED_PARAM_BOOL, "true", "Enable GLM cut separation for fractional solutions. Param " "`GLM_CUTS` must also be enabled for this to take effect."}, {"RCI_FRAC_CUTS", TYPED_PARAM_BOOL, "true", "Enable RCI cut separation for fractional solutions. Param " "`RCI_CUTS` must also be enabled for this to take effect."}, {0}, }}; static const SolverDescriptor STUB_SOLVER_DESCRIPTOR = {"stub", { {0}, }}; Solver mip_solver_create(const Instance *instance, SolverTypedParams *tparams, double timelimit, int32_t seed); Solver stub_solver_create(const Instance *instance, SolverTypedParams *tparams, double timelimit, int32_t randomseed); #if __cplusplus } #endif
48.226804
80
0.663531
87bf54b05f31067ed5ba7a7751b4fa4f75579f2c
5,097
swift
Swift
Pomme's Adventure Shared/PhysicsContact.swift
renaudjenny/Pomme-s-Adventure
6403ae56b1cdaf28de0517af318fd7e7bda7908f
[ "MIT" ]
2
2021-03-12T12:13:00.000Z
2021-03-13T19:11:55.000Z
Pomme's Adventure Shared/PhysicsContact.swift
renaudjenny/Pomme-s-Adventure
6403ae56b1cdaf28de0517af318fd7e7bda7908f
[ "MIT" ]
null
null
null
Pomme's Adventure Shared/PhysicsContact.swift
renaudjenny/Pomme-s-Adventure
6403ae56b1cdaf28de0517af318fd7e7bda7908f
[ "MIT" ]
null
null
null
import SpriteKit final class PhysicsContact: NSObject, SKPhysicsContactDelegate { let collisionBetweenMovePlayerAreaAndPlayer: () -> Void let borderNode: SKNode let groundNode: SKNode let playerNode: SKNode let ballHit: (SKNode) -> Void let playerTouched: (SKNode) -> Void let bubbleTouched: (SKNode) -> Void let bonusGathered: (SKNode) -> Void init( collisionBetweenMovePlayerAreaAndPlayer: @escaping () -> Void, borderNode: SKNode, groundNode: SKNode, playerNode: SKNode, ballHit: @escaping (SKNode) -> Void, playerTouched: @escaping (SKNode) -> Void, bubbleTouched: @escaping (SKNode) -> Void, bonusGathered: @escaping (SKNode) -> Void ) { self.collisionBetweenMovePlayerAreaAndPlayer = collisionBetweenMovePlayerAreaAndPlayer self.borderNode = borderNode self.groundNode = groundNode self.playerNode = playerNode self.ballHit = ballHit self.playerTouched = playerTouched self.bubbleTouched = bubbleTouched self.bonusGathered = bonusGathered super.init() } func didBegin(_ contact: SKPhysicsContact) { guard let nodeA = contact.bodyA.node, let nodeB = contact.bodyB.node else { return } switch (nodeA.name, nodeB.name) { case let (.some(ballName), _) where Ball.AppleType.names.contains(ballName): collisionBetween(ball: nodeA, object: nodeB) case let (_, .some(ballName)) where Ball.AppleType.names.contains(ballName): collisionBetween(ball: nodeB, object: nodeA) case let (.some(bonusName), _) where Bonus.GemType.names.contains(bonusName): bonusGathered(nodeA) case let (_, .some(bonusName)) where Bonus.GemType.names.contains(bonusName): bonusGathered(nodeB) #if os(iOS) || os(tvOS) case (NodeName.movePlayerArea.rawValue, _), (_, NodeName.movePlayerArea.rawValue): collisionBetweenMovePlayerAreaAndPlayer() #endif default: break } } func collisionBetween(ball: SKNode, object: SKNode) { if object === playerNode { playerTouched(ball) } else if object.name == NodeName.hitArea.rawValue { ballHit(ball) } else if object.name == Fireballs.name { // TODO: do another animation to remove the ball ballHit(ball) } else if object.name == Bubble.name { bubbleTouched(ball) } else if object === borderNode { // balls can be stuck to the border if they haven't enough velocity // In this case, let's them bonce in direction to the center with // enough Velocity to bounce again func runImpulse(impulse: CGVector) { ball.run(SKAction.sequence([ SKAction.scale(to: 1.2, duration: 1), SKAction.group([ SKAction.scale(to: 1, duration: 1), SKAction.applyImpulse(impulse, duration: 0.2) ]), ])) } if abs(ball.physicsBody?.velocity.dx ?? 0) <= 1 { let dx: CGFloat = groundNode.frame.midX - ball.frame.midX > 0 ? 1 : -1 runImpulse(impulse: CGVector(dx: dx, dy: 0)) } else if abs(ball.physicsBody?.velocity.dy ?? 0) <= 1 { let dy: CGFloat = groundNode.frame.midY - ball.frame.midY > 0 ? 1 : -1 runImpulse(impulse: CGVector(dx: 0, dy: dy)) } } } func didEnd(_ contact: SKPhysicsContact) { guard let nodeA = contact.bodyA.node, let nodeB = contact.bodyB.node else { return } switch (nodeA, nodeB) { case let (nodeA as SKEmitterNode, nodeB) where nodeA.name == Fireballs.name && nodeB.name == NodeName.border.rawValue: fireballTouchedBorder(fireball: nodeA) case let (nodeA, nodeB as SKEmitterNode) where nodeA.name == NodeName.border.rawValue && nodeB.name == Fireballs.name: fireballTouchedBorder(fireball: nodeB) default: break } } private func fireballTouchedBorder(fireball: SKEmitterNode) { fireball.particleAlphaSpeed = -2.5 fireball.emissionAngleRange = 2 * .pi } } extension GameScene { func ballHit(node: SKNode) { spell.mana.value += 5 removeBall(node) } private func removeBall(_ node: SKNode) { guard let appleType = Ball.AppleType(node: node) else { return } score += appleType.points ball.remove(ball: node) } func playerTouched(by node: SKNode) { ball.remove(ball: node) gameOver() } func bubbleTouched(by node: SKNode) { removeBall(node) spell.bubbleTouched() } func bonusGathered(_ node: SKNode) { guard let gemType = Bonus.GemType(node: node) else { return } score += gemType.points node.removeFromParent() } }
35.643357
126
0.596429
8ec2bfc70cd98f1b965e315bed998a8f4057789e
641
rb
Ruby
lib/terminal_output/styling/trait/color/reverse_video.rb
ntl/ansi-formatting
8b11b39a6dcab1bbef314af6988711efa5eee9ce
[ "MIT" ]
null
null
null
lib/terminal_output/styling/trait/color/reverse_video.rb
ntl/ansi-formatting
8b11b39a6dcab1bbef314af6988711efa5eee9ce
[ "MIT" ]
null
null
null
lib/terminal_output/styling/trait/color/reverse_video.rb
ntl/ansi-formatting
8b11b39a6dcab1bbef314af6988711efa5eee9ce
[ "MIT" ]
null
null
null
module TerminalOutput module Styling module Trait module Color module ReverseVideo extend Trait def self.variant?(variant) codes.key?(variant) end def self.get(variant) codes[variant] end def self.default_code fetch(:on) end def self.reset_code fetch(:off) end def self.codes { :on => SGR::Code.fetch(:negative_image), :off => SGR::Code.fetch(:positive_image) } end end end end end end
18.314286
54
0.466459
70c6ca43ae37583fe930a547cd92297eeebf44a9
2,410
kt
Kotlin
line-awesome/src/commonMain/kotlin/compose/icons/lineawesomeicons/Kaggle.kt
ravitejasc/compose-icons
09f752ef051b1c47e60554f3893bbed5ddd8bc1f
[ "MIT" ]
230
2020-11-11T14:52:11.000Z
2022-03-31T05:04:52.000Z
line-awesome/src/commonMain/kotlin/compose/icons/lineawesomeicons/Kaggle.kt
ravitejasc/compose-icons
09f752ef051b1c47e60554f3893bbed5ddd8bc1f
[ "MIT" ]
17
2021-03-02T00:00:32.000Z
2022-03-02T16:01:03.000Z
line-awesome/src/commonMain/kotlin/compose/icons/lineawesomeicons/Kaggle.kt
ravitejasc/compose-icons
09f752ef051b1c47e60554f3893bbed5ddd8bc1f
[ "MIT" ]
18
2021-02-08T06:18:41.000Z
2022-03-22T21:48:23.000Z
package compose.icons.lineawesomeicons import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.PathFillType.Companion.NonZero import androidx.compose.ui.graphics.SolidColor import androidx.compose.ui.graphics.StrokeCap.Companion.Butt import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.graphics.vector.ImageVector.Builder import androidx.compose.ui.graphics.vector.path import androidx.compose.ui.unit.dp import compose.icons.LineAwesomeIcons public val LineAwesomeIcons.Kaggle: ImageVector get() { if (_kaggle != null) { return _kaggle!! } _kaggle = Builder(name = "Kaggle", defaultWidth = 32.0.dp, defaultHeight = 32.0.dp, viewportWidth = 32.0f, viewportHeight = 32.0f).apply { path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(10.3516f, 4.0f) curveTo(10.1176f, 4.0f, 10.0f, 4.1166f, 10.0f, 4.3516f) lineTo(10.0f, 27.6445f) curveTo(10.0f, 27.8785f, 10.1166f, 27.9961f, 10.3516f, 27.9961f) lineTo(12.6484f, 27.9961f) curveTo(12.8824f, 27.9961f, 13.002f, 27.8795f, 13.002f, 27.6445f) lineTo(13.002f, 22.8086f) lineTo(14.8105f, 21.0859f) lineTo(20.0488f, 27.75f) curveTo(20.1908f, 27.915f, 20.3549f, 28.0f, 20.5449f, 28.0f) lineTo(23.7168f, 28.0f) curveTo(23.8828f, 28.0f, 23.977f, 27.9524f, 24.0f, 27.8574f) lineTo(23.9336f, 27.498f) lineTo(17.0234f, 18.9102f) lineTo(23.6504f, 12.498f) curveTo(23.7734f, 12.37f, 23.7304f, 12.0f, 23.3984f, 12.0f) lineTo(20.1172f, 12.0f) curveTo(19.9512f, 12.0f, 19.7851f, 12.086f, 19.6191f, 12.252f) lineTo(13.0f, 18.9746f) lineTo(13.0f, 4.3516f) curveTo(13.0f, 4.1166f, 12.8834f, 4.0f, 12.6484f, 4.0f) lineTo(10.3516f, 4.0f) close() } } .build() return _kaggle!! } private var _kaggle: ImageVector? = null
44.62963
93
0.594191
e72934bdb603f2cf4c15358bc7918d03f6b29e82
186
js
JavaScript
config/index.js
sebastianpodda/sardcoin-core
2a0ed61cd313acc4d48f004dfa84266fa44a8db1
[ "MIT", "X11", "Unlicense" ]
null
null
null
config/index.js
sebastianpodda/sardcoin-core
2a0ed61cd313acc4d48f004dfa84266fa44a8db1
[ "MIT", "X11", "Unlicense" ]
1
2021-05-07T11:44:21.000Z
2021-05-07T11:44:21.000Z
config/index.js
sebastianpodda/sardcoin-core
2a0ed61cd313acc4d48f004dfa84266fa44a8db1
[ "MIT", "X11", "Unlicense" ]
null
null
null
'use strict'; /** * Module dependencies. */ const path = require('path'); const defaults = { root: path.join(__dirname, '..'), }; /** * Expose */ module.exports = defaults;
10.333333
37
0.580645
1898fe3e322e6261aa95b0c5773c187fbc0d00bc
1,813
kt
Kotlin
data/src/main/java/at/guger/moneybook/data/repository/RemindersRepository.kt
guger/MoneyBook
d835994ea77db07119cc5e4a32299adda2357661
[ "Apache-2.0" ]
13
2020-01-31T21:30:50.000Z
2022-02-28T09:38:01.000Z
data/src/main/java/at/guger/moneybook/data/repository/RemindersRepository.kt
guger/MoneyBook
d835994ea77db07119cc5e4a32299adda2357661
[ "Apache-2.0" ]
56
2019-08-27T11:33:34.000Z
2022-02-15T10:32:01.000Z
data/src/main/java/at/guger/moneybook/data/repository/RemindersRepository.kt
guger/MoneyBook
d835994ea77db07119cc5e4a32299adda2357661
[ "Apache-2.0" ]
1
2020-04-19T09:28:24.000Z
2020-04-19T09:28:24.000Z
/* * Copyright 2021 Daniel Guger * * 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 at.guger.moneybook.data.repository import at.guger.moneybook.data.model.Reminder import at.guger.moneybook.data.provider.local.AppDatabase import at.guger.moneybook.data.provider.local.dao.ReminderDao /** * Repository class for handling [reminders][Reminder]. */ class RemindersRepository(database: AppDatabase) { //region Variables private val reminderDao: ReminderDao = database.reminderDao() //endregion //region Methods suspend fun getReminders(): List<Reminder> { return reminderDao.getReminders() } suspend fun getReminderForTransaction(transactionId: Long): Reminder? { return reminderDao.getReminderForTransaction(transactionId) } suspend fun insert(vararg reminder: Reminder) { reminderDao.insert(*reminder) } suspend fun update(reminder: Reminder) { reminderDao.update(reminder) } suspend fun delete(vararg reminder: Reminder) { reminderDao.delete(*reminder) } suspend fun deleteByTransactionId(transactionId: Long) { reminderDao.deleteByTransactionId(transactionId) } //endregion }
29.721311
79
0.692774
85d5fd76754ac4c1a3400af094cbf46ddf963cac
1,092
js
JavaScript
src/staff/components/OrgEditModal.js
Popov85/ratos3-frontend
017a433f89faed10733c3d961f93e0fb0a9bfe59
[ "MIT" ]
null
null
null
src/staff/components/OrgEditModal.js
Popov85/ratos3-frontend
017a433f89faed10733c3d961f93e0fb0a9bfe59
[ "MIT" ]
null
null
null
src/staff/components/OrgEditModal.js
Popov85/ratos3-frontend
017a433f89faed10733c3d961f93e0fb0a9bfe59
[ "MIT" ]
null
null
null
import React from 'react'; import PropTypes from 'prop-types'; import Modal from "react-bootstrap/Modal"; import {Alert} from "react-bootstrap"; import OrgEditContainer from "../containers/OrgEditContainer"; const OrgEditModal = props => { const {editableOrgId} = props; return ( <Modal id='orgEdit' show={props.show} backdrop='static' keyboard={false} scrollable={true} centered> <Alert variant="info" onClose={() => props.deactivateModal()} className="text-center m-0" dismissible> <strong>Organisation</strong> { editableOrgId ? '[edit]' : '[new]' } </Alert> <Modal.Body> <OrgEditContainer orgId = {editableOrgId}/> </Modal.Body> </Modal> ); }; OrgEditModal.propTypes = { show: PropTypes.bool.isRequired, editableOrgId: PropTypes.number, // Nullable for new objects deactivateModal: PropTypes.func.isRequired }; export default OrgEditModal;
28.736842
114
0.577839
4100fcac1b71200cd34bda2d68966cace9e69413
1,210
c
C
Tute04.c
IT1050-2022-Feb/tutorial-01-IT21285738
8021f3d96c31d5615ccaf60e804e28322499f254
[ "MIT" ]
null
null
null
Tute04.c
IT1050-2022-Feb/tutorial-01-IT21285738
8021f3d96c31d5615ccaf60e804e28322499f254
[ "MIT" ]
null
null
null
Tute04.c
IT1050-2022-Feb/tutorial-01-IT21285738
8021f3d96c31d5615ccaf60e804e28322499f254
[ "MIT" ]
null
null
null
/*Exercise 4 - Functions Implement the three functions minimum(), maximum() and multiply() below the main() function. Do not change the code given in the main() function when you are implementing your solution.*/ #include <stdio.h> //declaring Functions int minimum(int num1 , int num2); int maximum(int num1 , int num2); int multiply(int num1 , int num2); //function main begins program execution int main() { int no1, no2; printf("Enter a value for no 1 : "); scanf("%d", &no1); printf("Enter a value for no 2 : "); scanf("%d", &no2); printf("%d ", minimum(no1, no2)); printf("%d ", maximum(no1, no2)); printf("%d ", multiply(no1, no2)); return 0; } //function implementation int minimum(int num1 , int num2) { int min; if(num1 < num2) { min = num1; } else if (num1 > num2) { min = num2; } else min = num1; //if num1 and num2 are the same return min; } int maximum(int num1 , int num2) { int max; if(num1 > num2) { max = num1; } else if (num1 < num2) { max = num2; } else max = num1; //if num1 and num2 are the same return max; } int multiply(int num1 , int num2) { int mul; return mul = num1 * num2; }
18.059701
94
0.612397
28f316df8fb0051c1cf38a2591d808e1986a3b2b
1,898
rb
Ruby
src/in.rb
medoror/binary-resource
bbe14617d5830e189fa31e36544734a7a00a3bea
[ "Apache-2.0" ]
1
2020-05-12T22:05:35.000Z
2020-05-12T22:05:35.000Z
src/in.rb
medoror/binary-resource
bbe14617d5830e189fa31e36544734a7a00a3bea
[ "Apache-2.0" ]
null
null
null
src/in.rb
medoror/binary-resource
bbe14617d5830e189fa31e36544734a7a00a3bea
[ "Apache-2.0" ]
null
null
null
#!/usr/bin/env ruby require_relative './payload' require 'fileutils' require_relative './http_client' # puts __FILE__ # puts $PROGRAM_NAME class In < Payload # STDIN: # { # "source": { # "repo": "pivotal-cf/om", # "tag": "4.6.0" # }, # "version": { "version": "4.6.0" } # } # # STDOUT # { # "version": { "version":"4.6.0"}, # "metadata":[] # } attr_accessor :version def initialize(payload) super @version = payload["version"]["version"] end def get_download_link(payload) # explicitly check for linux binary until we inject distro choice from recipe begin payload["assets"].find {|asset| asset["name"].match?(/.*linux.*gz/)}["browser_download_url"] rescue NoMethodError => e raise "Download Link could not be retrieved" end end def main(destination_dir) response = HttpClient.get("https://api.github.com/repos/#{@owner}/#{@repo}/releases/tags/#{@version}") download_link = get_download_link(response) download_binary(download_link, destination_dir) untar_binary(download_link.match(/([^\/]+).gz/)[0], destination_dir) output_to_stdout(@version) end private def output_to_stdout(download_name) output = {"version" => {"version" => download_name}, "metadata" => []} puts output.to_json end def untar_binary(download_name, full_destination) system("tar -xf #{full_destination}/#{download_name} -C #{full_destination}") end def download_binary(download_link, full_destination) system("wget --no-check-certificate #{download_link} -P #{full_destination}") end end if $PROGRAM_NAME == __FILE__ standard_input = $stdin.read unless standard_input == '' in_script = In.new(JSON.parse(standard_input)) begin in_script.main(ARGV[0]) rescue Errno::ENOENT => e STDERR.puts e.message exit(1) end end end
23.432099
106
0.651212
7bb0c09dd29c3345d482ee89a9d19e9f15a4e03b
53
css
CSS
snippets/common/VS_Snippets_WebNet/System.Web.UI.HtmlControls.HtmlHeadCstr/Common/StyleSheet.css
BohdanMosiyuk/samples
59d435ba9e61e0fc19f5176c96b1cdbd53596142
[ "CC-BY-4.0", "MIT" ]
2
2020-02-22T09:30:21.000Z
2021-08-02T23:44:31.000Z
snippets/common/VS_Snippets_WebNet/System.Web.UI.HtmlControls.HtmlHeadCstr/Common/StyleSheet.css
BohdanMosiyuk/samples
59d435ba9e61e0fc19f5176c96b1cdbd53596142
[ "CC-BY-4.0", "MIT" ]
555
2019-09-23T22:22:58.000Z
2021-07-15T18:51:12.000Z
snippets/common/VS_Snippets_WebNet/System.Web.UI.HtmlControls.HtmlHeadCstr/Common/StyleSheet.css
BohdanMosiyuk/samples
59d435ba9e61e0fc19f5176c96b1cdbd53596142
[ "CC-BY-4.0", "MIT" ]
3
2020-01-29T16:31:15.000Z
2021-08-24T07:00:15.000Z
body { color:Blue; background-color: LightGrey; }
8.833333
29
0.698113
d5f3451575433153f0fc023061837af254ff182c
506
h
C
src/test/app_test.h
yipeiw/pserver
2a856ba0cda744e4b8adcd925238dd7d4609bea7
[ "Apache-2.0" ]
null
null
null
src/test/app_test.h
yipeiw/pserver
2a856ba0cda744e4b8adcd925238dd7d4609bea7
[ "Apache-2.0" ]
null
null
null
src/test/app_test.h
yipeiw/pserver
2a856ba0cda744e4b8adcd925238dd7d4609bea7
[ "Apache-2.0" ]
null
null
null
#include "system/app.h" namespace PS { // test via: // ./local.sh 2 2 ../src/test/app_test.conf class AppTest : public App { public: AppTest(const string& name) : App(name) { LL << "create app " << name_ << " at " << myNodeID(); } virtual ~AppTest() { LL << "destroy " << name_ << " at " << myNodeID(); } void init() { LL << "init app at " << myNodeID(); } void run() { LL << "run app at " << myNodeID(); } void process(const MessagePtr& msg) { } }; } // namespace PS
20.24
57
0.543478
31f2bbbd84dd8db8c5a0e60365ca358a5122d8c6
281
sql
SQL
etc/15_1.17.0_to_1.18.0.sql
silverbullet-dk/opentele-server-core-plugin
0b3bad26979d434dda8980db688401f2a3a1e954
[ "Apache-2.0" ]
null
null
null
etc/15_1.17.0_to_1.18.0.sql
silverbullet-dk/opentele-server-core-plugin
0b3bad26979d434dda8980db688401f2a3a1e954
[ "Apache-2.0" ]
null
null
null
etc/15_1.17.0_to_1.18.0.sql
silverbullet-dk/opentele-server-core-plugin
0b3bad26979d434dda8980db688401f2a3a1e954
[ "Apache-2.0" ]
null
null
null
ALTER TABLE [dbo].[patient_group] ADD [show_gestational_age] bit GO update [dbo].patient_group set show_gestational_age = 'FALSE' GO ALTER TABLE [dbo].[patient_group] ALTER COLUMN [show_gestational_age] bit NOT NULL GO ALTER TABLE [dbo].[patient] ADD [due_date] datetime2(7) GO
23.416667
82
0.775801
bfb51ff6e4d6a71119e07450d56ce0d261cc8d86
82
sql
SQL
prisma/migrations/20210911023900_init/migration.sql
AlexisG13/Ravn-Node.js-Challenge
c31187f4cc99184751d096d12bb04c704e4cbdff
[ "MIT" ]
null
null
null
prisma/migrations/20210911023900_init/migration.sql
AlexisG13/Ravn-Node.js-Challenge
c31187f4cc99184751d096d12bb04c704e4cbdff
[ "MIT" ]
null
null
null
prisma/migrations/20210911023900_init/migration.sql
AlexisG13/Ravn-Node.js-Challenge
c31187f4cc99184751d096d12bb04c704e4cbdff
[ "MIT" ]
null
null
null
-- DropForeignKey ALTER TABLE "Post" DROP CONSTRAINT "Post_id_resourceType_fkey";
27.333333
63
0.817073
cb4c14891f1faf0fc12150bc4bce976316be9309
3,314
go
Go
incubator/hnc/internal/kubectl/configset.go
christopherhein/multi-tenancy
35e48e80f89998d612b647fef20739794b54946d
[ "Apache-2.0" ]
848
2019-03-07T05:37:51.000Z
2022-03-30T11:41:11.000Z
incubator/hnc/internal/kubectl/configset.go
christopherhein/multi-tenancy
35e48e80f89998d612b647fef20739794b54946d
[ "Apache-2.0" ]
1,522
2019-03-13T18:01:58.000Z
2022-03-10T17:45:37.000Z
incubator/hnc/internal/kubectl/configset.go
christopherhein/multi-tenancy
35e48e80f89998d612b647fef20739794b54946d
[ "Apache-2.0" ]
175
2019-03-12T20:44:25.000Z
2022-03-08T16:55:40.000Z
/* 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 kubectl import ( "fmt" "os" "strings" "github.com/spf13/cobra" api "sigs.k8s.io/multi-tenancy/incubator/hnc/api/v1alpha2" ) var setResourceCmd = &cobra.Command{ Use: fmt.Sprintf("set-resource RESOURCE [--group GROUP] [--force] --mode <%s|%s|%s>", api.Propagate, api.Remove, api.Ignore), Short: "Sets the HNC configuration of a specific resource", Example: fmt.Sprintf(" # Set configuration of a core type\n" + " kubectl hns config set-resource secrets --mode Ignore\n\n" + " # Set configuration of a custom type\n" + " kubectl hns config set-resource crontabs --group stable.example.com --mode Propagate"), Args: cobra.ExactArgs(1), Run: func(cmd *cobra.Command, args []string) { resource := args[0] flags := cmd.Flags() group, _ := flags.GetString("group") modeStr, _ := flags.GetString("mode") mode := api.SynchronizationMode(normalizeModeString(modeStr)) force, _ := flags.GetBool("force") config := client.getHNCConfig() exist := false for i := 0; i < len(config.Spec.Resources); i++ { r := &config.Spec.Resources[i] if r.Group == group && r.Resource == resource { if r.Mode == api.Ignore && mode == api.Propagate && !force { fmt.Printf("Switching directly from 'Ignore' to 'Propagate' mode could cause existing %q objects in "+ "child namespaces to be overwritten by objects from ancestor namespaces.\n", resource) fmt.Println("If you are sure you want to proceed with this operation, use the '--force' flag.") fmt.Println("If you are not sure and would like to see what source objects would be overwritten," + "please switch to 'Remove' first. To see how to enable propagation safely, refer to " + "https://github.com/kubernetes-sigs/multi-tenancy/blob/master/incubator/hnc/docs/user-guide/how-to.md#admin-types") os.Exit(1) } r.Mode = mode exist = true break } } if !exist { config.Spec.Resources = append(config.Spec.Resources, api.ResourceSpec{ Group: group, Resource: resource, Mode: mode, }) } client.updateHNCConfig(config) }, } // normalizeModeString corrects format of input Synchronization Mode string func normalizeModeString(modeStr string) string { low := strings.ToLower(modeStr) return strings.Title(low) } func newSetResourceCmd() *cobra.Command { setResourceCmd.Flags().String("group", "", "The group of the resource; may be omitted for core resources (or explicitly set to the empty string)") setResourceCmd.Flags().String("mode", "", "The synchronization mode: one of Propagate, Remove or Ignore") setResourceCmd.Flags().BoolP("force", "f", false, "Allow the synchronization mode to be changed directly from Ignore to Propagate despite the dangers of doing so") return setResourceCmd }
36.822222
164
0.709113
b6e8c4123c5e99dbb9adc7053995cf486ce9045e
178
rb
Ruby
main/ruby_scripts/status.rb
ImperialCollegeLondon/hpc_portal
d6aa0fa45699f6dcd9224e31332287e549d29d02
[ "BSD-3-Clause" ]
null
null
null
main/ruby_scripts/status.rb
ImperialCollegeLondon/hpc_portal
d6aa0fa45699f6dcd9224e31332287e549d29d02
[ "BSD-3-Clause" ]
31
2021-08-05T14:44:51.000Z
2021-09-16T11:18:44.000Z
main/ruby_scripts/status.rb
ImperialCollegeLondon/champ
ab389b58418ee17ae0aeaa5391bd3e8760f85b84
[ "BSD-3-Clause" ]
null
null
null
require('ood_core') job_id = ARGV[0] clusters = OodCore::Clusters.load_file("/etc/ood/config/clusters.d/") cluster = clusters[ARGV[1]] puts cluster.job_adapter.status(job_id)
19.777778
69
0.747191
7abda23aeed7df88e943d2556a0050ab8f5dabb4
2,557
swift
Swift
21-Chain_of_Responsibility_Pattern.playground/Contents.swift
kingcos/Swift-3-Design-Patterns
3623be1b388ae51a728f4202425763af245fdc71
[ "Apache-2.0" ]
70
2016-12-06T11:18:21.000Z
2018-03-30T02:34:00.000Z
21-Chain_of_Responsibility_Pattern.playground/Contents.swift
kingcos/Swift-3-Design-Patterns
3623be1b388ae51a728f4202425763af245fdc71
[ "Apache-2.0" ]
null
null
null
21-Chain_of_Responsibility_Pattern.playground/Contents.swift
kingcos/Swift-3-Design-Patterns
3623be1b388ae51a728f4202425763af245fdc71
[ "Apache-2.0" ]
17
2017-08-14T06:41:05.000Z
2018-01-31T06:20:25.000Z
//: Playground - noun: a place where people can play // Powered by https://maimieng.com from https://github.com/kingcos/Swift-X-Design-Patterns import UIKit // 请求 struct Request { enum RequestType: String { case leave = "请假" case salary = "加薪" } var requestType: RequestType var requestContent: String var number: Int } // 经理协议 protocol Manager { var name: String { get } var superior: Manager? { get } func requestApplications(_ request: Request) } // 普通经理 struct CommonManager: Manager { var name: String var superior: Manager? func requestApplications(_ request: Request) { if request.requestType == .leave && request.number <= 2 { print("CommonManager 批准:\(request.requestType.rawValue) \(request.number) 天") } else { superior!.requestApplications(request) } } } // 总监 struct Majordomo: Manager { var name: String var superior: Manager? func requestApplications(_ request: Request) { if request.requestType == .leave && request.number <= 5 { print("Majordomo 批准:\(request.requestType.rawValue) \(request.number) 天") } else { superior!.requestApplications(request) } } } // 总经理 struct GeneralManager: Manager { var name: String var superior: Manager? init(_ name: String) { self.name = name } func requestApplications(_ request: Request) { if request.requestType == .leave { print("GeneralManager 批准:\(request.requestType.rawValue) \(request.number) 天") } else if request.requestType == .salary && request.number <= 500 { print("GeneralManager 批准:\(request.requestType.rawValue) \(request.number) 元") } else if request.requestType == .salary && request.number > 500 { print("GeneralManager 考虑考虑") } } } let generalMng = GeneralManager("总经理") let majordomo = Majordomo(name: "总监", superior: generalMng) let commonMng = CommonManager(name: "普通经理", superior: majordomo) let rqA = Request(requestType: .leave, requestContent: "小菜请假", number: 1) commonMng.requestApplications(rqA) let rqB = Request(requestType: .leave, requestContent: "小菜请假", number: 4) commonMng.requestApplications(rqB) let rqC = Request(requestType: .salary, requestContent: "小菜加薪", number: 200) commonMng.requestApplications(rqC) let rqD = Request(requestType: .salary, requestContent: "小菜加薪", number: 1000) commonMng.requestApplications(rqD)
28.098901
90
0.646852
128023d34667e64d05d3889ec2a393181410cc16
469
h
C
Sources/CLNetworking/EWSHttpRequest.h
coooliang/CLKits
a388f8a14b8ffa868c4856fde4a5bd18f5606012
[ "MIT" ]
1
2019-01-23T13:09:59.000Z
2019-01-23T13:09:59.000Z
Sources/CLNetworking/EWSHttpRequest.h
coooliang/CLKits
a388f8a14b8ffa868c4856fde4a5bd18f5606012
[ "MIT" ]
1
2018-12-13T02:17:50.000Z
2018-12-13T02:17:50.000Z
Sources/CLNetworking/EWSHttpRequest.h
coooliang/CLKits
a388f8a14b8ffa868c4856fde4a5bd18f5606012
[ "MIT" ]
null
null
null
#import <Foundation/Foundation.h> typedef void(^HTTPRequestSuccessCompletion)(NSString *redirectLocation, NSData *xmlData); typedef void(^HTTPRequestFailureCompletion)(NSError *error); typedef void(^HTTPRecieveDataBlock)(NSData *data); @interface EWSHttpRequest : NSObject -(void)ewsHttpRequest:(NSString *)soapXmlString url:(NSString *)url dict:(NSDictionary *)dict success:(HTTPRequestSuccessCompletion)success failure:(HTTPRequestFailureCompletion)failure; @end
39.083333
186
0.823028
3a6f6f9fa27234c460b65670d688440691e3849c
7,989
asm
Assembly
Transynther/x86/_processed/NONE/_xt_/i7-7700_9_0x48.log_21829_2839.asm
ljhsiun2/medusa
67d769b8a2fb42c538f10287abaf0e6dbb463f0c
[ "MIT" ]
9
2020-08-13T19:41:58.000Z
2022-03-30T12:22:51.000Z
Transynther/x86/_processed/NONE/_xt_/i7-7700_9_0x48.log_21829_2839.asm
ljhsiun2/medusa
67d769b8a2fb42c538f10287abaf0e6dbb463f0c
[ "MIT" ]
1
2021-04-29T06:29:35.000Z
2021-05-13T21:02:30.000Z
Transynther/x86/_processed/NONE/_xt_/i7-7700_9_0x48.log_21829_2839.asm
ljhsiun2/medusa
67d769b8a2fb42c538f10287abaf0e6dbb463f0c
[ "MIT" ]
3
2020-07-14T17:07:07.000Z
2022-03-21T01:12:22.000Z
.global s_prepare_buffers s_prepare_buffers: push %r11 push %r13 push %r9 push %rbp push %rbx push %rcx push %rdi push %rsi lea addresses_D_ht+0x8512, %rsi lea addresses_WT_ht+0xdeb2, %rdi clflush (%rsi) nop add %rbx, %rbx mov $77, %rcx rep movsl nop nop nop nop xor %r9, %r9 lea addresses_WC_ht+0x1b800, %rbp nop and %r13, %r13 mov $0x6162636465666768, %rbx movq %rbx, %xmm6 vmovups %ymm6, (%rbp) nop nop nop and $48911, %rsi lea addresses_normal_ht+0x19e12, %rsi lea addresses_UC_ht+0x7a12, %rdi nop nop nop nop add $8884, %r11 mov $51, %rcx rep movsq nop cmp $52856, %r13 lea addresses_WT_ht+0x6a12, %rsi lea addresses_D_ht+0x11212, %rdi add $54344, %r9 mov $70, %rcx rep movsb sub $8951, %rdi lea addresses_A_ht+0x1c312, %rsi nop nop nop nop nop inc %r9 mov $0x6162636465666768, %rbx movq %rbx, %xmm6 movups %xmm6, (%rsi) nop nop nop cmp %r11, %r11 lea addresses_A_ht+0x17628, %rdi cmp %r13, %r13 mov $0x6162636465666768, %rcx movq %rcx, %xmm6 vmovups %ymm6, (%rdi) nop nop nop nop sub $10513, %r13 lea addresses_normal_ht+0x13d52, %rbp nop nop nop nop nop inc %rbx vmovups (%rbp), %ymm6 vextracti128 $1, %ymm6, %xmm6 vpextrq $1, %xmm6, %rcx nop nop nop cmp $45305, %rdi lea addresses_WT_ht+0x20d2, %rbx cmp %rcx, %rcx movl $0x61626364, (%rbx) nop nop cmp $45471, %r11 lea addresses_WC_ht+0x1d112, %rsi lea addresses_WT_ht+0x9112, %rdi nop nop nop add $3952, %rbx mov $17, %rcx rep movsb nop nop nop nop nop and %rsi, %rsi lea addresses_UC_ht+0x12612, %r11 nop nop nop nop nop xor $44489, %rdi movb (%r11), %r9b nop sub %rcx, %rcx lea addresses_A_ht+0x1d812, %rcx nop nop nop nop nop add $55381, %rbx mov $0x6162636465666768, %r13 movq %r13, %xmm7 vmovups %ymm7, (%rcx) nop nop nop nop nop sub %r9, %r9 lea addresses_A_ht+0x1b612, %rsi lea addresses_WT_ht+0x13262, %rdi nop nop sub $49740, %r13 mov $25, %rcx rep movsw cmp $49755, %r13 lea addresses_UC_ht+0x17392, %rbx nop nop nop xor $31955, %r13 vmovups (%rbx), %ymm2 vextracti128 $0, %ymm2, %xmm2 vpextrq $1, %xmm2, %rsi nop nop nop nop xor %rbp, %rbp lea addresses_D_ht+0x1c912, %rsi lea addresses_WC_ht+0x6612, %rdi add $15807, %r13 mov $14, %rcx rep movsl nop nop nop add $16703, %rsi lea addresses_WT_ht+0x5252, %rbx nop nop cmp $35151, %rbp movb (%rbx), %cl nop nop nop nop and $7523, %r13 pop %rsi pop %rdi pop %rcx pop %rbx pop %rbp pop %r9 pop %r13 pop %r11 ret .global s_faulty_load s_faulty_load: push %r13 push %r8 push %r9 push %rcx push %rdx push %rsi // Faulty Load lea addresses_D+0x1a12, %rcx nop sub %rdx, %rdx mov (%rcx), %r13 lea oracles, %rcx and $0xff, %r13 shlq $12, %r13 mov (%rcx,%r13,1), %r13 pop %rsi pop %rdx pop %rcx pop %r9 pop %r8 pop %r13 ret /* <gen_faulty_load> [REF] {'OP': 'LOAD', 'src': {'type': 'addresses_D', 'AVXalign': False, 'congruent': 0, 'size': 16, 'same': False, 'NT': False}} [Faulty Load] {'OP': 'LOAD', 'src': {'type': 'addresses_D', 'AVXalign': False, 'congruent': 0, 'size': 8, 'same': True, 'NT': False}} <gen_prepare_buffer> {'OP': 'REPM', 'src': {'type': 'addresses_D_ht', 'congruent': 8, 'same': False}, 'dst': {'type': 'addresses_WT_ht', 'congruent': 4, 'same': False}} {'OP': 'STOR', 'dst': {'type': 'addresses_WC_ht', 'AVXalign': False, 'congruent': 1, 'size': 32, 'same': False, 'NT': False}} {'OP': 'REPM', 'src': {'type': 'addresses_normal_ht', 'congruent': 7, 'same': False}, 'dst': {'type': 'addresses_UC_ht', 'congruent': 11, 'same': False}} {'OP': 'REPM', 'src': {'type': 'addresses_WT_ht', 'congruent': 11, 'same': False}, 'dst': {'type': 'addresses_D_ht', 'congruent': 8, 'same': False}} {'OP': 'STOR', 'dst': {'type': 'addresses_A_ht', 'AVXalign': False, 'congruent': 7, 'size': 16, 'same': False, 'NT': False}} {'OP': 'STOR', 'dst': {'type': 'addresses_A_ht', 'AVXalign': False, 'congruent': 1, 'size': 32, 'same': False, 'NT': False}} {'OP': 'LOAD', 'src': {'type': 'addresses_normal_ht', 'AVXalign': False, 'congruent': 3, 'size': 32, 'same': False, 'NT': False}} {'OP': 'STOR', 'dst': {'type': 'addresses_WT_ht', 'AVXalign': False, 'congruent': 5, 'size': 4, 'same': False, 'NT': False}} {'OP': 'REPM', 'src': {'type': 'addresses_WC_ht', 'congruent': 6, 'same': False}, 'dst': {'type': 'addresses_WT_ht', 'congruent': 5, 'same': False}} {'OP': 'LOAD', 'src': {'type': 'addresses_UC_ht', 'AVXalign': False, 'congruent': 9, 'size': 1, 'same': False, 'NT': False}} {'OP': 'STOR', 'dst': {'type': 'addresses_A_ht', 'AVXalign': False, 'congruent': 9, 'size': 32, 'same': False, 'NT': False}} {'OP': 'REPM', 'src': {'type': 'addresses_A_ht', 'congruent': 10, 'same': False}, 'dst': {'type': 'addresses_WT_ht', 'congruent': 4, 'same': False}} {'OP': 'LOAD', 'src': {'type': 'addresses_UC_ht', 'AVXalign': False, 'congruent': 6, 'size': 32, 'same': False, 'NT': False}} {'OP': 'REPM', 'src': {'type': 'addresses_D_ht', 'congruent': 6, 'same': False}, 'dst': {'type': 'addresses_WC_ht', 'congruent': 10, 'same': False}} {'OP': 'LOAD', 'src': {'type': 'addresses_WT_ht', 'AVXalign': False, 'congruent': 6, 'size': 1, 'same': False, 'NT': True}} {'36': 21829} 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 */
33.995745
2,999
0.659657
86dbafa5480bbfd91a49f13985ba507161d569da
520
asm
Assembly
programs/oeis/315/A315489.asm
neoneye/loda
afe9559fb53ee12e3040da54bd6aa47283e0d9ec
[ "Apache-2.0" ]
22
2018-02-06T19:19:31.000Z
2022-01-17T21:53:31.000Z
programs/oeis/315/A315489.asm
neoneye/loda
afe9559fb53ee12e3040da54bd6aa47283e0d9ec
[ "Apache-2.0" ]
41
2021-02-22T19:00:34.000Z
2021-08-28T10:47:47.000Z
programs/oeis/315/A315489.asm
neoneye/loda
afe9559fb53ee12e3040da54bd6aa47283e0d9ec
[ "Apache-2.0" ]
5
2021-02-24T21:14:16.000Z
2021-08-09T19:48:05.000Z
; A315489: Coordination sequence Gal.5.292.5 where G.u.t.v denotes the coordination sequence for a vertex of type v in tiling number t in the Galebach list of u-uniform tilings. ; 1,6,11,16,22,27,32,38,43,48,54,60,65,70,76,81,86,92,97,102,108,114,119,124,130,135,140,146,151,156,162,168,173,178,184,189,194,200,205,210,216,222,227,232,238,243,248,254,259,264 mov $5,$0 sub $0,1 mov $3,$0 div $3,10 add $0,$3 mov $1,$0 add $0,$3 lpb $1 mov $1,2 mov $4,$0 lpe div $4,3 add $4,1 mov $0,$4 mov $2,$5 mul $2,5 add $0,$2
24.761905
180
0.676923
ac1a61dda4f0312a45b20819ea9b80b3fbc0f05f
124
sql
SQL
resource-server/src/main/resources/sql-scripts/schema.sql
andrei-punko/springboot-jwt
67c98ddca5278409ec49172d330c1f164e6ec11f
[ "MIT" ]
1
2020-03-09T15:44:25.000Z
2020-03-09T15:44:25.000Z
resource-server/src/main/resources/sql-scripts/schema.sql
andrei-punko/springboot-jwt
67c98ddca5278409ec49172d330c1f164e6ec11f
[ "MIT" ]
null
null
null
resource-server/src/main/resources/sql-scripts/schema.sql
andrei-punko/springboot-jwt
67c98ddca5278409ec49172d330c1f164e6ec11f
[ "MIT" ]
null
null
null
CREATE TABLE random_city ( id bigint(20) NOT NULL AUTO_INCREMENT, name varchar(255) DEFAULT NULL, PRIMARY KEY (id) );
20.666667
40
0.725806
49ff51d9d6190bc4654b92afbaeeea16863d3004
19,761
lua
Lua
spec/domain/trait/player/storage_spec.lua
czenker/lively-epsilon
8da2dd7912409378e7637d561363f623e5270bbe
[ "MIT" ]
9
2017-12-29T12:24:25.000Z
2021-04-26T15:48:09.000Z
spec/domain/trait/player/storage_spec.lua
czenker/lively-epsilon
8da2dd7912409378e7637d561363f623e5270bbe
[ "MIT" ]
3
2017-12-23T17:17:01.000Z
2018-01-09T22:05:13.000Z
spec/domain/trait/player/storage_spec.lua
czenker/lively-epsilon
8da2dd7912409378e7637d561363f623e5270bbe
[ "MIT" ]
2
2018-02-01T19:05:33.000Z
2018-02-11T01:42:00.000Z
insulate("Player:withStorage()", function() require "init" require "spec.mocks" require "spec.asserts" local product1 = productMock() local product2 = productMock() local product3 = productMock() it("creates a valid storage", function() local player = PlayerSpaceship() Player:withStorage(player) assert.is_true(Player:hasStorage(player)) assert.is_number(player:getMaxStorageSpace()) end) it("allows to configure the maxStorage", function() local player = PlayerSpaceship() Player:withStorage(player, {maxStorage = 1000}) assert.is_true(Player:hasStorage(player)) assert.is_same(1000, player:getMaxStorageSpace()) end) it("fails if first argument is a number", function() assert.has_error(function() Player:withStorage(42) end) end) it("fails if second argument is a number", function() assert.has_error(function() Player:withStorage(PlayerSpaceship(), 42) end) end) describe(":getStoredProducts()", function() it("returns all the products that are currently stored", function() local player = PlayerSpaceship() Player:withStorage(player) assert.is_same({}, player:getStoredProducts()) player:modifyProductStorage(product1, 1) assert.is_same(1, Util.size(player:getStoredProducts())) assert.contains_value(product1, player:getStoredProducts()) player:modifyProductStorage(product1, 1) assert.is_same(1, Util.size(player:getStoredProducts())) assert.contains_value(product1, player:getStoredProducts()) player:modifyProductStorage(product2, 1) assert.is_same(2, Util.size(player:getStoredProducts())) assert.contains_value(product2, player:getStoredProducts()) player:modifyProductStorage(product2, -1) assert.is_same(1, Util.size(player:getStoredProducts())) assert.contains_value(product1, player:getStoredProducts()) assert.not_contains_value(product2, player:getStoredProducts()) end) it("does not return rockets and probes, because we might not know the correct object to return", function() local player = PlayerSpaceship() Player:withStorage(player) player:setWeaponStorageMax("hvli", 5) player:setWeaponStorage("hvli", 5) player:setWeaponStorageMax("homing", 4) player:setWeaponStorage("homing", 4) player:setWeaponStorageMax("mine", 3) player:setWeaponStorage("mine", 3) player:setWeaponStorageMax("emp", 2) player:setWeaponStorage("emp", 2) player:setWeaponStorageMax("nuke", 1) player:setWeaponStorage("nuke", 1) player:setMaxScanProbeCount(4) player:setScanProbeCount(4) assert.is_same({}, player:getStoredProducts()) end) end) describe(":getProductStorage(), :getEmptyProductStorage(), :getMaxProductStorage()", function() it("returns the correct value", function() local player = PlayerSpaceship() Player:withStorage(player, {maxStorage = 100}) assert.is_same(0, player:getProductStorage(product1)) assert.is_same(100, player:getMaxProductStorage(product1)) assert.is_same(100, player:getEmptyProductStorage(product1)) assert.is_same(0, player:getProductStorage(product2)) assert.is_same(100, player:getMaxProductStorage(product2)) assert.is_same(100, player:getEmptyProductStorage(product2)) assert.is_same(0, player:getProductStorage(product3)) assert.is_same(100, player:getMaxProductStorage(product3)) assert.is_same(100, player:getEmptyProductStorage(product3)) player:modifyProductStorage(product1, 10) assert.is_same(10, player:getProductStorage(product1)) assert.is_same(100, player:getMaxProductStorage(product1)) assert.is_same(90, player:getEmptyProductStorage(product1)) assert.is_same(0, player:getProductStorage(product2)) assert.is_same(90, player:getMaxProductStorage(product2)) assert.is_same(90, player:getEmptyProductStorage(product2)) assert.is_same(0, player:getProductStorage(product3)) assert.is_same(90, player:getMaxProductStorage(product3)) assert.is_same(90, player:getEmptyProductStorage(product3)) player:modifyProductStorage(product2, 10) assert.is_same(10, player:getProductStorage(product1)) assert.is_same(90, player:getMaxProductStorage(product1)) assert.is_same(80, player:getEmptyProductStorage(product1)) assert.is_same(10, player:getProductStorage(product2)) assert.is_same(90, player:getMaxProductStorage(product2)) assert.is_same(80, player:getEmptyProductStorage(product2)) assert.is_same(0, player:getProductStorage(product3)) assert.is_same(80, player:getMaxProductStorage(product3)) assert.is_same(80, player:getEmptyProductStorage(product3)) player:modifyProductStorage(product2, -5) assert.is_same(10, player:getProductStorage(product1)) assert.is_same(95, player:getMaxProductStorage(product1)) assert.is_same(85, player:getEmptyProductStorage(product1)) assert.is_same(5, player:getProductStorage(product2)) assert.is_same(90, player:getMaxProductStorage(product2)) assert.is_same(85, player:getEmptyProductStorage(product2)) assert.is_same(0, player:getProductStorage(product3)) assert.is_same(85, player:getMaxProductStorage(product3)) assert.is_same(85, player:getEmptyProductStorage(product3)) end) it("works correctly with sized products", function() local product1 = productMock() local product2 = productMock() local product3 = productMock() product1.getSize = function() return 1 end product2.getSize = function() return 2 end product3.getSize = function() return 4 end local player = PlayerSpaceship() Player:withStorage(player, {maxStorage = 100}) assert.is_same(0, player:getProductStorage(product1)) assert.is_same(100, player:getMaxProductStorage(product1)) assert.is_same(100, player:getEmptyProductStorage(product1)) assert.is_same(0, player:getProductStorage(product2)) assert.is_same(50, player:getMaxProductStorage(product2)) assert.is_same(50, player:getEmptyProductStorage(product2)) assert.is_same(0, player:getProductStorage(product3)) assert.is_same(25, player:getMaxProductStorage(product3)) assert.is_same(25, player:getEmptyProductStorage(product3)) player:modifyProductStorage(product1, 10) assert.is_same(10, player:getProductStorage(product1)) assert.is_same(100, player:getMaxProductStorage(product1)) assert.is_same(90, player:getEmptyProductStorage(product1)) assert.is_same(0, player:getProductStorage(product2)) assert.is_same(45, player:getMaxProductStorage(product2)) assert.is_same(45, player:getEmptyProductStorage(product2)) assert.is_same(0, player:getProductStorage(product3)) assert.is_same(22, player:getMaxProductStorage(product3)) assert.is_same(22, player:getEmptyProductStorage(product3)) player:modifyProductStorage(product2, 10) assert.is_same(10, player:getProductStorage(product1)) assert.is_same(80, player:getMaxProductStorage(product1)) assert.is_same(70, player:getEmptyProductStorage(product1)) assert.is_same(10, player:getProductStorage(product2)) assert.is_same(45, player:getMaxProductStorage(product2)) assert.is_same(35, player:getEmptyProductStorage(product2)) assert.is_same(0, player:getProductStorage(product3)) assert.is_same(17, player:getMaxProductStorage(product3)) assert.is_same(17, player:getEmptyProductStorage(product3)) player:modifyProductStorage(product2, -5) assert.is_same(10, player:getProductStorage(product1)) assert.is_same(90, player:getMaxProductStorage(product1)) assert.is_same(80, player:getEmptyProductStorage(product1)) assert.is_same(5, player:getProductStorage(product2)) assert.is_same(45, player:getMaxProductStorage(product2)) assert.is_same(40, player:getEmptyProductStorage(product2)) assert.is_same(0, player:getProductStorage(product3)) assert.is_same(20, player:getMaxProductStorage(product3)) assert.is_same(20, player:getEmptyProductStorage(product3)) player:modifyProductStorage(product3, 5) assert.is_same(10, player:getProductStorage(product1)) assert.is_same(70, player:getMaxProductStorage(product1)) assert.is_same(60, player:getEmptyProductStorage(product1)) assert.is_same(5, player:getProductStorage(product2)) assert.is_same(35, player:getMaxProductStorage(product2)) assert.is_same(30, player:getEmptyProductStorage(product2)) assert.is_same(5, player:getProductStorage(product3)) assert.is_same(20, player:getMaxProductStorage(product3)) assert.is_same(15, player:getEmptyProductStorage(product3)) end) it("they fail when called without argument", function() local player = PlayerSpaceship() Player:withStorage(player) assert.has_error(function() player:getProductStorage() end) assert.has_error(function() player:getMaxProductStorage() end) assert.has_error(function() player:getEmptyProductStorage() end) end) it("works with rockets", function() local hvli = Product:new("HVLI", {id = "hvli"}) local player = PlayerSpaceship() Player:withStorage(player) player:setWeaponStorageMax("hvli", 8) player:setWeaponStorage("hvli", 6) assert.is_same(6, player:getProductStorage(hvli)) assert.is_same(8, player:getMaxProductStorage(hvli)) assert.is_same(2, player:getEmptyProductStorage(hvli)) for _, weapon in pairs({"hvli", "homing", "mine", "nuke", "emp"}) do local rocket = Product:new(weapon, {id = weapon}) player:setWeaponStorageMax(weapon, 0) player:setWeaponStorage(weapon, 0) assert.is_same(0, player:getProductStorage(rocket)) assert.is_same(0, player:getMaxProductStorage(rocket)) assert.is_same(0, player:getEmptyProductStorage(rocket)) end end) it("works with scan probes", function() local probe = Product:new("Scan Probe", {id = "scanProbe"}) local player = PlayerSpaceship() Player:withStorage(player) player:setMaxScanProbeCount(8) player:setScanProbeCount(6) assert.is_same(6, player:getProductStorage(probe)) assert.is_same(8, player:getMaxProductStorage(probe)) assert.is_same(2, player:getEmptyProductStorage(probe)) player:setMaxScanProbeCount(0) player:setScanProbeCount(0) assert.is_same(0, player:getProductStorage(probe)) assert.is_same(0, player:getMaxProductStorage(probe)) assert.is_same(0, player:getEmptyProductStorage(probe)) end) end) describe("getStorageSpace(), getEmptyStorageSpace(), getMaxStorageSpace()", function() it("returns the correct value", function() local player = PlayerSpaceship() Player:withStorage(player, {maxStorage = 100}) assert.is_same(0, player:getStorageSpace()) assert.is_same(100, player:getMaxStorageSpace()) assert.is_same(100, player:getEmptyStorageSpace()) player:modifyProductStorage(product1, 10) assert.is_same(10, player:getStorageSpace()) assert.is_same(100, player:getMaxStorageSpace()) assert.is_same(90, player:getEmptyStorageSpace()) player:modifyProductStorage(product2, 10) assert.is_same(20, player:getStorageSpace()) assert.is_same(100, player:getMaxStorageSpace()) assert.is_same(80, player:getEmptyStorageSpace()) player:modifyProductStorage(product2, -5) assert.is_same(15, player:getStorageSpace()) assert.is_same(100, player:getMaxStorageSpace()) assert.is_same(85, player:getEmptyStorageSpace()) end) it("returns the correct values for sized products", function() local product1 = productMock() local product2 = productMock() local product3 = productMock() product1.getSize = function() return 1 end product2.getSize = function() return 2 end product3.getSize = function() return 4 end local player = PlayerSpaceship() Player:withStorage(player, {maxStorage = 100}) assert.is_same(0, player:getStorageSpace()) assert.is_same(100, player:getMaxStorageSpace()) assert.is_same(100, player:getEmptyStorageSpace()) player:modifyProductStorage(product1, 10) assert.is_same(10, player:getStorageSpace()) assert.is_same(100, player:getMaxStorageSpace()) assert.is_same(90, player:getEmptyStorageSpace()) player:modifyProductStorage(product2, 10) assert.is_same(30, player:getStorageSpace()) assert.is_same(100, player:getMaxStorageSpace()) assert.is_same(70, player:getEmptyStorageSpace()) player:modifyProductStorage(product2, -5) assert.is_same(20, player:getStorageSpace()) assert.is_same(100, player:getMaxStorageSpace()) assert.is_same(80, player:getEmptyStorageSpace()) player:modifyProductStorage(product3, 5) assert.is_same(40, player:getStorageSpace()) assert.is_same(100, player:getMaxStorageSpace()) assert.is_same(60, player:getEmptyStorageSpace()) end) end) describe(":modifyProductStorage()", function() it("it allows to overload the storage so that important mission items are not lost", function() local player = PlayerSpaceship() Player:withStorage(player, {maxStorage = 100}) assert.is_same(0, player:getStorageSpace()) assert.is_same(100, player:getMaxStorageSpace()) assert.is_same(100, player:getEmptyStorageSpace()) assert.is_same(0, player:getProductStorage(product1)) assert.is_same(100, player:getMaxProductStorage(product1)) assert.is_same(100, player:getEmptyProductStorage(product1)) assert.is_same(0, player:getProductStorage(product2)) assert.is_same(100, player:getMaxProductStorage(product2)) assert.is_same(100, player:getEmptyProductStorage(product2)) player:modifyProductStorage(product1, 999) assert.is_same(999, player:getStorageSpace()) assert.is_same(100, player:getMaxStorageSpace()) assert.is_same(0, player:getEmptyStorageSpace()) assert.is_same(999, player:getProductStorage(product1)) assert.is_same(100, player:getMaxProductStorage(product1)) assert.is_same(0, player:getEmptyProductStorage(product1)) assert.is_same(0, player:getProductStorage(product2)) assert.is_same(0, player:getMaxProductStorage(product2)) assert.is_same(0, player:getEmptyProductStorage(product2)) end) it("it keeps sure the storage level will not be negative", function() local player = PlayerSpaceship() Player:withStorage(player, {maxStorage = 100}) assert.is_same(0, player:getStorageSpace()) assert.is_same(100, player:getMaxStorageSpace()) assert.is_same(100, player:getEmptyStorageSpace()) assert.is_same(0, player:getProductStorage(product1)) assert.is_same(100, player:getMaxProductStorage(product1)) assert.is_same(100, player:getEmptyProductStorage(product1)) assert.is_same(0, player:getProductStorage(product2)) assert.is_same(100, player:getMaxProductStorage(product2)) assert.is_same(100, player:getEmptyProductStorage(product2)) player:modifyProductStorage(product1, -10) assert.is_same(0, player:getStorageSpace()) assert.is_same(100, player:getMaxStorageSpace()) assert.is_same(100, player:getEmptyStorageSpace()) assert.is_same(0, player:getProductStorage(product1)) assert.is_same(100, player:getMaxProductStorage(product1)) assert.is_same(100, player:getEmptyProductStorage(product1)) assert.is_same(0, player:getProductStorage(product2)) assert.is_same(100, player:getMaxProductStorage(product2)) assert.is_same(100, player:getEmptyProductStorage(product2)) end) it("fails if no product is given", function() local player = PlayerSpaceship() Player:withStorage(player) assert.has_error(function() player:modifyProductStorage(nil, 10) end) end) it("fails if no amount is given", function() local player = PlayerSpaceship() Player:withStorage(player) assert.has_error(function() player:modifyProductStorage(product1, nil) end) end) it("allows to handle rockets", function() local player = PlayerSpaceship() Player:withStorage(player) for _, weapon in pairs({"hvli", "homing", "mine", "nuke", "emp"}) do local rocket = Product:new(weapon, {id = weapon}) player:setWeaponStorageMax(weapon, 4) player:setWeaponStorage(weapon, 0) player:modifyProductStorage(rocket, 2) assert.is_same(2, player:getWeaponStorage(weapon)) end end) it("allows to handle scan probes", function() local probe = Product:new("Scan Probe", {id = "scanProbe"}) local player = PlayerSpaceship() Player:withStorage(player) player:setMaxScanProbeCount(4) player:setScanProbeCount(0) player:modifyProductStorage(probe, 2) assert.is_same(2, player:getScanProbeCount()) end) end) describe(":setMaxStorageSpace()", function() it("allows to set the maximum storage space", function() local player = PlayerSpaceship() Player:withStorage(player, {maxStorage = 100}) assert.is_same(0, player:getStorageSpace()) assert.is_same(100, player:getMaxStorageSpace()) assert.is_same(100, player:getEmptyStorageSpace()) player:setMaxStorageSpace(120) assert.is_same(0, player:getStorageSpace()) assert.is_same(120, player:getMaxStorageSpace()) assert.is_same(120, player:getEmptyStorageSpace()) end) end) end)
46.170561
115
0.6527
738f2abbb84a028998a7cebb463436c0df03c832
61
rs
Rust
src/build_information.rs
shinnya/frugalos
ba38e0b8edd3f767fe9a6bb236dfbd8c0700c407
[ "MIT" ]
321
2018-10-26T02:43:49.000Z
2022-03-28T07:22:12.000Z
src/build_information.rs
shinnya/frugalos
ba38e0b8edd3f767fe9a6bb236dfbd8c0700c407
[ "MIT" ]
181
2018-10-26T02:44:45.000Z
2021-01-22T02:58:20.000Z
src/build_information.rs
shinnya/frugalos
ba38e0b8edd3f767fe9a6bb236dfbd8c0700c407
[ "MIT" ]
23
2018-10-26T06:54:26.000Z
2022-01-23T16:56:16.000Z
include!(concat!(env!("OUT_DIR"), "/build_information.rs"));
30.5
60
0.688525
becfcc53e1932b0e7d6f440f834e938f894288e6
337
rs
Rust
parser/src/internal/parser_impl/sub_parser_impl.rs
j5ik2o/parsing-rust
a951c7f0712a36d5e4fe93032c377b97f99b450a
[ "Apache-2.0", "MIT" ]
18
2021-11-09T07:34:55.000Z
2022-03-29T08:54:29.000Z
parser/src/internal/parser_impl/sub_parser_impl.rs
j5ik2o/parsing-rust
a951c7f0712a36d5e4fe93032c377b97f99b450a
[ "Apache-2.0", "MIT" ]
1
2021-11-06T11:52:59.000Z
2021-11-06T11:52:59.000Z
parser/src/internal/parser_impl/sub_parser_impl.rs
j5ik2o/oni-comb-rs
39e1810ff7b043531c672306b4443964861d266d
[ "Apache-2.0", "MIT" ]
null
null
null
use crate::core::Parser; use crate::extension::parser::SkipParser; use std::fmt::Debug; use std::ops::Sub; impl<'a, I, A, B> Sub<Parser<'a, I, B>> for Parser<'a, I, A> where A: Clone + Debug + 'a, B: Clone + Debug + 'a, { type Output = Self; fn sub(self, rhs: Parser<'a, I, B>) -> Self::Output { self.skip_right(rhs) } }
19.823529
60
0.593472
189d667c8523708afdbc376f68ba005e6b0f5fb6
86
kt
Kotlin
Android/app/src/main/java/com/versilistyson/searchflix/presentation/ui/common/StateComponent.kt
vdtyson/SearchFlix
895bb09903d38952a4373bbe7dd413301771e6c9
[ "MIT" ]
1
2020-04-28T01:05:50.000Z
2020-04-28T01:05:50.000Z
Android/app/src/main/java/com/versilistyson/searchflix/presentation/ui/common/StateComponent.kt
vdtyson/SearchFlix
895bb09903d38952a4373bbe7dd413301771e6c9
[ "MIT" ]
null
null
null
Android/app/src/main/java/com/versilistyson/searchflix/presentation/ui/common/StateComponent.kt
vdtyson/SearchFlix
895bb09903d38952a4373bbe7dd413301771e6c9
[ "MIT" ]
null
null
null
package com.versilistyson.searchflix.presentation.ui.common interface StateComponent
21.5
59
0.883721
0c91e1c1cf29e15371a4ee6e5142850adc128722
1,657
py
Python
utilities/visualisation/log_file_plotter.py
bootml/agent
84235db931d6e4ef956962961c619994898ebdd5
[ "Apache-2.0" ]
null
null
null
utilities/visualisation/log_file_plotter.py
bootml/agent
84235db931d6e4ef956962961c619994898ebdd5
[ "Apache-2.0" ]
null
null
null
utilities/visualisation/log_file_plotter.py
bootml/agent
84235db931d6e4ef956962961c619994898ebdd5
[ "Apache-2.0" ]
1
2018-09-27T14:31:41.000Z
2018-09-27T14:31:41.000Z
#!/usr/bin/env python3 # -*- coding: utf-8 -*- __author__ = 'cnheider' import csv import matplotlib.pyplot as plt import utilities as U # print(plt.style.available) plot_style = 'fivethirtyeight' # plot_style='bmh' # plot_style='ggplot' plt.style.use('seaborn-poster') plt.style.use(plot_style) plt.rcParams['axes.edgecolor'] = '#ffffff' plt.rcParams['axes.facecolor'] = '#ffffff' plt.rcParams['figure.facecolor'] = '#ffffff' plt.rcParams['patch.edgecolor'] = '#ffffff' plt.rcParams['patch.facecolor'] = '#ffffff' plt.rcParams['savefig.edgecolor'] = '#ffffff' plt.rcParams['savefig.facecolor'] = '#ffffff' plt.rcParams['xtick.labelsize'] = 16 plt.rcParams['ytick.labelsize'] = 16 # set up matplotlib is_ipython = 'inline' in plt.get_backend() if is_ipython: pass plt.ion() def simple_plot(file_path, name='Statistic Name'): with open(file_path, 'r') as f: agg = U.StatisticAggregator() reader = csv.reader(f, delimiter=' ', quotechar='|') for line in reader: agg.append(float(line[0])) plt.plot(agg.values) plt.title(name) plt.show() if __name__ == '__main__': # import configs.base_config as C # _list_of_files = list(C.LOG_DIRECTORY.glob('*.csv')) # _latest_model = max(_list_of_files, key=os.path.getctime) from tkinter import Tk from tkinter.filedialog import askopenfilename # import easygui # print easygui.fileopenbox() Tk().withdraw() # we don't want a full GUI, so keep the root window from appearing file_path = askopenfilename() # show an "Open" dialog box and return the path to the selected file file_name = file_path.split('/')[-1] simple_plot(file_path, file_name)
25.106061
101
0.703681
dc590a9afe4c09a37b2c9452948dce484d4aad05
1,080
swift
Swift
ExposurePlaybackTests/Program+Extensions.swift
EricssonBroadcastServices/iOSClientExposurePlayback
ddd54b285db84ac37740fa4d9a212dc25547b004
[ "Apache-2.0" ]
null
null
null
ExposurePlaybackTests/Program+Extensions.swift
EricssonBroadcastServices/iOSClientExposurePlayback
ddd54b285db84ac37740fa4d9a212dc25547b004
[ "Apache-2.0" ]
2
2018-11-28T12:17:26.000Z
2018-12-14T10:59:27.000Z
ExposurePlaybackTests/Program+Extensions.swift
EricssonBroadcastServices/iOSClientExposurePlayback
ddd54b285db84ac37740fa4d9a212dc25547b004
[ "Apache-2.0" ]
2
2018-03-07T20:49:38.000Z
2019-02-07T08:13:59.000Z
// // Program+Extensions.swift // ExposurePlaybackTests // // Created by Fredrik Sjöberg on 2018-02-11. // Copyright © 2018 emp. All rights reserved. // import Foundation import Exposure extension Program { static func validJson(programId: String, channelId: String, assetId: String) -> [String: Any] { return [ "programId": programId, "assetId": assetId, "channelId": channelId ] } } extension Dictionary where Key == String, Value == Any { func timestamp(starting: Int64, ending: Int64) -> Dictionary<String,Any> { var old = self let start = Date(milliseconds: starting) let end = Date(milliseconds: ending) let formatter = DateFormatter() formatter.locale = Locale(identifier: "en_GB") formatter.timeZone = TimeZone(abbreviation: "UTC") formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'" old["startTime"] = formatter.string(from: start) old["endTime"] = formatter.string(from: end) return old } }
28.421053
99
0.615741
0de769f59336ec4e5a209258197a1adf422acb53
348
sql
SQL
src/test/resources/liquibase/harness/change/expectedSql/mssql/addForeignKey.sql
AlexanderSashchenko/liquibase-test-harness
c626754b75e6470aa03bf6fb88073ff073039862
[ "Apache-2.0" ]
1
2021-02-25T04:30:04.000Z
2021-02-25T04:30:04.000Z
src/test/resources/liquibase/harness/change/expectedSql/mssql/addForeignKey.sql
AlexanderSashchenko/liquibase-test-harness
c626754b75e6470aa03bf6fb88073ff073039862
[ "Apache-2.0" ]
1
2021-06-21T08:40:11.000Z
2021-06-21T13:32:01.000Z
src/main/resources/liquibase/harness/change/expectedSql/mssql/addForeignKey.sql
Sfurti-yb/liquibase-test-harness
86b413938f13d9d899fc010ca42f26041b6fccb8
[ "Apache-2.0" ]
1
2021-03-08T20:36:14.000Z
2021-03-08T20:36:14.000Z
CREATE TABLE lbcat2.countries (id int NOT NULL, name varchar(50), CONSTRAINT PK_COUNTRIES PRIMARY KEY (id)) CREATE TABLE person (id int IDENTITY (1, 1) NOT NULL, CONSTRAINT PK_PERSON PRIMARY KEY (id)) ALTER TABLE person ADD country_id int ALTER TABLE person ADD CONSTRAINT fk_person_country FOREIGN KEY (country_id) REFERENCES lbcat2.countries (id)
87
109
0.804598
baa86ff0cd85c070c5d65578a2e4811378718ee4
4,147
sql
SQL
pkl.sql
Danamuktisatrio/ci
48bfff2db573be84eb4ab90cf3dbd0b7eb257ea4
[ "MIT" ]
null
null
null
pkl.sql
Danamuktisatrio/ci
48bfff2db573be84eb4ab90cf3dbd0b7eb257ea4
[ "MIT" ]
null
null
null
pkl.sql
Danamuktisatrio/ci
48bfff2db573be84eb4ab90cf3dbd0b7eb257ea4
[ "MIT" ]
null
null
null
-- phpMyAdmin SQL Dump -- version 5.0.2 -- https://www.phpmyadmin.net/ -- -- Host: 127.0.0.1 -- Waktu pembuatan: 05 Okt 2021 pada 16.51 -- Versi server: 10.4.14-MariaDB -- Versi PHP: 7.2.33 SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; 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 */; -- -- Database: `pkl` -- -- -------------------------------------------------------- -- -- Struktur dari tabel `desa` -- CREATE TABLE `desa` ( `id_desa` int(50) NOT NULL, `Nama_Desa` varchar(50) NOT NULL, `id_kec` int(50) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; -- -- Dumping data untuk tabel `desa` -- INSERT INTO `desa` (`id_desa`, `Nama_Desa`, `id_kec`) VALUES (1, 'TULUNGREJO', 1), (2, 'BANJAREJO', 1), (3, 'KEDUNGSALAM', 1), (4, 'TLOGOSARI', 1), (5, 'TEMPURSARI', 1), (6, 'DONOMULYO', 1), (7, 'PURWOREJO', 1), (8, 'SUMBEROTO', 1), (9, 'MENTARAWAN', 1), (10, 'PURWODADI', 1), (11, 'WONOKERTO', 2), (12, 'REJOSARI', 2), (13, 'BANTUR', 2), (14, 'WONOREJO', 2), (15, 'SRIGONCO', 2), (16, 'SUMBERBENING', 2), (17, 'BANDUNGREJO', 2), (18, 'PRINGGONDANI', 2), (19, 'REJOYOSO', 2), (20, 'KARANGSARI', 2), (21, 'SUKODONO', 3), (22, 'SUMBERSUKO', 3), (23, 'SRIMULYO', 3), (24, 'BATURETNO', 3), (25, 'BUMIREJO', 3), (26, 'AMADANOM', 3), (27, 'PAMOTAN', 3), (28, 'MAJANGTENGAH', 3), (29, 'REMBUN', 3), (30, 'POJOK', 3), (31, 'JAMBANGAN', 3), (32, 'TAWANGREJENI', 4), (33, 'KEMULAN', 4), (34, 'SAWAHAN', 4), (35, 'UDAAN', 4), (36, 'GEDOK KULON', 4), (37, 'GEDOK WETAN', 4), (38, 'TALOK', 4), (39, 'TANGGUNG', 4), (40, 'JERU', 4), (41, 'PAGEDANGAN', 4), (42, 'SANANKERTO', 4), (43, 'SANANREJO', 4), (44, 'KEDOK', 4), (45, 'TALANGSUKO', 4), (46, 'TUMPUKRENTENG', 4), (47, 'SUMBERPUTIH', 5), (48, 'WONOAYU', 5), (49, 'BAMBANG', 5), (50, 'BRINGIN', 5), (51, 'DADAPAN', 5), (52, 'PATOKPICIS', 5), (53, 'SUMBERPUTIH', 5), (54, 'BLAYU', 5), (55, 'CODO', 5), (56, 'SUKOLILO', 5), (57, 'KIDANGBANG', 5), (58, 'SUKOANYAR', 5), (59, 'WAJAK', 5), (60, 'NGEMBAL', 5), (61, 'SUMBERMANJINGKULON', 6); -- -------------------------------------------------------- -- -- Struktur dari tabel `kecamatan` -- CREATE TABLE `kecamatan` ( `id_kec` int(11) NOT NULL, `Nama_Kec` varchar(50) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; -- -- Dumping data untuk tabel `kecamatan` -- INSERT INTO `kecamatan` (`id_kec`, `Nama_Kec`) VALUES (1, 'DONOMULYO'), (2, 'BANTUR'), (3, 'DAMPIT'), (4, 'TUREN'), (5, 'WAJAK'), (6, 'PAGAK'), (7, 'KALIPARE'), (8, 'SUMBERMANJING WETAN'), (9, 'AMPELGADING'), (10, 'PONCOKUSUMO'), (11, 'GONDANGLEGI'), (12, 'KALIPARE'), (13, 'SUMBERPUCUNG'), (14, 'KEPANJEN'), (15, 'BULULAWANG'), (16, 'TAJINAN'), (17, 'TUMPANG'), (18, 'JABUNG'), (19, 'PAKIS'), (20, 'PAKISAJI'), (21, 'NGAJUM'), (22, 'WAGIR'), (23, 'DAU'), (24, 'KARANG PLOSO'), (25, 'SINGOSARI'), (26, 'LAWANG'), (27, 'PUJON'), (28, 'NGANTANG'), (29, 'KASEMBON'), (30, 'GEDANGAN'), (31, 'TIRTOYUDO'), (32, 'KROMENGAN'), (33, 'WONOSARI'), (34, 'PAGELARAN'); -- -- Indexes for dumped tables -- -- -- Indeks untuk tabel `desa` -- ALTER TABLE `desa` ADD PRIMARY KEY (`id_desa`), ADD KEY `id_kec` (`id_kec`); -- -- Indeks untuk tabel `kecamatan` -- ALTER TABLE `kecamatan` ADD PRIMARY KEY (`id_kec`); -- -- AUTO_INCREMENT untuk tabel yang dibuang -- -- -- AUTO_INCREMENT untuk tabel `desa` -- ALTER TABLE `desa` MODIFY `id_desa` int(50) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=62; -- -- AUTO_INCREMENT untuk tabel `kecamatan` -- ALTER TABLE `kecamatan` MODIFY `id_kec` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=35; -- -- Ketidakleluasaan untuk tabel pelimpahan (Dumped Tables) -- -- -- Ketidakleluasaan untuk tabel `desa` -- ALTER TABLE `desa` ADD CONSTRAINT `desa_ibfk_1` FOREIGN KEY (`id_kec`) REFERENCES `kecamatan` (`id_kec`); 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 */;
20.631841
88
0.605739
66edd2120c6bb93feabad5126b21576a4d37ee3f
698
lua
Lua
core/world/FreeEntity.lua
henry4k/apoapsis
bbe0cc4a5aea273f570dab786fd079400e86d70e
[ "MIT" ]
null
null
null
core/world/FreeEntity.lua
henry4k/apoapsis
bbe0cc4a5aea273f570dab786fd079400e86d70e
[ "MIT" ]
12
2015-01-04T21:02:35.000Z
2015-12-14T16:35:30.000Z
core/world/FreeEntity.lua
henry4k/konstrukt
bbe0cc4a5aea273f570dab786fd079400e86d70e
[ "MIT" ]
null
null
null
--- @classmod core.world.FreeEntity local class = require 'middleclass' local EffectTarget = require 'core/EffectTarget' local Entity = require 'core/world/Entity' local FreeEntity = class('core/world/FreeEntity') FreeEntity:include(EffectTarget) FreeEntity:include(Entity) function FreeEntity:initialize() self:initializeEffectTarget() self:initializeEntity() end function FreeEntity:destroy() self:destroyEntity() self:destroyEffectTarget() end function FreeEntity:setAttachmentTarget( target ) self.attachmentTarget = target for attachable, _ in pairs(self.attachments) do attachable:setAttachmentTarget(target) end end return FreeEntity
22.516129
51
0.756447
dbe35854154ff85524a983c24c0fea5447ab2392
1,851
lua
Lua
src/util/mbg/Event/DataOperateAction.lua
Karl5766/LuaSTG-x_BHElib
8f4504fb39d5081016b3b8a123b475a3a8087e07
[ "MIT" ]
9
2019-03-15T11:50:16.000Z
2021-06-03T12:52:30.000Z
src/util/mbg/Event/DataOperateAction.lua
Karl5766/LuaSTG-x_BHElib
8f4504fb39d5081016b3b8a123b475a3a8087e07
[ "MIT" ]
2
2019-08-28T10:35:33.000Z
2020-06-23T07:15:49.000Z
src/util/mbg/Event/DataOperateAction.lua
Karl5766/LuaSTG-x_BHElib
8f4504fb39d5081016b3b8a123b475a3a8087e07
[ "MIT" ]
5
2020-06-21T05:01:48.000Z
2022-01-16T17:02:20.000Z
--- --- DataOperateAction.lua --- --- Copyright (C) 2018 Xrysnow. All rights reserved. --- local mbg = require('util.mbg.main') local String = require('util.mbg.String') ---@class mbg.DataOperateAction:mbg.IAction local DataOperateAction = {} mbg.DataOperateAction = DataOperateAction local function _DataOperateAction() ---@type mbg.DataOperateAction local ret = {} ret.LValue = '' ret.TweenTime = 0 ret.Times = 0 ret.RValue = '' ret.TweenFunction = 0 ret.Operator = 0 return ret end local mt = { __call = function() return _DataOperateAction() end } setmetatable(DataOperateAction, mt) DataOperateAction.TweenFunctionType = { Proportional = 0, Fixed = 1, Sin = 2, } local TweenFunctionType = DataOperateAction.TweenFunctionType DataOperateAction.OperatorType = { ChangeTo = 0, Add = 1, Subtraction = 2, } ---ParseFrom ---@param c mbg.String ---@return mbg.DataOperateAction function DataOperateAction.ParseFrom(c) local sents = c:split(',') ---@type mbg.DataOperateAction local d = mbg.DataOperateAction() mbg.ActionHelper.ParseFirstSentence(String(sents[1]), d) local str = sents[2] if str == '固定' then d.TweenFunction = TweenFunctionType.Fixed elseif str == '正比' then d.TweenFunction = TweenFunctionType.Proportional elseif str == '正弦' then d.TweenFunction = TweenFunctionType.Sin else error("无法解析变化曲线名称: " .. sents[2]) end local s3 = String(sents[3]) local tweenTimeEnd = s3:find('帧') d.TweenTime = s3:sub(1, tweenTimeEnd - 1):toint() d.Times = nil local timesL = s3:findlast('%(') local timesR = s3:findlast('%)') if timesL ~= -1 and timesR ~= -1 then d.Times = s3:sub(timesL + 1, timesR - 1):toint() end return d end
24.355263
61
0.640735
c3ab43de668170406e0fc76e7a9e6d47442c45fc
1,883
go
Go
app/captcha/service/internal/data/captcha.go
MrDML/home
6d76fcf3391715b3281b08dff02de28286858368
[ "MIT" ]
null
null
null
app/captcha/service/internal/data/captcha.go
MrDML/home
6d76fcf3391715b3281b08dff02de28286858368
[ "MIT" ]
null
null
null
app/captcha/service/internal/data/captcha.go
MrDML/home
6d76fcf3391715b3281b08dff02de28286858368
[ "MIT" ]
null
null
null
package data import ( "context" "encoding/json" "fmt" "github.com/afocus/captcha" "github.com/go-kratos/kratos/v2/log" "home/app/captcha/service/internal/biz" "home/app/captcha/service/util" "image/color" "time" ) type captchaRepo struct { data *Data log *log.Helper } func NewCaptchaRepo(data *Data, logger log.Logger) biz.CaptchaRepo { return &captchaRepo{data: data, log: log.NewHelper(logger)} } func (r *captchaRepo) GetCaptcha(ctx context.Context, uuid string) (img []byte, err error) { // 业务逻辑处理 // 初始化对象 cap := captcha.New() // 设置字体 cap.SetFont("./app/captcha/service/conf/comic.ttf") // 创建验证码 4 个字符 captcha.NUM 字符模式数字类型 // 设置干扰强度 cap.SetDisturbance(captcha.MEDIUM) // 设置前景色 可以多个 随机替换文字颜色 默认黑色 cap.SetFrontColor(color.RGBA{0, 0, 0, 255}) // 设置背景色 可以多个 随机替换背景色 默认是白色 cap.SetBkgColor(color.RGBA{0, 128, 128, 128}, color.RGBA{255, 0, 0, 128}) image, code := cap.Create(6, captcha.ALL) if code != "" { // 将code存入redis var key = "imageCode:" + uuid set, err := r.data.rdb.SetEX(ctx, key, code, 60 * time.Second).Result() if err != nil { panic(err) } r.log.Infof("======>save image code :%s", set) } // 序列化 imgBytes, errMarshal := json.Marshal(image) return imgBytes, errMarshal } func (r*captchaRepo) GetImageCodeFromRdb(ctx context.Context, uuid string) (string, error) { imageCode, err := r.data.rdb.Get(ctx, uuid).Result() return imageCode, err } // SendSmsCode 发送短信验证码 func (r*captchaRepo) SendSmsCode(ctx context.Context, phone string) error { code := util.GetRandNumber(6) // TODO 发送短信 // 存入redis key := "SmsCode:" + phone if _, err := r.data.rdb.SetEX(ctx, key, code, time.Second * 120).Result(); err != nil{ return err } fmt.Println("短信验证码为: ", code) return nil } // GetSmsCode 获取短信验证码 func (r*captchaRepo) GetSmsCode(ctx context.Context, phone string) (string, error) { return "", nil }
20.922222
93
0.679235
1c5cced72f5f485bec542cf4da63ac1406e6f0fd
128
css
CSS
app/client/style.css
CraigOpie/inventory
c798ffbc2b84adc5d2019fbeed4bf7d3fdaa891b
[ "MIT" ]
null
null
null
app/client/style.css
CraigOpie/inventory
c798ffbc2b84adc5d2019fbeed4bf7d3fdaa891b
[ "MIT" ]
2
2021-05-11T09:26:35.000Z
2021-09-02T09:17:09.000Z
app/client/style.css
CraigOpie/inventory
c798ffbc2b84adc5d2019fbeed4bf7d3fdaa891b
[ "MIT" ]
null
null
null
.custom-background-image { background: url('images/background.jpg') no-repeat center center fixed; background-size: cover; }
32
73
0.757813
fdc521f45a3da50b4fe5a1cd802be958ed204f4d
135
kt
Kotlin
kgl-stb/src/nativeTest/kotlin/com/kgl/stb/SampleTestsNative.kt
ArcheCraft/kgl
8abab21ec63105c633d800cba1b9347b6a7df43d
[ "Apache-2.0" ]
87
2019-02-03T20:52:44.000Z
2022-02-16T07:03:06.000Z
kgl-stb/src/nativeTest/kotlin/com/kgl/stb/SampleTestsNative.kt
ArcheCraft/kgl
8abab21ec63105c633d800cba1b9347b6a7df43d
[ "Apache-2.0" ]
29
2019-01-30T22:15:05.000Z
2021-11-23T16:23:10.000Z
kgl-stb/src/nativeTest/kotlin/com/kgl/stb/SampleTestsNative.kt
ArcheCraft/kgl
8abab21ec63105c633d800cba1b9347b6a7df43d
[ "Apache-2.0" ]
13
2019-01-30T23:34:19.000Z
2022-03-03T23:45:10.000Z
package com.kgl.stb import kotlin.test.* class SampleTestsNative { @Test fun testHello() { assertTrue("Native" in "Native") } }
12.272727
34
0.696296
3dca76f6ae2d5b37b3add66b908037dd2728057f
4,049
rs
Rust
2017/day-25/src/bin/part-1.rs
frewsxcv/advent-of-code
1de3d2c47284cfa40505f22a59b61e7579a9af0b
[ "CC0-1.0" ]
1
2018-12-01T21:12:09.000Z
2018-12-01T21:12:09.000Z
2017/day-25/src/bin/part-1.rs
frewsxcv/advent-of-code
1de3d2c47284cfa40505f22a59b61e7579a9af0b
[ "CC0-1.0" ]
null
null
null
2017/day-25/src/bin/part-1.rs
frewsxcv/advent-of-code
1de3d2c47284cfa40505f22a59b61e7579a9af0b
[ "CC0-1.0" ]
null
null
null
// Begin in state A. // Perform a diagnostic checksum after 12399302 steps. // In state A: // If the current value is 0: // - Write the value 1. // - Move one slot to the right. // If the current value is 1: // - Write the value 0. // - Move one slot to the right. // - Continue with state C. // In state B: // If the current value is 0: // - Write the value 0. // - Move one slot to the left. // - Continue with state A. // If the current value is 1: // - Write the value 0. // - Move one slot to the right. // - Continue with state D. // In state C: // If the current value is 0: // - Write the value 1. // - Move one slot to the right. // - Continue with state D. // If the current value is 1: // - Write the value 1. // - Move one slot to the right. // - Continue with state A. // In state D: // If the current value is 0: // - Write the value 1. // - Move one slot to the left. // - Continue with state E. // If the current value is 1: // - Write the value 0. // - Move one slot to the left. // - Continue with state D. // In state E: // If the current value is 0: // - Write the value 1. // - Move one slot to the right. // - Continue with state F. // If the current value is 1: // - Write the value 1. // - Move one slot to the left. // - Continue with state B. // In state F: // If the current value is 0: // - Write the value 1. // - Move one slot to the right. // - Continue with state A. // If the current value is 1: // - Write the value 1. // - Move one slot to the right. // - Continue with state E. #[derive(Copy, Clone)] enum State { A, B, C, D, E, F, } impl State { fn run(self, index: &mut usize, buf: &mut [u8]) -> State { match self { State::A if buf[*index] == 0 => { buf[*index] = 1; *index += 1; State::B } State::A if buf[*index] == 1 => { buf[*index] = 0; *index += 1; State::C } State::B if buf[*index] == 0 => { buf[*index] = 0; *index -= 1; State::A } State::B if buf[*index] == 1 => { buf[*index] = 0; *index += 1; State::D } State::C if buf[*index] == 0 => { buf[*index] = 1; *index += 1; State::D } State::C if buf[*index] == 1 => { buf[*index] = 1; *index += 1; State::A } State::D if buf[*index] == 0 => { buf[*index] = 1; *index -= 1; State::E } State::D if buf[*index] == 1 => { buf[*index] = 0; *index -= 1; State::D } State::E if buf[*index] == 0 => { buf[*index] = 1; *index += 1; State::F } State::E if buf[*index] == 1 => { buf[*index] = 1; *index -= 1; State::B } State::F if buf[*index] == 0 => { buf[*index] = 1; *index += 1; State::A } State::F if buf[*index] == 1 => { buf[*index] = 1; *index += 1; State::E } _ => unreachable!(), } } } const NUM_STEPS: usize = 12_399_302; const INIT_SIZE: usize = 12_000_000; fn main() { let mut buf = vec![0; INIT_SIZE]; let mut index = INIT_SIZE / 2; let mut state = State::A; for _ in 0..NUM_STEPS { state = state.run(&mut index, &mut buf); } let sum: u32 = buf.into_iter().map(|n| n as u32).sum(); println!("solution: {}", sum); }
26.292208
62
0.427019
d4a3e8604403f0640db0861145851181fb3a8992
4,611
rs
Rust
daemon/src/config.rs
0xpr03/cf-tool
c4b62ba00a9fcc31c84b7679406e492172c2d460
[ "ECL-2.0", "Apache-2.0" ]
1
2019-01-08T18:49:06.000Z
2019-01-08T18:49:06.000Z
daemon/src/config.rs
0xpr03/cf-tool
c4b62ba00a9fcc31c84b7679406e492172c2d460
[ "ECL-2.0", "Apache-2.0" ]
2
2017-05-19T19:01:12.000Z
2017-08-26T21:27:58.000Z
daemon/src/config.rs
0xpr03/cf-tool
c4b62ba00a9fcc31c84b7679406e492172c2d460
[ "ECL-2.0", "Apache-2.0" ]
1
2019-01-08T18:49:08.000Z
2019-01-08T18:49:08.000Z
// Copyright 2017-2020 Aron Heinecke // // 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. use serde::Deserialize; use toml::de::from_str; use std; use std::fs::{metadata, File, OpenOptions}; use std::io::Read; use std::io::Write; use std::path::Path; use std::process::exit; use crate::CONFIG_PATH; use crate::error::Error; // pub mod config; // Config section /// Custom expect function logging errors plus custom messages on panic /// &'static str to prevent the usage of format!(), which would result in overhead #[inline] pub fn l_expect<T, E: std::fmt::Debug>(result: Result<T, E>, msg: &'static str) -> T { match result { Ok(v) => v, Err(e) => { error!("{}: {:?}", msg, e); panic!(); } } } /// Config Error struct #[derive(Debug)] pub enum ConfigError { ReadError, WriteError, CreateError, } /// Config struct pub type Config = ::std::sync::Arc<InnerConfig>; #[derive(Debug, Deserialize)] pub struct InnerConfig { pub db: DBConfig, pub main: MainConfig, pub ts: TSConfig, } /// TS config struct #[derive(Debug, Deserialize)] pub struct TSConfig { pub ip: String, pub port: u16, pub user: String, pub password: String, pub server_port: u16, pub unknown_id_check_enabled: bool, pub afk_move_enabled: bool, pub enabled: bool, pub cmd_limit_secs: u16, } /// Main config struct #[derive(Debug, Deserialize)] pub struct MainConfig { pub clan_ajax_url: String, pub clan_ajax_site_key: String, pub clan_ajax_exptected_per_site: u8, pub clan_ajax_start_row_key: String, pub clan_ajax_end_row_key: String, pub clan_ajax_max_sites: u8, pub clan_url: String, pub auto_fetch_unknown_names: bool, pub auto_leave_enabled: bool, pub auto_leave_max_age: u8, pub auto_leave_message_default: String, pub time: String, pub retries: u32, pub retry_interval: String, pub send_error_mail: bool, pub mail: Vec<String>, pub mail_from: String, } /// DB Config struct #[derive(Debug, Deserialize)] pub struct DBConfig { pub user: String, pub password: Option<String>, pub port: u16, pub db: String, pub ip: String, } /// Init config, reading from file or creating such pub fn init_config() -> Config { let mut path = l_expect(::std::env::current_dir(), "config folder"); // PathBuf path.push(CONFIG_PATH); // set_file_name doesn't return smth -> needs to be run on mut path trace!("config path {:?}", path); let data: String; if metadata(&path).is_ok() { info!("Config file found."); data = l_expect(read_config(&path), "unable to read config!"); } else { info!("Config file not found."); data = default_config(); l_expect(write_config_file(&path, &data), "unable to write config"); exit(0); } l_expect(parse_config(data), "unable to parse config") } /// Parse input toml to config struct fn parse_config(input: String) -> Result<Config, Error> { let a = from_str(&input)?; Ok(a) } #[cfg(test)] pub fn default_cfg_testing() -> Config { parse_config(default_config()).unwrap() } /// Read config from file. pub fn read_config(file: &Path) -> Result<String, ConfigError> { let mut f = OpenOptions::new() .read(true) .open(file) .map_err(|_| ConfigError::ReadError)?; let mut data = String::new(); f.read_to_string(&mut data) .map_err(|_| ConfigError::ReadError)?; Ok(data) } /// Writes the recived string into the file fn write_config_file(path: &Path, data: &str) -> Result<(), ConfigError> { let mut file = File::create(path).map_err(|_| ConfigError::CreateError)?; file.write_all(data.as_bytes()) .map_err(|_| ConfigError::WriteError)?; Ok(()) } /// Create a new config. fn default_config() -> String { trace!("Creating config.."); let toml = include_str!("config.toml"); toml.to_owned() } #[cfg(test)] mod test { use super::*; #[test] fn test_default_parse() { parse_config(default_config()).unwrap(); } }
26.198864
95
0.654956
6b35382527aab887493e92af2c484b2a8c66c413
1,920
c
C
cli.c
mtratsiuk/b2c
ba23e5de130b9cbaaf42311c03865b83acf1c5f5
[ "MIT" ]
null
null
null
cli.c
mtratsiuk/b2c
ba23e5de130b9cbaaf42311c03865b83acf1c5f5
[ "MIT" ]
null
null
null
cli.c
mtratsiuk/b2c
ba23e5de130b9cbaaf42311c03865b83acf1c5f5
[ "MIT" ]
null
null
null
#include <assert.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include "cli.h" #include "darray.h" Cli cli_create(void *state) { assert(state); Darray entries = darray_create(sizeof(CliEntry), 8); Cli cli = {.menu_entries = entries, .state = state}; return cli; } CliEntry cli_create_entry(KeyCode code, char *prompt, void (*action)(void *state)) { assert(action); assert(prompt); CliEntry entry = {.code = code, .prompt = prompt, .action = action}; return entry; } void cli_add_entry(Cli *cli, CliEntry entry) { assert(cli); darray_push(&cli->menu_entries, &entry); } void print_entry_callback(void *entry, size_t index) { CliEntry *cli_entry = entry; printf("%d) %s\n", cli_entry->code - '0', cli_entry->prompt); } int find_entry_callback(void *key, void *element) { return *(KeyCode *)key - ((CliEntry *)element)->code; } void cli_start(Cli *cli) { assert(cli); int key_code = KeyCode_Enter; while (1) { if (key_code == KeyCode_Enter) { darray_foreach(&cli->menu_entries, &print_entry_callback); } key_code = getchar(); if (key_code == KeyCode_Esc) { break; } CliEntry *entry = darray_find(&cli->menu_entries, &key_code, &find_entry_callback); if (entry) { entry->action(cli->state); } puts("\n"); } } char *cli_read_str(char *prompt) { puts(prompt); size_t entry_size = sizeof(char); size_t capacity = 16; char *str = malloc(entry_size * capacity); size_t size = 0; char ch = getchar(); if (ch == KeyCode_Enter) { ch = getchar(); } while (1) { if (ch == EOF || ch == KeyCode_Enter) { break; } if (size == capacity) { capacity *= 2; str = realloc(str, entry_size * capacity); } str[size] = ch; size += 1; ch = getchar(); } return realloc(str, entry_size * (strlen(str) + 1)); }
18.823529
73
0.609375
9c682b84768d1069980f6fc6263eedbc237c9cdf
4,937
js
JavaScript
stationsubcontract/pages/beautician/index.js
leeboo741/petMall
ec8da96d973b77ea6473d473e5432e72b6252983
[ "MIT" ]
null
null
null
stationsubcontract/pages/beautician/index.js
leeboo741/petMall
ec8da96d973b77ea6473d473e5432e72b6252983
[ "MIT" ]
4
2020-01-07T03:41:11.000Z
2020-01-07T03:41:12.000Z
stationsubcontract/pages/beautician/index.js
leeboo741/petMall
ec8da96d973b77ea6473d473e5432e72b6252983
[ "MIT" ]
null
null
null
const app = getApp(); const ServerManager = require("../../../services/serverManager.js"); const UserManager = require("../../../services/userService.js"); const ShareManager = require("../../../services/shareService"); const Utils = require("../../../utils/util.js"); Page({ data: { moreImageUrl: "/resource/redright.png", bathImageUrl: "/resource/xz.png", facialImageUrl: "/resource/mr.png", spImageUrl: "/resource/tsfw.png", indicatorDots: !1, leftMargin: "0", rightMargin: "0", currentIndex: 0, preCurrentTab: 1, currentTab: 1, itemNum: 2.6, autoplay: !1, interval: 5e3, duration: 1e3, workerId: "", bottom: "", workerName: "", loading: !0, bottomHeight: "", windowHeight: wx.getSystemInfoSync().windowHeight, showToast: !1, selectedTab: 1, screenWidth: "", screenHeight: "", apointmentText: "预约", px: "", rpx: "", shopId: "", currentId: "", px: "", hastime: !1, move: {}, commentWorkerConfig: {}, instrodution: "落花有意流水无情!", businessObj: null, selectedBeauticianNo: null, }, onLoad: function (res) { if (app.globalData.serviceSelectBusiness) { this.setData({ businessObj: app.globalData.serviceSelectBusiness, selectedBeauticianNo: res.beauticianno }) for (let index = 0; index < this.data.businessObj.business.beauticians.length; index++) { let beauticianObj = this.data.businessObj.business.beauticians[index]; if (beauticianObj.beauticianID == this.data.selectedBeauticianNo) { this.setData({ currentIndex: index }) } } } let e = this; wx.getSystemInfo({ success: function (t) { Utils.logInfo(t); var a = t.windowWidth, r = t.platform, n = a / 750, i = 750 / a, o = t.windowHeight, s = o * i - 442 - 128 - 170; e.data.bottom = "ios" == r ? 35 : 15, e.setData({ bottomHeight: s, px: n, screenHeight: a, screenWidth: o, bottom: e.data.bottom + "px" }); } }); }, /** * 预约 */ outBtn: function () { this.setData({ showToast: !1 }); }, /** * 滑动上一张下一张 */ nextWorker: function (t) { var e = t.currentTarget.dataset.index, a = this.data.worderList[e].id, r = this.data.selectedTab; this.setData({ currentIndex: e, workerId: a, selectedTab: 1, preCurrentTab: r }); }, /** * swiper 触发事件 */ handleChange: function (t) { var e = t.detail.current, a = this.data.worderList[e].id, r = this.data.selectedTab; this.setData({ currentIndex: e, workerId: a, selectedTab: 1, preCurrentTab: r }); }, /** * 选择(简介、作品、评价) */ changeTab: function (e) { var r = this, i = e.target.dataset.tab, o = this.data.selectedTab; if (1 == i) { this.setData({ selectedTab: 1 }); } if (2 == i) { this.setData({ selectedTab: 2 }); } else if (3 == i) { this.setData({ selectedTab: 3 }); } }, /** * 点赞 */ dianzan: function (res) { let index = res.currentTarget.dataset.index; let able = res.currentTarget.dataset.able; let workId = res.currentTarget.dataset.workid; let that = this; if (able) { UserManager.isLogin(function isLoginCallback() { ServerManager.addWorkLike(workId, UserManager.getBusinessNo(), function addWorkLikeCallback(result) { let num = app.globalData.serviceSelectBusiness.business.beauticians[that.data.currentIndex].works[index].likeNum + 1; app.globalData.serviceSelectBusiness.business.beauticians[that.data.currentIndex].works[index].likeNum = num; that.setData({ businessObj: app.globalData.serviceSelectBusiness }) }) }) } }, /** * 预约按钮修改预约取消 */ apointment: function () { this.setData({ showToast: !false }) }, cancel: function () { this.setData({ showToast: !1 }); }, /** * -------服务选择 */ toReservation: function (res) { let beauticianIndex = this.data.currentIndex; let beauticianObj = this.data.businessObj.business.beauticians[beauticianIndex]; app.globalData.serviceSelectBeautician = beauticianObj; let serverTypeNo = res.currentTarget.dataset.servertypeno; let serverType = this.data.businessObj.business.serverTypes[res.currentTarget.dataset.index]; app.globalData.serviceSelectServerType = serverType app.globalData.serviceSelectServer = serverType.services[0]; wx.navigateTo({ url: '/stationsubcontract/pages/appointment/index' }) this.setData({ showToast: !1 }); }, /** * 用户点击右上角分享 */ onShareAppMessage: function () { return ShareManager.getDefaultShareCard(); }, });
24.20098
127
0.584768
b16a7ba63b1d246da37f6e763a05f48f0dc67744
924
h
C
Aplicacion Movil/generated/bundles/login-transition/build/Android/Preview/app/src/main/include/Fuse.Triggers.Actions-5821cb24.h
marferfer/SpinOff-LoL
a9dba8ac9dd476ec1ef94712d9a8e76d3b45aca8
[ "Apache-2.0" ]
null
null
null
Aplicacion Movil/generated/bundles/login-transition/build/Android/Preview/app/src/main/include/Fuse.Triggers.Actions-5821cb24.h
marferfer/SpinOff-LoL
a9dba8ac9dd476ec1ef94712d9a8e76d3b45aca8
[ "Apache-2.0" ]
null
null
null
Aplicacion Movil/generated/bundles/login-transition/build/Android/Preview/app/src/main/include/Fuse.Triggers.Actions-5821cb24.h
marferfer/SpinOff-LoL
a9dba8ac9dd476ec1ef94712d9a8e76d3b45aca8
[ "Apache-2.0" ]
null
null
null
// This file was generated based on C:/Users/JuanJose/AppData/Local/Fusetools/Packages/Fuse.Triggers/1.9.0/Actions/DebugProperty.uno. // WARNING: Changes might be lost if you edit this file directly. #pragma once #include <Uno.Object.h> namespace g{ namespace Fuse{ namespace Triggers{ namespace Actions{ // public abstract interface ITaggedDebugProperty :6 // { uInterfaceType* ITaggedDebugProperty_typeof(); struct ITaggedDebugProperty { void(*fp_GetStringValue)(uObject*, uString**); void(*fp_GetTag)(uObject*, uString**); static uString* GetStringValue(const uInterface& __this) { uString* __retval; return __this.VTable<ITaggedDebugProperty>()->fp_GetStringValue(__this, &__retval), __retval; } static uString* GetTag(const uInterface& __this) { uString* __retval; return __this.VTable<ITaggedDebugProperty>()->fp_GetTag(__this, &__retval), __retval; } }; // } }}}} // ::g::Fuse::Triggers::Actions
35.538462
177
0.755411
0c8967029f04eaa76a7e75ae4334c986e1287fc3
1,887
py
Python
dataset_generator/learning/imitation/tensorflow/_layers.py
rjean/duckie-segmentation
5e720e1a96ef61c4560823030549ac1d5d16e2a4
[ "Apache-2.0" ]
1
2021-02-03T02:23:34.000Z
2021-02-03T02:23:34.000Z
dataset_generator/learning/imitation/tensorflow/_layers.py
rjean/mobile-segmentation
5e720e1a96ef61c4560823030549ac1d5d16e2a4
[ "Apache-2.0" ]
null
null
null
dataset_generator/learning/imitation/tensorflow/_layers.py
rjean/mobile-segmentation
5e720e1a96ef61c4560823030549ac1d5d16e2a4
[ "Apache-2.0" ]
null
null
null
import tensorflow as tf L2_LAMBDA = 1e-04 def _residual_block(x, size, dropout=False, dropout_prob=0.5, seed=None): residual = tf.layers.batch_normalization(x) # TODO: check if the defaults in Tf are the same as in Keras residual = tf.nn.relu(residual) residual = tf.layers.conv2d( residual, filters=size, kernel_size=3, strides=2, padding="same", kernel_initializer=tf.keras.initializers.he_normal(seed=seed), kernel_regularizer=tf.keras.regularizers.l2(L2_LAMBDA), ) if dropout: residual = tf.nn.dropout(residual, dropout_prob, seed=seed) residual = tf.layers.batch_normalization(residual) residual = tf.nn.relu(residual) residual = tf.layers.conv2d( residual, filters=size, kernel_size=3, padding="same", kernel_initializer=tf.keras.initializers.he_normal(seed=seed), kernel_regularizer=tf.keras.regularizers.l2(L2_LAMBDA), ) if dropout: residual = tf.nn.dropout(residual, dropout_prob, seed=seed) return residual def one_residual(x, keep_prob=0.5, seed=None): nn = tf.layers.conv2d( x, filters=32, kernel_size=5, strides=2, padding="same", kernel_initializer=tf.keras.initializers.he_normal(seed=seed), kernel_regularizer=tf.keras.regularizers.l2(L2_LAMBDA), ) nn = tf.layers.max_pooling2d(nn, pool_size=3, strides=2) rb_1 = _residual_block(nn, 32, dropout_prob=keep_prob, seed=seed) nn = tf.layers.conv2d( nn, filters=32, kernel_size=1, strides=2, padding="same", kernel_initializer=tf.keras.initializers.he_normal(seed=seed), kernel_regularizer=tf.keras.regularizers.l2(L2_LAMBDA), ) nn = tf.keras.layers.add([rb_1, nn]) nn = tf.layers.flatten(nn) return nn
29.484375
109
0.650768
19cc48afe8a6bcf2bffbab4b2a313a112ec7033f
2,885
sql
SQL
sql/_13_issues/_12_2h/cases/bug_bts_7856_4.sql
Zhaojia2019/cubrid-testcases
475a828e4d7cf74aaf2611fcf791a6028ddd107d
[ "BSD-3-Clause" ]
9
2016-03-24T09:51:52.000Z
2022-03-23T10:49:47.000Z
sql/_13_issues/_12_2h/cases/bug_bts_7856_4.sql
Zhaojia2019/cubrid-testcases
475a828e4d7cf74aaf2611fcf791a6028ddd107d
[ "BSD-3-Clause" ]
173
2016-04-13T01:16:54.000Z
2022-03-16T07:50:58.000Z
sql/_13_issues/_12_2h/cases/bug_bts_7856_4.sql
Zhaojia2019/cubrid-testcases
475a828e4d7cf74aaf2611fcf791a6028ddd107d
[ "BSD-3-Clause" ]
38
2016-03-24T17:10:31.000Z
2021-10-30T22:55:45.000Z
--TEST: [Merge Statement] The tuples that are not updated by the update_clause can be deleted by the delete_clause when the update_clause is with where conditions. drop table if exists t1, t2; create table t1(a int, b char(10)); insert into t1 values(1, 'aaa'); insert into t1 values(2, 'bbb'); insert into t1 values(3, 'ccc'); create table t2(a int, b char(10)); insert into t2 values(1, 'AAA'); insert into t2 values(2, 'BBB'); insert into t2 values(4, 'DDD'); merge into t1 using (select * from t2 where t2.a > 1) as d on (t1.a = d.a) when matched then update set t1.b = d.b where t1.a > 1 delete where t1.b='bbb'; select * from t1 order by 1; drop table t1, t2; create table t1(a int, b char(10)); insert into t1 values(1, 'aaa'); insert into t1 values(2, 'bbb'); insert into t1 values(3, 'ccc'); create table t2(a int, b char(10)); insert into t2 values(1, 'AAA'); insert into t2 values(2, 'BBB'); insert into t2 values(4, 'DDD'); create trigger trg before update on t1 execute insert into t2 values (NULL, NULL); merge into t1 using (select * from t2 where t2.a > 1) as d on (t1.a = d.a) when matched then update set t1.b = d.b where t1.a > 3 delete where t1.b='bbb'; select * from t1 order by 1; drop table t1, t2; --- default create table t1(a int , b char(10) default 'zzz'); insert into t1 values(1, 'aaa'); insert into t1 values(2, 'bbb'); insert into t1 values(3, 'ccc'); create table t2(a int, b char(10) default 'www'); insert into t2 values(1, 'AAA'); insert into t2 values(2, 'BBB'); insert into t2 values(4, 'DDD'); merge into t1 using (select * from t2 where t2.a > 1) as d on (t1.a = d.a) when matched then update set t1.b = default where t1.a > 1 delete where t1.b='zzz'; select * from t1 order by 1; drop table t1, t2; create table t1(a int , b char(10)); insert into t1 values(1, 'aaa'); insert into t1 values(2, 'bbb'); insert into t1 values(3, 'ccc'); create table t2(a int, b char(10)); insert into t2 values(1, 'AAA'); insert into t2 values(2, 'BBB'); insert into t2 values(4, 'DDD'); merge into t1 using (select * from t2 where t2.a > 1) as d on (t1.a = d.a) when matched then update set t1.b = left(d.b,1) where t1.a > 1 delete where left(t1.b,1)='B'; select * from t1 order by 1; drop table t1, t2; create table t1(a int , b char(10)); insert into t1 values(1, 'aaa'); insert into t1 values(2, 'bbb'); insert into t1 values(3, 'ccc'); create table t2(a int, b char(10)); insert into t2 values(1, 'AAA'); insert into t2 values(2, 'BBB'); insert into t2 values(4, 'DDD'); create trigger trg before update on t1 execute insert into t2 values (NULL, NULL); merge into t1 using (select * from t2 where t2.a > 1) as d on (t1.a = d.a) when matched then update set t1.b = left(d.b, 1) where t1.a > 1 delete where left(t1.b,1) > 'B'; select * from t1 order by 1; select if(count(*)=4, 'ok', 'nok') from t2; drop table t1, t2;
26.46789
163
0.669671
07f55c86a6ddc00beb02a1064badf44dc0b8c12a
8,713
swift
Swift
Source/UI/Effects/TimeStretch/TimeStretchUnitViewController.swift
kartik-venugopal/aural-player
73e1e2768563094da63a73bddb4e22b3469ebf3a
[ "MIT" ]
21
2022-02-07T23:42:43.000Z
2022-03-17T12:07:28.000Z
Source/UI/Effects/TimeStretch/TimeStretchUnitViewController.swift
kartik-venugopal/aural-player
73e1e2768563094da63a73bddb4e22b3469ebf3a
[ "MIT" ]
2
2022-03-01T20:20:27.000Z
2022-03-07T14:23:04.000Z
Source/UI/Effects/TimeStretch/TimeStretchUnitViewController.swift
kartik-venugopal/aural-player
73e1e2768563094da63a73bddb4e22b3469ebf3a
[ "MIT" ]
3
2022-02-10T16:42:31.000Z
2022-03-18T11:11:48.000Z
// // TimeStretchUnitViewController.swift // Aural // // Copyright © 2021 Kartik Venugopal. All rights reserved. // // This software is licensed under the MIT software license. // See the file "LICENSE" in the project root directory for license terms. // import Cocoa /* View controller for the Time effects unit */ class TimeStretchUnitViewController: EffectsUnitViewController { override var nibName: String? {"TimeStretchUnit"} // ------------------------------------------------------------------------ // MARK: UI fields @IBOutlet weak var timeStretchUnitView: TimeStretchUnitView! // ------------------------------------------------------------------------ // MARK: Services, utilities, helpers, and properties var timeStretchUnit: TimeStretchUnitDelegateProtocol = objectGraph.audioGraphDelegate.timeStretchUnit // ------------------------------------------------------------------------ // MARK: UI initialization / life-cycle override func awakeFromNib() { super.awakeFromNib() effectsUnit = graph.timeStretchUnit presetsWrapper = PresetsWrapper<TimeStretchPreset, TimeStretchPresets>(timeStretchUnit.presets) } override func oneTimeSetup() { super.oneTimeSetup() timeStretchUnitView.initialize(stateFunction: unitStateFunction) } override func initControls() { super.initControls() timeStretchUnitView.setState(rate: timeStretchUnit.rate, rateString: timeStretchUnit.formattedRate, shiftPitch: timeStretchUnit.shiftPitch, shiftPitchString: timeStretchUnit.formattedPitch) } // ------------------------------------------------------------------------ // MARK: Actions // Activates/deactivates the Time stretch effects unit @IBAction override func bypassAction(_ sender: AnyObject) { super.bypassAction(sender) // The playback rate may have changed, send out a notification messenger.publish(.effects_playbackRateChanged, payload: timeStretchUnit.effectiveRate) } // Updates the playback rate value @IBAction func timeStretchAction(_ sender: AnyObject) { timeStretchUnit.rate = timeStretchUnitView.rate timeStretchUnitView.setRate(timeStretchUnit.rate, rateString: timeStretchUnit.formattedRate, shiftPitchString: timeStretchUnit.formattedPitch) // If the unit is active, publish a notification that the playback rate has changed. Other UI elements may need to be updated as a result. if timeStretchUnit.isActive { messenger.publish(.effects_playbackRateChanged, payload: timeStretchUnit.rate) } } private let oneTenth: Float = 1.0 / 10.0 private let oneHundredth: Float = 1.0 / 100.0 @IBAction func increaseRateByTenthAction(_ sender: AnyObject) { _ = timeStretchUnit.increaseRate(by: oneTenth) timeStretchUnitView.setRate(timeStretchUnit.rate, rateString: timeStretchUnit.formattedRate, shiftPitchString: timeStretchUnit.formattedPitch) // If the unit is active, publish a notification that the playback rate has changed. Other UI elements may need to be updated as a result. if timeStretchUnit.isActive { messenger.publish(.effects_playbackRateChanged, payload: timeStretchUnit.rate) } } @IBAction func increaseRateByHundredthAction(_ sender: AnyObject) { _ = timeStretchUnit.increaseRate(by: oneHundredth) timeStretchUnitView.setRate(timeStretchUnit.rate, rateString: timeStretchUnit.formattedRate, shiftPitchString: timeStretchUnit.formattedPitch) // If the unit is active, publish a notification that the playback rate has changed. Other UI elements may need to be updated as a result. if timeStretchUnit.isActive { messenger.publish(.effects_playbackRateChanged, payload: timeStretchUnit.rate) } } @IBAction func decreaseRateByTenthAction(_ sender: AnyObject) { _ = timeStretchUnit.decreaseRate(by: oneTenth) timeStretchUnitView.setRate(timeStretchUnit.rate, rateString: timeStretchUnit.formattedRate, shiftPitchString: timeStretchUnit.formattedPitch) // If the unit is active, publish a notification that the playback rate has changed. Other UI elements may need to be updated as a result. if timeStretchUnit.isActive { messenger.publish(.effects_playbackRateChanged, payload: timeStretchUnit.rate) } } @IBAction func decreaseRateByHundredthAction(_ sender: AnyObject) { _ = timeStretchUnit.decreaseRate(by: oneHundredth) timeStretchUnitView.setRate(timeStretchUnit.rate, rateString: timeStretchUnit.formattedRate, shiftPitchString: timeStretchUnit.formattedPitch) // If the unit is active, publish a notification that the playback rate has changed. Other UI elements may need to be updated as a result. if timeStretchUnit.isActive { messenger.publish(.effects_playbackRateChanged, payload: timeStretchUnit.rate) } } // Toggles the "Shift pitch" option of the Time stretch effects unit @IBAction func shiftPitchAction(_ sender: AnyObject) { timeStretchUnit.shiftPitch = timeStretchUnitView.shiftPitch timeStretchUnitView.updatePitchShift(shiftPitchString: timeStretchUnit.formattedPitch) } // ------------------------------------------------------------------------ // MARK: Message handling override func initSubscriptions() { super.initSubscriptions() messenger.subscribe(to: .timeEffectsUnit_decreaseRate, handler: decreaseRate) messenger.subscribe(to: .timeEffectsUnit_increaseRate, handler: increaseRate) messenger.subscribe(to: .timeEffectsUnit_setRate, handler: setRate(_:)) } override func stateChanged() { super.stateChanged() timeStretchUnitView.stateChanged() } // Sets the playback rate to a specific value private func setRate(_ rate: Float) { timeStretchUnit.rate = rate timeStretchUnit.ensureActive() rateChange((rate, timeStretchUnit.formattedRate)) } // Increases the playback rate by a certain preset increment private func increaseRate() { rateChange(timeStretchUnit.increaseRate()) } // Decreases the playback rate by a certain preset decrement private func decreaseRate() { rateChange(timeStretchUnit.decreaseRate()) } // Changes the playback rate to a specific value private func rateChange(_ rateInfo: (rate: Float, rateString: String)) { messenger.publish(.effects_unitStateChanged) timeStretchUnitView.setRate(rateInfo.rate, rateString: rateInfo.rateString, shiftPitchString: timeStretchUnit.formattedPitch) stateChanged() showThisTab() messenger.publish(.effects_playbackRateChanged, payload: rateInfo.rate) } // ------------------------------------------------------------------------ // MARK: Theming override func applyColorScheme(_ scheme: ColorScheme) { super.applyColorScheme(scheme) timeStretchUnitView.applyColorScheme(scheme) } override func changeSliderColors() { timeStretchUnitView.redrawSliders() } override func changeActiveUnitStateColor(_ color: NSColor) { super.changeActiveUnitStateColor(color) if timeStretchUnit.isActive { timeStretchUnitView.changeActiveUnitStateColor(color) } } override func changeBypassedUnitStateColor(_ color: NSColor) { super.changeBypassedUnitStateColor(color) if timeStretchUnit.state == .bypassed { timeStretchUnitView.changeBypassedUnitStateColor(color) } } override func changeSuppressedUnitStateColor(_ color: NSColor) { super.changeSuppressedUnitStateColor(color) if timeStretchUnit.state == .suppressed { timeStretchUnitView.changeSuppressedUnitStateColor(color) } } override func changeFunctionButtonColor(_ color: NSColor) { super.changeFunctionButtonColor(color) timeStretchUnitView.changeFunctionButtonColor(color) } }
36.456067
146
0.64157
0cdb9744480da6f8e1b4899b7fcf04b7238e340b
1,551
py
Python
MachineLearning.BayesianNetwork/python-imp/bayes_core.py
JillyMan/decision-tree
8e2efc914aaade9cc97a2c94052bc909e50fdb48
[ "MIT" ]
null
null
null
MachineLearning.BayesianNetwork/python-imp/bayes_core.py
JillyMan/decision-tree
8e2efc914aaade9cc97a2c94052bc909e50fdb48
[ "MIT" ]
1
2019-12-29T13:49:52.000Z
2019-12-29T13:49:52.000Z
MachineLearning.BayesianNetwork/python-imp/bayes_core.py
JillyMan/MachineLerningFramework
8e2efc914aaade9cc97a2c94052bc909e50fdb48
[ "MIT" ]
null
null
null
import math RangeType = 'Range' BinaryType = 'Binary' class Hipothesis: def __init__(self, id, name, p): self.id = id self.name = name self.p = p class Attribute: def __init__(self, id, name, question, _type): self.id = id self.name = name self.question = question self.type = _type class Tag: def __init__(self, hipothesis, attribute, pp, pm): self.pp = pp self.pm = pm self.attribute = attribute self.hipothesis = hipothesis class InputType: def __init__(self, _type, value): self.type = _type self.value = int(value) class Binary(InputType): def __init__(self, value): InputType.__init__(self, BinaryType, value) class Range(InputType): def __init__(self, start, end, value): InputType.__init__(self, RangeType, value) self.start = int(start) self.end = int(end) def normalize(self): l = self.end - self.start v = self.value - self.start return v / l def phe_func(p, pp, pm): return (p * pp) / (p * pp + (1-p) * pm) def calc_probs(pp, pm, p): phe = phe_func(p, pp, pm) phne = phe_func(p, 1 - pp, 1 - pm) return (phe, phne) def lerp(start, end, t): return start + (end - start) * t def interpolate_result_clamp01(phne, ph, phe, r): if r > 0.5: return lerp(ph, phe, r) elif r < 0.5: return lerp(phne, ph, r) return ph def interpolate_result_binary(phne, phe, r): return phne if r == 0 else phe
23.149254
54
0.588008
da2e3e68e442e1e9d9e4bc5a3b172b942b936234
4,113
rs
Rust
src/geometry.rs
White-Green/ray-tracing
da7c357bf88bb67429fef8f05d7eeb0c25bd1955
[ "MIT" ]
null
null
null
src/geometry.rs
White-Green/ray-tracing
da7c357bf88bb67429fef8f05d7eeb0c25bd1955
[ "MIT" ]
null
null
null
src/geometry.rs
White-Green/ray-tracing
da7c357bf88bb67429fef8f05d7eeb0c25bd1955
[ "MIT" ]
null
null
null
use std::ops::{Add, Div, Mul, Neg, Sub}; #[derive(Clone, Copy, PartialEq, Debug)] pub struct Vec3<V> { x: V, y: V, z: V, } #[derive(Clone, Copy, PartialEq, Debug)] pub struct NormalizedVec3<V> { x: V, y: V, z: V, } impl<V> Vec3<V> { pub fn new(x: V, y: V, z: V) -> Self { Self { x, y, z } } pub fn inner_product<Rhs, P: Add<Output=P>>(self, rhs: Vec3<Rhs>) -> P where V: Mul<Rhs, Output=P> { self.x * rhs.x + self.y * rhs.y + self.z * rhs.z } pub fn outer_product<Rhs: Clone, P: Sub<Output=P>>(self, rhs: Vec3<Rhs>) -> Vec3<P> where V: Mul<Rhs, Output=P> + Clone { Vec3::new( self.y.clone() * rhs.z.clone() - self.z.clone() * rhs.y.clone(), self.z * rhs.x.clone() - self.x.clone() * rhs.z, self.x * rhs.y - self.y * rhs.x, ) } pub fn squared_len<P: Add<Output=P>>(self) -> P where V: Mul<Output=P>, Self: Clone { self.clone().inner_product(self) } pub fn x(&self) -> &V { &self.x } pub fn y(&self) -> &V { &self.y } pub fn z(&self) -> &V { &self.z } } impl Vec3<f64> { pub fn normalize(self) -> NormalizedVec3<f64> { let len = self.squared_len().sqrt(); NormalizedVec3 { x: self.x / len, y: self.y / len, z: self.z / len, } } } impl<V> From<NormalizedVec3<V>> for Vec3<V> { fn from(value: NormalizedVec3<V>) -> Self { Self { x: value.x, y: value.y, z: value.z, } } } impl<V> NormalizedVec3<V> { pub fn vec(self) -> Vec3<V> { Vec3::new(self.x, self.y, self.z) } } impl<V: Add> Add for Vec3<V> { type Output = Vec3<V::Output>; fn add(self, rhs: Self) -> Self::Output { Vec3::new(self.x + rhs.x, self.y + rhs.y, self.z + rhs.z) } } impl<V: Sub> Sub for Vec3<V> { type Output = Vec3<V::Output>; fn sub(self, rhs: Self) -> Self::Output { Vec3::new(self.x - rhs.x, self.y - rhs.y, self.z - rhs.z) } } impl<V: Neg> Neg for Vec3<V> { type Output = Vec3<V::Output>; fn neg(self) -> Self::Output { Vec3::new(-self.x, -self.y, -self.z) } } impl<Rhs: Clone, V: Mul<Rhs>> Mul<Rhs> for Vec3<V> { type Output = Vec3<V::Output>; fn mul(self, rhs: Rhs) -> Self::Output { Vec3::new(self.x * rhs.clone(), self.y * rhs.clone(), self.z * rhs) } } impl<Rhs: Clone, V: Div<Rhs>> Div<Rhs> for Vec3<V> { type Output = Vec3<V::Output>; fn div(self, rhs: Rhs) -> Self::Output { Vec3::new(self.x / rhs.clone(), self.y / rhs.clone(), self.z / rhs) } } #[cfg(test)] mod tests { use crate::geometry::Vec3; #[test] fn vec3_add_test() { assert_eq!(Vec3::new(1, 2, 3) + Vec3::new(5, 7, 9), Vec3::new(6, 9, 12)); } #[test] fn vec3_sub_test() { assert_eq!(Vec3::new(1, 2, 3) - Vec3::new(5, 7, 9), Vec3::new(-4, -5, -6)); } #[test] fn vec3_mul_test() { assert_eq!(Vec3::new(1, 2, 3) * 3, Vec3::new(3, 6, 9)); } #[test] fn vec3_div_test() { assert_eq!(Vec3::new(3, 7, 11) / 3, Vec3::new(1, 2, 3)); } #[test] fn vec3_inner_product_test() { assert_eq!(Vec3::new(1, 2, 3).inner_product(Vec3::new(5, 4, 6)), 5 + 8 + 18); } #[test] fn vec3_outer_product_test() { assert_eq!(Vec3::new(1, 2, 3).outer_product(Vec3::new(5, 4, 7)), Vec3::new(2, 8, -6)); } #[test] fn vec3_normalize_test() { let normalized: Vec3<_> = Vec3::new(1f64, 2f64, 3f64).normalize().into(); let len_expect = 3.7416573867739413855837487323165; let diff = normalized - Vec3::new(1f64 / len_expect, 2f64 / len_expect, 3f64 / len_expect); assert!(diff.x().abs() < 1e-3); assert!(diff.y().abs() < 1e-3); assert!(diff.z().abs() < 1e-3); } #[test] fn vec3_util_test() { assert_eq!(Vec3::new(1, 2, 3).x(), &1); assert_eq!(Vec3::new(1, 2, 3).y(), &2); assert_eq!(Vec3::new(1, 2, 3).z(), &3); } }
23.912791
99
0.502796
daf47ed7e044d4d71f34507fe9afc4deb45a85d6
445
kt
Kotlin
app/src/main/java/com/ozantopuz/tvshows/domain/repository/TvShowRepositoryImpl.kt
ozantopuz/TvShows
5bdd206c2e6d53e93af66b8c9a504e2faa933d7a
[ "MIT" ]
null
null
null
app/src/main/java/com/ozantopuz/tvshows/domain/repository/TvShowRepositoryImpl.kt
ozantopuz/TvShows
5bdd206c2e6d53e93af66b8c9a504e2faa933d7a
[ "MIT" ]
null
null
null
app/src/main/java/com/ozantopuz/tvshows/domain/repository/TvShowRepositoryImpl.kt
ozantopuz/TvShows
5bdd206c2e6d53e93af66b8c9a504e2faa933d7a
[ "MIT" ]
null
null
null
package com.ozantopuz.tvshows.domain.repository import com.ozantopuz.tvshows.data.datasource.TvShowRemoteDataSource import com.ozantopuz.tvshows.data.entity.TvShowResponse import javax.inject.Inject class TvShowRepositoryImpl @Inject constructor( private val remoteDataSource: TvShowRemoteDataSource ) : TvShowRepository { override suspend fun fetchTvShows(page: String): TvShowResponse = remoteDataSource.fetchTvShows(page) }
34.230769
69
0.824719
e76c7bfdde731c2eb0aff7f94af971ecb42cae54
10,197
js
JavaScript
src/project-tests/product-landing-page-tests.js
karlwhite247/freeCodeCamp-testable-projects
257afa3ca2d250a9336249827a82b5ab18d4fef7
[ "BSD-3-Clause" ]
1
2017-01-03T07:20:06.000Z
2017-01-03T07:20:06.000Z
src/project-tests/product-landing-page-tests.js
karlwhite247/freeCodeCamp-testable-projects
257afa3ca2d250a9336249827a82b5ab18d4fef7
[ "BSD-3-Clause" ]
1
2016-12-28T05:21:08.000Z
2016-12-28T05:21:08.000Z
src/project-tests/product-landing-page-tests.js
karlwhite247/freeCodeCamp-testable-projects
257afa3ca2d250a9336249827a82b5ab18d4fef7
[ "BSD-3-Clause" ]
4
2016-12-28T05:17:14.000Z
2020-08-11T01:22:29.000Z
export default function createProductLandingPageTests() { describe("#Product Landing Page tests", function() { describe("#Content", function() { it('1. My product landing page should have a <header> element with corresponding id="header".', function() { FCC_Global.assert.isNotNull(document.getElementById("header"), '#header is not defined '); }); it('2. I can see an image within the #header element with a corresponding id="header-img".', function() { const img = document.getElementById("header-img"); FCC_Global.assert.isNotNull(img, '#header-img is not defined '); FCC_Global.assert.strictEqual(img.nodeName, 'IMG', '#header-img is not an <img> element ') FCC_Global.assert.strictEqual(document.querySelectorAll('#header #header-img').length, 1, '#header-img is not a child of #header '); FCC_Global.assert.strictEqual(img.hasAttribute('src'), true, '#header-img must have a src attribute '); FCC_Global.assert.include(img.src, 'http', "The src attribute\'s value should be a url (http...) "); }); it('3. Within the <header> element I can see a <nav> element with corresponding id="nav-bar".', function() { FCC_Global.assert.isNotNull(document.getElementById("nav-bar"), '#nav-bar is not defined '); FCC_Global.assert.strictEqual(document.getElementById("nav-bar").nodeName, 'NAV', 'The #nav-bar element is not a <nav> element '); FCC_Global.assert.strictEqual(document.querySelectorAll('#header #nav-bar').length, 1, '#nav-bar is not a child of #header '); }); it('4. I can see at least three clickable elements inside the nav element, each with the class "nav-link".', function() { FCC_Global.assert.isAtLeast(document.querySelectorAll('#nav-bar .nav-link').length, 3, 'There are not at least 3 elements with a class of "nav-link" within the #nav-bar element '); }); it('5. When I click a .nav-link button in the nav element, I am taken to the corresponding section of the landing page.', function() { const navLinks = document.querySelectorAll('#nav-bar .nav-link'); FCC_Global.assert.isAtLeast(document.querySelectorAll('#nav-bar .nav-link').length, 3, 'There are not at least 3 elements with a class of "nav-link" '); navLinks.forEach(link => { FCC_Global.assert.isNotNull(link); FCC_Global.assert.strictEqual(link.hasAttribute('href'), true, 'Each .nav-link element should have an href attribute '); const linkDestination = link.getAttribute('href').slice(1); FCC_Global.assert.isNotNull(document.getElementById(linkDestination), 'The .nav-link with href="' + link.getAttribute('href') + '" is not linked to a corresponding element '); }); }); it('6. I can watch an embedded product video with id="video".', function() { const video = document.getElementById("video"); FCC_Global.assert.isNotNull(video, '#video is not defined '); FCC_Global.assert(video.nodeName === 'VIDEO' || video.nodeName === 'IFRAME', '#video should be an <iframe> or <video> element '); FCC_Global.assert.strictEqual(video.hasAttribute('src'), true, '#video should have a scr attribute '); }); it('7. My landing page has a <form> element with a corresponding id="form".', function() { FCC_Global.assert.isNotNull(document.getElementById('form'), '#form is not defined '); FCC_Global.assert.strictEqual(document.getElementById('form').nodeName, 'FORM', '#form should be a <form> element '); }); it('8. Within the form, there is an <input> field with id="email" where I can enter an email address.', function() { FCC_Global.assert.isNotNull(document.getElementById("email"), '#email is not defined '); FCC_Global.assert.strictEqual(document.querySelectorAll('#form #email').length, 1, '#email should be a child of the #form element '); FCC_Global.assert.strictEqual(document.getElementById("email").nodeName, 'INPUT', '#email should be an <input> element '); }); it('9. The #email input field should have placeholder text to let the user know what the field is for.', function() { FCC_Global.assert.isNotNull(document.getElementById("email"), '#email is not defined '); FCC_Global.assert.strictEqual(document.getElementById("email").hasAttribute('placeholder'), true, 'The input field does not have placeholder text '); FCC_Global.assert.isAbove(document.getElementById("email").getAttribute('placeholder').length, 0, 'The placeholder attribute should have some text '); }); it('10. The #email input field uses HTML5 validation to confirm that the entered text is an email address.', function() { const emailField = document.getElementById("email"); FCC_Global.assert.isNotNull(document.getElementById("email"), '#email is not defined '); FCC_Global.assert.strictEqual(emailField.type, "email", "Email field should use HTML5 validation "); }); it('11. Within the form, there is a submit <input> with corresponding id="submit".', function() { const submitButton = document.getElementById("submit"); FCC_Global.assert.isNotNull(submitButton, '#submit is not defined '); FCC_Global.assert.strictEqual(document.querySelectorAll('#form #submit').length, 1, '#submit should be a child of the #form element '); FCC_Global.assert.strictEqual(submitButton.nodeName, 'INPUT', '#email should be an <input> element '); FCC_Global.assert.strictEqual(submitButton.type, 'submit', 'The input type is incorrect '); }); it('12. When I click the #submit button, the email is submitted to a static page (use this mock URL: https://www.freecodecamp.com/email-submit) that confirms the email address was entered (and that it posted successfully).', function() { const emailField = document.getElementById("email"); const form = document.getElementById('form'); const submitButton = document.getElementById('submit'); FCC_Global.assert.isNotNull(submitButton, '#submit is not defined '); FCC_Global.assert.strictEqual(form.hasAttribute('action'), true, 'The #form should have an action attribute ') FCC_Global.assert.include(form.action, 'http', "The action attribute\'s value should be a url (http...) "); FCC_Global.assert.strictEqual(emailField.hasAttribute('name'), true, 'The #email input should have a name attribute '); FCC_Global.assert.strictEqual(emailField.name, "email", 'The name attribute should have a value of "email" '); }); }); // END #Content describe('#Layout', function() { it('1. The navbar should always be at the top of the viewport.', function() { const header = document.getElementById('header'); const headerChildren = header.children; // array of all potential elements serving as a navbar const navbarCandidates = [ header, ...headerChildren ]; // get the 'top' position value from the element whose value is closest to 0 function getNavbarPosition(candidates) { // by default, set to first candidate's top value var candidatePosition = Math.abs(candidates[0].getBoundingClientRect().top); for (var i = 1; i < candidates.length; i++) { // if another candidate has a top value closer to 0, replace the old value var currentCandidatePosition = Math.abs(candidates[i].getBoundingClientRect().top); if (currentCandidatePosition < candidatePosition) { candidatePosition = currentCandidatePosition; } } return candidatePosition }; FCC_Global.assert.approximately(getNavbarPosition(navbarCandidates), 0, 15, '#header or one of its children should be at the top of the viewport '); window.scroll(0, 500); FCC_Global.assert.approximately(getNavbarPosition(navbarCandidates), 0, 15, '#header or one of its children should be at the top of the viewport even after scrolling '); window.scroll(0, 0); }); it('2. My product landing page should have at least one media query.', function() { let queryRules = []; // loop through all associated stylesheets and look for media query for (var i = 0; i < document.styleSheets.length; i++) { if (document.styleSheets[i].cssRules !== null) { for (var j = 0; j < document.styleSheets[i].cssRules.length; j++) { if (document.styleSheets[i].cssRules[j].type === 4) { // push query rules to empty array queryRules.push(document.styleSheets[i].cssRules[j]); } } } } // there is one media query in Mocha.css, so must detect more than 1 query FCC_Global.assert.isAbove(queryRules.length, 1, 'No media queries detected '); }); it('3. My product landing page should utilize CSS flexbox at least once.', function() { // loop through all associated stylesheets and look for display of flex const flexCount = []; for (var i = 0; i < document.styleSheets.length; i++) { if (document.styleSheets[i].cssRules !== null) { for (var j = 0; j < document.styleSheets[i].cssRules.length; j++) { if (document.styleSheets[i].cssRules[j].style !== undefined && document.styleSheets[i].cssRules[j].style.display === 'flex' || document.styleSheets[i].cssRules[j].style !== undefined && document.styleSheets[i].cssRules[j].style.display === 'inline-flex') { flexCount.push(1); } } } } // our test suite uses a display of flex, so we need to count how many times its used // and confirm that its more than once. If we just detect one instance, its ours. FCC_Global.assert.isAbove(flexCount.length, 1, 'We do not detect a display property set to flex or inline-flex anywhere in your CSS ') }); }); // END #Layout }); // END #ProductLadingPageTests } // END createProductLandingPageTests()
64.949045
270
0.662842
f0887e58552c56bf7a982e28974d39223e7ce0e5
2,569
js
JavaScript
utils/stylesheet.js
ryanholder/reactnd-project-mobile-flashcards
8417aa2f5ad91a525d349cd1ba08f4ee937645b8
[ "MIT" ]
null
null
null
utils/stylesheet.js
ryanholder/reactnd-project-mobile-flashcards
8417aa2f5ad91a525d349cd1ba08f4ee937645b8
[ "MIT" ]
null
null
null
utils/stylesheet.js
ryanholder/reactnd-project-mobile-flashcards
8417aa2f5ad91a525d349cd1ba08f4ee937645b8
[ "MIT" ]
null
null
null
import { StyleSheet, Platform } from 'react-native'; import { white, black, orange, green, red, } from './colors'; export default StyleSheet.create({ center: { flex: 1, justifyContent: 'center', alignItems: 'center', }, container: { padding: 40, backgroundColor: white, }, label: { fontSize: 28, textAlign: 'center', }, input: { borderWidth: 1, borderRadius: 5, height: 44, marginTop: 10, padding: 8, width: '100%', }, buttonSubmit: { alignItems: 'center', backgroundColor: orange, borderRadius: 5, marginTop: 10, padding: 10, }, buttonTextSubmit: { fontSize: 20, color: white, }, item: { backgroundColor: white, borderRadius: Platform.OS === 'ios' ? 16 : 2, padding: 20, marginLeft: 10, marginRight: 10, marginTop: 17, justifyContent: 'center', shadowRadius: 3, shadowOpacity: 0.8, shadowColor: 'rgba(0, 0, 0, 0.24)', shadowOffset: { width: 0, height: 3, }, }, noDataText: { fontSize: 20, }, list: { flex: 1, alignSelf: 'stretch', }, title: { fontSize: 30, fontWeight: 'bold', color: black, }, quizItem: { backgroundColor: white, borderRadius: Platform.OS === 'ios' ? 16 : 2, padding: 20, margin: 20, borderWidth: 0, shadowRadius: 3, shadowOpacity: 0.8, shadowColor: 'rgba(0, 0, 0, 0.24)', shadowOffset: { width: 0, height: 3, }, flex: 1, alignItems: 'stretch', }, quizCenter: { flex: 1, }, question: { flex: 1, justifyContent: 'center', alignItems: 'center', }, buttonCorrect: { alignItems: 'center', backgroundColor: green, borderRadius: 5, marginTop: 10, marginLeft: 20, marginRight: 20, padding: 10, justifyContent: 'center', }, buttonIncorrect: { alignItems: 'center', backgroundColor: red, borderRadius: 5, marginTop: 10, marginLeft: 20, marginRight: 20, padding: 10, justifyContent: 'center', }, buttonFlip: { alignItems: 'center', backgroundColor: white, borderRadius: 5, marginTop: 10, marginLeft: 20, marginRight: 20, padding: 10, justifyContent: 'center', }, cardCount: { alignSelf: 'flex-start', }, face: { alignItems: 'center', flex: 1, }, back: { alignItems: 'center', flex: 1, }, quizResults: { alignItems: 'center', justifyContent: 'center', flex: 1, }, flipText: { color: red, }, });
17.717241
52
0.564033
e76490f38d1628c82aa89b00eb05ed61a716e391
497
js
JavaScript
src/components/icons/solid/ChevronCircleDown.js
MythicalFish/mythical.fish
c99209b42183a7e65d5c7384706838b925a8db0d
[ "MIT" ]
2
2019-04-10T01:46:31.000Z
2020-05-02T14:29:56.000Z
src/components/icons/solid/ChevronCircleDown.js
MythicalFish/mythical.fish
c99209b42183a7e65d5c7384706838b925a8db0d
[ "MIT" ]
null
null
null
src/components/icons/solid/ChevronCircleDown.js
MythicalFish/mythical.fish
c99209b42183a7e65d5c7384706838b925a8db0d
[ "MIT" ]
null
null
null
import React from 'react' const ChevronCircleDown = props => ( <svg fill='currentColor' viewBox='0 0 512 512' width='1em' height='1em' {...props} > <path d='M504 256c0 137-111 248-248 248S8 393 8 256 119 8 256 8s248 111 248 248zM273 369.9l135.5-135.5c9.4-9.4 9.4-24.6 0-33.9l-17-17c-9.4-9.4-24.6-9.4-33.9 0L256 285.1 154.4 183.5c-9.4-9.4-24.6-9.4-33.9 0l-17 17c-9.4 9.4-9.4 24.6 0 33.9L239 369.9c9.4 9.4 24.6 9.4 34 0z' /> </svg> ) export default ChevronCircleDown
31.0625
278
0.637827
ed90376f18aa5a60e443b5db3309f474e009926e
490
kt
Kotlin
app/src/main/java/com/uni7corn/utheme/App.kt
uni7corn/UTheme
127c4cf2b0752c5748e36d400d6f2ef0eec3fbac
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/uni7corn/utheme/App.kt
uni7corn/UTheme
127c4cf2b0752c5748e36d400d6f2ef0eec3fbac
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/uni7corn/utheme/App.kt
uni7corn/UTheme
127c4cf2b0752c5748e36d400d6f2ef0eec3fbac
[ "Apache-2.0" ]
null
null
null
package com.uni7corn.utheme import android.app.Application import android.content.Context class App : Application() { companion object { private lateinit var mContext: Application @JvmStatic fun getAppContext(): Application { return mContext } } override fun attachBaseContext(base: Context?) { super.attachBaseContext(base) } override fun onCreate() { super.onCreate() mContext = this } }
17.5
52
0.628571
8ec21d06dd5d4c7578cf5d935a09e467c81e71a7
1,783
rb
Ruby
lib/office_quote_controller.rb
emhopkins/office-quote-cli-app
dd64ffa680aabb210ebe98c2b6e2a5387ba0ee0c
[ "MIT" ]
null
null
null
lib/office_quote_controller.rb
emhopkins/office-quote-cli-app
dd64ffa680aabb210ebe98c2b6e2a5387ba0ee0c
[ "MIT" ]
null
null
null
lib/office_quote_controller.rb
emhopkins/office-quote-cli-app
dd64ffa680aabb210ebe98c2b6e2a5387ba0ee0c
[ "MIT" ]
null
null
null
class OfficeQuoteController def initialize quotes = Scraper.new quotes.get_quote_pages start_cli end def start_cli input = "" puts "Welcome to The Office Quote Generator" while input != "exit" do puts "If you'd like to exit, enter \"exit\"" puts "Please select from the following options: " puts "1. Choose a quote from a specific character" puts "2. Hear a dialogue quote (between multiple characters)" puts "3. Hear a random quote" input = gets.chomp if input == "1" get_quotes_by_character elsif input == "2" get_dialogue_quote elsif input == "3" get_random_quote elsif input != "exit" puts "Please enter 1, 2 or 3" end end end def get_quotes_by_character input = "" while input != "exit" && input != "n" && input != "N" do puts "You may choose from these characters: " Character.list_all_characters puts "Please select from one of the following characters by entering their name: " input = gets.chomp puts "Would you like to hear 1 or all of their quotes?" puts "Enter \"1\" for one quote and anything else to hear all." option = gets.chomp if option != "1" Character.list_all_quotes_for_character(input) else Character.random_quote_for_character(input) end puts "Would you like to choose another character? (y/n)" input = gets.chomp end end def get_dialogue_quote input = "" while input != "exit" && input != "n" && input != "N" do Quote.get_dialogue puts "Would you like to hear another dialogue? (y/n)" input = gets.chomp end end def get_random_quote input = "" while input != "exit" && input != "n" && input != "N" do Quote.get_random puts "Would you like to hear another quote? (y/n)" input = gets.chomp end end end
25.84058
85
0.67134
be24fa7a50809bdf13c2b06a0e6c819e07b8a109
493
swift
Swift
validation-test/compiler_crashers_fixed/01787-swift-clangmoduleunit-getimportedmodules.swift
ghostbar/swift-lang.deb
b1a887edd9178a0049a0ef839c4419142781f7a0
[ "Apache-2.0" ]
10
2015-12-25T02:19:46.000Z
2021-11-14T15:37:57.000Z
validation-test/compiler_crashers_fixed/01787-swift-clangmoduleunit-getimportedmodules.swift
ghostbar/swift-lang.deb
b1a887edd9178a0049a0ef839c4419142781f7a0
[ "Apache-2.0" ]
2
2016-02-01T08:51:00.000Z
2017-04-07T09:04:30.000Z
validation-test/compiler_crashers_fixed/01787-swift-clangmoduleunit-getimportedmodules.swift
ghostbar/swift-lang.deb
b1a887edd9178a0049a0ef839c4419142781f7a0
[ "Apache-2.0" ]
3
2016-04-02T15:05:27.000Z
2019-08-19T15:25:02.000Z
// RUN: not %target-swift-frontend %s -parse // Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing t = b: ()(i: T: Int = 0 return [") import Foundation func f<b(c: b { return """""foo"foobar"""[1)) deinit { } func f: B? { typealias R = a(n: A { } self.h : e?) -> U -> { protocol a : T> { typealias B : A, a: a { } } } protocol a { typealias B { return " typealias b : B>(array
18.259259
87
0.63286
fe343418d522240dac747066b0317c2fda92d7a4
7,208
asm
Assembly
Transynther/x86/_processed/AVXALIGN/_st_zr_un_4k_/i7-7700_9_0xca.log_21829_1551.asm
ljhsiun2/medusa
67d769b8a2fb42c538f10287abaf0e6dbb463f0c
[ "MIT" ]
9
2020-08-13T19:41:58.000Z
2022-03-30T12:22:51.000Z
Transynther/x86/_processed/AVXALIGN/_st_zr_un_4k_/i7-7700_9_0xca.log_21829_1551.asm
ljhsiun2/medusa
67d769b8a2fb42c538f10287abaf0e6dbb463f0c
[ "MIT" ]
1
2021-04-29T06:29:35.000Z
2021-05-13T21:02:30.000Z
Transynther/x86/_processed/AVXALIGN/_st_zr_un_4k_/i7-7700_9_0xca.log_21829_1551.asm
ljhsiun2/medusa
67d769b8a2fb42c538f10287abaf0e6dbb463f0c
[ "MIT" ]
3
2020-07-14T17:07:07.000Z
2022-03-21T01:12:22.000Z
.global s_prepare_buffers s_prepare_buffers: push %r10 push %r11 push %r15 push %rax push %rbx push %rcx push %rdi push %rsi lea addresses_normal_ht+0x1b2c, %rdi nop nop and %rax, %rax mov $0x6162636465666768, %r10 movq %r10, %xmm0 movups %xmm0, (%rdi) and %r15, %r15 lea addresses_UC_ht+0x10e2c, %rsi lea addresses_D_ht+0x142a4, %rdi nop nop nop nop nop sub %r11, %r11 mov $107, %rcx rep movsq nop nop nop nop xor %r15, %r15 lea addresses_D_ht+0x2d20, %rsi nop nop nop xor %rax, %rax mov (%rsi), %r10 nop nop nop nop nop xor $17667, %rcx lea addresses_WC_ht+0x1d70e, %rdi nop nop and $32627, %r15 mov (%rdi), %cx nop nop nop nop inc %rax lea addresses_normal_ht+0x111dc, %rcx nop nop nop and %r15, %r15 mov $0x6162636465666768, %r11 movq %r11, %xmm1 and $0xffffffffffffffc0, %rcx movaps %xmm1, (%rcx) nop inc %rax lea addresses_UC_ht+0x322c, %rsi nop nop add %rcx, %rcx movb (%rsi), %al nop nop and %rdi, %rdi lea addresses_A_ht+0x10ec4, %r15 nop nop add $15131, %rax mov (%r15), %esi nop nop nop sub $61890, %r10 lea addresses_A_ht+0x82c, %rsi lea addresses_normal_ht+0x125a6, %rdi clflush (%rdi) nop sub %rbx, %rbx mov $38, %rcx rep movsl nop nop nop nop sub %rdi, %rdi lea addresses_normal_ht+0x17afc, %rax nop nop nop nop nop add %rsi, %rsi movb $0x61, (%rax) nop nop nop xor %rdi, %rdi lea addresses_WC_ht+0x88ac, %r10 nop nop nop nop nop inc %rsi movw $0x6162, (%r10) nop add %r10, %r10 lea addresses_D_ht+0xc0ec, %rsi lea addresses_WC_ht+0x14dfc, %rdi nop nop nop nop and $42542, %r10 mov $127, %rcx rep movsq sub $12594, %rsi lea addresses_WC_ht+0x19144, %r15 nop add %r11, %r11 mov $0x6162636465666768, %rsi movq %rsi, %xmm3 movups %xmm3, (%r15) nop nop nop cmp %rdi, %rdi pop %rsi pop %rdi pop %rcx pop %rbx pop %rax pop %r15 pop %r11 pop %r10 ret .global s_faulty_load s_faulty_load: push %r10 push %r14 push %r15 push %r9 push %rbp push %rdx // Store lea addresses_WT+0x6a2c, %rdx and %r14, %r14 movl $0x51525354, (%rdx) and %r9, %r9 // Faulty Load mov $0x1244890000000a2c, %rbp nop inc %r15 movb (%rbp), %r10b lea oracles, %rdx and $0xff, %r10 shlq $12, %r10 mov (%rdx,%r10,1), %r10 pop %rdx pop %rbp pop %r9 pop %r15 pop %r14 pop %r10 ret /* <gen_faulty_load> [REF] {'src': {'congruent': 0, 'AVXalign': True, 'same': False, 'size': 2, 'NT': False, 'type': 'addresses_NC'}, 'OP': 'LOAD'} {'OP': 'STOR', 'dst': {'congruent': 11, 'AVXalign': False, 'same': False, 'size': 4, 'NT': False, 'type': 'addresses_WT'}} [Faulty Load] {'src': {'congruent': 0, 'AVXalign': False, 'same': True, 'size': 1, 'NT': True, 'type': 'addresses_NC'}, 'OP': 'LOAD'} <gen_prepare_buffer> {'OP': 'STOR', 'dst': {'congruent': 7, 'AVXalign': False, 'same': False, 'size': 16, 'NT': False, 'type': 'addresses_normal_ht'}} {'src': {'congruent': 8, 'same': False, 'type': 'addresses_UC_ht'}, 'OP': 'REPM', 'dst': {'congruent': 3, 'same': False, 'type': 'addresses_D_ht'}} {'src': {'congruent': 0, 'AVXalign': False, 'same': False, 'size': 8, 'NT': False, 'type': 'addresses_D_ht'}, 'OP': 'LOAD'} {'src': {'congruent': 1, 'AVXalign': False, 'same': False, 'size': 2, 'NT': False, 'type': 'addresses_WC_ht'}, 'OP': 'LOAD'} {'OP': 'STOR', 'dst': {'congruent': 1, 'AVXalign': True, 'same': True, 'size': 16, 'NT': False, 'type': 'addresses_normal_ht'}} {'src': {'congruent': 5, 'AVXalign': False, 'same': False, 'size': 1, 'NT': False, 'type': 'addresses_UC_ht'}, 'OP': 'LOAD'} {'src': {'congruent': 1, 'AVXalign': False, 'same': False, 'size': 4, 'NT': False, 'type': 'addresses_A_ht'}, 'OP': 'LOAD'} {'src': {'congruent': 9, 'same': False, 'type': 'addresses_A_ht'}, 'OP': 'REPM', 'dst': {'congruent': 1, 'same': False, 'type': 'addresses_normal_ht'}} {'OP': 'STOR', 'dst': {'congruent': 2, 'AVXalign': False, 'same': False, 'size': 1, 'NT': False, 'type': 'addresses_normal_ht'}} {'OP': 'STOR', 'dst': {'congruent': 7, 'AVXalign': False, 'same': False, 'size': 2, 'NT': False, 'type': 'addresses_WC_ht'}} {'src': {'congruent': 6, 'same': False, 'type': 'addresses_D_ht'}, 'OP': 'REPM', 'dst': {'congruent': 3, 'same': True, 'type': 'addresses_WC_ht'}} {'OP': 'STOR', 'dst': {'congruent': 3, 'AVXalign': False, 'same': False, 'size': 16, 'NT': False, 'type': 'addresses_WC_ht'}} {'c0': 1, '00': 21515, '54': 313} 54 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 54 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 54 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 54 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 54 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 54 00 00 54 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 54 00 00 00 00 00 00 00 00 00 00 00 00 00 54 00 00 00 00 00 00 00 00 54 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 54 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 54 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 54 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 54 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 54 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 */
35.507389
2,999
0.656632
3d58729365cab6672b0e7b134b1b2395dcdc48f0
6,948
lua
Lua
Code/['World']['Global']['Weapon_Plugin_Package']['Module']['C_Module']['PlayerBehaviorModule'].ModuleScript.lua
lilith-avatar/rapid-duel
e91ce60e5dbd490763964f3449d5f907d7216742
[ "MIT" ]
8
2021-04-20T09:39:22.000Z
2021-10-19T06:08:29.000Z
Code/['World']['Global']['Weapon_Plugin_Package']['Module']['C_Module']['PlayerBehaviorModule'].ModuleScript.lua
lilith-avatar/rapid-duel
e91ce60e5dbd490763964f3449d5f907d7216742
[ "MIT" ]
null
null
null
Code/['World']['Global']['Weapon_Plugin_Package']['Module']['C_Module']['PlayerBehaviorModule'].ModuleScript.lua
lilith-avatar/rapid-duel
e91ce60e5dbd490763964f3449d5f907d7216742
[ "MIT" ]
2
2021-05-08T11:36:09.000Z
2021-05-12T09:59:50.000Z
--- @module PlayerBehavior 枪械模块:玩家行为树 --- @copyright Lilith Games, Avatar Team --- @author RopzTao local PlayerBehavior, this = { playerActionStateFunc = {} ---状态触发表 }, nil local firParam = nil local function OnKeyDown() ---按C下蹲 if Input.GetPressKeyData(Enum.KeyCode.C) ~= Enum.KeyState.KeyStateNone then PlayerBehavior:PlayerCrouch() end ---按Shift进入快跑 if Input.GetPressKeyData(Enum.KeyCode.LeftShift) ~= Enum.KeyState.KeyStateNone then ---速度变化 PlayerBehavior:PlayerBehaviorChanged('isQuickly') ---准星消失 if PlayerGunMgr.gun then ---PlayerBehavior.gun.m_gui.crosshair:SetActive(false) end end ---按下空格键跳 if Input.GetPressKeyData(Enum.KeyCode.Space) ~= Enum.KeyState.KeyStateNone then PlayerBehavior:PlayerJump() end end local function OnKeyUp() ---抬起Shift结束快跑 if Input.GetPressKeyData(Enum.KeyCode.LeftShift) == Enum.KeyState.KeyStateRelease then PlayerBehavior:PlayerBehaviorChanged('isQuickly') end end ---初始化函数 function PlayerBehavior:Init() this = self self:InitListener() ---@type PlayerInstance 当前的玩家对象 self.player = localPlayer self.state = PlayerActionModeEnum.Run ---不同职业的配速 self.SpeedStdCoeft = self.player.SpeedScale.Value ---人物移动状态系数 self.coefInertia = 1 ---人物加速度系数 self.InerPara = GunConfig.GlobalConfig.InertialParam self.GunWeight = 1 self:InitialDataRead() self:InitPlayerAttributes() self:PlayerBehaviorChanged('isRun') Input.OnKeyDown:Connect(OnKeyDown) Input.OnKeyUp:Connect(OnKeyUp) self.player.OnDead:Connect( function() self.state = PlayerActionModeEnum.Run self.BehJudgeTab.isAim = false end ) end ---监听函数 function PlayerBehavior:InitListener() LinkConnects(localPlayer.C_Event, PlayerBehavior, this) end ---初始数据 function PlayerBehavior:InitialDataRead() ---玩家行为判断参数 self.BehJudgeTab = { isRun = false, isCrouch = false, isQuickly = false, isAim = false } self.keyDownTab = {} end ---玩家职业不同速度标准系数不同 ---@param _occ 职业种类 function PlayerBehavior:ChangeOccEventHandler(_occ) ---更新参数 self.SpeedStdCoeft = localPlayer.SpeedScale.Value end ---初始玩家设定 function PlayerBehavior:InitPlayerAttributes() self.player.JumpUpVelocity = GunConfig.GlobalConfig.JumpSpeed end ---装备枪更新跳跃速度 function PlayerBehavior:OnEquipWeaponEventHandler() if PlayerGunMgr.curGun == nil then return end self.player.JumpUpVelocity = GunConfig.GlobalConfig.JumpSpeed * self.SpeedStdCoeft * self.GunWeight end ---玩家行为判断 function PlayerBehavior:PlayerBehaviorChanged(_behavior) if self.BehJudgeTab[_behavior] then self.BehJudgeTab[_behavior] = false else self.BehJudgeTab[_behavior] = true end for k, v in pairs(self.BehJudgeTab) do if v then table.insert(self.keyDownTab, k) end end if #self.keyDownTab == 1 then firParam = string.gsub(tostring(self.keyDownTab[1]), 'is', '') self:PlayerModeChanged(firParam) elseif #self.keyDownTab == 2 then for i, j in pairs(self.keyDownTab) do firParam = string.gsub(tostring(j), 'is', '') if firParam ~= 'Run' then self:PlayerModeChanged(firParam .. 'Run') end end elseif #self.keyDownTab == 3 then for m, n in pairs(self.keyDownTab) do firParam = string.gsub(tostring(n), 'is', '') if firParam ~= 'Run' and firParam ~= 'Crouch' then self:PlayerModeChanged(firParam .. 'CrouchRun') end end end self.keyDownTab = {} end ---玩家状态判断 ---@param _modeName String function PlayerBehavior:PlayerModeChanged(_modeName) self.playerActionStateFunc[PlayerActionModeEnum[_modeName]] = function() self.state = PlayerActionModeEnum[_modeName] end self.playerActionStateFunc[PlayerActionModeEnum[_modeName]]() end ---@param direParam Float 摇杆方向对应不同速度的参数 local direRes, direParam, tt = 0, 1, 0 local directionFactor = Vector2.Zero ---前后左右移动速度不一致 function PlayerBehavior:DiffDireMovement(dt) ---如果摇杆的位移坐标前一帧为directionFactor,后一帧为原点 if Vector2(BattleGUI.horizontal, BattleGUI.vertical) == directionFactor and Vector2(BattleGUI.horizontal, BattleGUI.vertical) == Vector2.Zero then tt = 0 self.coefInertia = 1 else tt = tt + dt self.coefInertia = Asymptote(self.InerPara * tt) end directionFactor = Vector2(BattleGUI.horizontal, BattleGUI.vertical) if directionFactor ~= Vector2.Zero then direRes = Vector2.Dot(directionFactor, Vector2(0, 1)) / directionFactor.Magnitude if direRes >= 0.5 then direParam = 1.35 * directionFactor.Magnitude elseif direRes <= -0.5 then direParam = (1 / 1.2) * directionFactor.Magnitude else direParam = (1 / 1.05) * directionFactor.Magnitude end end end ---Update函数 function PlayerBehavior:Update(dt) localPlayer.ActionState.Value = self.state self:DiffDireMovement(dt) self:CharacterStartInertia() ---更新速度 for k, v in pairs(PlayerActionModeEnum) do if v == self.state then self.player.WalkSpeed = GunConfig.GlobalConfig[tostring(k) .. 'Speed'] * self.SpeedStdCoeft * self.coefInertia * direParam * self.GunWeight end end end ---人物启动加速惯性函数 ---匹配到对应的枪械的重量 function PlayerBehavior:CharacterStartInertia() ---不同枪械的质量系数 if PlayerGunMgr.curGun then self.GunWeight = 1 / PlayerGunMgr.curGun.config_weight end end ---玩家跳跃 function PlayerBehavior:PlayerJump() if (self.player.IsOnGround or self.player.State == Enum.CharacterState.Seated) and not isDead then if self.player:IsCrouch() then self.player:EndCrouch() self:PlayerBehaviorChanged('isCrouch') CameraControl:Crouch() return else if (PlayerGunMgr.curGun and PlayerGunMgr.curGun.m_isZoomIn) then PlayerGunMgr.curGun:MechanicalAimStop() end self.player:Jump() return end end end ---玩家蹲下 function PlayerBehavior:PlayerCrouch() self:PlayerBehaviorChanged('isCrouch') if not self.player:IsCrouch() then self.player:StartCrouch() else self.player:EndCrouch() end CameraControl:Crouch() end ---玩家蹲下重置 function PlayerBehavior:CrouchReset() if self.player:IsCrouch() then BattleGUI:PlayerCrouchClick() end end ---状态初始化或重置 function PlayerBehavior:InitsetOrReset() ---表现重置 self:CrouchReset() BattleGUI:GunInterReset() ---数据重置 self:InitialDataRead() self:InitPlayerAttributes() self:PlayerBehaviorChanged('isRun') self.player.Health = 100 end return PlayerBehavior
27.035019
116
0.665803
016d368f13289f909c62b804612e30451d898657
3,083
sql
SQL
sql/cohort_sepsis.sql
benpopoff/hyperoxemia-mimic
6cb32fddd2bead6a2a904ff2bee81c163a73e3c4
[ "MIT" ]
null
null
null
sql/cohort_sepsis.sql
benpopoff/hyperoxemia-mimic
6cb32fddd2bead6a2a904ff2bee81c163a73e3c4
[ "MIT" ]
null
null
null
sql/cohort_sepsis.sql
benpopoff/hyperoxemia-mimic
6cb32fddd2bead6a2a904ff2bee81c163a73e3c4
[ "MIT" ]
null
null
null
-- ------------------------------------------------------------------ -- -- Cohort sepsis selection -- -- Collect data for population with relevant data and flags -- -- ------------------------------------------------------------------ DROP MATERIALIZED VIEW IF EXISTS cohort_sepsis CASCADE; CREATE MATERIALIZED VIEW cohort_sepsis AS with abg_order as ( select icustay_id, charttime, po2, dense_rank() over (partition by icustay_id order by charttime) AS abg_nb from abg_sepsis where po2 is not NULL ), first as ( select icustay_id, po2 as first_po2 from abg_order where abg_nb = 1 ), abg_24 as ( select ie.icustay_id, round(cast(avg(po2) as numeric), 2) as avg_24_po2, min(po2) as min_24_po2, max(po2) as max_24_po2 from icustays as ie inner join abg_sepsis as ab using (icustay_id) where charttime <= ie.intime + interval '1' day group by ie.icustay_id ), abg_whole as ( select ie.icustay_id, round(cast(avg(po2) as numeric), 2) as avg_whole_po2, min(po2) as min_whole_po2, max(po2) as max_whole_po2 from icustays as ie inner join abg_sepsis as ab using (icustay_id) group by ie.icustay_id ), sources as ( select icustay_id, source_pulm, source_urogyn, source_neuro, source_dig, source_ost, source_ent, source_card, source_skin, source_other from infectious_sources ) select subject_id, icustay_id, hadm_id, first_po2, avg_24_po2, min_24_po2, max_24_po2, --avg_48_po2, --min_48_po2, --max_48_po2, --avg_72_po2, --min_72_po2, --max_72_po2, --avg_whole_po2, --min_whole_po2, --max_whole_po2, first_careunit, first_wardid, admission_type, intime, outtime, los_icu, los_hospital, vent_first_duration, vaso_firstday, norepinephrine_duration, norepinephrine_max_dose, admission_age, gender, height_firstday, weight_firstday, bmi_firstday, abg_count, lactate_max_firstday, pco2_max_firstday, ph_min_firstday, albumin_min_firstday, bicarbonate_min_firstday, bilirubin_max_firstday, creatinine_max_firstday, chloride_max_firstday, sodium_max_firstday, potassium_max_firstday, hematocrit_min_firstday, hemoglobin_min_firstday, platelet_min_firstday, ptt_min_firstday, rrt, comorbidity_cardio, comorbidity_vascular, comorbidity_neuro, comorbidity_pneumo, comorbidity_metabolic, comorbidity_renal, comorbidity_liver, comorbidity_cancer, sofa, sapsii, apsiii, noso_vap, noso_urinary, noso_cvc, noso_cvc_other, source_pulm, source_urogyn, source_neuro, source_dig, source_ost, source_ent, source_card, source_skin, source_other, death_thirtydays, death_icu, death_hosp, flag_shock from cohort_all left join first using (icustay_id) left join abg_24 using (icustay_id) left join abg_whole using (icustay_id) left join sources using (icustay_id) where flag_include = 1 and flag_sepsis = 1;
21.711268
75
0.674992
b3615d7927e479045f3dabeee87ce71a5fd86639
618
rb
Ruby
app/controllers/spree/api/v2/states_controller.rb
wildcardlabs/solidus_json_api
a6f2379df1c05d6b31097462789287b096b54982
[ "BSD-3-Clause" ]
15
2015-12-04T19:39:05.000Z
2016-08-20T09:42:54.000Z
app/controllers/spree/api/v2/states_controller.rb
spree-contrib/spree_api_v2
a6f2379df1c05d6b31097462789287b096b54982
[ "BSD-3-Clause" ]
6
2015-09-23T20:28:11.000Z
2015-10-14T22:22:39.000Z
app/controllers/spree/api/v2/states_controller.rb
BenMorganIO/solidus_json_api
a6f2379df1c05d6b31097462789287b096b54982
[ "BSD-3-Clause" ]
4
2017-03-19T16:05:27.000Z
2022-02-04T00:23:46.000Z
module Spree module Api module V2 class StatesController < Spree::Api::V2::BaseController skip_before_action :authenticate_user def index render_collection states end def show render_instance states.find(params[:id]) end private def states @states ||= begin if params[:country_id].present? Spree::Country.find(params[:country_id]).states.includes(:country) else Spree::State.includes(:country) end end end end end end end
20.6
80
0.550162
8586bdf6970371a55fd1a6f8fddc1bccd7804ff3
646
js
JavaScript
src/types/user/user.resolvers.js
perfettiful/FEM-api-design-graphql
ec4a73a86487c84da599ee57ee9f74858e45c88b
[ "MIT" ]
2
2022-01-12T00:49:55.000Z
2022-01-20T22:50:49.000Z
src/types/user/user.resolvers.js
perfettiful/FEM-api-design-graphql
ec4a73a86487c84da599ee57ee9f74858e45c88b
[ "MIT" ]
6
2021-05-08T09:55:14.000Z
2021-11-08T18:33:06.000Z
src/types/user/user.resolvers.js
perfettiful/FEM-api-design-graphql
ec4a73a86487c84da599ee57ee9f74858e45c88b
[ "MIT" ]
1
2022-02-03T00:33:59.000Z
2022-02-03T00:33:59.000Z
import { User } from './user.model' import { AuthenticationError } from 'apollo-server' import { newApiKey } from '../../utils/auth' const me = (_, args, ctx) => { if (!ctx.user) { throw new AuthenticationError() } return ctx.user } const updateMe = (_, args, ctx) => { if (!ctx.user) { throw new AuthenticationError() } return User.findByIdAndUpdate(ctx.user._id, args.input, { new: true }) .select('-password') .lean() .exec() } const signup = (_, args) => { return User.create({ ...args.input, apiKey: newApiKey() }) } export default { Query: { me }, Mutation: { updateMe, signup } }
17.944444
72
0.597523
599f6b782a86258ad7e810beb3525b50546fe09e
463
sql
SQL
Backend/database/stored procedures/get_all_project.sql
DevelopGadget/Kanban
6a8a3ab6fdced7ffcf932355c8993f53a04ad44e
[ "Apache-2.0" ]
null
null
null
Backend/database/stored procedures/get_all_project.sql
DevelopGadget/Kanban
6a8a3ab6fdced7ffcf932355c8993f53a04ad44e
[ "Apache-2.0" ]
8
2021-03-10T11:46:26.000Z
2022-02-27T01:32:05.000Z
Backend/database/stored procedures/get_all_project.sql
DevelopGadget/Kanban
6a8a3ab6fdced7ffcf932355c8993f53a04ad44e
[ "Apache-2.0" ]
null
null
null
ALTER PROCEDURE [dbo].GetAllProject @PageNumber INT = 1, @PageSize INT = 100, @Id NVARCHAR (MAX) AS BEGIN SELECT P FROM [dbo].Projects P RIGHT JOIN [dbo].MembersProject M ON P.[Id] = M.[IdProject] AND M.[IsActiveMember] = 1 AND (P.[Admin] = @Id OR @Id = M.[IdUser]) WHERE P.[IsActiveProject] = 1 ORDER BY P.[Id] ASC OFFSET (@PageNumber - 1) * @PageSize ROWS FETCH NEXT @PageSize ROWS ONLY END
30.866667
98
0.596112
b1c14e0ca01808fa97fb2281a813beef90be3852
48,809
h
C
include/graphical_model.h
junkyul/limid
1a97ad0e25a1b4ef8ee66fee7821f2dd925e845b
[ "BSD-3-Clause" ]
1
2016-06-23T18:08:49.000Z
2016-06-23T18:08:49.000Z
include/graphical_model.h
junkyul/limid
1a97ad0e25a1b4ef8ee66fee7821f2dd925e845b
[ "BSD-3-Clause" ]
null
null
null
include/graphical_model.h
junkyul/limid
1a97ad0e25a1b4ef8ee66fee7821f2dd925e845b
[ "BSD-3-Clause" ]
1
2016-06-24T05:39:11.000Z
2016-06-24T05:39:11.000Z
/* * graphical_model.h * * Created on: Feb 8, 2013 * Author: radu * * Copyright (c) 2015, International Business Machines Corporation * and University of California Irvine. All rights reserved. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /// \file graphical_model.h /// \brief A probabilistic graphical model /// \author Radu Marinescu #ifndef IBM_MERLIN_GRAPHICAL_MODEL_H_ #define IBM_MERLIN_GRAPHICAL_MODEL_H_ #include "enum.h" #include "factor.h" #include "graph.h" namespace merlin { /// /// \brief Graphical model base class. /// /// Simplest form of a *graphical model*, namely just a collection of /// variables and factors (defined on subsets of variables). /// Internally, factors and variables are mainly referenced by integer indices, with /// 0 <= f < nFactors() and 0 <= v < nvar(). However, many interface functions are called /// using a variable object, Var(label,dim). To convert, var(v) gives the vth Var object /// and the internal function _vindex(V) gives the index corresponding to variable object V. /// class graphical_model: public graph { public: // Useful typedefs: typedef size_t findex; ///< Factor index typedef size_t vindex; ///< Variable index typedef set<findex> flist; ///< Collection of factor indices // Constructors, copy and assignment: /// /// \brief Creates an empty graphical model. /// graphical_model() : m_factors(), m_vadj(), m_dims() { }; /// /// \brief Creates a graphical model by copying an existing one. /// \param gm An object of the same type /// graphical_model(const graphical_model& gm) : graph((graph&) gm), m_factors(gm.m_factors), m_vadj(gm.m_vadj), m_dims( gm.m_dims) { }; /// /// \brief Assignment operator (deep copy). /// \param gm The graphical model to be copied from /// \return a reference to the modified object containing the copied content. /// graphical_model& operator=(const graphical_model& gm) { graph::operator=((graph&) gm); // copy graph elements over m_factors = gm.m_factors; // copy list of factors m_vadj = gm.m_vadj; // variable dependencies m_dims = gm.m_dims; // and variable dimensions over return *this; }; /// /// \brief Clone the graphical model. /// \return the pointer to the new object representing the copy of /// the current model. /// virtual graphical_model* clone() { graphical_model* gm = new graphical_model(*this); return gm; }; /// /// \brief Constructor from a list of factors. /// \param fs The list of factors /// graphical_model(std::vector<factor> fs) : graph(), m_factors(fs), m_vadj(), m_dims() { fixup(); }; /// /// \brief Creates a graphical model from input iterators. /// \param first The iterator to beginning /// \param last The iterator to end /// template<class InputIterator> graphical_model(InputIterator first, InputIterator last) : m_factors(first, last), m_vadj(), m_dims() { fixup(); } /// /// \brief Destroys the graphical model. /// virtual ~graphical_model() { }; /// /// \brief Read the graphical model from a file in the UAI format. /// /// For details on the UAI file format see the main documentation of /// the library. In this format, the factor tables are assumed to be /// represented using the "least significant bit", namely the last variable /// in the factor scope changes the fastest. Moreover, the internal /// representation of the factor assumes that the scope is ordered /// lexicographically. /// /// \param file_name The full path to the file /// virtual void read(const char* file_name) { // Open the input stream std::ifstream is(file_name); if (is.fail()) { std::cout << "Error while opening the input file: " << file_name << std::endl; throw std::runtime_error("Input file error"); } // Read the header size_t nvar, ncliques, csize, v, nval; char st[1024]; is >> st; if ( strcasecmp(st,"MARKOV") ) throw std::runtime_error("Only UAI Markov-format files are supported currently"); // Read the number of variables and their domains is >> nvar; std::vector<size_t> dims(nvar); for (size_t i = 0; i < nvar; i++) is >> dims[i]; // Read the number of factors and their scopes (scope is a variable_set) is >> ncliques; std::vector<std::vector<variable> > cliques(ncliques); std::vector<variable_set> sets(ncliques); for (size_t i = 0; i < ncliques; i++) { is >> csize; cliques[i].reserve(csize); for (size_t j = 0; j < csize; j++) { is >> v; variable V(v, dims[v]); cliques[i].push_back(V); sets[i] |= V; } } // Read the factor tables (ensure conversion to ordered scopes) double fval; std::vector<factor> tables(ncliques); for (size_t i = 0; i < ncliques; i++) { is >> nval; assert(nval == sets[i].num_states()); tables[i] = factor(sets[i], 0.0); // preallocate memory convert_index ci(cliques[i], false, true); // convert from source order (littleEndian) to target order (bigEndian) for (size_t j = 0; j < nval; j++) { size_t k = ci.convert(j); // get the index in the factor table is >> fval; // read the factor value; if (fval == 0.0) fval = 1e-06; // for numerical stability tables[i][k] = fval; // save the factor value into the table } } m_factors = tables; fixup(); } /// /// \brief Write the graphical model to a file. /// /// In the output file, the factor tables are assumed to be represented /// using the "most significant digit", namely the first variable /// in the factor scope changes the fastest. The factor scopes are also /// ordered lexicographically. /// virtual void write(const char* file_name) { // Open the output stream std::ofstream os(file_name); if (os.fail()) { std::cout << "Error while opening the output file: " << file_name << std::endl; throw std::runtime_error("Output file error"); } // Write the header os << "MARKOV" << std::endl; os << nvar() << std::endl; for (size_t i = 0; i < m_dims.size(); ++i) { os << m_dims[i] << " "; } os << std::endl; // Write the factor scopes os << num_factors() << std::endl; for (size_t i = 0; i < m_factors.size(); ++i) { const factor& f = m_factors[i]; os << f.nvar(); variable_set::const_iterator si = f.vars().begin(); for (; si != f.vars().end(); ++si) { os << " " << (*si).label(); } os << std::endl; } // Write the factor tables os << std::endl; for (size_t i = 0; i < m_factors.size(); ++i) { const factor& f = m_factors[i]; os << f.numel() << std::endl; for (size_t j = 0; j < f.numel(); ++j) { os << " " << std::setiosflags(std::ios::fixed) << std::setprecision(8) << f[j]; } os << std::endl << std::endl; } // Close the output stream os.close(); } /// /// \brief Assert evidence into the graphical model. /// \param [in] file_name The full path to a file containing the evidence /// \param [out] evidence The map containing evidence variable value pairs /// \param [out] old_to_new The mappings between old and new variable indexes /// \return the list of new factors resulting from conditioning on the evidence. /// std::vector<factor> assert_evidence(const char* file_name, std::map<size_t, size_t>& evidence, std::map<size_t, size_t>& old_to_new) { std::ifstream is(file_name); if (is.fail()) { std::cout << "Error while reading evidence file: " << file_name << std::endl; throw std::runtime_error("Evidence file error"); } size_t num_vars; is >> num_vars; // first line is the number of evidence variable for (size_t i = 0; i < num_vars; ++i) { size_t var, val; is >> var >> val; // pair variable, value evidence[var] = val; } // Condition the factors on the evidence, and accumulate the constant variable_set non_evid_vars; std::vector<factor> temp; std::vector<factor>::const_iterator it = m_factors.begin(); for (; it != m_factors.end(); ++it) { factor f = (*it); for (std::map<size_t, size_t>::const_iterator mi = evidence.begin(); mi != evidence.end(); ++mi) { size_t v = mi->first; size_t k = mi->second; if (f.vars().contains(var(v))) { f = f.condition(var(v), k); } } if (f.isscalar()) { m_global_const *= f; // accumulate the global constant } else { temp.push_back(f); non_evid_vars |= f.vars(); } } // Re-index the non-evidence variables vindex idx = 0; for (variable_set::const_iterator ci = non_evid_vars.begin(); ci != non_evid_vars.end(); ++ci) { old_to_new[ci->label()] = idx; ++idx; } std::vector<factor> result; for (size_t i = 0; i < temp.size(); ++i) { const factor& f = temp[i]; variable_set vs; for (variable_set::const_iterator ci = f.vars().begin(); ci != f.vars().end(); ++ci) { vindex old_idx = ci->label(); size_t dim = ci->states(); vindex new_idx = old_to_new[old_idx]; vs |= variable(new_idx, dim); } result.push_back(factor(vs, (double*)f.table())); } return result; } /// /// \brief Assert evidence into the graphical model. /// \param [in] evidence The map containing evidence variable value pairs /// \param [out] old_to_new The mappings between old and new variable indexes /// \return the list of new factors resulting from conditioning on the evidence. /// std::vector<factor> assert_evidence(const std::map<size_t, size_t>& evidence, std::map<size_t, size_t>& old_to_new) { // Condition the factors on the evidence, and accumulate the constant variable_set non_evid_vars; std::vector<factor> temp; std::vector<factor>::const_iterator it = m_factors.begin(); for (; it != m_factors.end(); ++it) { factor f = (*it); for (std::map<size_t, size_t>::const_iterator mi = evidence.begin(); mi != evidence.end(); ++mi) { size_t v = mi->first; size_t k = mi->second; if (f.vars().contains(var(v))) { f = f.condition(var(v), k); } } if (f.isscalar()) { m_global_const *= f; // accumulate the global constant } else { temp.push_back(f); non_evid_vars |= f.vars(); } } // Re-index the non-evidence variables vindex idx = 0; for (variable_set::const_iterator ci = non_evid_vars.begin(); ci != non_evid_vars.end(); ++ci) { old_to_new[ci->label()] = idx; ++idx; } std::vector<factor> result; for (size_t i = 0; i < temp.size(); ++i) { const factor& f = temp[i]; variable_set vs; for (variable_set::const_iterator ci = f.vars().begin(); ci != f.vars().end(); ++ci) { vindex old_idx = ci->label(); size_t dim = ci->states(); vindex new_idx = old_to_new[old_idx]; vs |= variable(new_idx, dim); } result.push_back(factor(vs, (double*)f.table())); } return result; } // Basic accessors: /// /// \brief Return the number of variables in the model. /// size_t nvar() const { return m_vadj.size(); }; /// /// \brief Convert a variable index to Var object. /// \param i The variable index to be converted /// \return the Var object corresponding to the index. /// variable var(vindex i) const { return variable(i, m_dims[i]); }; /// /// \brief Return the number of factors in the model. /// size_t num_factors() const { return m_factors.size(); }; /// /// \brief Accessor for a factor. /// \param idx The index of the factor /// \return the factor corresponding to that index. /// const factor& get_factor(findex idx) const { return m_factors[idx]; }; /// /// \brief Accessor for the factor container. /// \return the list of factors of the model. /// const std::vector<factor>& get_factors() const { return m_factors; }; // Basic variable-based queries: /// /// \brief Factors depending on a variable. /// \param v The variable object /// \return the list of factor indexes containing the variable in their scopes. /// const flist& with_variable(const variable& v) const { return m_vadj[_vindex(v)]; } /// /// \brief Union of factors depending on a set of variables. /// \param vs The set of variable object /// \return the list of factor indexes containing those variables in their scopes. /// flist with_variable_set(const variable_set& vs) const { // or on all of a set of variables flist fs = with_variable(vs[0]); for (size_t v = 1; v < vs.size(); v++) fs &= with_variable(vs[v]); return fs; } /// /// \brief Intersection of factors depending on a set of variables. /// \param vs The set of variable object /// \return the list of factor indexes containing those variables in their scopes. /// flist intersects(const variable_set& vs) const { flist fs = with_variable(vs[0]); for (size_t v = 1; v < vs.size(); v++) fs |= with_variable(vs[v]); return fs; } /// /// \brief Factors depending on a variable. /// \param v The variable object /// \return the list of factor indexes containing the variable in their scopes. /// flist contains(const variable& v) const { return with_variable(v); } /// /// \brief Union of factors depending on a set of variables. /// \param vs The set of variable object /// \return the list of factor indexes containing those variables in their scopes. /// flist contains(const variable_set& vs) const { return with_variable_set(vs); } /// /// \brief Factors contained by a set of variables. /// \param vs The set of variables /// \return the list of factor indexes contained by the set of variables. /// flist contained_by(const variable_set& vs) const { flist fs2, fs = intersects(vs); for (size_t f = 0; f < fs.size(); f++) if (m_factors[fs[f]].vars() << vs) fs2 |= fs[f]; return fs2; } /// /// \brief Markov blanket of a variable. /// \param v The variable object /// \return the set of variables that form the Markov blanket /// (ie, the variables that *v* may depend on). /// variable_set markov_blanket(const variable& v) const { // variables that v may depend on variable_set vs; const flist& nbrs = with_variable(v); for (flist::const_iterator f = nbrs.begin(); f != nbrs.end(); ++f) vs |= get_factor(*f).vars(); vs /= v; return vs; } /// /// \brief Markov blanket of a set of variables. /// \param vs The set of variables /// \return the union of Markov blankets corresponding to the /// variables in the input set. /// variable_set markov_blanket(const variable_set& vs) const { variable_set ret = markov_blanket(vs[0]); for (size_t v = 1; v < vs.size(); v++) ret |= markov_blanket(vs[v]); return ret; } /// /// \brief Full adjacency matrix. /// \return the adjacency list associated with each variable in the model. /// std::vector<variable_set> mrf() const { // full variable-to-var adjacency std::vector<variable_set> vvs; for (size_t v = 0; v < nvar(); ++v) vvs.push_back(markov_blanket(var(v))); return vvs; } // Factor ("node") manipulation operations: /// /// \brief Add a new factor to the model. /// \param F The factor to be added /// \return the index associated with the newly added factor. /// virtual findex add_factor(const factor& F) { // add a factor to our collection const variable_set& v = F.vars(); findex use = add_node(); //if (use>=nFactors()) _factors.push_back(F); else _factors[use]=F; if (use >= num_factors()) { if (m_factors.capacity() > num_factors()) m_factors.push_back(F); else { // if we'd need to copy, do it manually std::vector<factor> tmp; tmp.reserve(2 * num_factors()); tmp.resize(num_factors() + 1); for (size_t i = 0; i < m_factors.size(); ++i) tmp[i].swap(m_factors[i]); tmp[num_factors()] = F; m_factors.swap(tmp); } } else m_factors[use] = F; insert(m_vadj, use, v); if (m_dims.size() < m_vadj.size()) m_dims.resize(m_vadj.size(), 0); for (variable_set::const_iterator i = v.begin(); i != v.end(); ++i) { // look up dimensions if required if (m_dims[_vindex(*i)] == 0) m_dims[_vindex(*i)] = i->states();// add if we haven't seen this var else if (m_dims[_vindex(*i)] != i->states()) // or check it against our current states throw std::runtime_error( "Incompatible state dimension in added factor"); } return use; // return the factor index used } /// /// \brief Remove a factor from the model. /// \param idx The index of the factor to be removed /// virtual void remove_factor(findex idx) { // remove a factor from the collection erase(m_vadj, idx, get_factor(idx).vars()); // remove from variable lists m_factors[idx] = factor(); // empty its position remove_node(idx); // and remove the node } /// /// \brief Remove all factors. /// void clear_factors() { m_factors.clear(); m_vadj.clear(); m_vadj.resize(nvar()); graph::clear(); }; /// /// \brief Find the factor with the smallest scope. /// \param fl The reference to a list of factors /// \return the index of the smallest factor (scope-wise). /// findex smallest(const flist& fl) { assert(fl.size() > 0); findex ret = *fl.begin(); for (flist::const_iterator f = fl.begin(); f != fl.end(); ++f) if (get_factor(ret).nvar() > get_factor(*f).nvar()) ret = *f; return ret; } /// /// \brief Find the factor with the largest scope. /// \param fl The reference to a list of factors /// \return the index of the largest factor (scope-wise). /// findex largest(const flist& fl) { assert(fl.size() > 0); findex ret = *fl.begin(); for (flist::const_iterator f = fl.begin(); f != fl.end(); ++f) if (get_factor(ret).nvar() < get_factor(*f).nvar()) ret = *f; return ret; } // Check graphical model properties: /// /// \brief Check if a binary model. /// \return *true* if all variables have at most two values in /// their domains. Otherwise return *false*. /// bool is_binary() const { for (size_t i = 0; i < m_dims.size(); ++i) { if (m_dims[i] > 2) return false; } return true; } /// /// \brief Check if a pairwise model. /// \return *true* if all factors involve at most two variables. /// Otherwise return *false*. /// bool is_pairwise() const { for (size_t i = 0; i < num_factors(); ++i) { if (m_factors[i].nvar() > 2) return false; } return true; } // Distribution-based operators: /// /// \brief Directly calculate joint distribution function. /// \param maxsize The maximum size allowed for the joint distribution /// \return the factor representing the full joint distribution of the model. factor joint(size_t maxsize = 0) const { if (maxsize) { size_t D = 1; for (size_t i = 0; i < nvar(); i++) { // check for joint being "small" D *= (m_dims[i] ? m_dims[i] : 1); if (D > maxsize) throw std::runtime_error("graphical model::joint too large"); } } factor F; // brute force construction of joint table for (size_t i = 0; i < num_factors(); i++) F *= m_factors[i]; return F; } // Ordering: variable (elimination) orders and factor orders /// /// \brief Find the induced width (complexity) of an elimination order. /// \param order The variable elimination order /// \return the induced width of the elimination order. /// size_t induced_width(const variable_order_t& order) const { //return pseudo_tree_size(order).first; size_t width = 0; std::vector<variable_set> adj = mrf(); size_t n = order.size(); graph g(n); // create the graph for (size_t i = 0; i < adj.size(); ++i) { const variable_set& vi = adj[i]; for (variable_set::const_iterator cj = vi.begin(); cj != vi.end(); ++cj) { size_t j = _vindex(*cj); g.add_edge(i, j); } } std::vector<size_t> position(n); for (size_t i = 0; i < n; ++i) { position[order[i]] = i; } // eliminate variables and create induced edges for (size_t i = 0; i < n; ++i) { size_t var = order[i]; size_t pos = position[var]; // find the neighbors appearing later in the ordering const set<edge_id> ns = g.neighbors(var); std::set<size_t> S; for (set<edge_id>::const_iterator si = ns.begin(); si != ns.end(); ++si) { size_t j = si->second; if (position[j] > pos) { S.insert(j); } } // connect the neighbors appearing later in the ordering width = std::max(width, S.size()); std::set<size_t>::iterator it1, it2; for (it1 = S.begin(); it1 != S.end(); ++it1) { it2 = it1; while (++it2 != S.end()) { size_t u = *it1, v = *it2; if (u != v) g.add_edge(u, v); } } } return width; } /// /// \brief Variable ordering methods. /// MER_ENUM( OrderMethod , MinFill,WtMinFill,MinWidth,WtMinWidth,Random ); /// /// \brief Find a variable elimination order. /// \param ord_type The ordering method /// \return the variable ordering corresponding to the method, such that /// the first variable in the ordering is eliminated first. /// virtual variable_order_t order(OrderMethod ord_type) const { variable_order_t order; order.resize(nvar()); if (ord_type == OrderMethod::Random) { // random orders are treated here for (size_t i = 0; i < nvar(); i++) order[i] = var(i).label(); // build a list of all the variables std::random_shuffle(order.begin(), order.end());// and randomly permute them return order; // then return } std::vector<variable_set> adj = mrf(); typedef std::pair<double, size_t> node_score_t; typedef std::multimap<double, size_t> score_map_t; score_map_t scores; std::vector<score_map_t::iterator> reverse(nvar()); for (size_t v = 0; v < nvar(); v++) // get initial scores reverse[v] = scores.insert(node_score_t(order_score(adj, v, ord_type), v)); for (size_t ii = 0; ii < nvar(); ++ii) {// Iterate through, selecting variables score_map_t::iterator first = scores.begin();// Choose a random entry from among the smallest score_map_t::iterator last = scores.upper_bound(first->first); std::advance(first, randi(std::distance(first, last))); size_t i = first->second; order[ii] = var(i).label(); // save its label in the ordering scores.erase(reverse[i]); // remove it from our list variable_set vi = adj[i]; // go through adjacent variables (copy: adj may change) variable_set fix; // and keep track of which need updating for (variable_set::const_iterator j = vi.begin(); j != vi.end(); ++j) { size_t v = _vindex(*j); adj[v] |= vi; // and update their adjacency structures adj[v] /= var(i); if (fix.size() < scores.size()) { if (ord_type == OrderMethod::MinWidth || ord_type == OrderMethod::WtMinWidth) fix |= adj[v]; //var(v); // (width methods only need v, not nbrs) else fix |= adj[v]; // come back and recalculate their scores } } for (variable_set::const_iterator j = fix.begin(); j != fix.end(); ++j) { size_t jj = j->label(); scores.erase(reverse[jj]); // remove and update (score,index) pairs reverse[jj] = scores.insert(node_score_t(order_score(adj, jj, ord_type), jj)); } } return order; } /// /// \brief Find a variable elimination order. /// \param ord_type The ordering method /// \return the variable ordering corresponding to the method, such that /// the first variable in the ordering is eliminated first. /// variable_order_t order2(OrderMethod ord_type) const { // variable order to be computed variable_order_t order; if (ord_type == OrderMethod::Random) { // random orders are treated here order.resize(nvar()); for (size_t i = 0; i < nvar(); i++) order[i] = var(i).label(); // build a list of all the variables std::random_shuffle(order.begin(), order.end());// and randomly permute them return order; // then return } // create a temporary graph graph G(nvar()); std::vector<variable_set> adj = mrf(); for (size_t i = 0; i < nvar(); ++i) { variable_set& vs = adj[i]; for (variable_set::const_iterator vi = vs.begin(); vi != vs.end(); ++vi) { size_t j = vi->label(); if (j != i) G.add_edge(i, j); } } // initialize the order size_t n = nvar(); order.reserve(n); // keeps track of node scores std::vector<int> scores(n); for (size_t i = 0; i < n; ++i) { scores[i] = order_score(G, i, ord_type); } // eliminate nodes until all gone int min_score = -1, num_nodes = n; size_t width = 0; while (num_nodes != 0) { // keeps track of minimal score nodes std::vector<size_t> candidates; // minimal score of 1 or higher std::vector<size_t> simplicial; // simplicial nodes (score 0) min_score = std::numeric_limits<int>::max(); // find node to eliminate for (size_t i = 0; i < n; ++i) { if (scores[i] == 0) { // score 0 simplicial.push_back(i); } else if (scores[i] < min_score) { // new, lower score (but greater 0) min_score = scores[i]; candidates.clear(); candidates.push_back(i); } else if (scores[i] == min_score) { // current min. found again candidates.push_back(i); } } // eliminate all nodes with score=0 -> no edges will have to be added for (std::vector<size_t>::iterator it = simplicial.begin(); it != simplicial.end(); ++it) { size_t v = (*it); order.push_back(v); --num_nodes; set<edge_id> temp = G.neighbors(v); width = std::max(width, temp.size()); for (set<edge_id>::const_iterator ci = temp.begin(); ci != temp.end(); ++ci) { size_t i = ci->first, j = ci->second; G.remove_edge(i, j); } G.remove_node(v); // and adj edges scores[v] = std::numeric_limits<int>::max(); } // anything left to eliminate? If not, we are done! if (min_score == std::numeric_limits<int>::max()) { break; } // Pick one of the minimal score nodes (with score >= 1), // breaking ties randomly size_t cand = candidates[randi(candidates.size())]; //size_t cand = candidates[0]; // first candidate in list (lexicograhically) order.push_back(cand); --num_nodes; // remember it's neighbors, to be used later set<edge_id> nlist = G.neighbors(cand); std::set<size_t> neighbors; for (set<edge_id>::const_iterator ci = nlist.begin(); ci != nlist.end(); ++ci) { if (ci->first == cand && ci->second != cand) neighbors.insert(ci->second); } // connect neighbors in primal graph std::set<size_t>::iterator it1, it2; for (it1 = neighbors.begin(); it1 != neighbors.end(); ++it1) { it2 = it1; while (++it2 != neighbors.end()) { size_t i = *it1, j = *it2; G.add_edge(i, j); } } // compute candidates for score update (node's neighbors and their neighbors) width = std::max(width, neighbors.size()); std::set<size_t> to_fix(neighbors); for (std::set<size_t>::const_iterator it = neighbors.begin(); it != neighbors.end(); ++it) { size_t v = (*it); const set<edge_id>& temp = G.neighbors(v); for (set<edge_id>::const_iterator ci = temp.begin(); ci != temp.end(); ++ci) { if (ci->first == v && v != ci->second) to_fix.insert(ci->second); } } to_fix.erase(cand); // remove node from primal graph for (set<edge_id>::const_iterator ci = nlist.begin(); ci != nlist.end(); ++ci) { size_t i = ci->first, j = ci->second; G.remove_edge(i, j); } G.remove_node(cand); // and adj edges scores[cand] = std::numeric_limits<int>::max(); // tag score // update scores in primal graph (candidate nodes computed earlier) for (std::set<size_t>::const_iterator it = to_fix.begin(); it != to_fix.end(); ++it) { size_t v = (*it); scores[v] = order_score(G, v, ord_type); } } return order; } /// /// \brief Find a constrained variable elimination order. /// \param ord_type The ordering method /// \param var_types The vector containing the variable types (SUM or MAX) /// \return the constrained variable ordering corresponding to the method, /// such that SUM variables are eliminated before any of the MAX variables. /// variable_order_t order2(OrderMethod ord_type, std::vector<bool> var_types) const { // variable order to be computed variable_order_t order; // create a temporary graph graph G(nvar()); std::vector<variable_set> adj = mrf(); for (size_t i = 0; i < nvar(); ++i) { variable_set& vs = adj[i]; for (variable_set::const_iterator vi = vs.begin(); vi != vs.end(); ++vi) { size_t j = _vindex(*vi); G.add_edge(i, j); } } // reserve space for the order size_t n = nvar(); order.reserve(n); // identify SUM and MAP variables std::set<size_t> sum_vars, map_vars; for (size_t i = 0; i < n; ++i) { if (var_types[i] == false) sum_vars.insert(i); else map_vars.insert(i); } // keeps track of node scores std::vector<int> scores(n); for (size_t i = 0; i < n; ++i) { scores[i] = order_score(G, i, ord_type); } // eliminate nodes until all gone int min_score = -1, num_nodes = n; size_t width = 0; while (num_nodes != 0) { // keeps track of minimal score nodes std::vector<size_t> candidates; // minimal score of 1 or higher std::vector<size_t> simplicial; // simplicial nodes (score 0) min_score = std::numeric_limits<int>::max(); // check if there are SUM vars left to eliminate std::set<size_t>::iterator start, stop; if (sum_vars.empty() == false) { // yes start = sum_vars.begin(); stop = sum_vars.end(); } else { // done, move to MAP vars start = map_vars.begin(); stop = map_vars.end(); } for (std::set<size_t>::iterator si = start; si != stop; ++si) { int v = *si; if (scores[v] == 0) { // score 0 simplicial.push_back(v); } else if (scores[v] < min_score) { // new, lower score (but greater 0) min_score = scores[v]; candidates.clear(); candidates.push_back(v); } else if (scores[v] == min_score) { // current min. found again candidates.push_back(v); } } // eliminate all nodes with score=0 -> no edges will have to be added for (std::vector<size_t>::iterator it = simplicial.begin(); it != simplicial.end(); ++it) { size_t v = (*it); order.push_back(v); --num_nodes; set<edge_id> temp = G.neighbors(v); width = std::max(width, temp.size()); for (set<edge_id>::const_iterator ci = temp.begin(); ci != temp.end(); ++ci) { size_t i = ci->first, j = ci->second; G.remove_edge(i, j); } G.remove_node(v); // and adj edges scores[v] = std::numeric_limits<int>::max(); if (var_types[v] == false) sum_vars.erase(v); else map_vars.erase(v); } // anything left to eliminate? If not, we are done! if (min_score == std::numeric_limits<int>::max()) { break; } // Pick one of the minimal score nodes (with score >= 1), // breaking ties randomly size_t cand = candidates[randi(candidates.size())]; //size_t cand = candidates[0]; // first candidate in list (lexicograhically) order.push_back(cand); --num_nodes; // remember it's neighbors, to be used later set<edge_id> nlist = G.neighbors(cand); std::set<size_t> neighbors; for (set<edge_id>::const_iterator ci = nlist.begin(); ci != nlist.end(); ++ci) { if (ci->first == cand && ci->second != cand) neighbors.insert(ci->second); } // connect neighbors in primal graph std::set<size_t>::iterator it1, it2; for (it1 = neighbors.begin(); it1 != neighbors.end(); ++it1) { it2 = it1; while (++it2 != neighbors.end()) { size_t i = *it1, j = *it2; G.add_edge(i, j); } } // compute candidates for score update (node's neighbors and their neighbors) width = std::max(width, neighbors.size()); std::set<size_t> to_fix(neighbors); for (std::set<size_t>::const_iterator it = neighbors.begin(); it != neighbors.end(); ++it) { size_t v = (*it); const set<edge_id>& temp = G.neighbors(v); for (set<edge_id>::const_iterator ci = temp.begin(); ci != temp.end(); ++ci) { if (ci->first == v && v != ci->second) to_fix.insert(ci->second); } } to_fix.erase(cand); // remove node from primal graph for (set<edge_id>::const_iterator ci = nlist.begin(); ci != nlist.end(); ++ci) { size_t i = ci->first, j = ci->second; G.remove_edge(i, j); } G.remove_node(cand); // and adj edges scores[cand] = std::numeric_limits<int>::max(); // tag score if (var_types[cand] == false) sum_vars.erase(cand); else map_vars.erase(cand); // update scores in primal graph (candidate nodes computed earlier) for (std::set<size_t>::const_iterator it = to_fix.begin(); it != to_fix.end(); ++it) { size_t v = (*it); scores[v] = order_score(G, v, ord_type); } } return order; } /// /// \brief Find a constrained variable elimination order. /// \param ord_type The ordering method /// \param var_types The vector containing the variable types (SUM or MAX) /// \return the constrained variable ordering corresponding to the method, /// such that SUM variables are eliminated before any of the MAX variables. /// variable_order_t order(OrderMethod ord_type, std::vector<bool> var_types) const { variable_order_t order; order.resize(nvar()); if (ord_type == OrderMethod::Random) { // random orders are treated here variable_order_t sumOrd, maxOrd; for (size_t i = 0; i < nvar(); i++) { // build a list of all the variables if (var_types[i] == true) maxOrd.push_back(var(i).label()); else sumOrd.push_back(var(i).label()); } std::random_shuffle(sumOrd.begin(), sumOrd.end());// and randomly permute them std::random_shuffle(maxOrd.begin(), maxOrd.end()); size_t i = 0; for (size_t j = 0; j < sumOrd.size(); ++j) order[i++] = sumOrd[j]; for (size_t j = 0; j < maxOrd.size(); ++j) order[i++] = maxOrd[j]; return order; // then return } std::vector<variable_set> adj = mrf(); typedef std::pair<double, size_t> node_score_t; typedef std::multimap<double, size_t> score_map_t; score_map_t scores; std::vector<score_map_t::iterator> reverse(nvar()); // get the sum and max variables variable_set sumVars; for (size_t v = 0; v < nvar(); ++v) { if (var_types[v] == false) sumVars |= var(v); } // get initial scores for (size_t v = 0; v < nvar(); ++v) { reverse[v] = scores.insert(node_score_t(order_score(adj, v, ord_type), v)); } // Iterate through, selecting sum variables first for (size_t ii = 0; ii < nvar(); ++ii) {// Iterate through, selecting variables score_map_t::iterator first, last; if (sumVars.size() > 0) { // Choose a random entry from among the smallest sum vars for (score_map_t::iterator fi = scores.begin(); fi != scores.end(); ++fi) { variable v = var(fi->second); if (sumVars.contains(v)) { first = fi; last = scores.upper_bound(first->first); break; } } } else { first = scores.begin();// Choose a random entry from among the smallest last = scores.upper_bound(first->first); std::advance(first, randi(std::distance(first, last))); } size_t i = first->second; order[ii] = var(i).label(); // save its label in the ordering scores.erase(reverse[i]); // remove it from our list sumVars /= var(i); variable_set vi = adj[i]; // go through adjacent variables (copy: adj may change) variable_set fix; // and keep track of which need updating for (variable_set::const_iterator j = vi.begin(); j != vi.end(); ++j) { size_t v = _vindex(*j); adj[v] |= vi; // and update their adjacency structures adj[v] /= var(i); if (fix.size() < scores.size()) { if (ord_type == OrderMethod::MinWidth || ord_type == OrderMethod::WtMinWidth) fix |= adj[v]; //var(v); // (width methods only need v, not nbrs) else fix |= adj[v]; // come back and recalculate their scores } } for (variable_set::const_iterator j = fix.begin(); j != fix.end(); ++j) { size_t jj = j->label(); scores.erase(reverse[jj]); // remove and update (score,index) pairs reverse[jj] = scores.insert(node_score_t(order_score(adj, jj, ord_type), jj)); } } return order; } /// /// \brief Look for a better order iteratively. /// \param ord_type The variable ordering method /// \param old_score The best score found so far /// \param old_order The order corresponding to the best score so far /// void improve_order(OrderMethod ord_type, double& old_score, variable_order_t& old_order) const { variable_order_t order; order.resize(nvar()); if (ord_type == OrderMethod::Random) { // random orders are treated here for (size_t i = 0; i < nvar(); i++) order[i] = var(i).label(); // build a list of all the variables std::random_shuffle(order.begin(), order.end());// and randomly permute them // !!! what scoring mechanism to use? //std::pair<size_t,size_t> newsize = pseudoTreeSize(order); //if (newsize.first < width || (newsize.first == width && newsize.second < height)) { // width=newsize.first; height=newsize.second; oldOrder=order; //} old_order = order; return; } std::vector<variable_set> adj = mrf(); typedef std::pair<double, size_t> NN; typedef std::multimap<double, size_t> sMap; sMap scores; std::vector<sMap::iterator> reverse(nvar()); double newScore; for (size_t v = 0; v < nvar(); v++) // get initial scores reverse[v] = scores.insert(NN(order_score(adj, v, ord_type), v)); for (size_t ii = 0; ii < nvar(); ++ii) {// Iterate through, selecting variables sMap::iterator first = scores.begin();// Choose a random entry from among the smallest newScore = std::max(first->first, newScore);// keep track of largest score for this ordering if (newScore > old_score) return; // & if worse than cutoff value, just quit sMap::iterator last = scores.upper_bound(first->first); std::advance(first, randi(std::distance(first, last))); size_t i = first->second; order[ii] = var(i).label(); // save its label in the ordering scores.erase(reverse[i]); // remove it from our list variable_set vi = adj[i]; // go through adjacent variables (copy: adj may change) variable_set fix; // and keep track of which need updating for (variable_set::const_iterator j = vi.begin(); j != vi.end(); ++j) { size_t v = _vindex(*j); adj[v] |= vi; // and update their adjacency structures adj[v] /= var(i); if (ord_type == OrderMethod::MinWidth || ord_type == OrderMethod::WtMinWidth) fix |= adj[v]; //var(v); // (width methods only need v, not nbrs) else fix |= adj[v]; // come back and recalculate their scores } for (variable_set::const_iterator j = fix.begin(); j != fix.end(); ++j) { size_t jj = j->label(); scores.erase(reverse[jj]); // remove and update (score,index) pairs reverse[jj] = scores.insert(NN(order_score(adj, jj, ord_type), jj)); } } // !!! check for tiebreaker? old_order = order; return; } // Helpful manipulation functions for other data: /// /// \brief Add the scope of a factor to the adjacency list /// \param adj The adjacency list to be modified /// \param idx The index of the factor /// \param vs The scope of the factor /// void insert(std::vector<flist>& adj, findex idx, const variable_set& vs) { if (vs.nvar() > 0 && adj.size() <= vs.rbegin()->label()) // if we need to, expand our set of variables adj.resize(vs.rbegin()->label() + 1); // to be large enough to be indexed by label for (size_t i = 0; i < vs.nvar(); ++i) adj[vs[i]] |= idx; // and add factor to adj list } /// /// \brief Remove the scope of a factor from the adjacency list /// \param adj The adjacency list to be modified /// \param idx The index of the factor /// \param vs The scope of the factor /// void erase(std::vector<flist>& adj, findex idx, const variable_set& vs) { for (size_t i = 0; i < vs.nvar(); ++i) adj[vs[i]] /= idx; // remove a factor from each var's adj list } // Simple optimum selection routines: /// /// \brief Find smallest factor with each variable and select its optimum. /// std::vector<size_t> max_simple() { std::vector<size_t> vals(nvar()); for (size_t v = 0; v < nvar(); ++v) if (with_variable(var(v)).size()) { vals[v] = get_factor(smallest(with_variable(var(v)))).argmax(); } return vals; } /// /// \brief Find *maxmarginal* for variable and select optimum given those so far. /// std::vector<size_t> max_sequential(const variable_order_t& order) { std::vector<size_t> vals(nvar()); variable_set done; for (variable_order_t::const_reverse_iterator v = order.rbegin(); v != order.rend(); ++v) { variable V = var(*v); const flist& use = with_variable(V); factor mm(V, 1.0); for (flist::const_iterator f = use.begin(); f != use.end(); ++f) { size_t condi = 0; variable_set condv = get_factor(*f).vars() & done; if (condv.size()) condi = sub2ind(condv, vals); mm *= get_factor(*f).condition(condv, condi).maxmarginal(V); } vals[*v] = mm.argmax(); done += V; } return vals; } /// /// \brief Compute the log-probability of a particular (complete) configuration. /// double logP(const std::vector<size_t>& config) { double val = 0.0; for (size_t f = 0; f < num_factors(); ++f) val += std::log(get_factor(f)[sub2ind(get_factor(f).vars(), config)]); return val; } /// /// \brief Output operator. /// \param out The reference of an output stream /// \param gm The reference of a graphical model /// \return the reference of the modified output stream containing the /// formatted content of the graphical model. /// friend std::ostream& operator<<(std::ostream& out, const graphical_model& gm) { out << "Dumping graphical model content with " << gm.nvar() << " variables and " << gm.num_factors() << " factors: " << std::endl; for (size_t j = 0; j < gm.get_factors().size(); j++) out << " " << j << " " << gm.get_factors()[j] << std::endl; return out; } /// /// \brief Return the constant resulted from asserting evidence in the model. /// double get_global_const() const { return m_global_const.max(); } protected: /// /// \brief Look up the index of a variable. /// \param v The variable object /// \return the index corresponding to the variable in the model. size_t _vindex(const variable& v) const { return v.label(); } /// /// \brief Mutable accessor of adjacency. /// \param v The variable object /// \return the list of factors containing the variable in their scope. /// flist& _with_variable(const variable& v) { return m_vadj[_vindex(v)]; } /// /// \brief Internal function for ensuring consistency of the model. /// void fixup() { size_t nVar = 0; m_vadj.clear(); m_dims.clear(); for (std::vector<merlin::factor>::iterator f = m_factors.begin(); f != m_factors.end(); ++f) { if (f->nvar()) nVar = std::max(nVar, f->vars().rbegin()->label() + 1); } m_vadj.resize(nVar); // reserve the variable adjaceny lists (factors) m_dims.resize(nVar); // make space for variable inclusion mapping for (size_t f = 0; f < m_factors.size(); ++f) { // for each factor, findex use = add_node(); // add a node in the graph (factor nodes indexed from 0) assert(use == f); const variable_set& v = m_factors[f].vars(); // save the variables' dimensions and for (variable_set::const_iterator i = v.begin(); i != v.end(); ++i) { // index this factor as including them m_dims[_vindex(*i)] = i->states(); // check against current values??? _with_variable(*i) |= f; } } } // Internal helper functions: /// /// \brief Compute the score of a variable for the elimination order. /// \param adj The adjacency lists /// \param i The index of the variable /// \param kOType The variable elimination order /// \return the score of the variable. /// double order_score(const std::vector<variable_set>& adj, size_t i, OrderMethod kOType) const { double s = 0.0; switch (kOType) { case OrderMethod::MinFill: for (variable_set::const_iterator j = adj[i].begin(); j != adj[i].end(); ++j) s += (adj[i] - adj[_vindex(*j)]).size(); break; case OrderMethod::WtMinFill: for (variable_set::const_iterator j = adj[i].begin(); j != adj[i].end(); ++j) s += (adj[i] - adj[*j]).num_states(); break; case OrderMethod::MinWidth: s = adj[i].size(); break; case OrderMethod::WtMinWidth: s = adj[i].num_states(); break; default: throw std::runtime_error("Unknown elimination ordering type"); break; } return s; } int order_score(const graph& g, size_t v, OrderMethod kOType) const { int s = 0.0; switch (kOType) { case OrderMethod::MinFill: { const set<edge_id>& nlist = g.neighbors(v); std::set<size_t> S; for (set<edge_id>::const_iterator ci = nlist.begin(); ci != nlist.end(); ++ci) { size_t i = ci->first, j = ci->second; if (i == v && i != j) S.insert(j); } std::set<size_t>::iterator it1, it2; for (it1 = S.begin(); it1 != S.end(); ++it1) { it2 = it1; while (++it2 != S.end()) { size_t i = *it1, j = *it2; if (g.edge(i, j) == edge_id::NO_EDGE) ++s; } } break; } case OrderMethod::WtMinFill: { const set<edge_id>& nlist = g.neighbors(v); std::set<size_t> S; for (set<edge_id>::const_iterator ci = nlist.begin(); ci != nlist.end(); ++ci) { size_t i = ci->first, j = ci->second; if (i == v && i != j) S.insert(j); } variable_set vs; std::set<size_t>::iterator it1, it2; for (it1 = S.begin(); it1 != S.end(); ++it1) { it2 = it1; while (++it2 != S.end()) { size_t i = *it1, j = *it2; if (g.edge(i, j) == edge_id::NO_EDGE) vs |= var(j); } } s = vs.num_states(); break; } case OrderMethod::MinWidth: { const set<edge_id>& nlist = g.neighbors(v); for (set<edge_id>::const_iterator ci = nlist.begin(); ci != nlist.end(); ++ci) { size_t i = ci->first, j = ci->second; if (i == v && i != j) ++s; } break; } case OrderMethod::WtMinWidth: { const set<edge_id>& nlist = g.neighbors(v); for (set<edge_id>::const_iterator ci = nlist.begin(); ci != nlist.end(); ++ci) { size_t i = ci->first, j = ci->second; if (i == v && i != j) s += var(j).states(); } break; } default: throw std::runtime_error("Unknown elimination ordering type"); break; } return s; } /// /// \brief Create a random elimination order. /// variable_order_t order_random() const { variable_order_t order; order.resize(nvar()); for (size_t i = 0; i < nvar(); i++) order[i] = var(i).label(); // build a list of all the variables std::random_shuffle(order.begin(), order.end());// and randomly permute them return order; } protected: // Members: std::vector<factor> m_factors; ///< Collection of all factors in the model. private: // Members: std::vector<flist> m_vadj; ///< Variable adjacency lists (variables to factors) std::vector<double> m_dims; ///< Dimensions of variables as stored in graphical model object factor m_global_const; ///< Constant produced by removing evidence (default 1.0) }; } // namespace // ToDo: // Container aspect: contains // vector<Factor> : insert(F), erase(i), compress (maximal sets only) // map<Var,set<fidx>> : find factors with var / varset // edges between factor "nodes" : add, remove, clear, neighborhood lists // Functional operations // Orderings: variable (elimination orders) and node (spanning & covering trees, etc) // MRF adj: map<Var, VarSet> , markovBlanket(v), cliques? // VarDepUpdates: change Var:FIdx map: erase(&map,i,vs), insert(&map,i,vs) // Edge/adjacency: edge(i,j), neighbors(i), // #endif /* GRAPHICAL_MODEL_H_ */
31.694156
117
0.629023
e77f0c5407dd60c163ea84ced05720eaa3766016
1,365
js
JavaScript
src/components/Home/index.js
indec-it/seed-backoffice-react
62fc7480ba3166cf9760963bf7c0fc653aea44d7
[ "MIT" ]
1
2018-05-16T15:34:54.000Z
2018-05-16T15:34:54.000Z
src/components/Home/index.js
indec-it/seed-backoffice-react
62fc7480ba3166cf9760963bf7c0fc653aea44d7
[ "MIT" ]
14
2018-07-09T23:20:44.000Z
2022-02-10T17:15:27.000Z
src/components/Home/index.js
indec-it/seed-backoffice-react
62fc7480ba3166cf9760963bf7c0fc653aea44d7
[ "MIT" ]
1
2020-05-20T11:30:59.000Z
2020-05-20T11:30:59.000Z
/* eslint-disable */ import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { Col, Container, Row, ButtonGroup } from 'reactstrap'; class Home extends Component { static propTypes = { profile: PropTypes.shape({}) }; static defaultProps = { profile: null }; constructor(props) { super(props); const component = null; this.state = { component }; } renderHome() { return ( <Container fluid> <Row className="no-padding align-items-center"> <Col sm={12} className="no-padding"> <hr className="hr-title"/> </Col> </Row> <Row className="no-padding align-items-center"> <Col md={4}> <h4 className="text-center">Lista de Instructivos</h4> <ButtonGroup vertical block> </ButtonGroup> </Col> <Col md={6} mdOffset={2}> </Col> </Row> </Container> ); } render() { return ( <Container fluid> {this.renderHome()} </Container> ); } } export default Home;
23.534483
78
0.441758
da38b0e69516ed55dca4677ec6fda5a9f9130e89
4,719
rs
Rust
src/models/timestamp.rs
jay3332/rs-cord
0096062a8cccc4721d0fac3ac8b3db73eae4c34b
[ "MIT" ]
5
2022-01-05T16:17:55.000Z
2022-01-11T01:24:10.000Z
src/models/timestamp.rs
jay3332/rs-cord
0096062a8cccc4721d0fac3ac8b3db73eae4c34b
[ "MIT" ]
null
null
null
src/models/timestamp.rs
jay3332/rs-cord
0096062a8cccc4721d0fac3ac8b3db73eae4c34b
[ "MIT" ]
null
null
null
use std::time::Duration; #[cfg(feature = "chrono")] extern crate chrono; #[cfg(feature = "chrono")] use chrono::{DateTime, NaiveDateTime, Utc}; /// An enum to represent relative time. /// /// # See /// [`Timestamp::as_relative_time`] #[derive(Clone, Debug)] pub enum RelativeTime { /// This timestamp is in the past. Past(Duration), /// This timestamp is in the future. Future(Duration), } /// Represents a timestamp which contains date and time. #[derive(Clone, Debug)] pub struct Timestamp { /// Unix timestamp in milliseconds timestamp: u64, } impl Timestamp { /// Creates a new timestamp from a Unix timestamp in milliseconds. #[must_use] pub fn from_unix(timestamp: u64) -> Self { Self { timestamp } } /// Creates a new timestamp from a Discord snowflake. #[must_use] pub fn from_snowflake(snowflake: u64) -> Self { Self::from_unix(snowflake >> 22) } /// Creates a new timestamp from a [`chrono::DateTime`]. /// /// # Panics /// - Timestamp is before the Unix epoch #[cfg(feature = "chrono")] #[must_use] pub fn from_datetime(dt: DateTime<Utc>) -> Self { Self::from_unix( dt.timestamp_millis() .try_into() .expect("Timestamp is before the Unix epoch."), ) } /// Creates a new timestamp from an ISO 8601 timestamp. /// /// # Panics /// - Timestamp is not a valid timestamp. #[cfg(feature = "chrono")] #[must_use] pub fn from_iso(iso: String) -> Self { Self::from_datetime( DateTime::parse_from_rfc3339(&iso) .expect("Failed to parse ISO 8601 timestamp. (Note: this is confined to the RFC 3339 standard.)") .with_timezone(&Utc) ) } /// The amount of milliseconds since the Unix epoch. #[must_use] pub fn timestamp_millis(&self) -> u64 { self.timestamp } /// The amount of seconds since the Unix epoch, as a whole number. #[must_use] pub fn timestamp_secs(&self) -> u64 { self.timestamp / 1000_u64 } /// Converts this timestamp into a tuple (seconds, nonoseconds). #[must_use] pub fn to_secs_nanos(&self) -> (u64, u32) { let secs = self.timestamp_secs(); let nanos = (self.timestamp - secs * 1000_u64) * 1_000_000_u64; #[allow(clippy::cast_possible_truncation)] (secs, nanos as u32) } /// The timestamp as a [`chrono::DateTime`]. #[cfg(feature = "chrono")] #[must_use] pub fn as_datetime(&self) -> DateTime<Utc> { let (secs, nanos) = self.to_secs_nanos(); #[allow(clippy::cast_possible_wrap)] DateTime::from_utc(NaiveDateTime::from_timestamp(secs as i64, nanos), Utc) } /// Returns a [`Duration`][`std::time::Duration`] that represents how much time has elapsed from this timestamp. /// /// Note that this method will panic if this timestamp is in the future. /// If you would like to convert this into relative time, use [`as_relative_time()`][`Timestamp::as_relative_time`]. /// /// # Panics /// - Timestamp is in the future #[cfg(feature = "chrono")] #[must_use] pub fn elapsed(&self) -> Duration { Duration::from_millis( (chrono::Utc::now().timestamp_millis() - self.timestamp_millis() as i64) .try_into() .expect("Timestamp is in the future."), ) } /// Returns a [`RelativeTime`] that represents how much time has elapsed from this timestamp. /// /// If the timestamp is exactly now, the returned value is [`RelativeTime::Future`]. /// /// # Example /// ```rust /// use rs_cord::{Timestamp, RelativeTime}; /// use RelativeTime::{Past, Future}; /// /// match Timestamp::from_unix(1234).as_relative_time() { /// Past(dur) => println!("{} seconds ago", dur.as_secs()), /// Future(dur) => println!("{} seconds from now", dur.as_secs()), /// } /// ``` #[cfg(feature = "chrono")] #[must_use] pub fn as_relative_time(&self) -> RelativeTime { let delta = chrono::Utc::now().timestamp_millis() - self.timestamp_millis() as i64; if delta <= 0 { RelativeTime::Future(Duration::from_millis(delta.abs() as u64)) } else { RelativeTime::Past(Duration::from_millis(delta as u64)) } } } #[cfg(feature = "chrono")] impl From<Timestamp> for DateTime<Utc> { fn from(ts: Timestamp) -> Self { ts.as_datetime() } } #[cfg(feature = "chrono")] impl From<DateTime<Utc>> for Timestamp { fn from(dt: DateTime<Utc>) -> Self { Self::from_datetime(dt) } }
29.867089
120
0.594194
475bb656c0135ea6f01cc7b591a56f1004247368
4,266
html
HTML
index.html
brnmpto/apple-clone
656ae361924001f8031e8874e9d011f8bd491a72
[ "MIT" ]
null
null
null
index.html
brnmpto/apple-clone
656ae361924001f8031e8874e9d011f8bd491a72
[ "MIT" ]
null
null
null
index.html
brnmpto/apple-clone
656ae361924001f8031e8874e9d011f8bd491a72
[ "MIT" ]
null
null
null
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="style.css"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css"> <title>Apple</title> </head> <body> <header> <div class="container"> <nav class="nav"> <ul class="nav-list nav-list-larger"> <li class="nav-item nav-items-hidden"> <a href="index.html" class="nav-link nav-link-apple"><i class="fa fa-apple"></i></a> </li> <li class="nav-item"> <a href="#" class="nav-link">Mac</a> </li> <li class="nav-item"> <a href="#" class="nav-link">iPad</a> </li> <li class="nav-item"> <a href="#" class="nav-link">iPhone</a> </li> <li class="nav-item"> <a href="#" class="nav-link">Watch</a> </li> <li class="nav-item"> <a href="#" class="nav-link">TV</a> </li> <li class="nav-item"> <a href="#" class="nav-link">Music</a> </li> <li class="nav-item"> <a href="#" class="nav-link">Support</a> </li> <li class="nav-item"> <a href="#" class="nav-link nav-link-search"><i class="fa fa-search"></i></a> </li> </ul> </nav> </div> </header> <section class="hero watch_series6"> <div class="container container-clock"> <div class="title"> <h2 class="title-img"><img class="title-watch" src="images/watch_series.png" alt=""></h2> <h3 class="title-sub-heading title-subheading-white">Um futuro mais saudável no seu pulso.</h3> </div> <div class="cta"> <a href="#" class="cta-link">Saiba mais <i class="fa fa-angle-right" aria-hidden="true"></i> </a> <a href="#" class="cta-link">Ver preços <i class="fa fa-angle-right" aria-hidden="true"></i> </a> </div> <div class="img-clock"> <img class="img-watch" src="images/img_1.png" alt=""> </div> </div> </section> <section class="hero ipad"> <div class="container container-ipad"> <div class="title title-text"> <h2 class="title-dark">iPad Air</h2> <h3 class="title-sub-heading title-sub-heading-dark">Cheio de potência, cor e possibilidades.</h3> </div> <div class="cta"> <a href="#" class="cta-link">Saiba mais <i class="fa fa-angle-right" aria-hidden="true"></i> </a> <a href="#" class="cta-link">Ver preços <i class="fa fa-angle-right" aria-hidden="true"></i> </a> </div> <div class="img-clock"> <img class="img-ipad" src="images/ipad.jpg" alt=""> </div> </div> </section> <section class="hero watch-se"> <div class="container container-watch-se"> <div class="title title-text"> <h2 class="title-img"><img class="title-watch" src="images/watch_se.png" alt=""></h2> <h3 class="title-sub-heading title-sub-heading-dark">É muito Apple Watch por menos.</h3> </div> <div class="cta"> <a href="#" class="cta-link">Saiba mais <i class="fa fa-angle-right" aria-hidden="true"></i> </a> <a href="#" class="cta-link">Ver preços <i class="fa fa-angle-right" aria-hidden="true"></i> </a> </div> <div class="img-clock"> <img class="img-watch-se" src="images/watch-se-img.jpg" alt=""> </div> </div> </section> </body> </html>
41.019231
117
0.454993
78b410055b56dd9d3123bfd61ba56dfd03a6c1ad
68
swift
Swift
Prelude-UIKit/LensHolder.swift
ryantstone/Kickstarter-Prelude
ee7a68e02da80c8742ee8027f70fa831a1826c86
[ "Apache-2.0" ]
460
2016-12-14T13:37:06.000Z
2022-03-04T07:43:47.000Z
Prelude-UIKit/LensHolder.swift
michaelevensen/Kickstarter-Prelude
03e377dd9d1ceaa81347a1475f0d43f8d4089983
[ "Apache-2.0" ]
18
2016-12-15T16:04:07.000Z
2019-03-19T21:33:48.000Z
Prelude-UIKit/LensHolder.swift
michaelevensen/Kickstarter-Prelude
03e377dd9d1ceaa81347a1475f0d43f8d4089983
[ "Apache-2.0" ]
83
2016-12-14T16:15:42.000Z
2022-03-22T00:59:27.000Z
import Foundation import Prelude extension NSObject: LensObject {}
13.6
33
0.823529
39bac38cb5e9f20fb774a5d1bec95447a3ff3089
3,612
js
JavaScript
src/modules/k8s/shared.js
smpio/kubernator
353263a1505ee1ccf204ca73f6164e2f2408e15d
[ "MIT" ]
511
2017-11-23T16:48:45.000Z
2022-01-03T03:58:28.000Z
src/modules/k8s/shared.js
smpio/kube-browser
353263a1505ee1ccf204ca73f6164e2f2408e15d
[ "MIT" ]
36
2017-11-23T10:04:04.000Z
2021-03-01T22:35:38.000Z
src/modules/k8s/shared.js
smpio/kube-browser
353263a1505ee1ccf204ca73f6164e2f2408e15d
[ "MIT" ]
41
2017-11-24T10:10:49.000Z
2021-07-28T05:48:20.000Z
import { call, put, take, takeEvery } from 'redux-saga/effects'; // import store from 'store'; import { NotiErrorApi, } from '../../middleware/notifications'; // constants // ----------- export const PREFIX = 'k8s'; export const LOADING = Symbol('LOADING'); export const FAILURE = Symbol('FAILURE'); export const ID = Symbol('ID'); export const URL = Symbol('URL'); export const YAML = Symbol('YAML'); export const VERSION = Symbol('VERSION'); export const VERSIONS = Symbol('VERSIONS'); export const GROUP_ID = Symbol('GROUP_ID'); export const RESOURCE_ID = Symbol('RESOURCE_ID'); export const RESOURCE_IDS = Symbol('RESOURCE_IDS'); export const ITEM_IDS = Symbol('ITEM_IDS'); export const IS_READONLY = Symbol('IS_READONLY'); export const IS_LISTABLE = Symbol('IS_LISTABLE'); export const CATALOG_LOADING_STAGE = Symbol('CATALOG_LOADING_STAGE'); export const CATALOG_LOADING_STAGE_GROUPS = Symbol('CATALOG_LOADING_STAGE_GROUPS'); export const CATALOG_LOADING_STAGE_RESOURCES = Symbol('CATALOG_LOADING_STAGE_RESOURCES'); export const CATALOG_LOADING_STAGE_NAMESPACES = Symbol('CATALOG_LOADING_STAGE_NAMESPACES'); export const URL_PART_GROUP = Symbol('URL_PART_GROUP'); export const URL_PART_RESOURCE = Symbol('URL_PART_RESOURCE'); export const NO_GROUP = '[nogroup]'; export const NO_NAMESPACE = '[nonamespace]'; export const NO_UID = '[nouid]'; export const UI_THROTTLE = 100; // network // --------- export const apiFlagsUnset = { [LOADING]: false, [FAILURE]: false, }; export function apiFlagsSet(state, action) { const { payload: { error } = {}} = action; return { [LOADING]: !error, [FAILURE]: !!error, }; } export async function apiFetch(url, options = {}, parser = 'json') { const netResponse = await fetch(url, options); if (netResponse.ok) return netResponse[parser](); else { let apiResponse; // parse as text try { apiResponse = await netResponse.text(); } catch (e) {} // parse as json try { apiResponse = JSON.parse(apiResponse); } catch (e) {} // notify throw new NotiErrorApi(apiResponse, netResponse); } } export async function cacheGet(url) { // cache is disabled because it is not important since new OpenAPI endpoint // but it can break things with CRDs and external APIServices let result = undefined; // store.get(url); if (!result) { result = await apiFetch(url); // store.set(url, result); } return Promise.resolve(result); } // actions // --------- export function* putTake(actionPut, actionsTake) { const $id = Date.now(); // put if (!actionPut.meta) actionPut.meta = {}; actionPut.meta.$id = $id; yield put(actionPut); // take const [actionTypeS/*, actionTypeF*/] = actionsTake; let action = { meta: { $id: null }}; while (action.meta.$id !== $id) { action = yield take(actionsTake); } // return action.type === actionTypeS ? action : null; } export function* takeEveryReq(actions, fn, _onSuccess) { const [REQUEST, SUCCESS, FAILURE] = actions; yield takeEvery(REQUEST, function* (action) { const { payload, meta, promise: { _resolve, _reject } = {}} = action; try { const payload = yield call(fn, action); if (payload) { yield put({ type: SUCCESS, payload, meta, }); if (_onSuccess) yield call(_onSuccess, payload); if (_resolve) _resolve(payload); } } catch (error) { if (_reject) _reject(error); yield put({ type: FAILURE, payload: { ...payload, error }, meta, }); } }); }
24.739726
91
0.654208
ec4bd7d969a2a3dc0207dd2a20b34e657008bb26
6,564
swift
Swift
Sources/FileGenerators/CPlusPlusWBPosterGenerator.swift
mipalgu/WhiteboardWrapperGenerator
d4718737614e804b39da44fdf86a3185b41a92be
[ "BSD-4-Clause" ]
null
null
null
Sources/FileGenerators/CPlusPlusWBPosterGenerator.swift
mipalgu/WhiteboardWrapperGenerator
d4718737614e804b39da44fdf86a3185b41a92be
[ "BSD-4-Clause" ]
null
null
null
Sources/FileGenerators/CPlusPlusWBPosterGenerator.swift
mipalgu/WhiteboardWrapperGenerator
d4718737614e804b39da44fdf86a3185b41a92be
[ "BSD-4-Clause" ]
null
null
null
/** * /file CPlusPlusWBPosterGenerator.swift * * Created by Carl Lusty in 2018. * Copyright (c) 2018 Carl Lusty * All rights reserved. */ import Foundation import DataStructures import Protocols import NamingFuncs import whiteboard_helpers final public class CPlusPlusWBPosterGenerator: FileGenerator { public typealias T = TSL public var name: String public var path: URL public var config: Config public init(path: URL, config: Config) { self.name = "guwhiteboardposter.cpp" self.path = path self.config = config } func createParserForPrimitives(type: String, inputVarName: String) -> String { switch(type) { case "int", "bool", "uint8_t", "int8_t", "uint16_t", "int16_t", "uint32_t", "int32_t", "uint64_t", "int64_t": return "static_cast<\(type)>(atoi(\(inputVarName).c_str()))" case "float", "double": return "static_cast<\(type)>(atof(\(inputVarName).c_str()))" case "std::string": return "\(inputVarName)" case "std::vector<int>": return "strtointvec(\(inputVarName))" default: return "\(inputVarName)" } } public func createContent(obj: T) -> String { let copyright = FileGeneratorHelpers.createCopyright(fileName: self.name) let tsl: TSL = obj //alias let classes: [TSLEntry] = tsl.entries let cns = WhiteboardHelpers().cNamespace(of: config.cNamespaces) let cppns = WhiteboardHelpers().cppNamespace(of: config.cppNamespaces) return """ \(copyright) /** Auto-generated, don't modify! */ #include <string> #include <vector> #include <cstdlib> #pragma clang diagnostic push #pragma clang diagnostic ignored \"-Wunused-macros\" #define WHITEBOARD_POSTER_STRING_CONVERSION #pragma clang diagnostic pop #include \"guwhiteboardtypelist_generated.h\" #include \"guwhiteboardposter.h\" using namespace std; using namespace \(WhiteboardHelpers().cppNamespace(of: config.cppNamespaces)); extern \"C\" { \(cns)_types whiteboard_type_for_message_named(const char *message_type) { return types_map[message_type]; } bool whiteboard_post(const char *message_type, const char *message_content) { return whiteboard_postmsg(types_map[message_type], message_content); } bool whiteboard_post_to(gu_simple_whiteboard_descriptor *wbd, const char *message_type, const char *message_content) { return whiteboard_postmsg_to(wbd, types_map[message_type], message_content); } bool whiteboard_postmsg(int message_index, const char *message_content) { return postmsg(\(cns)_types(message_index), message_content); } bool whiteboard_postmsg_to(gu_simple_whiteboard_descriptor *wbd, int message_index, const char *message_content) { return postmsg(\(cns)_types(message_index), message_content, wbd); } } // extern C #pragma clang diagnostic push #pragma clang diagnostic ignored \"-Wunused-function\" static vector<int> strtointvec(string str) { const char *sep = "|,"; char *context = NULLPTR; vector<int> array; for (char *element = strtok_r(const_cast<char *>(str.c_str()), sep, &context); element; element = strtok_r(NULLPTR, sep, &context)) array.push_back(atoi(element)); return array; } #pragma clang diagnostic pop #pragma clang diagnostic push #pragma clang diagnostic ignored \"-Wglobal-constructors\" #pragma clang diagnostic ignored \"-Wexit-time-destructors\" whiteboard_types_map \(cppns)::types_map; ///< global types map #pragma clang diagnostic pop \(config.cppNamespaces.map({ "namespace " + $0 + " {\n" }).joined(separator: "")) bool post(string message_type, string message_content, gu_simple_whiteboard_descriptor *wbd) { return postmsg(types_map[message_type], message_content, wbd); } bool postmsg(\(cns)_types message_index, std::string message_content, gu_simple_whiteboard_descriptor *wbd) { switch (message_index) { \(classes.map { entry in let CPlusPlusClassName = NamingFuncs.createCPlusPlusClassName(entry.type, config: config) let WBPtrClass = NamingFuncs.createCPlusPlusTemplateClassName(entry.name.string, config: config) let slotEnumName = NamingFuncs.createMsgEnumNameNamespaced(entry.name.string, config: config) return """ case \(slotEnumName): { \(entry.type.isCustomTypeClass ? "#ifdef \(WhiteboardHelpers().cppDefinedDef(forClassNamed: CPlusPlusClassName, namespaces: config.cppNamespaces))" : "") class \(WBPtrClass) msg_ptr(wbd); \(entry.type.isCustomTypeClass ? """ \(CPlusPlusClassName) v = msg_ptr.get(); v.from_string(message_content); """ : """ \(entry.type.typeName) v = \(createParserForPrimitives(type: entry.type.typeName, inputVarName: "message_content")); """) msg_ptr.post(v); return true; \(entry.type.isCustomTypeClass ? """ #else return false; #endif //\(WhiteboardHelpers().cppDefinedDef(forClassNamed: CPlusPlusClassName, namespaces: config.cppNamespaces)) """ : "") } """ }.reduce("", +) ) #pragma clang diagnostic push #pragma clang diagnostic ignored \"-Wunreachable-code\" (void) message_content; } return false; #pragma clang diagnostic pop } } whiteboard_types_map::whiteboard_types_map(): map<string, \(cns)_types>() { whiteboard_types_map &self = *this; \(classes.map { entry in let slotEnumName = NamingFuncs.createMsgEnumNameNamespaced(entry.name.string, config: config) return """ self[\"\(entry.name.string)\"] = \(slotEnumName); """ }.reduce("", +) ) (void) self; \(config.cppNamespaces.reversed().map({ "} // " + $0 + "\n" }).joined(separator: "")) """ } }
32.82
161
0.603595
106ebacb0e70715407ae6d582ca116898725c3f0
183
swift
Swift
Projects/Application/Tests/RIBs/Authentication/Register/Mock/RegisterDependencyMock.swift
interactord/modoo
e6394c899c4410d6b713dd4fb78b20c1065d7db0
[ "MIT" ]
4
2021-02-01T17:04:34.000Z
2021-04-17T04:09:04.000Z
Projects/Application/Tests/RIBs/Authentication/Register/Mock/RegisterDependencyMock.swift
interactord/modoo
e6394c899c4410d6b713dd4fb78b20c1065d7db0
[ "MIT" ]
30
2021-02-01T17:10:33.000Z
2021-03-22T01:54:58.000Z
Projects/Application/Tests/RIBs/Authentication/Register/Mock/RegisterDependencyMock.swift
interactord/modoo
e6394c899c4410d6b713dd4fb78b20c1065d7db0
[ "MIT" ]
null
null
null
import RIBs @testable import Application class RegisterDependencyMock: RegisterDependency { var mediaPickerUseCase: MediaPickerUseCase { UIMediaPickerPlatformUseCase() } }
16.636364
50
0.803279
9f110f331edc1b2da3c579f65fb1cab5eb96df9e
1,820
swift
Swift
corona-virus/corona-virus/views/LegalNoticesViewController.swift
sassoftware/sas-sdk-for-iOS-examples
02a3e03d027b2c712c4a525c1ee73114dd5b85f8
[ "Apache-2.0" ]
8
2018-04-18T18:30:17.000Z
2020-04-19T19:43:04.000Z
corona-virus/corona-virus/views/LegalNoticesViewController.swift
sassoftware/sas-sdk-for-iOS-examples
02a3e03d027b2c712c4a525c1ee73114dd5b85f8
[ "Apache-2.0" ]
8
2018-04-25T05:03:10.000Z
2019-09-30T15:07:09.000Z
corona-virus/corona-virus/views/LegalNoticesViewController.swift
sassoftware/sas-sdk-for-iOS-examples
02a3e03d027b2c712c4a525c1ee73114dd5b85f8
[ "Apache-2.0" ]
5
2018-04-20T15:04:37.000Z
2019-10-08T16:22:42.000Z
// // LegalNoticesViewController.swift // corona-virus // // Copyright © 2020 SAS. All rights reserved. // import UIKit class LegalNoticesViewController : UIViewController { @IBOutlet weak var containerView:UIView? @IBOutlet weak var closeButton:UIBarButtonItem? override func viewDidLoad() { super.viewDidLoad() navigationItem.title = NSLocalizedString("Legal Notices Title", comment: "") closeButton?.title = NSLocalizedString("Close Button Label", comment: "") guard let legalView = AppViewModel.shared.report?.loadReportObject(AppViewModel.shared.legalObjectID)?.view else { return } guard let container = containerView else { return } container.addSubview( legalView ) legalView.translatesAutoresizingMaskIntoConstraints = false let topConstraint = NSLayoutConstraint(item: legalView, attribute: .top, relatedBy: .equal, toItem: container, attribute: .top, multiplier: 1, constant: 0) let bottomConstraint = NSLayoutConstraint(item: legalView, attribute: .left, relatedBy: .equal, toItem: container, attribute: .left, multiplier: 1, constant: 0) let leftConstraint = NSLayoutConstraint(item: legalView, attribute: .right, relatedBy: .equal, toItem: container, attribute: .right, multiplier: 1, constant: 0) let rightConstraint = NSLayoutConstraint(item: legalView, attribute: .bottom, relatedBy: .equal, toItem: container, attribute: .bottom, multiplier: 1, constant: 0) container.addConstraints([ topConstraint, bottomConstraint, leftConstraint, rightConstraint]) } @IBAction func closeLegalNotice( sender: UIBarButtonItem ) { self.navigationController?.dismiss(animated: true, completion: {}) } }
41.363636
171
0.697253
d924b8e3e47f4c551be43e80bcad4c9a086de308
713
sql
SQL
packages/intranet-core/sql/postgresql/upgrade/upgrade-5.0.2.3.0-5.0.2.3.1.sql
iuri/tutortronics
463ea1535773d06ce34d269136eab3ecaffcb1cf
[ "Info-ZIP", "ImageMagick" ]
null
null
null
packages/intranet-core/sql/postgresql/upgrade/upgrade-5.0.2.3.0-5.0.2.3.1.sql
iuri/tutortronics
463ea1535773d06ce34d269136eab3ecaffcb1cf
[ "Info-ZIP", "ImageMagick" ]
null
null
null
packages/intranet-core/sql/postgresql/upgrade/upgrade-5.0.2.3.0-5.0.2.3.1.sql
iuri/tutortronics
463ea1535773d06ce34d269136eab3ecaffcb1cf
[ "Info-ZIP", "ImageMagick" ]
null
null
null
-- 5.0.2.3.0-5.0.2.3.1.sql SELECT acs_log__debug('/packages/intranet-core/sql/postgresql/upgrade/upgrade-5.0.2.3.0-5.0.2.3.1.sql',''); select im_menu__new ( null, -- p_menu_id 'im_menu', -- object_type now(), -- creation_date null, -- creation_user null, -- creation_ip null, -- context_id 'intranet-core', -- package_name 'admin_request_monitor', -- label 'Request Monitor', -- name '/request-monitor/index', -- url 2200, -- sort_order (select menu_id from im_menus where label = 'admin'), '[im_package_exists_p "xotcl-request-monitor"]' -- p_visible_tcl ); update im_menus set sort_order = 2200, menu_gif_small = 'arrow_right' where label = 'openacs_request_monitor';
31
110
0.684432
7aabff72cf86db3aad9e2f3854efb9266c58c8c8
514
rb
Ruby
attributes/install.rb
sous-chefs/traefik
dd57fcec8a6e3b04633d6cbff977dbf035c663b1
[ "Apache-2.0" ]
7
2016-11-22T21:27:44.000Z
2019-07-22T02:09:53.000Z
attributes/install.rb
sous-chefs/traefik
dd57fcec8a6e3b04633d6cbff977dbf035c663b1
[ "Apache-2.0" ]
4
2020-09-17T19:12:45.000Z
2021-08-20T15:03:00.000Z
attributes/install.rb
redguide/traefik
dd57fcec8a6e3b04633d6cbff977dbf035c663b1
[ "Apache-2.0" ]
4
2017-03-09T17:12:07.000Z
2017-08-14T17:51:54.000Z
default['traefik']['install']['version'] = '1.3.1' default['traefik']['install']['install_method'] = 'binary' default['traefik']['install']['binary']['version'] = node['traefik']['install']['version'] default['traefik']['install']['binary']['url'] = "https://github.com/containous/traefik/releases/download/v#{node['traefik']['install']['binary']['version']}/traefik_linux-amd64" default['traefik']['install']['binary']['checksum'] = nil default['traefik']['install']['binary']['path'] = '/usr/local/bin/traefik'
64.25
178
0.671206
cb38fe28f078cf020523f313e091214c323885ba
11,622
go
Go
workflow.go
snipem/awgo
09f767b094816cd865fa3b396d09023baeaa8ff5
[ "MIT" ]
736
2017-09-08T20:39:13.000Z
2022-03-31T15:04:35.000Z
workflow.go
snipem/awgo
09f767b094816cd865fa3b396d09023baeaa8ff5
[ "MIT" ]
76
2018-01-17T02:29:39.000Z
2022-03-19T10:57:01.000Z
workflow.go
snipem/awgo
09f767b094816cd865fa3b396d09023baeaa8ff5
[ "MIT" ]
39
2017-09-15T06:49:24.000Z
2022-01-25T10:39:50.000Z
// Copyright (c) 2018 Dean Jackson <deanishe@deanishe.net> // MIT Licence - http://opensource.org/licenses/MIT package aw import ( "fmt" "io" "log" "os" "os/exec" "path/filepath" "runtime/debug" "sync" "time" "go.deanishe.net/fuzzy" "github.com/deanishe/awgo/keychain" "github.com/deanishe/awgo/util" ) // AwGoVersion is the semantic version number of this library. const AwGoVersion = "0.27.1" // Default Workflow settings. Can be changed with the corresponding Options. // // See the Options and Workflow documentation for more information. const ( DefaultLogPrefix = "\U0001F37A" // Beer mug DefaultMaxLogSize = 1048576 // 1 MiB DefaultMaxResults = 0 // No limit, i.e. send all results to Alfred DefaultSessionName = "AW_SESSION_ID" // Workflow variable session ID is stored in DefaultMagicPrefix = "workflow:" // Prefix to call "magic" actions ) var ( startTime time.Time // Time execution started // The workflow object operated on by top-level functions. // wf *Workflow // Flag, as we only want to set up logging once // TODO: Better, more pluggable logging logInitialized bool ) // init creates the default Workflow. func init() { startTime = time.Now() } // Mockable function to run commands type commandRunner func(name string, arg ...string) error // Run command via exec.Command func runCommand(name string, arg ...string) error { return exec.Command(name, arg...).Run() } // Mockable exit function var exitFunc = os.Exit // Workflow provides a consolidated API for building Script Filters. // // As a rule, you should create a Workflow in init or main and call your main // entry-point via Workflow.Run(), which catches panics, and logs & shows the // error in Alfred. // // Script Filter // // To generate feedback for a Script Filter, use Workflow.NewItem() to create // new Items and Workflow.SendFeedback() to send the results to Alfred. // // Run Script // // Use the TextErrors option, so any rescued panics are printed as text, // not as JSON. // // Use ArgVars to set workflow variables, not Workflow/Feedback. // // See the _examples/ subdirectory for some full examples of workflows. type Workflow struct { sync.WaitGroup // Interface to workflow's settings. // Reads workflow variables by type and saves new values to info.plist. Config *Config // Call Alfred's AppleScript functions. Alfred *Alfred // Cache is a Cache pointing to the workflow's cache directory. Cache *Cache // Data is a Cache pointing to the workflow's data directory. Data *Cache // Session is a cache that stores session-scoped data. These data // persist until the user closes Alfred or runs a different workflow. Session *Session // Access macOS Keychain. Passwords are saved using the workflow's // bundle ID as the service name. Passwords are synced between // devices if you have iCloud Keychain turned on. Keychain *keychain.Keychain // The response that will be sent to Alfred. Workflow provides // convenience wrapper methods, so you don't normally have to // interact with this directly. Feedback *Feedback // Updater fetches updates for the workflow. Updater Updater // magicActions contains the magic actions registered for this workflow. // Several built-in actions are registered by default. See the docs for // MagicAction for details. magicActions *magicActions logPrefix string // Written to debugger to force a newline maxLogSize int // Maximum size of log file in bytes magicPrefix string // Overrides DefaultMagicPrefix for magic actions. maxResults int // max. results to send to Alfred. 0 means send all. sortOptions []fuzzy.Option // Options for fuzzy filtering textErrors bool // Show errors as plaintext, not Alfred JSON helpURL string // URL to help page (shown if there's an error) dir string // Directory workflow is in cacheDir string // Workflow's cache directory dataDir string // Workflow's data directory sessionName string // Name of the variable sessionID is stored in sessionID string // Random session ID execFunc commandRunner // Run external commands } // New creates and initialises a new Workflow, passing any Options to // Workflow.Configure(). // // For available options, see the documentation for the Option type and the // following functions. // // IMPORTANT: In order to be able to initialise the Workflow correctly, // New must be run within a valid Alfred environment; specifically // *at least* the following environment variables must be set: // // alfred_workflow_bundleid // alfred_workflow_cache // alfred_workflow_data // // If you aren't running from Alfred, or would like to specify a // custom environment, use NewFromEnv(). func New(opts ...Option) *Workflow { return NewFromEnv(nil, opts...) } // NewFromEnv creates a new Workflows from the specified Env. // If env is nil, the system environment is used. func NewFromEnv(env Env, opts ...Option) *Workflow { if env == nil { env = sysEnv{} } if err := validateEnv(env); err != nil { panic(err) } wf := &Workflow{ Config: NewConfig(env), Alfred: NewAlfred(env), Feedback: &Feedback{}, logPrefix: DefaultLogPrefix, maxLogSize: DefaultMaxLogSize, maxResults: DefaultMaxResults, sessionName: DefaultSessionName, sortOptions: []fuzzy.Option{}, execFunc: runCommand, } wf.magicActions = &magicActions{ actions: map[string]MagicAction{}, wf: wf, } // default magic actions wf.Configure(AddMagic( logMA{wf}, cacheMA{wf}, clearCacheMA{wf}, dataMA{wf}, clearDataMA{wf}, resetMA{wf}, )) wf.Configure(opts...) wf.Cache = NewCache(wf.CacheDir()) wf.Data = NewCache(wf.DataDir()) wf.Session = NewSession(wf.CacheDir(), wf.SessionID()) wf.Keychain = keychain.New(wf.BundleID()) wf.initializeLogging() return wf } // -------------------------------------------------------------------- // Initialisation methods // Configure applies one or more Options to Workflow. The returned Option reverts // all Options passed to Configure. func (wf *Workflow) Configure(opts ...Option) (previous Option) { prev := make(options, len(opts)) for i, opt := range opts { prev[i] = opt(wf) } return prev.apply } // initializeLogging ensures future log messages are written to // workflow's log file. func (wf *Workflow) initializeLogging() { if logInitialized { // All Workflows use the same global logger return } // Rotate log file if larger than MaxLogSize fi, err := os.Stat(wf.LogFile()) if err == nil { if fi.Size() >= int64(wf.maxLogSize) { newlog := wf.LogFile() + ".1" if err := os.Rename(wf.LogFile(), newlog); err != nil { fmt.Fprintf(os.Stderr, "Error rotating log: %v\n", err) } fmt.Fprintln(os.Stderr, "Rotated log") } } // Open log file file, err := os.OpenFile(wf.LogFile(), os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0600) if err != nil { wf.Fatal(fmt.Sprintf("Couldn't open log file %s : %v", wf.LogFile(), err)) } // Attach logger to file multi := io.MultiWriter(file, os.Stderr) log.SetOutput(multi) // Show filenames and line numbers if Alfred's debugger is open if wf.Debug() { log.SetFlags(log.Ltime | log.Lshortfile) } else { log.SetFlags(log.Ltime) } logInitialized = true } // -------------------------------------------------------------------- // API methods // BundleID returns the workflow's bundle ID. This library will not // work without a bundle ID, which is set in the workflow's main // setup sheet in Alfred Preferences. func (wf *Workflow) BundleID() string { s := wf.Config.Get(EnvVarBundleID) if s == "" { wf.Fatal("No bundle ID set. You *must* set a bundle ID to use AwGo.") } return s } // Name returns the workflow's name as specified in the workflow's main // setup sheet in Alfred Preferences. func (wf *Workflow) Name() string { return wf.Config.Get(EnvVarName) } // Version returns the workflow's version set in the workflow's configuration // sheet in Alfred Preferences. func (wf *Workflow) Version() string { return wf.Config.Get(EnvVarVersion) } // SessionID returns the session ID for this run of the workflow. // This is used internally for session-scoped caching. // // The session ID is persisted as a workflow variable. It and the session // persist as long as the user is using the workflow in Alfred. That // means that the session expires as soon as Alfred closes or the user // runs a different workflow. func (wf *Workflow) SessionID() string { if wf.sessionID == "" { ev := os.Getenv(wf.sessionName) if ev != "" { wf.sessionID = ev } else { wf.sessionID = NewSessionID() } } return wf.sessionID } // Debug returns true if Alfred's debugger is open. func (wf *Workflow) Debug() bool { return wf.Config.GetBool(EnvVarDebug) } // Args returns command-line arguments passed to the program. // It intercepts "magic args" and runs the corresponding actions, terminating // the workflow. See MagicAction for full documentation. func (wf *Workflow) Args() []string { prefix := DefaultMagicPrefix if wf.magicPrefix != "" { prefix = wf.magicPrefix } return wf.magicActions.args(os.Args[1:], prefix) } // Run runs your workflow function, catching any errors. // If the workflow panics, Run rescues and displays an error message in Alfred. func (wf *Workflow) Run(fn func()) { vstr := wf.Name() if wf.Version() != "" { vstr += "/" + wf.Version() } vstr = fmt.Sprintf(" %s (AwGo/%v) ", vstr, AwGoVersion) // Print right after Alfred's introductory blurb in the debugger. // Alfred strips whitespace. if wf.logPrefix != "" { fmt.Fprintln(os.Stderr, wf.logPrefix) } log.Println(util.Pad(vstr, "-", 50)) // Clear expired session data wf.Add(1) go func() { defer wf.Done() if err := wf.Session.Clear(false); err != nil { log.Printf("[ERROR] clear session: %v", err) } }() // Catch any `panic` and display an error in Alfred. // Fatal(msg) will terminate the process (via log.Fatal). defer func() { if r := recover(); r != nil { log.Println(util.Pad(" FATAL ERROR ", "-", 50)) log.Printf("%s : %s", r, debug.Stack()) log.Println(util.Pad(" END STACK TRACE ", "-", 50)) // log.Printf("Recovered : %x", r) err, ok := r.(error) if ok { wf.outputErrorMsg(err.Error()) } wf.outputErrorMsg(fmt.Sprintf("%v", r)) } }() // Call the workflow's main function. fn() wf.Wait() finishLog(false) } // -------------------------------------------------------------------- // Helper methods // outputErrorMsg prints and logs error, then exits process. func (wf *Workflow) outputErrorMsg(msg string) { if wf.textErrors { fmt.Print(msg) } else { wf.Feedback.Clear() wf.NewItem(msg).Icon(IconError) wf.SendFeedback() } log.Printf("[ERROR] %s", msg) // Show help URL or website URL if wf.helpURL != "" { log.Printf("Get help at %s", wf.helpURL) } finishLog(true) } // awDataDir is the directory for AwGo's own data. func (wf *Workflow) awDataDir() string { return util.MustExist(filepath.Join(wf.DataDir(), "_aw")) } // awCacheDir is the directory for AwGo's own cache. func (wf *Workflow) awCacheDir() string { return util.MustExist(filepath.Join(wf.CacheDir(), "_aw")) } // -------------------------------------------------------------------- // Package-level only // finishLog outputs the workflow duration func finishLog(fatal bool) { s := util.Pad(fmt.Sprintf(" %v ", time.Since(startTime)), "-", 50) if fatal { log.Println(s) exitFunc(1) } else { log.Println(s) } }
28.485294
82
0.677078
33916bcf220eb5da8cb55de5a53cd204d816b842
893
swift
Swift
Sources/Jaeger/Jaeger/Models/JaegerLog.swift
pauljohanneskraft/jaeger-swift
7cbb81865822225188b1b987ed6d26993ea906e3
[ "BSD-2-Clause" ]
17
2018-10-23T15:21:19.000Z
2020-08-05T12:01:01.000Z
Sources/Jaeger/Jaeger/Models/JaegerLog.swift
pauljohanneskraft/jaeger-swift
7cbb81865822225188b1b987ed6d26993ea906e3
[ "BSD-2-Clause" ]
9
2018-12-12T18:24:03.000Z
2020-08-01T22:48:07.000Z
Sources/Jaeger/Jaeger/Models/JaegerLog.swift
pauljohanneskraft/jaeger-swift
7cbb81865822225188b1b987ed6d26993ea906e3
[ "BSD-2-Clause" ]
8
2019-05-07T07:55:28.000Z
2020-08-04T14:27:16.000Z
// // JaegerLog.swift // Jaeger // // Created by Simon-Pierre Roy on 10/29/18. // import Foundation /** The Jaeger version of an OpenTracing Log. See the [Jaeger.Thrift](https://github.com/jaegertracing/jaeger-idl/blob/master/thrift/jaeger.thrift) definition. */ struct JaegerLog: Codable { /** Creates a Jaeger Log from an OpenTracing Log. - Parameter log: An OpenTracing Log. */ init(log: Log) { // usually unsafe, but it is OK when the timeIntervalSince1970 is expressed in microseconds, since this number will be smaller than Int64.max. timestamp = Int64(log.timestamp.timeIntervalSince1970.microseconds) fields = log.fields.map { JaegerTag(tag: $0) } } /// The time at which the event occurred with Unix time in microseconds. let timestamp: Int64 /// An arbitrary set of tags. let fields: [JaegerTag] }
27.060606
150
0.678611
64ee2dfa3e513e10fe5bd50d86f4148dd09a08fc
4,975
rs
Rust
src/app.rs
brunograssano/Conways-Game-of-Life
a4252e0f7abc37f41ab5c1127fc21680067f4380
[ "MIT" ]
null
null
null
src/app.rs
brunograssano/Conways-Game-of-Life
a4252e0f7abc37f41ab5c1127fc21680067f4380
[ "MIT" ]
null
null
null
src/app.rs
brunograssano/Conways-Game-of-Life
a4252e0f7abc37f41ab5c1127fc21680067f4380
[ "MIT" ]
null
null
null
use crate::board::Board; extern crate piston_window; use piston::input::{RenderEvent, UpdateEvent}; use piston_window::*; const MIN_SCALE_FACTOR : f64 = 6.0; const MAX_SCALE_FACTOR : f64 = 60.0; const WIDTH: u32 = 600; const HEIGHT: u32 = 600; const PADDING: f64 = 1.0; const NO_PADDING: f64 = 0.0; #[derive(Copy, Clone)] struct Offset{ x:i32, y:i32 } pub struct App{ padding : f64, start : bool, board : Board, scale_factor : f64, window_offset : Offset, window : PistonWindow, } impl App{ pub fn new(random_start:bool,colorful_game:bool,padding:bool)->App{ App{ padding : if padding {PADDING} else {NO_PADDING}, start : false, board : Board::new(random_start,colorful_game), scale_factor : 6.0, window_offset : Offset{ x: 0, y: 0 }, window: WindowSettings::new("Conway's Game of Life!", [WIDTH, HEIGHT]) .exit_on_esc(true).resizable(false).build().unwrap(), } } fn draw(&mut self,event:Event) { let scale_factor = self.scale_factor; let window_offset = self.window_offset; let padding = self.padding; let background_color = [1.0; 4]; let cells = self.board.get_cells(); self.window.draw_2d(&event, |context, graphics, _device| { clear(background_color, graphics); for i in 0..100 { for j in 0..100 { if cells[i][j].is_alive() { let color: [f32; 4] = cells[i][j].get_color(); let position: [f64; 4] = [scale_factor * (cells[i][j].get_x() + window_offset.x) as f64, scale_factor * (cells[i][j].get_y() + window_offset.y) as f64, scale_factor - padding, scale_factor - padding]; rectangle(color, position, context.transform, graphics); } } } }); } pub fn game_loop(&mut self) { let mut mouse_pos = (0.0, 0.0); let mut events = Events::new(EventSettings::new()); while let Some(e) = events.next(&mut self.window) { if let Some(_r) = e.render_args() { self.draw(e); } else if let Some(_u) = e.update_args() { if self.start { self.board.update_board(); } } else if let Some(button) = e.press_args() { self.manage_buttons(&mut mouse_pos, button); } else if let Some(cursor) = e.mouse_cursor_args() { mouse_pos = (cursor[0], cursor[1]); } else if let Some(s) = e.mouse_scroll_args() { self.manage_zoom(s); } } } fn manage_buttons(&mut self, mouse_pos: &mut (f64, f64), button: Button) { match button { Button::Mouse(_button) => { let (x, y) = mouse_pos; self.board.toggle_cell(((*x / self.scale_factor) as i32 - self.window_offset.x) as usize, ((*y / self.scale_factor) as i32 - self.window_offset.y) as usize); } Button::Keyboard(button) => { if button == Key::P { self.start = false; } else if button == Key::Return { self.start = true; } else if button == Key::Left { if self.window_offset.x < 0 { self.window_offset.x += 1; } } else if button == Key::Right { if (WIDTH as i32 / self.scale_factor as i32) < 100 && -self.window_offset.x < 100 - (WIDTH as i32 / self.scale_factor as i32) { self.window_offset.x -= 1; } } else if button == Key::Up { if self.window_offset.y < 0 { self.window_offset.y += 1; } } else if button == Key::Down { if (HEIGHT as i32 / self.scale_factor as i32) < 100 && -self.window_offset.y < 100 - (HEIGHT as i32 / self.scale_factor as i32) { self.window_offset.y -= 1; } } else if button == Key::R { self.start = false; self.board.restart(); } } _ => {} } } fn manage_zoom(&mut self, s: [f64; 2]) { self.scale_factor += s[1]; if self.scale_factor < MIN_SCALE_FACTOR { self.scale_factor = MIN_SCALE_FACTOR; self.window_offset.x = 0; self.window_offset.y = 0; } else if self.scale_factor > MAX_SCALE_FACTOR{ self.scale_factor = MAX_SCALE_FACTOR; } } }
37.126866
149
0.483417
9bd4556ec7d925f606c58a1b5d94478c37467392
1,730
js
JavaScript
src/components/Tinymce/src/helper.js
Shallower/mbs
c09d7252a39a3cbc72f23e13f6606b330e164eb0
[ "MIT" ]
null
null
null
src/components/Tinymce/src/helper.js
Shallower/mbs
c09d7252a39a3cbc72f23e13f6606b330e164eb0
[ "MIT" ]
null
null
null
src/components/Tinymce/src/helper.js
Shallower/mbs
c09d7252a39a3cbc72f23e13f6606b330e164eb0
[ "MIT" ]
null
null
null
const validEvents = [ 'onActivate', 'onAddUndo', 'onBeforeAddUndo', 'onBeforeExecCommand', 'onBeforeGetContent', 'onBeforeRenderUI', 'onBeforeSetContent', 'onBeforePaste', 'onBlur', 'onChange', 'onClearUndos', 'onClick', 'onContextMenu', 'onCopy', 'onCut', 'onDblclick', 'onDeactivate', 'onDirty', 'onDrag', 'onDragDrop', 'onDragEnd', 'onDragGesture', 'onDragOver', 'onDrop', 'onExecCommand', 'onFocus', 'onFocusIn', 'onFocusOut', 'onGetContent', 'onHide', 'onInit', 'onKeyDown', 'onKeyPress', 'onKeyUp', 'onLoadContent', 'onMouseDown', 'onMouseEnter', 'onMouseLeave', 'onMouseMove', 'onMouseOut', 'onMouseOver', 'onMouseUp', 'onNodeChange', 'onObjectResizeStart', 'onObjectResized', 'onObjectSelected', 'onPaste', 'onPostProcess', 'onPostRender', 'onPreProcess', 'onProgressState', 'onRedo', 'onRemove', 'onReset', 'onSaveContent', 'onSelectionChange', 'onSetAttrib', 'onSetContent', 'onShow', 'onSubmit', 'onUndo', 'onVisualAid', ]; const isValidKey = (key) => validEvents.indexOf(key) !== -1; export const bindHandlers = (initEvent, listeners, editor) => { Object.keys(listeners) .filter(isValidKey) .forEach((key) => { const handler = listeners[key]; if (typeof handler === 'function') { if (key === 'onInit') { handler(initEvent, editor); } else { editor.on(key.substring(2), (e) => handler(e, editor)); } } }); }; //# sourceMappingURL=helper.js.map
21.358025
71
0.553179
50c85a7f436247ee3153403efcf0cbd8f6f05c1c
451
go
Go
hardware/gpio-switch.go
MarkSaravi/drone2
d52a0471f63d3cb54e2faaa140a78f1dcdf0e5d0
[ "MIT" ]
1
2021-09-06T23:22:24.000Z
2021-09-06T23:22:24.000Z
hardware/gpio-switch.go
MarkSaravi/drone2
d52a0471f63d3cb54e2faaa140a78f1dcdf0e5d0
[ "MIT" ]
null
null
null
hardware/gpio-switch.go
MarkSaravi/drone2
d52a0471f63d3cb54e2faaa140a78f1dcdf0e5d0
[ "MIT" ]
null
null
null
package hardware import ( "log" "periph.io/x/periph/conn/gpio" "periph.io/x/periph/conn/gpio/gpioreg" ) type gpioswitch struct { pin gpio.PinIn } func (b *gpioswitch) Read() bool { return b.pin.Read() == gpio.Low } func NewGPIOSwitch(pinName string) *gpioswitch { var pin gpio.PinIn = gpioreg.ByName(pinName) if pin == nil { log.Fatal("Failed to find ", pinName) } pin.In(gpio.Float, gpio.NoEdge) return &gpioswitch{ pin: pin, } }
16.107143
48
0.685144
07ff2609c6e77b2504f7de1777d74b4b49fece4c
554
c
C
C/StandaloneExercises/Concatenation.c
TacPhoto/Learning
28fb3c6469164c57d0ccb973732168f01b685113
[ "MIT" ]
null
null
null
C/StandaloneExercises/Concatenation.c
TacPhoto/Learning
28fb3c6469164c57d0ccb973732168f01b685113
[ "MIT" ]
null
null
null
C/StandaloneExercises/Concatenation.c
TacPhoto/Learning
28fb3c6469164c57d0ccb973732168f01b685113
[ "MIT" ]
null
null
null
#include <stdio.h> #include <stdio.h> #define endl puts("") //don't laugh at me, I have never used strcat befor (or I have forgotten) int main() { char someText[256]="What's"; char anotherText[]="up?"; puts(someText); puts (anotherText); endl; strcat(someText," "); //please note this usage of strcat does not protect your code from overflow. I'm writting this code only to memorize strcat syntax strcat(someText, anotherText); puts("Let's see how it looks after concatenation"); endl; puts(someText); puts(anotherText); return 0; }
23.083333
153
0.703971
4605109b9c78b5f99b3471d6b66cbee030d898a8
75
sql
SQL
indicator/test/aroon_test.sql
modfin/tap
173440dc28778f9d216d85804e511b6bf6600518
[ "MIT" ]
26
2018-12-14T12:31:47.000Z
2022-01-16T22:09:01.000Z
indicator/test/aroon_test.sql
modfin/tap
173440dc28778f9d216d85804e511b6bf6600518
[ "MIT" ]
null
null
null
indicator/test/aroon_test.sql
modfin/tap
173440dc28778f9d216d85804e511b6bf6600518
[ "MIT" ]
1
2021-02-05T20:00:33.000Z
2021-02-05T20:00:33.000Z
SELECT * FROM tap_aroon(20, 0, '2017-12-31'::DATE-30, '2017-12-31'::DATE);
37.5
74
0.64
27bd49f2d6c95bb636d424eed587c4451258e276
6,758
css
CSS
resources/SitePageCopies/Ongoing Gender Partisanship in the Department of Education/frontend-pro.css
citemap/citemap.github.io
888a080dde2b5c925f4f92c8ac71a7d9fb696cc2
[ "MIT" ]
null
null
null
resources/SitePageCopies/Ongoing Gender Partisanship in the Department of Education/frontend-pro.css
citemap/citemap.github.io
888a080dde2b5c925f4f92c8ac71a7d9fb696cc2
[ "MIT" ]
null
null
null
resources/SitePageCopies/Ongoing Gender Partisanship in the Department of Education/frontend-pro.css
citemap/citemap.github.io
888a080dde2b5c925f4f92c8ac71a7d9fb696cc2
[ "MIT" ]
null
null
null
.ig_has_alt_cta .ig_cta_wrapper{padding:1em .5em;width:96%;margin:.5em auto;text-align:center}.ig_has_alt_cta .ig_cta_wrapper .ig_cta_alt,.ig_has_alt_cta .ig_cta_wrapper .ig_cta_alt:hover{font-size:1em;width:100%;text-align:center;display:block;text-decoration:underline;padding:.5em;color:inherit;opacity:.7;cursor:pointer}.ig_has_alt_cta .ig_cta_wrapper .ig_cta_alt:hover{text-decoration:none;color:inherit;opacity:.6}.ig_has_alt_cta .ig_cta_wrapper .ig_button{float:unset;margin-bottom:0}.ig_has_alt_cta .ig_cta_alt_button .ig_button,.ig_has_alt_cta .ig_cta_alt_button .ig_cta_alt,.ig_has_alt_cta .ig_cta_alt_button .ig_cta_alt:hover{font-size:inherit;width:47%;margin:0 0 0 2%;float:left;padding:.5em;text-align:center;display:block;cursor:pointer;text-decoration:none;box-sizing:border-box;height:100%;line-height:1.5}.ig_has_alt_cta .ig_cta_alt_button .ig_cta_alt{color:#666;background-color:#eee;box-shadow:inset 0 0 0 2px rgba(0,0,0,.2);padding:.5em}.ig_has_alt_cta .ig_cta_alt_button .ig_cta_alt:hover{color:#666;box-shadow:inset 0 0 0 2px rgba(0,0,0,.4)}.ig_has_alt_cta .ig_form_container .ig_cta_wrapper{padding:inherit;margin-top:0;margin-bottom:0;display:inline-block;width:100%}.ig_has_alt_cta .ig_form_container .ig_cta_alt,.ig_has_alt_cta .ig_form_container .ig_cta_alt:hover{font-size:.9em;padding:.5em 0}.ig_has_alt_cta .ig_form_container .ig_cta_alt_button .ig_button,.ig_has_alt_cta .ig_form_container .ig_cta_alt_button .ig_cta_alt,.ig_has_alt_cta .ig_form_container .ig_cta_alt_button .ig_cta_alt:hover{margin:0 auto;width:100%}.ig_has_alt_cta.ig_action_bar .ig_cta_wrapper{display:inline-block;vertical-align:top}.ig_has_alt_cta.ig_action_bar .ig_cta_alt_button{padding:.5em;bottom:0}.ig_has_alt_cta.ig_action_bar.ig_curved .ig_cta_wrapper,.ig_has_alt_cta.ig_action_bar.ig_hello .ig_cta_wrapper,.ig_has_alt_cta.ig_action_bar.ig_highlight .ig_cta_wrapper,.ig_has_alt_cta.ig_action_bar.ig_horizon .ig_cta_wrapper,.ig_has_alt_cta.ig_action_bar.ig_polka .ig_cta_wrapper,.ig_has_alt_cta.ig_action_bar.ig_prism .ig_cta_wrapper,.ig_has_alt_cta.ig_action_bar.ig_smooth .ig_cta_wrapper,.ig_has_alt_cta.ig_action_bar.ig_stone .ig_cta_wrapper{float:none}.ig_has_alt_cta.ig_action_bar .ig_cta_alt_button .ig_button,.ig_has_alt_cta.ig_action_bar .ig_cta_alt_button .ig_cta_alt{position:relative;width:99%;margin:0 0 .5em;float:left}@media only screen and (max-width:768px){.ig_has_alt_cta.ig_action_bar .ig_cta_wrapper{float:left;text-align:left;margin-left:.7em;padding-bottom:0}.ig_has_alt_cta.ig_action_bar.ig_curved .ig_cta_wrapper,.ig_has_alt_cta.ig_action_bar.ig_hello .ig_cta_wrapper,.ig_has_alt_cta.ig_action_bar.ig_highlight .ig_cta_wrapper,.ig_has_alt_cta.ig_action_bar.ig_horizon .ig_cta_wrapper,.ig_has_alt_cta.ig_action_bar.ig_polka .ig_cta_wrapper,.ig_has_alt_cta.ig_action_bar.ig_prism .ig_cta_wrapper,.ig_has_alt_cta.ig_action_bar.ig_smooth .ig_cta_wrapper,.ig_has_alt_cta.ig_action_bar.ig_stone .ig_cta_wrapper{text-align:center}.ig_has_alt_cta.ig_action_bar.ig_has_pwby .ig_cta_wrapper{margin-left:2.5em}.ig_has_alt_cta.ig_action_bar .ig_cta_wrapper .ig_cta_alt{position:relative}}.ig_has_alt_cta.ig_popup.ig_convert .ig_cta_alt_button .ig_cta_alt,.ig_has_alt_cta.ig_popup.ig_express .ig_cta_alt_button .ig_cta_alt{border-radius:2em}.ig_has_alt_cta.ig_popup.ig_pattern .ig_cta_alt_button .ig_button,.ig_has_alt_cta.ig_popup.ig_pattern .ig_cta_alt_button .ig_cta_alt,.ig_has_alt_cta.ig_popup.ig_persuade .ig_cta_alt_button .ig_button,.ig_has_alt_cta.ig_popup.ig_persuade .ig_cta_alt_button .ig_cta_alt{border-radius:.4em}.ig_has_alt_cta.ig_popup.ig_convert .ig_cta_alt_button .ig_button{border:0!important;box-shadow:inset 0 0 0 .2em rgba(0,0,0,.2)}@media only screen and (max-width:850px){.ig_has_alt_cta.ig_popup .ig_cta_alt_button .ig_button,.ig_has_alt_cta.ig_popup .ig_cta_alt_button .ig_cta_alt{width:70%!important;float:none;margin:0 auto}.ig_has_alt_cta.ig_popup .ig_cta_alt_button .ig_cta_alt{margin-top:.5em}}@media only screen and (max-width:644px){.ig_has_alt_cta.ig_popup .ig_cta_alt_button .ig_button,.ig_has_alt_cta.ig_popup .ig_cta_alt_button .ig_cta_alt{width:60%!important}}@media only screen and (max-width:425px){.ig_has_alt_cta.ig_popup .ig_cta_alt_button .ig_button,.ig_has_alt_cta.ig_popup .ig_cta_alt_button .ig_cta_alt{width:80%!important}}@media only screen and (max-width:375px){.ig_has_alt_cta.ig_popup .ig_cta_alt_button .ig_button,.ig_has_alt_cta.ig_popup .ig_cta_alt_button .ig_cta_alt{width:90%!important}}@media only screen and (max-width:644px){.ig_has_alt_cta.ig_inline .ig_cta_alt_button .ig_button,.ig_has_alt_cta.ig_inline .ig_cta_alt_button .ig_cta_alt{float:none;margin:0 auto;width:70%}.ig_has_alt_cta.ig_inline .ig_cta_alt_button .ig_cta_alt{margin-top:.5em}}@media only screen and (max-width:425px){.ig_has_alt_cta.ig_inline .ig_cta_alt_button .ig_button,.ig_has_alt_cta.ig_inline .ig_cta_alt_button .ig_cta_alt{width:90%}}.ig_has_alt_cta.ig_inline .ig_cta_wrapper{padding:1em 0 0}@media only screen and (max-width:768px){.ig_has_alt_cta.ig_interstitial .ig_cta_alt_button .ig_button,.ig_has_alt_cta.ig_interstitial .ig_cta_alt_button .ig_cta_alt{width:60%;float:none;margin:0 auto}.ig_has_alt_cta.ig_interstitial .ig_cta_alt_button .ig_cta_alt{margin-top:.5em}}@media only screen and (max-width:644px){.ig_has_alt_cta.ig_interstitial .ig_cta_alt_button .ig_button,.ig_has_alt_cta.ig_interstitial .ig_cta_alt_button .ig_cta_alt{width:90%}}.ig_sidebar .ig_has_alt_cta .ig_cta_alt_button .ig_button,.ig_sidebar .ig_has_alt_cta .ig_cta_alt_button .ig_cta_alt{width:100%;margin:0 auto .8em}.ig_has_alt_cta.ig_overlay.ig_bold .ig_cta_alt_button .ig_button,.ig_has_alt_cta.ig_overlay.ig_bold .ig_cta_alt_button .ig_cta_alt{padding:1.3em 1em;font-size:2em}@media only screen and (max-width:850px){.ig_has_alt_cta.ig_overlay.ig_stack .ig_cta_alt_button .ig_button,.ig_has_alt_cta.ig_overlay.ig_stack .ig_cta_alt_button .ig_cta_alt{float:none;margin:0 auto;width:80%}.ig_has_alt_cta.ig_overlay.ig_stack .ig_cta_alt_button .ig_cta_alt{margin-top:.5em}}@media only screen and (max-width:644px){.ig_has_alt_cta.ig_overlay .ig_cta_alt_button .ig_button,.ig_has_alt_cta.ig_overlay .ig_cta_alt_button .ig_cta_alt{float:none;margin:0 auto;width:70%}.ig_has_alt_cta.ig_overlay .ig_cta_alt_button .ig_cta_alt{margin-top:.5em}.ig_has_alt_cta.ig_overlay.ig_stack .ig_cta_alt_button .ig_button,.ig_has_alt_cta.ig_overlay.ig_stack .ig_cta_alt_button .ig_cta_alt{width:100%}.ig_has_alt_cta.ig_overlay.ig_bold .ig_cta_alt_button .ig_button{margin-bottom:4.5em}.ig_has_alt_cta.ig_overlay.ig_bold .ig_cta_alt_button .ig_cta_alt{margin-top:-3.5em}}@media only screen and (max-width:425px){.ig_has_alt_cta.ig_overlay .ig_cta_alt_button .ig_button,.ig_has_alt_cta.ig_overlay .ig_cta_alt_button .ig_cta_alt{width:90%}}
6,758
6,758
0.846848
5ca0004cf887cb3a5a880dc492c4e0be56bc567c
11,415
css
CSS
assets/front/css/responsive.css
ufairiya/fixmycar
a18ab4b2798b171973d2a2f0535709ac0a284279
[ "MIT" ]
null
null
null
assets/front/css/responsive.css
ufairiya/fixmycar
a18ab4b2798b171973d2a2f0535709ac0a284279
[ "MIT" ]
null
null
null
assets/front/css/responsive.css
ufairiya/fixmycar
a18ab4b2798b171973d2a2f0535709ac0a284279
[ "MIT" ]
null
null
null
/*css for header area*/ @media (max-width: 1024px) { .footer-top { padding: 0px 15px 65px; } .footer-mid { padding: 0px 15px 83px; } .ftr-email-form button { right: -61%; } } @media (max-width: 768px) { .about section.banner>img { display: none; } section.banner {} .about section.banner { word-wrap: break-word; overflow-wrap: break-word; } .about .inner-div { margin-bottom: 30px; } .featured-single-box { -webkit-box-orient: vertical; -webkit-box-direction: normal; -ms-flex-direction: column; flex-direction: column; text-align: center; margin-bottom: 75px; } .featured-single-box .icon { margin-right: 0; margin-bottom: 30px; } .featured-text h2 { font-size: 43px; } .featured-text p { font-size: 20px; line-height: 30px; } .featured-single-box.alter .icon { -webkit-box-ordinal-group: 0; -ms-flex-order: -1; order: -1; margin: 0; margin-bottom: 20px; } .button-div.text-center button { margin-bottom: 62px; } .footer .row {} .row.align-items-end p { margin-bottom: 20px; text-align: center; } p.ftr-btns {} .social-icon.text-sm-right.text-center.pb-2 { text-align: center !important; /* align-items: center; */ } .footer-logo.pb-2 { text-align: center !important; margin-bottom: 20px; } .footer-top { padding-bottom: 30px; } .footer-mid { padding-bottom: 38px; } img.indicator { display: none; } .section-padding { padding: 50px 0px; } .row { margin: 0; } .item-inner.text-center h4 { padding: 0px 57px; line-height: 28px; } .subscription form { -webkit-box-pack: center; -ms-flex-pack: center; justify-content: center; } .subscription form div { -ms-flex-preferred-size: 320px; flex-basis: 320px; } .subscription form div:first-child { padding-right: 20px; } .footer-top { padding: 0px 15px 65px; } .footer-mid-left { -webkit-box-pack: center; -ms-flex-pack: center; justify-content: center; } .footer-mid-left .footer-single-box { text-align: center; } .ftr-email-form button { right: -72% !important; } .footer-mid-right { width: 44%; margin: 0 auto; } .footer-mid-right h3 { text-align: center; } .phone-no, .envelope { -webkit-box-pack: center; -ms-flex-pack: center; justify-content: center; } .copyright { text-align: center; } .workflow-box-inner { padding: 56px 20px 19px 30px; min-height: 250px; } .content-inner { margin-bottom: 30px; } .about .banner { min-height: 500px; background-size: cover; background-color: #ffffff; background-repeat: no-repeat; background-image: url(../images/about/About_banner.png); } footer .row.align-items-end { -webkit-box-orient: vertical; -webkit-box-direction: normal; -ms-flex-direction: column; flex-direction: column; width: 100%; -webkit-box-pack: center; -ms-flex-pack: center; justify-content: center; -ms-flex-preferred-size: 100%; flex-basis: 100%; -webkit-box-align: center !important; -ms-flex-align: center !important; -ms-grid-row-align: center !important; align-items: center !important; -ms-flex-wrap: nowrap; flex-wrap: nowrap; } .contact .banner { background-image: url(../images/contact/banner.png); } .booking-page .banner { background-image: url(../images/about/booking-banner.png); } .about.faq .banner { background-image: url(../images/faq/faq.png); } .about.gift .banner { background-image: url(../images/giftcard/gift_banner.png); } .contact .banner>img, .booking-page .banner>img, .about.faq .banner>img, .about.gift .banner>img { display: none; } .contact .banner, .booking-page .banner, .about.faq .banner, .about.gift .banner { min-height: 500px; background-size: cover; background-color: #ffffff; background-repeat: no-repeat; } .send-it button { margin: 0; } .booking-step-sc.text-left button { width: 48%; margin-bottom: 30px; } .phone-no img { width: 25px; height: 25px; } } @media (max-width: 576px) { .faq-banner-from input[type="search"] { width: 100%; padding: 15px 16px; } form.faq-banner-from { width: 72%; } .faq-banner-from button[type="submit"] { padding: 7px 42px; } .booking-inner form {} .booking-inner form { width: 100%; } .booking-sidebar { width: 100%; } .booking-inner { -ms-flex-wrap: wrap; flex-wrap: wrap; } .contact .banner .content>p { font-size: 45px; line-height: 60px; } .send-it button { font-size: 16px; } .send-it p { width: 50%; } .title-count { margin-bottom: 10px; } .about .banner-inner { text-align: center; } .about .content>p { font-size: 40px; margin-bottom: 0px; } .about-list { padding: 20px; text-align: left; } .criteria-box { margin-bottom: 30px; } .workflow-box-inner { /* padding: 56px 20px 19px 30px;*/ min-height: auto; } .slider-area { padding: 227px 0px 105px; } .rating { position: static; padding: 0px 15px; margin-bottom: 30px; } .rating p { font-size: 14px; } .banner .indicator { width: auto; position: absolute; right: 0; top: 67%; -webkit-transform: translateY(-50%); transform: translateY(-50%); } .content.nav { -webkit-box-pack: center; -ms-flex-pack: center; justify-content: center; } .logo { -webkit-box-ordinal-group: 0; -ms-flex-order: -1; order: -1; width: 100%; padding-bottom: 10px; -webkit-box-pack: center !important; -ms-flex-pack: center !important; justify-content: center !important; } .single-slider .slider-title { font-size: 28px; line-height: 1.3; padding-left: 15px; padding-right: 15px; } .single-slider .sub-title { font-size: 23px; line-height: 1.3; } .bedrooms, .bathrooms { -webkit-box-pack: center; -ms-flex-pack: center; justify-content: center; padding-left: 15px; padding-right: 15px; } .continue-btn input { margin-bottom: 0; } .choice-form button { width: 290px; } .slider-4 .slider-title, .slider-4 .slider-title, .slider-2 .slider-title { margin-bottom: 25px; } .choice-form { padding-bottom: 20px; } .form-title p { font-size: 30px; line-height: 1.3; } .criteria-box { width: 100%; } .app-store { width: 93%; text-align: center; margin-top: 50px; margin-left: 0; } .app-store h2:after { left: 50%; -webkit-transform: translateX(-50%); transform: translateX(-50%); } .subscription form { padding: 0px 15px; } .subscription form div:first-child { padding-right: 0; } .footer-logo { margin-bottom: 30px; } .social-icon a:first-child { padding-left: 0; } .footer-mid-right { width: 80%; } .footer-mid-left .footer-single-box { -ms-flex-preferred-size: 395px; flex-basis: 395px; } .ftr-btns { -webkit-box-pack: center; -ms-flex-pack: center; justify-content: center; } .copyright { padding: 0px 15px 15px; } } @media (max-width: 425px) { .banner-inner.text-center { padding: 10px; } .contact .banner .content>p { font-size: 34px; line-height: 45px; } .contact .banner { background-position: top right; } p.head { font-size: 18px; } .send-it p { width: 100%; margin-bottom: 10px; } .send-it button {} .send-it { -webkit-box-orient: vertical; -webkit-box-direction: normal; -ms-flex-direction: column; flex-direction: column; text-align: center; } .contact-box-content input { width: 100%; } .ftr-email-form button { right: -70% !important; } .customer h2 { font-size: 30px; } .featured-text h2 { font-size: 33px; } .featured-text p { font-size: 17px; line-height: 25px; } .featured-single-box { padding: 15px; } } @media (max-width: 375px) { .ftr-email-form button { right: -66% !important; } } @media (max-width: 320px) { .ftr-email-form button { right: -62% !important; } } /* ===================responsive code for faq page =========================*/ @media (max-width: 768px) { .faq-area .row{ padding: 0 15px; } } @media (max-width: 576px) { .faq-content { flex-direction: column; } .faq-single-box { width: 100%; padding-bottom: 30px; } } /* ============= responsive code for giftcard page */ @media (max-width: 768px) { .giftcard-header, .checkout-header { flex-direction: column; } .giftcard-header h5, .checkout-header h5 { width: 100%; margin-bottom: 15px; } .giftcard-header .bar, .checkout-header .bar { width: 100%; } .gift-info { flex-direction: column; } .gift-form { width: 100%; } .gift-form .form-group { padding-bottom: 15px; } .gift-card { max-width: 80%; margin: 50px auto 0; } .check-img { justify-content: center; } } @media (max-width: 576px) { .gift-data label { text-align: left; } .gift-card { max-width: 97%; } select.first-select { margin-bottom: 15px; } }
22.921687
81
0.487078
570623b1a818d1c059755387e29e453c1f742557
6,964
swift
Swift
MACTableViewSwift/MACTableView/MACTableView.swift
MacOMNI/MACTableView-Swift
f1ba731286a100095d4837680df6ba9bdfabb8a2
[ "MIT" ]
1
2021-04-26T06:11:33.000Z
2021-04-26T06:11:33.000Z
MACTableViewSwift/MACTableView/MACTableView.swift
MacOMNI/MACTableView-Swift
f1ba731286a100095d4837680df6ba9bdfabb8a2
[ "MIT" ]
null
null
null
MACTableViewSwift/MACTableView/MACTableView.swift
MacOMNI/MACTableView-Swift
f1ba731286a100095d4837680df6ba9bdfabb8a2
[ "MIT" ]
null
null
null
// // MACTableView.swift // MACTableViewSwift // // Created by MacKun on 2016/12/23. // Copyright © 2016年 com.soullon. All rights reserved. // import UIKit import MJRefresh import DZNEmptyDataSet enum MACRefreshState{ case refreshing /** 下拉刷新的状态 */ case pulling /** pull 加载更多刷新中的状态 */ } enum MACCanLoadState { case none /**不支持下拉和加载更多*/ case refresh /**只支持下拉刷新*/ case all /** 同时支持下拉和加载更多*/ } protocol MACTableViewDelegate:class { func loadDataRefreshOrPull(state:MACRefreshState) } class MACTableView: UITableView { @IBInspectable var showEmpty = true /** 是否展示空白页,默认展示*/ @IBInspectable var emptyTitle = "" /** 空白标题 默认为 "",不显示*/ @IBInspectable var emptySubTitle = "暂无数据" /** 空白页展位图名称 默认为 nil,不显示*/ @IBInspectable var emptyImage = UIImage.init() /** 空白页展位图名称 默认为 nil,不显示*/ @IBInspectable var emptyAttributedTitle:NSAttributedString? /** 空白自定义标题 默认不显示*/ @IBInspectable var emptyAttributedSubTitle:NSAttributedString? /** 空白自定义副标题 默认不显示*/ var emptyColor = UIColor.clear /** 空白页颜色 默认为 clear*/ var macCanLoadState = MACCanLoadState.all { didSet { switch macCanLoadState { case .all: self.setRefreshFooter() self.setRefreshHeader() break case .refresh: self.setRefreshHeader() self.mj_footer = nil break default: self.mj_footer = nil self.mj_header = nil break } } } weak open var macTableViewDelegate: MACTableViewDelegate? { didSet { self.delegate = macTableViewDelegate as? UITableViewDelegate self.dataSource = macTableViewDelegate as? UITableViewDataSource } } override init(frame: CGRect, style: UITableViewStyle){ super.init(frame: frame, style: style) initUI() } required init?(coder aDecoder: NSCoder){ super.init(coder: aDecoder); initUI() } convenience init(frame: CGRect) { self.init(frame:frame, style:UITableViewStyle.plain); } convenience init(){ self.init(frame:.zero,style:.plain) initUI() } func initUI(){ self.separatorStyle = UITableViewCellSeparatorStyle.none self.tableFooterView = UIView() self.backgroundColor = UIColor.groupTableViewBackground self.macCanLoadState = MACCanLoadState.all } func beginLoading(){ self.mj_header.beginRefreshing { if self.showEmpty { self.emptyDataSetSource = self self.emptyDataSetDelegate = self } } } func endLoading(){ if self.mj_header.isRefreshing() { self.mj_header.endRefreshing() self.mj_header.endRefreshing(completionBlock: { self.mac_reloadData() }); } if self.mj_footer.isRefreshing() { self.mj_footer.endRefreshing(completionBlock: { self.mac_reloadData() }); } } //MARK:private methods func setRefreshHeader(){ if MACRefreshGifHeader.className.isEmpty { self.mj_header = MJRefreshNormalHeader (refreshingBlock: { self.refreshData() }); }else { let gifHeader = NSClassFromString(MACRefreshGifHeader.className) as! MJRefreshGifHeader.Type let header = gifHeader.init() header.setRefreshingTarget(self, refreshingAction: #selector(refreshData)) self.mj_header = header } self.mj_header.isMultipleTouchEnabled = false } func setRefreshFooter(){ self.mj_footer = MJRefreshAutoNormalFooter (refreshingBlock: { self.pullData() }); self.mj_footer.isMultipleTouchEnabled = false } func mac_reloadData(){ self.reloadData() if self.macCanLoadState == .all && self.isEmptyTableView() { self.mj_footer.isHidden = true } else if self.macCanLoadState == .all { self.mj_footer.isHidden = false } } func refreshData() { self.macTableViewDelegate?.loadDataRefreshOrPull(state: .refreshing) } func pullData(){ self.macTableViewDelegate?.loadDataRefreshOrPull(state: .pulling) } func isEmptyTableView() -> Bool { //FIXME:待完善 let src = self.dataSource var sections = 1 if (src != nil) && (src?.responds(to: #selector(getter: self.numberOfSections)))! { sections = (src?.numberOfSections!(in: self))! } if sections > 1 { return false } for index in 0..<sections { let rows = src?.tableView(self, numberOfRowsInSection: index) if rows!>0 { return false } } return true } } //MARK:代理方法 extension MACTableView : DZNEmptyDataSetSource,DZNEmptyDataSetDelegate{ func title(forEmptyDataSet scrollView: UIScrollView!) -> NSAttributedString! { let text = self.emptyTitle.lengthOfBytes(using: String.Encoding.utf8)>0 ? self.emptyTitle : "" let attributes = [NSFontAttributeName:UIFont.systemFont(ofSize: 18), NSForegroundColorAttributeName:UIColor.darkGray] return NSAttributedString.init(string: text, attributes: attributes) } func image(forEmptyDataSet scrollView: UIScrollView!) -> UIImage! { return self.emptyImage } func backgroundColor(forEmptyDataSet scrollView: UIScrollView!) -> UIColor! { return self.emptyColor } func verticalOffset(forEmptyDataSet scrollView: UIScrollView!) -> CGFloat { return -20.0 } func spaceHeight(forEmptyDataSet scrollView: UIScrollView!) -> CGFloat { return 0.0 } func emptyDataSetShouldDisplay(_ scrollView: UIScrollView!) -> Bool { return true } func emptyDataSet(_ scrollView: UIScrollView!, didTap view: UIView!) { self .beginLoading() } func emptyDataSetShouldAllowTouch(_ scrollView: UIScrollView!) -> Bool { return true } func emptyDataSetShouldAllowScroll(_ scrollView: UIScrollView!) -> Bool { return true } func imageAnimation(forEmptyDataSet scrollView: UIScrollView!) -> CAAnimation! { let animation = CABasicAnimation.init(keyPath: "transform") animation.fromValue = NSValue.init(caTransform3D: CATransform3DIdentity) animation.toValue = NSValue.init(caTransform3D: CATransform3DMakeRotation(CGFloat(M_PI_2), 0, 0, 1)) animation.duration = 0.25 animation.isCumulative = true animation.repeatCount = MAXFLOAT return animation } }
30.017241
108
0.606692