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
24f015f75bfc64d3c37965f8aaaca69fd88c59f0
1,586
kt
Kotlin
app/src/main/java/payment/sdk/android/demo/products/viewholder/ProductsViewHolder.kt
Mohmd-H-BH/payment-sdk-android
316d29a15cd95e79e7b71f875af4843af9620933
[ "MIT-0" ]
3
2020-07-11T17:25:07.000Z
2020-11-25T09:56:54.000Z
app/src/main/java/payment/sdk/android/demo/products/viewholder/ProductsViewHolder.kt
Mohmd-H-BH/payment-sdk-android
316d29a15cd95e79e7b71f875af4843af9620933
[ "MIT-0" ]
12
2019-11-27T15:58:05.000Z
2021-12-14T04:13:01.000Z
app/src/main/java/payment/sdk/android/demo/products/viewholder/ProductsViewHolder.kt
Mohmd-H-BH/payment-sdk-android
316d29a15cd95e79e7b71f875af4843af9620933
[ "MIT-0" ]
7
2019-12-04T07:43:49.000Z
2022-02-15T07:02:24.000Z
package payment.sdk.android.demo.products.viewholder import payment.sdk.android.R import payment.sdk.android.demo.dependency.formatter.Formatter import payment.sdk.android.demo.product_detail.ProductDetailActivity import payment.sdk.android.demo.products.data.ProductDomain import android.support.v7.widget.RecyclerView import android.view.View import android.widget.ImageView import android.widget.TextView import butterknife.BindView import butterknife.ButterKnife import butterknife.OnClick import com.bumptech.glide.Glide import java.util.* import javax.inject.Inject class ProductsViewHolder @Inject constructor( itemView: View, private val formatter: Formatter ) : RecyclerView.ViewHolder(itemView) { @BindView(R.id.basket_product_image) lateinit var productImageView: ImageView @BindView(R.id.basket_product_name) lateinit var productNameView: TextView @BindView(R.id.product_price) lateinit var productPriceView: TextView private lateinit var product: ProductDomain init { ButterKnife.bind(this, itemView) } fun bind(product: ProductDomain) { this.product = product productNameView.text = product.name productPriceView.text = formatter.formatAmount(product.prices[0].currency, product.prices[0].price, Locale.US) Glide.with(itemView.context).load(product.imageUrl).into(productImageView) } @OnClick(R.id.product) fun onProductClicked() { itemView.context.apply { startActivity(ProductDetailActivity.getIntent(this, product)) } } }
31.72
118
0.758512
5807fd10b82c781d0694bd3d706695c7f76b2701
380
h
C
derived.h
emaskovsky/examples-c-oop
ca44e204e120f2d5722b684fef7490521b5f5b8c
[ "Apache-2.0" ]
null
null
null
derived.h
emaskovsky/examples-c-oop
ca44e204e120f2d5722b684fef7490521b5f5b8c
[ "Apache-2.0" ]
null
null
null
derived.h
emaskovsky/examples-c-oop
ca44e204e120f2d5722b684fef7490521b5f5b8c
[ "Apache-2.0" ]
null
null
null
#ifndef DERIVED_H #define DERIVED_H #include "base.h" DECLARE_CLASS_BEGIN(Derived, Base) // the attributes int y; DECLARE_CLASS_END(Derived) DECLARE_CLASS_CONSTRUCTOR(Derived)(Derived *self, int x, int y); DECLARE_CLASS_VTABLE_BEGIN(Derived, Base) // the methods void (*setY)(void *, int); int (*getY)(void *); DECLARE_CLASS_VTABLE_END(Derived) #endif
16.521739
64
0.718421
1aca6b8fca54de5031757b90a95265742130df7a
3,673
rs
Rust
src/main.rs
UpsettingBoy/demangler-public
657fca289700e78baf8e1947226e80756656eccd
[ "Apache-2.0" ]
null
null
null
src/main.rs
UpsettingBoy/demangler-public
657fca289700e78baf8e1947226e80756656eccd
[ "Apache-2.0" ]
null
null
null
src/main.rs
UpsettingBoy/demangler-public
657fca289700e78baf8e1947226e80756656eccd
[ "Apache-2.0" ]
null
null
null
/* Copyright 2020 The University of Edinburgh 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. SPDX-License-Identifier: Apache-2.0 */ use std::error::Error; use structopt::StructOpt; mod filter; mod ompi; mod smt; #[derive(StructOpt)] #[structopt(author)] struct CliDemangle { #[structopt( name = "THREADS", required = true, help = "Intel-styled threads to demangle (no comma separated)." )] threads: Vec<u32>, } #[derive(StructOpt)] #[structopt(author)] struct CliGet { #[structopt(short = "t", long, help = "", possible_values = &filter::Thread::variants(), case_insensitive = true)] thread_rank: Option<filter::Thread>, #[structopt(short = "s", long, help = "", possible_values = &filter::Socket::variants(), case_insensitive = true)] socket: Option<filter::Socket>, #[structopt(short = "p", long, help = "", possible_values = &filter::CoreParity::variants(), case_insensitive = true)] parity: Option<filter::CoreParity>, } #[derive(StructOpt)] enum CliCommand { /// Demangle a set of Intel-styled threads. Demangle(CliDemangle), /// Display a set of demangled threads that satisfy certain condition(s). Get(CliGet), /// Reverse demangle. From a set of demangled Intel-styled threads, return the threads in which the program will be finally executed. Mangle(CliDemangle), } #[derive(StructOpt)] #[structopt(name = "dmglr", author, about)] struct CliInit { #[structopt(long, default_value = "4", help = "SMT configuration (2 or 4).")] smt: smt::SMT, #[structopt( short = "m", long = "mpi-program", default_value = "<program>", help = "Append 'program' to MPI recommended command." )] program: String, #[structopt(subcommand)] cmd: CliCommand, } fn main() -> Result<(), Box<dyn Error>> { let args: CliInit = CliInit::from_args(); match args.cmd { CliCommand::Demangle(dmg) => demangle_cmd(&args.smt, &args.program, dmg)?, CliCommand::Get(get) => get_cmd(&args.smt, &args.program, get)?, CliCommand::Mangle(mgl) => mangle_cmd(&args.smt, &args.program, mgl)?, } Ok(()) } fn demangle_cmd(smt: &smt::SMT, program: &str, dmg: CliDemangle) -> Result<(), Box<dyn Error>> { let mut output = Vec::with_capacity(dmg.threads.len()); for th in &dmg.threads { output.push(ompi::demangle(*th, smt)?); } output.sort(); ompi::show_cmd(&output, program); Ok(()) } fn mangle_cmd(smt: &smt::SMT, program: &str, dmg: CliDemangle) -> Result<(), Box<dyn Error>> { let mut output = Vec::with_capacity(dmg.threads.len()); for th in &dmg.threads { output.push(ompi::mangle(*th, smt)); } output.sort(); ompi::show_cmd(&output, program); Ok(()) } fn get_cmd(smt: &smt::SMT, program: &str, get: CliGet) -> Result<(), Box<dyn Error>> { let filter = filter::get_threads(smt, get.thread_rank, get.socket, get.parity)?; let mut output = Vec::with_capacity(filter.len()); for th in filter { output.push(ompi::demangle(th, smt)?); } output.sort(); ompi::show_cmd(&output, program); Ok(()) }
29.150794
137
0.646338
e8a9c43db3d689f8d0ea0574115329ffddff7570
317
lua
Lua
MMOCoreORB/bin/scripts/object/custom_content/tangible/event_perk/remembrance_day_player_resistance_sign.lua
V-Fib/FlurryClone
40e0ca7245ec31b3815eb6459329fd9e70f88936
[ "Zlib", "OpenSSL" ]
18
2017-02-09T15:36:05.000Z
2021-12-21T04:22:15.000Z
MMOCoreORB/bin/scripts/object/custom_content/tangible/event_perk/remembrance_day_player_resistance_sign.lua
V-Fib/FlurryClone
40e0ca7245ec31b3815eb6459329fd9e70f88936
[ "Zlib", "OpenSSL" ]
61
2016-12-30T21:51:10.000Z
2021-12-10T20:25:56.000Z
MMOCoreORB/bin/scripts/object/custom_content/tangible/event_perk/remembrance_day_player_resistance_sign.lua
V-Fib/FlurryClone
40e0ca7245ec31b3815eb6459329fd9e70f88936
[ "Zlib", "OpenSSL" ]
71
2017-01-01T05:34:38.000Z
2022-03-29T01:04:00.000Z
object_tangible_event_perk_remembrance_day_player_resistance_sign = object_tangible_event_perk_shared_remembrance_day_player_resistance_sign:new { } ObjectTemplates:addTemplate(object_tangible_event_perk_remembrance_day_player_resistance_sign, "object/tangible/event_perk/remembrance_day_player_resistance_sign.iff")
79.25
167
0.933754
bcb193b3b4236d3fef12de4acb2ffa3c86862c91
12,323
js
JavaScript
src/levels/totwc/areas/1/3/model.inc.js
koolaidbeems/koolaidbeems.github.io
68d5d29dd5b7c02646d8adfcf436badc7802e647
[ "WTFPL" ]
null
null
null
src/levels/totwc/areas/1/3/model.inc.js
koolaidbeems/koolaidbeems.github.io
68d5d29dd5b7c02646d8adfcf436badc7802e647
[ "WTFPL" ]
null
null
null
src/levels/totwc/areas/1/3/model.inc.js
koolaidbeems/koolaidbeems.github.io
68d5d29dd5b7c02646d8adfcf436badc7802e647
[ "WTFPL" ]
null
null
null
import * as Gbi from "../../../../../include/gbi" import { sky_09001000 } from "../../../../../textures/sky" import { totwc_seg7_texture_07001000 } from "../../../texture.inc" const totwc_seg7_vertex_070070C8 = [ { pos: [ 4506, -7679, 3686 ], flag: 0, tc: [ 990, 990 ], color: [ 254, 255, 203, 0 ] }, { pos: [ 3686, -7679, 3686 ], flag: 0, tc: [ 0, 990 ], color: [ 254, 255, 203, 0 ] }, { pos: [ 3686, -5119, 3686 ], flag: 0, tc: [ 0, -2204 ], color: [ 254, 255, 203, 255 ] }, { pos: [ 4506, -5119, 3686 ], flag: 0, tc: [ 990, -2204 ], color: [ 254, 255, 203, 255 ] }, { pos: [ 4506, -5119, -3685 ], flag: 0, tc: [ 990, -2204 ], color: [ 185, 208, 173, 255 ] }, { pos: [ 4506, -7679, -3685 ], flag: 0, tc: [ 990, 990 ], color: [ 185, 208, 173, 0 ] }, { pos: [ 4506, -5119, -4505 ], flag: 0, tc: [ 0, -2204 ], color: [ 185, 208, 173, 255 ] }, { pos: [ 4506, -7679, -4505 ], flag: 0, tc: [ 0, 990 ], color: [ 185, 208, 173, 0 ] }, { pos: [ 3686, -7679, -4505 ], flag: 0, tc: [ 0, 990 ], color: [ 185, 208, 173, 0 ] }, { pos: [ 3686, -7679, -3685 ], flag: 0, tc: [ 990, 990 ], color: [ 185, 208, 173, 0 ] }, { pos: [ 3686, -5119, -3685 ], flag: 0, tc: [ 990, -2204 ], color: [ 185, 208, 173, 255 ] }, { pos: [ 3686, -5119, -4505 ], flag: 0, tc: [ 0, -2204 ], color: [ 185, 208, 173, 255 ] }, { pos: [ -4505, -5119, 4506 ], flag: 0, tc: [ 990, -2204 ], color: [ 80, 134, 163, 255 ] }, { pos: [ -4505, -7679, 4506 ], flag: 0, tc: [ 990, 990 ], color: [ 80, 134, 163, 0 ] }, { pos: [ -3685, -7679, 4506 ], flag: 0, tc: [ 0, 990 ], color: [ 80, 134, 163, 0 ] }, { pos: [ -3685, -5119, 4506 ], flag: 0, tc: [ 0, -2204 ], color: [ 80, 134, 163, 255 ] }, ] const totwc_seg7_vertex_070071C8 = [ { pos: [ -3685, -5119, 4506 ], flag: 0, tc: [ 11210, -2204 ], color: [ 147, 206, 213, 255 ] }, { pos: [ -3685, -7679, 3686 ], flag: 0, tc: [ 10188, 990 ], color: [ 147, 206, 213, 0 ] }, { pos: [ -3685, -5119, 3686 ], flag: 0, tc: [ 10188, -2204 ], color: [ 147, 206, 213, 255 ] }, { pos: [ -3685, -7679, 4506 ], flag: 0, tc: [ 11210, 990 ], color: [ 147, 206, 213, 0 ] }, { pos: [ -4505, -5119, 3686 ], flag: 0, tc: [ 10188, -2204 ], color: [ 147, 206, 213, 255 ] }, { pos: [ -4505, -7679, 3686 ], flag: 0, tc: [ 10188, 990 ], color: [ 147, 206, 213, 0 ] }, { pos: [ -4505, -7679, 4506 ], flag: 0, tc: [ 11210, 990 ], color: [ 147, 206, 213, 0 ] }, { pos: [ -4505, -5119, 4506 ], flag: 0, tc: [ 11210, -2204 ], color: [ 147, 206, 213, 255 ] }, { pos: [ -3685, -5119, 3686 ], flag: 0, tc: [ 0, -2204 ], color: [ 197, 248, 255, 255 ] }, { pos: [ -4505, -7679, 3686 ], flag: 0, tc: [ 990, 990 ], color: [ 197, 248, 255, 0 ] }, { pos: [ -4505, -5119, 3686 ], flag: 0, tc: [ 990, -2204 ], color: [ 197, 248, 255, 255 ] }, { pos: [ -3685, -7679, 3686 ], flag: 0, tc: [ 0, 990 ], color: [ 197, 248, 255, 0 ] }, { pos: [ -3685, -7679, -4505 ], flag: 0, tc: [ -9228, 990 ], color: [ 193, 221, 255, 0 ] }, { pos: [ -4505, -7679, -4505 ], flag: 0, tc: [ -10250, 990 ], color: [ 193, 221, 255, 0 ] }, { pos: [ -4505, -5119, -4505 ], flag: 0, tc: [ -10250, -2204 ], color: [ 193, 221, 255, 255 ] }, { pos: [ -3685, -5119, -4505 ], flag: 0, tc: [ -9228, -2204 ], color: [ 193, 221, 255, 255 ] }, ] const totwc_seg7_vertex_070072C8 = [ { pos: [ 4506, -5119, -4505 ], flag: 0, tc: [ 990, -2204 ], color: [ 221, 255, 200, 255 ] }, { pos: [ 4506, -7679, -4505 ], flag: 0, tc: [ 990, 990 ], color: [ 221, 255, 200, 0 ] }, { pos: [ 3686, -5119, -4505 ], flag: 0, tc: [ 0, -2204 ], color: [ 221, 255, 200, 255 ] }, { pos: [ 3686, -7679, -4505 ], flag: 0, tc: [ 0, 990 ], color: [ 221, 255, 200, 0 ] }, { pos: [ 3686, -5119, 4506 ], flag: 0, tc: [ 0, -2204 ], color: [ 166, 161, 111, 255 ] }, { pos: [ 3686, -7679, 4506 ], flag: 0, tc: [ 0, 990 ], color: [ 166, 161, 111, 0 ] }, { pos: [ 4506, -5119, 4506 ], flag: 0, tc: [ 990, -2204 ], color: [ 166, 161, 111, 255 ] }, { pos: [ 4506, -7679, 4506 ], flag: 0, tc: [ 990, 990 ], color: [ 166, 161, 111, 0 ] }, { pos: [ -4505, -5119, -3685 ], flag: 0, tc: [ -10250, -2204 ], color: [ 101, 123, 151, 255 ] }, { pos: [ -4505, -7679, -3685 ], flag: 0, tc: [ -10250, 990 ], color: [ 101, 123, 151, 0 ] }, { pos: [ -3685, -5119, -3685 ], flag: 0, tc: [ -9228, -2204 ], color: [ 101, 123, 151, 255 ] }, { pos: [ -3685, -7679, -3685 ], flag: 0, tc: [ -9228, 990 ], color: [ 101, 123, 151, 0 ] }, { pos: [ 3686, -5119, -3685 ], flag: 0, tc: [ 0, -2204 ], color: [ 149, 158, 123, 255 ] }, { pos: [ 3686, -7679, -3685 ], flag: 0, tc: [ 0, 990 ], color: [ 149, 158, 123, 0 ] }, { pos: [ 4506, -5119, -3685 ], flag: 0, tc: [ 990, -2204 ], color: [ 149, 158, 123, 255 ] }, { pos: [ 4506, -7679, -3685 ], flag: 0, tc: [ 990, 990 ], color: [ 149, 158, 123, 0 ] }, ] const totwc_seg7_vertex_070073C8 = [ { pos: [ -3685, -7679, -3685 ], flag: 0, tc: [ 990, 990 ], color: [ 151, 169, 205, 0 ] }, { pos: [ -3685, -7679, -4505 ], flag: 0, tc: [ 0, 990 ], color: [ 151, 169, 205, 0 ] }, { pos: [ -3685, -5119, -4505 ], flag: 0, tc: [ 0, -2204 ], color: [ 151, 169, 205, 255 ] }, { pos: [ -3685, -5119, -3685 ], flag: 0, tc: [ 990, -2204 ], color: [ 151, 169, 205, 255 ] }, { pos: [ -4505, -5119, -4505 ], flag: 0, tc: [ 0, -2204 ], color: [ 151, 169, 205, 255 ] }, { pos: [ -4505, -7679, -4505 ], flag: 0, tc: [ 0, 990 ], color: [ 151, 169, 205, 0 ] }, { pos: [ -4505, -5119, -3685 ], flag: 0, tc: [ 990, -2204 ], color: [ 151, 169, 205, 255 ] }, { pos: [ -4505, -7679, -3685 ], flag: 0, tc: [ 990, 990 ], color: [ 151, 169, 205, 0 ] }, { pos: [ 4506, -5119, 4506 ], flag: 0, tc: [ 11210, -2204 ], color: [ 205, 196, 151, 255 ] }, { pos: [ 4506, -7679, 4506 ], flag: 0, tc: [ 11210, 990 ], color: [ 205, 196, 151, 0 ] }, { pos: [ 4506, -5119, 3686 ], flag: 0, tc: [ 10188, -2204 ], color: [ 205, 196, 151, 255 ] }, { pos: [ 4506, -7679, 3686 ], flag: 0, tc: [ 10188, 990 ], color: [ 205, 196, 151, 0 ] }, { pos: [ 3686, -7679, 3686 ], flag: 0, tc: [ 10188, 990 ], color: [ 205, 196, 151, 0 ] }, { pos: [ 3686, -7679, 4506 ], flag: 0, tc: [ 11210, 990 ], color: [ 205, 196, 151, 0 ] }, { pos: [ 3686, -5119, 4506 ], flag: 0, tc: [ 11210, -2204 ], color: [ 205, 196, 151, 255 ] }, { pos: [ 3686, -5119, 3686 ], flag: 0, tc: [ 10188, -2204 ], color: [ 205, 196, 151, 255 ] }, ] const totwc_seg7_vertex_070074C8 = [ { pos: [ -469, -7679, 1135 ], flag: 0, tc: [ 350, 13700 ], color: [ 155, 81, 32, 0 ] }, { pos: [ -469, -5119, 1135 ], flag: 0, tc: [ 350, 7468 ], color: [ 155, 81, 32, 255 ] }, { pos: [ -1134, -5119, 470 ], flag: 0, tc: [ 2638, 7468 ], color: [ 155, 81, 32, 255 ] }, { pos: [ -1134, -7679, 470 ], flag: 0, tc: [ 2638, 13700 ], color: [ 155, 81, 32, 0 ] }, { pos: [ 470, -7679, -1134 ], flag: 0, tc: [ 2638, 13700 ], color: [ 155, 81, 32, 0 ] }, { pos: [ 1135, -5119, -469 ], flag: 0, tc: [ 350, 7468 ], color: [ 155, 81, 32, 255 ] }, { pos: [ 1135, -7679, -469 ], flag: 0, tc: [ 350, 13700 ], color: [ 155, 81, 32, 0 ] }, { pos: [ 470, -5119, -1134 ], flag: 0, tc: [ 2638, 7468 ], color: [ 155, 81, 32, 255 ] }, { pos: [ 470, -7679, 1135 ], flag: 0, tc: [ 346, 13700 ], color: [ 125, 62, 28, 0 ] }, { pos: [ -469, -5119, 1135 ], flag: 0, tc: [ 2636, 7468 ], color: [ 125, 62, 28, 255 ] }, { pos: [ -469, -7679, 1135 ], flag: 0, tc: [ 2636, 13700 ], color: [ 125, 62, 28, 0 ] }, { pos: [ 470, -5119, 1135 ], flag: 0, tc: [ 346, 7468 ], color: [ 125, 62, 28, 255 ] }, { pos: [ 1135, -7679, -469 ], flag: 0, tc: [ 2638, 13700 ], color: [ 125, 62, 28, 0 ] }, { pos: [ 1135, -5119, 470 ], flag: 0, tc: [ 350, 7468 ], color: [ 125, 62, 28, 255 ] }, { pos: [ 1135, -7679, 470 ], flag: 0, tc: [ 350, 13700 ], color: [ 125, 62, 28, 0 ] }, { pos: [ 1135, -5119, -469 ], flag: 0, tc: [ 2638, 7468 ], color: [ 125, 62, 28, 255 ] }, ] const totwc_seg7_vertex_070075C8 = [ { pos: [ -1134, -7679, 470 ], flag: 0, tc: [ 350, 13700 ], color: [ 195, 103, 43, 0 ] }, { pos: [ -1134, -5119, 470 ], flag: 0, tc: [ 350, 7468 ], color: [ 195, 103, 43, 255 ] }, { pos: [ -1134, -5119, -469 ], flag: 0, tc: [ 2638, 7468 ], color: [ 195, 103, 43, 255 ] }, { pos: [ -1134, -7679, -469 ], flag: 0, tc: [ 2638, 13700 ], color: [ 195, 103, 43, 0 ] }, { pos: [ -469, -7679, -1134 ], flag: 0, tc: [ 2636, 13700 ], color: [ 195, 103, 43, 0 ] }, { pos: [ -469, -5119, -1134 ], flag: 0, tc: [ 2636, 7468 ], color: [ 195, 103, 43, 255 ] }, { pos: [ 470, -5119, -1134 ], flag: 0, tc: [ 346, 7468 ], color: [ 195, 103, 43, 255 ] }, { pos: [ 470, -7679, -1134 ], flag: 0, tc: [ 346, 13700 ], color: [ 195, 103, 43, 0 ] }, { pos: [ -1134, -7679, -469 ], flag: 0, tc: [ 2604, 13704 ], color: [ 228, 135, 57, 0 ] }, { pos: [ -469, -5119, -1134 ], flag: 0, tc: [ 330, 7468 ], color: [ 228, 135, 57, 255 ] }, { pos: [ -469, -7679, -1134 ], flag: 0, tc: [ 316, 13700 ], color: [ 228, 135, 57, 0 ] }, { pos: [ -1134, -5119, -469 ], flag: 0, tc: [ 2620, 7474 ], color: [ 228, 135, 57, 255 ] }, { pos: [ 1135, -7679, 470 ], flag: 0, tc: [ 322, 13686 ], color: [ 93, 46, 0, 0 ] }, { pos: [ 1135, -5119, 470 ], flag: 0, tc: [ 338, 7454 ], color: [ 93, 46, 0, 255 ] }, { pos: [ 470, -5119, 1135 ], flag: 0, tc: [ 2626, 7460 ], color: [ 93, 46, 0, 255 ] }, { pos: [ 470, -7679, 1135 ], flag: 0, tc: [ 2612, 13692 ], color: [ 93, 46, 0, 0 ] }, ] export const totwc_seg7_dl_070076C8 = [ Gbi.gsDPSetTextureImage(Gbi.G_IM_FMT_RGBA, Gbi.G_IM_SIZ_16b, 1, totwc_seg7_texture_07001000), Gbi.gsDPLoadBlock(Gbi.G_TX_LOADTILE, 0, 0, 32 * 32 - 1), Gbi.gsSPVertex(totwc_seg7_vertex_070070C8, 16, 0), ...Gbi.gsSP2Triangles( 0, 1, 2, 0x0, 3, 0, 2, 0x0), ...Gbi.gsSP2Triangles( 4, 5, 6, 0x0, 5, 7, 6, 0x0), ...Gbi.gsSP2Triangles( 8, 9, 10, 0x0, 11, 8, 10, 0x0), ...Gbi.gsSP2Triangles(12, 13, 14, 0x0, 12, 14, 15, 0x0), Gbi.gsSPVertex(totwc_seg7_vertex_070071C8, 16, 0), ...Gbi.gsSP2Triangles( 0, 1, 2, 0x0, 0, 3, 1, 0x0), ...Gbi.gsSP2Triangles( 4, 5, 6, 0x0, 4, 6, 7, 0x0), ...Gbi.gsSP2Triangles( 8, 9, 10, 0x0, 8, 11, 9, 0x0), ...Gbi.gsSP2Triangles(12, 13, 14, 0x0, 15, 12, 14, 0x0), Gbi.gsSPVertex(totwc_seg7_vertex_070072C8, 16, 0), ...Gbi.gsSP2Triangles( 0, 1, 2, 0x0, 1, 3, 2, 0x0), ...Gbi.gsSP2Triangles( 4, 5, 6, 0x0, 5, 7, 6, 0x0), ...Gbi.gsSP2Triangles( 8, 9, 10, 0x0, 9, 11, 10, 0x0), ...Gbi.gsSP2Triangles(12, 13, 14, 0x0, 13, 15, 14, 0x0), Gbi.gsSPVertex(totwc_seg7_vertex_070073C8, 16, 0), ...Gbi.gsSP2Triangles( 0, 1, 2, 0x0, 3, 0, 2, 0x0), ...Gbi.gsSP2Triangles( 4, 5, 6, 0x0, 5, 7, 6, 0x0), ...Gbi.gsSP2Triangles( 8, 9, 10, 0x0, 9, 11, 10, 0x0), ...Gbi.gsSP2Triangles(12, 13, 14, 0x0, 15, 12, 14, 0x0), Gbi.gsSPEndDisplayList(), ] export const totwc_seg7_dl_07007808 = [ Gbi.gsDPSetTextureImage(Gbi.G_IM_FMT_RGBA, Gbi.G_IM_SIZ_16b, 1, sky_09001000), Gbi.gsDPLoadBlock(Gbi.G_TX_LOADTILE, 0, 0, 32 * 32 - 1), Gbi.gsSPVertex(totwc_seg7_vertex_070074C8, 16, 0), ...Gbi.gsSP2Triangles( 0, 1, 2, 0x0, 0, 2, 3, 0x0), ...Gbi.gsSP2Triangles( 4, 5, 6, 0x0, 4, 7, 5, 0x0), ...Gbi.gsSP2Triangles( 8, 9, 10, 0x0, 8, 11, 9, 0x0), ...Gbi.gsSP2Triangles(12, 13, 14, 0x0, 12, 15, 13, 0x0), Gbi.gsSPVertex(totwc_seg7_vertex_070075C8, 16, 0), ...Gbi.gsSP2Triangles( 0, 1, 2, 0x0, 0, 2, 3, 0x0), ...Gbi.gsSP2Triangles( 4, 5, 6, 0x0, 4, 6, 7, 0x0), ...Gbi.gsSP2Triangles( 8, 9, 10, 0x0, 8, 11, 9, 0x0), ...Gbi.gsSP2Triangles(12, 13, 14, 0x0, 12, 14, 15, 0x0), Gbi.gsSPEndDisplayList(), ] export const totwc_seg7_dl_070078B8 = [ Gbi.gsDPSetCombineMode(Gbi.G_CC_MODULATERGB), Gbi.gsSPClearGeometryMode(Gbi.G_LIGHTING), Gbi.gsDPSetTile(Gbi.G_IM_FMT_RGBA, Gbi.G_IM_SIZ_16b, 0, 0, Gbi.G_TX_LOADTILE, 0, Gbi.G_TX_WRAP | Gbi.G_TX_NOMIRROR, Gbi.G_TX_NOMASK, Gbi.G_TX_NOLOD, Gbi.G_TX_WRAP | Gbi.G_TX_NOMIRROR, Gbi.G_TX_NOMASK, Gbi.G_TX_NOLOD), Gbi.gsSPTexture(0xFFFF, 0xFFFF, 0, Gbi.G_TX_RENDERTILE, Gbi.G_ON), Gbi.gsDPSetTile(Gbi.G_IM_FMT_RGBA, Gbi.G_IM_SIZ_16b, 8, 0, Gbi.G_TX_RENDERTILE, 0, Gbi.G_TX_WRAP | Gbi.G_TX_NOMIRROR, 5, Gbi.G_TX_NOLOD, Gbi.G_TX_WRAP | Gbi.G_TX_NOMIRROR, 5, Gbi.G_TX_NOLOD), Gbi.gsDPSetTileSize(0, 0, 0, (32 - 1) << Gbi.G_TEXTURE_IMAGE_FRAC, (32 - 1) << Gbi.G_TEXTURE_IMAGE_FRAC), Gbi.gsSPDisplayList(totwc_seg7_dl_070076C8), Gbi.gsSPDisplayList(totwc_seg7_dl_07007808), Gbi.gsSPTexture(0xFFFF, 0xFFFF, 0, Gbi.G_TX_RENDERTILE, Gbi.G_OFF), Gbi.gsDPSetCombineMode(Gbi.G_CC_SHADE), Gbi.gsSPSetGeometryMode(Gbi.G_LIGHTING), Gbi.gsSPEndDisplayList(), ]
70.417143
218
0.538262
5c35dcae6f97ff35596bcc16ac49e2f6af282e2f
15,259
c
C
linux-2.6.0/arch/ppc64/kernel/smp.c
dnhua/Linux_study
96863b599cbba9c925b3209bed07b1d7b60cb463
[ "MIT" ]
1
2020-11-10T12:47:02.000Z
2020-11-10T12:47:02.000Z
linux-2.6.0/arch/ppc64/kernel/smp.c
dnhua/Linux_study
96863b599cbba9c925b3209bed07b1d7b60cb463
[ "MIT" ]
null
null
null
linux-2.6.0/arch/ppc64/kernel/smp.c
dnhua/Linux_study
96863b599cbba9c925b3209bed07b1d7b60cb463
[ "MIT" ]
null
null
null
/* * SMP support for ppc. * * Written by Cort Dougan (cort@cs.nmt.edu) borrowing a great * deal of code from the sparc and intel versions. * * Copyright (C) 1999 Cort Dougan <cort@cs.nmt.edu> * * PowerPC-64 Support added by Dave Engebretsen, Peter Bergner, and * Mike Corrigan {engebret|bergner|mikec}@us.ibm.com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version * 2 of the License, or (at your option) any later version. */ #include <linux/config.h> #include <linux/kernel.h> #include <linux/module.h> #include <linux/sched.h> #include <linux/smp.h> #include <linux/smp_lock.h> #include <linux/interrupt.h> #include <linux/kernel_stat.h> #include <linux/delay.h> #include <linux/init.h> #include <linux/spinlock.h> #include <linux/cache.h> #include <linux/err.h> #include <asm/ptrace.h> #include <asm/atomic.h> #include <asm/irq.h> #include <asm/page.h> #include <asm/pgtable.h> #include <asm/hardirq.h> #include <asm/io.h> #include <asm/prom.h> #include <asm/smp.h> #include <asm/naca.h> #include <asm/paca.h> #include <asm/iSeries/LparData.h> #include <asm/iSeries/HvCall.h> #include <asm/iSeries/HvCallCfg.h> #include <asm/time.h> #include <asm/ppcdebug.h> #include "open_pic.h" #include <asm/machdep.h> #include <asm/xics.h> #include <asm/cputable.h> int smp_threads_ready; unsigned long cache_decay_ticks; /* initialised so it doesn't end up in bss */ cpumask_t cpu_online_map = CPU_MASK_NONE; EXPORT_SYMBOL(cpu_online_map); static struct smp_ops_t *smp_ops; static volatile unsigned int cpu_callin_map[NR_CPUS]; extern unsigned char stab_array[]; extern int cpu_idle(void *unused); void smp_call_function_interrupt(void); void smp_message_pass(int target, int msg, unsigned long data, int wait); #define smp_message_pass(t,m,d,w) smp_ops->message_pass((t),(m),(d),(w)) static inline void set_tb(unsigned int upper, unsigned int lower) { mttbl(0); mttbu(upper); mttbl(lower); } #ifdef CONFIG_PPC_ISERIES static unsigned long iSeries_smp_message[NR_CPUS]; void iSeries_smp_message_recv( struct pt_regs * regs ) { int cpu = smp_processor_id(); int msg; if ( num_online_cpus() < 2 ) return; for ( msg = 0; msg < 4; ++msg ) if ( test_and_clear_bit( msg, &iSeries_smp_message[cpu] ) ) smp_message_recv( msg, regs ); } static void smp_iSeries_message_pass(int target, int msg, unsigned long data, int wait) { int i; for (i = 0; i < NR_CPUS; ++i) { if (!cpu_online(i)) continue; if ((target == MSG_ALL) || (target == i) || ((target == MSG_ALL_BUT_SELF) && (i != smp_processor_id())) ) { set_bit(msg, &iSeries_smp_message[i]); HvCall_sendIPI(&(paca[i])); } } } static int smp_iSeries_numProcs(void) { unsigned np, i; struct ItLpPaca * lpPaca; np = 0; for (i=0; i < NR_CPUS; ++i) { lpPaca = paca[i].xLpPacaPtr; if ( lpPaca->xDynProcStatus < 2 ) { ++np; } } return np; } static int smp_iSeries_probe(void) { unsigned i; unsigned np = 0; struct ItLpPaca *lpPaca; for (i=0; i < NR_CPUS; ++i) { lpPaca = paca[i].xLpPacaPtr; if (lpPaca->xDynProcStatus < 2) { paca[i].active = 1; ++np; } } return np; } static void smp_iSeries_kick_cpu(int nr) { struct ItLpPaca * lpPaca; /* Verify we have a Paca for processor nr */ if ( ( nr <= 0 ) || ( nr >= NR_CPUS ) ) return; /* Verify that our partition has a processor nr */ lpPaca = paca[nr].xLpPacaPtr; if ( lpPaca->xDynProcStatus >= 2 ) return; /* The information for processor bringup must * be written out to main store before we release * the processor. */ mb(); /* The processor is currently spinning, waiting * for the xProcStart field to become non-zero * After we set xProcStart, the processor will * continue on to secondary_start in iSeries_head.S */ paca[nr].xProcStart = 1; } static void __devinit smp_iSeries_setup_cpu(int nr) { } /* This is called very early. */ void __init smp_init_iSeries(void) { smp_ops = &ppc_md.smp_ops; smp_ops->message_pass = smp_iSeries_message_pass; smp_ops->probe = smp_iSeries_probe; smp_ops->kick_cpu = smp_iSeries_kick_cpu; smp_ops->setup_cpu = smp_iSeries_setup_cpu; #warning fix for iseries systemcfg->processorCount = smp_iSeries_numProcs(); } #endif #ifdef CONFIG_PPC_PSERIES static void smp_openpic_message_pass(int target, int msg, unsigned long data, int wait) { /* make sure we're sending something that translates to an IPI */ if ( msg > 0x3 ){ printk("SMP %d: smp_message_pass: unknown msg %d\n", smp_processor_id(), msg); return; } switch ( target ) { case MSG_ALL: openpic_cause_IPI(msg, 0xffffffff); break; case MSG_ALL_BUT_SELF: openpic_cause_IPI(msg, 0xffffffff & ~(1 << smp_processor_id())); break; default: openpic_cause_IPI(msg, 1<<target); break; } } static int __init smp_openpic_probe(void) { int i; int nr_cpus = 0; for (i = 0; i < NR_CPUS; i++) { if (cpu_possible(i)) nr_cpus++; } if (nr_cpus > 1) openpic_request_IPIs(); return nr_cpus; } static void smp_kick_cpu(int nr) { /* Verify we have a Paca for processor nr */ if ( ( nr <= 0 ) || ( nr >= NR_CPUS ) ) return; /* The information for processor bringup must * be written out to main store before we release * the processor. */ mb(); /* The processor is currently spinning, waiting * for the xProcStart field to become non-zero * After we set xProcStart, the processor will * continue on to secondary_start */ paca[nr].xProcStart = 1; } #endif static void __init smp_space_timers(unsigned int max_cpus) { int i; unsigned long offset = tb_ticks_per_jiffy / max_cpus; unsigned long previous_tb = paca[boot_cpuid].next_jiffy_update_tb; for (i = 0; i < NR_CPUS; i++) { if (cpu_possible(i) && i != boot_cpuid) { paca[i].next_jiffy_update_tb = previous_tb + offset; previous_tb = paca[i].next_jiffy_update_tb; } } } #ifdef CONFIG_PPC_PSERIES static void __devinit pSeries_setup_cpu(int cpu) { if (OpenPIC_Addr) { do_openpic_setup_cpu(); } else { if (cpu != boot_cpuid) xics_setup_cpu(); } } static void smp_xics_message_pass(int target, int msg, unsigned long data, int wait) { int i; for (i = 0; i < NR_CPUS; ++i) { if (!cpu_online(i)) continue; if (target == MSG_ALL || target == i || (target == MSG_ALL_BUT_SELF && i != smp_processor_id())) { set_bit(msg, &xics_ipi_message[i].value); mb(); xics_cause_IPI(i); } } } static int __init smp_xics_probe(void) { int i; int nr_cpus = 0; for (i = 0; i < NR_CPUS; i++) { if (cpu_possible(i)) nr_cpus++; } #ifdef CONFIG_SMP extern void xics_request_IPIs(void); xics_request_IPIs(); #endif return nr_cpus; } static spinlock_t timebase_lock = SPIN_LOCK_UNLOCKED; static unsigned long timebase = 0; static void __devinit pSeries_give_timebase(void) { spin_lock(&timebase_lock); rtas_call(rtas_token("freeze-time-base"), 0, 1, NULL); timebase = get_tb(); spin_unlock(&timebase_lock); while (timebase) barrier(); rtas_call(rtas_token("thaw-time-base"), 0, 1, NULL); } static void __devinit pSeries_take_timebase(void) { while (!timebase) barrier(); spin_lock(&timebase_lock); set_tb(timebase >> 32, timebase & 0xffffffff); timebase = 0; spin_unlock(&timebase_lock); } /* This is called very early */ void __init smp_init_pSeries(void) { smp_ops = &ppc_md.smp_ops; if (naca->interrupt_controller == IC_OPEN_PIC) { smp_ops->message_pass = smp_openpic_message_pass; smp_ops->probe = smp_openpic_probe; } else { smp_ops->message_pass = smp_xics_message_pass; smp_ops->probe = smp_xics_probe; } if (systemcfg->platform == PLATFORM_PSERIES) { smp_ops->give_timebase = pSeries_give_timebase; smp_ops->take_timebase = pSeries_take_timebase; } smp_ops->kick_cpu = smp_kick_cpu; smp_ops->setup_cpu = pSeries_setup_cpu; } #endif void smp_local_timer_interrupt(struct pt_regs * regs) { if (!--(get_paca()->prof_counter)) { update_process_times(user_mode(regs)); (get_paca()->prof_counter)=get_paca()->prof_multiplier; } } void smp_message_recv(int msg, struct pt_regs *regs) { switch( msg ) { case PPC_MSG_CALL_FUNCTION: smp_call_function_interrupt(); break; case PPC_MSG_RESCHEDULE: /* XXX Do we have to do this? */ set_need_resched(); break; #if 0 case PPC_MSG_MIGRATE_TASK: /* spare */ break; #endif #ifdef CONFIG_XMON case PPC_MSG_XMON_BREAK: xmon(regs); break; #endif /* CONFIG_XMON */ default: printk("SMP %d: smp_message_recv(): unknown msg %d\n", smp_processor_id(), msg); break; } } void smp_send_reschedule(int cpu) { smp_message_pass(cpu, PPC_MSG_RESCHEDULE, 0, 0); } #ifdef CONFIG_XMON void smp_send_xmon_break(int cpu) { smp_message_pass(cpu, PPC_MSG_XMON_BREAK, 0, 0); } #endif /* CONFIG_XMON */ static void stop_this_cpu(void *dummy) { local_irq_disable(); while (1) ; } void smp_send_stop(void) { smp_call_function(stop_this_cpu, NULL, 1, 0); } /* * Structure and data for smp_call_function(). This is designed to minimise * static memory requirements. It also looks cleaner. * Stolen from the i386 version. */ static spinlock_t call_lock __cacheline_aligned_in_smp = SPIN_LOCK_UNLOCKED; static struct call_data_struct { void (*func) (void *info); void *info; atomic_t started; atomic_t finished; int wait; } *call_data; /* delay of at least 8 seconds on 1GHz cpu */ #define SMP_CALL_TIMEOUT (1UL << (30 + 3)) /* * This function sends a 'generic call function' IPI to all other CPUs * in the system. * * [SUMMARY] Run a function on all other CPUs. * <func> The function to run. This must be fast and non-blocking. * <info> An arbitrary pointer to pass to the function. * <nonatomic> currently unused. * <wait> If true, wait (atomically) until function has completed on other CPUs. * [RETURNS] 0 on success, else a negative status code. Does not return until * remote CPUs are nearly ready to execute <<func>> or are or have executed. * * You must not call this function with disabled interrupts or from a * hardware interrupt handler or from a bottom half handler. */ int smp_call_function (void (*func) (void *info), void *info, int nonatomic, int wait) { struct call_data_struct data; int ret = -1, cpus = num_online_cpus()-1; unsigned long timeout; if (!cpus) return 0; data.func = func; data.info = info; atomic_set(&data.started, 0); data.wait = wait; if (wait) atomic_set(&data.finished, 0); spin_lock(&call_lock); call_data = &data; wmb(); /* Send a message to all other CPUs and wait for them to respond */ smp_message_pass(MSG_ALL_BUT_SELF, PPC_MSG_CALL_FUNCTION, 0, 0); /* Wait for response */ timeout = SMP_CALL_TIMEOUT; while (atomic_read(&data.started) != cpus) { HMT_low(); if (--timeout == 0) { #ifdef CONFIG_DEBUG_KERNEL if (debugger) debugger(0); #endif printk("smp_call_function on cpu %d: other cpus not " "responding (%d)\n", smp_processor_id(), atomic_read(&data.started)); goto out; } } if (wait) { timeout = SMP_CALL_TIMEOUT; while (atomic_read(&data.finished) != cpus) { HMT_low(); if (--timeout == 0) { #ifdef CONFIG_DEBUG_KERNEL if (debugger) debugger(0); #endif printk("smp_call_function on cpu %d: other " "cpus not finishing (%d/%d)\n", smp_processor_id(), atomic_read(&data.finished), atomic_read(&data.started)); goto out; } } } ret = 0; out: HMT_medium(); spin_unlock(&call_lock); return ret; } void smp_call_function_interrupt(void) { void (*func) (void *info) = call_data->func; void *info = call_data->info; int wait = call_data->wait; /* * Notify initiating CPU that I've grabbed the data and am * about to execute the function */ atomic_inc(&call_data->started); /* * At this point the info structure may be out of scope unless wait==1 */ (*func)(info); if (wait) atomic_inc(&call_data->finished); } extern unsigned long decr_overclock; extern struct gettimeofday_struct do_gtod; struct thread_info *current_set[NR_CPUS]; static void __devinit smp_store_cpu_info(int id) { paca[id].pvr = _get_PVR(); } void __init smp_prepare_cpus(unsigned int max_cpus) { /* Fixup boot cpu */ smp_store_cpu_info(smp_processor_id()); cpu_callin_map[smp_processor_id()] = 1; paca[smp_processor_id()].prof_counter = 1; paca[smp_processor_id()].prof_multiplier = 1; /* * XXX very rough. */ cache_decay_ticks = HZ/100; #ifndef CONFIG_PPC_ISERIES paca[boot_cpuid].next_jiffy_update_tb = tb_last_stamp = get_tb(); /* * Should update do_gtod.stamp_xsec. * For now we leave it which means the time can be some * number of msecs off until someone does a settimeofday() */ do_gtod.tb_orig_stamp = tb_last_stamp; #endif max_cpus = smp_ops->probe(); smp_space_timers(max_cpus); } void __devinit smp_prepare_boot_cpu(void) { cpu_set(smp_processor_id(), cpu_online_map); /* FIXME: what about cpu_possible()? */ } int __devinit __cpu_up(unsigned int cpu) { struct pt_regs regs; struct task_struct *p; int c; paca[cpu].prof_counter = 1; paca[cpu].prof_multiplier = 1; paca[cpu].default_decr = tb_ticks_per_jiffy / decr_overclock; if (!(cur_cpu_spec->cpu_features & CPU_FTR_SLB)) { void *tmp; /* maximum of 48 CPUs on machines with a segment table */ if (cpu >= 48) BUG(); tmp = &stab_array[PAGE_SIZE * cpu]; memset(tmp, 0, PAGE_SIZE); paca[cpu].xStab_data.virt = (unsigned long)tmp; paca[cpu].xStab_data.real = (unsigned long)__v2a(tmp); } /* create a process for the processor */ /* only regs.msr is actually used, and 0 is OK for it */ memset(&regs, 0, sizeof(struct pt_regs)); p = copy_process(CLONE_VM|CLONE_IDLETASK, 0, &regs, 0, NULL, NULL); if (IS_ERR(p)) panic("failed fork for CPU %u: %li", cpu, PTR_ERR(p)); wake_up_forked_process(p); init_idle(p, cpu); unhash_process(p); paca[cpu].xCurrent = (u64)p; current_set[cpu] = p->thread_info; /* wake up cpus */ smp_ops->kick_cpu(cpu); /* * wait to see if the cpu made a callin (is actually up). * use this value that I found through experimentation. * -- Cort */ for (c = 5000; c && !cpu_callin_map[cpu]; c--) udelay(100); if (!cpu_callin_map[cpu]) { printk("Processor %u is stuck.\n", cpu); return -ENOENT; } printk("Processor %u found.\n", cpu); if (smp_ops->give_timebase) smp_ops->give_timebase(); cpu_set(cpu, cpu_online_map); return 0; } /* Activate a secondary processor. */ int __devinit start_secondary(void *unused) { unsigned int cpu = smp_processor_id(); atomic_inc(&init_mm.mm_count); current->active_mm = &init_mm; smp_store_cpu_info(cpu); set_dec(paca[cpu].default_decr); cpu_callin_map[cpu] = 1; smp_ops->setup_cpu(cpu); if (smp_ops->take_timebase) smp_ops->take_timebase(); local_irq_enable(); return cpu_idle(NULL); } int setup_profiling_timer(unsigned int multiplier) { return 0; } void __init smp_cpus_done(unsigned int max_cpus) { smp_ops->setup_cpu(boot_cpuid); /* XXX fix this, xics currently relies on it - Anton */ smp_threads_ready = 1; }
22.5059
87
0.691985
5fcee1244c6a24198233f0e18bc03ecc245d975b
1,792
css
CSS
app/assets/stylesheets/lit/lit_frontend.css
b2bmg/lit
b563f236feb8da9a591f99c142a5de35e16f0a84
[ "MIT" ]
219
2015-01-05T15:29:13.000Z
2022-02-03T01:41:22.000Z
app/assets/stylesheets/lit/lit_frontend.css
b2bmg/lit
b563f236feb8da9a591f99c142a5de35e16f0a84
[ "MIT" ]
93
2015-01-08T14:11:12.000Z
2021-12-24T14:27:53.000Z
app/assets/stylesheets/lit/lit_frontend.css
b2bmg/lit
b563f236feb8da9a591f99c142a5de35e16f0a84
[ "MIT" ]
66
2015-01-18T22:39:40.000Z
2022-03-22T08:54:07.000Z
.lit-key-generic { } .lit-key-highlight { text-decoration: underline !important; text-decoration-color: red !important; text-decoration-style: wavy !important; } #lit_button_wrapper { position: fixed; bottom: 20px; right: 20px; z-index: 100; background-color: red; border-radius: 4px; display: block; padding: 5px; cursor: pointer; color: white; } #lit_button_wrapper.lit-highlight-enabled { background-color: lightgreen; } #lit_textarea { position: absolute; padding: 0 0 1px 0; margin: 0 0 0 0; border: 0; border-bottom: 1px solid red; } .lit-translations-info.collapsed { position: fixed; bottom: 60px; right: 20px; z-index: 100; background-color: green; border-radius: 4px; display: block; padding: 5px; cursor: pointer; color: white; } .lit-translations-info.expanded { position: absolute; display: block; width: 80%; overflow: auto; height: 80%; right: 10%; left: 10%; top: 10%; background-color: rgba(240, 240, 240, 0.9); border: 1px solid black; z-index: 90; } .lit-translations-info.collapsed span.lit-open-button { display: block; } .lit-translations-info.expanded span.lit-open-button { display: none; } .lit-translations-info.collapsed span.lit-close-button { display: none; } .lit-translations-info.expanded span.lit-close-button { display: block; position: fixed; right: 10%; border: 2px solid black; font-size: 12pt; font-weight: bold; background-color: white; padding: 10px 10px 5px; } .lit-translations-info.collapsed ul.lit-translations-list { display: none; } .lit-translations-info.expanded ul.lit-translations-list { } .lit-translations-info.expanded ul.lit-translations-list li { margin: 5px; } .lit-translations-info.expanded #lit_textarea { padding: 2px; }
20.363636
61
0.699777
f08133a0ab8681553c9936415f848d5882f36db1
1,150
py
Python
src/controllers/storage.py
koddas/python-oop-consistency-lab
8ee3124aa230359d296fdfbe0c23773602769c8c
[ "MIT" ]
null
null
null
src/controllers/storage.py
koddas/python-oop-consistency-lab
8ee3124aa230359d296fdfbe0c23773602769c8c
[ "MIT" ]
null
null
null
src/controllers/storage.py
koddas/python-oop-consistency-lab
8ee3124aa230359d296fdfbe0c23773602769c8c
[ "MIT" ]
null
null
null
from entities.serializable import Serializable class Storage: ''' Storage represents a file storage that stores and retrieves objects ''' def __init__(self): pass def save(self, filename: str, data: Serializable) -> bool: ''' Stores a serializable object. If the object isn't explicitly marked as being serializable, this method will fail. ''' if not issubclass(data.__class__, Serializable): return False f = open(filename, "w") f.write(data.serialize()) f.close() return True def read(self, filename: str, class_name: type) -> Serializable: ''' Retrieves a serialized object. You specify the type of he object to deserialize by passing the class (as a type, not a string) as the second parameter. ''' if not issubclass(class_name, Serializable): return None f = open(filename, "r") data = f.read() f.close() deserialized = class_name.deserialize(data) return deserialized
28.75
78
0.578261
b951daafdf2ea631f4586edab95c7489c0b1ced2
1,785
h
C
slrs/camlibs/smal/ultrapocket.h
milinddeore/360D-Sampler
a17df51aa3f1252274337c2421b90e4bd1c6b40e
[ "MIT" ]
null
null
null
slrs/camlibs/smal/ultrapocket.h
milinddeore/360D-Sampler
a17df51aa3f1252274337c2421b90e4bd1c6b40e
[ "MIT" ]
null
null
null
slrs/camlibs/smal/ultrapocket.h
milinddeore/360D-Sampler
a17df51aa3f1252274337c2421b90e4bd1c6b40e
[ "MIT" ]
null
null
null
/* ultrapocket.h * * Copyright (C) 2003 Lee Benfield <lee@benf.org> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301 USA */ #ifndef __ULTRAPOCKET_H__ #define __ULTRAPOCKET_H__ 1 #include <gphoto2/gphoto2-library.h> #include <gphoto2/gphoto2-result.h> #ifndef CHECK_RESULT #define CHECK_RESULT(result) {int r = (result); if (r < 0) return (r);} #endif #define UP_FLAG_NEEDS_RESET 0x80 #define DO_GAMMA 1 #define GAMMA_NUMBER 0.5 typedef enum ultrapocket_IMG_TYPE { TYPE_QVGA = 0, TYPE_VGA = 1, TYPE_QVGA_BH = 2, TYPE_VGA_BH = 3 } smal_img_type; int ultrapocket_getpicsoverview(Camera *camera, GPContext *context,int *numpics, CameraList *list); int ultrapocket_exit(GPPort *port, GPContext *context); int ultrapocket_getrawpicture(Camera *camera, GPContext *context, unsigned char **pdata, int *size, const char *filename); int ultrapocket_getpicture(Camera *camera, GPContext *context, unsigned char **pdata, int *size, const char *filename); int ultrapocket_deletefile(Camera *camera, const char *filename); int ultrapocket_deleteall(Camera *camera); #endif
35
122
0.753501
94824e59e3bbeec4a54da13bbcefeb75688ccf0a
1,463
rs
Rust
exercises/space-age/example.rs
hunger/rust
0df41e20d0ddf7927dce28a78e50c1366980cb17
[ "MIT" ]
1
2019-08-01T06:36:55.000Z
2019-08-01T06:36:55.000Z
exercises/space-age/example.rs
hunger/rust
0df41e20d0ddf7927dce28a78e50c1366980cb17
[ "MIT" ]
null
null
null
exercises/space-age/example.rs
hunger/rust
0df41e20d0ddf7927dce28a78e50c1366980cb17
[ "MIT" ]
1
2020-12-24T15:13:15.000Z
2020-12-24T15:13:15.000Z
pub struct Duration { seconds: f64, } impl From<u64> for Duration { fn from(s: u64) -> Self { Duration { seconds: s as f64 } } } impl From<f64> for Duration { fn from(s: f64) -> Self { Duration { seconds: s } } } pub trait Planet { fn orbital_duration() -> Duration; fn years_during(d: &Duration) -> f64 { d.seconds / Self::orbital_duration().seconds } } pub struct Mercury; pub struct Venus; pub struct Earth; pub struct Mars; pub struct Jupiter; pub struct Saturn; pub struct Uranus; pub struct Neptune; impl Planet for Mercury { fn orbital_duration() -> Duration { Duration::from(7600543.81992) } } impl Planet for Venus { fn orbital_duration() -> Duration { Duration::from(19414149.052176) } } impl Planet for Earth { fn orbital_duration() -> Duration { Duration::from(31557600) } } impl Planet for Mars { fn orbital_duration() -> Duration { Duration::from(59354032.69008) } } impl Planet for Jupiter { fn orbital_duration() -> Duration { Duration::from(374355659.124) } } impl Planet for Saturn { fn orbital_duration() -> Duration { Duration::from(929292362.8848) } } impl Planet for Uranus { fn orbital_duration() -> Duration { Duration::from(2651370019.3296) } } impl Planet for Neptune { fn orbital_duration() -> Duration { Duration::from(5200418560.032) } }
18.2875
52
0.62201
8eb5802c987393a0d4c44f0c9301cb02e2cc52e6
2,013
sql
SQL
Documentation/DBScripts/1_category.sql
HPE-Legobricks/cal-eStore
e82b186c4dcf7c7be410029249b66f5e35cbb7bd
[ "ADSL" ]
null
null
null
Documentation/DBScripts/1_category.sql
HPE-Legobricks/cal-eStore
e82b186c4dcf7c7be410029249b66f5e35cbb7bd
[ "ADSL" ]
null
null
null
Documentation/DBScripts/1_category.sql
HPE-Legobricks/cal-eStore
e82b186c4dcf7c7be410029249b66f5e35cbb7bd
[ "ADSL" ]
null
null
null
USE calestore; INSERT INTO CATEGORY (`CATEGORY_ID`, `CATEGORY_NAME`, `CATEGORY_DESC`) VALUES (0, 'Laptops', ''); INSERT INTO `calestore`.`CATEGORY` (`CATEGORY_ID`, `CATEGORY_NAME`, `CATEGORY_DESC`) VALUES (0, 'Desktop', ''); INSERT INTO `calestore`.`CATEGORY` (`CATEGORY_ID`, `CATEGORY_NAME`, `CATEGORY_DESC`) VALUES (0, 'Hard Drive', ''); INSERT INTO `calestore`.`CATEGORY` (`CATEGORY_ID`, `CATEGORY_NAME`, `CATEGORY_DESC`) VALUES (0, 'VAS Services', ''); INSERT INTO `calestore`.`CATEGORY` (`CATEGORY_ID`, `CATEGORY_NAME`, `CATEGORY_DESC`) VALUES (0, 'Hardware Services', ''); INSERT INTO `calestore`.`CATEGORY` (`CATEGORY_ID`, `CATEGORY_NAME`, `CATEGORY_DESC`) VALUES (0, 'Deploy and Logistic', ''); INSERT INTO `calestore`.`CATEGORY` (`CATEGORY_ID`, `CATEGORY_NAME`, `CATEGORY_DESC`) VALUES (0, 'Recycling Services', ''); INSERT INTO `calestore`.`CATEGORY` (`CATEGORY_ID`, `CATEGORY_NAME`, `CATEGORY_DESC`) VALUES (0, 'Monitor', ''); INSERT INTO `calestore`.`CATEGORY` (`CATEGORY_ID`, `CATEGORY_NAME`, `CATEGORY_DESC`) VALUES (0, 'Data Encryption', ''); INSERT INTO `calestore`.`CATEGORY` (`CATEGORY_ID`, `CATEGORY_NAME`, `CATEGORY_DESC`) VALUES (0, 'Device & Data Security', ''); INSERT INTO `calestore`.`CATEGORY` (`CATEGORY_ID`, `CATEGORY_NAME`, `CATEGORY_DESC`) VALUES (0, 'Other', ''); INSERT INTO `calestore`.`CATEGORY` (`CATEGORY_ID`, `CATEGORY_NAME`, `CATEGORY_DESC`) VALUES (0, 'Graphics Card', ''); INSERT INTO `calestore`.`CATEGORY` (`CATEGORY_ID`, `CATEGORY_NAME`, `CATEGORY_DESC`) VALUES (0, 'Port', ''); INSERT INTO `calestore`.`CATEGORY` (`CATEGORY_ID`, `CATEGORY_NAME`, `CATEGORY_DESC`) VALUES (0, 'Processor', ''); INSERT INTO `calestore`.`CATEGORY`(`CATEGORY_ID`,`CATEGORY_NAME`,`CATEGORY_DESC`) VALUES(0,'Installation Services',''); INSERT INTO `calestore`.`CATEGORY`(`CATEGORY_ID`,`CATEGORY_NAME`,`CATEGORY_DESC`) VALUES(0,'Asset Tagging Services',''); INSERT INTO `calestore`.`CATEGORY`(`CATEGORY_ID`,`CATEGORY_NAME`,`CATEGORY_DESC`) VALUES(0,'Warranty Services','');
14.378571
81
0.704918
bebb9f72d65723025f5361a106f98638cf779bf6
216
rs
Rust
src/play/mod.rs
Canop/lapin
a6b34c93b065b2606bb7a0b1034083d96e15a741
[ "MIT" ]
38
2020-03-12T13:50:57.000Z
2022-01-19T02:44:24.000Z
src/play/mod.rs
Canop/lapin
a6b34c93b065b2606bb7a0b1034083d96e15a741
[ "MIT" ]
1
2020-06-23T05:41:02.000Z
2020-06-23T11:04:33.000Z
src/play/mod.rs
Canop/lapin
a6b34c93b065b2606bb7a0b1034083d96e15a741
[ "MIT" ]
5
2020-03-12T21:16:33.000Z
2021-06-26T22:45:27.000Z
use { crate::{ display::Layout, }, }; mod state; pub use { state::PlayLevelState, }; pub const LAYOUT: Layout = Layout { header_height: 0, pen_panel_height: 0, status_height: 1, };
12
35
0.578704
5e35aa1a8cda3c124bfbd7beaa5998b08a77449d
112
kt
Kotlin
app/src/main/java/com/sadge/devbhoomi_uttarakhand/data/Wildlife.kt
karanpreet8082/Devbhoomi-Uttarakhand
27712b367e05e3278592d8293eb03449d97bed64
[ "MIT" ]
2
2022-03-23T07:56:10.000Z
2022-03-24T04:48:58.000Z
app/src/main/java/com/sadge/devbhoomi_uttarakhand/data/Wildlife.kt
karanpreet8082/Devbhoomi-Uttarakhand
27712b367e05e3278592d8293eb03449d97bed64
[ "MIT" ]
8
2022-03-23T11:59:46.000Z
2022-03-24T06:50:25.000Z
app/src/main/java/com/sadge/devbhoomi_uttarakhand/data/Wildlife.kt
karanpreet8082/Devbhoomi-Uttarakhand
27712b367e05e3278592d8293eb03449d97bed64
[ "MIT" ]
3
2022-03-23T07:56:14.000Z
2022-03-23T11:20:29.000Z
package com.sadge.devbhoomi_uttarakhand.data data class Wildlife( val image: String, val name: String )
18.666667
44
0.75
0c838985451aa2ad22b242adc65e804a31a4160f
2,859
swift
Swift
lottie-swift/src/Private/Model/Objects/EffectValue.swift
MQZHot/lottie-ios
a274f67d63303789951f02b556ff5aff88dbc416
[ "Apache-2.0" ]
1
2021-07-20T13:57:50.000Z
2021-07-20T13:57:50.000Z
lottie-swift/src/Private/Model/Objects/EffectValue.swift
MQZHot/lottie-ios
a274f67d63303789951f02b556ff5aff88dbc416
[ "Apache-2.0" ]
1
2021-01-07T07:12:03.000Z
2021-01-07T07:12:03.000Z
lottie-swift/src/Private/Model/Objects/EffectValue.swift
MQZHot/lottie-ios
a274f67d63303789951f02b556ff5aff88dbc416
[ "Apache-2.0" ]
1
2021-01-30T09:11:23.000Z
2021-01-30T09:11:23.000Z
// // EffectValue.swift // Lottie_iOS // // Created by Viktor Radulov on 9/10/19. // Copyright © 2019 YurtvilleProds. All rights reserved. // import Foundation public enum EffectValueType: Int, Codable { case lineValue = 0 case flatValue = 2 case volumeValue = 3 case boolValue = 7 case boolValue2 = 10 } extension EffectValueType: ClassFamily { static var discriminator: Discriminator = .type func getType() -> AnyObject.Type { switch self { case .lineValue: return InterpolatableEffectValue<Vector1D>.self case .flatValue: return ArrayEffectValue.self case .volumeValue: return InterpolatableEffectValue<Vector3D>.self case .boolValue, .boolValue2: return BoolEffectValue.self } } } class EffectValue: Codable { fileprivate enum CodingKeys : String, CodingKey { case name = "nm" case index = "ix" case type = "ty" case value = "v" case attribute = "a" case key = "k" } let type: EffectValueType let index: Int let name: String required init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) self.type = try container.decode(EffectValueType.self, forKey: .type) self.index = try container.decode(Int.self, forKey: .index) self.name = try container.decode(String.self, forKey: .name) } func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) try container.encode(type, forKey: .type) try container.encode(index, forKey: .index) try container.encode(name, forKey: .name) } } class InterpolatableEffectValue<T>: EffectValue where T : Interpolatable & Codable { let value: KeyframeGroup<T> lazy var interpolator = KeyframeInterpolator(keyframes: value.keyframes) required init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) self.value = try container.decode(KeyframeGroup<T>.self, forKey: CodingKeys.value) try super.init(from: decoder) } } class ArrayEffectValue: EffectValue { let value: [Double] struct ArrayEffectValueContainer: Decodable { let a: Double let k: [Double] } required init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) let dictionary: ArrayEffectValueContainer = try container.decode(ArrayEffectValueContainer.self, forKey: .value) self.value = dictionary.k try super.init(from: decoder) } } class BoolEffectValue: EffectValue { let value: Bool required init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) let dictionary: [String: Int] = try container.decode([String: Int].self, forKey: CodingKeys.value) self.value = dictionary[CodingKeys.key.rawValue] == 0 ? false : true try super.init(from: decoder) } }
26.971698
114
0.720182
e7fcf109cce1b1c57ca682a8b6f5606efb8ee46b
643
py
Python
data/test1.py
moses-alexander/simple-python-parser
a15f53a86d61fa5d98f5ade149d8c3a178ebfb50
[ "BSD-3-Clause" ]
null
null
null
data/test1.py
moses-alexander/simple-python-parser
a15f53a86d61fa5d98f5ade149d8c3a178ebfb50
[ "BSD-3-Clause" ]
null
null
null
data/test1.py
moses-alexander/simple-python-parser
a15f53a86d61fa5d98f5ade149d8c3a178ebfb50
[ "BSD-3-Clause" ]
null
null
null
1+2 3+5 7+8 6>7 abs(-3) if 8 < 9: min(3,5) else 4 < 5: abs(-2) else 4 > 5: max(3, 7) round(2.1) round(3.6) len("jfdgge") type(4) any(1, 3, 4) any(0.0, 0.0, 0.0) all("abc", "a") all(0, 1) bin(45) lower("ABC") upper("abc") join("abc", "abc") bool(0) bool("abc") ord('r') chr(100) str(130) globals() help() hex(15) oct(27) pow(4,2) sum(1,2, 3) id(4) id("abc") not False none() none(0) # breaks here ... for now b = 1 print("a", b); print(); a = 5 #def append_element(self, val): newest =__Node(val);newestprev = self__trailerprev;self__trailerprevnext = newest;self__trailerprev = newest;newestnext = self__trailer;self__size = self__size + 1;
14.613636
196
0.62986
96683c41346e7de93524c24ca0f575e3105986f8
795
php
PHP
other_windows_tools/DragonByte SEO v2.0.39 PRO/upload/dbtech/dbseo/hooks/threadbit_process.php
ExaByt3s/hack_scripts
cc801b36ea25f3b5a82d2900f53f5036e7abd8ad
[ "WTFPL" ]
3
2021-01-22T19:32:23.000Z
2022-01-03T01:06:44.000Z
other_windows_tools/DragonByte SEO v2.0.39 PRO/upload/dbtech/dbseo/hooks/threadbit_process.php
a04512/hack_scripts
cc801b36ea25f3b5a82d2900f53f5036e7abd8ad
[ "WTFPL" ]
null
null
null
other_windows_tools/DragonByte SEO v2.0.39 PRO/upload/dbtech/dbseo/hooks/threadbit_process.php
a04512/hack_scripts
cc801b36ea25f3b5a82d2900f53f5036e7abd8ad
[ "WTFPL" ]
1
2021-12-10T13:18:16.000Z
2021-12-10T13:18:16.000Z
<?php do { if (!class_exists('DBSEO')) { // Set important constants define('DBSEO_CWD', DIR); define('DBSEO_TIMENOW', TIMENOW); define('IN_DBSEO', true); // Make sure we nab this class require_once(DBSEO_CWD . '/dbtech/dbseo/includes/class_core.php'); // Init DBSEO DBSEO::init(true); } if (!DBSEO::$config['dbtech_dbseo_active']) { // Mod is disabled break; } if ($thread['open'] == 10) { // Not a valid thread break; } if (!isset($thread['forumid'])) { // Thread is lacking forum info break; } if (isset(DBSEO::$cache['thread_pre'][$thread['threadid']])) { // Already cached break; } // Pre-cache thread info DBSEO::$cache['thread_pre'][$thread['threadid']] = $thread; } while (false); ?>
17.282609
69
0.583648
5748421f71eac278a9f46ab10b285ea5c1cd36df
849
h
C
System/Library/PrivateFrameworks/OfficeImport.framework/CMXmlUtils.h
lechium/iOS1351Headers
6bed3dada5ffc20366b27f7f2300a24a48a6284e
[ "MIT" ]
2
2021-11-02T09:23:27.000Z
2022-03-28T08:21:57.000Z
System/Library/PrivateFrameworks/OfficeImport.framework/CMXmlUtils.h
lechium/iOS1351Headers
6bed3dada5ffc20366b27f7f2300a24a48a6284e
[ "MIT" ]
null
null
null
System/Library/PrivateFrameworks/OfficeImport.framework/CMXmlUtils.h
lechium/iOS1351Headers
6bed3dada5ffc20366b27f7f2300a24a48a6284e
[ "MIT" ]
1
2022-03-28T08:21:59.000Z
2022-03-28T08:21:59.000Z
/* * This header is generated by classdump-dyld 1.5 * on Wednesday, October 27, 2021 at 3:22:40 PM Mountain Standard Time * Operating System: Version 13.5.1 (Build 17F80) * Image Source: /System/Library/PrivateFrameworks/OfficeImport.framework/OfficeImport * classdump-dyld is licensed under GPLv3, Copyright © 2013-2016 by Elias Limneos. Updated by Kevin Bradley. */ @interface CMXmlUtils : NSObject +(id)copyXhtmlDocument; +(id)copyHeadElementWithTitle:(id)arg1 deviceWidth:(int)arg2 ; +(void)filterString:(id)arg1 ; +(id)copyHeadElement; +(id)copyHeadElementForDeviceWidth:(int)arg1 ; +(id)copyFilteredString:(id)arg1 ; +(id)xhtmlStringWithXmlData:(id)arg1 ; +(id)copyHeadElementWithTitle:(id)arg1 ; @end
40.428571
130
0.647821
e0c3c990eb8cfede29c55e8763f697d3e0ffe6c1
4,202
swift
Swift
Auth0/CredentialsManagerError.swift
airtasker/Auth0.swift
275079e44cf97497ae870deda1bf28dba0b26684
[ "MIT" ]
null
null
null
Auth0/CredentialsManagerError.swift
airtasker/Auth0.swift
275079e44cf97497ae870deda1bf28dba0b26684
[ "MIT" ]
null
null
null
Auth0/CredentialsManagerError.swift
airtasker/Auth0.swift
275079e44cf97497ae870deda1bf28dba0b26684
[ "MIT" ]
null
null
null
import Foundation /** * Represents an error during a Credentials Manager operation. */ public struct CredentialsManagerError: Auth0Error { enum Code: Equatable { case noCredentials case noRefreshToken case renewFailed case biometricsFailed case revokeFailed case largeMinTTL(minTTL: Int, lifetime: Int) } let code: Code init(code: Code, cause: Error? = nil) { self.code = code self.cause = cause } /** The underlying `Error` value, if any. Defaults to `nil`. */ public let cause: Error? /** Description of the error. - Important: You should avoid displaying the error description to the user, it's meant for **debugging** only. */ public var debugDescription: String { switch self.code { case .noCredentials: return "No credentials were found in the store." case .noRefreshToken: return "The stored credentials instance does not contain a refresh token." case .renewFailed: return "The credentials renewal failed. See the underlying 'AuthenticationError' value" + " available in the 'cause' property." case .biometricsFailed: return "The Biometric authentication failed. See the underlying 'LAError' value" + " available in the 'cause' property." case .revokeFailed: return "The revocation of the refresh token failed. See the underlying 'AuthenticationError'" + " value available in the 'cause' property." case .largeMinTTL(let minTTL, let lifetime): return "The minTTL requested (\(minTTL)s) is greater than the" + " lifetime of the renewed access token (\(lifetime)s). Request a lower minTTL or increase the" + " 'Token Expiration' value in the settings page of your Auth0 API." } } // MARK: - Error Cases /// No credentials were found in the store. /// This error does not include a ``cause``. public static let noCredentials: CredentialsManagerError = .init(code: .noCredentials) /// The stored ``Credentials`` instance does not contain a refresh token. /// This error does not include a ``cause``. public static let noRefreshToken: CredentialsManagerError = .init(code: .noRefreshToken) /// The credentials renewal failed. /// The underlying ``AuthenticationError`` can be accessed via the ``cause`` property. public static let renewFailed: CredentialsManagerError = .init(code: .renewFailed) /// The Biometric authentication failed. /// The underlying `LAError` can be accessed via the ``cause`` property. public static let biometricsFailed: CredentialsManagerError = .init(code: .biometricsFailed) /// The revocation of the refresh token failed. /// The underlying ``AuthenticationError`` can be accessed via the ``cause`` property. public static let revokeFailed: CredentialsManagerError = .init(code: .revokeFailed) /// The `minTTL` requested is greater than the lifetime of the renewed access token. Request a lower `minTTL` or /// increase the **Token Expiration** value in the settings page of your [Auth0 API](https://manage.auth0.com/#/apis/). /// This error does not include a ``cause``. public static let largeMinTTL: CredentialsManagerError = .init(code: .largeMinTTL(minTTL: 0, lifetime: 0)) } // MARK: - Equatable extension CredentialsManagerError: Equatable { /// Conformance to `Equatable`. public static func == (lhs: CredentialsManagerError, rhs: CredentialsManagerError) -> Bool { return lhs.code == rhs.code && lhs.localizedDescription == rhs.localizedDescription } } // MARK: - Pattern Matching Operator public extension CredentialsManagerError { /// Matches `CredentialsManagerError` values in a switch statement. static func ~= (lhs: CredentialsManagerError, rhs: CredentialsManagerError) -> Bool { return lhs.code == rhs.code } /// Matches `Error` values in a switch statement. static func ~= (lhs: CredentialsManagerError, rhs: Error) -> Bool { guard let rhs = rhs as? CredentialsManagerError else { return false } return lhs.code == rhs.code } }
41.60396
123
0.683484
9294c60197d527f5542cc6a715a02096cbd390cc
647
h
C
engine/main/objects/static/triggers/common/handler/Handler.h
bwormguy/flash
d1f0cc40fce67e9932d4e9474da8d66cab055cdf
[ "MIT" ]
3
2020-08-25T07:49:45.000Z
2020-10-16T17:54:53.000Z
engine/main/objects/static/triggers/common/handler/Handler.h
bwormguy/flash
d1f0cc40fce67e9932d4e9474da8d66cab055cdf
[ "MIT" ]
1
2020-09-18T04:35:13.000Z
2020-09-18T04:35:13.000Z
engine/main/objects/static/triggers/common/handler/Handler.h
bwormguy/flash
d1f0cc40fce67e9932d4e9474da8d66cab055cdf
[ "MIT" ]
null
null
null
// // Created by roman on 04.10.2020. // #ifndef FLASH_HANDLER_H #define FLASH_HANDLER_H namespace Triggers { /** * @brief The base class of the Handler class hierarchy. Uses for change objects state. * @namespace Triggers * * This class defines base Handler interface. */ template<class Type> class Handler { public: Handler() = default; /** * @brief Method handles object before trigger action. * @param object Object. */ virtual void handle(Type &object) const noexcept = 0; virtual ~Handler() = default; }; } #endif //FLASH_HANDLER_H
20.21875
91
0.61051
4421ecd9a343d5e957804514500985cbc97038b9
288
sql
SQL
images/storage/bootstrap.sql
elston/carcassmysql
f4a00361536387a6ed5f3fbb10c585971a593de7
[ "MIT" ]
null
null
null
images/storage/bootstrap.sql
elston/carcassmysql
f4a00361536387a6ed5f3fbb10c585971a593de7
[ "MIT" ]
null
null
null
images/storage/bootstrap.sql
elston/carcassmysql
f4a00361536387a6ed5f3fbb10c585971a593de7
[ "MIT" ]
null
null
null
-- ... CREATE DATABASE IF NOT EXISTS `mediatry` DEFAULT CHARACTER SET utf8 DEFAULT COLLATE utf8_general_ci; -- ... CREATE USER 'mark'@'%' IDENTIFIED BY 'zuckerberg'; GRANT ALL ON `mediatry`.* TO 'mark'@'%'; -- ... FLUSH PRIVILEGES; -- mysql -h 127.0.0.1 -P 3306 -u mark -p mediatry
22.153846
50
0.663194
da7bb52a07f492454c696896d48986c9e3950b97
23,269
sql
SQL
src/main/resources/sql/h2/schema/001_schema_create_query.sql
scratchpaws/hellfrog-bot
71b9f3f5d71f7b0f636c3164471caac5c403aa48
[ "MIT" ]
1
2020-02-29T22:39:32.000Z
2020-02-29T22:39:32.000Z
src/main/resources/sql/h2/schema/001_schema_create_query.sql
scratchpaws/hellfrog-bot
71b9f3f5d71f7b0f636c3164471caac5c403aa48
[ "MIT" ]
null
null
null
src/main/resources/sql/h2/schema/001_schema_create_query.sql
scratchpaws/hellfrog-bot
71b9f3f5d71f7b0f636c3164471caac5c403aa48
[ "MIT" ]
null
null
null
---------------------- -- Create new entities ---------------------- -- hellfrog.settings.db.h2.CommonPreferencesDAOImpl -- hellfrog.settings.db.entity.CommonPreference create table common_preferences ( key varchar(60) not null primary key, string_value varchar(64) not null, long_value bigint not null, create_date timestamp not null default sysdate, update_date timestamp not null default sysdate ); comment on table common_preferences is 'Common bot settings'; comment on column common_preferences.KEY is 'Unique settings key'; comment on column common_preferences.string_value is 'Settings string value'; comment on column common_preferences.long_value is 'Settings numeric value'; comment on column common_preferences.create_date is 'Record create date'; comment on column common_preferences.update_date is 'Record update date'; -- hellfrog.settings.db.h2.ServerPreferencesDAOImpl -- hellfrog.settings.db.entity.ServerPreference create table server_preferences ( id bigint not null primary key, server_id bigint not null, key varchar(60) not null, string_value varchar(64) not null, long_value bigint not null, bool_value bigint not null, date_value timestamp not null, create_date timestamp not null default sysdate, update_date timestamp not null default sysdate, constraint uniq_serv_key unique (key, server_id) ); comment on table server_preferences is 'Settings for discord servers'; comment on column server_preferences.id is 'Unique record ID'; comment on column server_preferences.server_id is 'Discord server ID'; comment on column server_preferences.string_value is 'Settings string value'; comment on column server_preferences.long_value is 'Settings numeric value'; comment on column server_preferences.bool_value is 'Settings logical value'; comment on column server_preferences.date_value is 'Settings date and time value'; comment on column server_preferences.create_date is 'Record create date'; comment on column server_preferences.update_date is 'Record update date'; create sequence server_preference_ids start with 1 increment by 50; -- hellfrog.settings.db.h2.VotesDAOImpl -- hellfrog.settings.db.entity.Vote create table active_votes ( id bigint not null primary key, server_id bigint not null, text_chat_id bigint not null, message_id bigint not null default 0, vote_text varchar(2000), has_timer bigint not null default 0, finish_date timestamp, is_exceptional bigint not null default 0, has_default bigint not null default 0, win_threshold bigint not null default 0, create_date timestamp not null default sysdate, update_date timestamp not null default sysdate ); comment on table active_votes is 'Current active voices'; comment on column active_votes.id is 'Unique record ID'; comment on column active_votes.server_id is 'Discord server ID'; comment on column active_votes.text_chat_id is 'Discord text chat ID, what contain vote message'; comment on column active_votes.message_id is 'Discord message ID, what contain vote'; comment on column active_votes.vote_text is 'Voting text'; comment on column active_votes.has_timer is 'A flag indicating the presence of the voting expiration date (0 - no, 1 - yes)'; comment on column active_votes.finish_date is 'The date after which the voting will automatically stop'; comment on column active_votes.is_exceptional is 'A flag indicating that the user can choose only one item in the vote. (0 - no, 1 - yes)'; comment on column active_votes.has_default is 'A flag indicating that the first item in the vote is the default item. (0 - no, 1 - yes)'; comment on column active_votes.win_threshold is 'Numeric threshold for single choice with default vote point and second point'; comment on column active_votes.create_date is 'Record create date'; comment on column active_votes.update_date is 'Record update date'; create sequence active_vote_ids start with 1 increment by 50; -- hellfrog.settings.db.h2.VotesDAOImpl -- hellfrog.settings.db.entity.VotePoint create table vote_points ( id bigint not null primary key, vote_id bigint not null, point_text varchar(2000) not null, unicode_emoji varchar(12), custom_emoji_id bigint, create_date timestamp not null default sysdate, update_date timestamp not null default sysdate, constraint vote_point_fk foreign key (vote_id) references active_votes (id) ); comment on table vote_points is 'Voting points'; comment on column vote_points.id is 'Unique record ID'; comment on column vote_points.vote_id is 'Vote ID from active_votes.id'; comment on column vote_points.point_text is 'Text describing the voting point'; comment on column vote_points.unicode_emoji is 'Reaction for selecting an item from a list of standard Unicode emojis'; comment on column vote_points.custom_emoji_id is 'Reaction for selecting an item from the server''s emoji list (Discord custom emoji ID)'; comment on column vote_points.create_date is 'Record create date'; comment on column vote_points.update_date is 'Record update date'; create sequence vote_point_ids start with 1 increment by 50; -- hellfrog.settings.db.h2.VotesDAOImpl -- hellfrog.settings.db.entity.VoteRoleFilter create table vote_roles ( id bigint not null primary key, vote_id bigint not null, message_id bigint not null default 0, role_id bigint not null, create_date timestamp not null default sysdate, update_date timestamp not null default sysdate, constraint uniq_vote_role unique (vote_id, role_id), constraint vote_role_fk foreign key (vote_id) references active_votes (id) ); comment on table vote_roles is 'Roles of members who can vote'; comment on column vote_roles.id is 'Unique record ID'; comment on column vote_roles.vote_id is 'Vote ID from active_votes.id'; comment on column vote_roles.message_id is 'Discord message ID, what contain vote (indexed)'; comment on column vote_roles.role_id is 'Discord member role ID'; comment on column vote_roles.create_date is 'Record create date'; comment on column vote_roles.update_date is 'Record update date'; create index vote_roles_msg on vote_roles (message_id); create sequence vote_role_ids start with 1 increment by 50; -- hellfrog.settings.db.h2.BotOwnersDAOImpl -- hellfrog.settings.db.entity.BotOwner create table bot_owners ( user_id bigint not null primary key, create_date timestamp not null default sysdate ); comment on table bot_owners is 'Users who can control the bot with the same rights as the creator-owner'; comment on column bot_owners.user_id is 'Discord user ID'; comment on column bot_owners.create_date is 'Record create date'; -- hellfrog.settings.db.h2.UserRightsDAOImpl -- hellfrog.settings.db.entity.UserRight create table user_rights ( id bigint not null primary key, server_id bigint not null, user_id bigint not null, command_prefix varchar(20) not null, create_date timestamp not null default sysdate, constraint uniq_user_right unique (server_id, command_prefix, user_id) ); create index user_right_idx on user_rights (server_id, command_prefix); comment on table user_rights is 'List of members who have access to any commands of the bot'; comment on column user_rights.id is 'Unique record ID'; comment on column user_rights.server_id is 'Discord server ID'; comment on column user_rights.user_id is 'Discord member ID'; comment on column user_rights.command_prefix is 'Bot command prefix'; comment on column user_rights.create_date is 'Record create date'; create sequence user_right_ids start with 1 increment by 50; -- hellfrog.settings.db.h2.RoleRightsDAOImpl -- hellfrog.settings.db.entity.RoleRight create table role_rights ( id bigint not null primary key, server_id bigint not null, role_id bigint not null, command_prefix varchar(20) not null, create_date timestamp not null default sysdate, constraint uniq_role_right unique (server_id, command_prefix, role_id) ); create index role_right_idx on role_rights (server_id, command_prefix); comment on table role_rights is 'List of roles who have access to any commands of the bot'; comment on column role_rights.id is 'Unique record ID'; comment on column role_rights.server_id is 'Discord server ID'; comment on column role_rights.role_id is 'Discord members role ID'; comment on column role_rights.command_prefix is 'Bot command prefix'; comment on column role_rights.create_date is 'Record create date'; create sequence role_right_ids start with 1 increment by 50; -- hellfrog.settings.db.h2.ChannelRightsDAOImpl -- hellfrog.settings.db.entity.ChannelRight create table channel_rights ( id bigint not null primary key, server_id bigint not null, channel_id bigint not null, command_prefix varchar(20) not null, create_date timestamp not null default sysdate, constraint uniq_channel_right unique (server_id, command_prefix, channel_id) ); create index channel_right_idx on channel_rights (server_id, command_prefix); comment on table channel_rights is 'List of server channels where allowed execute any commands of the bot'; comment on column channel_rights.id is 'Unique record ID'; comment on column channel_rights.server_id is 'Discord server ID'; comment on column channel_rights.channel_id is 'Discord channel ID'; comment on column channel_rights.command_prefix is 'Bot command prefix'; comment on column channel_rights.create_date is 'Record create date'; create sequence channel_right_ids start with 1 increment by 50; -- hellfrog.settings.db.h2.ChannelCategoryRightsDAOImpl -- hellfrog.settings.db.entity.CategoryRight create table category_rights ( id bigint not null primary key, server_id bigint not null, category_id bigint not null, command_prefix varchar(20) not null, create_date timestamp not null default sysdate, constraint uniq_category_right unique (server_id, command_prefix, category_id) ); create index category_right_idx on category_rights (server_id, command_prefix); comment on table category_rights is 'List of server channels categories where allowed execute any commands of the bot'; comment on column category_rights.id is 'Unique record ID'; comment on column category_rights.server_id is 'Discord server ID'; comment on column category_rights.category_id is 'Discord channels category ID'; comment on column category_rights.command_prefix is 'Bot command prefix'; comment on column category_rights.create_date is 'Record create date'; create sequence category_right_ids start with 1 increment by 50; -- hellfrog.settings.db.h2.WtfAssignDAOImpl -- hellfrog.settings.db.entity.WtfEntry create table wtf_assigns ( id bigint not null primary key, server_id bigint not null, author_id bigint not null, target_id bigint not null, description varchar(2000), create_date timestamp not null default sysdate, update_date timestamp not null default sysdate, constraint uniq_wft_assign unique (server_id, author_id, target_id) ); comment on table wtf_assigns is 'Comments left by members about other members on the server'; comment on column wtf_assigns.id is 'Unique record ID'; comment on column wtf_assigns.server_id is 'Discord server ID'; comment on column wtf_assigns.author_id is 'Discord member ID by comment author'; comment on column wtf_assigns.target_id is 'Discord member ID by member about whom the comment was written'; comment on column wtf_assigns.description is 'Comment message'; comment on column wtf_assigns.create_date is 'Record create date'; comment on column wtf_assigns.update_date is 'Record update date'; create sequence wtf_assign_ids start with 1 increment by 50; -- hellfrog.settings.db.h2.WtfAssignDAOImpl -- hellfrog.settings.db.entity.WtfEntryAttach create table wtf_assigns_attaches ( id bigint not null primary key, entry_id bigint not null, uri varchar(2000) not null, create_date timestamp not null default sysdate, constraint wtf_attach_fk foreign key (entry_id) references wtf_assigns (id), constraint wtf_assigns_attaches unique (entry_id, uri) ); comment on table wtf_assigns_attaches is 'Attaches for comments that left by members'; comment on column wtf_assigns_attaches.id is 'Unique record ID'; comment on column wtf_assigns_attaches.entry_id is 'Comment ID. See wtf_assigns.id'; comment on column wtf_assigns_attaches.uri is 'Attachment URI'; comment on column wtf_assigns_attaches.create_date is 'Record create date'; create sequence wtf_assigns_attach_ids start with 1 increment by 50; -- hellfrog.settings.db.h2.TotalStatisticDAOImpl -- hellfrog.settings.db.entity.EmojiTotalStatistic create table emoji_total_statistics ( id bigint not null primary key, server_id bigint not null, emoji_id bigint not null, usages_count bigint not null default 0, last_usage timestamp not null default sysdate, create_date timestamp not null default sysdate, update_date timestamp not null default sysdate, constraint uniq_total_emoji_stat unique (server_id, emoji_id) ); comment on table emoji_total_statistics is 'Custom Discord emoji total statistics by servers'; comment on column emoji_total_statistics.id is 'Unique record ID'; comment on column emoji_total_statistics.server_id is 'Discord server ID'; comment on column emoji_total_statistics.emoji_id is 'Discord custom emoji ID'; comment on column emoji_total_statistics.usages_count is 'Custom emoji usages count'; comment on column emoji_total_statistics.last_usage is 'Custom emoji last usage'; comment on column emoji_total_statistics.create_date is 'Record create date'; comment on column emoji_total_statistics.update_date is 'Record update date'; create sequence emoji_total_stat_ids start with 1 increment by 50; -- hellfrog.settings.db.h2.TotalStatisticDAOImpl -- hellfrog.settings.db.entity.TextChannelTotalStatistic create table text_channel_total_stats ( id bigint not null primary key, server_id bigint not null, text_channel_id bigint not null, user_id bigint not null, messages_count bigint not null default 0, last_message_date timestamp not null default sysdate, symbols_count bigint not null default 0, bytes_count bigint not null default 0, create_date timestamp not null default sysdate, update_date timestamp not null default sysdate, constraint uniq_text_channel_total_stat unique (server_id, text_channel_id, user_id) ); comment on table text_channel_total_stats is 'General statistics on messages and members in channels'; comment on column text_channel_total_stats.id is 'Unique record ID'; comment on column text_channel_total_stats.server_id is 'Discord server ID'; comment on column text_channel_total_stats.text_channel_id is 'Discord channel ID'; comment on column text_channel_total_stats.user_id is 'Discord member ID'; comment on column text_channel_total_stats.messages_count is 'Total messages count'; comment on column text_channel_total_stats.last_message_date is 'Last message date by user in channel'; comment on column text_channel_total_stats.symbols_count is 'Total symbols count'; comment on column text_channel_total_stats.bytes_count is 'Total bytes count'; comment on column text_channel_total_stats.create_date is 'Record create date'; comment on column text_channel_total_stats.update_date is 'Record update date'; create sequence text_channel_total_stat_idx start with 1 increment by 50; -- hellfrog.settings.db.h2.AutoPromoteRolesDAOImpl -- hellfrog.settings.db.entity.AutoPromoteConfig create table auto_promote_configs ( id bigint not null primary key, server_id bigint not null, role_id bigint not null, timeout bigint not null default 0, create_date timestamp not null default sysdate, constraint uniq_auto_promote_role_cfg unique (server_id, role_id) ); comment on table auto_promote_configs is 'List of auto-assigned roles'; comment on column auto_promote_configs.id is 'Unique record ID'; comment on column auto_promote_configs.server_id is 'Discord server ID'; comment on column auto_promote_configs.role_id is 'Discord server role ID'; comment on column auto_promote_configs.timeout is 'The time, in seconds, after which all new members are assigned a role'; comment on column auto_promote_configs.create_date is 'Record create date'; create sequence auto_promote_config_idx start with 1 increment by 50; -- hellfrog.settings.db.h2.RoleAssignDAOImpl -- hellfrog.settings.db.entity.RoleAssign create table role_assign_queue ( id bigint not null primary key, server_id bigint not null, user_id bigint not null, role_id bigint not null, assign_date timestamp not null, create_date timestamp not null default sysdate ); create index role_assign_queue_servers on role_assign_queue(server_id); comment on table role_assign_queue is 'A queue of assigned roles for server members'; comment on column role_assign_queue.id is 'Unique record ID'; comment on column role_assign_queue.server_id is 'Discord server ID'; comment on column role_assign_queue.user_id is 'Discord member ID'; comment on column role_assign_queue.role_id is 'Discord server role ID'; comment on column role_assign_queue.assign_date is 'Date and time the specified role was assigned'; comment on column role_assign_queue.create_date is 'Record create date'; create sequence role_assign_queue_idx start with 1 increment by 50; -- hellfrog.settings.db.h2.EntityNameCacheDAOImpl -- hellfrog.settings.db.entity.EntityNameCache create table names_cache ( entity_id bigint not null primary key, entity_name varchar(120) not null, entity_type varchar(30) not null, create_date timestamp not null default sysdate, update_date timestamp not null default sysdate ); comment on table names_cache is 'Discord entity names global cache'; comment on column names_cache.entity_id is 'Discord entity ID'; comment on column names_cache.entity_name is 'Discord entity display name. For users use discrimination name'; comment on column names_cache.entity_type is 'Discord entity type name'; comment on column names_cache.create_date is 'Record create date'; comment on column names_cache.update_date is 'Record update date'; -- hellfrog.settings.db.h2.EntityNameCacheDAOImpl -- hellfrog.settings.db.entity.ServerNameCache create table server_names_cache ( id bigint not null primary key, server_id bigint not null, entity_id bigint not null, entity_name varchar(120) not null, create_date timestamp not null default sysdate, update_date timestamp not null default sysdate, constraint uniq_server_name unique (server_id, entity_id) ); comment on table server_names_cache is 'Discord servers entity display names cache'; comment on column server_names_cache.id is 'Unique record ID'; comment on column server_names_cache.server_id is 'Discord server ID'; comment on column server_names_cache.entity_id is 'Discord entity ID'; comment on column server_names_cache.entity_name is 'Discord entity display name'; comment on column server_names_cache.create_date is 'Record create date'; comment on column server_names_cache.update_date is 'Record update date'; create sequence server_name_cache_idx start with 1 increment by 50; -- hellfrog.settings.db.h2.CommunityControlDAOImpl -- hellfrog.settings.db.entity.CommunityControlSettings create table community_control_settings ( id bigint not null primary key, server_id bigint not null, assign_role_id bigint not null default 0, threshold bigint not null default 0, unicode_emoji varchar(12), custom_emoji_id bigint not null default 0, create_date timestamp not null default sysdate, update_date timestamp not null default sysdate, constraint uniq_community_control unique (server_id) ); comment on table community_control_settings is 'Community users control settings'; comment on column community_control_settings.id is 'Unique record ID'; comment on column community_control_settings.server_id is 'Discord server ID'; comment on column community_control_settings.assign_role_id is 'Role ID that obtained by exceeding the number of reactions'; comment on column community_control_settings.threshold is 'The threshold at which the role is assigned'; comment on column community_control_settings.unicode_emoji is 'Unicode emoji for which the role is assigned'; comment on column community_control_settings.custom_emoji_id is 'Discord custom emoji ID for which the role is assigned'; comment on column community_control_settings.create_date is 'Record create date'; comment on column community_control_settings.update_date is 'Record update date'; create sequence community_control_setting_idx start with 1 increment by 50; -- hellfrog.settings.db.h2.CommunityControlDAOImpl -- hellfrog.settings.db.entity.CommunityControlUser create table community_control_users ( id bigint not null primary key, server_id bigint not null, user_id bigint not null, create_date timestamp not null default sysdate, constraint uniq_community_control_user unique (server_id, user_id) ); create index community_control_users_srv_idx on community_control_users (server_id); comment on table community_control_users is 'User for community control'; comment on column community_control_users.id is 'Unique record ID'; comment on column community_control_users.server_id is 'Discord server ID'; comment on column community_control_users.user_id is 'Discord server member ID'; comment on column community_control_users.create_date is 'Record create date'; create sequence community_control_user_idx start with 1 increment by 50; ----------------------------- -- Schema versions table init ----------------------------- create table schema_versions ( version bigint not null primary key, script_name varchar(120), apply_date timestamp default sysdate, constraint schema_ver_uniq_script unique (script_name) ); comment on table schema_versions is 'A table listing all installed database migration schemes. The current version is the largest version of the script number.'; comment on column schema_versions.version is 'Migration script version number'; comment on column schema_versions.script_name is 'Migration script name'; comment on column schema_versions.apply_date is 'Migration script execution date and time'; -- Current schema version insert into schema_versions (version, script_name) values (1, '001_schema_create_query.sql');
47.294715
161
0.770639
7ab61ee0b233990b607177a3870383585588449f
67
rb
Ruby
lib/iirc/version.rb
awfulcooking/iirc
93950f91af20a0838a677ccc20106ac884d097bd
[ "MIT" ]
null
null
null
lib/iirc/version.rb
awfulcooking/iirc
93950f91af20a0838a677ccc20106ac884d097bd
[ "MIT" ]
null
null
null
lib/iirc/version.rb
awfulcooking/iirc
93950f91af20a0838a677ccc20106ac884d097bd
[ "MIT" ]
null
null
null
# frozen_string_literal: true module IIRC VERSION = "0.6.3" end
11.166667
29
0.716418
8a4010f28a68a837fd53c26b9092ef811882dc41
3,903
rs
Rust
components/engine_traits/src/options.rs
aknuds1/tikv
24ce8e093a8e0051ca6894a149a64f39c5e1d34b
[ "Apache-2.0" ]
null
null
null
components/engine_traits/src/options.rs
aknuds1/tikv
24ce8e093a8e0051ca6894a149a64f39c5e1d34b
[ "Apache-2.0" ]
null
null
null
components/engine_traits/src/options.rs
aknuds1/tikv
24ce8e093a8e0051ca6894a149a64f39c5e1d34b
[ "Apache-2.0" ]
null
null
null
// Copyright 2019 TiKV Project Authors. Licensed under Apache-2.0. use tikv_util::keybuilder::KeyBuilder; use crate::SeekMode; #[derive(Clone)] pub struct ReadOptions {} impl ReadOptions { pub fn new() -> ReadOptions { ReadOptions {} } } impl Default for ReadOptions { fn default() -> ReadOptions { ReadOptions {} } } #[derive(Clone)] pub struct WriteOptions { sync: bool, } impl WriteOptions { pub fn new() -> WriteOptions { WriteOptions { sync: false } } pub fn set_sync(&mut self, sync: bool) { self.sync = sync; } pub fn sync(&self) -> bool { self.sync } } impl Default for WriteOptions { fn default() -> WriteOptions { WriteOptions { sync: false } } } #[derive(Clone)] pub struct CFOptions {} impl CFOptions { pub fn new() -> CFOptions { CFOptions {} } } impl Default for CFOptions { fn default() -> CFOptions { CFOptions {} } } #[derive(Clone)] pub struct IterOptions { pub lower_bound: Option<KeyBuilder>, pub upper_bound: Option<KeyBuilder>, prefix_same_as_start: bool, fill_cache: bool, key_only: bool, seek_mode: SeekMode, } impl IterOptions { pub fn new( lower_bound: Option<KeyBuilder>, upper_bound: Option<KeyBuilder>, fill_cache: bool, ) -> IterOptions { IterOptions { lower_bound, upper_bound, prefix_same_as_start: false, fill_cache, key_only: false, seek_mode: SeekMode::TotalOrder, } } pub fn use_prefix_seek(mut self) -> IterOptions { self.seek_mode = SeekMode::Prefix; self } pub fn total_order_seek_used(&self) -> bool { self.seek_mode == SeekMode::TotalOrder } pub fn set_fill_cache(&mut self, v: bool) { self.fill_cache = v; } pub fn fill_cache(&self) -> bool { self.fill_cache } pub fn set_key_only(&mut self, v: bool) { self.key_only = v; } pub fn key_only(&self) -> bool { self.key_only } pub fn lower_bound(&self) -> Option<&[u8]> { self.lower_bound.as_ref().map(|v| v.as_slice()) } pub fn set_lower_bound(&mut self, bound: &[u8], reserved_prefix_len: usize) { let builder = KeyBuilder::from_slice(bound, reserved_prefix_len, 0); self.lower_bound = Some(builder); } pub fn set_vec_lower_bound(&mut self, bound: Vec<u8>) { self.lower_bound = Some(KeyBuilder::from_vec(bound, 0, 0)); } pub fn set_lower_bound_prefix(&mut self, prefix: &[u8]) { if let Some(ref mut builder) = self.lower_bound { builder.set_prefix(prefix); } } pub fn upper_bound(&self) -> Option<&[u8]> { self.upper_bound.as_ref().map(|v| v.as_slice()) } pub fn set_upper_bound(&mut self, bound: &[u8], reserved_prefix_len: usize) { let builder = KeyBuilder::from_slice(bound, reserved_prefix_len, 0); self.upper_bound = Some(builder); } pub fn set_vec_upper_bound(&mut self, bound: Vec<u8>) { self.upper_bound = Some(KeyBuilder::from_vec(bound, 0, 0)); } pub fn set_upper_bound_prefix(&mut self, prefix: &[u8]) { if let Some(ref mut builder) = self.upper_bound { builder.set_prefix(prefix); } } pub fn set_prefix_same_as_start(&mut self, enable: bool) { self.prefix_same_as_start = enable; } pub fn prefix_same_as_start(&self) -> bool { self.prefix_same_as_start } } impl Default for IterOptions { fn default() -> IterOptions { IterOptions { lower_bound: None, upper_bound: None, prefix_same_as_start: false, fill_cache: false, key_only: false, seek_mode: SeekMode::TotalOrder, } } }
22.824561
81
0.593133
75194e2d57bdf2c7aa5d960e520132bee6bca159
5,104
h
C
System/Library/Frameworks/PhotosUI.framework/PUPhotoStreamRecipientViewController.h
lechium/iOS1351Headers
6bed3dada5ffc20366b27f7f2300a24a48a6284e
[ "MIT" ]
2
2021-11-02T09:23:27.000Z
2022-03-28T08:21:57.000Z
System/Library/Frameworks/PhotosUI.framework/PUPhotoStreamRecipientViewController.h
lechium/iOS1351Headers
6bed3dada5ffc20366b27f7f2300a24a48a6284e
[ "MIT" ]
null
null
null
System/Library/Frameworks/PhotosUI.framework/PUPhotoStreamRecipientViewController.h
lechium/iOS1351Headers
6bed3dada5ffc20366b27f7f2300a24a48a6284e
[ "MIT" ]
1
2022-03-28T08:21:59.000Z
2022-03-28T08:21:59.000Z
/* * This header is generated by classdump-dyld 1.5 * on Wednesday, October 27, 2021 at 3:16:50 PM Mountain Standard Time * Operating System: Version 13.5.1 (Build 17F80) * Image Source: /System/Library/Frameworks/PhotosUI.framework/PhotosUI * classdump-dyld is licensed under GPLv3, Copyright © 2013-2016 by Elias Limneos. Updated by Kevin Bradley. */ #import <PhotosUI/PhotosUI-Structs.h> #import <UIKitCore/UIViewController.h> #import <libobjc.A.dylib/MFContactsSearchConsumer.h> #import <UIKit/UITableViewDataSource.h> #import <UIKit/UITableViewDelegate.h> #import <libobjc.A.dylib/CNContactPickerDelegate.h> #import <UIKit/UIPopoverPresentationControllerDelegate.h> #import <libobjc.A.dylib/MFComposeRecipientTextViewDelegate.h> #import <libobjc.A.dylib/IDSBatchIDQueryControllerDelegate.h> @class UITableView, MFComposeRecipientTextView, UIScrollView, MFContactsSearchManager, MFContactsSearchResultsModel, NSNumber, NSArray, IDSBatchIDQueryController, NSMutableSet, CNContactPickerViewController, CNContactStore, NSString; @interface PUPhotoStreamRecipientViewController : UIViewController <MFContactsSearchConsumer, UITableViewDataSource, UITableViewDelegate, CNContactPickerDelegate, UIPopoverPresentationControllerDelegate, MFComposeRecipientTextViewDelegate, IDSBatchIDQueryControllerDelegate> { UITableView* _searchResultsTable; MFComposeRecipientTextView* _recipientView; UIScrollView* _recipientContainerView; MFContactsSearchManager* _searchManager; MFContactsSearchResultsModel* _searchResultsModel; NSNumber* _currentSearchTaskID; NSArray* _searchResults; IDSBatchIDQueryController* _idsBatchIDQueryController; NSMutableSet* _validPhoneNumbers; BOOL _wasFirstResponder; BOOL _showingContactPicker; CNContactPickerViewController* _contactPickerPresentedController; CGSize _recipientViewSize; double _lastHeight; CNContactStore* _contactStore; id _delegate; double _bottomTableOffset; } @property (nonatomic,readonly) CNContactStore * contactStore; //@synthesize contactStore=_contactStore - In the implementation block @property (assign,nonatomic,__weak) id delegate; //@synthesize delegate=_delegate - In the implementation block @property (nonatomic,readonly) NSArray * recipients; @property (assign,nonatomic) double bottomTableOffset; //@synthesize bottomTableOffset=_bottomTableOffset - In the implementation block @property (readonly) unsigned long long hash; @property (readonly) Class superclass; @property (copy,readonly) NSString * description; @property (copy,readonly) NSString * debugDescription; +(void)recordRecentInvitationRecipient:(id)arg1 displayName:(id)arg2 date:(id)arg3 ; -(void)dealloc; -(id)delegate; -(void)setDelegate:(id)arg1 ; -(NSArray *)recipients; -(CNContactStore *)contactStore; -(id)initWithNibName:(id)arg1 bundle:(id)arg2 ; -(void)viewWillAppear:(BOOL)arg1 ; -(void)viewDidLoad; -(void)viewWillLayoutSubviews; -(void)viewWillTransitionToSize:(CGSize)arg1 withTransitionCoordinator:(id)arg2 ; -(void)viewDidAppear:(BOOL)arg1 ; -(void)prepareForPopoverPresentation:(id)arg1 ; -(void)popoverPresentationControllerDidDismissPopover:(id)arg1 ; -(long long)tableView:(id)arg1 numberOfRowsInSection:(long long)arg2 ; -(id)tableView:(id)arg1 cellForRowAtIndexPath:(id)arg2 ; -(void)tableView:(id)arg1 willDisplayCell:(id)arg2 forRowAtIndexPath:(id)arg3 ; -(void)tableView:(id)arg1 didSelectRowAtIndexPath:(id)arg2 ; -(void)batchQueryController:(id)arg1 updatedDestinationsStatus:(id)arg2 onService:(id)arg3 error:(id)arg4 ; -(void)contactPicker:(id)arg1 didSelectContactProperty:(id)arg2 ; -(void)contactPicker:(id)arg1 didSelectContact:(id)arg2 ; -(void)contactPickerDidCancel:(id)arg1 ; -(id)_searchManager; -(void)composeRecipientViewDidFinishPickingRecipient:(id)arg1 ; -(void)composeRecipientView:(id)arg1 didAddRecipient:(id)arg2 ; -(void)composeRecipientView:(id)arg1 didFinishEnteringAddress:(id)arg2 ; -(void)composeRecipientView:(id)arg1 didRemoveRecipient:(id)arg2 ; -(void)composeRecipientView:(id)arg1 textDidChange:(id)arg2 ; -(void)composeRecipientView:(id)arg1 didChangeSize:(CGSize)arg2 ; -(void)composeRecipientViewRequestAddRecipient:(id)arg1 ; -(void)composeRecipientView:(id)arg1 showPersonCardForAtom:(id)arg2 ; -(id)composeRecipientView:(id)arg1 composeRecipientForAddress:(id)arg2 ; -(void)consumeAutocompleteSearchResults:(id)arg1 taskID:(id)arg2 ; -(void)finishedSearchingForAutocompleteResults; -(void)finishedTaskWithID:(id)arg1 ; -(void)beganNetworkActivity; -(void)endedNetworkActivity; -(void)_dismissContactPicker; -(void)_setSearchResults:(id)arg1 ; -(void)makeRecipientViewFirstResponder; -(void)makeRecipientViewResignFirstResponder; -(void)setBottomTableOffset:(double)arg1 ; -(void)_searchForRecipientWithText:(id)arg1 ; -(id)_selectedNormalizedPhoneForRecipient:(id)arg1 ; -(void)_addRecipientForContact:(id)arg1 address:(id)arg2 kind:(unsigned long long)arg3 ; -(double)bottomTableOffset; @end
51.555556
276
0.789577
646235460cbf34d0f2d77a03681bcb20959337c4
2,681
kt
Kotlin
packages/android/java/util/adhoc-timer.kt
raghavv/mubble
a073cf28dd1f744fca9a24300f25df5fec0bc968
[ "MIT" ]
null
null
null
packages/android/java/util/adhoc-timer.kt
raghavv/mubble
a073cf28dd1f744fca9a24300f25df5fec0bc968
[ "MIT" ]
null
null
null
packages/android/java/util/adhoc-timer.kt
raghavv/mubble
a073cf28dd1f744fca9a24300f25df5fec0bc968
[ "MIT" ]
null
null
null
package util import android.os.Handler import android.os.Looper import core.MubbleLogger import org.jetbrains.anko.info /*------------------------------------------------------------------------------ About : A long lifespan (typically tied to a class lifetime) adHoc timer. Created on : 17/01/18 Author : Raghvendra Varma Copyright (c) 2018 Mubble Networks Private Limited. All rights reserved. -------------------------------------------------------------------------------- This class is not thread safe and is not intended to be. It is used as a timer helper and is always called from the thread that created it TODO ???? Test looper after the thread exits ------------------------------------------------------------------------------*/ /** * * @param * timerName : name of the timer, used for logging * callback : callback function, returns re-run after ms (0 stops the timer) */ class AdhocTimer(timerName: String, callback: () -> Long): MubbleLogger { override val customTag : String = "Adhoc:$timerName" private var scheduledAt : Long = 0L private val logging : Boolean = false private val looper : Looper = Looper.myLooper()!! private val handler : Handler = Handler(looper) private val runnable : Runnable = Runnable { check(looper === Looper.myLooper()) scheduledAt = 0L // Before we run the scheduled task, we mark the old schedule done val msAfter = callback() // If callback has return next schedule time and it did not call tickAfter if (logging) info { "Callback returned $msAfter" } // We will honor the return value only when callback has not explicitly set the timer again if (scheduledAt == 0L) reSchedule(msAfter) } fun tickAfter(ms: Long, overwrite : Boolean = false) { if (logging) info { "Came to tickAfter $ms" } check(looper === Looper.myLooper()) val newScheduledAt = System.currentTimeMillis() + ms // Already scheduled at a earlier time and not supposed to overwrite if (!overwrite && scheduledAt < newScheduledAt) return reSchedule(ms) } fun remove() { check(looper === Looper.myLooper()) if (logging) info { "Came to remove" } reSchedule(0) } private fun reSchedule(ms: Long) { if (scheduledAt > 0L) handler.removeCallbacks(runnable) scheduledAt = if (ms > 0) { if (logging) info { "Rescheduled timer after ${ms/1000} sec. Removed old: ${scheduledAt != 0L}" } handler.postDelayed(runnable, ms) System.currentTimeMillis() + ms } else { if (logging) info { "Not rescheduling timer. Removed old: ${scheduledAt != 0L}" } 0 } } }
30.465909
104
0.612085
1254acdfb7598a2bdb8e01beeaeede891087193b
2,411
h
C
src/FXPlatform/Htn/HtnMethod.h
Bijiazhou/InductorHtn
7abf7a6125fec50c66c02e623108b058eff34947
[ "MIT" ]
13
2019-05-20T23:45:43.000Z
2022-02-02T20:02:38.000Z
src/FXPlatform/Htn/HtnMethod.h
Bijiazhou/InductorHtn
7abf7a6125fec50c66c02e623108b058eff34947
[ "MIT" ]
3
2021-02-09T05:06:45.000Z
2021-04-23T19:50:15.000Z
src/FXPlatform/Htn/HtnMethod.h
Bijiazhou/InductorHtn
7abf7a6125fec50c66c02e623108b058eff34947
[ "MIT" ]
4
2020-09-26T04:11:49.000Z
2022-02-02T20:02:40.000Z
// // HtnMethod.hpp // GameLib // // Created by Eric Zinda on 1/15/19. // Copyright © 2019 Eric Zinda. All rights reserved. // #ifndef HtnMethod_hpp #define HtnMethod_hpp #include <memory> #include <string> #include <vector> class HtnTerm; enum class HtnMethodType { Normal, AllSetOf, AnySetOf }; // Methods are immutable once created // Has a head which is a term, defines all the variables which can be used for deletions and additions // Has a precondition which is a conjunction of goals // Has a list of tasks class HtnMethod { public: HtnMethod(std::shared_ptr<HtnTerm> head, const std::vector<std::shared_ptr<HtnTerm>> &condition, const std::vector<std::shared_ptr<HtnTerm>> &tasks, HtnMethodType methodType, bool isDefault) : m_condition(condition), m_documentOrder(0), m_head(head), m_isDefault(isDefault), m_methodType(methodType), m_tasks(tasks) { } HtnMethod(std::shared_ptr<HtnTerm> head, const std::vector<std::shared_ptr<HtnTerm>> &condition, const std::vector<std::shared_ptr<HtnTerm>> &tasks, HtnMethodType methodType, bool isDefault, int documentOrder) : m_condition(condition), m_documentOrder(documentOrder), m_head(head), m_isDefault(isDefault), m_methodType(methodType), m_tasks(tasks) { } const std::vector<std::shared_ptr<HtnTerm>> &condition() const { return m_condition; } int documentOrder() { return m_documentOrder; } int64_t dynamicSize() { return sizeof(HtnMethod) + (m_condition.size() + m_tasks.size()) * sizeof(std::shared_ptr<HtnTerm>); }; const std::shared_ptr<HtnTerm> head() const { return m_head; } bool isDefault() const { return m_isDefault; } HtnMethodType methodType() const { return m_methodType; } const std::vector<std::shared_ptr<HtnTerm>> tasks() const { return m_tasks; } std::string ToString() const; private: // *** Remember to update dynamicSize() if you change any member variables! std::vector<std::shared_ptr<HtnTerm>> m_condition; int m_documentOrder; // Order they were written down in the document. Monotonically increasing within a method, not guaranteed so outside of the method std::shared_ptr<HtnTerm> m_head; bool m_isDefault; HtnMethodType m_methodType; std::vector<std::shared_ptr<HtnTerm>> m_tasks; }; #endif /* HtnMethod_hpp */
34.442857
215
0.696392
25e7a0d092079f5afb9a3086726735ad51312b8f
372
asm
Assembly
oeis/016/A016204.asm
neoneye/loda-programs
84790877f8e6c2e821b183d2e334d612045d29c0
[ "Apache-2.0" ]
11
2021-08-22T19:44:55.000Z
2022-03-20T16:47:57.000Z
oeis/016/A016204.asm
neoneye/loda-programs
84790877f8e6c2e821b183d2e334d612045d29c0
[ "Apache-2.0" ]
9
2021-08-29T13:15:54.000Z
2022-03-09T19:52:31.000Z
oeis/016/A016204.asm
neoneye/loda-programs
84790877f8e6c2e821b183d2e334d612045d29c0
[ "Apache-2.0" ]
3
2021-08-22T20:56:47.000Z
2021-09-29T06:26:12.000Z
; A016204: Expansion of 1/((1-x)(1-2x)(1-9x)). ; Submitted by Jamie Morken(s1) ; 1,12,115,1050,9481,85392,768655,6918150,62263861,560375772,5043383995,45390460050,408514148641,3676627354152,33089646220135,297806816046750,2680261344551821,24122352101228532,217101168911581075 mov $2,1 lpb $0 sub $0,1 add $1,$2 mul $1,2 mul $2,9 add $2,1 lpe add $1,$2 mov $0,$1
24.8
195
0.733871
74ee7679b81a01405b927f6cfd11fd0a143825f1
10,460
rs
Rust
sf/src/integration.rs
SetTheorist/rust-special-functions
a03ea7f07677a79dc8c80c468e90c6525b64bf96
[ "BSD-3-Clause" ]
1
2021-09-20T15:38:10.000Z
2021-09-20T15:38:10.000Z
sf/src/integration.rs
SetTheorist/rust-special-functions
a03ea7f07677a79dc8c80c468e90c6525b64bf96
[ "BSD-3-Clause" ]
null
null
null
sf/src/integration.rs
SetTheorist/rust-special-functions
a03ea7f07677a79dc8c80c468e90c6525b64bf96
[ "BSD-3-Clause" ]
null
null
null
use crate::traits::*; use sf_hex_float::hexf; use crate::wide::Wide; macro_rules! Wide { ($x:tt) => { hexf!(:2:Wide:$x) } } // Trapezoidal // Erf / Tanh/Sinh ("stretched trapezoidal") // Simpson's // Gaussian &c. // adaptive? (may not need for purposes of spec.fun. implementations) // // extrapolation / sequence acceleration? // TODO: lots of other possibilities, // including returning a lot more information... // allow separate domain & range types? pub trait Integrator<X> { fn domain(&self) -> (X, X); fn integrate<F>(&self, f: F) -> X where F: Fn(X) -> X; } //////////////////////////////////////////////////////////////////////////////// // use trapezoidal rule to integrate on interval [a,b] // will actually evaluate f at n+1 points // non-adaptive, simply computes the sum #[derive(Clone,Copy,Debug,PartialEq)] pub struct Trapezoidal<X> { a: X, b: X, h: X, n: isize, } impl<X:Value> Trapezoidal<X> { pub fn new(a:X, b:X, n:usize) -> Self { let n = (n as isize).max(1); let h = (b - a) / n; Trapezoidal { a, b, h, n } } } impl<X:Value> Integrator<X> for Trapezoidal<X> { fn domain(&self) -> (X, X) { (self.a, self.b) } fn integrate<F:Fn(X)->X>(&self, f: F) -> X { let mut sum: X = (f(self.a) + f(self.b)) / 2; for i in 1..self.n { sum += f(self.a + self.h * i); } sum * self.h } } //////////////////////////////////////////////////////////////////////////////// use crate::trig::{*}; #[derive(Clone,Copy,Debug,PartialEq)] pub struct TanhRule<X> { a: X, b: X, h: X, n: isize, } impl<X:Value> TanhRule<X> { pub fn new(a:X, b:X, n:usize) -> Self { let n = ((n/2) as isize).max(1); let h = X::PI/sf_sqrt(ι(2*n):X); TanhRule { a, b, h, n } } } // TODO: cleanup to allow separate domain & range impl<X:Value+Trig+std::fmt::LowerExp> Integrator<X> for TanhRule<X> { fn domain(&self) -> (X, X) { (self.a, self.b) } fn integrate<F:Fn(X)->X>(&self, f: F) -> X { let mut sum = X::zero; for k in -self.n..(self.n+1) { let t = self.h * k; let xk = (self.b+self.a)/2 + (self.b-self.a)/2 * sf_tanh(t); let wk = (self.b - xk)*(xk - self.a)*2/(self.b - self.a); let fx = f(xk); sum += self.h * wk * fx; } sum } } //////////////////////////////////////////////////////////////////////////////// pub const GAUSS_LAGUERRE_23__MINUS16_XW : [(f64,f64); 23] = [ (0.049002324371591840306,0.22190661574048635538), (0.29530892594874725178,0.32104976470008496016), (0.7536138185285887951545,0.278749135218214369837), (1.426134556419966046761,0.1767533394965254559499), (2.316024117486417130275,0.085768604825166283443), (3.42754777110858566473,0.0323649818240780976858), (4.76620905785530189515,0.0095437317879520212865), (6.338912250703311815804,0.00219727093568472542502), (8.15417901904800412076,3.93148051086767951958e-4), (10.22243803068820728583,5.42468622855624168575e-5), (12.55641426652768159006,5.71056297226460570316e-6), (15.1716583032377972468,4.52274883380842870632e-7), (18.0872778846009670785,2.647475826439460948804e-8), (21.32697136926332214368,1.11999146278270073486e-9), (24.92052829583340470665,3.32778316600523246748e-11), (28.90608392557213166864,6.69403188135392417644e-13), (33.33365389681871113026,8.68586931031147065516e-15), (38.27098189613715205865,6.80879193066501873168e-17), (43.81391104513859513204,2.9392647035826944268e-19), (50.10658055247607312484,6.08154888669877801016e-22), (57.38634001743254160404,4.80417922537747243469e-25), (66.10656201861103391749,9.420868501665319089e-29), (77.43033332285853341849,1.55075461341823859578e-33), ]; pub const GAUSS_LAGUERRE_31__MINUS16_XW : [(f64,f64); 31] = [ (0.036522647328503509959,0.17586432444613712748), (0.220015204475143469789,0.27073761778435636951), (0.56105879494706826401,0.2639569283919817568983), (1.060601768819224091469,0.198584895894565763191), (1.71992834161345682058,0.1210259110847412642397), (2.54074661704199241945,0.060869396028334219468), (3.525219508135736550245,0.0254706998524582723923), (4.675998408487434218708,0.008896965036390985626383), (5.996264962691047116714,0.002595730985026274276425), (7.48978319393148230507,6.31783691684456499381e-4), (9.160964317142089903928,1.2795061355048080865e-4), (11.01494719689333321795,2.148017742901447252543e-5), (13.05769836962850538302,2.97453271841657528127e-6), (15.29613690399742024734,3.37711217487728408601e-7), (17.73829128807945658912,3.12058215642308271185e-8), (20.39349828433968086645,2.32647022458181265871e-9), (23.2726577269908978185,1.384951693641761203694e-10), (26.38856328166026057054,6.5030071504899334265e-12), (29.75633847390790131618,2.37349818522089644885e-13), (33.39402196211773333139,6.61688485881977495e-15), (37.32336994620830752938,1.37946242241157132683e-16), (41.57098404046517325882,2.095524502368928855981e-18), (46.1699442669051471296,2.24586941284345589486e-20), (51.16225909554449008362,1.62999520688889001886e-22), (56.60270492076548931907,7.5946764296094457962e-25), (62.56517947799614396278,2.11406726349682512438e-27), (69.15397796792722441543,3.1771582432328389273e-30), (76.52577385703082299522,2.2153508451285478668e-33), (84.9385629849746199209,5.5912112168394176093e-37), (94.88569604030576919858,3.19008374061398753179e-41), (107.63562348298177751,1.25165427667877407484e-46), ]; /* Mathematica: (though still requires manual editing, afterwards)) With[{alpha = -1/6, n = 41}, hexify[x_] := Module[{s}, s = BaseForm[x, 16] // ToString // StringSplit; If[Length[s] == 2, s[[1]], s[[2]] <> "p" <> s[[1]]]]; getx[r_] := x /. r; roots = Roots[LaguerreL[n, alpha, x] == 0, x] // N[#, 50] &; xs = Map[getx, ({ToRules[roots]} // Flatten)]; wgt[xi_] := {xi, xi Gamma[n + alpha + 1]/(n! (n + 1)^2 LaguerreL[n + 1, alpha, xi]^2)}; xws = Map[wgt, xs]; hexxws = Map[("(Wide!(\"" <> hexify[#[[1]]] <> "\"),Wide!(\"" <>hexify[#[[2]]] <> "\"))") &, xws] ] */ pub const GAUSS_LAGUERRE_41__MINUS16_XW__WIDE: [(Wide,Wide); 41] = [ (Wide!("0.07179609aaa3342e7687d711c4cbe49eb57564f873"),Wide!("0.2413407b4354bcb7cb214f709cad2b3243015102")), (Wide!("0.2ab6f7724cdbc34084b23255c71a54399c57b7dd53"),Wide!("0.3a085a70ef6d62bd72d6a62f356db6bad224eacf")), (Wide!("0.6ce26ab430835a7dc2fc106ab77a5b518b2f7a55f"),Wide!("0.3d67d6abcc4c596ea35a23b23246293f9bf361d2")), (Wide!("0.cdb6c59cbfae273b8bf794622cb7935d8eb10b591"),Wide!("0.3419f444b783ce0e205754dd8c65c8cff59c2892")), (Wide!("1.4d58970b91b12036fade5ad55916dea165fa4b658"),Wide!("0.253d2a2023026a1f151fadcd419dfe5ef9bc1db2")), (Wide!("1.ebf7ea49f0d148288b593897129da9339ed380b6b"),Wide!("0.16dd00cf9c7bc361dd5e31c21996863654d92a3a")), (Wide!("2.a9d0f7a9185e75bf88ee9f4c2855c83acd7b01a08"),Wide!("0.0c2bdf76a8031ef5963938e104d8581e1cdcaea47")), (Wide!("3.872cb29f800e80a0b36b0d56701f1eebc85d9998e"),Wide!("0.05a53a7ceb3d18451240297b449432e5e4b303001")), (Wide!("4.84616c67d0580731865b7034a7af5f3a011a14c5"),Wide!("0.0249786b5e9e1e6a3df149fcb76e8b833cfe9595d")), (Wide!("5.a1d3963523f4223c6f552713178ce378b164f3cb"),Wide!("0.00cf5ad68eb89cb269cc25bffd308055481358011")), (Wide!("6.dff6a8e3bb6cc4df094c33f458abb56567fc6c19"),Wide!("0.0040349a17c2eed10b2fc5b2361b1063d30f19008e")), (Wide!("8.3f4e37e32db9ab7921c72e8064028d6428b7fc3e"),Wide!("0.00115e75774f71f715ab0f5acba52ff428f0d6a739")), (Wide!("9.c06f360d8523dba3c09b921690f49baa1ca087b8"),Wide!("0.0004198d77ce97e13f4e7a8c7e4849f99c8d753f4b7")), (Wide!("b.640174992ed137d4c1665a74d85f3c6695ea63c4"),Wide!("0.0000d7c6eddbffd0509d5cd589947b14a446bfccadc")), (Wide!("d.2ac1664314c5b45a62a2a804d831c467b8fbb9d5"),Wide!("0.0000268d14bff159da1268974499761c53281efa3438")), (Wide!("f.158233485ad49c9ebbdd027a33b92882f8e70041"),Wide!("5.f81f7a11c349310bce144e0d969c0c6e32d3cd4p-6")), (Wide!("11.25302df49602da63194126bb31931f5f235e0be4"),Wide!("c.c69840fb386d045be9ebc480a8b6c1d5e4e173dp-7")), (Wide!("13.5ad3bba5186c0e4c658a629d293c40e5c22d9b5a"),Wide!("1.7891ec8e7c2627c5694acea1b28eae0511fa669p-7")), (Wide!("15.b794cb7f9092cce233d48ecff91505bdf103ede0"),Wide!("2.529b4c045bf7b190af70b98b756d36754fc9264p-8")), (Wide!("18.3cbefb2ff286b8ce6df5069f16a368d938dd06e9"),Wide!("3.20e80d0b08f13583eebb18f12e9dca124f78a87p-9")), (Wide!("1a.ebc6937897294d6410f89b82924f6f0f0f36a4fc"),Wide!("3.934291272d99ecfc107f45e752575557cbd67e5p-10")), (Wide!("1d.c64e932d42b5d8033c686b0ab5a76234a183ada8"),Wide!("3.71f2f1afbe73a802a41343044cc1764809a1bdcp-11")), (Wide!("20.ce3010c0743b2783f7b87012a5e37510155763b2"),Wide!("2.c79be181346eeab368963099052f43892d9f745p-12")), (Wide!("24.058352f9432e02f1eea85d6904c0613bdd9836ad"),Wide!("1.dcf550f72b9af12a7298b1490890819e3fe3f07p-13")), (Wide!("27.6eab23f5cf5f07232ea3788d44152b6b06494fc2"),Wide!("1.07276768f269d122738cad47deafa43e5778d02p-14")), (Wide!("2b.0c63135ba5e7059921af640c05626edfd2fbdf05"),Wide!("7.646862985d06c3c8ec490a810c47826c71c911ep-16")), (Wide!("2e.e1d1a59bf7220fecbbb6698fd57893f569a49110"),Wide!("2.ac9220893ed1c555e316b7b6ef34c8b205694e1p-17")), (Wide!("32.f29fdbbfaf39434b3f780468b0ffc0cede2434ec"),Wide!("c.48a327db79f1766f2fadb0fc8a685f26da74276p-19")), (Wide!("37.431827a372e119d88263ee2f071a55a2afa63b87"),Wide!("2.c0d5c805d0a52ff286c13299b8c83fa9d9be2d2p-20")), (Wide!("3b.d84fead42a22d0b756d8e2998e5724dd7cb342a4"),Wide!("7.8f477f142681919b1d7acfd446abf0b03853579p-22")), (Wide!("40.b86050aa20fbe6cda6b2de4ad2a650a6d180901a"),Wide!("f.8655f24280272a590ae6239209368e793a4c93p-24")), (Wide!("45.eab63339d6a7a2dd75da6c463ac43e90d62aa7f"),Wide!("1.72d3bb81f06612913a6d21dbc3aff80c6c48d8ep-25")), (Wide!("4b.7885cbe80509531697fce770d1485a95b472b1f"),Wide!("1.8481145c6af8f70e0c306a15da219173961c299p-27")), (Wide!("51.6d785763ab44ad58440fa9b8345d2e718e3ea53"),Wide!("1.112d07b0407a95834c1249c7656d47824ea1842p-29")), (Wide!("57.d8bc5b5f724665ffc53c4af5b388ddec6d74460"),Wide!("7.9a724a7dbde95f1253ae2d29db99a64cf7575dep-32")), (Wide!("5e.cec887c2d466096aa4d690337c71aa4b6e0c38f"),Wide!("1.fbc552ab48068052792b5321de6c5f67035dbaep-34")), (Wide!("66.6c7ca33cf7b129298d3d3689979a43279d0cc39"),Wide!("4.586741d5d1299968c7dcd8b7695cf2421d79610p-37")), (Wide!("6e.dd3c587ae8025ce3dd7f0f14de48c6cbc8a2878"),Wide!("4.3d2074257f909cea863be83a2dbab0cae9a5a6fp-40")), (Wide!("78.688ae7ebbcaddd6f8047e67a17bc2e2d26da766"),Wide!("1.67e7236b61d00240f7b89b4503aa532ea5d72b2p-43")), (Wide!("83.975afc69a97ed29f4b86f80258943c4c3141e3b"),Wide!("1.84fd999971cd1e553c0f0f341b633440060136ep-47")), (Wide!("91.ca86297cf7149c28ca594277597dd4d1788edb2"),Wide!("1.75472fe584ff0801849e1a64e3e665deb3c478ep-52")), ];
49.809524
110
0.747897
e78c65abcf5da9ee529395235c0b7720e40e33f5
974
js
JavaScript
src/utils/systemSetting.js
LinkCisss/PC-XTRB
5da37e4136658f7f08cb16bb20d62fa1e8c34852
[ "MIT" ]
null
null
null
src/utils/systemSetting.js
LinkCisss/PC-XTRB
5da37e4136658f7f08cb16bb20d62fa1e8c34852
[ "MIT" ]
null
null
null
src/utils/systemSetting.js
LinkCisss/PC-XTRB
5da37e4136658f7f08cb16bb20d62fa1e8c34852
[ "MIT" ]
null
null
null
/* * 系统设置类 * @description 目前全局代码中还有很多地方没有直接使用该工具函数 * @editor ZhangLei 2021-08-31 * * */ import { fs, AppPath } from "build/platform"; import path from "path"; /* * 获取保存的系统设置 * @description 读取目录和读取文件都用的同步方法 * @editor ZhangLei 2021-08-31 * @return {object | void} 系统设置对象,没有获取到就无返回值 * */ export function getSystemSetting() { const savePath = path.dirname(AppPath); if (fs.existsSync(`${savePath}/path.json`)) { try { const res = fs.readFileSync(`${savePath}/path.json`, "utf8"); const oldSetting = JSON.parse(res); console.log(oldSetting); return oldSetting; } catch (e) { } } } /* * 保存系统设置 * @description 同步保存 * @editor ZhangLei 2021-08-31 * @param {object} newSetting * */ export function saveSystemSetting(newSetting = {}) { const savePath = path.dirname(AppPath); const newSettingStr = JSON.stringify(newSetting); fs.writeFileSync(`${savePath}/path.json`, newSettingStr); }
23.756098
73
0.644764
9bdcc223e26dc6331af1e0ea2bc372a7ce8a26f2
2,601
js
JavaScript
src/components/header/header.js
Corea98/ecommerce-gatsby-strapi
e3318ff4bc6d0cd6c90dcacde895f21c49603ee6
[ "RSA-MD" ]
null
null
null
src/components/header/header.js
Corea98/ecommerce-gatsby-strapi
e3318ff4bc6d0cd6c90dcacde895f21c49603ee6
[ "RSA-MD" ]
null
null
null
src/components/header/header.js
Corea98/ecommerce-gatsby-strapi
e3318ff4bc6d0cd6c90dcacde895f21c49603ee6
[ "RSA-MD" ]
null
null
null
import React from "react" import { Link } from "gatsby" import PropTypes from "prop-types" import { css } from '@emotion/core' import styled from '@emotion/styled' // Hooks import useSearch from '../../hooks/useSearch' // Components import Nav from './nav' const Header = ({ isMobile, NavResponsive, MenuLink, SubMenuItem }) => { // Hooks const { SearchText } = useSearch() return ( <header css={css` background-color: #fafafa; `}> {/* PRIMERA BARRA */} <div className="container" css={css` display: none; @media (min-width: 1100px) { display: flex; justify-content: space-between; align-items: center; padding-top: 10px; margin-bottom: -5px; background-color: inherit; a, p { font-size: 1.3rem; color: black; } } `}> <p>+505 8888 8888</p> <Link to="/">Customer service</Link> </div> {/* BARRA CENTRAL */} <div className="container" css={css` display: none; @media (min-width: 1100px) { display: flex; justify-content: space-between; align-items: center; height: 55px; } `}> {/* BUSCADOR IZQUIERDA */} <SearchText /> {/* LOGO CENTRO */} <Link to="/" css={css` color: black; font-family: 'Lato', sans-serif; text-align: center; font-size: 2.1rem; margin-bottom: 15px; text-transform: uppercase; letter-spacing: 0.3rem; `}>Ecommerce</Link> {/* LOGIN Y CARRITO */} <div css={css` width: 26%; display: flex; justify-content: flex-end; a { font-size: 1.3rem; margin-left: 20px; color: black; &:hover { } } `}> <Link to="/login">Login</Link> <Link to="/cart">Cart</Link> </div> </div> {/* NAV */} <Nav isMobile={ isMobile } NavResponsive={ NavResponsive } MenuLink={ MenuLink } SubMenuItem={ SubMenuItem } /> {/* <div> <h1 > <Link to="/" style={{ color: `white`, textDecoration: `none`, }} > {siteTitle} </Link> </h1> </div> */} </header> )} Header.propTypes = { siteTitle: PropTypes.string, } Header.defaultProps = { siteTitle: ``, } export default Header
20.480315
73
0.477124
83563b8c5bb6a28ec0e1e455576b90468c2b2a7b
15,053
kt
Kotlin
common/src/test/kotlin/net/wuillemin/jds/common/security/client/ClientHttpRequestAuthenticatorJwtTest.kt
twuillemin/jds
1368aad39df7d444db3ad9289479b15d91dc9dd6
[ "Apache-2.0" ]
null
null
null
common/src/test/kotlin/net/wuillemin/jds/common/security/client/ClientHttpRequestAuthenticatorJwtTest.kt
twuillemin/jds
1368aad39df7d444db3ad9289479b15d91dc9dd6
[ "Apache-2.0" ]
null
null
null
common/src/test/kotlin/net/wuillemin/jds/common/security/client/ClientHttpRequestAuthenticatorJwtTest.kt
twuillemin/jds
1368aad39df7d444db3ad9289479b15d91dc9dd6
[ "Apache-2.0" ]
null
null
null
package net.wuillemin.jds.common.security.client import com.fasterxml.jackson.databind.ObjectMapper import com.nhaarman.mockitokotlin2.whenever import net.wuillemin.jds.common.config.CommonProperties import net.wuillemin.jds.common.dto.TokenResponse import net.wuillemin.jds.common.security.JWTConstant.Companion.HTTP_HEADER_AUTHORIZATION import net.wuillemin.jds.common.security.JWTConstant.Companion.HTTP_HEADER_BEARER_PREFIX import net.wuillemin.jds.common.security.ServerReference import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Assertions import org.junit.jupiter.api.Test import org.junit.jupiter.api.extension.ExtendWith import org.mockito.Mockito import org.slf4j.LoggerFactory import org.springframework.http.HttpEntity import org.springframework.http.HttpHeaders import org.springframework.http.HttpMethod.GET import org.springframework.http.HttpMethod.POST import org.springframework.http.MediaType import org.springframework.http.client.ClientHttpRequestInterceptor import org.springframework.test.context.junit.jupiter.SpringExtension import org.springframework.test.web.client.ExpectedCount.once import org.springframework.test.web.client.MockRestServiceServer import org.springframework.test.web.client.match.MockRestRequestMatchers.header import org.springframework.test.web.client.match.MockRestRequestMatchers.method import org.springframework.test.web.client.match.MockRestRequestMatchers.requestTo import org.springframework.test.web.client.response.MockRestResponseCreators.withSuccess import org.springframework.web.client.RestTemplate import java.net.URI import java.time.Instant @ExtendWith(SpringExtension::class) class ClientHttpRequestAuthenticatorJwtTest { private val objectMapper = ObjectMapper() private val logger = LoggerFactory.getLogger(ClientHttpRequestAuthenticatorJwtTest::class.java) @Test fun `JWT Authenticator adds an Authorization header`() { // Properties val properties = Mockito.mock(CommonProperties::class.java) val client = Mockito.mock(CommonProperties.Client::class.java) whenever(client.jwtAuthentications).thenReturn(listOf(CommonProperties.JWTAuthentication(URI.create("http://authserver"), "user", "password", listOf(ServerReference("localhost", 8080))))) whenever(properties.client).thenReturn(client) // Make the authenticator val authenticator = ClientHttpRequestAuthenticatorJwt(properties, logger) // Make the authenticator val interceptor = ClientHttpRequestInterceptor { request, body, execution -> authenticator.addAuthentication(request, body, execution) execution.execute(request, body) } // Make the rest template as a client val restTemplate = RestTemplate() restTemplate.interceptors.add(interceptor) // Mock the external server val mockServer = MockRestServiceServer.bindTo(restTemplate).build() // Mock the authentication server val mockAuthServer = MockRestServiceServer.bindTo(stealRestTemplateFromAuthenticator(authenticator)).build() // First query is for retrieving the token (make an expired token, so next call will be refresh) mockAuthServer.expect(once(), requestTo("http://authserver/login")) .andExpect(method(POST)) .andRespond( withSuccess( objectMapper.writeValueAsString( TokenResponse( "authTokenValue1", Instant.now().minusSeconds(1).epochSecond, "refreshTokenValue1", Instant.now().plusSeconds(6000).epochSecond)), MediaType.APPLICATION_JSON)) // Then we retrieve the data mockServer.expect(once(), requestTo("http://localhost:8080/test")) .andExpect(method(GET)) .andExpect(header(HTTP_HEADER_AUTHORIZATION, HTTP_HEADER_BEARER_PREFIX + "authTokenValue1")) .andRespond(withSuccess("response1", MediaType.TEXT_PLAIN)) // Second query is for retrieving the expired token (make an expired token and refresh, so next call will be full login) mockAuthServer.expect(once(), requestTo("http://authserver/refresh")) .andExpect(method(POST)) .andRespond( withSuccess( objectMapper.writeValueAsString( TokenResponse( "authTokenValue2", Instant.now().minusSeconds(1).epochSecond, "refreshTokenValue2", Instant.now().minusSeconds(1).epochSecond)), MediaType.APPLICATION_JSON)) // Then we retrieve the data mockServer.expect(once(), requestTo("http://localhost:8080/test")) .andExpect(method(GET)) .andExpect(header(HTTP_HEADER_AUTHORIZATION, HTTP_HEADER_BEARER_PREFIX + "authTokenValue2")) .andRespond(withSuccess("response2", MediaType.TEXT_PLAIN)) // Third query is for retrieving a valid token mockAuthServer.expect(once(), requestTo("http://authserver/login")) .andExpect(method(POST)) .andRespond( withSuccess( objectMapper.writeValueAsString( TokenResponse( "authTokenValue3", Instant.now().plusSeconds(600).epochSecond, "refreshTokenValue3", Instant.now().plusSeconds(6000).epochSecond)), MediaType.APPLICATION_JSON)) // Then we retrieve data mockServer.expect(once(), requestTo("http://localhost:8080/test")) .andExpect(method(GET)) .andExpect(header(HTTP_HEADER_AUTHORIZATION, HTTP_HEADER_BEARER_PREFIX + "authTokenValue3")) .andRespond(withSuccess("response3", MediaType.TEXT_PLAIN)) // Fourth query will send another time the valid token mockServer.expect(once(), requestTo("http://localhost:8080/test")) .andExpect(method(GET)) .andExpect(header(HTTP_HEADER_AUTHORIZATION, HTTP_HEADER_BEARER_PREFIX + "authTokenValue3")) .andRespond(withSuccess("response4", MediaType.TEXT_PLAIN)) // Do the query 1 val response1 = restTemplate.getForEntity(URI.create("http://localhost:8080/test"), String::class.java).body assertThat(response1).isNotNull() assertThat(response1).isEqualTo("response1") // Do the query 2 val response2 = restTemplate.getForEntity(URI.create("http://localhost:8080/test"), String::class.java).body assertThat(response2).isNotNull() assertThat(response2).isEqualTo("response2") // Do the query 3 val response3 = restTemplate.getForEntity(URI.create("http://localhost:8080/test"), String::class.java).body assertThat(response3).isNotNull() assertThat(response3).isEqualTo("response3") // Do the query 4 val response4 = restTemplate.getForEntity(URI.create("http://localhost:8080/test"), String::class.java).body assertThat(response4).isNotNull() assertThat(response4).isEqualTo("response4") // Check the server mockServer.verify() } @Test fun `JWT Authenticator overwrites an existing Authorization header`() { // Properties val properties = Mockito.mock(CommonProperties::class.java) val client = Mockito.mock(CommonProperties.Client::class.java) whenever(client.jwtAuthentications).thenReturn(listOf(CommonProperties.JWTAuthentication(URI.create("http://authserver"), "user", "password", listOf(ServerReference("localhost", 8080))))) whenever(properties.client).thenReturn(client) // Make the authenticator val authenticator = ClientHttpRequestAuthenticatorJwt(properties, logger) // Make the authenticator val interceptor = ClientHttpRequestInterceptor { request, body, execution -> authenticator.addAuthentication(request, body, execution) execution.execute(request, body) } // Make the rest template val restTemplate = RestTemplate() restTemplate.interceptors.add(interceptor) // Mock the target server val mockServer = MockRestServiceServer.bindTo(restTemplate).build() // Mock the authentication server val mockAuthServer = MockRestServiceServer.bindTo(stealRestTemplateFromAuthenticator(authenticator)).build() // First query is for retrieving the token mockAuthServer.expect(once(), requestTo("http://authserver/login")) .andExpect(method(POST)) .andRespond( withSuccess( objectMapper.writeValueAsString( TokenResponse( "authTokenValue1", Instant.now().plusSeconds(60).epochSecond, "refreshTokenValue1", Instant.now().plusSeconds(6000).epochSecond)), MediaType.APPLICATION_JSON)) // Then the query to the client mockServer.expect(once(), requestTo("http://localhost:8080/test")) .andExpect(method(GET)) .andExpect(header(HTTP_HEADER_AUTHORIZATION, HTTP_HEADER_BEARER_PREFIX + "authTokenValue1")) .andRespond(withSuccess("response1", MediaType.TEXT_PLAIN)) // Prepare the query val headers = HttpHeaders() headers.setBasicAuth("user", "password") val httpEntity = HttpEntity<Void>(headers) val response = restTemplate .exchange( URI.create("http://localhost:8080/test"), GET, httpEntity, String::class.java) .body assertThat(response).isNotNull() assertThat(response).isEqualTo("response1") // Check the server mockServer.verify() } @Test fun `JWT Authenticator fails if no response is given by the server`() { // Properties val properties = Mockito.mock(CommonProperties::class.java) val client = Mockito.mock(CommonProperties.Client::class.java) whenever(client.jwtAuthentications).thenReturn(listOf(CommonProperties.JWTAuthentication(URI.create("http://authserver"), "user", "password", listOf(ServerReference("localhost", 8080))))) whenever(properties.client).thenReturn(client) // Make the authenticator val authenticator = ClientHttpRequestAuthenticatorJwt(properties, logger) // Make the authenticator val interceptor = ClientHttpRequestInterceptor { request, body, execution -> authenticator.addAuthentication(request, body, execution) execution.execute(request, body) } // Make the rest template val restTemplate = RestTemplate() restTemplate.interceptors.add(interceptor) // Mock the server val mockServer = MockRestServiceServer.bindTo(restTemplate).build() // Mock the authentication server val mockAuthServer = MockRestServiceServer.bindTo(stealRestTemplateFromAuthenticator(authenticator)).build() // First query will not be received (as the token retrieving should fail) mockAuthServer.expect(once(), requestTo("http://authserver/login")) .andExpect(method(POST)) .andRespond(withSuccess("", MediaType.APPLICATION_JSON)) // Second query will be received (but token is expired) mockAuthServer.expect(once(), requestTo("http://authserver/login")) .andExpect(method(POST)) .andRespond( withSuccess( objectMapper.writeValueAsString( TokenResponse( "authTokenValue1", Instant.now().minusSeconds(60).epochSecond, "refreshTokenValue1", Instant.now().plusSeconds(6000).epochSecond)), MediaType.APPLICATION_JSON)) mockServer.expect(once(), requestTo("http://localhost:8080/test")) .andExpect(method(GET)) .andExpect(header(HTTP_HEADER_AUTHORIZATION, HTTP_HEADER_BEARER_PREFIX + "authTokenValue1")) .andRespond(withSuccess("response1", MediaType.TEXT_PLAIN)) // Third query will not be received (as the token refresh should fail) mockAuthServer.expect(once(), requestTo("http://authserver/refresh")) .andExpect(method(POST)) .andRespond(withSuccess("", MediaType.APPLICATION_JSON)) // Fourth query will be received mockAuthServer.expect(once(), requestTo("http://authserver/refresh")) .andExpect(method(POST)) .andRespond( withSuccess( objectMapper.writeValueAsString( TokenResponse( "authTokenValue2", Instant.now().plusSeconds(60).epochSecond, "refreshTokenValue2", Instant.now().plusSeconds(6000).epochSecond)), MediaType.APPLICATION_JSON)) mockServer.expect(once(), requestTo("http://localhost:8080/test")) .andExpect(method(GET)) .andExpect(header(HTTP_HEADER_AUTHORIZATION, HTTP_HEADER_BEARER_PREFIX + "authTokenValue2")) .andRespond(withSuccess("response2", MediaType.TEXT_PLAIN)) // Do the query 1 (that will fail) Assertions.assertThrows(Exception::class.java) { restTemplate.getForEntity(URI.create("http://localhost:8080/test"), String::class.java) } // Do the query 2 (that will have an expired token) val response1 = restTemplate.getForEntity(URI.create("http://localhost:8080/test"), String::class.java).body assertThat(response1).isNotNull() assertThat(response1).isEqualTo("response1") // Do the query 3 (that will fail) Assertions.assertThrows(Exception::class.java) { restTemplate.getForEntity(URI.create("http://localhost:8080/test"), String::class.java) } // Do the query 4 (that will have a good token) val response2 = restTemplate.getForEntity(URI.create("http://localhost:8080/test"), String::class.java).body assertThat(response2).isNotNull() assertThat(response2).isEqualTo("response2") // Check the server mockServer.verify() } private fun stealRestTemplateFromAuthenticator(authenticator: ClientHttpRequestAuthenticatorJwt): RestTemplate { val field = ClientHttpRequestAuthenticatorJwt::class.java.getDeclaredField("restTemplate") field.isAccessible = true val raw = field.get(authenticator) return raw as RestTemplate } }
46.316923
195
0.657344
6c86a1a129deecc9a441b4850280191b05df73d2
460
lua
Lua
utility.lua
salahzar/minetest-planets
5dbea908746a8a4d1fdf9a22f2a1babfbc8266a3
[ "Unlicense" ]
null
null
null
utility.lua
salahzar/minetest-planets
5dbea908746a8a4d1fdf9a22f2a1babfbc8266a3
[ "Unlicense" ]
null
null
null
utility.lua
salahzar/minetest-planets
5dbea908746a8a4d1fdf9a22f2a1babfbc8266a3
[ "Unlicense" ]
null
null
null
function dump(o) if type(o) == 'table' then local s = '{ ' for k, v in pairs(o) do if type(k) ~= 'number' then k = '"' .. k .. '"' end s = s .. '[' .. k .. '] = ' .. dump(v) .. ',' end return s .. '} ' else return tostring(o) end end function interp(s, tab) return (s:gsub('($%b{})', function(w) return tab[w:sub(3, -2)] or w end)) end --print( interp("${name} is ${value}", {name = "foo", value = "bar"}) ) getmetatable("").__mod = interp
25.555556
74
0.517391
98d3629557bf3b37e14d7b0b54269f5add82678a
1,142
html
HTML
src/pages/plp/index.html
vitaliysobur/gtm-demo
7540ef143b8fff68f2e123a6691519cdc8892892
[ "MIT" ]
null
null
null
src/pages/plp/index.html
vitaliysobur/gtm-demo
7540ef143b8fff68f2e123a6691519cdc8892892
[ "MIT" ]
null
null
null
src/pages/plp/index.html
vitaliysobur/gtm-demo
7540ef143b8fff68f2e123a6691519cdc8892892
[ "MIT" ]
1
2021-04-02T15:46:33.000Z
2021-04-02T15:46:33.000Z
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <meta http-equiv="X-UA-Compatible" content="ie=edge" /> <title>The Accessible E Store</title> <link rel="stylesheet" href="../../styles.scss" /> <link rel="stylesheet" href="./plp.scss" /> </head> <body class="page-plp"> <header data-template="global-header"></header> <div data-template="breadcrumb"></div> <div class="container"> <section id="content" class="main-content"> <h1 id="page-title" class="template-heading">Women’s Tops</h1> <div data-template="filters"></div> <div data-template="sort"></div> <div data-template="grid"></div> <div data-template="pagination"></div> </section> <section data-template="carousel"></section> </div> <footer data-template="footer"></footer> <div data-template="modal"></div> <div data-template="construction-modal"></div> <script src="../../scripts.js"></script> <script src="./plp.js"></script> </body> </html>
31.722222
76
0.594571
2f10385d10a160c1a07839c1f9de4853c8d8781b
1,868
php
PHP
tests/Unit/Implementation/Admin/GetTaskTest.php
timint/sveawebpay-php-checkout
ce37af54353e196a123af06b2a26e012f4398741
[ "Apache-2.0" ]
null
null
null
tests/Unit/Implementation/Admin/GetTaskTest.php
timint/sveawebpay-php-checkout
ce37af54353e196a123af06b2a26e012f4398741
[ "Apache-2.0" ]
null
null
null
tests/Unit/Implementation/Admin/GetTaskTest.php
timint/sveawebpay-php-checkout
ce37af54353e196a123af06b2a26e012f4398741
[ "Apache-2.0" ]
null
null
null
<?php namespace Svea\Checkout\Tests\Unit\Implementation\Admin; use Svea\Checkout\Implementation\Admin\GetTask; use Svea\Checkout\Model\Request; use Svea\Checkout\Tests\Unit\TestCase; use Svea\Checkout\Validation\Admin\ValidateGetTaskData; class GetTaskTest extends TestCase { /** * @var ValidateGetTaskData|\PHPUnit_Framework_MockObject_MockObject $validatorMock */ protected $validatorMock; /** * @var GetTask */ protected $getTask; public function setUp() { parent::setUp(); $this->validatorMock = $this->getMockBuilder('\Svea\Checkout\Validation\Admin\ValidateGetTaskData')->getMock(); $this->getTask = new GetTask($this->connectorMock, $this->validatorMock); } public function testPrepareData() { $locationUrl = 'http://webpaypaymentadminapi.test.svea.com/api/v1/queue/1'; $data = ['locationurl' => $locationUrl]; $this->getTask->prepareData($data); $requestModel = $this->getTask->getRequestModel(); $requestModel->getApiUrl(); $this->assertInstanceOf('\Svea\Checkout\Model\Request', $requestModel); $this->assertEquals(Request::METHOD_GET, $requestModel->getMethod()); $this->assertEquals($locationUrl, $requestModel->getApiUrl()); } public function testInvoke() { $fakeResponse = 'Test response!!!'; $this->connectorMock->expects($this->once()) ->method('sendRequest') ->will($this->returnValue(($fakeResponse))); $this->requestModel->setGetMethod(); $this->requestModel->setBody(null); $this->getTask->setRequestModel($this->requestModel); $this->getTask->invoke(); $this->assertEquals($fakeResponse, $this->getTask->getResponseHandler()); } public function testValidate() { $data = ['locationurl' => 'http://webpaypaymentadminapi.test.svea.com/api/v1/queue/1']; $this->validatorMock->expects($this->once()) ->method('validate'); $this->getTask->validateData($data); } }
27.470588
113
0.718951
9340c5b85ebb46cc81e392928f6d388b60c9202a
5,587
swift
Swift
Algorithm-Swift/BinaryTreeTraversal/BinaryTreeTraversal.swift
tracy-e/Algorithm-Swift
896a1faec361cfe057cc37517bbf1c7118f58a1b
[ "MIT" ]
null
null
null
Algorithm-Swift/BinaryTreeTraversal/BinaryTreeTraversal.swift
tracy-e/Algorithm-Swift
896a1faec361cfe057cc37517bbf1c7118f58a1b
[ "MIT" ]
null
null
null
Algorithm-Swift/BinaryTreeTraversal/BinaryTreeTraversal.swift
tracy-e/Algorithm-Swift
896a1faec361cfe057cc37517bbf1c7118f58a1b
[ "MIT" ]
null
null
null
// // BinaryTreeTraversal.swift // Algorithm-Swift // // Created by TracyYih on 2018/6/19. // Copyright © 2018年 TracyYih. All rights reserved. // /*************************************************************************************************** * * 从上往下打印出二叉树的每个节点,同层节点从左至右打印。 * **************************************************************************************************/ class BinaryTreeTraversal { class TreeNode { var val: Int var left: TreeNode? var right: TreeNode? init(_ val: Int) { self.val = val self.left = nil self.right = nil } } class Solution { // 从上到下分层遍历二叉树 func levelTraversal(_ root: TreeNode?) -> [Int] { if let root = root { var queue: [TreeNode] = [root] var result: [Int] = [] while queue.count > 0 { let node = queue.first! queue.remove(at: 0) result.append(node.val) if let left = node.left { queue.append(left) } if let right = node.right { queue.append(right) } } return result } return [] } // 二叉树的前序遍历 func preorderTraversal(_ root: TreeNode?) -> [Int] { if let root = root { var stack: [TreeNode] = [root] var result: [Int] = [] while stack.count > 0 { let node = stack.popLast()! result.append(node.val) if let right = node.right { stack.append(right) } if let left = node.left { stack.append(left) } } return result } return [] } // 二叉树的中序遍历 func inorderTraversal(_ root: TreeNode?) -> [Int] { var node: TreeNode? = root var stack: [TreeNode] = [] var result: [Int] = [] while node != nil || stack.count > 0 { if node != nil { stack.append(node!) node = node!.left } else if stack.count > 0 { node = stack.popLast() result.append(node!.val) node = node!.right } } return result } // 二叉树的后序遍历 func postorderTraversal(_ root: TreeNode?) -> [Int] { var node: TreeNode? = root var stack: [TreeNode] = [] var lastVisitNode: TreeNode? = nil var result: [Int] = [] while node != nil || stack.count > 0 { if node != nil { stack.append(node!) node = node!.left } else { let n = stack.last if n?.right != nil && lastVisitNode?.val != n?.right?.val { node = n?.right } else { let _ = stack.popLast() result.append(n!.val) lastVisitNode = n } } } return result } } } extension BinaryTreeTraversal: Testable { static func tree1() -> TreeNode { let tree = TreeNode(1) tree.left = TreeNode(2) tree.left?.right = TreeNode(3) return tree } static func tree2() -> TreeNode { let tree = TreeNode(8) tree.left = TreeNode(6) tree.right = TreeNode(10) tree.left?.left = TreeNode(5) tree.left?.right = TreeNode(7) tree.right?.left = TreeNode(9) tree.right?.right = TreeNode(11) return tree } static func testLevelTraversal() { let solution = Solution() assert(solution.levelTraversal(nil) == []) assert(solution.levelTraversal(TreeNode(1)) == [1]) assert(solution.levelTraversal(tree1()) == [1, 2, 3]) assert(solution.levelTraversal(tree2()) == [8, 6, 10, 5, 7, 9, 11]) } static func testPreorderTraversal() { let solution = Solution() assert(solution.preorderTraversal(nil) == []) assert(solution.preorderTraversal(TreeNode(1)) == [1]) assert(solution.preorderTraversal(tree1()) == [1, 2, 3]) assert(solution.preorderTraversal(tree2()) == [8, 6, 5, 7, 10, 9, 11]) } static func testInorderTraversal() { let solution = Solution() assert(solution.inorderTraversal(nil) == []) assert(solution.inorderTraversal(TreeNode(1)) == [1]) assert(solution.inorderTraversal(tree1()) == [2, 3, 1]) assert(solution.inorderTraversal(tree2()) == [5, 6, 7, 8, 9, 10, 11]) } static func testPostorderTraversal() { let solution = Solution() assert(solution.postorderTraversal(nil) == []) assert(solution.postorderTraversal(TreeNode(1)) == [1]) assert(solution.postorderTraversal(tree1()) == [3, 2, 1]) assert(solution.postorderTraversal(tree2()) == [5, 7, 6, 9, 11, 10, 8]) } static func runTests() { testLevelTraversal() testPreorderTraversal() testInorderTraversal() testPostorderTraversal() } }
31.564972
100
0.444067
2dabe733540de00661a5626fb8609926a67ce3e5
80,518
rs
Rust
shopify/src/events.rs
dholroyd/third-party-api-clients
9414c4513cb9dc1dbf79843979380d8cc2d8f83b
[ "MIT" ]
15
2021-07-15T18:58:32.000Z
2022-03-04T06:37:27.000Z
shopify/src/events.rs
dholroyd/third-party-api-clients
9414c4513cb9dc1dbf79843979380d8cc2d8f83b
[ "MIT" ]
4
2021-09-13T21:47:42.000Z
2022-03-31T03:30:39.000Z
shopify/src/events.rs
dholroyd/third-party-api-clients
9414c4513cb9dc1dbf79843979380d8cc2d8f83b
[ "MIT" ]
10
2021-08-21T08:15:41.000Z
2022-03-26T02:48:30.000Z
use anyhow::Result; use crate::Client; pub struct Events { pub client: Client, } impl Events { #[doc(hidden)] pub fn new(client: Client) -> Self { Events { client } } /** * Retrieves a list of events. Note: As of version 2019-07, this endpoint implements pagination by using links that are provided in the response header. Sending the page parameter will return an error. To learn more, see Making requests to paginated REST Admin API endpoints. * * This function performs a `GET` to the `/admin/api/2020-01/events.json` endpoint. * * https://shopify.dev/docs/admin-api/rest/reference/events/event#index-2020-01 * * **Parameters:** * * * `limit: &str` -- The number of results to show. * (default: 50, maximum: 250). * * `since_id: &str` -- Show only results after the specified ID. * * `created_at_min: &str` -- Show events created at or after this date and time. (format: 2014-04-25T16:15:47-04:00). * * `created_at_max: &str` -- Show events created at or before this date and time. (format: 2014-04-25T16:15:47-04:00). * * `filter: &str` -- Show events specified in this filter. * * `verb: &str` -- Show events of a certain type. * * `fields: &str` -- Show only certain fields, specified by a comma-separated list of field names. */ pub async fn deprecated_202001_get( &self, limit: &str, since_id: &str, created_at_min: &str, created_at_max: &str, filter: &str, verb: &str, fields: &str, ) -> Result<()> { let mut query_args: Vec<(String, String)> = Default::default(); if !created_at_max.is_empty() { query_args.push(("created_at_max".to_string(), created_at_max.to_string())); } if !created_at_min.is_empty() { query_args.push(("created_at_min".to_string(), created_at_min.to_string())); } if !fields.is_empty() { query_args.push(("fields".to_string(), fields.to_string())); } if !filter.is_empty() { query_args.push(("filter".to_string(), filter.to_string())); } if !limit.is_empty() { query_args.push(("limit".to_string(), limit.to_string())); } if !since_id.is_empty() { query_args.push(("since_id".to_string(), since_id.to_string())); } if !verb.is_empty() { query_args.push(("verb".to_string(), verb.to_string())); } let query_ = serde_urlencoded::to_string(&query_args).unwrap(); let url = format!("/admin/api/2020-01/events.json?{}", query_); self.client.get(&url, None).await } /** * Retrieves a single event by its ID. * * This function performs a `GET` to the `/admin/api/2020-01/events/{event_id}.json` endpoint. * * https://shopify.dev/docs/admin-api/rest/reference/events/event#show-2020-01 * * **Parameters:** * * * `event_id: &str` -- storefront_access_token_id. * * `fields: &str` -- Show only certain fields, specified by a comma-separated list of field names. */ pub async fn deprecated_202001_get_param(&self, event_id: &str, fields: &str) -> Result<()> { let mut query_args: Vec<(String, String)> = Default::default(); if !fields.is_empty() { query_args.push(("fields".to_string(), fields.to_string())); } let query_ = serde_urlencoded::to_string(&query_args).unwrap(); let url = format!( "/admin/api/2020-01/events/{}/json?{}", crate::progenitor_support::encode_path(&event_id.to_string()), query_ ); self.client.get(&url, None).await } /** * Retrieves a count of events. * * This function performs a `GET` to the `/admin/api/2020-01/events/count.json` endpoint. * * https://shopify.dev/docs/admin-api/rest/reference/events/event#count-2020-01 * * **Parameters:** * * * `created_at_min: &str` -- Count only events created at or after this date and time. (format: 2014-04-25T16:15:47-04:00). * * `created_at_max: &str` -- Count only events created at or before this date and time. (format: 2014-04-25T16:15:47-04:00). */ pub async fn deprecated_202001_get_count( &self, created_at_min: &str, created_at_max: &str, ) -> Result<()> { let mut query_args: Vec<(String, String)> = Default::default(); if !created_at_max.is_empty() { query_args.push(("created_at_max".to_string(), created_at_max.to_string())); } if !created_at_min.is_empty() { query_args.push(("created_at_min".to_string(), created_at_min.to_string())); } let query_ = serde_urlencoded::to_string(&query_args).unwrap(); let url = format!("/admin/api/2020-01/events/count.json?{}", query_); self.client.get(&url, None).await } /** * Retrieves a list of events. Note: As of version 2019-07, this endpoint implements pagination by using links that are provided in the response header. Sending the page parameter will return an error. To learn more, see Making requests to paginated REST Admin API endpoints. * * This function performs a `GET` to the `/admin/api/2020-04/events.json` endpoint. * * https://shopify.dev/docs/admin-api/rest/reference/events/event#index-2020-04 * * **Parameters:** * * * `limit: &str` -- The number of results to show. * (default: 50, maximum: 250). * * `since_id: &str` -- Show only results after the specified ID. * * `created_at_min: &str` -- Show events created at or after this date and time. (format: 2014-04-25T16:15:47-04:00). * * `created_at_max: &str` -- Show events created at or before this date and time. (format: 2014-04-25T16:15:47-04:00). * * `filter: &str` -- Show events specified in this filter. * * `verb: &str` -- Show events of a certain type. * * `fields: &str` -- Show only certain fields, specified by a comma-separated list of field names. */ pub async fn deprecated_202004_get( &self, limit: &str, since_id: &str, created_at_min: &str, created_at_max: &str, filter: &str, verb: &str, fields: &str, ) -> Result<()> { let mut query_args: Vec<(String, String)> = Default::default(); if !created_at_max.is_empty() { query_args.push(("created_at_max".to_string(), created_at_max.to_string())); } if !created_at_min.is_empty() { query_args.push(("created_at_min".to_string(), created_at_min.to_string())); } if !fields.is_empty() { query_args.push(("fields".to_string(), fields.to_string())); } if !filter.is_empty() { query_args.push(("filter".to_string(), filter.to_string())); } if !limit.is_empty() { query_args.push(("limit".to_string(), limit.to_string())); } if !since_id.is_empty() { query_args.push(("since_id".to_string(), since_id.to_string())); } if !verb.is_empty() { query_args.push(("verb".to_string(), verb.to_string())); } let query_ = serde_urlencoded::to_string(&query_args).unwrap(); let url = format!("/admin/api/2020-04/events.json?{}", query_); self.client.get(&url, None).await } /** * Retrieves a single event by its ID. * * This function performs a `GET` to the `/admin/api/2020-04/events/{event_id}.json` endpoint. * * https://shopify.dev/docs/admin-api/rest/reference/events/event#show-2020-04 * * **Parameters:** * * * `event_id: &str` -- storefront_access_token_id. * * `fields: &str` -- Show only certain fields, specified by a comma-separated list of field names. */ pub async fn deprecated_202004_get_param(&self, event_id: &str, fields: &str) -> Result<()> { let mut query_args: Vec<(String, String)> = Default::default(); if !fields.is_empty() { query_args.push(("fields".to_string(), fields.to_string())); } let query_ = serde_urlencoded::to_string(&query_args).unwrap(); let url = format!( "/admin/api/2020-04/events/{}/json?{}", crate::progenitor_support::encode_path(&event_id.to_string()), query_ ); self.client.get(&url, None).await } /** * Retrieves a count of events. * * This function performs a `GET` to the `/admin/api/2020-04/events/count.json` endpoint. * * https://shopify.dev/docs/admin-api/rest/reference/events/event#count-2020-04 * * **Parameters:** * * * `created_at_min: &str` -- Count only events created at or after this date and time. (format: 2014-04-25T16:15:47-04:00). * * `created_at_max: &str` -- Count only events created at or before this date and time. (format: 2014-04-25T16:15:47-04:00). */ pub async fn deprecated_202004_get_count( &self, created_at_min: &str, created_at_max: &str, ) -> Result<()> { let mut query_args: Vec<(String, String)> = Default::default(); if !created_at_max.is_empty() { query_args.push(("created_at_max".to_string(), created_at_max.to_string())); } if !created_at_min.is_empty() { query_args.push(("created_at_min".to_string(), created_at_min.to_string())); } let query_ = serde_urlencoded::to_string(&query_args).unwrap(); let url = format!("/admin/api/2020-04/events/count.json?{}", query_); self.client.get(&url, None).await } /** * Retrieves a list of events. Note: As of version 2019-07, this endpoint implements pagination by using links that are provided in the response header. Sending the page parameter will return an error. To learn more, see Making requests to paginated REST Admin API endpoints. * * This function performs a `GET` to the `/admin/api/2020-07/events.json` endpoint. * * https://shopify.dev/docs/admin-api/rest/reference/events/event#index-2020-07 * * **Parameters:** * * * `limit: &str` -- The number of results to show. * (default: 50, maximum: 250). * * `since_id: &str` -- Show only results after the specified ID. * * `created_at_min: &str` -- Show events created at or after this date and time. (format: 2014-04-25T16:15:47-04:00). * * `created_at_max: &str` -- Show events created at or before this date and time. (format: 2014-04-25T16:15:47-04:00). * * `filter: &str` -- Show events specified in this filter. * * `verb: &str` -- Show events of a certain type. * * `fields: &str` -- Show only certain fields, specified by a comma-separated list of field names. */ pub async fn deprecated_202007_get( &self, limit: &str, since_id: &str, created_at_min: &str, created_at_max: &str, filter: &str, verb: &str, fields: &str, ) -> Result<()> { let mut query_args: Vec<(String, String)> = Default::default(); if !created_at_max.is_empty() { query_args.push(("created_at_max".to_string(), created_at_max.to_string())); } if !created_at_min.is_empty() { query_args.push(("created_at_min".to_string(), created_at_min.to_string())); } if !fields.is_empty() { query_args.push(("fields".to_string(), fields.to_string())); } if !filter.is_empty() { query_args.push(("filter".to_string(), filter.to_string())); } if !limit.is_empty() { query_args.push(("limit".to_string(), limit.to_string())); } if !since_id.is_empty() { query_args.push(("since_id".to_string(), since_id.to_string())); } if !verb.is_empty() { query_args.push(("verb".to_string(), verb.to_string())); } let query_ = serde_urlencoded::to_string(&query_args).unwrap(); let url = format!("/admin/api/2020-07/events.json?{}", query_); self.client.get(&url, None).await } /** * Retrieves a single event by its ID. * * This function performs a `GET` to the `/admin/api/2020-07/events/{event_id}.json` endpoint. * * https://shopify.dev/docs/admin-api/rest/reference/events/event#show-2020-07 * * **Parameters:** * * * `event_id: &str` -- storefront_access_token_id. * * `fields: &str` -- Show only certain fields, specified by a comma-separated list of field names. */ pub async fn deprecated_202007_get_param(&self, event_id: &str, fields: &str) -> Result<()> { let mut query_args: Vec<(String, String)> = Default::default(); if !fields.is_empty() { query_args.push(("fields".to_string(), fields.to_string())); } let query_ = serde_urlencoded::to_string(&query_args).unwrap(); let url = format!( "/admin/api/2020-07/events/{}/json?{}", crate::progenitor_support::encode_path(&event_id.to_string()), query_ ); self.client.get(&url, None).await } /** * Retrieves a count of events. * * This function performs a `GET` to the `/admin/api/2020-07/events/count.json` endpoint. * * https://shopify.dev/docs/admin-api/rest/reference/events/event#count-2020-07 * * **Parameters:** * * * `created_at_min: &str` -- Count only events created at or after this date and time. (format: 2014-04-25T16:15:47-04:00). * * `created_at_max: &str` -- Count only events created at or before this date and time. (format: 2014-04-25T16:15:47-04:00). */ pub async fn deprecated_202007_get_count( &self, created_at_min: &str, created_at_max: &str, ) -> Result<()> { let mut query_args: Vec<(String, String)> = Default::default(); if !created_at_max.is_empty() { query_args.push(("created_at_max".to_string(), created_at_max.to_string())); } if !created_at_min.is_empty() { query_args.push(("created_at_min".to_string(), created_at_min.to_string())); } let query_ = serde_urlencoded::to_string(&query_args).unwrap(); let url = format!("/admin/api/2020-07/events/count.json?{}", query_); self.client.get(&url, None).await } /** * Retrieves a list of events. Note: As of version 2019-07, this endpoint implements pagination by using links that are provided in the response header. Sending the page parameter will return an error. To learn more, see Making requests to paginated REST Admin API endpoints. * * This function performs a `GET` to the `/admin/api/2020-10/events.json` endpoint. * * https://shopify.dev/docs/admin-api/rest/reference/events/event#index-2020-10 * * **Parameters:** * * * `limit: &str` -- The number of results to show. * (default: 50, maximum: 250). * * `since_id: &str` -- Show only results after the specified ID. * * `created_at_min: &str` -- Show events created at or after this date and time. (format: 2014-04-25T16:15:47-04:00). * * `created_at_max: &str` -- Show events created at or before this date and time. (format: 2014-04-25T16:15:47-04:00). * * `filter: &str` -- Show events specified in this filter. * * `verb: &str` -- Show events of a certain type. * * `fields: &str` -- Show only certain fields, specified by a comma-separated list of field names. */ pub async fn get( &self, limit: &str, since_id: &str, created_at_min: &str, created_at_max: &str, filter: &str, verb: &str, fields: &str, ) -> Result<()> { let mut query_args: Vec<(String, String)> = Default::default(); if !created_at_max.is_empty() { query_args.push(("created_at_max".to_string(), created_at_max.to_string())); } if !created_at_min.is_empty() { query_args.push(("created_at_min".to_string(), created_at_min.to_string())); } if !fields.is_empty() { query_args.push(("fields".to_string(), fields.to_string())); } if !filter.is_empty() { query_args.push(("filter".to_string(), filter.to_string())); } if !limit.is_empty() { query_args.push(("limit".to_string(), limit.to_string())); } if !since_id.is_empty() { query_args.push(("since_id".to_string(), since_id.to_string())); } if !verb.is_empty() { query_args.push(("verb".to_string(), verb.to_string())); } let query_ = serde_urlencoded::to_string(&query_args).unwrap(); let url = format!("/admin/api/2020-10/events.json?{}", query_); self.client.get(&url, None).await } /** * Retrieves a single event by its ID. * * This function performs a `GET` to the `/admin/api/2020-10/events/{event_id}.json` endpoint. * * https://shopify.dev/docs/admin-api/rest/reference/events/event#show-2020-10 * * **Parameters:** * * * `event_id: &str` -- storefront_access_token_id. * * `fields: &str` -- Show only certain fields, specified by a comma-separated list of field names. */ pub async fn get_param(&self, event_id: &str, fields: &str) -> Result<()> { let mut query_args: Vec<(String, String)> = Default::default(); if !fields.is_empty() { query_args.push(("fields".to_string(), fields.to_string())); } let query_ = serde_urlencoded::to_string(&query_args).unwrap(); let url = format!( "/admin/api/2020-10/events/{}/json?{}", crate::progenitor_support::encode_path(&event_id.to_string()), query_ ); self.client.get(&url, None).await } /** * Retrieves a count of events. * * This function performs a `GET` to the `/admin/api/2020-10/events/count.json` endpoint. * * https://shopify.dev/docs/admin-api/rest/reference/events/event#count-2020-10 * * **Parameters:** * * * `created_at_min: &str` -- Count only events created at or after this date and time. (format: 2014-04-25T16:15:47-04:00). * * `created_at_max: &str` -- Count only events created at or before this date and time. (format: 2014-04-25T16:15:47-04:00). */ pub async fn get_count(&self, created_at_min: &str, created_at_max: &str) -> Result<()> { let mut query_args: Vec<(String, String)> = Default::default(); if !created_at_max.is_empty() { query_args.push(("created_at_max".to_string(), created_at_max.to_string())); } if !created_at_min.is_empty() { query_args.push(("created_at_min".to_string(), created_at_min.to_string())); } let query_ = serde_urlencoded::to_string(&query_args).unwrap(); let url = format!("/admin/api/2020-10/events/count.json?{}", query_); self.client.get(&url, None).await } /** * Retrieves a list of events. Note: As of version 2019-07, this endpoint implements pagination by using links that are provided in the response header. Sending the page parameter will return an error. To learn more, see Making requests to paginated REST Admin API endpoints. * * This function performs a `GET` to the `/admin/api/2021-01/events.json` endpoint. * * https://shopify.dev/docs/admin-api/rest/reference/events/event#index-2021-01 * * **Parameters:** * * * `limit: &str` -- The number of results to show. * (default: 50, maximum: 250). * * `since_id: &str` -- Show only results after the specified ID. * * `created_at_min: &str` -- Show events created at or after this date and time. (format: 2014-04-25T16:15:47-04:00). * * `created_at_max: &str` -- Show events created at or before this date and time. (format: 2014-04-25T16:15:47-04:00). * * `filter: &str` -- Show events specified in this filter. * * `verb: &str` -- Show events of a certain type. * * `fields: &str` -- Show only certain fields, specified by a comma-separated list of field names. */ pub async fn deprecated_202101_get( &self, limit: &str, since_id: &str, created_at_min: &str, created_at_max: &str, filter: &str, verb: &str, fields: &str, ) -> Result<()> { let mut query_args: Vec<(String, String)> = Default::default(); if !created_at_max.is_empty() { query_args.push(("created_at_max".to_string(), created_at_max.to_string())); } if !created_at_min.is_empty() { query_args.push(("created_at_min".to_string(), created_at_min.to_string())); } if !fields.is_empty() { query_args.push(("fields".to_string(), fields.to_string())); } if !filter.is_empty() { query_args.push(("filter".to_string(), filter.to_string())); } if !limit.is_empty() { query_args.push(("limit".to_string(), limit.to_string())); } if !since_id.is_empty() { query_args.push(("since_id".to_string(), since_id.to_string())); } if !verb.is_empty() { query_args.push(("verb".to_string(), verb.to_string())); } let query_ = serde_urlencoded::to_string(&query_args).unwrap(); let url = format!("/admin/api/2021-01/events.json?{}", query_); self.client.get(&url, None).await } /** * Retrieves a single event by its ID. * * This function performs a `GET` to the `/admin/api/2021-01/events/{event_id}.json` endpoint. * * https://shopify.dev/docs/admin-api/rest/reference/events/event#show-2021-01 * * **Parameters:** * * * `event_id: &str` -- storefront_access_token_id. * * `fields: &str` -- Show only certain fields, specified by a comma-separated list of field names. */ pub async fn deprecated_202101_get_param(&self, event_id: &str, fields: &str) -> Result<()> { let mut query_args: Vec<(String, String)> = Default::default(); if !fields.is_empty() { query_args.push(("fields".to_string(), fields.to_string())); } let query_ = serde_urlencoded::to_string(&query_args).unwrap(); let url = format!( "/admin/api/2021-01/events/{}/json?{}", crate::progenitor_support::encode_path(&event_id.to_string()), query_ ); self.client.get(&url, None).await } /** * Retrieves a count of events. * * This function performs a `GET` to the `/admin/api/2021-01/events/count.json` endpoint. * * https://shopify.dev/docs/admin-api/rest/reference/events/event#count-2021-01 * * **Parameters:** * * * `created_at_min: &str` -- Count only events created at or after this date and time. (format: 2014-04-25T16:15:47-04:00). * * `created_at_max: &str` -- Count only events created at or before this date and time. (format: 2014-04-25T16:15:47-04:00). */ pub async fn deprecated_202101_get_count( &self, created_at_min: &str, created_at_max: &str, ) -> Result<()> { let mut query_args: Vec<(String, String)> = Default::default(); if !created_at_max.is_empty() { query_args.push(("created_at_max".to_string(), created_at_max.to_string())); } if !created_at_min.is_empty() { query_args.push(("created_at_min".to_string(), created_at_min.to_string())); } let query_ = serde_urlencoded::to_string(&query_args).unwrap(); let url = format!("/admin/api/2021-01/events/count.json?{}", query_); self.client.get(&url, None).await } /** * Retrieves a list of events. Note: As of version 2019-07, this endpoint implements pagination by using links that are provided in the response header. Sending the page parameter will return an error. To learn more, see Making requests to paginated REST Admin API endpoints. * * This function performs a `GET` to the `/admin/api/unstable/events.json` endpoint. * * https://shopify.dev/docs/admin-api/rest/reference/events/event#index-unstable * * **Parameters:** * * * `limit: &str` -- The number of results to show. * (default: 50, maximum: 250). * * `since_id: &str` -- Show only results after the specified ID. * * `created_at_min: &str` -- Show events created at or after this date and time. (format: 2014-04-25T16:15:47-04:00). * * `created_at_max: &str` -- Show events created at or before this date and time. (format: 2014-04-25T16:15:47-04:00). * * `filter: &str` -- Show events specified in this filter. * * `verb: &str` -- Show events of a certain type. * * `fields: &str` -- Show only certain fields, specified by a comma-separated list of field names. */ pub async fn deprecated_unstable_get( &self, limit: &str, since_id: &str, created_at_min: &str, created_at_max: &str, filter: &str, verb: &str, fields: &str, ) -> Result<()> { let mut query_args: Vec<(String, String)> = Default::default(); if !created_at_max.is_empty() { query_args.push(("created_at_max".to_string(), created_at_max.to_string())); } if !created_at_min.is_empty() { query_args.push(("created_at_min".to_string(), created_at_min.to_string())); } if !fields.is_empty() { query_args.push(("fields".to_string(), fields.to_string())); } if !filter.is_empty() { query_args.push(("filter".to_string(), filter.to_string())); } if !limit.is_empty() { query_args.push(("limit".to_string(), limit.to_string())); } if !since_id.is_empty() { query_args.push(("since_id".to_string(), since_id.to_string())); } if !verb.is_empty() { query_args.push(("verb".to_string(), verb.to_string())); } let query_ = serde_urlencoded::to_string(&query_args).unwrap(); let url = format!("/admin/api/unstable/events.json?{}", query_); self.client.get(&url, None).await } /** * Retrieves a single event by its ID. * * This function performs a `GET` to the `/admin/api/unstable/events/{event_id}.json` endpoint. * * https://shopify.dev/docs/admin-api/rest/reference/events/event#show-unstable * * **Parameters:** * * * `event_id: &str` -- storefront_access_token_id. * * `fields: &str` -- Show only certain fields, specified by a comma-separated list of field names. */ pub async fn deprecated_unstable_get_param(&self, event_id: &str, fields: &str) -> Result<()> { let mut query_args: Vec<(String, String)> = Default::default(); if !fields.is_empty() { query_args.push(("fields".to_string(), fields.to_string())); } let query_ = serde_urlencoded::to_string(&query_args).unwrap(); let url = format!( "/admin/api/unstable/events/{}/json?{}", crate::progenitor_support::encode_path(&event_id.to_string()), query_ ); self.client.get(&url, None).await } /** * Retrieves a count of events. * * This function performs a `GET` to the `/admin/api/unstable/events/count.json` endpoint. * * https://shopify.dev/docs/admin-api/rest/reference/events/event#count-unstable * * **Parameters:** * * * `created_at_min: &str` -- Count only events created at or after this date and time. (format: 2014-04-25T16:15:47-04:00). * * `created_at_max: &str` -- Count only events created at or before this date and time. (format: 2014-04-25T16:15:47-04:00). */ pub async fn deprecated_unstable_get_count( &self, created_at_min: &str, created_at_max: &str, ) -> Result<()> { let mut query_args: Vec<(String, String)> = Default::default(); if !created_at_max.is_empty() { query_args.push(("created_at_max".to_string(), created_at_max.to_string())); } if !created_at_min.is_empty() { query_args.push(("created_at_min".to_string(), created_at_min.to_string())); } let query_ = serde_urlencoded::to_string(&query_args).unwrap(); let url = format!("/admin/api/unstable/events/count.json?{}", query_); self.client.get(&url, None).await } /** * Retrieves a list of webhooks. Note: As of version 2019-10, this endpoint implements pagination by using links that are provided in the response header. To learn more, see Making requests to paginated REST Admin API endpoints. * * This function performs a `GET` to the `/admin/api/2020-01/webhooks.json` endpoint. * * https://shopify.dev/docs/admin-api/rest/reference/events/webhook#index-2020-01 * * **Parameters:** * * * `address: &str` -- Retrieve webhook subscriptions that send the POST request to this URI. * * `created_at_max: &str` -- Retrieve webhook subscriptions that were created before a given date and time (format: 2014-04-25T16:15:47-04:00). * * `created_at_min: &str` -- Retrieve webhook subscriptions that were created after a given date and time (format: 2014-04-25T16:15:47-04:00). * * `fields: &str` -- Comma-separated list of the properties you want returned for each item in the result list. Use this parameter to restrict the returned list of items to only those properties you specify. * * `limit: &str` -- Maximum number of webhook subscriptions that should be returned. Setting this parameter outside the maximum range will return an error. * (default: 50, maximum: 250). * * `since_id: &str` -- Restrict the returned list to webhook subscriptions whose id is greater than the specified since_id. * * `topic: &str` -- Show webhook subscriptions with a given topic. * For a list of valid values, refer to the topic property.>. * * `updated_at_min: &str` -- Retrieve webhooks that were updated before a given date and time (format: 2014-04-25T16:15:47-04:00). * * `updated_at_max: &str` -- Retrieve webhooks that were updated after a given date and time (format: 2014-04-25T16:15:47-04:00). */ pub async fn deprecated_202001_get_webhook( &self, address: &str, created_at_max: &str, created_at_min: &str, fields: &str, limit: &str, since_id: &str, topic: &str, updated_at_min: &str, updated_at_max: &str, ) -> Result<()> { let mut query_args: Vec<(String, String)> = Default::default(); if !address.is_empty() { query_args.push(("address".to_string(), address.to_string())); } if !created_at_max.is_empty() { query_args.push(("created_at_max".to_string(), created_at_max.to_string())); } if !created_at_min.is_empty() { query_args.push(("created_at_min".to_string(), created_at_min.to_string())); } if !fields.is_empty() { query_args.push(("fields".to_string(), fields.to_string())); } if !limit.is_empty() { query_args.push(("limit".to_string(), limit.to_string())); } if !since_id.is_empty() { query_args.push(("since_id".to_string(), since_id.to_string())); } if !topic.is_empty() { query_args.push(("topic".to_string(), topic.to_string())); } if !updated_at_max.is_empty() { query_args.push(("updated_at_max".to_string(), updated_at_max.to_string())); } if !updated_at_min.is_empty() { query_args.push(("updated_at_min".to_string(), updated_at_min.to_string())); } let query_ = serde_urlencoded::to_string(&query_args).unwrap(); let url = format!("/admin/api/2020-01/webhooks.json?{}", query_); self.client.get(&url, None).await } /** * Create a new webhook subscription by specifying both an address and a topic. * * This function performs a `POST` to the `/admin/api/2020-01/webhooks.json` endpoint. * * https://shopify.dev/docs/admin-api/rest/reference/events/webhook#create-2020-01 * * **Parameters:** * * * `format: &str` -- Use this parameter to select the data format for the payload. Valid values are json and xml. * (default: json). */ pub async fn deprecated_202001_create_webhooks( &self, format: &str, body: &serde_json::Value, ) -> Result<()> { let mut query_args: Vec<(String, String)> = Default::default(); if !format.is_empty() { query_args.push(("format".to_string(), format.to_string())); } let query_ = serde_urlencoded::to_string(&query_args).unwrap(); let url = format!("/admin/api/2020-01/webhooks.json?{}", query_); self.client .post(&url, Some(reqwest::Body::from(serde_json::to_vec(body)?))) .await } /** * Retrieves a count of existing webhook subscriptions. * * This function performs a `GET` to the `/admin/api/2020-01/webhooks/count.json` endpoint. * * https://shopify.dev/docs/admin-api/rest/reference/events/webhook#count-2020-01 * * **Parameters:** * * * `address: &str` -- Retrieve webhook subscriptions that send the POST request to this URI. * * `topic: &str` -- Show webhook subscriptions with a given topic. * For a list of valid values, refer to the topic property.>. */ pub async fn deprecated_202001_get_webhooks_count( &self, address: &str, topic: &str, ) -> Result<()> { let mut query_args: Vec<(String, String)> = Default::default(); if !address.is_empty() { query_args.push(("address".to_string(), address.to_string())); } if !topic.is_empty() { query_args.push(("topic".to_string(), topic.to_string())); } let query_ = serde_urlencoded::to_string(&query_args).unwrap(); let url = format!("/admin/api/2020-01/webhooks/count.json?{}", query_); self.client.get(&url, None).await } /** * Retrieves a single webhook subscription. * * This function performs a `GET` to the `/admin/api/2020-01/webhooks/{webhook_id}.json` endpoint. * * https://shopify.dev/docs/admin-api/rest/reference/events/webhook#show-2020-01 * * **Parameters:** * * * `webhook_id: &str` -- storefront_access_token_id. * * `fields: &str` -- Comma-separated list of the properties you want returned for each item in the result list. Use this parameter to restrict the returned list of items to only those properties you specify. */ pub async fn deprecated_202001_get_webhooks_param_webhook( &self, webhook_id: &str, fields: &str, ) -> Result<()> { let mut query_args: Vec<(String, String)> = Default::default(); if !fields.is_empty() { query_args.push(("fields".to_string(), fields.to_string())); } let query_ = serde_urlencoded::to_string(&query_args).unwrap(); let url = format!( "/admin/api/2020-01/webhooks/{}/json?{}", crate::progenitor_support::encode_path(&webhook_id.to_string()), query_ ); self.client.get(&url, None).await } /** * Update a webhook subscription's topic or address URIs. * * This function performs a `PUT` to the `/admin/api/2020-01/webhooks/{webhook_id}.json` endpoint. * * https://shopify.dev/docs/admin-api/rest/reference/events/webhook#update-2020-01 * * **Parameters:** * * * `webhook_id: &str` -- storefront_access_token_id. */ pub async fn deprecated_202001_update_webhooks_param_webhook( &self, webhook_id: &str, body: &serde_json::Value, ) -> Result<()> { let url = format!( "/admin/api/2020-01/webhooks/{}/json", crate::progenitor_support::encode_path(&webhook_id.to_string()), ); self.client .put(&url, Some(reqwest::Body::from(serde_json::to_vec(body)?))) .await } /** * Delete a webhook subscription. * * This function performs a `DELETE` to the `/admin/api/2020-01/webhooks/{webhook_id}.json` endpoint. * * https://shopify.dev/docs/admin-api/rest/reference/events/webhook#destroy-2020-01 * * **Parameters:** * * * `webhook_id: &str` -- storefront_access_token_id. */ pub async fn deprecated_202001_delete_webhooks_param_webhook( &self, webhook_id: &str, ) -> Result<()> { let url = format!( "/admin/api/2020-01/webhooks/{}/json", crate::progenitor_support::encode_path(&webhook_id.to_string()), ); self.client.delete(&url, None).await } /** * Retrieves a list of webhooks. Note: As of version 2019-10, this endpoint implements pagination by using links that are provided in the response header. To learn more, see Making requests to paginated REST Admin API endpoints. * * This function performs a `GET` to the `/admin/api/2020-04/webhooks.json` endpoint. * * https://shopify.dev/docs/admin-api/rest/reference/events/webhook#index-2020-04 * * **Parameters:** * * * `address: &str` -- Retrieve webhook subscriptions that send the POST request to this URI. * * `created_at_max: &str` -- Retrieve webhook subscriptions that were created before a given date and time (format: 2014-04-25T16:15:47-04:00). * * `created_at_min: &str` -- Retrieve webhook subscriptions that were created after a given date and time (format: 2014-04-25T16:15:47-04:00). * * `fields: &str` -- Comma-separated list of the properties you want returned for each item in the result list. Use this parameter to restrict the returned list of items to only those properties you specify. * * `limit: &str` -- Maximum number of webhook subscriptions that should be returned. Setting this parameter outside the maximum range will return an error. * (default: 50, maximum: 250). * * `since_id: &str` -- Restrict the returned list to webhook subscriptions whose id is greater than the specified since_id. * * `topic: &str` -- Show webhook subscriptions with a given topic. * For a list of valid values, refer to the topic property.>. * * `updated_at_min: &str` -- Retrieve webhooks that were updated before a given date and time (format: 2014-04-25T16:15:47-04:00). * * `updated_at_max: &str` -- Retrieve webhooks that were updated after a given date and time (format: 2014-04-25T16:15:47-04:00). */ pub async fn deprecated_202004_get_webhook( &self, address: &str, created_at_max: &str, created_at_min: &str, fields: &str, limit: &str, since_id: &str, topic: &str, updated_at_min: &str, updated_at_max: &str, ) -> Result<()> { let mut query_args: Vec<(String, String)> = Default::default(); if !address.is_empty() { query_args.push(("address".to_string(), address.to_string())); } if !created_at_max.is_empty() { query_args.push(("created_at_max".to_string(), created_at_max.to_string())); } if !created_at_min.is_empty() { query_args.push(("created_at_min".to_string(), created_at_min.to_string())); } if !fields.is_empty() { query_args.push(("fields".to_string(), fields.to_string())); } if !limit.is_empty() { query_args.push(("limit".to_string(), limit.to_string())); } if !since_id.is_empty() { query_args.push(("since_id".to_string(), since_id.to_string())); } if !topic.is_empty() { query_args.push(("topic".to_string(), topic.to_string())); } if !updated_at_max.is_empty() { query_args.push(("updated_at_max".to_string(), updated_at_max.to_string())); } if !updated_at_min.is_empty() { query_args.push(("updated_at_min".to_string(), updated_at_min.to_string())); } let query_ = serde_urlencoded::to_string(&query_args).unwrap(); let url = format!("/admin/api/2020-04/webhooks.json?{}", query_); self.client.get(&url, None).await } /** * Create a new webhook subscription by specifying both an address and a topic. * * This function performs a `POST` to the `/admin/api/2020-04/webhooks.json` endpoint. * * https://shopify.dev/docs/admin-api/rest/reference/events/webhook#create-2020-04 * * **Parameters:** * * * `format: &str` -- Use this parameter to select the data format for the payload. Valid values are json and xml. * (default: json). */ pub async fn deprecated_202004_create_webhooks( &self, format: &str, body: &serde_json::Value, ) -> Result<()> { let mut query_args: Vec<(String, String)> = Default::default(); if !format.is_empty() { query_args.push(("format".to_string(), format.to_string())); } let query_ = serde_urlencoded::to_string(&query_args).unwrap(); let url = format!("/admin/api/2020-04/webhooks.json?{}", query_); self.client .post(&url, Some(reqwest::Body::from(serde_json::to_vec(body)?))) .await } /** * Retrieves a count of existing webhook subscriptions. * * This function performs a `GET` to the `/admin/api/2020-04/webhooks/count.json` endpoint. * * https://shopify.dev/docs/admin-api/rest/reference/events/webhook#count-2020-04 * * **Parameters:** * * * `address: &str` -- Retrieve webhook subscriptions that send the POST request to this URI. * * `topic: &str` -- Show webhook subscriptions with a given topic. * For a list of valid values, refer to the topic property.>. */ pub async fn deprecated_202004_get_webhooks_count( &self, address: &str, topic: &str, ) -> Result<()> { let mut query_args: Vec<(String, String)> = Default::default(); if !address.is_empty() { query_args.push(("address".to_string(), address.to_string())); } if !topic.is_empty() { query_args.push(("topic".to_string(), topic.to_string())); } let query_ = serde_urlencoded::to_string(&query_args).unwrap(); let url = format!("/admin/api/2020-04/webhooks/count.json?{}", query_); self.client.get(&url, None).await } /** * Retrieves a single webhook subscription. * * This function performs a `GET` to the `/admin/api/2020-04/webhooks/{webhook_id}.json` endpoint. * * https://shopify.dev/docs/admin-api/rest/reference/events/webhook#show-2020-04 * * **Parameters:** * * * `webhook_id: &str` -- storefront_access_token_id. * * `fields: &str` -- Comma-separated list of the properties you want returned for each item in the result list. Use this parameter to restrict the returned list of items to only those properties you specify. */ pub async fn deprecated_202004_get_webhooks_param_webhook( &self, webhook_id: &str, fields: &str, ) -> Result<()> { let mut query_args: Vec<(String, String)> = Default::default(); if !fields.is_empty() { query_args.push(("fields".to_string(), fields.to_string())); } let query_ = serde_urlencoded::to_string(&query_args).unwrap(); let url = format!( "/admin/api/2020-04/webhooks/{}/json?{}", crate::progenitor_support::encode_path(&webhook_id.to_string()), query_ ); self.client.get(&url, None).await } /** * Update a webhook subscription's topic or address URIs. * * This function performs a `PUT` to the `/admin/api/2020-04/webhooks/{webhook_id}.json` endpoint. * * https://shopify.dev/docs/admin-api/rest/reference/events/webhook#update-2020-04 * * **Parameters:** * * * `webhook_id: &str` -- storefront_access_token_id. */ pub async fn deprecated_202004_update_webhooks_param_webhook( &self, webhook_id: &str, body: &serde_json::Value, ) -> Result<()> { let url = format!( "/admin/api/2020-04/webhooks/{}/json", crate::progenitor_support::encode_path(&webhook_id.to_string()), ); self.client .put(&url, Some(reqwest::Body::from(serde_json::to_vec(body)?))) .await } /** * Delete a webhook subscription. * * This function performs a `DELETE` to the `/admin/api/2020-04/webhooks/{webhook_id}.json` endpoint. * * https://shopify.dev/docs/admin-api/rest/reference/events/webhook#destroy-2020-04 * * **Parameters:** * * * `webhook_id: &str` -- storefront_access_token_id. */ pub async fn deprecated_202004_delete_webhooks_param_webhook( &self, webhook_id: &str, ) -> Result<()> { let url = format!( "/admin/api/2020-04/webhooks/{}/json", crate::progenitor_support::encode_path(&webhook_id.to_string()), ); self.client.delete(&url, None).await } /** * Retrieves a list of webhooks. Note: As of version 2019-10, this endpoint implements pagination by using links that are provided in the response header. To learn more, see Making requests to paginated REST Admin API endpoints. * * This function performs a `GET` to the `/admin/api/2020-07/webhooks.json` endpoint. * * https://shopify.dev/docs/admin-api/rest/reference/events/webhook#index-2020-07 * * **Parameters:** * * * `address: &str` -- Retrieve webhook subscriptions that send the POST request to this URI. * * `created_at_max: &str` -- Retrieve webhook subscriptions that were created before a given date and time (format: 2014-04-25T16:15:47-04:00). * * `created_at_min: &str` -- Retrieve webhook subscriptions that were created after a given date and time (format: 2014-04-25T16:15:47-04:00). * * `fields: &str` -- Comma-separated list of the properties you want returned for each item in the result list. Use this parameter to restrict the returned list of items to only those properties you specify. * * `limit: &str` -- Maximum number of webhook subscriptions that should be returned. Setting this parameter outside the maximum range will return an error. * (default: 50, maximum: 250). * * `since_id: &str` -- Restrict the returned list to webhook subscriptions whose id is greater than the specified since_id. * * `topic: &str` -- Show webhook subscriptions with a given topic. * For a list of valid values, refer to the topic property.>. * * `updated_at_min: &str` -- Retrieve webhooks that were updated before a given date and time (format: 2014-04-25T16:15:47-04:00). * * `updated_at_max: &str` -- Retrieve webhooks that were updated after a given date and time (format: 2014-04-25T16:15:47-04:00). */ pub async fn deprecated_202007_get_webhook( &self, address: &str, created_at_max: &str, created_at_min: &str, fields: &str, limit: &str, since_id: &str, topic: &str, updated_at_min: &str, updated_at_max: &str, ) -> Result<()> { let mut query_args: Vec<(String, String)> = Default::default(); if !address.is_empty() { query_args.push(("address".to_string(), address.to_string())); } if !created_at_max.is_empty() { query_args.push(("created_at_max".to_string(), created_at_max.to_string())); } if !created_at_min.is_empty() { query_args.push(("created_at_min".to_string(), created_at_min.to_string())); } if !fields.is_empty() { query_args.push(("fields".to_string(), fields.to_string())); } if !limit.is_empty() { query_args.push(("limit".to_string(), limit.to_string())); } if !since_id.is_empty() { query_args.push(("since_id".to_string(), since_id.to_string())); } if !topic.is_empty() { query_args.push(("topic".to_string(), topic.to_string())); } if !updated_at_max.is_empty() { query_args.push(("updated_at_max".to_string(), updated_at_max.to_string())); } if !updated_at_min.is_empty() { query_args.push(("updated_at_min".to_string(), updated_at_min.to_string())); } let query_ = serde_urlencoded::to_string(&query_args).unwrap(); let url = format!("/admin/api/2020-07/webhooks.json?{}", query_); self.client.get(&url, None).await } /** * Create a new webhook subscription by specifying both an address and a topic. * * This function performs a `POST` to the `/admin/api/2020-07/webhooks.json` endpoint. * * https://shopify.dev/docs/admin-api/rest/reference/events/webhook#create-2020-07 * * **Parameters:** * * * `format: &str` -- Use this parameter to select the data format for the payload. Valid values are json and xml. * (default: json). */ pub async fn deprecated_202007_create_webhooks( &self, format: &str, body: &serde_json::Value, ) -> Result<()> { let mut query_args: Vec<(String, String)> = Default::default(); if !format.is_empty() { query_args.push(("format".to_string(), format.to_string())); } let query_ = serde_urlencoded::to_string(&query_args).unwrap(); let url = format!("/admin/api/2020-07/webhooks.json?{}", query_); self.client .post(&url, Some(reqwest::Body::from(serde_json::to_vec(body)?))) .await } /** * Retrieves a count of existing webhook subscriptions. * * This function performs a `GET` to the `/admin/api/2020-07/webhooks/count.json` endpoint. * * https://shopify.dev/docs/admin-api/rest/reference/events/webhook#count-2020-07 * * **Parameters:** * * * `address: &str` -- Retrieve webhook subscriptions that send the POST request to this URI. * * `topic: &str` -- Show webhook subscriptions with a given topic. * For a list of valid values, refer to the topic property.>. */ pub async fn deprecated_202007_get_webhooks_count( &self, address: &str, topic: &str, ) -> Result<()> { let mut query_args: Vec<(String, String)> = Default::default(); if !address.is_empty() { query_args.push(("address".to_string(), address.to_string())); } if !topic.is_empty() { query_args.push(("topic".to_string(), topic.to_string())); } let query_ = serde_urlencoded::to_string(&query_args).unwrap(); let url = format!("/admin/api/2020-07/webhooks/count.json?{}", query_); self.client.get(&url, None).await } /** * Retrieves a single webhook subscription. * * This function performs a `GET` to the `/admin/api/2020-07/webhooks/{webhook_id}.json` endpoint. * * https://shopify.dev/docs/admin-api/rest/reference/events/webhook#show-2020-07 * * **Parameters:** * * * `webhook_id: &str` -- storefront_access_token_id. * * `fields: &str` -- Comma-separated list of the properties you want returned for each item in the result list. Use this parameter to restrict the returned list of items to only those properties you specify. */ pub async fn deprecated_202007_get_webhooks_param_webhook( &self, webhook_id: &str, fields: &str, ) -> Result<()> { let mut query_args: Vec<(String, String)> = Default::default(); if !fields.is_empty() { query_args.push(("fields".to_string(), fields.to_string())); } let query_ = serde_urlencoded::to_string(&query_args).unwrap(); let url = format!( "/admin/api/2020-07/webhooks/{}/json?{}", crate::progenitor_support::encode_path(&webhook_id.to_string()), query_ ); self.client.get(&url, None).await } /** * Update a webhook subscription's topic or address URIs. * * This function performs a `PUT` to the `/admin/api/2020-07/webhooks/{webhook_id}.json` endpoint. * * https://shopify.dev/docs/admin-api/rest/reference/events/webhook#update-2020-07 * * **Parameters:** * * * `webhook_id: &str` -- storefront_access_token_id. */ pub async fn deprecated_202007_update_webhooks_param_webhook( &self, webhook_id: &str, body: &serde_json::Value, ) -> Result<()> { let url = format!( "/admin/api/2020-07/webhooks/{}/json", crate::progenitor_support::encode_path(&webhook_id.to_string()), ); self.client .put(&url, Some(reqwest::Body::from(serde_json::to_vec(body)?))) .await } /** * Delete a webhook subscription. * * This function performs a `DELETE` to the `/admin/api/2020-07/webhooks/{webhook_id}.json` endpoint. * * https://shopify.dev/docs/admin-api/rest/reference/events/webhook#destroy-2020-07 * * **Parameters:** * * * `webhook_id: &str` -- storefront_access_token_id. */ pub async fn deprecated_202007_delete_webhooks_param_webhook( &self, webhook_id: &str, ) -> Result<()> { let url = format!( "/admin/api/2020-07/webhooks/{}/json", crate::progenitor_support::encode_path(&webhook_id.to_string()), ); self.client.delete(&url, None).await } /** * Retrieves a list of webhooks. Note: As of version 2019-10, this endpoint implements pagination by using links that are provided in the response header. To learn more, see Making requests to paginated REST Admin API endpoints. * * This function performs a `GET` to the `/admin/api/2020-10/webhooks.json` endpoint. * * https://shopify.dev/docs/admin-api/rest/reference/events/webhook#index-2020-10 * * **Parameters:** * * * `address: &str` -- Retrieve webhook subscriptions that send the POST request to this URI. * * `created_at_max: &str` -- Retrieve webhook subscriptions that were created before a given date and time (format: 2014-04-25T16:15:47-04:00). * * `created_at_min: &str` -- Retrieve webhook subscriptions that were created after a given date and time (format: 2014-04-25T16:15:47-04:00). * * `fields: &str` -- Comma-separated list of the properties you want returned for each item in the result list. Use this parameter to restrict the returned list of items to only those properties you specify. * * `limit: &str` -- Maximum number of webhook subscriptions that should be returned. Setting this parameter outside the maximum range will return an error. * (default: 50, maximum: 250). * * `since_id: &str` -- Restrict the returned list to webhook subscriptions whose id is greater than the specified since_id. * * `topic: &str` -- Show webhook subscriptions with a given topic. * For a list of valid values, refer to the topic property.>. * * `updated_at_min: &str` -- Retrieve webhooks that were updated before a given date and time (format: 2014-04-25T16:15:47-04:00). * * `updated_at_max: &str` -- Retrieve webhooks that were updated after a given date and time (format: 2014-04-25T16:15:47-04:00). */ pub async fn get_webhook( &self, address: &str, created_at_max: &str, created_at_min: &str, fields: &str, limit: &str, since_id: &str, topic: &str, updated_at_min: &str, updated_at_max: &str, ) -> Result<()> { let mut query_args: Vec<(String, String)> = Default::default(); if !address.is_empty() { query_args.push(("address".to_string(), address.to_string())); } if !created_at_max.is_empty() { query_args.push(("created_at_max".to_string(), created_at_max.to_string())); } if !created_at_min.is_empty() { query_args.push(("created_at_min".to_string(), created_at_min.to_string())); } if !fields.is_empty() { query_args.push(("fields".to_string(), fields.to_string())); } if !limit.is_empty() { query_args.push(("limit".to_string(), limit.to_string())); } if !since_id.is_empty() { query_args.push(("since_id".to_string(), since_id.to_string())); } if !topic.is_empty() { query_args.push(("topic".to_string(), topic.to_string())); } if !updated_at_max.is_empty() { query_args.push(("updated_at_max".to_string(), updated_at_max.to_string())); } if !updated_at_min.is_empty() { query_args.push(("updated_at_min".to_string(), updated_at_min.to_string())); } let query_ = serde_urlencoded::to_string(&query_args).unwrap(); let url = format!("/admin/api/2020-10/webhooks.json?{}", query_); self.client.get(&url, None).await } /** * Create a new webhook subscription by specifying both an address and a topic. * * This function performs a `POST` to the `/admin/api/2020-10/webhooks.json` endpoint. * * https://shopify.dev/docs/admin-api/rest/reference/events/webhook#create-2020-10 * * **Parameters:** * * * `format: &str` -- Use this parameter to select the data format for the payload. Valid values are json and xml. * (default: json). */ pub async fn create_webhooks(&self, format: &str, body: &serde_json::Value) -> Result<()> { let mut query_args: Vec<(String, String)> = Default::default(); if !format.is_empty() { query_args.push(("format".to_string(), format.to_string())); } let query_ = serde_urlencoded::to_string(&query_args).unwrap(); let url = format!("/admin/api/2020-10/webhooks.json?{}", query_); self.client .post(&url, Some(reqwest::Body::from(serde_json::to_vec(body)?))) .await } /** * Retrieves a count of existing webhook subscriptions. * * This function performs a `GET` to the `/admin/api/2020-10/webhooks/count.json` endpoint. * * https://shopify.dev/docs/admin-api/rest/reference/events/webhook#count-2020-10 * * **Parameters:** * * * `address: &str` -- Retrieve webhook subscriptions that send the POST request to this URI. * * `topic: &str` -- Show webhook subscriptions with a given topic. * For a list of valid values, refer to the topic property.>. */ pub async fn get_webhooks_count(&self, address: &str, topic: &str) -> Result<()> { let mut query_args: Vec<(String, String)> = Default::default(); if !address.is_empty() { query_args.push(("address".to_string(), address.to_string())); } if !topic.is_empty() { query_args.push(("topic".to_string(), topic.to_string())); } let query_ = serde_urlencoded::to_string(&query_args).unwrap(); let url = format!("/admin/api/2020-10/webhooks/count.json?{}", query_); self.client.get(&url, None).await } /** * Retrieves a single webhook subscription. * * This function performs a `GET` to the `/admin/api/2020-10/webhooks/{webhook_id}.json` endpoint. * * https://shopify.dev/docs/admin-api/rest/reference/events/webhook#show-2020-10 * * **Parameters:** * * * `webhook_id: &str` -- storefront_access_token_id. * * `fields: &str` -- Comma-separated list of the properties you want returned for each item in the result list. Use this parameter to restrict the returned list of items to only those properties you specify. */ pub async fn get_webhooks_param_webhook(&self, webhook_id: &str, fields: &str) -> Result<()> { let mut query_args: Vec<(String, String)> = Default::default(); if !fields.is_empty() { query_args.push(("fields".to_string(), fields.to_string())); } let query_ = serde_urlencoded::to_string(&query_args).unwrap(); let url = format!( "/admin/api/2020-10/webhooks/{}/json?{}", crate::progenitor_support::encode_path(&webhook_id.to_string()), query_ ); self.client.get(&url, None).await } /** * Update a webhook subscription's topic or address URIs. * * This function performs a `PUT` to the `/admin/api/2020-10/webhooks/{webhook_id}.json` endpoint. * * https://shopify.dev/docs/admin-api/rest/reference/events/webhook#update-2020-10 * * **Parameters:** * * * `webhook_id: &str` -- storefront_access_token_id. */ pub async fn update_webhooks_param_webhook( &self, webhook_id: &str, body: &serde_json::Value, ) -> Result<()> { let url = format!( "/admin/api/2020-10/webhooks/{}/json", crate::progenitor_support::encode_path(&webhook_id.to_string()), ); self.client .put(&url, Some(reqwest::Body::from(serde_json::to_vec(body)?))) .await } /** * Delete a webhook subscription. * * This function performs a `DELETE` to the `/admin/api/2020-10/webhooks/{webhook_id}.json` endpoint. * * https://shopify.dev/docs/admin-api/rest/reference/events/webhook#destroy-2020-10 * * **Parameters:** * * * `webhook_id: &str` -- storefront_access_token_id. */ pub async fn delete_webhooks_param_webhook(&self, webhook_id: &str) -> Result<()> { let url = format!( "/admin/api/2020-10/webhooks/{}/json", crate::progenitor_support::encode_path(&webhook_id.to_string()), ); self.client.delete(&url, None).await } /** * Retrieves a list of webhooks. Note: As of version 2019-10, this endpoint implements pagination by using links that are provided in the response header. To learn more, see Making requests to paginated REST Admin API endpoints. * * This function performs a `GET` to the `/admin/api/2021-01/webhooks.json` endpoint. * * https://shopify.dev/docs/admin-api/rest/reference/events/webhook#index-2021-01 * * **Parameters:** * * * `address: &str` -- Retrieve webhook subscriptions that send the POST request to this URI. * * `created_at_max: &str` -- Retrieve webhook subscriptions that were created before a given date and time (format: 2014-04-25T16:15:47-04:00). * * `created_at_min: &str` -- Retrieve webhook subscriptions that were created after a given date and time (format: 2014-04-25T16:15:47-04:00). * * `fields: &str` -- Comma-separated list of the properties you want returned for each item in the result list. Use this parameter to restrict the returned list of items to only those properties you specify. * * `limit: &str` -- Maximum number of webhook subscriptions that should be returned. Setting this parameter outside the maximum range will return an error. * (default: 50, maximum: 250). * * `since_id: &str` -- Restrict the returned list to webhook subscriptions whose id is greater than the specified since_id. * * `topic: &str` -- Show webhook subscriptions with a given topic. * For a list of valid values, refer to the topic property.>. * * `updated_at_min: &str` -- Retrieve webhooks that were updated before a given date and time (format: 2014-04-25T16:15:47-04:00). * * `updated_at_max: &str` -- Retrieve webhooks that were updated after a given date and time (format: 2014-04-25T16:15:47-04:00). */ pub async fn deprecated_202101_get_webhook( &self, address: &str, created_at_max: &str, created_at_min: &str, fields: &str, limit: &str, since_id: &str, topic: &str, updated_at_min: &str, updated_at_max: &str, ) -> Result<()> { let mut query_args: Vec<(String, String)> = Default::default(); if !address.is_empty() { query_args.push(("address".to_string(), address.to_string())); } if !created_at_max.is_empty() { query_args.push(("created_at_max".to_string(), created_at_max.to_string())); } if !created_at_min.is_empty() { query_args.push(("created_at_min".to_string(), created_at_min.to_string())); } if !fields.is_empty() { query_args.push(("fields".to_string(), fields.to_string())); } if !limit.is_empty() { query_args.push(("limit".to_string(), limit.to_string())); } if !since_id.is_empty() { query_args.push(("since_id".to_string(), since_id.to_string())); } if !topic.is_empty() { query_args.push(("topic".to_string(), topic.to_string())); } if !updated_at_max.is_empty() { query_args.push(("updated_at_max".to_string(), updated_at_max.to_string())); } if !updated_at_min.is_empty() { query_args.push(("updated_at_min".to_string(), updated_at_min.to_string())); } let query_ = serde_urlencoded::to_string(&query_args).unwrap(); let url = format!("/admin/api/2021-01/webhooks.json?{}", query_); self.client.get(&url, None).await } /** * Create a new webhook subscription by specifying both an address and a topic. * * This function performs a `POST` to the `/admin/api/2021-01/webhooks.json` endpoint. * * https://shopify.dev/docs/admin-api/rest/reference/events/webhook#create-2021-01 * * **Parameters:** * * * `format: &str` -- Use this parameter to select the data format for the payload. Valid values are json and xml. * (default: json). */ pub async fn deprecated_202101_create_webhooks( &self, format: &str, body: &serde_json::Value, ) -> Result<()> { let mut query_args: Vec<(String, String)> = Default::default(); if !format.is_empty() { query_args.push(("format".to_string(), format.to_string())); } let query_ = serde_urlencoded::to_string(&query_args).unwrap(); let url = format!("/admin/api/2021-01/webhooks.json?{}", query_); self.client .post(&url, Some(reqwest::Body::from(serde_json::to_vec(body)?))) .await } /** * Retrieves a count of existing webhook subscriptions. * * This function performs a `GET` to the `/admin/api/2021-01/webhooks/count.json` endpoint. * * https://shopify.dev/docs/admin-api/rest/reference/events/webhook#count-2021-01 * * **Parameters:** * * * `address: &str` -- Retrieve webhook subscriptions that send the POST request to this URI. * * `topic: &str` -- Show webhook subscriptions with a given topic. * For a list of valid values, refer to the topic property.>. */ pub async fn deprecated_202101_get_webhooks_count( &self, address: &str, topic: &str, ) -> Result<()> { let mut query_args: Vec<(String, String)> = Default::default(); if !address.is_empty() { query_args.push(("address".to_string(), address.to_string())); } if !topic.is_empty() { query_args.push(("topic".to_string(), topic.to_string())); } let query_ = serde_urlencoded::to_string(&query_args).unwrap(); let url = format!("/admin/api/2021-01/webhooks/count.json?{}", query_); self.client.get(&url, None).await } /** * Retrieves a single webhook subscription. * * This function performs a `GET` to the `/admin/api/2021-01/webhooks/{webhook_id}.json` endpoint. * * https://shopify.dev/docs/admin-api/rest/reference/events/webhook#show-2021-01 * * **Parameters:** * * * `webhook_id: &str` -- storefront_access_token_id. * * `fields: &str` -- Comma-separated list of the properties you want returned for each item in the result list. Use this parameter to restrict the returned list of items to only those properties you specify. */ pub async fn deprecated_202101_get_webhooks_param_webhook( &self, webhook_id: &str, fields: &str, ) -> Result<()> { let mut query_args: Vec<(String, String)> = Default::default(); if !fields.is_empty() { query_args.push(("fields".to_string(), fields.to_string())); } let query_ = serde_urlencoded::to_string(&query_args).unwrap(); let url = format!( "/admin/api/2021-01/webhooks/{}/json?{}", crate::progenitor_support::encode_path(&webhook_id.to_string()), query_ ); self.client.get(&url, None).await } /** * Update a webhook subscription's topic or address URIs. * * This function performs a `PUT` to the `/admin/api/2021-01/webhooks/{webhook_id}.json` endpoint. * * https://shopify.dev/docs/admin-api/rest/reference/events/webhook#update-2021-01 * * **Parameters:** * * * `webhook_id: &str` -- storefront_access_token_id. */ pub async fn deprecated_202101_update_webhooks_param_webhook( &self, webhook_id: &str, body: &serde_json::Value, ) -> Result<()> { let url = format!( "/admin/api/2021-01/webhooks/{}/json", crate::progenitor_support::encode_path(&webhook_id.to_string()), ); self.client .put(&url, Some(reqwest::Body::from(serde_json::to_vec(body)?))) .await } /** * Delete a webhook subscription. * * This function performs a `DELETE` to the `/admin/api/2021-01/webhooks/{webhook_id}.json` endpoint. * * https://shopify.dev/docs/admin-api/rest/reference/events/webhook#destroy-2021-01 * * **Parameters:** * * * `webhook_id: &str` -- storefront_access_token_id. */ pub async fn deprecated_202101_delete_webhooks_param_webhook( &self, webhook_id: &str, ) -> Result<()> { let url = format!( "/admin/api/2021-01/webhooks/{}/json", crate::progenitor_support::encode_path(&webhook_id.to_string()), ); self.client.delete(&url, None).await } /** * Retrieves a list of webhooks. Note: As of version 2019-10, this endpoint implements pagination by using links that are provided in the response header. To learn more, see Making requests to paginated REST Admin API endpoints. * * This function performs a `GET` to the `/admin/api/unstable/webhooks.json` endpoint. * * https://shopify.dev/docs/admin-api/rest/reference/events/webhook#index-unstable * * **Parameters:** * * * `address: &str` -- Retrieve webhook subscriptions that send the POST request to this URI. * * `created_at_max: &str` -- Retrieve webhook subscriptions that were created before a given date and time (format: 2014-04-25T16:15:47-04:00). * * `created_at_min: &str` -- Retrieve webhook subscriptions that were created after a given date and time (format: 2014-04-25T16:15:47-04:00). * * `fields: &str` -- Comma-separated list of the properties you want returned for each item in the result list. Use this parameter to restrict the returned list of items to only those properties you specify. * * `limit: &str` -- Maximum number of webhook subscriptions that should be returned. Setting this parameter outside the maximum range will return an error. * (default: 50, maximum: 250). * * `since_id: &str` -- Restrict the returned list to webhook subscriptions whose id is greater than the specified since_id. * * `topic: &str` -- Show webhook subscriptions with a given topic. * For a list of valid values, refer to the topic property.>. * * `updated_at_min: &str` -- Retrieve webhooks that were updated before a given date and time (format: 2014-04-25T16:15:47-04:00). * * `updated_at_max: &str` -- Retrieve webhooks that were updated after a given date and time (format: 2014-04-25T16:15:47-04:00). */ pub async fn deprecated_unstable_get_webhook( &self, address: &str, created_at_max: &str, created_at_min: &str, fields: &str, limit: &str, since_id: &str, topic: &str, updated_at_min: &str, updated_at_max: &str, ) -> Result<()> { let mut query_args: Vec<(String, String)> = Default::default(); if !address.is_empty() { query_args.push(("address".to_string(), address.to_string())); } if !created_at_max.is_empty() { query_args.push(("created_at_max".to_string(), created_at_max.to_string())); } if !created_at_min.is_empty() { query_args.push(("created_at_min".to_string(), created_at_min.to_string())); } if !fields.is_empty() { query_args.push(("fields".to_string(), fields.to_string())); } if !limit.is_empty() { query_args.push(("limit".to_string(), limit.to_string())); } if !since_id.is_empty() { query_args.push(("since_id".to_string(), since_id.to_string())); } if !topic.is_empty() { query_args.push(("topic".to_string(), topic.to_string())); } if !updated_at_max.is_empty() { query_args.push(("updated_at_max".to_string(), updated_at_max.to_string())); } if !updated_at_min.is_empty() { query_args.push(("updated_at_min".to_string(), updated_at_min.to_string())); } let query_ = serde_urlencoded::to_string(&query_args).unwrap(); let url = format!("/admin/api/unstable/webhooks.json?{}", query_); self.client.get(&url, None).await } /** * Create a new webhook subscription by specifying both an address and a topic. * * This function performs a `POST` to the `/admin/api/unstable/webhooks.json` endpoint. * * https://shopify.dev/docs/admin-api/rest/reference/events/webhook#create-unstable * * **Parameters:** * * * `format: &str` -- Use this parameter to select the data format for the payload. Valid values are json and xml. * (default: json). */ pub async fn deprecated_unstable_create_webhooks( &self, format: &str, body: &serde_json::Value, ) -> Result<()> { let mut query_args: Vec<(String, String)> = Default::default(); if !format.is_empty() { query_args.push(("format".to_string(), format.to_string())); } let query_ = serde_urlencoded::to_string(&query_args).unwrap(); let url = format!("/admin/api/unstable/webhooks.json?{}", query_); self.client .post(&url, Some(reqwest::Body::from(serde_json::to_vec(body)?))) .await } /** * Retrieves a count of existing webhook subscriptions. * * This function performs a `GET` to the `/admin/api/unstable/webhooks/count.json` endpoint. * * https://shopify.dev/docs/admin-api/rest/reference/events/webhook#count-unstable * * **Parameters:** * * * `address: &str` -- Retrieve webhook subscriptions that send the POST request to this URI. * * `topic: &str` -- Show webhook subscriptions with a given topic. * For a list of valid values, refer to the topic property.>. */ pub async fn deprecated_unstable_get_webhooks_count( &self, address: &str, topic: &str, ) -> Result<()> { let mut query_args: Vec<(String, String)> = Default::default(); if !address.is_empty() { query_args.push(("address".to_string(), address.to_string())); } if !topic.is_empty() { query_args.push(("topic".to_string(), topic.to_string())); } let query_ = serde_urlencoded::to_string(&query_args).unwrap(); let url = format!("/admin/api/unstable/webhooks/count.json?{}", query_); self.client.get(&url, None).await } /** * Retrieves a single webhook subscription. * * This function performs a `GET` to the `/admin/api/unstable/webhooks/{webhook_id}.json` endpoint. * * https://shopify.dev/docs/admin-api/rest/reference/events/webhook#show-unstable * * **Parameters:** * * * `webhook_id: &str` -- storefront_access_token_id. * * `fields: &str` -- Comma-separated list of the properties you want returned for each item in the result list. Use this parameter to restrict the returned list of items to only those properties you specify. */ pub async fn deprecated_unstable_get_webhooks_param_webhook( &self, webhook_id: &str, fields: &str, ) -> Result<()> { let mut query_args: Vec<(String, String)> = Default::default(); if !fields.is_empty() { query_args.push(("fields".to_string(), fields.to_string())); } let query_ = serde_urlencoded::to_string(&query_args).unwrap(); let url = format!( "/admin/api/unstable/webhooks/{}/json?{}", crate::progenitor_support::encode_path(&webhook_id.to_string()), query_ ); self.client.get(&url, None).await } /** * Update a webhook subscription's topic or address URIs. * * This function performs a `PUT` to the `/admin/api/unstable/webhooks/{webhook_id}.json` endpoint. * * https://shopify.dev/docs/admin-api/rest/reference/events/webhook#update-unstable * * **Parameters:** * * * `webhook_id: &str` -- storefront_access_token_id. */ pub async fn deprecated_unstable_update_webhooks_param_webhook( &self, webhook_id: &str, body: &serde_json::Value, ) -> Result<()> { let url = format!( "/admin/api/unstable/webhooks/{}/json", crate::progenitor_support::encode_path(&webhook_id.to_string()), ); self.client .put(&url, Some(reqwest::Body::from(serde_json::to_vec(body)?))) .await } /** * Delete a webhook subscription. * * This function performs a `DELETE` to the `/admin/api/unstable/webhooks/{webhook_id}.json` endpoint. * * https://shopify.dev/docs/admin-api/rest/reference/events/webhook#destroy-unstable * * **Parameters:** * * * `webhook_id: &str` -- storefront_access_token_id. */ pub async fn deprecated_unstable_delete_webhooks_param_webhook( &self, webhook_id: &str, ) -> Result<()> { let url = format!( "/admin/api/unstable/webhooks/{}/json", crate::progenitor_support::encode_path(&webhook_id.to_string()), ); self.client.delete(&url, None).await } }
42.024008
279
0.605231
40cd7e1eb82c142d33648fc83e09c14326738da2
3,960
sql
SQL
jhip_patient_info.sql
ZBT-95/-IRIS-
a9901a22f73c10fecf0ef847f9d4def33c1ab0a7
[ "MIT" ]
1
2021-01-27T10:52:45.000Z
2021-01-27T10:52:45.000Z
jhip_patient_info.sql
ZBT-95/-IRIS-
a9901a22f73c10fecf0ef847f9d4def33c1ab0a7
[ "MIT" ]
1
2021-02-26T13:41:47.000Z
2021-02-26T13:41:47.000Z
jhip_patient_info.sql
ZBT-95/-IRIS-
a9901a22f73c10fecf0ef847f9d4def33c1ab0a7
[ "MIT" ]
2
2021-01-23T05:32:26.000Z
2022-01-26T01:48:15.000Z
/* Navicat MySQL Data Transfer Source Server : localhost Source Server Version : 80021 Source Host : localhost:3306 Source Database : 测试 Target Server Type : MYSQL Target Server Version : 80021 File Encoding : 65001 Date: 2021-02-26 14:08:01 */ SET FOREIGN_KEY_CHECKS=0; -- ---------------------------- -- Table structure for jhip_patient_info -- ---------------------------- DROP TABLE IF EXISTS `jhip_patient_info`; CREATE TABLE `jhip_patient_info` ( `id` bigint unsigned NOT NULL AUTO_INCREMENT COMMENT '主键', `mpi_id` varchar(45) DEFAULT NULL COMMENT '患者主索引号', `patient_id` varchar(45) DEFAULT NULL COMMENT '患者住院ID', `patient_type` varchar(45) DEFAULT NULL, `outp_no` varchar(45) DEFAULT NULL, `inp_no` varchar(45) DEFAULT NULL, `hospital_domain_code` varchar(15) DEFAULT NULL COMMENT '医院域代码', `hospital_domain_name` varchar(45) DEFAULT NULL COMMENT '医院名称', `name` varchar(45) DEFAULT NULL COMMENT '患者姓名', `pyname` varchar(45) DEFAULT NULL COMMENT '患者拼音名', `sex` varchar(20) DEFAULT NULL COMMENT '性别', `date_of_birth` date DEFAULT NULL COMMENT '出生日期', `id_type` varchar(10) NOT NULL COMMENT '证件类别', `id_card` varchar(45) DEFAULT NULL COMMENT '证件号码', `company` varchar(50) DEFAULT NULL COMMENT '工作单位', `street_address` varchar(100) DEFAULT NULL COMMENT '街道地址', `zone` varchar(30) DEFAULT NULL COMMENT '区,镇,乡', `city` varchar(30) DEFAULT NULL COMMENT '所在城市', `province` varchar(40) DEFAULT NULL COMMENT '省,市,自治区,直辖市', `post_code` varchar(12) DEFAULT NULL COMMENT '邮编', `country_code` varchar(45) DEFAULT NULL COMMENT '国家代码', `addr_type` varchar(2) DEFAULT NULL COMMENT '地址类型 ', `phone_home` varchar(20) DEFAULT NULL COMMENT '家庭手机', `phone_business` varchar(20) DEFAULT NULL COMMENT '工作手机', `marriage` varchar(10) DEFAULT NULL COMMENT '婚姻状况', `mother_pid` varchar(45) DEFAULT NULL COMMENT '母亲住院ID', `nation` varchar(45) DEFAULT NULL COMMENT '民族', `birth_place` varchar(100) DEFAULT NULL COMMENT '出生地', `blood_type` varchar(20) DEFAULT NULL COMMENT '血型', `nationnality` varchar(45) DEFAULT NULL COMMENT '国籍', `death_date` varchar(0) DEFAULT NULL COMMENT '患者死亡日期和时间', `death_id` varchar(45) DEFAULT NULL COMMENT '患者死亡标识', `profession` varchar(45) DEFAULT NULL COMMENT '职业', `contact_name` varchar(45) DEFAULT NULL COMMENT '联系人姓名', `contact_phone` varchar(20) DEFAULT NULL COMMENT '联系人电话', `contact_relation` varchar(45) DEFAULT NULL COMMENT '与联系人关系', `contact_name2` varchar(45) DEFAULT NULL COMMENT '联系人姓名2', `contact_phone2` varchar(20) DEFAULT NULL COMMENT '联系人电话2', `contact_relation2` varchar(45) DEFAULT NULL COMMENT '与联系人关系2', `create_date` datetime DEFAULT NULL COMMENT '创建时间', `updated` datetime DEFAULT NULL COMMENT '更新时间', `removed` varchar(0) DEFAULT NULL COMMENT '删除时间', `is_master` tinyint(1) DEFAULT '0' COMMENT '是否患者主索引', `supplier_system_id` varchar(20) DEFAULT NULL COMMENT '患者来源系统ID', `inp_on_supplier` varchar(12) DEFAULT NULL COMMENT '患者在业务系统ID', `domian_id` varchar(20) DEFAULT NULL COMMENT '区域ID', `combine_type` int DEFAULT NULL COMMENT '合并方式', `is_matched` tinyint(1) DEFAULT NULL COMMENT '是否已匹配', `register` varchar(45) DEFAULT NULL COMMENT '挂号员信息', PRIMARY KEY (`id`,`id_type`), KEY `name` (`name`), KEY `phone_home` (`phone_home`), KEY `phone_business` (`phone_business`), KEY `patient_id` (`patient_id`), KEY `id_card` (`id_card`) ) ENGINE=InnoDB AUTO_INCREMENT=5013 DEFAULT CHARSET=utf8 COMMENT='���滼�߻�����Ϣ'; -- ---------------------------- -- Records of jhip_patient_info -- ---------------------------- INSERT INTO `jhip_patient_info` VALUES ('1', '21d6e7a04b3743e38d1cdcc80ae705f3', '658**25', '', '', '', '', '', '李琴娥', '', 'F', '2019-02-01', 'PN', '433101196502082000', '', '湖南省吉首市***2组', '', '', '湖南省', '416000', '', '', '', '', '', '', '', '', '', '中国', '', '', '', '', '', '', '', '', '', '2021-01-23 16:25:49', '2021-01-23 17:20:11', '', '0', '', '', '', '1', '1', '');
47.142857
373
0.672222
7480ff6075c776c9843ab4dcb44964ab2517b9f7
6,702
rs
Rust
src/tests/request.rs
Estocy/backend
9dddcfa3f9a202ea7086f90e03562c85f574bef8
[ "MIT" ]
1
2020-11-23T22:47:23.000Z
2020-11-23T22:47:23.000Z
src/tests/request.rs
Estocy/backend
9dddcfa3f9a202ea7086f90e03562c85f574bef8
[ "MIT" ]
null
null
null
src/tests/request.rs
Estocy/backend
9dddcfa3f9a202ea7086f90e03562c85f574bef8
[ "MIT" ]
null
null
null
use chrono::NaiveDate; use rocket::http::ContentType; use rocket::http::Status; use rocket_contrib::json::Json; use serde_json; use uuid::Uuid; use crate::{ get_rocket_instance, models::client::{Client, NewClient}, models::product::{NewProduct, Product, NewProductReceiver}, models::request::{NewRequest, Request, RequestReceiver}, models::user::{NewUser, User}, }; #[test] fn create() { let client = rocket::local::Client::new(get_rocket_instance()).expect("valid rocket instance"); let (response_request, response_request_expected) = create_request(); assert_eq!(response_request.user_id, response_request_expected.user_id); assert_eq!( response_request.client_id, response_request_expected.client_id ); assert_eq!( response_request.sale_date, response_request_expected.sale_date ); assert_eq!( response_request.delivery_date, response_request_expected.delivery_date ); assert_eq!(response_request.status, response_request_expected.status); assert_eq!( response_request.comments, response_request_expected.comments ); assert_eq!(response_request.price, response_request_expected.price); assert_eq!( response_request.discount, response_request_expected.discount ); assert_eq!(response_request.freight, response_request_expected.freight); client .delete(format!("/requests/{}", response_request.id)) .header(ContentType::JSON) .dispatch(); } #[test] fn show() { let client = rocket::local::Client::new(get_rocket_instance()).expect("valid rocket instance"); let (response_request, response_request_expected) = create_request(); let mut response = client .get(format!("/requests/{}", response_request.id)) .header(ContentType::JSON) .dispatch(); let response_request: Request = serde_json::from_str(response.body_string().unwrap().as_str()).unwrap(); assert_eq!(response_request.user_id, response_request_expected.user_id); assert_eq!( response_request.client_id, response_request_expected.client_id ); assert_eq!( response_request.sale_date, response_request_expected.sale_date ); assert_eq!( response_request.delivery_date, response_request_expected.delivery_date ); assert_eq!(response_request.status, response_request_expected.status); assert_eq!( response_request.comments, response_request_expected.comments ); assert_eq!(response_request.price, response_request_expected.price); assert_eq!( response_request.discount, response_request_expected.discount ); assert_eq!(response_request.freight, response_request_expected.freight); client .delete(format!("/requests/{}", response_request.id)) .header(ContentType::JSON) .dispatch(); } #[test] fn delete() { let client = rocket::local::Client::new(get_rocket_instance()).expect("valid rocket instance"); let (response_request, ..) = create_request(); let response = client .delete(format!("/requests/{}", response_request.id)) .header(ContentType::JSON) .dispatch(); assert_eq!(response.status(), Status::Ok); } fn create_request() -> (Request, Request) { let client = rocket::local::Client::new(get_rocket_instance()).expect("valid rocket instance"); let users = NewUser { name: "Quick", email: "henrique.fquick@gmail.com", password: "123", share_photos: None, darkmode: Some(false), }; let mut response_create = client .post("/users") .header(ContentType::JSON) .body(serde_json::to_string(&users).unwrap()) .dispatch(); let response_user_create: User = serde_json::from_str(response_create.body_string().unwrap().as_str()).unwrap(); let clients = NewClient { user_id: response_user_create.id, name: "Quick2", email: "henrique.fquick@gmail.com", phone_number: "31998180608", address: "Rua teste", }; let mut response_client = client .post(format!("/clients")) .header(ContentType::JSON) .body(serde_json::to_string(&clients).unwrap()) .dispatch(); let response_client_created: Client = serde_json::from_str(response_client.body_string().unwrap().as_str()).unwrap(); let product = NewProduct { name: "Produto", code: 1, description: "Descricao", store_name: Some("Store name"), store_price: Some(10.5), price: 10.5, additional_charge: Some(10.0), color: "#ffffff", weight: 10.0, brand: "brand", stock_amount: 10, }; let product_category = NewProductReceiver { product: product, categories: Vec::<Uuid>::new(), }; let mut response_product = client .post("/products") .header(ContentType::JSON) .body(serde_json::to_string(&product_category).unwrap()) .dispatch(); let response_product_created: Product = serde_json::from_str(response_product.body_string().unwrap().as_str()).unwrap(); let request = NewRequest { code: 1, user_id: response_user_create.id, client_id: response_client_created.id, sale_date: NaiveDate::from_ymd(2020, 11, 25), delivery_date: NaiveDate::from_ymd(2020, 11, 25), status: 0, comments: Some("comentário"), price: 10.0, discount: 0.0, freight: 5.0, }; let request_product = RequestReceiver { request: request, product_id: response_product_created.id, amount: 1, additional_costs: 10.5, discount: 2.0, }; let response_request_expected = Request { id: Uuid::new_v4(), code: 1, user_id: response_user_create.id, client_id: response_client_created.id, sale_date: NaiveDate::from_ymd(2020, 11, 25), delivery_date: NaiveDate::from_ymd(2020, 11, 25), status: 0, comments: Some(String::from("comentário")), price: 10.0, discount: 0.0, freight: 5.0, }; let mut response = client .post("/requests") .header(ContentType::JSON) .body(serde_json::to_string(&request_product).unwrap()) .dispatch(); assert_eq!(response.status(), Status::Ok); let response_request: Request = serde_json::from_str(response.body_string().unwrap().as_str()).unwrap(); (response_request, response_request_expected) }
27.809129
99
0.642644
9a9df5929a9a9d17269f26ebf2c870e64ec70435
895
css
CSS
static/jslibs/style.jrac.css
ekorolev/autocard
7207ace9d8541916c04686e3d1e584d80210923a
[ "MIT" ]
null
null
null
static/jslibs/style.jrac.css
ekorolev/autocard
7207ace9d8541916c04686e3d1e584d80210923a
[ "MIT" ]
null
null
null
static/jslibs/style.jrac.css
ekorolev/autocard
7207ace9d8541916c04686e3d1e584d80210923a
[ "MIT" ]
null
null
null
/* jQuery Resize And Crop (jrac) */ .jrac_container { margin-bottom: 1em; } .jrac_viewport { position: relative; overflow: hidden; border:1px solid #ccc; width:640px; height:480px; background-image: url('images/viewport_background.gif'); border: dashed 5px #999; } .jrac_loading { background-image: url('images/loading.gif'); background-repeat:no-repeat; background-position:center; position: absolute; top:0;left:0;right:0;bottom:0; } .jrac_crop { position: absolute; border: 2px solid yellow; } .jrac_crop_drag_handler { position: absolute; top:0;left:0;right:0;bottom:0; background-color: #fff; opacity: .1; /* FX/Opera/Safari/Chrome */ -ms-filter: "alpha(opacity=10)"; /* IE8 */ filter: alpha(opacity = 10); /* IE6/IE7 */ } .jrac_viewport img, .jrac_crop_drag_handler { cursor: pointer; } .jrac_zoom_slider_label { margin-top: .5em; }
19.888889
58
0.687151
83cee958c434d6d680efc7399ea5307e6a586d87
47,086
kt
Kotlin
src/commonMain/kotlin/com/twelfthmile/kyuga/kYuga.kt
messai-engineering/Kyuga
308f0f89bdf02424ae236e56b38f722ca47b063d
[ "MIT" ]
null
null
null
src/commonMain/kotlin/com/twelfthmile/kyuga/kYuga.kt
messai-engineering/Kyuga
308f0f89bdf02424ae236e56b38f722ca47b063d
[ "MIT" ]
4
2020-04-16T08:25:45.000Z
2021-05-13T10:23:46.000Z
src/commonMain/kotlin/com/twelfthmile/kyuga/kYuga.kt
messai-engineering/Kyuga
308f0f89bdf02424ae236e56b38f722ca47b063d
[ "MIT" ]
null
null
null
package com.twelfthmile.kyuga import com.twelfthmile.kyuga.expectations.MultDate import com.twelfthmile.kyuga.expectations.formatDateDefault import com.twelfthmile.kyuga.expectations.log import com.twelfthmile.kyuga.regex.EMAIL_ADDRESS import com.twelfthmile.kyuga.regex.PHONE import com.twelfthmile.kyuga.regex.WEB_URL import com.twelfthmile.kyuga.types.GenTrie import com.twelfthmile.kyuga.types.Pair import com.twelfthmile.kyuga.types.Response import com.twelfthmile.kyuga.types.RootTrie import com.twelfthmile.kyuga.utils.* fun Char.isAlpha(): Boolean = this in 'a'..'z' || this in 'A'..'Z' private val TOKENIZE_REGEX = "[. ]".toRegex() object Kyuga { private val D_DEBUG = false private val root: RootTrie get() = LazyHolder.root private object LazyHolder { internal var root = createRoot() } private fun createRoot(): RootTrie { val root = RootTrie() root.next["FSA_MONTHS"] = GenTrie() root.next["FSA_DAYS"] = GenTrie() root.next["FSA_TIMEPRFX"] = GenTrie() root.next["FSA_AMT"] = GenTrie() root.next["FSA_TIMES"] = GenTrie() root.next["FSA_TZ"] = GenTrie() root.next["FSA_DAYSFFX"] = GenTrie() root.next["FSA_UPI"] = GenTrie() seeding(FSA_MONTHS, root.next["FSA_MONTHS"]) seeding(FSA_DAYS, root.next["FSA_DAYS"]) seeding(FSA_TIMEPRFX, root.next["FSA_TIMEPRFX"]) seeding(FSA_AMT, root.next["FSA_AMT"]) seeding(FSA_TIMES, root.next["FSA_TIMES"]) seeding(FSA_TZ, root.next["FSA_TZ"]) seeding(FSA_DAYSFFX, root.next["FSA_DAYSFFX"]) seeding(FSA_UPI, root.next["FSA_UPI"]) return root } private fun seeding(type: String, root: GenTrie?) { var t: GenTrie? var c = 0 for (fsaCldr in type.split(",").toTypedArray()) { c++ t = root val len = fsaCldr.length var i = 0 while (i < len) { val ch = fsaCldr[i] t!!.child = true if (!t.next.containsKey(ch)) t.next[ch] = GenTrie() t = t.next[ch] if (i == len - 1) { t!!.leaf = true t.token = fsaCldr.replace(";", "") } else if (i < len - 1 && fsaCldr[i + 1].toInt() == 59) { //semicolon t!!.leaf = true t.token = fsaCldr.replace(";", "") i++ //to skip semicolon } i++ } } } fun tokenise(message: List<String>): List<String> = message.map { val parseResponse = parse(it) parseResponse?.type ?: when (Util.checkForId(it)) { true -> if (it != "EMAILADDR") "IDVAL" else it false -> it } } fun tokenize(message: String): String { val cleanMessage = message .replace(EMAIL_ADDRESS, " EMAILADDR ") val candidateTokens = cleanMessage .split(TOKENIZE_REGEX) .map { it.trim() } return try { val tokens = tokenise(candidateTokens).filter { it.isNotBlank() } tokens.filterIndexed { index, it -> if (it.isNotEmpty()) { if (index > 0) tokens[index - 1] != it else true } else false } } catch (e: Exception) { candidateTokens }.joinToString(" ") } /** * Returns Pair of index upto which date was read and the date object * * @param str date string * @return A last index for date string, b date object * returns null if string is not of valid date format */ fun parseDate(str: String): Pair<Int, MultDate>? { val configMap = generateDefaultConfig() return getIntegerDatePair(str, configMap) } private fun getIntegerDatePair(str: String, configMap: Map<String, String>): Pair<Int, MultDate>? { val (a, b) = parseInternal(str, configMap) ?: return null val d = b.getDate(configMap) ?: return null return Pair(a, d) } /** * Returns Pair of index upto which date was read and the date object * * @param str date string * @param config pass the message date string for defaulting * @return A last index for date string, b date object * returns null if string is not of valid date format */ fun parseDate(str: String, config: Map<String, String>): Pair<Int, MultDate>? { return getIntegerDatePair(str, config) } /** * Returns Response containing data-type, captured string and index upto which data was read * * @param str string to be parsed * @param config config for parsing (Eg: date-defaulting) * @return Yuga Response type */ fun parse(str: String, config: Map<String, String>): Response? { return getResponse(str, config) } private fun getResponse(str: String, config: Map<String, String>): Response? { val p = parseInternal(str, config) ?: return null val (a, b) = prepareResult(str, p, config)!! return when (b) { is MultDate -> Response(a, p.b.getValMap(), b, p.a) is String -> Response(a, p.b.getValMap(), b, p.a) else -> throw IllegalArgumentException("Error while creating response") } } /** * Returns Response containing data-type, captured string and index upto which data was read * * @param str string to be parsed * @return Yuga Response type */ fun parse(str: String): Response? { val configMap = generateDefaultConfig() return getResponse(str, configMap) } // Pair <Type,String> private fun prepareResult( str: String, p: Pair<Int, FsaContextMap>, config: Map<String, String> ): Pair<String, Any>? { val index = p.a val map = p.b if (map.type == TY_DTE) { if (map.contains(DT_MMM) && map.size() < 3) //may fix return Pair(TY_STR, str.substring(0, index)) if (map.contains(DT_HH) && map.contains(DT_mm) && !map.contains(DT_D) && !map.contains( DT_DD ) && !map.contains(DT_MM) && !map.contains(DT_MMM) && !map.contains(DT_YY) && !map.contains( DT_YYYY ) ) { map.setType(TY_TME, null) map.setVal("time", map[DT_HH] + ":" + map[DT_mm]) return Pair(TY_TME, str.substring(0, index)) } val d = map.getDate(config) return if (d != null) p.b.type?.let { Pair<String, Any>(it, d) } else Pair(TY_STR, str.substring(0, index)) } else { return if (map[map.type!!] != null) { if (map.type == TY_ACC && config.containsKey(YUGA_SOURCE_CONTEXT) && config[YUGA_SOURCE_CONTEXT] == YUGA_SC_CURR) { Pair<String, Any>(TY_AMT, map[map.type!!]!!.replace("X".toRegex(), "")) } else { p.b.type?.let { map[map.type!!]?.let { tg -> Pair<String, Any>(it, tg) } } } } else p.b.type?.let { Pair<String, Any>(it, str.substring(0, index)) } } } private fun generateDefaultConfig(): Map<String, String> { val config = mutableMapOf<String, String>() config[YUGA_CONF_DATE] = formatDateDefault(MultDate()) return config } fun checkTypes(type: String, word: String): Pair<Int, String>? { return Util.checkTypes(root, type, word) } private fun parseInternal(inputStr: String, config: Map<String, String>): Pair<Int, FsaContextMap>? { var str = inputStr var state = 1 var i = 0 var c: Char val map = FsaContextMap() val delimiterStack = DelimiterStack() str = str.toLowerCase() var counter = 0 while (state > 0 && i < str.length) { c = str[i] when (state) { 1 -> if (Util.isNumber(c)) { map.setType(TY_NUM, null) map.put(TY_NUM, c) state = 2 } else if (Util.checkTypes(root, "FSA_MONTHS", str.substring(i))?.let { map.setType(TY_DTE, null) map.put(DT_MMM, it.b) i += it.a true } == true) { state = 33 } else if (Util.checkTypes(root, "FSA_DAYS", str.substring(i))?.let { map.setType(TY_DTE, null) map.put(DT_DD, it.b) i += it.a true } == true) { state = 30 } else if (c.toInt() == CH_HYPH) {//it could be a negative number state = 37 } else if (c.toInt() == CH_LSBT) {//it could be an OTP state = 1 } else { state = accAmtNumPct(str, i, map, config) if (map.type == null) return null if (state == -1 && map.type != TY_PCT) { i -= 1 } } 2 -> if (Util.isNumber(c)) { map.append(c) state = 3 } else if (Util.isTimeOperator(c)) { delimiterStack.push(c) map.setType(TY_DTE, DT_HH) state = 4 } else if (Util.isDateOperator(c) || c.toInt() == CH_COMA) { delimiterStack.push(c) map.setType(TY_DTE, DT_D) state = 16 } else if (checkMonthType(str, i)?.let { map.setType(TY_DTE, DT_D) map.put(DT_MMM, it.b) i += it.a true } == true) { state = 24 } else { state = accAmtNumPct(str, i, map, config) if (state == -1 && map.type != TY_PCT) i -= 1 } 3 -> if (Util.isNumber(c)) { map.append(c) state = 8 } else if (Util.isTimeOperator(c)) { delimiterStack.push(c) map.setType(TY_DTE, DT_HH) state = 4 } else if (Util.isDateOperator(c) || c.toInt() == CH_COMA) { delimiterStack.push(c) map.setType(TY_DTE, DT_D) state = 16 } else if (checkMonthType(str, i)?.let { map.setType(TY_DTE, DT_D) map.put(DT_MMM, it.b) i += it.a true } == true) { state = 24 } else if (Util.checkTypes(root, "FSA_DAYSFFX", str.substring(i))?.let { map.setType(TY_DTE, DT_D) i += it.a true } == true) { state = 32 } else { state = accAmtNumPct(str, i, map, config) if (state == -1 && map.type != TY_PCT) i -= 1 } 4 //hours to mins -> if (Util.isNumber(c)) { map.upgrade(c)//hh to mm state = 5 } else { //saw a colon randomly, switch back to num from hours if (!map.contains(DT_MMM)) map.setType(TY_NUM, TY_NUM) i -= 2 //move back so that colon is omitted state = -1 } 5 -> if (Util.isNumber(c)) { map.append(c) state = 5 } else if (c.toInt() == CH_COLN) state = 6 else if (c == 'a' && i + 1 < str.length && str[i + 1] == 'm') { i += 1 state = -1 } else if (c == 'p' && i + 1 < str.length && str[i + 1] == 'm') { map.put(DT_HH, (map[DT_HH]!!.toInt() + 12).toString()) i += 1 state = -1 } else if (Util.checkTypes(root, "FSA_TIMES", str.substring(i))?.let { i += it.a true } == true) { state = -1 } else state = 7 6 //for seconds -> if (Util.isNumber(c)) { map.upgrade(c) if (i + 1 < str.length && Util.isNumber(str[i + 1])) map.append(str[i + 1]) i = i + 1 state = -1 } else state = -1 7 -> { if (c == 'a' && i + 1 < str.length && str[i + 1] == 'm') { i = i + 1 val hh = map[DT_HH]!!.toInt() if (hh == 12) map.put(DT_HH, 0.toString()) } else if (c == 'p' && i + 1 < str.length && str[i + 1] == 'm') { val hh = map[DT_HH]!!.toInt() if (hh != 12) map.put(DT_HH, (hh + 12).toString()) i = i + 1 } else if (Util.checkTypes(root, "FSA_TIMES", str.substring(i))?.let { i += it.a true } == true) { // emptiness } else i -= 2 state = -1 } 8 -> if (Util.isNumber(c)) { map.append(c) state = 9 } else { state = accAmtNumPct(str, i, map, config) if (c.toInt() == CH_SPACE && state == -1 && i + 1 < str.length && Util.isNumber(str[i + 1])) state = 12 else if (c.toInt() == CH_HYPH && state == -1 && i + 1 < str.length && Util.isNumber(str[i + 1])) state = 45 else if (state == -1 && map.type != TY_PCT) i = i - 1 } 9 -> if (Util.isDateOperator(c)) { delimiterStack.push(c) state = 25 } else if (Util.isNumber(c)) { map.append(c) counter = 5 state = 15 } else { state = accAmtNumPct(str, i, map, config) if (state == -1 && map.type != TY_PCT) {//NUM i = i - 1 } }//handle for num case 10 -> if (Util.isNumber(c)) { map.append(c) map.setType(TY_AMT, TY_AMT) state = 14 } else { //saw a fullstop randomly map.pop()//remove the dot which was appended i = i - 2 state = -1 } 11 -> if (c.toInt() == 42 || c.toInt() == 88 || c.toInt() == 120) //*Xx map.append('X') else if (c.toInt() == CH_HYPH) state = 11 else if (Util.isNumber(c)) { map.append(c) state = 13 } else if (c == ' ' && i + 1 < str.length && (str[i + 1].toInt() == 42 || str[i + 1].toInt() == 88 || str[i + 1].toInt() == 120 || Util.isNumber( str[i + 1] )) ) state = 11 else if (c.toInt() == CH_FSTP && lookAheadForInstr(str, i).let { if (it > 0) { i = it true } else { false } }) { // emptiness } else { i -= 1 state = -1 } 12 -> if (Util.isNumber(c)) { map.setType(TY_AMT, TY_AMT) map.append(c) } else if (c.toInt() == CH_COMA) //comma state = 12 else if (c.toInt() == CH_FSTP) { //dot map.append(c) state = 10 } else if (c.toInt() == CH_HYPH && i + 1 < str.length && Util.isNumber(str[i + 1])) { state = 39 } else { if (i - 1 > 0 && str[i - 1].toInt() == CH_COMA) i = i - 2 else i = i - 1 state = -1 } 13 -> if (Util.isNumber(c)) map.append(c) else if (c.toInt() == 42 || c.toInt() == 88 || c.toInt() == 120) //*Xx map.append('X') else if (c.toInt() == CH_FSTP && config.containsKey(YUGA_SOURCE_CONTEXT) && config[YUGA_SOURCE_CONTEXT] == YUGA_SC_CURR) { //LIC **150.00 fix map.setType(TY_AMT, TY_AMT) map.put(TY_AMT, map[TY_AMT]!!.replace("X".toRegex(), "")) map.append(c) state = 10 } else if (c.toInt() == CH_FSTP && lookAheadForInstr(str, i).let { if (it > 0) { i = it true } else { false } }) { // emptiness } else { i = i - 1 state = -1 } 14 -> if (Util.isNumber(c)) { map.append(c) } else if (c.toInt() == CH_PCT) { map.setType(TY_PCT, TY_PCT) state = -1 } else if ((c == 'k' || c == 'c') && i + 1 < str.length && str[i + 1] == 'm') { map.setType(TY_DST, TY_DST) i += 1 state = -1 } else if ((c == 'k' || c == 'm') && i + 1 < str.length && str[i + 1] == 'g') { map.setType(TY_WGT, TY_WGT) i += 1 state = -1 } else { var tempBrk = true if (c.toInt() == CH_FSTP && i + 1 < str.length && Util.isNumber(str[i + 1])) { val samt = map[map.type!!] if (samt!!.contains(".")) { val samtarr = samt.split("\\.".toRegex()) if (samtarr.size == 2) { map.type = TY_DTE map.put(DT_D, samtarr[0]) map.put(DT_MM, samtarr[1]) state = 19 tempBrk = false } } } if (tempBrk) { i -= 1 state = -1 } } 15 -> if (Util.isNumber(c)) { counter++ map.append(c) } else if (c.toInt() == CH_COMA) //comma state = 12 else if (c.toInt() == CH_FSTP) { //dot map.append(c) state = 10 } else if ((c.toInt() == 42 || c.toInt() == 88 || c.toInt() == 120) && i + 1 < str.length && (Util.isNumber( str[i + 1] ) || str[i + 1].toInt() == CH_HYPH || str[i + 1].toInt() == 42 || str[i + 1].toInt() == 88 || str[i + 1].toInt() == 120) ) {//*Xx map.setType(TY_ACC, TY_ACC) map.append('X') state = 11 } else if (c.toInt() == CH_SPACE && i + 2 < str.length && Util.isNumber(str[i + 1]) && Util.isNumber( str[i + 2] ) ) { state = 41 } else { i = i - 1 state = -1 }// else if (c == Constants.CH_ATRT) { // delimiterStack.push(c); // state = 43; // } 16 -> if (Util.isNumber(c)) { map.upgrade(c) state = 17 } else if (c.toInt() == CH_SPACE || c.toInt() == CH_COMA) state = 16 else if (checkMonthType(str, i)?.let { map.put(DT_MMM, it.b) i += it.a true } == true) { state = 24 } else if (c.toInt() == CH_FSTP) { //dot map.setType(TY_NUM, TY_NUM) map.append(c) state = 10 } else if (i > 0 && Util.checkTypes(root, "FSA_TIMES", str.substring(i))?.let { map.setType(TY_TME, null) var s = str.substring(0, i) if (it.b == "mins" || it.b == "minutes") s = "00$s" extractTime(s, map.getValMap()) i += it.a true } == true) { state = -1 } else {//this is just a number, not a date //to cater to 16 -Nov -17 if (delimiterStack.pop() .toInt() == CH_SPACE && c.toInt() == CH_HYPH && i + 1 < str.length && (Util.isNumber( str[i + 1] ) || checkMonthType(str, i + 1) != null) ) { state = 16 } else { map.setType(TY_NUM, TY_NUM) var j = i while (!Util.isNumber(str[j])) j-- i = j state = -1 } }//we should handle amt case, where comma led to 16 as opposed to 12 17 -> if (Util.isNumber(c)) { map.append(c) state = 18 } else if (Util.isDateOperator(c)) { delimiterStack.push(c) state = 19 } else if (c.toInt() == CH_COMA && delimiterStack.pop().toInt() == CH_COMA) { //comma map.setType(TY_NUM, TY_NUM) state = 12 } else if (c.toInt() == CH_FSTP && delimiterStack.pop().toInt() == CH_COMA) { //dot map.setType(TY_NUM, TY_NUM) map.append(c) state = 10 } else { map.setType(TY_STR, TY_STR) i = i - 1 state = -1 }//we should handle amt case, where comma led to 16,17 as opposed to 12 18 -> if (Util.isDateOperator(c)) { delimiterStack.push(c) state = 19 } else if (Util.isNumber(c) && delimiterStack.pop().toInt() == CH_COMA) { map.setType(TY_NUM, TY_NUM) state = 12 map.append(c) } else if (Util.isNumber(c) && delimiterStack.pop().toInt() == CH_HYPH) { map.setType(TY_NUM, TY_NUM) state = 42 map.append(c) } else if (c.toInt() == CH_COMA && delimiterStack.pop().toInt() == CH_COMA) { //comma map.setType(TY_NUM, TY_NUM) state = 12 } else if (c.toInt() == CH_FSTP && delimiterStack.pop().toInt() == CH_COMA) { //dot map.setType(TY_NUM, TY_NUM) map.append(c) state = 10 } else if (c.toInt() == CH_FSTP && map.contains(DT_D) && map.contains(DT_MM)) { //dot state = -1 } else { map.setType(TY_STR, TY_STR) i = i - 1 state = -1 }//we should handle amt case, where comma led to 16,17 as opposed to 12 19 //year -> if (Util.isNumber(c)) { map.upgrade(c) state = 20 } else { i = i - 2 state = -1 } 20 //year++ -> if (Util.isNumber(c)) { map.append(c) state = 21 } else if (c == ':') { if (map.contains(DT_YY)) map.convert(DT_YY, DT_HH) else if (map.contains(DT_YYYY)) map.convert(DT_YYYY, DT_HH) state = 4 } else { map.remove(DT_YY)//since there is no one number year i = i - 1 state = -1 } 21 -> if (Util.isNumber(c)) { map.upgrade(c) state = 22 } else if (c == ':') { if (map.contains(DT_YY)) map.convert(DT_YY, DT_HH) else if (map.contains(DT_YYYY)) map.convert(DT_YYYY, DT_HH) state = 4 } else { i = i - 1 state = -1 } 22 -> if (Util.isNumber(c)) { map.append(c) state = -1 } else { map.remove(DT_YYYY)//since there is no three number year i = i - 1 state = -1 } 24 -> if (Util.isDateOperator(c) || c.toInt() == CH_COMA) { delimiterStack.push(c) state = 24 } else if (Util.isNumber(c)) { map.upgrade(c) state = 20 } else if (c.toInt() == CH_SQOT && i + 1 < str.length && Util.isNumber(str[i + 1])) { state = 24 } else if (c == '|') { state = 24 } else { i = i - 1 state = -1 } 25//potential year start comes here -> if (Util.isNumber(c)) { map.setType(TY_DTE, DT_YYYY) map.put(DT_MM, c) state = 26 } else if (i > 0 && Util.checkTypes(root, "FSA_TIMES", str.substring(i))?.let { map.setType(TY_TME, null) var s = str.substring(0, i) if (it.b == "mins") s = "00$s" extractTime(s, map.getValMap()) i += it.a true } == true) { state = -1 } else { //it wasn't year, it was just a number i = i - 2 state = -1 } 26 -> if (Util.isNumber(c)) { map.append(c) state = 27 } else { map.setType(TY_STR, TY_STR) i = i - 1 state = -1 } 27 -> if (Util.isDateOperator(c)) { delimiterStack.push(c) state = 28 } else if (Util.isNumber(c)) {//it was a number, most probably telephone number if (map.type == TY_DTE) { map.setType(TY_NUM, TY_NUM) } map.append(c) if ((delimiterStack.pop().toInt() == CH_SLSH || delimiterStack.pop() .toInt() == CH_HYPH) && i + 1 < str.length && Util.isNumber( str[i + 1] ) && (i + 2 == str.length || Util.isDelimiter(str[i + 2])) ) {//flight time 0820/0950 map.setType(TY_TMS, TY_TMS) map.append(str[i + 1]) i = i + 1 state = -1 } else if (delimiterStack.pop().toInt() == CH_SPACE) { state = 41 } else state = 12 } else if (c.toInt() == 42 || c.toInt() == 88 || c.toInt() == 120) {//*Xx map.setType(TY_ACC, TY_ACC) map.append('X') state = 11 } else { map.setType(TY_STR, TY_STR) i = i - 1 state = -1 } 28 -> if (Util.isNumber(c)) { map.put(DT_D, c) state = 29 } else { map.setType(TY_STR, TY_STR) i = i - 2 state = -1 } 29 -> { if (Util.isNumber(c)) { map.append(c) } else i = i - 1 state = -1 } 30 -> if (c.toInt() == CH_COMA || c.toInt() == CH_SPACE) state = 30 else if (Util.isNumber(c)) { map.put(DT_D, c) state = 31 } else { map.type = TY_DTE i = i - 1 state = -1 } 31 -> if (Util.isNumber(c)) { map.append(c) state = 32 } else if (checkMonthType(str, i)?.let { map.put(DT_MMM, it.b) i += it.a true } == true) { state = 24 } else if (c.toInt() == CH_COMA || c.toInt() == CH_SPACE) state = 32 else { i = i - 1 state = -1 } 32 -> if (checkMonthType(str, i)?.let { map.put(DT_MMM, it.b) i += it.a true } == true) { state = 24 } else if (c.toInt() == CH_COMA || c.toInt() == CH_SPACE) state = 32 else if (Util.checkTypes(root, "FSA_DAYSFFX", str.substring(i))?.let { i += it.a true } == true) { state = 32 } else { var j = i while (!Util.isNumber(str[j])) j-- i = j state = -1 } 33 -> if (Util.isNumber(c)) { map.put(DT_D, c) state = 34 } else if (c.toInt() == CH_SPACE || c.toInt() == CH_COMA || c.toInt() == CH_HYPH) state = 33 else { map.type = TY_DTE i -= 1 state = -1 } 34 -> if (Util.isNumber(c)) { map.append(c) state = 35 } else if (c.toInt() == CH_SPACE || c.toInt() == CH_COMA) state = 35 else { map.type = TY_DTE i -= 1 state = -1 } 35 -> if (Util.isNumber(c)) { if (i > 1 && Util.isNumber(str[i - 1])) { map.convert(DT_D, DT_YYYY) map.append(c) } else map.put(DT_YY, c) state = 20 } else if (c.toInt() == CH_SPACE || c.toInt() == CH_COMA) state = 40 else { map.type = TY_DTE i -= 1 state = -1 } 36 -> if (Util.isNumber(c)) { map.append(c) counter++ } else if (c.toInt() == CH_FSTP && i + 1 < str.length && Util.isNumber(str[i + 1])) { map.append(c) state = 10 } else if (c.toInt() == CH_HYPH && i + 1 < str.length && Util.isNumber(str[i + 1])) { delimiterStack.push(c) map.append(c) state = 16 } else { if (counter == 12 || Util.isNumber(str.substring(1, i))) map.setType(TY_NUM, TY_NUM) else return null state = -1 } 37 -> if (Util.isNumber(c)) { map.setType(TY_AMT, TY_AMT) map.put(TY_AMT, '-') map.append(c) state = 12 } else if (c.toInt() == CH_FSTP) { map.put(TY_AMT, '-') map.append(c) state = 10 } else state = -1 38 -> { i = map.index!! state = -1 } 39//instrno -> if (Util.isNumber(c)) map.append(c) else { map.setType(TY_ACC, TY_ACC) state = -1 } 40 -> if (Util.isNumber(c)) { map.put(DT_YY, c) state = 20 } else if (c.toInt() == CH_SPACE || c.toInt() == CH_COMA) state = 40 else { map.type = TY_DTE i -= 1 state = -1 } 41//for phone numbers; same as 12 + space; coming from 27 -> when { Util.isNumber(c) -> { map.append(c) } c.toInt() == CH_SPACE -> state = 41 else -> { i = if (i - 1 > 0 && str[i - 1].toInt() == CH_SPACE) i - 2 else i - 1 state = -1 } } 42 //18=12 case, where 7-2209 was becoming amt as part of phn support -> if (Util.isNumber(c)) { map.append(c) } else if (c.toInt() == CH_HYPH && i + 1 < str.length && Util.isNumber(str[i + 1])) { state = 39 } else { i -= 1 state = -1 } 43 //1234567890@ybl -> if (Util.isLowerAlpha(c) || Util.isNumber(c)) { map.setType(TY_VPD, TY_VPD) map.append(delimiterStack.pop()) map.append(c) state = 44 } else { state = -1 } 44 -> if (Util.isLowerAlpha(c) || Util.isNumber(c) || c.toInt() == CH_FSTP) { map.append(c) state = 44 } else state = -1 45 -> if (Util.isNumber(c)) { map.append(c) } else if (c.toInt() == CH_HYPH && i + 1 < str.length && Util.isNumber(str[i + 1])) { state = 39 } else { i -= if (i - 1 > 0 && str[i - 1].toInt() == CH_COMA) 2 else 1 state = -1 } } i++ if (D_DEBUG) { log("ch:" + c + " state:" + state + " map:" + map.print()) } } if (map.type == null) return null //sentence end cases if (state == 10) { map.pop() i -= 1 } else if (state == 36) { if (counter == 12 || Util.isNumber(str.substring(1, i))) map.setType(TY_NUM, TY_NUM) else return null } if (map.type == TY_AMT) { if (!map.contains(map.type!!) || map[map.type!!]!!.contains(".") && map[map.type!!]!!.split("\\.".toRegex()) .dropLastWhile { it.isEmpty() }.toTypedArray()[0].length > 8 || !map[map.type!!]!!.contains( "." ) && map[map.type!!]!!.length > 8 ) map.setType(TY_NUM, TY_NUM) } if (map.type == TY_NUM) { if (i < str.length && str[i].isAlpha() && !config.containsKey(YUGA_SOURCE_CONTEXT)) { var j = i while (j < str.length && str[j] != ' ') j++ map.setType(TY_STR, TY_STR) i = j } else if (map[TY_NUM] != null) { if (map[TY_NUM]!!.length == 10 && (map[TY_NUM]!![0] == '9' || map[TY_NUM]!![0] == '8' || map[TY_NUM]!![0] == '7')) map.setVal("num_class", TY_PHN) else if (map[TY_NUM]!!.length == 12 && map[TY_NUM]!!.startsWith("91")) map.setVal("num_class", TY_PHN) else if (map[TY_NUM]!!.length == 11 && map[TY_NUM]!!.startsWith("18")) map.setVal("num_class", TY_PHN) else if (map[TY_NUM]!!.length == 11 && map[TY_NUM]!![0] == '0') map.setVal("num_class", TY_PHN) else map.setVal("num_class", TY_NUM) } } else if (map.type == TY_DTE && i + 1 < str.length) { val `in` = i + skip(str.substring(i)) val sub = str.substring(`in`) if (`in` < str.length) { val pFSATimePrex = Util.checkTypes(root, "FSA_TIMEPRFX", sub) val pFSATz = Util.checkTypes(root, "FSA_TZ", sub) if (Util.isNumber(str[`in`]) || Util.checkTypes( root, "FSA_MONTHS", sub ) != null || Util.checkTypes(root, "FSA_DAYS", sub) != null ) { val kl = parseInternal(sub, config) if (kl != null && kl.b.type == TY_DTE) { map.putAll(kl.b) i = `in` + kl.a } } else if (pFSATimePrex != null) { val iTime = `in` + pFSATimePrex.a + 1 + skip(str.substring(`in` + pFSATimePrex.a + 1)) if (iTime < str.length && (Util.isNumber(str[iTime]) || Util.checkTypes( root, "FSA_DAYS", str.substring(iTime) ) != null) ) { val p_ = parseInternal(str.substring(iTime), config) if (p_ != null && p_.b.type == TY_DTE) { map.putAll(p_.b) i = iTime + p_.a } } } else if (pFSATz != null) { val j = skipForTZ(str.substring(`in` + pFSATz.a + 1), map) i = `in` + pFSATz.a + 1 + j } else if (sub.toLowerCase().startsWith("pm") || sub.toLowerCase().startsWith("am")) { //todo handle appropriately for pm i = `in` + 2 } } } else if (map.type == TY_TMS) { val v = map[map.type!!] if (v != null && v.length == 8 && Util.isHour(v[0], v[1]) && Util.isHour(v[4], v[5])) { extractTime(v.substring(0, 4), map.getValMap(), "dept") extractTime(v.substring(4, 8), map.getValMap(), "arrv") } } return Pair(i, map) } private fun checkMonthType( str: String, i: Int ) = Util.checkTypes(root, "FSA_MONTHS", str.substring(i)) private fun skipForTZ(str: String, map: FsaContextMap): Int { var state = 1 var i = 0 var c: Char while (state > 0 && i < str.length) { c = str[i] when (state) { 1 -> if (c.toInt() == CH_SPACE || c.toInt() == CH_PLUS || Util.isNumber(c)) state = 1 else if (c.toInt() == CH_COLN) state = 2 else { val s_ = str.substring(0, i).trim { it <= ' ' } if (s_.length == 4 && Util.isNumber(s_)) {//we captured a year after IST Mon Sep 04 13:47:13 IST 2017 map.put(DT_YYYY, s_) state = -2 } else state = -1 } 2 -> //todo re-adjust GMT time, current default +5:30 for IST state = if (Util.isNumber(c)) 3 else -1 3 -> state = if (Util.isNumber(c)) 4 else -1 4 -> state = if (c.toInt() == CH_SPACE) 5 else -2 5 -> { val sy = str.substring(i, i + 4) if (i + 3 < str.length && Util.isNumber(sy)) { map.put(DT_YYYY, sy) i += 3 } state = -2 } } i++ } val s_ = str.substring(0, i).trim { it <= ' ' } if (state == 1 && s_.length == 4 && Util.isNumber(s_)) //we captured a year after IST Mon Sep 04 13:47:13 IST 2017 map.put(DT_YYYY, s_) return if (state == -1) 0 else i } private fun skip(str: String): Int { var i = 0 while (i < str.length) { if (str[i] == ' ' || str[i] == ',' || str[i] == '(' || str[i] == ':') i++ else break } return i } private fun nextSpace(str: String): Int { var i = 0 while (i < str.length) { if (str[i] == ' ') return i else i++ } return i } private fun accAmtNumPct(str: String, i: Int, map: FsaContextMap, config: Map<String, String>): Int { //acc num amt pct val c = str[i] val subStr = str.substring(i) val pFSAAmt = Util.checkTypes(root, "FSA_AMT", subStr) val pFSATimes = Util.checkTypes(root, "FSA_TIMES", subStr) if (c.toInt() == CH_FSTP) { //dot if (i == 0 && config.containsKey(YUGA_SOURCE_CONTEXT) && config[YUGA_SOURCE_CONTEXT] == YUGA_SC_CURR) map.setType(TY_AMT, TY_AMT) map.append(c) return 10 } else if (c.toInt() == 42 || c.toInt() == 88 || c.toInt() == 120) {//*Xx map.setType(TY_ACC, TY_ACC) map.append('X') return 11 } else if (c.toInt() == CH_COMA) { //comma return 12 } else if (c.toInt() == CH_PCT || c.toInt() == CH_SPACE && i + 1 < str.length && str[i + 1].toInt() == CH_PCT) { //pct map.setType(TY_PCT, TY_PCT) return -1 } else if (c.toInt() == CH_PLUS) { if (config.containsKey(YUGA_SOURCE_CONTEXT) && config[YUGA_SOURCE_CONTEXT] == YUGA_SC_CURR) { return -1 } map.setType(TY_STR, TY_STR) return 36 } else if (i > 0 && pFSAAmt != null) { map.index = pFSAAmt.a map.setType(TY_AMT, TY_AMT) map.append(getAmt(pFSAAmt.b)) return 38 } else if (i > 0 && pFSATimes != null) { val ind = i + pFSATimes.a map.index = ind map.setType(TY_TME, null) var s = str.substring(0, i) if (pFSATimes.b == "mins") s = "00$s" extractTime(s, map.getValMap()) return 38 } else return -1 } private fun getAmt(type: String): String { when (type) { "lakh", "lac" -> return "00000" "k" -> return "000" else -> return "" } } private fun extractTime(str: String, valMap: MutableMap<String, String>, vararg prefix: String) { var pre = "" if (prefix.isNotEmpty()) pre = prefix[0] + "_" val pattern = "([0-9]{2})([0-9]{2})?([0-9]{2})?".toRegex() val m = pattern.find(str) m?.let { val gps = it.groups valMap[pre + "time"] = gps[1]?.value.toString() + if (it.groups.size > 1 && gps[2] != null) ":" + gps[2]?.value.toString() else ":00" } } private fun lookAheadForInstr(str: String, index: Int): Int { var c: Char for (i in index until str.length) { c = str[i] if (c.toInt() == CH_FSTP) { } else return if (c.toInt() == 42 || c.toInt() == 88 || c.toInt() == 120 || Util.isNumber(c)) i else -1 } return -1 } internal class DelimiterStack { private val stack: MutableList<Char> = mutableListOf() fun push(ch: Char) { stack.add(ch) } fun pop(): Char { return if (stack.isNotEmpty()) { stack[stack.size - 1] } else '~' } } }
39.30384
161
0.376503
9b886cdcaf3e48d450367daf38c2c337521a2538
47
lua
Lua
entities/entities/npc_headcrab_black.lua
Ifzero-org/zombieMaster
72932ee1c6955f045566dcd11e13f375431ddbe5
[ "Apache-2.0" ]
null
null
null
entities/entities/npc_headcrab_black.lua
Ifzero-org/zombieMaster
72932ee1c6955f045566dcd11e13f375431ddbe5
[ "Apache-2.0" ]
null
null
null
entities/entities/npc_headcrab_black.lua
Ifzero-org/zombieMaster
72932ee1c6955f045566dcd11e13f375431ddbe5
[ "Apache-2.0" ]
null
null
null
ENT.Type = "point" ENT.Base = "npc_remove_base"
23.5
28
0.723404
5958d4ea063fb2877fd9520ffa93b9b86eba86bc
12,885
h
C
vendors/marvell/WMSDK/mw320/sdk/src/wlan/wifidriver/incl/mlan_sdio.h
cringti/amazon-freertos
c334212b824703a6c5d4069fcc001511e6955c14
[ "MIT" ]
3
2020-03-18T09:56:10.000Z
2021-04-23T17:19:01.000Z
vendors/marvell/WMSDK/mw320/sdk/src/wlan/wifidriver/incl/mlan_sdio.h
swhan1610/amazon-freertos
a9b6dafaf09dda6b0762688a99ab68f27657b29e
[ "MIT" ]
null
null
null
vendors/marvell/WMSDK/mw320/sdk/src/wlan/wifidriver/incl/mlan_sdio.h
swhan1610/amazon-freertos
a9b6dafaf09dda6b0762688a99ab68f27657b29e
[ "MIT" ]
1
2022-01-28T07:39:40.000Z
2022-01-28T07:39:40.000Z
/** @file mlan_sdio.h * * @brief This file contains definitions for SDIO interface. * * (C) Copyright 2008-2018 Marvell International Ltd. All Rights Reserved * * MARVELL CONFIDENTIAL * The source code contained or described herein and all documents related to * the source code ("Material") are owned by Marvell International Ltd or its * suppliers or licensors. Title to the Material remains with Marvell International Ltd * or its suppliers and licensors. The Material contains trade secrets and * proprietary and confidential information of Marvell or its suppliers and * licensors. The Material is protected by worldwide copyright and trade secret * laws and treaty provisions. No part of the Material may be used, copied, * reproduced, modified, published, uploaded, posted, transmitted, distributed, * or disclosed in any way without Marvell's prior express written permission. * * No license under any patent, copyright, trade secret or other intellectual * property right is granted to or conferred upon you by disclosure or delivery * of the Materials, either expressly, by implication, inducement, estoppel or * otherwise. Any license under such intellectual property rights must be * express and approved by Marvell in writing. * */ /**************************************************** Change log: ****************************************************/ #ifndef _MLAN_SDIO_H #define _MLAN_SDIO_H /** Block mode */ #define BLOCK_MODE 1 /** Fixed address mode */ #define FIXED_ADDRESS 0 /* Host Control Registers */ /** Host Control Registers : Host to Card Event */ #define HOST_TO_CARD_EVENT_REG 0x00 /** Host Control Registers : Host terminates Command 53 */ #define HOST_TERM_CMD53 (0x1U << 2) /** Host Control Registers : Host without Command 53 finish host */ #define HOST_WO_CMD53_FINISH_HOST (0x1U << 2) /** Host Control Registers : Host power up */ #define HOST_POWER_UP (0x1U << 1) /** Host Control Registers : Host power down */ #define HOST_POWER_DOWN (0x1U << 0) /** Host Control Registers : Host interrupt RSR */ #define HOST_INT_RSR_REG 0x01 /** Host Control Registers : Upload host interrupt RSR */ #define UP_LD_HOST_INT_RSR (0x1U) #define HOST_INT_RSR_MASK 0x3F /** Host Control Registers : Host interrupt mask */ #define HOST_INT_MASK_REG 0x02 /** Host Control Registers : Upload host interrupt mask */ #define UP_LD_HOST_INT_MASK (0x1U) /** Host Control Registers : Download host interrupt mask */ #define DN_LD_HOST_INT_MASK (0x2U) /** Enable Host interrupt mask */ #define HIM_ENABLE (UP_LD_HOST_INT_MASK | DN_LD_HOST_INT_MASK) /** Disable Host interrupt mask */ #define HIM_DISABLE 0xff /** Host Control Registers : Host interrupt status */ #define HOST_INT_STATUS_REG 0x03 /** Host Control Registers : Upload host interrupt status */ #define UP_LD_HOST_INT_STATUS (0x1U) /** Host Control Registers : Download host interrupt status */ #define DN_LD_HOST_INT_STATUS (0x2U) #define WLAN_VALUE1 0x80002080 /** Port for registers */ #define REG_PORT 0 /** LSB of read bitmap */ #define RD_BITMAP_L 0x04 /** MSB of read bitmap */ #define RD_BITMAP_U 0x05 /** LSB of write bitmap */ #define WR_BITMAP_L 0x06 /** MSB of write bitmap */ #define WR_BITMAP_U 0x07 /** LSB of read length for port 0 */ #define RD_LEN_P0_L 0x08 /** MSB of read length for port 0 */ #define RD_LEN_P0_U 0x09 /** Ctrl port */ #define CTRL_PORT 0 /** Ctrl port mask */ #define CTRL_PORT_MASK 0x0001 /** Data port mask */ #define DATA_PORT_MASK 0xfffe /** Misc. Config Register : Auto Re-enable interrupts */ #define AUTO_RE_ENABLE_INT MBIT(4) /** Host Control Registers : Host transfer status */ #define HOST_RESTART_REG 0x28 /** Host Control Registers : Download CRC error */ #define DN_LD_CRC_ERR (0x1U << 2) /** Host Control Registers : Upload restart */ #define UP_LD_RESTART (0x1U << 1) /** Host Control Registers : Download restart */ #define DN_LD_RESTART (0x1U << 0) /* Card Control Registers */ /** Card Control Registers : Card to host event */ #define CARD_TO_HOST_EVENT_REG 0x30 /** Card Control Registers : Card I/O ready */ #define CARD_IO_READY (0x1U << 3) /** Card Control Registers : CIS card ready */ #define CIS_CARD_RDY (0x1U << 2) /** Card Control Registers : Upload card ready */ #define UP_LD_CARD_RDY (0x1U << 1) /** Card Control Registers : Download card ready */ #define DN_LD_CARD_RDY (0x1U << 0) /** Card Control Registers : Host interrupt mask register */ #define HOST_INTERRUPT_MASK_REG 0x34 /** Card Control Registers : Host power interrupt mask */ #define HOST_POWER_INT_MASK (0x1U << 3) /** Card Control Registers : Abort card interrupt mask */ #define ABORT_CARD_INT_MASK (0x1U << 2) /** Card Control Registers : Upload card interrupt mask */ #define UP_LD_CARD_INT_MASK (0x1U << 1) /** Card Control Registers : Download card interrupt mask */ #define DN_LD_CARD_INT_MASK (0x1U << 0) /** Card Control Registers : Card interrupt status register */ #define CARD_INTERRUPT_STATUS_REG 0x38 /** Card Control Registers : Power up interrupt */ #define POWER_UP_INT (0x1U << 4) /** Card Control Registers : Power down interrupt */ #define POWER_DOWN_INT (0x1U << 3) /** Card Control Registers : Card interrupt RSR register */ #define CARD_INTERRUPT_RSR_REG 0x3c /** Card Control Registers : Power up RSR */ #define POWER_UP_RSR (0x1U << 4) /** Card Control Registers : Power down RSR */ #define POWER_DOWN_RSR (0x1U << 3) /** Card Control Registers : SQ Read base address 0 register */ #define READ_BASE_0_REG 0x40 /** Card Control Registers : SQ Read base address 1 register */ #define READ_BASE_1_REG 0x41 /** Card Control Registers : Card revision register */ #define CARD_REVISION_REG 0x5c /** Firmware status 0 register (SCRATCH0_0) */ #define CARD_FW_STATUS0_REG 0x60 /** Firmware status 1 register (SCRATCH0_1) */ #define CARD_FW_STATUS1_REG 0x61 /** Rx length register (SCRATCH0_2) */ #define CARD_RX_LEN_REG 0x62 /** Rx unit register (SCRATCH0_3) */ #define CARD_RX_UNIT_REG 0x63 /** Card Control Registers : Card OCR 0 register */ #define CARD_OCR_0_REG 0x68 /** Card Control Registers : Card OCR 1 register */ #define CARD_OCR_1_REG 0x69 /** Card Control Registers : Card OCR 3 register */ #define CARD_OCR_3_REG 0x6A /** Card Control Registers : Card config register */ #define CARD_CONFIG_REG 0x6B /** Card Control Registers : Miscellaneous Configuration Register */ #define CARD_MISC_CFG_REG 0x6C /** Card Control Registers : Debug 0 register */ #define DEBUG_0_REG 0x70 /** Card Control Registers : SD test BUS 0 */ #define SD_TESTBUS0 (0x1U) /** Card Control Registers : Debug 1 register */ #define DEBUG_1_REG 0x71 /** Card Control Registers : SD test BUS 1 */ #define SD_TESTBUS1 (0x1U) /** Card Control Registers : Debug 2 register */ #define DEBUG_2_REG 0x72 /** Card Control Registers : SD test BUS 2 */ #define SD_TESTBUS2 (0x1U) /** Card Control Registers : Debug 3 register */ #define DEBUG_3_REG 0x73 /** Card Control Registers : SD test BUS 3 */ #define SD_TESTBUS3 (0x1U) /** Host Control Registers : I/O port 0 */ #define IO_PORT_0_REG 0x78 /** Host Control Registers : I/O port 1 */ #define IO_PORT_1_REG 0x79 /** Host Control Registers : I/O port 2 */ #define IO_PORT_2_REG 0x7A /** Event header Len*/ #define MLAN_EVENT_HEADER_LEN 8 /** SDIO byte mode size */ #define MAX_BYTE_MODE_SIZE 512 #if defined(SDIO_MULTI_PORT_TX_AGGR) || defined(SDIO_MULTI_PORT_RX_AGGR) /** The base address for packet with multiple ports aggregation */ #define SDIO_MPA_ADDR_BASE 0x1000 #endif #ifdef SDIO_MULTI_PORT_TX_AGGR /** SDIO Tx aggregation in progress ? */ #define MP_TX_AGGR_IN_PROGRESS(a) (a->mpa_tx.pkt_cnt>0) /** SDIO Tx aggregation buffer room for next packet ? */ #define MP_TX_AGGR_BUF_HAS_ROOM(a,mbuf, len) ((a->mpa_tx.buf_len+len)<= a->mpa_tx.buf_size) /** Copy current packet (SDIO Tx aggregation buffer) to SDIO buffer */ #define MP_TX_AGGR_BUF_PUT(a, mbuf, port) do{ \ pmadapter->callbacks.moal_memmove(a->pmoal_handle, &a->mpa_tx.buf[a->mpa_tx.buf_len],mbuf->pbuf+mbuf->data_offset,mbuf->data_len);\ a->mpa_tx.buf_len += mbuf->data_len; \ if(!a->mpa_tx.pkt_cnt){ \ a->mpa_tx.start_port = port; \ } \ if(a->mpa_tx.start_port<=port){ \ a->mpa_tx.ports |= (1<<(a->mpa_tx.pkt_cnt)); \ }else{ \ a->mpa_tx.ports |= (1<<(a->mpa_tx.pkt_cnt+1+(MAX_PORT - a->mp_end_port))); \ } \ a->mpa_tx.pkt_cnt++; \ }while(0); /** SDIO Tx aggregation limit ? */ #define MP_TX_AGGR_PKT_LIMIT_REACHED(a) (a->mpa_tx.pkt_cnt==a->mpa_tx.pkt_aggr_limit) /** SDIO Tx aggregation port limit ? */ #define MP_TX_AGGR_PORT_LIMIT_REACHED(a) ((a->curr_wr_port < \ a->mpa_tx.start_port) && (((MAX_PORT - \ a->mpa_tx.start_port) + a->curr_wr_port) >= \ SDIO_MP_AGGR_DEF_PKT_LIMIT)) /** Reset SDIO Tx aggregation buffer parameters */ #define MP_TX_AGGR_BUF_RESET(a) do{ \ a->mpa_tx.pkt_cnt = 0; \ a->mpa_tx.buf_len = 0; \ a->mpa_tx.ports = 0; \ a->mpa_tx.start_port = 0; \ } while(0); #endif /* SDIO_MULTI_PORT_TX_AGGR */ #ifdef SDIO_MULTI_PORT_RX_AGGR /** SDIO Rx aggregation limit ? */ #define MP_RX_AGGR_PKT_LIMIT_REACHED(a) (a->mpa_rx.pkt_cnt== a->mpa_rx.pkt_aggr_limit) /** SDIO Rx aggregation port limit ? */ #define MP_RX_AGGR_PORT_LIMIT_REACHED(a) ((a->curr_rd_port < \ a->mpa_rx.start_port) && (((MAX_PORT - \ a->mpa_rx.start_port) + a->curr_rd_port) >= \ SDIO_MP_AGGR_DEF_PKT_LIMIT)) /** SDIO Rx aggregation in progress ? */ #define MP_RX_AGGR_IN_PROGRESS(a) (a->mpa_rx.pkt_cnt>0) /** SDIO Rx aggregation buffer room for next packet ? */ #define MP_RX_AGGR_BUF_HAS_ROOM(a,rx_len) ((a->mpa_rx.buf_len+rx_len)<=a->mpa_rx.buf_size) /** Prepare to copy current packet from card to SDIO Rx aggregation buffer */ #define MP_RX_AGGR_SETUP(a, mbuf, port, rx_len) do{ \ a->mpa_rx.buf_len += rx_len; \ if(!a->mpa_rx.pkt_cnt){ \ a->mpa_rx.start_port = port; \ } \ if(a->mpa_rx.start_port<=port){ \ a->mpa_rx.ports |= (1<<(a->mpa_rx.pkt_cnt)); \ }else{ \ a->mpa_rx.ports |= (1<<(a->mpa_rx.pkt_cnt+1)); \ } \ a->mpa_rx.mbuf_arr[a->mpa_rx.pkt_cnt] = mbuf; \ a->mpa_rx.len_arr[a->mpa_rx.pkt_cnt] = rx_len; \ a->mpa_rx.pkt_cnt++; \ }while(0); /** Reset SDIO Rx aggregation buffer parameters */ #define MP_RX_AGGR_BUF_RESET(a) do{ \ a->mpa_rx.pkt_cnt = 0; \ a->mpa_rx.buf_len = 0; \ a->mpa_rx.ports = 0; \ a->mpa_rx.start_port = 0; \ } while(0); #endif /* SDIO_MULTI_PORT_RX_AGGR */ /** Enable host interrupt */ mlan_status wlan_enable_host_int(pmlan_adapter pmadapter); /** Probe and initialization function */ mlan_status wlan_sdio_probe(pmlan_adapter pmadapter); /** multi interface download check */ mlan_status wlan_check_winner_status(mlan_adapter * pmadapter, t_u32 * val); /** Firmware status check */ mlan_status wlan_check_fw_status(mlan_adapter * pmadapter, t_u32 pollnum); /** Read interrupt status */ t_void wlan_interrupt(pmlan_adapter pmadapter); /** Process Interrupt Status */ /* wmsdk */ /* mlan_status wlan_process_int_status(mlan_adapter * pmadapter); */ /** Transfer data to card */ mlan_status wlan_sdio_host_to_card(mlan_adapter * pmadapter, t_u8 type, mlan_buffer * mbuf, mlan_tx_param * tx_param); mlan_status wlan_set_sdio_gpio_int(IN pmlan_private priv); mlan_status wlan_cmd_sdio_gpio_int(pmlan_private pmpriv, IN HostCmd_DS_COMMAND * cmd, IN t_u16 cmd_action, IN t_void * pdata_buf); #endif /* _MLAN_SDIO_H */
41.166134
135
0.636865
15a949d885be9c18269de0c46d9fe494fb31604d
370
rb
Ruby
app/helpers/courses_helper.rb
sonnguyen9800/RAD19_group_s3634703_s3634132-
7abe8ad8d4df6efcb85be74c412f3973d0043825
[ "Unlicense" ]
1
2020-05-09T12:43:42.000Z
2020-05-09T12:43:42.000Z
app/helpers/courses_helper.rb
sonnguyen9800/RAD19_group_s3634703_s3634132-
7abe8ad8d4df6efcb85be74c412f3973d0043825
[ "Unlicense" ]
6
2020-06-25T09:48:01.000Z
2022-03-31T01:09:12.000Z
app/helpers/courses_helper.rb
sonnguyen9800/RAD19_group_s3634703_s3634132-
7abe8ad8d4df6efcb85be74c412f3973d0043825
[ "Unlicense" ]
null
null
null
module CoursesHelper def current_coordinator_owned? @course = Course.find(params[:id]) if logged_in? == false flash[:danger] = 'Error' redirect_to courses_path elsif (logged_in? && current_coordinator == @course.coordinator) || current_coordinator.adminflag == true return true else redirect_to courses_path end end end
23.125
109
0.686486
e9a34ec123d34c42110dfe3ad5096a6d9d3e070d
115
rb
Ruby
app/models/system_access_request_group.rb
hcbl1212/administrative_forms
a9c7e529ff7f30be65597ddbcd88eab0f2110db9
[ "MIT" ]
null
null
null
app/models/system_access_request_group.rb
hcbl1212/administrative_forms
a9c7e529ff7f30be65597ddbcd88eab0f2110db9
[ "MIT" ]
null
null
null
app/models/system_access_request_group.rb
hcbl1212/administrative_forms
a9c7e529ff7f30be65597ddbcd88eab0f2110db9
[ "MIT" ]
null
null
null
class SystemAccessRequestGroup < ApplicationRecord belongs_to :group belongs_to :system_access_request end
23
50
0.826087
cb335bbea455cc947098e6ca86ee14a89aad8060
1,559
h
C
swig/classes/include/wxPrintDialogData.h
eumario/wxruby
c348d0dd64f9549f51cbfd22658de42e7ca37194
[ "MIT" ]
7
2019-02-18T23:54:31.000Z
2021-12-04T01:06:37.000Z
swig/classes/include/wxPrintDialogData.h
eumario/wxruby
c348d0dd64f9549f51cbfd22658de42e7ca37194
[ "MIT" ]
null
null
null
swig/classes/include/wxPrintDialogData.h
eumario/wxruby
c348d0dd64f9549f51cbfd22658de42e7ca37194
[ "MIT" ]
null
null
null
// Copyright 2004-2007, wxRuby development team // released under the MIT-like wxRuby2 license #if !defined(_wxPrintDialogData_h_) #define _wxPrintDialogData_h_ class wxPrintDialogData : public wxObject { public: wxPrintDialogData(); wxPrintDialogData(const wxPrintDialogData& dialogData); wxPrintDialogData(const wxPrintData& printData); ~wxPrintDialogData(); int GetFromPage() const; int GetToPage() const; int GetMinPage() const; int GetMaxPage() const; int GetNoCopies() const; bool GetAllPages() const; bool GetSelection() const; bool GetCollate() const; bool GetPrintToFile() const; void SetFromPage(int v); void SetToPage(int v); void SetMinPage(int v); void SetMaxPage(int v); void SetNoCopies(int v); void SetAllPages(bool flag); void SetSelection(bool flag); void SetCollate(bool flag); void SetPrintToFile(bool flag); void EnablePrintToFile(bool flag); void EnableSelection(bool flag); void EnablePageNumbers(bool flag); void EnableHelp(bool flag); bool GetEnablePrintToFile() const; bool GetEnableSelection() const; bool GetEnablePageNumbers() const; bool GetEnableHelp() const; // Is this data OK for showing the print dialog? bool Ok() const; wxPrintData& GetPrintData(); void SetPrintData(const wxPrintData& printData); void operator=(const wxPrintDialogData& data); void operator=(const wxPrintData& data); // Sets internal m_printData member }; #endif
27.839286
81
0.697883
7c1200d4add48a65205e3ae99fd3738aead0f0f3
351
swift
Swift
validation-test/compiler_crashers_fixed/01420-swift-printingdiagnosticconsumer-handlediagnostic.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/01420-swift-printingdiagnosticconsumer-handlediagnostic.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/01420-swift-printingdiagnosticconsumer-handlediagnostic.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 struct X<d where h: T.Element == d e where g, k : U) -> V { typealias f = [c, B class A { init <T>(x: B(A, end: T>?) -> Int = e("a<T>],
29.25
87
0.65812
6f31101f39cb53b2e2267912d9f8befd667e97a5
8,278
kt
Kotlin
service/src/test/java/com/tink/service/insight/InsightActionConvertersTest.kt
tink-ab/tink-core-android
93705434ef983bec8193eae3e9dd28be3cd9a809
[ "MIT" ]
null
null
null
service/src/test/java/com/tink/service/insight/InsightActionConvertersTest.kt
tink-ab/tink-core-android
93705434ef983bec8193eae3e9dd28be3cd9a809
[ "MIT" ]
4
2022-01-19T11:03:51.000Z
2022-03-31T12:15:55.000Z
service/src/test/java/com/tink/service/insight/InsightActionConvertersTest.kt
tink-ab/tink-core-android
93705434ef983bec8193eae3e9dd28be3cd9a809
[ "MIT" ]
4
2020-03-20T08:59:18.000Z
2021-11-01T08:40:39.000Z
package com.tink.service.insight import com.tink.model.insights.InsightAction import com.tink.model.misc.Amount import com.tink.model.misc.ExactNumber import com.tink.rest.models.ActionableInsight import com.tink.rest.models.InsightActionData import com.tink.rest.tools.GeneratedCodeConverters import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test class InsightActionConvertersTest { private val viewTransactionsActionDataJson = "{\n" + "\"type\": \"VIEW_TRANSACTIONS_BY_CATEGORY\"," + " \"transactionIdsByCategory\": {\n" + " \"expenses:food.coffee\": {\n" + " \"transactionIds\": [\n" + " \"f5dd06dafc504c1fa152be62408bcdff\"\n" + " ]\n" + " },\n" + " \"expenses:food.groceries\": {\n" + " \"transactionIds\": [\n" + " \"0b18859117d645feaffbe5af5896e52a\",\n" + " \"7a3d7bc881b64994a80fb9c1cdd6ded3\",\n" + " \"c4d0f21822e84b7db54d54f7f33f0b47\"\n" + " ]\n" + " }\n" + " }\n" + " }" @Test fun `convert ViewTransactionsByCategoryData`() { val data = GeneratedCodeConverters.moshi .adapter(InsightActionData::class.java) .fromJson(viewTransactionsActionDataJson) as InsightActionData.ViewTransactionsByCategoryActionData val coffeeTransactions = data.transactionIdsByCategory .getValue("expenses:food.coffee") .transactionIds val groceryTransactions = data.transactionIdsByCategory .getValue("expenses:food.groceries") .transactionIds assertThat(coffeeTransactions).asList().contains("f5dd06dafc504c1fa152be62408bcdff") assertThat(groceryTransactions).asList() .contains("0b18859117d645feaffbe5af5896e52a").asList() .contains("7a3d7bc881b64994a80fb9c1cdd6ded3").asList() .contains("c4d0f21822e84b7db54d54f7f33f0b47") } private val acknowledgeActionData = "{\n \"type\": \"ACKNOWLEDGE\"\n}" @Test fun `convert Acknowledge`() { val data = GeneratedCodeConverters.moshi .adapter(InsightActionData::class.java) .fromJson(acknowledgeActionData) assertThat(data is InsightActionData.Acknowledge) } private val insightJson = "{\n" + " \"createdTime\": 1549976786000,\n" + " \"data\": {\n" + " \"type\": \"ACCOUNT_BALANCE_LOW\",\n" + " \"accountId\": \"c6f26025fbb949a08348e2f73f0ae12c\",\n" + " \"balance\": {\n" + " \"currencyCode\": \"EUR\",\n" + " \"amount\": 2.42\n" + " }\n" + " },\n" + " \"description\": \"The balance on your bank account x is low. \\nDo you want to transfer money to this account?\",\n" + " \"id\": \"e2b746ed27c542ce846a8d693474df21\",\n" + " \"insightActions\": [\n" + " {\n" + " \"data\": {\n" + " \"type\": \"CREATE_TRANSFER\",\n" + " \"sourceAccount\": \"iban://SE9832691627751644451227\",\n" + " \"destinationAccount\": \"iban://NL41INGB1822913977\",\n" + " \"amount\": {\n" + " \"currencyCode\": \"EUR\",\n" + " \"amount\": 30.00\n" + " },\n" + " \"sourceAccountNumber\": \"1234567890\",\n" + " \"destinationAccountNumber\": \"1234098765\"" + " },\n" + " \"label\": \"Make transfer\"\n" + " }\n" + " ],\n" + " \"title\": \"Your balance on bank account x is low\",\n" + " \"type\": \"ACCOUNT_BALANCE_LOW\",\n" + " \"userId\": \"d9f134ee2eb44846a4e02990ecc8d32e\"\n" + " }" @Test fun `convert basic insight`() { val insight = GeneratedCodeConverters.moshi .adapter(ActionableInsight::class.java) .fromJson(insightJson)!! .toCoreModel() val action = insight.actions.first() assertThat(action.actionType).isEqualTo(InsightAction.Type.CREATE_TRANSFER) val data = action.data as InsightAction.Data.CreateTransfer assertThat(data.amount).isEqualTo(Amount(ExactNumber(30.00), "EUR")) assertThat(data.sourceUri).isEqualTo("iban://SE9832691627751644451227") assertThat(data.destinationUri).isEqualTo("iban://NL41INGB1822913977") } private val viewBudgetActionDataJson = """ { "type": "VIEW_BUDGET", "budgetId": "cbbac116e43c4b21b7013091ec03d590", "budgetPeriodStartTime": 1567296000000 } """.trimIndent() @Test fun `convert ViewBudgetActionData`() { val data = GeneratedCodeConverters.moshi .adapter(InsightActionData::class.java) .fromJson(viewBudgetActionDataJson) as InsightActionData.ViewBudgetActionData val budgetId = data.budgetId val periodStartTime = data.budgetPeriodStartTime assertThat(budgetId).isEqualTo("cbbac116e43c4b21b7013091ec03d590") assertThat(periodStartTime).isEqualTo(1567296000000) } private val createBudgetActionDataJson = """ { "type": "CREATE_BUDGET", "budgetSuggestion": { "filter": { "categories": ["expenses:food.bars"], "accounts": ["d2b49640cbba4d8899a4886b6e8892f8"] }, "amount": { "currencyCode": "EUR", "amount": 300.0 }, "periodicityType": "BUDGET_PERIODICITY_TYPE_RECURRING", "recurringPeriodicityData": { "periodUnit": "MONTH" } } } """.trimIndent() @Test fun `convert CreateBudgetActionData`() { val data = GeneratedCodeConverters.moshi .adapter(InsightActionData::class.java) .fromJson(createBudgetActionDataJson) as InsightActionData.CreateBudgetActionData val suggestedAmount = data.budgetSuggestion.amount val suggestedFilter = data.budgetSuggestion.filter val periodicityType = data.budgetSuggestion.periodicityType val recurringPeriodicity = data.budgetSuggestion.recurringPeriodicityData val oneOffPeriodicity = data.budgetSuggestion.oneOffPeriodicityData assertThat(suggestedAmount!!.amount).isEqualTo(300.0) assertThat(suggestedAmount.currencyCode).isEqualTo("EUR") assertThat(suggestedFilter!!.categories).asList().contains("expenses:food.bars") assertThat(suggestedFilter.accounts).asList().contains("d2b49640cbba4d8899a4886b6e8892f8") assertThat(periodicityType!!.value).isEqualTo("BUDGET_PERIODICITY_TYPE_RECURRING") assertThat(oneOffPeriodicity).isNull() assertThat(recurringPeriodicity).isNotNull assertThat(recurringPeriodicity!!.periodUnit.value).isEqualTo("MONTH") } private val categorizeTransactionsActionDataJson = """ { "type": "CATEGORIZE_TRANSACTIONS", "transactionIds": [ "d2b49640cbba4d8899a4886b6e8892f8", "e8d668ddbe8d49ff81f40c8fb3b47c5d" ] } """.trimIndent() @Test fun `convert CategorizeTransactionsData`() { val data = GeneratedCodeConverters.moshi .adapter(InsightActionData::class.java) .fromJson(categorizeTransactionsActionDataJson) as InsightActionData.CategorizeTransactionsActionData val transactions = data.transactionIds assertThat(transactions).asList().contains("d2b49640cbba4d8899a4886b6e8892f8") assertThat(transactions).asList().contains("e8d668ddbe8d49ff81f40c8fb3b47c5d") } }
39.798077
136
0.571636
6fec54604380b2d8e3eda38d897bf23bfb74f647
981
sql
SQL
1GDAW/BBDD/SQL/Equipo base especialistas 1-12-17.sql
Barraguesh/2GDAW
64ce784973c747c9d7bd23d83206193ae1d98bbc
[ "MIT" ]
null
null
null
1GDAW/BBDD/SQL/Equipo base especialistas 1-12-17.sql
Barraguesh/2GDAW
64ce784973c747c9d7bd23d83206193ae1d98bbc
[ "MIT" ]
null
null
null
1GDAW/BBDD/SQL/Equipo base especialistas 1-12-17.sql
Barraguesh/2GDAW
64ce784973c747c9d7bd23d83206193ae1d98bbc
[ "MIT" ]
2
2020-09-18T17:13:35.000Z
2021-04-22T20:12:01.000Z
/*Especialista A: Dani*/ --1-- SELECT APELLIDO,SALARIO,DEPT_NO FROM EMPLE WHERE SALARIO > 200000 AND DEPT_NO IN (10,20); --2-- SELECT APELLIDO,SALARIO FROM EMPLE WHERE SALARIO BETWEEN 150000 AND 200000; --3-- SELECT APELLIDO FROM EMPLE WHERE DEPT_NO IN (10, 30); --4-- SELECT APELLIDO,OFICIO FROM EMPLE WHERE ID_JEFE IS null; /*Especialista B: Aitor*/ --1-- SELECT APELLIDO FROM EMPLE WHERE APELLIDO LIKE 'J%'; --2-- SELECT APELLIDO,SALARIO FROM EMPLE WHERE SALARIO NOT BETWEEN 150000 AND 200000; --3-- SELECT APELLIDO FROM EMPLE WHERE DEPT_NO NOT IN (10,30); --4-- SELECT DISTINCT OFICIO FROM EMPLE; /*Especialista C: Alejandro*/ /*Especialista D: Andrea*/ --1-- SELECT APELLIDO FROM EMPLE WHERE APELLIDO LIKE 'A%O%'; --2-- SELECT APELLIDO FROM EMPLE WHERE UPPER (OFICIO) NOT IN ('VENDEDOR', 'ANALISTA', 'EMPLEADO'); --3-- SELECT APELLIDO FROM EMPLE WHERE (COMISION_PCT IS NOT NULL); --4-- SELECT * FROM EMPLE WHERE UPPER (OFICIO) = 'ANALISTA' ORDER BY EMP_NO;
16.35
65
0.716616
510475c2f797297891a900dc460529caef3dd2f6
3,724
c
C
src/flags.c
nudon/fancierGameEngine
bdba885e6bdbb51826eadc0d348c96bb6c5361b0
[ "MIT" ]
null
null
null
src/flags.c
nudon/fancierGameEngine
bdba885e6bdbb51826eadc0d348c96bb6c5361b0
[ "MIT" ]
null
null
null
src/flags.c
nudon/fancierGameEngine
bdba885e6bdbb51826eadc0d348c96bb6c5361b0
[ "MIT" ]
null
null
null
#include <stdlib.h> #include <stdint.h> #include <stdio.h> #include <math.h> #include "flags.h" #define COMP_PREY 0 #define COMP_HUNTER 1 #define COMP_USER 2 #define COMP_TRAVEL 3 #define COMP_HOLDABLE 4 #define BODY_INVULN 0 #define BODY_DAMAGER 1 #define DRAW_OUTLINE 0 #define DRAW_PICTURE 1 #define DRAW_EVENTS 2 #define DRAW_BBOX 3 #define NUM_BITS 8 typedef uint8_t flag_bits; int test_bit(flag_bits a, int bit_place); void set_bit(flag_bits *a, int bit_place, int val); enum flag_type {compound_flags, body_flags, draw_flags, not_set}; struct flags_struct { enum flag_type mode; flag_bits flag_bits; }; flags* make_flags() { flags* new = calloc(1,sizeof(flags)); new->mode = not_set; return new; } void flags_set_type_body(flags* a) { a->mode = body_flags; } void flags_set_type_comp(flags* a) { a->mode = compound_flags; } void flags_set_type_draw(flags* a) { a->mode = draw_flags; } void free_flags(flags* rm) { free(rm); } int test_bit(flag_bits a, int bit_place) { return (a >> bit_place) % 2; } //have to set bit_place in a to zero first to be able to use | to set it void set_bit(flag_bits *a, int bit_place, int val) { val = val % 2; int bf = ~(1 << bit_place); int bit = val << bit_place; int temp = *a & bf; *a = temp | bit; } int is_invuln(flags* a) { return test_bit(a->flag_bits, BODY_INVULN); } void set_invuln(flags *a, int val) { set_bit(&(a->flag_bits), BODY_INVULN, val); } int is_damager(flags* a) { return test_bit(a->flag_bits, BODY_DAMAGER); } void set_damager(flags *a, int val) { set_bit(&(a->flag_bits), BODY_DAMAGER, val); } int is_prey(flags *a) { return test_bit(a->flag_bits, COMP_PREY); } void set_prey(flags *a, int val) { set_bit(&(a->flag_bits), COMP_PREY, val); } int is_hunter(flags *a) { return test_bit(a->flag_bits, COMP_HUNTER); } void set_hunter(flags *a, int val) { set_bit(&(a->flag_bits), COMP_HUNTER, val); } int is_user(flags *a) { return test_bit(a->flag_bits, COMP_USER); } void set_user(flags *a, int val) { set_bit(&(a->flag_bits), COMP_USER, val); } int is_travel(flags *a) { return test_bit(a->flag_bits, COMP_TRAVEL); } void set_travel(flags *a, int val) { set_bit(&(a->flag_bits), COMP_TRAVEL, val); } int is_holdable(flags *a) { return test_bit(a->flag_bits, COMP_HOLDABLE); } void set_holdable(flags *a, int val) { set_bit(&(a->flag_bits), COMP_HOLDABLE, val); } int is_draw_outline(flags* a) { return test_bit(a->flag_bits, DRAW_OUTLINE); } void set_draw_outline(flags* a, int val) { set_bit(&(a->flag_bits), DRAW_OUTLINE, val); } int is_draw_picture(flags* a) { return test_bit(a->flag_bits, DRAW_PICTURE); } void set_draw_picture(flags* a, int val) { set_bit(&(a->flag_bits), DRAW_PICTURE, val); } int is_draw_events(flags* a) { return test_bit(a->flag_bits, DRAW_EVENTS); } void set_draw_events(flags* a, int val) { set_bit(&(a->flag_bits), DRAW_EVENTS, val); } int is_draw_bbox(flags* a) { return test_bit(a->flag_bits, DRAW_BBOX); } void set_draw_bbox(flags* a, int val) { set_bit(&(a->flag_bits), DRAW_BBOX, val); } void copy_flags(flags* src, flags* dst) { if (src->mode != dst->mode) { fprintf(stderr, "warning, flag types not equal\n"); } dst->flag_bits = dst->flag_bits; } char* flags_to_text(flags* flags) { char* text = malloc(sizeof(char*) * (NUM_BITS + 1)) ; snprintf(text, NUM_BITS, "%d", flags->flag_bits); return text; } flags* text_to_flags(char* text) { long val = atoi(text); if (val > pow(2, NUM_BITS) - 1) { fprintf(stderr, "Warning, bit val is larger than flags data type can hold\n"); } flag_bits temp = (flag_bits)val; flags* flags = make_flags(); flags->flag_bits = temp; return flags; }
20.921348
82
0.686627
2104dcb874eed8ac37b05ab6baa6d3b29ec3fd0d
45
kt
Kotlin
libraries/tools/kotlin-gradle-plugin-integration-tests/src/test/resources/testProject/js-composite-build/src/main/kotlin/Main.kt
Mu-L/kotlin
5c3ce66e9979d2b3592d06961e181fa27fa88431
[ "ECL-2.0", "Apache-2.0" ]
45,293
2015-01-01T06:23:46.000Z
2022-03-31T21:55:51.000Z
libraries/tools/kotlin-gradle-plugin-integration-tests/src/test/resources/testProject/js-composite-build/app/src/main/kotlin/Main.kt
Seantheprogrammer93/kotlin
f7aabf03f89bdd39d9847572cf9e0051ea42c247
[ "ECL-2.0", "Apache-2.0" ]
3,386
2015-01-12T13:28:50.000Z
2022-03-31T17:48:15.000Z
libraries/tools/kotlin-gradle-plugin-integration-tests/src/test/resources/testProject/js-composite-build/app/src/main/kotlin/Main.kt
Seantheprogrammer93/kotlin
f7aabf03f89bdd39d9847572cf9e0051ea42c247
[ "ECL-2.0", "Apache-2.0" ]
6,351
2015-01-03T12:30:09.000Z
2022-03-31T20:46:54.000Z
fun main() { println(Singleton.test()) }
11.25
29
0.6
f60f6f78a03f4ab3e69aaf02e249b7cabb3d1321
2,117
swift
Swift
Sources/GraphKit/Components/LineGraph.swift
RMcBrideTaylor/GraphKit
e58b0e1bc2e01529ab00ede32511e39a9f065ea6
[ "MIT" ]
17
2020-02-29T14:00:45.000Z
2021-12-03T05:05:47.000Z
Sources/GraphKit/Components/LineGraph.swift
RMcBrideTaylor/GraphKit
e58b0e1bc2e01529ab00ede32511e39a9f065ea6
[ "MIT" ]
2
2020-03-20T16:09:30.000Z
2022-02-03T17:21:44.000Z
Sources/GraphKit/Components/LineGraph.swift
RMcBrideTaylor/GraphKit
e58b0e1bc2e01529ab00ede32511e39a9f065ea6
[ "MIT" ]
3
2020-02-25T00:38:11.000Z
2022-03-24T17:55:09.000Z
// // LineGraph.swift // GraphKit // // Created by Reginald McBride-Taylor on 1/25/20. // Copyright © 2020 Reginald McBride-Taylor. All rights reserved. // import SwiftUI public struct LineGraph<T : ShapeStyle, U: ShapeStyle>: View, Graph { @State public var data : [Double] @State public var style : LineGraphStyle<T, U> = LineGraphStyle() public var body: some View { ZStack{ Grid(count: 10) .appearance(style.appearance) .gridType(style.grid) VStack { HStack { if self.style.labels.lowerY != "" || self.style.labels.upperY != "" { VStack{ Text(self.style.labels.upperY) Spacer() Text(self.style.labels.lowerY) } } VStack{ GeometryReader { geometry in Line(points: self.data, geometry: geometry, style: self.style) } } } if self.style.labels.lowerX != "" || self.style.labels.upperX != "" { HStack { Text(self.style.labels.lowerX) Spacer() Text(self.style.labels.upperX) } .padding(.leading, 15) } } } } } struct LineGraph_Previews: PreviewProvider { @State static var points = [10.0, 1.0, 6.0, 9.5, 5.0, 10.0] @State static var s = LineGraphStyle<Color, LinearGradient>( strokeWidth: 1, curve: .continuous, appearance: .auto, grid: .horizontal ) static var previews: some View { LineGraph(data: points, style: s) .padding(10) .background(Color.black) .frame(height: 250) } }
28.608108
90
0.432215
6fd4bd1ae16e23f3dc77183e8f88bb1ce194a5d2
1,626
kt
Kotlin
app/src/main/java/com/example/testbank/repository/local/model/more/BaseMoreModel.kt
aucd29/testbank
7b82096b854f200928a2c1c528f287c80f1a963f
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/example/testbank/repository/local/model/more/BaseMoreModel.kt
aucd29/testbank
7b82096b854f200928a2c1c528f287c80f1a963f
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/example/testbank/repository/local/model/more/BaseMoreModel.kt
aucd29/testbank
7b82096b854f200928a2c1c528f287c80f1a963f
[ "Apache-2.0" ]
null
null
null
package com.example.testbank.repository.local.model.more import com.example.testbank.base.adapter.ListAdapterViewType open class BaseMoreModel( var id: Int, override val viewType: Int ) : ListAdapterViewType<Int> { override fun diff(): Int = id companion object { const val TYPE_HEADER = 0 const val TYPE_SUBJECT = 1 const val TYPE_MENU = 2 const val TYPE_BANNER = 3 const val TYPE_BAR = 4 } } class MoreHeaderModel( id: Int, val userName: String, val banner: MoreHeaderEventBanner? = null, ) : BaseMoreModel(id, TYPE_HEADER) data class MoreHeaderEventBanner( val title: String, val link: String = "", val backgroundColor: String?, val textColor: String?, val startIcon: String?, ) class MoreSubjectModel( id: Int, val title: String, val backgroundColor: String = "#ffffff", ) : BaseMoreModel(id, TYPE_SUBJECT) class MoreMenuModel( id: Int, val title: String, val isBadge: Boolean = false, val badgeBackground: String? = null, val badgeText: String? = null, val badgeTextColor: String? = null, val backgroundColor: String = "#ffffff", ) : BaseMoreModel(id, TYPE_MENU) class MoreBannerModel( id: Int, val title: String, val description: String, val textColor: String, var cardBackgroundColor: String, val icon: String, val backgroundColor: String = "#ffffff", ) : BaseMoreModel(id, TYPE_BANNER) class MoreBarModel( id: Int, val topBackgroundColor: String? = null, val bottomBackgroundColor: String? = null ) : BaseMoreModel(id, TYPE_BAR)
24.636364
60
0.675277
0db3a3762199b44f2846193a3a3c1bc18f7fe87d
3,513
swift
Swift
Extension/ViewController.swift
CepheusSun/TodayExtension
df177c3e67a24ae3ed42e50645821725049da349
[ "MIT" ]
2
2018-02-08T15:23:09.000Z
2020-08-05T02:36:48.000Z
Extension/ViewController.swift
CepheusSun/TodayExtension
df177c3e67a24ae3ed42e50645821725049da349
[ "MIT" ]
null
null
null
Extension/ViewController.swift
CepheusSun/TodayExtension
df177c3e67a24ae3ed42e50645821725049da349
[ "MIT" ]
null
null
null
// // ViewController.swift // Extension // // Created by sunny on 2017/6/30. // Copyright © 2017年 CepheusSun. All rights reserved. // import UIKit import RxSwift import RxCocoa class ViewController: UIViewController { @IBOutlet weak var tableView: UITableView! let userdefaultKey = "com.sunny.todolist" static let userdefault = UserDefaults(suiteName: "group.com.sunny.group") let disposeBag = DisposeBag() fileprivate lazy var dataSource: [String] = { guard let arr = ViewController.userdefault?.array(forKey: self.userdefaultKey) else { return [] } return arr as! [String] }() override func viewDidLoad() { super.viewDidLoad() tableView.tableFooterView = UIView() } @IBAction func addItem(_ sender: Any) { let alert = UIAlertController(title: "添加任务", message: "请输入你要添加的任务", preferredStyle: .alert) let todo = Variable<String?>("") alert.addTextField { [unowned self, todo] (textField) in textField.rx.text.bind(to: todo).disposed(by: self.disposeBag) } alert.addAction(UIAlertAction(title: "取消", style: .cancel, handler: nil)) alert.addAction(UIAlertAction(title: "确定", style: .default, handler: { [unowned self, todo] (action) in self.dataSource.append(todo.value!) self.tableView.reloadData() ViewController.userdefault?.set(self.dataSource, forKey: self.userdefaultKey) print(self.dataSource) })) present(alert, animated: true, completion: nil) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } } extension ViewController: UITableViewDelegate, UITableViewDataSource { func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return dataSource.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = TodoCell.cell(with: tableView) cell.headerImageView.image = #imageLiteral(resourceName: "icon_small.png") cell.titleLabel.text = dataSource[indexPath.row] return cell } func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath) -> UITableViewCellEditingStyle { return .delete } func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { return true } func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) { if editingStyle == .delete { dataSource.remove(at: indexPath.row) tableView.deleteRows(at: [indexPath], with: .fade) ViewController.userdefault?.set(self.dataSource, forKey: self.userdefaultKey) } } func tableView(_ tableView: UITableView, titleForDeleteConfirmationButtonForRowAt indexPath: IndexPath) -> String? { return "删除" } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let detailViewController = UIViewController() detailViewController.view.backgroundColor = UIColor.white detailViewController.title = dataSource[indexPath.row] navigationController?.pushViewController(detailViewController, animated: true) } }
34.441176
127
0.666667
b5078fcfea098ac04ddf31fe587d2de467490ad6
20,975
rs
Rust
dolby_vision/src/xml/parser.rs
nekno/dovi_tool
6673e09e66d46a9e99a5e0bf425d35a4f66515da
[ "MIT" ]
null
null
null
dolby_vision/src/xml/parser.rs
nekno/dovi_tool
6673e09e66d46a9e99a5e0bf425d35a4f66515da
[ "MIT" ]
null
null
null
dolby_vision/src/xml/parser.rs
nekno/dovi_tool
6673e09e66d46a9e99a5e0bf425d35a4f66515da
[ "MIT" ]
null
null
null
use anyhow::{bail, ensure, Result}; use roxmltree::{Document, Node}; use std::cmp::min; use std::collections::HashMap; use std::fs::File; use std::io::Read; use std::path::Path; use crate::rpu::extension_metadata::blocks::*; use crate::rpu::generate::{GenerateConfig, ShotFrameEdit, VideoShot}; use crate::rpu::vdr_dm_data::CmVersion; #[derive(Default, Debug)] pub struct CmXmlParser { opts: XmlParserOpts, cm_version: String, separator: char, target_displays: HashMap<String, TargetDisplay>, pub config: GenerateConfig, } #[derive(Default, Debug)] pub struct XmlParserOpts { pub canvas_width: Option<u16>, pub canvas_height: Option<u16>, } #[derive(Default, Debug)] pub struct TargetDisplay { id: String, peak_nits: u16, } impl CmXmlParser { pub fn parse_file(file_path: &Path, opts: XmlParserOpts) -> Result<CmXmlParser> { let mut s = String::new(); File::open(file_path)?.read_to_string(&mut s)?; Self::new(s, opts) } pub fn new(s: String, opts: XmlParserOpts) -> Result<CmXmlParser> { let mut parser = CmXmlParser { opts, ..Default::default() }; let doc = roxmltree::Document::parse(&s).unwrap(); parser.cm_version = parser.parse_cm_version(&doc)?; parser.separator = if parser.is_cmv4() { ' ' } else { ',' }; // Override version if !parser.is_cmv4() { parser.config.cm_version = CmVersion::V29; } if let Some(output) = doc.descendants().find(|e| e.has_tag_name("Output")) { parser.parse_global_level5(&output)?; if let Some(video) = output.descendants().find(|e| e.has_tag_name("Video")) { let (max_frame_average_light_level, max_content_light_level) = parser.parse_level6(&video); let (min_display_mastering_luminance, max_display_mastering_luminance) = parser.parse_mastering_display_metadata(&video); parser.config.level6 = ExtMetadataBlockLevel6 { max_display_mastering_luminance, min_display_mastering_luminance, max_content_light_level, max_frame_average_light_level, }; parser.target_displays = parser.parse_target_displays(&video); parser.config.shots = parser.parse_shots(&video)?; parser.config.shots.sort_by_key(|s| s.start); let first_shot = parser.config.shots.first().unwrap(); let last_shot = parser.config.shots.last().unwrap(); parser.config.length = (last_shot.start + last_shot.duration) - first_shot.start; } else { bail!("Could not find Video node"); } } else { bail!("Could not find Output node"); } Ok(parser) } fn parse_cm_version(&self, doc: &Document) -> Result<String> { if let Some(node) = doc.descendants().find(|e| e.has_tag_name("DolbyLabsMDF")) { let version_attr = node.attribute("version"); let version_node = if let Some(version_node) = node.children().find(|e| e.has_tag_name("Version")) { version_node.text() } else { None }; let version_level254 = if let Some(level254_node) = node.descendants().find(|e| e.has_tag_name("Level254")) { let cm_version_node = level254_node .children() .find(|e| e.has_tag_name("CMVersion")) .unwrap(); let cm_version = cm_version_node.text().unwrap(); if cm_version.contains('4') { Some("4.0.2") } else { None } } else { None }; if version_node.is_some() || version_level254.is_some() { if let Some(v) = version_node { Ok(v.to_string()) } else if let Some(v) = version_level254 { Ok(v.to_string()) } else if let Some(v) = version_attr { Ok(v.to_string()) } else { bail!("No CM version found!"); } } else if let Some(v) = version_attr { Ok(v.to_string()) } else { bail!("No CM version found!"); } } else { bail!("Could not find DolbyLabsMDF root node."); } } fn parse_level6(&self, video: &Node) -> (u16, u16) { if let Some(node) = video.descendants().find(|e| e.has_tag_name("Level6")) { let maxfall = if let Some(fall) = node.children().find(|e| e.has_tag_name("MaxFALL")) { fall.text().map_or(0, |e| e.parse::<u16>().unwrap()) } else { 0 }; let maxcll = if let Some(cll) = node.children().find(|e| e.has_tag_name("MaxCLL")) { cll.text().map_or(0, |e| e.parse::<u16>().unwrap()) } else { 0 }; (maxfall, maxcll) } else { (0, 0) } } fn parse_mastering_display_metadata(&self, video: &Node) -> (u16, u16) { if let Some(node) = video .descendants() .find(|e| e.has_tag_name("MasteringDisplay")) { let min = if let Some(min_brightness) = node .children() .find(|e| e.has_tag_name("MinimumBrightness")) { min_brightness.text().map_or(0, |e| { let v = e.parse::<f32>().unwrap(); (v * 10000.0) as u16 }) } else { 0 }; let max = if let Some(max_brightness) = node.children().find(|e| e.has_tag_name("PeakBrightness")) { max_brightness .text() .map_or(0, |e| e.parse::<u16>().unwrap()) } else { 0 }; (min, max) } else { (0, 0) } } fn parse_target_displays(&self, video: &Node) -> HashMap<String, TargetDisplay> { let mut targets = HashMap::new(); video .descendants() .filter(|e| e.has_tag_name("TargetDisplay")) .for_each(|e| { let id = e .children() .find(|e| e.has_tag_name("ID")) .unwrap() .text() .unwrap() .to_string(); let peak_nits = e .children() .find(|e| e.has_tag_name("PeakBrightness")) .unwrap() .text() .unwrap() .parse::<u16>() .unwrap(); targets.insert(id.clone(), TargetDisplay { id, peak_nits }); }); targets } fn parse_shots(&self, video: &Node) -> Result<Vec<VideoShot>> { let shots = video .descendants() .filter(|e| e.has_tag_name("Shot")) .map(|n| { let mut shot = VideoShot { id: n .children() .find(|e| e.has_tag_name("UniqueID")) .unwrap() .text() .unwrap() .to_string(), ..Default::default() }; if let Some(record) = n.children().find(|e| e.has_tag_name("Record")) { shot.start = record .children() .find(|e| e.has_tag_name("In")) .unwrap() .text() .unwrap() .parse::<usize>() .unwrap(); shot.duration = record .children() .find(|e| e.has_tag_name("Duration")) .unwrap() .text() .unwrap() .parse::<usize>() .unwrap(); } shot.metadata_blocks = self.parse_shot_trims(&n)?; let frames = n.children().filter(|e| e.has_tag_name("Frame")); for frame in frames { let edit_offset = frame .children() .find(|e| e.has_tag_name("EditOffset")) .unwrap() .text() .unwrap() .parse::<usize>() .unwrap(); shot.frame_edits.push(ShotFrameEdit { edit_offset, metadata_blocks: self.parse_shot_trims(&frame)?, }); } Ok(shot) }) .collect(); shots } fn parse_shot_trims(&self, node: &Node) -> Result<Vec<ExtMetadataBlock>> { let mut metadata_blocks = Vec::new(); let dynamic_meta_tag = if self.is_cmv4() { "DVDynamicData" } else { "PluginNode" }; if let Some(defaults_node) = node .descendants() .find(|e| e.has_tag_name(dynamic_meta_tag)) { if self.is_cmv4() { let level_nodes = defaults_node .children() .filter(|e| e.has_attribute("level")); for level_node in level_nodes { let level = level_node.attribute("level").unwrap(); self.parse_trim_levels(&level_node, level, &mut metadata_blocks)?; } } else { let edr_nodes = defaults_node .children() .filter(|e| e.has_tag_name("DolbyEDR") && e.has_attribute("level")); for edr in edr_nodes { let level = edr.attribute("level").unwrap(); self.parse_trim_levels(&edr, level, &mut metadata_blocks)?; } }; } Ok(metadata_blocks) } fn parse_trim_levels( &self, node: &Node, level: &str, metadata_blocks: &mut Vec<ExtMetadataBlock>, ) -> Result<()> { if level == "1" { metadata_blocks.push(ExtMetadataBlock::Level1(self.parse_level1_trim(node)?)); } else if level == "2" { metadata_blocks.push(ExtMetadataBlock::Level2(self.parse_level2_trim(node)?)); } else if level == "3" { metadata_blocks.push(ExtMetadataBlock::Level3(self.parse_level3_trim(node)?)); } else if level == "5" { metadata_blocks.push(ExtMetadataBlock::Level5(self.parse_level5_trim(node)?)); } else if level == "8" { metadata_blocks.push(ExtMetadataBlock::Level8(self.parse_level8_trim(node)?)); } else if level == "9" { metadata_blocks.push(ExtMetadataBlock::Level9(self.parse_level9_trim(node)?)); } Ok(()) } pub fn parse_global_level5(&mut self, output: &Node) -> Result<()> { let canvas_ar = if let Some(canvas_ar) = output .children() .find(|e| e.has_tag_name("CanvasAspectRatio")) { canvas_ar.text().and_then(|v| v.parse::<f32>().ok()) } else { None }; let image_ar = if let Some(image_ar) = output .children() .find(|e| e.has_tag_name("ImageAspectRatio")) { image_ar.text().and_then(|v| v.parse::<f32>().ok()) } else { None }; if let (Some(c_ar), Some(i_ar)) = (canvas_ar, image_ar) { self.config.level5 = self .calculate_level5_metadata(c_ar, i_ar) .ok() .unwrap_or_default(); } Ok(()) } pub fn parse_level1_trim(&self, node: &Node) -> Result<ExtMetadataBlockLevel1> { let measurements = node .children() .find(|e| e.has_tag_name("ImageCharacter")) .unwrap() .text() .unwrap(); let measurements: Vec<&str> = measurements.split(self.separator).collect(); ensure!( measurements.len() == 3, "invalid L1 trim: should be 3 values" ); let min_pq = (measurements[0].parse::<f32>().unwrap() * 4095.0).round() as u16; let avg_pq = (measurements[1].parse::<f32>().unwrap() * 4095.0).round() as u16; let max_pq = (measurements[2].parse::<f32>().unwrap() * 4095.0).round() as u16; Ok(ExtMetadataBlockLevel1::from_stats(min_pq, max_pq, avg_pq)) } pub fn parse_level2_trim(&self, node: &Node) -> Result<ExtMetadataBlockLevel2> { let target_id = node .children() .find(|e| e.has_tag_name("TID")) .unwrap() .text() .unwrap() .to_string(); let trim = node .children() .find(|e| e.has_tag_name("Trim")) .unwrap() .text() .unwrap(); let trim: Vec<&str> = trim.split(self.separator).collect(); let target_display = self .target_displays .get(&target_id) .expect("No target display found for L2 trim"); ensure!(trim.len() == 9, "invalid L2 trim: should be 9 values"); let trim_lift = trim[3].parse::<f32>().unwrap(); let trim_gain = trim[4].parse::<f32>().unwrap(); let trim_gamma = trim[5].parse::<f32>().unwrap().clamp(-1.0, 1.0); let trim_slope = min( 4095, ((((trim_gain + 2.0) * (1.0 - trim_lift / 2.0) - 2.0) * 2048.0) + 2048.0).round() as u16, ); let trim_offset = min( 4095, ((((trim_gain + 2.0) * (trim_lift / 2.0)) * 2048.0) + 2048.0).round() as u16, ); let trim_power = min( 4095, (((2.0 / (1.0 + trim_gamma / 2.0) - 2.0) * 2048.0) + 2048.0).round() as u16, ); let trim_chroma_weight = min( 4095, ((trim[6].parse::<f32>().unwrap() * 2048.0) + 2048.0).round() as u16, ); let trim_saturation_gain = min( 4095, ((trim[7].parse::<f32>().unwrap() * 2048.0) + 2048.0).round() as u16, ); let ms_weight = min( 4095, ((trim[8].parse::<f32>().unwrap() * 2048.0) + 2048.0).round() as i16, ); Ok(ExtMetadataBlockLevel2 { trim_slope, trim_offset, trim_power, trim_chroma_weight, trim_saturation_gain, ms_weight, ..ExtMetadataBlockLevel2::from_nits(target_display.peak_nits) }) } pub fn parse_level3_trim(&self, node: &Node) -> Result<ExtMetadataBlockLevel3> { let measurements = node .children() .find(|e| e.has_tag_name("L1Offset")) .unwrap() .text() .unwrap(); let measurements: Vec<&str> = measurements.split(self.separator).collect(); ensure!( measurements.len() == 3, "invalid L3 trim: should be 3 values" ); Ok(ExtMetadataBlockLevel3 { min_pq_offset: ((measurements[0].parse::<f32>().unwrap() * 2048.0) + 2048.0).round() as u16, max_pq_offset: ((measurements[1].parse::<f32>().unwrap() * 2048.0) + 2048.0).round() as u16, avg_pq_offset: ((measurements[2].parse::<f32>().unwrap() * 2048.0) + 2048.0).round() as u16, }) } pub fn parse_level5_trim(&self, node: &Node) -> Result<ExtMetadataBlockLevel5> { let ratios = node .children() .find(|e| e.has_tag_name("AspectRatios")) .unwrap() .text() .unwrap(); let ratios: Vec<&str> = ratios.split(self.separator).collect(); ensure!(ratios.len() == 2, "invalid L5 trim: should be 2 values"); let canvas_ar = ratios[0].parse::<f32>().unwrap(); let image_ar = ratios[1].parse::<f32>().unwrap(); Ok(self .calculate_level5_metadata(canvas_ar, image_ar) .ok() .unwrap_or_default()) } // FIXME: No reference to compare impl pub fn parse_level8_trim(&self, node: &Node) -> Result<ExtMetadataBlockLevel8> { let target_id = node .children() .find(|e| e.has_tag_name("TID")) .unwrap() .text() .unwrap() .to_string(); let trim = node .children() .find(|e| e.has_tag_name("L8Trim")) .unwrap() .text() .unwrap(); let trim: Vec<&str> = trim.split(self.separator).collect(); let target_display = self .target_displays .get(&target_id) .expect("No target display found for L8 trim"); ensure!(trim.len() == 6, "invalid L8 trim: should be 6 values"); let trim_lift = trim[0].parse::<f32>().unwrap(); let trim_gain = trim[1].parse::<f32>().unwrap(); let trim_gamma = trim[2].parse::<f32>().unwrap().clamp(-1.0, 1.0); let trim_slope = min( 4095, ((((trim_gain + 2.0) * (1.0 - trim_lift / 2.0) - 2.0) * 2048.0) + 2048.0).round() as u16, ); let trim_offset = min( 4095, ((((trim_gain + 2.0) * (trim_lift / 2.0)) * 2048.0) + 2048.0).round() as u16, ); let trim_power = min( 4095, (((2.0 / (1.0 + trim_gamma / 2.0) - 2.0) * 2048.0) + 2048.0).round() as u16, ); let trim_chroma_weight = min( 4095, ((trim[3].parse::<f32>().unwrap() * 2048.0) + 2048.0).round() as u16, ); let trim_saturation_gain = min( 4095, ((trim[4].parse::<f32>().unwrap() * 2048.0) + 2048.0).round() as u16, ); let ms_weight = min( 4095, ((trim[5].parse::<f32>().unwrap() * 2048.0) + 2048.0).round() as u16, ); Ok(ExtMetadataBlockLevel8 { target_display_index: target_display.id.parse::<u8>()?, trim_slope, trim_offset, trim_power, trim_chroma_weight, trim_saturation_gain, ms_weight, }) } pub fn parse_level9_trim(&self, node: &Node) -> Result<ExtMetadataBlockLevel9> { let source_color_model = node .children() .find(|e| e.has_tag_name("SourceColorModel")) .unwrap() .text() .unwrap(); let source_primary_index = source_color_model.parse::<u8>()?; Ok(ExtMetadataBlockLevel9 { source_primary_index, }) } fn calculate_level5_metadata( &self, canvas_ar: f32, image_ar: f32, ) -> Result<ExtMetadataBlockLevel5> { ensure!( self.opts.canvas_width.is_some(), "Missing canvas width to calculate L5" ); ensure!( self.opts.canvas_height.is_some(), "Missing canvas height to calculate L5" ); let cw = self.opts.canvas_width.unwrap() as f32; let ch = self.opts.canvas_height.unwrap() as f32; let mut calculated_level5 = ExtMetadataBlockLevel5::default(); if (canvas_ar - image_ar).abs() < f32::EPSILON { // No AR difference, zero offsets } else if image_ar > canvas_ar { let image_h = (ch * (canvas_ar / image_ar)).round(); let diff = ch - image_h; let offset_top = (diff / 2.0).trunc(); let offset_bottom = diff - offset_top; calculated_level5.active_area_top_offset = offset_top as u16; calculated_level5.active_area_bottom_offset = offset_bottom as u16; } else { let image_w = (cw * (image_ar / canvas_ar)).round(); let diff = cw - image_w; let offset_left = (diff / 2.0).trunc(); let offset_right = diff - offset_left; calculated_level5.active_area_left_offset = offset_left as u16; calculated_level5.active_area_right_offset = offset_right as u16; } Ok(calculated_level5) } pub fn is_cmv4(&self) -> bool { self.cm_version == "4.0.2" } }
32.97956
99
0.484577
b3269965f91d1533715f992a8b342ab01ad114eb
4,470
asm
Assembly
TurtleTools/Examples/echo.asm
foxostro/TurtleTTL
7d2163b11b91ae04ad69d38c0354194b9c306ed0
[ "MIT" ]
1
2021-08-18T22:30:11.000Z
2021-08-18T22:30:11.000Z
TurtleTools/Examples/old/echo.asm
foxostro/Turtle16
67e6d2afa02f2bc07711f8e8d756e5b891ea8df5
[ "MIT" ]
null
null
null
TurtleTools/Examples/old/echo.asm
foxostro/Turtle16
67e6d2afa02f2bc07711f8e8d756e5b891ea8df5
[ "MIT" ]
null
null
null
let kSerialInterface = 7 let kDataPort = 1 let kControlPort = 0 let kResetCommand = 0 let kPutCommand = 1 let kGetCommand = 2 let kGetNumberOfBytesCommand = 3 LI A, 0 LI B, 0 LI D, kSerialInterface LI X, 0 LI Y, 0 LI U, 0 LI V, 0 LXY serial_init JALR NOP NOP LI A, 'r' LXY serial_put JALR NOP NOP LI A, 'e' LXY serial_put JALR NOP NOP LI A, 'a' LXY serial_put JALR NOP NOP LI A, 'd' LXY serial_put JALR NOP NOP LI A, 'y' LXY serial_put JALR NOP NOP LI A, '.' LXY serial_put JALR NOP NOP LI A, 10 LXY serial_put JALR NOP NOP # Now, we enter a loop where we wait for serial input and then echo it to # serial output. beginningOfInputLoop: waitForInput: LXY serial_get_number_available_bytes JALR NOP NOP LI B, 0 CMP CMP LXY waitForInput JE NOP NOP # Read a byte and echo it back. LXY serial_get JALR # The return value is in "A". NOP NOP LXY serial_put # The parameter is in "A". JALR NOP NOP LXY beginningOfInputLoop JMP NOP NOP HLT # unreachable serial_init: # Preserve the value of the link register by # storing return address at address 10 and 11. LI U, 0 LI V, 10 MOV M, G LI V, 11 MOV M, H LI D, kSerialInterface LI Y, kDataPort LI P, kResetCommand LI Y, kControlPort LI P, 0 # Lower SCK LI P, 1 # Raise SCK LXY delay JALR NOP NOP LI Y, kDataPort MOV A, P # Store the status in A LI Y, kControlPort LI P, 0 # Lower SCK LXY delay JALR NOP NOP # Retrieve the return address from memory at address 10 and 11, # and then return from the call. LI U, 0 LI V, 10 MOV X, M LI V, 11 MOV Y, M JMP NOP NOP serial_put: # Preserve the value of the link register by # storing return address at address 10 and 11. LI U, 0 LI V, 10 MOV M, G LI V, 11 MOV M, H # The A register contains the character to output. # Copy it into memory at address 5. LI U, 0 LI V, 5 MOV M, A LI D, 7 # The Serial Interface device LI Y, kDataPort LI P, kPutCommand LI Y, kControlPort LI P, 1 # Raise SCK LXY delay JALR NOP NOP LI Y, kControlPort LI P, 0 # Lower SCK LXY delay JALR NOP NOP LI Y, kDataPort LI U, 0 LI V, 5 MOV P, M # Retrieve the byte from address 5 and pass it to the serial device. LI Y, kControlPort LI P, 1 # Raise SCK LXY delay JALR NOP NOP LI Y, kControlPort LI P, 0 # Lower SCK LXY delay JALR NOP NOP # Retrieve the return address from memory at address 10 and 11, # and then return from the call. LI U, 0 LI V, 10 MOV X, M LI V, 11 MOV Y, M JMP NOP NOP serial_get: # Preserve the value of the link register by # storing return address at address 10 and 11. LI U, 0 LI V, 10 MOV M, G LI V, 11 MOV M, H LI Y, kDataPort LI P, kGetCommand LI Y, kControlPort LI P, 1 # Raise SCK LXY delay JALR NOP NOP LI U, 0 LI V, 5 MOV M, P # Store the input byte in memory at address 5. LI Y, kControlPort LI P, 0 # Lower SCK LXY delay JALR NOP NOP # Set the return value in "A". LI U, 0 LI V, 5 MOV A, M # Retrieve the return address from memory at address 10 and 11, # and then return from the call. LI U, 0 LI V, 10 MOV X, M LI V, 11 MOV Y, M JMP NOP NOP serial_get_number_available_bytes: # Preserve the value of the link register by # storing return address at address 10 and 11. LI U, 0 LI V, 10 MOV M, G LI V, 11 MOV M, H LI D, kSerialInterface LI Y, kDataPort LI P, kGetNumberOfBytesCommand LI Y, kControlPort LI P, 1 # Raise SCK LXY delay JALR NOP NOP LI U, 0 LI V, 5 MOV M, P # Store the number of available bytes in memory at address 5. LI Y, kControlPort LI P, 0 # Lower SCK LXY delay JALR NOP NOP # Set the return value in "A". LI U, 0 LI V, 5 MOV A, M # Retrieve the return address from memory at address 10 and 11, # and then return from the call. LI U, 0 LI V, 10 MOV X, M LI V, 11 MOV Y, M JMP NOP NOP delay256: LI A, 0 delay256_0: # Increment A by 1. If the value is not equal to 255 then loop. LI B, 1 ADD _ ADD A LI B, 255 CMP CMP LXY delay256_0 JNE NOP NOP MOV X, G MOV Y, H JMP NOP NOP delay: # Preserve the value of the link register by # storing return address at address 0 and 1. LI U, 0 LI V, 0 MOV M, G LI V, 1 MOV M, H LI A, 0 delay_0: # Call delay256, making sure to preserve "A" in memory at address 2. LI U, 0 LI V, 2 MOV M, A LXY delay256 JALR NOP NOP MOV A, M # Increment A by 1. If the value is not equal to 1 then loop. # Adjust the upper limit of the loop according to the CPU speed. LI B, 1 ADD _ ADD A LI B, 1 CMP CMP LXY delay_0 JNE NOP NOP # Retrieve the return address from memory at address 0 and 1, # and then return from the call. LI U, 0 LI V, 0 MOV X, M LI V, 1 MOV Y, M JMP NOP NOP
11.732283
77
0.707159
fe52c33de08577f2c778b83d3c1c5096d08feeec
2,539
h
C
Code/Framework/AzCore/AzCore/Memory/AllocatorWrapper.h
aaarsene/o3de
37e3b0226958974defd14dd6d808e8557dcd7345
[ "Apache-2.0", "MIT" ]
1
2021-09-13T00:01:12.000Z
2021-09-13T00:01:12.000Z
Code/Framework/AzCore/AzCore/Memory/AllocatorWrapper.h
aaarsene/o3de
37e3b0226958974defd14dd6d808e8557dcd7345
[ "Apache-2.0", "MIT" ]
null
null
null
Code/Framework/AzCore/AzCore/Memory/AllocatorWrapper.h
aaarsene/o3de
37e3b0226958974defd14dd6d808e8557dcd7345
[ "Apache-2.0", "MIT" ]
1
2021-07-20T11:07:25.000Z
2021-07-20T11:07:25.000Z
/* * Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. * * SPDX-License-Identifier: Apache-2.0 OR MIT * */ #pragma once #include <AzCore/base.h> #include <AzCore/std/typetraits/alignment_of.h> #include <AzCore/std/typetraits/aligned_storage.h> #include <AzCore/std/utils.h> namespace AZ { /** * Safe wrapper for an instance of an allocator. * * Generally it is preferred to use AllocatorInstance<> for allocator singletons over this wrapper, * but you may want to use this wrapper in particular when scoping a custom allocator to the lifetime * of some other object. */ template<class Allocator> class AllocatorWrapper { public: using Descriptor = typename Allocator::Descriptor; AllocatorWrapper() { } ~AllocatorWrapper() { Destroy(); } AllocatorWrapper(const Allocator&) = delete; /// Creates the wrapped allocator. You may pass any custom arguments to the allocator's constructor. template<typename... Args> void Create(const Descriptor& desc, Args&&... args) { Destroy(); m_allocator = new (&m_storage) Allocator(AZStd::forward<Args>(args)...); m_allocator->Create(desc); m_allocator->PostCreate(); } /// Destroys the wrapped allocator. void Destroy() { if (m_allocator) { m_allocator->PreDestroy(); m_allocator->Destroy(); m_allocator->~Allocator(); } m_allocator = nullptr; } /// Provides access to the wrapped allocator. Allocator* Get() const { return m_allocator; } /// Provides access to the wrapped allocator. Allocator& operator*() const { return *m_allocator; } /// Provides access to the wrapped allocator. Allocator* operator->() const { return m_allocator; } /// Support for conversion to a boolean, returns true if the allocator has been created. operator bool() const { return m_allocator != nullptr; } private: Allocator* m_allocator = nullptr; typename AZStd::aligned_storage<sizeof(Allocator), AZStd::alignment_of<Allocator>::value>::type m_storage; }; }
27.301075
158
0.59039
7078fab5fffc4108e077310f43b993e1849ba263
967
h
C
RepWallet/Classes/DocumentPickerCell.h
flosSoftware/repwallet
f255ff5867aab920e05f2046df287e225230d238
[ "MIT" ]
null
null
null
RepWallet/Classes/DocumentPickerCell.h
flosSoftware/repwallet
f255ff5867aab920e05f2046df287e225230d238
[ "MIT" ]
null
null
null
RepWallet/Classes/DocumentPickerCell.h
flosSoftware/repwallet
f255ff5867aab920e05f2046df287e225230d238
[ "MIT" ]
null
null
null
// // DocumentPickerCell.h // repWallet // // Created by Alberto Fiore on 27/02/13. // Copyright (c) 2013 Alberto Fiore. All rights reserved. // #import "BaseDataEntryCell.h" #import "DocumentViewController.h" #define SEE_BUTTON_HEIGHT 40.0 #define SEE_BUTTON_WIDTH 125.0 #define IPAD_SEE_BUTTON_HEIGHT 80.0 #define IPAD_SEE_BUTTON_WIDTH 250.0 #define SEE_BTN_INTERNAL_HEIGHT 22.75 #define IPAD_SEE_BTN_INTERNAL_HEIGHT 45.5 @interface DocumentPickerCell : BaseDataEntryCell<DocumentViewControllerDelegate> { } @property (nonatomic, retain) UIButton *btn; @property (nonatomic, retain) NSSet *docs; @property (nonatomic, retain) NSSet *oldDocs; @property (nonatomic, retain) DAO *dao; @property (nonatomic, retain) DocumentViewController *docuVC; - (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier boundClassName:(NSString *)boundClassName dataKey:(NSString *)dataKey label:(NSString *)label dao:(DAO *)dao; @end
27.628571
201
0.783868
a33bc1c60288e5f4f1db36d3e35f7cdb5ff6d5ee
1,939
kt
Kotlin
app/src/main/java/com/tjl/lazysdk/HmsAnalyticsActivity.kt
LazyBonesLZ/LazySDK
26ec43cd3198b4f8342c06b93553b3aeb2be9f41
[ "Apache-2.0" ]
2
2019-04-18T06:32:07.000Z
2020-05-08T08:46:30.000Z
app/src/main/java/com/tjl/lazysdk/HmsAnalyticsActivity.kt
LazyBonesLZ/LazySDK
26ec43cd3198b4f8342c06b93553b3aeb2be9f41
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/tjl/lazysdk/HmsAnalyticsActivity.kt
LazyBonesLZ/LazySDK
26ec43cd3198b4f8342c06b93553b3aeb2be9f41
[ "Apache-2.0" ]
3
2019-06-11T01:17:47.000Z
2019-09-17T09:49:41.000Z
package com.tjl.lazysdk import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import com.huawei.hms.analytics.HiAnalytics import com.huawei.hms.analytics.HiAnalyticsInstance import com.huawei.hms.analytics.HiAnalyticsTools import kotlinx.android.synthetic.main.activity_hms_analytics.* import java.text.SimpleDateFormat import java.util.* class HmsAnalyticsActivity : AppCompatActivity() { private lateinit var hmsAnalyticsInstance: HiAnalyticsInstance override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_hms_analytics) initHMSAnalytics() logEvent.setOnClickListener { val time = SimpleDateFormat("YYYY-MM-dd HH:mm:ss").format(Date()) val data = Bundle() data.putString("time",time) logEvent("CustomEvents",data) val tmpMsg = "CustomEvents: Usr Time=$time" status.text = tmpMsg } setUserProperty.setOnClickListener { val time = SimpleDateFormat("YYYY-MM-dd HH:mm:ss").format(Date()) val tmpMsg = "UserProper: Usr Time=$time" status.text = tmpMsg setUserProperty("UserProper", "Usr Time:$time") } } private fun initHMSAnalytics() { HiAnalyticsTools.enableLog() hmsAnalyticsInstance = HiAnalytics.getInstance(this) hmsAnalyticsInstance.setAnalyticsCollectionEnabled(true) hmsAnalyticsInstance.setAutoCollectionEnabled(true) } private fun logEvent(eventName:String,data:Bundle){ hmsAnalyticsInstance.logEvent(eventName,data) } private fun setUserProperty(propertyName:String,proprety:String){ hmsAnalyticsInstance.setUserProperty(propertyName,proprety) } //adb shell setprop debug.huawei.hms.analytics.app <package_name> //adb shell setprop debug.huawei.hms.analytics.app .none. }
35.254545
77
0.709128
bf80fa9acf61584b7eefb76fd17b103a63e7a090
1,046
swift
Swift
test/stdlib/MixedTypeArithmeticsDiagnostics.swift
YellowChang/Swift
d352652a72c73157d94e5fdc0fb477453da41c94
[ "Apache-2.0" ]
394
2016-04-05T12:09:40.000Z
2021-01-24T09:30:54.000Z
test/stdlib/MixedTypeArithmeticsDiagnostics.swift
YellowChang/Swift
d352652a72c73157d94e5fdc0fb477453da41c94
[ "Apache-2.0" ]
19
2016-07-06T15:01:49.000Z
2022-02-03T18:11:25.000Z
test/stdlib/MixedTypeArithmeticsDiagnostics.swift
YellowChang/Swift
d352652a72c73157d94e5fdc0fb477453da41c94
[ "Apache-2.0" ]
45
2016-04-18T12:46:28.000Z
2021-04-23T16:14:40.000Z
//===--- MixedTypeArithmeticsDiagnostics.swift ----------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// // RUN: %target-typecheck-verify-swift func mixedTypeArithemtics() { _ = (42 as Int64) + (0 as Int) // expected-warning {{'+' is deprecated:}} do { var x = Int8() x += (42 as Int) // expected-warning {{'+=' is deprecated:}} } _ = (42 as Int32) - (0 as Int) // expected-warning {{'-' is deprecated:}} do { var x = Int16() x -= (42 as Int) // expected-warning {{'-=' is deprecated:}} } // With Int on both sides should NOT result in warning do { var x = Int() x += (42 as Int) } }
29.055556
80
0.56501
d316ee073e73026e7ecb3a76eb88b8837d22224f
305
sql
SQL
db/procedure.sql
xkoderx/FRESTAPI
8acf0ac4e06390e2937dee9810b684df8aaf4545
[ "MIT" ]
null
null
null
db/procedure.sql
xkoderx/FRESTAPI
8acf0ac4e06390e2937dee9810b684df8aaf4545
[ "MIT" ]
null
null
null
db/procedure.sql
xkoderx/FRESTAPI
8acf0ac4e06390e2937dee9810b684df8aaf4545
[ "MIT" ]
null
null
null
CREATE PROCEDURE empleadoaddoedit ( IN _id INT, IN _name VARCHAR(45), IN _salary INT ) BEGIN IF _id = 0 THEN INSERT INTO empleados(name,salary) VALUES (_name, _salary); SET _id =LAST_INSERT_ID(); ELSE UPDATE empleados SET name= _name, salary= _salary WHERE id = _id; END IF; SELECT _id AS id; END
15.25
35
0.734426
62aad8803bba796696e7a5b4d8a27133dd43d038
1,750
asm
Assembly
programs/oeis/280/A280321.asm
karttu/loda
9c3b0fc57b810302220c044a9d17db733c76a598
[ "Apache-2.0" ]
1
2021-03-15T11:38:20.000Z
2021-03-15T11:38:20.000Z
programs/oeis/280/A280321.asm
karttu/loda
9c3b0fc57b810302220c044a9d17db733c76a598
[ "Apache-2.0" ]
null
null
null
programs/oeis/280/A280321.asm
karttu/loda
9c3b0fc57b810302220c044a9d17db733c76a598
[ "Apache-2.0" ]
null
null
null
; A280321: Number of 2 X 2 matrices with all elements in {0,..,n} having determinant = n*permanent. ; 1,12,25,49,81,121,169,225,289,361,441,529,625,729,841,961,1089,1225,1369,1521,1681,1849,2025,2209,2401,2601,2809,3025,3249,3481,3721,3969,4225,4489,4761,5041,5329,5625,5929,6241,6561,6889,7225,7569,7921,8281,8649,9025,9409,9801,10201,10609,11025,11449,11881,12321,12769,13225,13689,14161,14641,15129,15625,16129,16641,17161,17689,18225,18769,19321,19881,20449,21025,21609,22201,22801,23409,24025,24649,25281,25921,26569,27225,27889,28561,29241,29929,30625,31329,32041,32761,33489,34225,34969,35721,36481,37249,38025,38809,39601,40401,41209,42025,42849,43681,44521,45369,46225,47089,47961,48841,49729,50625,51529,52441,53361,54289,55225,56169,57121,58081,59049,60025,61009,62001,63001,64009,65025,66049,67081,68121,69169,70225,71289,72361,73441,74529,75625,76729,77841,78961,80089,81225,82369,83521,84681,85849,87025,88209,89401,90601,91809,93025,94249,95481,96721,97969,99225,100489,101761,103041,104329,105625,106929,108241,109561,110889,112225,113569,114921,116281,117649,119025,120409,121801,123201,124609,126025,127449,128881,130321,131769,133225,134689,136161,137641,139129,140625,142129,143641,145161,146689,148225,149769,151321,152881,154449,156025,157609,159201,160801,162409,164025,165649,167281,168921,170569,172225,173889,175561,177241,178929,180625,182329,184041,185761,187489,189225,190969,192721,194481,196249,198025,199809,201601,203401,205209,207025,208849,210681,212521,214369,216225,218089,219961,221841,223729,225625,227529,229441,231361,233289,235225,237169,239121,241081,243049,245025,247009,249001 mov $1,3 trn $1,$0 mov $4,$0 mul $0,$1 pow $1,$0 mov $2,$4 mul $2,4 add $1,$2 mov $3,$4 mul $3,$4 mov $2,$3 mul $2,4 add $1,$2
102.941176
1,521
0.804
dff83122bd7a883e7986d9dd211e8b9c21c430c2
1,136
ts
TypeScript
packages/cast/blockchain-driver-eth/src/signer/walletSigner.ts
castframework/gba
6acbcfc7f6b687bb1e698b613102ade36b5bd4c0
[ "Apache-2.0" ]
3
2022-02-01T09:07:58.000Z
2022-02-10T10:08:08.000Z
packages/cast/blockchain-driver-eth/src/signer/walletSigner.ts
castframework/cast
6acbcfc7f6b687bb1e698b613102ade36b5bd4c0
[ "Apache-2.0" ]
null
null
null
packages/cast/blockchain-driver-eth/src/signer/walletSigner.ts
castframework/cast
6acbcfc7f6b687bb1e698b613102ade36b5bd4c0
[ "Apache-2.0" ]
null
null
null
import { EthereumSignedTx, EthereumTx } from '../types'; import { Signer } from '@castframework/types'; import { addHexPrefix, bufferToHex, privateToAddress, toBuffer, } from 'ethereumjs-util'; // eslint-disable-next-line @typescript-eslint/no-var-requires const Accounts = require('web3-eth-accounts'); export class PrivateKeySigner implements Signer<EthereumTx, EthereumSignedTx> { // eslint-disable-next-line @typescript-eslint/ban-ts-comment // @ts-ignore accountBase = new Accounts(); constructor(private readonly privateKey: string) {} public async sign(transaction: EthereumTx): Promise<EthereumSignedTx> { const account = this.accountBase.privateKeyToAccount(this.privateKey); try { const signature = await account.signTransaction(transaction); if (!signature.rawTransaction) { throw new Error('Error while signing the transaction'); } return signature.rawTransaction; } catch (e) { return Promise.reject(e); } } public getPublicKey(): string { return addHexPrefix( bufferToHex(privateToAddress(toBuffer(this.privateKey))), ); } }
29.128205
79
0.713028
efde26d18537f60dc11d9a1f3a673a54b12265e3
325
sql
SQL
presto-product-tests/src/main/resources/sql-tests/testcases/window_functions/rowsRangeLeadLag.sql
sreekanth370/presto
6be1558cfa40e8122eb714ba21e94927b410098b
[ "Apache-2.0" ]
9,782
2016-03-18T15:16:19.000Z
2022-03-31T07:49:41.000Z
presto-product-tests/src/main/resources/sql-tests/testcases/window_functions/rowsRangeLeadLag.sql
sreekanth370/presto
6be1558cfa40e8122eb714ba21e94927b410098b
[ "Apache-2.0" ]
10,310
2016-03-18T01:03:00.000Z
2022-03-31T23:54:08.000Z
presto-product-tests/src/main/resources/sql-tests/testcases/window_functions/rowsRangeLeadLag.sql
sreekanth370/presto
6be1558cfa40e8122eb714ba21e94927b410098b
[ "Apache-2.0" ]
3,803
2016-03-18T22:54:24.000Z
2022-03-31T07:49:46.000Z
-- database: presto; groups: window; select orderkey, suppkey, discount, lead(discount) over (partition by suppkey order by orderkey desc) next_discount, extendedprice, lag(extendedprice) over (partition by discount order by extendedprice range current row) previous_extendedprice from tpch.tiny.lineitem where partkey = 272
40.625
111
0.815385
0ba85fbeb42af5350f4ee75ef084944f0049c3d4
624
js
JavaScript
src/pages/editor/Editor.js
lightvdv/AnkiChrome
391d2dadb399815d2f171c5254e42ec1682f064d
[ "MIT" ]
null
null
null
src/pages/editor/Editor.js
lightvdv/AnkiChrome
391d2dadb399815d2f171c5254e42ec1682f064d
[ "MIT" ]
2
2021-07-06T13:17:56.000Z
2021-11-13T18:09:28.000Z
src/pages/editor/Editor.js
lightvdv/AnkiChrome
391d2dadb399815d2f171c5254e42ec1682f064d
[ "MIT" ]
null
null
null
import {Button, makeStyles} from "@material-ui/core"; import React from "react"; const useStyles = makeStyles({ editor:{ position: "fixed", zIndex: 10000, top: "100px", left: "100px" } }); export function Editor(){ const classes = useStyles(); return <div className={classes.editor}> <Button color="secondary" variant="contained" onClick={() => { chrome.storage.sync.set({"create_card": new Date().toString()}); }}> Hello Anki </Button>; </div> } export default Editor;
20.8
84
0.527244
f6a15691a324daf4370a86375d2322bc12febef1
169
sql
SQL
src/main/resources/db/migration/V005__add-columns-cartao.sql
edsonmoreirazup/bootcamp-02-template-proposta
0b9fd726fe2435a584e25bece3e0867dc8b886bf
[ "Apache-2.0" ]
null
null
null
src/main/resources/db/migration/V005__add-columns-cartao.sql
edsonmoreirazup/bootcamp-02-template-proposta
0b9fd726fe2435a584e25bece3e0867dc8b886bf
[ "Apache-2.0" ]
null
null
null
src/main/resources/db/migration/V005__add-columns-cartao.sql
edsonmoreirazup/bootcamp-02-template-proposta
0b9fd726fe2435a584e25bece3e0867dc8b886bf
[ "Apache-2.0" ]
null
null
null
ALTER TABLE cartao ADD COLUMN data_criacao DATETIME NOT NULL, ADD COLUMN status_cartao VARCHAR(45) NOT NULL, ADD COLUMN titular_cartao VARCHAR(60) NOT NULL;
33.8
51
0.763314
c42d9d2c0fafe03413ab6ffa882d5c0d59513a53
5,620
h
C
CONTRIB/ExeLoader/include/ExeLoader.h
Cwc-Test/CpcdosOS2.1
d52c170be7f11cc50de38ef536d4355743d21706
[ "Apache-2.0" ]
null
null
null
CONTRIB/ExeLoader/include/ExeLoader.h
Cwc-Test/CpcdosOS2.1
d52c170be7f11cc50de38ef536d4355743d21706
[ "Apache-2.0" ]
null
null
null
CONTRIB/ExeLoader/include/ExeLoader.h
Cwc-Test/CpcdosOS2.1
d52c170be7f11cc50de38ef536d4355743d21706
[ "Apache-2.0" ]
2
2019-09-01T10:38:54.000Z
2020-06-26T19:57:39.000Z
/* -== ExeLoader ==- * * Load .exe / .dll from memory and remap functions * Run your binaries on any x86 hardware * * @autors * - Maeiky * - Sebastien FAVIER * * Copyright (c) 2020 - V·Liance / SPinti-Software. All rights reserved. * * The contents of this file are subject to the Apache License Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * If a copy of the Apache License Version 2.0 was not distributed with this file, * You can obtain one at https://www.apache.org/licenses/LICENSE-2.0.html * */ #ifndef EXELOADER_Exeloader_H #define EXELOADER_Exeloader_H #include "_Config.h" #include <cstdlib> #include <cstdio> #include <cstring> #include <cstdarg> #include <csignal> #include <memory> #include <wchar.h> #include "ConvertUTF.h" extern void _EXE_LOADER_DEBUG(int alert, const char* format_FR, const char* format_EN, ...); //#define _EXE_LOADER_DEBUG_S(_msg, ...) _EXE_LOADER_DEBUG(0, _msg, _msg); #define _EXE_LOADER_DEBUG_(_msg, ...) _EXE_LOADER_DEBUG(0, _msg, _msg, __VA_ARGS__); #include "FuncPrototype/win.h" #include "MemoryModule.h" #ifdef CpcDos #include "FuncPrototype/CPC_WPR.h" //#include "Lib_GZ/SysUtils/CpcDosHeader.h" #endif #ifndef STDCALL #define STDCALL __stdcall #endif #ifndef FuncTableStructure #define FuncTableStructure typedef void* (*FUNC_)(); typedef struct { const char* sFuncName; FUNC_* dFunc; } FuncTable; #undef PFUNC_ #define PFUNC_ FUNC_* #endif #define Func(_func) (void*)(&_func) #define DEREF_32(name) *(DWORD *)(name) #define BLOCKSIZE 100 extern HMEMORYMODULE AddLibrary(const char* _sPath); //ExeLoader.cpp extern DWORD My_GetLastError(); extern FARPROC MyMemoryDefaultGetProcAddress(HCUSTOMMODULE module, LPCSTR name, void *userdata); extern MemoryModule* memory_module; extern bool is_in_aLibList(HMEMORYMODULE _handle); extern "C" bool fStartExeLoader(const char* Source_File); typedef void* (*FUNC_)(); typedef struct {const char* sLib; const char* sFuncName;FUNC_ dFunc;} sFunc; /// Main Func Ptr ///s typedef int (*addNumberProc)(int, int); typedef void (*testFunc)(); typedef int (*mainFunc)(); typedef int (*mainFunc2)(int argc, char* argv[]); typedef int (WINAPI *winMain)(HINSTANCE hInstance, HINSTANCE hPrevInstance, PWSTR pCmdLine, int nCmdShow); //int WINAPI wWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, PWSTR pCmdLine, int nCmdShow); typedef void (*FUNC_Version)(int _nMajor, int _nMinor); /// Generic Func Ptr /// typedef bool (*funcPtr_bool)(void*); typedef int (*funcPtr_int)(void*); typedef int (*funcPtrPtr_int)(void*,void*); typedef bool (*funcPtrIntPtr_bool)(void*,int,void*); typedef int (*funcPtrIntIntPtr_int)(void*,int,int,void*); /// Log /// #define showfunc_unimplt(name, ...) _EXE_LOADER_DEBUG(0, "\n-->Appel de Fonction non implémenté: " name, "\n-->Call not implemented func: " name , __VA_ARGS__); #define showfunc(name, ...) _EXE_LOADER_DEBUG(0, "\n-->Appel de: " name, "\n-->Call: " name , __VA_ARGS__); #define showfunc_ret(name, ...) _EXE_LOADER_DEBUG(0, "\n-->Retour: " name, "\n-->Return: " name , __VA_ARGS__); #define showinf(name, ...) _EXE_LOADER_DEBUG(0, "\n--: " name, "\n---: " name , __VA_ARGS__); extern int exe_arg_nb; extern char** exe_arg; extern HINSTANCE hExeloader; //extern HWND hwnd_View; typedef struct { HBITMAP hbmp; HWND hwnd_View; void* pixels; int idx; int width; int height; int id_context; // cpcdos } ContextInf; extern int aContext_count; extern ContextInf aContext[50]; HWND pixView_createWindow( HINSTANCE hInstance, ContextInf* _context); void pixView_update(ContextInf* _context); void pixView_MakeSurface(ContextInf* _context); #ifdef Show_AllFuncTable #define showfunc_opt showfunc #else #define showfunc_opt #endif #ifndef Show_FuncTable #undef showfunc #define showfunc #undef showfunc_ret #define showfunc_ret #undef showfunc_unimplt #define showfunc_unimplt #undef showfunc_opt #define showfunc_opt #endif inline static size_t wcslen_(const wchar_t *s){ size_t ln = 0; while (s[ln] != L'\0'){ if (s[++ln] == L'\0')return ln; if (s[++ln] == L'\0')return ln; if (s[++ln] == L'\0')return ln; ++ln; }return ln; } /// STRING /// class WStr { public: wchar_t* src; size_t len; UTF8* utf8; WStr(const wchar_t* _src):utf8(0) { src = (wchar_t*)_src; len = wcslen_(src); } inline char* ToCStr(){ const UTF16* input = (const UTF16*)src; UTF8* utf8 = (UTF8*)malloc(len+1);//+1 for null terminating char UTF8* outStart = (UTF8*)utf8; ConversionResult res = ConvertUTF16toUTF8(&input, &input[len], &utf8, &utf8[len], ConversionFlags::lenientConversion); //Possible value of res: conversionOK || sourceExhausted || targetExhausted *utf8 = 0; //Terminate string return (char*)outStart; } ~WStr(){ free(utf8); } }; //////////////// #ifndef No_vswprintf #define vswprintf_ARG(format, dest, max, ret)va_list _arg_;va_start (_arg_, format);int ret = vswprintf((wchar_t*)dest, max, format, _arg_);va_end (_arg_); #else #define msg_no_vswprintf L"\nWarning[No vswprintf]" #define vswprintf_ARG(format, dest, max, ret) int ret = sizeof(msg_no_vswprintf);if(ret<max){memcpy(dest, msg_no_vswprintf,ret);}; #endif #ifndef No_vsnprintf #define vsnprintf_ARG(format, dest, max, ret)va_list _arg_;va_start (_arg_, format);int ret = vsnprintf((char*)dest, max, format, _arg_);va_end (_arg_); #else #define msg_no_vsnprintf L"\nWarning[No No_vsnprintf]" #define vsnprintf_ARG(format, dest, max, ret) int ret = sizeof(msg_no_vsnprintf);if(ret<max){memcpy(dest, msg_no_vsnprintf,ret);}; #endif #endif //EXELOADER_Exeloader_H
28.241206
160
0.721174
50022a7d10e19b2e6a2a86af2a0b4344be27b9a1
345
js
JavaScript
Web.Client/src/Components/Common/Link.js
naskodaskalov/Bulls-And-Cows
5d5bd822cde666913fc578e40ffd907e6f1b684a
[ "Apache-2.0" ]
null
null
null
Web.Client/src/Components/Common/Link.js
naskodaskalov/Bulls-And-Cows
5d5bd822cde666913fc578e40ffd907e6f1b684a
[ "Apache-2.0" ]
null
null
null
Web.Client/src/Components/Common/Link.js
naskodaskalov/Bulls-And-Cows
5d5bd822cde666913fc578e40ffd907e6f1b684a
[ "Apache-2.0" ]
null
null
null
import React from 'react' import { NavLink } from 'react-router-dom' import './Buttons.css' const Link = (props) => { var isButton = props.isButton != null ? props.isButton : '' return ( <NavLink to={props.link} activeClassName='active' className={`nav-link ${isButton}`}> {props.name} </NavLink> ) } export default Link
20.294118
89
0.649275
0a044eebd416bef85db69550d2e58a505a85dcd1
1,779
kt
Kotlin
app/src/main/java/com/jakelaurie/squadspook/di/module/NetworkModule.kt
jakelaurieNZ/SquadSpook
46dc4bca860450966db9ddb83b6f329919518a6d
[ "MIT" ]
null
null
null
app/src/main/java/com/jakelaurie/squadspook/di/module/NetworkModule.kt
jakelaurieNZ/SquadSpook
46dc4bca860450966db9ddb83b6f329919518a6d
[ "MIT" ]
1
2018-07-15T17:53:58.000Z
2018-07-15T17:53:58.000Z
app/src/main/java/com/jakelaurie/squadspook/di/module/NetworkModule.kt
jakelaurieNZ/SquadSpook
46dc4bca860450966db9ddb83b6f329919518a6d
[ "MIT" ]
null
null
null
package com.jakelaurie.squadspook.di.module import com.google.gson.Gson import com.google.gson.GsonBuilder import com.jakelaurie.squadspook.annotations.OpenForTesting import com.jakelaurie.squadspook.data.network.PlayerApi import com.jakelaurie.squadspook.data.network.ServerApi import dagger.Module import dagger.Provides import okhttp3.OkHttpClient import retrofit2.Retrofit import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory import retrofit2.converter.gson.GsonConverterFactory import javax.inject.Named import javax.inject.Singleton @OpenForTesting @Module class NetworkModule { @Provides @Singleton fun providesOkHttpClient(): OkHttpClient = OkHttpClient.Builder().build() @Provides @Singleton fun providesGson(): Gson = GsonBuilder().create() @Provides @Singleton fun providesRetrofitBuilder(okHttpClient: OkHttpClient, gson : Gson): Retrofit.Builder { return Retrofit.Builder() .client(okHttpClient) .addConverterFactory(GsonConverterFactory.create(gson)) .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) } @Provides @Singleton fun providesServerApi(retrofitBuilder: Retrofit.Builder, @Named("serverApiUrl") serverApiUrl: String): ServerApi { return retrofitBuilder .baseUrl(serverApiUrl) .build() .create(ServerApi::class.java) } @Provides @Singleton fun providesPlayerApi(retrofitBuilder: Retrofit.Builder, @Named("playerApiUrl") playerApiUrl: String): PlayerApi { return retrofitBuilder .baseUrl(playerApiUrl) .build() .create(PlayerApi::class.java) } }
31.767857
92
0.694772
24beb9885d389b811855bfc4c8b08f03faaa0a4c
266
kt
Kotlin
app/src/main/java/dev/vaibhav/quizzify/data/models/remote/QuizResponse.kt
Vaibhav2002/Quizzify
7527d4bc20d86808b2a04c193466273663cff9f0
[ "MIT" ]
3
2022-03-31T12:47:38.000Z
2022-03-31T19:02:12.000Z
app/src/main/java/dev/vaibhav/quizzify/data/models/remote/QuizResponse.kt
Vaibhav2002/Quizzify
7527d4bc20d86808b2a04c193466273663cff9f0
[ "MIT" ]
null
null
null
app/src/main/java/dev/vaibhav/quizzify/data/models/remote/QuizResponse.kt
Vaibhav2002/Quizzify
7527d4bc20d86808b2a04c193466273663cff9f0
[ "MIT" ]
null
null
null
package dev.vaibhav.quizzify.data.models.remote import com.google.gson.annotations.SerializedName data class QuizResponse( @SerializedName("response_code") val responseCode: Int = 0, @SerializedName("results") val results: List<Result> = listOf() )
26.6
49
0.74812
b639204f343092fe978f4fc75395cd81f5bc3a40
90
rb
Ruby
app/models/twitter_photo.rb
bringel/tagstream
c9c5dde7baabc34449ad9a1bc4e1890b8ec0b4d1
[ "MIT" ]
null
null
null
app/models/twitter_photo.rb
bringel/tagstream
c9c5dde7baabc34449ad9a1bc4e1890b8ec0b4d1
[ "MIT" ]
2
2016-04-28T17:25:23.000Z
2016-04-28T17:26:05.000Z
app/models/twitter_photo.rb
bringel/spotlens
c9c5dde7baabc34449ad9a1bc4e1890b8ec0b4d1
[ "MIT" ]
null
null
null
class TwitterPhoto < ActiveRecord::Base validates(:tweet_id, {:uniqueness => true}) end
22.5
45
0.744444
743f4598c2fa18dcb54cf4fe7b880eb3a65db939
2,963
h
C
StresserEngine/GenericHandle.h
AvivShabtay/Stresser
7182a8ff61e927219415c2068e0874b94c2156b1
[ "MIT" ]
7
2020-09-04T14:08:07.000Z
2022-01-20T12:11:04.000Z
StresserEngine/GenericHandle.h
AvivShabtay/Stresser
7182a8ff61e927219415c2068e0874b94c2156b1
[ "MIT" ]
15
2021-04-26T08:48:26.000Z
2021-07-10T14:52:37.000Z
StresserEngine/GenericHandle.h
AvivShabtay/Stresser
7182a8ff61e927219415c2068e0874b94c2156b1
[ "MIT" ]
5
2020-10-24T16:21:12.000Z
2022-01-23T11:20:17.000Z
#pragma once #include <ntifs.h> /* Represent the valid traits for using GenericHandle object. */ struct CommonTraits { static void close(const HANDLE handle) { UNREFERENCED_PARAMETER(handle); } static bool isValid(const HANDLE handle) { UNREFERENCED_PARAMETER(handle); return false; } static HANDLE invalidHandle() { return nullptr; } }; /* * Define object for managing handle safely. * Credit for @Zodiacon: https://github.com/zodiacon/ndcoslo2019/tree/master/CppKernel */ template<typename T, typename Traits = CommonTraits> class GenericHandle final { public: explicit GenericHandle(T handle = Traits::invalidHandle(), const bool owner = true) : m_handle(handle), m_owner(owner) { } /* Destructor */ ~GenericHandle() { __try { this->reset(); } __except (EXCEPTION_EXECUTE_HANDLER) { KdPrint(("Exception accrued in GenericHandle destructor\n")); } } // Disable copyable: GenericHandle(GenericHandle&) = delete; GenericHandle& operator=(const GenericHandle&) = delete; /* Move constructor */ GenericHandle(GenericHandle&& other) noexcept { this->m_handle = other.m_handle; this->m_owner = other.m_owner; other.m_handle = nullptr; } /* Move assignment */ GenericHandle& operator=(GenericHandle&& other) noexcept { if (this != &other) { this->reset(); this->m_handle = other.m_handle; this->m_owner = other.m_owner; other.m_handle = nullptr; } return *this; } /* Equality operator. */ bool operator==(const GenericHandle& other) { return this->m_handle == other.m_handle; } /* Function like call to return the object handle member. */ operator T() const { return this->get(); } /* Return the handle member. */ T get() const { return this->m_handle; } /* Verify if the handle member is valid. */ operator bool const() { return Traits::isValid(this->m_handle); } /* Return the address of the handle member. */ T* getAddressOf() { NT_ASSERT(!Traits::isValid(this->m_handle)); return &this->m_handle; } /* Close the current handle and manage another one. */ void reset(T handle = nullptr, bool owner = true) { if (this->m_owner && this->m_handle) { Traits::close(this->m_handle); } this->m_handle = handle; this->m_owner = owner; } /* * Stop manage the handle member. * @note The handle would not be release in class destruction. */ T detach() { auto handle = this->m_handle; this->m_handle = nullptr; return handle; } private: T m_handle; bool m_owner; }; /* Represent traits for simple kernel handle. */ struct KernelHandleTraits : CommonTraits { static void close(const HANDLE handle) { if (nullptr != handle) { ZwClose(handle); } } static bool isValid(const HANDLE handle) { return handle != nullptr; } static HANDLE invalidHandle() { return nullptr; } }; /* Define smart pointer for kernel space. */ using AutoKernelHandle = GenericHandle<HANDLE, KernelHandleTraits>;
18.63522
86
0.685116
970e64b662c8b1723f560c17570a471daf0abf4b
723
swift
Swift
RevolutTestTests/Stubs/StubURLSessionFetcher.swift
ipavlidakis/RevolutAPI
f5737897aefd39da48131319cb56460cb72230fb
[ "MIT" ]
null
null
null
RevolutTestTests/Stubs/StubURLSessionFetcher.swift
ipavlidakis/RevolutAPI
f5737897aefd39da48131319cb56460cb72230fb
[ "MIT" ]
null
null
null
RevolutTestTests/Stubs/StubURLSessionFetcher.swift
ipavlidakis/RevolutAPI
f5737897aefd39da48131319cb56460cb72230fb
[ "MIT" ]
null
null
null
// // StubURLSessionFetcher.swift // RevolutTestTests // // Created by Ilias Pavlidakis on 1/16/19. // Copyright © 2019 Ilias Pavlidakis. All rights reserved. // import Foundation @testable import RevolutTest final class StubURLSessionFetcher { private(set) var fetchWasCalled: (request: URLRequest, completionBlock: (Result) -> Void)? var fetchStubResult: StubURLSessionDataTask = StubURLSessionDataTask() } extension StubURLSessionFetcher: URLSessionFetching { func fetch( from request: URLRequest, completionBlock: @escaping (Result) -> Void) -> URLSessionTask { fetchWasCalled = (request: request, completionBlock: completionBlock) return fetchStubResult } }
24.1
94
0.726141
157807cc4ac6c5a87d03de96b95c5570e5f53576
174
rb
Ruby
db/migrate/20160916081213_add_admin_user_id_to_application_submission_url.rb
maninderbawavip/pupilfirst
59d7846d5fe3cd2deb20afcef89b67f06bea325a
[ "MIT" ]
null
null
null
db/migrate/20160916081213_add_admin_user_id_to_application_submission_url.rb
maninderbawavip/pupilfirst
59d7846d5fe3cd2deb20afcef89b67f06bea325a
[ "MIT" ]
5
2021-03-30T10:35:43.000Z
2022-02-26T07:59:12.000Z
db/migrate/20160916081213_add_admin_user_id_to_application_submission_url.rb
rkyankya/Uni
6327fb5e7bdf849e3794bd0da34a63c3bf519408
[ "MIT" ]
null
null
null
class AddAdminUserIdToApplicationSubmissionUrl < ActiveRecord::Migration[6.0] def change add_reference :application_submission_urls, :admin_user, index: true end end
29
77
0.816092
0b9b80c225b518a078b36396f1fbccc56916e124
738
py
Python
server/waitFramerate.py
mboerwinkle/RingGame
5a9b6a6ea394c1e88689fa062d4d348383ab406a
[ "MIT" ]
null
null
null
server/waitFramerate.py
mboerwinkle/RingGame
5a9b6a6ea394c1e88689fa062d4d348383ab406a
[ "MIT" ]
null
null
null
server/waitFramerate.py
mboerwinkle/RingGame
5a9b6a6ea394c1e88689fa062d4d348383ab406a
[ "MIT" ]
null
null
null
import time #Timing stuff lastTime = None prevFrameTime = 0; def waitFramerate(T): #TODO if we have enough time, call the garbage collector global lastTime, prevFrameTime ctime = time.monotonic() if lastTime: frameTime = ctime-lastTime #how long the last frame took sleepTime = T-frameTime #how much time is remaining in target framerate if prevFrameTime > frameTime and prevFrameTime > 1.2*T: print("Peak frame took "+str(prevFrameTime)[:5]+"/"+str(int(1.0/prevFrameTime))+" FPS (Target "+str(T)[:5]+")") if(sleepTime <= 0): #we went overtime. set start of next frame to now, and continue lastTime = ctime else: lastTime = lastTime+T time.sleep(sleepTime) prevFrameTime = frameTime else: lastTime = ctime
32.086957
114
0.720867
d5bd266ca2d700f53c71826b11582ae40e5ce3d0
2,541
h
C
src/Utilities/Iterator.h
Otamaa/Antares
7241a5ff20f4dbf7153cc77e16edca5c9db473d4
[ "BSD-4-Clause" ]
4
2021-04-24T04:34:06.000Z
2021-09-19T13:55:33.000Z
src/Utilities/Iterator.h
Otamaa/Antares
7241a5ff20f4dbf7153cc77e16edca5c9db473d4
[ "BSD-4-Clause" ]
null
null
null
src/Utilities/Iterator.h
Otamaa/Antares
7241a5ff20f4dbf7153cc77e16edca5c9db473d4
[ "BSD-4-Clause" ]
2
2021-08-17T14:44:45.000Z
2021-09-19T11:02:04.000Z
#pragma once #include <ArrayClasses.h> #include <vector> template<typename T> class Iterator { private: const T* items{ nullptr }; size_t count{ 0 }; public: Iterator() = default; Iterator(const T* first, size_t count) : items(first), count(count) {} Iterator(const std::vector<T> &vec) : items(vec.data()), count(vec.size()) {} Iterator(const VectorClass<T> &vec) : items(vec.Items), count(static_cast<size_t>(vec.Capacity)) {} Iterator(const DynamicVectorClass<T> &vec) : items(vec.Items), count(static_cast<size_t>(vec.Count)) {} T at(size_t index) const { return this->items[index]; } size_t size() const { return this->count; } const T* begin() const { return this->items; } const T* end() const { if(!this->valid()) { return nullptr; } return &this->items[count]; } bool valid() const { return items != nullptr; } bool empty() const { return !this->valid() || !this->count; } bool contains(T other) const { return std::find(this->begin(), this->end(), other) != this->end(); } operator bool() const { return !this->empty(); } bool operator !() const { return this->empty(); } const T& operator [](size_t index) const { return this->items[index]; } template<typename Out, typename = std::enable_if_t<std::is_assignable<Out&, T>::value>> operator Iterator<Out>() const { // note: this does only work if pointer-to-derived equals pointer-to-base. // if derived has virtual methods and base hasn't, this will just break. return Iterator<Out>(reinterpret_cast<const Out*>(this->items), this->count); } }; template <typename T> Iterator<T> make_iterator_single(const T& value) { return Iterator<T>(&value, 1); } template <typename T, size_t Size> Iterator<T> make_iterator(const T(&arr)[Size]) { return Iterator<T>(arr, Size); } template <typename T> Iterator<T> make_iterator(const T* ptr, size_t size) { return Iterator<T>(ptr, size); } // vector classes template <typename T> Iterator<T> make_iterator(const VectorClass<T>& value) { return Iterator<T>(value); } template <typename T> Iterator<T> make_iterator(const DynamicVectorClass<T>& value) { return Iterator<T>(value); } template <typename T> Iterator<T> make_iterator(const std::vector<T>& value) { return Iterator<T>(value); } // iterator does not keep temporary alive, thus rvalues are forbidden. // use the otherwise wierd const&& to not catch any lvalues template <typename T> void make_iterator_single(const T&&) = delete; template <typename T> void make_iterator(const T&&) = delete;
23.527778
104
0.689886
fd649e1dcd9774437f0055d4badd67cf9dbce7b3
126
h
C
Engine/Device/DeviceShader.h
RichardUSTC/JyRender
06107edd8bc3c28732fb70f6a3ae50c924535030
[ "MIT" ]
1
2018-12-16T15:49:13.000Z
2018-12-16T15:49:13.000Z
Engine/Device/DeviceShader.h
RichardUSTC/JyRender
06107edd8bc3c28732fb70f6a3ae50c924535030
[ "MIT" ]
null
null
null
Engine/Device/DeviceShader.h
RichardUSTC/JyRender
06107edd8bc3c28732fb70f6a3ae50c924535030
[ "MIT" ]
null
null
null
#pragma once #include "Common/Ref.h" class GraphicShader : public Ref {}; using GraphicShaderPtr = OwnerPtr<GraphicShader>;
18
49
0.761905
01cd0f71ab72ff586b4bf4c2a7c0a80d531d5e8b
2,803
rs
Rust
bootloader/src/main.rs
carlosdamazio/KalcOS
262d5bfbc913e1f234f4cbcdea451699cdd944da
[ "MIT" ]
null
null
null
bootloader/src/main.rs
carlosdamazio/KalcOS
262d5bfbc913e1f234f4cbcdea451699cdd944da
[ "MIT" ]
2
2021-12-08T01:33:05.000Z
2022-01-17T17:34:35.000Z
bootloader/src/main.rs
carlosdamazio/KalcOS
262d5bfbc913e1f234f4cbcdea451699cdd944da
[ "MIT" ]
null
null
null
#![no_main] #![no_std] extern crate rlibc; mod elf; mod file; use core::cell::UnsafeCell; use core::mem::{size_of, transmute}; use core::slice::from_raw_parts_mut; use log::{info, error}; use uefi::prelude::*; use uefi::proto::media::fs::SimpleFileSystem; use uefi::proto::media::file::*; use uefi::table::boot::MemoryType; use uefi::table::runtime::Time; use uefi::Char16; const FILE_INFO_BUFFER_LEN: usize = { let align = size_of::<FileInfoHeader>(); let required = align + 11 * size_of::<Char16>(); align * ((required + (align - 1)) / align) }; fn get_image_fs( st: &SystemTable<Boot>, _handle: Handle, ) -> &UnsafeCell<SimpleFileSystem> { st.boot_services().locate_protocol::<SimpleFileSystem>().unwrap() } #[no_mangle] pub extern "C" fn efi_main(image_handle: Handle, mut system_table: SystemTable<Boot>) -> Status { // Initialize UEFI and boot services info!("Initializing system table..."); uefi_services::init(&mut system_table)?; info!("Starting boot services..."); let kernel_elf_slice = uefi::CString16::try_from("KalcOS.elf").unwrap(); let kernel_elf_name = &uefi::CStr16::from_u16_with_nul(kernel_elf_slice.to_u16_slice_with_nul()).unwrap(); let root = get_image_fs(&system_table, image_handle); let root = unsafe { &mut *root.get() }; info!("Loading kernel..."); let mut kernel_file = match file::get_regular_file(root, kernel_elf_name) { Ok(file) => file, Err(err) => { error!("couldn't open kernel file"); return err.status() } }; let mut buf = [0u8; FILE_INFO_BUFFER_LEN]; let info = kernel_file .get_info::<FileInfo>(&mut buf) .unwrap(); let kernel_pool = system_table.boot_services().allocate_pool( MemoryType::LOADER_DATA, info.file_size() as usize ).unwrap(); match kernel_file.read( unsafe {from_raw_parts_mut(kernel_pool, info.file_size() as usize)} ) { Ok(_) => {} Err(_) => error!("couldn't read kernel") }; let file_header = elf::get_file_header(kernel_pool); let program_headers = elf::get_program_headers(&kernel_pool, file_header); elf::allocate_kernel(&system_table, program_headers, &mut kernel_file ); info!("Kernel entry point at: 0x{:x}, calling it...", file_header.e_entry); let entry: extern "sysv64" fn () -> u64 = unsafe { transmute(file_header.e_entry) }; let res: u64 = entry(); info!("Kernel initialized! Response: {}\n", res); uefi::Status::SUCCESS } #[derive(Debug)] #[repr(C)] struct FileInfoHeader { size: u64, file_size: u64, physical_size: u64, create_time: Time, last_access_time: Time, modification_time: Time, attribute: FileAttribute, }
31.494382
111
0.64538
c47ef6d95b569b0c6578d1afddd80a16938f83ab
3,186
h
C
Mocha/Mocha.h
avaidyam/Mocha
c1d7e6721f13e00e90e075a5fceab942901235ee
[ "BSD-3-Clause" ]
8
2016-01-01T14:59:28.000Z
2021-05-06T00:38:26.000Z
Mocha/Mocha.h
avaidyam/Mocha
c1d7e6721f13e00e90e075a5fceab942901235ee
[ "BSD-3-Clause" ]
null
null
null
Mocha/Mocha.h
avaidyam/Mocha
c1d7e6721f13e00e90e075a5fceab942901235ee
[ "BSD-3-Clause" ]
null
null
null
/* * Mocha.framework * * Copyright (c) 2013 Galaxas0. All rights reserved. * For more copyright and licensing information, please see LICENSE.md. */ // TODO: Add NSAppearance. // TODO: Add NSEventRecognizer. // TODO: Add NSUserNotification. // TODO: Add NSScrollView Live Magnify/Scroll // TODO: NSScrollView Floating Subviews // TODO: NSWindow/Application Occlusion // Frameworks #import <AppKit/AppKit.h> #import <CoreData/CoreData.h> #import <QuartzCore/QuartzCore.h> #import <Foundation/Foundation.h> // Classes #import "BINAnimation.h" #import "NSSystemInfo.h" #import "NSImagePicker.h" #import "BINInspectorBar.h" // Foundation Categories #import "NSAffineTransform+BINExtensions.h" #import "NSCache+BINExtensions.h" #import "NSError+BINExtensions.h" #import "NSObject+BINExtensions.h" #import "NSProcessInfo+BINExtensions.h" #import "NSString+BINExtensions.h" #import "NSTimer+BINExtensions.h" #import "NSUserDefaults+BINExtensions.h" #import "NSUUID+BINExtensions.h" // Quartz Categories #import "CAAnimation+BINExtensions.h" #import "CATransaction+BINExtensions.h" // AppKit Graphics Categories #import "NSBezierPath+BINExtensions.h" #import "NSColor+BINExtensions.h" #import "NSGradient+BINExtensions.h" #import "NSImage+BINExtensions.h" #import "NSShadow+BINExtensions.h" // AppKit Control Categories #import "NSControl+BINExtensions.h" #import "NSClipView+BINExtensions.h" #import "NSTextField+BINExtensions.h" #import "NSTextView+BINExtensions.h" // AppKit Display Categories #import "NSAlert+BINExtensions.h" #import "NSColorPanel+BINExtensions.h" #import "NSPopover+BINExtensions.h" #import "NSView+BINExtensions.h" #import "NSWindow+BINExtensions.h" extern void NSMoveToApplicationsFolderIfNecessary(NSString *firstRunUserDefaultsKey); extern BOOL NSWillLaunchItemAtURLOnLogin(NSURL *itemURL, BOOL *hidden); extern void NSLaunchItemAtURLOnLogin(NSURL *itemURL, BOOL enabled, BOOL hidden); // Adds Modern Objective-C Booleans to OS X 10.7. #if __has_feature(objc_bool) && (!defined(__MAC_10_8) || __MAC_OS_X_VERSION_MIN_REQUIRED < __MAC_10_8) #undef YES #define YES __objc_yes #undef NO #define NO __objc_no #endif // Adds Modern Objective-C Subscripting to OS X 10.7. // The actual implementation of these methods is handled by the // libarclite framework, and so they do not need to be implemented. #if (!defined(__MAC_10_8) || __MAC_OS_X_VERSION_MIN_REQUIRED < __MAC_10_8) @interface NSArray (BINIndexing) - (id)objectAtIndexedSubscript:(NSUInteger)idx; @end @interface NSMutableArray (BINIndexing) - (void)setObject:(id)obj atIndexedSubscript:(NSUInteger)idx; @end @interface NSDictionary (BINIndexing) - (id)objectForKeyedSubscript:(id)key; @end @interface NSMutableDictionary (BINIndexing) - (void)setObject:(id)obj forKeyedSubscript:(id)key; @end #endif // Adds an interface for the firstObject method, existing since 10.7. @interface NSArray (BINAdditions) - (id)firstObject; @end // These methods existed in AppKit since 10.7, but were made public // and subsequently deprecated in 10.9. They are AppStore compatible. @interface NSData (Base64) - (id)initWithBase64Encoding:(NSString *)base64String; - (NSString *)base64Encoding; @end
29.229358
102
0.784055
6ee59845ca8e0d696baa80d6c0c16459b9983897
595
html
HTML
public/views/dashboard/exposure.html
arjun-k-r/shocktrade.js
84fca5ea28839cc5ebdd2b122c930d2aa49da581
[ "Apache-2.0" ]
null
null
null
public/views/dashboard/exposure.html
arjun-k-r/shocktrade.js
84fca5ea28839cc5ebdd2b122c930d2aa49da581
[ "Apache-2.0" ]
null
null
null
public/views/dashboard/exposure.html
arjun-k-r/shocktrade.js
84fca5ea28839cc5ebdd2b122c930d2aa49da581
[ "Apache-2.0" ]
null
null
null
<div class="row" ng-controller="ExposureController" ng-init="exposureChart(getContestID(), getUserID(), selectedExposure)"> <div class="col-md-12" style="padding-bottom: 4px"> <select class="form-control symbol_input_text_field" ng-model="selectedExposure" ng-options="e.label for e in exposures" ng-change="exposureChart(getContestID(), getUserID(), selectedExposure)"> <option value="">-- Select an Exposure --</option> </select> </div> <nvd3 ng-if="data" options="options" data="data"></nvd3> </div>
45.769231
110
0.62521
f596decb0216a0efba7c1be2716986c462ac5260
6,647
rs
Rust
src/gpio_sd.rs
ForsakenHarmony/esp32c3-pac
7d9eb9a5b5a51077d1d1eb6c6efd186064b7149b
[ "Apache-2.0", "MIT" ]
null
null
null
src/gpio_sd.rs
ForsakenHarmony/esp32c3-pac
7d9eb9a5b5a51077d1d1eb6c6efd186064b7149b
[ "Apache-2.0", "MIT" ]
null
null
null
src/gpio_sd.rs
ForsakenHarmony/esp32c3-pac
7d9eb9a5b5a51077d1d1eb6c6efd186064b7149b
[ "Apache-2.0", "MIT" ]
null
null
null
#[doc = r"Register block"] #[repr(C)] pub struct RegisterBlock { #[doc = "0x00 - GPIO_SIGMADELTA0"] pub sigmadelta0: SIGMADELTA0, #[doc = "0x04 - GPIO_SIGMADELTA1"] pub sigmadelta1: SIGMADELTA1, #[doc = "0x08 - GPIO_SIGMADELTA2"] pub sigmadelta2: SIGMADELTA2, #[doc = "0x0c - GPIO_SIGMADELTA3"] pub sigmadelta3: SIGMADELTA3, _reserved4: [u8; 16usize], #[doc = "0x20 - GPIO_SIGMADELTA_CG"] pub sigmadelta_cg: SIGMADELTA_CG, #[doc = "0x24 - GPIO_SIGMADELTA_MISC"] pub sigmadelta_misc: SIGMADELTA_MISC, #[doc = "0x28 - GPIO_SIGMADELTA_VERSION"] pub sigmadelta_version: SIGMADELTA_VERSION, } #[doc = "GPIO_SIGMADELTA0\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [sigmadelta0](sigmadelta0) module"] pub type SIGMADELTA0 = crate::Reg<u32, _SIGMADELTA0>; #[allow(missing_docs)] #[doc(hidden)] pub struct _SIGMADELTA0; #[doc = "`read()` method returns [sigmadelta0::R](sigmadelta0::R) reader structure"] impl crate::Readable for SIGMADELTA0 {} #[doc = "`write(|w| ..)` method takes [sigmadelta0::W](sigmadelta0::W) writer structure"] impl crate::Writable for SIGMADELTA0 {} #[doc = "GPIO_SIGMADELTA0"] pub mod sigmadelta0; #[doc = "GPIO_SIGMADELTA1\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [sigmadelta1](sigmadelta1) module"] pub type SIGMADELTA1 = crate::Reg<u32, _SIGMADELTA1>; #[allow(missing_docs)] #[doc(hidden)] pub struct _SIGMADELTA1; #[doc = "`read()` method returns [sigmadelta1::R](sigmadelta1::R) reader structure"] impl crate::Readable for SIGMADELTA1 {} #[doc = "`write(|w| ..)` method takes [sigmadelta1::W](sigmadelta1::W) writer structure"] impl crate::Writable for SIGMADELTA1 {} #[doc = "GPIO_SIGMADELTA1"] pub mod sigmadelta1; #[doc = "GPIO_SIGMADELTA2\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [sigmadelta2](sigmadelta2) module"] pub type SIGMADELTA2 = crate::Reg<u32, _SIGMADELTA2>; #[allow(missing_docs)] #[doc(hidden)] pub struct _SIGMADELTA2; #[doc = "`read()` method returns [sigmadelta2::R](sigmadelta2::R) reader structure"] impl crate::Readable for SIGMADELTA2 {} #[doc = "`write(|w| ..)` method takes [sigmadelta2::W](sigmadelta2::W) writer structure"] impl crate::Writable for SIGMADELTA2 {} #[doc = "GPIO_SIGMADELTA2"] pub mod sigmadelta2; #[doc = "GPIO_SIGMADELTA3\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [sigmadelta3](sigmadelta3) module"] pub type SIGMADELTA3 = crate::Reg<u32, _SIGMADELTA3>; #[allow(missing_docs)] #[doc(hidden)] pub struct _SIGMADELTA3; #[doc = "`read()` method returns [sigmadelta3::R](sigmadelta3::R) reader structure"] impl crate::Readable for SIGMADELTA3 {} #[doc = "`write(|w| ..)` method takes [sigmadelta3::W](sigmadelta3::W) writer structure"] impl crate::Writable for SIGMADELTA3 {} #[doc = "GPIO_SIGMADELTA3"] pub mod sigmadelta3; #[doc = "GPIO_SIGMADELTA_CG\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [sigmadelta_cg](sigmadelta_cg) module"] pub type SIGMADELTA_CG = crate::Reg<u32, _SIGMADELTA_CG>; #[allow(missing_docs)] #[doc(hidden)] pub struct _SIGMADELTA_CG; #[doc = "`read()` method returns [sigmadelta_cg::R](sigmadelta_cg::R) reader structure"] impl crate::Readable for SIGMADELTA_CG {} #[doc = "`write(|w| ..)` method takes [sigmadelta_cg::W](sigmadelta_cg::W) writer structure"] impl crate::Writable for SIGMADELTA_CG {} #[doc = "GPIO_SIGMADELTA_CG"] pub mod sigmadelta_cg; #[doc = "GPIO_SIGMADELTA_MISC\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [sigmadelta_misc](sigmadelta_misc) module"] pub type SIGMADELTA_MISC = crate::Reg<u32, _SIGMADELTA_MISC>; #[allow(missing_docs)] #[doc(hidden)] pub struct _SIGMADELTA_MISC; #[doc = "`read()` method returns [sigmadelta_misc::R](sigmadelta_misc::R) reader structure"] impl crate::Readable for SIGMADELTA_MISC {} #[doc = "`write(|w| ..)` method takes [sigmadelta_misc::W](sigmadelta_misc::W) writer structure"] impl crate::Writable for SIGMADELTA_MISC {} #[doc = "GPIO_SIGMADELTA_MISC"] pub mod sigmadelta_misc; #[doc = "GPIO_SIGMADELTA_VERSION\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [sigmadelta_version](sigmadelta_version) module"] pub type SIGMADELTA_VERSION = crate::Reg<u32, _SIGMADELTA_VERSION>; #[allow(missing_docs)] #[doc(hidden)] pub struct _SIGMADELTA_VERSION; #[doc = "`read()` method returns [sigmadelta_version::R](sigmadelta_version::R) reader structure"] impl crate::Readable for SIGMADELTA_VERSION {} #[doc = "`write(|w| ..)` method takes [sigmadelta_version::W](sigmadelta_version::W) writer structure"] impl crate::Writable for SIGMADELTA_VERSION {} #[doc = "GPIO_SIGMADELTA_VERSION"] pub mod sigmadelta_version;
68.525773
430
0.723033
98d9e36d5ca4af3759a18fea125da476d3e20b1a
4,311
html
HTML
_includes/nav.html
clarkio/clarkio.github.io
3613a810609da7d903fc6c95768c048b6b9c14cf
[ "Apache-2.0" ]
2
2018-01-18T05:30:28.000Z
2022-02-01T01:04:01.000Z
_includes/nav.html
clarkio/clarkio.github.io
3613a810609da7d903fc6c95768c048b6b9c14cf
[ "Apache-2.0" ]
5
2016-11-03T04:18:11.000Z
2021-11-20T23:37:25.000Z
_includes/nav.html
clarkio/clarkio.github.io
3613a810609da7d903fc6c95768c048b6b9c14cf
[ "Apache-2.0" ]
2
2016-11-03T04:06:27.000Z
2018-05-21T17:10:22.000Z
<!-- Navigation --> <nav class="navbar navbar-default navbar-custom navbar-fixed-top"> <div class="container-fluid"> <!-- Brand and toggle get grouped for better mobile display --> <div class="navbar-header page-scroll"> <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <ul class="list-inline text-center"> {% if site.twitter_username %} <li> <a href="https://twitter.com/{{ site.twitter_username }}"> <span class="fa-stack fa-lg"> <i class="fa fa-circle fa-stack-2x fa-inverse"></i> <i class="fa fa-twitter fa-stack-1x"></i> </span> </a> </li> {% endif %} {% if site.facebook_username %} <li> <a href="https://www.facebook.com/{{ site.facebook_username }}"> <span class="fa-stack fa-lg"> <i class="fa fa-circle fa-stack-2x fa-inverse"></i> <i class="fa fa-facebook fa-stack-1x"></i> </span> </a> </li> {% endif %} {% if site.github_username %} <li> <a href="https://github.com/{{ site.github_username }}"> <span class="fa-stack fa-lg"> <i class="fa fa-circle fa-stack-2x fa-inverse"></i> <i class="fa fa-github fa-stack-1x"></i> </span> </a> </li> {% endif %} <li> <a href="https://www.youtube.com/c/clarkio"> <span class="fa-stack fa-lg"> <i class="fa fa-circle fa-stack-2x fa-inverse"></i> <i class="fa fa-youtube fa-stack-1x"></i> </span> </a> </li> <li> <a href="https://www.instagram.com/_clarkio/"> <span class="fa-stack fa-lg"> <i class="fa fa-circle fa-stack-2x fa-inverse"></i> <i class="fa fa-instagram fa-stack-1x"></i> </span> </a> </li> <li> <a href="https://www.twitch.tv/clarkio/"> <span class="fa-stack fa-lg"> <i class="fa fa-circle fa-stack-2x fa-inverse"></i> <i class="fa fa-twitch fa-stack-1x"></i> </span> </a> </li> <li> <a href="{{ " /feed.xml " | prepend: site.baseurl }}"> <span class="fa-stack fa-lg"> <i class="fa fa-circle fa-stack-2x fa-inverse"></i> <i class="fa fa-rss fa-stack-1x"></i> </span> </a> </li> </ul> <!--<a class="navbar-brand" href="{{ site.baseurl }}/">{{ site.title }}</a>--> </div> <!-- Collect the nav links, forms, and other content for toggling --> <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1"> <ul class="nav navbar-nav navbar-right"> <li> <a href="{{ site.baseurl }}/">Home</a> </li> {% assign sorted_pages = site.pages | sort:"order" %} {% for page in sorted_pages %}{% if page.title %} <li> <a href="{{ page.url | prepend: site.baseurl }}">{{ page.title }}</a> </li> {% endif %}{% endfor %} </ul> </div> <!-- /.navbar-collapse --> </div> <!-- /.container --> </nav>
45.861702
123
0.393876
4fe93edd6b3aa62d66ef5e39c77b071e51029b9e
3,489
swift
Swift
trifle/trifle/Classes/Home/View/PictrueCollectionView.swift
DD2641817107/trifle
4dec3c8a3c05c7a67d73fbbc0f9355151d227fbe
[ "Apache-2.0" ]
1
2019-10-26T18:46:06.000Z
2019-10-26T18:46:06.000Z
trifle/trifle/Classes/Home/View/PictrueCollectionView.swift
DD2641817107/trifle
4dec3c8a3c05c7a67d73fbbc0f9355151d227fbe
[ "Apache-2.0" ]
null
null
null
trifle/trifle/Classes/Home/View/PictrueCollectionView.swift
DD2641817107/trifle
4dec3c8a3c05c7a67d73fbbc0f9355151d227fbe
[ "Apache-2.0" ]
null
null
null
// // PictrueCollectionView.swift // trifle // // Created by TOMY on 2019/4/2. // Copyright © 2019年 tone. All rights reserved. // import UIKit import SDWebImage import FLAnimatedImage class PictrueCollectionView: UICollectionView { //定义模型数组 var picURLs : [URL] = [URL](){ didSet{ self.reloadData() } } override func awakeFromNib() { super.awakeFromNib() dataSource = self delegate = self } } extension PictrueCollectionView : UICollectionViewDataSource,UICollectionViewDelegate { func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return picURLs.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "PicCell", for: indexPath) as! PictrueViewCell cell.picURL = picURLs[indexPath.item] return cell } func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { let userInfo = ["indexPath" : indexPath,"picURLs" : picURLs] as [String : Any] NotificationCenter.default.post(name: NSNotification.Name(showPhotoBrowserNote), object: self, userInfo: userInfo) } } class PictrueViewCell: UICollectionViewCell { @IBOutlet weak var imageView: UIImageView! @IBOutlet weak var labelView: UILabel! var picURL : URL? { didSet{ guard let picURL = picURL else { return } imageView.contentMode = .scaleAspectFill labelView.isHidden = true labelView.text = nil let URLString = picURL.absoluteString if (URLString as NSString).lowercased.hasSuffix("gif"){ labelView.text = "动图" labelView.isHidden = false } let image = SDWebImageManager.shared().imageCache?.imageFromDiskCache(forKey: URLString) imageView.image = image } } } extension PictrueCollectionView : AnimatorPhotoBrowserPresentedDelegate { func startRect(indexPath: IndexPath) -> CGRect { let cell = self.cellForItem(at: indexPath)! let startFrame = self.convert(cell.frame, to: UIApplication.shared.keyWindow!) return startFrame } func endRect(indexPath: IndexPath) -> CGRect { let picURl = picURLs[indexPath.item] let image = SDWebImageManager.shared().imageCache?.imageFromDiskCache(forKey: picURl.absoluteString) let width : CGFloat = UIScreen.main.bounds.width let height : CGFloat = (width * image!.size.height) / image!.size.width var y : CGFloat = 0 if height > UIScreen.main.bounds.height{ y = 20 }else{ y = (UIScreen.main.bounds.height - height) * 0.5 } return CGRect(x: 0, y: y, width: width, height: height) } func imageView(indexPath: IndexPath) -> UIImageView { let picURl = picURLs[indexPath.item] let image = SDWebImageManager.shared().imageCache?.imageFromDiskCache(forKey: picURl.absoluteString) let imageView : UIImageView = UIImageView() imageView.image = image! imageView.contentMode = .scaleAspectFill imageView.clipsToBounds = true return imageView } }
31.432432
122
0.638578
39d6f382c8c3e32f1eeeadaaedd8a0c999759f72
4,875
js
JavaScript
services/api/lib/user.js
developmentseed/pearl-backend
38b7c9197855c135e522bf8b5a315a10006ef510
[ "MIT" ]
28
2022-03-28T18:32:47.000Z
2022-03-31T15:00:29.000Z
services/api/lib/user.js
developmentseed/pearl-backend
38b7c9197855c135e522bf8b5a315a10006ef510
[ "MIT" ]
1
2022-03-17T08:38:01.000Z
2022-03-17T08:38:01.000Z
services/api/lib/user.js
developmentseed/pearl-backend
38b7c9197855c135e522bf8b5a315a10006ef510
[ "MIT" ]
null
null
null
'use strict'; const { Err } = require('@openaddresses/batch-schema'); const Generic = require('@openaddresses/batch-generic'); const { sql } = require('slonik'); /** * @class */ class User extends Generic { static _table = 'users'; static _patch = require('../schema/req.body.PatchUser.json'); static _res = require('../schema/res.User.json'); static async is_admin(req) { if (!req.auth || !req.auth.access || req.auth.access !== 'admin') { throw new Err(403, null, 'Admin token required'); } return true; } /** * Return a list of users * * @param {Pool} pool - Instantiated Postgres Pool * @param {Object} query - Query Object * @param {Number} [query.limit=100] - Max number of results to return * @param {Number} [query.page=0] - Page of users to return * @param {String} [query.filter=] - Username or Email fragment to filter by * @param {String} [query.sort=created] Field to sort by * @param {String} [query.order=asc] Sort Order (asc/desc) */ static async list(pool, query = {}) { if (!query.limit) query.limit = 100; if (!query.page) query.page = 0; if (!query.filter) query.filter = ''; if (!query.sort) query.sort = 'created'; if (!query.order || query.order === 'asc') { query.order = sql`asc`; } else { query.order = sql`desc`; } try { const pgres = await pool.query(sql` SELECT count(*) OVER() AS count, id, created, updated, username, access, email, flags FROM users WHERE username iLIKE '%'||${query.filter}||'%' OR email iLIKE '%'||${query.filter}||'%' ORDER BY ${sql.identifier(['users', query.sort])} ${query.order} LIMIT ${query.limit} OFFSET ${query.page * query.limit} `); return this.deserialize(pgres.rows); } catch (err) { throw new Err(500, err, 'Internal error'); } } async commit(pool) { try { await pool.query(sql` UPDATE users SET access = ${this.access}, flags = ${JSON.stringify(this.flags)}, updated = NOW() WHERE id = ${this.id} `); return this; } catch (err) { throw new Err(500, err, 'Failed to update user'); } } static async from(pool, uid, idField = 'id') { try { const pgres = await pool.query(sql` SELECT id, created, updated, username, access, email, flags FROM users WHERE ${sql.identifier(['users', idField])} = ${uid} `); if (!pgres.rows.length) { throw new Err(404, null, 'User not found'); } return this.deserialize(pgres.rows[0]); } catch (err) { throw new Err(500, err, 'Internal Error'); } } static async generate(pool, user) { if (!user.username) throw new Err(400, null, 'username required'); if (!user.email) throw new Err(400, null, 'email required'); if (!user.access) user.access = 'user'; if (!user.flags) user.flags = {}; if (user.username === 'internal') throw new Err(400, null, '"internal" is not a valid username'); try { const pgres = await pool.query(sql` INSERT INTO users ( username, email, auth0_id, access, flags ) VALUES ( ${user.username}, ${user.email}, ${user.auth0Id}, ${user.access}, ${JSON.stringify(user.flags)} ) RETURNING * `); return this.deserialize(pgres.rows[0]); } catch (err) { if (err.originalError && err.originalError.code && err.originalError.code === '23505') { throw new Err(400, err, 'Cannot create duplicate user'); } else if (err) { throw new Err(500, err, 'Failed to create user'); } } } } module.exports = User;
31.050955
105
0.443897
2d863959aa737472bd50c3fab86f5ad152ae3bee
1,238
asm
Assembly
programs/oeis/198/A198694.asm
neoneye/loda
afe9559fb53ee12e3040da54bd6aa47283e0d9ec
[ "Apache-2.0" ]
22
2018-02-06T19:19:31.000Z
2022-01-17T21:53:31.000Z
programs/oeis/198/A198694.asm
neoneye/loda
afe9559fb53ee12e3040da54bd6aa47283e0d9ec
[ "Apache-2.0" ]
41
2021-02-22T19:00:34.000Z
2021-08-28T10:47:47.000Z
programs/oeis/198/A198694.asm
neoneye/loda
afe9559fb53ee12e3040da54bd6aa47283e0d9ec
[ "Apache-2.0" ]
5
2021-02-24T21:14:16.000Z
2021-08-09T19:48:05.000Z
; A198694: 7*4^n-1. ; 6,27,111,447,1791,7167,28671,114687,458751,1835007,7340031,29360127,117440511,469762047,1879048191,7516192767,30064771071,120259084287,481036337151,1924145348607,7696581394431,30786325577727,123145302310911,492581209243647,1970324836974591,7881299347898367,31525197391593471,126100789566373887,504403158265495551,2017612633061982207,8070450532247928831,32281802128991715327,129127208515966861311,516508834063867445247,2066035336255469780991,8264141345021879123967,33056565380087516495871,132226261520350065983487,528905046081400263933951,2115620184325601055735807,8462480737302404222943231,33849922949209616891772927,135399691796838467567091711,541598767187353870268366847,2166395068749415481073467391,8665580274997661924293869567,34662321099990647697175478271,138649284399962590788701913087,554597137599850363154807652351,2218388550399401452619230609407,8873554201597605810476922437631,35494216806390423241907689750527,141976867225561692967630759002111,567907468902246771870523036008447,2271629875608987087482092144033791,9086519502435948349928368576135167,36346078009743793399713474304540671,145384312038975173598853897218162687,581537248155900694395415588872650751 mov $1,4 pow $1,$0 mul $1,7 sub $1,1 mov $0,$1
137.555556
1,169
0.924879
bccb76303d2023c026e93ceeb95f23785917d1fb
410
js
JavaScript
lib/6to5/transformation/transformers/es6/unicode-regex.js
luca-barbieri/5to6
5c97c3c342380363378b6241491ea852f9a6087a
[ "MIT" ]
4
2015-04-05T22:38:45.000Z
2018-06-20T03:36:56.000Z
lib/6to5/transformation/transformers/es6/unicode-regex.js
luca-barbieri/5to6
5c97c3c342380363378b6241491ea852f9a6087a
[ "MIT" ]
null
null
null
lib/6to5/transformation/transformers/es6/unicode-regex.js
luca-barbieri/5to6
5c97c3c342380363378b6241491ea852f9a6087a
[ "MIT" ]
null
null
null
"use strict"; var rewritePattern = require("regexpu/rewrite-pattern"); var pull = require("lodash/array/pull"); exports.Literal = function (node) { var regex = node.regex; if (!regex) return; var flags = regex.flags.split(""); if (regex.flags.indexOf("u") < 0) return; pull(flags, "u"); regex.pattern = rewritePattern(regex.pattern, regex.flags); regex.flags = flags.join(""); };
24.117647
61
0.64878
de68361f4cfd66c87d549ff8552b4a3618c8ebd5
43,503
rs
Rust
sdk/worklink/src/error_meta.rs
DreamStageLive/aws-sdk-rust
112463db6195c0b8c052495a1794e07bf0e2f274
[ "Apache-2.0" ]
null
null
null
sdk/worklink/src/error_meta.rs
DreamStageLive/aws-sdk-rust
112463db6195c0b8c052495a1794e07bf0e2f274
[ "Apache-2.0" ]
null
null
null
sdk/worklink/src/error_meta.rs
DreamStageLive/aws-sdk-rust
112463db6195c0b8c052495a1794e07bf0e2f274
[ "Apache-2.0" ]
null
null
null
// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. #[non_exhaustive] #[derive(std::fmt::Debug)] pub enum Error { InternalServerErrorException(crate::error::InternalServerErrorException), InvalidRequestException(crate::error::InvalidRequestException), ResourceAlreadyExistsException(crate::error::ResourceAlreadyExistsException), ResourceNotFoundException(crate::error::ResourceNotFoundException), TooManyRequestsException(crate::error::TooManyRequestsException), UnauthorizedException(crate::error::UnauthorizedException), Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>), } impl std::fmt::Display for Error { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { Error::InternalServerErrorException(inner) => inner.fmt(f), Error::InvalidRequestException(inner) => inner.fmt(f), Error::ResourceAlreadyExistsException(inner) => inner.fmt(f), Error::ResourceNotFoundException(inner) => inner.fmt(f), Error::TooManyRequestsException(inner) => inner.fmt(f), Error::UnauthorizedException(inner) => inner.fmt(f), Error::Unhandled(inner) => inner.fmt(f), } } } impl From<smithy_http::result::SdkError<crate::error::AssociateDomainError>> for Error { fn from(err: smithy_http::result::SdkError<crate::error::AssociateDomainError>) -> Self { match err { smithy_http::result::SdkError::ServiceError { err, .. } => match err.kind { crate::error::AssociateDomainErrorKind::InternalServerErrorException(inner) => { Error::InternalServerErrorException(inner) } crate::error::AssociateDomainErrorKind::InvalidRequestException(inner) => { Error::InvalidRequestException(inner) } crate::error::AssociateDomainErrorKind::ResourceAlreadyExistsException(inner) => { Error::ResourceAlreadyExistsException(inner) } crate::error::AssociateDomainErrorKind::ResourceNotFoundException(inner) => { Error::ResourceNotFoundException(inner) } crate::error::AssociateDomainErrorKind::TooManyRequestsException(inner) => { Error::TooManyRequestsException(inner) } crate::error::AssociateDomainErrorKind::UnauthorizedException(inner) => { Error::UnauthorizedException(inner) } crate::error::AssociateDomainErrorKind::Unhandled(inner) => Error::Unhandled(inner), }, _ => Error::Unhandled(err.into()), } } } impl From<smithy_http::result::SdkError<crate::error::AssociateWebsiteAuthorizationProviderError>> for Error { fn from( err: smithy_http::result::SdkError< crate::error::AssociateWebsiteAuthorizationProviderError, >, ) -> Self { match err { smithy_http::result::SdkError::ServiceError { err, ..} => match err.kind { crate::error::AssociateWebsiteAuthorizationProviderErrorKind::InternalServerErrorException(inner) => Error::InternalServerErrorException(inner), crate::error::AssociateWebsiteAuthorizationProviderErrorKind::InvalidRequestException(inner) => Error::InvalidRequestException(inner), crate::error::AssociateWebsiteAuthorizationProviderErrorKind::ResourceAlreadyExistsException(inner) => Error::ResourceAlreadyExistsException(inner), crate::error::AssociateWebsiteAuthorizationProviderErrorKind::ResourceNotFoundException(inner) => Error::ResourceNotFoundException(inner), crate::error::AssociateWebsiteAuthorizationProviderErrorKind::TooManyRequestsException(inner) => Error::TooManyRequestsException(inner), crate::error::AssociateWebsiteAuthorizationProviderErrorKind::UnauthorizedException(inner) => Error::UnauthorizedException(inner), crate::error::AssociateWebsiteAuthorizationProviderErrorKind::Unhandled(inner) => Error::Unhandled(inner), } _ => Error::Unhandled(err.into()), } } } impl From<smithy_http::result::SdkError<crate::error::AssociateWebsiteCertificateAuthorityError>> for Error { fn from( err: smithy_http::result::SdkError<crate::error::AssociateWebsiteCertificateAuthorityError>, ) -> Self { match err { smithy_http::result::SdkError::ServiceError { err, ..} => match err.kind { crate::error::AssociateWebsiteCertificateAuthorityErrorKind::InternalServerErrorException(inner) => Error::InternalServerErrorException(inner), crate::error::AssociateWebsiteCertificateAuthorityErrorKind::InvalidRequestException(inner) => Error::InvalidRequestException(inner), crate::error::AssociateWebsiteCertificateAuthorityErrorKind::ResourceAlreadyExistsException(inner) => Error::ResourceAlreadyExistsException(inner), crate::error::AssociateWebsiteCertificateAuthorityErrorKind::ResourceNotFoundException(inner) => Error::ResourceNotFoundException(inner), crate::error::AssociateWebsiteCertificateAuthorityErrorKind::TooManyRequestsException(inner) => Error::TooManyRequestsException(inner), crate::error::AssociateWebsiteCertificateAuthorityErrorKind::UnauthorizedException(inner) => Error::UnauthorizedException(inner), crate::error::AssociateWebsiteCertificateAuthorityErrorKind::Unhandled(inner) => Error::Unhandled(inner), } _ => Error::Unhandled(err.into()), } } } impl From<smithy_http::result::SdkError<crate::error::CreateFleetError>> for Error { fn from(err: smithy_http::result::SdkError<crate::error::CreateFleetError>) -> Self { match err { smithy_http::result::SdkError::ServiceError { err, .. } => match err.kind { crate::error::CreateFleetErrorKind::InternalServerErrorException(inner) => { Error::InternalServerErrorException(inner) } crate::error::CreateFleetErrorKind::InvalidRequestException(inner) => { Error::InvalidRequestException(inner) } crate::error::CreateFleetErrorKind::ResourceAlreadyExistsException(inner) => { Error::ResourceAlreadyExistsException(inner) } crate::error::CreateFleetErrorKind::ResourceNotFoundException(inner) => { Error::ResourceNotFoundException(inner) } crate::error::CreateFleetErrorKind::TooManyRequestsException(inner) => { Error::TooManyRequestsException(inner) } crate::error::CreateFleetErrorKind::UnauthorizedException(inner) => { Error::UnauthorizedException(inner) } crate::error::CreateFleetErrorKind::Unhandled(inner) => Error::Unhandled(inner), }, _ => Error::Unhandled(err.into()), } } } impl From<smithy_http::result::SdkError<crate::error::DeleteFleetError>> for Error { fn from(err: smithy_http::result::SdkError<crate::error::DeleteFleetError>) -> Self { match err { smithy_http::result::SdkError::ServiceError { err, .. } => match err.kind { crate::error::DeleteFleetErrorKind::InternalServerErrorException(inner) => { Error::InternalServerErrorException(inner) } crate::error::DeleteFleetErrorKind::InvalidRequestException(inner) => { Error::InvalidRequestException(inner) } crate::error::DeleteFleetErrorKind::ResourceNotFoundException(inner) => { Error::ResourceNotFoundException(inner) } crate::error::DeleteFleetErrorKind::TooManyRequestsException(inner) => { Error::TooManyRequestsException(inner) } crate::error::DeleteFleetErrorKind::UnauthorizedException(inner) => { Error::UnauthorizedException(inner) } crate::error::DeleteFleetErrorKind::Unhandled(inner) => Error::Unhandled(inner), }, _ => Error::Unhandled(err.into()), } } } impl From<smithy_http::result::SdkError<crate::error::DescribeAuditStreamConfigurationError>> for Error { fn from( err: smithy_http::result::SdkError<crate::error::DescribeAuditStreamConfigurationError>, ) -> Self { match err { smithy_http::result::SdkError::ServiceError { err, ..} => match err.kind { crate::error::DescribeAuditStreamConfigurationErrorKind::InternalServerErrorException(inner) => Error::InternalServerErrorException(inner), crate::error::DescribeAuditStreamConfigurationErrorKind::InvalidRequestException(inner) => Error::InvalidRequestException(inner), crate::error::DescribeAuditStreamConfigurationErrorKind::ResourceNotFoundException(inner) => Error::ResourceNotFoundException(inner), crate::error::DescribeAuditStreamConfigurationErrorKind::TooManyRequestsException(inner) => Error::TooManyRequestsException(inner), crate::error::DescribeAuditStreamConfigurationErrorKind::UnauthorizedException(inner) => Error::UnauthorizedException(inner), crate::error::DescribeAuditStreamConfigurationErrorKind::Unhandled(inner) => Error::Unhandled(inner), } _ => Error::Unhandled(err.into()), } } } impl From<smithy_http::result::SdkError<crate::error::DescribeCompanyNetworkConfigurationError>> for Error { fn from( err: smithy_http::result::SdkError<crate::error::DescribeCompanyNetworkConfigurationError>, ) -> Self { match err { smithy_http::result::SdkError::ServiceError { err, ..} => match err.kind { crate::error::DescribeCompanyNetworkConfigurationErrorKind::InternalServerErrorException(inner) => Error::InternalServerErrorException(inner), crate::error::DescribeCompanyNetworkConfigurationErrorKind::InvalidRequestException(inner) => Error::InvalidRequestException(inner), crate::error::DescribeCompanyNetworkConfigurationErrorKind::ResourceNotFoundException(inner) => Error::ResourceNotFoundException(inner), crate::error::DescribeCompanyNetworkConfigurationErrorKind::TooManyRequestsException(inner) => Error::TooManyRequestsException(inner), crate::error::DescribeCompanyNetworkConfigurationErrorKind::UnauthorizedException(inner) => Error::UnauthorizedException(inner), crate::error::DescribeCompanyNetworkConfigurationErrorKind::Unhandled(inner) => Error::Unhandled(inner), } _ => Error::Unhandled(err.into()), } } } impl From<smithy_http::result::SdkError<crate::error::DescribeDeviceError>> for Error { fn from(err: smithy_http::result::SdkError<crate::error::DescribeDeviceError>) -> Self { match err { smithy_http::result::SdkError::ServiceError { err, .. } => match err.kind { crate::error::DescribeDeviceErrorKind::InternalServerErrorException(inner) => { Error::InternalServerErrorException(inner) } crate::error::DescribeDeviceErrorKind::InvalidRequestException(inner) => { Error::InvalidRequestException(inner) } crate::error::DescribeDeviceErrorKind::ResourceNotFoundException(inner) => { Error::ResourceNotFoundException(inner) } crate::error::DescribeDeviceErrorKind::TooManyRequestsException(inner) => { Error::TooManyRequestsException(inner) } crate::error::DescribeDeviceErrorKind::UnauthorizedException(inner) => { Error::UnauthorizedException(inner) } crate::error::DescribeDeviceErrorKind::Unhandled(inner) => Error::Unhandled(inner), }, _ => Error::Unhandled(err.into()), } } } impl From<smithy_http::result::SdkError<crate::error::DescribeDevicePolicyConfigurationError>> for Error { fn from( err: smithy_http::result::SdkError<crate::error::DescribeDevicePolicyConfigurationError>, ) -> Self { match err { smithy_http::result::SdkError::ServiceError { err, ..} => match err.kind { crate::error::DescribeDevicePolicyConfigurationErrorKind::InternalServerErrorException(inner) => Error::InternalServerErrorException(inner), crate::error::DescribeDevicePolicyConfigurationErrorKind::InvalidRequestException(inner) => Error::InvalidRequestException(inner), crate::error::DescribeDevicePolicyConfigurationErrorKind::ResourceNotFoundException(inner) => Error::ResourceNotFoundException(inner), crate::error::DescribeDevicePolicyConfigurationErrorKind::TooManyRequestsException(inner) => Error::TooManyRequestsException(inner), crate::error::DescribeDevicePolicyConfigurationErrorKind::UnauthorizedException(inner) => Error::UnauthorizedException(inner), crate::error::DescribeDevicePolicyConfigurationErrorKind::Unhandled(inner) => Error::Unhandled(inner), } _ => Error::Unhandled(err.into()), } } } impl From<smithy_http::result::SdkError<crate::error::DescribeDomainError>> for Error { fn from(err: smithy_http::result::SdkError<crate::error::DescribeDomainError>) -> Self { match err { smithy_http::result::SdkError::ServiceError { err, .. } => match err.kind { crate::error::DescribeDomainErrorKind::InternalServerErrorException(inner) => { Error::InternalServerErrorException(inner) } crate::error::DescribeDomainErrorKind::InvalidRequestException(inner) => { Error::InvalidRequestException(inner) } crate::error::DescribeDomainErrorKind::ResourceNotFoundException(inner) => { Error::ResourceNotFoundException(inner) } crate::error::DescribeDomainErrorKind::TooManyRequestsException(inner) => { Error::TooManyRequestsException(inner) } crate::error::DescribeDomainErrorKind::UnauthorizedException(inner) => { Error::UnauthorizedException(inner) } crate::error::DescribeDomainErrorKind::Unhandled(inner) => Error::Unhandled(inner), }, _ => Error::Unhandled(err.into()), } } } impl From<smithy_http::result::SdkError<crate::error::DescribeFleetMetadataError>> for Error { fn from(err: smithy_http::result::SdkError<crate::error::DescribeFleetMetadataError>) -> Self { match err { smithy_http::result::SdkError::ServiceError { err, .. } => match err.kind { crate::error::DescribeFleetMetadataErrorKind::InternalServerErrorException( inner, ) => Error::InternalServerErrorException(inner), crate::error::DescribeFleetMetadataErrorKind::InvalidRequestException(inner) => { Error::InvalidRequestException(inner) } crate::error::DescribeFleetMetadataErrorKind::ResourceNotFoundException(inner) => { Error::ResourceNotFoundException(inner) } crate::error::DescribeFleetMetadataErrorKind::TooManyRequestsException(inner) => { Error::TooManyRequestsException(inner) } crate::error::DescribeFleetMetadataErrorKind::UnauthorizedException(inner) => { Error::UnauthorizedException(inner) } crate::error::DescribeFleetMetadataErrorKind::Unhandled(inner) => { Error::Unhandled(inner) } }, _ => Error::Unhandled(err.into()), } } } impl From<smithy_http::result::SdkError<crate::error::DescribeIdentityProviderConfigurationError>> for Error { fn from( err: smithy_http::result::SdkError< crate::error::DescribeIdentityProviderConfigurationError, >, ) -> Self { match err { smithy_http::result::SdkError::ServiceError { err, ..} => match err.kind { crate::error::DescribeIdentityProviderConfigurationErrorKind::InternalServerErrorException(inner) => Error::InternalServerErrorException(inner), crate::error::DescribeIdentityProviderConfigurationErrorKind::InvalidRequestException(inner) => Error::InvalidRequestException(inner), crate::error::DescribeIdentityProviderConfigurationErrorKind::ResourceNotFoundException(inner) => Error::ResourceNotFoundException(inner), crate::error::DescribeIdentityProviderConfigurationErrorKind::TooManyRequestsException(inner) => Error::TooManyRequestsException(inner), crate::error::DescribeIdentityProviderConfigurationErrorKind::UnauthorizedException(inner) => Error::UnauthorizedException(inner), crate::error::DescribeIdentityProviderConfigurationErrorKind::Unhandled(inner) => Error::Unhandled(inner), } _ => Error::Unhandled(err.into()), } } } impl From<smithy_http::result::SdkError<crate::error::DescribeWebsiteCertificateAuthorityError>> for Error { fn from( err: smithy_http::result::SdkError<crate::error::DescribeWebsiteCertificateAuthorityError>, ) -> Self { match err { smithy_http::result::SdkError::ServiceError { err, ..} => match err.kind { crate::error::DescribeWebsiteCertificateAuthorityErrorKind::InternalServerErrorException(inner) => Error::InternalServerErrorException(inner), crate::error::DescribeWebsiteCertificateAuthorityErrorKind::InvalidRequestException(inner) => Error::InvalidRequestException(inner), crate::error::DescribeWebsiteCertificateAuthorityErrorKind::ResourceNotFoundException(inner) => Error::ResourceNotFoundException(inner), crate::error::DescribeWebsiteCertificateAuthorityErrorKind::TooManyRequestsException(inner) => Error::TooManyRequestsException(inner), crate::error::DescribeWebsiteCertificateAuthorityErrorKind::UnauthorizedException(inner) => Error::UnauthorizedException(inner), crate::error::DescribeWebsiteCertificateAuthorityErrorKind::Unhandled(inner) => Error::Unhandled(inner), } _ => Error::Unhandled(err.into()), } } } impl From<smithy_http::result::SdkError<crate::error::DisassociateDomainError>> for Error { fn from(err: smithy_http::result::SdkError<crate::error::DisassociateDomainError>) -> Self { match err { smithy_http::result::SdkError::ServiceError { err, .. } => match err.kind { crate::error::DisassociateDomainErrorKind::InternalServerErrorException(inner) => { Error::InternalServerErrorException(inner) } crate::error::DisassociateDomainErrorKind::InvalidRequestException(inner) => { Error::InvalidRequestException(inner) } crate::error::DisassociateDomainErrorKind::ResourceNotFoundException(inner) => { Error::ResourceNotFoundException(inner) } crate::error::DisassociateDomainErrorKind::TooManyRequestsException(inner) => { Error::TooManyRequestsException(inner) } crate::error::DisassociateDomainErrorKind::UnauthorizedException(inner) => { Error::UnauthorizedException(inner) } crate::error::DisassociateDomainErrorKind::Unhandled(inner) => { Error::Unhandled(inner) } }, _ => Error::Unhandled(err.into()), } } } impl From<smithy_http::result::SdkError<crate::error::DisassociateWebsiteAuthorizationProviderError>> for Error { fn from( err: smithy_http::result::SdkError< crate::error::DisassociateWebsiteAuthorizationProviderError, >, ) -> Self { match err { smithy_http::result::SdkError::ServiceError { err, ..} => match err.kind { crate::error::DisassociateWebsiteAuthorizationProviderErrorKind::InternalServerErrorException(inner) => Error::InternalServerErrorException(inner), crate::error::DisassociateWebsiteAuthorizationProviderErrorKind::InvalidRequestException(inner) => Error::InvalidRequestException(inner), crate::error::DisassociateWebsiteAuthorizationProviderErrorKind::ResourceAlreadyExistsException(inner) => Error::ResourceAlreadyExistsException(inner), crate::error::DisassociateWebsiteAuthorizationProviderErrorKind::ResourceNotFoundException(inner) => Error::ResourceNotFoundException(inner), crate::error::DisassociateWebsiteAuthorizationProviderErrorKind::TooManyRequestsException(inner) => Error::TooManyRequestsException(inner), crate::error::DisassociateWebsiteAuthorizationProviderErrorKind::UnauthorizedException(inner) => Error::UnauthorizedException(inner), crate::error::DisassociateWebsiteAuthorizationProviderErrorKind::Unhandled(inner) => Error::Unhandled(inner), } _ => Error::Unhandled(err.into()), } } } impl From<smithy_http::result::SdkError<crate::error::DisassociateWebsiteCertificateAuthorityError>> for Error { fn from( err: smithy_http::result::SdkError< crate::error::DisassociateWebsiteCertificateAuthorityError, >, ) -> Self { match err { smithy_http::result::SdkError::ServiceError { err, ..} => match err.kind { crate::error::DisassociateWebsiteCertificateAuthorityErrorKind::InternalServerErrorException(inner) => Error::InternalServerErrorException(inner), crate::error::DisassociateWebsiteCertificateAuthorityErrorKind::InvalidRequestException(inner) => Error::InvalidRequestException(inner), crate::error::DisassociateWebsiteCertificateAuthorityErrorKind::ResourceNotFoundException(inner) => Error::ResourceNotFoundException(inner), crate::error::DisassociateWebsiteCertificateAuthorityErrorKind::TooManyRequestsException(inner) => Error::TooManyRequestsException(inner), crate::error::DisassociateWebsiteCertificateAuthorityErrorKind::UnauthorizedException(inner) => Error::UnauthorizedException(inner), crate::error::DisassociateWebsiteCertificateAuthorityErrorKind::Unhandled(inner) => Error::Unhandled(inner), } _ => Error::Unhandled(err.into()), } } } impl From<smithy_http::result::SdkError<crate::error::ListDevicesError>> for Error { fn from(err: smithy_http::result::SdkError<crate::error::ListDevicesError>) -> Self { match err { smithy_http::result::SdkError::ServiceError { err, .. } => match err.kind { crate::error::ListDevicesErrorKind::InternalServerErrorException(inner) => { Error::InternalServerErrorException(inner) } crate::error::ListDevicesErrorKind::InvalidRequestException(inner) => { Error::InvalidRequestException(inner) } crate::error::ListDevicesErrorKind::ResourceNotFoundException(inner) => { Error::ResourceNotFoundException(inner) } crate::error::ListDevicesErrorKind::TooManyRequestsException(inner) => { Error::TooManyRequestsException(inner) } crate::error::ListDevicesErrorKind::UnauthorizedException(inner) => { Error::UnauthorizedException(inner) } crate::error::ListDevicesErrorKind::Unhandled(inner) => Error::Unhandled(inner), }, _ => Error::Unhandled(err.into()), } } } impl From<smithy_http::result::SdkError<crate::error::ListDomainsError>> for Error { fn from(err: smithy_http::result::SdkError<crate::error::ListDomainsError>) -> Self { match err { smithy_http::result::SdkError::ServiceError { err, .. } => match err.kind { crate::error::ListDomainsErrorKind::InternalServerErrorException(inner) => { Error::InternalServerErrorException(inner) } crate::error::ListDomainsErrorKind::InvalidRequestException(inner) => { Error::InvalidRequestException(inner) } crate::error::ListDomainsErrorKind::ResourceNotFoundException(inner) => { Error::ResourceNotFoundException(inner) } crate::error::ListDomainsErrorKind::TooManyRequestsException(inner) => { Error::TooManyRequestsException(inner) } crate::error::ListDomainsErrorKind::UnauthorizedException(inner) => { Error::UnauthorizedException(inner) } crate::error::ListDomainsErrorKind::Unhandled(inner) => Error::Unhandled(inner), }, _ => Error::Unhandled(err.into()), } } } impl From<smithy_http::result::SdkError<crate::error::ListFleetsError>> for Error { fn from(err: smithy_http::result::SdkError<crate::error::ListFleetsError>) -> Self { match err { smithy_http::result::SdkError::ServiceError { err, .. } => match err.kind { crate::error::ListFleetsErrorKind::InternalServerErrorException(inner) => { Error::InternalServerErrorException(inner) } crate::error::ListFleetsErrorKind::InvalidRequestException(inner) => { Error::InvalidRequestException(inner) } crate::error::ListFleetsErrorKind::TooManyRequestsException(inner) => { Error::TooManyRequestsException(inner) } crate::error::ListFleetsErrorKind::UnauthorizedException(inner) => { Error::UnauthorizedException(inner) } crate::error::ListFleetsErrorKind::Unhandled(inner) => Error::Unhandled(inner), }, _ => Error::Unhandled(err.into()), } } } impl From<smithy_http::result::SdkError<crate::error::ListTagsForResourceError>> for Error { fn from(err: smithy_http::result::SdkError<crate::error::ListTagsForResourceError>) -> Self { match err { smithy_http::result::SdkError::ServiceError { err, .. } => match err.kind { crate::error::ListTagsForResourceErrorKind::InvalidRequestException(inner) => { Error::InvalidRequestException(inner) } crate::error::ListTagsForResourceErrorKind::Unhandled(inner) => { Error::Unhandled(inner) } }, _ => Error::Unhandled(err.into()), } } } impl From<smithy_http::result::SdkError<crate::error::ListWebsiteAuthorizationProvidersError>> for Error { fn from( err: smithy_http::result::SdkError<crate::error::ListWebsiteAuthorizationProvidersError>, ) -> Self { match err { smithy_http::result::SdkError::ServiceError { err, ..} => match err.kind { crate::error::ListWebsiteAuthorizationProvidersErrorKind::InternalServerErrorException(inner) => Error::InternalServerErrorException(inner), crate::error::ListWebsiteAuthorizationProvidersErrorKind::InvalidRequestException(inner) => Error::InvalidRequestException(inner), crate::error::ListWebsiteAuthorizationProvidersErrorKind::ResourceNotFoundException(inner) => Error::ResourceNotFoundException(inner), crate::error::ListWebsiteAuthorizationProvidersErrorKind::TooManyRequestsException(inner) => Error::TooManyRequestsException(inner), crate::error::ListWebsiteAuthorizationProvidersErrorKind::UnauthorizedException(inner) => Error::UnauthorizedException(inner), crate::error::ListWebsiteAuthorizationProvidersErrorKind::Unhandled(inner) => Error::Unhandled(inner), } _ => Error::Unhandled(err.into()), } } } impl From<smithy_http::result::SdkError<crate::error::ListWebsiteCertificateAuthoritiesError>> for Error { fn from( err: smithy_http::result::SdkError<crate::error::ListWebsiteCertificateAuthoritiesError>, ) -> Self { match err { smithy_http::result::SdkError::ServiceError { err, ..} => match err.kind { crate::error::ListWebsiteCertificateAuthoritiesErrorKind::InternalServerErrorException(inner) => Error::InternalServerErrorException(inner), crate::error::ListWebsiteCertificateAuthoritiesErrorKind::InvalidRequestException(inner) => Error::InvalidRequestException(inner), crate::error::ListWebsiteCertificateAuthoritiesErrorKind::TooManyRequestsException(inner) => Error::TooManyRequestsException(inner), crate::error::ListWebsiteCertificateAuthoritiesErrorKind::UnauthorizedException(inner) => Error::UnauthorizedException(inner), crate::error::ListWebsiteCertificateAuthoritiesErrorKind::Unhandled(inner) => Error::Unhandled(inner), } _ => Error::Unhandled(err.into()), } } } impl From<smithy_http::result::SdkError<crate::error::RestoreDomainAccessError>> for Error { fn from(err: smithy_http::result::SdkError<crate::error::RestoreDomainAccessError>) -> Self { match err { smithy_http::result::SdkError::ServiceError { err, .. } => match err.kind { crate::error::RestoreDomainAccessErrorKind::InternalServerErrorException(inner) => { Error::InternalServerErrorException(inner) } crate::error::RestoreDomainAccessErrorKind::InvalidRequestException(inner) => { Error::InvalidRequestException(inner) } crate::error::RestoreDomainAccessErrorKind::ResourceNotFoundException(inner) => { Error::ResourceNotFoundException(inner) } crate::error::RestoreDomainAccessErrorKind::TooManyRequestsException(inner) => { Error::TooManyRequestsException(inner) } crate::error::RestoreDomainAccessErrorKind::UnauthorizedException(inner) => { Error::UnauthorizedException(inner) } crate::error::RestoreDomainAccessErrorKind::Unhandled(inner) => { Error::Unhandled(inner) } }, _ => Error::Unhandled(err.into()), } } } impl From<smithy_http::result::SdkError<crate::error::RevokeDomainAccessError>> for Error { fn from(err: smithy_http::result::SdkError<crate::error::RevokeDomainAccessError>) -> Self { match err { smithy_http::result::SdkError::ServiceError { err, .. } => match err.kind { crate::error::RevokeDomainAccessErrorKind::InternalServerErrorException(inner) => { Error::InternalServerErrorException(inner) } crate::error::RevokeDomainAccessErrorKind::InvalidRequestException(inner) => { Error::InvalidRequestException(inner) } crate::error::RevokeDomainAccessErrorKind::ResourceNotFoundException(inner) => { Error::ResourceNotFoundException(inner) } crate::error::RevokeDomainAccessErrorKind::TooManyRequestsException(inner) => { Error::TooManyRequestsException(inner) } crate::error::RevokeDomainAccessErrorKind::UnauthorizedException(inner) => { Error::UnauthorizedException(inner) } crate::error::RevokeDomainAccessErrorKind::Unhandled(inner) => { Error::Unhandled(inner) } }, _ => Error::Unhandled(err.into()), } } } impl From<smithy_http::result::SdkError<crate::error::SignOutUserError>> for Error { fn from(err: smithy_http::result::SdkError<crate::error::SignOutUserError>) -> Self { match err { smithy_http::result::SdkError::ServiceError { err, .. } => match err.kind { crate::error::SignOutUserErrorKind::InternalServerErrorException(inner) => { Error::InternalServerErrorException(inner) } crate::error::SignOutUserErrorKind::InvalidRequestException(inner) => { Error::InvalidRequestException(inner) } crate::error::SignOutUserErrorKind::ResourceNotFoundException(inner) => { Error::ResourceNotFoundException(inner) } crate::error::SignOutUserErrorKind::TooManyRequestsException(inner) => { Error::TooManyRequestsException(inner) } crate::error::SignOutUserErrorKind::UnauthorizedException(inner) => { Error::UnauthorizedException(inner) } crate::error::SignOutUserErrorKind::Unhandled(inner) => Error::Unhandled(inner), }, _ => Error::Unhandled(err.into()), } } } impl From<smithy_http::result::SdkError<crate::error::TagResourceError>> for Error { fn from(err: smithy_http::result::SdkError<crate::error::TagResourceError>) -> Self { match err { smithy_http::result::SdkError::ServiceError { err, .. } => match err.kind { crate::error::TagResourceErrorKind::InvalidRequestException(inner) => { Error::InvalidRequestException(inner) } crate::error::TagResourceErrorKind::Unhandled(inner) => Error::Unhandled(inner), }, _ => Error::Unhandled(err.into()), } } } impl From<smithy_http::result::SdkError<crate::error::UntagResourceError>> for Error { fn from(err: smithy_http::result::SdkError<crate::error::UntagResourceError>) -> Self { match err { smithy_http::result::SdkError::ServiceError { err, .. } => match err.kind { crate::error::UntagResourceErrorKind::InvalidRequestException(inner) => { Error::InvalidRequestException(inner) } crate::error::UntagResourceErrorKind::Unhandled(inner) => Error::Unhandled(inner), }, _ => Error::Unhandled(err.into()), } } } impl From<smithy_http::result::SdkError<crate::error::UpdateAuditStreamConfigurationError>> for Error { fn from( err: smithy_http::result::SdkError<crate::error::UpdateAuditStreamConfigurationError>, ) -> Self { match err { smithy_http::result::SdkError::ServiceError { err, ..} => match err.kind { crate::error::UpdateAuditStreamConfigurationErrorKind::InternalServerErrorException(inner) => Error::InternalServerErrorException(inner), crate::error::UpdateAuditStreamConfigurationErrorKind::InvalidRequestException(inner) => Error::InvalidRequestException(inner), crate::error::UpdateAuditStreamConfigurationErrorKind::ResourceNotFoundException(inner) => Error::ResourceNotFoundException(inner), crate::error::UpdateAuditStreamConfigurationErrorKind::TooManyRequestsException(inner) => Error::TooManyRequestsException(inner), crate::error::UpdateAuditStreamConfigurationErrorKind::UnauthorizedException(inner) => Error::UnauthorizedException(inner), crate::error::UpdateAuditStreamConfigurationErrorKind::Unhandled(inner) => Error::Unhandled(inner), } _ => Error::Unhandled(err.into()), } } } impl From<smithy_http::result::SdkError<crate::error::UpdateCompanyNetworkConfigurationError>> for Error { fn from( err: smithy_http::result::SdkError<crate::error::UpdateCompanyNetworkConfigurationError>, ) -> Self { match err { smithy_http::result::SdkError::ServiceError { err, ..} => match err.kind { crate::error::UpdateCompanyNetworkConfigurationErrorKind::InternalServerErrorException(inner) => Error::InternalServerErrorException(inner), crate::error::UpdateCompanyNetworkConfigurationErrorKind::InvalidRequestException(inner) => Error::InvalidRequestException(inner), crate::error::UpdateCompanyNetworkConfigurationErrorKind::ResourceNotFoundException(inner) => Error::ResourceNotFoundException(inner), crate::error::UpdateCompanyNetworkConfigurationErrorKind::TooManyRequestsException(inner) => Error::TooManyRequestsException(inner), crate::error::UpdateCompanyNetworkConfigurationErrorKind::UnauthorizedException(inner) => Error::UnauthorizedException(inner), crate::error::UpdateCompanyNetworkConfigurationErrorKind::Unhandled(inner) => Error::Unhandled(inner), } _ => Error::Unhandled(err.into()), } } } impl From<smithy_http::result::SdkError<crate::error::UpdateDevicePolicyConfigurationError>> for Error { fn from( err: smithy_http::result::SdkError<crate::error::UpdateDevicePolicyConfigurationError>, ) -> Self { match err { smithy_http::result::SdkError::ServiceError { err, ..} => match err.kind { crate::error::UpdateDevicePolicyConfigurationErrorKind::InternalServerErrorException(inner) => Error::InternalServerErrorException(inner), crate::error::UpdateDevicePolicyConfigurationErrorKind::InvalidRequestException(inner) => Error::InvalidRequestException(inner), crate::error::UpdateDevicePolicyConfigurationErrorKind::ResourceNotFoundException(inner) => Error::ResourceNotFoundException(inner), crate::error::UpdateDevicePolicyConfigurationErrorKind::TooManyRequestsException(inner) => Error::TooManyRequestsException(inner), crate::error::UpdateDevicePolicyConfigurationErrorKind::UnauthorizedException(inner) => Error::UnauthorizedException(inner), crate::error::UpdateDevicePolicyConfigurationErrorKind::Unhandled(inner) => Error::Unhandled(inner), } _ => Error::Unhandled(err.into()), } } } impl From<smithy_http::result::SdkError<crate::error::UpdateDomainMetadataError>> for Error { fn from(err: smithy_http::result::SdkError<crate::error::UpdateDomainMetadataError>) -> Self { match err { smithy_http::result::SdkError::ServiceError { err, .. } => match err.kind { crate::error::UpdateDomainMetadataErrorKind::InternalServerErrorException( inner, ) => Error::InternalServerErrorException(inner), crate::error::UpdateDomainMetadataErrorKind::InvalidRequestException(inner) => { Error::InvalidRequestException(inner) } crate::error::UpdateDomainMetadataErrorKind::ResourceNotFoundException(inner) => { Error::ResourceNotFoundException(inner) } crate::error::UpdateDomainMetadataErrorKind::TooManyRequestsException(inner) => { Error::TooManyRequestsException(inner) } crate::error::UpdateDomainMetadataErrorKind::UnauthorizedException(inner) => { Error::UnauthorizedException(inner) } crate::error::UpdateDomainMetadataErrorKind::Unhandled(inner) => { Error::Unhandled(inner) } }, _ => Error::Unhandled(err.into()), } } } impl From<smithy_http::result::SdkError<crate::error::UpdateFleetMetadataError>> for Error { fn from(err: smithy_http::result::SdkError<crate::error::UpdateFleetMetadataError>) -> Self { match err { smithy_http::result::SdkError::ServiceError { err, .. } => match err.kind { crate::error::UpdateFleetMetadataErrorKind::InternalServerErrorException(inner) => { Error::InternalServerErrorException(inner) } crate::error::UpdateFleetMetadataErrorKind::InvalidRequestException(inner) => { Error::InvalidRequestException(inner) } crate::error::UpdateFleetMetadataErrorKind::ResourceNotFoundException(inner) => { Error::ResourceNotFoundException(inner) } crate::error::UpdateFleetMetadataErrorKind::TooManyRequestsException(inner) => { Error::TooManyRequestsException(inner) } crate::error::UpdateFleetMetadataErrorKind::UnauthorizedException(inner) => { Error::UnauthorizedException(inner) } crate::error::UpdateFleetMetadataErrorKind::Unhandled(inner) => { Error::Unhandled(inner) } }, _ => Error::Unhandled(err.into()), } } } impl From<smithy_http::result::SdkError<crate::error::UpdateIdentityProviderConfigurationError>> for Error { fn from( err: smithy_http::result::SdkError<crate::error::UpdateIdentityProviderConfigurationError>, ) -> Self { match err { smithy_http::result::SdkError::ServiceError { err, ..} => match err.kind { crate::error::UpdateIdentityProviderConfigurationErrorKind::InternalServerErrorException(inner) => Error::InternalServerErrorException(inner), crate::error::UpdateIdentityProviderConfigurationErrorKind::InvalidRequestException(inner) => Error::InvalidRequestException(inner), crate::error::UpdateIdentityProviderConfigurationErrorKind::ResourceNotFoundException(inner) => Error::ResourceNotFoundException(inner), crate::error::UpdateIdentityProviderConfigurationErrorKind::TooManyRequestsException(inner) => Error::TooManyRequestsException(inner), crate::error::UpdateIdentityProviderConfigurationErrorKind::UnauthorizedException(inner) => Error::UnauthorizedException(inner), crate::error::UpdateIdentityProviderConfigurationErrorKind::Unhandled(inner) => Error::Unhandled(inner), } _ => Error::Unhandled(err.into()), } } } impl std::error::Error for Error {}
57.696286
167
0.644277
34f2e8e027076116b54c56383a4a727dda8c7d7a
324
sql
SQL
Framework/Tests/GetIntegerValue.dbo.sql
chrisoldwood/SS-Unit
7f78d94b500157a403d91852721a34ef6b603f7c
[ "MIT" ]
7
2015-07-28T14:17:09.000Z
2021-11-15T18:10:42.000Z
Framework/Tests/GetIntegerValue.dbo.sql
chrisoldwood/SS-Unit
7f78d94b500157a403d91852721a34ef6b603f7c
[ "MIT" ]
6
2015-01-18T01:02:26.000Z
2019-03-26T08:16:26.000Z
Framework/Tests/GetIntegerValue.dbo.sql
chrisoldwood/SS-Unit
7f78d94b500157a403d91852721a34ef6b603f7c
[ "MIT" ]
null
null
null
/** * \file * \brief The GetIntegerValue user-defined function. * \author Chris Oldwood */ if (object_id('dbo.GetIntegerValue') is not null) drop function dbo.GetIntegerValue; go /** * An example UDF that returns an integer value. */ create function dbo.GetIntegerValue() returns int as begin return 42; end go
14.727273
53
0.719136
6ed868f2cb8b18895f1ceb97e656a35863381bc0
8,052
xhtml
HTML
src/epub/text/chapter-1-12.xhtml
standardebooks/francisco-de-quevedo_pablo-de-segovia-the-spanish-sharper_pedro-pineda
7ec97c4b2746e9d9e279d7202ee8226e2a9cc91e
[ "CC0-1.0" ]
null
null
null
src/epub/text/chapter-1-12.xhtml
standardebooks/francisco-de-quevedo_pablo-de-segovia-the-spanish-sharper_pedro-pineda
7ec97c4b2746e9d9e279d7202ee8226e2a9cc91e
[ "CC0-1.0" ]
null
null
null
src/epub/text/chapter-1-12.xhtml
standardebooks/francisco-de-quevedo_pablo-de-segovia-the-spanish-sharper_pedro-pineda
7ec97c4b2746e9d9e279d7202ee8226e2a9cc91e
[ "CC0-1.0" ]
null
null
null
<?xml version="1.0" encoding="utf-8"?> <html xmlns="http://www.w3.org/1999/xhtml" xmlns:epub="http://www.idpf.org/2007/ops" epub:prefix="z3998: http://www.daisy.org/z3998/2012/vocab/structure/, se: https://standardebooks.org/vocab/1.0" xml:lang="en-GB"> <head> <title>XII</title> <link href="../css/core.css" rel="stylesheet" type="text/css"/> <link href="../css/local.css" rel="stylesheet" type="text/css"/> </head> <body epub:type="bodymatter z3998:fiction"> <section id="book-1" epub:type="part"> <section id="chapter-1-12" epub:type="chapter"> <header> <h3 epub:type="ordinal z3998:roman">XII</h3> <p epub:type="bridgehead">Of my flight from Segovia, with what happened to me by the way to Madrid.</p> </header> <p>A carrier was setting out that morning with a load from the inn for Madrid. He had a spare ass, which I hired, and went before to wait for him without the city gate. He came accordingly; I mounted, and began my journey, and said to myself, “Farewell to thee forever, thou knave of an uncle, dishonour of our family, stretcher of windpipes.” I considered I was going to Madrid, the Court of Spain, where, to my great satisfaction, nobody knew me, and there I must trust to my ingenuity. The first thing I resolved to do was to lay aside my scholar’s habit, and clothe myself in the fashion. But let us return to my uncle, who was in a great rage at the letter I left him, which was to this effect:</p> <blockquote epub:type="z3998:letter"> <p epub:type="z3998:salutation">“<abbr>Mr.</abbr> Alonso Ramplón.</p> <p>“Since it has pleased God to show me such signal mercies, as to take away my good father, and to order my mother to be conveyed to Toledo, where I know the best that can come of her is to vanish away in smoke; all I could wish for at present would be to see you served as you serve others. I design to be singular in my family, for I can never make more than one, unless I fall under your hands, and you carve me up as you do others. Do not inquire after me, for I am in duty bound to deny the kindred that is between us. Serve God and the king.”</p> </blockquote> <p>It is impossible to express how, in all likelihood, he railed and swore at me; but let us leave him there, and return to my journey. I was mounted on a dappled ass of La Mancha, and wished with all my heart that I might meet nobody; when on a sudden I discovered at a distance a gentleman going apace, with his cloak hanging on his shoulders, his sword by his side, close breeches, and boots on, altogether, to outward appearance, genteel enough, with a clean starched band, and his hat on one side. I conceived he was some man of quality that was walking, and had left his coach behind him; and accordingly, when I came up, I saluted him. He looked at me, and said, “It is very likely, good sir, that you travel more easy on that ass than I do with all my equipage.” Imagining he had meant his coach and servants he left behind, I answered, “In troth, sir, I reckon it more easy travelling than in a coach, for though there is no dispute that you go very easily in that you have left behind you, yet the jolting of it is troublesome.” “What coach behind?” replied he, much disturbed, and turning short to look about him, the sudden motion made his breeches drop down, for it broke the one point he had to hold them up; and though he saw me ready to burst with laughing, he asked to borrow one of me. Perceiving he had no more shirt than would come within the waistband of his breeches, and scarce reach to acquaint his breech he had any, I replied, “As I hope for mercy, sir, you had best wait till your servants come up, for I cannot possibly assist you, having but one single point to hold up my own breeches.” “If you are in jest, sir,” quoth he, holding his breeches in his hands, “let it pass, for I do not understand what you mean by servants.” With this he went on, and was so plain in letting me know he was poor, that before we had gone half a league together, he owned he should never be able to get to Madrid, unless I would let him ride upon my ass awhile, he was so tired with walking with his breeches in his hands, which moved me to compassion, and I alighted. He was so encumbered with his breeches, that I was fain to help him up, and was much surprised at what I discovered by my feeling; for behind, as far as was covered with the cloak, the hinder parts had no other fence against the eyes and the air. He, being sensible of the discovery I had made, very discreetly prevented what reflection I might make by saying, “All is not gold that glitters, sir Licentiate,” giving me that title on account of my long scholar’s robe; “no doubt but when you saw my fine starched band, and the show I made, you fancied I was the Lord knows who.<a href="endnotes.xhtml#note-17" id="noteref-17" epub:type="noteref">17</a> Little do you think how many fine outsides are as bare within as what you felt.” I assured him upon my word that I had conceited much different matters from what I found. “Why then, sir,” replied he, “let me tell you, all you have seen as yet is nothing, for everything about me is remarkable, and no part of me is truly clad. Such as you see me, I am a real substantial gentleman, of a good family and known seat on the mountains; and could I but feed my body as I keep my seat and gentility, I should be a happy man. But as the world goes, good sir, there is no keeping up noble blood without bread and meat, and, God be praised, it runs red in every man’s veins; nor can he be a worthy person who is worth nothing.<a href="endnotes.xhtml#note-18" id="noteref-18" epub:type="noteref">18</a> I am now convinced of the value of a good pedigree, for being ready to starve one day, they would not give a chop of mutton in the cook’s-shop for mine; for they said it was not flourished with gold letters; but the leaf gold on pills is more valuable, and few men of letters have any gold. I have sold all to my very burial-place, that nothing may be called mine when I am dead, for my father Toribio Rodriguez Vallejo Gomez de Ampuero y Jordan lost all he had in the world by being bound for others. I have nothing now left to sell but the title of Don, and I am so unfortunate, that I can find nobody that has occasion for it, because there is scarce a scoundrel now but usurps it.” Though the poor gentleman’s misfortunes were intermixed with something that was comical, I could not but pity him, asked his name, whither he was going, and what to do? He answered with all his father’s names, Don Toribio Rodriguez Vallejo Gomez de Ampuero y Jordan. Never did I hear such an empty sounding jingling name, or so like the clattering of a bell, as beginning in “Don” and ending in “dan.” He added, he was going to Madrid, because a threadbare elder brother, as he was, soon grew tainted and mouldy in a country town, and had no way to subsist; and therefore he was going to the common refuge of distressed persons, where there is room for all, and open house kept for wandering spongers: “And I never want five or six crowns in my pocket,” said he, “as soon as I am there, nor a good bed, meat, and drink, and sometimes a forbidden pleasure; for a good wit at Court is like the philosopher’s stone, which converts all it touches into gold.” This to me was the most welcome news I had ever heard; and therefore, as it were to divert the tediousness of our journey, I desired him to inform me how, and by whom, he, and others in his condition, could live at Court; for to me it appeared a very difficult matter, because everyone there seemed so far from being contented with his own, that he aimed at what belonged to others. “There are many of all sorts,” replied my spark, “but flattery is like a master-key, which introduces a man wheresoever he pleases, in such great places; and that you may not think strange of what I say, do but listen to my adventures and contrivances, and you will be convinced of the truth of it.”</p> </section> </section> </body> </html>
322.08
5,857
0.754471
66e14fb01f8013838d594876a397eb063fc5cc7f
305
swift
Swift
SwiftUIX/Color.swift
heartsker/SwiftUIX
16bdf301ac1ad8c1d78697c4cbeda8d2e7e24c59
[ "MIT" ]
null
null
null
SwiftUIX/Color.swift
heartsker/SwiftUIX
16bdf301ac1ad8c1d78697c4cbeda8d2e7e24c59
[ "MIT" ]
null
null
null
SwiftUIX/Color.swift
heartsker/SwiftUIX
16bdf301ac1ad8c1d78697c4cbeda8d2e7e24c59
[ "MIT" ]
null
null
null
// // Color.swift // SwiftUIX // // Created by Daniel Pustotin on 25.09.2021. // import SwiftUI public extension Color { static let prettySet: [Color] = [.blue, .orange, .pink, .purple, .white] static let allBasics: [Color] = [.black, .blue, .gray, .green, .orange, .pink, .purple, .red, .white] }
21.785714
102
0.645902
1faaba84265a270b2794cb1775bd5d1f1ea71af3
1,709
html
HTML
index.html
AcheronandStyx/Coding_Knowledge_Checker
623448559d8de21490708cfbc3d8f6c1f5efc5dc
[ "ADSL" ]
null
null
null
index.html
AcheronandStyx/Coding_Knowledge_Checker
623448559d8de21490708cfbc3d8f6c1f5efc5dc
[ "ADSL" ]
null
null
null
index.html
AcheronandStyx/Coding_Knowledge_Checker
623448559d8de21490708cfbc3d8f6c1f5efc5dc
[ "ADSL" ]
null
null
null
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width+device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Js Knowledge Checker</title> <link rel="stylesheet" href="./assets/css/style.css"> </head> <body> <header> <div> <nav> <a href="./scores.html">View High Scores</a> </nav> <h2 id="countdown">Time: </h2> </div> <div id="intro" data-state="visible"> <h1 class="page-title">Javascript Knowledge Checker</h1> <p>Try to answer the following code-related questions within the time limit. Keep in mind that incorrect answers will penalize your score/time by ten seconds!</p> <div class="form-group"> <button class="btn" id="start-quiz" type="submit">Start Quiz!</button> </div> </div> <div id="question"></div> <div> <h3 id="grade"></h3> </div> <div id="score-form" class="hidden"> <h3>Knowledge Check Complete!</h3> <p id="final-score"></p> <form id="score"> <div class="form-group"> <input type="text" name="initials" class="text-input" placeholder="Enter your intials"/> </div> <div class="form-group"> <button class="btn" id="submit-score" type="submit">Submit</button> </div> </form> </div> </header> <main> </main> <footer> </footer> <script src="./assets/js/script.js"></script> </body> </html>
31.648148
124
0.516091
b16a8072b24210f20f82ac62217938588611d645
3,285
h
C
src/cfg.h
tdunnick/phineas
9dba7a646cfbb936a76eb60f052bbfc3a629af19
[ "Apache-2.0" ]
3
2018-06-18T00:55:53.000Z
2021-09-28T12:57:18.000Z
src/cfg.h
tdunnick/phineas
9dba7a646cfbb936a76eb60f052bbfc3a629af19
[ "Apache-2.0" ]
null
null
null
src/cfg.h
tdunnick/phineas
9dba7a646cfbb936a76eb60f052bbfc3a629af19
[ "Apache-2.0" ]
null
null
null
/* * cfg.h * * Copyright 2011-2012 Thomas L Dunnick * * 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. */ #ifndef __CFG__ #define __CFG__ #include "xml.h" /* * common xpaths to values */ #define XINSTALL "Phineas.InstallDirectory" #define XORG "Phineas.Organization" #define XPARTY "Phineas.PartyId" #define XRETRY "Phineas.Sender.MaxRetry" #define XDELAY "Phineas.Sender.DelayRetry" #define XSOAP "Phineas.SoapTemplate" #define XACK "Phineas.AckTemplate" #define XSENDCA "Phineas.Sender.CertificateAuthority" #define XBASICAUTH "Phineas.Receiver.BasicAuth" /* * common xpath prefixes to configuration */ #define XMAP "Phineas.Sender.MapInfo.Map" #define XROUTE "Phineas.Sender.RouteInfo.Route" #define XSERVICE "Phineas.Receiver.MapInfo.Map" #define XQUEUE "Phineas.QueueInfo.Queue" #define XCONN "Phineas.QueueInfo.Connection" #define XTYPE "Phineas.QueueInfo.Type" /* * macros for the above... */ #define cfg_map_index(x,n) cfg_index((x),XMAP,(n)) #define cfg_route_index(x,n) cfg_index((x),XROUTE,(n)) #define cfg_service_index(x,n) cfg_index((x),XSERVICE,(n)) #define cfg_queue_index(x,n) cfg_index((x),XQUEUE,(n)) #define cfg_conn_index(x,n) cfg_index((x),XCONN,(n)) #define cfg_type_index(x,n) cfg_index((x),XTYPE,(n)) /* * macros for getting */ #define cfg_installdir(x) xml_get_text((x),XINSTALL) #define cfg_org(x) xml_get_text((x),XORG) #define cfg_party(x) xml_get_text((x),XPARTY) #define cfg_retries(x) xml_get_int((x),XRETRY) #define cfg_delay(x) xml_get_int((x),XDELAY) #define cfg_soap(x) xml_get_text((x),XSOAP) #define cfg_senderca(x) xml_get_text((x),XSENDCA) #define cfg_timeout(x) 10000 #define cfg_map(x,i,s) xml_getf((x),"%s[%d].%s",XMAP,(i),(s)) #define cfg_route(x,i,s) xml_getf((x),"%s[%d].%s",XROUTE,(i),(s)) #define cfg_service(x,i,s) xml_getf((x),"%s[%d].%s",XSERVICE,(i),(s)) #define cfg_queue(x,i,s) xml_getf((x),"%s[%d].%s",XQUEUE,(i),(s)) #define cfg_conn(x,i,s) xml_getf((x),"%s[%d].%s",XCONN,(i),(s)) #define cfg_type(x,i,s) xml_getf((x),"%s[%d].%s",XTYPE,(i),(s)) extern char ConfigName[]; extern XML *Config; /* used for configuration encryption */ extern char *ConfigCert; extern char *ConfigPass; extern int ConfigAlgorithm; /* * remove formatted config */ void cfg_clean (char *path); /* * free up configuration and remove formatted config */ void cfg_free (); /* * load a configuration, decrypting it if credentials found */ XML *cfg_load (char *path); /* * save a configuration, encrypting it if credentials found */ int cfg_save (XML *xml, char *path); /* * create a censored configuration for display purposes, and return * it's name. */ char *cfg_format (); /* * find the index for a repeated configuration item */ int cfg_index (XML *xml, char *path, char *name); #endif /* __CFG__ */
30.137615
76
0.716286
e5776a7d7f1cc99a4d749c42a8b2d1ded61305e3
9,138
ts
TypeScript
src/mockLink.test.ts
dpovey/mock-apollo-client
652109766343e4ae4dad8c95d5a32523d646c22b
[ "MIT" ]
98
2019-05-04T14:18:39.000Z
2022-03-24T16:28:57.000Z
src/mockLink.test.ts
dpovey/mock-apollo-client
652109766343e4ae4dad8c95d5a32523d646c22b
[ "MIT" ]
29
2019-12-13T13:21:48.000Z
2021-12-09T08:54:38.000Z
src/mockLink.test.ts
dpovey/mock-apollo-client
652109766343e4ae4dad8c95d5a32523d646c22b
[ "MIT" ]
14
2019-10-09T00:12:06.000Z
2021-12-09T03:45:34.000Z
import { gql, Operation, Observer } from '@apollo/client/core'; import { print } from 'graphql'; import { MockLink } from './mockLink'; import { createMockSubscription } from './mockSubscription'; describe('class MockLink', () => { let mockLink: MockLink; const queryOne = gql`query One {one}`; const queryTwo = gql`query Two {two}`; beforeEach(() => { jest.spyOn(console, 'warn') .mockReset(); mockLink = new MockLink(); }); describe('method setRequestHandler', () => { it('throws when a handler has already been defined for a query', () => { mockLink.setRequestHandler(queryOne, () => Promise.resolve({ data: {} })); expect(() => mockLink.setRequestHandler(queryOne, () => <any>{})) .toThrow('Request handler already defined for query'); expect(console.warn).not.toBeCalled(); }); it('does not throw when two handlers are added for two different queries', () => { expect(() => { mockLink.setRequestHandler(queryOne, () => Promise.resolve({ data: {} })); mockLink.setRequestHandler(queryTwo, () => Promise.resolve({ data: {} })); }).not.toThrow(); }); describe('when queries contain @client directives', () => { const clientSideQuery = gql`query One {one @client}`; const mixedQueryOne = gql`query Three {a @client b}`; const mixedQueryTwo = gql`query Four {c @client d}`; it('does not throw, but warns, when adding client-side query', () => { expect(() => { mockLink.setRequestHandler(clientSideQuery, jest.fn()); }).not.toThrow(); expect(console.warn).toBeCalledTimes(1); expect(console.warn).toBeCalledWith('Warning: mock-apollo-client - The query is entirely client side (using @client directives) so the request handler will not be registered.'); }); it('throws when the same mixed query is added twice', () => { mockLink.setRequestHandler(mixedQueryOne, jest.fn()); expect(() => { mockLink.setRequestHandler(mixedQueryOne, jest.fn()); }).toThrowError('Request handler already defined for query'); expect(console.warn).not.toBeCalled(); }); it('does not throw when two different mixed queries are added', () => { mockLink.setRequestHandler(mixedQueryOne, jest.fn()); expect(() => { mockLink.setRequestHandler(mixedQueryTwo, jest.fn()); }).not.toThrow(); expect(console.warn).not.toBeCalled(); }); }); describe('when queries contain __typename field', () => { it('does not throw when adding query', () => { const query = gql`query Person { __typename name }`; expect(() => { mockLink.setRequestHandler(query, jest.fn()); }).not.toThrow(); }); }); }); describe('method request', () => { const queryOneOperation = { query: queryOne, variables: { a: 'one' } } as Partial<Operation> as Operation; const createMockObserver = (): jest.Mocked<Observer<any>> => ({ next: jest.fn(), error: jest.fn(), complete: jest.fn(), }); it('throws when a handler is not defined for the query', () => { expect(() => mockLink.request(queryOneOperation)) .toThrowError(`Request handler not defined for query: ${print(queryOne)}`) }); it('correctly executes the handler when the handler is defined as a promise and it and successfully resolves', async () => { const handler = jest.fn().mockResolvedValue({ data: 'Query one result' }); mockLink.setRequestHandler(queryOne, handler); const observer = createMockObserver(); const observable = mockLink.request(queryOneOperation); observable.subscribe(observer); await new Promise(r => setTimeout(r, 0)); expect(handler).toBeCalledTimes(1); expect(handler).toBeCalledWith({ a: 'one' }); expect(observer.next).toBeCalledTimes(1); expect(observer.next).toBeCalledWith({ data: 'Query one result' }); expect(observer.error).not.toBeCalled(); expect(observer.complete).toBeCalledTimes(1); }); it('correctly executes the handler when the handler is defined as a promise and it rejects', async () => { const handler = jest.fn().mockRejectedValue('Test error'); mockLink.setRequestHandler(queryOne, handler); const observer = createMockObserver(); const observable = mockLink.request(queryOneOperation); observable.subscribe(observer); await new Promise(r => setTimeout(r, 0)); expect(handler).toBeCalledTimes(1); expect(handler).toBeCalledWith({ a: 'one' }); expect(observer.next).not.toBeCalled(); expect(observer.error).toBeCalledTimes(1); expect(observer.error).toBeCalledWith('Test error'); expect(observer.complete).not.toBeCalled(); }); it('returns an error when the handler is defined but returns undefined', async () => { const handler = jest.fn().mockReturnValue(undefined); mockLink.setRequestHandler(queryOne, handler); const observer = createMockObserver(); const observable = mockLink.request(queryOneOperation); observable.subscribe(observer); await new Promise(r => setTimeout(r, 0)); expect(observer.next).not.toBeCalled(); expect(observer.error).toBeCalledTimes(1); expect(observer.error).toBeCalledWith(new Error("Request handler must return a promise or subscription. Received 'undefined'.")); expect(observer.complete).not.toBeCalled(); }); it('returns an error when the handler is defined but throws', async () => { const handler = jest.fn(() => { throw new Error('Error in handler') }); mockLink.setRequestHandler(queryOne, handler); const observer = createMockObserver(); const observable = mockLink.request(queryOneOperation); observable.subscribe(observer); await new Promise(r => setTimeout(r, 0)); expect(observer.next).not.toBeCalled(); expect(observer.error).toBeCalledTimes(1); expect(observer.error).toBeCalledWith(new Error('Unexpected error whilst calling request handler: Error in handler')); expect(observer.complete).not.toBeCalled(); }); it('correctly executes the handler when handler is defined as a subscription and it produces data', async () => { const subscription = createMockSubscription(); const handler = jest.fn().mockReturnValue(subscription); mockLink.setRequestHandler(queryOne, handler); const observer = createMockObserver(); const observable = mockLink.request(queryOneOperation); observable.subscribe(observer); subscription.next({ data: 'Query one result' }); subscription.next({ data: 'Query one result' }); await new Promise(r => setTimeout(r, 0)); expect(handler).toBeCalledTimes(1); expect(handler).toBeCalledWith({ a: 'one' }); expect(observer.next).toBeCalledTimes(2); expect(observer.next).toBeCalledWith({ data: 'Query one result' }); expect(observer.error).not.toBeCalled(); expect(observer.complete).not.toBeCalledTimes(1); expect(subscription.closed).toBe(false); }) it('correctly executes the handler when handler is defined as a subscription and it produces an error', async () => { const subscription = createMockSubscription(); const handler = jest.fn().mockReturnValue(subscription); mockLink.setRequestHandler(queryOne, handler); const observer = createMockObserver(); const observable = mockLink.request(queryOneOperation); observable.subscribe(observer); subscription.error('Test error'); await new Promise(r => setTimeout(r, 0)); expect(handler).toBeCalledTimes(1); expect(handler).toBeCalledWith({ a: 'one' }); expect(observer.next).not.toBeCalled(); expect(observer.error).toBeCalledTimes(1); expect(observer.error).toBeCalledWith('Test error'); expect(observer.complete).not.toBeCalled(); expect(subscription.closed).toBe(true); }); it('correctly executes the handler when query contains __typename field', async () => { const personQueryWithTypename = gql`query Person { __typename name}`; const personQueryWithoutTypename = gql`query Person { name }`; const handler = jest.fn().mockResolvedValue({ data: { __typename: 'Person', name: 'Bob' } }); mockLink.setRequestHandler(personQueryWithoutTypename, handler); const observer = createMockObserver(); const queryOperation = { query: personQueryWithTypename } as Partial<Operation> as Operation; const observable = mockLink.request(queryOperation); observable.subscribe(observer); await new Promise(r => setTimeout(r, 0)); expect(handler).toBeCalledTimes(1); expect(handler).toBeCalledWith(undefined); expect(observer.next).toBeCalledTimes(1); expect(observer.next).toBeCalledWith({ data: { __typename: 'Person', name: 'Bob' } }); expect(observer.error).not.toBeCalled(); expect(observer.complete).toBeCalledTimes(1); }); }); });
37.146341
185
0.657803
d1a1bca50ca4ab5e12c41c21fa0f8cb0fd65f71e
6,865
sql
SQL
src/test/regress/sql/query_finish.sql
zhangh43/gpdb
3e2d569b3d5faacdb5813f5a1d4f967607553498
[ "PostgreSQL", "Apache-2.0" ]
1
2017-09-15T06:09:56.000Z
2017-09-15T06:09:56.000Z
src/test/regress/sql/query_finish.sql
guofengrichard/gpdb
29bdd6ef38d8d9b9cb04ca31d44e279eb9f640d3
[ "PostgreSQL", "Apache-2.0" ]
6
2018-08-04T07:51:37.000Z
2018-11-26T07:09:44.000Z
src/test/regress/sql/query_finish.sql
guofengrichard/gpdb
29bdd6ef38d8d9b9cb04ca31d44e279eb9f640d3
[ "PostgreSQL", "Apache-2.0" ]
1
2018-12-04T09:13:57.000Z
2018-12-04T09:13:57.000Z
create schema qf; -- Create and load common test tables. CREATE TABLE qf.lineitem ( l_orderkey bigint NOT NULL, l_partkey integer NOT NULL, l_suppkey integer NOT NULL, l_linenumber integer NOT NULL, l_quantity numeric(15,2) NOT NULL, l_extendedprice numeric(15,2) NOT NULL, l_discount numeric(15,2) NOT NULL, l_tax numeric(15,2) NOT NULL, l_returnflag character(1) NOT NULL, l_linestatus character(1) NOT NULL, l_shipdate date NOT NULL, l_commitdate date NOT NULL, l_receiptdate date NOT NULL, l_shipinstruct character(25) NOT NULL, l_shipmode character(10) NOT NULL, l_comment character varying(44) NOT NULL ) DISTRIBUTED BY (l_orderkey); \copy qf.lineitem ( L_ORDERKEY, L_PARTKEY, L_SUPPKEY,L_LINENUMBER,L_QUANTITY, L_EXTENDEDPRICE,L_DISCOUNT,L_TAX,L_RETURNFLAG,L_LINESTATUS,L_SHIPDATE,L_COMMITDATE,L_RECEIPTDATE,L_SHIPINSTRUCT,L_SHIPMODE,L_COMMENT) from 'data/lineitem_small.csv' with delimiter '|'; CREATE TABLE qf.orders ( o_orderkey bigint NOT NULL, o_custkey integer NOT NULL, o_orderstatus character(1) NOT NULL, o_totalprice numeric(15,2) NOT NULL, o_orderdate date NOT NULL, o_orderpriority character(15) NOT NULL, o_clerk character(15) NOT NULL, o_shippriority integer NOT NULL, o_comment character varying(79) NOT NULL ) DISTRIBUTED BY (o_orderkey); \copy qf.orders ( O_ORDERKEY,O_CUSTKEY,O_ORDERSTATUS,O_TOTALPRICE,O_ORDERDATE,O_ORDERPRIORITY,O_CLERK,O_SHIPPRIORITY,O_COMMENT) from 'data/order_small.csv' with delimiter '|'; CREATE TABLE qf.supplier ( s_suppkey integer NOT NULL, s_name character(25) NOT NULL, s_address character varying(40) NOT NULL, s_nationkey integer NOT NULL, s_phone character(15) NOT NULL, s_acctbal numeric(15,2) NOT NULL, s_comment character varying(101) NOT NULL ) DISTRIBUTED BY (s_suppkey); \copy qf.supplier (S_SUPPKEY,S_NAME,S_ADDRESS,S_NATIONKEY,S_PHONE,S_ACCTBAL,S_COMMENT) from 'data/supplier.csv' with delimiter '|'; create table skewed_lineitem as select 1 AS l_skewkey, * from qf.lineitem distributed by (l_skewkey); insert into skewed_lineitem values( 2, generate_series(1, 3), 42, 15, 23, 0, 4000, 0.1, 0.3, NULL, NULL, '2001-01-01', '2012-12-01', NULL, 'foobarfoobarbaz', '0937', 'supercalifragilisticexpialidocious'); -- -- The actual tests. -- -- It used to fail because query cancel is sent and QE goes out of -- transaction block, though QD sends 2PC request. begin; drop table if exists qf.foo; create table qf.foo as select i a, i b from generate_series(1, 100)i; select case when gp_segment_id = 0 then pg_sleep(3) end from qf.foo limit 1; commit; -- with order by. CTE can prevent LIMIT from being pushed down. begin; drop table if exists qf.bar2; create table qf.bar2 as select i a, i b from generate_series(1, 100)i; with t2 as( select * from skewed_lineitem order by l_orderkey ) select * from t2 order by 1,2,3,4,5 limit 1; commit; -- with window function. begin; drop table if exists qf.bar3; create table qf.bar3(a int, b text, c numeric) with (appendonly=true); insert into qf.bar3 select a, repeat('x', 10) b, b from qf.bar2; with t3 as( select l_skewkey, count(*) over (partition by l_skewkey order by l_quantity, l_orderkey) from skewed_lineitem ) select * from t3 order by 1,2 limit 2; commit; -- combination. begin; drop table if exists qf.bar4; create table qf.bar4(a int, b int, c text) with (appendonly=true, orientation=column); insert into qf.bar4 select a, b, 'foo' from qf.bar2; with t4a as( select l_skewkey, count(*) over (partition by l_skewkey order by l_quantity, l_orderkey) from skewed_lineitem ), t4b as ( select * from skewed_lineitem order by l_orderkey ) select a.l_skewkey, b.l_skewkey from t4a a inner join t4b b on a.l_skewkey = b.l_skewkey order by 1, 2 limit 3; commit; -- median. begin; drop table if exists qf.bar5; create table qf.bar5(a int, b int); insert into qf.bar5 select i, i % 10 from generate_series(1, 10)i; with t5a as( select l_skewkey, median(l_quantity) med from skewed_lineitem group by l_skewkey ), t5b as ( select * from skewed_lineitem order by l_orderkey ) select a.l_skewkey, a.med from t5a a inner join t5b b on a.l_skewkey = b.l_skewkey order by a.l_skewkey, a.med limit 1; commit; --Combination median and windows begin; with t3 as( select l_skewkey, count(*) over (partition by l_skewkey order by l_quantity, l_orderkey) from skewed_lineitem ), t4 as ( select l_skewkey, median(l_quantity) med from skewed_lineitem group by l_skewkey ) select a.l_skewkey from t3 a left outer join t4 b on a. l_skewkey = b. l_skewkey order by a.l_skewkey limit 1; commit; --csq begin; select l_returnflag from skewed_lineitem t1 where l_skewkey in (select l_skewkey from skewed_lineitem t2 where t1.l_shipinstruct = t2.l_shipinstruct) order by l_returnflag limit 3; commit; -- -- Exercise query-finish flag in sort. -- with t6a as( select l_skewkey, count(*) over (partition by l_skewkey order by l_quantity, l_orderkey) from skewed_lineitem ), t6b as ( select * from skewed_lineitem order by l_orderkey ), t6c as ( select l_skewkey, median(l_quantity) med from skewed_lineitem group by l_skewkey ) select a.l_skewkey, b.l_orderkey, c.med from t6a a inner join t6b b on a.l_skewkey = b.l_skewkey inner join t6c c on b.l_skewkey = c.l_skewkey order by 1, 2, 3 limit 2; -- -- Exercise query-finish vs motion/interconnect -- with t7a as( select l_skewkey, l_orderkey from skewed_lineitem ), t7b as ( select * from skewed_lineitem ) select count(*) from( select b.l_skewkey, b.l_orderkey from t7a a inner join t7b b on a.l_orderkey = b.l_orderkey limit 2 )s; select l1.l_partkey, l1.l_suppkey, l1.l_comment from skewed_lineitem l1 inner join qf.orders o1 on l1.l_orderkey = o1.o_orderkey where l1.l_suppkey = ( select s_suppkey from skewed_lineitem l2 inner join qf.supplier on l2.l_suppkey = s_suppkey where s_nationkey = 11 and l2.l_returnflag = 'A' limit 1 ) limit -1; select l1.l_partkey, l1.l_suppkey, l1.l_comment from skewed_lineitem l1 inner join qf.orders o1 on l1.l_orderkey = o1.o_orderkey where l1.l_suppkey in ( select s_suppkey from skewed_lineitem l2 inner join qf.supplier on l2.l_suppkey = s_suppkey where s_nationkey = 11 and l2.l_returnflag = 'A' limit 2 ) limit -1; select l1.l_partkey, l1.l_suppkey, l1.l_comment from skewed_lineitem l1 inner join qf.orders o1 on l1.l_orderkey = o1.o_orderkey where exists ( select * from qf.supplier where l1.l_suppkey = s_suppkey and s_nationkey = 11 and l1.l_returnflag = 'A' ) limit -1; -- cause hashjoin to spill set statement_mem = '1MB'; select l1.l_partkey IS NOT NULL as part_is_not_null from skewed_lineitem l1 inner join qf.supplier s1 on l1.l_suppkey = s1.s_suppkey limit 2; reset statement_mem;
26.921569
263
0.742462
6df63abc101d733f900c9643b6afb944c2c3afe5
352
sql
SQL
db/seeds.sql
mwturner611/Burger_Quest
61ec178f8512c4d3ff80b71583aec95d05148699
[ "MIT" ]
null
null
null
db/seeds.sql
mwturner611/Burger_Quest
61ec178f8512c4d3ff80b71583aec95d05148699
[ "MIT" ]
null
null
null
db/seeds.sql
mwturner611/Burger_Quest
61ec178f8512c4d3ff80b71583aec95d05148699
[ "MIT" ]
null
null
null
-- starter file for burgers table USE burgers_db; INSERT INTO burgers (burger_name,devoured) VALUES ("Pharmacy Burger",false); INSERT INTO burgers (burger_name,devoured) VALUES ("Cheese Burger",false); INSERT INTO burgers (burger_name,devoured) VALUES ("Chili Burger",false); INSERT INTO burgers (burger_name,devoured) VALUES ("Farm Burger",false);
25.142857
42
0.778409
5c4267499ac76167fbed3dbca148c349887d27b4
4,637
h
C
XDBLESDK.framework/Headers/WMBLETool.h
WangMing1998/XDBLESDK
1baab264f629454afe740963619749b0b2f2a146
[ "MIT" ]
null
null
null
XDBLESDK.framework/Headers/WMBLETool.h
WangMing1998/XDBLESDK
1baab264f629454afe740963619749b0b2f2a146
[ "MIT" ]
null
null
null
XDBLESDK.framework/Headers/WMBLETool.h
WangMing1998/XDBLESDK
1baab264f629454afe740963619749b0b2f2a146
[ "MIT" ]
null
null
null
// // WMBLETool.h // WMBluetoothDemo // // Created by Heaton on 2017/12/29. // Copyright © 2017年 WangMingDeveloper. All rights reserved. // #import <Foundation/Foundation.h> #import <CoreBluetooth/CoreBluetooth.h> #import "WMBLEPeripheral.h" #import "WMBLEDefine.h" typedef BOOL (^WMBLEFilterPeripheralsRlueBlock)(NSString *peripheralName, NSDictionary *advertisementData, NSNumber *RSSI); typedef void (^WMBLECentralManagerDidUpdateStateBlock)(CBCentralManager *central); typedef void (^WMBLEDiscoverPeripheralsBlock)(CBCentralManager *central,WMBLEPeripheral *peripheral,NSDictionary *advertisementData, NSNumber *RSSI); typedef void (^WMBLEConnectedPeripheralBlock)(CBCentralManager *central,WMBLEPeripheral *peripheral); typedef void (^WMBLEFailToConnectBlock)(CBCentralManager *central,WMBLEPeripheral *peripheral,NSError *error); typedef void (^WMBLEDisconnectBlock)(CBCentralManager *central,WMBLEPeripheral *peripheral,NSError *error); typedef void (^WMBLEDiscoverServicesBlock)(WMBLEPeripheral *peripheral,CBService *service,NSError *error); typedef void (^WMBLEDiscoverCharacteristicsBlock)(WMBLEPeripheral *peripheral,CBService *service,NSError *error); typedef void (^WMBLEDidupdateValueForCharacteristicBlock)(WMBLEPeripheral *peripheral,CBCharacteristic *characteristic,NSError *error); typedef void (^WMBLEDidWriteValueForCharacteristicBlock)(WMBLEPeripheral *peripheral,CBCharacteristic *characteristic,NSError *error); typedef void (^WMBLEDidUpdateNotificationStateForCharacteristicBlock)(WMBLEPeripheral *peripheral,CBCharacteristic *characteristic,NSError *error); typedef void (^WMBLEDidReadRSSIBlock)(WMBLEPeripheral *peripheral,NSNumber *RSSI,NSError *error); typedef void (^WMBLEDiscoverDescriptorsForCharacteristicBlock)(WMBLEPeripheral *peripheral,CBCharacteristic *service,NSError *error); typedef void (^WMBLEReadValueForDescriptorsBlock)(WMBLEPeripheral *peripheral,CBDescriptor *descriptor,NSError *error); @interface WMBLETool : NSObject @property(nonatomic,copy) WMBLEFilterPeripheralsRlueBlock bleFiliterPeralsRuleBlock; @property(nonatomic,copy) WMBLECentralManagerDidUpdateStateBlock bleDidUpdateStateBlock; @property(nonatomic,copy) WMBLEDiscoverPeripheralsBlock bleDiscoverPeripheralsBlock; @property(nonatomic,copy) WMBLEConnectedPeripheralBlock bleConnectedPeripheralBlock; @property(nonatomic,copy) WMBLEFailToConnectBlock bleConnectedFailPeripheralBlock; @property(nonatomic,copy) WMBLEDisconnectBlock bleDisconnectedPeripheralBlock; @property(nonatomic,copy) WMBLEDiscoverServicesBlock bleDiscoverServicesBlock; @property(nonatomic,copy) WMBLEDiscoverCharacteristicsBlock bleDiscoverCharacteristicsBlock; @property(nonatomic,copy) WMBLEDidupdateValueForCharacteristicBlock bleDidupdateValueForCharacteristicsBlock; // 向特征写入数据成功与否回调 @property(nonatomic,copy) WMBLEDidWriteValueForCharacteristicBlock bleDidWriteValueForCharacteristicBlock; @property(nonatomic,copy) WMBLEDidReadRSSIBlock bleDidReadRSSIBlock; @property(nonatomic,copy) WMBLEDidUpdateNotificationStateForCharacteristicBlock bleDidUpdateNotificationStateForCharacteristicBlock; @property(nonatomic,assign) CBManagerState bleState; @property(nonatomic,strong) NSMutableArray<WMBLEPeripheral *> *connectedPeripherals; + (instancetype)shareInstance; /** Peripherals service id, please fill nil if scanning all of the peripherals @param services services array @param options Scan Settings --> options keyx CBCentralManagerScanOptionAllowDuplicatesKey YES/ON:Whether to repeat scanning devices have been found */ -(void)startScanWithServices:(NSArray<CBUUID *>*)services options:(NSDictionary *)options; -(void)stopScanPeripherals; /** Links to bluetooth peripherals @param peripheral The custom of bluetooth peripherals @param options Connection Settings -->options Key CBConnectPeripheralOptionNotifyOnConnectionKey CBConnectPeripheralOptionNotifyOnDisconnectionKey CBConnectPeripheralOptionNotifyOnNotificationKey */ -(void)connectWitpPeripheral:(WMBLEPeripheral *)peripheral options:(NSDictionary *)options; /** Disconnect the bluetooth device @param peripheral The custom of bluetooth peripherals */ -(void)disconnectWithPeripheral:(WMBLEPeripheral *)peripheral; /** Disconnect all of the peripherals */ -(void)disconnectAllPeripheral; -(void)autoReconnectPeripheralWithUUIDs:(NSArray<NSUUID *>*)uuids; -(void)sendSmallData:(NSData *)data peripheral:(WMBLEPeripheral *)peripheral characteristic:(CBCharacteristic *)characteristic; @end
51.522222
149
0.820142
e53529014af6ad9ec58a8f332e350ba160eb7529
1,515
ts
TypeScript
mobile/src/app/services/app-update.service.ts
jabardigitalservice/sapawarga-ionic
50bf92fcdd0f66ba758375c92e1b094f04c88154
[ "MIT" ]
null
null
null
mobile/src/app/services/app-update.service.ts
jabardigitalservice/sapawarga-ionic
50bf92fcdd0f66ba758375c92e1b094f04c88154
[ "MIT" ]
1
2020-01-21T00:51:36.000Z
2020-01-21T00:51:36.000Z
mobile/src/app/services/app-update.service.ts
jabardigitalservice/sapawarga-ionic
50bf92fcdd0f66ba758375c92e1b094f04c88154
[ "MIT" ]
null
null
null
import { Injectable } from '@angular/core'; // plugin import { AppVersion } from '@ionic-native/app-version/ngx'; import { environment } from '../../environments/environment'; import { UtilitiesService } from './utilities.service'; import { HTTP } from '@ionic-native/http/ngx'; import * as compareVersions from 'compare-versions'; @Injectable({ providedIn: 'root' }) export class AppUpdateService { constructor( private nativeHttp: HTTP, private appVersion: AppVersion, private util: UtilitiesService ) {} private getVersionNumberAPI() { return this.nativeHttp.get( `${environment.API_STORAGE}/version.json`, {}, { 'Content-Type': 'application/json' } ); } checkAppUpdate() { this.appVersion .getVersionNumber() .then(sistemVersion => { this.getVersionNumberAPI().then(val => { const respon = JSON.parse(val.data); const latestVersionReleased = respon.version; const isForceUpdateNeeded = respon.force_update; const currentAppVersion = sistemVersion.split('-')[0]; // parsing version sistem // compare version if currentAppVersion < latestVersionReleased than return true const compare = compareVersions.compare( currentAppVersion, latestVersionReleased, '<' ); if (isForceUpdateNeeded === true && compare === true) { this.util.presentModal(); } }); }) .catch(_ => {}); } }
29.134615
91
0.625743
71799ccd6ecca0bf22e0385ef51a7eb8a764fa96
730
ts
TypeScript
frontend/src/app/_component/auth.component/auth.component.ts
ssh-user/e-shop-v2
3c859083fd472901fe30a1e0bafbd945899acd4c
[ "MIT" ]
1
2021-02-12T12:34:39.000Z
2021-02-12T12:34:39.000Z
frontend/src/app/_component/auth.component/auth.component.ts
ssh-user/e-shop-v2
3c859083fd472901fe30a1e0bafbd945899acd4c
[ "MIT" ]
null
null
null
frontend/src/app/_component/auth.component/auth.component.ts
ssh-user/e-shop-v2
3c859083fd472901fe30a1e0bafbd945899acd4c
[ "MIT" ]
null
null
null
import { Component, OnInit } from '@angular/core'; import { AuthService } from '../../_service/auth.service'; import { User } from '../../_model/user.model'; @Component({ moduleId: module.id, selector: 'auth-menu', templateUrl: 'auth.component.html', styleUrls: ['auth.component.css'] }) export class AuthMenuComponent implements OnInit { public user: User; constructor(private auth: AuthService) { }; ngOnInit() { this.auth.user$.subscribe((user) => { this.user = user; }, (err) => { }); if (!this.auth.isSendReqToCheck) this.auth.checkAuth().subscribe((user: User) => { this.user = user; this.auth.login(user); }); }; };
24.333333
90
0.584932
b6f50a0e980b3adc54acaa3b062b0891d698cd82
17
rb
Ruby
lib/ccb.rb
eiffelqiu/ccb
8a487b2967cb5cf266db1d74182894f393b9ea29
[ "MIT" ]
null
null
null
lib/ccb.rb
eiffelqiu/ccb
8a487b2967cb5cf266db1d74182894f393b9ea29
[ "MIT" ]
null
null
null
lib/ccb.rb
eiffelqiu/ccb
8a487b2967cb5cf266db1d74182894f393b9ea29
[ "MIT" ]
null
null
null
require 'ccb/cli'
17
17
0.764706
0a14d4c54730f4e9cec5f5f0acac85dcac09d651
757
ts
TypeScript
meet_menu_ts/GUI/ActionButtonText.ts
titiceral/meet_menu_gl
ffafc6261a8d667136fc9f5402260c2b4d493423
[ "MIT" ]
null
null
null
meet_menu_ts/GUI/ActionButtonText.ts
titiceral/meet_menu_gl
ffafc6261a8d667136fc9f5402260c2b4d493423
[ "MIT" ]
null
null
null
meet_menu_ts/GUI/ActionButtonText.ts
titiceral/meet_menu_gl
ffafc6261a8d667136fc9f5402260c2b4d493423
[ "MIT" ]
null
null
null
/// <reference path="./IButton.ts" /> class ActionButtonText extends IButton { // interface redéfinition eventOnActiveHandler: () => void; eventOnDesactivateHandler: () => void; /** * */ constructor(anchorMesh: any, strName: string, strLabel: string) { super(anchorMesh, strName); this.guiButton = GuiFactoryManager.Instance().CreateGuiTextButton( strName, strLabel ); super.InitialiseButton(); } //#region Ibutton héritage OnProgress(progressPercentage: number): void { throw new Error("Method not implemented."); } OnClicked(): void { if (this.isClicked) { this.eventOnDesactivateHandler(); } else { this.eventOnActiveHandler(); } } //#endregion IButton héritage }
22.264706
70
0.65786
087640c06782c093043a987f3233b87da1b20086
813
go
Go
cmd/auth/internal/infrastructure/persistence/token.go
PeppyHare/go-boilerplate
7db88b1565e02b7ad1ed840ede7c2ff0a6c3819d
[ "MIT" ]
1
2021-01-06T13:26:37.000Z
2021-01-06T13:26:37.000Z
cmd/auth/internal/infrastructure/persistence/token.go
PeppyHare/go-boilerplate
7db88b1565e02b7ad1ed840ede7c2ff0a6c3819d
[ "MIT" ]
null
null
null
cmd/auth/internal/infrastructure/persistence/token.go
PeppyHare/go-boilerplate
7db88b1565e02b7ad1ed840ede7c2ff0a6c3819d
[ "MIT" ]
null
null
null
/* Package persistence holds view models and repository interfaces */ package persistence import ( "context" "encoding/json" ) // Token the token persistence model interface type Token interface { GetID() string GetClientID() string GetUserID() string GetAccess() string GetRefresh() string GetScope() string GetCode() string GetData() json.RawMessage } // TokenRepository allows to get/save current state of token to mysql storage type TokenRepository interface { Get(ctx context.Context, id string) (Token, error) GetByCode(ctx context.Context, code string) (Token, error) GetByAccess(ctx context.Context, access string) (Token, error) GetByRefresh(ctx context.Context, refresh string) (Token, error) Add(ctx context.Context, token Token) error Delete(ctx context.Context, id string) error }
25.40625
77
0.768758