hexsha
stringlengths
40
40
size
int64
5
1.05M
ext
stringclasses
98 values
lang
stringclasses
21 values
max_stars_repo_path
stringlengths
3
945
max_stars_repo_name
stringlengths
4
118
max_stars_repo_head_hexsha
stringlengths
40
78
max_stars_repo_licenses
sequencelengths
1
10
max_stars_count
int64
1
368k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
3
945
max_issues_repo_name
stringlengths
4
118
max_issues_repo_head_hexsha
stringlengths
40
78
max_issues_repo_licenses
sequencelengths
1
10
max_issues_count
int64
1
134k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
3
945
max_forks_repo_name
stringlengths
4
135
max_forks_repo_head_hexsha
stringlengths
40
78
max_forks_repo_licenses
sequencelengths
1
10
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
5
1.05M
avg_line_length
float64
1
1.03M
max_line_length
int64
2
1.03M
alphanum_fraction
float64
0
1
e25bd724e631d4851260b743bc2098646d4412f7
728
js
JavaScript
src/routes.js
adornodev/gostack-fastfeet
d288b0e49b8376945bcefe0931d672e1c9e2ff70
[ "MIT" ]
null
null
null
src/routes.js
adornodev/gostack-fastfeet
d288b0e49b8376945bcefe0931d672e1c9e2ff70
[ "MIT" ]
1
2021-05-11T01:51:12.000Z
2021-05-11T01:51:12.000Z
src/routes.js
adornodev/gostack-fastfeet
d288b0e49b8376945bcefe0931d672e1c9e2ff70
[ "MIT" ]
null
null
null
import { Router } from 'express'; import RecipientController from './app/controllers/RecipientController'; import SessionController from './app/controllers/SessionController'; import UserController from './app/controllers/UserController'; import authMiddleware from './app/middlewares/auth'; const routes = Router(); routes.post('/sessions', SessionController.store); routes.put('/users/:id', authMiddleware, UserController.update); routes.post('/users', authMiddleware, UserController.store); routes.get('/users', authMiddleware, UserController.index); routes.post('/recipients', authMiddleware, RecipientController.store); routes.put('/recipients/:id', authMiddleware, RecipientController.update); export default routes;
38.315789
74
0.791209
8db65c02ea5a5594928235ea696b7e401c81fe4f
3,324
js
JavaScript
src/components/layout.js
seandolinar/stats-seandolinar-gatsby
9036ab9ca5e70874edf8a258e815b1d94453b079
[ "MIT" ]
null
null
null
src/components/layout.js
seandolinar/stats-seandolinar-gatsby
9036ab9ca5e70874edf8a258e815b1d94453b079
[ "MIT" ]
null
null
null
src/components/layout.js
seandolinar/stats-seandolinar-gatsby
9036ab9ca5e70874edf8a258e815b1d94453b079
[ "MIT" ]
null
null
null
import React, { useState } from 'react'; import PropTypes from 'prop-types'; import Helmet from 'react-helmet'; import { StaticQuery, graphql } from 'gatsby'; import AdSense from 'react-adsense'; import ErrorBoundary from './ErrorBoundary'; import Header from './header'; import MenuCategory from './MenuCategory'; import ButtonMenu from './ButtonMenu'; import './layout.css'; import '../styles/layout.scss'; import { setConfig } from 'react-hot-loader'; setConfig({ pureSFC: true }); const Layout = ({ children, pageType }) => { // return (<StaticQuery // query={graphql` // query SiteTitleQuery { // site { // siteMetadata { // title // } // } // } // `} // render={data => (); // )} // /> const [isMenuMobileOpen, setMenuOpen] = useState(false); return <div className="site-wrapper"> <Helmet title="stats.seandolinar.com" meta={[ { name: 'google-site-verification', content: '4zzLgNmIbi66VfwfkRprZoo2eebh52ac6wdyqkWl9Nk' } ]} > <html lang="en" /> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width" /> <link href="https://fonts.googleapis.com/css?family=Lato:900" rel="stylesheet" /> <link href="https://fonts.googleapis.com/css?family=Titillium+Web" rel="stylesheet" /> {/* <link rel="canonical" href="https://stats.seandolinar.com" /> */} <script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script> <script async src="https://www.googletagmanager.com/gtag/js?id=UA-46773652-1"></script> <script> { `window.dataLayer = window.dataLayer || []; function gtag(){dataLayer.push(arguments);} gtag('js', new Date()); gtag('config', 'UA-46773652-1');` } </script> <meta property="og:site_name" content="stats.seandolinar.com" /> </Helmet> <Header /> <div className="site-header-menu-mobile"> <ButtonMenu onClick={() => setMenuOpen(!isMenuMobileOpen)} isMenuOpen={isMenuMobileOpen}></ButtonMenu> </div> <div className="site-content-wrapper"> <MenuCategory isMenuMobileOpen={isMenuMobileOpen} /> <main className={'site-content ' + pageType} > <div className="ra-column visible-desktop"> <ErrorBoundary> <AdSense.Google client='ca-pub-9996180831969957' slot='2589150622' style={{ display: 'block', margin: 'auto' }} format='auto' responsive='true' /> </ErrorBoundary> </div> <div className="ra-column visible-desktop right"> <ErrorBoundary> <AdSense.Google client='ca-pub-9996180831969957' slot='9693615028' style={{ display: 'block', margin: 'auto' }} format='auto' responsive='true' /> </ErrorBoundary> </div> {children} </main> </div> <footer> <div className="footer-content"> @seandolinar </div> </footer> </div> } Layout.propTypes = { children: PropTypes.node.isRequired, }; export default Layout;
29.945946
108
0.566185
c6de1529b185b3a64ab927082f7d9a4dcddd85c1
3,698
py
Python
examples/face_detection/main.py
Ishticode/kornia
974abb43ec72d12dbd244a2fb247bbbab8498de0
[ "ECL-2.0", "Apache-2.0" ]
418
2018-10-02T22:31:36.000Z
2019-01-16T14:15:45.000Z
examples/face_detection/main.py
Ishticode/kornia
974abb43ec72d12dbd244a2fb247bbbab8498de0
[ "ECL-2.0", "Apache-2.0" ]
94
2019-01-17T22:10:45.000Z
2019-05-22T23:47:58.000Z
examples/face_detection/main.py
Ishticode/kornia
974abb43ec72d12dbd244a2fb247bbbab8498de0
[ "ECL-2.0", "Apache-2.0" ]
25
2018-10-02T22:50:04.000Z
2019-01-13T18:14:11.000Z
"""Script that finds faces and blurs using FaceDetection and blurring APIs.""" import argparse import cv2 import numpy as np import torch import kornia as K from kornia.contrib import FaceDetector, FaceDetectorResult, FaceKeypoint def draw_keypoint(img: np.ndarray, det: FaceDetectorResult, kpt_type: FaceKeypoint) -> np.ndarray: kpt = det.get_keypoint(kpt_type).int().tolist() return cv2.circle(img, kpt, 2, (255, 0, 0), 2) def scale_image(img: np.ndarray, size: int) -> np.ndarray: h, w = img.shape[:2] scale = 1. * size / w return cv2.resize(img, (int(w * scale), int(h * scale))) def apply_blur_face(img: torch.Tensor, img_vis: np.ndarray, det: FaceDetectorResult): # crop the face x1, y1 = det.xmin.int(), det.ymin.int() x2, y2 = det.xmax.int(), det.ymax.int() roi = img[..., y1:y2, x1:x2] # apply blurring and put back to the visualisation image roi = K.filters.gaussian_blur2d(roi, (21, 21), (35., 35.)) roi = K.color.rgb_to_bgr(roi) img_vis[y1:y2, x1:x2] = K.tensor_to_image(roi) def my_app(args): # select the device device = torch.device('cpu') if args.cuda and torch.cuda.is_available(): device = torch.device('cuda:0') # load the image and scale img_raw = cv2.imread(args.image_file, cv2.IMREAD_COLOR) img_raw = scale_image(img_raw, args.image_size) # preprocess img = K.image_to_tensor(img_raw, keepdim=False).to(device) img = K.color.bgr_to_rgb(img.float()) # create the detector and find the faces ! face_detection = FaceDetector().to(device) with torch.no_grad(): dets = face_detection(img) dets = [FaceDetectorResult(o) for o in dets] # show image img_vis = img_raw.copy() for b in dets: if b.score < args.vis_threshold: continue # draw face bounding box img_vis = cv2.rectangle( img_vis, b.top_left.int().tolist(), b.bottom_right.int().tolist(), (0, 255, 0), 4) if args.blur_faces: apply_blur_face(img, img_vis, b) if args.vis_keypoints: # draw facial keypoints img_vis = draw_keypoint(img_vis, b, FaceKeypoint.EYE_LEFT) img_vis = draw_keypoint(img_vis, b, FaceKeypoint.EYE_RIGHT) img_vis = draw_keypoint(img_vis, b, FaceKeypoint.NOSE) img_vis = draw_keypoint(img_vis, b, FaceKeypoint.MOUTH_LEFT) img_vis = draw_keypoint(img_vis, b, FaceKeypoint.MOUTH_RIGHT) # draw the text score cx = int(b.xmin) cy = int(b.ymin + 12) img_vis = cv2.putText( img_vis, f"{b.score:.2f}", (cx, cy), cv2.FONT_HERSHEY_DUPLEX, 0.5, (255, 255, 255)) # save and show image cv2.imwrite(args.image_out, img_vis) cv2.namedWindow('face_detection', cv2.WINDOW_NORMAL) cv2.imshow('face_detection', img_vis) cv2.waitKey(0) if __name__ == "__main__": parser = argparse.ArgumentParser(description='Face and Landmark Detection') parser.add_argument('--image_file', required=True, type=str, help='the image file to be detected.') parser.add_argument('--image_out', required=True, type=str, help='the file path to write the output.') parser.add_argument('--image_size', default=320, type=int, help='the image size to process.') parser.add_argument('--vis_threshold', default=0.8, type=float, help='visualization_threshold') parser.add_argument('--vis_keypoints', dest='vis_keypoints', action='store_true') parser.add_argument('--cuda', dest='cuda', action='store_true') parser.add_argument('--blur_faces', dest='blur_faces', action='store_true') args = parser.parse_args() my_app(args)
35.557692
106
0.659275
e27a10678e1e2d06fcfe824a0a7ea04d55e074cb
1,497
js
JavaScript
src/components/layout.js
Quentin0292/TravelMountains
60ecf4ab88ce47a9a8c9905e727f1a9972c5dc73
[ "MIT" ]
null
null
null
src/components/layout.js
Quentin0292/TravelMountains
60ecf4ab88ce47a9a8c9905e727f1a9972c5dc73
[ "MIT" ]
null
null
null
src/components/layout.js
Quentin0292/TravelMountains
60ecf4ab88ce47a9a8c9905e727f1a9972c5dc73
[ "MIT" ]
null
null
null
/** * Layout component that queries for data * with Gatsby's useStaticQuery component * * See: https://www.gatsbyjs.org/docs/use-static-query/ */ import React from "react" import PropTypes from "prop-types" import { useStaticQuery, graphql } from "gatsby" import { FaTwitter, FaFacebook, FaSnapchatGhost } from "react-icons/fa" import Header from "./header" import "./layout.css" import test from "../images/mountains.jpg" const Layout = ({ children }) => { const data = useStaticQuery(graphql` query SiteTitleQuery { site { siteMetadata { title } } } `) return ( <> <Header siteTitle={data.site.siteMetadata.title} /> <div> <main>{children}</main> <footer> <p> Images courtesy of <a href="https://unsplash.com/">unsplash</a>. </p> <p> Why are you even reading this ?! There's never anything interesting in the footer ! </p> <ul> <li> <a href="#"> <FaTwitter /> </a> </li> <li> <a href="#"> <FaFacebook /> </a> </li> <li> <a href="#"> <FaSnapchatGhost /> </a> </li> </ul> </footer> </div> </> ) } Layout.propTypes = { children: PropTypes.node.isRequired, } export default Layout
21.385714
79
0.490314
b61b5acd3a06f38834a7ff1f0a91cdd227a73d71
358
rb
Ruby
spec/factories/access_policies.rb
process-project/iee
4137286d53cfdb52ce74353d199dc1ce16e75da0
[ "MIT" ]
null
null
null
spec/factories/access_policies.rb
process-project/iee
4137286d53cfdb52ce74353d199dc1ce16e75da0
[ "MIT" ]
4
2021-05-20T07:14:38.000Z
2022-02-12T01:50:21.000Z
spec/factories/access_policies.rb
process-project/iee
4137286d53cfdb52ce74353d199dc1ce16e75da0
[ "MIT" ]
null
null
null
# frozen_string_literal: true FactoryBot.define do factory :access_policy do access_method resource trait :user_access_policy do user end trait :group_access_policy do group end factory :user_access_policy, traits: [:user_access_policy] factory :group_access_policy, traits: [:group_access_policy] end end
17.9
64
0.72067
a16c7de2daacc27634406cccadfa284484b65ad4
384
tsx
TypeScript
CoreReact/clientapp/src/__tests__/home/AppComponent.test.tsx
chesteryang/CoreReact
1e0ad6ca4495506b5e1c79ee4f59be140ab39c0f
[ "MIT" ]
1
2019-05-03T16:41:49.000Z
2019-05-03T16:41:49.000Z
CoreReact/clientapp/src/__tests__/home/AppComponent.test.tsx
chesteryang/CoreReact
1e0ad6ca4495506b5e1c79ee4f59be140ab39c0f
[ "MIT" ]
6
2021-03-01T21:29:54.000Z
2022-03-03T22:02:28.000Z
CoreReact/clientapp/src/__tests__/home/AppComponent.test.tsx
chesteryang/CoreReact
1e0ad6ca4495506b5e1c79ee4f59be140ab39c0f
[ "MIT" ]
1
2021-01-03T08:38:09.000Z
2021-01-03T08:38:09.000Z
import * as React from 'react' import * as ReactDOM from 'react-dom' import App from '../../home/AppComponent' import { mount } from 'enzyme' it('renders without crashing', () => { const div = document.createElement('div') ReactDOM.render(<App />, div) ReactDOM.unmountComponentAtNode(div) }) it('passed snapshot testing', () => { expect(mount(<App />)).toMatchSnapshot() })
27.428571
43
0.679688
e474188f7eb2b6db2d3224b571f65870ba583f22
4,310
rs
Rust
client/src/client.rs
oguzbilgener/noxious
c33f420c8aa9b46b23b1d5325d31ba3ec15e98e7
[ "Apache-2.0", "MIT" ]
47
2021-03-10T12:38:46.000Z
2022-03-22T09:14:34.000Z
client/src/client.rs
oguzbilgener/noxious
c33f420c8aa9b46b23b1d5325d31ba3ec15e98e7
[ "Apache-2.0", "MIT" ]
1
2021-11-02T21:20:00.000Z
2021-11-02T21:20:00.000Z
client/src/client.rs
oguzbilgener/noxious
c33f420c8aa9b46b23b1d5325d31ba3ec15e98e7
[ "Apache-2.0", "MIT" ]
null
null
null
use std::collections::HashMap; use crate::{ error::{ApiErrorResponse, ClientError}, proxy::Proxy, }; use noxious::proxy::{ProxyConfig, ProxyWithToxics}; use reqwest::{Client as HttpClient, Response, StatusCode}; /// A client for Noxious and Toxiproxy /// It follows the same naming conventions for the methods. #[derive(Debug)] pub struct Client { base_url: String, } // TODO: fix the error type pub type Result<T> = std::result::Result<T, ClientError>; impl Client { /// Create a new client /// /// Panics if the given url starts with `https://`. pub fn new(url: &str) -> Client { if url.starts_with("https://") { panic!("the toxiproxy client does not support https"); } let base_url = if !url.starts_with("http://") { format!("http://{}", url) } else { url.to_owned() }; Client { base_url } } /// Returns a proxy by name, if it already exists pub async fn proxy(&self, name: &str) -> Result<Proxy> { let res = HttpClient::new() .get(self.base_url.clone() + "/proxies/" + name) .send() .await?; if res.status().is_success() { Ok(Proxy::from_proxy_with_toxics( &self.base_url, res.json::<ProxyWithToxics>().await?, )) } else { Err(get_error_body(res, StatusCode::OK).await) } } /// Returns a map with all the proxies and their toxics pub async fn proxies(&self) -> Result<HashMap<String, Proxy>> { let res = HttpClient::new() .get(self.base_url.clone() + "/proxies") .send() .await?; if res.status().is_success() { Ok(res .json::<HashMap<String, ProxyWithToxics>>() .await? .into_iter() .map(|(name, proxy)| (name, Proxy::from_proxy_with_toxics(&self.base_url, proxy))) .collect()) } else { Err(get_error_body(res, StatusCode::OK).await) } } /// Instantiates a new proxy config, sends it to the server /// The server starts listening on the specified address pub async fn create_proxy(&self, name: &str, listen: &str, upstream: &str) -> Result<Proxy> { let mut proxy = Proxy::new(&self.base_url, name, listen, upstream); proxy.save().await?; Ok(proxy) } /// Create a list of proxies using a configuration list. If a proxy already exists, /// it will be replaced with the specified configuration. pub async fn populate(&self, proxies: &[ProxyConfig]) -> Result<Vec<Proxy>> { let res = HttpClient::new() .post(self.base_url.clone() + "/populate") .json(proxies) .send() .await?; if res.status().is_success() { Ok(res .json::<Vec<ProxyWithToxics>>() .await? .into_iter() .map(|item| Proxy::from_proxy_with_toxics(&self.base_url, item)) .collect::<Vec<Proxy>>()) } else { Err(get_error_body(res, StatusCode::CREATED).await) } } /// Resets the state of all proxies by removing all the toxic from all proxies pub async fn reset_state(&self) -> Result<()> { let res = HttpClient::new() .post(self.base_url.clone() + "/reset") .send() .await?; if res.status().is_success() { Ok(()) } else { Err(get_error_body(res, StatusCode::NO_CONTENT).await) } } } pub(crate) async fn get_error_body(res: Response, expected_status: StatusCode) -> ClientError { let code = res.status(); if let Ok(api_error) = res.json::<ApiErrorResponse>().await { ClientError::ApiError(api_error) } else { ClientError::UnexpectedStatusCode(code.into(), expected_status.into()) } } #[cfg(test)] mod tests { use super::*; #[test] #[should_panic] fn client_does_not_allow_https() { let _client = Client::new("https://blahblah"); } #[test] fn client_adds_protocol() { let client = Client::new("blahblah"); assert_eq!("http://blahblah", client.base_url); } }
31.459854
98
0.555684
a4a31771f65944e9739597e2b64e22c01cd88e6d
417
php
PHP
resources/views/freearticles/show_fields.blade.php
devyassinepro/blogpro
cf18ccd0c7aef0e7e5cf53332e1118b0a023d3d3
[ "MIT" ]
null
null
null
resources/views/freearticles/show_fields.blade.php
devyassinepro/blogpro
cf18ccd0c7aef0e7e5cf53332e1118b0a023d3d3
[ "MIT" ]
null
null
null
resources/views/freearticles/show_fields.blade.php
devyassinepro/blogpro
cf18ccd0c7aef0e7e5cf53332e1118b0a023d3d3
[ "MIT" ]
null
null
null
<!-- Id Field --> <div class="form-group"> {!! Form::label('id', 'Id:') !!} <p>{{ $freearticles->id }}</p> </div> <!-- Title Field --> <div class="form-group"> {!! Form::label('title', 'Title:') !!} <p>{{ $freearticles->title }}</p> </div> <!-- Description Field --> <div class="form-group"> {!! Form::label('description', 'Description:') !!} <p>{{ $freearticles->description }}</p> </div>
21.947368
54
0.517986
36c9f1abf987c5262d29f8cf069043f24dcfab9c
591
sh
Shell
.docker/gencrt.sh
magmaticlabs/obsidian
1cb1a8b66d5805f5a263b174dfec683aedca87f2
[ "MIT" ]
6
2019-06-07T21:26:32.000Z
2020-02-18T08:11:01.000Z
.docker/gencrt.sh
magmaticlabs/obsidian
1cb1a8b66d5805f5a263b174dfec683aedca87f2
[ "MIT" ]
1
2019-07-26T05:26:22.000Z
2019-07-26T05:26:22.000Z
.docker/gencrt.sh
magmaticlabs/obsidian
1cb1a8b66d5805f5a263b174dfec683aedca87f2
[ "MIT" ]
null
null
null
#!/bin/bash # Create the root key openssl genrsa -out nginx/rootCA.key 2048 # Create the root cert openssl req -x509 -new -nodes -key nginx/rootCA.key -sha256 -days 1024 -subj "/C=US/ST=NC/O=localhost/OU=localhost/CN=localhost" -out nginx/rootCA.pem # Create the CSR openssl req -new -nodes -out nginx/server.csr -newkey rsa:2048 -keyout nginx/server.key -subj "/C=US/ST=NC/O=localhost/OU=localhost/CN=localhost" # Create the cert openssl x509 -req -in nginx/server.csr -CA nginx/rootCA.pem -CAkey nginx/rootCA.key -CAcreateserial -out nginx/server.crt -days 500 -sha256 -extfile v3.ext
42.214286
155
0.751269
98c6356ebedbe885c1649fe8a67fb6f7406812b5
781
lua
Lua
sv_criminalDoctor.lua
itschip/chip_criminalDoctor
3b31f95945a55444e56807a12c1fc61a6f08fed2
[ "MIT" ]
4
2020-07-11T17:51:50.000Z
2022-01-05T18:17:13.000Z
sv_criminalDoctor.lua
itschip/chip_criminalDoctor
3b31f95945a55444e56807a12c1fc61a6f08fed2
[ "MIT" ]
null
null
null
sv_criminalDoctor.lua
itschip/chip_criminalDoctor
3b31f95945a55444e56807a12c1fc61a6f08fed2
[ "MIT" ]
3
2020-10-06T21:59:38.000Z
2021-07-27T20:37:00.000Z
ESX = nil TriggerEvent('esx:getSharedObject', function(obj) ESX = obj end) RegisterServerEvent("chip_cDoc:takeMoney") AddEventHandler("chip_cDoc:takeMoney", function() local _source = source local xPlayer = ESX.GetPlayerFromId(_source) if xPlayer.getMoney() > Config.toPay then xPlayer.removeMoney(Config.toPay) TriggerClientEvent("chip_cDoc:getHelp", source) else TriggerClientEvent('mythic_notify:client:SendAlert', source, { type = 'error', text = 'You dont have enough money', style = { ['background-color'] = '#ffffff', ['color'] = '#000000' } }) end end) RegisterCommand("fuckoff", function() local xPlayer = ESX.GetPlayerFromId(source) xPlayer.addMoney(4000) end)
30.038462
80
0.65557
bee78c314ffe5745683106ea650964cb8993faed
31
ts
TypeScript
src/components/CookieBanner/index.ts
jr-duboc/erreur-200
807d245ce90c9f6294ec6d1921748758b5bb1a11
[ "MIT" ]
1
2021-02-07T17:27:21.000Z
2021-02-07T17:27:21.000Z
src/components/CookieBanner/index.ts
jr-duboc/erreur-200
807d245ce90c9f6294ec6d1921748758b5bb1a11
[ "MIT" ]
8
2021-02-09T20:12:15.000Z
2022-01-31T12:02:46.000Z
src/components/CookieBanner/index.ts
jr-duboc/erreur-200
807d245ce90c9f6294ec6d1921748758b5bb1a11
[ "MIT" ]
1
2022-01-27T21:19:29.000Z
2022-01-27T21:19:29.000Z
export * from './CookieBanner'
15.5
30
0.709677
ccb37acfc76c157b1b3a858d6e6f43bceab0db56
2,549
swift
Swift
UnitTests/Generated/TypeErase.generated.swift
LaudateCorpus1/SourceryTemplates
faf42897266c43fac2a19e90ca473984c0aeec80
[ "MIT" ]
96
2017-05-15T01:17:25.000Z
2022-03-19T12:27:23.000Z
UnitTests/Generated/TypeErase.generated.swift
LaudateCorpus1/SourceryTemplates
faf42897266c43fac2a19e90ca473984c0aeec80
[ "MIT" ]
2
2017-05-18T23:03:39.000Z
2017-06-02T20:38:48.000Z
UnitTests/Generated/TypeErase.generated.swift
LaudateCorpus1/SourceryTemplates
faf42897266c43fac2a19e90ca473984c0aeec80
[ "MIT" ]
15
2017-05-16T20:58:38.000Z
2021-11-30T05:07:21.000Z
// Generated using Sourcery 0.13.1 — https://github.com/krzysztofzablocki/Sourcery // DO NOT EDIT // MARK: - Type Eraser for Pokemon private class _AnyPokemonBase<PokemonType>: Pokemon { init() { guard type(of: self) != _AnyPokemonBase.self else { fatalError("_AnyPokemonBase<PokemonType> instances can not be created; create a subclass instance instead") } } func attack(move: PokemonType) -> Void { fatalError("Must override") } } private final class _AnyPokemonBox<Concrete: Pokemon>: _AnyPokemonBase<Concrete.PokemonType> { var concrete: Concrete typealias PokemonType = Concrete.PokemonType init(_ concrete: Concrete) { self.concrete = concrete } override func attack(move: PokemonType) -> Void { return concrete.attack(move: move) } } final class AnyPokemon<PokemonType>: Pokemon { private let box: _AnyPokemonBase<PokemonType> init<Concrete: Pokemon>(_ concrete: Concrete) where Concrete.PokemonType == PokemonType { self.box = _AnyPokemonBox(concrete) } func attack(move: PokemonType) -> Void { return box.attack(move: move) } } // MARK: - Type Eraser for Row private class _AnyRowBase<Model>: Row { init() { guard type(of: self) != _AnyRowBase.self else { fatalError("_AnyRowBase<Model> instances can not be created; create a subclass instance instead") } } func configure(model: Model) -> Void { fatalError("Must override") } var sizeLabelText: String { get { fatalError("Must override") } set { fatalError("Must override") } } } private final class _AnyRowBox<Concrete: Row>: _AnyRowBase<Concrete.Model> { var concrete: Concrete typealias Model = Concrete.Model init(_ concrete: Concrete) { self.concrete = concrete } override func configure(model: Model) -> Void { return concrete.configure(model: model) } override var sizeLabelText: String { get { return concrete.sizeLabelText } set { concrete.sizeLabelText = newValue } } } final class AnyRow<Model>: Row { private let box: _AnyRowBase<Model> init<Concrete: Row>(_ concrete: Concrete) where Concrete.Model == Model { self.box = _AnyRowBox(concrete) } func configure(model: Model) -> Void { return box.configure(model: model) } var sizeLabelText: String { get { return box.sizeLabelText } set { box.sizeLabelText = newValue } } }
25.237624
119
0.651236
9690440647b512a252808f66c6c6d3ebfd94a099
1,866
lua
Lua
crosshair_built_in/client.lua
XenoS-ITA/crosshair_built_in
ef14aa3bc8cb2c7affbfe3e0cafc8353a3da0804
[ "MIT" ]
1
2022-02-18T11:54:25.000Z
2022-02-18T11:54:25.000Z
crosshair_built_in/client.lua
XenoS-ITA/crosshair_built_in
ef14aa3bc8cb2c7affbfe3e0cafc8353a3da0804
[ "MIT" ]
null
null
null
crosshair_built_in/client.lua
XenoS-ITA/crosshair_built_in
ef14aa3bc8cb2c7affbfe3e0cafc8353a3da0804
[ "MIT" ]
null
null
null
local resName = GetCurrentResourceName() local active = false Citizen.CreateThread(function() if GetResourceKvpString(resName..":checked") == "false" then active = true DisableDefaultCrosshair() end Citizen.Wait(500) SendNuiMessage(json.encode({ crosshair = GetResourceKvpString(resName..":crosshair"), checked = GetResourceKvpString(resName..":checked"), dimension = GetResourceKvpString(resName..":dimension") })) end) IsControlJustPressed("O", function() if not IsPauseMenuActive() then SendNuiMessage(json.encode({ active = true, crosshair = GetResourceKvpString(resName..":crosshair"), checked = GetResourceKvpString(resName..":checked"), dimension = GetResourceKvpString(resName..":dimension") })) SetNuiFocus(true, true) SetCursorLocation(0.1, 0.1) end end) RegisterNUICallback("disable", function() SendNuiMessage(json.encode({ active = false })) SetNuiFocus(false, false) end) RegisterNetEvent("crosshair:active", function(active) SendNuiMessage(json.encode({ active = active })) end) RegisterNUICallback("disable_dcross", function() active = true DisableDefaultCrosshair() end) RegisterNUICallback("enable_dcross", function() active = false end) RegisterNUICallback("save_data", function(data) SetResourceKvp(resName..":crosshair", tostring(data.crosshair)) SetResourceKvp(resName..":checked", tostring(data.checked)) SetResourceKvp(resName..":dimension", tostring(data.dimension)) end) function DisableDefaultCrosshair() Citizen.CreateThread(function() while active do HideHudComponentThisFrame(14) Citizen.Wait(4) end end) end
28.707692
69
0.651125
346f601f8635ff0a482b015ca7f93176f0a8f048
452
rs
Rust
src/types/mod.rs
lmy441900/iota-client-v2
33ca8fdb3d3318480011d108680794e235b0324a
[ "Apache-2.0" ]
null
null
null
src/types/mod.rs
lmy441900/iota-client-v2
33ca8fdb3d3318480011d108680794e235b0324a
[ "Apache-2.0" ]
null
null
null
src/types/mod.rs
lmy441900/iota-client-v2
33ca8fdb3d3318480011d108680794e235b0324a
[ "Apache-2.0" ]
null
null
null
//! Types used across the library. mod core; mod error; mod node; mod preset_node; // Exports. pub use self::core::*; pub use self::error::Error; pub use self::node::{Auth, Node}; pub use self::preset_node::PresetNode; /// The canonical [Result] type used across the library, with [Error] as the error type. /// /// [Result]: ::core::result::Result /// [Error]: self::error::Error pub type Result<T> = ::core::result::Result<T, self::error::Error>;
23.789474
88
0.676991
f9cd5764e431cd582246590fd0920deef0af150d
164
sql
SQL
medium/_05_err_x/cases/deriv3.sql
Zhaojia2019/cubrid-testcases
475a828e4d7cf74aaf2611fcf791a6028ddd107d
[ "BSD-3-Clause" ]
9
2016-03-24T09:51:52.000Z
2022-03-23T10:49:47.000Z
medium/_05_err_x/cases/deriv3.sql
Zhaojia2019/cubrid-testcases
475a828e4d7cf74aaf2611fcf791a6028ddd107d
[ "BSD-3-Clause" ]
173
2016-04-13T01:16:54.000Z
2022-03-16T07:50:58.000Z
medium/_05_err_x/cases/deriv3.sql
Zhaojia2019/cubrid-testcases
475a828e4d7cf74aaf2611fcf791a6028ddd107d
[ "BSD-3-Clause" ]
38
2016-03-24T17:10:31.000Z
2021-10-30T22:55:45.000Z
autocommit off; select * from product_v p , (select baa.code from inventory_v i where p.product_code=i.product_code) as baa(code); rollback;
20.5
58
0.670732
a16f5f7b96b81304430feceb97b2a7198fc42bf1
813
tsx
TypeScript
frontend/src/site/HomePage.tsx
credo-science/credo-classify
1cc5e00a4df36c4069c0d0fbc19f579780b79ca5
[ "MIT" ]
null
null
null
frontend/src/site/HomePage.tsx
credo-science/credo-classify
1cc5e00a4df36c4069c0d0fbc19f579780b79ca5
[ "MIT" ]
8
2021-03-30T12:52:01.000Z
2022-03-12T00:19:45.000Z
frontend/src/site/HomePage.tsx
credo-science/credo-classify
1cc5e00a4df36c4069c0d0fbc19f579780b79ca5
[ "MIT" ]
1
2020-06-12T13:29:34.000Z
2020-06-12T13:29:34.000Z
import React from "react"; import { Jumbotron } from "react-bootstrap"; import { useI18n } from "../utils"; import { Link } from "react-router-dom"; const HomePage: React.FC = () => { const _ = useI18n(); return ( <Jumbotron> <h1 className="display-4">{_("home.title")}</h1> <p className="lead">{_("home.lead")}</p> <hr className="my-4" /> <p>{_("home.description")}</p> <div className="text-center"> <Link to="/classify" className="btn btn-lg btn-success mb-4"> {_("home.classify")} </Link> <br /> <a className="btn btn-primary btn-lg" href="https://credo.science/" role="button" target="_blank" rel="noopener noreferrer"> {_("home.website")} </a> </div> </Jumbotron> ); }; export default HomePage;
28.034483
132
0.567036
14500b88030086e25e4d015a46767c500e2d812d
245
ts
TypeScript
apps/api-server/src/enums/WriteRoomPublicMessageFailureType.ts
flocon-trpg/servers
5f6ed37c7db5b10e163904b2b9f3858c96264658
[ "MIT" ]
5
2021-12-10T04:33:15.000Z
2022-02-22T03:22:58.000Z
apps/api-server/src/enums/WriteRoomPublicMessageFailureType.ts
flocon-trpg/servers
5f6ed37c7db5b10e163904b2b9f3858c96264658
[ "MIT" ]
65
2021-11-03T22:41:41.000Z
2022-03-19T18:43:46.000Z
apps/api-server/src/enums/WriteRoomPublicMessageFailureType.ts
flocon-trpg/servers
5f6ed37c7db5b10e163904b2b9f3858c96264658
[ "MIT" ]
1
2021-12-17T09:25:03.000Z
2021-12-17T09:25:03.000Z
export enum WriteRoomPublicMessageFailureType { RoomNotFound = 'RoomNotFound', NotAuthorized = 'NotAuthorized', NotParticipant = 'NotParticipant', NotAllowedChannelKey = 'NotAllowedChannelKey', SyntaxError = 'SyntaxError', }
30.625
50
0.746939
a3e81727e903d0e5f4a86e30d70b533a85a40f63
8,720
java
Java
tangram/src/main/java/com/tmall/wireless/tangram3/support/async/CardLoadSupport.java
SubinVane/Tangram-Android
90f85a121d0625236ba95f2853b7224d177dd921
[ "MIT" ]
1
2020-06-16T09:12:02.000Z
2020-06-16T09:12:02.000Z
tangram/src/main/java/com/tmall/wireless/tangram3/support/async/CardLoadSupport.java
SubinVane/Tangram-Android
90f85a121d0625236ba95f2853b7224d177dd921
[ "MIT" ]
null
null
null
tangram/src/main/java/com/tmall/wireless/tangram3/support/async/CardLoadSupport.java
SubinVane/Tangram-Android
90f85a121d0625236ba95f2853b7224d177dd921
[ "MIT" ]
null
null
null
/* * MIT License * * Copyright (c) 2018 Alibaba Group * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.tmall.wireless.tangram3.support.async; import com.tmall.wireless.tangram3.TangramEngine; import com.tmall.wireless.tangram3.dataparser.concrete.Card; import com.tmall.wireless.tangram3.structure.BaseCell; import java.util.List; import io.reactivex.Observable; import io.reactivex.ObservableEmitter; import io.reactivex.ObservableOnSubscribe; import io.reactivex.functions.Action; import io.reactivex.functions.Consumer; import io.reactivex.functions.Predicate; /** * A helper class supports loading data of a card */ public class CardLoadSupport { private static int sInitialPage = 1; public static void setInitialPage(int initialPage) { sInitialPage = initialPage; } private AsyncPageLoader mAsyncPageLoader; private AsyncLoader mAsyncLoader; public CardLoadSupport() {} /** * construct with a custom {@link AsyncLoader} * @param loader custom loader */ public CardLoadSupport(AsyncLoader loader) { this(loader, null); } /** * construct with a custom {@link AsyncPageLoader} * @param loader custom page loader */ public CardLoadSupport(AsyncPageLoader loader) { this(null, loader); } /** * construct with a custom {@link AsyncLoader} and a custom {@link AsyncPageLoader} * @param loader custom loader * @param pageLoader custom page loader */ public CardLoadSupport(AsyncLoader loader, AsyncPageLoader pageLoader) { this.mAsyncLoader = loader; this.mAsyncPageLoader = pageLoader; } public void replaceLoader(AsyncLoader loader) { this.mAsyncLoader = loader; } public void replaceLoader(AsyncPageLoader pageLoader) { this.mAsyncPageLoader = pageLoader; } public void replaceLoader(AsyncLoader loader, AsyncPageLoader pageLoader) { this.mAsyncLoader = loader; this.mAsyncPageLoader = pageLoader; } /** * start load data for a card, usually called by {@link TangramEngine} * @param card the card need async loading data */ public void doLoad(final Card card) { if (mAsyncLoader == null) { return; } if (!card.loading && !card.loaded) { card.loading = true; mAsyncLoader.loadData(card, new AsyncLoader.LoadedCallback() { @Override public void finish() { card.loading = false; card.loaded = true; } @Override public void finish(List<BaseCell> cells) { finish(); card.addCells(cells); card.notifyDataChange(); } public void fail(boolean loaded) { card.loading = false; card.loaded = loaded; } }); } } /** * start load data with paging for a card, usually called by {@link TangramEngine} * @param card the card need async loading data */ public void loadMore(final Card card) { if (mAsyncPageLoader == null) { return; } if (!card.loading && card.loadMore && card.hasMore) { card.loading = true; if (!card.loaded) { card.page = sInitialPage; } mAsyncPageLoader.loadData(card.page, card, new AsyncPageLoader.LoadedCallback() { @Override public void finish(boolean hasMore) { card.loaded = true; card.loading = false; card.page++; card.hasMore = hasMore; } @Override public void finish(List<BaseCell> cells, boolean hasMore) { if (card.page == sInitialPage) { card.setCells(cells); } else { card.addCells(cells); } finish(hasMore); card.notifyDataChange(); } @Override public void fail(boolean retry) { card.loaded = true; card.loading = false; card.hasMore = retry; } }); } } private Observable<Card> mLoadCardObservable; private Observable<Card> mLoadMoreCardObservable; private ObservableEmitter<Card> mLoadCardObserver; private ObservableEmitter<Card> mLoadMoreObserver; /** * * @return An observable start loading a card */ public Observable<Card> observeCardLoading() { if (mLoadCardObservable == null) { mLoadCardObservable = Observable.create(new ObservableOnSubscribe<Card>() { @Override public void subscribe(ObservableEmitter<Card> emitter) throws Exception { mLoadCardObserver = emitter; } }).filter(new Predicate<Card>() { @Override public boolean test(Card card) throws Exception { return !card.loading && !card.loaded; } }).doOnNext(new Consumer<Card>() { @Override public void accept(Card card) throws Exception { card.loading = true; } }).doOnDispose(new Action() { @Override public void run() throws Exception { mLoadCardObserver = null; } }); } return mLoadCardObservable; } /** * Start to load data for a card, usually called by {@link TangramEngine} * @param card the card need reactively loading data */ public void reactiveDoLoad(Card card) { if (mLoadCardObserver == null) { return; } mLoadCardObserver.onNext(card); } /** * * @return An observable start loading more for a card */ public Observable<Card> observeCardLoadingMore() { if (mLoadMoreCardObservable == null) { mLoadMoreCardObservable = Observable.create(new ObservableOnSubscribe<Card>() { @Override public void subscribe(ObservableEmitter<Card> emitter) throws Exception { mLoadMoreObserver = emitter; } }).filter(new Predicate<Card>() { @Override public boolean test(Card card) throws Exception { return !card.loading && card.loadMore && card.hasMore; } }).doOnNext(new Consumer<Card>() { @Override public void accept(Card card) throws Exception { card.loading = true; if (!card.loaded) { card.page = sInitialPage; } } }).doOnDispose(new Action() { @Override public void run() throws Exception { mLoadMoreObserver = null; } }); } return mLoadMoreCardObservable; } /** * Start to load more data for a card, usually called by {@link TangramEngine} * @param card the card need reactively loading data */ public void reactiveDoLoadMore(Card card) { if (mLoadMoreObserver == null) { return; } mLoadMoreObserver.onNext(card); } }
32.177122
93
0.572477
d0586b91c9610e5377da9c79d103b39b507b5ff8
1,732
cpp
C++
src/napc-core/HAL/arduino/HAL_napc_getFreeMemory.cpp
nap-software/libnapc-arduino-releases
f8f4447422b38ee7e8bb494e341cea7e64d03f02
[ "MIT" ]
null
null
null
src/napc-core/HAL/arduino/HAL_napc_getFreeMemory.cpp
nap-software/libnapc-arduino-releases
f8f4447422b38ee7e8bb494e341cea7e64d03f02
[ "MIT" ]
null
null
null
src/napc-core/HAL/arduino/HAL_napc_getFreeMemory.cpp
nap-software/libnapc-arduino-releases
f8f4447422b38ee7e8bb494e341cea7e64d03f02
[ "MIT" ]
null
null
null
/* * MIT License * * Copyright (c) 2022 nap.software * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #if defined(ARDUINO) extern "C" { #include <napc-core/_private/_napc-core.h> #ifdef __arm__ // should use uinstd.h to define sbrk but Due causes a conflict extern "C" char* sbrk(int incr); #else // __ARM__ extern char *__brkval; #endif // __arm__ napc_size HAL_napc_getFreeMemory(void) { char top; #ifdef __arm__ return &top - reinterpret_cast<char*>(sbrk(0)); #elif defined(CORE_TEENSY) || (ARDUINO > 103 && ARDUINO != 151) return &top - __brkval; #else // __arm__ return __brkval ? &top - __brkval : &top - __malloc_heap_start; #endif // __arm__ } } #endif
36.851064
80
0.729215
b0bc973f2a51a87bf18f8614c9fcb313b63606ab
62
py
Python
wsgi.py
yoophi/flask-login-sample
ae76e2c396896f99b1ba8add44c752d5abc22c01
[ "MIT" ]
null
null
null
wsgi.py
yoophi/flask-login-sample
ae76e2c396896f99b1ba8add44c752d5abc22c01
[ "MIT" ]
null
null
null
wsgi.py
yoophi/flask-login-sample
ae76e2c396896f99b1ba8add44c752d5abc22c01
[ "MIT" ]
null
null
null
from flask_login_sample import create_app app = create_app()
15.5
41
0.822581
15bfd6c2bfb3339d52db67022e6ce7987787b412
44
rb
Ruby
lib/state_machine-mongoid.rb
martinciu/state_machine-mongoid
33cc3103d0308058735af71f464e786da257e290
[ "MIT" ]
1
2015-11-05T15:24:07.000Z
2015-11-05T15:24:07.000Z
lib/state_machine-mongoid.rb
martinciu/state_machine-mongoid
33cc3103d0308058735af71f464e786da257e290
[ "MIT" ]
null
null
null
lib/state_machine-mongoid.rb
martinciu/state_machine-mongoid
33cc3103d0308058735af71f464e786da257e290
[ "MIT" ]
null
null
null
require 'state_machine/integrations/mongoid'
44
44
0.886364
7bcf92faf4120d40cff902712e7f64451cdc89aa
93
cpp
C++
tools/stb_image.cpp
ShirokoSama/ShadingSandbox
b407aea1c018bcb46061f3d165c9671d2cb3c139
[ "MIT" ]
null
null
null
tools/stb_image.cpp
ShirokoSama/ShadingSandbox
b407aea1c018bcb46061f3d165c9671d2cb3c139
[ "MIT" ]
null
null
null
tools/stb_image.cpp
ShirokoSama/ShadingSandbox
b407aea1c018bcb46061f3d165c9671d2cb3c139
[ "MIT" ]
1
2019-12-05T11:50:24.000Z
2019-12-05T11:50:24.000Z
// // Created by Srf on 2017/10/5. // #define STB_IMAGE_IMPLEMENTATION #include "stb_image.h"
18.6
32
0.731183
e24082ed5aff5ab1870b55dfa05dc96db817674d
1,613
js
JavaScript
www/service-worker.js
ahmedavid/dwHeroku
26c216ff1017619d1a9b405a78002cefcb776d04
[ "MIT" ]
null
null
null
www/service-worker.js
ahmedavid/dwHeroku
26c216ff1017619d1a9b405a78002cefcb776d04
[ "MIT" ]
null
null
null
www/service-worker.js
ahmedavid/dwHeroku
26c216ff1017619d1a9b405a78002cefcb776d04
[ "MIT" ]
null
null
null
// /** // * Check out https://googlechrome.github.io/sw-toolbox/ for // * more info on how to use sw-toolbox to custom configure your service worker. // */ // // // 'use strict'; // importScripts('./build/sw-toolbox.js'); // // self.toolbox.options.cache = { // name: 'ionic-cache' // }; // // // pre-cache our key assets // self.toolbox.precache( // [ // '/**/*', // './build/main.js', // './build/main.css', // './build/polyfills.js', // 'index.html', // 'manifest.json' // ] // ); // // // // // dynamically cache any other local assets // self.toolbox.router.any('/*', self.toolbox.cacheFirst); // // // for any other requests go to the network, cache, // // and then only use that cached resource if your user goes offline // self.toolbox.router.default = self.toolbox.networkFirst; self.addEventListener('install', function(event) { event.waitUntil( caches.open('dwAppCache').then(function(cache) { var precache_urls =[ '/', './build/main.js', './build/0.js', './build/1.js', './build/2.js', './build/main.css', './build/polyfills.js', 'index.html', 'manifest.json' ]; return cache.addAll(precache_urls); }) ); }); self.addEventListener('fetch', function(event) { console.log(event.request.url); event.request.url = event.request.url.replace(/^https:\/\//i, 'http://'); event.respondWith( caches.match(event.request).then(function(response) { return response || fetch(event.request).then(function(response) { cache.addAll(response); }); }) ); });
23.720588
81
0.591445
339ee8dd4f70adbf16f3b63fea947d43f858dc97
6,103
c
C
multiProcess_pipeComm_task2/utils.c
Nikoletos-K/Disease-Monitor
e1cf0c971276887fc8b1c639b2bea8dd13fba20f
[ "MIT" ]
1
2021-03-11T18:35:31.000Z
2021-03-11T18:35:31.000Z
multiProcess_pipeComm_task2/utils.c
Nikoletos-K/Disease-Monitor
e1cf0c971276887fc8b1c639b2bea8dd13fba20f
[ "MIT" ]
null
null
null
multiProcess_pipeComm_task2/utils.c
Nikoletos-K/Disease-Monitor
e1cf0c971276887fc8b1c639b2bea8dd13fba20f
[ "MIT" ]
null
null
null
#include <stdio.h> #include <stdlib.h> #include <string.h> #include "utils.h" int input(char * inputStr){ if(!strcmp(inputStr,"-w")) return w; else if(!strcmp(inputStr,"-b")) return b; else if(!strcmp(inputStr,"-i")) return i; else return inputError; } int Prompt(char * inputStr){ if(inputStr==NULL) return NO_INPUT; if(!strcmp(inputStr,"/listCountries") || !strcmp(inputStr,"1")) return LIST; else if(!strcmp(inputStr,"/diseaseFrequency") || !strcmp(inputStr,"2")) return DISEASE_FREQUENCY; else if(!strcmp(inputStr,"/topk-AgeRanges") || !strcmp(inputStr,"3")) return TOPK_AGE_RANGES; else if(!strcmp(inputStr,"/searchPatientRecord") || !strcmp(inputStr,"5")) return SEARCH_PATIENT; else if(!strcmp(inputStr,"/numPatientDischarges") || !strcmp(inputStr,"6")) return NUM_PDISCHARGES; else if(!strcmp(inputStr,"/numPatientAdmissions") || !strcmp(inputStr,"7")) return NUM_PADMISSIONS; else if(!strcmp(inputStr,"/exit") || !strcmp(inputStr,"x")) return EXIT; else return ERROR; } int errorHandler(int errorCode,char * errorStr){ char * error = "\n\tERROR:" ; if(errorStr!=NULL){ printf("%s %s \n",error,errorStr); return noError; } switch(errorCode){ case inputError: printf("%s Execution arguments doesn't correspond to the project \n",error); printf(" Suggested command: ./diseaseMonitor -p patientRecordsFile -h1 diseaseHashTableNumOfEntries -h2 HashTableNumOfEntries -b bucketSize \n"); break; case commandLine: printf("%s Missing or wrong arguments in execution command \n",error); exit(1); break; case dateMissing: printf("%s Command can not be executed with only one date\n",error); break; case noError: break; } return noError; } int dateCompare(const void * date1,const void * date2){ // compares two dates char * d1 = *(char**) date1; char * d2 = *(char**) date2; if(!strcmp(date2,"-")) return 0; char *token; int d[2],m[2],y[2]; for(int i=0;i<2;i++){ int t=0; char buffer[20]; if(i==0) strcpy(buffer,d1); else strcpy(buffer,d2); token = strtok(buffer,"-"); while(token!=NULL){ if(t==0) d[i] = atoi(token); else if(t==1) m[i] = atoi(token); else if(t==2) y[i] = atoi(token); token = strtok(NULL,"-"); t++; } } if(y[0]>y[1]) return 1; else if(y[0]<y[1]) return -1; else{ if(m[0]>m[1]) return 1; else if(m[0]<m[1]) return -1; else{ if(d[0]>d[1]) return 1; else if(d[0]<d[1]) return -1; else return 0; } } } int dateExists(char * date1){ // checks if a date exists logically if(!strcmp(date1,"-")) return 1; char buffer[DATE_BUFFER]; int d1,m1; strcpy(buffer,date1); strtok(buffer,"-"); d1 = atoi(buffer); if(d1>31 || d1<1) return 0; strcpy(buffer,date1+3); strtok(buffer,"-"); m1 = atoi(buffer); if(m1>12 || m1<1) return 0; return 1; } int integerComparator(void* v1,void* v2){ return *((int*) v1) - *((int*) v2); } int stringComparator(void * v1,void * v2){ return strcmp((char*)v1,(char*)v2); } void printOptions(){ printf("System utilities:\n"); printf("1./listCountries\n"); printf("2./diseaseFrequency\n"); printf("3./topk-AgeRanges\n"); printf("4./searchPatientRecord\n"); printf("5./numPatientAdmissions\n"); printf("6./numPatientDischarges\n"); printf("7./exit\n"); } npipe_connection * create_pipeConnection(int index){ char fifoname[20] = "NAMED_PIPE|"; char process_index[20]; sprintf(process_index,"%d",index); strcat(fifoname,process_index); npipe_connection * new = malloc(sizeof(npipe_connection)); new->connection_names = malloc(2*sizeof(char *)); new->index = index; new->pipe_filedesc = malloc(2*sizeof(int)); new->subdirectories = malloc(sizeof(char*)); new->subdirs_concat = NULL; new->numOfSubdirs = 0; for(int i=0;i<2;i++){ char buffer[20]; strcpy(buffer,fifoname); if(i==PARENT){ strcat(buffer,"|PARENT"); new->connection_names[PARENT] = strdup(buffer); }else{ strcat(buffer,"|CHILD"); new->connection_names[CHILD] = strdup(buffer); } if(mkfifo(buffer,0666)==-1 && (errno!=EEXIST)){ fprintf(stderr,"Named pipe %s creation failed\n",buffer); exit(1); } } return new; } void set_pid(pid_t pid,npipe_connection * pipe){ pipe->pid = pid; } void destroy_pipeConnection(npipe_connection * pipe){ for(int i=0;i<2;i++){ remove(pipe->connection_names[i]); free(pipe->connection_names[i]); } free(pipe->subdirectories); free(pipe->subdirs_concat); free(pipe->connection_names); free(pipe->pipe_filedesc); free(pipe); } void insert_subdirectory(npipe_connection * pipe,char *subdirectory){ pipe->subdirectories = realloc(pipe->subdirectories,(pipe->numOfSubdirs+1)*sizeof(char*)); pipe->subdirectories[pipe->numOfSubdirs] = subdirectory; pipe->numOfSubdirs++; if(pipe->subdirs_concat==NULL){ pipe->subdirs_concat = malloc((strlen(subdirectory)+2)*sizeof(char)); strcpy(pipe->subdirs_concat,subdirectory); strcat(pipe->subdirs_concat,"%"); }else{ pipe->subdirs_concat = realloc(pipe->subdirs_concat,(strlen(pipe->subdirs_concat)+strlen(subdirectory)+2)*sizeof(char)); strcat(pipe->subdirs_concat,subdirectory); strcat(pipe->subdirs_concat,"%"); } } int onlyLettersandNumbers(char * str){ int i=0; while(str[i]!='\0'){ if(str[i]>='0' && str[i]<='9') i++; else if(str[i]>='a' && str[i]<='z') i++; else if(str[i]>='A' && str[i]<='Z') i++; else return 0; } return 1; } char * insertSizetoMessage(char * str,int size){ char tempBuffer[100]; sprintf(tempBuffer,"%d",size); strcat(tempBuffer,"%"); size = strlen(str)+strlen(tempBuffer)+1; str = realloc(str,(strlen(str)+strlen(tempBuffer)+1)*sizeof(char)); char * temp = strdup(str); strcpy(str,tempBuffer); strcat(str,temp); free(temp); return str; } void printInteger(void * i){ printf("%d\n",*(int*)i); } void printString(void * i){ printf("%s\n",(char*)i); } void getCountry(char * path,char * country){ char * token; token = strtok(path,"/"); while(token!=NULL){ strcpy(country,token); token = strtok(NULL,"/"); if(token==NULL) break; country[0] = '\0'; } }
22.192727
148
0.656071
06abd83c3dad840e73ad92563d65ec64c7de44b3
158
lua
Lua
world/Plugins/Docker/error.lua
yangchuansheng/dockercraft
b606ddae081a2c461de243f3a0c0acaa9103df9c
[ "Apache-2.0" ]
119
2015-11-24T04:29:15.000Z
2022-03-23T06:43:14.000Z
world/Plugins/Docker/error.lua
rtannert/dockercraft
520171a32a84bad7bbd2eb5cc27ab0166b46bbc4
[ "Apache-2.0" ]
1
2016-05-26T21:47:38.000Z
2016-05-26T21:47:38.000Z
world/Plugins/Docker/error.lua
rtannert/dockercraft
520171a32a84bad7bbd2eb5cc27ab0166b46bbc4
[ "Apache-2.0" ]
16
2016-09-26T07:38:00.000Z
2022-01-07T21:15:37.000Z
-- NewError returns an error object. -- An error has a code and a message function NewError(code, message) err = {code=code, message=message} return err end
26.333333
36
0.746835
23c075124eb1c4544cce52a637bdf685f17f4e0a
676
js
JavaScript
js/components/Article/__tests__/Article-test.js
everdimension/relay-newslist
b73398094c98feb2e7beeb49698db4e1c42ed116
[ "BSD-3-Clause" ]
null
null
null
js/components/Article/__tests__/Article-test.js
everdimension/relay-newslist
b73398094c98feb2e7beeb49698db4e1c42ed116
[ "BSD-3-Clause" ]
null
null
null
js/components/Article/__tests__/Article-test.js
everdimension/relay-newslist
b73398094c98feb2e7beeb49698db4e1c42ed116
[ "BSD-3-Clause" ]
null
null
null
import React from 'react'; import { expect } from 'chai'; import { shallow } from 'enzyme'; import Article from '../Article'; describe('Article', () => { const mockArticle = { title: 'rnd', id: '1', content: 'rnd', type: 'rnd', }; it('renders with an .Article class', () => { const wrapper = shallow(<Article article={mockArticle} />); expect(wrapper.find('.Article')).to.have.length(1); }); it('renders article\'s content in a paragraph', () => { const wrapper = shallow(<Article article={mockArticle} />); expect(wrapper.find('p')).to.have.length(1); expect(wrapper.find('p').text()).to.equal(mockArticle.content); }); });
27.04
67
0.609467
db4173158968d81e6da1b7b4073218d7569122e5
11,042
sql
SQL
contrib/tablefunc/sql/tablefunc.sql
credativ/postgresql-lts
e74962afb643a2e0798fabffe941557470775d49
[ "PostgreSQL" ]
2
2015-01-30T06:26:26.000Z
2017-11-04T14:42:58.000Z
contrib/tablefunc/sql/tablefunc.sql
credativ/postgresql-lts
e74962afb643a2e0798fabffe941557470775d49
[ "PostgreSQL" ]
null
null
null
contrib/tablefunc/sql/tablefunc.sql
credativ/postgresql-lts
e74962afb643a2e0798fabffe941557470775d49
[ "PostgreSQL" ]
null
null
null
-- -- first, define the functions. Turn off echoing so that expected file -- does not depend on contents of tablefunc.sql. -- SET client_min_messages = warning; \set ECHO none \i tablefunc.sql \set ECHO all RESET client_min_messages; -- -- normal_rand() -- no easy way to do this for regression testing -- SELECT avg(normal_rand)::int FROM normal_rand(100, 250, 0.2); -- -- crosstab() -- CREATE TABLE ct(id int, rowclass text, rowid text, attribute text, val text); \copy ct from 'data/ct.data' SELECT * FROM crosstab2('SELECT rowid, attribute, val FROM ct where rowclass = ''group1'' and (attribute = ''att2'' or attribute = ''att3'') ORDER BY 1,2;'); SELECT * FROM crosstab3('SELECT rowid, attribute, val FROM ct where rowclass = ''group1'' and (attribute = ''att2'' or attribute = ''att3'') ORDER BY 1,2;'); SELECT * FROM crosstab4('SELECT rowid, attribute, val FROM ct where rowclass = ''group1'' and (attribute = ''att2'' or attribute = ''att3'') ORDER BY 1,2;'); SELECT * FROM crosstab2('SELECT rowid, attribute, val FROM ct where rowclass = ''group1'' ORDER BY 1,2;'); SELECT * FROM crosstab3('SELECT rowid, attribute, val FROM ct where rowclass = ''group1'' ORDER BY 1,2;'); SELECT * FROM crosstab4('SELECT rowid, attribute, val FROM ct where rowclass = ''group1'' ORDER BY 1,2;'); SELECT * FROM crosstab2('SELECT rowid, attribute, val FROM ct where rowclass = ''group2'' and (attribute = ''att1'' or attribute = ''att2'') ORDER BY 1,2;'); SELECT * FROM crosstab3('SELECT rowid, attribute, val FROM ct where rowclass = ''group2'' and (attribute = ''att1'' or attribute = ''att2'') ORDER BY 1,2;'); SELECT * FROM crosstab4('SELECT rowid, attribute, val FROM ct where rowclass = ''group2'' and (attribute = ''att1'' or attribute = ''att2'') ORDER BY 1,2;'); SELECT * FROM crosstab2('SELECT rowid, attribute, val FROM ct where rowclass = ''group2'' ORDER BY 1,2;'); SELECT * FROM crosstab3('SELECT rowid, attribute, val FROM ct where rowclass = ''group2'' ORDER BY 1,2;'); SELECT * FROM crosstab4('SELECT rowid, attribute, val FROM ct where rowclass = ''group2'' ORDER BY 1,2;'); SELECT * FROM crosstab('SELECT rowid, attribute, val FROM ct where rowclass = ''group1'' ORDER BY 1,2;') AS c(rowid text, att1 text, att2 text); SELECT * FROM crosstab('SELECT rowid, attribute, val FROM ct where rowclass = ''group1'' ORDER BY 1,2;') AS c(rowid text, att1 text, att2 text, att3 text); SELECT * FROM crosstab('SELECT rowid, attribute, val FROM ct where rowclass = ''group1'' ORDER BY 1,2;') AS c(rowid text, att1 text, att2 text, att3 text, att4 text); -- check it works with OUT parameters, too CREATE FUNCTION crosstab_out(text, OUT rowid text, OUT att1 text, OUT att2 text, OUT att3 text) RETURNS setof record AS '$libdir/tablefunc','crosstab' LANGUAGE C STABLE STRICT; SELECT * FROM crosstab_out('SELECT rowid, attribute, val FROM ct where rowclass = ''group1'' ORDER BY 1,2;'); -- -- hash based crosstab -- create table cth(id serial, rowid text, rowdt timestamp, attribute text, val text); insert into cth values(DEFAULT,'test1','01 March 2003','temperature','42'); insert into cth values(DEFAULT,'test1','01 March 2003','test_result','PASS'); -- the next line is intentionally left commented and is therefore a "missing" attribute -- insert into cth values(DEFAULT,'test1','01 March 2003','test_startdate','28 February 2003'); insert into cth values(DEFAULT,'test1','01 March 2003','volts','2.6987'); insert into cth values(DEFAULT,'test2','02 March 2003','temperature','53'); insert into cth values(DEFAULT,'test2','02 March 2003','test_result','FAIL'); insert into cth values(DEFAULT,'test2','02 March 2003','test_startdate','01 March 2003'); insert into cth values(DEFAULT,'test2','02 March 2003','volts','3.1234'); -- next group tests for NULL rowids insert into cth values(DEFAULT,NULL,'25 October 2007','temperature','57'); insert into cth values(DEFAULT,NULL,'25 October 2007','test_result','PASS'); insert into cth values(DEFAULT,NULL,'25 October 2007','test_startdate','24 October 2007'); insert into cth values(DEFAULT,NULL,'25 October 2007','volts','1.41234'); -- return attributes as plain text SELECT * FROM crosstab( 'SELECT rowid, rowdt, attribute, val FROM cth ORDER BY 1', 'SELECT DISTINCT attribute FROM cth ORDER BY 1') AS c(rowid text, rowdt timestamp, temperature text, test_result text, test_startdate text, volts text); -- this time without rowdt SELECT * FROM crosstab( 'SELECT rowid, attribute, val FROM cth ORDER BY 1', 'SELECT DISTINCT attribute FROM cth ORDER BY 1') AS c(rowid text, temperature text, test_result text, test_startdate text, volts text); -- convert attributes to specific datatypes SELECT * FROM crosstab( 'SELECT rowid, rowdt, attribute, val FROM cth ORDER BY 1', 'SELECT DISTINCT attribute FROM cth ORDER BY 1') AS c(rowid text, rowdt timestamp, temperature int4, test_result text, test_startdate timestamp, volts float8); -- source query and category query out of sync SELECT * FROM crosstab( 'SELECT rowid, rowdt, attribute, val FROM cth ORDER BY 1', 'SELECT DISTINCT attribute FROM cth WHERE attribute IN (''temperature'',''test_result'',''test_startdate'') ORDER BY 1') AS c(rowid text, rowdt timestamp, temperature int4, test_result text, test_startdate timestamp); -- if category query generates no rows, get expected error SELECT * FROM crosstab( 'SELECT rowid, rowdt, attribute, val FROM cth ORDER BY 1', 'SELECT DISTINCT attribute FROM cth WHERE attribute = ''a'' ORDER BY 1') AS c(rowid text, rowdt timestamp, temperature int4, test_result text, test_startdate timestamp, volts float8); -- if category query generates more than one column, get expected error SELECT * FROM crosstab( 'SELECT rowid, rowdt, attribute, val FROM cth ORDER BY 1', 'SELECT DISTINCT rowdt, attribute FROM cth ORDER BY 2') AS c(rowid text, rowdt timestamp, temperature int4, test_result text, test_startdate timestamp, volts float8); -- if source query returns zero rows, get zero rows returned SELECT * FROM crosstab( 'SELECT rowid, rowdt, attribute, val FROM cth WHERE false ORDER BY 1', 'SELECT DISTINCT attribute FROM cth ORDER BY 1') AS c(rowid text, rowdt timestamp, temperature text, test_result text, test_startdate text, volts text); -- if source query returns zero rows, get zero rows returned even if category query generates no rows SELECT * FROM crosstab( 'SELECT rowid, rowdt, attribute, val FROM cth WHERE false ORDER BY 1', 'SELECT DISTINCT attribute FROM cth WHERE false ORDER BY 1') AS c(rowid text, rowdt timestamp, temperature text, test_result text, test_startdate text, volts text); -- check it works with a named result rowtype create type my_crosstab_result as ( rowid text, rowdt timestamp, temperature int4, test_result text, test_startdate timestamp, volts float8); CREATE FUNCTION crosstab_named(text, text) RETURNS setof my_crosstab_result AS '$libdir/tablefunc','crosstab_hash' LANGUAGE C STABLE STRICT; SELECT * FROM crosstab_named( 'SELECT rowid, rowdt, attribute, val FROM cth ORDER BY 1', 'SELECT DISTINCT attribute FROM cth ORDER BY 1'); -- check it works with OUT parameters CREATE FUNCTION crosstab_out(text, text, OUT rowid text, OUT rowdt timestamp, OUT temperature int4, OUT test_result text, OUT test_startdate timestamp, OUT volts float8) RETURNS setof record AS '$libdir/tablefunc','crosstab_hash' LANGUAGE C STABLE STRICT; SELECT * FROM crosstab_out( 'SELECT rowid, rowdt, attribute, val FROM cth ORDER BY 1', 'SELECT DISTINCT attribute FROM cth ORDER BY 1'); -- -- connectby -- -- test connectby with text based hierarchy CREATE TABLE connectby_text(keyid text, parent_keyid text, pos int); \copy connectby_text from 'data/connectby_text.data' -- with branch, without orderby SELECT * FROM connectby('connectby_text', 'keyid', 'parent_keyid', 'row2', 0, '~') AS t(keyid text, parent_keyid text, level int, branch text); -- without branch, without orderby SELECT * FROM connectby('connectby_text', 'keyid', 'parent_keyid', 'row2', 0) AS t(keyid text, parent_keyid text, level int); -- with branch, with orderby SELECT * FROM connectby('connectby_text', 'keyid', 'parent_keyid', 'pos', 'row2', 0, '~') AS t(keyid text, parent_keyid text, level int, branch text, pos int) ORDER BY t.pos; -- without branch, with orderby SELECT * FROM connectby('connectby_text', 'keyid', 'parent_keyid', 'pos', 'row2', 0) AS t(keyid text, parent_keyid text, level int, pos int) ORDER BY t.pos; -- test connectby with int based hierarchy CREATE TABLE connectby_int(keyid int, parent_keyid int); \copy connectby_int from 'data/connectby_int.data' -- with branch SELECT * FROM connectby('connectby_int', 'keyid', 'parent_keyid', '2', 0, '~') AS t(keyid int, parent_keyid int, level int, branch text); -- without branch SELECT * FROM connectby('connectby_int', 'keyid', 'parent_keyid', '2', 0) AS t(keyid int, parent_keyid int, level int); -- recursion detection INSERT INTO connectby_int VALUES(10,9); INSERT INTO connectby_int VALUES(11,10); INSERT INTO connectby_int VALUES(9,11); -- should fail due to infinite recursion SELECT * FROM connectby('connectby_int', 'keyid', 'parent_keyid', '2', 0, '~') AS t(keyid int, parent_keyid int, level int, branch text); -- infinite recursion failure avoided by depth limit SELECT * FROM connectby('connectby_int', 'keyid', 'parent_keyid', '2', 4, '~') AS t(keyid int, parent_keyid int, level int, branch text); -- should fail as first two columns must have the same type SELECT * FROM connectby('connectby_int', 'keyid', 'parent_keyid', '2', 0, '~') AS t(keyid text, parent_keyid int, level int, branch text); -- should fail as key field datatype should match return datatype SELECT * FROM connectby('connectby_int', 'keyid', 'parent_keyid', '2', 0, '~') AS t(keyid float8, parent_keyid float8, level int, branch text); -- tests for values using custom queries -- query with one column - failed SELECT * FROM connectby('connectby_int', '1; --', 'parent_keyid', '2', 0) AS t(keyid int, parent_keyid int, level int); -- query with two columns first value as NULL SELECT * FROM connectby('connectby_int', 'NULL::int, 1::int; --', 'parent_keyid', '2', 0) AS t(keyid int, parent_keyid int, level int); -- query with two columns second value as NULL SELECT * FROM connectby('connectby_int', '1::int, NULL::int; --', 'parent_keyid', '2', 0) AS t(keyid int, parent_keyid int, level int); -- query with two columns, both values as NULL SELECT * FROM connectby('connectby_int', 'NULL::int, NULL::int; --', 'parent_keyid', '2', 0) AS t(keyid int, parent_keyid int, level int); -- test for falsely detected recursion DROP TABLE connectby_int; CREATE TABLE connectby_int(keyid int, parent_keyid int); INSERT INTO connectby_int VALUES(11,NULL); INSERT INTO connectby_int VALUES(10,11); INSERT INTO connectby_int VALUES(111,11); INSERT INTO connectby_int VALUES(1,111); -- this should not fail due to recursion detection SELECT * FROM connectby('connectby_int', 'keyid', 'parent_keyid', '11', 0, '-') AS t(keyid int, parent_keyid int, level int, branch text);
51.12037
174
0.733472
a3c7ea976cf91377f1c225c52682f4e7ecefb84b
6,519
java
Java
redef/src/main/java/com/prime/redef/flatui/FlatLoadingLayout.java
SemihCatal/RecipeJungle-Android
cec4b3428338277f2f02c8e7588905b296d29e01
[ "Apache-2.0" ]
null
null
null
redef/src/main/java/com/prime/redef/flatui/FlatLoadingLayout.java
SemihCatal/RecipeJungle-Android
cec4b3428338277f2f02c8e7588905b296d29e01
[ "Apache-2.0" ]
27
2019-07-19T16:25:34.000Z
2019-07-24T17:26:12.000Z
redef/src/main/java/com/prime/redef/flatui/FlatLoadingLayout.java
SemihCatal/RecipeJungle-Android
cec4b3428338277f2f02c8e7588905b296d29e01
[ "Apache-2.0" ]
1
2020-01-09T13:29:54.000Z
2020-01-09T13:29:54.000Z
package com.prime.redef.flatui; import android.content.Context; import android.os.Handler; import android.util.AttributeSet; import android.view.View; import android.view.animation.AccelerateInterpolator; import android.view.animation.AlphaAnimation; import android.view.animation.Animation; import android.view.animation.DecelerateInterpolator; import android.widget.Button; import android.widget.LinearLayout; import android.widget.RelativeLayout; import android.widget.TextView; import com.prime.redef.R; import com.prime.redef.core.Action; import com.prime.redef.utils.ViewUtils; import com.wang.avi.AVLoadingIndicatorView; import java.util.ArrayList; import java.util.HashMap; public class FlatLoadingLayout extends RelativeLayout { private enum State { IDLE, LOADING, ERROR } private final static int FADE_DURATION = 300; private final static int BUTTON_CLICK_TRESHOLD = 150; private AVLoadingIndicatorView indicator; private LinearLayout errorLayout; private TextView errorText; private Button retryButton; private State state = State.IDLE; private long lastButtonPressed = 0; private Action onButtonClickedListener; public FlatLoadingLayout(Context context) { super(context); init(context); } public FlatLoadingLayout(Context context, AttributeSet attrs) { super(context, attrs); init(context); } public FlatLoadingLayout(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(context); } public FlatLoadingLayout(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) { super(context, attrs, defStyleAttr, defStyleRes); init(context); } private void init(Context context) { View.inflate(context, R.layout.layout_loading, this); indicator = findViewById(R.id.indicator); errorLayout = findViewById(R.id.error_layout); errorText = findViewById(R.id.error_message); retryButton = findViewById(R.id.retry_button); indicator.setVisibility(INVISIBLE); errorLayout.setVisibility(INVISIBLE); retryButton.setEnabled(false); retryButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { onButtonClicked(); } }); } private boolean fadeInView(final View view, final Action afterFade) { view.clearAnimation(); view.animate().cancel(); if (view.getVisibility() == VISIBLE) { if (afterFade != null) afterFade.action(); return false; } view.setVisibility(VISIBLE); Animation anim = new AlphaAnimation(0, 1); anim.setInterpolator(new DecelerateInterpolator()); anim.setDuration(FADE_DURATION); anim.setAnimationListener(new Animation.AnimationListener() { @Override public void onAnimationStart(Animation animation) { } @Override public void onAnimationEnd(Animation animation) { if (afterFade != null) afterFade.action(); } @Override public void onAnimationRepeat(Animation animation) { } }); view.startAnimation(anim); return true; } private boolean fadeOutView(final View view, final Action afterFade) { view.clearAnimation(); view.animate().cancel(); if (view.getVisibility() != VISIBLE) { if (afterFade != null) afterFade.action(); return false; } Animation anim = new AlphaAnimation(1, 0); anim.setInterpolator(new AccelerateInterpolator()); anim.setDuration(FADE_DURATION); anim.setAnimationListener(new Animation.AnimationListener() { @Override public void onAnimationStart(Animation animation) { } @Override public void onAnimationEnd(Animation animation) { view.setVisibility(INVISIBLE); if (afterFade != null) afterFade.action(); } @Override public void onAnimationRepeat(Animation animation) { } }); view.startAnimation(anim); return true; } private void dissappearView(final View view) { view.clearAnimation(); view.animate().cancel(); if (view.getVisibility() == VISIBLE) { view.setVisibility(INVISIBLE); } } private void onButtonClicked() { long currentTime = System.currentTimeMillis(); if (currentTime - lastButtonPressed < BUTTON_CLICK_TRESHOLD) return; lastButtonPressed = currentTime; if (state != State.ERROR) return; if (onButtonClickedListener != null) onButtonClickedListener.action(); } public void loading() { if (state == State.LOADING) return; state = State.LOADING; fadeInView(indicator, null); // NOT: İkisinden biri olabilirdi //fadeOutView(errorLayout, null); dissappearView(errorLayout); } public void idle() { idle(null); } public void idle(final Action onFinish) { if (state == State.IDLE) return; state = State.IDLE; boolean fadeRequired; fadeRequired = fadeOutView(indicator, null); fadeRequired |= fadeOutView(errorLayout, null); if (fadeRequired) { Handler handler = new Handler(); handler.postDelayed(new Runnable() { @Override public void run() { if (onFinish != null) onFinish.action(); } }, FADE_DURATION); } else { if (onFinish != null) onFinish.action(); } } public void error(String message) { errorText.setText(message); retryButton.setEnabled(true); if (state == State.ERROR) return; state = State.ERROR; // NOT: İkisinden biri olabilirdi //fadeOutView(indicator, null); dissappearView(indicator); fadeInView(errorLayout, null); } public void setOnButtonClickedListener(Action onButtonClickedListener) { this.onButtonClickedListener = onButtonClickedListener; } }
28.718062
102
0.618807
cd66d98b61c55aef2e812cd831df9dcefcf6ad0f
14,305
cs
C#
ECode.Core/Utility/NetworkUtil.cs
gz-chenzd/ECode
4b7e9914d3de52b2a04244e8695e67ac666feb78
[ "MIT" ]
10
2020-03-23T10:01:25.000Z
2020-12-09T09:32:36.000Z
ECode.Core/Utility/NetworkUtil.cs
gz-chenzd/ECode
4b7e9914d3de52b2a04244e8695e67ac666feb78
[ "MIT" ]
null
null
null
ECode.Core/Utility/NetworkUtil.cs
gz-chenzd/ECode
4b7e9914d3de52b2a04244e8695e67ac666feb78
[ "MIT" ]
4
2020-03-27T09:24:16.000Z
2021-04-22T10:21:59.000Z
using System; using System.Collections.Generic; using System.Net; using System.Net.NetworkInformation; using System.Net.Sockets; using ECode.Core; namespace ECode.Utility { public static class NetworkUtil { /// <summary> /// Gets local host name. /// </summary> public static string GetHostName() { return Dns.GetHostName(); } /// <summary> /// Gets local host ips. /// </summary> public static IPAddress[] GetIPAddresses() { var list = new List<IPAddress>(); foreach (var nic in NetworkInterface.GetAllNetworkInterfaces()) { if (nic.OperationalStatus != OperationalStatus.Up) { continue; } foreach (var addr in nic.GetIPProperties().UnicastAddresses) { list.Add(addr.Address); } } return list.ToArray(); } /// <summary> /// Gets mailbox's domain. /// </summary> public static string GetMxDomain(string mailbox) { AssertUtil.ArgumentNotEmpty(mailbox, nameof(mailbox)); if (!ValidateUtil.IsMailAddress(mailbox)) { throw new ArgumentException($"Argument '{mailbox}' is not valid mail address."); } return mailbox.Split('@', 2)[1]; } /// <summary> /// Gets if the specified string value is IP address. /// </summary> /// <param name="value">Value to check.</param> /// <returns>Returns true if specified value is IP address.</returns> /// <exception cref="ArgumentNullException">Is raised when <b>value</b> is null.</exception> /// <exception cref="ArgumentException">Is raised when any of the arguments has invalid value.</exception> public static bool IsIPAddress(string value) { AssertUtil.ArgumentNotEmpty(value, nameof(value)); return IPAddress.TryParse(value, out IPAddress ip); } /// <summary> /// Gets if specified IP address is private LAN IP address. For example 192.168.x.x is private ip. /// </summary> /// <param name="ip">IP address to check.</param> /// <returns>Returns true if IP is private IP.</returns> /// <exception cref="ArgumentNullException">Is raised when <b>ip</b> is null reference.</exception> /// <exception cref="ArgumentException">Is raised when any of the arguments has invalid value.</exception> public static bool IsPrivateIPAddress(string ip) { AssertUtil.ArgumentNotEmpty(ip, nameof(ip)); if (!IsIPAddress(ip)) { throw new ArgumentException($"Argument '{ip}' is not valid ip address."); } return IsPrivateIPAddress(IPAddress.Parse(ip)); } /// <summary> /// Gets if specified IP address is private LAN IP address. For example 192.168.x.x is private ip. /// </summary> /// <param name="ip">IP address to check.</param> /// <returns>Returns true if IP is private IP.</returns> /// <exception cref="ArgumentNullException">Is raised when <b>ip</b> is null reference.</exception> public static bool IsPrivateIPAddress(IPAddress ip) { AssertUtil.ArgumentNotNull(ip, nameof(ip)); if (ip.AddressFamily != AddressFamily.InterNetwork) { return false; } var ipBytes = ip.GetAddressBytes(); /* Private IPs: First Octet = 192 AND Second Octet = 168 (Example: 192.168.X.X) First Octet = 172 AND (Second Octet >= 16 AND Second Octet <= 31) (Example: 172.16.X.X - 172.31.X.X) First Octet = 10 (Example: 10.X.X.X) First Octet = 169 AND Second Octet = 254 (Example: 169.254.X.X) */ if (ipBytes[0] == 192 && ipBytes[1] == 168) { return true; } if (ipBytes[0] == 172 && ipBytes[1] >= 16 && ipBytes[1] <= 31) { return true; } if (ipBytes[0] == 10) { return true; } if (ipBytes[0] == 169 && ipBytes[1] == 254) { return true; } return false; } /// <summary> /// Gets if the specified IP address is multicast address. /// </summary> /// <param name="ip">IP address.</param> /// <returns>Returns true if <b>ip</b> is muticast address, otherwise false.</returns> /// <exception cref="ArgumentNullException">Is raised when <b>ip</b> s null reference.</exception> public static bool IsMulticastIPAddress(IPAddress ip) { AssertUtil.ArgumentNotNull(ip, nameof(ip)); // IPv4 multicast 224.0.0.0 to 239.255.255.255 if (ip.IsIPv6Multicast) { return true; } if (ip.AddressFamily == AddressFamily.InterNetwork) { var ipBytes = ip.GetAddressBytes(); if (ipBytes[0] >= 224 && ipBytes[0] <= 239) { return true; } } return false; } /// <summary> /// Compares 2 IP addresses. /// </summary> /// <param name="ipA">The first IP address to compare.</param> /// <param name="ipB">The second IP address to compare.</param> /// <returns> /// Returns 0 if IPs are equal, /// returns positive value if the second IP is bigger than the first IP, /// returns negative value if the second IP is smaller than the first IP. /// </returns> public static int Compare(IPAddress ipA, IPAddress ipB) { AssertUtil.ArgumentNotNull(ipA, nameof(ipA)); AssertUtil.ArgumentNotNull(ipB, nameof(ipB)); byte[] ipABytes = ipA.GetAddressBytes(); byte[] ipBBytes = ipB.GetAddressBytes(); // IPv4 and IPv6 if (ipABytes.Length < ipBBytes.Length) { return 1; } // IPv6 and IPv4 if (ipABytes.Length > ipBBytes.Length) { return -1; } // IPv4 and IPv4 OR IPv6 and IPv6 for (int i = 0; i < ipABytes.Length; i++) { if (ipABytes[i] < ipBBytes[i]) { return 1; } else if (ipABytes[i] > ipBBytes[i]) { return -1; } } return 0; } /// <summary> /// Gets if the specified IP address is in the range. /// </summary> /// <param name="ip">The IP address to check.</param> /// <param name="range">The IP address range.</param> /// <returns>Returns true if the IP address is in the range.</returns> public static bool IsIPAddressInRange(IPAddress ip, string range) { AssertUtil.ArgumentNotNull(ip, nameof(ip)); AssertUtil.ArgumentNotEmpty(range, nameof(range)); string ipString = ip.ToString(); if (ipString == range) { return true; } if (ip.AddressFamily == AddressFamily.InterNetwork) { if (range.IndexOf('-') > 0) { string[] items = range.Split(new char[] { '-' }, 2); if (!IPAddress.TryParse(items[0], out IPAddress ipStart)) { throw new ArgumentException($"Agument '{range}' value is not valid ip range."); } if (!int.TryParse(items[1], out int endValue) || endValue > 255) { throw new ArgumentException($"Agument '{range}' value is not valid ip range."); } byte[] ipBytes = ip.GetAddressBytes(); byte[] startBytes = ipStart.GetAddressBytes(); for (int i = 0; i < 4; i++) { if (i == 3) { return ipBytes[i] >= startBytes[i] && ipBytes[i] <= endValue; } else if (ipBytes[i] != startBytes[i]) { return false; } } } else if (range.IndexOf('/') > 0) { string[] items = range.Split(new char[] { '/' }, 2); if (!IPAddress.TryParse(items[0], out IPAddress ipStart)) { throw new ArgumentException($"Agument '{range}' value is not valid ip range."); } if (!int.TryParse(items[1], out int maskValue) || maskValue > 32) { throw new ArgumentException($"Agument '{range}' value is not valid ip range."); } byte[] ipBytes = ip.GetAddressBytes(); byte[] startBytes = ipStart.GetAddressBytes(); for (int i = 0; i < 4; i++) { int endValue = startBytes[i]; if (((i + 1) * 8 - maskValue) > 0) { endValue += (int)Math.Pow(2, (i + 1) * 8 - maskValue) - 1; } if (ipBytes[i] < startBytes[i] || ipBytes[i] > endValue) { return false; } } return true; } } else if (ip.AddressFamily == AddressFamily.InterNetworkV6) { if (range.IndexOf('-') > 0) { string[] items = range.Split(new char[] { '-' }, 2); if (!IPAddress.TryParse(items[0], out IPAddress ipStart)) { throw new ArgumentException($"Agument '{range}' value is not valid ip range."); } if (items[1].Length > 4) { throw new ArgumentException($"Agument '{range}' value is not valid ip range."); } byte[] last2Bytes = items[1].PadLeft(4, '0').FromHex(); byte[] ipBytes = ip.GetAddressBytes(); byte[] startBytes = ipStart.GetAddressBytes(); for (int i = 0; i < 16; i++) { if (i >= 14) { if (ipBytes[i] < startBytes[i] || ipBytes[i] > last2Bytes[i - 14]) { return false; } } else if (ipBytes[i] != startBytes[i]) { return false; } } return true; } } return false; } /// <summary> /// Parses IPEndPoint from the specified string value. /// </summary> /// <param name="value">IPEndPoint string value.</param> /// <returns>Returns parsed IPEndPoint.</returns> /// <exception cref="ArgumentNullException">Is raised when <b>value</b> is null reference.</exception> /// <exception cref="ArgumentException">Is raised when any of the arguments has invalid value.</exception> public static IPEndPoint ParseIPEndPoint(string value) { AssertUtil.ArgumentNotEmpty(value, nameof(value)); try { string[] ip_port = value.Split(":", true, false, "[]"); if (ip_port[0].StartsWith('[')) { ip_port[0] = ip_port[0].TrimStart('[').TrimEnd(']'); } return new IPEndPoint(IPAddress.Parse(ip_port[0]), Convert.ToInt32(ip_port[1])); } catch (Exception ex) { throw new ArgumentException($"Argument '{value}' is not valid IPEndPoint value.", ex); } } /// <summary> /// Gets if socket async methods supported by OS. /// </summary> /// <returns>returns ture if supported, otherwise false.</returns> public static bool IsSocketAsyncSupported() { try { using (var e = new SocketAsyncEventArgs()) { return true; } } catch (NotSupportedException ex) { string dummy = ex.Message; return false; } } /// <summary> /// Creates a new socket for the specified end point. /// </summary> /// <param name="localEP">Local end point.</param> /// <param name="protocol">Protocol type.</param> /// <returns>Retruns newly created socket.</returns> /// <exception cref="ArgumentNullException">Is raised when <b>localEP</b> is null.</exception> public static Socket CreateSocket(IPEndPoint localEP, ProtocolType protocol) { AssertUtil.ArgumentNotNull(localEP, nameof(localEP)); var socketType = SocketType.Stream; if (protocol == ProtocolType.Udp) { socketType = SocketType.Dgram; } if (localEP.AddressFamily == AddressFamily.InterNetwork) { var socket = new Socket(AddressFamily.InterNetwork, socketType, protocol); socket.Bind(localEP); return socket; } else if (localEP.AddressFamily == AddressFamily.InterNetworkV6) { var socket = new Socket(AddressFamily.InterNetworkV6, socketType, protocol); socket.Bind(localEP); return socket; } else { throw new ArgumentException($"Argument '{localEP.ToString()}' is not valid IPEndPoint value."); } } } }
36.679487
116
0.484656
697218f938739e780f715397f051fdec3a5a90b1
217
rb
Ruby
lib/adroll/api/service.rb
springbot/adroller
f7023e0287c8b93ba83551bb420222f1e83ac538
[ "MIT" ]
5
2016-08-30T20:41:05.000Z
2020-08-25T15:37:00.000Z
lib/adroll/api/service.rb
springbot/adroller
f7023e0287c8b93ba83551bb420222f1e83ac538
[ "MIT" ]
17
2016-07-25T16:19:34.000Z
2018-05-08T15:38:58.000Z
lib/adroll/api/service.rb
springbot/adroller
f7023e0287c8b93ba83551bb420222f1e83ac538
[ "MIT" ]
2
2016-10-12T19:33:56.000Z
2017-05-05T15:59:44.000Z
require 'adroll/service' module AdRoll module Api class Service < AdRoll::Service def service_url File.join(AdRoll.api_base_url, self.class.name.demodulize.underscore) end end end end
18.083333
77
0.695853
0d6d9058e8a384dbd90805014bf05f2fbc953e26
6,817
cshtml
C#
web/Views/Home/Index.cshtml
ONLYOFFICE/OneClickInstall
f2f60159ce58007debc68d1e9b408d3f1378cda3
[ "Apache-2.0" ]
60
2015-05-28T15:49:39.000Z
2021-11-07T20:18:41.000Z
web/Views/Home/Index.cshtml
ONLYOFFICE/OneClickInstall
f2f60159ce58007debc68d1e9b408d3f1378cda3
[ "Apache-2.0" ]
2
2015-10-03T15:09:31.000Z
2016-07-06T14:50:12.000Z
web/Views/Home/Index.cshtml
ONLYOFFICE/OneClickInstall
f2f60159ce58007debc68d1e9b408d3f1378cda3
[ "Apache-2.0" ]
60
2015-05-30T08:19:32.000Z
2020-11-19T13:59:25.000Z
@{ ViewBag.Title = OneClickHomePageResource.InstallationPageTitle; } @section leftSide { @Html.Partial("_IndexLeftSidePartial") } @section rightSide { @Html.Partial("_IndexRightSidePartial") } <div id="connectionErrorPop" class="popup"> <div class="popup-caption"> <div class="popup-error"></div> @OneClickHomePageResource.ConnectionErrorHdr <div class="popup-close"></div> </div> <div class="popup-body"> <div class="bottom-indent"> <div class="error-message"></div> <div class="default-message"> <div> @OneClickHomePageResource.ConnectionErrorText_1<br/> @OneClickHomePageResource.ConnectionErrorText_2 </div> <br> <a href="@Settings.HelpUrl" target="_blank" class="underline">@OneClickHomePageResource.LearnMore</a> </div> </div> <a class="button black okbtn">@OneClickCommonResource.Ok</a> </div> </div> <div id="installErrorPop" class="popup"> <div class="popup-caption"> <div class="popup-error"></div> @OneClickHomePageResource.InstallationErrorHdr <div class="popup-close"></div> </div> <div class="popup-body"> <div class="bottom-indent"> <div class="error-message"></div> <div class="default-message">@OneClickHomePageResource.InstallationErrorText</div> <br> <span>@OneClickHomePageResource.ContactSupport&nbsp;</span> <a href="@Settings.DevUrl" target="_blank" class="underline">@Settings.DevUrl</a> </div> <a class="button black okbtn">@OneClickCommonResource.Ok</a> </div> </div> <div id="existVersionErrorPop" class="popup"> <div class="popup-caption"> <div class="popup-error"></div> @OneClickHomePageResource.ExistVersionErrorHdr <div class="popup-close"></div> </div> <div class="popup-body"> <div class="bottom-indent"> <div class="error-message"></div> <div class="default-message"> <div> @OneClickHomePageResource.ExistVersionErrorText </div> <br> <span>@OneClickHomePageResource.ContactSupport&nbsp;</span> <a href="@Settings.DevUrl" target="_blank" class="underline">@Settings.DevUrl</a> </div> </div> <a class="button black okbtn">@OneClickCommonResource.Ok</a> </div> </div> @if (ViewBag.Enterprise) { <div id="trialPop" class="popup"> <div class="popup-caption"> @OneClickHomePageResource.RequestForm <div class="popup-close"></div> </div> <div class="popup-body"> <div class="disconnected" style="height: 480px;"> <div class="bottom-indent label"> @OneClickHomePageResource.TrialDescText </div> <div class="bottom-indent"> <input id="name" type="text" class="group-top" placeholder="@OneClickHomePageResource.NamePlaceholder" /> <input id="email" type="text" class="group-center" placeholder="@OneClickHomePageResource.EmailPlaceholder" /> <input id="phone" type="text" class="group-center" placeholder="@OneClickHomePageResource.PhonePlaceholder" /> <input id="companyName" type="text" class="group-center" placeholder="@OneClickHomePageResource.CompanyNamePlaceholder" /> <div class="custom-select group-center"> <input id="companySize" type="text" class="custom-select-value" placeholder="@OneClickHomePageResource.CompanySizePlaceholder" readonly="readonly"/> <div class="custom-select-switch"></div> <div class="custom-select-options"> <div class="custom-select-options-inner"> <div class="custom-select-option" data-value="5">@String.Format(OneClickHomePageResource.EmployeesCount, "1 - 5")</div> <div class="custom-select-option" data-value="14">@String.Format(OneClickHomePageResource.EmployeesCount, "6 - 14")</div> <div class="custom-select-option" data-value="64">@String.Format(OneClickHomePageResource.EmployeesCount, "15 - 64")</div> <div class="custom-select-option" data-value="350">@String.Format(OneClickHomePageResource.EmployeesCount, "65 - 350")</div> <div class="custom-select-option" data-value="1499">@String.Format(OneClickHomePageResource.EmployeesCount, "351 - 1499")</div> <div class="custom-select-option" data-value="1500">@String.Format(OneClickHomePageResource.EmployeesMoreThanCount, "1500")</div> </div> </div> </div> <input id="position" type="text" class="group-bottom" placeholder="@OneClickHomePageResource.PositionPlaceholder" /> </div> <a id="trialBtn" class="button black">@OneClickCommonResource.GetLicenseFile</a> </div> <div class="connected display-none" style="height: 480px;"> <h1 class="blue bottom-indent">@OneClickHomePageResource.TrialReadyText</h1> <a class="button green okbtn">@OneClickCommonResource.Ok</a> </div> </div> </div> } @section scripts { @Scripts.Render("~/bundles/homepage") <script> $(function () { ActionUrl.UploadFile = '@Url.Action("UploadFile", "Home")'; ActionUrl.Connect = '@Url.Action("Connect", "Home")'; ActionUrl.StartInstall = '@Url.Action("StartInstall", "Home")'; ActionUrl.InstallProgress = '@Url.Action("InstallProgress", "Home")'; SetupInfo.connectionSettings = JSON.parse(@Html.Raw(Json.Encode(ViewBag.ConnectionSettings))); SetupInfo.availableComponents = JSON.parse(@Html.Raw(Json.Encode(ViewBag.AvailableComponents))); SetupInfo.installedComponents = JSON.parse(@Html.Raw(Json.Encode(ViewBag.InstalledComponents))); SetupInfo.selectedComponents = JSON.parse(@Html.Raw(Json.Encode(ViewBag.SelectedComponents))); SetupInfo.installationProgress = JSON.parse(@Html.Raw(Json.Encode(ViewBag.InstallationProgress))); SetupInfo.osInfo = JSON.parse(@Html.Raw(Json.Encode(ViewBag.OsInfo))); SetupInfo.trialFileName = '@Settings.TrialFileName'; SetupInfo.enterprise = Boolean(@(ViewBag.Enterprise ? 1 : 0)); InstallManager.init(); }); </script> }
46.691781
172
0.595717
f2035d55167952bad1b2980f66af46a14e20d846
268
cpp
C++
lldb/packages/Python/lldbsuite/test/commands/process/launch/main.cpp
medismailben/llvm-project
e334a839032fe500c3bba22bf976ab7af13ce1c1
[ "Apache-2.0" ]
2,338
2018-06-19T17:34:51.000Z
2022-03-31T11:00:37.000Z
packages/Python/lldbsuite/test/functionalities/process_launch/main.cpp
DalavanCloud/lldb
e913eaf2468290fb94c767d474d611b41a84dd69
[ "Apache-2.0" ]
3,740
2019-01-23T15:36:48.000Z
2022-03-31T22:01:13.000Z
packages/Python/lldbsuite/test/functionalities/process_launch/main.cpp
DalavanCloud/lldb
e913eaf2468290fb94c767d474d611b41a84dd69
[ "Apache-2.0" ]
500
2019-01-23T07:49:22.000Z
2022-03-30T02:59:37.000Z
#include <stdio.h> #include <stdlib.h> int main (int argc, char **argv) { char buffer[1024]; fgets (buffer, sizeof (buffer), stdin); fprintf (stdout, "%s", buffer); fgets (buffer, sizeof (buffer), stdin); fprintf (stderr, "%s", buffer); return 0; }
14.888889
41
0.619403
5ad1496f59241213c07bfe72fabe11b808197cd2
2,166
cs
C#
Commands/CommandList.cs
VHonzik/gash
d79648b256eb583457faf02b354f38cf11fb846c
[ "MIT" ]
10
2017-04-20T06:48:44.000Z
2022-02-06T00:59:15.000Z
Commands/CommandList.cs
VHonzik/gash
d79648b256eb583457faf02b354f38cf11fb846c
[ "MIT" ]
7
2017-04-30T22:11:17.000Z
2017-05-17T00:11:26.000Z
Commands/CommandList.cs
VHonzik/gash
d79648b256eb583457faf02b354f38cf11fb846c
[ "MIT" ]
3
2019-04-08T23:37:09.000Z
2021-08-18T07:31:14.000Z
using System; using System.Collections; using System.Collections.Generic; namespace Gash.Commands { internal class CommandList : IEnumerable<ICommand> { private List<ICommand> KnownCommands = new List<ICommand>(); private Dictionary<string, ICommand> KnownCommandsMap = new Dictionary<string, ICommand>(); public void RegisterCommand(ICommand command) { KnownCommands.Add(command); KnownCommandsMap.Add(command.Name(), command); } internal void ParseLine(string line) { ParsingResult result = new ParsingResult(); foreach (var command in KnownCommands) { result = command.Parse(line); if (result.Type == ParsingResultType.Success || result.Type == ParsingResultType.SuccessReachedEnd || result.Type == ParsingResultType.ParsingFailure || result.Type == ParsingResultType.MissingParam) { break; } } if (result.Type == ParsingResultType.WrongCommand) { string command = line; var parsingResult = ParsingHelpers.TryAnyCommandBody(line); if (parsingResult.WasSuccessful && parsingResult.Value.Length > 0) { command = parsingResult.Value; } GConsole.WriteLine(GConsole.ColorifyText(1,String.Format(Resources.text.UnknownCommand, command))); } } internal bool FindMan(string commandName) { ICommand result = null; if (KnownCommandsMap.TryGetValue(commandName, out result)) { result.PrintManPage(); return true; } return false; } public IEnumerator<ICommand> GetEnumerator() { return KnownCommands.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return KnownCommands.GetEnumerator(); } } }
31.852941
118
0.545706
9e06f133f1210ee5da0ea93ab0607a099132dce5
6,287
swift
Swift
GlowingRemote/DevicesViewController.swift
Shark/GlowingRemote
bee9f09b9724dac845fb99c3cb97c74382e98339
[ "0BSD" ]
null
null
null
GlowingRemote/DevicesViewController.swift
Shark/GlowingRemote
bee9f09b9724dac845fb99c3cb97c74382e98339
[ "0BSD" ]
null
null
null
GlowingRemote/DevicesViewController.swift
Shark/GlowingRemote
bee9f09b9724dac845fb99c3cb97c74382e98339
[ "0BSD" ]
null
null
null
// // ViewController.swift // GlowingRemote // // Created by Felix Seidel on 17/07/15. // Copyright © 2015 Felix Seidel. All rights reserved. // import UIKit import WatchConnectivity class DevicesViewController: UITableViewController { var devices : Array<Device>? var stateManager : StateManager? override func viewDidLoad() { super.viewDidLoad() let delegate = (UIApplication.sharedApplication().delegate) as! AppDelegate stateManager = delegate.stateManager } override func viewWillAppear(animated: Bool) { NSNotificationCenter.defaultCenter().addObserver(self, selector: "refresh", name: "StateChanged", object: nil) self.devices = stateManager?.devices if(self.devices == nil) { updateDevices() } } override func viewWillDisappear(animated: Bool) { NSNotificationCenter.defaultCenter().removeObserver(self, name: "refresh", object: nil) } override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 2; } override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? { if(section == 0) { return "RGB-Strips" } else { return "Steckdosen" } } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { let devPerSect = devicesPerSection(devices) if(section == 0) { return devPerSect["RGBStrip"]!.count } else { return devPerSect["RCSwitch"]!.count } } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell: UITableViewCell = tableView.dequeueReusableCellWithIdentifier("state_cell")! let nameLabel : UILabel = cell.viewWithTag(1) as! UILabel let stateSwitch : UISwitch = cell.viewWithTag(2) as! UISwitch let devPerSect = devicesPerSection(devices) var currentDevice : Device if(indexPath.section == 0) { currentDevice = devPerSect["RGBStrip"]![indexPath.row] as! Device } else { currentDevice = devPerSect["RCSwitch"]![indexPath.row] as! Device } nameLabel.text = currentDevice.name stateSwitch.setOn(currentDevice.state.power, animated: true) stateSwitch.setValue(currentDevice, forKey: "device") stateSwitch.addTarget(self, action: "stateSwitchValueDidChange:", forControlEvents: .ValueChanged); return cell } func stateSwitchValueDidChange(sender: UISwitch!) { let device = sender.valueForKey("device") as! Device if sender.on { stateManager!.switchOn(device, completionHandler: {(Bool) -> Void in if(WCSession.defaultSession().reachable) { WCSession.defaultSession().sendMessage(["id": device.id, "power": device.state.power], replyHandler: nil, errorHandler: {(error) -> Void in print(error) }) } }) } else { stateManager!.switchOff(device, completionHandler: {(Bool) -> Void in if(WCSession.defaultSession().reachable) { WCSession.defaultSession().sendMessage(["id": device.id, "power": device.state.power], replyHandler: nil, errorHandler: {(error) -> Void in print(error) }) } }) } } private func devicesPerSection(devices : NSArray?) -> NSDictionary { let dict = NSMutableDictionary() dict.setValue(NSMutableArray(), forKey: "RCSwitch") dict.setValue(NSMutableArray(), forKey: "RGBStrip") if devices != nil { for device in devices! { let type = (device as! Device).type if(type == "RCSwitch") { dict["RCSwitch"]!.addObject(device) } else if(type == "RGBStrip") { dict["RGBStrip"]!.addObject(device) } } } return dict } func updateDevices() { stateManager!.updateDevices({ (success) -> Void in if(success) { self.devices = self.stateManager!.devices self.updateDeviceContext(self.devices!) } dispatch_async(dispatch_get_main_queue()) { if(success) { self.tableView.reloadData() } else { self.showDevicesNotAvailableAlert() } } }) } func updateStateRemotely() { stateManager!.updateState({ (success) -> Void in if(success) { self.devices = self.stateManager!.devices dispatch_async(dispatch_get_main_queue()) { self.tableView.reloadData() self.updateDeviceContext(self.devices!) } } }) } func refresh() { self.devices = self.stateManager!.devices dispatch_async(dispatch_get_main_queue()) { self.tableView.reloadData() self.updateDeviceContext(self.devices!) } } func updateDeviceContext(devices: Array<Device>) { let context = ["devices": devices] do { try WCSession.defaultSession().updateApplicationContext(context) } catch { print(error) } } @IBAction func unwindToDevices(segue: UIStoryboardSegue) { } private func showDevicesNotAvailableAlert() { dispatch_async(dispatch_get_main_queue()) { let baseUrl = self.stateManager?.apiBaseUrl?.absoluteString let alertController = UIAlertController(title: "Fehler", message: "Konnte Geräte nicht von \(baseUrl) laden.", preferredStyle: .Alert) alertController.addAction(UIAlertAction(title: "OK", style: .Default) { (action) in }) self.presentViewController(alertController, animated: true, completion: nil) } } }
34.543956
159
0.577541
b28fb7a4d9306748ae20068a6bc9b05472bb8b29
3,462
css
CSS
get started style.css
sn262000/casetools-car-rental
c6f8439703fb5e2480ee680389f63973bb51bd13
[ "CC-BY-3.0" ]
null
null
null
get started style.css
sn262000/casetools-car-rental
c6f8439703fb5e2480ee680389f63973bb51bd13
[ "CC-BY-3.0" ]
null
null
null
get started style.css
sn262000/casetools-car-rental
c6f8439703fb5e2480ee680389f63973bb51bd13
[ "CC-BY-3.0" ]
null
null
null
* { margin: 0; padding: 0; } .hero{ height: 100vh; width: 100%; background-image: url(sky.jpg); background-position: center; position: relative; overflow: hidden; } .highway { height: 200px; width: 500%; display: block; background-image: url(road.jpg); position: absolute; bottom: 0; left: 0; right: 0; z-index: 1; background-repeat: repeat-x; animation: highway 5s linear infinite; } @keyframes highway { 100%{ transform: translatex(-3400px); }10 } .city{ height: 250px; width: 500%; background-image: url(city3.png); position: absolute; bottom: 200px; left: 0; right: 0; display: block; z-index: 1; background-repeat: repeat-x; animation: city 20s linear infinite; } @keyframes city { 100%{ transform: translatex(-1400px); } } .car { width: 400px; left: 38.3%; bottom: -15.6%; transform: translatex(-50%); position: absolute; z-index: 5; } .car img{ width: 200%; animation: car 1s linear infinite; } @keyframe car { 100%{ transform: translateY(-1px); } 50%{ transform: translateY(1px); } 0%{ transform: translateY(-1px); } } .wheel { left: 50%; bottom: 178px; transform: translatex(-50%); position: absolute; z-index: 2; } .wheel img{ width: 119px; height: 119px; animation: wheel 1s linear infinite; } .back-wheel { left: -240px; position: absolute; } .front-wheel { left: 170px; position: absolute; } @keyframes wheel { 100%{ transform: rotate(360deg); } } .leftmenu{ width: 20%; line-height: 100px; float: left; /* background-color: yellow;*/ } .leftmenu h4{ padding-left: 75px; font-weight: bold; color: black; font-size: 42px; font-family: 'Montserrat', sans-serif; } .rightmenu{ width:70%; height: 100px; float: right; /* background-color: red; */ } .rightmenu ul{ margin-left: 700px; } .rightmenu ul li { font-family: 'Montserrat', sans-serif; text-decoration-color: black; display: inline-block; list-style: none; font-size: 15px; color:black; font-weight: bold; line-height: 100px; margin-left: 40px; text-transform: uppercase; } #fisrtlist{ color: orange; } .rightmenu ul li:hover{ color: orange; } .text{ width: 100%; margin-top: 185px; text-transform: uppercase; text-align: center; color:black; } .text h4{ font-size: 24px; font-family: 'Open Sans', sans-serif; } .text h1{ font-size:42px; font-family: 'Montserrat', sans-serif; font-weight: 700px; margin:14px 0px; } .text h3{ font-size: 22px; font-family: 'Open Sans', sans-serif; } #buttonone{ background-color: transparent; border: none; font-size: 19px; font-weight: bold; text-transform: uppercase; line-height: 40px; width: 150px; font-family: 'Montserrat', sans-serif; margin-top: 25px; border: 3px solid white; } .aw{ text-decoration: none; color: black; background: rgba(29,171,209,1); position: fixed; top: 50%; left: 50%; transform: translate(-50%,-50%); padding: 30px 10px; font-family: sans-serif; font-weight: bold; font-size:10vw text-transform: uppercase; border-radius: 50%; z-index: 6; animation: animate 2s linear infinite; } @keyframes animate { 0%{ box-shadow: 0 0 0 0 rgba(29,171,209,0.6), 0 0 0 0 rgba(29,171,209,0.6); } 30%{ box-shadow: 0 0 0 50px rgba(29,171,209,0), 0 0 0 0 rgba(29,171,209,0.6); } 65%{ box-shadow: 0 0 0 50px rgba(29,171,209,0), 0 0 0 30px rgba(29,171,209,0); } 100%{ box-shadow: 0 0 0 0 rgba(29,171,209,0), 0 0 0 30px rgba(29,171,209,0); } }
14.669492
77
0.657423
c61fe484c1d44414412e4c5f1b12d185255c8a39
68
rb
Ruby
lib/rotas/version.rb
trombik/rotas
552eb990bad38c47d2ca6f99a13afa2ab4442747
[ "MIT" ]
null
null
null
lib/rotas/version.rb
trombik/rotas
552eb990bad38c47d2ca6f99a13afa2ab4442747
[ "MIT" ]
null
null
null
lib/rotas/version.rb
trombik/rotas
552eb990bad38c47d2ca6f99a13afa2ab4442747
[ "MIT" ]
null
null
null
# frozen_string_literal: true module Rotas VERSION = "0.1.0" end
11.333333
29
0.720588
ff309fdd5a997b5d53c2fabfa2c08b9af650c2aa
176
py
Python
fibonacci.py
leantab/algorithms
63648855da19d41904da39dfeca9ab1094d9c9a1
[ "MIT" ]
null
null
null
fibonacci.py
leantab/algorithms
63648855da19d41904da39dfeca9ab1094d9c9a1
[ "MIT" ]
null
null
null
fibonacci.py
leantab/algorithms
63648855da19d41904da39dfeca9ab1094d9c9a1
[ "MIT" ]
null
null
null
memo = { 0: 0, 1: 1, 2: 1, } def fib(n): if n in memo: return memo[n] val = fib(n-1) + fib(n-2) memo[n] = val return val print(fib(35))
10.352941
29
0.4375
bb81bd020f00b13965236a56db0f197fa8169f3c
6,980
swift
Swift
ShoB/Model/Order.swift
iDara09/ShoB
ae5a6a9094f93f1c0e847c45f0d96bb5be52dbd7
[ "MIT" ]
114
2019-07-27T18:16:48.000Z
2022-01-09T13:41:46.000Z
ShoB/Model/Order.swift
bdaralan/ShoB
ae5a6a9094f93f1c0e847c45f0d96bb5be52dbd7
[ "MIT" ]
2
2019-09-29T01:12:51.000Z
2019-09-29T01:19:34.000Z
ShoB/Model/Order.swift
bdaralan/ShoB
ae5a6a9094f93f1c0e847c45f0d96bb5be52dbd7
[ "MIT" ]
13
2019-08-12T15:37:58.000Z
2021-12-25T21:21:37.000Z
// // Order+CoreDataClass.swift // ShoB // // Created by Dara Beng on 6/13/19. // Copyright © 2019 Dara Beng. All rights reserved. // // import CoreData import SwiftUI import Combine /// An order of a store or a customer. class Order: NSManagedObject, ObjectValidatable { @NSManaged var orderDate: Date! @NSManaged var deliverDate: Date! @NSManaged var deliveredDate: Date? @NSManaged var discount: Cent @NSManaged var note: String @NSManaged var orderItems: Set<OrderItem> @NSManaged var customer: Customer? @NSManaged var store: Store? /// A formatted string of deliver date. Example: 12-31-2019. /// /// Used to group date into section when using fetch controller. @NSManaged private(set) var deliverDateSection: String /// Used to manually mark order as has changes. var isMarkedValuesChanged = false override func awakeFromInsert() { super.awakeFromInsert() orderDate = Date.currentYMDHM deliverDate = Date.currentYMDHM } override func willChangeValue(forKey key: String) { super.willChangeValue(forKey: key) objectWillChange.send() } override func didChangeValue(forKey key: String) { // update deliverDateSection when deliverDate value changed if key == #keyPath(Order.deliverDate) { let deliverDateSection = #keyPath(Order.deliverDateSection) let value = Self.deliverDateSectionFormatter.string(from: deliverDate) setPrimitiveValue(value, forKey: deliverDateSection) } super.didChangeValue(forKey: key) } override func didSave() { super.didSave() isMarkedValuesChanged = false } /// The total after discount. func total() -> Cent { subtotal() - discount } /// The total before discount. func subtotal() -> Cent { orderItems.map({ $0.price * $0.quantity }).reduce(0, +) } } extension Order { func isValid() -> Bool { hasValidInputs() && store != nil } func hasValidInputs() -> Bool { !orderItems.isEmpty } func hasChangedValues() -> Bool { hasPersistentChangedValues || isMarkedValuesChanged } } extension Order { /// Copy necessary values from the an order to another order. /// - Important: The two orders MUST be from the same context. /// - Parameters: /// - oldOrder: The order to copy values from. /// - newOrder: The order to copy values to. static func again(oldOrder: Order, newOrder: Order) { // copy necessary values newOrder.discount = oldOrder.discount newOrder.note = oldOrder.note newOrder.customer = oldOrder.customer newOrder.store = oldOrder.store // copy delivery time but set the day to today let calendar = Calendar.current let today = Date.currentYMDHM let newDateComponents = calendar.dateComponents([.hour, .minute], from: oldOrder.deliverDate) let newDate = calendar.date( bySettingHour: newDateComponents.hour!, minute: newDateComponents.minute!, second: 0, of: today ) newOrder.deliverDate = newDate // copy order items oldOrder.orderItems.forEach { let copyItem = OrderItem(context: newOrder.managedObjectContext!) copyItem.name = $0.name copyItem.price = $0.price copyItem.quantity = $0.quantity copyItem.order = newOrder } } } // MARK: - Fetch Request extension Order { @nonobjc class func fetchRequest() -> NSFetchRequest<Order> { return NSFetchRequest<Order>(entityName: "Order") } /// A request to fetch today orders. /// - Parameter storeID: The store ID. static func requestDeliverToday(storeID: String) -> NSFetchRequest<Order> { requestDeliver(from: Date.startOfToday(), to: Date.startOfToday(addingDay: 1), storeID: storeID) } /// A request to fetch orders from date to another date. /// - Parameters: /// - startDate: The earliest date to be included. /// - endDate: The latest date but NOT included. The default is `nil` which means no boundary. /// - storeID: The store ID. static func requestDeliver(from startDate: Date, to endDate: Date? = nil, storeID: String) -> NSFetchRequest<Order> { let request = Order.fetchRequest() as NSFetchRequest<Order> let deliverDate = #keyPath(Order.deliverDate) let storeUID = #keyPath(Order.store.uniqueID) if let endDate = endDate { let matchDateQuery = "\(deliverDate) >= %@ AND \(deliverDate) < %@" let matchDate = NSPredicate(format: matchDateQuery, startDate as NSDate, endDate as NSDate) request.predicate = NSCompoundPredicate(storeID: storeID, keyPath: storeUID, and: [matchDate]) } else { let matchDateQuery = "\(deliverDate) >= %@" let matchDate = NSPredicate(format: matchDateQuery, startDate as NSDate) request.predicate = NSCompoundPredicate(storeID: storeID, keyPath: storeUID, and: [matchDate]) } request.sortDescriptors = [.init(key: deliverDate, ascending: true)] return request } /// A request to fetch orders from the past day up to but not including today. /// - Parameters: /// - fromPastDay: The number of days that have been passed. For instance, 7 means last week. /// - storeID: The store ID. static func requestDeliver(fromPastDay: Int, storeID: String) -> NSFetchRequest<Order> { let request = Order.fetchRequest() as NSFetchRequest<Order> let deliverDate = #keyPath(Order.deliverDate) let storeUID = #keyPath(Order.store.uniqueID) let today = Date.startOfToday() as NSDate let pastDay = Date.startOfToday(addingDay: -fromPastDay) as NSDate let matchDateQuery = "\(deliverDate) >= %@ AND \(deliverDate) < %@" let matchDate = NSPredicate(format: matchDateQuery, pastDay, today) request.predicate = NSCompoundPredicate(storeID: storeID, keyPath: storeUID, and: [matchDate]) request.sortDescriptors = [.init(key: deliverDate, ascending: false)] return request } static func requestNoObject() -> NSFetchRequest<Order> { let request = Order.fetchRequest() as NSFetchRequest<Order> request.predicate = .init(value: false) request.sortDescriptors = [] return request } } extension Order { /// A formatter used to format `deliverDateSection`. static let deliverDateSectionFormatter: DateFormatter = { let formatter = DateFormatter() formatter.dateFormat = "MM-dd-yyyy" // example: 12-31-2019 return formatter }() }
33.557692
121
0.631948
1a5b41b689e4aa8d1b2ce5c205f818e03edf6738
4,542
py
Python
redis_metrics/tests/test_forms.py
bradmontgomery/django-redis-metrics
b1466b5742f3f1e3aac4264cb8b73e25e765e972
[ "MIT" ]
52
2015-01-03T19:40:50.000Z
2022-01-23T14:08:43.000Z
redis_metrics/tests/test_forms.py
bradmontgomery/django-redis-metrics
b1466b5742f3f1e3aac4264cb8b73e25e765e972
[ "MIT" ]
31
2015-01-05T10:28:50.000Z
2020-03-30T15:42:35.000Z
redis_metrics/tests/test_forms.py
bradmontgomery/django-redis-metrics
b1466b5742f3f1e3aac4264cb8b73e25e765e972
[ "MIT" ]
11
2015-03-07T12:15:53.000Z
2019-11-03T15:31:59.000Z
from __future__ import unicode_literals from django.test import TestCase try: from unittest.mock import call, patch except ImportError: from mock import call, patch from ..forms import AggregateMetricForm, MetricCategoryForm class TestAggregateMetricForm(TestCase): def test_form(self): """Test that form has choices populated from R.metric_slugs""" # Set up a mock result for R.metric_slugs config = {'return_value.metric_slugs.return_value': ['test-slug']} with patch('redis_metrics.forms.R', **config) as mock_R: form = AggregateMetricForm() mock_R.assert_has_calls([ call(), call().metric_slugs(), ]) self.assertEqual( form.fields['metrics'].choices, [('test-slug', 'test-slug')] ) def test_cleaned_data(self): """Verify we get expected results from cleaned_data""" # Set up a mock result for R.metric_slugs config = {'return_value.metric_slugs.return_value': ['test-slug']} with patch('redis_metrics.forms.R', **config): form = AggregateMetricForm({"metrics": ["test-slug"]}) self.assertTrue(form.is_valid()) self.assertEqual(form.cleaned_data, {"metrics": ["test-slug"]}) class TestMetricCategoryForm(TestCase): def test_form(self): """Test that the form has choices from R.metric_slugs, and that providing a ``category`` argument sets initial values.""" # Set up a mock result for R.metric_slugs & R._category_slugs config = { 'return_value.metric_slugs.return_value': ['test-slug'], 'return_value._category_slugs.return_value': ['test-slug'] } with patch('redis_metrics.forms.R', **config) as mock_R: # No Category form = MetricCategoryForm() self.assertFalse(form.fields['metrics'].required) mock_R.assert_has_calls([ call(), call().metric_slugs(), ]) self.assertEqual( form.fields['metrics'].choices, [('test-slug', 'test-slug')] ) self.assertEqual(form.fields['metrics'].initial, None) self.assertEqual(form.fields['category_name'].initial, None) self.assertFalse(mock_R._category_slugs.called) mock_R.reset_mock() # With a Category initial = {'category_name': "Sample Category"} form = MetricCategoryForm(initial=initial) self.assertFalse(form.fields['metrics'].required) self.assertEqual(form.fields['metrics'].initial, ['test-slug']) self.assertEqual( form.fields['category_name'].initial, "Sample Category" ) r = mock_R.return_value r._category_slugs.assert_called_once_with("Sample Category") def test_cleaned_data(self): """Verify we get expected results from cleaned_data.""" # Set up a mock result for R.metric_slugs & R._category_slugs config = { 'return_value.metric_slugs.return_value': ['test-slug'], 'return_value._category_slugs.return_value': ['test-slug'] } with patch('redis_metrics.forms.R', **config): data = { 'category_name': 'Sample Data', 'metrics': ['test-slug'], } form = MetricCategoryForm(data) self.assertTrue(form.is_valid()) self.assertEqual(form.cleaned_data, data) def test_categorize_metrics(self): """Test the ``categorize_metrics`` method; This method should be called after POSTing.""" k = { 'return_value.metric_slugs.return_value': ['foo', 'bar', 'baz'], 'return_value._category_slugs.return_value': ['foo', 'bar'], } with patch('redis_metrics.forms.R', **k) as mock_R: data = {'category_name': 'Foo', 'metrics': ['foo', 'bar']} form = MetricCategoryForm(data) self.assertTrue(form.is_valid()) form.categorize_metrics() # This is what should happen in the form when POSTing mock_R.assert_has_calls([ # happens in __init__ call(), call().metric_slugs(), # happens in categorize_metrics call().reset_category('Foo', ['foo', 'bar']) ])
38.491525
79
0.580581
da1a800eacdca4a42a94bb58647ec0be23453283
795
php
PHP
resources/views/page/showcat.blade.php
akibhasan50/laravel-crud
fca0e11b570ad1819fd8a3185957757c5dc6025a
[ "MIT" ]
null
null
null
resources/views/page/showcat.blade.php
akibhasan50/laravel-crud
fca0e11b570ad1819fd8a3185957757c5dc6025a
[ "MIT" ]
null
null
null
resources/views/page/showcat.blade.php
akibhasan50/laravel-crud
fca0e11b570ad1819fd8a3185957757c5dc6025a
[ "MIT" ]
null
null
null
@extends('welcome') @section('content') <div class="container"> <h1 class="text-center">Single Catagories</h1> <div class="row justify-content-center"> <div class="col-lg-10"> <div class="nav"> <a href="{{route('addcatagory')}}" class="btn btn-outline-success mr-3">Add Catagory</a> <a href="{{route('allcatagory')}}" class="btn btn-outline-danger">All Catagory</a> </div> <ul class="list-group"> <li class="list-group-item ">{{$cat->name}}</li> <li class="list-group-item">{{$cat->slugname}}</li> <li class="list-group-item ">{{$cat->created_at}}</li> </ul> </div> </div> </div> @endsection
30.576923
104
0.493082
cd8aca0041ae8a4a3446f96afdf3eea0e3130564
9,811
cs
C#
AmerFamilyPlayoffs.Api.Tests/ApiContextTest.cs
sewright22/AmerFamilyPlayoffs
66cff549a4fd22d1d7bbbcd3f834f214fa1d5c22
[ "MIT" ]
1
2020-12-04T08:40:22.000Z
2020-12-04T08:40:22.000Z
AmerFamilyPlayoffs.Api.Tests/ApiContextTest.cs
sewright22/AmerFamilyPlayoffs
66cff549a4fd22d1d7bbbcd3f834f214fa1d5c22
[ "MIT" ]
2
2020-12-12T01:14:34.000Z
2020-12-12T18:04:07.000Z
AmerFamilyPlayoffs.Api.Tests/ApiContextTest.cs
sewright22/AmerFamilyPlayoffs
66cff549a4fd22d1d7bbbcd3f834f214fa1d5c22
[ "MIT" ]
1
2020-12-12T01:12:04.000Z
2020-12-12T01:12:04.000Z
namespace AmerFamilyPlayoffs.Api.Tests { using AmerFamilyPlayoffs.Data; using Microsoft.EntityFrameworkCore; using System; using System.Collections.Generic; using System.Linq; using Xunit; public class ApiContextTest { protected ApiContextTest(DbContextOptions<AmerFamilyPlayoffContext> contextOptions) { ContextOptions = contextOptions; Seed(); } protected DbContextOptions<AmerFamilyPlayoffContext> ContextOptions { get; } private void Seed() { using (var context = new AmerFamilyPlayoffContext(ContextOptions)) { context.Database.EnsureDeleted(); context.Database.EnsureCreated(); this.SeedConferences(context); this.SeedSeasons(context); this.SeedTeams(context); this.SeedSeasonTeams(context); this.SeedPlayoffs(context); this.SeedPlayoffTeams(context); } } public virtual void SeedConferences(AmerFamilyPlayoffContext context) { context.Conferences.Add(new Conference { Name = "AFC", }); context.Conferences.Add(new Conference { Name = "NFC", }); context.SaveChanges(); } public virtual void SeedSeasons(AmerFamilyPlayoffContext context) { var seasonList = new List<Season>(); var twentyEighteenSeason = new Season { Year = 2018, Description = "2018-2019" }; var twentyNineteenSeason = new Season { Year = 2019, Description = "2019-2020" }; var twentyTwentySeason = new Season { Year = 2020, Description = "2020-2021" }; seasonList.Add(twentyEighteenSeason); seasonList.Add(twentyNineteenSeason); seasonList.Add(twentyTwentySeason); context.AddRange(seasonList); context.SaveChanges(); } public virtual void SeedSeasonTeams(AmerFamilyPlayoffContext context) { var afcConferenceId = context.Conferences.FirstOrDefault(c => c.Name == "AFC").Id; var nfcConferenceId = context.Conferences.FirstOrDefault(c => c.Name == "NFC").Id; foreach (var season in context.Seasons) { SaveConferenceToTeam(context, "BAL", afcConferenceId, season.Id); SaveConferenceToTeam(context, "BUF", afcConferenceId, season.Id); SaveConferenceToTeam(context, "CIN", afcConferenceId, season.Id); SaveConferenceToTeam(context, "CLE", afcConferenceId, season.Id); SaveConferenceToTeam(context, "DEN", afcConferenceId, season.Id); SaveConferenceToTeam(context, "HOU", afcConferenceId, season.Id); SaveConferenceToTeam(context, "IND", afcConferenceId, season.Id); SaveConferenceToTeam(context, "JAX", afcConferenceId, season.Id); SaveConferenceToTeam(context, "KC", afcConferenceId, season.Id); SaveConferenceToTeam(context, "LAC", afcConferenceId, season.Id); SaveConferenceToTeam(context, "LV", afcConferenceId, season.Id); SaveConferenceToTeam(context, "MIA", afcConferenceId, season.Id); SaveConferenceToTeam(context, "NE", afcConferenceId, season.Id); SaveConferenceToTeam(context, "NYJ", afcConferenceId, season.Id); SaveConferenceToTeam(context, "PIT", afcConferenceId, season.Id); SaveConferenceToTeam(context, "TEN", afcConferenceId, season.Id); SaveConferenceToTeam(context, "ARI", nfcConferenceId, season.Id); SaveConferenceToTeam(context, "ATL", nfcConferenceId, season.Id); SaveConferenceToTeam(context, "CAR", nfcConferenceId, season.Id); SaveConferenceToTeam(context, "CHI", nfcConferenceId, season.Id); SaveConferenceToTeam(context, "DAL", nfcConferenceId, season.Id); SaveConferenceToTeam(context, "DET", nfcConferenceId, season.Id); SaveConferenceToTeam(context, "GB", nfcConferenceId, season.Id); SaveConferenceToTeam(context, "LAR", nfcConferenceId, season.Id); SaveConferenceToTeam(context, "MIN", nfcConferenceId, season.Id); SaveConferenceToTeam(context, "NO", nfcConferenceId, season.Id); SaveConferenceToTeam(context, "NYG", nfcConferenceId, season.Id); SaveConferenceToTeam(context, "PHI", nfcConferenceId, season.Id); SaveConferenceToTeam(context, "SEA", nfcConferenceId, season.Id); SaveConferenceToTeam(context, "SF", nfcConferenceId, season.Id); SaveConferenceToTeam(context, "TB", nfcConferenceId, season.Id); SaveConferenceToTeam(context, "WAS", nfcConferenceId, season.Id); } context.SaveChanges(); } private static void SaveConferenceToTeam(AmerFamilyPlayoffContext context, string abbreviation, int conferenceId, int seasonId) { foreach (var team in context.Teams.Where(st => st.Abbreviation == abbreviation).ToList()) { context.Add(new SeasonTeam { SeasonId = seasonId, Team = team, ConferenceId = conferenceId }); } } public virtual void SeedTeams(AmerFamilyPlayoffContext context) { var teamList = new List<Team>(); teamList.Add(new Team { Abbreviation = "ARI", Location = "Arizona", Name = "Cardinals" }); teamList.Add(new Team { Abbreviation = "ATL", Location = "Atlanta", Name = "Falcons" }); teamList.Add(new Team { Abbreviation = "BAL", Location = "Baltimore", Name = "Ravens" }); teamList.Add(new Team { Abbreviation = "BUF", Location = "Buffalo", Name = "Bills" }); teamList.Add(new Team { Abbreviation = "CAR", Location = "Carolina", Name = "Panthers" }); teamList.Add(new Team { Abbreviation = "CHI", Location = "Chicago", Name = "Bears" }); teamList.Add(new Team { Abbreviation = "CIN", Location = "Cincinnati", Name = "Bengals" }); teamList.Add(new Team { Abbreviation = "CLE", Location = "Cleveland", Name = "Browns" }); teamList.Add(new Team { Abbreviation = "DAL", Location = "Dallas", Name = "Cowboys" }); teamList.Add(new Team { Abbreviation = "DEN", Location = "Denver", Name = "Broncos" }); teamList.Add(new Team { Abbreviation = "DET", Location = "Detroit", Name = "Lions" }); teamList.Add(new Team { Abbreviation = "GB", Location = "Green Bay", Name = "Packers" }); teamList.Add(new Team { Abbreviation = "HOU", Location = "Houston", Name = "Texans" }); teamList.Add(new Team { Abbreviation = "IND", Location = "Indianapolis", Name = "Colts" }); teamList.Add(new Team { Abbreviation = "JAX", Location = "Jacksonville", Name = "Jaguars" }); teamList.Add(new Team { Abbreviation = "KC", Location = "Kansas City", Name = "Chiefs" }); teamList.Add(new Team { Abbreviation = "LAC", Location = "Los Angeles", Name = "Chargers" }); teamList.Add(new Team { Abbreviation = "LAR", Location = "Los Angeles", Name = "Rams" }); teamList.Add(new Team { Abbreviation = "LV", Location = "Las Vegas", Name = "Raiders" }); teamList.Add(new Team { Abbreviation = "MIA", Location = "Miami", Name = "Dolphins" }); teamList.Add(new Team { Abbreviation = "MIN", Location = "Minnesota", Name = "Vikings" }); teamList.Add(new Team { Abbreviation = "NE", Location = "New England", Name = "Patriots" }); teamList.Add(new Team { Abbreviation = "NO", Location = "New Orleans", Name = "Saints" }); teamList.Add(new Team { Abbreviation = "NYG", Location = "New York", Name = "Giants" }); teamList.Add(new Team { Abbreviation = "NYJ", Location = "New York", Name = "Jets" }); teamList.Add(new Team { Abbreviation = "PHI", Location = "Philadelphia", Name = "Eagles" }); teamList.Add(new Team { Abbreviation = "PIT", Location = "Pittsburgh", Name = "Steelers" }); teamList.Add(new Team { Abbreviation = "SEA", Location = "Seattle", Name = "Seahawks" }); teamList.Add(new Team { Abbreviation = "SF", Location = "San Francisco", Name = "49ers" }); teamList.Add(new Team { Abbreviation = "TB", Location = "Tampa Bay", Name = "Buccaneers" }); teamList.Add(new Team { Abbreviation = "TEN", Location = "Tennessee", Name = "Titans" }); teamList.Add(new Team { Abbreviation = "WAS", Location = "Washington", Name = "Football Team" }); context.AddRange(teamList); context.SaveChanges(); } public virtual void SeedPlayoffs(AmerFamilyPlayoffContext context) { context.Add(new Playoff { Season = context.Seasons.FirstOrDefault(s => s.Year == 2019) }); context.SaveChanges(); } public virtual void SeedPlayoffTeams(AmerFamilyPlayoffContext context) { context.Add(new PlayoffTeam { PlayoffId = 1, SeasonTeamId = 2, Seed = 3, }); context.SaveChanges(); } } }
48.569307
135
0.579859
6faf554c9e8c358a0c5c8e68c9e7b6e1a0e14cfc
917
rb
Ruby
app/controllers/application_controller.rb
nbert100/sinatra_places
b026a5c68cb30ee8d06c5f6663b97b14b0c5c033
[ "Unlicense" ]
null
null
null
app/controllers/application_controller.rb
nbert100/sinatra_places
b026a5c68cb30ee8d06c5f6663b97b14b0c5c033
[ "Unlicense" ]
3
2020-06-25T07:43:38.000Z
2022-02-26T05:33:34.000Z
app/controllers/application_controller.rb
nbert100/sinatra_places
b026a5c68cb30ee8d06c5f6663b97b14b0c5c033
[ "Unlicense" ]
null
null
null
require './config/environment' class ApplicationController < Sinatra::Base configure do set :public_folder, 'public' set :views, 'app/views' enable :sessions set :session_secret, "places_app" register Sinatra::Flash set :show_exceptions, false end error do "404 ERROR PAGE: Well! This is embarrassing! #{env['sinatra.error'].message}" end get '/' do if logged_in? redirect "/users/#{current_user.id}" else erb :welcome end end helpers do def logged_in? !!current_user end def current_user @current_user ||= User.find_by(id: session[:user_id]) end def authorized_to_edit?(place) place.user == current_user end def redirect_if_not_logged_in if !logged_in? flash[:error] = "Please log in to view this page" redirect '/' end end end end
17.634615
81
0.613959
aea243a7b0b6c5d11dc412ceeaf199ebbd64c829
4,399
cs
C#
Samples/HtcMockSymphony/ArmoniK.Samples.HtcMockSymphonyPackage/ServiceContainer.cs
aneoconsulting/ArmoniK.Samples
4aff75a3ef73a5fc04402e25250c349397c6cf43
[ "Apache-2.0" ]
5
2021-12-19T22:56:47.000Z
2022-01-17T13:19:33.000Z
Samples/HtcMockSymphony/ArmoniK.Samples.HtcMockSymphonyPackage/ServiceContainer.cs
aneoconsulting/ArmoniK.Samples
4aff75a3ef73a5fc04402e25250c349397c6cf43
[ "Apache-2.0" ]
null
null
null
Samples/HtcMockSymphony/ArmoniK.Samples.HtcMockSymphonyPackage/ServiceContainer.cs
aneoconsulting/ArmoniK.Samples
4aff75a3ef73a5fc04402e25250c349397c6cf43
[ "Apache-2.0" ]
null
null
null
// This file is part of the ArmoniK project // // Copyright (C) ANEO, 2021-2022. // W. Kirschenmann <[email protected]> // J. Gurhem <[email protected]> // D. Dubuc <[email protected]> // L. Ziane Khodja <[email protected]> // F. Lemaitre <[email protected]> // S. Djebbar <[email protected]> // J. Fonseca <[email protected]> // D. Brasseur <[email protected]> // // 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. using ArmoniK.DevelopmentKit.Common.Exceptions; using ArmoniK.DevelopmentKit.SymphonyApi; using ArmoniK.DevelopmentKit.SymphonyApi.api; using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.Linq; using System.Text; using Htc.Mock.Core; namespace ArmoniK.Samples.HtcMockSymphony.Packages { public class ServiceContainer : ServiceContainerBase { private ILogger<ServiceContainer> _logger; public override void OnCreateService(ServiceContext serviceContext) { _logger = LoggerFactory.CreateLogger<ServiceContainer>(); } public override void OnSessionEnter(SessionContext sessionContext) { //END USER PLEASE FIXME } public override byte[] OnInvoke(SessionContext sessionContext, TaskContext taskContext) { try { var (runConfiguration, request) = DataAdapter.ReadPayload(taskContext.TaskInput); var inputs = request.Dependencies .ToDictionary(id => id, id => { _logger.LogInformation("Looking for result for Id {id}", id); var isOkay = taskContext.DataDependencies.TryGetValue(id, out var data); if (!isOkay) { throw new KeyNotFoundException(id); } return Encoding.Default.GetString(data); }); var requestProcessor = new RequestProcessor(true, true, true, runConfiguration, _logger); var res = requestProcessor.GetResult(request, inputs); _logger.LogDebug("Result for processing request is HasResult={hasResult}, Value={value}", res.Result.HasResult, res.Result.Value); if (res.Result.HasResult) { return Encoding.Default.GetBytes(res.Result.Value); } var requests = res.SubRequests.GroupBy(r => r.Dependencies is null || r.Dependencies.Count == 0) .ToDictionary(g => g.Key, g => g); var readyRequests = requests[true]; var requestsCount = readyRequests.Count(); _logger.LogDebug("Will submit {count} new tasks", requestsCount); var payloads = new List<byte[]>(requestsCount); payloads.AddRange(readyRequests.Select(readyRequest => DataAdapter.BuildPayload(runConfiguration, readyRequest))); var taskIds = SubmitTasks(payloads); var req = requests[false].Single(); req.Dependencies.Clear(); foreach (var t in taskIds) { req.Dependencies.Add(t); } SubmitTasksWithDependencies(new List<Tuple<byte[], IList<string>>>( new List<Tuple<byte[], IList<string>>> { new( DataAdapter.BuildPayload(runConfiguration, req), req.Dependencies ), }), true); return null; } catch (Exception ex) { _logger.LogError(ex, "Error while computing task"); throw new WorkerApiException("Error while computing task", ex); } } public override void OnSessionLeave(SessionContext sessionContext) { //END USER PLEASE FIXME } public override void OnDestroyService(ServiceContext serviceContext) { //END USER PLEASE FIXME } } }
32.345588
105
0.622414
029ab28c0d8d12a4cebdeb14483fe8731bda23ad
17,991
cxx
C++
SimModel_Python_API/simmodel_swig/SimModel_Dll_lib/framework/SimSpaceBoundary.cxx
EnEff-BIM/EnEffBIM-Framework
6328d39b498dc4065a60b5cc9370b8c2a9a1cddf
[ "MIT" ]
3
2016-05-30T15:12:16.000Z
2022-03-22T08:11:13.000Z
SimModel_Python_API/simmodel_swig/SimModel_Dll_lib/framework/SimSpaceBoundary.cxx
EnEff-BIM/EnEffBIM-Framework
6328d39b498dc4065a60b5cc9370b8c2a9a1cddf
[ "MIT" ]
21
2016-06-13T11:33:45.000Z
2017-05-23T09:46:52.000Z
SimModel_Python_API/simmodel_swig/SimModel_Dll_lib/framework/SimSpaceBoundary.cxx
EnEff-BIM/EnEffBIM-Framework
6328d39b498dc4065a60b5cc9370b8c2a9a1cddf
[ "MIT" ]
null
null
null
// Copyright (c) 2005-2014 Code Synthesis Tools CC // // This program was generated by CodeSynthesis XSD, an XML Schema to // C++ data binding compiler. // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License version 2 as // published by the Free Software Foundation. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA // // In addition, as a special exception, Code Synthesis Tools CC gives // permission to link this program with the Xerces-C++ library (or with // modified versions of Xerces-C++ that use the same license as Xerces-C++), // and distribute linked combinations including the two. You must obey // the GNU General Public License version 2 in all respects for all of // the code used other than Xerces-C++. If you modify this copy of the // program, you may extend this exception to your version of the program, // but you are not obligated to do so. If you do not wish to do so, delete // this exception statement from your version. // // Furthermore, Code Synthesis Tools CC makes a special exception for // the Free/Libre and Open Source Software (FLOSS) which is described // in the accompanying FLOSSE file. // // Begin prologue. // // // End prologue. #include <xsd/cxx/pre.hxx> #include "SimSpaceBoundary.hxx" namespace schema { namespace simxml { namespace ResourcesGeneral { // SimSpaceBoundary // const SimSpaceBoundary::RelatingSpace_optional& SimSpaceBoundary:: RelatingSpace () const { return this->RelatingSpace_; } SimSpaceBoundary::RelatingSpace_optional& SimSpaceBoundary:: RelatingSpace () { return this->RelatingSpace_; } void SimSpaceBoundary:: RelatingSpace (const RelatingSpace_type& x) { this->RelatingSpace_.set (x); } void SimSpaceBoundary:: RelatingSpace (const RelatingSpace_optional& x) { this->RelatingSpace_ = x; } void SimSpaceBoundary:: RelatingSpace (::std::auto_ptr< RelatingSpace_type > x) { this->RelatingSpace_.set (x); } const SimSpaceBoundary::RelatedBuildingElement_optional& SimSpaceBoundary:: RelatedBuildingElement () const { return this->RelatedBuildingElement_; } SimSpaceBoundary::RelatedBuildingElement_optional& SimSpaceBoundary:: RelatedBuildingElement () { return this->RelatedBuildingElement_; } void SimSpaceBoundary:: RelatedBuildingElement (const RelatedBuildingElement_type& x) { this->RelatedBuildingElement_.set (x); } void SimSpaceBoundary:: RelatedBuildingElement (const RelatedBuildingElement_optional& x) { this->RelatedBuildingElement_ = x; } void SimSpaceBoundary:: RelatedBuildingElement (::std::auto_ptr< RelatedBuildingElement_type > x) { this->RelatedBuildingElement_.set (x); } const SimSpaceBoundary::ConnectionGeometry_optional& SimSpaceBoundary:: ConnectionGeometry () const { return this->ConnectionGeometry_; } SimSpaceBoundary::ConnectionGeometry_optional& SimSpaceBoundary:: ConnectionGeometry () { return this->ConnectionGeometry_; } void SimSpaceBoundary:: ConnectionGeometry (const ConnectionGeometry_type& x) { this->ConnectionGeometry_.set (x); } void SimSpaceBoundary:: ConnectionGeometry (const ConnectionGeometry_optional& x) { this->ConnectionGeometry_ = x; } void SimSpaceBoundary:: ConnectionGeometry (::std::auto_ptr< ConnectionGeometry_type > x) { this->ConnectionGeometry_.set (x); } const SimSpaceBoundary::PhysicalOrVirtualBoundary_optional& SimSpaceBoundary:: PhysicalOrVirtualBoundary () const { return this->PhysicalOrVirtualBoundary_; } SimSpaceBoundary::PhysicalOrVirtualBoundary_optional& SimSpaceBoundary:: PhysicalOrVirtualBoundary () { return this->PhysicalOrVirtualBoundary_; } void SimSpaceBoundary:: PhysicalOrVirtualBoundary (const PhysicalOrVirtualBoundary_type& x) { this->PhysicalOrVirtualBoundary_.set (x); } void SimSpaceBoundary:: PhysicalOrVirtualBoundary (const PhysicalOrVirtualBoundary_optional& x) { this->PhysicalOrVirtualBoundary_ = x; } void SimSpaceBoundary:: PhysicalOrVirtualBoundary (::std::auto_ptr< PhysicalOrVirtualBoundary_type > x) { this->PhysicalOrVirtualBoundary_.set (x); } const SimSpaceBoundary::InternalOrExternalBoundary_optional& SimSpaceBoundary:: InternalOrExternalBoundary () const { return this->InternalOrExternalBoundary_; } SimSpaceBoundary::InternalOrExternalBoundary_optional& SimSpaceBoundary:: InternalOrExternalBoundary () { return this->InternalOrExternalBoundary_; } void SimSpaceBoundary:: InternalOrExternalBoundary (const InternalOrExternalBoundary_type& x) { this->InternalOrExternalBoundary_.set (x); } void SimSpaceBoundary:: InternalOrExternalBoundary (const InternalOrExternalBoundary_optional& x) { this->InternalOrExternalBoundary_ = x; } void SimSpaceBoundary:: InternalOrExternalBoundary (::std::auto_ptr< InternalOrExternalBoundary_type > x) { this->InternalOrExternalBoundary_.set (x); } const SimSpaceBoundary::OthersideSpaceBoundary_optional& SimSpaceBoundary:: OthersideSpaceBoundary () const { return this->OthersideSpaceBoundary_; } SimSpaceBoundary::OthersideSpaceBoundary_optional& SimSpaceBoundary:: OthersideSpaceBoundary () { return this->OthersideSpaceBoundary_; } void SimSpaceBoundary:: OthersideSpaceBoundary (const OthersideSpaceBoundary_type& x) { this->OthersideSpaceBoundary_.set (x); } void SimSpaceBoundary:: OthersideSpaceBoundary (const OthersideSpaceBoundary_optional& x) { this->OthersideSpaceBoundary_ = x; } void SimSpaceBoundary:: OthersideSpaceBoundary (::std::auto_ptr< OthersideSpaceBoundary_type > x) { this->OthersideSpaceBoundary_.set (x); } const SimSpaceBoundary::ChildSpaceBoundaries_optional& SimSpaceBoundary:: ChildSpaceBoundaries () const { return this->ChildSpaceBoundaries_; } SimSpaceBoundary::ChildSpaceBoundaries_optional& SimSpaceBoundary:: ChildSpaceBoundaries () { return this->ChildSpaceBoundaries_; } void SimSpaceBoundary:: ChildSpaceBoundaries (const ChildSpaceBoundaries_type& x) { this->ChildSpaceBoundaries_.set (x); } void SimSpaceBoundary:: ChildSpaceBoundaries (const ChildSpaceBoundaries_optional& x) { this->ChildSpaceBoundaries_ = x; } void SimSpaceBoundary:: ChildSpaceBoundaries (::std::auto_ptr< ChildSpaceBoundaries_type > x) { this->ChildSpaceBoundaries_.set (x); } const SimSpaceBoundary::GrossSurfaceArea_optional& SimSpaceBoundary:: GrossSurfaceArea () const { return this->GrossSurfaceArea_; } SimSpaceBoundary::GrossSurfaceArea_optional& SimSpaceBoundary:: GrossSurfaceArea () { return this->GrossSurfaceArea_; } void SimSpaceBoundary:: GrossSurfaceArea (const GrossSurfaceArea_type& x) { this->GrossSurfaceArea_.set (x); } void SimSpaceBoundary:: GrossSurfaceArea (const GrossSurfaceArea_optional& x) { this->GrossSurfaceArea_ = x; } const SimSpaceBoundary::SurfaceNormal_optional& SimSpaceBoundary:: SurfaceNormal () const { return this->SurfaceNormal_; } SimSpaceBoundary::SurfaceNormal_optional& SimSpaceBoundary:: SurfaceNormal () { return this->SurfaceNormal_; } void SimSpaceBoundary:: SurfaceNormal (const SurfaceNormal_type& x) { this->SurfaceNormal_.set (x); } void SimSpaceBoundary:: SurfaceNormal (const SurfaceNormal_optional& x) { this->SurfaceNormal_ = x; } void SimSpaceBoundary:: SurfaceNormal (::std::auto_ptr< SurfaceNormal_type > x) { this->SurfaceNormal_.set (x); } } } } #include <xsd/cxx/xml/dom/parsing-source.hxx> #include <xsd/cxx/tree/type-factory-map.hxx> namespace _xsd { static const ::xsd::cxx::tree::type_factory_plate< 0, char > type_factory_plate_init; } namespace schema { namespace simxml { namespace ResourcesGeneral { // SimSpaceBoundary // SimSpaceBoundary:: SimSpaceBoundary () : ::schema::simxml::SimModelCore::SimResourceObject (), RelatingSpace_ (this), RelatedBuildingElement_ (this), ConnectionGeometry_ (this), PhysicalOrVirtualBoundary_ (this), InternalOrExternalBoundary_ (this), OthersideSpaceBoundary_ (this), ChildSpaceBoundaries_ (this), GrossSurfaceArea_ (this), SurfaceNormal_ (this) { } SimSpaceBoundary:: SimSpaceBoundary (const RefId_type& RefId) : ::schema::simxml::SimModelCore::SimResourceObject (RefId), RelatingSpace_ (this), RelatedBuildingElement_ (this), ConnectionGeometry_ (this), PhysicalOrVirtualBoundary_ (this), InternalOrExternalBoundary_ (this), OthersideSpaceBoundary_ (this), ChildSpaceBoundaries_ (this), GrossSurfaceArea_ (this), SurfaceNormal_ (this) { } SimSpaceBoundary:: SimSpaceBoundary (const SimSpaceBoundary& x, ::xml_schema::flags f, ::xml_schema::container* c) : ::schema::simxml::SimModelCore::SimResourceObject (x, f, c), RelatingSpace_ (x.RelatingSpace_, f, this), RelatedBuildingElement_ (x.RelatedBuildingElement_, f, this), ConnectionGeometry_ (x.ConnectionGeometry_, f, this), PhysicalOrVirtualBoundary_ (x.PhysicalOrVirtualBoundary_, f, this), InternalOrExternalBoundary_ (x.InternalOrExternalBoundary_, f, this), OthersideSpaceBoundary_ (x.OthersideSpaceBoundary_, f, this), ChildSpaceBoundaries_ (x.ChildSpaceBoundaries_, f, this), GrossSurfaceArea_ (x.GrossSurfaceArea_, f, this), SurfaceNormal_ (x.SurfaceNormal_, f, this) { } SimSpaceBoundary:: SimSpaceBoundary (const ::xercesc::DOMElement& e, ::xml_schema::flags f, ::xml_schema::container* c) : ::schema::simxml::SimModelCore::SimResourceObject (e, f | ::xml_schema::flags::base, c), RelatingSpace_ (this), RelatedBuildingElement_ (this), ConnectionGeometry_ (this), PhysicalOrVirtualBoundary_ (this), InternalOrExternalBoundary_ (this), OthersideSpaceBoundary_ (this), ChildSpaceBoundaries_ (this), GrossSurfaceArea_ (this), SurfaceNormal_ (this) { if ((f & ::xml_schema::flags::base) == 0) { ::xsd::cxx::xml::dom::parser< char > p (e, true, false, true); this->parse (p, f); } } void SimSpaceBoundary:: parse (::xsd::cxx::xml::dom::parser< char >& p, ::xml_schema::flags f) { this->::schema::simxml::SimModelCore::SimResourceObject::parse (p, f); for (; p.more_content (); p.next_content (false)) { const ::xercesc::DOMElement& i (p.cur_element ()); const ::xsd::cxx::xml::qualified_name< char > n ( ::xsd::cxx::xml::dom::name< char > (i)); // RelatingSpace // if (n.name () == "RelatingSpace" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/ResourcesGeneral") { ::std::auto_ptr< RelatingSpace_type > r ( RelatingSpace_traits::create (i, f, this)); if (!this->RelatingSpace_) { this->RelatingSpace_.set (r); continue; } } // RelatedBuildingElement // if (n.name () == "RelatedBuildingElement" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/ResourcesGeneral") { ::std::auto_ptr< RelatedBuildingElement_type > r ( RelatedBuildingElement_traits::create (i, f, this)); if (!this->RelatedBuildingElement_) { this->RelatedBuildingElement_.set (r); continue; } } // ConnectionGeometry // if (n.name () == "ConnectionGeometry" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/ResourcesGeneral") { ::std::auto_ptr< ConnectionGeometry_type > r ( ConnectionGeometry_traits::create (i, f, this)); if (!this->ConnectionGeometry_) { this->ConnectionGeometry_.set (r); continue; } } // PhysicalOrVirtualBoundary // if (n.name () == "PhysicalOrVirtualBoundary" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/ResourcesGeneral") { ::std::auto_ptr< PhysicalOrVirtualBoundary_type > r ( PhysicalOrVirtualBoundary_traits::create (i, f, this)); if (!this->PhysicalOrVirtualBoundary_) { this->PhysicalOrVirtualBoundary_.set (r); continue; } } // InternalOrExternalBoundary // if (n.name () == "InternalOrExternalBoundary" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/ResourcesGeneral") { ::std::auto_ptr< InternalOrExternalBoundary_type > r ( InternalOrExternalBoundary_traits::create (i, f, this)); if (!this->InternalOrExternalBoundary_) { this->InternalOrExternalBoundary_.set (r); continue; } } // OthersideSpaceBoundary // if (n.name () == "OthersideSpaceBoundary" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/ResourcesGeneral") { ::std::auto_ptr< OthersideSpaceBoundary_type > r ( OthersideSpaceBoundary_traits::create (i, f, this)); if (!this->OthersideSpaceBoundary_) { this->OthersideSpaceBoundary_.set (r); continue; } } // ChildSpaceBoundaries // if (n.name () == "ChildSpaceBoundaries" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/ResourcesGeneral") { ::std::auto_ptr< ChildSpaceBoundaries_type > r ( ChildSpaceBoundaries_traits::create (i, f, this)); if (!this->ChildSpaceBoundaries_) { this->ChildSpaceBoundaries_.set (r); continue; } } // GrossSurfaceArea // if (n.name () == "GrossSurfaceArea" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/ResourcesGeneral") { if (!this->GrossSurfaceArea_) { this->GrossSurfaceArea_.set (GrossSurfaceArea_traits::create (i, f, this)); continue; } } // SurfaceNormal // if (n.name () == "SurfaceNormal" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/ResourcesGeneral") { ::std::auto_ptr< SurfaceNormal_type > r ( SurfaceNormal_traits::create (i, f, this)); if (!this->SurfaceNormal_) { this->SurfaceNormal_.set (r); continue; } } break; } } SimSpaceBoundary* SimSpaceBoundary:: _clone (::xml_schema::flags f, ::xml_schema::container* c) const { return new class SimSpaceBoundary (*this, f, c); } SimSpaceBoundary& SimSpaceBoundary:: operator= (const SimSpaceBoundary& x) { if (this != &x) { static_cast< ::schema::simxml::SimModelCore::SimResourceObject& > (*this) = x; this->RelatingSpace_ = x.RelatingSpace_; this->RelatedBuildingElement_ = x.RelatedBuildingElement_; this->ConnectionGeometry_ = x.ConnectionGeometry_; this->PhysicalOrVirtualBoundary_ = x.PhysicalOrVirtualBoundary_; this->InternalOrExternalBoundary_ = x.InternalOrExternalBoundary_; this->OthersideSpaceBoundary_ = x.OthersideSpaceBoundary_; this->ChildSpaceBoundaries_ = x.ChildSpaceBoundaries_; this->GrossSurfaceArea_ = x.GrossSurfaceArea_; this->SurfaceNormal_ = x.SurfaceNormal_; } return *this; } SimSpaceBoundary:: ~SimSpaceBoundary () { } } } } #include <istream> #include <xsd/cxx/xml/sax/std-input-source.hxx> #include <xsd/cxx/tree/error-handler.hxx> namespace schema { namespace simxml { namespace ResourcesGeneral { } } } #include <xsd/cxx/post.hxx> // Begin epilogue. // // // End epilogue.
29.835821
132
0.617642
65b251e46399748335df9fa09ee9fd776196f642
577
lua
Lua
samples/demo_next_block.lua
gberger/malu
36fc6c6bf6db2cd18fb39397262038cf4f14a1f3
[ "MIT" ]
1
2016-12-13T15:53:53.000Z
2016-12-13T15:53:53.000Z
samples/demo_next_block.lua
gberger/malu
36fc6c6bf6db2cd18fb39397262038cf4f14a1f3
[ "MIT" ]
null
null
null
samples/demo_next_block.lua
gberger/malu
36fc6c6bf6db2cd18fb39397262038cf4f14a1f3
[ "MIT" ]
null
null
null
@dofile "samples/def_defmacro.lua" @defmacro demo_next_block do print('Reading block...') local block = macros.next_block(next_char) print('Read block is:') print(macros.stringify_tokens(block)) return '' end @demo_next_block do local a = 1 local b = 2 if a > b then repeat local f = function() return 5 end until 1 == 1 elseif a < 0 then while true do a = 10 break end else for i = 1, 10 do a = 15 end end end
17.484848
45
0.514731
c6af7936d1037219b9dc7a79657866759751c6fe
2,579
py
Python
chess-dictionary-validator/chess-dictionary-validator.py
valeriybercha/automate-the-boring-stuff
dbd66f9640596d975be4bd808dc6fa22e47ec407
[ "MIT" ]
1
2022-02-20T14:02:37.000Z
2022-02-20T14:02:37.000Z
chess-dictionary-validator/chess-dictionary-validator.py
valeriybercha/automate-the-boring-stuff
dbd66f9640596d975be4bd808dc6fa22e47ec407
[ "MIT" ]
null
null
null
chess-dictionary-validator/chess-dictionary-validator.py
valeriybercha/automate-the-boring-stuff
dbd66f9640596d975be4bd808dc6fa22e47ec407
[ "MIT" ]
null
null
null
# Chess Dictionary Validator Practice Project # Chapter 5 - Dictionary and Structuing Data (Automate the Boring Stuff with Python) # Developer: Valeriy B. def chess_dictionary_validator(inp): # Creating a blank chess dictionary chess_dictionary = dict() # Creating a chess board chess_board = list() for number in range(1, 9): for character in range(97, 105): chess_board.append(chr(character) + str(number)) # Adding chess board to chess dictionary chess_dictionary["chess_board"] = chess_board # Chess pieces chess_pieces = ["king", "queen", "rook", "bishop", "knight", "pawn"] # Blank lists for 'white' and 'black' pieces black_white_pieces = list() for element in range(2): if element == 0: # Adding 'white' pieces to the list for item in chess_pieces: if item == "king" or item == "queen": black_white_pieces.append("w" + item) elif item == "rook" or item == "bishop" or item == "knight": for loop in range(1, 3): black_white_pieces.append("w" + item + str(loop)) elif item == "pawn": for loop in range(1, 9): black_white_pieces.append("w" + item + str(loop)) else: # Adding 'black' pieces to the list for item in chess_pieces: if item == "king" or item == "queen": black_white_pieces.append("b" + item) elif item == "rook" or item == "bishop" or item == "knight": for loop in range(1, 3): black_white_pieces.append("b" + item + str(loop)) elif item == "pawn": for loop in range(1, 9): black_white_pieces.append("b" + item + str(loop)) # Adding pieces to dictionary chess_dictionary["black_white_pieces"] = black_white_pieces # Creating 2 variables for 'piece' and 'position' validation piece_validation = inp.split()[0] position_validation = inp.split()[1] # Verifying if 'piece' and 'position' variables are in the dictionary if piece_validation in chess_dictionary["black_white_pieces"]: if position_validation in chess_dictionary["chess_board"]: print(True) else: print(False) else: print(False) validator = input("Enter a piece and piece position on the board (e.g. 'wking c6'): ") chess_dictionary_validator(validator)
37.376812
86
0.578131
bac025618a16186bb10a22a2656fe3d362d54a98
6,900
swift
Swift
about.iOS/about.Swift/10.Properties.playground/Contents.swift
skyfe79/TIL-iOS
00b4f4410aa22efca2e27257ea9b5554e0f2f9d4
[ "MIT" ]
null
null
null
about.iOS/about.Swift/10.Properties.playground/Contents.swift
skyfe79/TIL-iOS
00b4f4410aa22efca2e27257ea9b5554e0f2f9d4
[ "MIT" ]
null
null
null
about.iOS/about.Swift/10.Properties.playground/Contents.swift
skyfe79/TIL-iOS
00b4f4410aa22efca2e27257ea9b5554e0f2f9d4
[ "MIT" ]
null
null
null
/*: # Properties */ import UIKit /*: ## Stored Properties */ do { struct FixedLengthRange { var firstValue: Int let length: Int } var rangeOfThreeItems = FixedLengthRange(firstValue: 0, length: 3) // the range represents integer values 0, 1, and 2 rangeOfThreeItems.firstValue = 6 // the range now represents integer values 6, 7, and 8 } /*: ### Stored Properties of Constant Structure Instances */ do { struct FixedLengthRange { var firstValue: Int let length: Int } let rangeOfFourItems = FixedLengthRange(firstValue: 0, length: 4) // this range represents integer values 0, 1, 2, and 3 //error rangeOfFourItems.firstValue = 6 // this will report an error, even though firstValue is a variable property } /*: ### Lazy Stored Properties * You must always declare a lazy property as a variable (with the var keyword), because its initial value might not be retrieved until after instance initialization completes. Constant properties must always have a value before initialization completes, and therefore cannot be declared as lazy. */ do { class DataImporter { /* DataImporter is a class to import data from an external file. The class is assumed to take a non-trivial amount of time to initialize. */ var fileName = "data.txt" // the DataImporter class would provide data importing functionality here } class DataManager { lazy var importer = DataImporter() var data = [String]() // the DataManager class would provide data management functionality here } let manager = DataManager() manager.data.append("Some data") manager.data.append("Some more data") // the DataImporter instance for the importer property has not yet been created print(manager.importer.fileName) // the DataImporter instance for the importer property has now been created // Prints "data.txt" } /*: ### Stored Properties and Instance Variables */ /*: ## Computed Properties */ do { struct Point { var x = 0.0, y = 0.0 } struct Size { var width = 0.0, height = 0.0 } struct Rect { var origin = Point() var size = Size() var center: Point { get { let centerX = origin.x + (size.width / 2) let centerY = origin.y + (size.height / 2) return Point(x: centerX, y: centerY) } set(newCenter) { origin.x = newCenter.x - (size.width / 2) origin.y = newCenter.y - (size.height / 2) } } } var square = Rect(origin: Point(x: 0.0, y: 0.0), size: Size(width: 10.0, height: 10.0)) let initialSquareCenter = square.center square.center = Point(x: 15.0, y: 15.0) print("square.origin is now at (\(square.origin.x), \(square.origin.y))") // Prints "square.origin is now at (10.0, 10.0)" } /*: ### Shorthand Setter Declaration */ do { struct Point { var x = 0.0, y = 0.0 } struct Size { var width = 0.0, height = 0.0 } struct AlternativeRect { var origin = Point() var size = Size() var center: Point { get { let centerX = origin.x + (size.width / 2) let centerY = origin.y + (size.height / 2) return Point(x: centerX, y: centerY) } set { origin.x = newValue.x - (size.width / 2) origin.y = newValue.y - (size.height / 2) } } } } /*: ### Read-Only Computed Properties */ do { struct Cuboid { var width = 0.0, height = 0.0, depth = 0.0 var volume: Double { return width * height * depth } } let fourByFiveByTwo = Cuboid(width: 4.0, height: 5.0, depth: 2.0) print("the volume of fourByFiveByTwo is \(fourByFiveByTwo.volume)") // Prints "the volume of fourByFiveByTwo is 40.0" } /*: ## Property Observers */ do { class StepCounter { var totalSteps: Int = 0 { willSet(newTotalSteps) { print("About to set totalSteps to \(newTotalSteps)") } didSet { if totalSteps > oldValue { print("Added \(totalSteps - oldValue) steps") } } } } let stepCounter = StepCounter() stepCounter.totalSteps = 200 // About to set totalSteps to 200 // Added 200 steps stepCounter.totalSteps = 360 // About to set totalSteps to 360 // Added 160 steps stepCounter.totalSteps = 896 // About to set totalSteps to 896 // Added 536 steps } /*: ## Global and Local Variables */ /*: ## Type Properties */ /*: ### Type Property Syntax */ do { struct SomeStructure { static var storedTypeProperty = "Some value." static var computedTypeProperty: Int { return 1 } } enum SomeEnumeration { static var storedTypeProperty = "Some value." static var computedTypeProperty: Int { return 6 } } class SomeClass { static var storedTypeProperty = "Some value." static var computedTypeProperty: Int { return 27 } class var overrideableComputedTypeProperty: Int { return 107 } } print(SomeStructure.storedTypeProperty) // Prints "Some value." SomeStructure.storedTypeProperty = "Another value." print(SomeStructure.storedTypeProperty) // Prints "Another value." print(SomeEnumeration.computedTypeProperty) // Prints "6" print(SomeClass.computedTypeProperty) // Prints "27" } /*: ### Querying and Setting Type Properties */ do { struct AudioChannel { static let thresholdLevel = 10 static var maxInputLevelForAllChannels = 0 var currentLevel: Int = 0 { didSet { if currentLevel > AudioChannel.thresholdLevel { // cap the new audio level to the threshold level currentLevel = AudioChannel.thresholdLevel } if currentLevel > AudioChannel.maxInputLevelForAllChannels { // store this as the new overall maximum input level AudioChannel.maxInputLevelForAllChannels = currentLevel } } } } var leftChannel = AudioChannel() var rightChannel = AudioChannel() leftChannel.currentLevel = 7 print(leftChannel.currentLevel) // Prints "7" print(AudioChannel.maxInputLevelForAllChannels) // Prints "7" rightChannel.currentLevel = 11 print(rightChannel.currentLevel) // Prints "10" print(AudioChannel.maxInputLevelForAllChannels) // Prints "10" }
27.272727
296
0.588406
e27df7fa86884987e3603996a03b931bce3f828c
1,494
py
Python
merge_data_and_k-mer_hsp90s.py
jacksonh1/54-2018-07-28-k_mer_coverage_overlay_redo
c5d1581bb77c0cd6e6afbb55281957b98c5a31df
[ "MIT" ]
null
null
null
merge_data_and_k-mer_hsp90s.py
jacksonh1/54-2018-07-28-k_mer_coverage_overlay_redo
c5d1581bb77c0cd6e6afbb55281957b98c5a31df
[ "MIT" ]
null
null
null
merge_data_and_k-mer_hsp90s.py
jacksonh1/54-2018-07-28-k_mer_coverage_overlay_redo
c5d1581bb77c0cd6e6afbb55281957b98c5a31df
[ "MIT" ]
null
null
null
#!//Users/Jackson/miniconda3/bin/python ''' Created by: Jackson Halpin Date: 5/15/18 ''' import numpy as np import pandas as pd import glob import os np.set_printoptions(suppress=True) import sys import os # %% # ============================================================================== # // TITLE # ============================================================================== # input1 = './m1v2/YMR186W-SRR1520311-Galaxy53-Rm_rRNA_on_data_17--norc-m1-v2-p4.csv' # input2 = './m1v2/YPL240C-SRR1520311-Galaxy53-Rm_rRNA_on_data_17--norc-m1-v2-p4.csv' # base = os.path.basename(Input_name) # basenoext = os.path.splitext(base)[0] input1 = str(sys.argv[1]) input2 = str(sys.argv[2]) input3 = str(sys.argv[3]) # %% # ============================================================================== # // input and merge along alignment_position # ============================================================================== df1 = pd.read_csv(input1) gene1 = '_' + 'data' df2 = pd.read_csv(input2) gene2 = '_' + 'kmers' df3 = pd.merge(df1, df2, on='alignment_position', how='outer', suffixes=(gene1, gene2)) df3 = df3.sort_values('alignment_position') df3['identity'] = df3['sequence' + gene1] != df3['sequence' + gene2] df3.identity = df3.identity.apply(int) # %% # ============================================================================== # // TITLE # ============================================================================== df3.to_csv(input3, index=False)
29.88
85
0.466533
1473a09cb62842b11049c997f6780d49e23a6fe5
863
ts
TypeScript
src/tapped-type.ts
yaroslavya/type-vein
f896047d616415e82e7f70e7f981037de63a76e1
[ "MIT" ]
null
null
null
src/tapped-type.ts
yaroslavya/type-vein
f896047d616415e82e7f70e7f981037de63a76e1
[ "MIT" ]
null
null
null
src/tapped-type.ts
yaroslavya/type-vein
f896047d616415e82e7f70e7f981037de63a76e1
[ "MIT" ]
null
null
null
import { SourceType } from "./source-type"; export const TappedTypeSymbol: unique symbol = Symbol(); /** * A TappedType is a SourceType in an altered form. Its metadata contains a reference to the SourceType it was tapped from. */ export interface TappedType<T extends SourceType = SourceType> { [TappedTypeSymbol]: TappedType.Metadata<T>; } export module TappedType { /** * Checks if a given thing is a TappedType. */ export function is(x?: any): x is TappedType { return SourceType.is(((x || {}) as any as TappedType)[TappedTypeSymbol]?.source); } export interface Metadata<T extends SourceType = SourceType> { source: T; } export function createMetadata<T extends SourceType = SourceType>(source: T): Metadata<T> { return { source }; } }
28.766667
124
0.634994
accbc79ead86ecdcdcf2f740befaaa81f6f76bc0
82
sql
SQL
fbwiki/mediawiki/extensions/OATHAuth/sql/mysql/patch-remove_module_specific_fields.sql
FrederickOberg/frederickoberg.github.io
a1ba4076482dbdba8a0b717db6034d138f01cabe
[ "CC-BY-3.0" ]
1
2020-10-26T00:55:50.000Z
2020-10-26T00:55:50.000Z
fbwiki/mediawiki/extensions/OATHAuth/sql/mysql/patch-remove_module_specific_fields.sql
FrederickOberg/frederickoberg.github.io
a1ba4076482dbdba8a0b717db6034d138f01cabe
[ "CC-BY-3.0" ]
1
2020-11-09T22:18:02.000Z
2020-11-09T22:18:02.000Z
fbwiki/mediawiki/extensions/OATHAuth/sql/mysql/patch-remove_module_specific_fields.sql
FrederickOberg/frederickoberg.github.io
a1ba4076482dbdba8a0b717db6034d138f01cabe
[ "CC-BY-3.0" ]
1
2020-10-26T01:00:32.000Z
2020-10-26T01:00:32.000Z
ALTER TABLE /*_*/oathauth_users DROP COLUMN secret, DROP COLUMN scratch_tokens;
20.5
31
0.792683
df0767d6540a305876a928d87b0367ef7e16fb8d
10,717
rb
Ruby
lib/dart-rb.rb
target/dart-rb
627f8a55f13b1611ada54e1640c76a0942a07d77
[ "Apache-2.0" ]
null
null
null
lib/dart-rb.rb
target/dart-rb
627f8a55f13b1611ada54e1640c76a0942a07d77
[ "Apache-2.0" ]
null
null
null
lib/dart-rb.rb
target/dart-rb
627f8a55f13b1611ada54e1640c76a0942a07d77
[ "Apache-2.0" ]
null
null
null
require 'dart/version' require 'dart/errors' require 'dart/bindings' require 'dart/helpers' require 'dart/convert' require 'dart/cached' module Dart module Common #----- Introspection Methods -----# def obj? @impl.obj? end def object? obj? end def arr? @impl.arr? end def array? arr? end def aggr? @impl.aggr? end def aggregate? aggr? end def str? @impl.str? end def string? str? end def int? @impl.int? end def integer? int? end def dcm? @impl.dcm? end def decimal? dcm? end def bool? @impl.bool? end def boolean? bool? end def null? @impl.null? end def get_type @impl.get_type end def finalized? @impl.finalized? end def get_bytes @impl.get_bytes end def to_s @impl.to_s end def to_json to_s end def dup Helpers.wrap_ffi(@impl.dup) end private def native @impl end end module Unwrappable def unwrap @unwrapped ||= @impl.unwrap end end # God I love ruby sometimes. # This would've taken literally hundreds of lines in C++ module Arithmetic ops = %w{ + - * / % ** & | ^ <=> }.each do |op| eval <<-METHOD def #{op}(num) if num.is_a?(Arithmetic) then unwrap #{op} num.unwrap else unwrap #{op} num end end METHOD end def -@ -unwrap end def coerce(num) [num, unwrap] end end module Bitwise ops = %w{ & | ^ }.each do |op| eval <<-METHOD def #{op}(num) if num.is_a?(Bitwise) then unwrap #{op} num.unwrap else unwrap #{op} num end end METHOD end def ~ ~unwrap end end class Object include Enumerable include Convert include Common prepend Cached def initialize(val = nil) if val.is_a?(Dart::FFI::Packet) @def_val = proc { nil } @impl = val elsif block_given? @def_val = proc { |h, k| yield(h, k) } @impl = Dart::FFI::Packet.make_obj else @def_val = proc { val } @impl = Dart::FFI::Packet.make_obj end end def [](key) if has_key?(key) then @impl.lookup(key) else @def_val.call(self, key) end end def []=(key, value) # Perform the insertion. @impl.update(key, value) end def delete(key) val = self[key] @impl.remove(key) val end def clear @impl.clear self end def has_key?(key) contains?(key) end def size @impl.size end def empty? size == 0 end def lower @impl = @impl.lower self end def finalize lower end def lift @impl = @impl.lift self end def definalize lift end #----- Language Overrides -----# def ==(other) return true if equal?(other) case other when Object then @impl == other.send(:native) when ::Hash then size == other.size && other.each { |k, v| return false unless self[k] == v } && true else false end end def each # Create an enumerator to either consume or return. enum = Enumerator.new do |y| # Get an iterator from our implementation it = @impl.iterator key_it = @impl.key_iterator # Call our block for each child. args = ::Array.new while it.has_next args[0] = Helpers.wrap_ffi(key_it.unwrap) args[1] = Helpers.wrap_ffi(it.unwrap) y.yield(args) it.next key_it.next end end # Check if we can consume the enumerator. if block_given? then enum.each { |a| yield a } && self else enum end end def to_h out = ::Hash.new each { |(k, v)| out[k.unwrap] = v } out end private def make_cache ::Hash.new end def contains?(key) @impl.has_key?(key) end end class Array include Enumerable include Convert include Common prepend Cached def initialize(val_or_size = nil, def_val = nil) if val_or_size.is_a?(Dart::FFI::Packet) && def_val.nil? @impl = val_or_size elsif val_or_size.is_a?(Fixnum) @impl = Dart::FFI::Packet.make_arr if def_val.nil? then @impl.resize(val_or_size) else val_or_size.times { push(def_val) } end else @impl = Dart::FFI::Packet.make_arr end end def [](idx) # Invert our index if it's negative idx = size + idx if idx < 0 @impl.lookup(idx) end def first self[0] end def last self[-1] end def []=(idx, elem) raise ArgumentError, 'Dart Arrays can only index with an integer' unless idx.is_a?(::Fixnum) @impl.resize(idx + 1) if idx >= size @impl.update(idx, elem) end def insert(idx, *elems) raise ArgumentError, 'Dart Arrays can only index with an integer' unless idx.is_a?(::Fixnum) # Iterate over the supplied elements and insert them. @impl.resize(idx) if idx > size elems.each.with_index { |v, i| @impl.insert(idx + i, v) } self end def delete_at(idx) val = self[idx] @impl.remove(idx) val end def unshift(*elems) insert(0, *elems) end def shift delete_at(0) unless empty? end def push(*elems) insert(size, *elems) end def pop delete_at(size - 1) unless empty? end def clear @impl.clear self end def size @impl.size end def empty? size == 0 end #----- Language Overrides -----# def ==(other) return true if equal?(other) case other when Array then @impl == other.send(:native) when ::Array then size == other.size && each_with_index { |v, i| return false unless v == other[i] } && true else false end end def each # Create an enumerator to either consume or return. enum = Enumerator.new do |y| # Get an iterator from our implementation it = @impl.iterator # Call our block for each child. while it.has_next y << Helpers.wrap_ffi(it.unwrap) it.next end end # Check if we can consume the enumerator. if block_given? then enum.each { |v| yield v } && self else enum end end def to_a out = Array.new each { |v| out.push(v) } out end private def make_cache ::Array.new end def contains?(idx) idx < size end end class String include Common include Unwrappable def initialize(val = ::String.new) if val.is_a?(Dart::FFI::Packet) @impl = val else # Create our implementation as the given string. raise ArgumentError, 'Dart::String can only be constructed from a String' unless val.is_a?(::String) @impl = Dart::FFI::Packet.make_str(val) end end def [](idx) unwrap[idx] end def size @impl.size end def empty? size == 0 end def ==(other) return true if equal?(other) case other when String then @impl == other.send(:native) when ::String then unwrap == other else false end end end class Integer include Common include Bitwise include Arithmetic include Unwrappable include ::Comparable def initialize(val = 0) if val.is_a?(Dart::FFI::Packet) @impl = val else # Create our implementation as the given integer. raise ArgumentError, 'Dart::Integer can only be constructed from a Numeric type' unless val.is_a?(::Numeric) raise ArgumentError, 'Dart::Integer conversion would lose precision' unless val.to_i == val @impl = Dart::FFI::Packet.make_primitive(val.to_i, :int) end end def ==(other) return true if equal?(other) case other when Integer then @impl == other.send(:native) when ::Fixnum then unwrap == other else false end end end class Decimal include Common include Arithmetic include Unwrappable include ::Comparable def initialize(val = 0.0) if val.is_a?(Dart::FFI::Packet) @impl = val else # Create our implementation as the given decimal. raise ArgumentError, 'Dart::Decimal can only be constructed from a Numeric type' unless val.is_a?(::Numeric) @impl = Dart::FFI::Packet.make_primitive(val.to_f, :dcm) end end def ==(other) return true if equal?(other) case other when Decimal then @impl == other.send(:native) when ::Float then unwrap == other else false end end end class Boolean include Common include Unwrappable def initialize(val = false) if val.is_a?(Dart::FFI::Packet) @impl = val else # Create our implementation as the given decimal. unless val.is_a?(TrueClass) || val.is_a?(FalseClass) raise ArgumentError, 'Dart::Decimal can only be constructed from a Boolean' end @impl = Dart::FFI::Packet.make_primitive(val ? 1 : 0, :bool) end end def ==(other) return true if equal?(other) case other when Boolean then @impl == other.send(:native) when ::TrueClass then unwrap when ::FalseClass then !unwrap else false end end end class Null include Common def initialize @impl = Dart::FFI::Packet.make_null end def ==(other) return true if equal?(other) case other when Null then true when NilClass then true else false end end end def self.from_json(str, finalize = true) Helpers.wrap_ffi(Dart::FFI::Packet.from_json(str, finalize)) end def self.from_bytes(bytes) Helpers.wrap_ffi(Dart::FFI::Packet.from_bytes(bytes)) end module Patch def ==(other) if other.is_a?(Dart::Common) then other == self else super end end end end # XXX: Doesn't feel good. #----- Monkey Patches -----# class Hash prepend Dart::Patch include Dart::Convert end class Array prepend Dart::Patch include Dart::Convert end class String prepend Dart::Patch include Dart::Convert end class Fixnum include Dart::Convert end class Float include Dart::Convert end class NilClass include Dart::Convert end
18.351027
116
0.567603
53f20dca67aa4bbff4bb7d694b32f1ad8fb2b861
1,269
lua
Lua
src/utils/Constants.lua
striver-ing/WuZiQi
0372cbbea0c8e8c02adc625eda5b745c0faad8f8
[ "MIT" ]
4
2020-06-09T17:05:41.000Z
2021-08-21T06:19:35.000Z
src/utils/Constants.lua
striver-ing/WuZiQi
0372cbbea0c8e8c02adc625eda5b745c0faad8f8
[ "MIT" ]
null
null
null
src/utils/Constants.lua
striver-ing/WuZiQi
0372cbbea0c8e8c02adc625eda5b745c0faad8f8
[ "MIT" ]
null
null
null
---------------------------- --版权: [email protected] --作用: 全局变量 --作者: liubo --时间: 20160129 --备注: ---------------------------- --帧数 FPS = 60 --棋盘 -- 左下角坐标 CHESS_OFFSETX = 25 CHESS_OFFSETY = 51 --棋盘格子的宽度 CHESS_SETP = 48 CHESS_GRID_NUM = 15 --棋子类型 NO_CHESS = -1 WHITE = 0 BLACK = 1 --无穷大 INFINITY = 0Xffffff --置换表的大小 HASH_TABLE_SIZE = 1024 * 1024 --描述棋盘估分的含义 准确值 最坏值 最好值 ENTRY_TYPE = { exact = 0, lowerBound = 1, upperBound = 2 } --发送消息的头 MSG = { ADD_CHESS = 0x10000001, TALK = 0x10000002, --请求 如悔棋重玩 REQUEST = 0x10000003, --悔棋 RETRACT = 0x10000004, RETRACT_OK = 0x10000005, RETRACT_REFUSED = 0x10000006, --重玩 RESTART = 0x10000007, RESTART_OK = 0x10000008, RESTART_REFUSED = 0x10000009, } -- --棋型分数 从高位到低位分别表示 -- --连五,活四,眠四,活三,活二/眠三,活一/眠二, 眠一 -- SCORE = { -- --活 -- ONE = 10, -- TWO = 100, -- THREE = 1000, -- FOUR =100000, -- FIVE = 1000000, -- --眠 -- SONE = 1, -- STWO = 10, -- STHREE = 100, -- SFOUR = 10000 -- } --音效 SAVA_STRING_SOUND_EFFECT_ENABLE = "usersoundeffectenable" SAVA_STRING_SOUND_MUSIC_ENABLE = "usersoundmusicenable"
17.383562
57
0.51773
cf0666c2251ebcbe3928de349930ee837c4d0e70
2,259
php
PHP
database/migrations/2020_03_16_014330_create_table_products.php
codersharer/wantgains
44b4a3db54a7bfb79951d41a25641cd165d52867
[ "MIT" ]
null
null
null
database/migrations/2020_03_16_014330_create_table_products.php
codersharer/wantgains
44b4a3db54a7bfb79951d41a25641cd165d52867
[ "MIT" ]
null
null
null
database/migrations/2020_03_16_014330_create_table_products.php
codersharer/wantgains
44b4a3db54a7bfb79951d41a25641cd165d52867
[ "MIT" ]
null
null
null
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class CreateTableProducts extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('products', function (Blueprint $table) { $table->bigIncrements('id'); $table->string('product_id_in_aff')->nullable(false)->comment('link在联盟中的id'); $table->integer('affiliate_id')->nullable(false)->comment('联盟id'); $table->string('id_in_aff')->nullable(false)->comment('商家在联盟中id'); $table->bigInteger('domain_id')->nullable(false)->comment('domainid'); $table->string('domain')->nullable()->comment('domain'); $table->text('name')->nullable(false)->comment('促销名称'); $table->text('category')->nullable()->comment('分类'); $table->text('description')->nullable()->comment('描述'); $table->text('track_link')->nullable()->comment('促销链接'); $table->text('destination_url')->nullable()->comment('实际最终地址'); $table->text('image_url')->nullable()->comment('图片url'); $table->float('price',20,2)->nullable()->comment('原价'); $table->float('real_price',20,2)->nullable()->comment('实际价格'); $table->string('sku')->nullable()->comment('sku'); $table->dateTime('promotion_start_at')->nullable()->comment('促销开始时间'); $table->dateTime('promotion_end_at')->nullable()->comment('促销结束时间'); $table->tinyInteger('is_promotion')->nullable(false)->default(0)->comment('是否为促销 0.否 1.是'); $table->tinyInteger('status')->nullable(false)->default(1)->comment('状态 0.下线 1.在线'); $table->unique(['affiliate_id', 'product_id_in_aff'], 'unique_affiliateid_productidinaff'); $table->index(['domain'], 'idx_domain'); $table->index(['domain_id'], 'idx_domainid'); $table->index(['updated_at'], 'idx_updatedat'); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('products'); } }
41.833333
103
0.582559
719563ccb71108ab470a75eb967edd15cb55f6c5
4,827
rs
Rust
pallets/provider/src/tests.rs
LwwL-123/hamster
3766d19a742421b8b7eb0a545c69de19f3b6ac13
[ "Apache-2.0" ]
3
2022-01-10T03:32:04.000Z
2022-03-18T06:43:05.000Z
pallets/provider/src/tests.rs
LwwL-123/hamster
3766d19a742421b8b7eb0a545c69de19f3b6ac13
[ "Apache-2.0" ]
null
null
null
pallets/provider/src/tests.rs
LwwL-123/hamster
3766d19a742421b8b7eb0a545c69de19f3b6ac13
[ "Apache-2.0" ]
4
2022-01-10T10:27:01.000Z
2022-03-28T05:45:56.000Z
use crate::{Error, mock::*}; use frame_support::{assert_ok, assert_noop}; use primitives::p_provider::ResourceStatus; #[test] fn it_works_for_default_value() { new_test_pub().execute_with(|| { // Dispatch a signed extrinsic. // Read pallet storage and assert an expected result. assert_eq!(Provider::resource_index(), 1); }); } #[test] fn it_works_for_register_resource(){ new_test_ext().execute_with(|| { let peer_id = "abcd"; let cpu:u64 = 1; let memory:u64 = 1; let system = "ubuntu"; let cpu_model = "Intel 8700k"; let price = 1000; let rent_duration_hour:u32 = 1; let resource_index:u64 = 0; let account_id = 1; assert_ok!(Provider::register_resource( Origin::signed(account_id), peer_id.as_bytes().to_vec(), cpu, memory, system.as_bytes().to_vec(), cpu_model.as_bytes().to_vec(), price, rent_duration_hour )); assert_eq!(Provider::resource_count(), 1); let mut a = Vec::new(); let x:u64 = 0; a.push(x); assert_eq!(Provider::provider(account_id), Some(a)); assert_eq!(Provider::resource_index(),resource_index+1); let compute_resource = Provider::resource(resource_index).unwrap(); assert_eq!(peer_id.as_bytes().to_vec(),compute_resource.peer_id); let mut future_expired_resouce = Vec::new(); future_expired_resouce.push(resource_index); assert_eq!(Provider::future_expired_resource(600),Some(future_expired_resouce)); }) } #[test] fn it_works_for_modify_resource_price(){ new_test_pub().execute_with(|| { let resource_index:u64 = 1; let modify_price_u128:u128 = 300; let modify_price_u64:u64 = 300; assert_noop!(Provider::modify_resource_price(Origin::signed(1),2,100),Error::<Test>::ResourceNotFound); assert_noop!(Provider::modify_resource_price(Origin::signed(2),1,100),Error::<Test>::IllegalRequest); assert_ok!(Provider::modify_resource_price(Origin::signed(1),resource_index,modify_price_u64)); let compute_resource = Provider::resource(resource_index).unwrap(); assert_eq!(modify_price_u128,compute_resource.rental_info.rent_unit_price); }); } #[test] fn is_works_for_add_resource_duration(){ new_test_pub().execute_with(||{ let resource_index:u64 = 1; assert_noop!(Provider::add_resource_duration(Origin::signed(1),2,1),Error::<Test>::ResourceNotFound); assert_noop!(Provider::add_resource_duration(Origin::signed(2),1,1),Error::<Test>::IllegalRequest); assert_ok!(Provider::add_resource_duration(Origin::signed(1),1,1)); let compute_resource = Provider::resource(resource_index).unwrap(); let end_of_rent = 1200; assert_eq!(end_of_rent,compute_resource.rental_info.end_of_rent); let mut future_expired_resouce = Vec::new(); future_expired_resouce.push(resource_index); assert_eq!(Provider::future_expired_resource(end_of_rent),Some(future_expired_resouce)); assert_eq!(Provider::future_expired_resource(600),Some(Vec::new())); }); } #[test] fn is_works_for_remove_resource(){ new_test_pub().execute_with(||{ assert_noop!(Provider::remove_resource(Origin::signed(1),2),Error::<Test>::ResourceNotFound); assert_noop!(Provider::remove_resource(Origin::signed(2),1),Error::<Test>::IllegalRequest); let resource_index:u64 = 1; assert_ok!(Provider::remove_resource(Origin::signed(1),resource_index)); assert_eq!(Provider::resource_count(), 0); assert_eq!(Provider::future_expired_resource(600),Some(Vec::new())); assert_eq!(Provider::resource(resource_index),None); }); } #[test] fn is_work_for_change_resource_status(){ new_test_with_resource_offline().execute_with(|| { assert_noop!(Provider::change_resource_status(Origin::signed(1),2),Error::<Test>::ResourceNotFound); assert_noop!(Provider::change_resource_status(Origin::signed(2),1),Error::<Test>::IllegalRequest); let resource_index:u64 = 1; assert_ok!(Provider::change_resource_status(Origin::signed(1),resource_index)); let compute_resource = Provider::resource(resource_index).unwrap(); assert_eq!(ResourceStatus::Unused,compute_resource.status); }); new_test_pub().execute_with(|| { assert_noop!(Provider::change_resource_status(Origin::signed(1),2),Error::<Test>::ResourceNotFound); assert_noop!(Provider::change_resource_status(Origin::signed(2),1),Error::<Test>::IllegalRequest); assert_noop!(Provider::change_resource_status(Origin::signed(1),1),Error::<Test>::UnmodifiableStatusNow); }); }
36.293233
113
0.671639
0276aff95eb79ef76baddcf8dac2319d4bf66be9
1,986
cpp
C++
parts/Drive.cpp
fdekruijff/Group-Project-TICT-V1GP-15
ec1de58bf3e5f22066f563e0014760e54d779159
[ "MIT" ]
null
null
null
parts/Drive.cpp
fdekruijff/Group-Project-TICT-V1GP-15
ec1de58bf3e5f22066f563e0014760e54d779159
[ "MIT" ]
null
null
null
parts/Drive.cpp
fdekruijff/Group-Project-TICT-V1GP-15
ec1de58bf3e5f22066f563e0014760e54d779159
[ "MIT" ]
null
null
null
#include <cmath> #include <iostream> #include <unistd.h> #include "./piprograms/BrickPi3.cpp" #include <thread> #include <signal.h> #include <vector> using namespace std; BrickPi3 BP; uint8_t s_contrast = PORT_2; // Light sensor uint8_t m_head = PORT_A; // Head motor uint8_t m_left = PORT_B; // Left motor uint8_t m_right = PORT_C; // Right motor void exit_signal_handler(int signo); //Stop void stop(void){ BP.set_motor_power(m_right, 0); BP.set_motor_power(m_left, 0); } //Drive void dodge(int turn_drive, int degrees, int distance){ //Makes Wall-E turn and drive straight int power =40; if(turn_drive== 0){ BP.set_motor_limits(m_left,35,1200); BP.set_motor_limits(m_right,35,1200); BP.set_motor_position_relative(m_left,degrees*5.95); BP.set_motor_position_relative(m_right,degrees*5.85*-1); }else if(turn_drive==1){ if(distance < 0){ distance *= -1; power *= -1; } BP.set_motor_power(m_left, power); BP.set_motor_power(m_right, power); usleep(76927*distance); stop(); } } int main(){ signal(SIGINT, exit_signal_handler); // register the exit function for Ctrl+C BP.detect(); // Make sure that the BrickPi3 is communicating and that the firmware is compatible with the drivers. BP.set_motor_limits(PORT_B, 60, 0); BP.set_motor_limits(PORT_C, 60, 0); char inp; while(true){ cout << "Press s (stop), d (drive): " << endl; cin >> inp; //Take input from the terminal if (inp=='d'){ //drive or steer, degrees, (rigth positive, left negative), distance int turn_drive = 0; int degrees = 90; int distance =-10; dodge(turn_drive, degrees, distance); }else if (inp=='s'){ stop(); } } return 0; } // Signal handler that will be called when Ctrl+C is pressed to stop the program void exit_signal_handler(int signo){ if(signo == SIGINT){ BP.reset_all(); // Reset everything so there are no run-away motors exit(-2); } }
24.219512
117
0.666163
7daf4a3bbd9019d62aa1c45f353f1f17f54bf242
3,981
rb
Ruby
spec/support/shared_contexts/searches/regulations/base_context.rb
steveholmes/trade-tariff-management
e0693f91976116c24cc6513a165a07e27dabc0c5
[ "MIT" ]
4
2018-11-05T17:33:01.000Z
2020-12-21T11:38:04.000Z
spec/support/shared_contexts/searches/regulations/base_context.rb
steveholmes/trade-tariff-management
e0693f91976116c24cc6513a165a07e27dabc0c5
[ "MIT" ]
97
2018-02-19T16:42:16.000Z
2020-11-06T12:18:26.000Z
spec/support/shared_contexts/searches/regulations/base_context.rb
steveholmes/trade-tariff-management
e0693f91976116c24cc6513a165a07e27dabc0c5
[ "MIT" ]
3
2019-01-10T09:55:32.000Z
2019-07-16T11:31:02.000Z
require 'rails_helper' shared_context "regulations_search_base_context" do let(:group_aaa) do create(:regulation_group, regulation_group_id: "AAA") end let(:group_bbb) do create(:regulation_group, regulation_group_id: "BBB") end let(:base_i1111111) do create(:base_regulation, base_regulation_role: 1, base_regulation_id: "I1111111", information_text: "Base I1111111", regulation_group_id: group_aaa.regulation_group_id, validity_start_date: 1.year.ago) end let(:base_i2222222) do create(:base_regulation, base_regulation_role: 1, base_regulation_id: "I2222222", information_text: "Base I2222222", regulation_group_id: group_bbb.regulation_group_id, validity_start_date: 1.year.ago, effective_end_date: 1.year.from_now) end let(:provisional_anti_dumping_i3333333) do create(:base_regulation, base_regulation_role: 2, base_regulation_id: "I3333333", information_text: "Provisional anti dumping I3333333", regulation_group_id: group_aaa.regulation_group_id, antidumping_regulation_role: 1, related_antidumping_regulation_id: base_i1111111.base_regulation_id, validity_start_date: 1.year.ago) end let(:definitive_anti_dumping_i4444444) do create(:base_regulation, base_regulation_role: 3, base_regulation_id: "I4444444", information_text: "Definitive anti dumping I4444444", regulation_group_id: group_bbb.regulation_group_id, validity_start_date: 1.year.ago, effective_end_date: 1.year.from_now, antidumping_regulation_role: 1, related_antidumping_regulation_id: base_i2222222.base_regulation_id) end let(:modification_r5555555) do create(:modification_regulation, modification_regulation_role: 4, modification_regulation_id: "R5555555", information_text: "Modification R5555555", validity_start_date: 1.year.ago, validity_end_date: 5.days.from_now) end let(:modification_r6666666) do create(:modification_regulation, modification_regulation_role: 4, modification_regulation_id: "R6666666", information_text: "Modification R6666666", validity_start_date: 1.year.ago, validity_end_date: 3.days.from_now) end let(:prorogation_r9999999) do create(:prorogation_regulation, prorogation_regulation_role: 5, prorogation_regulation_id: "R9999999", information_text: "Prorogation R9999999", published_date: 10.days.ago) end let(:complete_abrogation_r7777777) do create(:complete_abrogation_regulation, complete_abrogation_regulation_role: 6, complete_abrogation_regulation_id: "R7777777", information_text: "Complete abrogation R7777777", published_date: 9.days.ago) end let(:explicit_abrogation_r8888888) do create(:explicit_abrogation_regulation, explicit_abrogation_regulation_role: 7, explicit_abrogation_regulation_id: "R8888888", information_text: "Explicit abrogation R8888888", published_date: 1.year.ago) end let(:full_temporary_stop_r9191919) do create(:fts_regulation, full_temporary_stop_regulation_role: 8, full_temporary_stop_regulation_id: "R9191919", information_text: "Full temporary stop R9191919", validity_start_date: 1.year.ago) end before do base_i1111111 base_i2222222 provisional_anti_dumping_i3333333 definitive_anti_dumping_i4444444 modification_r5555555 modification_r6666666 complete_abrogation_r7777777 explicit_abrogation_r8888888 prorogation_r9999999 full_temporary_stop_r9191919 end private def search_results(search_ops) ::RegulationsSearch.new(search_ops) .results .all .sort_by(&:start_date) end def date_to_format(date_in_string) date_in_string.to_date .strftime("%d/%m/%Y") end end
30.389313
74
0.731726
7d3a6e742567d844b90b360859d1e0ff374e2fee
6,570
sql
SQL
Utility Scripts/Decrypt All Encrypted Objects in Server.sql
Tovli/MadeiraToolbox
6945a7a2a36eba3f1ea9808263d27f3b87efde71
[ "MIT" ]
72
2020-04-18T14:29:16.000Z
2022-03-25T09:20:20.000Z
Utility Scripts/Decrypt All Encrypted Objects in Server.sql
Tovli/MadeiraToolbox
6945a7a2a36eba3f1ea9808263d27f3b87efde71
[ "MIT" ]
7
2020-12-05T07:10:47.000Z
2022-03-12T09:29:31.000Z
Utility Scripts/Decrypt All Encrypted Objects in Server.sql
Tovli/MadeiraToolbox
6945a7a2a36eba3f1ea9808263d27f3b87efde71
[ "MIT" ]
36
2020-06-13T16:57:48.000Z
2022-03-24T11:58:18.000Z
-- Must connect to SQL Server using the Dedicate Admin Connection, eg "admin:localhost". Verified with SQL Server 2012. -- Originally from Williams Orellana's blog: http://williamsorellana.org/2012/02/decrypt-sql-stored-procedures/ -- Adapted from Jason Stangroome: https://gist.github.com/jstangroome/4020443 -- The results will be returned in a grid. Be sure to enable "Retain CR/LF on copy or save" (Tools > Options... > Query Results > SQL Server > Results to Grid) SET NOCOUNT, ARITHABORT, XACT_ABORT ON; SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED; DROP TABLE IF EXISTS #Results; CREATE TABLE #Results (DatabaseName sysname, SchemaName sysname, ObjectName sysname, ObjectType sysname NULL, ObjectDefinition nvarchar(max) NULL, DefinitionLength INT NULL); DECLARE @Modules AS TABLE (DBName sysname, ObjectID INT); DECLARE @DatabaseName SYSNAME; DECLARE @ObjectOwnerOrSchema SYSNAME DECLARE @ObjectName SYSNAME DECLARE @spExecuteSQL NVARCHAR(1000) DECLARE @CMD NVARCHAR(MAX) DECLARE DBs CURSOR LOCAL FAST_FORWARD FOR SELECT [name] FROM sys.databases WHERE HAS_DBACCESS([name]) = 1 OPEN DBs; WHILE 1=1 BEGIN FETCH NEXT FROM DBs INTO @DatabaseName; IF @@FETCH_STATUS <> 0 BREAK; SET @spExecuteSQL = QUOTENAME(@DatabaseName) + N'..sp_executesql' INSERT INTO @Modules(DBName,ObjectID) EXEC @spExecuteSQL N'SELECT DISTINCT DB_NAME(), id FROM syscomments WHERE encrypted = 1' WITH RECOMPILE; END CLOSE DBs; DEALLOCATE DBs; DECLARE @ObjectID INT; DECLARE Obj CURSOR LOCAL FAST_FORWARD FOR SELECT DBName, ObjectID FROM @Modules; OPEN Obj; WHILE 1=1 BEGIN FETCH NEXT FROM Obj INTO @DatabaseName, @ObjectID IF @@FETCH_STATUS <> 0 BREAK; SET @ObjectOwnerOrSchema = OBJECT_SCHEMA_NAME(@ObjectID, DB_ID(@DatabaseName)) SET @ObjectName = OBJECT_NAME(@ObjectID, DB_ID(@DatabaseName)) SET @spExecuteSQL = QUOTENAME(@DatabaseName) + N'..sp_executesql' DECLARE @i INT DECLARE @ObjectDataLength INT DECLARE @ContentOfEncryptedObject NVARCHAR(MAX) DECLARE @ContentOfDecryptedObject VARCHAR(MAX) DECLARE @ContentOfFakeObject NVARCHAR(MAX) DECLARE @ContentOfFakeEncryptedObject NVARCHAR(MAX) DECLARE @ObjectType NVARCHAR(128) -- Determine the type of the object IF OBJECT_ID(QUOTENAME(@DatabaseName) + N'.' + QUOTENAME(@ObjectOwnerOrSchema) + '.' + QUOTENAME(@ObjectName), 'PROCEDURE') IS NOT NULL SET @ObjectType = 'PROCEDURE' ELSE IF OBJECT_ID(QUOTENAME(@DatabaseName) + N'.' + QUOTENAME(@ObjectOwnerOrSchema) + '.' + QUOTENAME(@ObjectName), 'TRIGGER') IS NOT NULL SET @ObjectType = 'TRIGGER' ELSE IF OBJECT_ID(QUOTENAME(@DatabaseName) + N'.' + QUOTENAME(@ObjectOwnerOrSchema) + '.' + QUOTENAME(@ObjectName), 'VIEW') IS NOT NULL SET @ObjectType = 'VIEW' ELSE SET @ObjectType = 'FUNCTION' -- Get the binary representation of the object- syscomments no longer holds -- the content of encrypted object. SET @CMD = N' SELECT TOP 1 @ContentOfEncryptedObject = imageval FROM sys.sysobjvalues WHERE objid = @ObjectID AND valclass = 1 and subobjid = 1' EXEC @spExecuteSQL @CMD, N'@ContentOfEncryptedObject NVARCHAR(MAX) OUTPUT, @ObjectID INT', @ContentOfEncryptedObject OUTPUT, @ObjectID; SET @ObjectDataLength = DATALENGTH(@ContentOfEncryptedObject)/2 -- We need to alter the existing object and make it into a dummy object -- in order to decrypt its content. This is done in a transaction -- (which is later rolled back) to ensure that all changes have a minimal -- impact on the database. SET @ContentOfFakeObject = N'ALTER ' + @ObjectType + N' ' + QUOTENAME(@ObjectOwnerOrSchema) + '.' + QUOTENAME(@ObjectName) + N' WITH ENCRYPTION AS' WHILE DATALENGTH(@ContentOfFakeObject)/2 < @ObjectDataLength BEGIN IF DATALENGTH(@ContentOfFakeObject)/2 + 8000 < @ObjectDataLength SET @ContentOfFakeObject = @ContentOfFakeObject + REPLICATE(N'-', 8000) ELSE SET @ContentOfFakeObject = @ContentOfFakeObject + REPLICATE(N'-', @ObjectDataLength - (DATALENGTH(@ContentOfFakeObject)/2)) END -- Since we need to alter the object in order to decrypt it, this is done -- in a transaction SET XACT_ABORT OFF BEGIN TRY BEGIN TRAN EXEC @spExecuteSQL @ContentOfFakeObject IF @@ERROR <> 0 ROLLBACK TRAN -- Get the encrypted content of the new "fake" object. SET @CMD = N' SELECT TOP 1 @ContentOfFakeEncryptedObject = imageval FROM sys.sysobjvalues WHERE objid = @ObjectID AND valclass = 1 and subobjid = 1' EXEC @spExecuteSQL @CMD, N'@ContentOfFakeEncryptedObject NVARCHAR(MAX) OUTPUT, @ObjectID INT', @ContentOfFakeEncryptedObject OUTPUT, @ObjectID; IF @@TRANCOUNT > 0 ROLLBACK TRAN -- Generate a CREATE script for the dummy object text. SET @ContentOfFakeObject = N'CREATE ' + @ObjectType + N' ' +QUOTENAME(@ObjectOwnerOrSchema) + '.' + QUOTENAME(@ObjectName) + N' WITH ENCRYPTION AS' WHILE DATALENGTH(@ContentOfFakeObject)/2 < @ObjectDataLength BEGIN IF DATALENGTH(@ContentOfFakeObject)/2 + 8000 < @ObjectDataLength SET @ContentOfFakeObject = @ContentOfFakeObject + REPLICATE(N'-', 8000) ELSE SET @ContentOfFakeObject = @ContentOfFakeObject + REPLICATE(N'-', @ObjectDataLength - (DATALENGTH(@ContentOfFakeObject)/2)) END SET @i = 1 --Fill the variable that holds the decrypted data with a filler character SET @ContentOfDecryptedObject = N'' WHILE DATALENGTH(@ContentOfDecryptedObject)/2 < @ObjectDataLength BEGIN IF DATALENGTH(@ContentOfDecryptedObject)/2 + 8000 < @ObjectDataLength SET @ContentOfDecryptedObject = @ContentOfDecryptedObject + REPLICATE(N'A', 8000) ELSE SET @ContentOfDecryptedObject = @ContentOfDecryptedObject + REPLICATE(N'A', @ObjectDataLength - (DATALENGTH(@ContentOfDecryptedObject)/2)) END WHILE @i <= @ObjectDataLength BEGIN --xor real & fake & fake encrypted SET @ContentOfDecryptedObject = STUFF(@ContentOfDecryptedObject, @i, 1, NCHAR( UNICODE(SUBSTRING(@ContentOfEncryptedObject, @i, 1)) ^ ( UNICODE(SUBSTRING(@ContentOfFakeObject, @i, 1)) ^ UNICODE(SUBSTRING(@ContentOfFakeEncryptedObject, @i, 1)) ))) SET @i = @i + 1 END END TRY BEGIN CATCH PRINT N'Error decrypting ' + @ObjectType + N' ' +QUOTENAME(@DatabaseName) + N'.' +QUOTENAME(@ObjectOwnerOrSchema) + '.' + QUOTENAME(@ObjectName) + N':' PRINT ERROR_MESSAGE() SET @ContentOfDecryptedObject = NULL END CATCH INSERT INTO #Results VALUES(@DatabaseName, @ObjectOwnerOrSchema, @ObjectName, @ObjectType, @ContentOfDecryptedObject, @ObjectDataLength) END CLOSE Obj; DEALLOCATE Obj; -- output the content of the decrypted object SELECT DatabaseName, SchemaName, ObjectName, ObjectType , DecryptedDefinition = SUBSTRING(ObjectDefinition, 1, DefinitionLength) --, DecryptedDefinitionXML = (SELECT SUBSTRING(ObjectDefinition, 1, DefinitionLength) FOR XML PATH(''), TYPE) FROM #Results
35.13369
174
0.771385
43da14ef1d231fb06005266481c6713cbfdc3e12
565
tsx
TypeScript
hooks/useRelativeYMotion/useRelativeYMotion.tsx
andy-hook/andyhook.dev
383cb512392a3bcda268a2c347f16d7983029f4a
[ "MIT" ]
9
2021-04-13T20:28:34.000Z
2022-03-02T12:54:15.000Z
hooks/useRelativeYMotion/useRelativeYMotion.tsx
andy-hook/2021
d8b3c42ae337903720554229f3049b3ac7e98810
[ "MIT" ]
2
2021-01-03T15:54:50.000Z
2021-01-03T16:05:38.000Z
hooks/useRelativeYMotion/useRelativeYMotion.tsx
andy-hook/andyhook.dev
383cb512392a3bcda268a2c347f16d7983029f4a
[ "MIT" ]
null
null
null
import { useMemo } from 'react' import { useBreakpoint } from 'styled-breakpoints/react-styled' import { inclusiveDown } from '../../style/responsive' import { getRelativeMotionProps, RelativeMotionProps, } from './getRelativeMotionProps' function useRelativeYMotion(offsetValue: number): RelativeMotionProps { const enableRelativeYDistance = useBreakpoint(inclusiveDown('xl')) return useMemo( () => getRelativeMotionProps(Boolean(enableRelativeYDistance), offsetValue), [enableRelativeYDistance, offsetValue] ) } export { useRelativeYMotion }
29.736842
80
0.771681
234b2ca0158891f86692b7384cf4b9f67f37f7bc
3,713
dart
Dart
lib/src/widget/tooltip.dart
CalsRanna/ant_design_flutter
ced75b9859b9081306ba1dde16ef206efb8516ac
[ "MIT" ]
null
null
null
lib/src/widget/tooltip.dart
CalsRanna/ant_design_flutter
ced75b9859b9081306ba1dde16ef206efb8516ac
[ "MIT" ]
null
null
null
lib/src/widget/tooltip.dart
CalsRanna/ant_design_flutter
ced75b9859b9081306ba1dde16ef206efb8516ac
[ "MIT" ]
null
null
null
import 'dart:math'; import 'package:ant_design_flutter/src/enum/placement.dart'; import 'package:ant_design_flutter/src/enum/trigger.dart'; import 'package:ant_design_flutter/src/style/color.dart'; import 'package:flutter/gestures.dart'; import 'package:flutter/material.dart' show Material; import 'package:flutter/widgets.dart'; class Tooltip extends StatefulWidget { const Tooltip({ Key? key, required this.child, this.placement = Placement.top, required this.label, this.trigger = Trigger.hover, }) : super(key: key); final Widget child; final Placement placement; final String label; final Trigger trigger; @override State<Tooltip> createState() => _TooltipState(); } class _TooltipState extends State<Tooltip> { bool hovered = false; bool inserted = false; LayerLink link = LayerLink(); late OverlayEntry entry; @override void initState() { super.initState(); } @override Widget build(BuildContext context) { return MouseRegion( onEnter: _handleEnter, onExit: _handleExit, child: CompositedTransformTarget(link: link, child: widget.child), ); } void updateOverlayEntry() { entry.remove(); var size = context.size; entry = OverlayEntry( builder: (context) => Positioned( height: 38, child: CompositedTransformFollower( followerAnchor: Alignment.bottomCenter, link: link, offset: Offset(0, -1 * size!.height), showWhenUnlinked: false, targetAnchor: Alignment.topCenter, child: Material( elevation: 4, child: _TooltipOverlayEntry(label: widget.label), ), ), ), ); Overlay.of(context)!.insert(entry); } void _handleEnter(PointerEnterEvent event) { var size = context.size; entry = OverlayEntry( builder: (context) => Positioned( height: 38, child: CompositedTransformFollower( followerAnchor: Alignment.bottomCenter, link: link, offset: Offset(0, -1 * size!.height), showWhenUnlinked: false, targetAnchor: Alignment.topCenter, child: Material( elevation: 4, child: _TooltipOverlayEntry(label: widget.label), ), ), ), ); Overlay.of(context)!.insert(entry); } void _handleExit(PointerExitEvent event) { entry.remove(); } } class _TooltipOverlayEntry extends StatelessWidget { const _TooltipOverlayEntry({Key? key, required this.label}) : super(key: key); final String label; @override Widget build(BuildContext context) { return Stack( alignment: AlignmentDirectional.bottomCenter, clipBehavior: Clip.none, children: [ Positioned( bottom: -4, child: Transform.rotate( angle: pi / 4, child: Container( decoration: const BoxDecoration( borderRadius: BorderRadius.only( bottomRight: Radius.circular(2), ), color: Colors.gray_10, ), height: 8, width: 8, ), ), ), Container( alignment: AlignmentDirectional.center, decoration: BoxDecoration( borderRadius: BorderRadius.circular(2), color: Colors.gray_10, ), padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 12), child: Text( label, style: const TextStyle( color: Colors.white, fontSize: 14, height: 1, ), ), ), ], ); } }
25.965035
80
0.594129
41646cff5a0df96c00f9ff2475473d6737910e8c
5,859
rs
Rust
src/data_type.rs
segfo/qrcode
ffb9a41e9c31e5a97bb0b329e57758914e79b68f
[ "Apache-2.0" ]
null
null
null
src/data_type.rs
segfo/qrcode
ffb9a41e9c31e5a97bb0b329e57758914e79b68f
[ "Apache-2.0" ]
null
null
null
src/data_type.rs
segfo/qrcode
ffb9a41e9c31e5a97bb0b329e57758914e79b68f
[ "Apache-2.0" ]
1
2018-12-02T20:32:36.000Z
2018-12-02T20:32:36.000Z
use std; use std::ops::Deref; use std::iter::FromIterator; #[derive(PartialEq)] pub enum DataKind{ Binary,Text } trait AsciiCharType{ fn get_chartype_count(&self)->usize; } struct CharVec{ v:Vec<char>, } impl Deref for CharVec{ type Target=Vec<char>; fn deref(&self)-> &Self::Target{ &self.v } } impl std::ops::DerefMut for CharVec{ fn deref_mut(&mut self) -> &mut Self::Target{ return &mut self.v; } } // イテレータ周りをVecのものを流用する impl FromIterator<char> for CharVec{ fn from_iter<T:IntoIterator<Item=char>>(iter: T) -> Self { let mut c = Vec::<char>::new(); for i in iter{ c.push(i); } CharVec::new(c) } } impl IntoIterator for CharVec{ type Item = char; type IntoIter = ::std::vec::IntoIter<char>; fn into_iter(self)->Self::IntoIter{ self.v.into_iter() } } impl CharVec{ fn new(v:Vec<char>)->Self{ CharVec{ v:v, } } fn alpha(&self,d:u32)->(usize,usize){ let d = d as usize; if 0x41+5 <= d && d <= 0x5a-5|| 0x61+5 <= d && d <= 0x7a-5 { return (d-5,d+5); } if d>0x7a-5{return (d-5,0x7a);} if d<0x41+5{return (0x41,d+5);} if d<0x61+5{return (0x61,d+5);} if d>0x5a-5{return (d-5,0x5a);} (0,0) } } impl AsciiCharType for CharVec{ fn get_chartype_count(&self)->usize{ let mut num=0; let mut numeric = false; let mut v = (*self).clone(); let mut hexstring = true; let mut alphabet_only_hexstr = false; v.sort(); v.dedup(); let mut pmin = 0x00; let mut pmax = 0x00; for c in v.iter(){ let d = *c as u32; if c.is_ascii_hexdigit()==false{ hexstring = false; }else if c.is_ascii_hexdigit()&&c.is_ascii_alphabetic(){ alphabet_only_hexstr = true; } match d{ 0x20...0x2f|0x3a...0x40|0x5b...0x60|0x7b...0x7e=>num+=1, 0x30...0x39 =>{ numeric = true; }, 0x41...0x5a|0x61...0x7a=>{ let (min,max) = self.alpha(d); if pmin <= min && min < pmax { pmax = max; continue; } if max <= pmax && pmin < max { pmin = min; continue; } // かぶりがなかったらとりあえず登録 if pmin < pmax{num += pmax-pmin+1;} if pmin > pmax{num += pmin+1-pmax;} // 新しく範囲を決定する。(ソートされているのでこれで問題なし) pmax = max; pmin = min; }, _=>{ // バイナリデータが入ってきた。 return 256; }, } } if hexstring && alphabet_only_hexstr{ return 16; } if numeric{ num+=10; } if pmax!=pmin{ num += pmax-pmin+1; } num } } use std::env; use std::io::*; macro_rules! input { (source = $s:expr, $($r:tt)*) => { let mut iter = $s.split_whitespace(); let mut next = || { iter.next().unwrap() }; input_inner!{next, $($r)*} }; ($($r:tt)*) => { let stdin = std::io::stdin(); let mut bytes = std::io::Read::bytes(std::io::BufReader::new(stdin.lock())); let mut next = move || -> String{ bytes .by_ref() .map(|r|r.unwrap() as char) .skip_while(|c|c.is_whitespace()) .take_while(|c|!c.is_whitespace()) .collect() }; input_inner!{next, $($r)*} }; } macro_rules! input_inner { ($next:expr) => {}; ($next:expr, ) => {}; ($next:expr, $var:ident : $t:tt $($r:tt)*) => { let $var = read_value!($next, $t); input_inner!{$next $($r)*} }; } macro_rules! read_value { ($next:expr, ( $($t:tt),* )) => { ( $(read_value!($next, $t)),* ) }; ($next:expr, [ $t:tt ; $len:expr ]) => { (0..$len).map(|_| read_value!($next, $t)).collect::<Vec<_>>() }; ($next:expr, chars) => { read_value!($next, String).chars().collect::<Vec<char>>() }; ($next:expr, usize1) => { read_value!($next, usize) - 1 }; ($next:expr, $t:ty) => { $next().parse::<$t>().expect("Parse error") }; } pub fn datatype_detect(data:&[u8])->DataKind{ let vec:CharVec = data.iter().map(|byte| *byte as char).collect(); if vec.get_chartype_count() < (0x7f-0x20){ DataKind::Text }else{ DataKind::Binary } } /* fn main() ->std::io::Result<()> { let arg:Vec<String> = env::args().collect(); let vec:CharVec; if arg.len()>=2{ vec=arg[1].chars().collect(); }else{ let stdout = std::io::stdout(); let mut handle = stdout.lock(); handle.write("判定対象の文字列を入力してください > ".as_bytes())?; handle.flush()?; input!{s:String}; vec=s.chars().collect(); } let chars = vec.get_chartype_count() as f64; let s:String = vec.into_iter().collect(); println!("文字列: {}",s); println!("文字列長: {}",s.len()); println!("この文字列に含まれる文字の種類(推定値): {}",chars); let N = s.len(); let mut ans = 0 as u64; let max_degree = 127; // 256の127乗がf64で表せる最大の値なので。 let remainder = N % max_degree; let num_of_degloop = N / max_degree; let c = chars as f64; for _i in 0..num_of_degloop{ ans += c.powi(max_degree as i32).log2() as u64; } ans += c.powi(remainder as i32).log2() as u64; println!("強度(おおよそのbit数): {}",ans); Ok(()) } */
25.810573
84
0.465096
afa1582486062513f0f1eb75735134e1ec84de21
4,904
py
Python
parameter_estimation.py
squeegene/SEIR_CT
78e7f5788d62a53b68eb19827ff9dc4bac0bd205
[ "Apache-2.0" ]
null
null
null
parameter_estimation.py
squeegene/SEIR_CT
78e7f5788d62a53b68eb19827ff9dc4bac0bd205
[ "Apache-2.0" ]
null
null
null
parameter_estimation.py
squeegene/SEIR_CT
78e7f5788d62a53b68eb19827ff9dc4bac0bd205
[ "Apache-2.0" ]
null
null
null
# Parameter Estimation import matplotlib.pyplot as plt import numpy import os import pandas import scipy import scipy.integrate # GLOBAL CONSTANTS delta = 2.703e-5 # Natural Birth Rate (unrelated to disease) gamma = 0.07 # Rate of Removal [days^-1] mu = 2.403e-5 # Natural Death Rate (unrelated to disease) sigma = 0.2 # Average Incubation Period [days^-1] N = 3565287 # Total Population of CT [persons] cfr = 0.022 # Case Fatality Rate [1.4% (NY) - 3%] beds = 8798 # Number of hospital beds available icub = 674 # Number of ICU beds available def estimate(): nyt = pandas.read_csv('data/nytimes.csv') nytct = nyt[(nyt.state == "Connecticut")].copy() nytct['date'] = pandas.to_datetime(nytct['date']) nytct['difference'] = nytct['cases'].diff() nytct['pct_change'] = nytct['cases'].pct_change() nytct = nytct.reset_index() nytct.index += 0 # ODE VARIABLES tf = 360 dt = 1 tspan = [0, tf] teval = numpy.arange(0, tf, dt) targs = [tf, dt, tspan, teval] (betasearch, esearch, isearch) = search(targs, nytct) # (betasearch, esearch, isearch) = (0.42, 100, 50) # Results for tf = 30 # (betasearch, esearch, isearch) = (0.16, 1650, 950) # Results for tf = 60 # (betasearch, esearch, isearch) = (0.11, 950, 1950) # Results for tf = 150 R = (betasearch*sigma)/((mu+gamma)*(mu+sigma)) # Basic Reproduction Number print(betasearch, esearch, isearch, R) # INITIAL CONDITIONS e0 = esearch/N # Exposed i0 = isearch/N # Active Infected r0 = 0 # Recovered (effectively 0) s0 = 1-e0-i0-r0 # Susceptible # INIT init = [s0, e0, i0, r0, betasearch] beta = numpy.ones(tf) * betasearch # SOLVE ODE solution = scipy.integrate.solve_ivp(rhs, tspan, init, t_eval=teval) solution = numpy.c_[numpy.transpose(solution['y'])] seir = pandas.DataFrame(data=solution) seir['date'] = pandas.date_range(start='3/8/2020', periods=len(seir), freq='D') seir.columns = ['susceptible', 'exposed', 'infected', 'recovered', 'beta', 'date'] plt.xlabel("Days Since Start of Simulation") plt.ylabel("Portion of Population in Compartment") plt.xticks(numpy.arange(0, tf, 30)) plt.yticks(numpy.arange(0, 1, 0.05)) plt.grid(True) plt.plot(seir.index, seir['susceptible'], 'g-', label='Susceptible') plt.plot(seir.index, seir['exposed'], 'b-', label='Exposed') plt.plot(seir.index, seir['infected'], 'r-', label=r'Infected, $\beta$=0.16') plt.plot(nytct.index, nytct['cases']/N, label='Actual Infected, per NYT/JHU') plt.plot(seir.index, seir['recovered'], 'k-', label='Recovered') plt.plot(seir.index, beta, 'm-', label=r'$\beta$') # plt.plot(seir['date'], seir['infected'], label=r'Proportion of Infected, Simulated with $\beta$=0.11') # plt.scatter(nytct['date'].head(tf), nytct['cases'].head(tf)/N, label='Proportion of Infected, per NYT/JHU') # plt.gcf().autofmt_xdate() plt.legend() plt.tight_layout() plt.show() def rhs(dt, init): # Unpack Arguments s = init[0] e = init[1] i = init[2] r = init[3] beta = init[4] # Solve dynamics sdot = delta - (beta*s*i) - (mu*s) edot = (beta*s*i) - (mu*e) - (sigma*e) idot = (sigma*e) - (gamma*i) - (mu*i) rdot = (gamma*i) - (mu*r) return [sdot, edot, idot, rdot, 0] def search(targs, comparison_data): tf = targs[0] dt = targs[1] tspan = targs[2] teval = targs[3] # SEARCH FOR SMALLEST ERROR IN SIMULATIONS base_error = 10 for beta in numpy.arange(0.1, 0.6, 0.01): for e in numpy.arange(0, 2000, 50): for i in numpy.arange(0, 2000, 50): print(beta, e, i) # INITIAL CONDITIONS e0 = e/N # Exposed i0 = i/N # Active Infected r0 = 0/N # Recovered s0 = 1-e0-i0-r0 # Susceptible # INIT init = [s0, e0, i0, r0, beta] # SOLVE ODE solution = scipy.integrate.solve_ivp(rhs, tspan, init, t_eval=teval) solution = numpy.c_[numpy.transpose(solution['y'])] seir = pandas.DataFrame(data=solution) seir['date'] = pandas.date_range(start='3/8/2020', periods=len(seir), freq='D') seir.columns = ['susceptible', 'exposed', 'infected', 'recovered', 'beta', 'date'] error = (((comparison_data['cases']/N).head(tf).subtract(seir['infected']))**2).sum() if (error < base_error): print("New Minimum Error") base_error = error betasearch = beta esearch = e isearch = i return(betasearch, esearch, isearch) if __name__ == "__main__": estimate()
35.79562
113
0.577692
3fce782791ace40fa83b0fd2f37763784ee0d381
5,960
asm
Assembly
Transynther/x86/_processed/US/_zr_/i3-7100_9_0x84_notsx.log_4003_213.asm
ljhsiun2/medusa
67d769b8a2fb42c538f10287abaf0e6dbb463f0c
[ "MIT" ]
9
2020-08-13T19:41:58.000Z
2022-03-30T12:22:51.000Z
Transynther/x86/_processed/US/_zr_/i3-7100_9_0x84_notsx.log_4003_213.asm
ljhsiun2/medusa
67d769b8a2fb42c538f10287abaf0e6dbb463f0c
[ "MIT" ]
1
2021-04-29T06:29:35.000Z
2021-05-13T21:02:30.000Z
Transynther/x86/_processed/US/_zr_/i3-7100_9_0x84_notsx.log_4003_213.asm
ljhsiun2/medusa
67d769b8a2fb42c538f10287abaf0e6dbb463f0c
[ "MIT" ]
3
2020-07-14T17:07:07.000Z
2022-03-21T01:12:22.000Z
.global s_prepare_buffers s_prepare_buffers: push %r10 push %r13 push %r14 push %r15 push %r9 push %rcx push %rdi push %rsi lea addresses_normal_ht+0x13c01, %rsi nop nop cmp %r14, %r14 mov (%rsi), %r15 nop xor %r9, %r9 lea addresses_normal_ht+0x1169d, %r9 cmp %rsi, %rsi mov $0x6162636465666768, %r15 movq %r15, %xmm2 vmovups %ymm2, (%r9) nop nop and %rdi, %rdi lea addresses_normal_ht+0x2241, %r10 nop nop nop nop and %r13, %r13 vmovups (%r10), %ymm6 vextracti128 $1, %ymm6, %xmm6 vpextrq $0, %xmm6, %rsi nop nop nop nop cmp $44644, %rsi lea addresses_normal_ht+0x1d7c1, %rsi lea addresses_A_ht+0x13849, %rdi clflush (%rdi) nop and $42456, %r9 mov $45, %rcx rep movsl nop nop nop add $28420, %rsi lea addresses_A_ht+0x40c1, %r14 nop nop nop nop sub %r13, %r13 vmovups (%r14), %ymm4 vextracti128 $1, %ymm4, %xmm4 vpextrq $0, %xmm4, %r10 nop nop nop nop cmp %r15, %r15 lea addresses_WT_ht+0x1b141, %r13 sub $8381, %rdi mov $0x6162636465666768, %r9 movq %r9, %xmm5 vmovups %ymm5, (%r13) nop nop nop and %r9, %r9 lea addresses_D_ht+0x8141, %r9 nop and %r10, %r10 mov (%r9), %rdi nop nop add $40356, %rsi lea addresses_WC_ht+0x7041, %rsi xor %r9, %r9 mov (%rsi), %r13d nop xor %r13, %r13 pop %rsi pop %rdi pop %rcx pop %r9 pop %r15 pop %r14 pop %r13 pop %r10 ret .global s_faulty_load s_faulty_load: push %r12 push %r15 push %rcx push %rdi push %rdx push %rsi // Faulty Load lea addresses_US+0x1a641, %rdx cmp $5205, %r15 movups (%rdx), %xmm6 vpextrq $1, %xmm6, %rcx lea oracles, %rdi and $0xff, %rcx shlq $12, %rcx mov (%rdi,%rcx,1), %rcx pop %rsi pop %rdx pop %rdi pop %rcx pop %r15 pop %r12 ret /* <gen_faulty_load> [REF] {'src': {'type': 'addresses_US', 'same': False, 'size': 4, 'congruent': 0, 'NT': False, 'AVXalign': False}, 'OP': 'LOAD'} [Faulty Load] {'src': {'type': 'addresses_US', 'same': True, 'size': 16, 'congruent': 0, 'NT': False, 'AVXalign': False}, 'OP': 'LOAD'} <gen_prepare_buffer> {'src': {'type': 'addresses_normal_ht', 'same': False, 'size': 8, 'congruent': 5, 'NT': False, 'AVXalign': True}, 'OP': 'LOAD'} {'dst': {'type': 'addresses_normal_ht', 'same': False, 'size': 32, 'congruent': 2, 'NT': False, 'AVXalign': False}, 'OP': 'STOR'} {'src': {'type': 'addresses_normal_ht', 'same': True, 'size': 32, 'congruent': 10, 'NT': False, 'AVXalign': False}, 'OP': 'LOAD'} {'src': {'type': 'addresses_normal_ht', 'congruent': 2, 'same': False}, 'dst': {'type': 'addresses_A_ht', 'congruent': 2, 'same': False}, 'OP': 'REPM'} {'src': {'type': 'addresses_A_ht', 'same': False, 'size': 32, 'congruent': 6, 'NT': False, 'AVXalign': False}, 'OP': 'LOAD'} {'dst': {'type': 'addresses_WT_ht', 'same': False, 'size': 32, 'congruent': 8, 'NT': False, 'AVXalign': False}, 'OP': 'STOR'} {'src': {'type': 'addresses_D_ht', 'same': True, 'size': 8, 'congruent': 3, 'NT': True, 'AVXalign': False}, 'OP': 'LOAD'} {'src': {'type': 'addresses_WC_ht', 'same': False, 'size': 4, 'congruent': 7, 'NT': False, 'AVXalign': True}, 'OP': 'LOAD'} {'00': 4003} 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 */
42.571429
2,999
0.657718
ddc4971e8276539bde5c7d9b89d9f3b959c66787
3,005
java
Java
src/authoring/displaydeprecated/AuthoringDisplayDeprecated.java
YashasManjunatha/voogasalad
fb33d06458ca22bf36d0866c8776ff85dd6b2943
[ "MIT" ]
null
null
null
src/authoring/displaydeprecated/AuthoringDisplayDeprecated.java
YashasManjunatha/voogasalad
fb33d06458ca22bf36d0866c8776ff85dd6b2943
[ "MIT" ]
null
null
null
src/authoring/displaydeprecated/AuthoringDisplayDeprecated.java
YashasManjunatha/voogasalad
fb33d06458ca22bf36d0866c8776ff85dd6b2943
[ "MIT" ]
null
null
null
package authoring.displaydeprecated; import java.util.ResourceBundle; import authoring.Game; import javafx.scene.Node; import javafx.scene.Scene; import javafx.scene.layout.BorderPane; import javafx.stage.Stage; /** * @author Maddie Wilkinson * */ public class AuthoringDisplayDeprecated { public static final String DEFAULT_RESOURCE_PATH = "authoring.display.resources/"; public static final String DEFAULT_CSS_PATH = "authoring/display/resources/"; public static final String DEFAULT_LANGUAGE = "English"; public static final String DEFAULT_STYLE = "myStyle.css"; private BorderPane root; private ResourceBundle myResources; //rename more accurately; it's the button names & stuff specifically private Game myGame; private LevelPanelDeprecated myLevelPanel; private GameViewWindowDeprecated myGameViewWindow; private ObjectInfoPanelDeprecated myObjectInfoPanel; private TemplateObjectPanelDeprecated myTemplatePanel; private SaveBarDeprecated mySaveBar; public AuthoringDisplayDeprecated(Stage stage, Game game) { myGame = new Game(); loadResources(); initialize(stage); } public void loadResources() { myResources = ResourceBundle.getBundle(DEFAULT_RESOURCE_PATH + DEFAULT_LANGUAGE); } public void initialize(Stage stage) { Scene newScene = setUpScene(); // newScene.getStylesheets().add(DEFAULT_CSS_PATH + DEFAULT_STYLE); stage.setScene(newScene); stage.show(); } public Scene setUpScene() { initVars(); root = new BorderPane(); root.setRight(myGameViewWindow.asNode()); root.setLeft(myLevelPanel.asNode()); root.setCenter(myObjectInfoPanel.asNode()); // root.setBottom(myTemplatePanel.asNode()); root.setTop(mySaveBar.asNode()); return new Scene(root); } private void initVars() { myGameViewWindow = makeGameViewWindow(); myObjectInfoPanel = makeObjectPropertyPanel(); myLevelPanel = makeLevelPanel(myGameViewWindow, myObjectInfoPanel); myTemplatePanel = makeTemplatePanel(); mySaveBar = makeSaveBar(); } private LevelPanelDeprecated makeLevelPanel(GameViewWindowDeprecated gameViewWindow, ObjectInfoPanelDeprecated objectInfoPanel) { LevelPanelDeprecated levelPanel = new LevelPanelDeprecated(myResources, myGame, root, gameViewWindow, objectInfoPanel); return levelPanel; } private TemplateObjectPanelDeprecated makeTemplatePanel() { TemplateObjectPanelDeprecated templatePanel = new TemplateObjectPanelDeprecated(myResources, myGame, root); return templatePanel; } private ObjectInfoPanelDeprecated makeObjectPropertyPanel() { ObjectInfoPanelDeprecated objectInfoPanel = new ObjectInfoPanelDeprecated(myResources, myGame, root); return objectInfoPanel; } private GameViewWindowDeprecated makeGameViewWindow() { GameViewWindowDeprecated gameViewWindow = new GameViewWindowDeprecated(myResources, myGame, root, 600, 600); return gameViewWindow; } private SaveBarDeprecated makeSaveBar() { SaveBarDeprecated saveBar = new SaveBarDeprecated(myResources, myGame, root); return saveBar; } }
31.968085
130
0.797338
7f3acfc89c8103f61f4c8612fbb10ab72639c005
1,317
cs
C#
Assets/Scripts/MapElements/TerrainElement.cs
dmdSpirit/Tactical
58c81bbad7213f2b0c49978f204cf46216f2bed7
[ "MIT" ]
3
2019-07-19T11:19:07.000Z
2021-07-03T16:08:59.000Z
Assets/Scripts/MapElements/TerrainElement.cs
dmdSpirit/Tactical
58c81bbad7213f2b0c49978f204cf46216f2bed7
[ "MIT" ]
null
null
null
Assets/Scripts/MapElements/TerrainElement.cs
dmdSpirit/Tactical
58c81bbad7213f2b0c49978f204cf46216f2bed7
[ "MIT" ]
1
2021-09-04T22:11:26.000Z
2021-09-04T22:11:26.000Z
using UnityEngine; namespace dmdspirit.Tactical { // Basically this enum contains terrain material names for easier inEditor map editing. public enum TerrainType { Empty, Grass, Rock } [System.Serializable] public class TerrainElement { public MapElement mapElement; public bool canStandOn; public TerrainType terrainType; // I don't want to make TerrainType.Empty the default value here because it can lead to some confusion when new created // terrain elements will not be seen in editor. public TerrainElement() : this(new MapElement(MapElementType.Terrain), true, TerrainType.Rock) { } public TerrainElement(int x, int y, int height, bool canStandOn, TerrainType terrainType) : this(new MapElement(x, y, height, MapElementType.Terrain), canStandOn, terrainType) { } public TerrainElement(MapElement mapElement, bool canStandOn, TerrainType terrainType) { this.mapElement = mapElement; this.canStandOn = canStandOn; this.terrainType = terrainType; } public override string ToString() { return $"({mapElement.x},{mapElement.y},{mapElement.height}) {terrainType.ToString()} Terrain"; } } }
34.657895
187
0.654518
9f53825b60cd1c571e56f09889e8e7785d543751
3,751
swift
Swift
Example/Tests/AircraftTests.swift
zingdrones/AirMapSDK-Swift
8ad647767f02ac31705373381f929490b74c5eef
[ "Apache-2.0" ]
43
2016-08-09T08:38:43.000Z
2021-03-08T23:28:41.000Z
Example/Tests/AircraftTests.swift
zingdrones/AirMapSDK-Swift
8ad647767f02ac31705373381f929490b74c5eef
[ "Apache-2.0" ]
37
2016-08-12T18:26:46.000Z
2021-04-26T05:59:33.000Z
Example/Tests/AircraftTests.swift
isabella232/AirMapSDK-Swift
63d9d4e72f84cfdd465fe1958da61eb27af3b0b3
[ "Apache-2.0" ]
18
2017-04-04T23:06:49.000Z
2022-02-02T04:02:11.000Z
// // AircraftTests.swift // AirMapSDK // // Created by Adolfo Martinelli on 7/18/16. // Copyright © 2016 AirMap, Inc. All rights reserved. // @testable import AirMap import Nimble import RxSwift class AircraftTests: TestCase { func testCreateAircraft() { let aircraft = AircraftFactory.defaultAircraft() stub(.post, Config.AirMapApi.pilotUrl + "/1234/aircraft", with: "pilot_aircraft_create_success.json") { request in let json = request.bodyJson() expect(json.keys.count).to(equal(2)) expect(json["model_id"] as? String).to(equal(aircraft.model.modelId)) expect(json["nickname"] as? String).to(equal(aircraft.nickname)) } waitUntil { done in AirMap.rx.createAircraft(aircraft) .subscribe( onNext: { aircraft in let ref = AircraftFactory.defaultAircraft() expect(aircraft.nickname).to(equal(ref.nickname)) expect(aircraft.aircraftId).to(equal(ref.aircraftId)) expect(aircraft.model.name).to(equal(ref.model.name)) expect(aircraft.model.modelId).to(equal(ref.model.modelId)) expect(aircraft.model.manufacturer.name).to(equal(ref.model.manufacturer.name)) expect(aircraft.model.manufacturer.id).to(equal(ref.model.manufacturer.id)) }, onError: { error in expect(error).to(beNil()); done() }, onCompleted: done ) .disposed(by: self.disposeBag) } } func testListAircraftManufacturers() { stub(.get, Config.AirMapApi.aircraftUrl + "/manufacturer", with: "aircraft_manufacturers_success.json") waitUntil { done in AirMap.rx.listManufacturers() .subscribe( onNext: { manufacturers in let refManufacturer = AircraftFactory.defaultAircraft().model.manufacturer expect(manufacturers.count).to(equal(2)) expect(manufacturers.first?.name).to(equal(refManufacturer?.name)) expect(manufacturers.first?.id).to(equal(refManufacturer?.id)) }, onError: { error in expect(error).to(beNil()); done() }, onCompleted: done ) .disposed(by: self.disposeBag) } } func testListAircraftModels() { stub(.get, Config.AirMapApi.aircraftUrl + "/model", with: "aircraft_models_success.json") waitUntil { done in AirMap.rx.listModels() .subscribe( onNext: { models in let ref = AircraftFactory.defaultAircraft() expect(models.count).to(equal(2)) expect(models.first?.modelId).to(equal(ref.model.modelId)) expect(models.first?.name).to(equal(ref.model.name)) expect(models.first?.manufacturer).toNot(beNil()) expect(models.first?.manufacturer.name).to(equal(ref.model.manufacturer.name)) expect(models.first?.manufacturer.id).to(equal(ref.model.manufacturer.id)) }, onError: { error in expect(error).to(beNil()); done() }, onCompleted: done ) .disposed(by: self.disposeBag) } } func testGetAircraftModel() { stub(.get, Config.AirMapApi.aircraftUrl + "/model/1234", with: "aircraft_model_success.json") waitUntil { done in AirMap.rx.getModel("1234") .subscribe( onNext: { model in let ref = AircraftFactory.defaultAircraft() expect(model).toNot(beNil()) expect(model.modelId).to(equal(ref.model.modelId)) expect(model.name).to(equal(ref.model.name)) expect(model.manufacturer).toNot(beNil()) expect(model.manufacturer.id).to(equal(ref.model.manufacturer.id)) expect(model.manufacturer.name).to(equal(ref.model.manufacturer.name)) expect(model.metadata["flight_time"] as? Int).to(equal(20)) expect(model.metadata["image"] as? String).to(equal("http://cdn.airmap.io/acme-superdrone5000.jpg")) }, onError: { error in expect(error).to(beNil()); done() }, onCompleted: done ) .disposed(by: self.disposeBag) } } }
32.617391
116
0.68675
a9edb6a84fb56292b2a8635f56c19db17d4adc19
4,724
php
PHP
resources/views/settings/feeds.blade.php
webstylecenter/feednews
6048f54ee2c7f7a486f3069fbc34ea540ec26001
[ "MIT" ]
1
2021-02-15T18:35:43.000Z
2021-02-15T18:35:43.000Z
resources/views/settings/feeds.blade.php
webstylecenter/feednews
6048f54ee2c7f7a486f3069fbc34ea540ec26001
[ "MIT" ]
18
2021-02-02T19:23:27.000Z
2022-02-16T10:34:27.000Z
resources/views/settings/feeds.blade.php
webstylecenter/feednews
6048f54ee2c7f7a486f3069fbc34ea540ec26001
[ "MIT" ]
null
null
null
@php $values = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f']; @endphp <div class="content-left"> <div class="form"> <h1>Add RSS Feed</h1> <p> <input type="text" name="url" value="" placeholder="Insert RSS feed url" /><br /> or <input class="websiteurl" type="text" name="website" value="" placeholder="Insert website url" /><br /> <input type="text" name="icon" value="" placeholder="FontAwesome icon (optional)" /><br /> <select name="category"> <option value="">Select category</option> @foreach($categories as $category) <option value="{{ $category->id }}">{{ $category->name }}</option> @endforeach <option value="">Other</option> </select><br /> <input type="checkbox" name="autoPin" value="1" id="autoPin"/><label for="autoPin">Automatically pin new items</label><br /> <input type="text" name="color" class="spectrum" value="#{{ $values[array_rand($values, 1)] . $values[array_rand($values, 1)] . $values[array_rand($values, 1)] . $values[array_rand($values, 1)] . $values[array_rand($values, 1)] . $values[array_rand($values, 1)] }}" placeholder="Insert RGB without the #" /><br /> <input type="submit" value="Add" class="js-settings-add-feed fluent-blue" /> </p> </div> @if($availableFeeds) <div class="addUserFeeds"> <h2>Ready to follow</h2> <div class="refreshNotice">Refresh the page when you're ready!</div> <table> <tbody> @php $previousCategory = null; @endphp @foreach($availableFeeds as $feed) @if($feed->category && $previousCategory !== $feed->category->name) </tbody> </table> <h3>{{ $feed->category->name }}</h3> <table> <tbody> @php $previousCategory = $feed->category->name; @endphp @endif <tr> <td>{{ $feed->name }}</td> <td>{{ $feed->category->name ?? 'other' }}</td> <td><button class="button js-follow-feed fluent-blue" data-feed-id="{{ $feed->id }}">Follow</button></td> </tr> @endforeach </tbody> </table> </div> @endif </div> <div class="content-right"> <div class="userFeeds"> <h1>Currently following:</h1> @if($userFeeds) <table> <tbody> @foreach($userFeeds as $feed) <tr data-feed-id="{{ $feed->id }}" data-feed-name="{{ $feed->feed->name }}"> <td> <div class="feedColor"> <input type="text" class="spectrum js-update-feed-color" name="color" value="{{ $feed->color }}" /> </div> </td> <td class="feedName"> {{ $feed->feed->name }} </td> <td class="feedIcon" data-balloon="Click to set feed icon" data-balloon-pos="left"> <span class="fa fa-{{ $feed->icon === '' ? 'plus emptyIcon' : $feed->icon }} js-open-icon-selector"></span> </td> <td class="feedUrl hide-if-mobile"> <a href="{{ $feed->feed->url }}" target="_blank">{{ $feed->feed->url }}</a> </td> <td class="feedIcon hide-if-mobile"> <input data-balloon="Automaticly pin new items" data-balloon-pos="left" title="Autopin new items" class="js-update-auto-pin" type="checkbox" value="1" @if($feed->auto_pin)checked="checked"@endif /> </td> {{-- <td class="feedAmount hide-if-mobile">--}} {{-- {{ $feed->items->count() }}--}} {{-- </td>--}} <td class="feedActions"> <button class="js-settings-remove-feed fa fa-trash"></button> </td> </tr> @endforeach </tbody> </table> @else <p>Add your first RSS Feed to have it listed here</p> @endif </div> </div>
45.423077
325
0.433743
9c11622ad5360672763ee08fb99262f1a136dbf2
960
swift
Swift
Pod/Classes/ui/CardKit/SetPassCodeModule/SetPassCodeInteractor.swift
ShiftFinancial/apto-ui-sdk-ios
64e9f3632cd6ff78e9c2343a4c78552883f7f87a
[ "MIT" ]
null
null
null
Pod/Classes/ui/CardKit/SetPassCodeModule/SetPassCodeInteractor.swift
ShiftFinancial/apto-ui-sdk-ios
64e9f3632cd6ff78e9c2343a4c78552883f7f87a
[ "MIT" ]
null
null
null
Pod/Classes/ui/CardKit/SetPassCodeModule/SetPassCodeInteractor.swift
ShiftFinancial/apto-ui-sdk-ios
64e9f3632cd6ff78e9c2343a4c78552883f7f87a
[ "MIT" ]
null
null
null
import AptoSDK import Foundation class SetPassCodeInteractor: SetCodeInteractorProtocol { private let platform: AptoPlatformProtocol private let card: Card private let verification: Verification? init(platform: AptoPlatformProtocol, card: Card, verification: Verification?) { self.platform = platform self.card = card self.verification = verification } func changeCode(_ code: String, completion: @escaping Result<Card, NSError>.Callback) { platform.setCardPassCode(card.accountId, passCode: code, verificationId: verification?.verificationId) { [weak self] result in guard let self = self else { return } switch result { case let .failure(error): completion(.failure(error)) case .success: completion(.success(self.card)) } } } }
33.103448
102
0.605208
f4cdc8840ec1d264f11e0e4ec48fbc598ca85e21
65
ts
TypeScript
Interface/src/index.ts
agentx-cgn/Automaton
5ab80a6139b9a35361d9c16a81fa468c07b439fa
[ "MIT" ]
null
null
null
Interface/src/index.ts
agentx-cgn/Automaton
5ab80a6139b9a35361d9c16a81fa468c07b439fa
[ "MIT" ]
null
null
null
Interface/src/index.ts
agentx-cgn/Automaton
5ab80a6139b9a35361d9c16a81fa468c07b439fa
[ "MIT" ]
null
null
null
import m from "mithril"; m.render(document.body, "hello world");
21.666667
39
0.723077
67d0b3db4733cd961f91f8098e817bd186e141d7
2,016
psd1
PowerShell
eval/dsc/akshcihost/xHyper-V/3.17.0.0/DSCResources/MSFT_xVMHyperV/en-US/MSFT_xVMHyperV.psd1
olaseniadeniji/aks-hci
39c54d080a5c9278903f7141be15b5e26ef9bad8
[ "MIT" ]
267
2016-01-27T19:02:25.000Z
2022-03-24T14:21:07.000Z
DSCResources/MSFT_xVMHyperV/en-US/MSFT_xVMHyperV.psd1
TheGitHubBro/xHyper-V
e68e33892ab63996ab98665b7c9eab6b0a1a9c97
[ "MIT" ]
184
2016-01-27T13:57:43.000Z
2022-01-02T20:10:51.000Z
DSCResources/MSFT_xVMHyperV/en-US/MSFT_xVMHyperV.psd1
TheGitHubBro/xHyper-V
e68e33892ab63996ab98665b7c9eab6b0a1a9c97
[ "MIT" ]
75
2016-01-27T12:53:11.000Z
2022-03-29T09:03:09.000Z
ConvertFrom-StringData @' RoleMissingError = Please ensure that '{0}' role is installed with its PowerShell module. MoreThanOneVMExistsError = More than one VM with the name '{0}' exists. PathDoesNotExistError = Path '{0}' does not exist. VhdPathDoesNotExistError = Vhd '{0}' does not exist. MinMemGreaterThanStartupMemError = MinimumMemory '{0}' should not be greater than StartupMemory '{1}' MinMemGreaterThanMaxMemError = MinimumMemory '{0}' should not be greater than MaximumMemory '{1}' StartUpMemGreaterThanMaxMemError = StartupMemory '{0}' should not be greater than MaximumMemory '{1}'. VhdUnsupportedOnGen2VMError = Generation 2 virtual machines do not support the .VHD virtual disk extension. CannotUpdatePropertiesOnlineError = Can not change properties for VM '{0}' in '{1}' state unless 'RestartIfNeeded' is set to true. AutomaticCheckpointsUnsupported = AutomaticCheckpoints are not supported on this host. AdjustingGreaterThanMemoryWarning = VM {0} '{1}' is greater than {2} '{3}'. Adjusting {0} to be '{3}'. AdjustingLessThanMemoryWarning = VM {0} '{1}' is less than {2} '{3}'. Adjusting {0} to be '{3}'. VMStateWillBeOffWarning = VM '{0}' state will be 'OFF' and not 'Paused'. CheckingVMExists = Checking if VM '{0}' exists ... VMExists = VM '{0}' exists. VMDoesNotExist = VM '{0}' does not exist. CreatingVM = Creating VM '{0}' ... VMCreated = VM '{0}' created. VMPropertyShouldBe = VM property '{0}' should be '{1}', actual '{2}'. VMPropertySet = VM property '{0}' is '{1}'. VMPropertiesUpdated = VM '{0}' properties have been updated. WaitingForVMIPAddress = Waiting for IP Address for VM '{0}' ... QueryingVM = Querying VM '{0}'. '@
69.517241
134
0.606151
7f1a6ad6912ded0dc1e143d595ae2eeaf8df308e
266
cs
C#
BeatSaber99Client/Packets/EventLogPacket.cs
Guad/beatsaber99
c5aff73f5a574aa0e547a6ab9c673efc31eebd84
[ "MIT" ]
10
2020-04-20T21:13:16.000Z
2020-06-17T05:49:37.000Z
BeatSaber99Client/Packets/EventLogPacket.cs
Guad/beatsaber99
c5aff73f5a574aa0e547a6ab9c673efc31eebd84
[ "MIT" ]
5
2020-04-20T18:41:05.000Z
2021-04-06T09:57:58.000Z
BeatSaber99Client/Packets/EventLogPacket.cs
Guad/beatsaber99
c5aff73f5a574aa0e547a6ab9c673efc31eebd84
[ "MIT" ]
1
2020-04-24T16:58:06.000Z
2020-04-24T16:58:06.000Z
using BeatSaber99Client.UI; namespace BeatSaber99Client.Packets { public class EventLogPacket : IPacket { public string Text { get; set; } public void Dispatch() { PluginUI.instance.PushEventLog(Text); } } }
19
49
0.605263
45a5e0d49594c69357ddab2f5c9384de6c32e229
1,713
py
Python
report/models.py
GilbertTan19/Empire_of_Movies-deploy
e9e05530a25e76523e624591c966dccf84898ace
[ "MIT" ]
null
null
null
report/models.py
GilbertTan19/Empire_of_Movies-deploy
e9e05530a25e76523e624591c966dccf84898ace
[ "MIT" ]
2
2021-03-30T14:31:18.000Z
2021-04-08T21:22:09.000Z
report/models.py
GilbertTan19/Empire_of_Movies-deploy
e9e05530a25e76523e624591c966dccf84898ace
[ "MIT" ]
5
2020-07-13T03:17:07.000Z
2020-07-22T03:15:57.000Z
from django.db import models from articles.models import Discussion, Review, Comment from threadedcomments.models import ThreadedComment from django.contrib.auth import get_user_model class Report(models.Model): short_reason = models.CharField(max_length=255) long_reason = models.TextField() author = models.ForeignKey( get_user_model(), related_name='reports', on_delete=models.CASCADE, ) reported = models.ForeignKey( get_user_model(), related_name="reported", on_delete=models.CASCADE, ) date = models.DateTimeField(auto_now_add=True, null=True, blank=True) discussion = models.ForeignKey( Discussion, default=None, on_delete=models.CASCADE, related_name='discussion_report', blank=True, null=True, ) review = models.ForeignKey( Review, default=None, on_delete=models.CASCADE, related_name='review_report', blank=True, null=True, ) comment = models.ForeignKey( ThreadedComment, default=None, on_delete=models.CASCADE, related_name='comment_report', blank=True, null=True, ) def __str__(self): return self.short_reason or ' ' @classmethod def create(self, reported, reporter, short_reason, long_reason, discussion, review, comment): report = self(short_reason=short_reason, long_reason=long_reason, discussion=discussion, \ review=review, comment=comment, author=reporter, reported=reported) return report # def get_absolute_url(self): # return reverse('', args=[str(self.movie.id), str(self.id)])
31.145455
98
0.655575
2c9538b4dc6b7d58d4f3e82ae47bf7022e232a3a
2,701
py
Python
imitator_my_plate.py
choonkiattay/EasyOCRGen
d277aac4c2d0d53433d71c24095ca77b6dd5745a
[ "W3C" ]
null
null
null
imitator_my_plate.py
choonkiattay/EasyOCRGen
d277aac4c2d0d53433d71c24095ca77b6dd5745a
[ "W3C" ]
null
null
null
imitator_my_plate.py
choonkiattay/EasyOCRGen
d277aac4c2d0d53433d71c24095ca77b6dd5745a
[ "W3C" ]
1
2020-07-12T04:12:57.000Z
2020-07-12T04:12:57.000Z
import glob import os import argparse import cv2 import random from utils import augmentation from utils import singularity from generators import image_gen from utils import image_preprocess def init_args(): parser = argparse.ArgumentParser() parser.add_argument('--imitatee_dir', type=str, help='Full path to imitatee directory, ' 'Please include "/" at EOL') parser.add_argument('--pers_trans', type=str, help='on, off') parser.add_argument('--augment', type=str, help='on, off') parser.add_argument('--grayscale', type=str, help='on, off') parser.add_argument('--single_line', type=str, help='on, off') parser.add_argument('--save_dir', type=str, help='Full path to save directory, ' 'Please include "/" at EOL') parser.print_help() return parser.parse_args() def imitator(imitatee_dir, pers_trans, augment, grayscale, single_line, save_dir): plate_ninja = singularity.Singularity() plate_aug = augmentation.Augmenters() img_preproc = image_preprocess.ImagePreprocess() imitatee=[] img_gen = image_gen.ImageGenerator(save_dir) for imitatee_file in glob.glob(os.path.join(imitatee_dir, '*.jpg')): imitatee_name = imitatee_file.split('/')[-1].split('.')[0].split('_')[-1] for index, character in enumerate(imitatee_name): if character.isdigit(): imitatee_name = imitatee_name[:index] + ' ' + imitatee_name[index:] break imitatee.append(imitatee_name) print(imitatee) print("\n{}".format(len(imitatee))) img_gen.plate_image(imitatee, pers_trans) for n, image in enumerate(sorted(glob.glob(os.path.join(save_dir, '*.jpg')))): print('Postprocessing: {}'.format(n - 1), end='\r') # print('Still going Be patient') img = cv2.imread(image) if single_line == 'on': img = plate_ninja.vlp_singularity(img) if augment == 'on': augmenter = [plate_aug.invert_color(img), plate_aug.salt_pepper(img), plate_aug.random_resize(img), plate_aug.plate_blur(img)] img = random.choice(augmenter) if grayscale == 'on': img = img_preproc.gray(img) cv2.imwrite(image, img) print('Done Postprocessing ') if __name__ == '__main__': args = init_args() if not os.path.exists(args.save_dir): imitator(imitatee_dir=args.imitatee_dir, save_dir=args.save_dir, pers_trans=args.pers_trans, augment=args.augment, grayscale=args.grayscale, single_line=args.single_line) else: print('Destination directory exists. Please choose new directory')
39.720588
111
0.651981
2c9978d285f178cfd502a749f91cca93a8ce3f0e
1,090
py
Python
traffic/drawing/__init__.py
MichelKhalaf/traffic
84e315d84a4ab9d8711414e7c275733e27a089ed
[ "MIT" ]
null
null
null
traffic/drawing/__init__.py
MichelKhalaf/traffic
84e315d84a4ab9d8711414e7c275733e27a089ed
[ "MIT" ]
null
null
null
traffic/drawing/__init__.py
MichelKhalaf/traffic
84e315d84a4ab9d8711414e7c275733e27a089ed
[ "MIT" ]
null
null
null
# flake8: noqa from pathlib import Path import matplotlib as mpl import matplotlib.pyplot as plt from .cartopy import * _traffic_style = """ figure.figsize: 10, 7 figure.edgecolor: white figure.facecolor: white lines.linewidth: 1.5 lines.markeredgewidth: 0 lines.markersize: 10 lines.dash_capstyle: butt legend.fancybox: True font.size: 13 axes.prop_cycle: cycler('color', ['4c78a8', 'f58518', '54a24b', 'b79a20', '439894', 'e45756', 'd67195', 'b279a2', '9e765f', '7970ce']) axes.linewidth: 0 axes.titlesize: 16 axes.labelsize: 14 xtick.labelsize: 14 ytick.labelsize: 14 xtick.major.size: 0 xtick.minor.size: 0 ytick.major.size: 0 ytick.minor.size: 0 axes.grid: True grid.alpha: 0.3 grid.linewidth: 0.5 grid.linestyle: - grid.color: 0e1111 savefig.transparent: True savefig.bbox: tight savefig.format: png """ config_dir = mpl.get_configdir() mpl_style_location = Path(f"{config_dir}/stylelib/traffic.mplstyle") if not mpl_style_location.parent.is_dir(): mpl_style_location.parent.mkdir(parents=True) mpl_style_location.write_text(_traffic_style) plt.style.reload_library()
20.566038
134
0.763303
48dfc11988dac083447652d3bd955e9fd98a73b5
2,325
sh
Shell
script.sh
Oknesif/bashColorScript
ecfa174290c5c1d2a2ba397ca84c4b8da3286143
[ "Apache-2.0" ]
1
2017-11-29T09:27:31.000Z
2017-11-29T09:27:31.000Z
script.sh
Oknesif/BashColorScript
ecfa174290c5c1d2a2ba397ca84c4b8da3286143
[ "Apache-2.0" ]
null
null
null
script.sh
Oknesif/BashColorScript
ecfa174290c5c1d2a2ba397ca84c4b8da3286143
[ "Apache-2.0" ]
null
null
null
if [ -z $1 ] || [ -z $2 ] then echo "Usage: $0 <input directory> <color>" exit 0 fi # Check if given directory is valid DIR=$(pwd)/$1 if [ ! -d $DIR ] then echo -e "$DIR\nIt is not a directory!" exit 0 fi newcolor=$2 ######################################################### # # # Normalize colors # # # ######################################################### if [[ "$newcolor" =~ 0x[0-9A-Fa-f]{6} ]] then # The color was given in a hex format, expand it to an array and convert to decimal newcolors=($(sed 's/0x\(..\)\(..\)\(..\)/\1 \2 \3/' <<< "$newcolor")) newcolors[0]=$(echo "ibase=16;obase=A;${newcolors[0]}" | bc) newcolors[1]=$(echo "ibase=16;obase=A;${newcolors[1]}" | bc) newcolors[2]=$(echo "ibase=16;obase=A;${newcolors[2]}" | bc) # TODO - debugging, delete echo "Color entered in hex, components are: R:${newcolors[0]}, G:${newcolors[1]}, B:${newcolors[2]}" elif [[ "$newcolor" =~ [0-9]{1,3},[0-9]{1,3},[0-9]{1,3} ]] then # Color was entered in decimal, just convert to array newcolor=($(sed 's/\(.\{1,3\}\),\(.\{1,3\}\),\(.\{1,3\}\)/\1 \2 \3/' <<< "$newcolor")) # TODO - debugging, delete echo "Color entered in hex, components are: R:${newcolors[0]}, G:${newcolors[1]}, B:${newcolors[2]}" else echo "Color is in an unknown format. Valid formats are hex: '0xNNNNNN' and dec: 'n,n,n'" exit 0 fi # Compute the scale factors to obtain the new colors from the old by multiplying conversion[0]=$(echo "${newcolors[0]} / 255" | bc -l ) conversion[1]=$(echo "${newcolors[1]} / 255" | bc -l ) conversion[2]=$(echo "${newcolors[2]} / 255" | bc -l ) # TODO - debug, delete echo "R: ${colors[0]} => ${newcolors[0]} (${conversion[0]})" echo "G: ${colors[1]} => ${newcolors[1]} (${conversion[1]})" echo "B: ${colors[2]} => ${newcolors[2]} (${conversion[2]})" for i in $1/**/**/*.png; do outfile="${i/$1/$1_colored}" outpath="$(dirname $i)" outpath="${outpath/$1/$1_colored}" # echo "Outpath is $outpath" echo "Outfile is $outfile" mkdir -p $outpath convert -color-matrix \ " ${conversion[0]} 0 0 \ 0 ${conversion[1]} 0 \ 0 0 ${conversion[2]} " \ $i $outfile done
31.849315
103
0.510108
14dfab2fa1f81fcc08d46a0ddca4e69b704156d4
127
ts
TypeScript
client/app/components/routines/index.ts
liu-jianyang/quickstart
23d98e84010c557ea329d998d45908012669a9dc
[ "MIT" ]
null
null
null
client/app/components/routines/index.ts
liu-jianyang/quickstart
23d98e84010c557ea329d998d45908012669a9dc
[ "MIT" ]
null
null
null
client/app/components/routines/index.ts
liu-jianyang/quickstart
23d98e84010c557ea329d998d45908012669a9dc
[ "MIT" ]
null
null
null
export * from './routines-list.component'; export * from './routine-detail.component'; export * from './routine-new.component';
42.333333
43
0.724409
5459981a201fe4423a8b52d9fe9ad6f4d24ad1c7
3,941
css
CSS
ozone/src/components/detailpage.css
1stBoltCrux/capStone
e9148a7635c608e69cebdb1793a6c1d047ea24c3
[ "Unlicense", "MIT" ]
null
null
null
ozone/src/components/detailpage.css
1stBoltCrux/capStone
e9148a7635c608e69cebdb1793a6c1d047ea24c3
[ "Unlicense", "MIT" ]
null
null
null
ozone/src/components/detailpage.css
1stBoltCrux/capStone
e9148a7635c608e69cebdb1793a6c1d047ea24c3
[ "Unlicense", "MIT" ]
null
null
null
.bottomButtons a { width: 90px; margin: 0 4% 0 4%; } .detailPageBackdrop { z-index: 10; position: fixed; top: 0; left: 0; width: 100%; height: 100%; } .modalOverlay { z-index: 1; position: absolute; top: 0; left: 0; width: 100%; height: 100%; } .detailPageWrapper { background-color: black; top: 50%; left: 50%; transform: translate(-50%, -50%); z-index: 2; position: relative; overflow: auto; height: 100%; width: 350px; } .detailInfoBox h3 { color: #89DA2F; font-weight: lighter; } .detail { text-align: center; } .starWrapper { display: flex; } .detailInfoBox { display: flex; flex-direction: column; align-items: center; color: white; height: 250px; width: 100%; background-image: url(./../imgs/detail-backdrop.svg); background-position: center; background-repeat: no-repeat; background-size: cover; } .detail { display: flex; align-items: center; height: 42px; } .infoButton button { width: 100px; margin: auto; height: 30px; text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.8); border-radius: 18px; border: none; background-color: #89DA2F; color: white; font-size: 1.1rem; box-shadow: 2px 2px 4px rgba(0, 0, 0, 0.5); position: relative; top: 5px; } .infoButton button:focus { outline: 0; } .infoButton button:hover { animation: hoverScale .2s ease both; cursor: pointer; } @keyframes hoverScale { 0% { transform: scale(1); } 100% { transform: scale(1.03); } } .routeImage { height: 350px; width: 100%; background-image: url(./../imgs/noimg.png); background-position: center; background-size:cover; } .buttonBackdrop { color: #89DA2F; height: 300px; width: 100%; background-image: url(./../imgs/button-backdrop.svg); } .topButtons { position: relative; top: 3.5vh; display: flex; justify-content: space-around; } .topButton1 { margin:auto; display: flex; align-items: flex-end; justify-content: center; height: 90px; width: 90px; border-radius: 50%; background-position: center; background-repeat: no-repeat; background-size: cover; background-image: url(./../imgs/shield.svg); box-shadow: 3px 3px 3px rgba(0,0,0,.5) } .topButton1:hover, .topButton2:hover, .topButton3:hover, .bottomButton1:hover, .bottomButton2:hover { animation: hoverScale .2s ease both; cursor: pointer; } .topButton2 { margin:auto; display: flex; align-items: flex-end; justify-content: center; height: 90px; width: 90px; border-radius: 50%; background-position: center; background-repeat: no-repeat; background-size: cover; background-image: url(./../imgs/greencheck.svg); box-shadow: 3px 3px 3px rgba(0,0,0,.5) } .topButton3 { margin:auto; display: flex; align-items: flex-end; justify-content: center; height: 90px; width: 90px; border-radius: 50%; background-position: center; background-repeat: no-repeat; background-size: cover; background-image: url(./../imgs/clipboard.svg); box-shadow: 3px 3px 3px rgba(0,0,0,.5) } .bottomButtons { display: flex; justify-content: center; position: relative; top: 28% } .bottomButton1 { margin:0; display: flex; align-items: flex-end; justify-content: center; height: 90px; width: 90px; border-radius: 50%; background-position: center; background-repeat: no-repeat; background-size: cover; background-image: url(./../imgs/list.svg); box-shadow: 3px 3px 4px rgba(0,0,0,.5) } .bottomButton2 { display: flex; align-items: flex-end; justify-content: center; height: 90px; width: 90px; border-radius: 50%; background-position: center; background-repeat: no-repeat; background-size: cover; background-image: url(./../imgs/star.svg); box-shadow: 3px 3px 4px rgba(0,0,0,.5) } .bottomButton1 p, .bottomButton2 p, .topButton1 p, .topButton2 p, .topButton3 p { position: relative; top: 20%; } .testing { display: none; }
18.077982
101
0.662015
c9447c7c00ad461e9a1cdcbce6fc2e3f10a0e188
749
tsx
TypeScript
src/utils/dva.tsx
youyouqiu/app_v2
2f07ac13e85322e84c90960b6a717f19922c0f8d
[ "MIT" ]
1
2019-11-06T01:29:19.000Z
2019-11-06T01:29:19.000Z
src/utils/dva.tsx
youyouqiu/app_v2
2f07ac13e85322e84c90960b6a717f19922c0f8d
[ "MIT" ]
2
2020-07-17T01:31:51.000Z
2020-07-17T01:31:51.000Z
src/utils/dva.tsx
youyouqiu/app_v2
2f07ac13e85322e84c90960b6a717f19922c0f8d
[ "MIT" ]
null
null
null
import React from 'react'; import { create } from 'dva-core'; import createLoading from 'dva-loading' import { Provider, connect } from 'react-redux'; import {Model} from 'dva' export { connect }; export interface Options { models: Model[] initialState: any onError: (e: Error) => void } export default ((options: Options): any => { const { models } = options const app = create(options) if (!global.dvaRegistered) {models.forEach(model => app.model(model))} global.dvaRegistered = true app.start() app.use(createLoading()) const store: any = app._store app._start = (container: any) => (): Element => <Provider store={store}>{container}</Provider> app.getStore = (): any => store global.store = store return app })
24.966667
96
0.676903
259675114074f858be176ec173c584ab34eb28f8
2,390
cs
C#
dsis/shared/src/Core.FormGenerator/src/Layout/Impl/OptionPageLayout.cs
jonnyzzz/phd-project
beab8615585bd52ef9ee1c19d1557e8c933c047a
[ "Apache-2.0" ]
1
2019-12-24T15:52:45.000Z
2019-12-24T15:52:45.000Z
dsis/shared/src/Core.FormGenerator/src/Layout/Impl/OptionPageLayout.cs
jonnyzzz/phd-project
beab8615585bd52ef9ee1c19d1557e8c933c047a
[ "Apache-2.0" ]
null
null
null
dsis/shared/src/Core.FormGenerator/src/Layout/Impl/OptionPageLayout.cs
jonnyzzz/phd-project
beab8615585bd52ef9ee1c19d1557e8c933c047a
[ "Apache-2.0" ]
null
null
null
using System; using System.Collections.Generic; using System.Windows.Forms; using EugenePetrenko.Shared.Core.Ioc.Api; namespace EugenePetrenko.Core.FormGenerator.Layout.Impl { [ComponentImplementation] public class OptionPageLayout : IOptionPageLayout { private readonly IDockLayout myLayout; public OptionPageLayout(IDockLayout layout) { myLayout = layout; } public Panel Layout<Q>(IEnumerable<Q> controls) where Q : IOptionPageControl { var pn = myLayout.Layout(DockStyle.Top, CollectControls(controls)); return pn; } private static List<Control> CollectControls<Q>(IEnumerable<Q> controls) where Q : IOptionPageControl { var result = new List<Control>(); foreach (Q q in controls) { AddAttribute(q.Title, q.Description, q.Control, result); } return result; } public void Layout<Q>(ScrollableControl host, IEnumerable<Q> controls) where Q : IOptionPageControl { myLayout.Layout(host, DockStyle.Top, CollectControls(controls)); } private static void AddAttribute(string title, string description, Control field, ICollection<Control> result) { var panel = new Panel { Width = 150, Padding = new Padding(0, 0, 5, 5), }; var caption = new Label { Text = title, Width = 120, Dock = DockStyle.Left, }; field.Width = 150; field.Padding = new Padding(0, 0, 35, 0); var sz = Math.Max(field.Height, caption.Height); panel.Dock = DockStyle.Top; field.Dock = DockStyle.Top; panel.Controls.Add(field); panel.Controls.Add(caption); Func<Padding, int> pSz = x => x.Top + x.Bottom; panel.Height = sz + pSz(panel.Margin) + pSz(panel.Padding); result.Add(panel); if (description != null) { var label = new Label { Margin = new Padding(10, 0, 0, 0), Dock = DockStyle.Top, Text = description }; result.Add(label); } } } }
28.452381
115
0.535146
e856bc58fbb672520a6c00d681e69b6f025d459e
540
cs
C#
OktaSdkExtensions/Resources/Organisations/OrganisationSettingsUserAccountAttributes.cs
fossabot/okta-sdk-dotnet-extensions
5f940c6c94eea62acfd0f8fd524ed71cb1cb92a1
[ "Apache-2.0" ]
null
null
null
OktaSdkExtensions/Resources/Organisations/OrganisationSettingsUserAccountAttributes.cs
fossabot/okta-sdk-dotnet-extensions
5f940c6c94eea62acfd0f8fd524ed71cb1cb92a1
[ "Apache-2.0" ]
1
2021-03-01T02:34:05.000Z
2021-03-01T02:34:05.000Z
OktaSdkExtensions/Resources/Organisations/OrganisationSettingsUserAccountAttributes.cs
fossabot/okta-sdk-dotnet-extensions
5f940c6c94eea62acfd0f8fd524ed71cb1cb92a1
[ "Apache-2.0" ]
2
2021-03-01T02:27:02.000Z
2021-09-16T15:27:08.000Z
using Okta.Sdk; namespace Finbourne.Extensions.Okta.Sdk.Resources.Organisations { public class OrganisationSettingsUserAccountAttributes : Resource, IOrganisationSettingsUserAccountAttributes { public bool? SecondaryEmail { get => GetBooleanProperty("secondaryEmail"); set => this["secondaryEmail"] = value; } public bool? SecondaryImage { get => GetBooleanProperty("secondaryEmail"); set => this["secondaryEmail"] = value; } } }
28.421053
113
0.631481
438bf3ed1bce1a8be53b71fc6c678fda1fb06e54
6,980
ts
TypeScript
src/app/app.module.ts
hainguyen81/ngx-admin
6c3e549bf0c7621e4d0efe7fea1835910901adf0
[ "MIT" ]
null
null
null
src/app/app.module.ts
hainguyen81/ngx-admin
6c3e549bf0c7621e4d0efe7fea1835910901adf0
[ "MIT" ]
4
2020-08-11T15:27:31.000Z
2022-03-02T06:53:54.000Z
src/app/app.module.ts
hainguyen81/ngx-admin
6c3e549bf0c7621e4d0efe7fea1835910901adf0
[ "MIT" ]
null
null
null
/** * @license * Copyright Akveo. All Rights Reserved. * Licensed under the MIT License. See License.txt in the project root for license information. */ import {CoreModule} from './@core/core.module'; import {BrowserModule} from '@angular/platform-browser'; import {BrowserAnimationsModule} from '@angular/platform-browser/animations'; import {Injector, NgModule} from '@angular/core'; import {HttpClientModule} from '@angular/common/http'; import {ThemeModule} from './@theme/theme.module'; import {AppComponent} from './app.component'; import {AppRoutingModule} from './app-routing.module'; /* Nebular Theme */ import { NbButtonModule, NbChatModule, NbCheckboxModule, NbDatepickerModule, NbDialogModule, NbIconLibraries, NbIconModule, NbInputModule, NbMenuModule, NbSelectModule, NbSidebarModule, NbThemeModule, NbToastrModule, NbWindowModule, } from '@nebular/theme'; /* API Configuration */ import {AppConfig} from './config/app.config'; /* Authentication */ import {NbAuthModule} from '@nebular/auth'; import {NbxOAuth2AuthStrategy} from './auth/auth.oauth2.strategy'; import {NbxAuthOAuth2Token} from './auth/auth.oauth2.token'; /* Logger */ import {LoggerModule} from 'ngx-logger'; /* Database */ import {NgxIndexedDBModule} from 'ngx-indexed-db'; /* i18n */ import {TranslateModule} from '@ngx-translate/core'; /* Toaster */ import {ToastContainerModule, ToastrModule} from 'ngx-toastr'; /* Mock data */ import {MockDataModule} from './@core/mock/mock.data.module'; /* SplitPane */ import {AngularSplitModule} from 'angular-split'; /* Formly for form builder */ import {ReactiveFormsModule} from '@angular/forms'; import {FormlyModule} from '@ngx-formly/core'; import {FormlyMaterialModule} from '@ngx-formly/material'; /* Treeview */ import {TreeviewModule} from 'ngx-treeview'; /* Angular material modules */ import {AppMaterialModule} from './app.material.module'; /* Device Detector */ import {DeviceDetectorModule} from 'ngx-device-detector'; /* Pipes */ import {NgPipesModule} from 'ngx-pipes'; /* Lightbox */ import {LightboxModule} from 'ngx-lightbox'; /* Popup, Dialogs */ import {AlertPopupModule, ConfirmPopupModule, PromptPopupModule} from 'ngx-material-popup'; import {ModalDialogModule} from 'ngx-modal-dialog'; import {FormlyMatDatepickerModule} from '@ngx-formly/material/datepicker'; @NgModule({ declarations: [AppComponent], imports: [ BrowserModule, BrowserAnimationsModule, HttpClientModule, AppRoutingModule, /* Angular material modules */ AppMaterialModule, /* Popup, Dialogs */ AlertPopupModule, ConfirmPopupModule, PromptPopupModule, ModalDialogModule.forRoot(), /* Core Module for layout */ CoreModule.forRoot(), /* Mock Data Module */ MockDataModule.forRoot(), /* Device Detector */ DeviceDetectorModule.forRoot(), /* Pipes */ NgPipesModule, /* Lightbox */ LightboxModule, /* Theme */ ThemeModule.forRoot(), NbThemeModule.forRoot({name: AppConfig.COMMON.theme}), NbIconModule, NbInputModule, NbCheckboxModule, NbButtonModule, NbSelectModule, NbSidebarModule.forRoot(), NbMenuModule.forRoot(), NbDatepickerModule.forRoot(), NbDialogModule.forRoot(), NbWindowModule.forRoot(), NbToastrModule.forRoot(), NbChatModule.forRoot({ messageGoogleMapKey: 'AIzaSyA_wNuCzia92MAmdLRzmqitRGvCF7wCZPY', }), /* i18n */ TranslateModule.forRoot(), /* Toaster */ ToastrModule.forRoot(AppConfig.TOASTER), ToastContainerModule, /* Logger */ LoggerModule.forRoot(AppConfig.COMMON.logConfig), /* Database */ NgxIndexedDBModule.forRoot(AppConfig.Db), /* Authentication */ NbAuthModule.forRoot({ strategies: [ NbxOAuth2AuthStrategy.setup({ name: 'email', baseEndpoint: AppConfig.API.user.baseUrl, token: { class: NbxAuthOAuth2Token, key: 'access_token', // this parameter tells where to look for the token }, login: { endpoint: AppConfig.API.user.login, method: AppConfig.API.user.method, headers: AppConfig.API.headers, redirect: { success: '/dashboard', failure: null, // stay on the same page }, }, register: { redirect: { success: '/dashboard', failure: null, // stay on the same page }, }, }), ], forms: { login: { // delay before redirect after a successful login, while success message is shown to the user redirectDelay: 500, strategy: 'email', // strategy id key. rememberMe: false, // whether to show or not the `rememberMe` checkbox showMessages: { // show/not show success/error messages success: false, error: true, }, socialLinks: [], // social links at the bottom of a page }, }, }), /* SplitPane */ AngularSplitModule.forRoot(), /* Tree-view */ TreeviewModule.forRoot(), /* Formly for form builder */ ReactiveFormsModule, FormlyModule.forRoot(), /** * - Bootstrap: FormlyBootstrapModule * - Material2: FormlyMaterialModule * - Ionic: FormlyIonicModule * - PrimeNG: FormlyPrimeNGModule * - Kendo: FormlyKendoModule * - NativeScript: FormlyNativescriptModule */ /*FormlyBootstrapModule,*/ FormlyMaterialModule, FormlyMatDatepickerModule, ], providers: AppConfig.Providers, bootstrap: [AppComponent], }) export class AppModule { constructor(injector: Injector, iconLibraries: NbIconLibraries) { // @ts-ignore AppConfig.Injector = Injector.create({providers: AppConfig.Providers, parent: injector}); iconLibraries.registerFontPack('fa', {packClass: 'fa', iconClassPrefix: 'fa'}); iconLibraries.registerFontPack('fas', {packClass: 'fas', iconClassPrefix: 'fa'}); iconLibraries.registerFontPack('far', {packClass: 'far', iconClassPrefix: 'fa'}); iconLibraries.registerFontPack('ion', {iconClassPrefix: 'ion'}); } }
33.080569
113
0.591404
c82c1767b1547625340e1be9d532e5784666e220
114
php
PHP
resources/views/pages/home.blade.php
FraOliv/laravel-migration-seeder
ed3c5e26360f99dd7e4f37fc3aebd11e805b9b73
[ "MIT" ]
null
null
null
resources/views/pages/home.blade.php
FraOliv/laravel-migration-seeder
ed3c5e26360f99dd7e4f37fc3aebd11e805b9b73
[ "MIT" ]
null
null
null
resources/views/pages/home.blade.php
FraOliv/laravel-migration-seeder
ed3c5e26360f99dd7e4f37fc3aebd11e805b9b73
[ "MIT" ]
null
null
null
@extends('layouts.app') @section('title') Home @endsection @section('main_content') <h1>Home</h1> @endsection
14.25
24
0.701754
b074b798a3f0b17f93ec94ffe132e73768fea87e
3,823
py
Python
bin/list_rc_log.py
roxell/lkft-tools
bd1981b1f616114cb260878fe7319753107e581b
[ "MIT" ]
3
2018-12-14T02:37:10.000Z
2020-04-30T19:07:01.000Z
bin/list_rc_log.py
roxell/lkft-tools
bd1981b1f616114cb260878fe7319753107e581b
[ "MIT" ]
25
2018-07-27T13:38:17.000Z
2021-10-05T13:01:36.000Z
bin/list_rc_log.py
roxell/lkft-tools
bd1981b1f616114cb260878fe7319753107e581b
[ "MIT" ]
12
2018-07-09T22:52:32.000Z
2021-11-29T19:45:33.000Z
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import argparse import datetime import os import pytz import sys import re sys.path.append(os.path.join(sys.path[0], "../", "lib")) import stable_email # noqa: E402 def get_number(s): match = re.search('(\d+)', s) if match: return int(match.group(1)) else: return None if __name__ == "__main__": # Arguments ap = argparse.ArgumentParser() g = ap.add_mutually_exclusive_group(required=False) g.add_argument( "-d", "--days", help="Number of days back to look at; default is 7.", type=int, default=7, ) g.add_argument( "-s", "--since", help="Look as far as the given date (UTC).", type=lambda s: datetime.datetime.strptime(s, "%Y-%m-%d").replace( tzinfo=pytz.utc ), ) args = ap.parse_args() NOW = datetime.datetime.utcnow().replace(tzinfo=pytz.utc) if not args.since: limit = datetime.timedelta(days=args.days) DT_LIMIT = NOW - limit else: DT_LIMIT = args.since # Find review requests coming from Greg from_greg = stable_email.get_review_requests(DT_LIMIT) # Find oldest review request (will stop next search at this point) oldest = NOW for msgid in from_greg.keys(): commit = from_greg[msgid]["request"] dt = commit.committed_datetime if dt < oldest: oldest = dt print("Oldest: %s" % oldest) # Look for replies to Greg's emails from_greg = stable_email.get_review_replies(oldest, from_greg) print("* Computing elapsed time...") rclog = {} for msgid in from_greg.keys(): request_commit = from_greg[msgid]["request"] r = stable_email.Review(request_commit, None) ymd = r.get_ymd() linux_ver = r.get_linux_version() # Did we record any review replies? if "replies" in from_greg[msgid]: # If so, complete the Review object for reply_msg in from_greg[msgid]["replies"]: r.reply = reply_msg sla = r.get_sla_mark() # Print summary if not r.get_regressions_detected(): regression_summary = "No regressions reported" else: regression_summary = "REGRESSIONS REPORTED!" linux_ver += "-REGRESSIONS" print( "[%s] %s: %s (%s) %s (from %s)" % ( ymd, linux_ver, r.get_elapsed_time(), r.get_sla_mark(), regression_summary, r.get_from(), ) ) if ymd not in rclog: rclog[ymd] = {sla: [linux_ver]} else: if sla in rclog[ymd]: rclog[ymd][sla].append(linux_ver) else: rclog[ymd][sla] = [linux_ver] else: print("[%s] %s: No reply yet (%s)" % (ymd, linux_ver, r.get_sla_mark())) # cheap json print(str(rclog).replace("'", '"')) # {'2019-08-09': {'<48h': ['4.4.189']}, '2019-08-08': {'<24h': ['5.2.8', '4.19.66', '4.14.138']}} print("") for date in sorted(rclog, reverse=True): slas = rclog[date] print("### {}".format(date)) for sla in sorted(slas, key=lambda sla: get_number(sla)): releases = slas[sla] releases.sort(key=lambda s: list(map(get_number, s.split('.')))) print("#### {}".format(", ".join(releases))) print("<!-- sla {} {} -->".format(sla.strip("h"), len(releases))) print("- XXX in {}".format(sla)) print("")
30.102362
101
0.516872
45cfece39f36e8b5450e4f78d6ba66e2e3a3b5f0
146
py
Python
aiohttp_socks/proxy/enums.py
RomaLash/aiohttp-socks
b80e493e1974587b2ee839e42953ccf2b049b4fa
[ "Apache-2.0" ]
1
2021-02-28T15:52:03.000Z
2021-02-28T15:52:03.000Z
aiohttp_socks/proxy/enums.py
rytilahti/aiohttp-socks
005c87cbcfda415cdfb43dc55bbee617e428d0f1
[ "Apache-2.0" ]
null
null
null
aiohttp_socks/proxy/enums.py
rytilahti/aiohttp-socks
005c87cbcfda415cdfb43dc55bbee617e428d0f1
[ "Apache-2.0" ]
null
null
null
from enum import Enum class SocksVer(object): SOCKS4 = 1 SOCKS5 = 2 class ProxyType(Enum): SOCKS4 = 1 SOCKS5 = 2 HTTP = 3
11.230769
23
0.60274
10c14db8fc6671cf44ab9286ef4b8732525efb6b
2,905
sh
Shell
run_ide.sh
hpe-container-platform-community/vagrant-box-kubedirector-lab
da501f7e406713a6242225f9662665b0f6621a87
[ "Apache-2.0" ]
1
2021-06-30T15:05:25.000Z
2021-06-30T15:05:25.000Z
run_ide.sh
hpe-container-platform-community/vagrant-box-kubedirector-lab
da501f7e406713a6242225f9662665b0f6621a87
[ "Apache-2.0" ]
null
null
null
run_ide.sh
hpe-container-platform-community/vagrant-box-kubedirector-lab
da501f7e406713a6242225f9662665b0f6621a87
[ "Apache-2.0" ]
1
2021-12-06T21:44:12.000Z
2021-12-06T21:44:12.000Z
#!/bin/bash if [[ $(whoami) == "vagrant" || $(hostname) == "control-plane.minikube.internal" ]]; then echo "Aborting. This script should not be run in vagrant box by vagrant user." exit 1 fi git_vars=1 if [[ -z $GIT_USER ]]; then echo "GIT_USER variable not found" git_vars=0 else CURRENT_GIT_USER=$(git config credential.https://github.com.username) if [[ "$CURRENT_GIT_USER" != "$GIT_USER" ]]; then echo "Found username '${CURRENT_GIT_USER}' in project git config." echo "Found username '${GIT_USER}' in GIT_USER environment variable." while true; do read -p "Would you like to update your git config to '${GIT_USER}'?" yn case $yn in [Yy]* ) git config credential.https://github.com.username $GIT_USER; break;; [Nn]* ) break;; * ) echo "Please answer yes or no.";; esac done fi fi if [[ -z $GIT_PASS ]]; then echo "GIT_PASS variable not found" git_vars=0 fi if [[ -z $GIT_AUTHOR_NAME ]]; then echo "GIT_AUTHOR_NAME variable not found" git_vars=0 fi if [[ -z $GIT_COMMITTER_NAME ]]; then echo "GIT_COMMITTER_NAME variable not found" git_vars=0 fi if [[ -z $GIT_AUTHOR_EMAIL ]]; then echo "GIT_AUTHOR_EMAIL variable not found" git_vars=0 fi if [[ -z $GIT_COMMITTER_EMAIL ]]; then echo "GIT_COMMITER_EMAIL variable not found" git_vars=0 fi if [[ $git_vars == 0 ]]; then echo echo "WARNING:" echo "One or more git variables were not set." echo "You will not be able to push/pull to github from inside theia." echo echo "TIP:" echo "you can set these variables in .bashrc or .bash_profile, e.g." echo ------------------------------------- echo export GIT_USER=your_git_username echo export GIT_PASS=your_git_password echo export GIT_AUTHOR_NAME="Your name" echo export GIT_COMMITTER_NAME="Your name" echo export GIT_AUTHOR_EMAIL=your@email echo export GIT_COMMITTER_EMAIL=your@email echo ------------------------------------- echo while true; do read -p "Do you want to continue without git configured in Theia?" yn case $yn in [Yy]* ) break;; [Nn]* ) exit;; * ) echo "Please answer yes or no.";; esac done fi vagrant ssh -c " export SHELL=/bin/bash export THEIA_DEFAULT_PLUGINS=local-dir:/home/vagrant/plugins export GOPATH=/home/project export PATH=\$PATH:\$GOPATH/bin # set env variables from local environment export GIT_USER='$GIT_USER' export GIT_PASS='$GIT_PASS' export GIT_AUTHOR_NAME='$GIT_AUTHOR_NAME' export GIT_COMMITTER_NAME='$GIT_COMMITTER_NAME' export GIT_AUTHOR_EMAIL='$GIT_AUTHOR_EMAIL' export GIT_COMMITTER_EMAIL='$GIT_COMMITTER_EMAIL' export GIT_ASKPASS=/home/vagrant/git_env_password.sh cd /home/vagrant node ./src-gen/backend/main.js /vagrant/src/github.com/bluek8s/kubedirector/ --hostname=0.0.0.0 "
27.932692
99
0.659552
06f58e1270708541f61e9ed1f410e84e3afbbf00
949
py
Python
cluster_config/generate_push.py
tapanalyticstoolkit/cluster-config
d2a02c058b4d13987924eed7476a9bb0586549c8
[ "Apache-2.0" ]
null
null
null
cluster_config/generate_push.py
tapanalyticstoolkit/cluster-config
d2a02c058b4d13987924eed7476a9bb0586549c8
[ "Apache-2.0" ]
2
2017-03-22T21:08:15.000Z
2017-03-22T21:13:20.000Z
cluster_config/generate_push.py
tapanalyticstoolkit/cluster-config
d2a02c058b4d13987924eed7476a9bb0586549c8
[ "Apache-2.0" ]
1
2020-11-10T16:58:38.000Z
2020-11-10T16:58:38.000Z
from __future__ import print_function import argparse import datetime from cluster_config import generate, push from cluster_config.cdh.cluster import Cluster def cli(parser=None): if parser is None: parser = argparse.ArgumentParser(description="Auto generate various CDH configurations based on system resources") parser = generate.cli(parser) parser = push.cli(parser) return parser def main(): from cluster_config.cdh.cluster import Cluster #from cluster_config import push from cluster_config.utils.cli import parse args = parse(cli()) cluster = Cluster(args.host, args.port, args.username, args.password, args.cluster) run(args, cluster) def run(args, cluster=None): if cluster is None: cluster = Cluster(args.host, args.port, args.username, args.password, args.cluster) dt = datetime.datetime.now() generate.run(args, cluster, dt) push.run(args, cluster, dt)
25.648649
122
0.727081
ddc733229b0fb797cfe8991fec44b1602936e6e8
15,669
java
Java
src/main/java/com/example/lovenews/base/TabDetailPager.java
wuyinlei/Lovenews
d56e1bc35ff6ddd3ae286570a59bcd3fa953e449
[ "Apache-2.0" ]
null
null
null
src/main/java/com/example/lovenews/base/TabDetailPager.java
wuyinlei/Lovenews
d56e1bc35ff6ddd3ae286570a59bcd3fa953e449
[ "Apache-2.0" ]
null
null
null
src/main/java/com/example/lovenews/base/TabDetailPager.java
wuyinlei/Lovenews
d56e1bc35ff6ddd3ae286570a59bcd3fa953e449
[ "Apache-2.0" ]
null
null
null
package com.example.lovenews.base; import android.app.Activity; import android.content.Intent; import android.graphics.Color; import android.os.Handler; import android.os.Message; import android.support.v4.view.PagerAdapter; import android.support.v4.view.ViewPager; import android.text.TextUtils; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import com.example.lovenews.R; import com.example.lovenews.activity.NewsDetailActivity; import com.example.lovenews.bean.NewsData; import com.example.lovenews.bean.TabData; import com.example.lovenews.contants.Contants; import com.example.lovenews.utils.CacheUtils; import com.example.lovenews.utils.PrefUtils; import com.example.lovenews.view.RefreshListView; import com.example.lovenews.view.TopNewsViewPager; import com.google.gson.Gson; import com.lidroid.xutils.BitmapUtils; import com.lidroid.xutils.HttpUtils; import com.lidroid.xutils.ViewUtils; import com.lidroid.xutils.exception.HttpException; import com.lidroid.xutils.http.ResponseInfo; import com.lidroid.xutils.http.callback.RequestCallBack; import com.lidroid.xutils.http.client.HttpRequest; import com.lidroid.xutils.view.annotation.ViewInject; import com.viewpagerindicator.CirclePageIndicator; import java.util.List; /** * Created by 若兰 on 2016/1/16. * 一个懂得了编程乐趣的小白,希望自己 * 能够在这个道路上走的很远,也希望自己学习到的 * 知识可以帮助更多的人,分享就是学习的一种乐趣 * QQ:1069584784 * csdn:http://blog.csdn.net/wuyinlei */ public class TabDetailPager extends BaseMenuDetailPager implements ViewPager.OnPageChangeListener { NewsData.NewsTabData mTabData; /** * */ private String mUrl = null; private TabData mFromTabData; /** * 头条新闻位置指示器 */ @ViewInject(R.id.indicator) private CirclePageIndicator mIndicator; @ViewInject(R.id.viewPager) private TopNewsViewPager mViewPager; /** * 头条新闻标题 */ @ViewInject(R.id.tvTitle) private TextView mTextView; @ViewInject(R.id.lv_list) private RefreshListView mListView; private List<TabData.TopNewsData> mTopnews; private List<TabData.TabNewsData> mNewsDataList; private String mMoreUrl; private NewsAdapter adapter; private String mRead_ids; private Handler mHandler; public TabDetailPager(Activity activity, NewsData.NewsTabData newsTabData) { super(activity); mTabData = newsTabData; //初始化地址 mUrl = Contants.BASE_URL + mTabData.url; } @Override public View initViews() { View view = View.inflate(mActivity, R.layout.tab_detail_pager, null); /** * 加载头布局 */ View headerView = View.inflate(mActivity, R.layout.list_header_top_news, null); //注解 ViewUtils.inject(this, view); ViewUtils.inject(this, headerView); //将头条新闻以头布局的相识加给listview mListView.addHeaderView(headerView); /** * 设置下拉刷新的事件监听 */ mListView.setOnRefreshListener(new RefreshListView.OnRefreshListener() { /** * 下拉刷新 */ @Override public void onRefresh() { getDataFromServer(); } /** * 上拉加载更多 */ @Override public void onLoadMore() { if (mMoreUrl != null) { getMoreDataFromServer(); } else { Toast.makeText(mActivity, "已经是最后一页了", Toast.LENGTH_SHORT).show(); mListView.OnRefreshComplete(false); //收起脚部局 } } }); mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { //Toast.makeText(mActivity, "position:" + position, Toast.LENGTH_SHORT).show(); /** * 每个新闻都有一个id,我们记录id,然后就能设置已读和未读 * * 3222,22511,5541,44515,45414 */ mRead_ids = PrefUtils.getString(mActivity, "read_ids", ""); String ids = mNewsDataList.get(position).id; /** * 在本地记录是否阅读了新闻 * * 如果包含了不加 */ if (!mRead_ids.contains(ids)) { mRead_ids = mRead_ids + ids + ","; PrefUtils.setString(mActivity, "read_ids", mRead_ids); } //实现局部界面刷新 view---->被点击的item的对象 changeReadState(view); //adapter.notifyDataSetChanged(); /** * 跳转到新闻详情页面 */ Intent intent = new Intent(mActivity, NewsDetailActivity.class); intent.putExtra("url", mNewsDataList.get(position).url); mActivity.startActivity(intent); } }); return view; } /** * 改变已经读的颜色 */ private void changeReadState(View view) { TextView tvTitle = (TextView) view.findViewById(R.id.tvTitle); tvTitle.setTextColor(Color.GRAY); } /** * 初始话数据 */ @Override public void initData() { //tvTitle.setText(mTabData.title); String cache = CacheUtils.getCache(mUrl, mActivity); if (!TextUtils.isEmpty(cache)) { parseData(cache, false); } getDataFromServer(); } @Override public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { } @Override public void onPageSelected(int position) { mTextView.setText(mTopnews.get(position).title); } @Override public void onPageScrollStateChanged(int state) { } /** * ViewPager适配器 */ class TopNewsAdapter extends PagerAdapter { private BitmapUtils mBitmapUtils; public TopNewsAdapter() { mBitmapUtils = new BitmapUtils(mActivity); //设置默认的加载的图片 mBitmapUtils.configDefaultLoadingImage(R.mipmap.topnews_item_default); } @Override public int getCount() { return mFromTabData.data.topnews.size(); } @Override public boolean isViewFromObject(View view, Object object) { return view == object; } @Override public Object instantiateItem(ViewGroup container, int position) { ImageView image = new ImageView(mActivity); //image.setImageResource(R.mipmap.topnews_item_default); //完全匹配父控件的宽高 image.setScaleType(ImageView.ScaleType.FIT_XY); TabData.TopNewsData topNewsData = mFromTabData.data.topnews.get(position); //传递imageview对象和图片地址 mBitmapUtils.display(image, topNewsData.topimage); image.setOnTouchListener(new TopNewsTouchListener()); container.addView(image); return image; } @Override public void destroyItem(ViewGroup container, int position, Object object) { container.removeView((View) object); } } /** * 头条新闻的额触摸监听 */ class TopNewsTouchListener implements View.OnTouchListener{ @Override public boolean onTouch(View v, MotionEvent event) { switch (event.getAction()){ case MotionEvent.ACTION_DOWN: //移除所有的handler消息 mHandler.removeCallbacksAndMessages(null); break; case MotionEvent.ACTION_CANCEL: mHandler.sendEmptyMessageDelayed(0,3000); break; case MotionEvent.ACTION_UP: mHandler.sendEmptyMessageDelayed(0,3000); break; } return true; } } /** * 请求服务器数据 */ private void getDataFromServer() { HttpUtils utils = new HttpUtils(); utils.send(HttpRequest.HttpMethod.GET, mUrl, new RequestCallBack<String>() { @Override public void onSuccess(ResponseInfo<String> responseInfo) { String result = (String) responseInfo.result; //System.out.println("返回结果:" + result); //Log.d("TabDetailPager", "页签详情页" + result); parseData(result, false); mListView.OnRefreshComplete(true); /** * 保存缓存 */ CacheUtils.setCache(mUrl, result, mActivity); } @Override public void onFailure(HttpException error, String msg) { Toast.makeText(mActivity, msg, Toast.LENGTH_SHORT) .show(); error.printStackTrace(); mListView.OnRefreshComplete(false); } }); } /** * 请求服务器数据 * <p/> * 请求更多数据 */ private void getMoreDataFromServer() { HttpUtils utils = new HttpUtils(); utils.send(HttpRequest.HttpMethod.GET, mMoreUrl, new RequestCallBack<String>() { @Override public void onSuccess(ResponseInfo<String> responseInfo) { String result = (String) responseInfo.result; //System.out.println("返回结果:" + result); //Log.d("TabDetailPager", "页签详情页" + result); parseData(result, true); mListView.OnRefreshComplete(true); } @Override public void onFailure(HttpException error, String msg) { Toast.makeText(mActivity, msg, Toast.LENGTH_SHORT) .show(); error.printStackTrace(); mListView.OnRefreshComplete(false); } }); } /** * 解析数据 * * @param result 数据的结果 * @param isMore 是否加载更多 */ private void parseData(String result, boolean isMore) { Gson gson = new Gson(); mFromTabData = gson.fromJson(result, TabData.class); /** * 获取到下一页数据的地址 */ String more = mFromTabData.data.more; /** * 处理更多页面的逻辑 */ if (!TextUtils.isEmpty(more)) { //地址拼接 mMoreUrl = Contants.BASE_URL + more; } else { //否则设置为空 mMoreUrl = null; } //Log.d("TabDetailPager", "mFromTabData:" + mFromTabData); if (!isMore) { /* mNewsDataList = mFromTabData.data.news; //判断是否为空 if (mNewsDataList != null) { adapter = new NewsAdapter(); mListView.setAdapter(adapter); }*/ initLists(); /* mTopnews = mFromTabData.data.topnews; //判断是否为空 if (mTopnews != null) { mTextView.setText(mTopnews.get(0).title); *//** * 在拿到数据之后在去设置adapter *//* mViewPager.setAdapter(new TopNewsAdapter()); //mViewPager.setOnPageChangeListener(this); mIndicator.setViewPager(mViewPager); mIndicator.setSnap(true);//快照显示 mIndicator.setOnPageChangeListener(this); //让指示器重新定位到第一个 mIndicator.onPageSelected(0); }*/ indicatorInit(); /** * 自动轮播条显示 */ if (mHandler == null) { mHandler = new Handler() { @Override public void handleMessage(Message msg) { super.handleMessage(msg); int currentItem = mViewPager.getCurrentItem(); if (currentItem < mTopnews.size() - 1) { currentItem++; } else { currentItem = 0; } //切换到下一个页面 mViewPager.setCurrentItem(currentItem); //继续延时3秒发消息 mHandler.sendEmptyMessageDelayed(0, 3000); } }; //延时3秒发消息 mHandler.sendEmptyMessageDelayed(0, 3000); } } else { //如果是加载下一页,需要将数据追加到集合中 List<TabData.TabNewsData> news = mFromTabData.data.news; mNewsDataList.addAll(news); adapter.notifyDataSetChanged(); } } /** * 初始化listview数据 */ private void initLists() { mNewsDataList = mFromTabData.data.news; //判断是否为空 if (mNewsDataList != null) { adapter = new NewsAdapter(); mListView.setAdapter(adapter); } } /** * 初始化Indicator和viewpager的数据 */ private void indicatorInit() { mTopnews = mFromTabData.data.topnews; //判断是否为空 if (mTopnews != null) { mTextView.setText(mTopnews.get(0).title); /** * 在拿到数据之后在去设置adapter */ mViewPager.setAdapter(new TopNewsAdapter()); //mViewPager.setOnPageChangeListener(this); mIndicator.setViewPager(mViewPager); mIndicator.setSnap(true);//快照显示 mIndicator.setOnPageChangeListener(this); //让指示器重新定位到第一个 mIndicator.onPageSelected(0); } } /** * 新闻列表的适配器 */ class NewsAdapter extends BaseAdapter { private BitmapUtils mBitmapUtils; public NewsAdapter() { mBitmapUtils = new BitmapUtils(mActivity); mBitmapUtils.configDefaultLoadingImage(R.mipmap.pic_item_list_default); } @Override public int getCount() { return mNewsDataList.size(); } @Override public TabData.TabNewsData getItem(int position) { return mNewsDataList.get(position); } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { ViewHolder holder; //view的复用 if (convertView == null) { holder = new ViewHolder(); convertView = View.inflate(mActivity, R.layout.list_news_item, null); holder.mIvImage = (ImageView) convertView.findViewById(R.id.ivImage); holder.mTvData = (TextView) convertView.findViewById(R.id.tvData); holder.mTvTitle = (TextView) convertView.findViewById(R.id.tvTitle); convertView.setTag(holder); } else { holder = (ViewHolder) convertView.getTag(); } TabData.TabNewsData item = getItem(position); holder.mTvData.setText(item.pubdate); mBitmapUtils.display(holder.mIvImage, item.listimage); holder.mTvTitle.setText(item.title); mRead_ids = PrefUtils.getString(mActivity, "read_ids", ""); if (mRead_ids.contains(getItem(position).id)) { holder.mTvTitle.setTextColor(Color.GRAY); } else { holder.mTvTitle.setTextColor(Color.BLACK); } return convertView; } } static class ViewHolder { private TextView mTvTitle; private TextView mTvData; private ImageView mIvImage; } }
28.697802
99
0.559257
8544a4d65554e0155e5823aeaf85d3017d378c3d
35,743
cs
C#
sdk/network/Azure.ResourceManager.Network/src/Generated/ExpressRouteCircuitsClient.cs
mjaow/azure-sdk-for-net
ad9838c78ab168cc643e06d81c497608e6e1cb4c
[ "MIT" ]
null
null
null
sdk/network/Azure.ResourceManager.Network/src/Generated/ExpressRouteCircuitsClient.cs
mjaow/azure-sdk-for-net
ad9838c78ab168cc643e06d81c497608e6e1cb4c
[ "MIT" ]
null
null
null
sdk/network/Azure.ResourceManager.Network/src/Generated/ExpressRouteCircuitsClient.cs
mjaow/azure-sdk-for-net
ad9838c78ab168cc643e06d81c497608e6e1cb4c
[ "MIT" ]
null
null
null
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // <auto-generated/> #nullable disable using System; using System.Threading; using System.Threading.Tasks; using Azure; using Azure.Core; using Azure.Core.Pipeline; using Azure.ResourceManager.Network.Models; namespace Azure.ResourceManager.Network { /// <summary> The ExpressRouteCircuits service client. </summary> public partial class ExpressRouteCircuitsClient { private readonly ClientDiagnostics _clientDiagnostics; private readonly HttpPipeline _pipeline; internal ExpressRouteCircuitsRestClient RestClient { get; } /// <summary> Initializes a new instance of ExpressRouteCircuitsClient for mocking. </summary> protected ExpressRouteCircuitsClient() { } /// <summary> Initializes a new instance of ExpressRouteCircuitsClient. </summary> /// <param name="clientDiagnostics"> The handler for diagnostic messaging in the client. </param> /// <param name="pipeline"> The HTTP pipeline for sending and receiving REST requests and responses. </param> /// <param name="subscriptionId"> The subscription credentials which uniquely identify the Microsoft Azure subscription. The subscription ID forms part of the URI for every service call. </param> /// <param name="endpoint"> server parameter. </param> internal ExpressRouteCircuitsClient(ClientDiagnostics clientDiagnostics, HttpPipeline pipeline, string subscriptionId, Uri endpoint = null) { RestClient = new ExpressRouteCircuitsRestClient(clientDiagnostics, pipeline, subscriptionId, endpoint); _clientDiagnostics = clientDiagnostics; _pipeline = pipeline; } /// <summary> Gets information about the specified express route circuit. </summary> /// <param name="resourceGroupName"> The name of the resource group. </param> /// <param name="circuitName"> The name of express route circuit. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> public virtual async Task<Response<ExpressRouteCircuit>> GetAsync(string resourceGroupName, string circuitName, CancellationToken cancellationToken = default) { using var scope = _clientDiagnostics.CreateScope("ExpressRouteCircuitsClient.Get"); scope.Start(); try { return await RestClient.GetAsync(resourceGroupName, circuitName, cancellationToken).ConfigureAwait(false); } catch (Exception e) { scope.Failed(e); throw; } } /// <summary> Gets information about the specified express route circuit. </summary> /// <param name="resourceGroupName"> The name of the resource group. </param> /// <param name="circuitName"> The name of express route circuit. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> public virtual Response<ExpressRouteCircuit> Get(string resourceGroupName, string circuitName, CancellationToken cancellationToken = default) { using var scope = _clientDiagnostics.CreateScope("ExpressRouteCircuitsClient.Get"); scope.Start(); try { return RestClient.Get(resourceGroupName, circuitName, cancellationToken); } catch (Exception e) { scope.Failed(e); throw; } } /// <summary> Updates an express route circuit tags. </summary> /// <param name="resourceGroupName"> The name of the resource group. </param> /// <param name="circuitName"> The name of the circuit. </param> /// <param name="parameters"> Parameters supplied to update express route circuit tags. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> public virtual async Task<Response<ExpressRouteCircuit>> UpdateTagsAsync(string resourceGroupName, string circuitName, TagsObject parameters, CancellationToken cancellationToken = default) { using var scope = _clientDiagnostics.CreateScope("ExpressRouteCircuitsClient.UpdateTags"); scope.Start(); try { return await RestClient.UpdateTagsAsync(resourceGroupName, circuitName, parameters, cancellationToken).ConfigureAwait(false); } catch (Exception e) { scope.Failed(e); throw; } } /// <summary> Updates an express route circuit tags. </summary> /// <param name="resourceGroupName"> The name of the resource group. </param> /// <param name="circuitName"> The name of the circuit. </param> /// <param name="parameters"> Parameters supplied to update express route circuit tags. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> public virtual Response<ExpressRouteCircuit> UpdateTags(string resourceGroupName, string circuitName, TagsObject parameters, CancellationToken cancellationToken = default) { using var scope = _clientDiagnostics.CreateScope("ExpressRouteCircuitsClient.UpdateTags"); scope.Start(); try { return RestClient.UpdateTags(resourceGroupName, circuitName, parameters, cancellationToken); } catch (Exception e) { scope.Failed(e); throw; } } /// <summary> Gets all the stats from an express route circuit in a resource group. </summary> /// <param name="resourceGroupName"> The name of the resource group. </param> /// <param name="circuitName"> The name of the express route circuit. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> public virtual async Task<Response<ExpressRouteCircuitStats>> GetStatsAsync(string resourceGroupName, string circuitName, CancellationToken cancellationToken = default) { using var scope = _clientDiagnostics.CreateScope("ExpressRouteCircuitsClient.GetStats"); scope.Start(); try { return await RestClient.GetStatsAsync(resourceGroupName, circuitName, cancellationToken).ConfigureAwait(false); } catch (Exception e) { scope.Failed(e); throw; } } /// <summary> Gets all the stats from an express route circuit in a resource group. </summary> /// <param name="resourceGroupName"> The name of the resource group. </param> /// <param name="circuitName"> The name of the express route circuit. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> public virtual Response<ExpressRouteCircuitStats> GetStats(string resourceGroupName, string circuitName, CancellationToken cancellationToken = default) { using var scope = _clientDiagnostics.CreateScope("ExpressRouteCircuitsClient.GetStats"); scope.Start(); try { return RestClient.GetStats(resourceGroupName, circuitName, cancellationToken); } catch (Exception e) { scope.Failed(e); throw; } } /// <summary> Gets all stats from an express route circuit in a resource group. </summary> /// <param name="resourceGroupName"> The name of the resource group. </param> /// <param name="circuitName"> The name of the express route circuit. </param> /// <param name="peeringName"> The name of the peering. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> public virtual async Task<Response<ExpressRouteCircuitStats>> GetPeeringStatsAsync(string resourceGroupName, string circuitName, string peeringName, CancellationToken cancellationToken = default) { using var scope = _clientDiagnostics.CreateScope("ExpressRouteCircuitsClient.GetPeeringStats"); scope.Start(); try { return await RestClient.GetPeeringStatsAsync(resourceGroupName, circuitName, peeringName, cancellationToken).ConfigureAwait(false); } catch (Exception e) { scope.Failed(e); throw; } } /// <summary> Gets all stats from an express route circuit in a resource group. </summary> /// <param name="resourceGroupName"> The name of the resource group. </param> /// <param name="circuitName"> The name of the express route circuit. </param> /// <param name="peeringName"> The name of the peering. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> public virtual Response<ExpressRouteCircuitStats> GetPeeringStats(string resourceGroupName, string circuitName, string peeringName, CancellationToken cancellationToken = default) { using var scope = _clientDiagnostics.CreateScope("ExpressRouteCircuitsClient.GetPeeringStats"); scope.Start(); try { return RestClient.GetPeeringStats(resourceGroupName, circuitName, peeringName, cancellationToken); } catch (Exception e) { scope.Failed(e); throw; } } /// <summary> Gets all the express route circuits in a resource group. </summary> /// <param name="resourceGroupName"> The name of the resource group. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> public virtual AsyncPageable<ExpressRouteCircuit> ListAsync(string resourceGroupName, CancellationToken cancellationToken = default) { if (resourceGroupName == null) { throw new ArgumentNullException(nameof(resourceGroupName)); } async Task<Page<ExpressRouteCircuit>> FirstPageFunc(int? pageSizeHint) { using var scope = _clientDiagnostics.CreateScope("ExpressRouteCircuitsClient.List"); scope.Start(); try { var response = await RestClient.ListAsync(resourceGroupName, cancellationToken).ConfigureAwait(false); return Page.FromValues(response.Value.Value, response.Value.NextLink, response.GetRawResponse()); } catch (Exception e) { scope.Failed(e); throw; } } async Task<Page<ExpressRouteCircuit>> NextPageFunc(string nextLink, int? pageSizeHint) { using var scope = _clientDiagnostics.CreateScope("ExpressRouteCircuitsClient.List"); scope.Start(); try { var response = await RestClient.ListNextPageAsync(nextLink, resourceGroupName, cancellationToken).ConfigureAwait(false); return Page.FromValues(response.Value.Value, response.Value.NextLink, response.GetRawResponse()); } catch (Exception e) { scope.Failed(e); throw; } } return PageableHelpers.CreateAsyncEnumerable(FirstPageFunc, NextPageFunc); } /// <summary> Gets all the express route circuits in a resource group. </summary> /// <param name="resourceGroupName"> The name of the resource group. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> public virtual Pageable<ExpressRouteCircuit> List(string resourceGroupName, CancellationToken cancellationToken = default) { if (resourceGroupName == null) { throw new ArgumentNullException(nameof(resourceGroupName)); } Page<ExpressRouteCircuit> FirstPageFunc(int? pageSizeHint) { using var scope = _clientDiagnostics.CreateScope("ExpressRouteCircuitsClient.List"); scope.Start(); try { var response = RestClient.List(resourceGroupName, cancellationToken); return Page.FromValues(response.Value.Value, response.Value.NextLink, response.GetRawResponse()); } catch (Exception e) { scope.Failed(e); throw; } } Page<ExpressRouteCircuit> NextPageFunc(string nextLink, int? pageSizeHint) { using var scope = _clientDiagnostics.CreateScope("ExpressRouteCircuitsClient.List"); scope.Start(); try { var response = RestClient.ListNextPage(nextLink, resourceGroupName, cancellationToken); return Page.FromValues(response.Value.Value, response.Value.NextLink, response.GetRawResponse()); } catch (Exception e) { scope.Failed(e); throw; } } return PageableHelpers.CreateEnumerable(FirstPageFunc, NextPageFunc); } /// <summary> Gets all the express route circuits in a subscription. </summary> /// <param name="cancellationToken"> The cancellation token to use. </param> public virtual AsyncPageable<ExpressRouteCircuit> ListAllAsync(CancellationToken cancellationToken = default) { async Task<Page<ExpressRouteCircuit>> FirstPageFunc(int? pageSizeHint) { using var scope = _clientDiagnostics.CreateScope("ExpressRouteCircuitsClient.ListAll"); scope.Start(); try { var response = await RestClient.ListAllAsync(cancellationToken).ConfigureAwait(false); return Page.FromValues(response.Value.Value, response.Value.NextLink, response.GetRawResponse()); } catch (Exception e) { scope.Failed(e); throw; } } async Task<Page<ExpressRouteCircuit>> NextPageFunc(string nextLink, int? pageSizeHint) { using var scope = _clientDiagnostics.CreateScope("ExpressRouteCircuitsClient.ListAll"); scope.Start(); try { var response = await RestClient.ListAllNextPageAsync(nextLink, cancellationToken).ConfigureAwait(false); return Page.FromValues(response.Value.Value, response.Value.NextLink, response.GetRawResponse()); } catch (Exception e) { scope.Failed(e); throw; } } return PageableHelpers.CreateAsyncEnumerable(FirstPageFunc, NextPageFunc); } /// <summary> Gets all the express route circuits in a subscription. </summary> /// <param name="cancellationToken"> The cancellation token to use. </param> public virtual Pageable<ExpressRouteCircuit> ListAll(CancellationToken cancellationToken = default) { Page<ExpressRouteCircuit> FirstPageFunc(int? pageSizeHint) { using var scope = _clientDiagnostics.CreateScope("ExpressRouteCircuitsClient.ListAll"); scope.Start(); try { var response = RestClient.ListAll(cancellationToken); return Page.FromValues(response.Value.Value, response.Value.NextLink, response.GetRawResponse()); } catch (Exception e) { scope.Failed(e); throw; } } Page<ExpressRouteCircuit> NextPageFunc(string nextLink, int? pageSizeHint) { using var scope = _clientDiagnostics.CreateScope("ExpressRouteCircuitsClient.ListAll"); scope.Start(); try { var response = RestClient.ListAllNextPage(nextLink, cancellationToken); return Page.FromValues(response.Value.Value, response.Value.NextLink, response.GetRawResponse()); } catch (Exception e) { scope.Failed(e); throw; } } return PageableHelpers.CreateEnumerable(FirstPageFunc, NextPageFunc); } /// <summary> Deletes the specified express route circuit. </summary> /// <param name="resourceGroupName"> The name of the resource group. </param> /// <param name="circuitName"> The name of the express route circuit. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> public virtual async Task<ExpressRouteCircuitsDeleteOperation> StartDeleteAsync(string resourceGroupName, string circuitName, CancellationToken cancellationToken = default) { if (resourceGroupName == null) { throw new ArgumentNullException(nameof(resourceGroupName)); } if (circuitName == null) { throw new ArgumentNullException(nameof(circuitName)); } using var scope = _clientDiagnostics.CreateScope("ExpressRouteCircuitsClient.StartDelete"); scope.Start(); try { var originalResponse = await RestClient.DeleteAsync(resourceGroupName, circuitName, cancellationToken).ConfigureAwait(false); return new ExpressRouteCircuitsDeleteOperation(_clientDiagnostics, _pipeline, RestClient.CreateDeleteRequest(resourceGroupName, circuitName).Request, originalResponse); } catch (Exception e) { scope.Failed(e); throw; } } /// <summary> Deletes the specified express route circuit. </summary> /// <param name="resourceGroupName"> The name of the resource group. </param> /// <param name="circuitName"> The name of the express route circuit. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> public virtual ExpressRouteCircuitsDeleteOperation StartDelete(string resourceGroupName, string circuitName, CancellationToken cancellationToken = default) { if (resourceGroupName == null) { throw new ArgumentNullException(nameof(resourceGroupName)); } if (circuitName == null) { throw new ArgumentNullException(nameof(circuitName)); } using var scope = _clientDiagnostics.CreateScope("ExpressRouteCircuitsClient.StartDelete"); scope.Start(); try { var originalResponse = RestClient.Delete(resourceGroupName, circuitName, cancellationToken); return new ExpressRouteCircuitsDeleteOperation(_clientDiagnostics, _pipeline, RestClient.CreateDeleteRequest(resourceGroupName, circuitName).Request, originalResponse); } catch (Exception e) { scope.Failed(e); throw; } } /// <summary> Creates or updates an express route circuit. </summary> /// <param name="resourceGroupName"> The name of the resource group. </param> /// <param name="circuitName"> The name of the circuit. </param> /// <param name="parameters"> Parameters supplied to the create or update express route circuit operation. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> public virtual async Task<ExpressRouteCircuitsCreateOrUpdateOperation> StartCreateOrUpdateAsync(string resourceGroupName, string circuitName, ExpressRouteCircuit parameters, CancellationToken cancellationToken = default) { if (resourceGroupName == null) { throw new ArgumentNullException(nameof(resourceGroupName)); } if (circuitName == null) { throw new ArgumentNullException(nameof(circuitName)); } if (parameters == null) { throw new ArgumentNullException(nameof(parameters)); } using var scope = _clientDiagnostics.CreateScope("ExpressRouteCircuitsClient.StartCreateOrUpdate"); scope.Start(); try { var originalResponse = await RestClient.CreateOrUpdateAsync(resourceGroupName, circuitName, parameters, cancellationToken).ConfigureAwait(false); return new ExpressRouteCircuitsCreateOrUpdateOperation(_clientDiagnostics, _pipeline, RestClient.CreateCreateOrUpdateRequest(resourceGroupName, circuitName, parameters).Request, originalResponse); } catch (Exception e) { scope.Failed(e); throw; } } /// <summary> Creates or updates an express route circuit. </summary> /// <param name="resourceGroupName"> The name of the resource group. </param> /// <param name="circuitName"> The name of the circuit. </param> /// <param name="parameters"> Parameters supplied to the create or update express route circuit operation. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> public virtual ExpressRouteCircuitsCreateOrUpdateOperation StartCreateOrUpdate(string resourceGroupName, string circuitName, ExpressRouteCircuit parameters, CancellationToken cancellationToken = default) { if (resourceGroupName == null) { throw new ArgumentNullException(nameof(resourceGroupName)); } if (circuitName == null) { throw new ArgumentNullException(nameof(circuitName)); } if (parameters == null) { throw new ArgumentNullException(nameof(parameters)); } using var scope = _clientDiagnostics.CreateScope("ExpressRouteCircuitsClient.StartCreateOrUpdate"); scope.Start(); try { var originalResponse = RestClient.CreateOrUpdate(resourceGroupName, circuitName, parameters, cancellationToken); return new ExpressRouteCircuitsCreateOrUpdateOperation(_clientDiagnostics, _pipeline, RestClient.CreateCreateOrUpdateRequest(resourceGroupName, circuitName, parameters).Request, originalResponse); } catch (Exception e) { scope.Failed(e); throw; } } /// <summary> Gets the currently advertised ARP table associated with the express route circuit in a resource group. </summary> /// <param name="resourceGroupName"> The name of the resource group. </param> /// <param name="circuitName"> The name of the express route circuit. </param> /// <param name="peeringName"> The name of the peering. </param> /// <param name="devicePath"> The path of the device. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> public virtual async Task<ExpressRouteCircuitsListArpTableOperation> StartListArpTableAsync(string resourceGroupName, string circuitName, string peeringName, string devicePath, CancellationToken cancellationToken = default) { if (resourceGroupName == null) { throw new ArgumentNullException(nameof(resourceGroupName)); } if (circuitName == null) { throw new ArgumentNullException(nameof(circuitName)); } if (peeringName == null) { throw new ArgumentNullException(nameof(peeringName)); } if (devicePath == null) { throw new ArgumentNullException(nameof(devicePath)); } using var scope = _clientDiagnostics.CreateScope("ExpressRouteCircuitsClient.StartListArpTable"); scope.Start(); try { var originalResponse = await RestClient.ListArpTableAsync(resourceGroupName, circuitName, peeringName, devicePath, cancellationToken).ConfigureAwait(false); return new ExpressRouteCircuitsListArpTableOperation(_clientDiagnostics, _pipeline, RestClient.CreateListArpTableRequest(resourceGroupName, circuitName, peeringName, devicePath).Request, originalResponse); } catch (Exception e) { scope.Failed(e); throw; } } /// <summary> Gets the currently advertised ARP table associated with the express route circuit in a resource group. </summary> /// <param name="resourceGroupName"> The name of the resource group. </param> /// <param name="circuitName"> The name of the express route circuit. </param> /// <param name="peeringName"> The name of the peering. </param> /// <param name="devicePath"> The path of the device. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> public virtual ExpressRouteCircuitsListArpTableOperation StartListArpTable(string resourceGroupName, string circuitName, string peeringName, string devicePath, CancellationToken cancellationToken = default) { if (resourceGroupName == null) { throw new ArgumentNullException(nameof(resourceGroupName)); } if (circuitName == null) { throw new ArgumentNullException(nameof(circuitName)); } if (peeringName == null) { throw new ArgumentNullException(nameof(peeringName)); } if (devicePath == null) { throw new ArgumentNullException(nameof(devicePath)); } using var scope = _clientDiagnostics.CreateScope("ExpressRouteCircuitsClient.StartListArpTable"); scope.Start(); try { var originalResponse = RestClient.ListArpTable(resourceGroupName, circuitName, peeringName, devicePath, cancellationToken); return new ExpressRouteCircuitsListArpTableOperation(_clientDiagnostics, _pipeline, RestClient.CreateListArpTableRequest(resourceGroupName, circuitName, peeringName, devicePath).Request, originalResponse); } catch (Exception e) { scope.Failed(e); throw; } } /// <summary> Gets the currently advertised routes table associated with the express route circuit in a resource group. </summary> /// <param name="resourceGroupName"> The name of the resource group. </param> /// <param name="circuitName"> The name of the express route circuit. </param> /// <param name="peeringName"> The name of the peering. </param> /// <param name="devicePath"> The path of the device. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> public virtual async Task<ExpressRouteCircuitsListRoutesTableOperation> StartListRoutesTableAsync(string resourceGroupName, string circuitName, string peeringName, string devicePath, CancellationToken cancellationToken = default) { if (resourceGroupName == null) { throw new ArgumentNullException(nameof(resourceGroupName)); } if (circuitName == null) { throw new ArgumentNullException(nameof(circuitName)); } if (peeringName == null) { throw new ArgumentNullException(nameof(peeringName)); } if (devicePath == null) { throw new ArgumentNullException(nameof(devicePath)); } using var scope = _clientDiagnostics.CreateScope("ExpressRouteCircuitsClient.StartListRoutesTable"); scope.Start(); try { var originalResponse = await RestClient.ListRoutesTableAsync(resourceGroupName, circuitName, peeringName, devicePath, cancellationToken).ConfigureAwait(false); return new ExpressRouteCircuitsListRoutesTableOperation(_clientDiagnostics, _pipeline, RestClient.CreateListRoutesTableRequest(resourceGroupName, circuitName, peeringName, devicePath).Request, originalResponse); } catch (Exception e) { scope.Failed(e); throw; } } /// <summary> Gets the currently advertised routes table associated with the express route circuit in a resource group. </summary> /// <param name="resourceGroupName"> The name of the resource group. </param> /// <param name="circuitName"> The name of the express route circuit. </param> /// <param name="peeringName"> The name of the peering. </param> /// <param name="devicePath"> The path of the device. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> public virtual ExpressRouteCircuitsListRoutesTableOperation StartListRoutesTable(string resourceGroupName, string circuitName, string peeringName, string devicePath, CancellationToken cancellationToken = default) { if (resourceGroupName == null) { throw new ArgumentNullException(nameof(resourceGroupName)); } if (circuitName == null) { throw new ArgumentNullException(nameof(circuitName)); } if (peeringName == null) { throw new ArgumentNullException(nameof(peeringName)); } if (devicePath == null) { throw new ArgumentNullException(nameof(devicePath)); } using var scope = _clientDiagnostics.CreateScope("ExpressRouteCircuitsClient.StartListRoutesTable"); scope.Start(); try { var originalResponse = RestClient.ListRoutesTable(resourceGroupName, circuitName, peeringName, devicePath, cancellationToken); return new ExpressRouteCircuitsListRoutesTableOperation(_clientDiagnostics, _pipeline, RestClient.CreateListRoutesTableRequest(resourceGroupName, circuitName, peeringName, devicePath).Request, originalResponse); } catch (Exception e) { scope.Failed(e); throw; } } /// <summary> Gets the currently advertised routes table summary associated with the express route circuit in a resource group. </summary> /// <param name="resourceGroupName"> The name of the resource group. </param> /// <param name="circuitName"> The name of the express route circuit. </param> /// <param name="peeringName"> The name of the peering. </param> /// <param name="devicePath"> The path of the device. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> public virtual async Task<ExpressRouteCircuitsListRoutesTableSummaryOperation> StartListRoutesTableSummaryAsync(string resourceGroupName, string circuitName, string peeringName, string devicePath, CancellationToken cancellationToken = default) { if (resourceGroupName == null) { throw new ArgumentNullException(nameof(resourceGroupName)); } if (circuitName == null) { throw new ArgumentNullException(nameof(circuitName)); } if (peeringName == null) { throw new ArgumentNullException(nameof(peeringName)); } if (devicePath == null) { throw new ArgumentNullException(nameof(devicePath)); } using var scope = _clientDiagnostics.CreateScope("ExpressRouteCircuitsClient.StartListRoutesTableSummary"); scope.Start(); try { var originalResponse = await RestClient.ListRoutesTableSummaryAsync(resourceGroupName, circuitName, peeringName, devicePath, cancellationToken).ConfigureAwait(false); return new ExpressRouteCircuitsListRoutesTableSummaryOperation(_clientDiagnostics, _pipeline, RestClient.CreateListRoutesTableSummaryRequest(resourceGroupName, circuitName, peeringName, devicePath).Request, originalResponse); } catch (Exception e) { scope.Failed(e); throw; } } /// <summary> Gets the currently advertised routes table summary associated with the express route circuit in a resource group. </summary> /// <param name="resourceGroupName"> The name of the resource group. </param> /// <param name="circuitName"> The name of the express route circuit. </param> /// <param name="peeringName"> The name of the peering. </param> /// <param name="devicePath"> The path of the device. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> public virtual ExpressRouteCircuitsListRoutesTableSummaryOperation StartListRoutesTableSummary(string resourceGroupName, string circuitName, string peeringName, string devicePath, CancellationToken cancellationToken = default) { if (resourceGroupName == null) { throw new ArgumentNullException(nameof(resourceGroupName)); } if (circuitName == null) { throw new ArgumentNullException(nameof(circuitName)); } if (peeringName == null) { throw new ArgumentNullException(nameof(peeringName)); } if (devicePath == null) { throw new ArgumentNullException(nameof(devicePath)); } using var scope = _clientDiagnostics.CreateScope("ExpressRouteCircuitsClient.StartListRoutesTableSummary"); scope.Start(); try { var originalResponse = RestClient.ListRoutesTableSummary(resourceGroupName, circuitName, peeringName, devicePath, cancellationToken); return new ExpressRouteCircuitsListRoutesTableSummaryOperation(_clientDiagnostics, _pipeline, RestClient.CreateListRoutesTableSummaryRequest(resourceGroupName, circuitName, peeringName, devicePath).Request, originalResponse); } catch (Exception e) { scope.Failed(e); throw; } } } }
49.850767
251
0.613211
8b1baff4913f7d79fe18e038b4d446be54c67ac0
5,255
rb
Ruby
spec/features/instructor_role_spec.rb
patmbolger/WikiEduDashboard
1cdcb0204f3fb48c031c2255284b88b1bddc621f
[ "MIT" ]
1
2019-05-24T14:04:36.000Z
2019-05-24T14:04:36.000Z
spec/features/instructor_role_spec.rb
enterstudio/WikiEduDashboard
1cdcb0204f3fb48c031c2255284b88b1bddc621f
[ "MIT" ]
null
null
null
spec/features/instructor_role_spec.rb
enterstudio/WikiEduDashboard
1cdcb0204f3fb48c031c2255284b88b1bddc621f
[ "MIT" ]
1
2017-02-24T05:20:14.000Z
2017-02-24T05:20:14.000Z
# frozen_string_literal: true require 'rails_helper' describe 'Instructor users', type: :feature, js: true do before do include Devise::TestHelpers, type: :feature Capybara.current_driver = :selenium page.current_window.resize_to(1920, 1080) end before :each do instructor = create(:user, id: 100, username: 'Professor Sage', wiki_token: 'foo', wiki_secret: 'bar') create(:user, id: 101, username: 'Student A') create(:user, id: 102, username: 'Student B') create(:course, id: 10001, title: 'My Active Course', school: 'University', term: 'Term', slug: 'University/Course_(Term)', submitted: true, passcode: 'passcode', start: '2015-01-01'.to_date, end: '2020-01-01'.to_date, user_count: 2, trained_count: 0) create(:courses_user, id: 1, user_id: 100, course_id: 10001, role: 1) create(:courses_user, id: 2, user_id: 101, course_id: 10001, role: 0) create(:courses_user, id: 3, user_id: 102, course_id: 10001, role: 0) create(:campaign, id: 1, title: 'Fall 2015') create(:campaigns_course, campaign_id: 1, course_id: 10001) login_as(instructor, scope: :user) stub_oauth_edit stub_raw_action stub_info_query end describe 'visiting the students page' do let(:week) { create(:week, course_id: Course.first.id) } let(:tm) { TrainingModule.all.first } let!(:block) do create(:block, week_id: week.id, training_module_ids: [tm.id], due_date: Date.today) end before do TrainingModulesUsers.destroy_all Timecop.travel(1.year.from_now) end after do Timecop.return end it 'should be able to add students' do allow_any_instance_of(WikiApi).to receive(:get_user_id).and_return(123) visit "/courses/#{Course.first.slug}/students" sleep 1 click_button 'Enrollment' within('#users') { all('input')[1].set('Risker') } click_button 'Enroll' click_button 'OK' expect(page).to have_content 'Risker was added successfully' end it 'should not be able to add nonexistent users as students' do allow_any_instance_of(WikiApi).to receive(:get_user_id).and_return(nil) visit "/courses/#{Course.first.slug}/students" sleep 1 click_button 'Enrollment' within('#users') { all('input')[1].set('NotARealUser') } click_button 'Enroll' click_button 'OK' expect(page).to have_content 'NotARealUser is not an existing user.' end it 'should be able to remove students' do visit "/courses/#{Course.first.slug}/students" sleep 1 # Click the Enrollment button click_button 'Enrollment' sleep 1 # Remove a user page.all('button.border.plus')[1].click click_button 'OK' sleep 1 visit "/courses/#{Course.first.slug}/students" expect(page).to have_content 'Student A' expect(page).not_to have_content 'Student B' end it 'should be able to assign articles' do visit "/courses/#{Course.first.slug}/students" sleep 1 # Assign an article click_button 'Assign Articles' sleep 1 page.all('button.border')[0].click within('#users') { first('input').set('Article 1') } click_button 'Assign' click_button 'OK' sleep 1 page.first('button.border.assign-button').click sleep 1 # Assign a review page.all('button.border')[1].click within('#users') { first('input').set('Article 2') } click_button 'Assign' click_button 'OK' sleep 1 page.all('button.border.assign-button')[0].click sleep 1 # Leave editing mode within 'div.controls' do click_button 'Done' end expect(page).to have_content 'Article 1' expect(page).to have_content 'Article 2' # Delete an assignments visit "/courses/#{Course.first.slug}/students" click_button 'Assign Articles' page.first('button.border.assign-button').click page.accept_confirm do click_button '-' end sleep 1 within 'div.controls' do click_button 'Done' end expect(page).not_to have_content 'Article 1' end it 'should be able to remove students from the course' do visit "/courses/#{Course.first.slug}/students" click_button 'Enrollment' page.first('button.border.plus').click click_button 'OK' sleep 1 expect(page).not_to have_content 'Student A' end it 'should be able to notify users with overdue training' do visit "/courses/#{Course.first.slug}/students" sleep 1 # Notify users with overdue training page.accept_confirm do page.first('button.notify_overdue').click end sleep 1 end end after do logout Capybara.use_default_driver end end
27.227979
90
0.597146
da4c4589da5c8d929f0185bff17eb76ba4fb276a
902
php
PHP
views/medical-income/view.php
Charlieevox/hris
bfc00b0dcbb49d3d0f73fc81cc2f0b6d3def6c73
[ "BSD-3-Clause" ]
null
null
null
views/medical-income/view.php
Charlieevox/hris
bfc00b0dcbb49d3d0f73fc81cc2f0b6d3def6c73
[ "BSD-3-Clause" ]
null
null
null
views/medical-income/view.php
Charlieevox/hris
bfc00b0dcbb49d3d0f73fc81cc2f0b6d3def6c73
[ "BSD-3-Clause" ]
null
null
null
<?php use yii\helpers\Html; use yii\widgets\DetailView; /* @var $this yii\web\View */ /* @var $model app\models\MsPersonnelHead */ $this->title = 'View Medical Income: ' . ' ' . $model->id; $this->params['breadcrumbs'][] = ['label' => 'Proposal', 'url' => ['index']]; $this->params['breadcrumbs'][] = 'View ' . $model->id; ?> <div class="proposal-view"> <?= $this->render('_form', ['model' => $model, 'personnelModel' => $personnelModel,]) ?> </div> <?php $js = <<< SCRIPT $(document).ready(function(){ $(":input").attr("disabled","disabled"); // $(".btn").attr("disabled","disabled"); $(".text-center").hide(); $(".td-input").hide(); $(".btn").attr("disabled","disabled"); $(".kv-date-calendar" ).hide(); $(".btn btn-primary" ).hide(); $("#submitBtn" ).hide(); }); SCRIPT; $this->registerJs($js);
27.333333
77
0.52439
da28718e3ae4f468fbc4c656d88da485273129ba
1,233
php
PHP
app/HPCFront/Repositories/ProjectRepository.php
jairoserrano/HPCFront
a69753d15c97678e305bb80f547324aa42a88c8b
[ "MIT" ]
1
2015-08-16T04:50:09.000Z
2015-08-16T04:50:09.000Z
app/HPCFront/Repositories/ProjectRepository.php
jairoserrano/HPCFront
a69753d15c97678e305bb80f547324aa42a88c8b
[ "MIT" ]
null
null
null
app/HPCFront/Repositories/ProjectRepository.php
jairoserrano/HPCFront
a69753d15c97678e305bb80f547324aa42a88c8b
[ "MIT" ]
null
null
null
<?php namespace HPCFront\Repositories; use HPCFront\Entities\Project; class ProjectRepository extends BaseRepository { public function getEntity() { return new Project(); } public function findWithAllJobsInformation($id) { return $this->entity->with( array( 'jobs' => function($query){ $query->orderBy('created_at', 'ASC'); }, 'jobs.entries', ) )->where('id', '=', $id)->first(); } public function getAllUserProjects($id){ return $this->entity ->where('user_owner', '=', $id) ->orderBy('created_at', 'DESC') ->get(); } public function getLastProject(){ return ($this->entity->count() > 0) ? $this->entity->orderBy('id', 'DESC')->first() : 0 ; } public function getUserProjects($user_id){ return $this->entity ->with( array( 'projects' => function($query) use ($user_id){ $query->where('user_owner', '=', $user_id); }, 'projects.jobs' ) ) ->get(); } }
25.6875
97
0.468775
93f3144243882fca5d8c28d812be9e429756c5c5
7,928
cs
C#
DSCMS/DSCMS/Views/Maintenance/SupportingDocumentDownload.aspx.designer.cs
Ruke45/DManagement
5b26150c2912efd6ff557e4766147457f24210a8
[ "Apache-2.0" ]
null
null
null
DSCMS/DSCMS/Views/Maintenance/SupportingDocumentDownload.aspx.designer.cs
Ruke45/DManagement
5b26150c2912efd6ff557e4766147457f24210a8
[ "Apache-2.0" ]
null
null
null
DSCMS/DSCMS/Views/Maintenance/SupportingDocumentDownload.aspx.designer.cs
Ruke45/DManagement
5b26150c2912efd6ff557e4766147457f24210a8
[ "Apache-2.0" ]
null
null
null
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace DSCMS.Views.Maintenance { public partial class SupportingDocumentDownload { /// <summary> /// diviframe control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.HtmlControls.HtmlGenericControl diviframe; /// <summary> /// Btnsd control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.Button Btnsd; /// <summary> /// txtFromDate control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.TextBox txtFromDate; /// <summary> /// Calendar2 control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.Calendar Calendar2; /// <summary> /// RvFromDate control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.RequiredFieldValidator RvFromDate; /// <summary> /// labstartdatevalidation control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.Label labstartdatevalidation; /// <summary> /// txtTodate control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.TextBox txtTodate; /// <summary> /// Calendar3 control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.Calendar Calendar3; /// <summary> /// RequiredFieldValidator2 control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.RequiredFieldValidator RequiredFieldValidator2; /// <summary> /// labdatevalidation control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.Label labdatevalidation; /// <summary> /// txtCertificateNo control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.TextBox txtCertificateNo; /// <summary> /// lblcusid control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.HtmlControls.HtmlGenericControl lblcusid; /// <summary> /// divhid control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.HtmlControls.HtmlGenericControl divhid; /// <summary> /// ddUserID control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.DropDownList ddUserID; /// <summary> /// Button4 control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.Button Button4; /// <summary> /// Label1 control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.Label Label1; /// <summary> /// CheckB1 control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.CheckBox CheckB1; /// <summary> /// Button6 control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.Button Button6; /// <summary> /// Button5 control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.Button Button5; /// <summary> /// Button1 control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.Button Button1; /// <summary> /// Button2 control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.Button Button2; /// <summary> /// Button3 control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.Button Button3; /// <summary> /// GridView1 control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.GridView GridView1; } }
35.55157
99
0.546039
cd1ad3ba47815fda7d09926698bd149ef496482e
458
cs
C#
projects/RyLogViewer2/src/Interfaces/ILicencedFeature.cs
psryland/rylogic_code
f79e471fe0d6714c5e0cf8385ddc2a88ab2e082b
[ "CNRI-Python" ]
2
2020-11-11T16:19:04.000Z
2021-01-19T01:53:29.000Z
projects/RyLogViewer2/src/Interfaces/ILicencedFeature.cs
psryland/rylogic_code
f79e471fe0d6714c5e0cf8385ddc2a88ab2e082b
[ "CNRI-Python" ]
1
2020-07-27T09:00:21.000Z
2020-07-27T10:58:10.000Z
projects/RyLogViewer2/src/Interfaces/ILicencedFeature.cs
psryland/rylogic_code
f79e471fe0d6714c5e0cf8385ddc2a88ab2e082b
[ "CNRI-Python" ]
1
2021-04-04T01:39:55.000Z
2021-04-04T01:39:55.000Z
namespace RyLogViewer { /// <summary>Interface for controlling time limited features</summary> public interface ILicensedFeature { /// <summary>An html description of the licensed feature</summary> string FeatureDescription { get; } /// <summary>True if the licensed feature is still currently in use</summary> bool FeatureInUse { get; } /// <summary>Called to stop the use of the feature</summary> void CloseFeature(); } }
28.625
80
0.70524
7ad3c4aba6e618a79ec9988e0aaab1974f9c788d
2,101
cs
C#
src/libraries/System.Reflection.Metadata/src/System/Reflection/Internal/Utilities/BitArithmetic.cs
jtschuster/runtime
edd359716c2096274e656d26ed8945d99afc2da5
[ "MIT" ]
null
null
null
src/libraries/System.Reflection.Metadata/src/System/Reflection/Internal/Utilities/BitArithmetic.cs
jtschuster/runtime
edd359716c2096274e656d26ed8945d99afc2da5
[ "MIT" ]
1
2021-11-19T10:42:54.000Z
2021-11-19T10:42:54.000Z
src/libraries/System.Reflection.Metadata/src/System/Reflection/Internal/Utilities/BitArithmetic.cs
jtschuster/runtime
edd359716c2096274e656d26ed8945d99afc2da5
[ "MIT" ]
null
null
null
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Diagnostics; #if NETCOREAPP using System.Numerics; #endif namespace System.Reflection.Internal { internal static class BitArithmetic { internal static int CountBits(int v) { return CountBits(unchecked((uint)v)); } internal static int CountBits(uint v) { #if NETCOREAPP return BitOperations.PopCount(v); #else unchecked { v -= ((v >> 1) & 0x55555555u); v = (v & 0x33333333u) + ((v >> 2) & 0x33333333u); return (int)((v + (v >> 4) & 0xF0F0F0Fu) * 0x1010101u) >> 24; } #endif } internal static int CountBits(ulong v) { #if NETCOREAPP return BitOperations.PopCount(v); #else const ulong Mask01010101 = 0x5555555555555555UL; const ulong Mask00110011 = 0x3333333333333333UL; const ulong Mask00001111 = 0x0F0F0F0F0F0F0F0FUL; const ulong Mask00000001 = 0x0101010101010101UL; v -= ((v >> 1) & Mask01010101); v = (v & Mask00110011) + ((v >> 2) & Mask00110011); return (int)(unchecked(((v + (v >> 4)) & Mask00001111) * Mask00000001) >> 56); #endif } internal static uint Align(uint position, uint alignment) { Debug.Assert(CountBits(alignment) == 1); uint result = position & ~(alignment - 1); if (result == position) { return result; } return result + alignment; } internal static int Align(int position, int alignment) { Debug.Assert(position >= 0 && alignment > 0); Debug.Assert(CountBits(alignment) == 1); int result = position & ~(alignment - 1); if (result == position) { return result; } return result + alignment; } } }
28.013333
90
0.535459
d8fd7c008e696ed8499e337288efe7abfc95c40a
1,182
rb
Ruby
benchmarks/subset.rb
janosch-x/immutable_set
8224cc7664d8c96b7b55a2e3d97413af7b980876
[ "MIT" ]
1
2018-06-27T00:13:16.000Z
2018-06-27T00:13:16.000Z
benchmarks/subset.rb
janosch-x/immutable_set
8224cc7664d8c96b7b55a2e3d97413af7b980876
[ "MIT" ]
null
null
null
benchmarks/subset.rb
janosch-x/immutable_set
8224cc7664d8c96b7b55a2e3d97413af7b980876
[ "MIT" ]
null
null
null
require_relative './shared' # distinct case is extremely fast both w. gem and stdlib # (except on Ruby < 2.3, where the gem is much faster) benchmark( method: :subset?, caption: '#(proper_)subset/superset? with 5M subset items', cases: { 'stdlib' => [S.new(1..4_900_000), S.new(1..5_000_000)], 'gem' => [I.new(1..4_900_000), I.new(1..5_000_000)], 'gem w/o C' => [P.new(1..4_900_000), P.new(1..5_000_000)], } ) benchmark( method: :subset?, caption: '#(proper_)subset/superset? with 5M overlapping items', cases: { 'stdlib' => [S.new(1..4_900_000), S.new((1..4_900_001).to_a - [4_800_000])], 'gem' => [I.new(1..4_900_000), I.from_ranges(1..4_799_999, 4_800_001..4_900_001)], 'gem w/o C' => [P.new(1..4_900_000), P.from_ranges(1..4_799_999, 4_800_001..4_900_001)], } ) benchmark( method: :subset?, caption: '#(proper_)subset/superset? with 100k overlapping items', cases: { 'stdlib' => [S.new(1..99_000), S.new((1..99_001).to_a - [90_000])], 'gem' => [I.new(1..99_000), I.from_ranges(1..89_999, 90_001..99_001)], 'gem w/o C' => [P.new(1..99_000), P.from_ranges(1..89_999, 90_001..99_001)], } )
33.771429
92
0.610829
e26e004f2593fd14175e8738ec972a524e280576
576
py
Python
setup.py
JanSiebert/async-telegram-bot-python
e87a1c7cce0f2e22ec757b03d10d4a394d592bf6
[ "MIT" ]
2
2017-06-02T11:24:26.000Z
2019-07-09T11:30:18.000Z
setup.py
JanSiebert/async-telegram-bot-python
e87a1c7cce0f2e22ec757b03d10d4a394d592bf6
[ "MIT" ]
null
null
null
setup.py
JanSiebert/async-telegram-bot-python
e87a1c7cce0f2e22ec757b03d10d4a394d592bf6
[ "MIT" ]
3
2017-06-02T11:24:32.000Z
2021-12-20T22:08:24.000Z
from distutils.core import setup def readme(): with open('README.rst') as f: return f.read() setup( name = 'AsyncTelegramBot', packages = ['AsyncTelegramBot'], version = '0.2', description = 'Wrapper for Telegram`s Bot API utilizing asyncio', author = 'Jan Siebert', author_email = '[email protected]', url = 'https://github.com/JanSiebert/async-telegram-bot-python', download_url = 'https://github.com/JanSiebert/async-telegram-bot-python/tarball/0.1', keywords = ['testing', 'async', 'bot', 'api', 'telegram', 'wrapper'], classifiers = [], )
30.315789
87
0.671875
4d0ad218764bb1f56b56125233a30cdbf66646c5
186
cs
C#
BlazorUtils.WebTest.0.5/Models/WebsiteInfo.cs
LMT-Team/Blazor-Utils
a2e4439caca3285a4406af629a355b79531341ed
[ "MIT" ]
3
2022-01-07T08:44:45.000Z
2022-01-07T08:45:05.000Z
BlazorUtils.WebTest.0.5/Models/WebsiteInfo.cs
15110123/Blazor-Utils
a2e4439caca3285a4406af629a355b79531341ed
[ "MIT" ]
1
2019-03-07T02:16:56.000Z
2019-07-07T09:27:35.000Z
BlazorUtils.WebTest.0.5/Models/WebsiteInfo.cs
15110123/Blazor-Utils
a2e4439caca3285a4406af629a355b79531341ed
[ "MIT" ]
null
null
null
namespace BlazorUtils.WebTest._0._5.Models { public class WebsiteInfo { public string websiteName { get; set; } public string[] developers { get; set; } } }
20.666667
48
0.623656
f48ba80c68349c38c5de6a9dfd1edb01c894f1b8
6,321
ts
TypeScript
src/__test__/lifecycle.test.ts
AEPKILL/husky-di
5f5de4ba7e146e3cb2bdd3ed66b70d515a159d48
[ "MIT" ]
null
null
null
src/__test__/lifecycle.test.ts
AEPKILL/husky-di
5f5de4ba7e146e3cb2bdd3ed66b70d515a159d48
[ "MIT" ]
null
null
null
src/__test__/lifecycle.test.ts
AEPKILL/husky-di
5f5de4ba7e146e3cb2bdd3ed66b70d515a159d48
[ "MIT" ]
null
null
null
/** * @overview * @author AEPKILL * @created 2021-10-11 13:45:53 */ import { ClassProvider, createContainer, FactoryProvider, inject, LifecycleEnum, Ref, ServiceIdentifierManager, } from '..'; describe('lifecycle test', () => { const serviceIdentifierManager = new ServiceIdentifierManager(); const ITest = serviceIdentifierManager.createServiceIdentifier<Test>('test'); class Test { constructor( @inject('factory') readonly a: number, @inject('factory') readonly b: number, @inject('factory') readonly c: number, @inject('factory', { ref: true }) readonly d: Ref<number> ) {} } test('transient lifecycle', () => { const container = createContainer('Transient'); let count = 0; container.register( 'test', new ClassProvider({ useClass: Test, }) ); container.register( 'factory', new FactoryProvider({ useFactory() { return count++; }, }) ); const test = container.resolve(ITest); expect(test.a).toBe(0); expect(test.b).toBe(1); expect(test.c).toBe(2); expect(test.d.current).toBe(3); expect(test.d.current).toBe(3); }); test('singleton lifecycle', () => { const container = createContainer('Singleton'); let count = 0; container.register( 'test', new ClassProvider({ useClass: Test, }) ); container.register( 'factory', new FactoryProvider({ lifecycle: LifecycleEnum.singleton, useFactory() { return count++; }, }) ); const test = container.resolve(ITest); expect(test.a).toBe(0); expect(test.b).toBe(0); expect(test.c).toBe(0); expect(container.resolve('factory')).toBe(0); }); test('resolutionScoped lifecycle', () => { const container = createContainer('ResolutionScoped'); let count = 0; container.register( 'test', new ClassProvider({ useClass: Test, }) ); container.register( 'factory', new FactoryProvider({ lifecycle: LifecycleEnum.resolutionScoped, useFactory() { return count++; }, }) ); const test = container.resolve(ITest); expect(test.a).toBe(0); expect(test.b).toBe(0); expect(test.c).toBe(0); expect(container.resolve('factory')).toBe(1); expect(test.d.current).toBe(0); }); test('resolutionScoped for factory', () => { const IA = serviceIdentifierManager.createServiceIdentifier<number>('IA'); const IB = serviceIdentifierManager.createServiceIdentifier<number>('IB'); let count = 0; const container = createContainer('FactoryResolutionScoped', container => { container.register( IA, new FactoryProvider({ lifecycle: LifecycleEnum.resolutionScoped, useFactory() { return count++; }, }) ); container.register( IB, new FactoryProvider({ useFactory(container) { return container.resolve(IA) + container.resolve(IA); }, }) ); }); expect(container.resolve(IB)).toBe(0); }); test('resolutionScoped ref for class', () => { class A { constructor( @inject('b') readonly b: B, @inject('c', { ref: true }) readonly c: Ref<C> ) {} } class B {} class C { constructor(@inject('b') readonly b: B) {} } const container = createContainer('ResolutionScopedRefForClass'); container.register( 'a', new ClassProvider({ lifecycle: LifecycleEnum.resolutionScoped, useClass: A, }) ); container.register( 'b', new ClassProvider({ lifecycle: LifecycleEnum.resolutionScoped, useClass: B, }) ); container.register( 'c', new ClassProvider({ lifecycle: LifecycleEnum.resolutionScoped, useClass: C, }) ); const IA = serviceIdentifierManager.createServiceIdentifier<A>('a'); const a = container.resolve(IA); expect(a.b).toBe(a.c.current.b); }); test('resolutionScoped ref for class with multiple', () => { const serviceIdentifierManager = new ServiceIdentifierManager(); const IA = serviceIdentifierManager.createServiceIdentifier<A>('IA'); const IB = serviceIdentifierManager.createServiceIdentifier<B>('IB'); class A { constructor( @inject(IB) readonly b: B, @inject(IB, { ref: true }) readonly b2: Ref<B>, @inject(IB, { multiple: true }) readonly b3: B[], @inject(IB) readonly b4: B ) {} } class B { constructor() {} } const container = createContainer( 'ResolutionScopedMultipleRefForClass', container => { container.register( IA, new ClassProvider({ useClass: A, }) ); container.register( IB, new ClassProvider({ lifecycle: LifecycleEnum.resolutionScoped, useClass: B, }) ); } ); const a = container.resolve(IA); expect(a.b).not.toBe(a.b2); expect(a.b).not.toBe(a.b3); expect(a.b).toBe(a.b4); expect(a.b).toBe(a.b2.current); expect(a.b).toBe(a.b3[0]); }); test('resolutionScoped ref for class with multiple', () => { const serviceIdentifierManager = new ServiceIdentifierManager(); const IA = serviceIdentifierManager.createServiceIdentifier<A>('IA333333'); const IB = serviceIdentifierManager.createServiceIdentifier<B>('IB333333'); class A { constructor( @inject(IB, { multiple: true }) readonly b: B[], @inject(IB) readonly b2: B ) {} } class B { constructor() {} } const container = createContainer( 'ResolutionScopedMultipleRefForClass2', container => { container.register( IA, new ClassProvider({ useClass: A, }) ); container.register( IB, new ClassProvider({ lifecycle: LifecycleEnum.resolutionScoped, useClass: B, }) ); } ); const a = container.resolve(IA); expect(a.b[0]).toBe(a.b2); }); });
23.585821
79
0.570479
a19050c1bc0c29422dd09d32c372d9472c98ed13
2,274
hpp
C++
src/atria/funken/state.hpp
superdev999/atria
caf48a7aa7ddda1c4df9ee047a68dfda4d3b9fba
[ "MIT" ]
257
2015-09-23T22:02:46.000Z
2021-12-13T16:57:06.000Z
src/atria/funken/state.hpp
superdev999/atria
caf48a7aa7ddda1c4df9ee047a68dfda4d3b9fba
[ "MIT" ]
13
2016-01-03T02:13:24.000Z
2019-05-13T07:47:55.000Z
src/atria/funken/state.hpp
superdev999/atria
caf48a7aa7ddda1c4df9ee047a68dfda4d3b9fba
[ "MIT" ]
31
2015-10-07T11:18:12.000Z
2021-09-17T20:33:06.000Z
// // Copyright (C) 2014, 2015 Ableton AG, Berlin. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the "Software"), // to deal in the Software without restriction, including without limitation // the rights to use, copy, modify, merge, publish, distribute, sublicense, // and/or sell copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL // THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // /*! * @file */ #pragma once #include <atria/funken/detail/root_signals.hpp> #include <atria/funken/detail/access.hpp> #include <atria/funken/detail/watchable.hpp> namespace atria { namespace funken { template <typename T> class state : private detail::watchable<T> { using signal_ptr_t = decltype( detail::make_state_signal(std::declval<T>())); public: using value_type = T; state() : signal_(detail::make_state_signal(T())) {} state(T value) : signal_(detail::make_state_signal(std::move(value))) {} state(const state&) = delete; state(state&&) = default; state& operator=(const state&) = delete; state& operator=(state&&) = default; template <typename T2> void set(T2&& value) { signal_->push_down(std::forward<T2>(value)); } const T& get() const { return signal_->last(); } private: const signal_ptr_t& signal() { return signal_; } const signal_ptr_t& roots() { return signal_; } friend class detail::access; signal_ptr_t signal_; }; template <typename T> state<T> make_state(T value) { return value; } } // namespace funken } // namespace atria
28.074074
77
0.718558
b8bd7dc97d76d1b994b659c1fd2e82e559f9de70
2,555
h
C
stabla.h
stefancertic/SS7Client
5f76adcb07bc2f67d70a761704b295b79de38e54
[ "MIT" ]
20
2017-01-03T20:24:30.000Z
2021-11-08T20:17:10.000Z
stabla.h
stefancertic/SS7Client
5f76adcb07bc2f67d70a761704b295b79de38e54
[ "MIT" ]
null
null
null
stabla.h
stefancertic/SS7Client
5f76adcb07bc2f67d70a761704b295b79de38e54
[ "MIT" ]
8
2017-01-03T20:24:33.000Z
2020-05-06T09:50:15.000Z
#ifndef _STABLA_H_ #define _STABLA_H_ 0 #define BACKLOG 5 #define BUFFER_SIZE 8000 #define MAX_DESCRIPTOR 20 char niz_parametara[10][30]; /* struktura koja sadrzi informacije o cvoru */ typedef struct Cvor{ char prva[20]; char druga[50]; char treca[500]; char cetvrta[500]; struct Cvor* levo; struct Cvor* desno; }cvor; typedef struct CvorH{ char id[25]; char imsi[16]; char msc[20]; char dest[30]; char pdu[500]; int poslato; int br_paketa; int min; struct tm* vreme; struct CvorH* levo; struct CvorH* desno; }cvorH; /* struktura cvor sadrzi buffer i pokazivac na sledeci cvor */ typedef struct cvor_liste{ unsigned char buffer[1000]; struct cvor_liste* sledeci_cvor; int velicinapaketa; }Cvor_liste; cvor* kreiraj_cvor(char* prva, char *druga, char* treca, char* cetvrta); cvor* dodaj_cvor(cvor* stablo, char* prva,char* druga,char* treca, char* cetvrta); cvor* pronadji_cvor(cvor* stablo, char* prva, char* druga); cvor* pronadji_cvor_po_vrednosti(cvor* stablo, char* vrednost); void oslobodi_memoriju(cvor* stablo); void ispisi_stablo(cvor* stablo); void error_fatal (char *format, ...); int hctoi(const char h); void funkcija_konverzija (int c, char *br,int sirina); int konverzija_u_dekadno(char* broj); int koliko_ima_parametara (char* parametri); int indeks_karaktera(char* parametri, char c, int poc_poz); void rasparcaj (char* parametri); void izvuci_parametre(cvor* stablo,char* ime_paketa,char* parametri); void obradi_broj (char *broj); int indeks_a0(unsigned char* buffer, int count); cvorH* dodajIDuHash(cvorH* pocetak, char* id, char* imsi, char* msc, char* dest, char* pdu); cvorH* kreiraj_cvorHM(char* id, char* imsi, char* msc, char* dest, char* pdu); void oslobodi_memorijuHM(cvorH* stablo); void ispisiHM(cvorH* stablo); cvorH* min_cvor(cvorH* koren); cvorH* nadji_cvor_za_hlr (cvorH* pocetak); cvorH* nadji_cvor_za_forwardSM (cvorH* pocetak); Cvor_liste* napravi_cvor_liste(unsigned char* paket, int velicina); void dodaj_u_red(Cvor_liste** pocetak_reda, Cvor_liste** kraj_reda,unsigned char* paket, int velicina); int uzmi_iz_reda(Cvor_liste** pocetak_reda, Cvor_liste** kraj_reda,unsigned char* paket); int procitaj_prvi_u_redu (Cvor_liste** pocetak_reda, Cvor_liste** kraj_reda,unsigned char* paket); void ispisi_red(Cvor_liste* pocetak_reda); void oslobodi_red(Cvor_liste** pocetak_reda, Cvor_liste** kraj_reda); cvorH* nadji_poslato_za_insert(cvorH* pocetak); cvorH* nadji_cvor_br_paketa(cvorH* pocetakHM, int pot_id); int br_elemenata_uHM (cvorH* pocetak); void obradi_imsi (char *broj); #endif
31.9375
103
0.765166
c9fb14e861b3b95ce92b4e16e55ab5f499c202f9
243
ts
TypeScript
lib/form/admin/google.ts
ex-trap/crowi
59fc7d76ec74db65a629162570e994887e5b0c7e
[ "MIT" ]
1,136
2015-01-07T12:02:32.000Z
2022-02-21T14:23:53.000Z
lib/form/admin/google.ts
ex-trap/crowi
59fc7d76ec74db65a629162570e994887e5b0c7e
[ "MIT" ]
537
2015-03-13T01:08:02.000Z
2022-03-17T20:34:30.000Z
lib/form/admin/google.ts
inductor/crowi
74e86691eddb3c5a9adb12abd1cc6b7a724edd7d
[ "MIT" ]
273
2015-02-24T08:49:59.000Z
2022-02-24T05:31:44.000Z
import form from 'express-form' const { field } = form export default form( field('settingForm[google:clientId]') .trim() .is(/^[\d.a-z\-.]+$/), field('settingForm[google:clientSecret]') .trim() .is(/^[\da-zA-Z\-_]+$/), )
20.25
43
0.580247