hexsha stringlengths 40 40 | size int64 5 1.05M | ext stringclasses 98
values | lang stringclasses 21
values | max_stars_repo_path stringlengths 3 945 | max_stars_repo_name stringlengths 4 118 | max_stars_repo_head_hexsha stringlengths 40 78 | max_stars_repo_licenses listlengths 1 10 | max_stars_count int64 1 368k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 3 945 | max_issues_repo_name stringlengths 4 118 | max_issues_repo_head_hexsha stringlengths 40 78 | max_issues_repo_licenses listlengths 1 10 | max_issues_count int64 1 134k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 3 945 | max_forks_repo_name stringlengths 4 135 | max_forks_repo_head_hexsha stringlengths 40 78 | max_forks_repo_licenses listlengths 1 10 | max_forks_count int64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 5 1.05M | avg_line_length float64 1 1.03M | max_line_length int64 2 1.03M | alphanum_fraction float64 0 1 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
afe65a6bf168cc2e5149d4dd63f11853fcc45cc4 | 6,736 | html | HTML | tutorials/en/foundation/7.1/notifications/push-notifications-overview/push-notifications-native-ios-applications/interactive-and-silent-notifications-in-native-ios-applications.html | MobileFirst-Platform-Developer-Center/DevCenter | ac2351ef8878ff5101f0041323b68f3418b059e6 | [
"Apache-2.0"
] | 17 | 2016-07-07T07:24:22.000Z | 2022-01-21T07:19:10.000Z | tutorials/en/foundation/7.1/notifications/push-notifications-overview/push-notifications-native-ios-applications/interactive-and-silent-notifications-in-native-ios-applications.html | Acidburn0zzz/DevCenter-1 | ac2351ef8878ff5101f0041323b68f3418b059e6 | [
"Apache-2.0"
] | 49 | 2016-04-01T07:13:23.000Z | 2022-03-08T11:28:04.000Z | tutorials/en/foundation/7.1/notifications/push-notifications-overview/push-notifications-native-ios-applications/interactive-and-silent-notifications-in-native-ios-applications.html | Acidburn0zzz/DevCenter-1 | ac2351ef8878ff5101f0041323b68f3418b059e6 | [
"Apache-2.0"
] | 36 | 2016-07-07T07:24:27.000Z | 2022-01-05T13:40:34.000Z | ---
layout: tutorial
title: Interactive and Silent Notifications in Native iOS Applications
relevantTo: [ios]
---
<br>
<strong>Prerequisite:</strong> Make sure that you read the <a href="../">Push notifications in native iOS applications</a> tutorial first.</p>
<h2>Silent Notifications</h2>
<p>iOS 7 and above.</p>
<p>Silent notifications is a feature allowing to send notifications without disturbing the user. Notifications are not shown in the notification center or notification bar.<br />
Callback methods are executed even when the application is running in the background.</p>
<blockquote><p>For more information, refer to the "silent notifications" topics in the MobileFirst Platform user documentation, and in Apple's user documentation.</p></blockquote>
<h4>Server API for silent notification</h4>
<p>To send silent notification, set a string to indicate the type. Create a notification object by using the <code>WL.Server.createDefaultNotification</code> API and set the type as below:<br />
{% highlight objc %}notification.APNS.type = "DEFAULT" | "SILENT" | "MIXED"; {% endhighlight %}</p>
<ul>
<li><code>DEFAULT</code> means normal notification, which shows the alert and is kept in the notification center if the application is running in the background.</li>
<li><code>SILENT</code> means silent notification, which does not show any alert or the message is not placed in the notification center. In the silent type, the aps tag of push notification contains only content-available.</li>
<li><code>MIXED</code> means a combination of the above: This option invokes the callback method silently and shows the alert.</li>
</ul>
<h4>Client-side API for silent notification</h4>
<p>To handle silent notification on the client-side:</p>
<ul>
<li>Enable the application capability to perform background tasks on receiving the remote notifications<br />
To enable background processing, select the project in XCode and in the capabilities tab, select the appropriate background modes, like Remote notifications and Background fetch.
</li>
<li>Implement a new callback method in the <code>AppDelegate</code> <code>(application: didReceiveRemoteNotification:fetchCompletionHandler:)</code> to receive silent notifications when the application is running in the background.</li>
<li>In the callback, check whether the notification is silent by checking that the key content-available is set to 1.</li>
<li>Call the <code>fetchCompletionHandler</code> block method at the end of the notification handler.</li>
</ul>
<h2>Interactive Notifications</h2>
<p>iOS 8 and above.</p>
<p>Interactive notifications enable users to take actions when a notification is received without the application being open.<br />
When an interactive notification is received, the device shows action buttons along with the notification message.</p>
<blockquote><p>For more information, refer to the "interactive notifications" topics in the MobileFirst Platform user documentation, and in Apple's user documentation.</p></blockquote>
<h4>Server API for interactive notification</h4>
<p>To send interactive notification, set a string to indicate the category.<br />
Categories describe a custom type of notification that your application sends and contains actions that a user can perform in response.</p>
<ul>
<li>For event-source notifications, create a notification object and set the category as below:<br />
{% highlight objc %}
notification.APNS.category = "poll";
{% endhighlight %}</li>
<li>For broadcast/tag-based notifications, create a notification object and set the category as below:<br />
{% highlight objc %}
notification.settings.apns.category = "poll";
{% endhighlight %}</li>
<li>The category name must be same as the one used on the client side.</li>
</ul>
<h4>Client-side steps for interactive notification</h4>
<p>To handle interactive notification on the client-side:</p>
<ul>
<li>Enable the application capability to perform background tasks on receiving the remote notifications. This step is required if some of the actions are background-enabled.<br />
To enable background processing, select the project in XCode and in the capabilities tab, select the appropriate background modes like Remote notifications and Background fetch.</li>
<li>Set categories before setting <code>deviceToken</code> on <code>WLPush</code> object in <code>didRegisterForRemoteNotificationsWithDeviceToken</code> method in the <code>AppDelegate</code> class.
<p>
{% highlight objc %}
-(void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken{
NSLog(@"APNS Token : %@", deviceToken);
if([application respondsToSelector:@selector(registerUserNotificationSettings:)]){
UIUserNotificationType userNotificationTypes = UIUserNotificationTypeNone | UIUserNotificationTypeSound | UIUserNotificationTypeAlert | UIUserNotificationTypeBadge;
UIMutableUserNotificationAction *acceptAction = [[UIMutableUserNotificationAction alloc] init];
acceptAction.identifier = @"OK";
acceptAction.title = @"OK";
UIMutableUserNotificationAction *rejetAction = [[UIMutableUserNotificationAction alloc] init];
rejetAction.identifier = @"Cancel";
rejetAction.title = @"Cancel";
[rejetAction setActivationMode:UIUserNotificationActivationModeBackground];</p>
UIMutableUserNotificationCategory *cateogory = [[UIMutableUserNotificationCategory alloc] init];
cateogory.identifier = @"poll";
[cateogory setActions:@[acceptAction,rejetAction] forContext:UIUserNotificationActionContextDefault];
[cateogory setActions:@[acceptAction,rejetAction] forContext:UIUserNotificationActionContextMinimal];</p>
NSSet *catgories = [NSSet setWithObject:cateogory];
[application registerUserNotificationSettings:[UIUserNotificationSettings settingsForTypes:userNotificationTypes categories:catgories]];
}
[[WLPush sharedInstance] setTokenFromClient:deviceToken];
}
{% endhighlight %}</li>
<li>To handle the actions the user selects, use the <code>handleActionWithIdentifier</code> method of the <code>UIApplicationDelegate</code> protocol:<br />
{% highlight objc %}
- (void)application:(UIApplication *)application handleActionWithIdentifier:(NSString *)identifier forRemoteNotification:(NSDictionary *)userInfo completionHandler:(void (^)())completionHandler {
if ([identifier isEqualToString:@"OK"]) {
NSLog(@"OK was tapped");
}
else if ([identifier isEqualToString:@"Cancel"]) {
NSLog(@"Cancel was tapped");
}
if (completionHandler) {
completionHandler();
}
}
{% endhighlight %}</p>
<p>Make sure to call the <code>completionHandler</code>.</li>
</ul>
| 70.905263 | 236 | 0.770338 |
96e11b856af9afb8fc7be4e11ef2826322b030ac | 1,411 | sql | SQL | sql/create_players.sql | hculpan/node-charnomic | e81a12e1d187c9540734312faecc7f10fdd1f456 | [
"MIT"
] | null | null | null | sql/create_players.sql | hculpan/node-charnomic | e81a12e1d187c9540734312faecc7f10fdd1f456 | [
"MIT"
] | null | null | null | sql/create_players.sql | hculpan/node-charnomic | e81a12e1d187c9540734312faecc7f10fdd1f456 | [
"MIT"
] | null | null | null | use charnomic;
DELIMITER $$
create procedure create_players()
begin
drop table if exists players;
create table players (
id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
password VARCHAR(20),
firstname VARCHAR(30),
lastname VARCHAR(50),
joined DATETIME DEFAULT CURRENT_TIMESTAMP,
turn BOOLEAN DEFAULT 0,
onleave BOOLEAN DEFAULT 0,
active BOOLEAN DEFAULT 1,
points INT DEFAULT 0,
level INT DEFAULT 1,
gold INT DEFAULT 0,
vetoes INT DEFAULT 3,
leftgame DATETIME NULL,
monitor BOOLEAN DEFAULT 0
);
insert into players (lastname, firstname, points, onleave) values ('Boivin', 'Bill', 10, 1);
insert into players (lastname, firstname, points, monitor) values ('Culpan', 'Harry', 18, 1);
insert into players (lastname, firstname, points, onleave) values ('Duignan', 'Chris', 17, 1);
insert into players (lastname, firstname, points, onleave) values ('Koehler', 'Steve', 20, 1);
insert into players (lastname, firstname, points) values ('Mele', 'Al', 19);
insert into players (lastname, firstname, points, turn) values ('Thomason', 'Mike', 19, 1);
insert into players (lastname, firstname, points) values ('Wiegand', 'Paul', 19);
commit;
end $$
delimiter ;
-- Execute the procedure
call create_players();
-- Drop the procedure
drop procedure create_players;
| 31.355556 | 98 | 0.664068 |
9d43fecd48313909dfbfb9bd1bfc917cc574d1a1 | 692 | html | HTML | etlapp/restapi/app/views/signin.scala.html | sleshJdev/bigdatalab | c33a768a18bdd031787d82053ac25dccc0f22212 | [
"MIT"
] | null | null | null | etlapp/restapi/app/views/signin.scala.html | sleshJdev/bigdatalab | c33a768a18bdd031787d82053ac25dccc0f22212 | [
"MIT"
] | null | null | null | etlapp/restapi/app/views/signin.scala.html | sleshJdev/bigdatalab | c33a768a18bdd031787d82053ac25dccc0f22212 | [
"MIT"
] | null | null | null | @()
@import helper._
@main("Sign In") {
<div class="form-container">
<h3>Sign In</h3>
@form(action = routes.AuthController.signIn()) {
<div class="form-group">
<label for="login">Email address</label>
<input type="text" name="login" class="form-control" id="login" placeholder="Login">
</div>
<div class="form-group">
<label for="password">Password</label>
<input type="password" name="password" class="form-control" id="password" placeholder="Password">
</div>
<button type="submit" class="btn btn-default">Submit</button>
}
</div>
} | 34.6 | 113 | 0.539017 |
5118836a4fc11e82f51a7d05e139f7422c029b65 | 2,012 | c | C | d/laerad/mon/stag.c | Dbevan/SunderingShadows | 6c15ec56cef43c36361899bae6dc08d0ee907304 | [
"MIT"
] | 13 | 2019-07-19T05:24:44.000Z | 2021-11-18T04:08:19.000Z | d/laerad/mon/stag.c | Dbevan/SunderingShadows | 6c15ec56cef43c36361899bae6dc08d0ee907304 | [
"MIT"
] | 4 | 2021-03-15T18:56:39.000Z | 2021-08-17T17:08:22.000Z | d/laerad/mon/stag.c | Dbevan/SunderingShadows | 6c15ec56cef43c36361899bae6dc08d0ee907304 | [
"MIT"
] | 13 | 2019-09-12T06:22:38.000Z | 2022-01-31T01:15:12.000Z | //Coded by Bane//
#include <std.h>
inherit WEAPONLESS;
void create(){
object ob;
::create();
set_id(({"stag","black stag","Black Stag", "forestmon"}));
set_name("Black Stag");
set_short("A Black Stag");
set_long(
"This mystical creature roams these forests in search of lost "+
"souls that it can steal and drag to Kelemvor's domain. It stands about 6 "+
"feet tall and is covered in thick black fur. Its eyes glow "+
"a fiendish red and smoke trails from its nostrils."
);
set_body_type("quadruped");
set_race("stag");
set_gender("male");
set_size(2);
set_hd(20,40);
set_hp(200);
set_alignment(9);
set_exp(12000);
set_overall_ac(-8);
set("aggressive",0);
add_limb("antlers","head",0,0,0);
set_mob_magic_resistance("average");
set_property("no bump",1);
set_base_damage_type("piercing");
set_attack_limbs(({"antlers"}));
set_attacks_num(1);
set_damage(5,6);
set_funcs(({"headbutt"}));
set_func_chance(30);
set_moving(1);
set_speed(100);
set_max_level(35); //added by Ares 3-31-05, they should be moving on long before now, but just in case
if(!random(15)) {
ob = new("/d/common/obj/brewing/herb_special_inherit");
ob->set_herb_name("fur");
ob->move(TO);
}
}
void headbutt(object targ){
tell_room(ETO,"%^RED%^The Black Stag lowers its antlers.");
if(!"daemon/saving_d"->saving_throw(targ,"breath_weapon")){
tell_object(targ,"%^BOLD%^RED%^The Black Stag slams its antlers into you!");
tell_room(ETO,"%^BOLD%^RED%^The Black Stag slams its antlers into "+targ->query_cap_name()+"!",targ);
targ->do_damage(targ->return_target_limb(),roll_dice(8,8));
return 1;
}
tell_object(targ,"%^BOLD%^RED%^The Black Stag gallops past you barely missing its attack!");
tell_room(ETO,"%^BOLD%^RED%^The Black Stag gallops past "+targ->query_cap_name()+" barely missing its attack!",targ);
return 1;
}
void paralyzed(int time,string message){return 1;}
| 34.101695 | 121 | 0.659543 |
164a940929daeb63de5aeeef74e425c7c7ffbb7c | 1,072 | ts | TypeScript | projects/s-js-utils/src/lib/objects/map-as-keys.spec.ts | simontonsoftware/s-js-utils | a5c6228ad4b90aaa8ea99752261f1eb8c29c4f70 | [
"MIT"
] | 10 | 2018-07-24T02:32:57.000Z | 2021-04-15T07:19:51.000Z | projects/s-js-utils/src/lib/objects/map-as-keys.spec.ts | simontonsoftware/s-js-utils | a5c6228ad4b90aaa8ea99752261f1eb8c29c4f70 | [
"MIT"
] | 13 | 2018-09-02T02:06:17.000Z | 2020-06-25T11:53:01.000Z | projects/s-js-utils/src/lib/objects/map-as-keys.spec.ts | simontonsoftware/s-js-utils | a5c6228ad4b90aaa8ea99752261f1eb8c29c4f70 | [
"MIT"
] | null | null | null | import { expectCallsAndReset } from 's-ng-dev-utils';
import { mapAsKeys } from './map-as-keys';
describe('mapAsKeys()', () => {
it('works with arrays', () => {
const result = mapAsKeys([1, 2, 3], (item) => item * item);
expect(result).toEqual({ 1: 1, 2: 4, 3: 9 });
});
it('works with objects', () => {
const result = mapAsKeys({ a: 'foo', b: 'bar' }, (_item, key) =>
key.toUpperCase(),
);
expect(result).toEqual({ foo: 'A', bar: 'B' });
});
it('works with empty and null collections', () => {
const iteratee = () => 'a';
expect(mapAsKeys({}, iteratee)).toEqual({});
expect(mapAsKeys([], iteratee)).toEqual({});
expect(mapAsKeys(null as [] | null, iteratee)).toEqual({});
expect(mapAsKeys(undefined as {} | undefined, iteratee)).toEqual({});
});
it('provides the right iteratee arguments', () => {
const spy = jasmine.createSpy();
mapAsKeys([1, 2], spy);
expectCallsAndReset(spy, [1, 0], [2, 1]);
mapAsKeys({ a: 1, b: 2 }, spy);
expectCallsAndReset(spy, [1, 'a'], [2, 'b']);
});
});
| 30.628571 | 73 | 0.55597 |
3dbc7345375831a0802736ab1fc64cac1a83e521 | 2,150 | rs | Rust | crates/ruma-client-api/src/presence/get_presence.rs | gnunicorn/ruma | ed36ae5ac70d2c669ea3fe05fd0d33b88aff79ba | [
"MIT"
] | null | null | null | crates/ruma-client-api/src/presence/get_presence.rs | gnunicorn/ruma | ed36ae5ac70d2c669ea3fe05fd0d33b88aff79ba | [
"MIT"
] | null | null | null | crates/ruma-client-api/src/presence/get_presence.rs | gnunicorn/ruma | ed36ae5ac70d2c669ea3fe05fd0d33b88aff79ba | [
"MIT"
] | null | null | null | //! `GET /_matrix/client/*/presence/{userId}/status`
pub mod v3 {
//! `/v3/` ([spec])
//!
//! [spec]: https://spec.matrix.org/v1.2/client-server-api/#get_matrixclientv3presenceuseridstatus
use std::time::Duration;
use ruma_common::{api::ruma_api, presence::PresenceState};
use ruma_identifiers::UserId;
ruma_api! {
metadata: {
description: "Get presence status for this user.",
method: GET,
name: "get_presence",
r0_path: "/_matrix/client/r0/presence/:user_id/status",
stable_path: "/_matrix/client/v3/presence/:user_id/status",
rate_limited: false,
authentication: AccessToken,
added: 1.0,
}
request: {
/// The user whose presence state will be retrieved.
#[ruma_api(path)]
pub user_id: &'a UserId,
}
response: {
/// The state message for this user if one was set.
#[serde(skip_serializing_if = "Option::is_none")]
pub status_msg: Option<String>,
/// Whether or not the user is currently active.
#[serde(skip_serializing_if = "Option::is_none")]
pub currently_active: Option<bool>,
/// The length of time in milliseconds since an action was performed by the user.
#[serde(
with = "ruma_serde::duration::opt_ms",
default,
skip_serializing_if = "Option::is_none",
)]
pub last_active_ago: Option<Duration>,
/// The user's presence state.
pub presence: PresenceState,
}
error: crate::Error
}
impl<'a> Request<'a> {
/// Creates a new `Request` with the given user ID.
pub fn new(user_id: &'a UserId) -> Self {
Self { user_id }
}
}
impl Response {
/// Creates a new `Response` with the given presence state.
pub fn new(presence: PresenceState) -> Self {
Self { presence, status_msg: None, currently_active: None, last_active_ago: None }
}
}
}
| 31.15942 | 102 | 0.552558 |
bd8118b2052d637c9db839eb5c8c9aa8db83b95b | 1,791 | swift | Swift | Test/Transition/Interactivity/InteractivityFirstViewController.swift | LeeJoey77/CustomTransition | f6d11725fcabb23ee4ca5f7e0604ced13c67e36f | [
"MIT"
] | null | null | null | Test/Transition/Interactivity/InteractivityFirstViewController.swift | LeeJoey77/CustomTransition | f6d11725fcabb23ee4ca5f7e0604ced13c67e36f | [
"MIT"
] | null | null | null | Test/Transition/Interactivity/InteractivityFirstViewController.swift | LeeJoey77/CustomTransition | f6d11725fcabb23ee4ca5f7e0604ced13c67e36f | [
"MIT"
] | null | null | null | //
// InteractivityFirstViewController.swift
// Test
//
// Created by JoeyLee on 2020/4/22.
// Copyright © 2020 JoeyLee. All rights reserved.
//
import UIKit
class InteractivityFirstViewController: UIViewController {
@IBOutlet var interactiveTransitionRecognizer: UIScreenEdgePanGestureRecognizer!
let customTransitionDelegate: InteractivityTransitionDelegate = InteractivityTransitionDelegate()
override func viewDidLoad() {
super.viewDidLoad()
}
@IBAction func interactiveTransitionRecognizerAction(_ sender: UIScreenEdgePanGestureRecognizer) {
// 在开始触发手势时,调用animationButtonDidClicked方法,只会调用一次
if sender.state == .began {
self.animationButtonDidClicked(sender)
}
}
/**
这个函数可以在按钮点击时触发,也可以在手势滑动时被触发,通过sender的类型来判断具体是那种情况
如果是通过滑动手势触发,则需要设置customTransitionDelegate的gestureRecognizer属性
:param: sender 事件的发送者,可能是button,也有可能是手势
*/
@IBAction func animationButtonDidClicked(_ sender: AnyObject) {
if let secondVC = storyboard?.instantiateViewController(identifier: "InteractivitySecondViewController") as? InteractivitySecondViewController {
if sender.isKind(of: UIGestureRecognizer.self) {
customTransitionDelegate.gestureRecognizer = interactiveTransitionRecognizer
} else {
customTransitionDelegate.gestureRecognizer = nil
}
// 设置targetEdge为右边,也就是检测从右边向左滑动的手势
customTransitionDelegate.targetEdge = .right
// 设置动画代理
secondVC.transitioningDelegate = customTransitionDelegate
secondVC.modalPresentationStyle = .fullScreen
self.present(secondVC, animated: true, completion: nil)
}
}
}
| 33.792453 | 152 | 0.694026 |
616bed292b9e555dc2ae63cfdc43b2fc7e62d444 | 2,136 | swift | Swift | Sources/Eval/Utilities/Utils.swift | tevelee/Eval | df80bd880d561f1f12bdbac087f835bb13916d5e | [
"Apache-2.0"
] | 170 | 2018-01-05T14:55:25.000Z | 2022-02-28T07:56:19.000Z | Sources/Eval/Utilities/Utils.swift | tevelee/Eval | df80bd880d561f1f12bdbac087f835bb13916d5e | [
"Apache-2.0"
] | 9 | 2018-01-14T07:24:25.000Z | 2021-03-29T17:42:15.000Z | Sources/Eval/Utilities/Utils.swift | tevelee/Eval | df80bd880d561f1f12bdbac087f835bb13916d5e | [
"Apache-2.0"
] | 8 | 2018-01-09T02:56:00.000Z | 2022-03-08T23:14:54.000Z | /*
* Copyright (c) 2018 Laszlo Teveli.
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.
*/
import Foundation
/// Syntactic sugar for `MatchElement` instances to feel like concatenation, whenever the input requires an array of elements.
/// - parameter left: Left hand side
/// - parameter right: Right hand side
/// - returns: An array with two elements (left and right in this order)
public func + (left: PatternElement, right: PatternElement) -> [PatternElement] {
return [left, right]
}
/// Syntactic sugar for appended arrays
/// - parameter array: The array to append
/// - parameter element: The appended element
/// - returns: A new array by appending `array` with `element`
internal func + <A>(array: [A], element: A) -> [A] {
return array + [element]
}
/// Syntactic sugar for appending mutable arrays
/// - parameter array: The array to append
/// - parameter element: The appended element
internal func += <A> (array: inout [A], element: A) {
array = array + element //swiftlint:disable:this shorthand_operator
}
/// Helpers on `String` to provide `Int` based subscription features and easier usage
extension String {
/// Shorter syntax for trimming
/// - returns: The `String` without the prefix and postfix whitespace characters
func trim() -> String {
return trimmingCharacters(in: .whitespacesAndNewlines)
}
}
| 38.836364 | 126 | 0.718165 |
228f46ed7c823c3324a5077631c1fcf3674c0679 | 1,043 | asm | Assembly | test_util/test_util_op8_data.asm | nealvis/nv_c64_util_test | e9893f7c2bb0a3b55bd93e02d17cf497f84f625b | [
"MIT"
] | null | null | null | test_util/test_util_op8_data.asm | nealvis/nv_c64_util_test | e9893f7c2bb0a3b55bd93e02d17cf497f84f625b | [
"MIT"
] | null | null | null | test_util/test_util_op8_data.asm | nealvis/nv_c64_util_test | e9893f7c2bb0a3b55bd93e02d17cf497f84f625b | [
"MIT"
] | null | null | null | //////////////////////////////////////////////////////////////////////////////
// test_util_op8_data.asm
// Copyright(c) 2021 Neal Smith.
// License: MIT. See LICENSE file in root directory.
//////////////////////////////////////////////////////////////////////////////
// This file contains data (variables) to be used as 8 bit operands
// for testing nv_c64_util macros that need 8 bit operands
// import all nv_c64_util macros and data. The data
// will go in default place
#import "../../nv_c64_util/nv_c64_util_macs_and_data.asm"
op8_00: .byte $00
op8_01: .byte $01
op8_02: .byte $02
op8_03: .byte $03
op8_04: .byte $04
op8_05: .byte $05
op8_06: .byte $06
op8_07: .byte $07
op8_08: .byte $08
op8_09: .byte $09
op8_10: .byte $10
op8_0F: .byte $0F
op8_20: .byte $20
op8_22: .byte $22
op8_33: .byte $33
op8_3F: .byte $3F
op8_40: .byte $40
op8_7D: .byte $7D
op8_7F: .byte $7F
op8_80: .byte $80 // -128
op8_81: .byte $81 // -127
op8_99: .byte $99
op8_AA: .byte $AA
op8_F0: .byte $F0
op8_FD: .byte $FD
op8_FE: .byte $FE
op8_FF: .byte $FF
| 25.439024 | 78 | 0.590604 |
eb4e2a8c28727b2e36b54d78cceb3fc585d08f0e | 476 | dart | Dart | test/test_to_work_item_links_test.dart | sowderca/azure_devops_sdk | 1ef1b3b5f72dca3d5075d211f97196caa99494ad | [
"MIT"
] | 2 | 2019-10-07T12:30:29.000Z | 2021-03-19T11:49:53.000Z | test/test_to_work_item_links_test.dart | sowderca/azure_devops_sdk | 1ef1b3b5f72dca3d5075d211f97196caa99494ad | [
"MIT"
] | null | null | null | test/test_to_work_item_links_test.dart | sowderca/azure_devops_sdk | 1ef1b3b5f72dca3d5075d211f97196caa99494ad | [
"MIT"
] | null | null | null | import 'package:azure_devops_sdk/api.dart';
import 'package:test/test.dart';
// tests for TestToWorkItemLinks
void main() {
var instance = TestToWorkItemLinks();
group('test TestToWorkItemLinks', () {
// TestMethod test (default value: null)
test('to test the property `test`', () async {
// TODO
});
// List<WorkItemReference> workItems (default value: [])
test('to test the property `workItems`', () async {
// TODO
});
});
}
| 20.695652 | 60 | 0.628151 |
20c60cefcf3c91a397e6e21d898a1f7f08e69e91 | 1,392 | swift | Swift | SlideOutMenu/SlideOutMenu/SlideOutMenu.swift | DevLiuSir/SwiftUI-DesignCode | 2cb90f3e2bdc5442f0923f3ad6adac43a4004286 | [
"MIT"
] | 153 | 2020-10-30T07:22:36.000Z | 2022-03-30T12:06:12.000Z | __SwiftUI-DesignCode-Projects/SwiftUI-Slide-Out-Menu/SlideOutMenu/SlideOutMenu.swift | luannguyen252/my-swift-journey | 788d66f256358dc5aefa2f3093ef74fd572e83b3 | [
"MIT"
] | 1 | 2021-06-30T02:31:18.000Z | 2021-07-02T07:36:40.000Z | SlideOutMenu/SlideOutMenu/SlideOutMenu.swift | DevLiuSir/SwiftUI-DesignCode | 2cb90f3e2bdc5442f0923f3ad6adac43a4004286 | [
"MIT"
] | 24 | 2020-11-05T09:05:35.000Z | 2022-01-28T08:34:57.000Z | //
// SlideOutMenu.swift
// SlideOutMenu
//
// Created by Liu Chuan on 2020/12/05.
//
import SwiftUI
struct SlideOutMenu: View {
/// 左边菜单栏的宽度
@Binding var menuWidth: CGFloat
@Binding var isDark: Bool
@Binding var offsetX: CGFloat
private let edges = UIApplication.shared.windows.first?.safeAreaInsets
var body: some View {
ZStack(alignment: Alignment(horizontal: .leading, vertical: .center)) {
VStack(spacing: 0) {
MenuHeaderView(wdith: $menuWidth,x: $offsetX)
ItemListView(dark: $isDark)
Divider() //分割线
MenuBottomView(wdith: $menuWidth, isDark: $isDark)
}
}
.padding(.trailing, UIScreen.main.bounds.width - menuWidth)
.edgesIgnoringSafeArea(.all)
/* 阴影的处理 */
.shadow(color: Color.black.opacity(offsetX != 0 ? 0.1 : 0), radius: 5, x: 5, y: 0)
.offset(x: offsetX)
.background(
Color.black.opacity(offsetX == 0 ? 0.5 : 0) // 右边阴影
.ignoresSafeArea(.all, edges: .vertical)
.onTapGesture {
withAnimation {
offsetX = -menuWidth // 点击阴影,修改offset,从而隐藏menu
}
})
}
}
| 27.294118 | 90 | 0.499282 |
74b94fc3e2e0fd0e8d0f0273ee010e3801f40684 | 367 | js | JavaScript | src/types/chr.js | aaditmshah/aang | e82951245bfb840b24ecb9076cc2250962846b27 | [
"MIT"
] | null | null | null | src/types/chr.js | aaditmshah/aang | e82951245bfb840b24ecb9076cc2250962846b27 | [
"MIT"
] | null | null | null | src/types/chr.js | aaditmshah/aang | e82951245bfb840b24ecb9076cc2250962846b27 | [
"MIT"
] | 1 | 2019-11-08T08:47:19.000Z | 2019-11-08T08:47:19.000Z | "use strict";
const fun = require("./fun");
const curry = require("./curry");
const stringify = require("../stringify");
module.exports = fun((functor, chr) => {
if (typeof chr !== "string" || chr.length !== 1) {
const value = stringify(chr);
throw new TypeError(`${value} is not a string`);
} else return curry(functor, chr);
});
| 28.230769 | 56 | 0.580381 |
41303c49b0623b5b0dcd7925022164af0f115ce8 | 1,840 | c | C | programs/sample-bridge/ziti-ncat.c | nf-dev/ziti-sdk-c | 38e4258830049c3c43577ab0863642e061f36f66 | [
"Apache-2.0"
] | 5 | 2020-01-10T13:51:28.000Z | 2020-05-15T17:35:49.000Z | programs/sample-bridge/ziti-ncat.c | NetFoundry/ziti-sdk-c | 014c505ff765d3467e71bfd092515fd733cb1404 | [
"Apache-2.0"
] | 28 | 2019-12-04T19:59:34.000Z | 2020-05-19T03:18:20.000Z | programs/sample-bridge/ziti-ncat.c | nf-dev/ziti-sdk-c | 38e4258830049c3c43577ab0863642e061f36f66 | [
"Apache-2.0"
] | 1 | 2019-12-31T23:04:13.000Z | 2019-12-31T23:04:13.000Z | /*
Copyright (c) 2022 NetFoundry, Inc.
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
https://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.
*/
#include <ziti/ziti.h>
#include <stdio.h>
#define STDIN 0
#define STDOUT 1
typedef struct {
uv_loop_t *loop;
const char *service;
} zcat_opts;
// on successful connect bridge Ziti connection to standard input and output
void on_connect(ziti_connection conn, int status) {
if (status == ZITI_OK) {
ziti_conn_bridge_fds(conn, STDIN, STDOUT, ziti_shutdown, ziti_conn_context(conn));
} else {
fprintf(stderr, "ziti connection failed: %s", ziti_errorstr(status));
ziti_shutdown(ziti_conn_context(conn));
}
}
void on_ziti_event(ziti_context ztx, const ziti_event_t *ev) {
if (ev->type == ZitiContextEvent && ev->event.ctx.ctrl_status == ZITI_OK) {
zcat_opts *opts = ziti_app_ctx(ztx);
ziti_connection zconn;
ziti_conn_init(ztx, &zconn, NULL);
ziti_dial(zconn, opts->service, on_connect, NULL);
}
}
int main(int argc, char *argv[]) {
uv_loop_t *l = uv_loop_new();
zcat_opts opts = {
.loop = l,
.service = argv[2]
};
ziti_options zopts = {
.config = argv[1],
.event_cb = on_ziti_event,
.events = ZitiContextEvent,
.app_ctx = &opts
};
ziti_init_opts(&zopts, l);
uv_run(l, UV_RUN_DEFAULT);
}
| 27.878788 | 90 | 0.674457 |
1ff4915bbbe6c07fc34084301a26828e80d02053 | 11,353 | ps1 | PowerShell | Centrify.Samples.PowerShell.Example.ps1 | centrify/centrify-samples-powershell | aa8e63c7c1bd2b1097e6897ff7c459cc4e14de23 | [
"Apache-2.0"
] | 11 | 2016-08-19T20:44:47.000Z | 2021-03-19T16:53:00.000Z | Centrify.Samples.PowerShell.Example.ps1 | centrify/CentrifyAPIExamples_PowerShell | aa8e63c7c1bd2b1097e6897ff7c459cc4e14de23 | [
"Apache-2.0"
] | 3 | 2017-11-17T20:31:19.000Z | 2018-05-22T18:48:35.000Z | Centrify.Samples.PowerShell.Example.ps1 | centrify/centrify-samples-powershell | aa8e63c7c1bd2b1097e6897ff7c459cc4e14de23 | [
"Apache-2.0"
] | 10 | 2016-10-26T23:24:14.000Z | 2021-08-23T03:40:26.000Z | # Copyright 2016 Centrify Corporation
#
# 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.
[CmdletBinding()]
param(
#Used for interactive auth only. Comment out for OAuth
#[Parameter(Mandatory=$true)]
#[string]$username = "",
[string]$endpoint = "https://cloud.centrify.com"
)
# Get the directory the example script lives in
$exampleRootDir = Split-Path -Parent $MyInvocation.MyCommand.Path
# Import the Centrify.Samples.Powershell and Centrify.Samples.PowerShell.CPS modules
Import-Module $exampleRootDir\module\Centrify.Samples.Powershell.psm1 3>$null 4>$null
Import-Module $exampleRootDir\module\Centrify.Samples.PowerShell.CPS.psm1 3> $null 4>$null
Import-Module $exampleRootDir\module\Centrify.Samples.PowerShell.CPS.Export.psm1 3> $null 4>$null
# If Verbose is enabled, we'll pass it through
$enableVerbose = ($PSBoundParameters['Verbose'] -eq $true)
# Import sample function definitions
. $exampleRootDir\functions\Centrify.Samples.PowerShell.IssueUserCert.ps1
. $exampleRootDir\functions\Centrify.Samples.PowerShell.Query.ps1
. $exampleRootDir\functions\Centrify.Samples.PowerShell.GetUPData.ps1
. $exampleRootDir\functions\Centrify.Samples.PowerShell.GetRoleApps.ps1
. $exampleRootDir\functions\Centrify.Samples.PowerShell.CreateUser.ps1
. $exampleRootDir\functions\Centrify.Samples.PowerShell.SetUserState.ps1
. $exampleRootDir\functions\Centrify.Samples.PowerShell.UpdateApplicationDE.ps1
. $exampleRootDir\functions\Centrify.Samples.PowerShell.HandleAppClick.ps1
. $exampleRootDir\functions\Centrify.Samples.PowerShell.CheckProxyHealth.ps1
. $exampleRootDir\functions\Centrify.Samples.PowerShell.GetNicepLinks.ps1
. $exampleRootDir\functions\Centrify.Samples.PowerShell.GetPolicyBlock.ps1
. $exampleRootDir\functions\Centrify.Samples.PowerShell.SavePolicyBlock3.ps1
# Import sample function definitions for CPS
. $exampleRootDir\functions\Centrify.Samples.PowerShell.CPS.AddResource.ps1
. $exampleRootDir\functions\Centrify.Samples.PowerShell.CPS.AddAccount.ps1
. $exampleRootDir\functions\Centrify.Samples.PowerShell.CPS.UpdateMembersCollection.ps1
try
{
# MFA login and get a bearer token as the provided user, uses interactive Read-Host/Write-Host to perform MFA
# If you already have a bearer token and endpoint, no need to do this, just start using Centrify-InvokeREST
#$token = Centrify-InteractiveLogin-GetToken -Username $username -Endpoint $endpoint -Verbose:$enableVerbose
#Authorization using OAuth2 Auth Code Flow.
#$token = Centrify-OAuthCodeFlow -Endpoint $endpoint -Appid "applicationId" -Clientid "client@domain" -Clientsecret "clientSec" -Scope "scope" -Verbose:$enableVerbose
#Authorization using OAuth2 Implicit Flow.
#$token = Centrify-OAuthImplicit -Endpoint $endpoint -Appid "applicationId" -Clientid "client@domain" -Clientsecret "clientSec" -Scope "scope" -Verbose:$enableVerbose
#Authorization using OAuth2 Cleint Credentials Flow. If interactive or MFA is desired, use OnDemandChallenge APIs https://developer.centrify.com/reference#post_security-ondemandchallenge
$token = Centrify-OAuth-ClientCredentials -Endpoint $endpoint -Appid "applicationId" -Clientid "client@domain" -Clientsecret "clientSec" -Scope "scope" -Verbose:$enableVerbose
#Authorization using OAuth2 Resopurce Owner Flow. If interactive or MFA is desired, use OnDemandChallenge APIs https://developer.centrify.com/reference#post_security-ondemandchallenge
#$token = Centrify-OAuthResourceOwner -Endpoint $endpoint -Appid "applicationId" -Clientid "client@domain" -Clientsecret "clientSec" -Username "user@domain" -Password "password" -Scope "scope" -Verbose:$enableVerbose
# Issue a certificate for the logged in user. This only needs to be called once.
#$userCert = IssueUserCert -Endpoint $token.Endpoint -BearerToken $token.BearerToken
#Write user cert to file. This only needs to be called once. File location can be customized as needed.
#$certificateFile = $username + "_certificate.p12"
#$certbytes = [Convert]::FromBase64String($userCert)
#[io.file]::WriteAllBytes("C:\\" + $certificateFile,$certBytes)
#Get a certificate from file for use instead of MFA login. This can be called after IssueUserCert has been completed and the certificate has been written to file.
#$certificate = new-object System.Security.Cryptography.X509Certificates.X509Certificate2("C:\\$certificateFile")
#Negotiate an ASPXAUTH token from a certificate stored on file. This replaces the need for Centrify-InteractiveLogin-GetToken. This can be called after IssueUserCert has been completed and the certificate has been written to file.
#$token = Centrify-CertSsoLogin-GetToken -Certificate $certificate -Endpoint $endpoint -Verbose:$enableVerbose
# Get information about the user who owns this token via /security/whoami
$userInfo = Centrify-InvokeREST -Endpoint $token.Endpoint -Method "/security/whoami" -Token $token.BearerToken -Verbose:$enableVerbose
Write-Host "Current user: " $userInfo.Result.User
# Run a query for top user logins from last 30 days
#$query = "select NormalizedUser as User, Count(*) as Count from Event where EventType = 'Cloud.Core.Login' and WhenOccurred >= DateFunc('now', '-30') group by User order by count desc"
#$queryResult = Query -Endpoint $token.Endpoint -BearerToken $token.BearerToken -Query $query
#Write-Host "Query resulted in " $queryResult.FullCount " results, first row is: " $queryResult.Results[0].Row
# Get user's assigned applications
#$myApplications = GetUPData -Endpoint $token.Endpoint -BearerToken $token.BearerToken
#foreach($app in $myApplications)
#{
#Write-Host "Assigned to me => Name: " $app.DisplayName " Key: " $app.AppKey " Icon: " $app.Icon
#}
# Get apps assigned to sysadmin role
#$sysadminApps = GetRoleApps -Endpoint $token.Endpoint -BearerToken $token.BearerToken -Role "sysadmin"
#foreach($app in $sysadminApps)
#{
# Write-Host "Assigned to sysadmin role members => Key: " $app.Row.ID
#}
# Create a new CUS user
#$newUserUUID = CreateUser -Endpoint $token.Endpoint -BearerToken $token.BearerToken -Username "apitest@contoso" -Password "newP@3651awdF@!%^"
#Write-Host "Create user result: " $newUserUUID
# Lock a CUS user
#SetUserState -Endpoint $token.Endpoint -BearerToken $token.BearerToken -UserUuid $newUserUUID -NewState "Locked"
# Unlock a CUS user
#SetUserState -Endpoint $token.Endpoint -BearerToken $token.BearerToken -UserUuid $newUserUUID -NewState "None"
# Update the credentials for my UP app...
#UpdateApplicationDE -Endpoint $token.Endpoint -BearerToken $token.BearerToken -AppKey "someAppKeyFromGetUPData" -Username "newUsername" -Password "newPassword"
# Simulate an App Click and return SAML Response...
#$appClickResult = HandleAppClick -Endpoint $token.Endpoint -BearerToken $token.BearerToken -AppKey "37864871-0004-47f1-bbb6-09a33ee6ea9f"
# Parse out SAML Response
#$appClickResult -match "value=(?<content>.*)/>"
#Clean SAML Response
#$SAMLResponse = $matches['content'].Replace('"', "")
#Print SAML Response
#Write-Host $SAMLResponse
# Check Cloud Connector Health
#Get a list of connectors registered to a tenant using a Redrock Query and then loop through the connector list and write results to file.
#$connectorUuidList = Query -Endpoint $token.Endpoint -BearerToken $token.BearerToken -Query "select MachineName, ID from proxy"
#foreach($row in $connectorUuidList.Results)
#{
#Write-Host "Checking health of Cloud Connector on" $row.Row.MachineName
#$connectorHealth = CheckProxyHealth -Endpoint $token.Endpoint -BearerToken $token.BearerToken -ProxyUuid $row.Row.ID
#$connectorHealth.Connectors| ConvertTo-Json | Out-File -Append ("C:\filelocation\" + $row.Row.MachineName + ".json")
#}
#Get/Save Policy
#$getPolicyLinksResult = GetNicepLinks -Endpoint $token.Endpoint -BearerToken $token.BearerToken
#$getPolicyBlockResult = GetPolicyBlock -Endpoint $token.Endpoint -BearerToken $token.BearerToken -Name "/Policy/name"
#$savePolicyBlock = SavePolicyBlock -Endpoint $token.Endpoint -BearerToken $token.BearerToken -PolicyJsonBlock $getPolicyBlockResult
# Create New CPS Resource
#AddResource -Endpoint $token.Endpoint -BearerToken $token.BearerToken -Name "ResourceName" -FQDN "Machine FQDN" -ComputerClass "Windows" -SessionType "Rdp" -Description "Some Description"
# Add User to a CPS Resource
#AddAccount -Endpoint $token.Endpoint -BearerToken $token.BearerToken -User "Username" -Password "Password" -Description "Some Description" -Host "ComputerID"
# Update a CPS Set/Collection
#UpdateMembersCollection -Endpoint $token.Endpoint -BearerToken $token.BearerToken -id "setGUID" -key "AccountOrServerKey" -table "Server or VaultAccount"
# Import CPS entities (Systems, Domains, Databases, Accounts) listed in a CSV file
#Centrify-CPS-Import -Endpoint $token.Endpoint -Token $token.BearerToken -CSVFile "C:\Sample\Sample.CSV" -Verbose:$enableVerbose
# Escrow feature (export Systems, Domains, Databases, Accounts and their attributes into a CSV file and email it to designated recipients)
# Replace the args with args for your instance (i.e., FilePath, Emails)
#Set-EscrowKey -Endpoint $token.Endpoint -Token $token.BearerToken -FilePath 'C:\pubKey.asc' -Verbose:$enableVerbose
#Set-EscrowEmail -Endpoint $token.Endpoint -Token $token.BearerToken -Emails 'admin1@company1.com, admin2@company2.com' -Verbose:$enableVerbose
#Get-EscrowEmail -Endpoint $token.Endpoint -Token $token.BearerToken -Verbose:$enableVerbose
#Run-Escrow -Endpoint $token.Endpoint -Token $token.BearerToken -Verbose:$enableVerbose
#Schedule-Escrow -Endpoint $token.Endpoint -Token $token.BearerToken -Verbose:$enableVerbose
#Unschedule-Escrow -Endpoint $token.Endpoint -Token $token.BearerToken -Verbose:$enableVerbose
#Get-EscrowScheduleStatus -Endpoint $token.Endpoint -Token $token.BearerToken -Verbose:$enableVerbose
# We're done, and don't want to use this token for anything else, so invalidate it by logging out
#$logoutResult = Centrify-InvokeREST -Endpoint $token.Endpoint -Method "/security/logout" -Token $token.BearerToken -Verbose:$enableVerbose
}
finally
{
# Always remove the Centrify.Samples.Powershell and Centrify.Samples.Powershell.CPS modules, makes development iteration on the module itself easier
Remove-Module Centrify.Samples.Powershell 4>$null
Remove-Module Centrify.Samples.Powershell.CPS 4>$null
Remove-Module Centrify.Samples.PowerShell.CPS.Export 4>$null
} | 64.505682 | 234 | 0.75381 |
748179c769ff06685f95aad52bd8ae8f5eae118b | 574 | html | HTML | search/templates/search/search_results.html | UtkarshAgrawalDTU/Betagram | d0c82d87949361d7b66483c57ac2760eebd626fe | [
"MIT"
] | 1 | 2020-03-22T17:30:30.000Z | 2020-03-22T17:30:30.000Z | search/templates/search/search_results.html | UtkarshAgrawalDTU/Betagram | d0c82d87949361d7b66483c57ac2760eebd626fe | [
"MIT"
] | 4 | 2021-04-08T19:17:13.000Z | 2022-03-12T00:15:53.000Z | search/templates/search/search_results.html | UtkarshAgrawalDTU/Betagram | d0c82d87949361d7b66483c57ac2760eebd626fe | [
"MIT"
] | null | null | null | {% extends 'base.html' %}
{% block title %}Search Results{% endblock %}
{% block body %}
<h1>Search Results</h1>
<br>
<br>
{% for obj in user %}
<a href = "{% url 'profile' obj.username %}">
<div class="row" style="max-width: 800px; height: 60px;">
<img src="{{obj.profile.image.url}}" class = "rounded-circle mx-4" width="50px" height="50px">
<h3 class="pt-1">{{obj.username}}</h3>
</div>
</a>
<br>
{% endfor %}
{% if user.count == 0%}
<h2>No results found</h2>
{% endif %}
{% endblock %} | 22.076923 | 110 | 0.513937 |
f1c331ee9a35255ef077c0dc0ced1e1bcf5521a8 | 6,985 | sql | SQL | src/models/db/bdd_tests.sql | Nomost80/pimp-my-fridge | b09ad7866ddb584a1e74392552c93dfd877b5275 | [
"MIT"
] | null | null | null | src/models/db/bdd_tests.sql | Nomost80/pimp-my-fridge | b09ad7866ddb584a1e74392552c93dfd877b5275 | [
"MIT"
] | null | null | null | src/models/db/bdd_tests.sql | Nomost80/pimp-my-fridge | b09ad7866ddb584a1e74392552c93dfd877b5275 | [
"MIT"
] | null | null | null | CALL `PimpMyFridge_Project`.`insert_Values` ('2017-10-24 10:08:00', 'Capteur 1', '21');
CALL `PimpMyFridge_Project`.`insert_Values` ('2017-10-24 10:08:00', 'Capteur 2', '22');
CALL `PimpMyFridge_Project`.`insert_Values` ('2017-10-24 10:08:00', 'Capteur 3', '23');
CALL `PimpMyFridge_Project`.`insert_Values` ('2017-10-24 10:08:00', 'Capteur 4', '24');
CALL `PimpMyFridge_Project`.`insert_Values` ('2017-10-24 10:09:00', 'Capteur 1', '21');
CALL `PimpMyFridge_Project`.`insert_Values` ('2017-10-24 10:09:01', 'Capteur 1', '21');
CALL `PimpMyFridge_Project`.`insert_Values` ('2017-10-24 10:09:02', 'Capteur 1', '21');
CALL `PimpMyFridge_Project`.`insert_Values` ('2017-10-24 10:09:03', 'Capteur 1', '21');
CALL `PimpMyFridge_Project`.`insert_Values` ('2017-10-24 10:09:04', 'Capteur 1', '21');
CALL `PimpMyFridge_Project`.`insert_Values` ('2017-10-24 10:09:05', 'Capteur 1', '21');
CALL `PimpMyFridge_Project`.`insert_Values` ('2017-10-24 10:09:06', 'Capteur 1', '21');
CALL `PimpMyFridge_Project`.`insert_Values` ('2017-10-24 10:09:07', 'Capteur 1', '21');
CALL `PimpMyFridge_Project`.`insert_Values` ('2017-10-24 10:09:08', 'Capteur 1', '21');
CALL `PimpMyFridge_Project`.`insert_Values` ('2017-10-24 10:09:09', 'Capteur 1', '21');
CALL `PimpMyFridge_Project`.`insert_Values` ('2017-10-24 10:09:10', 'Capteur 1', '22');
CALL `PimpMyFridge_Project`.`insert_Values` ('2017-10-24 10:09:11', 'Capteur 1', '22');
CALL `PimpMyFridge_Project`.`insert_Values` ('2017-10-24 10:09:12', 'Capteur 1', '22');
CALL `PimpMyFridge_Project`.`insert_Values` ('2017-10-24 10:09:13', 'Capteur 1', '22');
CALL `PimpMyFridge_Project`.`insert_Values` ('2017-10-24 10:09:14', 'Capteur 1', '22');
CALL `PimpMyFridge_Project`.`insert_Values` ('2017-10-24 10:09:15', 'Capteur 1', '22');
CALL `PimpMyFridge_Project`.`insert_Values` ('2017-10-24 10:09:16', 'Capteur 1', '23');
CALL `PimpMyFridge_Project`.`insert_Values` ('2017-10-24 10:09:17', 'Capteur 1', '23');
CALL `PimpMyFridge_Project`.`insert_Values` ('2017-10-24 10:09:18', 'Capteur 1', '23');
CALL `PimpMyFridge_Project`.`insert_Values` ('2017-10-24 10:09:19', 'Capteur 1', '23');
CALL `PimpMyFridge_Project`.`insert_Values` ('2017-10-24 10:09:00', 'Capteur 2', '30');
CALL `PimpMyFridge_Project`.`insert_Values` ('2017-10-24 10:09:01', 'Capteur 2', '29');
CALL `PimpMyFridge_Project`.`insert_Values` ('2017-10-24 10:09:02', 'Capteur 2', '28');
CALL `PimpMyFridge_Project`.`insert_Values` ('2017-10-24 10:09:03', 'Capteur 2', '27');
CALL `PimpMyFridge_Project`.`insert_Values` ('2017-10-24 10:09:04', 'Capteur 2', '26');
CALL `PimpMyFridge_Project`.`insert_Values` ('2017-10-24 10:09:05', 'Capteur 2', '25');
CALL `PimpMyFridge_Project`.`insert_Values` ('2017-10-24 10:09:06', 'Capteur 2', '24');
CALL `PimpMyFridge_Project`.`insert_Values` ('2017-10-24 10:09:07', 'Capteur 2', '23');
CALL `PimpMyFridge_Project`.`insert_Values` ('2017-10-24 10:09:08', 'Capteur 2', '22');
CALL `PimpMyFridge_Project`.`insert_Values` ('2017-10-24 10:09:09', 'Capteur 2', '21');
CALL `PimpMyFridge_Project`.`insert_Values` ('2017-10-24 10:09:10', 'Capteur 2', '20');
CALL `PimpMyFridge_Project`.`insert_Values` ('2017-10-24 10:09:11', 'Capteur 2', '19');
CALL `PimpMyFridge_Project`.`insert_Values` ('2017-10-24 10:09:12', 'Capteur 2', '18');
CALL `PimpMyFridge_Project`.`insert_Values` ('2017-10-24 10:09:13', 'Capteur 2', '17');
CALL `PimpMyFridge_Project`.`insert_Values` ('2017-10-24 10:09:14', 'Capteur 2', '16');
CALL `PimpMyFridge_Project`.`insert_Values` ('2017-10-24 10:09:15', 'Capteur 2', '15');
CALL `PimpMyFridge_Project`.`insert_Values` ('2017-10-24 10:09:16', 'Capteur 2', '14');
CALL `PimpMyFridge_Project`.`insert_Values` ('2017-10-24 10:09:17', 'Capteur 2', '13');
CALL `PimpMyFridge_Project`.`insert_Values` ('2017-10-24 10:09:18', 'Capteur 2', '12');
CALL `PimpMyFridge_Project`.`insert_Values` ('2017-10-24 10:09:19', 'Capteur 2', '11');
CALL `PimpMyFridge_Project`.`insert_Values` ('2017-10-24 10:09:00', 'Capteur 3', '30');
CALL `PimpMyFridge_Project`.`insert_Values` ('2017-10-24 10:09:01', 'Capteur 3', '30');
CALL `PimpMyFridge_Project`.`insert_Values` ('2017-10-24 10:09:02', 'Capteur 3', '30');
CALL `PimpMyFridge_Project`.`insert_Values` ('2017-10-24 10:09:03', 'Capteur 3', '30');
CALL `PimpMyFridge_Project`.`insert_Values` ('2017-10-24 10:09:07', 'Capteur 3', '25');
CALL `PimpMyFridge_Project`.`insert_Values` ('2017-10-24 10:09:08', 'Capteur 3', '25');
CALL `PimpMyFridge_Project`.`insert_Values` ('2017-10-24 10:09:09', 'Capteur 3', '25');
CALL `PimpMyFridge_Project`.`insert_Values` ('2017-10-24 10:09:10', 'Capteur 3', '26');
CALL `PimpMyFridge_Project`.`insert_Values` ('2017-10-24 10:09:11', 'Capteur 3', '24');
CALL `PimpMyFridge_Project`.`insert_Values` ('2017-10-24 10:09:12', 'Capteur 3', '24');
CALL `PimpMyFridge_Project`.`insert_Values` ('2017-10-24 10:09:13', 'Capteur 3', '24');
CALL `PimpMyFridge_Project`.`insert_Values` ('2017-10-24 10:09:14', 'Capteur 3', '23');
CALL `PimpMyFridge_Project`.`insert_Values` ('2017-10-24 10:09:15', 'Capteur 3', '23');
CALL `PimpMyFridge_Project`.`insert_Values` ('2017-10-24 10:09:16', 'Capteur 3', '23');
CALL `PimpMyFridge_Project`.`insert_Values` ('2017-10-24 10:09:17', 'Capteur 3', '23');
CALL `PimpMyFridge_Project`.`insert_Values` ('2017-10-24 10:09:18', 'Capteur 3', '22');
CALL `PimpMyFridge_Project`.`insert_Values` ('2017-10-24 10:09:19', 'Capteur 3', '22');
CALL `PimpMyFridge_Project`.`insert_Values` ('2017-10-24 10:09:00', 'Capteur 4', '12');
CALL `PimpMyFridge_Project`.`insert_Values` ('2017-10-24 10:09:01', 'Capteur 4', '12');
CALL `PimpMyFridge_Project`.`insert_Values` ('2017-10-24 10:09:02', 'Capteur 4', '13');
CALL `PimpMyFridge_Project`.`insert_Values` ('2017-10-24 10:09:03', 'Capteur 4', '13');
CALL `PimpMyFridge_Project`.`insert_Values` ('2017-10-24 10:09:07', 'Capteur 4', '14');
CALL `PimpMyFridge_Project`.`insert_Values` ('2017-10-24 10:09:08', 'Capteur 4', '14');
CALL `PimpMyFridge_Project`.`insert_Values` ('2017-10-24 10:09:09', 'Capteur 4', '15');
CALL `PimpMyFridge_Project`.`insert_Values` ('2017-10-24 10:09:10', 'Capteur 4', '15');
CALL `PimpMyFridge_Project`.`insert_Values` ('2017-10-24 10:09:11', 'Capteur 4', '16');
CALL `PimpMyFridge_Project`.`insert_Values` ('2017-10-24 10:09:12', 'Capteur 4', '16');
CALL `PimpMyFridge_Project`.`insert_Values` ('2017-10-24 10:09:13', 'Capteur 4', '17');
CALL `PimpMyFridge_Project`.`insert_Values` ('2017-10-24 10:09:14', 'Capteur 4', '17');
CALL `PimpMyFridge_Project`.`insert_Values` ('2017-10-24 10:09:15', 'Capteur 4', '18');
CALL `PimpMyFridge_Project`.`insert_Values` ('2017-10-24 10:09:16', 'Capteur 4', '18');
CALL `PimpMyFridge_Project`.`insert_Values` ('2017-10-24 10:09:17', 'Capteur 4', '19');
CALL `PimpMyFridge_Project`.`insert_Values` ('2017-10-24 10:09:18', 'Capteur 4', '19');
CALL `PimpMyFridge_Project`.`insert_Values` ('2017-10-24 10:09:19', 'Capteur 4', '20');
CALL `PimpMyFridge_Project`.`select_ValuesFromSensor` ('Capteur 1', '2017-10-24 10:08:00', '2017-10-24 10:10:00');
| 81.22093 | 114 | 0.693057 |
d6c2f601a0b156c10f8d5972a586f91a1701c199 | 4,997 | lua | Lua | Applications/Robot/Robot.lua | RomanZSeldinov/MineOS | 3be5054038cfdfc57d67b27594ceffe429e4c694 | [
"MIT"
] | null | null | null | Applications/Robot/Robot.lua | RomanZSeldinov/MineOS | 3be5054038cfdfc57d67b27594ceffe429e4c694 | [
"MIT"
] | null | null | null | Applications/Robot/Robot.lua | RomanZSeldinov/MineOS | 3be5054038cfdfc57d67b27594ceffe429e4c694 | [
"MIT"
] | null | null | null | local c = require("component")
local modem = c.modem
local gpu = c.gpu
local event = require("event")
local port = 512
modem.open(port)
local direction = 1
local xSize, ySize = gpu.getResolution()
local xPos, yPos = math.floor(xSize/2), math.floor(ySize/2)
local xScreen, yScreen = 0, 0
local points = {
}
local homePoint = {x = xPos, y = yPos}
local function checkRange(xCoord, yCoord)
local xRelative, yRelative = xCoord, yCoord
if xRelative >= (0 + xScreen) and xRelative <= (xSize + xScreen) and yRelative >= (0 + yScreen) and yRelative <= (ySize + yScreen) then return true end
end
local function drawTurtle()
if checkRange(xPos, yPos) then
ecs.square(xPos - xScreen - 2, yPos - yScreen - 1, 5, 3, 0x880000)
ecs.colorText(xPos - xScreen, yPos - yScreen, 0xffffff, "R")
local xDir, yDir = xPos - xScreen, yPos - yScreen
if direction == 1 then
gpu.set(xDir, yDir - 1, "^")
elseif direction == 2 then
gpu.set(xDir + 2, yDir, ">")
elseif direction == 4 then
gpu.set(xDir - 2, yDir, "<")
else
gpu.set(xDir, yDir + 1, "|")
end
end
end
local function drawPoints()
if #points > 0 then
for i = 1, #points do
if points[i] then
if not points[i].completed then
if checkRange(points[i].x, points[i].y) then
ecs.colorTextWithBack(points[i].x - xScreen, points[i].y - yScreen, 0xffffff - points[i].color, points[i].color, tostring(i))
end
end
end
end
end
end
local function drawHome()
if checkRange(homePoint.x, homePoint.y) then
ecs.colorTextWithBack(homePoint.x - xScreen, homePoint.y - yScreen, 0xffffff, ecs.colors.blue, "H")
end
end
local function drawAll()
gpu.setBackground(0xffffff)
gpu.setForeground(0xcccccc)
gpu.fill(1, 1, xSize, ySize, "*")
drawHome()
drawTurtle()
drawPoints()
end
local function turtleExecute(command)
modem.broadcast(port, command)
os.sleep(0.4)
end
local function changeDirection(newDirection)
if newDirection ~= direction then
if direction == 1 then
if newDirection == 2 then
turtleExecute("turnRight")
elseif newDirection == 3 then
turtleExecute("turnRight")
turtleExecute("turnRight")
elseif newDirection == 4 then
turtleExecute("turnLeft")
end
elseif direction == 2 then
if newDirection == 1 then
turtleExecute("turnLeft")
elseif newDirection == 3 then
turtleExecute("turnRight")
elseif newDirection == 4 then
turtleExecute("turnRight")
turtleExecute("turnRight")
end
elseif direction == 3 then
if newDirection == 1 then
turtleExecute("turnLeft")
turtleExecute("turnLeft")
elseif newDirection == 2 then
turtleExecute("turnLeft")
elseif newDirection == 4 then
turtleExecute("turnRight")
end
elseif direction == 4 then
if newDirection == 1 then
turtleExecute("turnRight")
elseif newDirection == 2 then
turtleExecute("turnRight")
turtleExecute("turnRight")
elseif newDirection == 3 then
turtleExecute("turnLeft")
end
end
direction = newDirection
end
end
local function moveTurtle()
if direction == 1 then
yPos = yPos - 1
elseif direction == 2 then
xPos = xPos + 1
elseif direction == 3 then
yPos = yPos + 1
else
xPos = xPos - 1
end
turtleExecute("forward")
end
local function moveToPoint(number)
local xToMove, yToMove = points[number].x + xScreen, points[number].y + yScreen
local xDifference, yDifference = xPos + xScreen - xToMove, yPos + yScreen - yToMove
--ecs.error("xDifference = "..tostring(xDifference)..", yDifference = "..tostring(yDifference))
if yDifference > 0 then
changeDirection(1)
elseif yDifference < 0 then
changeDirection(3)
end
for i = 1, math.abs(yDifference) do
moveTurtle()
drawAll()
end
if xDifference > 0 then
changeDirection(4)
elseif xDifference < 0 then
changeDirection(2)
end
for i = 1, math.abs(xDifference) do
moveTurtle()
drawAll()
end
drawAll()
end
local function moveToEveryPoint()
for i = 1, #points do
moveToPoint(i)
points[i].completed = true
end
points = {}
drawAll()
--ecs.error("Все точки пройдены!")
end
----------------------------------------------------------------------------------------
drawAll()
while true do
local e = {event.pull()}
if e[1] == "key_down" then
if e[4] == 200 then
yScreen = yScreen - 1
elseif e[4] == 208 then
yScreen = yScreen + 1
elseif e[4] == 203 then
xScreen = xScreen - 1
elseif e[4] == 205 then
xScreen = xScreen + 1
elseif e[4] == 28 then
moveToEveryPoint()
end
drawAll()
elseif e[1] == "touch" then
local xPoint, yPoint = e[3] + xScreen, e[4] + yScreen
table.insert(points, {x = xPoint, y = yPoint, color = math.random(0x000000, 0xffffff)})
drawAll()
end
end
| 24.140097 | 153 | 0.625575 |
f07bcc1be66ad63b427b651f681533f05db82f52 | 430 | py | Python | topics/migrations/0003_topic_word.py | acdh-oeaw/mmp | 7ef8f33eafd3a7985328d374130f1cbe31f77df0 | [
"MIT"
] | 2 | 2021-06-02T11:27:54.000Z | 2021-08-25T10:29:04.000Z | topics/migrations/0003_topic_word.py | acdh-oeaw/mmp | 7ef8f33eafd3a7985328d374130f1cbe31f77df0 | [
"MIT"
] | 86 | 2021-01-29T12:31:34.000Z | 2022-03-28T11:41:04.000Z | topics/migrations/0003_topic_word.py | acdh-oeaw/mmp | 7ef8f33eafd3a7985328d374130f1cbe31f77df0 | [
"MIT"
] | null | null | null | # Generated by Django 3.2 on 2021-10-21 19:26
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('topics', '0002_alter_modelingprocess_modeling_type'),
]
operations = [
migrations.AddField(
model_name='topic',
name='word',
field=models.JSONField(default='{}'),
preserve_default=False,
),
]
| 21.5 | 63 | 0.597674 |
fb8dd2bebbadae2a0cc1e516ea8f452f8e7dd983 | 5,226 | java | Java | hychat/src/main/java/huayang/hychat/model/po/ChatFriend.java | phy19870227/huayang-ChatProject | 9068804d3395c3dc42144bf50a64b9520caecf3b | [
"Apache-2.0"
] | null | null | null | hychat/src/main/java/huayang/hychat/model/po/ChatFriend.java | phy19870227/huayang-ChatProject | 9068804d3395c3dc42144bf50a64b9520caecf3b | [
"Apache-2.0"
] | null | null | null | hychat/src/main/java/huayang/hychat/model/po/ChatFriend.java | phy19870227/huayang-ChatProject | 9068804d3395c3dc42144bf50a64b9520caecf3b | [
"Apache-2.0"
] | null | null | null | package huayang.hychat.model.po;
import java.io.Serializable;
public class ChatFriend implements Serializable {
/**
* This field was generated by MyBatis Generator.
* This field corresponds to the database column chat_friend.friend_flow
*
* @mbggenerated
*/
private String friendFlow;
/**
* This field was generated by MyBatis Generator.
* This field corresponds to the database column chat_friend.origin_user_flow
*
* @mbggenerated
*/
private String originUserFlow;
/**
* This field was generated by MyBatis Generator.
* This field corresponds to the database column chat_friend.target_user_flow
*
* @mbggenerated
*/
private String targetUserFlow;
/**
* This field was generated by MyBatis Generator.
* This field corresponds to the database table chat_friend
*
* @mbggenerated
*/
private static final long serialVersionUID = 1L;
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column chat_friend.friend_flow
*
* @return the value of chat_friend.friend_flow
*
* @mbggenerated
*/
public String getFriendFlow() {
return friendFlow;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column chat_friend.friend_flow
*
* @param friendFlow the value for chat_friend.friend_flow
*
* @mbggenerated
*/
public void setFriendFlow(String friendFlow) {
this.friendFlow = friendFlow;
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column chat_friend.origin_user_flow
*
* @return the value of chat_friend.origin_user_flow
*
* @mbggenerated
*/
public String getOriginUserFlow() {
return originUserFlow;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column chat_friend.origin_user_flow
*
* @param originUserFlow the value for chat_friend.origin_user_flow
*
* @mbggenerated
*/
public void setOriginUserFlow(String originUserFlow) {
this.originUserFlow = originUserFlow;
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column chat_friend.target_user_flow
*
* @return the value of chat_friend.target_user_flow
*
* @mbggenerated
*/
public String getTargetUserFlow() {
return targetUserFlow;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column chat_friend.target_user_flow
*
* @param targetUserFlow the value for chat_friend.target_user_flow
*
* @mbggenerated
*/
public void setTargetUserFlow(String targetUserFlow) {
this.targetUserFlow = targetUserFlow;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table chat_friend
*
* @mbggenerated
*/
@Override
public boolean equals(Object that) {
if (this == that) {
return true;
}
if (that == null) {
return false;
}
if (getClass() != that.getClass()) {
return false;
}
ChatFriend other = (ChatFriend) that;
return (this.getFriendFlow() == null ? other.getFriendFlow() == null : this.getFriendFlow().equals(other.getFriendFlow()))
&& (this.getOriginUserFlow() == null ? other.getOriginUserFlow() == null : this.getOriginUserFlow().equals(other.getOriginUserFlow()))
&& (this.getTargetUserFlow() == null ? other.getTargetUserFlow() == null : this.getTargetUserFlow().equals(other.getTargetUserFlow()));
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table chat_friend
*
* @mbggenerated
*/
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((getFriendFlow() == null) ? 0 : getFriendFlow().hashCode());
result = prime * result + ((getOriginUserFlow() == null) ? 0 : getOriginUserFlow().hashCode());
result = prime * result + ((getTargetUserFlow() == null) ? 0 : getTargetUserFlow().hashCode());
return result;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table chat_friend
*
* @mbggenerated
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(getClass().getSimpleName());
sb.append(" [");
sb.append("Hash = ").append(hashCode());
sb.append(", friendFlow=").append(friendFlow);
sb.append(", originUserFlow=").append(originUserFlow);
sb.append(", targetUserFlow=").append(targetUserFlow);
sb.append(", serialVersionUID=").append(serialVersionUID);
sb.append("]");
return sb.toString();
}
} | 31.107143 | 147 | 0.634137 |
fa306a1a40369fe551f3c29f28865f0d36df31b2 | 703 | dart | Dart | lootbox/lib/common/models/Collectible.dart | GamePowerDev/nft-collectibles-wallet | 51fc682d7ad44079f57461e7011603db986b47fb | [
"Apache-2.0"
] | null | null | null | lootbox/lib/common/models/Collectible.dart | GamePowerDev/nft-collectibles-wallet | 51fc682d7ad44079f57461e7011603db986b47fb | [
"Apache-2.0"
] | null | null | null | lootbox/lib/common/models/Collectible.dart | GamePowerDev/nft-collectibles-wallet | 51fc682d7ad44079f57461e7011603db986b47fb | [
"Apache-2.0"
] | 2 | 2021-04-07T17:05:31.000Z | 2021-07-04T11:02:41.000Z | import 'package:flutter/material.dart';
class Collectible {
final String? id, image, title, description;
final Color? color;
Collectible({
this.id,
this.image,
this.title,
this.description,
this.color,
});
}
// Test Data
List<Collectible> collectibles = [
Collectible(title: 'Mike', id: 'asset-1'),
Collectible(title: 'David', id: 'asset-2'),
Collectible(title: 'Authur', id: 'asset-3'),
Collectible(title: 'Mike', id: 'asset-4'),
Collectible(title: 'David', id: 'asset-5'),
Collectible(title: 'Authur', id: 'asset-6'),
Collectible(title: 'Mike', id: 'asset-7'),
Collectible(title: 'David', id: 'asset-8'),
Collectible(title: 'Authur', id: 'asset-9'),
]; | 26.037037 | 46 | 0.642959 |
40223b9bdddaaeaee70150f8cd257b0aef71cdf2 | 4,672 | py | Python | dominio/alertas/controllers.py | MinisterioPublicoRJ/apimpmapas | 196ad25a4922448b8ae7a66012a2843c7b7194ad | [
"MIT"
] | 6 | 2020-02-11T18:45:58.000Z | 2020-05-26T12:37:28.000Z | dominio/alertas/controllers.py | MinisterioPublicoRJ/apimpmapas | 196ad25a4922448b8ae7a66012a2843c7b7194ad | [
"MIT"
] | 120 | 2019-07-01T14:45:32.000Z | 2022-01-25T19:10:16.000Z | dominio/alertas/controllers.py | MinisterioPublicoRJ/apimpmapas | 196ad25a4922448b8ae7a66012a2843c7b7194ad | [
"MIT"
] | null | null | null | from django.conf import settings
from dominio.alertas import messages
from dominio.alertas.tasks import async_envia_email_ouvidoria
from dominio.db_connectors import get_hbase_table
class HBaseAccessController:
hbase_cf = None
hbase_table_name = None
hbase_all_cf = None
hbase_all_table_name = None
def __init__(self, orgao_id, alerta_id):
self.orgao_id = str(orgao_id)
self.alerta_id = str(alerta_id)
@property
def get_table(self):
return get_hbase_table(
settings.PROMOTRON_HBASE_NAMESPACE
+
self.hbase_table_name
)
@property
def get_all_table(self):
return get_hbase_table(
settings.PROMOTRON_HBASE_NAMESPACE
+
self.hbase_all_table_name
)
def get_row_key(self, alerta_id):
return f"{alerta_id}".encode()
def get_row_data(self, orgao_id, alerta_id):
sigla = alerta_id.split('.')[0]
return {
f"{self.hbase_cf}:orgao".encode(): orgao_id.encode(),
f"{self.hbase_cf}:alerta_id".encode(): alerta_id.encode(),
f"{self.hbase_cf}:sigla".encode(): sigla.encode(),
}
class DispensaAlertaController(HBaseAccessController):
hbase_cf = "dados_alertas"
hbase_table_name = settings.HBASE_DISPENSAR_ALERTAS_TABLE
hbase_all_cf = "dados_alertas"
hbase_all_table_name = settings.HBASE_DISPENSAR_ALLALERTAS_TABLE
def dispensa_para_orgao(self):
row_key = self.get_row_key(self.alerta_id)
data = self.get_row_data(self.orgao_id, self.alerta_id)
self.get_table.put(row_key, data)
def retorna_para_orgao(self):
row_key = self.get_row_key(self.alerta_id)
self.get_table.delete(row_key)
def retorna_para_todos_orgaos(self):
row_key = self.get_row_key(".".join(self.alerta_id.split(".")[:-1]))
self.get_all_table.delete(row_key)
def dispensa_para_todos_orgaos(self):
alrt_key = ".".join(self.alerta_id.split(".")[:-1])
row_key = self.get_row_key(alrt_key)
data = self.get_row_data("ALL", alrt_key)
self.get_all_table.put(row_key, data)
class EnviaAlertaOuvidoriaController(HBaseAccessController):
dispensa_controller_class = None
messager_class = None
def rollback(self):
self.get_table.delete(self.row_key)
def success(self):
dispensa_controller = self.dispensa_controller_class(
self.orgao_id,
self.alerta_id
)
dispensa_controller.dispensa_para_todos_orgaos()
@property
def row_key(self):
return self.get_row_key(self.alerta_id)
@property
def row_data(self):
return self.get_row_data(self.orgao_id, self.alerta_id)
@property
def alerta_already_sent(self):
result = self.get_table.scan(row_prefix=self.row_key)
try:
next(result)
sent = True
except StopIteration:
sent = False
return sent
def save_alerta_state(self):
self.get_table.put(
self.row_key,
self.row_data
)
def envia_email(self):
async_envia_email_ouvidoria.delay(self)
def render_message(self):
messager = self.messager_class(self.orgao_id, self.alerta_id)
return messager.render()
def prepara_resposta(self, already_sent):
# TODO: talvez levantar excessão e tratar na view
status = 201
msg = "Alerta enviado para ouvidoria com sucesso"
if already_sent:
status = 409
msg = "Este alerta já foi enviado para ouvidoria"
resp = {"detail": msg}
return resp, status
def envia(self):
already_sent = self.alerta_already_sent
if not already_sent:
self.save_alerta_state()
self.envia_email()
return self.prepara_resposta(already_sent)
class EnviaAlertaComprasOuvidoriaController(EnviaAlertaOuvidoriaController):
alerta_sigla = "COMP"
hbase_cf = "dados_alertas"
hbase_table_name = settings.HBASE_ALERTAS_OUVIDORIA_TABLE
email_subject = settings.EMAIL_SUBJECT_OUVIDORIA_COMPRAS
dispensa_controller_class = DispensaAlertaController
messager_class = messages.MensagemOuvidoriaCompras
class EnviaAlertaISPSOuvidoriaController(EnviaAlertaOuvidoriaController):
alerta_sigla = "ISPS"
hbase_cf = "dados_alertas"
hbase_table_name = settings.HBASE_ALERTAS_OUVIDORIA_TABLE
email_subject = settings.EMAIL_SUBJECT_OUVIDORIA_SANEAMENTO
dispensa_controller_class = DispensaAlertaController
messager_class = messages.MensagemOuvidoriaISPS
| 29.2 | 76 | 0.680223 |
a4496c6d1bdff7f0a0cee9dc4c37ea97e0c5769a | 744 | swift | Swift | Brandingdong/Brandingdong/Model/Login/UserData.swift | ByoungilYoun/Brandingdong_iOS | d2c306c1ec779b3044e78298a7542497526f5f86 | [
"MIT"
] | null | null | null | Brandingdong/Brandingdong/Model/Login/UserData.swift | ByoungilYoun/Brandingdong_iOS | d2c306c1ec779b3044e78298a7542497526f5f86 | [
"MIT"
] | 10 | 2020-08-26T05:53:34.000Z | 2020-09-30T10:39:05.000Z | Brandingdong/Brandingdong/Model/Login/UserData.swift | ByoungilYoun/Brandingdong_iOS | d2c306c1ec779b3044e78298a7542497526f5f86 | [
"MIT"
] | 5 | 2020-08-13T12:37:44.000Z | 2020-09-03T10:29:23.000Z | //
// SignUpData.swift
// Brandingdong
//
// Created by 이진욱 on 2020/09/09.
// Copyright © 2020 jwlee. All rights reserved.
//
import UIKit
struct SignUpData: Codable {
var username: String
var email: String
var password1: String
var password2: String
var phonenumber: String
init (dic: [String:Any]) {
self.username = dic["username"] as? String ?? ""
self.email = dic["email"] as? String ?? ""
self.password1 = dic["password1"] as? String ?? ""
self.password2 = dic["password2"] as? String ?? ""
self.phonenumber = dic["phonenumber"] as? String ?? ""
}
}
struct SignInData: Codable {
let username: String
let password: String
struct Events: Codable {
var images: String
}
}
| 20.666667 | 58 | 0.633065 |
7af6587beb4ae280749fa8e41eead14446c6b5ff | 351 | dart | Dart | repo_support/tool/demoidb_project_generate.dart | braulio94/flutter_app_example | f2fe199ed0b6bb682038e9e24a0966de75cdf8fa | [
"BSD-2-Clause"
] | null | null | null | repo_support/tool/demoidb_project_generate.dart | braulio94/flutter_app_example | f2fe199ed0b6bb682038e9e24a0966de75cdf8fa | [
"BSD-2-Clause"
] | null | null | null | repo_support/tool/demoidb_project_generate.dart | braulio94/flutter_app_example | f2fe199ed0b6bb682038e9e24a0966de75cdf8fa | [
"BSD-2-Clause"
] | null | null | null | import 'package:path/path.dart';
import 'package:tekartik_build_utils/flutter/app/generate.dart';
String idbExampleDirName = join('..', 'demo_idb');
Future main() async {
await generate();
}
Future generate({bool force}) async {
await gitGenerate(
dirName: idbExampleDirName,
appName: 'tekartik_demoidb_app',
force: force);
}
| 21.9375 | 64 | 0.706553 |
e8227ed1ca66aa2337691379499390df6e809668 | 12,345 | cpp | C++ | sp/src/public/interpolatortypes.cpp | joshmartel/source-sdk-2013 | 524e87f708d6c30360613b1f65ee174deafa20f4 | [
"Unlicense"
] | 2,268 | 2015-01-01T19:31:56.000Z | 2022-03-31T20:15:31.000Z | sp/src/public/interpolatortypes.cpp | joshmartel/source-sdk-2013 | 524e87f708d6c30360613b1f65ee174deafa20f4 | [
"Unlicense"
] | 241 | 2015-01-01T15:26:14.000Z | 2022-03-31T22:09:59.000Z | sp/src/public/interpolatortypes.cpp | DimasDSF/SMI | 76cc2df8d1f51eb06743d66169524c3493b6d407 | [
"Unlicense"
] | 2,174 | 2015-01-01T08:18:05.000Z | 2022-03-31T10:43:59.000Z | //========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
//=============================================================================
#include "basetypes.h"
#include "tier1/strtools.h"
#include "interpolatortypes.h"
#include "tier0/dbg.h"
#include "mathlib/mathlib.h"
// memdbgon must be the last include file in a .cpp file!!!
#include "tier0/memdbgon.h"
struct InterpolatorNameMap_t
{
int type;
char const *name;
char const *printname;
};
static InterpolatorNameMap_t g_InterpolatorNameMap[] =
{
{ INTERPOLATE_DEFAULT, "default", "Default" },
{ INTERPOLATE_CATMULL_ROM_NORMALIZEX, "catmullrom_normalize_x", "Catmull-Rom (Norm X)" },
{ INTERPOLATE_EASE_IN, "easein", "Ease In" },
{ INTERPOLATE_EASE_OUT, "easeout", "Ease Out" },
{ INTERPOLATE_EASE_INOUT, "easeinout", "Ease In/Out" },
{ INTERPOLATE_BSPLINE, "bspline", "B-Spline" },
{ INTERPOLATE_LINEAR_INTERP, "linear_interp", "Linear Interp." },
{ INTERPOLATE_KOCHANEK_BARTELS, "kochanek", "Kochanek-Bartels" },
{ INTERPOLATE_KOCHANEK_BARTELS_EARLY, "kochanek_early", "Kochanek-Bartels Early" },
{ INTERPOLATE_KOCHANEK_BARTELS_LATE, "kochanek_late", "Kochanek-Bartels Late" },
{ INTERPOLATE_SIMPLE_CUBIC, "simple_cubic", "Simple Cubic" },
{ INTERPOLATE_CATMULL_ROM, "catmullrom", "Catmull-Rom" },
{ INTERPOLATE_CATMULL_ROM_NORMALIZE, "catmullrom_normalize", "Catmull-Rom (Norm)" },
{ INTERPOLATE_CATMULL_ROM_TANGENT, "catmullrom_tangent", "Catmull-Rom (Tangent)" },
{ INTERPOLATE_EXPONENTIAL_DECAY, "exponential_decay", "Exponential Decay" },
{ INTERPOLATE_HOLD, "hold", "Hold" },
};
int Interpolator_InterpolatorForName( char const *name )
{
for ( int i = 0; i < NUM_INTERPOLATE_TYPES; ++i )
{
InterpolatorNameMap_t *slot = &g_InterpolatorNameMap[ i ];
if ( !Q_stricmp( name, slot->name ) )
return slot->type;
}
Assert( !"Interpolator_InterpolatorForName failed!!!" );
return INTERPOLATE_DEFAULT;
}
char const *Interpolator_NameForInterpolator( int type, bool printname )
{
int i = (int)type;
int c = ARRAYSIZE( g_InterpolatorNameMap );
if ( i < 0 || i >= c )
{
Assert( "!Interpolator_NameForInterpolator: bogus type!" );
// returns "unspecified!!!";
return printname ? g_InterpolatorNameMap[ 0 ].printname : g_InterpolatorNameMap[ 0 ].name;
}
return printname ? g_InterpolatorNameMap[ i ].printname : g_InterpolatorNameMap[ i ].name;
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
struct CurveNameMap_t
{
int type;
int hotkey;
};
static CurveNameMap_t g_CurveNameMap[] =
{
{ CURVE_CATMULL_ROM_TO_CATMULL_ROM, '1' },
{ CURVE_EASE_IN_TO_EASE_OUT, '2' },
{ CURVE_EASE_IN_TO_EASE_IN, '3' },
{ CURVE_EASE_OUT_TO_EASE_OUT, '4' },
{ CURVE_BSPLINE_TO_BSPLINE, '5' },
{ CURVE_LINEAR_INTERP_TO_LINEAR_INTERP, '6' },
{ CURVE_KOCHANEK_BARTELS_TO_KOCHANEK_BARTELS, '7' },
{ CURVE_KOCHANEK_BARTELS_EARLY_TO_KOCHANEK_BARTELS_EARLY, '8' },
{ CURVE_KOCHANEK_BARTELS_LATE_TO_KOCHANEK_BARTELS_LATE, '9' },
{ CURVE_SIMPLE_CUBIC_TO_SIMPLE_CUBIC, '0' },
};
// Turn enum into string and vice versa
int Interpolator_CurveTypeForName( const char *name )
{
char sz[ 128 ];
Q_strncpy( sz, name, sizeof( sz ) );
int leftcurve = 0;
int rightcurve = 0;
int skip = Q_strlen( "curve_" );
if ( !Q_strnicmp( sz, "curve_", skip ) )
{
char *p = sz + skip;
char *second = Q_stristr( p, "_to_curve_" );
char save = *second;
*second = 0;
leftcurve = Interpolator_InterpolatorForName( p );
*second = save;
p = second + Q_strlen( "_to_curve_" );
rightcurve = Interpolator_InterpolatorForName( p );
}
return MAKE_CURVE_TYPE( leftcurve, rightcurve );
}
const char *Interpolator_NameForCurveType( int type, bool printname )
{
static char outname[ 256 ];
int leftside = GET_LEFT_CURVE( type );
int rightside = GET_RIGHT_CURVE( type );
if ( !printname )
{
Q_snprintf( outname, sizeof( outname ), "curve_%s_to_curve_%s",
Interpolator_NameForInterpolator( leftside, printname ),
Interpolator_NameForInterpolator( rightside, printname ) );
}
else
{
Q_snprintf( outname, sizeof( outname ), "%s <-> %s",
Interpolator_NameForInterpolator( leftside, printname ),
Interpolator_NameForInterpolator( rightside, printname ) );
}
return outname;
}
void Interpolator_CurveInterpolatorsForType( int type, int& inbound, int& outbound )
{
inbound = GET_LEFT_CURVE( type );
outbound = GET_RIGHT_CURVE( type );
}
int Interpolator_CurveTypeForHotkey( int key )
{
int c = ARRAYSIZE( g_CurveNameMap );
for ( int i = 0; i < c; ++i )
{
CurveNameMap_t *slot = &g_CurveNameMap[ i ];
if ( slot->hotkey == key )
return slot->type;
}
return -1;
}
void Interpolator_GetKochanekBartelsParams( int interpolationType, float& tension, float& bias, float& continuity )
{
switch ( interpolationType )
{
default:
tension = 0.0f;
bias = 0.0f;
continuity = 0.0f;
Assert( 0 );
break;
case INTERPOLATE_KOCHANEK_BARTELS:
tension = 0.77f;
bias = 0.0f;
continuity = 0.77f;
break;
case INTERPOLATE_KOCHANEK_BARTELS_EARLY:
tension = 0.77f;
bias = -1.0f;
continuity = 0.77f;
break;
case INTERPOLATE_KOCHANEK_BARTELS_LATE:
tension = 0.77f;
bias = 1.0f;
continuity = 0.77f;
break;
}
}
void Interpolator_CurveInterpolate( int interpolationType,
const Vector &vPre,
const Vector &vStart,
const Vector &vEnd,
const Vector &vNext,
float f,
Vector &vOut )
{
vOut.Init();
switch ( interpolationType )
{
default:
Warning( "Unknown interpolation type %d\n",
(int)interpolationType );
// break; // Fall through and use catmull_rom as default
case INTERPOLATE_DEFAULT:
case INTERPOLATE_CATMULL_ROM_NORMALIZEX:
Catmull_Rom_Spline_NormalizeX(
vPre,
vStart,
vEnd,
vNext,
f,
vOut );
break;
case INTERPOLATE_CATMULL_ROM:
Catmull_Rom_Spline(
vPre,
vStart,
vEnd,
vNext,
f,
vOut );
break;
case INTERPOLATE_CATMULL_ROM_NORMALIZE:
Catmull_Rom_Spline_Normalize(
vPre,
vStart,
vEnd,
vNext,
f,
vOut );
break;
case INTERPOLATE_CATMULL_ROM_TANGENT:
Catmull_Rom_Spline_Tangent(
vPre,
vStart,
vEnd,
vNext,
f,
vOut );
break;
case INTERPOLATE_EASE_IN:
{
f = sin( M_PI * f * 0.5f );
// Fixme, since this ignores vPre and vNext we could omit computing them aove
VectorLerp( vStart, vEnd, f, vOut );
}
break;
case INTERPOLATE_EASE_OUT:
{
f = 1.0f - sin( M_PI * f * 0.5f + 0.5f * M_PI );
// Fixme, since this ignores vPre and vNext we could omit computing them aove
VectorLerp( vStart, vEnd, f, vOut );
}
break;
case INTERPOLATE_EASE_INOUT:
{
f = SimpleSpline( f );
// Fixme, since this ignores vPre and vNext we could omit computing them aove
VectorLerp( vStart, vEnd, f, vOut );
}
break;
case INTERPOLATE_LINEAR_INTERP:
// Fixme, since this ignores vPre and vNext we could omit computing them aove
VectorLerp( vStart, vEnd, f, vOut );
break;
case INTERPOLATE_KOCHANEK_BARTELS:
case INTERPOLATE_KOCHANEK_BARTELS_EARLY:
case INTERPOLATE_KOCHANEK_BARTELS_LATE:
{
float t, b, c;
Interpolator_GetKochanekBartelsParams( interpolationType, t, b, c );
Kochanek_Bartels_Spline_NormalizeX
(
t, b, c,
vPre,
vStart,
vEnd,
vNext,
f,
vOut
);
}
break;
case INTERPOLATE_SIMPLE_CUBIC:
Cubic_Spline_NormalizeX(
vPre,
vStart,
vEnd,
vNext,
f,
vOut );
break;
case INTERPOLATE_BSPLINE:
BSpline(
vPre,
vStart,
vEnd,
vNext,
f,
vOut );
break;
case INTERPOLATE_EXPONENTIAL_DECAY:
{
float dt = vEnd.x - vStart.x;
if ( dt > 0.0f )
{
float val = 1.0f - ExponentialDecay( 0.001, dt, f * dt );
vOut.y = vStart.y + val * ( vEnd.y - vStart.y );
}
else
{
vOut.y = vStart.y;
}
}
break;
case INTERPOLATE_HOLD:
{
vOut.y = vStart.y;
}
break;
}
}
void Interpolator_CurveInterpolate_NonNormalized( int interpolationType,
const Vector &vPre,
const Vector &vStart,
const Vector &vEnd,
const Vector &vNext,
float f,
Vector &vOut )
{
vOut.Init();
switch ( interpolationType )
{
default:
Warning( "Unknown interpolation type %d\n",
(int)interpolationType );
// break; // Fall through and use catmull_rom as default
case INTERPOLATE_CATMULL_ROM_NORMALIZEX:
case INTERPOLATE_DEFAULT:
case INTERPOLATE_CATMULL_ROM:
case INTERPOLATE_CATMULL_ROM_NORMALIZE:
case INTERPOLATE_CATMULL_ROM_TANGENT:
Catmull_Rom_Spline(
vPre,
vStart,
vEnd,
vNext,
f,
vOut );
break;
case INTERPOLATE_EASE_IN:
{
f = sin( M_PI * f * 0.5f );
// Fixme, since this ignores vPre and vNext we could omit computing them aove
VectorLerp( vStart, vEnd, f, vOut );
}
break;
case INTERPOLATE_EASE_OUT:
{
f = 1.0f - sin( M_PI * f * 0.5f + 0.5f * M_PI );
// Fixme, since this ignores vPre and vNext we could omit computing them aove
VectorLerp( vStart, vEnd, f, vOut );
}
break;
case INTERPOLATE_EASE_INOUT:
{
f = SimpleSpline( f );
// Fixme, since this ignores vPre and vNext we could omit computing them aove
VectorLerp( vStart, vEnd, f, vOut );
}
break;
case INTERPOLATE_LINEAR_INTERP:
// Fixme, since this ignores vPre and vNext we could omit computing them aove
VectorLerp( vStart, vEnd, f, vOut );
break;
case INTERPOLATE_KOCHANEK_BARTELS:
case INTERPOLATE_KOCHANEK_BARTELS_EARLY:
case INTERPOLATE_KOCHANEK_BARTELS_LATE:
{
float t, b, c;
Interpolator_GetKochanekBartelsParams( interpolationType, t, b, c );
Kochanek_Bartels_Spline
(
t, b, c,
vPre,
vStart,
vEnd,
vNext,
f,
vOut
);
}
break;
case INTERPOLATE_SIMPLE_CUBIC:
Cubic_Spline(
vPre,
vStart,
vEnd,
vNext,
f,
vOut );
break;
case INTERPOLATE_BSPLINE:
BSpline(
vPre,
vStart,
vEnd,
vNext,
f,
vOut );
break;
case INTERPOLATE_EXPONENTIAL_DECAY:
{
float dt = vEnd.x - vStart.x;
if ( dt > 0.0f )
{
float val = 1.0f - ExponentialDecay( 0.001, dt, f * dt );
vOut.y = vStart.y + val * ( vEnd.y - vStart.y );
}
else
{
vOut.y = vStart.y;
}
}
break;
case INTERPOLATE_HOLD:
{
vOut.y = vStart.y;
}
break;
}
}
void Interpolator_CurveInterpolate_NonNormalized( int interpolationType,
const Quaternion &vPre,
const Quaternion &vStart,
const Quaternion &vEnd,
const Quaternion &vNext,
float f,
Quaternion &vOut )
{
vOut.Init();
switch ( interpolationType )
{
default:
Warning( "Unknown interpolation type %d\n",
(int)interpolationType );
// break; // Fall through and use catmull_rom as default
case INTERPOLATE_CATMULL_ROM_NORMALIZEX:
case INTERPOLATE_DEFAULT:
case INTERPOLATE_CATMULL_ROM:
case INTERPOLATE_CATMULL_ROM_NORMALIZE:
case INTERPOLATE_CATMULL_ROM_TANGENT:
case INTERPOLATE_KOCHANEK_BARTELS:
case INTERPOLATE_KOCHANEK_BARTELS_EARLY:
case INTERPOLATE_KOCHANEK_BARTELS_LATE:
case INTERPOLATE_SIMPLE_CUBIC:
case INTERPOLATE_BSPLINE:
// FIXME, since this ignores vPre and vNext we could omit computing them aove
QuaternionSlerp( vStart, vEnd, f, vOut );
break;
case INTERPOLATE_EASE_IN:
{
f = sin( M_PI * f * 0.5f );
// Fixme, since this ignores vPre and vNext we could omit computing them aove
QuaternionSlerp( vStart, vEnd, f, vOut );
}
break;
case INTERPOLATE_EASE_OUT:
{
f = 1.0f - sin( M_PI * f * 0.5f + 0.5f * M_PI );
// Fixme, since this ignores vPre and vNext we could omit computing them aove
QuaternionSlerp( vStart, vEnd, f, vOut );
}
break;
case INTERPOLATE_EASE_INOUT:
{
f = SimpleSpline( f );
// Fixme, since this ignores vPre and vNext we could omit computing them aove
QuaternionSlerp( vStart, vEnd, f, vOut );
}
break;
case INTERPOLATE_LINEAR_INTERP:
// Fixme, since this ignores vPre and vNext we could omit computing them aove
QuaternionSlerp( vStart, vEnd, f, vOut );
break;
case INTERPOLATE_EXPONENTIAL_DECAY:
vOut.Init();
break;
case INTERPOLATE_HOLD:
{
vOut = vStart;
}
break;
}
} | 24.397233 | 115 | 0.662373 |
cfc518ec4dc9539b3c4a7617e1d2141717ede0f5 | 1,310 | lua | Lua | lovr-api/graphics/newModel.lua | jmiskovic/aquadeck | d9f1efa31cd9ac445ee5aa39339a5671ee80ff8b | [
"Unlicense"
] | 32 | 2017-01-13T23:15:10.000Z | 2022-02-12T11:36:53.000Z | lovr-api/graphics/newModel.lua | jmiskovic/aquadeck | d9f1efa31cd9ac445ee5aa39339a5671ee80ff8b | [
"Unlicense"
] | 55 | 2017-11-22T07:34:49.000Z | 2022-03-14T19:24:51.000Z | lovr-api/graphics/newModel.lua | jmiskovic/aquadeck | d9f1efa31cd9ac445ee5aa39339a5671ee80ff8b | [
"Unlicense"
] | 25 | 2017-10-06T21:57:27.000Z | 2022-03-14T19:17:19.000Z | return {
tag = 'graphicsObjects',
summary = 'Create a new Model.',
description = [[
Creates a new Model from a file. The supported 3D file formats are OBJ, glTF, and STL.
]],
arguments = {
filename = {
type = 'string',
description = 'The filename of the model to load.'
},
modelData = {
type = 'ModelData',
description = 'The ModelData containing the data for the Model.'
}
},
returns = {
model = {
type = 'Model',
description = 'The new Model.'
}
},
variants = {
{
arguments = { 'filename' },
returns = { 'model' }
},
{
arguments = { 'modelData' },
returns = { 'model' }
}
},
notes = [[
Diffuse and emissive textures will be loaded in the sRGB encoding, all other textures will be
loaded as linear.
Currently, the following features are not supported by the model importer:
- OBJ: Quads are not supported (only triangles).
- glTF: Sparse accessors are not supported.
- glTF: Morph targets are not supported.
- glTF: base64 images are not supported (base64 buffer data works though).
- glTF: Only the default scene is loaded.
- glTF: Currently, each skin in a Model can have up to 48 joints.
- STL: ASCII STL files are not supported.
]]
}
| 27.291667 | 97 | 0.60916 |
baf02bf34287a05e4db5d68e1ce42fbe79b41a85 | 924 | sql | SQL | contrib/babelfishpg_money/fixeddecimal--aggs.sql | faizol/babelfish_extensions | 3dab47c2a27a784906426c9401fc99c9519906d1 | [
"PostgreSQL",
"Apache-2.0",
"BSD-3-Clause"
] | 115 | 2021-10-29T18:17:24.000Z | 2022-03-28T01:05:20.000Z | contrib/babelfishpg_money/fixeddecimal--aggs.sql | faizol/babelfish_extensions | 3dab47c2a27a784906426c9401fc99c9519906d1 | [
"PostgreSQL",
"Apache-2.0",
"BSD-3-Clause"
] | 81 | 2021-10-29T19:22:51.000Z | 2022-03-31T19:31:12.000Z | contrib/babelfishpg_money/fixeddecimal--aggs.sql | faizol/babelfish_extensions | 3dab47c2a27a784906426c9401fc99c9519906d1 | [
"PostgreSQL",
"Apache-2.0",
"BSD-3-Clause"
] | 53 | 2021-10-30T01:26:50.000Z | 2022-03-22T00:12:47.000Z |
-- Aggregate Support
CREATE FUNCTION fixeddecimal_avg_accum(INTERNAL, FIXEDDECIMAL)
RETURNS INTERNAL
AS 'babelfishpg_money', 'fixeddecimal_avg_accum'
LANGUAGE C IMMUTABLE;
CREATE FUNCTION fixeddecimal_sum(INTERNAL)
RETURNS FIXEDDECIMAL
AS 'babelfishpg_money', 'fixeddecimal_sum'
LANGUAGE C IMMUTABLE;
CREATE FUNCTION fixeddecimal_avg(INTERNAL)
RETURNS FIXEDDECIMAL
AS 'babelfishpg_money', 'fixeddecimal_avg'
LANGUAGE C IMMUTABLE;
CREATE AGGREGATE min(FIXEDDECIMAL) (
SFUNC = fixeddecimalsmaller,
STYPE = FIXEDDECIMAL,
SORTOP = <
);
CREATE AGGREGATE max(FIXEDDECIMAL) (
SFUNC = fixeddecimallarger,
STYPE = FIXEDDECIMAL,
SORTOP = >
);
CREATE AGGREGATE sum(FIXEDDECIMAL) (
SFUNC = fixeddecimal_avg_accum,
FINALFUNC = fixeddecimal_sum,
STYPE = INTERNAL
);
CREATE AGGREGATE avg(FIXEDDECIMAL) (
SFUNC = fixeddecimal_avg_accum,
FINALFUNC = fixeddecimal_avg,
STYPE = INTERNAL
);
| 20.533333 | 62 | 0.767316 |
dc0c493065ce7903cc36658358bf4e2a7816ba81 | 4,321 | py | Python | nmfamv2/mixtures/run_log.py | gmarupilla/NMRFAMv2 | 2e9e7e1f43dbf1d8bcdbcff044bb686db3af09e0 | [
"MIT"
] | null | null | null | nmfamv2/mixtures/run_log.py | gmarupilla/NMRFAMv2 | 2e9e7e1f43dbf1d8bcdbcff044bb686db3af09e0 | [
"MIT"
] | null | null | null | nmfamv2/mixtures/run_log.py | gmarupilla/NMRFAMv2 | 2e9e7e1f43dbf1d8bcdbcff044bb686db3af09e0 | [
"MIT"
] | null | null | null | import json
import os
from nmfamv2.graphics import MetaboliteGraphic, MixtureGraphic, ScaledGraphic
class RunLog:
def __init__(self, user_dir):
self.user_dir = user_dir
self.top_dirname = os.path.join(user_dir, "logs")
self.mixture_dir = os.path.join(self.top_dirname, "mixtures")
self.metab_dir = os.path.join(self.top_dirname, "metabolites")
self.fitted_dir = os.path.join(self.top_dirname, "fitted")
os.mkdir(self.top_dirname)
os.mkdir(self.mixture_dir)
os.mkdir(self.metab_dir)
os.mkdir(self.fitted_dir)
def log_mixture(self, mixture, label):
# Write Log Data
mixLogData = mixture.getLogData()
with open(os.path.join(self.mixture_dir, "mixture" + label + ".txt"), 'w') as file:
file.write(json.dumps(mixLogData))
# Write Graphs
mixtureGraphic = MixtureGraphic(mixture)
mixtureGraphic.write_mixture(self.mixture_dir, label)
def log_metab_list(self, metabolite_list, label):
# Write Log Data
for metab in metabolite_list:
metabLogData = metab.getLogData()
with open(os.path.join(self.metab_dir, metab.name + label + ".txt"), 'w') as file:
file.write(json.dumps(metabLogData))
# Write Graphs
metaboliteGraphic = MetaboliteGraphic(metabolite_list)
metaboliteGraphic.write_metabolites(self.metab_dir, label)
def log_fitted_all_metabs(self, metabolite_list, mixture, each_metabolite_scale, path=""):
new_path = self.fitted_dir + path
if not os.path.isdir(new_path):
os.mkdir(new_path)
scaledGraphic = ScaledGraphic(metabolite_list, mixture, each_metabolite_scale)
scaledGraphic.write_all_scaled_mat_plot_graphics(self.fitted_dir + path)
def log_fitted_metabs(self, metabolite_list, mixture, each_metabolite_scale, path=""):
new_path = self.fitted_dir + path
if not os.path.isdir(new_path):
os.mkdir(new_path)
scaledGraphic = ScaledGraphic(metabolite_list, mixture, each_metabolite_scale)
scaledGraphic.write_fitted_mat_plot_graphic(self.fitted_dir + path)
from nmfamv2.spectrum import Spectrum
from nmfamv2.metabolite.metabolite import Metabolite
# TODO: Move tests
def test_logMixture():
runLog = RunLog("RunLogTests")
mixture = Spectrum([0, 1, 2, 3, 4, 5, 6, 7], [1, 1, 1, 1, 1, 1, 1, 1])
runLog.log_mixture(mixture, "original")
def test_logMetab():
runLog = RunLog("RunLogTests")
metabolite_list = [
Metabolite("A", [0, 1, 2, 3, 4, 5, 6, 7], [0, 0, 0, 0, 0, 0, 1, 0], peak_ppms=[6], peak_inds=[6]),
Metabolite("B", [0, 1, 2, 3, 4, 5, 6, 7], [0, 0, 1, 0, 0, 0, 0, 0], peak_ppms=[2], peak_inds=[2]),
Metabolite("C", [0, 1, 2, 3, 4, 5, 6, 7], [0, 0, 0, 0, 0, 0, 1, 0], peak_ppms=[6], peak_inds=[6])
]
runLog.log_metab_list(metabolite_list, "shifted")
def test_logAllFitted():
runLog = RunLog("RunLogTests")
# Define metabolite_list
metabolite_list = [
Metabolite("A", [0, 1, 2, 3, 4, 5, 6, 7], [0, 0, 0, 0, 0, 0, 1, 0], peak_ppms=[6], peak_inds=[6]),
Metabolite("B", [0, 1, 2, 3, 4, 5, 6, 7], [0, 0, 1, 0, 0, 0, 0, 0], peak_ppms=[2], peak_inds=[2]),
Metabolite("C", [0, 1, 2, 3, 4, 5, 6, 7], [0, 0, 0, 0, 0, 0, 1, 0], peak_ppms=[6], peak_inds=[6])
]
# Define a mixture
mixture = Spectrum([0, 1, 2, 3, 4, 5, 6, 7], [1, 1, 1, 1, 1, 1, 1, 1])
# Create scales
scales = [3, 4, 2]
runLog.log_fitted_all_metabs(metabolite_list, mixture, scales)
def test_logFitted():
runLog = RunLog("RunLogTests")
# Define metabolite_list
metabolite_list = [
Metabolite("A", [0, 1, 2, 3, 4, 5, 6, 7], [0, 0, 0, 0, 0, 0, 1, 0], peak_ppms=[6], peak_inds=[6]),
Metabolite("B", [0, 1, 2, 3, 4, 5, 6, 7], [0, 0, 1, 0, 0, 0, 0, 0], peak_ppms=[2], peak_inds=[2]),
Metabolite("C", [0, 1, 2, 3, 4, 5, 6, 7], [0, 0, 0, 0, 0, 0, 1, 0], peak_ppms=[6], peak_inds=[6])
]
# Define a mixture
mixture = Spectrum([0, 1, 2, 3, 4, 5, 6, 7], [1, 1, 1, 1, 1, 1, 1, 1])
# Create scales
scales = [3, 4, 2]
runLog.log_fitted_metabs(metabolite_list, mixture, scales)
# test_logMixture()
# test_logMetab()
# test_logAllFitted()
# test_logFitted()
| 35.130081 | 106 | 0.615367 |
d275ed207204be6a2a089d43b24248fe5e51eec0 | 853 | php | PHP | plugins/media-library-assistant/examples/plugins/smart-media-categories/admin/views/smc-sync-category-block.php | csgis/wordpress-components | df4ef6e4876a0338b00a1ab2f3d976431643bc6c | [
"Apache-2.0"
] | null | null | null | plugins/media-library-assistant/examples/plugins/smart-media-categories/admin/views/smc-sync-category-block.php | csgis/wordpress-components | df4ef6e4876a0338b00a1ab2f3d976431643bc6c | [
"Apache-2.0"
] | null | null | null | plugins/media-library-assistant/examples/plugins/smart-media-categories/admin/views/smc-sync-category-block.php | csgis/wordpress-components | df4ef6e4876a0338b00a1ab2f3d976431643bc6c | [
"Apache-2.0"
] | 3 | 2019-01-04T14:08:52.000Z | 2019-11-27T07:56:52.000Z | <?php
/*
* Category Block Parameters
*
* $tax_name taxonomy name, display format
* $tax_attr taxonomy slug, attribute format
* $tax_checklist checklist for one taxonomy
* $taxonomy_options sync/ignore radio buttons for one taxonomy
*/
?>
<div id="smc-sync-<?php echo $tax_attr; ?>-block">
<span class="title smc-sync-categories-label"><?php echo $tax_name; ?>
<span class="catshow"><?php _e( 'more', $this->plugin_slug ); ?></span>
<span class="cathide" style="display:none;"><?php _e( 'less', 'smart-media-categories' ); ?></span>
</span>
<input id="smc-tax-input-<?php echo $tax_attr; ?>" type="hidden" name="tax_input[<?php echo $tax_attr; ?>][]" value="0" />
<ul class="cat-checklist" id="smc-tax-checklist-<?php echo $tax_attr; ?>">
<?php echo $tax_checklist; ?>
</ul>
<?php echo $taxonomy_options; ?>
</div>
| 38.772727 | 124 | 0.649472 |
8093a36f138faf12833f532a3284c7605a29f3a4 | 1,374 | java | Java | UparivanjeBrojeva/src/jasarsoft/UparivanjeBrojeva.java | jasarsoft/java-ex | 6e644eb905d600f8f97a1669a7e327368ea3aaba | [
"Apache-2.0"
] | null | null | null | UparivanjeBrojeva/src/jasarsoft/UparivanjeBrojeva.java | jasarsoft/java-ex | 6e644eb905d600f8f97a1669a7e327368ea3aaba | [
"Apache-2.0"
] | null | null | null | UparivanjeBrojeva/src/jasarsoft/UparivanjeBrojeva.java | jasarsoft/java-ex | 6e644eb905d600f8f97a1669a7e327368ea3aaba | [
"Apache-2.0"
] | null | null | null | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package jasarsoft;
//ukljucivanje Scanner potrebnog za ucitavanje sa tastature
import java.util.Scanner;
/**
*
* @author jasarsoft
*/
public class UparivanjeBrojeva {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
/*da bi se ucitalo sa tastature potrebno je definisati scanner
koji moze da se nazove bilo kako, u ovom slucaju je sc*/
Scanner sc=new Scanner(System.in);
//------------------------DRUGI ZADATKA-----------------------------
//Ucitati dva realna broja i odstampati manji, a ukoliko su jednaki,
//ispisati poruku "Uneti brojevi su jednaki."
float a,b;
System.out.println("Unesite prvi broj");
a=sc.nextFloat();
System.out.println("Unesite drugi broj");
b=sc.nextFloat();
if(a==b){
System.out.println("Uneti brojevi su jednaki.");
}
else if(a<b){
System.out.println("Manji je prvi broj a="+a);
}
else {
System.out.println("Manji je drugi broj b="+b);
}
}
}
| 29.869565 | 80 | 0.556769 |
393b9c6158981a354f5e0845656907e472ea3ebf | 3,348 | swift | Swift | 0050-generative-art-pt2/Joy/Joy/ViewController.swift | loseth/episode-code-samples | 798cd62406f325cc776bd41cfc99450d1ca1e94e | [
"MIT"
] | 683 | 2017-12-09T21:29:01.000Z | 2022-03-30T08:48:39.000Z | 0050-generative-art-pt2/Joy/Joy/ViewController.swift | loseth/episode-code-samples | 798cd62406f325cc776bd41cfc99450d1ca1e94e | [
"MIT"
] | 62 | 2018-03-05T20:30:16.000Z | 2022-03-24T14:41:58.000Z | 0050-generative-art-pt2/Joy/Joy/ViewController.swift | loseth/episode-code-samples | 798cd62406f325cc776bd41cfc99450d1ca1e94e | [
"MIT"
] | 262 | 2018-01-30T02:17:40.000Z | 2022-03-28T09:57:23.000Z | import UIKit
class ViewController: UIViewController {
let imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: 600, height: 600))
let amplitudeLabel = UILabel()
let amplitudeSlider = UISlider()
let centerLabel = UILabel()
let centerSlider = UISlider()
let plateauLabel = UILabel()
let plateauSlider = UISlider()
let curveLabel = UILabel()
let curveSlider = UISlider()
var amplitude: Float = 0.5
var center: Float = 0.5
var plateauSize: Float = 0.5
var curveSize: Float = 0.5
override func viewDidLoad() {
super.viewDidLoad()
setImage()
amplitudeLabel.text = "Amplitude"
amplitudeLabel.textColor = .white
amplitudeSlider.value = amplitude
amplitudeSlider.isContinuous = false
amplitudeSlider.addTarget(self, action: #selector(amplitudeChanged), for: .valueChanged)
centerLabel.text = "Center"
centerLabel.textColor = .white
centerSlider.value = center
centerSlider.isContinuous = false
centerSlider.addTarget(self, action: #selector(centerChanged), for: .valueChanged)
plateauLabel.text = "Plateau size"
plateauLabel.textColor = .white
plateauSlider.value = plateauSize
plateauSlider.isContinuous = false
plateauSlider.addTarget(self, action: #selector(plateauChanged), for: .valueChanged)
curveLabel.text = "Curve size"
curveLabel.textColor = .white
curveSlider.value = curveSize
curveSlider.isContinuous = false
curveSlider.addTarget(self, action: #selector(curveChanged), for: .valueChanged)
let stackView = UIStackView(arrangedSubviews: [
imageView,
amplitudeLabel,
amplitudeSlider,
centerLabel,
centerSlider,
plateauLabel,
plateauSlider,
curveLabel,
curveSlider,
])
stackView.axis = .vertical
stackView.spacing = 8
stackView.translatesAutoresizingMaskIntoConstraints = false
view.backgroundColor = .black
view.addSubview(stackView)
NSLayoutConstraint.activate([
stackView.centerXAnchor.constraint(equalTo: view.centerXAnchor),
stackView.centerYAnchor.constraint(equalTo: view.centerYAnchor),
])
}
@objc func amplitudeChanged() {
amplitude = amplitudeSlider.value
setImage()
}
@objc func centerChanged() {
center = centerSlider.value
setImage()
}
@objc func plateauChanged() {
plateauSize = plateauSlider.value
setImage()
}
@objc func curveChanged() {
curveSize = curveSlider.value
setImage()
}
func setImage() {
// Current.date = { Date.init(timeIntervalSince1970: 1517202000) }
// var rng = SystemRandomNumberGenerator()
let newImage = image(
amplitude: CGFloat(self.amplitude),
center: CGFloat(self.center),
plateauSize: CGFloat(self.plateauSize),
curveSize: CGFloat(self.curveSize),
isPointFreeAnniversary: Current.date().isPointFreeAnniversary
).run(using: &Current.rng)
self.imageView.image = newImage
}
}
struct Environment {
var calendar = Calendar.current
var date = { Date() }
var rng = AnyRandomNumberGenerator(rng: SystemRandomNumberGenerator())
}
var Current = Environment()
extension Date {
var isPointFreeAnniversary: Bool {
let components = Current.calendar.dateComponents([.day, .month], from: self)
return components.day == 29 && components.month == 1
}
}
| 27 | 92 | 0.701912 |
f72b5cd0c1640808d5030d94742d89cd34f3b5e7 | 766 | h | C | cbits/Cbc.h | amosr/limp-cbc | 3d6b9c580c529c0a7151aa7c758305bdf626f0af | [
"MIT"
] | 8 | 2015-05-11T04:18:49.000Z | 2020-02-16T00:14:35.000Z | cbits/Cbc.h | amosr/limp-cbc | 3d6b9c580c529c0a7151aa7c758305bdf626f0af | [
"MIT"
] | 9 | 2015-06-06T22:02:28.000Z | 2020-02-01T22:03:59.000Z | cbits/Cbc.h | amosr/limp-cbc | 3d6b9c580c529c0a7151aa7c758305bdf626f0af | [
"MIT"
] | 4 | 2015-05-20T22:04:53.000Z | 2020-01-29T21:46:25.000Z |
#ifdef FROM_CPP
extern "C" {
#else
typedef struct CbcModel CbcModel;
#endif
CbcModel* newModel();
void freeModel(CbcModel* model);
void loadProblem(CbcModel* model, int ncols, int nrows,
int* starts, int* indices, double* values,
double* collb, double* colub,
double* obj,
double* rowlb, double* rowub);
void setInteger (CbcModel* model, int col);
void branchAndBound (CbcModel* model);
int getNumCols (CbcModel* model);
const double* getBestSolution (CbcModel* model);
void setObjSense(CbcModel* model, double dir);
void setLogLevel(CbcModel* model, int level);
int isProvenInfeasible(CbcModel* model);
double getCoinDblMax();
#ifdef FROM_CPP
}
#endif
| 21.277778 | 66 | 0.654047 |
7fcd0d697f2c5d534226f201e4b7407fdc8c05c9 | 9,345 | go | Go | pkg/util/util.go | christianh814/cli-v2 | 05fdc1b57a5780e4f196f7d291523246dfbc0d76 | [
"Apache-2.0"
] | null | null | null | pkg/util/util.go | christianh814/cli-v2 | 05fdc1b57a5780e4f196f7d291523246dfbc0d76 | [
"Apache-2.0"
] | null | null | null | pkg/util/util.go | christianh814/cli-v2 | 05fdc1b57a5780e4f196f7d291523246dfbc0d76 | [
"Apache-2.0"
] | null | null | null | // Copyright 2022 The Codefresh Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package util
import (
"bytes"
"context"
"fmt"
"io"
"os"
"os/signal"
"regexp"
"strings"
"sync"
"time"
"github.com/argoproj-labs/argocd-autopilot/pkg/kube"
"github.com/briandowns/spinner"
"github.com/codefresh-io/cli-v2/pkg/log"
"github.com/codefresh-io/cli-v2/pkg/reporter"
"github.com/codefresh-io/cli-v2/pkg/store"
kubeutil "github.com/codefresh-io/cli-v2/pkg/util/kube"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
v1 "k8s.io/api/core/v1"
kerrors "k8s.io/apimachinery/pkg/api/errors"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/tools/clientcmd"
)
const (
indentation = " "
)
var (
spinnerCharSet = spinner.CharSets[26]
spinnerDuration = time.Millisecond * 500
appsetFieldRegexp = regexp.MustCompile(`[\./]`)
)
// ContextWithCancelOnSignals returns a context that is canceled when one of the specified signals
// are received
func ContextWithCancelOnSignals(ctx context.Context, sigs ...os.Signal) context.Context {
ctx, cancel := context.WithCancel(ctx)
sig := make(chan os.Signal, 1)
signal.Notify(sig, sigs...)
go func() {
cancels := 0
for {
s := <-sig
cancels++
if cancels == 1 {
log.G(ctx).Printf("got signal: %s", s)
reportCancel(reporter.CANCELED)
cancel()
} else {
reporter.G().Close(reporter.ABRUPTLY_CANCELED, nil)
log.G(ctx).Printf("forcing exit")
os.Exit(1)
}
}
}()
return ctx
}
// Die panics it the error is not nil. If a cause string is provided it will
// be displayed in the error message.
func Die(err error, cause ...string) {
if err != nil {
if len(cause) > 0 {
panic(fmt.Errorf("%s: %w", cause[0], err))
}
panic(err)
}
}
// WithSpinner create a spinner that prints a message and canceled if the
// given context is canceled or the returned stop function is called.
func WithSpinner(ctx context.Context, msg ...string) func() {
if os.Getenv("NO_COLOR") != "" { // https://no-color.org/
log.G(ctx).Info(msg)
return func() {}
}
ctx, cancel := context.WithCancel(ctx)
s := spinner.New(
spinnerCharSet,
spinnerDuration,
)
if len(msg) > 0 {
s.Prefix = msg[0]
}
go func() {
s.Start()
<-ctx.Done()
s.Stop()
fmt.Println("")
}()
return func() {
cancel()
// wait just enough time to prevent logs jumbling between spinner and main flow
time.Sleep(time.Millisecond * 100)
}
}
// Doc returns a string where all the '<BIN>' are replaced with the binary name
// and all the '\t' are replaced with a uniformed indentation using space.
func Doc(doc string) string {
doc = strings.ReplaceAll(doc, "<BIN>", store.Get().BinaryName)
doc = strings.ReplaceAll(doc, "\t", indentation)
return doc
}
type AsyncRunner struct {
wg sync.WaitGroup
errC chan error
}
// NewAsyncRunner initializes a new AsyncRunner that can run up to
// n async operations.
func NewAsyncRunner(n int) *AsyncRunner {
return &AsyncRunner{
wg: sync.WaitGroup{},
errC: make(chan error, n),
}
}
// Run runs another async operation
func (ar *AsyncRunner) Run(f func() error) {
ar.wg.Add(1)
go func() {
defer ar.wg.Done()
if err := f(); err != nil {
ar.errC <- err
}
}()
}
// Wait waits for all async operations to finish and returns an error
// if one of the async operations returned an error, otherwise, returns
// nil.
func (ar *AsyncRunner) Wait() error {
ar.wg.Wait()
select {
case err := <-ar.errC:
return err
default:
return nil
}
}
func EscapeAppsetFieldName(field string) string {
return appsetFieldRegexp.ReplaceAllString(field, "_")
}
func CurrentServer() (string, error) {
configAccess := clientcmd.NewDefaultPathOptions()
conf, err := configAccess.GetStartingConfig()
if err != nil {
return "", err
}
server := conf.Clusters[conf.Contexts[conf.CurrentContext].Cluster].Server
return server, nil
}
func DecorateErrorWithDocsLink(err error, link ...string) error {
if len(link) == 0 {
return fmt.Errorf("%s\nfor more information: %s", err.Error(), store.Get().DocsLink)
}
return fmt.Errorf("%s\nfor more information: %s", err.Error(), link[0])
}
func reportCancel(status reporter.CliStepStatus) {
reporter.G().ReportStep(reporter.CliStepData{
Step: reporter.SIGNAL_TERMINATION,
Status: status,
Description: "Cancelled by an external signal",
Err: nil,
})
}
func IsIP(s string) (bool, error) {
return regexp.MatchString(`^((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$`, s)
}
func RunNetworkTest(ctx context.Context, kubeFactory kube.Factory, urls ...string) error {
const networkTestsTimeout = 120 * time.Second
var testerPodName string
envVars := map[string]string{
"URLS": strings.Join(urls, ","),
"IN_CLUSTER": "1",
}
env := prepareEnvVars(envVars)
client, err := kubeFactory.KubernetesClientSet()
if err != nil {
return fmt.Errorf("failed to create kubernetes client: %w", err)
}
err = kubeutil.LaunchJob(ctx, kubeutil.LaunchJobOptions{
Client: client,
Namespace: store.Get().DefaultNamespace,
JobName: &store.Get().NetworkTesterName,
Image: &store.Get().NetworkTesterImage,
Env: env,
RestartPolicy: v1.RestartPolicyNever,
BackOffLimit: 0,
})
if err != nil {
return err
}
defer func() {
deferErr := client.BatchV1().Jobs(store.Get().DefaultNamespace).Delete(ctx, store.Get().NetworkTesterName, metav1.DeleteOptions{})
if deferErr != nil {
log.G(ctx).Errorf("fail to delete job resource '%s': %s", store.Get().NetworkTesterName, deferErr.Error())
}
}()
defer func(name *string) {
deferErr := client.CoreV1().Pods(store.Get().DefaultNamespace).Delete(ctx, *name, metav1.DeleteOptions{})
if deferErr != nil {
log.G(ctx).Errorf("fail to delete tester pod '%s': %s", testerPodName, deferErr.Error())
}
}(&testerPodName)
log.G(ctx).Info("Running network test...")
ticker := time.NewTicker(5 * time.Second)
defer ticker.Stop()
var podLastState *v1.Pod
timeoutChan := time.After(networkTestsTimeout)
Loop:
for {
select {
case <-ticker.C:
log.G(ctx).Debug("Waiting for network tester to finish")
if testerPodName == "" {
testerPodName, err = getTesterPodName(ctx, client)
if err != nil {
return err
}
}
pod, err := client.CoreV1().Pods(store.Get().DefaultNamespace).Get(ctx, testerPodName, metav1.GetOptions{})
if err != nil {
if statusError, errIsStatusError := err.(*kerrors.StatusError); errIsStatusError {
if statusError.ErrStatus.Reason == metav1.StatusReasonNotFound {
log.G(ctx).Debug("Network tester pod not found")
}
}
}
if len(pod.Status.ContainerStatuses) == 0 {
log.G(ctx).Debug("Network tester pod: creating container")
continue
}
if pod.Status.ContainerStatuses[0].State.Running != nil {
log.G(ctx).Debug("Network tester pod: running")
}
if pod.Status.ContainerStatuses[0].State.Waiting != nil {
log.G(ctx).Debug("Network tester pod: waiting")
}
if pod.Status.ContainerStatuses[0].State.Terminated != nil {
log.G(ctx).Debug("Network tester pod: terminated")
podLastState = pod
break Loop
}
case <-timeoutChan:
return fmt.Errorf("network test timeout reached!")
}
}
return checkPodLastState(ctx, client, testerPodName, podLastState)
}
func prepareEnvVars(vars map[string]string) []v1.EnvVar {
var env []v1.EnvVar
for key, value := range vars {
env = append(env, v1.EnvVar{
Name: key,
Value: value,
})
}
return env
}
func getTesterPodName(ctx context.Context, client kubernetes.Interface) (string, error) {
pods, err := client.CoreV1().Pods(store.Get().DefaultNamespace).List(ctx, metav1.ListOptions{})
if err != nil {
return "", fmt.Errorf("failed to get pods from cluster: %w", err)
}
for _, pod := range pods.Items {
if pod.ObjectMeta.GenerateName == store.Get().NetworkTesterGenerateName {
return pod.ObjectMeta.Name, nil
}
}
return "", nil
}
func checkPodLastState(ctx context.Context, client kubernetes.Interface, name string, podLastState *v1.Pod) error {
req := client.CoreV1().Pods(store.Get().DefaultNamespace).GetLogs(name, &v1.PodLogOptions{})
podLogs, err := req.Stream(ctx)
if err != nil {
return fmt.Errorf("Failed to get network-tester pod logs: %w", err)
}
defer podLogs.Close()
logsBuf := new(bytes.Buffer)
_, err = io.Copy(logsBuf, podLogs)
if err != nil {
return fmt.Errorf("Failed to read network-tester pod logs: %w", err)
}
logs := strings.Trim(logsBuf.String(), "\n")
log.G(ctx).Debug(logs)
if podLastState.Status.ContainerStatuses[0].State.Terminated.ExitCode != 0 {
terminationMessage := strings.Trim(podLastState.Status.ContainerStatuses[0].State.Terminated.Message, "\n")
return fmt.Errorf("Network test failed with: %s", terminationMessage)
}
return nil
}
| 26.853448 | 132 | 0.684109 |
80dc3eee362c11c6e36bd9aa7ff6e503f2211ccf | 2,973 | java | Java | src/main/java/org/apache/sysml/udf/lib/DynamicReadMatrixCP.java | keshavbashyal/incubator-systemml | 5d09d27ad8dc644ed930a8f8bbba70e26c13de7d | [
"Apache-2.0"
] | 1 | 2021-05-31T19:50:45.000Z | 2021-05-31T19:50:45.000Z | src/main/java/org/apache/sysml/udf/lib/DynamicReadMatrixCP.java | keshavbashyal/incubator-systemml | 5d09d27ad8dc644ed930a8f8bbba70e26c13de7d | [
"Apache-2.0"
] | null | null | null | src/main/java/org/apache/sysml/udf/lib/DynamicReadMatrixCP.java | keshavbashyal/incubator-systemml | 5d09d27ad8dc644ed930a8f8bbba70e26c13de7d | [
"Apache-2.0"
] | null | null | null | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.sysml.udf.lib;
import org.apache.sysml.parser.DMLTranslator;
import org.apache.sysml.runtime.matrix.data.InputInfo;
import org.apache.sysml.runtime.matrix.data.MatrixBlock;
import org.apache.sysml.runtime.matrix.data.OutputInfo;
import org.apache.sysml.runtime.util.DataConverter;
import org.apache.sysml.udf.FunctionParameter;
import org.apache.sysml.udf.Matrix;
import org.apache.sysml.udf.PackageFunction;
import org.apache.sysml.udf.PackageRuntimeException;
import org.apache.sysml.udf.Scalar;
import org.apache.sysml.udf.Matrix.ValueType;
/**
*
*
*/
public class DynamicReadMatrixCP extends PackageFunction
{
private static final long serialVersionUID = 1L;
private Matrix _ret;
@Override
public int getNumFunctionOutputs()
{
return 1;
}
@Override
public FunctionParameter getFunctionOutput(int pos)
{
return _ret;
}
@Override
public void execute()
{
try
{
String fname = ((Scalar) this.getFunctionInput(0)).getValue();
Integer m = Integer.parseInt(((Scalar) this.getFunctionInput(1)).getValue());
Integer n = Integer.parseInt(((Scalar) this.getFunctionInput(2)).getValue());
String format = ((Scalar) this.getFunctionInput(3)).getValue();
InputInfo ii = InputInfo.stringToInputInfo(format);
OutputInfo oi = OutputInfo.BinaryBlockOutputInfo;
MatrixBlock mbTmp = DataConverter.readMatrixFromHDFS(fname, ii, m, n, DMLTranslator.DMLBlockSize, DMLTranslator.DMLBlockSize);
String fnameTmp = createOutputFilePathAndName("TMP");
_ret = new Matrix(fnameTmp, m, n, ValueType.Double);
_ret.setMatrixDoubleArray(mbTmp, oi, ii);
//NOTE: The packagesupport wrapper creates a new MatrixObjectNew with the given
// matrix block. This leads to a dirty state of the new object. Hence, the resulting
// intermediate plan variable will be exported in front of MR jobs and during this export
// the format will be changed to binary block (the contract of external functions),
// no matter in which format the original matrix was.
}
catch(Exception e)
{
throw new PackageRuntimeException("Error executing dynamic read of matrix",e);
}
}
}
| 34.172414 | 132 | 0.749411 |
71a221b9588c7011453e4843d7b23ca066c75178 | 941 | tsx | TypeScript | source/components/Divider/Divider.tsx | EasySimple/fishd-mobile | 6a1da1ae9088b5d248e9f9a5b10db94a4f70463a | [
"MIT"
] | 55 | 2020-01-21T06:50:33.000Z | 2022-03-28T02:36:47.000Z | source/components/Divider/Divider.tsx | hangaoke1/fishd-mobile | db4b2cd6c29723b8fc28c4fd81c688dcd5b544c5 | [
"MIT"
] | 21 | 2020-05-21T07:30:41.000Z | 2022-03-06T03:02:51.000Z | source/components/Divider/Divider.tsx | hangaoke1/fishd-mobile | db4b2cd6c29723b8fc28c4fd81c688dcd5b544c5 | [
"MIT"
] | 9 | 2021-04-02T06:24:13.000Z | 2021-12-03T07:16:00.000Z | import classnames from 'classnames';
import * as React from 'react';
import { DividerPropsType } from './PropsType';
export interface DividerProps extends DividerPropsType {
prefixCls?: string;
className?: string;
style?: React.CSSProperties;
}
class Divider extends React.Component<DividerProps, any> {
static defaultProps = {
prefixCls: 'fm-divider',
dashed: false,
hairline: true,
contentPosition: 'center',
};
render() {
const { className, prefixCls, dashed, hairline, contentPosition, style, children, ...restProps } = this.props;
const wrapCls = classnames(prefixCls, className, {
[`${prefixCls}--dashed`]: dashed,
[`${prefixCls}--hairline`]: hairline,
[`${prefixCls}--content-${contentPosition}`]: children,
});
return (
<div role="separator" {...restProps} style={style} className={wrapCls}>
{children}
</div>
);
}
}
export default Divider;
| 26.885714 | 114 | 0.658874 |
90ea5cd2bc780ca1bd43b58ba6c69c50884f9118 | 531 | py | Python | programs/pattern3.py | VishalAgr11/CSE-programs | 082c984908886adb09fc1a8dcd60482bdd99dbfe | [
"MIT"
] | 1 | 2021-11-15T15:21:29.000Z | 2021-11-15T15:21:29.000Z | programs/pattern3.py | VishalAgr11/CSE-programs | 082c984908886adb09fc1a8dcd60482bdd99dbfe | [
"MIT"
] | null | null | null | programs/pattern3.py | VishalAgr11/CSE-programs | 082c984908886adb09fc1a8dcd60482bdd99dbfe | [
"MIT"
] | 2 | 2021-11-14T01:45:51.000Z | 2021-11-15T15:21:08.000Z | '''
*000*000*
0*00*00*0
00*0*0*00
000***000
Utkarsh
'''
l=int(input())
b=int(input())
print("With for\n")
for i in range(1,b+1):
for j in range(1,l+1):
if j==(l+1)//2 or j==i or j==(l+1)-i:
print('*',end='')
else:
print('0',end='')
print()
i=1
j=1
print("\nWith while\n")
while i<=b:
while j<=l:
if j==(l+1)//2 or j==i or j==(l+1)-i:
print('*',end='')
else:
print('0',end='')
j+=1
j=1
print()
i+=1
| 14.75 | 45 | 0.403013 |
edfc566d63bb71179413202d81793fd73244855d | 168 | sql | SQL | SQL/relacionar tabelas e group by.sql | ThiagoMendes1/exercicios-Full-Stack | 2ada8a0bbd3a9383de061863700f4ab9d36b9ad9 | [
"MIT"
] | null | null | null | SQL/relacionar tabelas e group by.sql | ThiagoMendes1/exercicios-Full-Stack | 2ada8a0bbd3a9383de061863700f4ab9d36b9ad9 | [
"MIT"
] | 1 | 2020-08-29T21:43:11.000Z | 2020-08-29T21:43:11.000Z | SQL/relacionar tabelas e group by.sql | ThiagoMendes1/exercicios-Full-Stack | 2ada8a0bbd3a9383de061863700f4ab9d36b9ad9 | [
"MIT"
] | null | null | null | select nomecategoria, count(produtoID) as total
from produtos p
inner join categorias c on p.categoriaID = c.categoriaID
group by p.categoriaID
order by total desc | 33.6 | 61 | 0.797619 |
370a3b82d010355b75109becb293c73b17108f1a | 631 | dart | Dart | seed_reader/test/routes/home/home_page_test.dart | CristianDRM/mobile-test | e82777ba7a2547b9eef693e2999c7fadcb3c0b09 | [
"MIT"
] | null | null | null | seed_reader/test/routes/home/home_page_test.dart | CristianDRM/mobile-test | e82777ba7a2547b9eef693e2999c7fadcb3c0b09 | [
"MIT"
] | null | null | null | seed_reader/test/routes/home/home_page_test.dart | CristianDRM/mobile-test | e82777ba7a2547b9eef693e2999c7fadcb3c0b09 | [
"MIT"
] | null | null | null | import 'package:flutter_test/flutter_test.dart';
import 'package:seed_reader/generated/l10n.dart';
import 'package:seed_reader/routes/home/components/home_actions_button.dart';
import 'package:seed_reader/routes/home/home_page.dart';
import '../../common/base_testable_widget.dart';
void main() {
testWidgets('render components', (WidgetTester tester) async {
await tester.pumpWidget(
const BaseWidgetTest(
child: HomePage(),
),
);
await tester.pumpAndSettle();
expect(find.text(S.current.homePageTitle), findsOneWidget);
expect(find.byType(HomeActionsButton), findsOneWidget);
});
}
| 30.047619 | 77 | 0.733756 |
80af9f99b4a551cdd64dae82bc313a8d221b021e | 5,439 | java | Java | core/src/main/java/org/jfantasy/framework/lucene/handler/PropertyFieldHandler.java | limaofeng/jfantasy-framework | 781246acef1b32ba3a20dc0d988dcd31df7e3e21 | [
"MIT"
] | 1 | 2021-08-13T15:25:01.000Z | 2021-08-13T15:25:01.000Z | core/src/main/java/org/jfantasy/framework/lucene/handler/PropertyFieldHandler.java | limaofeng/jfantasy-framework | 781246acef1b32ba3a20dc0d988dcd31df7e3e21 | [
"MIT"
] | 1 | 2021-09-11T01:28:09.000Z | 2021-09-11T13:33:40.000Z | core/src/main/java/org/jfantasy/framework/lucene/handler/PropertyFieldHandler.java | limaofeng/jfantasy-framework | 781246acef1b32ba3a20dc0d988dcd31df7e3e21 | [
"MIT"
] | null | null | null | package org.jfantasy.framework.lucene.handler;
import org.apache.lucene.document.Document;
import org.jfantasy.framework.lucene.annotations.IndexProperty;
import org.jfantasy.framework.util.reflect.Property;
public class PropertyFieldHandler extends AbstractFieldHandler {
public PropertyFieldHandler(Object obj, Property property, String prefix) {
super(obj, property, prefix);
}
@Override
public void handle(Document doc) {
IndexProperty ip = this.property.getAnnotation(IndexProperty.class);
process(doc, ip.analyze(), ip.store(), ip.boost());
}
protected void process(Document doc, boolean analyze, boolean store, float boost) {
Class<?> type = this.property.getPropertyType();
if (type.isArray()) {
processArray(doc, analyze, store, boost);
} else {
processPrimitive(doc, analyze, store, boost);
}
}
private void processArray(Document doc, boolean analyze, boolean store, float boost) {
Object objValue = this.property.getValue(this.obj);
if (objValue == null) {
return;
}
Class<?> type = this.property.getPropertyType();
String fieldName = this.prefix + this.property.getName();
// org.apache.lucene.document.Field f = new
// org.apache.lucene.document.Field(fieldName,
// getArrayString(objValue, type.getComponentType()), store ? Field.Store.YES :
// Field.Store.NO,
// analyze ? Field.Index.ANALYZED : Field.Index.NOT_ANALYZED);
// f.setBoost(boost);
// doc.add(f);
}
private void processPrimitive(Document doc, boolean analyze, boolean store, float boost) {
Object objValue = this.property.getValue(this.obj);
if (objValue == null) {
return;
}
Class<?> type = this.property.getPropertyType();
String fieldName = this.prefix + this.property.getName();
// IndexableField f = null;
// if (DataType.isString(type) || type.isEnum()) { //TODO 枚举使用字符串的方式处理
// f = new org.apache.lucene.document.Field(fieldName, objValue.toString(),
// store ?
// Field.Store.YES : Field.Store.NO, analyze ? Field.Index.ANALYZED :
// Field.Index.NOT_ANALYZED);
// } else if ((DataType.isBoolean(type)) || (DataType.isBooleanObject(type))) {
// f = new org.apache.lucene.document.Field(fieldName, objValue.toString(),
// store ?
// Field.Store.YES : Field.Store.NO, Field.Index.NOT_ANALYZED);
// } else if ((DataType.isChar(type)) || (DataType.isCharObject(type))) {
// f = new org.apache.lucene.document.Field(fieldName, objValue.toString(),
// store ?
// Field.Store.YES : Field.Store.NO, Field.Index.NOT_ANALYZED);
// } else if ((DataType.isInteger(type)) || (DataType.isIntegerObject(type))) {
// int v = Integer.parseInt(objValue.toString());
// f = new NumericDocValuesField(fieldName, store ? Field.Store.YES :
// Field.Store.NO,
// true).setIntValue(v);
// } else if ((DataType.isLong(type)) || (DataType.isLongObject(type))) {
// long v = Long.parseLong(objValue.toString());
// f = new NumericField(fieldName, store ? Field.Store.YES : Field.Store.NO,
// true).setLongValue(v);
// } else if ((DataType.isShort(type)) || (DataType.isShortObject(type))) {
// short v = Short.parseShort(objValue.toString());
// f = new NumericField(fieldName, store ? Field.Store.YES : Field.Store.NO,
// true).setIntValue(v);
// } else if ((DataType.isFloat(type)) || (DataType.isFloatObject(type))) {
// float v = Float.parseFloat(objValue.toString());
// f = new NumericField(fieldName, store ? Field.Store.YES : Field.Store.NO,
// true).setFloatValue(v);
// } else if ((DataType.isDouble(type)) || (DataType.isDoubleObject(type))) {
// double v = Double.parseDouble(objValue.toString());
// f = new NumericField(fieldName, store ? Field.Store.YES : Field.Store.NO,
// true).setDoubleValue(v);
// } else if (DataType.isDate(type)) {
// Date date = (Date) objValue;
// f = new NumericField(fieldName, store ? Field.Store.YES : Field.Store.NO,
// true).setLongValue(date.getTime());
// } else if (DataType.isTimestamp(type)) {
// Timestamp ts = (Timestamp) objValue;
// f = new NumericField(fieldName, store ? Field.Store.YES : Field.Store.NO,
// true).setLongValue(ts.getTime());
// } else if ((DataType.isSet(type)) || (DataType.isList(type))) {
// Collection<?> coll = (Collection<?>) objValue;
// StringBuilder sb = new StringBuilder();
// for (Object o : coll) {
// sb.append(o).append(";");
// }
// f = new org.apache.lucene.document.Field(fieldName, sb.toString(), store ?
// Field.Store.YES : Field.Store.NO, analyze ? Field.Index.ANALYZED :
// Field.Index.NOT_ANALYZED);
// } else if (DataType.isMap(type)) {
// Map<?, ?> map = (Map<?, ?>) objValue;
// StringBuilder sb = new StringBuilder();
// for (Map.Entry<?, ?> entry : map.entrySet()) {
// sb.append(entry.getValue()).append(";");
// }
// f = new org.apache.lucene.document.Field(fieldName, sb.toString(), store ?
// Field.Store.YES : Field.Store.NO, analyze ? Field.Index.ANALYZED :
// Field.Index.NOT_ANALYZED);
// } else if (BigDecimal.class.equals(type)) {
// f = new NumericField(fieldName, store ? Field.Store.YES : Field.Store.NO,
// true).setDoubleValue(((BigDecimal) objValue).doubleValue());
// }
// if (f != null) {
// f.setBoost(boost);
// doc.add(f);
// }
}
}
| 44.950413 | 92 | 0.65012 |
5b03aebfe740d45d6783b4af3b78df3457f4c2ab | 3,124 | lua | Lua | lib/resty/statsd.lua | metwork-framework/lua-resty-statsd | 166b3a1db02d3e92961d298c1ecf58f668211814 | [
"BSD-3-Clause"
] | null | null | null | lib/resty/statsd.lua | metwork-framework/lua-resty-statsd | 166b3a1db02d3e92961d298c1ecf58f668211814 | [
"BSD-3-Clause"
] | 2 | 2018-10-01T08:44:37.000Z | 2019-01-08T09:12:39.000Z | lib/resty/statsd.lua | metwork-framework/lua-resty-statsd | 166b3a1db02d3e92961d298c1ecf58f668211814 | [
"BSD-3-Clause"
] | null | null | null | local _M = {}
require "resty.core"
local mt = { __index = _M }
function _M.new(options)
options = options or {}
local self = {
host = options.host or "127.0.0.1",
port = options.port or 8125,
tags = options.tags or {},
timeout = options.timeout or 250,
queue = {},
delay = (options.delay or 500) / 1000,
timer_started = false
}
return setmetatable(self, mt)
end
local function create_message(self, key, value, kind, sample_rate, tags)
local rate = ""
if sample_rate and sample_rate ~= 1 then
rate = "|@"..sample_rate
end
local new_table = {}
local k = nil
local v = nil
if self.tags ~= nil then
for k, v in pairs(self.tags) do
table.insert(new_table, ",")
table.insert(new_table, k)
table.insert(new_table, "=")
table.insert(new_table, v)
end
end
if tags ~= nil then
for k, v in pairs(tags) do
table.insert(new_table, ",")
table.insert(new_table, k)
table.insert(new_table, "=")
table.insert(new_table, v)
end
end
local tag_string = table.concat(new_table)
local message = {
key,
tag_string,
":",
value,
"|",
kind,
rate,
"\n"
}
return message
end
local send_messages
local function set_timer(self)
if not self.timer_started then
local ok, err = ngx.timer.at(self.delay, send_messages, self)
self.timer_started = ok
end
end
send_messages = function(premature, self)
if premature then
return
end
-- mark as not started. openresty has no "repeat" so we must do logic ourselves
self.timer_started = false
local q = self.queue
if #q == 0 then
set_timer(self)
return
end
local sock = ngx.socket.udp()
local ok, err = sock:setpeername(self.host, self.port)
if not ok then
ngx.log(ngx.ERR, "setpeername failed for ", self.host, ":", self.port, " => ", err)
self.queue = {}
set_timer(self)
return
end
sock:settimeout(self.timeout)
for i=1,#q do
if q[i] ~= nil then
local message = table.concat(q[i])
local ok, err = sock:send(message)
if not ok then
ngx.log(ngx.ERR, "send failed for ", self.host, ":", self.port, " => ", err)
end
end
end
sock:close()
self.queue = {}
set_timer(self)
end
local insert = table.insert
local function queue(self, key, value, kind, sample_rate, tags)
local message = create_message(self, key, value, kind, sample_rate, tags)
insert(self.queue, message)
set_timer(self)
end
function _M.gauge(self, key, value, sample_rate, tags)
return queue(self, key, value, "g", sample_rate, tags)
end
function _M.count(self, key, value, sample_rate, tags)
return queue(self, key, value, "c", sample_rate, tags)
end
function _M.timing(self, key, value, tags)
return queue(self, key, value, "ms", nil, tags)
end
return _M
| 24.40625 | 92 | 0.580666 |
8cb07c6b194e2156ccd919a2d6073a2ea2e1c5ed | 396 | swift | Swift | PinPoint/NetworkServices/UserModel.swift | AaronCab/PinPoint | 80a68bbe2c535288c515b971949354624931f164 | [
"MIT"
] | 1 | 2019-05-29T21:12:23.000Z | 2019-05-29T21:12:23.000Z | PinPoint/NetworkServices/UserModel.swift | AaronCab/PinPoint | 80a68bbe2c535288c515b971949354624931f164 | [
"MIT"
] | 5 | 2019-04-09T20:42:47.000Z | 2019-05-10T15:55:57.000Z | PinPoint/NetworkServices/UserModel.swift | AaronCab/PinPoint | 80a68bbe2c535288c515b971949354624931f164 | [
"MIT"
] | null | null | null | //
// UserModel.swift
// PinPoint
//
// Created by Aaron Cabreja on 4/10/19.
// Copyright © 2019 Pursuit. All rights reserved.
//
import Foundation
struct UserModel: Codable {
let name: String
let lat: Double
let long: Double
let photo: String
let interst1: String
let interest2: String
let interest3: String
let interest4: String
let interest5: String
}
| 18.857143 | 50 | 0.671717 |
17652f66a852ffd16ff9056f0bfbfd67af00904c | 5,750 | htm | HTML | gerandotexto.htm | EditoraFacil/SeuLivro | a794bd519a0b287afee23254a9f90292f84b87fd | [
"CC-BY-3.0"
] | null | null | null | gerandotexto.htm | EditoraFacil/SeuLivro | a794bd519a0b287afee23254a9f90292f84b87fd | [
"CC-BY-3.0"
] | null | null | null | gerandotexto.htm | EditoraFacil/SeuLivro | a794bd519a0b287afee23254a9f90292f84b87fd | [
"CC-BY-3.0"
] | null | null | null | <html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=windows-1252">
<title>Gerando Texto</title>
<base target="mostra">
<p>
<a target="_blank" href="http://www.livropublicado.com.br/">
<img border="0" src="http://www.livropublicado.com.br/images/image001.png" width="300" height="78" align="left"></a></p>
<div align="center">
<center>
<table border="0" cellpadding="0" cellspacing="0" style="border-collapse: collapse" bordercolor="#111111" width="51%">
<tr>
<td width="200%" background="http://4.bp.blogspot.com/-4SHsamqjaKQ/U5ILVYfVQ0I/AAAAAAAADyo/f185JxqqC90/s1600/gradiente-office-como-usar-michael-jackson-apenas-um-show.PNG">
<p align="center"><form name='formulario' method='get' action='http://baixargospelfacil.esy.es/gerandotexto.php'>
<p align="center">
</p>
<p align="center">
<b><font size="5" color="#FFFFFF">Texto:</font></b></p>
<p align="center">
<input type="text" name="a1" size="56" style="color: #800000; font-weight: bold"></p>
<p align="center">
<b><font size="4" color="#FFFFFF">Fonte:</font></b> <select size="1" name="a2" style="color: #800000; font-weight: bold">
<option>Akronim</option>
<option>Alex Brush</option>
<option>Alfa Slab One</option>
<option>Allerta Stencil</option>
<option>Anton</option>
<option>Archivo Black</option>
<option>Asset</option>
<option>Audiowide</option>
<option>Bangers</option>
<option>Bevan</option>
<option>Black Ops One</option>
<option>Bowlby One SC</option>
<option>Bungee Inline</option>
<option>Bungee Outline</option>
<option>Bungee shade</option>
<option>Bungee</option>
<option>Butcherman</option>
<option>Cabin Sketch</option>
<option>Calligraffitti</option>
<option>Ceviche One</option>
<option>Chango</option>
<option>Chewy</option>
<option>Codystar</option>
<option>Coiny</option>
<option>Crafty Girls</option>
<option>Creepster</option>
<option>Diplomata SC</option>
<option>Diplomata</option>
<option>Eagle Lake</option>
<option>Ewert</option>
<option>Fascinate Iline</option>
<option>Fascinate</option>
<option>Faster One</option>
<option>Finger Paint</option>
<option>Flavors</option>
<option>Freckle Face</option>
<option>Fredoka One</option>
<option>Frijole</option>
<option>Fruktur</option>
<option>Gloria Hallelujah</option>
<option>Great Vibes</option>
<option>Hanalei Fill</option>
<option>Hanalei</option>
<option>Handlee</option>
<option>Holtwood One SC</option>
<option>Iceberg</option>
<option>Kaushan Script</option>
<option>Kavoon</option>
<option>Kumar One Outline</option>
<option>Kumar One</option>
<option>Lemon</option>
<option>Lobster Two</option>
<option>Londrina Outline</option>
<option>Londrina Shadow</option>
<option>Luckiest Guy</option>
<option>Meddon</option>
<option>Merienda One</option>
<option>Merienda</option>
<option>Miltonian Tattoo</option>
<option>Miltonian</option>
<option>Modak</option>
<option>Molle</option>
<option>Monoton</option>
<option>Mystery Quest</option>
<option>New Rocker</option>
<option>Niconne</option>
<option>Nosifer</option>
<option>Oleo Script</option>
<option>Orbriton</option>
<option>Parisienne</option>
<option>Patua One</option>
<option>Permanent Marker</option>
<option>Piedra</option>
<option>Plaster</option>
<option>Poiret One</option>
<option>Racing Sans One</option>
<option>Rammetto One</option>
<option>Righteous</option>
<option>Rock Salt</option>
<option>Ruslan Display</option>
<option>Russo One</option>
<option>Ruthie</option>
<option>Rye</option>
<option>Sacramento</option>
<option>Sancreek</option>
<option>Satisfy</option>
<option>Shojumaru</option>
<option>Shrikhand</option>
<option>Sigmar One</option>
<option>Six Caps</option>
<option>Slackey</option>
<option>Special Elite</option>
<option>Syncopate</option>
<option>Tangerine</option>
<option>Trade Winds</option>
<option>Ultra</option>
<option>Uncial Anciqua</option>
<option>Vast Shadow</option>
<option>Wallpoet</option>
<option>Walter Turncoat</option>
<option>Wendy One</option>
<option>Yellowtail</option>
<option>Yeseva One</option>
</select> <b><font size="4"><font color="#FFFFFF">Cor:</font> </font></b>
<input type="text" name="a3" size="24" style="color: #800000; font-weight: bold"></p>
<p align="center">
<font color="#FFFFFF"><b><font size="4">Tamanho:</font></b> </font> <input type="text" name="a4" size="16" style="color: #800000; font-weight: bold" value="60"></p>
<p align="center">
</p>
</p>
<p align="center">
<input type='submit' name='btnEnviarDados' value='Enviar' style="font-size: 18 pt; color: #800000; font-weight: bold; border: 2px solid #FFFFFF; padding-left: 4; padding-right: 4; padding-top: 1; padding-bottom: 1">
<p align="center">
<b><font style="font-size: 16pt"><font color="#FFFF00">Cores mais usadas:</font> <font color="#FFFFFF">
white -</font>Black<font color="#FFFFFF"> - </font><font color="#0000FF">Blue</font>
- <font color="#FF0000">Red</font> - <font color="#008000">Green</font> -
<font color="#FFFF00">Yellow</font> </font></b>
</form>
</p>
</td>
</tr>
</table>
</center>
</div>
<p align="center">
<p align="center">
<p align="center">
<p align="center"><b><font size="4">Em Texto você escreve a palavra que desejar
| Em Fonte escolha o nome na opção veja os
exemplos abaixo</font></b></p>
<p align="center"><b><font size="4">Em Cor você pode colocar o nome, o numero ou
o código da cor
da lista abaixo | Em Tamanho digite o tamanho da fonte |
<a href="http://www.livropublicado.com.br/exemplos.htm">Voltar</a></font></b></p>
<p align="center">
<p align="center">
<iframe name="mostra" width="100%" height="73%" border="0" frameborder="0" align="middle" src="http://www.livropublicado.com.br/exemplos.htm" scrolling="no">
</iframe></p>
| 31.767956 | 216 | 0.709913 |
b0af864f6dfa841c64e08fdc41f93db9d07fc802 | 1,262 | swift | Swift | Yelp/FilterSettings.swift | seanmcr/yelp | c2a500bd91ca210bd522e8c252effc611da32765 | [
"Apache-2.0"
] | null | null | null | Yelp/FilterSettings.swift | seanmcr/yelp | c2a500bd91ca210bd522e8c252effc611da32765 | [
"Apache-2.0"
] | 1 | 2017-04-10T07:53:33.000Z | 2017-04-10T22:28:07.000Z | Yelp/FilterSettings.swift | seanmcr/yelp | c2a500bd91ca210bd522e8c252effc611da32765 | [
"Apache-2.0"
] | null | null | null | //
// FilterSettings.swift
// Yelp
//
// Created by Sean McRoskey on 4/8/17.
// Copyright © 2017 Timothy Lee. All rights reserved.
//
import Foundation
class FilterSettings {
var onlyDeals: Bool?
var sortMode: YelpSortMode?
var categories: [String]?
var distance: Int?
func saveToUserDefaults(){
let userDefaults = UserDefaults.standard
userDefaults.setValuesForKeys([
"onlyDeals": onlyDeals as Any,
"sortMode": sortMode?.rawValue as Any,
"categories": categories as Any,
"distance": distance as Any
])
userDefaults.synchronize()
}
static func getFromUserDefaults() -> FilterSettings {
let filterSettings = FilterSettings()
let userDefaults = UserDefaults.standard
filterSettings.onlyDeals = userDefaults.value(forKey: "onlyDeals") as? Bool
let sortMode = userDefaults.value(forKey: "sortMode") as? Int
filterSettings.sortMode = (sortMode != nil) ? YelpSortMode(rawValue: sortMode!) : nil
filterSettings.categories = userDefaults.value(forKey: "categories") as? [String]
filterSettings.distance = userDefaults.value(forKey: "distance") as? Int
return filterSettings
}
}
| 32.358974 | 93 | 0.655309 |
dcd300a6d2e8bb84051f250cad9846653e7d1178 | 885 | swift | Swift | ExchangeRate/MainTableViewCell.swift | alexktchen/ExchangeRate | 08af48307149e5a4a41af6a0d36a37f970a17364 | [
"MIT"
] | 1 | 2017-05-11T11:35:47.000Z | 2017-05-11T11:35:47.000Z | ExchangeRate/MainTableViewCell.swift | alexktchen/ExchangeRate | 08af48307149e5a4a41af6a0d36a37f970a17364 | [
"MIT"
] | null | null | null | ExchangeRate/MainTableViewCell.swift | alexktchen/ExchangeRate | 08af48307149e5a4a41af6a0d36a37f970a17364 | [
"MIT"
] | null | null | null | //
// MainTableViewCell.swift
// ExchangeRate
//
// Created by Alex Chen on 2015/9/24.
// Copyright © 2015 Alex Chen. All rights reserved.
//
import Foundation
import UIKit
import Core
class MainTableViewCell: UITableViewCell {
@IBOutlet weak var displayNameLabel: UILabel!
@IBOutlet weak var flagImage: UIImageView!
@IBOutlet weak var priceLabel: UILabel!
@IBOutlet weak var currencyLabel: UILabel!
@IBOutlet weak var symbolLabel: UILabel!
internal required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)!
}
override func drawRect(rect: CGRect) {
self.flagImage.layer.cornerRadius = self.flagImage.frame.size.width / 2
self.flagImage.clipsToBounds = true
self.flagImage.layer.borderWidth = 2.0
self.flagImage.layer.borderColor = CustomColors.lightGrayColor.CGColor
}
} | 26.818182 | 79 | 0.698305 |
04bad11c3dd421b8b06b15c2f5a345dfc3f8e484 | 3,147 | html | HTML | w/jul05_esv.html | RubeRad/dailycc | 313924b5cda06c621d2de629ce9d029bba5d00bd | [
"MIT"
] | 1 | 2021-01-05T04:16:11.000Z | 2021-01-05T04:16:11.000Z | w/jul05_esv.html | RubeRad/dailycc | 313924b5cda06c621d2de629ce9d029bba5d00bd | [
"MIT"
] | 10 | 2020-01-29T04:59:20.000Z | 2022-03-12T22:45:00.000Z | w/jul05_esv.html | RubeRad/dailycc | 313924b5cda06c621d2de629ce9d029bba5d00bd | [
"MIT"
] | 2 | 2020-01-03T16:54:52.000Z | 2020-03-31T16:52:43.000Z | <h2><center>Westminster Larger Catechism</center></h2>
<p><a name="q99" title="q99"></a>Q. 99. <b>What rules are to be observed for the right understanding of the ten commandments?</b><br />
A. For the right understanding of the ten commandments, these rules are to be observed:</p><p>1. That the law is perfect, and bindeth everyone to full conformity in the whole man unto the righteousness thereof, and unto entire obedience forever; so as to require the utmost perfection of every duty, and to forbid the least degree of every sin.<sup><a href="http://esvonline.org/Psalm19:7,James2:10,Matthew5:21-22">[422]</a></sup></p><p>2. That it is spiritual, and so reacheth the understanding, will, affections, and all other powers of the soul; as well as words, works, and gestures.<sup><a href="http://esvonline.org/Romans7:14,Deuteronomy6:5,Matthew22:37-39,Matthew5:21-22,27-28,33-34,37-39,43-44">[423]</a></sup></p><p>3. That one and the same thing, in divers respects, is required or forbidden in several commandments.<sup><a href="http://esvonline.org/Colossians3:5,Amos8:5,Proverbs1:19;1Timothy6:10">[424]</a></sup></p><p>4. That as, where a duty is commanded, the contrary sin is forbidden;<sup><a href="http://esvonline.org/Isaiah58:13,Deuteronomy6:13,Matthew4:9-10,Matthew15:4-6">[425]</a></sup> and, where a sin is forbidden, the contrary duty is commanded:<sup><a href="http://esvonline.org/Matthew5:21-25,Ephesians4:28">[426]</a></sup> so, where a promise is annexed, the contrary threatening is included;<sup><a href="http://esvonline.org/Exodus20:12,Proverbs30:17">[427]</a></sup> and, where a threatening is annexed, the contrary promise is included.<sup><a href="http://esvonline.org/Jeremiah18:7-8,Exodus20:7,Psalm15:1,4-5,Psalm24:4-5">[428]</a></sup></p><p>5. That what God forbids, is at no time to be done;<sup><a href="http://esvonline.org/Job13:7-8,Romans3:8,Job36:21,Hebrews11:25">[429]</a></sup> what he commands, is always our duty;<sup><a href="http://esvonline.org/Deuteronomy4:8-9">[430]</a></sup> and yet every particular duty is not to be done at all times.<sup><a href="http://esvonline.org/Matthew12:7">[431]</a></sup></p><p>6. That under one sin or duty, all of the same kind are forbidden or commanded; together with all the causes, means, occasions, and appearances thereof, and provocations thereunto.<sup><a href="http://esvonline.org/Matthew5:21-22,27-28,Matthew15:4-6,Hebrews10:24-25;1Thessalonians5:22,Jude23,Galatians5:26,Colossians3:21">[432]</a></sup></p><p>7. That what is forbidden or commanded to ourselves, we are bound, according to our places to endeavour that it may be avoided or performed by others, according to the duty of their places.<sup><a href="http://esvonline.org/Exodus20:10,Leviticus19:17,Genesis18:19,Joshua14:15,Deuteronomy6:6-7">[433]</a></sup></p><p>8. That in what is commanded to others, we are bound, according to our places and callings, to be helpful to them;<sup><a href="http://esvonline.org/2Corinthians1:24">[434]</a></sup> and to take heed of partaking with others in what is forbidden them.<sup><a href="http://esvonline.org/1Timothy5:22,Ephesians5:11">[435]</a></sup></p>
| 786.75 | 2,955 | 0.738799 |
e595b2e4f889b3f4dc52768cd27370344b4a9f33 | 193 | kt | Kotlin | app/src/main/java/com/example/malfoodware/DataLayer/DBInterface.kt | MikeAllport/FoodDiary | e369ac67843b37ffd246336012e2b7d3169d59bd | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/example/malfoodware/DataLayer/DBInterface.kt | MikeAllport/FoodDiary | e369ac67843b37ffd246336012e2b7d3169d59bd | [
"Apache-2.0"
] | 4 | 2021-01-05T18:12:20.000Z | 2021-01-05T18:19:09.000Z | app/src/main/java/com/example/malfoodware/DataLayer/DBInterface.kt | MikeAllport/FoodDiary | e369ac67843b37ffd246336012e2b7d3169d59bd | [
"Apache-2.0"
] | null | null | null | package com.example.malfoodware.DataLayer
import android.database.sqlite.SQLiteDatabase
interface DBInterface {
fun onCreate(db: SQLiteDatabase?)
fun deleteTable(db: SQLiteDatabase)
} | 24.125 | 45 | 0.803109 |
a641b326bac03c2aa065adac939f7235251682b5 | 2,590 | dart | Dart | lib/ui/pages/sign.dart | ngaurav/chi_food | 18143b47bb03bb70c26f02d5fd170f679596f77e | [
"MIT"
] | 85 | 2020-07-13T02:06:43.000Z | 2022-03-29T01:11:28.000Z | lib/ui/pages/sign.dart | ngaurav/chi_food | 18143b47bb03bb70c26f02d5fd170f679596f77e | [
"MIT"
] | null | null | null | lib/ui/pages/sign.dart | ngaurav/chi_food | 18143b47bb03bb70c26f02d5fd170f679596f77e | [
"MIT"
] | 30 | 2021-04-17T03:45:03.000Z | 2021-12-26T12:15:54.000Z | import 'package:chifood/bloc/authBloc/AuthBloc.dart';
import 'package:chifood/bloc/authBloc/AuthState.dart';
import 'package:chifood/config.dart';
import 'package:chifood/ui/widgets/loginForm.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
class SignScreen extends StatefulWidget {
@override
_SignScreenState createState() => _SignScreenState();
}
class _SignScreenState extends State<SignScreen> {
@override
Widget build(BuildContext context) {
return Scaffold(
body: GestureDetector(
onTap: (){
FocusScope.of(context).unfocus();
},
child:BlocListener<AuthenticationBloc,AuthenticationState>(
listener: (context,state){
if(state is FailAuthenticated){
Scaffold.of(context)..hideCurrentSnackBar() ..showSnackBar(
SnackBar(
content: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [Text('Login Failure'), Icon(Icons.error)],
),
backgroundColor: Colors.red,
),
);
} else if (state is Authenticated){
Navigator.of(context).popAndPushNamed('/HomePage');
}
},
child: SafeArea(
top: false,
bottom: false,
child: Stack(
children: <Widget>[
Image.asset('${asset}signin.jpeg',fit: BoxFit.cover,width: double.infinity,height: double.infinity,),
Positioned(
bottom: 0,
left: 0,
right: 0,
child: Container(
height: MediaQuery.of(context).size.height*0.5,
padding: EdgeInsets.all(16.0),
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.only(topLeft: Radius.circular(45.0),topRight: Radius.circular(45.0)),
),
child: Column(
crossAxisAlignment:CrossAxisAlignment.start ,
mainAxisSize: MainAxisSize.min,
children: <Widget>[
Text("Please Sign In",style: TextStyle(fontWeight: FontWeight.bold),),
LoginForm()
],
),
),
)
],
),
),
)
),
);
}
}
| 35 | 118 | 0.520463 |
70a3c9e7f7b842d41d80af10a49fc63ee9506217 | 1,127 | cs | C# | src/lib/Microsoft.Health.Fhir.Ingest/Data/IHashCodeGenerator.cs | msebragge/iomt-fhir | f3731567c858c9cdee1636f6ed2a1e3539b4cffa | [
"MIT"
] | 1 | 2022-01-04T10:02:46.000Z | 2022-01-04T10:02:46.000Z | src/lib/Microsoft.Health.Fhir.Ingest/Data/IHashCodeGenerator.cs | msebragge/iomt-fhir | f3731567c858c9cdee1636f6ed2a1e3539b4cffa | [
"MIT"
] | null | null | null | src/lib/Microsoft.Health.Fhir.Ingest/Data/IHashCodeGenerator.cs | msebragge/iomt-fhir | f3731567c858c9cdee1636f6ed2a1e3539b4cffa | [
"MIT"
] | null | null | null | // -------------------------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License (MIT). See LICENSE in the repo root for license information.
// -------------------------------------------------------------------------------------------------
using System;
namespace Microsoft.Health.Fhir.Ingest.Data
{
public interface IHashCodeGenerator : IDisposable
{
/// <summary>
/// Generates a hashcode given the supplied input. The hashcode generated will be a positive number represented as a string.
/// The hashcode will further be restricted by applying the moduluss of the supplied range parameter.
/// </summary>
/// <param name="value">The value to generate a hash code for</param>
/// <param name="range">A range to restrict the returned hashcodes to (i.e. 0 - range). Must be a greater than zero.</param>
/// <returns>The hash code value represented as a string</returns>
string GenerateHashCode(string value, int range = 256);
}
}
| 51.227273 | 132 | 0.566992 |
50411e5f25bbf3939458345d4ace583b66e5c602 | 8,131 | swift | Swift | ios/ios/news_service.grpc.swift | fb64/grpc-fullstack-demo | 39a53279d0a3baa198dfd1620859a51e31886130 | [
"MIT"
] | 25 | 2018-09-12T06:55:35.000Z | 2022-03-30T04:30:29.000Z | ios/ios/news_service.grpc.swift | fb64/grpc-fullstack-demo | 39a53279d0a3baa198dfd1620859a51e31886130 | [
"MIT"
] | 2 | 2019-06-27T22:35:43.000Z | 2022-01-06T10:04:00.000Z | ios/ios/news_service.grpc.swift | fb64/grpc-fullstack-demo | 39a53279d0a3baa198dfd1620859a51e31886130 | [
"MIT"
] | 3 | 2019-02-06T12:41:08.000Z | 2020-12-24T14:31:24.000Z | //
// DO NOT EDIT.
//
// Generated by the protocol buffer compiler.
// Source: news_service.proto
//
//
// Copyright 2018, gRPC Authors All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import Foundation
import Dispatch
import SwiftGRPC
import SwiftProtobuf
internal protocol Demo_NewsServicegetNewsCall: ClientCallUnary {}
fileprivate final class Demo_NewsServicegetNewsCallBase: ClientCallUnaryBase<Demo_NewsRequest, Demo_NewsResponse>, Demo_NewsServicegetNewsCall {
override class var method: String { return "/demo.NewsService/getNews" }
}
internal protocol Demo_NewsServicesubscribeCall: ClientCallServerStreaming {
/// Do not call this directly, call `receive()` in the protocol extension below instead.
func _receive(timeout: DispatchTime) throws -> Demo_News?
/// Call this to wait for a result. Nonblocking.
func receive(completion: @escaping (ResultOrRPCError<Demo_News?>) -> Void) throws
}
internal extension Demo_NewsServicesubscribeCall {
/// Call this to wait for a result. Blocking.
func receive(timeout: DispatchTime = .distantFuture) throws -> Demo_News? { return try self._receive(timeout: timeout) }
}
fileprivate final class Demo_NewsServicesubscribeCallBase: ClientCallServerStreamingBase<Demo_SubscribeRequest, Demo_News>, Demo_NewsServicesubscribeCall {
override class var method: String { return "/demo.NewsService/subscribe" }
}
internal protocol Demo_NewsServicepostNewsCall: ClientCallUnary {}
fileprivate final class Demo_NewsServicepostNewsCallBase: ClientCallUnaryBase<Demo_News, Demo_News>, Demo_NewsServicepostNewsCall {
override class var method: String { return "/demo.NewsService/postNews" }
}
/// Instantiate Demo_NewsServiceServiceClient, then call methods of this protocol to make API calls.
internal protocol Demo_NewsServiceService: ServiceClient {
/// Synchronous. Unary.
func getNews(_ request: Demo_NewsRequest) throws -> Demo_NewsResponse
/// Asynchronous. Unary.
func getNews(_ request: Demo_NewsRequest, completion: @escaping (Demo_NewsResponse?, CallResult) -> Void) throws -> Demo_NewsServicegetNewsCall
/// Asynchronous. Server-streaming.
/// Send the initial message.
/// Use methods on the returned object to get streamed responses.
func subscribe(_ request: Demo_SubscribeRequest, completion: ((CallResult) -> Void)?) throws -> Demo_NewsServicesubscribeCall
/// Synchronous. Unary.
func postNews(_ request: Demo_News) throws -> Demo_News
/// Asynchronous. Unary.
func postNews(_ request: Demo_News, completion: @escaping (Demo_News?, CallResult) -> Void) throws -> Demo_NewsServicepostNewsCall
}
internal final class Demo_NewsServiceServiceClient: ServiceClientBase, Demo_NewsServiceService {
/// Synchronous. Unary.
internal func getNews(_ request: Demo_NewsRequest) throws -> Demo_NewsResponse {
return try Demo_NewsServicegetNewsCallBase(channel)
.run(request: request, metadata: metadata)
}
/// Asynchronous. Unary.
internal func getNews(_ request: Demo_NewsRequest, completion: @escaping (Demo_NewsResponse?, CallResult) -> Void) throws -> Demo_NewsServicegetNewsCall {
return try Demo_NewsServicegetNewsCallBase(channel)
.start(request: request, metadata: metadata, completion: completion)
}
/// Asynchronous. Server-streaming.
/// Send the initial message.
/// Use methods on the returned object to get streamed responses.
internal func subscribe(_ request: Demo_SubscribeRequest, completion: ((CallResult) -> Void)?) throws -> Demo_NewsServicesubscribeCall {
return try Demo_NewsServicesubscribeCallBase(channel)
.start(request: request, metadata: metadata, completion: completion)
}
/// Synchronous. Unary.
internal func postNews(_ request: Demo_News) throws -> Demo_News {
return try Demo_NewsServicepostNewsCallBase(channel)
.run(request: request, metadata: metadata)
}
/// Asynchronous. Unary.
internal func postNews(_ request: Demo_News, completion: @escaping (Demo_News?, CallResult) -> Void) throws -> Demo_NewsServicepostNewsCall {
return try Demo_NewsServicepostNewsCallBase(channel)
.start(request: request, metadata: metadata, completion: completion)
}
}
/// To build a server, implement a class that conforms to this protocol.
/// If one of the methods returning `ServerStatus?` returns nil,
/// it is expected that you have already returned a status to the client by means of `session.close`.
internal protocol Demo_NewsServiceProvider: ServiceProvider {
func getNews(request: Demo_NewsRequest, session: Demo_NewsServicegetNewsSession) throws -> Demo_NewsResponse
func subscribe(request: Demo_SubscribeRequest, session: Demo_NewsServicesubscribeSession) throws -> ServerStatus?
func postNews(request: Demo_News, session: Demo_NewsServicepostNewsSession) throws -> Demo_News
}
extension Demo_NewsServiceProvider {
internal var serviceName: String { return "demo.NewsService" }
/// Determines and calls the appropriate request handler, depending on the request's method.
/// Throws `HandleMethodError.unknownMethod` for methods not handled by this service.
internal func handleMethod(_ method: String, handler: Handler) throws -> ServerStatus? {
switch method {
case "/demo.NewsService/getNews":
return try Demo_NewsServicegetNewsSessionBase(
handler: handler,
providerBlock: { try self.getNews(request: $0, session: $1 as! Demo_NewsServicegetNewsSessionBase) })
.run()
case "/demo.NewsService/subscribe":
return try Demo_NewsServicesubscribeSessionBase(
handler: handler,
providerBlock: { try self.subscribe(request: $0, session: $1 as! Demo_NewsServicesubscribeSessionBase) })
.run()
case "/demo.NewsService/postNews":
return try Demo_NewsServicepostNewsSessionBase(
handler: handler,
providerBlock: { try self.postNews(request: $0, session: $1 as! Demo_NewsServicepostNewsSessionBase) })
.run()
default:
throw HandleMethodError.unknownMethod
}
}
}
internal protocol Demo_NewsServicegetNewsSession: ServerSessionUnary {}
fileprivate final class Demo_NewsServicegetNewsSessionBase: ServerSessionUnaryBase<Demo_NewsRequest, Demo_NewsResponse>, Demo_NewsServicegetNewsSession {}
internal protocol Demo_NewsServicesubscribeSession: ServerSessionServerStreaming {
/// Send a message to the stream. Nonblocking.
func send(_ message: Demo_News, completion: @escaping (Error?) -> Void) throws
/// Do not call this directly, call `send()` in the protocol extension below instead.
func _send(_ message: Demo_News, timeout: DispatchTime) throws
/// Close the connection and send the status. Non-blocking.
/// This method should be called if and only if your request handler returns a nil value instead of a server status;
/// otherwise SwiftGRPC will take care of sending the status for you.
func close(withStatus status: ServerStatus, completion: (() -> Void)?) throws
}
internal extension Demo_NewsServicesubscribeSession {
/// Send a message to the stream and wait for the send operation to finish. Blocking.
func send(_ message: Demo_News, timeout: DispatchTime = .distantFuture) throws { try self._send(message, timeout: timeout) }
}
fileprivate final class Demo_NewsServicesubscribeSessionBase: ServerSessionServerStreamingBase<Demo_SubscribeRequest, Demo_News>, Demo_NewsServicesubscribeSession {}
internal protocol Demo_NewsServicepostNewsSession: ServerSessionUnary {}
fileprivate final class Demo_NewsServicepostNewsSessionBase: ServerSessionUnaryBase<Demo_News, Demo_News>, Demo_NewsServicepostNewsSession {}
| 47 | 165 | 0.77223 |
5452c6c457b91a1b8ce8134c1621785f17d6ffc0 | 1,564 | lua | Lua | Assets/sgk/Lua/view/ShowPreFinishTip.lua | freeGamePerson/dev_update | 80f75ff1ba6fd0d008e6a4989c2ba09e48129c38 | [
"BSD-3-Clause"
] | 1 | 2019-12-30T06:54:48.000Z | 2019-12-30T06:54:48.000Z | Assets/sgk/Lua/view/ShowPreFinishTip.lua | freeGamePerson/dev_update | 80f75ff1ba6fd0d008e6a4989c2ba09e48129c38 | [
"BSD-3-Clause"
] | null | null | null | Assets/sgk/Lua/view/ShowPreFinishTip.lua | freeGamePerson/dev_update | 80f75ff1ba6fd0d008e6a4989c2ba09e48129c38 | [
"BSD-3-Clause"
] | 3 | 2019-12-30T06:54:52.000Z | 2020-12-31T10:04:10.000Z | local ItemHelper = require "utils.ItemHelper"
local ShowPreFinishTip = {}
function ShowPreFinishTip:Start(data)
self:initData(data)
self:initUi(data)
module.guideModule.PlayByType(1300, 0.2)
end
function ShowPreFinishTip:initData(data)
self.itemTab = {}
self.fun = nil
if data then
self.itemTab = data.itemTab or {}
self.fun = data.fun or nil
end
end
function ShowPreFinishTip:initUi(data)
self.root = CS.SGK.UIReference.Setup(self.gameObject)
self.view = self.root.view
if self.fun then
self.view.GetBtn[CS.UGUIClickEventListener].onClick = function ( ... )
self.fun()
for i=1,#self.itemTab do
self.itemTab[i].pos = {self.itemTab[i].view.transform.position.x,self.itemTab[i].view.transform.position.y,0}
end
DispatchEvent("GiftBoxPre_to_FlyItem",self.itemTab)
CS.UnityEngine.GameObject.Destroy(self.gameObject)
end
end
self:initView()
end
function ShowPreFinishTip:initView()
local parent = self.view.Content
local prefab = self.view.Content.IconFrame
for i=1,#self.itemTab do
local _view = utils.SGKTools.GetCopyUIItem(parent,prefab,i)
local _tab = self.itemTab[i]
self.itemTab[i].view = _view
utils.IconFrameHelper.Create(_view,{type=_tab.type,id=_tab.id,count =_tab.count or 0,showDetail=true,showName =true});
end
end
function ShowPreFinishTip:deActive()
utils.SGKTools.PlayDestroyAnim(self.gameObject)
return true;
end
return ShowPreFinishTip
| 28.436364 | 126 | 0.683504 |
fc4f4f632a2043dcd9aa9436a83480310a879123 | 2,093 | ps1 | PowerShell | release.ps1 | SettingDust/new-tab | 67b1fd22d63bcc85b23e555b37988387b924701b | [
"MIT"
] | 1 | 2018-05-27T08:37:07.000Z | 2018-05-27T08:37:07.000Z | release.ps1 | SettingDust/new-tab | 67b1fd22d63bcc85b23e555b37988387b924701b | [
"MIT"
] | null | null | null | release.ps1 | SettingDust/new-tab | 67b1fd22d63bcc85b23e555b37988387b924701b | [
"MIT"
] | null | null | null | Write-Output "---------- Release $args ----------"
# config.js
$config = Get-Content src/config/index.js
$config = $config -replace "(\d+\.){2}\d+", $args
Set-Content src/config/index.js -Value $config
npm run build
# CHANGELOG.md
$changelog = Get-Content CHANGELOG.md
[System.Collections.ArrayList]$changelog = $changelog
$timestamp = Get-Date -Format "MM dd, yyyy"
$changelog.Insert(2, "## $args`n###### _$timestamp`_`n- `n")
Set-Content CHANGELOG.md -Value $changelog
# README.md
$readme = Get-Content README.md
$readme = $readme -replace "(\d+\.){2}\d+", $args
Set-Content README.md -Value $readme
$distPath = "dist"
Set-Location $distPath
# manifest.json
$manifest = Get-Content manifest.json
$manifest = $manifest -replace "(\d+\.){2}\d+", $args -replace "\]\,", "]"
# $manifest = $manifest[0..20] + $manifest[22]
[System.Collections.ArrayList]$manifest = $manifest
$manifest.RemoveAt(25)
Set-Content manifest.json -Value $manifest
# index.html
$html = Get-Content index.html
$html = $html -replace "<!\-\-", "" -replace "\-\->", ""
# $html = $html[0..9] + $html[11..12]
[System.Collections.ArrayList]$html = $html
$html.RemoveAt(10)
Set-Content index.html -Value $html
$files = @()
foreach ($name in Get-ChildItem -name)
{
$format = Get-Item $name
# Write-Output $format.Extension
if ($name -ne "images" -and $format.Extension -ne ".zip")
{
$files += $name
}
}
$releasesPath = "../releases"
if (!(Test-Path $releasesPath))
{
New-Item $releasesPath -type directory
}
# Write-Output $files
Compress-Archive -Path $files -Force -DestinationPath "$releasesPath/new-tab v$args.zip"
Write-Output "---------- Done ----------"
Set-Location ".."
Write-Output "After this operation, changes of the dist folder will be cleaned up."
$confirmation = Read-Host "Do you want to continue? [Y/n]"
if ($confirmation -eq 'y' -or $confirmation -eq 'Y')
{
Remove-Item -Recurse "$distPath/assets"
Get-ChildItem $distPath | Where-Object{ $_.Name -Match "js$" } | Remove-Item
git checkout -- $distPath
Write-Output "---------- Done ----------"
}
| 27.181818 | 88 | 0.648352 |
b2b83258ced2fe53705502f4829a8ece857f0dd4 | 1,121 | lua | Lua | scripts/vscripts/lua_abilities/spectre_desolate_lua/spectre_desolate_lua.lua | xuzolin/dota-2-lua-abilities | 5c1ff468bdcf3d9bec7be2acb750db7d4f5be98c | [
"MIT"
] | 125 | 2018-03-26T21:35:49.000Z | 2022-03-31T21:01:38.000Z | scripts/vscripts/lua_abilities/spectre_desolate_lua/spectre_desolate_lua.lua | hanzhengit/dota-2-lua-abilities | c6d7b7cff8be6bc32f3580411f31c24b8c0b0eca | [
"MIT"
] | 2 | 2020-07-05T16:02:19.000Z | 2020-11-18T02:24:48.000Z | scripts/vscripts/lua_abilities/spectre_desolate_lua/spectre_desolate_lua.lua | hanzhengit/dota-2-lua-abilities | c6d7b7cff8be6bc32f3580411f31c24b8c0b0eca | [
"MIT"
] | 40 | 2019-03-02T11:17:10.000Z | 2022-03-31T05:45:26.000Z | -- Created by Elfansoer
--[[
Ability checklist (erase if done/checked):
- Scepter Upgrade
- Break behavior
- Linken/Reflect behavior
- Spell Immune/Invulnerable/Invisible behavior
- Illusion behavior
- Stolen behavior
]]
--------------------------------------------------------------------------------
spectre_desolate_lua = class({})
LinkLuaModifier( "modifier_spectre_desolate_lua", "lua_abilities/spectre_desolate_lua/modifier_spectre_desolate_lua", LUA_MODIFIER_MOTION_NONE )
--------------------------------------------------------------------------------
-- Init Abilities
function spectre_desolate_lua:Precache( context )
PrecacheResource( "soundfile", "soundevents/game_sounds_heroes/game_sounds_spectre.vsndevts", context )
PrecacheResource( "particle", "particles/units/heroes/hero_spectre/spectre_desolate.vpcf", context )
end
function spectre_desolate_lua:Spawn()
if not IsServer() then return end
end
--------------------------------------------------------------------------------
-- Passive Modifier
function spectre_desolate_lua:GetIntrinsicModifierName()
return "modifier_spectre_desolate_lua"
end | 37.366667 | 144 | 0.644068 |
dfe59a06815369c9cd4f3f99ca80017ee03551bc | 437 | asm | Assembly | programs/oeis/076/A076895.asm | neoneye/loda | afe9559fb53ee12e3040da54bd6aa47283e0d9ec | [
"Apache-2.0"
] | 22 | 2018-02-06T19:19:31.000Z | 2022-01-17T21:53:31.000Z | programs/oeis/076/A076895.asm | neoneye/loda | afe9559fb53ee12e3040da54bd6aa47283e0d9ec | [
"Apache-2.0"
] | 41 | 2021-02-22T19:00:34.000Z | 2021-08-28T10:47:47.000Z | programs/oeis/076/A076895.asm | neoneye/loda | afe9559fb53ee12e3040da54bd6aa47283e0d9ec | [
"Apache-2.0"
] | 5 | 2021-02-24T21:14:16.000Z | 2021-08-09T19:48:05.000Z | ; A076895: a(1) = 1, a(n) = n - a(ceiling(n/2)).
; 1,1,2,3,3,4,4,5,6,7,7,8,9,10,10,11,11,12,12,13,14,15,15,16,16,17,17,18,19,20,20,21,22,23,23,24,25,26,26,27,27,28,28,29,30,31,31,32,33,34,34,35,36,37,37,38,38,39,39,40,41,42,42,43,43,44,44,45,46,47,47,48,48,49,49,50,51,52,52,53,54,55,55,56,57,58,58,59,59,60,60,61,62,63,63,64,64,65,65,66
lpb $0
add $0,1
add $1,$0
div $1,2
add $0,$1
sub $0,1
div $0,2
lpe
add $1,1
mov $0,$1
| 31.214286 | 288 | 0.588101 |
3ee8b90d4b94830701766887e1f1a28b44ad3075 | 254 | h | C | OSX/GCDConfig.h | malord/prime | f0e8be99b7dcd482708b9c928322bc07a3128506 | [
"MIT"
] | null | null | null | OSX/GCDConfig.h | malord/prime | f0e8be99b7dcd482708b9c928322bc07a3128506 | [
"MIT"
] | null | null | null | OSX/GCDConfig.h | malord/prime | f0e8be99b7dcd482708b9c928322bc07a3128506 | [
"MIT"
] | null | null | null | // Copyright 2000-2021 Mark H. P. Lord
#ifndef PRIME_OSX_GCDCONFIG_H
#define PRIME_OSX_GCDCONFIG_H
#include "../Config.h"
#if defined(PRIME_OS_OSX) && !defined(PRIME_NO_GCD)
#include <dispatch/dispatch.h>
#else
#define PRIME_NO_GCD
#endif
#endif
| 13.368421 | 51 | 0.751969 |
e864469da6e4f6c0718c1ed885e85e3cdc87a9c7 | 5,633 | cpp | C++ | qtdeclarative/src/qml/debugger/qqmldebug.cpp | wgnet/wds_qt | 8db722fd367d2d0744decf99ac7bafaba8b8a3d3 | [
"Apache-2.0"
] | 1 | 2020-04-30T15:47:35.000Z | 2020-04-30T15:47:35.000Z | qtdeclarative/src/qml/debugger/qqmldebug.cpp | wgnet/wds_qt | 8db722fd367d2d0744decf99ac7bafaba8b8a3d3 | [
"Apache-2.0"
] | null | null | null | qtdeclarative/src/qml/debugger/qqmldebug.cpp | wgnet/wds_qt | 8db722fd367d2d0744decf99ac7bafaba8b8a3d3 | [
"Apache-2.0"
] | null | null | null | /****************************************************************************
**
** Copyright (C) 2015 The Qt Company Ltd.
** Contact: http://www.qt.io/licensing/
**
** This file is part of the QtQml module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL21$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see http://www.qt.io/terms-conditions. For further
** information use the contact form at http://www.qt.io/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 or version 3 as published by the Free
** Software Foundation and appearing in the file LICENSE.LGPLv21 and
** LICENSE.LGPLv3 included in the packaging of this file. Please review the
** following information to ensure the GNU Lesser General Public License
** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** As a special exception, The Qt Company gives you certain additional
** rights. These rights are described in The Qt Company LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "qqmldebug.h"
#include "qqmldebugconnector_p.h"
#include <private/qqmlengine_p.h>
QT_BEGIN_NAMESPACE
QQmlDebuggingEnabler::QQmlDebuggingEnabler(bool printWarning)
{
#ifndef QQML_NO_DEBUG_PROTOCOL
if (!QQmlEnginePrivate::qml_debugging_enabled
&& printWarning) {
qDebug("QML debugging is enabled. Only use this in a safe environment.");
}
QQmlEnginePrivate::qml_debugging_enabled = true;
#else
Q_UNUSED(printWarning);
#endif
}
/*!
* \enum QQmlDebuggingEnabler::StartMode
*
* Defines the debug server's start behavior. You can interrupt QML engines starting while a debug
* client is connecting, in order to set breakpoints in or profile startup code.
*
* \value DoNotWaitForClient Run any QML engines as usual while the debug services are connecting.
* \value WaitForClient If a QML engine starts while the debug services are connecting,
* interrupt it until they are done.
*/
/*!
* Enables debugging for QML engines created after calling this function. The debug server will
* listen on \a port at \a hostName and block the QML engine until it receives a connection if
* \a mode is \c WaitForClient. If \a mode is not specified it won't block and if \a hostName is not
* specified it will listen on all available interfaces. You can only start one debug server at a
* time. A debug server may have already been started if the -qmljsdebugger= command line argument
* was given. This method returns \c true if a new debug server was successfully started, or
* \c false otherwise.
*/
bool QQmlDebuggingEnabler::startTcpDebugServer(int port, StartMode mode, const QString &hostName)
{
#ifndef QQML_NO_DEBUG_PROTOCOL
QQmlDebugConnector::setPluginKey(QLatin1String("QQmlDebugServer"));
QQmlDebugConnector *connector = QQmlDebugConnector::instance();
if (connector) {
QVariantHash configuration;
configuration[QLatin1String("portFrom")] = configuration[QLatin1String("portTo")] = port;
configuration[QLatin1String("block")] = (mode == WaitForClient);
configuration[QLatin1String("hostAddress")] = hostName;
return connector->open(configuration);
}
#else
Q_UNUSED(port);
Q_UNUSED(block);
Q_UNUSED(hostName);
#endif
return false;
}
/*!
* \since 5.6
*
* Enables debugging for QML engines created after calling this function. The debug server will
* connect to a debugger waiting on a local socket at the given \a socketFileName and block the QML
* engine until the connection is established if \a mode is \c WaitForClient. If \a mode is not
* specified it will not block. You can only start one debug server at a time. A debug server may
* have already been started if the -qmljsdebugger= command line argument was given. This method
* returns \c true if a new debug server was successfully started, or \c false otherwise.
*/
bool QQmlDebuggingEnabler::connectToLocalDebugger(const QString &socketFileName, StartMode mode)
{
#ifndef QQML_NO_DEBUG_PROTOCOL
QQmlDebugConnector::setPluginKey(QLatin1String("QQmlDebugServer"));
QQmlDebugConnector *connector = QQmlDebugConnector::instance();
if (connector) {
QVariantHash configuration;
configuration[QLatin1String("fileName")] = socketFileName;
configuration[QLatin1String("block")] = (mode == WaitForClient);
return connector->open(configuration);
}
#else
Q_UNUSED(fileName);
Q_UNUSED(block);
#endif
return false;
}
enum { HookCount = 3 };
// Only add to the end, and bump version if you do.
quintptr Q_QML_EXPORT qtDeclarativeHookData[] = {
// Version of this Array. Bump if you add to end.
1,
// Number of entries in this array.
HookCount,
// TypeInformationVersion, an integral value, bumped whenever private
// object sizes or member offsets that are used in Qt Creator's
// data structure "pretty printing" change.
2
};
Q_STATIC_ASSERT(HookCount == sizeof(qtDeclarativeHookData) / sizeof(qtDeclarativeHookData[0]));
QT_END_NAMESPACE
| 39.950355 | 100 | 0.71951 |
61748dbfd638ad4aaeafdf5092edd85c5c4e0a55 | 898 | sql | SQL | sql/advanced_select/q3_occupations.sql | mxdzi/hackerrank | 4455f73e4479a4204b2e1167253f6a02351aa5b7 | [
"MIT"
] | null | null | null | sql/advanced_select/q3_occupations.sql | mxdzi/hackerrank | 4455f73e4479a4204b2e1167253f6a02351aa5b7 | [
"MIT"
] | null | null | null | sql/advanced_select/q3_occupations.sql | mxdzi/hackerrank | 4455f73e4479a4204b2e1167253f6a02351aa5b7 | [
"MIT"
] | null | null | null | set @row1=0, @row2=0, @row3=0, @row4=0;
SELECT
MIN(Doctor), MIN(Professor), MIN(Singer), MIN(Actor)
FROM
(SELECT
CASE
WHEN occupation = 'Doctor' THEN (@row1:=@row1 + 1)
WHEN occupation = 'Professor' THEN (@row2:=@row2 + 1)
WHEN occupation = 'Singer' THEN (@row3:=@row3 + 1)
WHEN occupation = 'Actor' THEN (@row4:=@row4 + 1)
END AS `row`,
CASE
WHEN occupation = 'Doctor' THEN `name`
END AS Doctor,
CASE
WHEN occupation = 'Professor' THEN `name`
END AS Professor,
CASE
WHEN occupation = 'Singer' THEN `name`
END AS Singer,
CASE
WHEN occupation = 'Actor' THEN `name`
END AS Actor
FROM
occupations
ORDER BY `name`) tmp
GROUP BY `row`
| 32.071429 | 69 | 0.487751 |
5114bfad69084e8225be5982534486613f510027 | 3,504 | lua | Lua | Themes/default/Graphics/ScreenSelectMusic CourseContentsList.lua | fpmuniz/stepmania | 984dc8668f1fedacf553f279a828acdebffc5625 | [
"MIT"
] | 1,514 | 2015-01-02T17:00:28.000Z | 2022-03-30T14:11:21.000Z | Themes/default/Graphics/ScreenSelectMusic CourseContentsList.lua | fpmuniz/stepmania | 984dc8668f1fedacf553f279a828acdebffc5625 | [
"MIT"
] | 1,462 | 2015-01-01T10:53:29.000Z | 2022-03-27T04:35:53.000Z | Themes/default/Graphics/ScreenSelectMusic CourseContentsList.lua | fpmuniz/stepmania | 984dc8668f1fedacf553f279a828acdebffc5625 | [
"MIT"
] | 552 | 2015-01-02T05:34:41.000Z | 2022-03-26T05:19:19.000Z | -- Man, I hate this thing. I tried to do what I could with it, though.
-- I'm not really sure why this needs to be separate from the main CourseContentsList creation...
local transform = function(self,offsetFromCenter,itemIndex,numItems)
self:y( offsetFromCenter * 62 )
-- First condition is for making sure the items disappear before going past the banner.
-- Second condition is to make their transition from the bottom of the screen look a little smoother.
-- The exact numbers will likely need changing if "NumItemsToDraw" is changed.
if offsetFromCenter < -1 or offsetFromCenter > 5 then
self:diffusealpha(0)
-- And this is just so the objects don't look quite as "THERE" underneath the info pane and footer.
elseif offsetFromCenter < 0 or offsetFromCenter > 4 then
self:diffusealpha(0.6)
end
end
return Def.CourseContentsList {
MaxSongs = 999,
NumItemsToDraw = 12,
ShowCommand=cmd(bouncebegin,0.3;zoomy,1),
HideCommand=cmd(linear,0.3;zoomy,0),
SetCommand=function(self)
self:SetFromGameState()
self:SetCurrentAndDestinationItem(0)
self:SetPauseCountdownSeconds(1)
self:SetSecondsPauseBetweenItems( 0.25 )
self:SetTransformFromFunction(transform)
--
self:SetDestinationItem( math.max(0,self:GetNumItems() - 5) )
self:SetLoop(false)
self:SetMask(0,0)
end,
CurrentTrailP1ChangedMessageCommand=cmd(playcommand,"Set"),
CurrentTrailP2ChangedMessageCommand=cmd(playcommand,"Set"),
Display = Def.ActorFrame {
InitCommand=cmd(setsize,290,64),
LoadActor(THEME:GetPathG("CourseEntryDisplay","bar")) .. {
SetSongCommand=function(self, params)
if params.Difficulty then
self:diffuse(ColorLightTone(CustomDifficultyToColor(params.Difficulty)));
else
self:diffuse( color("#FFFFFF") );
end
-- These tweens were actually messing up the visibility of the scroller objects, so...
--(cmd(finishtweening;diffusealpha,0;sleep,0.125*params.Number;smooth,0.2;diffusealpha,1))(self);
end
},
Def.TextBanner {
InitCommand=cmd(x,-10;y,-1;Load,"TextBannerCourse";SetFromString,"", "", "", "", "", ""),
SetSongCommand=function(self, params)
if params.Song then
if GAMESTATE:GetCurrentCourse():GetDisplayFullTitle() == "Abomination" then
-- abomination hack
if PREFSMAN:GetPreference("EasterEggs") then
if params.Number % 2 ~= 0 then
-- turkey march
local artist = params.Song:GetDisplayArtist();
self:SetFromString( "Turkey", "", "", "", artist, "" );
else
self:SetFromSong( params.Song );
end;
else
self:SetFromSong( params.Song );
end;
else
self:SetFromSong( params.Song );
end;
self:diffuse(color("#000000"));
self:diffusealpha(0.8);
-- self:glow("1,1,1,0.5");
else
self:SetFromString( "??????????", "??????????", "", "", "", "" );
self:diffuse( color("#FFFFFF") );
-- self:glow("1,1,1,0");
end
--(cmd(finishtweening;diffusealpha,0;sleep,0.125*params.Number;smooth,0.2;diffusealpha,1))(self);
end
},
LoadFont("CourseEntryDisplay","difficulty") .. {
Text="0",
InitCommand=cmd(x,210;y,0;zoom,0.75),
SetSongCommand=function(self, params)
if params.PlayerNumber ~= GAMESTATE:GetMasterPlayerNumber() then return end
self:settext( params.Meter );
self:diffuse(ColorDarkTone(CustomDifficultyToColor(params.Difficulty) ));
--(cmd(finishtweening;zoomy,0;sleep,0.125*params.Number;linear,0.125;zoom,1.1;linear,0.05;zoom,1))(self);
end
},
}
} | 36.884211 | 109 | 0.689498 |
56d0915478697d95bd227f55aec1317969bdc6fd | 2,804 | go | Go | geometry_test.go | RXDA/geography | 01b9cdea5dfbff763ab5a9a526cace4adf5bd6f6 | [
"MIT"
] | 1 | 2019-10-17T06:07:14.000Z | 2019-10-17T06:07:14.000Z | geometry_test.go | RXDA/geography | 01b9cdea5dfbff763ab5a9a526cace4adf5bd6f6 | [
"MIT"
] | 3 | 2019-06-11T03:46:30.000Z | 2019-07-09T20:52:58.000Z | geometry_test.go | RXDA/geography | 01b9cdea5dfbff763ab5a9a526cace4adf5bd6f6 | [
"MIT"
] | 1 | 2021-06-02T01:56:29.000Z | 2021-06-02T01:56:29.000Z | package geography
import (
"database/sql/driver"
"testing"
"github.com/davecgh/go-spew/spew"
"github.com/go-courier/sqlx/v2"
"github.com/go-courier/sqlx/v2/builder"
"github.com/go-courier/sqlx/v2/migration"
"github.com/go-courier/sqlx/v2/mysqlconnector"
"github.com/go-courier/sqlx/v2/postgresqlconnector"
"github.com/google/uuid"
"github.com/sirupsen/logrus"
"github.com/stretchr/testify/require"
)
var (
mysqlConnector = &mysqlconnector.MysqlConnector{
Host: "root@tcp(0.0.0.0:3306)",
Extra: "charset=utf8mb4&parseTime=true&interpolateParams=true&autocommit=true&loc=Local",
}
postgresConnector = &postgresqlconnector.PostgreSQLConnector{
Host: "postgres://postgres@0.0.0.0:5432",
Extra: "sslmode=disable",
Extensions: []string{"postgis", "hstore"},
}
)
func init() {
logrus.SetLevel(logrus.DebugLevel)
}
type Geometries struct {
ID string `db:"F_id"`
Point Point `db:"F_point"`
MultiPoint MultiPoint `db:"F_multi_point,null"`
LineString LineString `db:"F_line_string,null"`
MultiLineString MultiLineString `db:"F_multi_line_string,null"`
Polygon Polygon `db:"f_polygon,null"`
MultiPolygon MultiPolygon `db:"f_multi_polygon,null"`
Geometry Geometry `db:"f_geometry"`
}
func (Geometries) PrimaryKey() []string {
return []string{"ID"}
}
func (Geometries) TableName() string {
return "t_geom"
}
func TestGeomRW(t *testing.T) {
tt := require.New(t)
dbGeom := sqlx.NewDatabase("geo")
for _, connector := range []driver.Connector{
postgresConnector,
mysqlConnector,
} {
db := dbGeom.OpenDB(connector)
userTable := dbGeom.Register(&Geometries{})
err := migration.Migrate(db, nil)
tt.NoError(err)
g := Geometries{
ID: uuid.New().String(),
Point: Point{-1, 2},
MultiPoint: MultiPoint{{-1, 2}, {2, 1}},
LineString: LineString{{-1, 2}, {2, 1}},
MultiLineString: MultiLineString{{{-1, 2}, {2, 1}}, {{-1, 2}, {2, 1}}},
Polygon: Polygon{
{{-1, 2}, {2, 1}, {2, 2}, {2, 3}, {-1, 2}},
{{-1, 2}, {2, 1}, {2, 2}, {-1, 2}},
{{-1, 2}, {2, 3}, {2, 4}, {-1, 2}},
},
MultiPolygon: MultiPolygon{{{{-1, 2}, {2, 1}, {-1, 2}, {-1, 2}}}, {{{-1, 2}, {2, 1}, {-1, 2}, {-1, 2}}}},
Geometry: ToGeometry(Point{-1, 2}),
}
_, errInsert := db.ExecExpr(sqlx.InsertToDB(db, g, nil))
tt.NoError(errInsert)
{
gForSelect := Geometries{}
err := db.QueryExprAndScan(
builder.Select(nil).From(
userTable,
builder.Where(userTable.F("ID").Eq(g.ID)),
),
&gForSelect,
)
tt.NoError(err)
spew.Dump(gForSelect)
}
dbGeom.Tables.Range(func(t *builder.Table, idx int) {
_, err := db.ExecExpr(db.Dialect().DropTable(t))
tt.NoError(err)
})
}
}
| 26.205607 | 108 | 0.614123 |
4a7ffb064efeb4780740b7778658c44df49e6b9f | 1,194 | html | HTML | html-css/doc/basico/sesion5/galeria2.html | PCianes/OpenBootcamp | 0568ee025155b3e26b2248c2046bbae1d8e50acc | [
"MIT"
] | null | null | null | html-css/doc/basico/sesion5/galeria2.html | PCianes/OpenBootcamp | 0568ee025155b3e26b2248c2046bbae1d8e50acc | [
"MIT"
] | null | null | null | html-css/doc/basico/sesion5/galeria2.html | PCianes/OpenBootcamp | 0568ee025155b3e26b2248c2046bbae1d8e50acc | [
"MIT"
] | null | null | null | <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" type="text/css" href="css/galeria2.css" />
</head>
<body>
<div class="galeria">
<input type="radio" name="navegacion" id="_1" checked>
<input type="radio" name="navegacion" id="_2">
<input type="radio" name="navegacion" id="_3">
<input type="radio" name="navegacion" id="_4">
<img src="imagen1.jpg" width="260" height="300" alt="Galeria CSS 1" />
<img src="imagen2.jpg" width="260" height="300" alt="Galeria CSS 2" />
<img src="imagen3.jpg" width="260" height="300" alt="Galeria CSS 3" />
<img src="imagen4.jpg" width="260" height="300" alt="Galeria CSS 4" />
</div>
<p> <a href="https://developer.mozilla.org/es/docs/Web/CSS/:nth-of-type" target="_blank">Info sobre la pseudo-clase nth-of-type</a></p>
<p>
<a href="https://www.w3schools.com/css/css_combinators.asp" target="_blank">Info sobre los cominadores CSS</a></p>
</body>
</html> | 39.8 | 141 | 0.616415 |
7cdd679632be2342adabaa464c92b76114dda3ae | 4,102 | lua | Lua | lua/cccomplete/elixir.lua | RobertDober/vimine | f75fc19bf96fa3039a30eb433f7932822c413aa8 | [
"Apache-2.0"
] | 1 | 2021-02-28T04:09:01.000Z | 2021-02-28T04:09:01.000Z | lua/cccomplete/elixir.lua | RobertDober/vimine | f75fc19bf96fa3039a30eb433f7932822c413aa8 | [
"Apache-2.0"
] | 5 | 2020-12-17T18:54:05.000Z | 2020-12-18T07:51:40.000Z | lua/cccomplete/elixir.lua | RobertDober/vimine | f75fc19bf96fa3039a30eb433f7932822c413aa8 | [
"Apache-2.0"
] | null | null | null | -- local dbg = require("debugger")
-- dbg.auto_where = 2
local A = require "tools.active_support"
local T = require "tools"()
local H = require "cccomplete.helpers"()
local S = require "tools.string"
local F = require "tools.fn"
local L = require "tools.list"
local equals = require'tools.functors'.equals
local function _upt_to_lib(path)
local segments = S.split(path, "/")
local tail = L.tail_from(segments, equals("lib"))
return table.concat(tail, "/")
end
local function defmodule_completion(ctxt)
if string.match(ctxt.line, "^module%s*$") then
local path = _upt_to_lib(ctxt.file_path)
local lines = {
"defmodule " .. A.camelize_path(path) .. " do",
" ",
"end"
}
return H.make_return_object{lines = lines, offset = 1}
end
end
local function test_completion(ctxt)
if string.match(ctxt.line, "^module%s*$") then
local lines = {
"defmodule " .. A.camelize_path(ctxt.file_path) .. " do",
" use ExUnit.Case",
"",
" ",
"end"
}
return H.make_return_object{lines = lines, offset = 3}
end
end
local function complete_special(ctxt)
local file_name = ctxt.file_name
if not file_name then
return nil
end
if string.match(file_name, "_test[.]exs$") then
return test_completion(ctxt)
else
return defmodule_completion(ctxt)
end
end
local function fn_complete_bare(ctxt)
local line = string.gsub(ctxt.line, "%s*$", "")
return H.complete_with_end(line)
end
local fn_patterns = {
["%s+->%s+$"] = fn_complete_bare,
}
local function fn_complete_first_docstring(with)
local with = with or ""
return function(ctxt)
local line = string.gsub(ctxt.line, ">%s*", with .. "> ")
return H.make_return_object{lines = {line}, offset = 0}
end
end
local function fn_complete_docstring(with)
local with = with or ""
return function(ctxt)
local line = string.gsub(ctxt.line, ">", with .. ">")
local number = string.match(line, "([(]%d+[)])")
return H.make_return_object{lines = {line, H.indent(line) .. "..." .. number .. "> "}}
end
end
local doctest_patterns = {
["^%s%s%s%s+iex>"] = fn_complete_first_docstring("(0)"),
["^%s%s%s%s+[.][.][.]>"] = fn_complete_docstring("(0)"),
["^%s%s%s%s+iex[(]%d+[)]>"] = fn_complete_docstring(),
["^%s%s%s%s+[.][.][.][(]%d+[)]>"] = fn_complete_docstring(),
}
local function fn_continue_pipe(ctxt)
return H.make_return_object{lines = {ctxt.line, H.indent(ctxt.line, "|> ")}}
end
local function fn_first_pipe(ctxt)
local line = string.gsub(ctxt.line, "%s*>%s*$", "")
return H.make_return_object{lines = {line, H.indent(line, "|> ")}}
end
local pipe_patterns = {
["%s>%s*$"] = fn_first_pipe,
["^%s*|>%s"] = fn_continue_pipe
}
local function fn_doctest(ctxt)
return H.make_return_object{lines = {ctxt.line, H.indent(ctxt.line), H.indent(ctxt.line, '"""')}}
end
local function fn_pure_docstring(ctxt)
local doctype = "@" .. string.match(ctxt.line, '^%s*(%w+)$')
return H.make_return_object{lines = {H.indent(ctxt.line, doctype .. ' """'), H.indent(ctxt.line), H.indent(ctxt.line, '"""')}}
end
local docstring_patterns = {
['^%s*doc$'] = fn_pure_docstring,
['^%s*moduledoc$'] = fn_pure_docstring,
['^%s*@doc%s+"""'] = fn_doctest,
['^%s*@moduledoc%s+"""'] = fn_doctest,
}
local function spec_complete(ctxt)
local fun_name = string.match(ctxt.post_line, "^%s*defp?%s([%w_?!]+)")
if fun_name then
local line = H.indent(ctxt.post_line) .. "@spec " .. fun_name .. "("
return H.make_return_object{lines = {line}, offset = 0}
end
end
local spec_patterns = {
['^%s*spec'] = spec_complete,
}
local all_patterns = {
doctest_patterns, docstring_patterns, pipe_patterns, fn_patterns, spec_patterns
}
return function()
local function complete(ctxt)
local special_completion = complete_special(ctxt)
if special_completion then
return special_completion
end
local completion = H.complete_from_patterns(ctxt, all_patterns)
if completion then
return completion
else
return H.complete_with_do(ctxt)
end
end
return {
complete = complete
}
end
| 28.685315 | 128 | 0.653096 |
4a5771aca8e1c71bd9e6f05ace0fe2f62691f59c | 4,119 | html | HTML | pa1-skeleton/pa1-data/0/creees.stanford.edu_events_film-series.html | yzhong94/cs276-spring-2019 | a4780a9f88b8c535146040fe11bb513c91c5693b | [
"MIT"
] | null | null | null | pa1-skeleton/pa1-data/0/creees.stanford.edu_events_film-series.html | yzhong94/cs276-spring-2019 | a4780a9f88b8c535146040fe11bb513c91c5693b | [
"MIT"
] | null | null | null | pa1-skeleton/pa1-data/0/creees.stanford.edu_events_film-series.html | yzhong94/cs276-spring-2019 | a4780a9f88b8c535146040fe11bb513c91c5693b | [
"MIT"
] | null | null | null | center for russian east european & eurasian studies skip to content skip to navigation stanford university home about creees history newsletter support creees people faculty & affiliates steering committee visiting scholars ma students staff student resources courses grants stanford in moscow contact us contact information directions join mailing list direct links multimedia apply ma program coterminal degree student grants research seminars public events lectures & performances film events ukrainian studies the alexander dallin lecture stanford berkeley conference outreach newsletter alumni k 12 teachers creees sponsored film series the stanford romanian film series 2010 2011 introduction and commentary by suzan negip schatt lecturer in romanian stanford special language program and florentina mocanu phd candidate drama department the stanford hungarian film series 2010 2011 pivotal women directors of hungarian cinema marta meszaros and ildiko enyedi introduction and commentary by eva soos szoke lecturer in hungarian special language program the stanford czech film series 2010 2011 introduction and commentary by jara dusatko lecturer in czech stanford special language program the stanford central asian film series 2010 2011 films of central asia two epochs of national identity formation introduction and commentary by alma kunanbaeva stanford anthropology department creees special film events filmmaker karpo godina at stanford screening of medusa's raft preceded by a short film and followed by a q&a session with the director thursday october 7 2010 at 6 30 pm annenberg auditorium cummings art building co sponsored by creees department of art and art history film and media studies and the europe center in the name of their mothers 2010 dir mary skinner 60 min movie screening with introduction and q&a session with filmmaker mary skinner thursday october 28 2010 at 7 00 pm language corner bldg 260 pigott hall rm 113 co sponsored by the taube center for jewish studies ukrainian film festival new films and new names from ukraine conducted by dr yuri shevchuk director of the ukrainian film club columbian university thursday february 10th and friday february 11th starting at 6 00 pm each day hartley conference room mitchell earth sciences building 397 panama mall film screenings to be followed by discussion led by dr yuri shevchuk when i want to whistle i whistle eu cand vreau sa fluier fluier romania sweden 2010 dir florin serban 94 min 35 mm film screening followed by q&a session with the film director florin serban friday april 1 2011 at 6 30 pm note new time cubberly auditorium co sponsored by the billie achilles fund bechtel international center graduate student council romanian student association special language program drama department and the europe center stanford iseees uc berkeley irc bucharest romania romanian honorary consulate san francisco casa romana hayward blue collar films san francisco coupa cafe palo alto the great famine 2011 prod austin hoyt and melissa martin 60 min documentary screening with introduction and q&a session with the film writer producer austin hoyt wednesday april 6 2011 at 7 30 pm history corner bldg 200 room 002 co sponsored by the hoover institution creees co sponsored film events and series russian film series introduction and commentary by julie draskoczy phd unaff 13th united nations association film festival population migration globalization fri 10 22 to sun 10 31 palo alto east palo alto san francisco stanford the battle of chernobyl russian ukraine usa 2006 dir thomas johnson 93 min documentary screening and q&a session wednesday may 25 2011 7 00 pm 9 00 pm cubberly auditorium co sponsored by the school of education crothers global citizenship stanford continuing studies center for russian east european and eurasian studies department of slavic languages and literatures and the stanford film society creees home stanford home ica humanities & sciences contact us directions join our lists newsletter stanford university all rights reserved stanford ca 94305 650 723 2300 terms of use copyright complaints
| 2,059.5 | 4,118 | 0.843166 |
fb172b12666f847ef0088281f990c2613f37d643 | 14,461 | lua | Lua | 1_game_memory_answer.lua | matukaz/Vaimne-Tervis | 596cb601203dbf3839535b6b06d4d80a2ee024ff | [
"Apache-2.0"
] | null | null | null | 1_game_memory_answer.lua | matukaz/Vaimne-Tervis | 596cb601203dbf3839535b6b06d4d80a2ee024ff | [
"Apache-2.0"
] | null | null | null | 1_game_memory_answer.lua | matukaz/Vaimne-Tervis | 596cb601203dbf3839535b6b06d4d80a2ee024ff | [
"Apache-2.0"
] | null | null | null | ---------------------------------------------------------------------------------------------
--
--
--
---------------------------------------------------------------------------------------------
local composer = require( "composer" )
local scene = composer.newScene()
-- Require the widget library
local widget = require( "widget" )
display.setStatusBar( display.HiddenStatusBar )
-- CREATE OBJECTS
function scene:create( event )
local sceneGroup = self.view
display.setDefault( "background", 1, 1, 1 )
local backButton
local areAnswersVisible = false
local maxAnswers = 8
local answer = {}
-- false answer -1
local person_answers ={-1,-1,-1,-1,-1,-1,-1,-1}
-- get numbers from the last scene (1_game_memory)
answer = event.params
local turnmusicOnOrOff = answer[table.maxn(answer)]
print(turnmusicOnOrOff.. " Turnmusic")
-- gradient for top box
local gradient = {
type = 'gradient',
--color1 = { 1, 1, 1 },
color1 = {76/255,143/255,199/255},
color2 = { 57/255, 107/255, 149/255 }, --green color
direction = "down"
}
-- This is the top box
local statusBoxHeight = 100
local statusBox = display.newRect( display.contentCenterX, display.screenOriginY, display.actualContentWidth, statusBoxHeight )
statusBox:setFillColor( gradient )
-- statusBox.fill = gradient
statusBox.alpha = 0.9
--Create a text object to show the current status
local statusText = display.newText( "", statusBox.x, statusBox.y, native.systemFontBold, 18 )
--DEBUG messages in commandline
print("Vastuste/Answer vaade 1_game_memory")
print ( table.concat(answer, ", ") )
local answerLabels = display.newText("Sisesta numbrid õiges järjekorras!", display.contentCenterX, 38, native.systemFontBold, 18)
answerLabels:setFillColor( 0, 0, 0 )
local function textListener( event )
if event.phase == "began" then
event.target.text=''
event.text=''
--statusText = display.newText( event.target.name, statusBox.x, statusBox.y, native.systemFontBold, 18 )
elseif event.phase == "ended" then
-- textField/Box loses focus
elseif event.phase == "ended" or event.phase == "submitted" then
elseif event.phase == "editing" then
local txt = event.text
if(string.len(txt)>2)then
txt=string.sub(txt, 1, 2)
event.target.text=txt
end
table.remove(person_answers,event.target.id)
table.insert(person_answers,event.target.id,event.target.text )
end
end
---------------------------------------------------------------------------------------------
-- this is background for answer once answers are submitted alpha = 1 that means they will show if answer is right(green) or wrong(red)
local rightAnswerBoxes = {}
local tHeight = 40
local tWidth = 110
local borders = 2
rightAnswerBoxes[1] = display.newRoundedRect( 80, 78, tWidth+borders, tHeight+borders, 3)
rightAnswerBoxes[2] = display.newRoundedRect( 240, 78, tWidth+borders, tHeight+borders, 3)
rightAnswerBoxes[3] = display.newRoundedRect( 80, 128, tWidth+borders, tHeight+borders, 3)
rightAnswerBoxes[4] = display.newRoundedRect( 240, 128,tWidth+borders, tHeight+borders, 3)
rightAnswerBoxes[5] = display.newRoundedRect( 80, 178, tWidth+borders, tHeight+borders, 3)
rightAnswerBoxes[6] = display.newRoundedRect( 240, 178, tWidth+borders, tHeight+borders, 3)
rightAnswerBoxes[7] = display.newRoundedRect( 80, 228,tWidth+borders, tHeight+borders, 3)
rightAnswerBoxes[8] = display.newRoundedRect( 240, 228, tWidth+borders, tHeight+borders, 3)
-- Add options to all of the rightAnswerBoxes
for _, rightAnswerBox in ipairs(rightAnswerBoxes) do
rightAnswerBox:setFillColor(127/255,255/255,0) -- kõigile green background.
rightAnswerBox.strokeWidth = 0
rightAnswerBox.alpha = 0
sceneGroup:insert(rightAnswerBox)
end
---------------------------------------------------------------------------------------------
local textFieldArrays = {}
textFieldArrays[1] = native.newTextField( 80, 80, tWidth, tHeight )
textFieldArrays[1].text = "esimene"
textFieldArrays[2] = native.newTextField( 240, 80, tWidth, tHeight )
textFieldArrays[2].text = "teine"
textFieldArrays[3] = native.newTextField( 80, 130, tWidth, tHeight )
textFieldArrays[3].text = "kolmas"
textFieldArrays[4] = native.newTextField( 240, 130, tWidth, tHeight )
textFieldArrays[4].text = "neljas"
textFieldArrays[5] = native.newTextField( 80, 180, tWidth, tHeight )
textFieldArrays[5].text = "viies"
textFieldArrays[6] = native.newTextField( 240, 180, tWidth, tHeight )
textFieldArrays[6].text = "kuues"
textFieldArrays[7] = native.newTextField( 80, 230, tWidth, tHeight )
textFieldArrays[7].text = "seitsmes"
textFieldArrays[8] = native.newTextField( 240, 230, tWidth, tHeight )
textFieldArrays[8].text = "kaheksas"
for _, textFieldArray in ipairs(textFieldArrays) do
textFieldArray:addEventListener( "userInput", textListener )
textFieldArray.inputType = "number"
textFieldArray.font = native.newFont( "Helvetica-Bold", 16 )
textFieldArray:setTextColor( 0.5, 0.5, 0.5 )
textFieldArray.id = _
sceneGroup:insert(textFieldArray)
end
---------------------------------------------------------------------------------------------
local nextGameRelease = function( event )
-- scrollView:removeSelf() -- Hide keyboard when the user clicks nextGameButton
native.setKeyboardFocus( nil )
composer.gotoScene( "gamelist", "fade", 100 )
composer.removeScene( "1_game_memory_answer" )
return true -- indicates successful touch
end
local restartGameButtonOnStatusBoxOnPress = function( event )
print("backButtonRelease function")
local options =
{
effect = "fade",
time = 100,
params = { turnMusic = turnmusicOnOrOff }
}
composer.gotoScene( "1_game_memory", options )
composer.removeScene( "1_game_memory_answer" )
return true -- indicates successful touch
end
---------------------------------------------------------------------------------------------
local submitRelease = function( event )
if areAnswersVisible == true then
nextGameRelease()
end
areAnswersVisible = true
backButton.alpha = 1
submitCheckMarkButton.isVisible = false
restartGameButtonOnStatusBox.isVisible = true
native.setKeyboardFocus( nil )
local rightAnswers = 0
for i=1,#answer-1 do
if answer[i] == tonumber(person_answers[i]) then
rightAnswers = rightAnswers + 1
rightAnswerBoxes[i].alpha = 1
else
rightAnswerBoxes[i]:setFillColor(1,0,0)
rightAnswerBoxes[i].alpha = 1 -- kõigile red background valedele vastustele.
end
end
---------------------------------------------------------------------------------------------
-- TODO _ näidata ka millised vastused olig õiged ja millised valed.
--[[
elseif string.len(renameBox.text) == 0 then
local alert = native.showAlert( "Warning", "You have not entered anything.", { "OK" }, onComplete )
end
--]]
-- local alert = native.showAlert( "Warning", "You have not entered anything.", { "OK" }, onComplete )
if(answerLabels ~=nil) then
answerLabels:removeSelf()
answerLabels=nil
end
local answerLabels = display.newText(rightAnswers .. "/8 õiget vastust", display.contentCenterX, 38, native.systemFontBold, 18)
answerLabels:setFillColor( 0, 0, 0 )
sceneGroup:insert(answerLabels)
---------------------------------------------------------------------------------------------
-- get highscore from database
local dbPath = system.pathForFile("gamescores.db", system.DocumentsDirectory)
local db = sqlite3.open( dbPath )
for row in db:nrows("SELECT * FROM gamescores WHERE id=1") do
print("printing")
-- local text = row.score.." "..row.highscore
highScore = tonumber(row.highscorewordmemory)
end
-- update highscore
if rightAnswers > highScore then
-- siia panna image " new high score "
local update = "UPDATE gamescores SET highscorewordmemory ='"..rightAnswers.."',lastscorewordmemory ='"..rightAnswers.."' WHERE id = 1"
db:exec(update)
else
print("no new highscore set")
local update = "UPDATE gamescores SET lastscorewordmemory ='".. rightAnswers .."' WHERE id = 1"
db:exec(update)
end
--submitButton:removeSelf()
submitButton=nil
---------------------------------------------------------------------------------------------
local nextGameButton = widget.newButton
{
defaultFile = "images/button/green.png",
overFile = "images/button/greenover.png",
label = "Menüü",
--emboss = true,
-- white and grey, default= normal. over= pressed
labelColor = { default={ 1, 1, 1 }, over={ 0, 0, 0, 1 } },
onPress = nextGamePress,
onRelease = nextGameRelease,
}
nextGameButton.x = display.contentCenterX; nextGameButton.y = 230+60
sceneGroup:insert(nextGameButton)
---------------------------------------------------------------------------------------------
local restartGameButton = widget.newButton
{
defaultFile = "images/button/blue.png",
overFile = "images/button/blueover.png",
label = "Restart",
--emboss = true,
-- white and grey, default= normal. over= pressed
labelColor = { default={ 1, 1, 1 }, over={ 0, 0, 0, 1 } },
onPress = restartGameButtonOnStatusBoxOnPress,
}
restartGameButton.x = display.contentCenterX; restartGameButton.y = 230+65+56
sceneGroup:insert(restartGameButton)
return true -- indicates successful touch
end
---------------------------------------------------------------------------------------------
local submitButton = widget.newButton
{
defaultFile = "images/button/green.png",
overFile = "images/button/greenover.png",
label = "Esita",
--emboss = true,
-- white and grey, default= normal. over= pressed
labelColor = { default={ 1, 1, 1 }, over={ 0, 0, 0, 1 } },
onPress = submitPress,
onRelease = submitRelease,
}
submitButton.x = display.contentCenterX; submitButton.y = 230+60
---------------------------------------------------------------------------------------------
function backButtonRelease()
print("backButtonRelease function")
composer.gotoScene( "1_game_instructions", "fade", 100 )
composer.removeScene( "1_game_memory_answer" )
return true -- indicates successful touch
end
backButton = widget.newButton
{
defaultFile = "images/back_button.png",
overFile = "images/back_buttonOver.png",
label = "",
--emboss = true,
-- white and grey, default= normal. over= pressed
labelColor = { default={ 1, 1, 1 }, over={ 0, 0, 0, 1 } },
onPress = backButtonPress,
onRelease = backButtonRelease,
}
-- 20 on siis Y, et täpselt olla samas kohas. ja 30 selleks, et pilt ise on umbes 60 pixlit+paddingud ja seetõttu on selline arv.
backButton.x = 30; backButton.y = statusBox.y+25
backButton.alpha = 0
sceneGroup:insert(backButton)
submitCheckMarkButton = widget.newButton
{
defaultFile = "images/arrow.png",
overFile = "images/arrowOver.png",
label = "",
--emboss = true,
-- white and grey, default= normal. over= pressed
labelColor = { default={ 1, 1, 1 }, over={ 0, 0, 0, 1 } },
onPress = submitPress,
onRelease = submitRelease,
}
-- 20 on siis Y, et täpselt olla samas kohas. ja 30 selleks, et pilt ise on umbes 60 pixlit+paddingud ja seetõttu on selline arv.
submitCheckMarkButton.x = display.actualContentWidth-30; submitCheckMarkButton.y = statusBox.y+25
restartGameButtonOnStatusBox = widget.newButton
{
defaultFile = "images/arrowcircle.png",
overFile = "images/arrowcircle.png",
label = "",
--emboss = true,
-- white and grey, default= normal. over= pressed
labelColor = { default={ 1, 1, 1 }, over={ 0, 0, 0, 1 } },
onPress = restartGameButtonOnStatusBoxOnPress,
}
-- 20 on siis Y, et täpselt olla samas kohas. ja 30 selleks, et pilt ise on umbes 60 pixlit+paddingud ja seetõttu on selline arv.
restartGameButtonOnStatusBox .x = display.actualContentWidth-30; restartGameButtonOnStatusBox.y = statusBox.y+25
restartGameButtonOnStatusBox.isVisible = false
sceneGroup:insert( restartGameButtonOnStatusBox )
--submitCheckMarkButton.onPress = nextGamePress
sceneGroup:insert( submitCheckMarkButton)
sceneGroup:insert(answerLabels)
sceneGroup:insert(submitButton)
sceneGroup:insert(statusBox)
sceneGroup:insert(statusText)
-- sceneGroup:insert()
end
---------------------------------------------------------------------------------------------
function scene:show( event )
local sceneGroup = self.view
local phase = event.phase
if phase == "will" then
-- Called when the scene is still off screen and is about to move on screen
elseif phase == "did" then
-- Called when the scene is now on screen
--
-- INSERT code here to make the scene come alive
-- e.g. start timers, begin animation, play audio, etc.
end
end
function scene:hide( event )
local sceneGroup = self.view
local phase = event.phase
if event.phase == "will" then
-- Called when the scene is on screen and is about to move off screen
--background:removeSelf()
--background = nil
-- INSERT code here to pause the scene
-- e.g. stop timers, stop animation, unload sounds, etc.)
elseif phase == "did" then
-- Called when the scene is now off screen
end
end
function scene:destroy( event )
local sceneGroup = self.view
-- Called prior to the removal of scene's "view" (sceneGroup)
--
-- INSERT code here to cleanup the scene
-- e.g. remove display objects, remove touch listeners, save state, etc.
end
---------------------------------------------------------------------------------------------
--[[
function onKeyEvent( event )
local phase = event.phase
local keyName = event.keyName
print( event.phase, event.keyName )
if ( "back" == keyName and phase == "up" ) then
print("backButtonRelease function")
composer.removeScene( "1_game_memory_answer" )
composer.gotoScene( "1_game_instructions", "fade", 100 )
end
return true -- to Override physical back button
end
Runtime:addEventListener( "key", onKeyEvent )
--]]
-- Listener setup
scene:addEventListener( "create", scene )
scene:addEventListener( "show", scene )
scene:addEventListener( "hide", scene )
scene:addEventListener( "destroy", scene )
---------------------------------------------------------------------------------------------
return scene
| 28.522682 | 144 | 0.634327 |
2007a1286bfb47d8411ffa15fe036c00f405cf82 | 466 | css | CSS | assets/css/theme.css | srilakshmikanthanp/srilakshmikanthanp.github.io | 908892b268196d369e5d4b4d5bbd92d63e0d620c | [
"MIT"
] | 3 | 2021-06-07T01:13:46.000Z | 2022-02-16T15:35:59.000Z | assets/css/theme.css | srilakshmikanthanp/srilakshmikanthanp.github.io | 908892b268196d369e5d4b4d5bbd92d63e0d620c | [
"MIT"
] | null | null | null | assets/css/theme.css | srilakshmikanthanp/srilakshmikanthanp.github.io | 908892b268196d369e5d4b4d5bbd92d63e0d620c | [
"MIT"
] | null | null | null | /**
* Copyright (c) 2021 Sri Lakshmi Kanthan P
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
:root {
--pri-bg-col: 10, 25, 47;
--pri-fg-col: 255, 255, 255;
--sec-bg-col: 100, 255, 218;
--sec-fg-col: 100, 255, 218;
}
::-webkit-scrollbar {
width: 7px;
background: rgb(var(--pri-bg-col));
}
::-webkit-scrollbar-thumb {
border-radius: 10px;
background: rgb(var(--sec-bg-col));
}
| 19.416667 | 51 | 0.594421 |
458789172429e365a54005b2bc8a83cc43c6b845 | 1,735 | asm | Assembly | programs/oeis/276/A276764.asm | karttu/loda | 9c3b0fc57b810302220c044a9d17db733c76a598 | [
"Apache-2.0"
] | 1 | 2021-03-15T11:38:20.000Z | 2021-03-15T11:38:20.000Z | programs/oeis/276/A276764.asm | karttu/loda | 9c3b0fc57b810302220c044a9d17db733c76a598 | [
"Apache-2.0"
] | null | null | null | programs/oeis/276/A276764.asm | karttu/loda | 9c3b0fc57b810302220c044a9d17db733c76a598 | [
"Apache-2.0"
] | null | null | null | ; A276764: 1^2 + 3^2, 2^2 + 4^2, 5^2 + 7^2, 6^2 + 8^2, ...
; 10,20,74,100,202,244,394,452,650,724,970,1060,1354,1460,1802,1924,2314,2452,2890,3044,3530,3700,4234,4420,5002,5204,5834,6052,6730,6964,7690,7940,8714,8980,9802,10084,10954,11252,12170,12484,13450,13780,14794,15140,16202,16564,17674,18052,19210,19604,20810,21220,22474,22900,24202,24644,25994,26452,27850,28324,29770,30260,31754,32260,33802,34324,35914,36452,38090,38644,40330,40900,42634,43220,45002,45604,47434,48052,49930,50564,52490,53140,55114,55780,57802,58484,60554,61252,63370,64084,66250,66980,69194,69940,72202,72964,75274,76052,78410,79204,81610,82420,84874,85700,88202,89044,91594,92452,95050,95924,98570,99460,102154,103060,105802,106724,109514,110452,113290,114244,117130,118100,121034,122020,125002,126004,129034,130052,133130,134164,137290,138340,141514,142580,145802,146884,150154,151252,154570,155684,159050,160180,163594,164740,168202,169364,172874,174052,177610,178804,182410,183620,187274,188500,192202,193444,197194,198452,202250,203524,207370,208660,212554,213860,217802,219124,223114,224452,228490,229844,233930,235300,239434,240820,245002,246404,250634,252052,256330,257764,262090,263540,267914,269380,273802,275284,279754,281252,285770,287284,291850,293380,297994,299540,304202,305764,310474,312052,316810,318404,323210,324820,329674,331300,336202,337844,342794,344452,349450,351124,356170,357860,362954,364660,369802,371524,376714,378452,383690,385444,390730,392500,397834,399620,405002,406804,412234,414052,419530,421364,426890,428740,434314,436180,441802,443684,449354,451252,456970,458884,464650,466580,472394,474340,480202,482164,488074,490052,496010,498004
mov $1,$0
mul $0,2
mod $1,2
sub $0,$1
add $0,2
pow $0,2
mov $1,$0
add $1,1
mul $1,2
| 133.461538 | 1,590 | 0.810951 |
fb380996fd47ebee4d3bd4acf394103f02c9e6c3 | 2,685 | java | Java | app/src/main/java/com/wtowto7207/firstcode/mymap/Info.java | wtowto7207/mymap | f5d979320d66628459dd08009d5d0257ead9b577 | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/wtowto7207/firstcode/mymap/Info.java | wtowto7207/mymap | f5d979320d66628459dd08009d5d0257ead9b577 | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/wtowto7207/firstcode/mymap/Info.java | wtowto7207/mymap | f5d979320d66628459dd08009d5d0257ead9b577 | [
"Apache-2.0"
] | null | null | null | package com.wtowto7207.firstcode.mymap;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Administrator on 2015/8/5.
*/
public class Info implements Serializable {
private static final long serialVersionUID = -4525278913679491045L;
private double latitude, longitude;
private int imgId;
private String name;
private String distance;
private int zan;
private int zanId;
private boolean isFirstClick;
public static List<Info> infos = new ArrayList<Info>();
static {
//infos.add();
infos.add(new Info(34.242652, 108.971171, R.drawable.a01, "英伦贵族小旅馆",
"距离209米", R.drawable.map_zan, 1456,true));
infos.add(new Info(34.242952, 108.972171, R.drawable.a02, "沙井国际洗浴会所",
"距离897米", R.drawable.map_zan, 456,true));
infos.add(new Info(34.242852, 108.973171, R.drawable.a03, "五环服装城",
"距离249米", R.drawable.map_zan, 1456,true));
infos.add(new Info(34.242152, 108.971971, R.drawable.a04, "老米家泡馍小炒",
"距离679米", R.drawable.map_zan, 1456,true));
}
public Info(double latitude, double longitude, int imgId, String name,
String distance, int zanId, int counter,boolean isFirstClick) {
this.latitude = latitude;
this.longitude = longitude;
this.imgId = imgId;
this.name = name;
this.distance = distance;
this.zanId = zanId;
this.zan = counter;
this.isFirstClick = isFirstClick;
}
public double getmLatitude() {
return latitude;
}
public void setmLatitude(double mLatitude) {
this.latitude = mLatitude;
}
public double getmLongitude() {
return longitude;
}
public void setmLongitude(double mLongitude) {
this.longitude = mLongitude;
}
public int getImgId() {
return imgId;
}
public void setImgId(int imgId) {
this.imgId = imgId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDistance() {
return distance;
}
public void setDistance(String distance) {
this.distance = distance;
}
public int getZanId(){ return zanId;}
public void setZanId(int zanId){ this.zanId = zanId;}
public int getZan() {
return zan;
}
public void setZan(int zan) {
this.zan = zan;
}
public boolean getFirstClick(){
return isFirstClick;
}
public void setFirstClick(boolean isFirstClick){
this.isFirstClick = isFirstClick;
}
}
| 23.761062 | 79 | 0.616015 |
650f4d544268699293dfae61c4d5b0971b890ccb | 50 | py | Python | src/converters/__init__.py | Peilonrayz/json_to_object | ae5ba42dcab71010302f42d78dbfd559c12496c9 | [
"MIT"
] | null | null | null | src/converters/__init__.py | Peilonrayz/json_to_object | ae5ba42dcab71010302f42d78dbfd559c12496c9 | [
"MIT"
] | null | null | null | src/converters/__init__.py | Peilonrayz/json_to_object | ae5ba42dcab71010302f42d78dbfd559c12496c9 | [
"MIT"
] | null | null | null | from .converter import Converter, Converters, ron
| 25 | 49 | 0.82 |
4c0e7422d9456a4941663efaf97928e7177c4010 | 652 | php | PHP | app/Models/MessageBox.php | karkilil/notice_board | 6ab29f1a7020625657ceb6052c2fec0d3bb22e68 | [
"MIT"
] | null | null | null | app/Models/MessageBox.php | karkilil/notice_board | 6ab29f1a7020625657ceb6052c2fec0d3bb22e68 | [
"MIT"
] | null | null | null | app/Models/MessageBox.php | karkilil/notice_board | 6ab29f1a7020625657ceb6052c2fec0d3bb22e68 | [
"MIT"
] | null | null | null | <?php namespace Notice\Models;
use Illuminate\Database\Eloquent\Model;
class MessageBox extends Model {
/**
* Generated
*/
public $timestamps = false;
protected $table = 'message_box';
protected $fillable = ['id', 'boxtype_id', 'msg_id', 'user_id'];
public function boxtype() {
return $this->belongsTo(\Notice\Models\Boxtype::class, 'boxtype_id', 'id');
}
public function tblMessage() {
return $this->belongsTo(\Notice\Models\TblMessage::class, 'msg_id', 'id');
}
public function user() {
return $this->belongsTo(\Notice\Models\User::class, 'user_id', 'user_id');
}
}
| 21.733333 | 83 | 0.625767 |
8078c1568b68405d4edc4fb2e34afc662a3c4866 | 2,613 | java | Java | Chapter6/Convert/Convert.java | IbrahimElsayed26498/Java | 60006de56cde96a9224990b58cd1fa372282239b | [
"Apache-2.0"
] | null | null | null | Chapter6/Convert/Convert.java | IbrahimElsayed26498/Java | 60006de56cde96a9224990b58cd1fa372282239b | [
"Apache-2.0"
] | null | null | null | Chapter6/Convert/Convert.java | IbrahimElsayed26498/Java | 60006de56cde96a9224990b58cd1fa372282239b | [
"Apache-2.0"
] | null | null | null | // Convert.java
import java.util.Scanner;
import java.util.Random;
public class Convert
{
public static void main(String[] args )
{
int[] decimal = new int[256];
Random randomNumber = new Random();
System.out.printf("Decimal\t\t\tBinary\t\t\tOctal\t\t\tHexadecimal\n");
for ( int i = 1; i <= 256; i++ )
{
System.out.printf("%d\t\t\t", i);
toBinary( i );
if ( i < 128)
{
System.out.printf("\t\t\t");
toOctal( i );
}
else
{
System.out.printf("\t\t");
toOctal( i );
}
System.out.printf("\t\t");
toHexadecimal( i );
System.out.println("");
}
}
public static void toBinary( int number )
{
int number_copy = number;
int[] digits = new int[10];
//
for ( int j = 0 ; j < 10; j++)
digits[j] = -1;
int i = 0;
while ( number != 0 )
{
digits[i] = number % 2;
number /= 2;
i++;
}
for (int k = i; k >=0; k-- )
{
if ( digits[k] > -1 )
System.out.printf("%d", digits[k]);
}
}
public static void toOctal( int number )
{
int number_copy = number;
int[] digits = new int[10];
//
for ( int j = 0 ; j < 10; j++)
digits[j] = -1;
int i = 0;
while ( number != 0 )
{
digits[i] = number % 8;
number /= 8;
i++;
}
for (int k = i; k >=0; k-- )
{
if ( digits[k] > -1 )
System.out.printf("%d", digits[k]);
}
}
public static void toHexadecimal( int number )
{
int number_copy = number;
String[] digits = new String[10];
//
for ( int j = 0 ; j < 10; j++)
digits[j] = "-1";
int i = 0;
while ( number != 0 )
{
digits[i] = hexed ( number % 16 );
number /= 16;
i++;
}
for (int k = i; k >=0; k-- )
{
if ( digits[k] != "-1" )
System.out.printf("%s", digits[k]);
}
}
public static String hexed( int n )
{
switch( n )
{
case 0:
return "0";
case 1:
return "1";
case 2:
return "2";
case 3:
return "3";
case 4:
return "4";
case 5:
return "5";
case 6:
return "6";
case 7:
return "7";
case 8:
return "8";
case 9:
return "9";
case 10:
return "A";
case 11:
return "B";
case 12:
return "C";
case 13:
return "D";
case 14:
return "E";
case 15:
return "F";
default:
return "-1";
}
}
}
| 17.536913 | 75 | 0.433219 |
42d11bf3700cbd2885f6ce5dc44f55c8c8aab2e2 | 5,664 | dart | Dart | edgehead/lib/ruleset/ruleset.dart | kwight/egamebook | c2836ef4d718805847bda5512b88afeb8c1e5b34 | [
"BSD-3-Clause"
] | 160 | 2018-08-16T06:16:12.000Z | 2022-03-13T16:22:37.000Z | edgehead/lib/ruleset/ruleset.dart | kwight/egamebook | c2836ef4d718805847bda5512b88afeb8c1e5b34 | [
"BSD-3-Clause"
] | 134 | 2019-04-06T00:06:53.000Z | 2021-07-12T16:57:26.000Z | edgehead/lib/ruleset/ruleset.dart | kwight/egamebook | c2836ef4d718805847bda5512b88afeb8c1e5b34 | [
"BSD-3-Clause"
] | 16 | 2018-09-18T02:44:04.000Z | 2021-12-09T01:13:00.000Z | library edgehead.ruleset;
import 'package:edgehead/fractal_stories/context.dart';
import 'package:meta/meta.dart';
bool _alwaysApplicableCallback(ApplicabilityContext _) => true;
typedef RuleApplyCallback = void Function(ActionContext context);
typedef RuleIsApplicableCallback = bool Function(ApplicabilityContext context);
class NoRuleApplicableException implements Exception {
final String message;
NoRuleApplicableException(this.message);
@override
String toString() => message;
}
@immutable
class Prerequisite implements Comparable<Prerequisite> {
/// The priority of a [Rule]. The higher the priority, the sooner the
/// rule will be tried.
final int priority;
/// When `true`, the prerequisite will check whether the rule has been
/// applied.
final bool onlyOnce;
/// The unique identifier of the prerequisite, or the rule / event / object
/// to which this prerequisite is attached.
///
/// When used in [Rule], this is the same as [Rule.hash]. When used
/// as a prerequisite for something else, like a room, this is some kind
/// of unique hash of that object.
final int hash;
final RuleIsApplicableCallback _isApplicableCallback;
const Prerequisite(
this.hash, this.priority, this.onlyOnce, this._isApplicableCallback);
const Prerequisite.alwaysTrue()
: hash = -1,
priority = 0,
onlyOnce = false,
_isApplicableCallback = _alwaysApplicableCallback;
@override
int compareTo(Prerequisite other) => -priority.compareTo(other.priority);
bool isSatisfiedBy(ApplicabilityContext context) {
if (onlyOnce && context.world.ruleHistory.query(hash).hasHappened) {
// This prerequisite+rule is applicable only once, and that has already
// happened.
return false;
}
return _isApplicableCallback(context);
}
}
@immutable
class Rule {
final int hash;
final Prerequisite prerequisite;
final RuleApplyCallback applyCallback;
Rule(
this.hash,
int priority,
bool onlyOnce,
RuleIsApplicableCallback isApplicableCallback,
this.applyCallback,
) : prerequisite =
Prerequisite(hash, priority, onlyOnce, isApplicableCallback);
@override
String toString() => "Rule<hash=$hash>";
}
@immutable
class Ruleset {
final Rule rule1;
final Rule rule2;
final Rule rule3;
final Rule rule4;
final Rule rule5;
final Rule rule6;
final Rule rule7;
final Rule rule8;
final Rule rule9;
final Rule rule10;
/// When using this constructor, you **MUST** provide the rules in order
/// from highest [Prerequisite.priority] to lowest.
const Ruleset(this.rule1,
[this.rule2,
this.rule3,
this.rule4,
this.rule5,
this.rule6,
this.rule7,
this.rule8,
this.rule9,
this.rule10]);
/// Creates an empty ruleset. Will throw when you try to [Ruleset.apply].
const Ruleset.empty()
: rule1 = null,
rule2 = null,
rule3 = null,
rule4 = null,
rule5 = null,
rule6 = null,
rule7 = null,
rule8 = null,
rule9 = null,
rule10 = null;
/// Prefer using the [Ruleset] constructor, which is much faster, but which
/// requires the rules to be provided in order from highest priority to
/// lowest.
factory Ruleset.unordered(Iterable<Rule> rules) {
final iter = rules.iterator;
final ordered = List.generate(10, (_) {
if (!iter.moveNext()) return null;
return iter.current;
}, growable: false)
..sort((a, b) {
if (a == null) return 1;
if (b == null) return -1;
return a.prerequisite.compareTo(b.prerequisite);
});
assert(ordered.length == 10);
return Ruleset(
ordered[0],
ordered[1],
ordered[2],
ordered[3],
ordered[4],
ordered[5],
ordered[6],
ordered[7],
ordered[8],
ordered[9],
);
}
/// An inefficient way of getting all rules as a list.
List<Rule> get _all => List<Rule>.unmodifiable(<Rule>[
rule1,
rule2,
rule3,
rule4,
rule5,
rule6,
rule7,
rule8,
rule9,
rule10
]);
/// Runs the ruleset, choosing the most specific rule and running its
/// [Rule.applyCallback].
///
/// This also records the used rule into [context.outputWorld]'s history.
///
/// Throws [NoRuleApplicableException] when no rule is applicable.
void apply(ActionContext context) {
if (rule1 == null) throw StateError('Trying to use an empty ruleset.');
for (int i = 0; i < 10; i++) {
final rule = _getByIndex(i);
if (rule == null) break;
if (rule.prerequisite.isSatisfiedBy(context)) {
rule.applyCallback(context);
context.outputWorld?.recordRule(rule);
// TODO: when 2+ rules of same priority are applicable, use sim.random
return;
}
}
throw NoRuleApplicableException("No rule was applicable. "
"Action history: ${context.world?.actionHistory?.describe()}, "
"Rules: $_all");
}
/// The rules are baked into the class as separate fields
/// ([rule1] .. [rule10]) for performance reasons. This method returns
/// the appropriate rule by its index.
Rule _getByIndex(int index) {
if (index == 0) return rule1;
if (index == 1) return rule2;
if (index == 2) return rule3;
if (index == 3) return rule4;
if (index == 4) return rule5;
if (index == 5) return rule6;
if (index == 6) return rule7;
if (index == 7) return rule8;
if (index == 8) return rule9;
if (index == 9) return rule10;
throw ArgumentError.value(index);
}
}
| 27.230769 | 79 | 0.646186 |
53e8ebc8f22909f1d6f52e9437b10aaa61fedd35 | 3,975 | java | Java | app/src/main/java/com/eternel/wlsmv/mvp/ui/activity/TagDetailActivity.java | etenel/MovieTest | b788b5843c18df5a0e3b0a2a7228001f700b6476 | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/eternel/wlsmv/mvp/ui/activity/TagDetailActivity.java | etenel/MovieTest | b788b5843c18df5a0e3b0a2a7228001f700b6476 | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/eternel/wlsmv/mvp/ui/activity/TagDetailActivity.java | etenel/MovieTest | b788b5843c18df5a0e3b0a2a7228001f700b6476 | [
"Apache-2.0"
] | null | null | null | package com.eternel.wlsmv.mvp.ui.activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Message;
import android.os.PersistableBundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.view.ViewPager;
import com.blankj.utilcode.util.FragmentUtils;
import com.blankj.utilcode.util.LogUtils;
import com.eternel.wlsmv.R;
import com.eternel.wlsmv.di.component.DaggerTagDetailComponent;
import com.eternel.wlsmv.di.module.TagDetailModule;
import com.eternel.wlsmv.mvp.contract.TagDetailContract;
import com.eternel.wlsmv.mvp.presenter.TagDetailPresenter;
import com.eternel.wlsmv.mvp.ui.adapter.TabAdapter;
import com.eternel.wlsmv.mvp.ui.fragment.TagImageFragment;
import com.jess.arms.base.BaseActivity;
import com.jess.arms.di.component.AppComponent;
import com.jess.arms.utils.ArmsUtils;
import java.util.ArrayList;
import java.util.List;
import butterknife.BindView;
import static com.jess.arms.utils.Preconditions.checkNotNull;
public class TagDetailActivity extends BaseActivity<TagDetailPresenter> implements TagDetailContract.View {
@BindView(R.id.m_tab)
TabLayout mTab;
@BindView(R.id.m_pager)
ViewPager mPager;
private int tab = 0;
private List<Fragment> mFragments;
private List<String> titles;
private TagImageFragment HotFragment;
private TagImageFragment NewFragment;
private String tag_name;
@Override
public void setupActivityComponent(@NonNull AppComponent appComponent) {
DaggerTagDetailComponent //如找不到该类,请编译一下项目
.builder()
.appComponent(appComponent)
.tagDetailModule(new TagDetailModule(this))
.build()
.inject(this);
}
@Override
public int initView(@Nullable Bundle savedInstanceState) {
return R.layout.activity_tag_detail; //如果你不需要框架帮你设置 setContentView(id) 需要自行设置,请返回 0
}
@Override
public void initData(@Nullable Bundle savedInstanceState) {
tag_name = getIntent().getStringExtra("tag_name");
LogUtils.e(tag_name);
if (savedInstanceState == null) {
HotFragment = TagImageFragment.newInstance(tag_name,"weekly");
NewFragment = TagImageFragment.newInstance(tag_name,"new");
} else {
tab = savedInstanceState.getInt("fragment");
FragmentManager fm = getSupportFragmentManager();
HotFragment = (TagImageFragment) FragmentUtils.findFragment(fm, TagImageFragment.class);
NewFragment = (TagImageFragment) FragmentUtils.findFragment(fm, TagImageFragment.class);
}
if (mFragments == null) {
mFragments = new ArrayList<>();
mFragments.add(HotFragment);
mFragments.add(NewFragment);
}
if (titles == null) {
titles = new ArrayList<>();
titles.add("热门");
titles.add("最新");
}
mPager.setAdapter(new TabAdapter(getSupportFragmentManager(), mFragments, titles));
mTab.setupWithViewPager(mPager);
mPager.setCurrentItem(0);
}
@Override
public void onSaveInstanceState(Bundle outState, PersistableBundle outPersistentState) {
super.onSaveInstanceState(outState, outPersistentState);
outState.putInt("fragment", tab);
}
@Override
public void showLoading() {
}
@Override
public void hideLoading() {
}
@Override
public void showMessage(@NonNull String message) {
checkNotNull(message);
ArmsUtils.snackbarText(message);
}
@Override
public void launchActivity(@NonNull Intent intent) {
checkNotNull(intent);
ArmsUtils.startActivity(intent);
}
@Override
public void killMyself() {
finish();
}
}
| 32.056452 | 107 | 0.698616 |
594aafeaa6907d6a4909d07d538b1d9670c6169a | 1,665 | cpp | C++ | Games/NetGame/Code/Game/GameState.cpp | tonyatpeking/SmuSpecialTopic | b61d44e4efacb3c504847deb4d00234601bca49c | [
"MIT"
] | null | null | null | Games/NetGame/Code/Game/GameState.cpp | tonyatpeking/SmuSpecialTopic | b61d44e4efacb3c504847deb4d00234601bca49c | [
"MIT"
] | null | null | null | Games/NetGame/Code/Game/GameState.cpp | tonyatpeking/SmuSpecialTopic | b61d44e4efacb3c504847deb4d00234601bca49c | [
"MIT"
] | null | null | null | #include "Engine/Core/EngineCommon.hpp"
#include "Engine/Core/Console.hpp"
#include "Engine/Math/Vec3.hpp"
#include "Engine/Renderer/Renderer.hpp"
#include "Engine/Time/TweenSystem.hpp"
#include "Game/GameState.hpp"
#include "Game/GameCommon.hpp"
#include "Game/GameState_Playing.hpp"
#include "Game/GameState_Loading.hpp"
#include "Game/GameState_MainMenu.hpp"
#include "Game/GameState_Victory.hpp"
#include "Game/GameState_Lobby.hpp"
GameState::GameState( GameStateType gameStateType )
: m_gameStateType( gameStateType )
{
m_tweenSystem = new TweenSystem();
}
GameState* GameState::MakeGameState( GameStateType gameStateType )
{
switch( gameStateType )
{
case GameStateType::PLAYING:
return new GameState_Playing();
case GameStateType::LOADING:
return new GameState_Loading();
case GameStateType::MAIN_MENU:
return new GameState_MainMenu();
case GameStateType::VICTORY:
return new GameState_Victory();
case GameStateType::LOBBY:
return new GameState_Lobby();
default:
LOG_FATAL( "Unimplemented GameState: " + GameStateType::ToString( gameStateType ) );
return nullptr;
}
}
GameState::~GameState()
{
delete m_tweenSystem;
}
void GameState::Update()
{
float ds = g_gameClock->GetDeltaSecondsF();
m_tweenSystem->Update( ds );
}
void GameState::Render() const
{
}
void GameState::OnEnter()
{
m_UITimeOfEnter = g_UIClock->GetTimeSinceStartupF();
g_console->Print( ToString() );
}
void GameState::OnExit()
{
}
void GameState::ProcessInput()
{
}
String GameState::ToString()
{
return GameStateType::ToString( m_gameStateType );
}
| 21.075949 | 92 | 0.712312 |
0a090bf5ead276ab3f1a48d5db8296250357e4e1 | 800 | ts | TypeScript | src/users/users.service.ts | shinsw627/nest-prac | e82d2c58486e49d00f309d862cbe4671a789ede2 | [
"MIT"
] | null | null | null | src/users/users.service.ts | shinsw627/nest-prac | e82d2c58486e49d00f309d862cbe4671a789ede2 | [
"MIT"
] | null | null | null | src/users/users.service.ts | shinsw627/nest-prac | e82d2c58486e49d00f309d862cbe4671a789ede2 | [
"MIT"
] | null | null | null | import { ConflictException, Injectable } from '@nestjs/common';
import * as bcrypt from 'bcrypt';
import { UserRequestDto } from './dtos/users.request.dto';
import { UsersRepository } from './users.repository';
@Injectable()
export class UsersService {
constructor(private readonly usersRepository: UsersRepository) {}
async signUp(body: UserRequestDto) {
const { email, password, name, phone } = body;
const isUserExist = await this.usersRepository.existsByEmail(email);
if (isUserExist) {
throw new ConflictException('해당 유저는 이미 존재합니다.');
}
const hashedPassword = await bcrypt.hash(password, 10);
const user = await this.usersRepository.create({
email,
password: hashedPassword,
name,
phone,
});
return user.readOnlyData;
}
}
| 27.586207 | 72 | 0.6925 |
7c9d2a613ec104825e64f460c969e8cc8f8b892f | 45 | rs | Rust | src/db/exec/mod.rs | twilco/cratify | 3fb6c4fd150a80c95e895131255e07c24d942cf2 | [
"Apache-2.0",
"MIT"
] | 5 | 2018-10-28T03:51:52.000Z | 2020-08-26T21:42:48.000Z | src/db/exec/mod.rs | twilco/cratify | 3fb6c4fd150a80c95e895131255e07c24d942cf2 | [
"Apache-2.0",
"MIT"
] | 22 | 2018-09-30T20:53:36.000Z | 2022-03-08T22:32:33.000Z | src/db/exec/mod.rs | twilco/cratify | 3fb6c4fd150a80c95e895131255e07c24d942cf2 | [
"Apache-2.0",
"MIT"
] | null | null | null | pub(crate) mod executor;
pub(crate) mod msg;
| 15 | 24 | 0.733333 |
5c5b0f62993cf4427d6c50c33d7b152d15d9bb0f | 1,589 | h | C | android-emu/android/base/files/MemStream.h | riscv-android-src/device-generic-goldfish-opengl | ee1b0db045b2e40160e56d5335f637f8d756135a | [
"Apache-2.0"
] | 1 | 2022-01-08T17:41:53.000Z | 2022-01-08T17:41:53.000Z | android-emu/android/base/files/MemStream.h | riscv-android-src/device-generic-goldfish-opengl | ee1b0db045b2e40160e56d5335f637f8d756135a | [
"Apache-2.0"
] | 2 | 2021-07-28T11:11:39.000Z | 2021-11-23T03:00:17.000Z | android-emu/android/base/files/MemStream.h | riscv-android-src/device-generic-goldfish-opengl | ee1b0db045b2e40160e56d5335f637f8d756135a | [
"Apache-2.0"
] | 2 | 2021-07-24T08:14:11.000Z | 2021-11-04T12:46:22.000Z | // Copyright 2015 The Android Open Source Project
//
// 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.
#pragma once
#include "android/base/Compiler.h"
#include "android/base/files/Stream.h"
#include <vector>
namespace android {
namespace base {
// An implementation of the Stream interface on top of a vector.
class MemStream : public Stream {
public:
using Buffer = std::vector<char>;
MemStream(int reserveSize = 512);
MemStream(Buffer&& data);
MemStream(MemStream&& other) = default;
MemStream& operator=(MemStream&& other) = default;
int writtenSize() const;
int readPos() const;
int readSize() const;
// Stream interface implementation.
ssize_t read(void* buffer, size_t size) override;
ssize_t write(const void* buffer, size_t size) override;
// Snapshot support.
void save(Stream* stream) const;
void load(Stream* stream);
const Buffer& buffer() const { return mData; }
private:
DISALLOW_COPY_AND_ASSIGN(MemStream);
Buffer mData;
int mReadPos = 0;
};
} // namespace base
} // namespace android
| 26.932203 | 75 | 0.712398 |
4b23573bea80800dd2050df4bd98de2efcd2095f | 601 | html | HTML | Modulo-1/EXs/ex015/pagina02.html | DarkEyeBr/HTML-CSS | c13eff070a02912230b03aee48f290315b1395d9 | [
"MIT"
] | 2 | 2020-11-23T19:19:35.000Z | 2020-12-08T23:33:59.000Z | Modulo-1/EXs/ex015/pagina02.html | DarkEyeBr/HTML-CSS | c13eff070a02912230b03aee48f290315b1395d9 | [
"MIT"
] | null | null | null | Modulo-1/EXs/ex015/pagina02.html | DarkEyeBr/HTML-CSS | c13eff070a02912230b03aee48f290315b1395d9 | [
"MIT"
] | null | null | null | <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Segunda Página</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<h1>Segunda Página</h1>
<h2>Teste de estilo</h2>
<p>Lorem, ipsum dolor sit amet consectetur adipisicing elit. Dolorum nihil eligendi aliquam quam officiis exercitationem voluptas, ea corrupti itaque commodi quas explicabo quibusdam laborum illum placeat, ab voluptatibus enim reprehenderit!</p>
<p><a href="index.html">Voltar</a></p>
</body>
</html> | 40.066667 | 249 | 0.705491 |
049fac2256b78084c0e226ca71dadf82210179c6 | 873 | java | Java | Spring-Cloud-Eureka/application-server/src/main/java/com/boeing/poc/applicationserver/ApplicationServerApplication.java | raghudv9/Spring-Cloud-Examples | f3c28d7683514f40d7a07693535bb0c23b282203 | [
"Apache-2.0"
] | null | null | null | Spring-Cloud-Eureka/application-server/src/main/java/com/boeing/poc/applicationserver/ApplicationServerApplication.java | raghudv9/Spring-Cloud-Examples | f3c28d7683514f40d7a07693535bb0c23b282203 | [
"Apache-2.0"
] | null | null | null | Spring-Cloud-Eureka/application-server/src/main/java/com/boeing/poc/applicationserver/ApplicationServerApplication.java | raghudv9/Spring-Cloud-Examples | f3c28d7683514f40d7a07693535bb0c23b282203 | [
"Apache-2.0"
] | null | null | null | package com.poc.applicationserver;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.actuate.endpoint.web.annotation.RestControllerEndpoint;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@SpringBootApplication
@EnableDiscoveryClient
@RestController
public class ApplicationServerApplication {
@Value("${server.instance.name}")
public String instance;
public static void main(String[] args) {
SpringApplication.run(ApplicationServerApplication.class, args);
}
@RequestMapping("/")
public String message() {
return "Hello from "+ instance;
}
}
| 30.103448 | 87 | 0.827033 |
e783bd8822a84db47aebf7ebe1381139a978fa26 | 686 | js | JavaScript | src/store/store.js | mhillerstrom/Quasar-Cordova | 853bba0274a1c944727be20f7352b6f9e2c41bad | [
"MIT"
] | 2 | 2020-10-20T23:04:13.000Z | 2020-10-20T23:04:16.000Z | src/store/store.js | mhillerstrom/Quasar-Cordova | 853bba0274a1c944727be20f7352b6f9e2c41bad | [
"MIT"
] | null | null | null | src/store/store.js | mhillerstrom/Quasar-Cordova | 853bba0274a1c944727be20f7352b6f9e2c41bad | [
"MIT"
] | 1 | 2020-06-20T20:32:51.000Z | 2020-06-20T20:32:51.000Z | // The server may have made changes to the store before rendering the initial html. It writes those changes to window.__INITIAL_STATE__. We need to set out local store to be the same as the server so vue does not throw an hydration error (server and client html out of sync)
import Vue from 'vue'
import VueStash from 'vue-stash'
import defaultStore from './store-defs'
Vue.use(VueStash)
let store = defaultStore
try {
// eslint-disable-next-line no-undef
if (typeof window !== 'undefined' && window.__INITIAL_STATE__) {
// eslint-disable-next-line no-undef
store = window.__INITIAL_STATE__
}
// eslint-disable-next-line no-empty
} catch (err) {}
export default store
| 34.3 | 274 | 0.746356 |
529b80d1fce1b9dd17f40af6b9914c6b9067c2bd | 6,913 | dart | Dart | touch_point_click_service_provider/lib/src/screens/requests/requestTracking.dart | iwmakhupane12/touch_point_click_service_provider | 5ea7892d05ffff892c8562414b819693c203edbd | [
"MIT"
] | null | null | null | touch_point_click_service_provider/lib/src/screens/requests/requestTracking.dart | iwmakhupane12/touch_point_click_service_provider | 5ea7892d05ffff892c8562414b819693c203edbd | [
"MIT"
] | null | null | null | touch_point_click_service_provider/lib/src/screens/requests/requestTracking.dart | iwmakhupane12/touch_point_click_service_provider | 5ea7892d05ffff892c8562414b819693c203edbd | [
"MIT"
] | null | null | null | import 'package:flutter/material.dart';
import 'package:touch_point_click_service_provider/src/appUsedStylesSizes/appIconsUsed.dart';
import 'package:touch_point_click_service_provider/src/appUsedStylesSizes/appTextStyles.dart';
import 'package:touch_point_click_service_provider/src/components/onlineOfflineAppBar.dart';
import 'package:touch_point_click_service_provider/src/components/utilWidget.dart';
import 'package:touch_point_click_service_provider/src/screens/requests/invoiceUpdate.dart';
class RequestTracking extends StatefulWidget {
final OnlineOfflineAppBar onlineOfflineAppBar;
RequestTracking(this.onlineOfflineAppBar);
@override
_RequestTrackingState createState() => _RequestTrackingState();
}
class _RequestTrackingState extends State<RequestTracking> {
final FontWeight normal = FontWeight.normal;
final Color black = Colors.black;
final Color white = Colors.white;
List<Widget> timeLineInfo = [];
List<TimeLineHeader> timeLineList = [];
@override
void initState() {
super.initState();
initTimeLineClassesList();
initTimeLine();
}
@override
Widget build(BuildContext context) {
return ListView(children: [stickyHeader()]);
}
Widget stickyHeader() {
return UtilWidget.stickyHeader(
"Request Id: 45632",
Column(children: timeLineInfo),
);
}
void initTimeLineClassesList() {
timeLineList.add(new TimeLineHeader(
"0", "Request Accepted", "22 Mar 2020", "16:47", ""));
timeLineList.add(new TimeLineHeader(
"1", "Going To Client's Location?", "24 Mar 2020", "12:00", "Yes"));
timeLineList.add(new TimeLineHeader(
"2", "Arrived At Location?", "24 Mar 2020", "12:22", "Yes"));
timeLineList.add(new TimeLineHeader(
"3", "Started Working?", "24 Mar 2020", "12:30", "Yes"));
timeLineList
.add(new TimeLineHeader("4", "Complete?", "24 Mar 2020", "13:30", ""));
}
void initTimeLine() {
for (int i = 0; i < 5; i++) {
timeLineInfo.add(timeLineWidget(i));
}
}
Widget popTextButton(String clicked) {
return UtilWidget.baseCard(
50,
Material(
color: Colors.transparent,
child: InkWell(
onTap: () => Navigator.pop(context, clicked),
borderRadius: BorderRadius.circular(25.0),
child: Align(
alignment: Alignment.center,
child: Text(
clicked,
style: AppTextStyles.normalBlack(normal, black),
),
),
),
),
);
}
void clientPaidBy() {
showDialog<String>(
context: context,
builder: (BuildContext context) => SimpleDialog(
title: Text("Did the client pay or they asked for an invoice?"),
children: [
popTextButton("Payed"),
popTextButton("Invoice"),
],
),
).then(
(value) {
if (value != null) {
changeScreen();
}
},
);
}
void changeScreen() {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) =>
InvoiceUpdate(onlineOfflineAppBar: widget.onlineOfflineAppBar),
),
);
}
Widget timeLineWidget(int index) {
return Container(
child: Row(
children: [
Column(
children: [
index > 0
? Container(
width: 2,
height: 50,
color: Colors.grey,
)
: new Container(height: 50),
Container(
margin: EdgeInsets.only(left: 5, right: 5),
padding: EdgeInsets.all(5),
decoration: BoxDecoration(
color: Colors.green,
borderRadius: BorderRadius.circular(50)),
child: AppIconsUsed.timeLineCheck,
),
index < 4
? Container(
width: 2,
height: 50,
color: Colors.grey,
)
: new Container(height: 50),
],
),
Expanded(
child: Container(
margin: EdgeInsets.all(10),
decoration: BoxDecoration(
color: Colors.white,
boxShadow: [
BoxShadow(
blurRadius: 10,
color: Colors.black26, //Color(0x802196F3),
)
],
borderRadius: BorderRadius.circular(25)),
height: 95,
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(timeLineList.elementAt(index).getTitle(),
overflow: TextOverflow.ellipsis,
maxLines: 1,
style: AppTextStyles.normalBlack(normal, black)),
timeLineList.elementAt(index).getID() == "0"
? SizedBox(height: 15.0)
: Container(),
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(
"${timeLineList.elementAt(index).getDate()} @ ${timeLineList.elementAt(index).getTime()}",
overflow: TextOverflow.ellipsis,
maxLines: 1,
style: AppTextStyles.normalGreyishSmall()),
timeLineList.elementAt(index).getID() != "0"
? ElevatedButton(
onPressed: () {
timeLineList.elementAt(index).getID() == "4"
? clientPaidBy()
: null;
},
style: UtilWidget.buttonStyle,
child: Text(
"Yes",
style: AppTextStyles.normalBlackSmall(
normal, white),
),
)
: Container(),
],
),
],
),
),
),
)
],
),
);
}
}
class TimeLineHeader {
String _id, _title, _date, _time, _btnText;
TimeLineHeader(this._id, this._title, this._date, this._time, this._btnText);
String getID() => this._id;
String getTitle() => this._title;
String getDate() => this._date;
String getTime() => this._time;
String getBtnText() => this._btnText;
}
| 32.303738 | 118 | 0.503255 |
2155276b3319ca199057c6b7c6b50a6838ee3bc9 | 933 | rs | Rust | src/rust/nomad-client-gen/src/models/node_purge_response.rs | inickles/grapl | f906aba74b2249c9c7d7b1afe6fc540551cdee8b | [
"Apache-2.0"
] | 313 | 2018-10-15T05:58:39.000Z | 2020-04-21T20:31:39.000Z | src/rust/nomad-client-gen/src/models/node_purge_response.rs | graplsec/grapl | 68386b425c8e9e34f7380a078279b67b316fe2a0 | [
"Apache-2.0"
] | 33 | 2018-10-16T00:47:10.000Z | 2020-03-16T22:32:45.000Z | src/rust/nomad-client-gen/src/models/node_purge_response.rs | graplsec/grapl | 68386b425c8e9e34f7380a078279b67b316fe2a0 | [
"Apache-2.0"
] | 29 | 2018-11-18T08:39:14.000Z | 2020-04-09T20:59:15.000Z | /*
* Nomad
*
* No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator)
*
* The version of the OpenAPI document: 1.1.4
* Contact: support@hashicorp.com
* Generated by: https://openapi-generator.tech
*/
#[derive(Clone, Debug, PartialEq, Default, Serialize, Deserialize)]
pub struct NodePurgeResponse {
#[serde(rename = "EvalCreateIndex", skip_serializing_if = "Option::is_none")]
pub eval_create_index: Option<i32>,
#[serde(rename = "EvalIDs", skip_serializing_if = "Option::is_none")]
pub eval_ids: Option<Vec<String>>,
#[serde(rename = "NodeModifyIndex", skip_serializing_if = "Option::is_none")]
pub node_modify_index: Option<i32>,
}
impl NodePurgeResponse {
pub fn new() -> NodePurgeResponse {
NodePurgeResponse {
eval_create_index: None,
eval_ids: None,
node_modify_index: None,
}
}
}
| 31.1 | 109 | 0.6806 |
3e71192de86d75d4c4eb3c7300e3982827efd24c | 640 | asm | Assembly | programs/oeis/217/A217775.asm | neoneye/loda | afe9559fb53ee12e3040da54bd6aa47283e0d9ec | [
"Apache-2.0"
] | 22 | 2018-02-06T19:19:31.000Z | 2022-01-17T21:53:31.000Z | programs/oeis/217/A217775.asm | neoneye/loda | afe9559fb53ee12e3040da54bd6aa47283e0d9ec | [
"Apache-2.0"
] | 41 | 2021-02-22T19:00:34.000Z | 2021-08-28T10:47:47.000Z | programs/oeis/217/A217775.asm | neoneye/loda | afe9559fb53ee12e3040da54bd6aa47283e0d9ec | [
"Apache-2.0"
] | 5 | 2021-02-24T21:14:16.000Z | 2021-08-09T19:48:05.000Z | ; A217775: a(n) = n*(n+1) + (n+2)*(n+3) + (n+4)*(n+5).
; 26,44,68,98,134,176,224,278,338,404,476,554,638,728,824,926,1034,1148,1268,1394,1526,1664,1808,1958,2114,2276,2444,2618,2798,2984,3176,3374,3578,3788,4004,4226,4454,4688,4928,5174,5426,5684,5948,6218,6494,6776,7064,7358,7658,7964,8276,8594,8918,9248,9584,9926,10274,10628,10988,11354,11726,12104,12488,12878,13274,13676,14084,14498,14918,15344,15776,16214,16658,17108,17564,18026,18494,18968,19448,19934,20426,20924,21428,21938,22454,22976,23504,24038,24578,25124,25676,26234,26798,27368,27944,28526,29114,29708,30308,30914
mov $1,3
mul $1,$0
add $0,5
mul $1,$0
add $1,26
mov $0,$1
| 64 | 525 | 0.742188 |
5829f6f819e076469a3aee7c0b148162807d034c | 78,463 | h | C | src/multi_index_array/LibMIAAlgorithm.h | extragoya/LibNT | 60372bf4e3c5d6665185358c4756da4fe547f093 | [
"BSD-3-Clause"
] | 1 | 2021-04-26T05:11:32.000Z | 2021-04-26T05:11:32.000Z | src/multi_index_array/LibMIAAlgorithm.h | extragoya/LibNT | 60372bf4e3c5d6665185358c4756da4fe547f093 | [
"BSD-3-Clause"
] | null | null | null | src/multi_index_array/LibMIAAlgorithm.h | extragoya/LibNT | 60372bf4e3c5d6665185358c4756da4fe547f093 | [
"BSD-3-Clause"
] | 1 | 2017-09-21T15:38:23.000Z | 2017-09-21T15:38:23.000Z | /***************************************************************************
The code for introsort and natural mergesort is modified from Keith Schwarz's versions.
Original code can be found online at:
1. http://www.keithschwarz.com/interesting/code/?dir=introsort
2. http://www.keithschwarz.com/interesting/code/?dir=natural-mergesort
1. This is an implementation of introsort, that accepts a user-defined swapper.
This is necessary for sorting index and data arrays (based on only the index
arrays), which is a necessary operation in sparse MIAs and lattices. Unlike
the STL version, this code will only use iter_swap (and not create temp
buffers), meaning we can safely use distances between iterators to swap entries
in the data container when we swap indices.
As well, reliance on STL algorithms was removed, as
these may or may not use temporary buffers, etc. This required using a non-STL
implementation of heapsort, as Schawrz's code used the STL version.
2. natural mergesort, modified along the lines of above
Keith Schwarz's original file headers are included before each sort implementation
***************************************************************************
*
* An implementation of the introsort (introspective sort) algorithm, a
* hybrid of quicksort, heapsort, and insertion sort that has particularly
* good runtime behavior. It is one of the fastest comparison sorting
* algorithms in use today, and is the usual implementation of the std::sort
* algorithm provided with the C++ STL.
*
* Introsort aims to get the benefits of quicksort (good locality, in-place,
* fast runtime) without running into any of its degenerate cases. To do so,
* the algorithm begins by guessing what the appropriate depth for the
* quicksort recursion should be, then fires off a quicksort routine. If
* quicksort ever makes too many recursive calls, the introsort routine
* switches over to using heapsort to sort the range. This means that in
* the best case, the algorithm runs a standard quicksort with minimal
* bookkeeping overhead and thus runs extremely quickly. In the worst case,
* the algorithm switches to heapsort and avoids the O(n^2) worst-case of
* quicksort.
*
* The algorithm also contains an additional optimization. Rather than
* using the O(n lg n) sorts (quicksort and heapsort) to completely sort the
* input, instead introsort picks some "block size" and then uses the sorts
* only on subranges larger than the block size. It then makes a final pass
* over the input using insertion sort to fix up the range. Since insertion
* sort runs extremely quickly (O(n)) when all of the elements in the range
* are known to be a constant number of positions from their final locations,
* this step runs rapidly. It also decreases the overall work necessary by
* the algorithm, since heapsort and quicksort are expensive on small ranges.
*
* This implementation of introsort uses the provided STL implementation of
* heapsort (make_heap, sort_heap) for simplicity, but has its own versions
* of the quicksort and insertion sort routines. It is based on David
* Musser's original paper on introsort (which can be found at
* http://www.cs.rpi.edu/~musser/gp/introsort.ps), though it does not use
* directly any of the code it contains.
*/
#define ROUND_DOWN(x, s) ((x) & ~((s)-1))
#ifndef LIBMIAALGORITHM
#define LIBMIAALGORITHM
#define _MIN_GALLOP_ 7
//#include <boost/timer/timer.hpp>
#include <forward_list>
//#include <boost/timer/timer.hpp>
#include "LibMIATimSort.h"
namespace LibMIA
{
namespace internal
{
//little swapper structur for the CO format, just used as part of a benchmark comparison vs the LCO format for sorting
template<typename MainIterator, typename FollowerIterator, size_t co_length>
struct CoSwapper
{
typedef FollowerIterator FollowerItType;
typedef MainIterator MainItType;
const MainIterator _mainBegin;
const FollowerIterator _followBegin;
CoSwapper(MainIterator _mainIt, FollowerIterator _followIt) : _mainBegin(_mainIt), _followBegin(_followIt)
{
}
void operator()(MainIterator it1, MainIterator it2) const
{
std::iter_swap(_followBegin + (it1 - _mainBegin), _followBegin + (it2 - _mainBegin));
auto it_raw = it1.m_iter; //now actually get the raw iterators pointing to the packed CO data
auto it_raw2 = it2.m_iter;
static_for<0, co_length>::_do([&](int i) //swap values, based on how many numbers are in each CO index
{
std::iter_swap(it_raw + i, it_raw2 + i);
});
}
FollowerItType getFollowIt(MainIterator it) const
{
return _followBegin + (it - _mainBegin);
}
};
//little swapper structur for the CO format as used by MTT, just used as part of a benchmark comparison vs the LCO format for sorting
template<typename MainIterator, typename FollowerIterator, size_t co_length>
struct CoSwapperMTT
{
typedef FollowerIterator FollowerItType;
typedef MainIterator MainItType;
const MainIterator _mainBegin;
const FollowerIterator _followBegin;
CoSwapperMTT(MainIterator _mainIt, FollowerIterator _followIt) : _mainBegin(_mainIt), _followBegin(_followIt)
{
}
void operator()(MainIterator it1, MainIterator it2) const
{
std::iter_swap(_followBegin + (it1 - _mainBegin), _followBegin + (it2 - _mainBegin));
auto const it_array = *it1; //now actually get the raw iterators pointing to the packed CO data
auto const it_array2 = *it2;
static_for<0, co_length>::_do([&](int i)
{
std::iter_swap(it_array[i], it_array2[i]); //swap values, based on how many numbers are in each CO index
});
}
FollowerItType getFollowIt(MainIterator it) const
{
return _followBegin + (it - _mainBegin);
}
};
//will also swap a second set of data. Two sets of data must correspond with each other.
template<typename MainIterator, typename FollowerIterator>
struct DualSwapper
{
typedef FollowerIterator FollowerItType;
typedef MainIterator MainItType;
const MainIterator _mainBegin;
const FollowerIterator _followBegin;
DualSwapper(MainIterator _mainIt,FollowerIterator _followIt): _mainBegin(_mainIt),_followBegin(_followIt)
{
}
void operator()(MainIterator it1, MainIterator it2) const
{
std::iter_swap(_followBegin+(it1-_mainBegin),_followBegin+(it2-_mainBegin));
std::iter_swap(it1,it2);
}
FollowerItType getFollowIt(MainIterator it) const
{
return _followBegin+(it-_mainBegin);
}
};
//will also swap a two more sets of data. Two sets of data must correspond with each other.
template<typename MainIterator, typename FollowerIterator,typename FollowerIterator2>
struct TripleSwapper
{
const MainIterator _mainBegin;
const FollowerIterator _followBegin;
const FollowerIterator2 _followBegin2;
TripleSwapper(MainIterator _mainIt,FollowerIterator _followIt,FollowerIterator2 _followIt2): _mainBegin(_mainIt),_followBegin(_followIt),_followBegin2(_followIt2)
{
}
void operator()(MainIterator it1, MainIterator it2) const
{
std::iter_swap(_followBegin2+(it1-_mainBegin),_followBegin2+(it2-_mainBegin));
std::iter_swap(_followBegin+(it1-_mainBegin),_followBegin+(it2-_mainBegin));
std::iter_swap(it1,it2);
}
};
/**
* Function: InterpolationSearch(RandomIterator begin, RandomIterator end,
* Element elem);
* ------------------------------------------------------------------------
* Performs interpolation search on the sorted range [begin, end). It is
* assumed that this range consists of finite integral values and that the
* input is sorted in ascending order. Returns whether the element was
* located.
*/
template <typename RandomIterator, typename Element >
RandomIterator InterpolationSearchUpperBound(RandomIterator begin, RandomIterator end,
const typename std::iterator_traits<RandomIterator>::value_type val,const Element & elemGetter) {
RandomIterator it;
typename std::iterator_traits<RandomIterator>::value_type temp;
typedef typename std::iterator_traits<RandomIterator>::difference_type diffT;
diffT step;
while (begin<end)
{
if(elemGetter(*begin)>val)
return begin;
it = begin;
temp=elemGetter(*(end - 1));
if(temp==val)
return end;
//std::cout << "end val is " << elemGetter(*(end - 1)) << " with distance " << end - begin << std::endl;
if(temp==val+1)
step=(end-begin)/2;
else{
const double interpolation = 1 / (double(temp) - double(val));
step=diffT(interpolation * (double(end - begin) - 1));
}
//std::cout << "step is " << step << std::endl;
std::advance (it,step);
//std::cout << "new elem is " << elemGetter(*it) << std::endl;
if (!(val<elemGetter(*it))) // or: if (!comp(val,*it)), for version (2)
{ begin=++it; }
else {end=it;
}
}
return begin;
}
template <typename RandomIterator>
RandomIterator InterpolationSearchUpperBound(RandomIterator begin, RandomIterator end,
const typename std::iterator_traits<RandomIterator>::value_type val) {
RandomIterator it;
typename std::iterator_traits<RandomIterator>::value_type temp;
typedef typename std::iterator_traits<RandomIterator>::difference_type diffT;
diffT step;
while (begin<end)
{
if(*begin>val)
return begin;
it = begin;
temp=*(end - 1);
if(temp==val)
return end;
//std::cout << "end val is " << elemGetter(*(end - 1)) << " with distance " << end - begin << std::endl;
if(temp==val+1)
step=(end-begin)/2;
else{
const double interpolation = 1 / (double(temp) - double(val));
step=diffT(interpolation * (double(end - begin) - 1));
}
//std::cout << "step is " << step << std::endl;
std::advance (it,step);
//std::cout << "new elem is " << elemGetter(*it) << std::endl;
if (!(val<*it)) // or: if (!comp(val,*it)), for version (2)
{ begin=++it; }
else {end=it;
}
}
return begin;
}
template <typename RandomIterator>
RandomIterator InterpolationSearchUpperBound(RandomIterator begin, RandomIterator end) {
return InterpolationSearchUpperBound(begin, end, *begin);
}
/**
* Function: InterpolationSearch(RandomIterator begin, RandomIterator end,
* Element elem);
* ------------------------------------------------------------------------
* Performs interpolation search on the sorted range [begin, end). It is
* assumed that this range consists of finite integral values and that the
* input is sorted in ascending order. Returns whether the element was
* located.
*/
template <typename RandomIterator, typename Element >
RandomIterator InterpolationSearchLowerBound(RandomIterator begin, RandomIterator end,
typename std::iterator_traits<RandomIterator>::value_type val,const Element & elemGetter) {
RandomIterator it;
typename std::iterator_traits<RandomIterator>::value_type temp;
typedef typename std::iterator_traits<RandomIterator>::difference_type diffT;
diffT step;
while (begin<end)
{
if(elemGetter(*begin)==val)
return begin;
it = begin;
temp=elemGetter(*(end - 1));
if(temp<=val+1)
step=(end-begin)/2;
else{
const double interpolation = 1 / (double(temp) - double(val));
step=diffT(interpolation * (double(end - begin) - 1));
}
//std::cout << "step is " << step << std::endl;
std::advance (it,step);
//std::cout << "new elem is " << elemGetter(*it) << std::endl;
if (elemGetter(*it)<val) // or: if (!comp(val,*it)), for version (2)
{ begin=++it; }
else {end=it;
}
}
return begin;
}
/**
* Function: InterpolationSearch(RandomIterator begin, RandomIterator end,
* Element elem);
* ------------------------------------------------------------------------
* Performs interpolation search on the sorted range [begin, end). It is
* assumed that this range consists of finite integral values and that the
* input is sorted in ascending order. Returns whether the element was
* located.
*/
template <typename RandomIterator, typename Element >
RandomIterator InterpolationSearchLowerBound(RandomIterator begin, RandomIterator end,
typename std::iterator_traits<RandomIterator>::value_type val) {
RandomIterator it;
typename std::iterator_traits<RandomIterator>::value_type temp;
typedef typename std::iterator_traits<RandomIterator>::difference_type diffT;
diffT step;
while (begin<end)
{
if(*begin==val)
return begin;
it = begin;
temp=*(end - 1);
if(temp<=val+1)
step=(end-begin)/2;
else{
const double interpolation = 1 / (double(temp) - double(val));
step=diffT(interpolation * (double(end - begin) - 1));
}
std::advance (it,step);
if (*it<val) // or: if (!comp(val,*it)), for version (2)
{ begin=++it; }
else {end=it;
}
}
return begin;
}
/**
* Function: Introsort(RandomIterator begin, RandomIterator end);
* ------------------------------------------------------------------------
* Sorts the range [begin, end) into ascending order using the introsort
* algorithm.
*/
template <typename RandomIterator>
void Introsort(RandomIterator begin, RandomIterator end);
/**
* Function: Introsort(RandomIterator begin, RandomIterator end,
* Comparator comp);
* -----------------------------------------------------------------------
* Sorts the range [begin, end) into ascending order (according to comp)
* using the introsort algorithm.
*/
template <typename RandomIterator, typename Comparator>
void Introsort(RandomIterator begin, RandomIterator end, Comparator comp);
/**
* Function: Introsort(RandomIterator begin, RandomIterator end,
* Comparator comp);
* -----------------------------------------------------------------------
* Sorts the range [begin, end) into ascending order (according to comp)
* and using swapper to perform the swap using the introsort algorithm.
*/
template <typename RandomIterator, typename Comparator, typename Swapper>
void Introsort(RandomIterator begin, RandomIterator end, Comparator comp, Swapper swapper);
/* * * * * Implementation Below This Point * * * * */
namespace introsort_detail {
/**
* Function: Partition(RandomIterator begin, RandomIterator end,
* Comparator comp);
* Usage: Partition(begin, end, comp);
* -------------------------------------------------------------
* Applies the partition algorithm to the range [begin, end),
* assuming that the pivot element is pointed at by begin.
* Comparisons are performed using comp. Returns an iterator
* to the final position of the pivot element.
*/
template <typename RandomIterator, typename Comparator, typename Swapper>
RandomIterator Partition(RandomIterator begin, RandomIterator end,
const Comparator & comp,const Swapper & swapper) {
/* The following algorithm for doing an in-place partition is
* one of the most efficient partitioning algorithms. It works
* by maintaining two pointers, one on the left-hand side of
* the range and one on the right-hand side, and marching them
* inward until each one encounters a mismatch. Once the
* mismatch is found, the mismatched elements are swapped and
* the process continues. When the two endpoints meet, we have
* found the ultimate location of the pivot.
*/
RandomIterator lhs = begin + 1;
RandomIterator rhs = end - 1;
while (true) {
/* Keep marching the right-hand side inward until we encounter
* an element that's too small to be on the left or we hit the
* left-hand pointer.
*/
while (lhs < rhs && !comp(*rhs, *begin))
--rhs;
/* Keep marching the left-hand side forward until we encounter
* a the right-hand side or an element that's too big to be
* on the left-hand side.
*/
while (lhs < rhs && comp(*lhs,*begin))
++lhs;
/* Now, if the two pointers have hit one another, we've found
* the crossover point and are done.
*/
if (lhs == rhs) break;
/* Otherwise, exchange the elements pointed at by rhs and lhs. */
swapper(lhs, rhs);
}
/* When we have reached this point, the two iterators have crossed
* and we have the partition point. However, there is one more edge
* case to consider. If the pivot element is the smallest element
* in the range, then the two pointers will cross over on the first
* step. In this case, we don't want to exchange the pivot element
* and the crossover point.
*/
if (!comp(*lhs,*begin))
return begin;
/* Otherwise, exchange the pivot and crossover, then return the
* crossover.
*/
swapper(begin, lhs);
return lhs;
}
/**
* Function: SiftDown(RandomIterator start, RandomIterator end,RandomIterator current,Comparator comp,Swapper swapper);
* ---------------------------------------------------------------
* Sifts element at current
*/
template <typename RandomIterator, typename Comparator,typename Swapper>
void SiftDown( RandomIterator begin, ptrdiff_t _size,ptrdiff_t _curIdx,const Comparator & comp,const Swapper &swapper)
{
auto root = _curIdx;
while ( root*2+1 < _size ) {
auto child = root*2+1;
if ((child + 1 < _size) && comp(*(begin+child),*(begin+child+1))) {
child += 1;
}
if (comp(*(begin+root), *(begin+child))) {
swapper(begin+child, begin+root );
root = child;
}
else
return;
}
}
/**
* Function: HeapSort(RandomIterator start, RandomIterator end,Comparator comp,Swapper swapper);
* ---------------------------------------------------------------
* Main heap sort function
*/
template <typename RandomIterator, typename Comparator,typename Swapper>
void HeapSort( RandomIterator begin, RandomIterator end,const Comparator & comp,const Swapper & swapper)
{
long long i_start, i_end;
long long _size = end - begin;
/* heapify */
for (i_start = (_size-2)/2; i_start >=0; i_start--) {
SiftDown(begin,_size,i_start, comp, swapper);
}
for (i_end=_size-1; i_end > 0; i_end--) {
swapper(begin+i_end,begin);
SiftDown(begin, i_end,0,comp,swapper);
}
}
/**
* Function: MedianOfThree(RandomIterator one, RandomIterator two,
* RandomIterator three, Comparator comp);
* ---------------------------------------------------------------
* Returns the middle element of the three, according to comp.
*/
template <typename RandomIterator, typename Comparator>
RandomIterator MedianOfThree(RandomIterator one, RandomIterator two,
RandomIterator three, const Comparator& comp) {
/* Do all three comparisons to determine which is in the middle. */
const bool comp12 = comp(*one, *two);
const bool comp13 = comp(*one, *three);
const bool comp23 = comp(*two, *three);
/* Based on the relationships between them, return the proper entry. */
if (comp12 && comp23) return two; // 1 < 2 < 3
if (comp12 && !comp23 && comp13) return three; // 1 < 3 <= 2
if (!comp12 && comp13) return one; // 2 <= 1 < 3
if (!comp12 && !comp13 && comp23) return three; // 2 < 3 <= 1
if (comp12 && !comp13) return one; // 3 <= 1 < 2
return two; // 3 <= 2 <= 1
}
/**
* Function: IntrosortRec(RandomIterator begin, RandomIterator end,
* size_t depth, Comparator comp);
* ---------------------------------------------------------------------
* Uses the introsort logic (hybridized quicksort and heapsort) to
* sort the range [begin, end) into ascending order by comp.
*/
template <typename RandomIterator, typename Comparator,typename Swapper>
void IntrosortRec(RandomIterator begin, RandomIterator end,
size_t depth, const Comparator & comp,const Swapper & swapper) {
/* Constant controlling the minimum size of a range to sort. Increasing
* this value reduces the amount of recursion performed, but may increase
* the final runtime by increasing the time it takes insertion sort to
* fix up the sequence.
*/
const size_t kBlockSize = 50;
/* Cache how many elements there are. */
const size_t numElems = size_t(end - begin);
/* If there are fewer elements in the range than the block size, we're
* done.
*/
if (numElems < kBlockSize) return;
/* If the depth is zero, sort everything using heapsort, then bail out. */
if (depth == 0) {
HeapSort(begin,end,comp,swapper);
return;
}
/* Otherwise, use a median-of-three to pick a (hopefully) good pivot,
* and partition the input with it.
*/
RandomIterator pivot = MedianOfThree(begin, // First elem
begin + numElems / 2, // Middle elem
end - 1, comp); // Last elem
/* Swap the pivot in place. */
swapper(pivot, begin);
/* Get the partition point and sort both halves. */
RandomIterator partitionPoint = Partition(begin, end, comp,swapper);
IntrosortRec(begin, partitionPoint, depth - 1, comp,swapper);
IntrosortRec(partitionPoint + 1, end, depth - 1, comp,swapper);
}
/**
* Function: IntrosortDepth(RandomIterator begin, RandomIterator end);
* ---------------------------------------------------------------------
* Returns the maximum depth to which introsort should be run on a range
* of the specified size. This is currently 2 lg (|end - begin|), as
* suggested in David Musser's paper.
*/
template <typename RandomIterator>
size_t IntrosortDepth(RandomIterator begin, RandomIterator end) {
size_t numElems = size_t(end - begin);
/* Compute lg(numElems) by shifting the number down until we zero it. */
size_t lg2 = 0;
for (; numElems != 0; numElems >>= 1, ++lg2)
;
/* Return twice this value. */
return lg2 * 2;
}
}
/**
* Function: InsertionSort(RandomIterator begin, RandomIterator end,
* Comparator comp);
* ----------------------------------------------------------------------
* Sorts the range [begin, end) into ascending order (according to comp)
* using insertion sort.
*/
template <typename RandomIterator, typename Comparator, typename Swapper>
inline void InsertionSort(RandomIterator begin, RandomIterator end,
Comparator comp,Swapper swapper) {
/* Edge case check - if there are no elements or exactly one element,
* we're done.
*/
if (begin == end || begin + 1 == end) return;
/* Starting at the second element and continuing rightward, put each
* element in its proper position.
*/
for (RandomIterator itr = begin + 1; itr != end; ++itr) {
/* Continue swapping down until we hit the beginning or are in the
* correct position.
*/
for (RandomIterator test = itr; test != begin && comp(*test, *(test - 1)); --test)
swapper(test, test - 1);
}
}
/**
* Function: InsertionSortImproved(RandomIterator begin, RandomIterator end,FollowIt followBegin,
* Comparator comp);
* ----------------------------------------------------------------------
* Sorts the range [begin, end) into ascending order (according to comp)
* using insertion sort. Uses improvements found in http://www.drdobbs.com/architecture-and-design/algorithm-improvement-through-performanc/220000504?pgno=1
*/
template <typename RandomIterator, typename Comparator, typename FollowIt>
inline void InsertionSortImproved(RandomIterator begin, RandomIterator end,FollowIt followBegin,
Comparator comp) {
if (end == begin)
return;
auto followIt=followBegin+1;
for (auto it=begin+1;it<end;++it,++followIt)
{
if (comp(*it,*(it-1))) // no need to do (j > 0) compare for the first iteration
{
auto curElement = *it;
auto followElement = *followIt;
*it=*(it-1);
*followIt=*(followIt-1);
auto it2=it-1;
auto followIt2=followIt-1;
for (; it2>begin && curElement < *(it2-1); --it2,--followIt2)
{
*it2=*(it2-1);
*followIt2=*(followIt2-1);
}
*it2 = curElement; // always necessary work/write
*followIt2 = followElement; // always necessary work/write
}
// Perform no work at all if the first comparison fails - i.e. never assign an element to itself!
}
}
/**
* Function: InsertionSortImproved(RandomIterator begin, RandomIterator end,FollowIt followBegin,
* Comparator comp);
* ----------------------------------------------------------------------
* Sorts the range [begin, end) into ascending order (according to comp)
* using insertion sort. Uses improvements found in http://www.drdobbs.com/architecture-and-design/algorithm-improvement-through-performanc/220000504?pgno=1
*/
template <typename RandomIterator, typename Comparator>
inline void InsertionSortImproved(RandomIterator begin, RandomIterator end,
Comparator comp) {
if (end == begin)
return;
for (auto it = begin + 1; it<end; ++it)
{
if (comp(*it, *(it - 1))) // no need to do (j > 0) compare for the first iteration
{
auto curElement = *it;
*it = *(it - 1);
auto it2 = it - 1;
for (; it2>begin && curElement < *(it2 - 1); --it2)
{
*it2 = *(it2 - 1);
}
*it2 = curElement; // always necessary work/write
}
// Perform no work at all if the first comparison fails - i.e. never assign an element to itself!
}
}
/* Implementation of introsort. */
template <typename RandomIterator, typename Comparator, typename Swapper>
void Introsort(RandomIterator begin, RandomIterator end, Comparator comp, Swapper swapper) {
/* Give easy access to the utiltiy functions. */
using namespace introsort_detail;
/* Fire off a recursive call to introsort using the depth estimate of
* 2 lg (|end - begin|), as suggested in the original paper.
*/
IntrosortRec(begin, end, IntrosortDepth(begin, end), comp,swapper);
/* Use insertion sort to clean everything else up. */
InsertionSort(begin, end, comp,swapper);
}
/* Non-swapper version calls the swapper version. */
template <typename RandomIterator, typename Comparator>
void Introsort(RandomIterator begin, RandomIterator end, Comparator comp) {
/* Give easy access to the utiltiy functions. */
auto swapper=[](RandomIterator one, RandomIterator two){
std::iter_swap(one,two);
};
Introsort(begin,end,comp,swapper);
}
/* Non-comparator version calls the comparator version. */
template <typename RandomIterator>
void Introsort(RandomIterator begin, RandomIterator end) {
Introsort(begin, end,
std::less<typename std::iterator_traits<RandomIterator>::value_type>());
}
//tailored made to sort CO format
template <typename RandomIterator, typename FollowIt, size_t co_length>
void IntrosortCO(RandomIterator begin, RandomIterator end, FollowIt followBegin, const std::array<size_t, co_length> & sortOrder) {
typedef typename std::iterator_traits<RandomIterator>::value_type index_type;
auto sort_compare = [sortOrder](const index_type& idx1, const index_type& idx2){
const index_type* it = &idx1;
const index_type* it2 = &idx2;
for (int i = co_length - 1; i >= 0; --i){
auto left = *(it + sortOrder[i]);
auto right = *(it2 + sortOrder[i]);
if (left < right){
return true;
}
else if (left > right){
return false;
}
}
return false;
};
typedef CoSwapper<RandomIterator, FollowIt, co_length> Swapper;
Introsort(begin, end, sort_compare, Swapper(begin, followBegin));
}
//tailored made to sort CO format
template <typename RandomIterator, typename FollowIt, size_t co_length>
void IntrosortCO_MTT(RandomIterator begin, RandomIterator end, FollowIt followBegin, const std::array<size_t, co_length> & sortOrder) {
typedef typename std::iterator_traits<RandomIterator>::value_type it_value_type;
auto sort_compare = [sortOrder](const it_value_type& idx_array, const it_value_type& idx_array2){
bool less_than = true;
for (int i = co_length - 1; i >= 0; --i){
auto left = *(idx_array[sortOrder[i]]);
auto right = *(idx_array2[sortOrder[i]]);
if (left < right){
return true;
}
else if (left > right){
return false;
}
}
return false;
};
typedef CoSwapperMTT<RandomIterator, FollowIt, co_length> Swapper;
Introsort(begin, end, sort_compare, Swapper(begin, followBegin));
}
/**************************************************************************
* File: NaturalMergesort.hh
* Author: Keith Schwarz (htiek@cs.stanford.edu)
*
* An implementation of the natural mergesort algorithm. Natural mergesort
* is a bottom-up mergesort algorithm that works by implicitly splitting the
* input up into a sequence of ascending subranges, then merging adjacent
* subranges together until the entire input is sorted. Since at each stage
* the number of sorted subranges decreases by a factor of two, and there
* are at most n sorted subranges in the initial input, there can be at most
* O(lg n) rounds of merging. Moreover, each merge of two sequences takes
* at most O(n) time, since the maximum size of any two sequences to merge
* is at most the size of the input array. This gives a worst-case upper
* bound of O(n lg n) runtime. The merging is done out-of-place for
* simplicity and thus the algorithm uses O(n) auxiliary storage space.
*
* However, this algorithm runs very quickly if the input is already sorted
* to some initial extent. In the best case, if the input is already
* fully-sorted, the algorithm will terminate after running one pass over
* the input, using only O(n) time. In this sense, natural mergesort is
* an adaptive sorting algorithm.
*/
/**
* Function: NaturalMergesort(ForwardIterator begin, ForwardIterator end);
* ------------------------------------------------------------------------
* Sorts the range specified by [begin, end) using the natural mergesort
* algorithm. Auxiliary storage space is placed into a temporary vector.
*/
template <typename ForwardIterator>
void NaturalMergesort(ForwardIterator begin, ForwardIterator end);
/**
* Function: NaturalMergesort(ForwardIterator begin, ForwardIterator end,
* Comparator comp);
* ------------------------------------------------------------------------
* Sorts the range specified by [begin, end) using the natural mergesort
* algorithm. Auxiliary storage space is placed into a temporary vector,
* and the sequence is ordered by the strict weak ordering comp.
*/
template <typename ForwardIterator, typename FollowIt,typename Comparator>
void NaturalMergesort(ForwardIterator begin, ForwardIterator end,FollowIt followBegin, std::vector<typename std::iterator_traits<ForwardIterator>::value_type> & mainScratch,
std::vector<typename std::iterator_traits<FollowIt>::value_type> & followScratch,
Comparator comp);
/* * * * * Implementation Below This Point * * * * */
namespace naturalmergesort_detail {
/**
* Function: SortedRangeEnd(ForwardIterator begin, ForwardIterator end,
* Comparator comp);
* ---------------------------------------------------------------------
* Returns an iterator to the end of the longest nondecreasing range
* starting at begin in the range [begin, end), according to comparison
* comp. If the entire sequence is sorted, end is returned.
*/
template <typename ForwardIterator, typename Comparator>
ForwardIterator SortedRangeEnd(ForwardIterator begin, ForwardIterator end,
const Comparator & comp) {
/* Edge case - if the input is empty, we're done. */
if (begin == end) return end;
// if(finder(*(end-1))==finder(*begin)) return end;
// //if(log2((unsigned)(end-begin))< (end-begin)/(finder(*(end-1))-finder(*begin))){
// InterpolationSearch(begin,end,finder);
// std::exit(1);
// return begin;
//
//// }
// else{
/* Get an iterator that's one step ahead of begin. */
ForwardIterator next = begin; ++next;
/* Keep marching these iterators forward until we find a mismatch or
* hit the end. A mismatch occurs when the element after the current
* is strictly less than the current element.
*/
for (; next != end && !comp(*next, *begin); ++next, ++begin)
;
/* The above loop stops either when next is the end of the sequence or
* when next is the crossover point. In either case, return next.
*/
return next;
// }
}
/**
* Function: Merge(ForwardIterator begin, ForwardIterator mid,
* ForwardIterator end, Comparator comp);
* ---------------------------------------------------------------------
* Merges the sorted ranges [begin, mid) and [mid, end) together into
* one sorted range, using comp as the comparator.
*/
template<typename MainIterator,typename FollowIterator,typename ScratchIterator,typename ScratchIterator2,typename Comp>
void Merge(MainIterator begin, MainIterator mid,MainIterator end, FollowIterator followIt,ScratchIterator scratchIt1, ScratchIterator2 scratchIt2,
const Comp & comp) {
const size_t kBlockSize = 6;
if((size_t)(end-begin)<kBlockSize){
InsertionSort(begin,end,comp,internal::DualSwapper<MainIterator,FollowIterator>(begin,followIt));
std::copy(begin, end, scratchIt1);
std::copy(followIt, followIt+(end-begin), scratchIt2);
return;
}
/* Continuously choose the smaller of the two to go in front until some
* range is consumed.
*/
MainIterator one = begin, two = mid;
FollowIterator followOne=followIt, followTwo=followIt+(mid-begin);
while (one != mid && two != end) {
if (comp(*one, *two)) { // First sequence has smaller element
*scratchIt1++=*one;
*scratchIt2++=*followOne;
++one;
++followOne;
} else { // Second sequence has smaller element.
*scratchIt1++=*two;
*scratchIt2++=*followTwo;
++two;
++followTwo;
}
}
//std::cout << " finished initial merge one: " <<one-begin << " two: " << two-begin << std::endl;
/* Once one of the sequences has been exhausted, one of two cases holds:
*
* 1. The first sequence was consumed. In that case, the rest of the
* second sequence is valid and we can just copy the merged sequence
* in front of it.
* 2. The second sequence was consumed. In that case, we copy the rest
* of the first sequence into the merged sequence, then write the
* merged sequence back.
*/
if (two == end){
std::copy(one, mid, scratchIt1);
std::copy(followOne, followIt+(mid-begin), scratchIt2);
}
else{
std::copy(two, end, scratchIt1);
std::copy(followTwo, followIt+(end-begin), scratchIt2);
}
// std::copy(scratchSpace1.begin(), sIt1, begin);
// std::copy(scratchSpace2.begin(), sIt2, swapper.getFollowIt(begin));
}
template<typename MainIterator,typename FollowIterator,typename ScratchIterator,typename ScratchIterator2,typename Comp>
bool MergeSortLoop(MainIterator begin, MainIterator end, FollowIterator followBegin, ScratchIterator scratchBegin1, ScratchIterator2 scratchBegin2,const Comp& comp){
bool haveMerged=false;
auto scratchIt1=scratchBegin1;
auto scratchIt2=scratchBegin2;
auto followIt=followBegin;
for (auto itr = begin; itr != end; ) {
/* See how far this range extends. */
//findtimer.resume();
auto rangeEnd = SortedRangeEnd(itr, end, comp);
//findtimer.stop();
/* If we hit the end of the range, we're done with this iteration. */
if (rangeEnd == end){
if(haveMerged){
std::copy(itr,end,scratchIt1);
std::copy(followIt,followBegin+(end-begin),scratchIt2);
}
break;
}
/* See where the end of that range is. */
//findtimer.resume();
auto nextRangeEnd = SortedRangeEnd(rangeEnd, end, comp);
//findtimer.stop();
/* Merge this range with the range after it. */
Merge(itr, rangeEnd, nextRangeEnd,followIt, scratchIt1,scratchIt2,comp);
/* Flag that we did at least one merge so we don't stop early. */
haveMerged = true;
/* Advance the iterator to the start of the next sequence, which is
* directly after the end of the second sorted range.
*/
itr = nextRangeEnd;
scratchIt1=scratchBegin1+(itr-begin);
scratchIt2=scratchBegin2+(itr-begin);
followIt=followBegin+(itr-begin);
}
return haveMerged;
}
}
/* Main implementation of the algorithm. */
template <typename ForwardIterator, typename FollowIt,typename Comparator>
void NaturalMergesort(ForwardIterator begin, ForwardIterator end,FollowIt followBegin, std::vector<typename std::iterator_traits<ForwardIterator>::value_type> & mainScratch,
std::vector<typename std::iterator_traits<FollowIt>::value_type> & followScratch,
Comparator comp) {
/* Make utility functions implicitly available. */
using namespace naturalmergesort_detail;
const size_t kBlockSize = 24;
/* As an edge case, if the input range is empty, we're trivially done. */
if (end-begin<2) return;
if((size_t)(end-begin)<kBlockSize){
InsertionSort(begin,end,comp,internal::DualSwapper<ForwardIterator,FollowIt>(begin,followBegin));
return;
}
/* Determine the type of the element being iterated over. */
mainScratch.resize(end-begin);
followScratch.resize(end-begin);
/* Create a vector of Ts that will hold the merged sequence. */
/* Track whether the current iteration of the algorithm has made any
* changes. If it didn't, then we can finish early.
*/
bool haveMerged;
/* Continuously loop, merging together ranges until the input is fully
* sorted.
*/
//boost::timer::cpu_timer findtimer;
size_t ctr=0;
do {
/* We have not yet merged anything, so clear this flag. */
//std::cout << "Iteration " << ctr++ << std::endl;
/* Scan forward in the loop, looking for adjacent pairs of sorted ranges
* and merging them.
*/
//we alternate whether we use the original container or the scrathspace to hold the merged lists
if(ctr%2==0){
haveMerged=MergeSortLoop(begin, end, followBegin, mainScratch.begin(), followScratch.begin(),comp);
}
else
haveMerged=MergeSortLoop(mainScratch.begin(), mainScratch.end(), followScratch.begin(), begin, followBegin,comp);
if(!haveMerged && ctr%2){ //if we are done, and the scratchspace holds the final merged lists, we need a final copy back
std::copy(mainScratch.begin(), mainScratch.end(),begin);
std::copy(followScratch.begin(), followScratch.end(),followBegin);
}
ctr++;
} while (haveMerged);
//std::cout << "finding time in sort " << boost::timer::format(findtimer.elapsed()) << std::endl;
}
template <typename Iter,typename ref_t>
ptrdiff_t gallopLeft(ref_t key, Iter const base, ptrdiff_t const len) {
assert( len > 0 );
if (key<=*base)
return 0;
typedef ptrdiff_t diff_t;
diff_t lastOfs = 0;
diff_t ofs = 1;
diff_t const maxOfs = len ;
while(ofs < maxOfs && key > *(base + ofs)) {
lastOfs = ofs;
ofs = (ofs << 1) + 1;
if(ofs <= 0) { // int overflow
ofs = maxOfs;
}
}
if(ofs > maxOfs) {
ofs = maxOfs;
}
assert( -1 <= lastOfs && lastOfs < ofs && ofs <= len );
return std::lower_bound(base+(lastOfs+1), base+ofs, key) - base;
}
template <typename Iter, typename ref_t>
ptrdiff_t gallopRight(ref_t key, Iter const base, ptrdiff_t const len) {
assert( len > 0);
if (key<*base)
return 0;
typedef ptrdiff_t diff_t;
diff_t ofs = 1;
diff_t lastOfs = 0;
diff_t const maxOfs = len;
while(ofs < maxOfs && key>= *(base + ofs)) {
lastOfs = ofs;
ofs = (ofs << 1) + 1;
if(ofs <= 0) { // int overflow
ofs = maxOfs;
}
}
if(ofs > maxOfs) {
ofs = maxOfs;
}
assert( 0 <= lastOfs && lastOfs < ofs && ofs <= len );
return std::upper_bound(base+(lastOfs+1), base+ofs, key) - base;
}
template <typename Iter, typename ref_t,typename Comp>
ptrdiff_t gallopRight(ref_t key, Iter const base, ptrdiff_t const len,Comp comp) {
assert( len > 0);
if (comp(key,*base))
return 0;
typedef ptrdiff_t diff_t;
diff_t ofs = 1;
diff_t lastOfs = 0;
diff_t const maxOfs = len;
while(ofs < maxOfs && !comp(key,*(base + ofs))) {
lastOfs = ofs;
ofs = (ofs << 1) + 1;
if(ofs <= 0) { // int overflow
ofs = maxOfs;
}
}
if(ofs > maxOfs) {
ofs = maxOfs;
}
assert( 0 <= lastOfs && lastOfs < ofs && ofs <= len );
return std::upper_bound(base+(lastOfs+1), base+ofs, key,comp) - base;
}
template <typename Iter,typename ref_t>
ptrdiff_t gallopLeftBack(ref_t key, Iter const base, ptrdiff_t const len) {
assert( len > 0 );
if(key>*(base+len-1))
return len;
typedef ptrdiff_t diff_t;
diff_t lastOfs = 0;
diff_t ofs = 1;
diff_t hint=len-1;
diff_t const maxOfs = len;
while(ofs < maxOfs && key<= *(base + (hint - ofs))) {
lastOfs = ofs;
ofs = (ofs << 1) + 1;
if(ofs <= 0) {
ofs = maxOfs;
}
}
if(ofs > maxOfs) {
ofs = maxOfs;
}
diff_t const tmp = lastOfs;
lastOfs = hint - ofs;
ofs = hint - tmp;
assert( -1 <= lastOfs && lastOfs < ofs && ofs <= len );
return std::lower_bound(base+(lastOfs+1), base+ofs, key) - base;
}
template<typename It, typename FollowIt>
void GallopMerge(It const base1, FollowIt const baseFollow1,ptrdiff_t len1, It const base2, FollowIt const baseFollow2,ptrdiff_t len2,It dest,FollowIt destFollow,bool do_copy=true) {
assert( len1 > 0 && len2 > 0 );
// std::cout << "First" << std::endl;
// for(auto it=base1;it<base1+len1;++it)
// std::cout << *it << " " ;
// std::cout << std::endl;
//
// std::cout << "Second" << std::endl;
// for(auto it=base2;it<base2+len2;++it)
// std::cout << *it << " " ;
// std::cout << std::endl;
typedef typename std::iterator_traits<It>::value_type index_type;
const size_t kBlockSize = 500;
if(len1+len2<kBlockSize){
std::copy(base1, base1+len1, dest);
std::copy(baseFollow1, baseFollow1+len1, destFollow);
if(do_copy){
std::copy(base2, base2+len2, dest+len1);
std::copy(baseFollow2, baseFollow2+len2, destFollow+len1);
}
Introsort(dest, dest+len1+len2, std::less<index_type>(),internal::DualSwapper<It,FollowIt>(dest,destFollow));
return;
}
typedef It iter_t;
typedef FollowIt iter_t2;
typedef ptrdiff_t diff_t;
iter_t cursor1 = base1;
iter_t cursor2 = base2;
iter_t2 cursorFollow1 = baseFollow1;
iter_t2 cursorFollow2 = baseFollow2;
diff_t k = gallopRight(*base2, base1, len1);
//std::cout << "First gallop right " << k << std::endl;
assert( k >= 0 );
if(k>0){
dest=std::copy(base1,base1+k,dest);
destFollow=std::copy(baseFollow1,baseFollow1+k,destFollow);
}
cursor1 += k;
cursorFollow1+=k;
len1 -= k;
if(len1 == 0) {
if (do_copy){
std::copy(cursor2, cursor2 + len2, dest);
std::copy(cursorFollow2, cursorFollow2 + len2, destFollow);
}
return;
}
k = gallopLeftBack(*(cursor1 + (len1 - 1)), base2, len2);
//std::cout << "First gallop left " << k << " " << len2 << std::endl;
if(k<len2){
if(do_copy){
std::copy_backward(base2+k,base2+len2,dest+len1+len2);
std::copy_backward(baseFollow2+k,baseFollow2+len2,destFollow+len1+len2);
}
len2=k;
}
assert(len2>=1);
*(dest++) = *(cursor2++);
*(destFollow++) = *(cursorFollow2++);
if(--len2 == 0) {
std::copy(cursor1, cursor1 + len1, dest);
std::copy(cursorFollow1, cursorFollow1 + len1, destFollow);
return;
}
if(len1 == 1) {
std::copy(cursor2, cursor2 + len2, dest);
std::copy(cursorFollow2, cursorFollow2 + len2, destFollow);
*(dest + len2) = *cursor1;
*(destFollow + len2) = *cursorFollow1;
return;
}
assert( len2 > 0 );
assert( len1 > 1 );
//std::cout << "Did setup" << std::endl;
int minGallop(_MIN_GALLOP_);
// outer:
while(true) {
int count1 = 0;
int count2 = 0;
//std::cout << "loop" << std::endl;
bool break_outer = false;
do {
assert( len1 > 1 && len2 > 0 );
if(*cursor2 < *cursor1) {
*(dest++) = *(cursor2++);
*(destFollow++) = *(cursorFollow2++);
++count2;
count1 = 0;
if(--len2 == 0) {
break_outer = true;
break;
}
}
else {
*(dest++) = *(cursor1++);
*(destFollow++) = *(cursorFollow1++);
++count1;
count2 = 0;
if(--len1 == 1) {
break_outer = true;
break;
}
}
} while( (count1 | count2) < minGallop );
if(break_outer) {
break;
}
do {
assert( len1 > 1 && len2 > 0 );
count1 = gallopRight(*cursor2, cursor1, len1);
assert(count1<len1);
if(count1 != 0) {
std::copy_backward(cursor1, cursor1 + count1, dest + count1);
std::copy_backward(cursorFollow1, cursorFollow1 + count1, destFollow + count1);
dest += count1;
cursor1 += count1;
destFollow += count1;
cursorFollow1 += count1;
len1 -= count1;
if(len1 <= 1) {
break_outer = true;
break;
}
}
*(dest++) = *(cursor2++);
*(destFollow++) = *(cursorFollow2++);
if(--len2 == 0) {
break_outer = true;
break;
}
count2 = gallopLeft(*cursor1, cursor2, len2);
assert(count2<=len2);
if(count2 != 0) {
std::copy(cursor2, cursor2 + count2, dest);
std::copy(cursorFollow2, cursorFollow2 + count2, destFollow);
dest += count2;
cursor2 += count2;
destFollow += count2;
cursorFollow2 += count2;
len2 -= count2;
if(len2 == 0) {
break_outer = true;
break;
}
}
*(dest++) = *(cursor1++);
*(destFollow++) = *(cursorFollow1++);
if(--len1 == 1) {
break_outer = true;
break;
}
--minGallop;
} while( (count1 >= _MIN_GALLOP_) | (count2 >= _MIN_GALLOP_) );
if(break_outer) {
break;
}
if(minGallop < 0) {
minGallop = 0;
}
minGallop += 2;
} // end of "outer" loop
//std::cout << "Finished loop" << std::endl;
if(len1 == 1) {
assert( len2 > 0 );
//std::cout << "len2" << len2 << std::endl;
std::copy(cursor2, cursor2 + len2, dest);
std::copy(cursorFollow2, cursorFollow2 + len2, destFollow);
*(dest + len2) = *cursor1;
*(destFollow + len2) = *cursorFollow1;
}
else {
assert( len1 != 0 && "Comparision function violates its general contract");
assert( len2 == 0 );
assert( len1 > 1 );
//std::cout << "len1" << len1 << std::endl;
std::copy(cursor1, cursor1 + len1, dest);
std::copy(cursorFollow1, cursorFollow1 + len1, destFollow);
}
//std::cout << "Finished merge" << std::endl;
}
template<typename ForwardIt, typename FollowIt>
void BlindMerge(ForwardIt begin1, ForwardIt end1, FollowIt followBegin1, ForwardIt begin2, ForwardIt end2,FollowIt followBegin2,ForwardIt output, FollowIt followOutput,int array_location_2,int array_location_output){
// std::cout << "First" << std::endl;
// for(auto it=begin1;it<end1;++it)
// std::cout << *it << std::endl;
// std::cout << std::endl;
// std::cout << "Second" << std::endl;
// for(auto it=begin2;it<end2;++it)
// std::cout << *it << std::endl;
// std::cout << std::endl;
//auto old_output=output;
//auto total=end1-begin1+end2-begin2;
typedef typename std::iterator_traits<ForwardIt>::value_type index_type;
const size_t kBlockSize = 500;
if(end1-begin1+end2-begin2<kBlockSize){
auto output_end=std::copy(begin1, end1, output);
auto it2=std::copy(followBegin1, followBegin1+(end1-begin1), followOutput);
if(array_location_2 !=array_location_output){
output_end=std::copy(begin2, end2, output_end);
std::copy(followBegin2, followBegin2+(end2-begin2), it2);
}
Introsort(output, output_end, std::less<index_type>(),internal::DualSwapper<ForwardIt,FollowIt>(output,followOutput));
return;
}
if(array_location_2 ==array_location_output){
while(end2>=begin2 && *(end2-1)>*(end1-1)){
end2--;
}
}
int inner_loop_iterations=std::min(end1-begin1,end2-begin2);;
while(inner_loop_iterations){
int idx=0;
for(;idx< ROUND_DOWN(inner_loop_iterations, 4);idx+=4){
if (*begin1<*begin2) { // First sequence has smaller element
*output++=*begin1++;
*followOutput++=*followBegin1++;
} else { // Second sequence has smaller element.
*output++=*begin2++;
*followOutput++=*followBegin2++;
}
if (*begin1<*begin2) { // First sequence has smaller element
*output++=*begin1++;
*followOutput++=*followBegin1++;
} else { // Second sequence has smaller element.
*output++=*begin2++;
*followOutput++=*followBegin2++;
}
if (*begin1<*begin2) { // First sequence has smaller element
*output++=*begin1++;
*followOutput++=*followBegin1++;
} else { // Second sequence has smaller element.
*output++=*begin2++;
*followOutput++=*followBegin2++;
}
if (*begin1<*begin2) { // First sequence has smaller element
*output++=*begin1++;
*followOutput++=*followBegin1++;
} else { // Second sequence has smaller element.
*output++=*begin2++;
*followOutput++=*followBegin2++;
}
}
for(;idx< inner_loop_iterations;++idx){
if (*begin1<*begin2) { // First sequence has smaller element
*output++=*begin1++;
*followOutput++=*followBegin1++;
} else { // Second sequence has smaller element.
*output++=*begin2++;
*followOutput++=*followBegin2++;
}
}
inner_loop_iterations=std::min(end1-begin1,end2-begin2);
}
if (begin2 == end2){
std::copy(begin1, end1, output);
std::copy(followBegin1, followBegin1+(end1-begin1), followOutput);
}
else{
if(array_location_2!=array_location_output){
std::copy(begin2, end2, output);
std::copy(followBegin2, followBegin2+(end2-begin2), followOutput);
}
}
// for(auto it=old_output;it<old_output+total;++it)
// std::cout << *it << " ";
// std::cout << std::endl;
}
template<typename index_type>
int getNextValidRun(int start, const std::vector<index_type>& array_locations){
int next_loc;
for(next_loc=start+1;next_loc<array_locations.size();++next_loc){
if(array_locations[next_loc]!=0)
break;
}
return next_loc;
}
template<typename ForwardIt, typename FollowIt,typename index_type>
int PingPongMerge(ForwardIt begin1, FollowIt followBegin1, ForwardIt begin2, FollowIt followBegin2,std::vector<index_type> & run_starts, std::vector<index_type> & run_sizes){
std::vector<index_type> array_locations(run_starts.size());
// std::cout << "Run starts" << std::endl;
// for(auto &x: run_starts)
// std::cout << x << " ";
// std::cout << std::endl;
for (auto& x: array_locations){
x=1;
}
int run_idx=0;
int run_idx_next=1;
int next_to_begin=1;
int run_total=run_starts.size();
auto elem_list_size=run_starts.size();
ForwardIt runStart2, runEnd2;
FollowIt runFollowStart2;
//boost::timer::cpu_timer blind_merge;
//blind_merge.stop();
//std::cout << "run totals " << run_total << std::endl;
while(elem_list_size>1){
//std::cout << "SANE" << std::endl;
if(run_idx_next>=run_total||run_sizes[run_idx]+run_sizes[run_idx_next]>run_sizes[0]+run_sizes[next_to_begin]){
run_idx=0;
run_idx_next=next_to_begin;
//std::cout << "We need to start loop over " << run_idx << " " << run_idx_next << std::endl;
}
else{
//assert(run_idx<run_total);
//assert(run_idx_next<run_total);
if(array_locations[run_idx_next]==1){
runStart2=begin1+run_starts[run_idx_next];
runFollowStart2=followBegin1+run_starts[run_idx_next];
}
else{
runStart2=begin2+run_starts[run_idx_next];
runFollowStart2=followBegin2+run_starts[run_idx_next];
}
runEnd2=runStart2+run_sizes[run_idx_next];
//std::cout << "About to merge " << run_idx << " and " << run_idx_next << std::endl;
//std::cout << "start is " << run_starts[run_idx] << " and " << run_starts[run_idx_next] << std::endl;
//std::cout << "size is " << run_sizes[run_idx] << " and " << run_sizes[run_idx_next] << std::endl;
if(array_locations[run_idx]==1){
//blind_merge.resume();
//GallopMerge(begin1+run_starts[run_idx], followBegin1+run_starts[run_idx],run_sizes[run_idx], runStart2, runFollowStart2,run_sizes[run_idx_next],begin2+run_starts[run_idx],followBegin2+run_starts[run_idx],array_locations[run_idx_next]==1);
BlindMerge(begin1+run_starts[run_idx],begin1+run_starts[run_idx]+run_sizes[run_idx],followBegin1+run_starts[run_idx],runStart2,runEnd2,runFollowStart2,begin2+run_starts[run_idx],followBegin2+run_starts[run_idx],array_locations[run_idx_next],2);
//blind_merge.stop();
array_locations[run_idx]=2;
}
else{
// blind_merge.resume();
//GallopMerge(begin2+run_starts[run_idx], followBegin2+run_starts[run_idx],run_sizes[run_idx], runStart2, runFollowStart2,run_sizes[run_idx_next],begin1+run_starts[run_idx],followBegin1+run_starts[run_idx],array_locations[run_idx_next]==2);
BlindMerge(begin2+run_starts[run_idx],begin2+run_starts[run_idx]+run_sizes[run_idx],followBegin2+run_starts[run_idx],runStart2,runEnd2,runFollowStart2,begin1+run_starts[run_idx],followBegin1+run_starts[run_idx],array_locations[run_idx_next],1);
//blind_merge.stop();
array_locations[run_idx]=1;
}
array_locations[run_idx_next]=0;
//std::cout <<"Done merge " <<std::endl;
run_sizes[run_idx]+=run_sizes[run_idx_next];
run_idx=getNextValidRun(run_idx,array_locations);
//std::cout << "sanity " << run_idx_next << " and " << next_to_begin << std::endl;
if (run_idx_next==next_to_begin){
next_to_begin=run_idx;
//std::cout << "Next to begin updated " << next_to_begin << std::endl;
}
//std::cout << "Got valid run " << run_idx << std::endl;
run_idx_next=getNextValidRun(run_idx,array_locations);
//std::cout << "Got next valid run " << run_idx_next << std::endl;
elem_list_size--;
}
}
// std::cout << "Blind Merge " << boost::timer::format(blind_merge.elapsed()) << std::endl;
//std::cout << "Finsihed" << elem_list_size << std::endl;
return array_locations[0];
}
template<typename index_type>
void SortRunsBySize(std::vector<index_type>& run_sizes,std::vector<index_type>& head_offsets,std::vector<index_type>& run_designations){
std::vector<index_type> run_refs(run_sizes.size());
std::vector<index_type> run_refs2(run_sizes.size());
typedef decltype(run_refs.begin()) it_type;
for(auto _idx=0;_idx<run_refs.size();++_idx){
run_refs[_idx]=_idx;
}
// std::cout << "Run sizes" << std::endl;
// for(auto &x: run_sizes)
// std::cout << x << " ";
// std::cout << std::endl;
//sort runs by size
internal::Introsort(run_sizes.begin(),run_sizes.end(),std::less<index_type>(),internal::TripleSwapper<it_type,it_type,it_type>(run_sizes.begin(),head_offsets.begin(),run_refs.begin()));
//reverse the run specifications
for(auto _idx=0;_idx<run_refs.size();++_idx){
run_refs2[run_refs[_idx]]=_idx+1; //run designations are 1-indexed
}
// std::cout << "Run refs" << std::endl;
// for(auto &x: run_refs2)
// std::cout << x << " ";
// std::cout << std::endl;
//update the run designations to the sorted layout
for(auto it=run_designations.begin();it<run_designations.end();++it){
if(*it>0)
*it=run_refs2[*it-1];
else
*it=-1*(run_refs2[std::abs(*it)-1]);
}
}
template <typename ForwardIt,typename FollowIt>
void PerformPatienceRun(ForwardIt begin, ForwardIt end,FollowIt followBegin, std::vector<typename std::iterator_traits<ForwardIt>::value_type> & mainScratch,
std::vector<typename std::iterator_traits<FollowIt>::value_type> & followScratch) {
//boost::timer::cpu_timer total, setup;
//first let's record the number of runs and their size
typedef typename std::iterator_traits<ForwardIt>::value_type index_type;
std::vector<index_type> tails;
std::vector<index_type> heads;
std::vector<index_type> run_sizes;
std::vector<index_type> head_offsets;
std::vector<index_type> temp_starts;
std::vector<index_type> run_starts;
std::vector<index_type> copy_space(end-begin);
auto cur_it=begin;
heads.reserve(std::floor(std::sqrt(end-begin)));
tails.reserve(std::floor(std::sqrt(end-begin)));
run_sizes.reserve(std::floor(std::sqrt(end-begin)));
head_offsets.reserve(std::floor(std::sqrt(end-begin)));
head_offsets.push_back(0);
heads.push_back(*cur_it);
index_type cur_min=*cur_it;
index_type cur_max=*cur_it;
tails.push_back(*cur_it++);
run_sizes.push_back(1);
auto search_region=tails.size();
copy_space[0]=1;
decltype(tails.begin()) find_it;
//boost::timer::cpu_timer creating_runs,finding_timer;
//std::cout << "Setup " << boost::timer::format(setup.elapsed()) << std::endl;
//std::cout << "Current tail " << *(tails.begin()) << std::endl;
while(cur_it<end){
if(*cur_it>cur_min){
//finding_timer.resume();
find_it=std::upper_bound(tails.end()-search_region,tails.end(),*cur_it,std::greater<index_type>());
//auto k=gallopRight(*cur_it, tails.end()-search_region, search_region,std::greater<index_type>());
//find_it=tails.end()-search_region+k;
//finding_timer.stop();
//std::cout << "for val " << *cur_it << " found tail " << *find_it << std::endl;
auto run_number=find_it-tails.begin();
copy_space[cur_it-begin]=run_number+1; //record the run number where the current index should reside in
*find_it=*cur_it++;
run_sizes[run_number]++;
if(find_it!=tails.begin()){
while(cur_it< end && *cur_it>*find_it && *cur_it<*(find_it-1)){
copy_space[cur_it-begin]=run_number+1;
*find_it=*cur_it++;
run_sizes[run_number]++;
}
}
else{
while(cur_it<end && *cur_it>*find_it){
copy_space[cur_it-begin]=run_number+1;
*find_it=*cur_it++;
run_sizes[run_number]++;
}
}
if(find_it==tails.end()-1)
cur_min=*(cur_it-1);
}
// else if(*cur_it<cur_max){
// //finding_timer.resume();
// //find_it=std::lower_bound(heads.end()-search_region,heads.end(),*cur_it);
// auto k=gallopRight(*cur_it, heads.end()-search_region, search_region);
// find_it=heads.end()-search_region+k;
// //finding_timer.stop();
// //std::cout << "for val " << *cur_it << " found head " << *find_it << std::endl;
// auto run_number=find_it-heads.begin();
// copy_space[cur_it-begin]=-1*(run_number+1); //record the run number where the current index should reside in
// *find_it=*cur_it++;
// run_sizes[run_number]++;
// head_offsets[run_number]++;
//// if(find_it!=heads.begin()){
//// while(cur_it< end && *cur_it<*find_it && *cur_it>*(find_it-1)){
//// copy_space[cur_it-begin]=-1*(run_number+1);
//// *find_it=*cur_it++;
//// run_sizes[run_number]++;
//// head_offsets[run_number]++;
////
//// }
//// }
//// else{
//// while(cur_it<end && *cur_it<*find_it){
//// copy_space[cur_it-begin]=run_number+1;
//// *find_it=*cur_it++;
//// run_sizes[run_number]++;
//// head_offsets[run_number]++;
////
//// }
//// }
// if(find_it==heads.end()-1)
// cur_max=*(cur_it-1);
// }
else{
// std::cout << "Making new run " << *cur_it << std::endl;;
copy_space[cur_it-begin]=tails.size()+1;
heads.push_back(*cur_it);
tails.push_back(*cur_it++);
head_offsets.push_back(0);
run_sizes.push_back(1);
//search_region=tails.size();
search_region=std::min(tails.size(),(size_t)1000);
cur_min=*(cur_it-1);
cur_max=*(cur_it-1);
}
}
//std::cout << "Creating runs " << boost::timer::format(creating_runs.elapsed()) << " there are " << run_sizes.size() << std::endl;
//std::cout << "Finding runs " << boost::timer::format(finding_timer.elapsed()) << std::endl;
// for(auto it=begin;it<end;++it)
// std::cout << *it << " ";
// std::cout << std::endl;
// for(auto&x: run_sizes)
// std::cout << x << " ";
// std::cout << std::endl;
//sort by run_sizes, and update the runs designations array to reflect hte new sort order
//boost::timer::cpu_timer sorting_runs;
SortRunsBySize(run_sizes,head_offsets,copy_space);
//std::cout << "Sorting runs " << boost::timer::format(sorting_runs.elapsed()) << std::endl;
// std::cout << "Sorted" << std::endl;
// for(auto&x: run_sizes)
// std::cout << x << " ";
// std::cout << std::endl;
//
// for(auto&x: copy_space)
// std::cout << x << " ";
// std::cout << std::endl;
//calculate run_starts
run_starts.resize(run_sizes.size());
run_starts[0]=0;
for(auto _idx=1;_idx<run_sizes.size();++_idx){
run_starts[_idx]=run_starts[_idx-1]+run_sizes[_idx-1];
}
std::vector<index_type> head_starts=head_offsets;
cur_it=begin;
auto follow_it=followBegin;
// for(auto it=begin;it<end;++it){
// std::cout << *it << " " ;
// }
// std::cout << std::endl;
// for(auto it=copy_space.begin();it<copy_space.end();++it){
// std::cout << *it << " " ;
// }
// std::cout << std::endl;
//pack the runs in, with smallest runs going in first
//boost::timer::cpu_timer packing_runs;
int cur_run_start,cur_head_offset;
for(auto _idx=0;_idx<end-begin;++_idx,++cur_it,++follow_it){
//std::cout << "Taking " << _idx << "run " << copy_space[_idx] << "put into " << temp_starts[copy_space[_idx]] << std::endl;
auto cur_run=std::abs(copy_space[_idx])-1;
if(copy_space[_idx]>0){
cur_run_start=run_starts[cur_run]+head_offsets[cur_run];
head_offsets[cur_run]++;
}
else{
cur_run_start=run_starts[cur_run]+head_starts[cur_run]-1;
head_starts[cur_run]--;
}
mainScratch[cur_run_start]=*cur_it;
followScratch[cur_run_start]=*follow_it;
}
//std::cout << "Packing runs " << boost::timer::format(packing_runs.elapsed()) << std::endl;
// for(auto it=mainScratch.begin();it<mainScratch.end();++it){
// std::cout << *it << std::endl;
// }
// std::cout << "main scratch done" << std::endl;
//boost::timer::cpu_timer merging_runs;
int last_array=PingPongMerge(mainScratch.begin(),followScratch.begin(),begin, followBegin, run_starts, run_sizes);
if (last_array==1){
std::copy(mainScratch.begin(), mainScratch.end(),begin);
std::copy(followScratch.begin(), followScratch.end(),followBegin);
}
//gfx::timsort(begin,end,followBegin,followBegin+(end-begin),mainScratch,followScratch);
//std::cout << "Merging runs " << boost::timer::format(packing_runs.elapsed()) << std::endl;
//std::cout << "Total " << boost::timer::format(total.elapsed()) << std::endl;
// auto it2=mainScratch.begin();
// for(auto it=begin;it<end;++it){
// std::cout << *it << std::endl;
// }
//std::cout << "Finished merge " << *begin << std::endl;
}
template<typename index_type>
void SortRunsBySize(std::vector<int>& run_sizes,std::vector<index_type>& run_designations){
std::vector<int> run_refs(run_sizes.size());
std::vector<int> run_refs2(run_sizes.size());
typedef decltype(run_refs.begin()) it_type;
for(auto _idx=0;_idx<run_refs.size();++_idx){
run_refs[_idx]=_idx;
}
// std::cout << "Run sizes" << std::endl;
// for(auto &x: run_sizes)
// std::cout << x << " ";
// std::cout << std::endl;
//sort runs by size
internal::Introsort(run_sizes.begin(),run_sizes.end(),std::less<index_type>(),internal::DualSwapper<it_type,it_type>(run_sizes.begin(),run_refs.begin()));
//reverse the run specifications
for(auto _idx=0;_idx<run_refs.size();++_idx){
run_refs2[run_refs[_idx]]=_idx; //run designations are 1-indexed
}
// std::cout << "Run refs" << std::endl;
// for(auto &x: run_refs2)
// std::cout << x << " ";
// std::cout << std::endl;
//update the run designations to the sorted layout
for(auto it=run_designations.begin();it<run_designations.end();++it){
*it=run_refs2[*it];
}
}
template <typename ForwardIt,typename FollowIt>
void PingPongSortRuns(ForwardIt begin, ForwardIt end,FollowIt followBegin, std::vector<typename std::iterator_traits<ForwardIt>::value_type> & mainScratch,
std::vector<typename std::iterator_traits<FollowIt>::value_type> & followScratch) {
// for(auto it=begin;it<end;++it){
// std::cout << *it << std::endl;
// }
std::vector<int> run_sizes;
run_sizes.reserve(std::floor(std::sqrt(end-begin)));
std::vector<int> run_designations(end-begin);
run_sizes.push_back(1);
for(auto cur_it=begin+1;cur_it<end;++cur_it){
if(*cur_it>=*(cur_it-1)){
run_sizes.back()++;
run_designations[cur_it-begin]=run_sizes.size()-1;
}
else{
run_sizes.push_back(1);
run_designations[cur_it-begin]=run_sizes.size()-1;
}
}
// for(auto &x:run_sizes){
// std::cout << x<< std::endl;
// }
SortRunsBySize(run_sizes,run_designations);
std::vector<int> run_starts(run_sizes.size());
run_starts[0]=0;
for(auto _idx=1;_idx<run_sizes.size();++_idx){
run_starts[_idx]=run_starts[_idx-1]+run_sizes[_idx-1];
}
auto temp_starts=run_starts;
auto cur_it=begin;
auto follow_it=followBegin;
for(auto _idx=0;_idx<end-begin;++_idx,++cur_it,++follow_it){
//std::cout << "Taking " << _idx << "run " << copy_space[_idx] << "put into " << temp_starts[copy_space[_idx]] << std::endl;
auto cur_run=run_designations[_idx];
auto cur_run_start=temp_starts[cur_run];
mainScratch[cur_run_start]=*cur_it;
followScratch[cur_run_start]=*follow_it;
temp_starts[cur_run]++;
}
int last_array=PingPongMerge(mainScratch.begin(),followScratch.begin(),begin, followBegin, run_starts, run_sizes);
if (last_array==1){
std::copy(mainScratch.begin(), mainScratch.end(),begin);
std::copy(followScratch.begin(), followScratch.end(),followBegin);
}
// auto it2=mainScratch.begin();
// for(auto it=begin;it<end;++it){
// std::cout << *it << std::endl;
// }
}
template<typename MainIterator,typename FollowIterator,typename ScratchIterator,typename ScratchIterator2,typename HistIt,typename BufferIt, typename FollowBufferIt,unsigned long Radix,unsigned long bufferSize>
void RadixIteration(MainIterator begin, FollowIterator followBegin,ScratchIterator scratchIt1, ScratchIterator2 scratchIt2,HistIt histIt,BufferIt bufferIt,FollowBufferIt followBufferIt,size_t length,unsigned long shift_amount){
//std::cout << "RadixIteration bitMask " << bitMask << " shift_amount " << shift_amount << std::endl;
constexpr unsigned long bitMask=Radix-1;
std::array<unsigned int, Radix> bufferCounts;
for(auto &i: bufferCounts)
i=0;
auto followIt=followBegin;
for (auto it=begin;it<begin+length;++it,++followIt) {
auto pos = *it>>shift_amount & bitMask;
//std::cout << "*it " << *it << " pos " << pos << " histIt[pos] " << histIt[pos] << std::endl;
*(bufferIt+pos*bufferSize+bufferCounts[pos])=*it;
*(followBufferIt+pos*bufferSize+bufferCounts[pos]++)=*followIt;
if(bufferCounts[pos]==bufferSize){
std::copy(bufferIt+pos*bufferSize,bufferIt+(pos+1)*bufferSize,scratchIt1 + histIt[pos]);
std::copy(followBufferIt+pos*bufferSize,followBufferIt+(pos+1)*bufferSize,scratchIt2 + histIt[pos]);
histIt[pos]+=bufferSize; //update the histogram counter
bufferCounts[pos]=0; //reset the buffer ctr
}
}
for(int i=0;i<Radix;++i){
if(bufferCounts[i]){
std::copy(bufferIt+i*bufferSize,bufferIt+i*bufferSize+bufferCounts[i],scratchIt1 + histIt[i]);
std::copy(followBufferIt+i*bufferSize,followBufferIt+i*bufferSize+bufferCounts[i],scratchIt2 + histIt[i]);
}
}
}
template<typename MainIterator,typename FollowIterator,typename ScratchIterator,typename ScratchIterator2,typename HistIt,unsigned long Radix>
void RadixIteration(MainIterator begin, FollowIterator followBegin,ScratchIterator scratchIt1, ScratchIterator2 scratchIt2,HistIt histIt,size_t length,unsigned long shift_amount){
//std::cout << "RadixIteration bitMask " << bitMask << " shift_amount " << shift_amount << std::endl;
constexpr unsigned long bitMask=Radix-1;
auto followIt=followBegin;
for (auto it=begin;it<begin+length;++it,++followIt) {
auto pos = *it>>shift_amount & bitMask;
//std::cout << "*it " << *it << " pos " << pos << " histIt[pos] " << histIt[pos]+1 << std::endl;
*(scratchIt1 + histIt[pos]) = *it;
//std::cout << "Assigned scratchIt1" << std::endl;
*(scratchIt2 + histIt[pos]++) = *followIt;
//std::cout << "Assigned scratchIt2" << std::endl;
}
}
template<typename MainIterator,typename FollowIterator,typename ScratchIterator,typename ScratchIterator2>
void RadixSort(MainIterator begin, MainIterator end, FollowIterator followBegin,ScratchIterator scratchIt1, ScratchIterator2 scratchIt2, typename std::iterator_traits<MainIterator>::value_type max_size) {
typedef typename std::iterator_traits<MainIterator>::value_type index_type;
typedef typename std::iterator_traits<FollowIterator>::value_type follow_type;
static_assert(std::is_integral<index_type>::value,"Must input an integral type for main interator");
constexpr unsigned long Radix = 2048;
constexpr unsigned long bitMask = Radix-1;
constexpr unsigned long bit_size = 11;
constexpr unsigned long bufferSize=8;
auto current_bit_size=(unsigned long)std::ceil(std::log2(max_size));
unsigned long pass_number=std::ceil((double)current_bit_size/bit_size);
typedef std::vector<size_t> Hist;
Hist histograms(Radix*pass_number,0);
typedef std::array<index_type,Radix*bufferSize> Buffer;
Buffer buffer;
typedef std::array<follow_type,Radix*bufferSize> FollowBuffer;
FollowBuffer followBuffer;
typedef typename Hist::iterator HistIt;
typedef typename Buffer::iterator BufferIt;
typedef typename FollowBuffer::iterator FollowBufferIt;
//std::cout << "Histcount " << histCount << std::endl;
auto hist_begin=histograms.begin();
// 1. parallel histogramming pass
//
for (auto it=begin; it < end; ++it) {
auto val=*it;
for(int i=0;i<pass_number;++i){
auto curHistBegin=hist_begin+i*Radix;
size_t pos=val>>(i*bit_size) & bitMask;
curHistBegin[pos]++;
}
}
std::vector<size_t> sums(pass_number,0);
size_t tsum;
for(int j=0;j<pass_number;++j){
auto curHistBegin=hist_begin+j*Radix;
for (size_t i = 0; i < Radix; ++i) {
tsum=*(curHistBegin+i)+sums[j];
*(curHistBegin+i)=sums[j];
sums[j]=tsum;
}
}
size_t length=end-begin;
int starting_pass=1; //pass number starts at one, skipping hte most LSD
unsigned long shift_amount=starting_pass*bit_size;
//std::cout << "pass_number " << pass_number << std::endl;
for(int i=starting_pass;i<pass_number;++i){
// for(auto it=histograms.begin()+i*kHist;it<histograms.begin()+(i+1)*kHist;++it)
// std::cout << *it << std::endl;
if ((i-starting_pass)%2==0){
RadixIteration<MainIterator,FollowIterator,ScratchIterator,ScratchIterator2,HistIt,BufferIt,FollowBufferIt,Radix,bufferSize>(begin,followBegin,scratchIt1,scratchIt2,
histograms.begin()+i*Radix,buffer.begin(),followBuffer.begin(),length,shift_amount);
}
else{
RadixIteration<MainIterator,FollowIterator,ScratchIterator,ScratchIterator2,HistIt,BufferIt,FollowBufferIt,Radix,bufferSize>(scratchIt1,scratchIt2,begin,followBegin,
histograms.begin()+i*Radix,buffer.begin(),followBuffer.begin(),length,shift_amount);
}
shift_amount+=bit_size;
//std::cout << "Pass " << i << std::endl;
}
//if the elements remain in the scratch arrays, copy them back to the appropriate location
if(std::max((int)pass_number-starting_pass,0)%2==1){
std::copy(scratchIt1,scratchIt1+length,begin);
std::copy(scratchIt2,scratchIt2+length,followBegin);
}
InsertionSortImproved(begin,begin+length,followBegin,std::less<index_type>()); //clean up
}
} // namespace internal
}// namespace LibMIA
#endif // LIBMIAALGORITHM
| 35.893413 | 260 | 0.602704 |
4f3777c1ccad0247d18f6c1f0cbd19d3ae214fc2 | 341 | asm | Assembly | libsrc/stdio/mc1000/conio_vars.asm | jpoikela/z88dk | 7108b2d7e3a98a77de99b30c9a7c9199da9c75cb | [
"ClArtistic"
] | 640 | 2017-01-14T23:33:45.000Z | 2022-03-30T11:28:42.000Z | libsrc/stdio/mc1000/conio_vars.asm | jpoikela/z88dk | 7108b2d7e3a98a77de99b30c9a7c9199da9c75cb | [
"ClArtistic"
] | 1,600 | 2017-01-15T16:12:02.000Z | 2022-03-31T12:11:12.000Z | libsrc/stdio/mc1000/conio_vars.asm | jpoikela/z88dk | 7108b2d7e3a98a77de99b30c9a7c9199da9c75cb | [
"ClArtistic"
] | 215 | 2017-01-17T10:43:03.000Z | 2022-03-23T17:25:02.000Z |
SECTION data_clib
PUBLIC __mc1000_modeval
PUBLIC __mc1000_mode
PUBLIC __ink_colour
PUBLIC __MODE2_attr
__mc1000_mode: defb 0x00 ; 0 = text, 1 = hires, 2 = colour
__mc1000_modeval: defb 0x00 ; lores mode 0x9e ;hires mode
__ink_colour: defb 7
__MODE2_attr: defb @11000000,@00000000
| 24.357143 | 86 | 0.665689 |
df14dfa478a991b601182737cfca2115777e4095 | 1,904 | lua | Lua | modules/heroes/BGs.lua | D-m-L/evonara | 0c70f25ca9a833599929ac5895722357721ce61e | [
"MIT"
] | null | null | null | modules/heroes/BGs.lua | D-m-L/evonara | 0c70f25ca9a833599929ac5895722357721ce61e | [
"MIT"
] | null | null | null | modules/heroes/BGs.lua | D-m-L/evonara | 0c70f25ca9a833599929ac5895722357721ce61e | [
"MIT"
] | null | null | null | local Sky = {}
function Sky:init()
self.canvas = lg.newCanvas(scrn.w / scrn.scl, scrn.h / scrn.scl)
self.tcanvas = lg.newCanvas(scrn.w / scrn.scl, scrn.h / scrn.scl)
self.topcolor = {111, 60, 103, 255}
self.botcolor = {250, 190, 120, 255}
self.img = lg.newImage('gfx/skies/sky3.png')
self.imgh = self.img:getHeight()
self.imgw = self.img:getWidth()
self.cloud = lg.newImage('gfx/skies/clound.png')
self.cloudtrans = 150
self.x = 000
self.y = 0
self.r = 0
self.clouds = {}
for i = 1, 10 do
self.clouds[i] = ents.Create( "bgcloud", math.random(1, scrn.w), math.random(1, scrn.h) )
end
-- self.ct = math.randXYZtable( 50, 24 * 200 / 8, 24 * 200 / 8)
end
function Sky:update()
end
function Sky:draw(player)
lg.setCanvas(self.canvas)
--Draw the top color box
lg.setColor(self.topcolor)
lg.rectangle('fill', 0, 0, scrn.w, scrn.h * scrn.vscl)
--Draw the bottom color box, taking into account if there is a player reference
lg.setColor(self.botcolor)
local px
if player then px = math.floor(-player.x / 32) else px = 0 end
lg.rectangle('fill', 0, scrn.h/16 + self.imgh * cam.zoom, scrn.w, scrn.h)
--Draw the sky image
lg.setColor(white)
lg.draw(self.img, px - self.imgw / 2, self.imgh * cam.zoom, 0, 1 / cam.zoom * cam.zoom, 1 / cam.zoom * cam.zoom )
-- lg.draw(sky.img, 0, 100, 0, 1, 1)
self:drawClouds(player)
lg.setCanvas(canvas)
lg.setColor(white)
lg.draw(self.canvas, scrn.x, scrn.y, scrn.r, 1, 1 * scrn.vscl, 0, 0, scrn.xsk, scrn.ysk)
lg.setColor(255,255,255, self.cloudtrans)
lg.draw(self.tcanvas, scrn.x, scrn.y, scrn.r, 1, 1 * scrn.vscl, 0, 0, scrn.xsk, scrn.ysk)
--lg.draw(self.canvas, 0, 0, 0, scrn.scl, scrn.vscl)
end
function Sky:drawClouds(player)
lg.setCanvas(self.tcanvas)
love.graphics.setBackgroundColor(0,0,0,0)
lg.clear(self.canvas)
for i = 1, 10 do
self.clouds[i]:skydraw()
end
end
return Sky | 31.213115 | 115 | 0.657038 |
46d13c4c03ff3e6e70a99adda3095c3e0fe9631e | 1,760 | html | HTML | other/js/13.html | 5201314999/draftCode | ae76f9d97a9e5b23ca0fec4862048cafbde34595 | [
"MIT"
] | null | null | null | other/js/13.html | 5201314999/draftCode | ae76f9d97a9e5b23ca0fec4862048cafbde34595 | [
"MIT"
] | 9 | 2021-03-09T12:06:23.000Z | 2022-03-26T05:41:48.000Z | other/js/13.html | 5201314999/draftCode | ae76f9d97a9e5b23ca0fec4862048cafbde34595 | [
"MIT"
] | null | null | null | <!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title>防抖函数,节流函数的封装测试</title>
<meta name='viewport' content='width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no' />
<meta name="description" content="">
<meta name="keywords" content="">
<link href="" rel="stylesheet">
<style>
#test {
height: 200px;
background-color: rgba(0, 0, 0, 0.65);
color: red;
text-align: center;
font-size: 30px;
}
</style>
</head>
<body>
<!-- <input type="text" id="test"> -->
<div id="test"></div>
<script>
'use strict';
function throttle(fn, delay) {
let lastDate = 0, timeout;
let context = this;
// console.log(context);
return (...args)=> {
console.log(args);
let nowDate = + new Date();
if (nowDate - lastDate >= delay) {
lastDate = nowDate;
fn.apply(context,args);
}
clearTimeout(timeout);
timeout = setTimeout(() => {
fn.appl(context,args);
}, delay);
}
}
let obj = {
funA: function () {
let funB=throttle((event,a)=>{
console.log(a);
console.log('借宿');
},2000);
document.getElementById('test').addEventListener('mousemove',function(){
funB(event,'222');
});
}
}
obj.funA();
</script>
</body>
</html> | 28.387097 | 122 | 0.448295 |
c1e91081ee5426617560e096c1c686c4daf79988 | 469 | asm | Assembly | data/pokemon/base_stats/sinnoh/tangrowth.asm | Dev727/ancientplatinum | 8b212a1728cc32a95743e1538b9eaa0827d013a7 | [
"blessing"
] | null | null | null | data/pokemon/base_stats/sinnoh/tangrowth.asm | Dev727/ancientplatinum | 8b212a1728cc32a95743e1538b9eaa0827d013a7 | [
"blessing"
] | null | null | null | data/pokemon/base_stats/sinnoh/tangrowth.asm | Dev727/ancientplatinum | 8b212a1728cc32a95743e1538b9eaa0827d013a7 | [
"blessing"
] | null | null | null | db 0 ; 465 DEX NO
db 100, 100, 125, 50, 110, 50
; hp atk def spd sat sdf
db GRASS, GRASS ; type
db 30 ; catch rate
db 211 ; base exp
db NO_ITEM, NO_ITEM ; items
db GENDER_F50 ; gender ratio
db 100 ; unknown 1
db 20 ; step cycles to hatch
db 5 ; unknown 2
INCBIN "gfx/pokemon/sinnoh/tangrowth/front.dimensions"
db 0, 0, 0, 0 ; padding
db GROWTH_MEDIUM_FAST ; growth rate
dn EGG_PLANT, EGG_PLANT ; egg groups
; tm/hm learnset
tmhm
; end
| 21.318182 | 55 | 0.667377 |
872884a21661c409a3f5f3158c1cbc7a71ea2b43 | 7,686 | swift | Swift | iOS-sample-projects/firefox-ios-master/Client/Frontend/Browser/TabPeekViewController.swift | atierian/privacyflash-pro | 1953aef307c8ec4b26274fb16af103672f534601 | [
"MIT"
] | 142 | 2020-01-06T11:06:05.000Z | 2022-02-14T00:37:29.000Z | iOS-sample-projects/firefox-ios-master/Client/Frontend/Browser/TabPeekViewController.swift | atierian/privacyflash-pro | 1953aef307c8ec4b26274fb16af103672f534601 | [
"MIT"
] | 24 | 2020-01-12T20:30:15.000Z | 2022-02-13T02:46:00.000Z | iOS-sample-projects/firefox-ios-master/Client/Frontend/Browser/TabPeekViewController.swift | atierian/privacyflash-pro | 1953aef307c8ec4b26274fb16af103672f534601 | [
"MIT"
] | 10 | 2020-01-06T23:14:28.000Z | 2021-08-12T13:48:21.000Z | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import UIKit
import Shared
import Storage
import WebKit
protocol TabPeekDelegate: AnyObject {
func tabPeekDidAddBookmark(_ tab: Tab)
@discardableResult func tabPeekDidAddToReadingList(_ tab: Tab) -> ReadingListItem?
func tabPeekRequestsPresentationOf(_ viewController: UIViewController)
func tabPeekDidCloseTab(_ tab: Tab)
}
class TabPeekViewController: UIViewController, WKNavigationDelegate {
fileprivate static let PreviewActionAddToBookmarks = NSLocalizedString("Add to Bookmarks", tableName: "3DTouchActions", comment: "Label for preview action on Tab Tray Tab to add current tab to Bookmarks")
fileprivate static let PreviewActionCopyURL = NSLocalizedString("Copy URL", tableName: "3DTouchActions", comment: "Label for preview action on Tab Tray Tab to copy the URL of the current tab to clipboard")
fileprivate static let PreviewActionCloseTab = NSLocalizedString("Close Tab", tableName: "3DTouchActions", comment: "Label for preview action on Tab Tray Tab to close the current tab")
weak var tab: Tab?
fileprivate weak var delegate: TabPeekDelegate?
fileprivate var fxaDevicePicker: UINavigationController?
fileprivate var isBookmarked: Bool = false
fileprivate var isInReadingList: Bool = false
fileprivate var hasRemoteClients: Bool = false
fileprivate var ignoreURL: Bool = false
fileprivate var screenShot: UIImageView?
fileprivate var previewAccessibilityLabel: String!
fileprivate var webView: WKWebView?
// Preview action items.
override var previewActionItems: [UIPreviewActionItem] {
get {
return previewActions
}
}
lazy var previewActions: [UIPreviewActionItem] = {
var actions = [UIPreviewActionItem]()
let urlIsTooLongToSave = self.tab?.urlIsTooLong ?? false
if !self.ignoreURL && !urlIsTooLongToSave {
if !self.isBookmarked {
actions.append(UIPreviewAction(title: TabPeekViewController.PreviewActionAddToBookmarks, style: .default) { [weak self] previewAction, viewController in
guard let wself = self, let tab = wself.tab else { return }
wself.delegate?.tabPeekDidAddBookmark(tab)
})
}
if self.hasRemoteClients {
actions.append(UIPreviewAction(title: Strings.SendToDeviceTitle, style: .default) { [weak self] previewAction, viewController in
guard let wself = self, let clientPicker = wself.fxaDevicePicker else { return }
wself.delegate?.tabPeekRequestsPresentationOf(clientPicker)
})
}
// only add the copy URL action if we don't already have 3 items in our list
// as we are only allowed 4 in total and we always want to display close tab
if actions.count < 3 {
actions.append(UIPreviewAction(title: TabPeekViewController.PreviewActionCopyURL, style: .default) {[weak self] previewAction, viewController in
guard let wself = self, let url = wself.tab?.canonicalURL else { return }
UIPasteboard.general.url = url
SimpleToast().showAlertWithText(Strings.AppMenuCopyURLConfirmMessage, bottomContainer: wself.view)
})
}
}
actions.append(UIPreviewAction(title: TabPeekViewController.PreviewActionCloseTab, style: .destructive) { [weak self] previewAction, viewController in
guard let wself = self, let tab = wself.tab else { return }
wself.delegate?.tabPeekDidCloseTab(tab)
})
return actions
}()
init(tab: Tab, delegate: TabPeekDelegate?) {
self.tab = tab
self.delegate = delegate
super.init(nibName: nil, bundle: nil)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
webView?.navigationDelegate = nil
self.webView = nil
}
override func viewDidLoad() {
super.viewDidLoad()
if let webViewAccessibilityLabel = tab?.webView?.accessibilityLabel {
previewAccessibilityLabel = String(format: NSLocalizedString("Preview of %@", tableName: "3DTouchActions", comment: "Accessibility label, associated to the 3D Touch action on the current tab in the tab tray, used to display a larger preview of the tab."), webViewAccessibilityLabel)
}
// if there is no screenshot, load the URL in a web page
// otherwise just show the screenshot
setupWebView(tab?.webView)
guard let screenshot = tab?.screenshot else { return }
setupWithScreenshot(screenshot)
}
fileprivate func setupWithScreenshot(_ screenshot: UIImage) {
let imageView = UIImageView(image: screenshot)
self.view.addSubview(imageView)
imageView.snp.makeConstraints { make in
make.edges.equalTo(self.view)
}
screenShot = imageView
screenShot?.accessibilityLabel = previewAccessibilityLabel
}
fileprivate func setupWebView(_ webView: WKWebView?) {
guard let webView = webView, let url = webView.url, !isIgnoredURL(url) else { return }
let clonedWebView = WKWebView(frame: webView.frame, configuration: webView.configuration)
clonedWebView.allowsLinkPreview = false
clonedWebView.accessibilityLabel = previewAccessibilityLabel
self.view.addSubview(clonedWebView)
clonedWebView.snp.makeConstraints { make in
make.edges.equalTo(self.view)
}
clonedWebView.navigationDelegate = self
self.webView = clonedWebView
clonedWebView.load(URLRequest(url: url))
}
func setState(withProfile browserProfile: BrowserProfile, clientPickerDelegate: DevicePickerViewControllerDelegate) {
assert(Thread.current.isMainThread)
guard let tab = self.tab else {
return
}
guard let displayURL = tab.url?.absoluteString, !displayURL.isEmpty else {
return
}
browserProfile.places.isBookmarked(url: displayURL) >>== { isBookmarked in
self.isBookmarked = isBookmarked
}
browserProfile.remoteClientsAndTabs.getClientGUIDs().uponQueue(.main) {
guard let clientGUIDs = $0.successValue else {
return
}
self.hasRemoteClients = !clientGUIDs.isEmpty
let clientPickerController = DevicePickerViewController()
clientPickerController.pickerDelegate = clientPickerDelegate
clientPickerController.profile = browserProfile
clientPickerController.profileNeedsShutdown = false
if let url = tab.url?.absoluteString {
clientPickerController.shareItem = ShareItem(url: url, title: tab.title, favicon: nil)
}
self.fxaDevicePicker = UINavigationController(rootViewController: clientPickerController)
}
let result = browserProfile.readingList.getRecordWithURL(displayURL).value.successValue
self.isInReadingList = !(result?.url.isEmpty ?? true)
self.ignoreURL = isIgnoredURL(displayURL)
}
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
screenShot?.removeFromSuperview()
screenShot = nil
}
}
| 43.423729 | 294 | 0.677726 |
bff2e3bb2f0309e236cb8fd20a196c29bdfc9c82 | 1,657 | rs | Rust | other-benchmarks/rust-gql/src/schema.rs | negezor/node-graphql-benchmarks | e33c6c9fd3a5b7b6179d688f67c3ebf3b851b1d4 | [
"MIT"
] | null | null | null | other-benchmarks/rust-gql/src/schema.rs | negezor/node-graphql-benchmarks | e33c6c9fd3a5b7b6179d688f67c3ebf3b851b1d4 | [
"MIT"
] | null | null | null | other-benchmarks/rust-gql/src/schema.rs | negezor/node-graphql-benchmarks | e33c6c9fd3a5b7b6179d688f67c3ebf3b851b1d4 | [
"MIT"
] | null | null | null | use async_graphql::{ComplexObject, EmptyMutation, EmptySubscription, ID, Object, Schema, SimpleObject};
use md5;
use uuid::Uuid;
use rand::Rng;
use fake::{self, Fake};
#[derive(SimpleObject)]
pub struct Book {
pub id: ID,
pub name: String,
pub num_pages: i32,
}
#[derive(SimpleObject)]
#[graphql(complex)]
pub struct Author {
pub id: ID,
pub name: String,
pub company: String,
#[graphql(skip)]
books: Vec<Book>,
}
#[ComplexObject]
impl Author {
async fn md5(&self) -> String {
format!("{:x}", md5::compute(self.name.as_bytes()))
}
async fn books(&self) -> &Vec<Book> {
&self.books
}
}
pub struct QueryRoot;
#[Object]
impl QueryRoot {
async fn authors(&self) -> Vec<Author> {
let mut authors: Vec<Author> = vec![];
for _i in 0..20 {
let mut books: Vec<Book> = vec![];
for _i in 0..3 {
books.push(Book {
id: ID(format!("{}", Uuid::new_v4())),
name: fake::faker::name::en::LastName().fake(),
num_pages: rand::thread_rng().gen_range(100..10000),
});
}
authors.push(Author {
id: ID(format!("{}", Uuid::new_v4())),
name: fake::faker::name::en::FirstName().fake(),
company: fake::faker::company::en::Bs().fake(),
books
});
}
authors
}
}
pub type ServerSchema = Schema<QueryRoot, EmptyMutation, EmptySubscription>;
pub fn new_schema() -> ServerSchema {
Schema::new(QueryRoot, EmptyMutation, EmptySubscription)
} | 23.338028 | 103 | 0.537719 |
7e4c3890a9fa4b20269ffc0ac97790d04823ac1a | 2,460 | sql | SQL | users.sql | ajanyan/transfer | b86bed565c3bed26f96aad26d1b10465ae1346db | [
"MIT"
] | null | null | null | users.sql | ajanyan/transfer | b86bed565c3bed26f96aad26d1b10465ae1346db | [
"MIT"
] | null | null | null | users.sql | ajanyan/transfer | b86bed565c3bed26f96aad26d1b10465ae1346db | [
"MIT"
] | 2 | 2018-10-02T19:32:59.000Z | 2018-12-05T11:33:50.000Z | -- phpMyAdmin SQL Dump
-- version 4.6.4
-- https://www.phpmyadmin.net/
--
-- Host: 127.0.0.1
-- Generation Time: Aug 29, 2018 at 04:56 PM
-- Server version: 5.7.14
-- PHP Version: 5.6.25
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET time_zone = "+00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;
--
-- Database: `transfer`
--
-- --------------------------------------------------------
--
-- Table structure for table `users`
--
CREATE TABLE `users` (
`id` int(11) NOT NULL,
`name` varchar(100) COLLATE utf8_unicode_ci NOT NULL,
`email` varchar(100) COLLATE utf8_unicode_ci NOT NULL,
`password` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`gender` enum('Male','Female') COLLATE utf8_unicode_ci NOT NULL,
`phone` varchar(15) COLLATE utf8_unicode_ci NOT NULL,
`created` datetime NOT NULL,
`modified` datetime NOT NULL,
`status` enum('1','0') COLLATE utf8_unicode_ci NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
--
-- Dumping data for table `users`
--
INSERT INTO `users` (`id`, `name`, `email`, `password`, `gender`, `phone`, `created`, `modified`, `status`) VALUES
(1, 'clince', 'clincepro@gmail.com', 'qwerty', 'Male', '9447626859', '2018-08-08 00:00:00', '2018-08-16 00:00:00', '1'),
(2, 'Clince Joshy', 'clince@gmail.com', 'd8578edf8458ce06fbc5bb76a58c5ca4', 'Male', '9447626859', '2018-08-28 15:03:39', '2018-08-28 15:03:39', '1'),
(3, 'demo', 'demo@dd.com', '006d2143154327a64d86a264aea225f3', 'Male', '23', '2018-08-29 01:34:33', '2018-08-29 01:34:33', '1'),
(4, 'Clince Joshy', 'c@gmail.com', 'd8578edf8458ce06fbc5bb76a58c5ca4', 'Male', '9447626859', '2018-08-29 14:05:40', '2018-08-29 14:05:40', '1'),
(5, 'cc', 'cc@cc.com', '76d80224611fc919a5d54f0ff9fba446', 'Male', '1', '2018-08-29 16:55:23', '2018-08-29 16:55:23', '1');
--
-- Indexes for dumped tables
--
--
-- Indexes for table `users`
--
ALTER TABLE `users`
ADD PRIMARY KEY (`id`);
--
-- AUTO_INCREMENT for dumped tables
--
--
-- AUTO_INCREMENT for table `users`
--
ALTER TABLE `users`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=6;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
| 33.243243 | 149 | 0.673171 |
5c5de85ff109900998ba7753f49938d04df6bfcb | 3,301 | c | C | firmware/test/commands/test_command_controller_map_motors.c | kbhomes/ps2plus | 63467133367082ec06c88e5c0fd623373709717e | [
"MIT"
] | null | null | null | firmware/test/commands/test_command_controller_map_motors.c | kbhomes/ps2plus | 63467133367082ec06c88e5c0fd623373709717e | [
"MIT"
] | null | null | null | firmware/test/commands/test_command_controller_map_motors.c | kbhomes/ps2plus | 63467133367082ec06c88e5c0fd623373709717e | [
"MIT"
] | null | null | null | #include "test_commands.h"
#define MM_COMMAND_ID 0x4D
#define MM_PAYLOAD_SIZE 6
const uint8_t MM_PAYLOAD_MAP_SMALL_MOTOR[MM_PAYLOAD_SIZE] = { 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF };
const uint8_t MM_PAYLOAD_MAP_LARGE_MOTOR[MM_PAYLOAD_SIZE] = { 0xFF, 0x01, 0xFF, 0xFF, 0xFF, 0xFF };
const uint8_t MM_PAYLOAD_MAP_BOTH_MOTORS[MM_PAYLOAD_SIZE] = { 0x00, 0x01, 0xFF, 0xFF, 0xFF, 0xFF };
const uint8_t MM_PAYLOAD_MAP_NO_MOTORS[MM_PAYLOAD_SIZE] = { 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF };
void test_command_controller_map_motors_small_motor() {
uint8_t *actual_output = helper_run_command(&state, MM_COMMAND_ID, MM_PAYLOAD_MAP_SMALL_MOTOR, MM_PAYLOAD_SIZE);
TEST_ASSERT_EQUAL_HEX8_ARRAY_MESSAGE(MM_PAYLOAD_MAP_NO_MOTORS, actual_output, MM_PAYLOAD_SIZE, "Motors should initially be unmapped");
TEST_ASSERT_EQUAL_HEX8_MESSAGE(0x00, state.rumble_motor_small.mapping, "Small motor should be mapped");
TEST_ASSERT_EQUAL_HEX8_MESSAGE(0xFF, state.rumble_motor_large.mapping, "Large motor should be unmapped");
}
void test_command_controller_map_motors_large_motor() {
uint8_t *actual_output = helper_run_command(&state, MM_COMMAND_ID, MM_PAYLOAD_MAP_LARGE_MOTOR, MM_PAYLOAD_SIZE);
TEST_ASSERT_EQUAL_HEX8_ARRAY_MESSAGE(MM_PAYLOAD_MAP_NO_MOTORS, actual_output, MM_PAYLOAD_SIZE, "Motors should initially be unmapped");
TEST_ASSERT_EQUAL_HEX8_MESSAGE(0xFF, state.rumble_motor_small.mapping, "Small motor should be unmapped");
TEST_ASSERT_EQUAL_HEX8_MESSAGE(0x01, state.rumble_motor_large.mapping, "Large motor should be mapped");
}
void test_command_controller_map_motors_both_motors() {
uint8_t *actual_output = helper_run_command(&state, MM_COMMAND_ID, MM_PAYLOAD_MAP_BOTH_MOTORS, MM_PAYLOAD_SIZE);
TEST_ASSERT_EQUAL_HEX8_ARRAY_MESSAGE(MM_PAYLOAD_MAP_NO_MOTORS, actual_output, MM_PAYLOAD_SIZE, "Motors should initially be unmapped");
TEST_ASSERT_EQUAL_HEX8_MESSAGE(0x00, state.rumble_motor_small.mapping, "Small motor should be mapped");
TEST_ASSERT_EQUAL_HEX8_MESSAGE(0x01, state.rumble_motor_large.mapping, "Large motor should be mapped");
}
void test_command_controller_map_motors_no_motors() {
uint8_t *actual_output = helper_run_command(&state, MM_COMMAND_ID, MM_PAYLOAD_MAP_NO_MOTORS, MM_PAYLOAD_SIZE);
TEST_ASSERT_EQUAL_HEX8_ARRAY_MESSAGE(MM_PAYLOAD_MAP_NO_MOTORS, actual_output, MM_PAYLOAD_SIZE, "Motors should initially be unmapped");
TEST_ASSERT_EQUAL_HEX8_MESSAGE(0xFF, state.rumble_motor_small.mapping, "Small motor should be unmapped");
TEST_ASSERT_EQUAL_HEX8_MESSAGE(0xFF, state.rumble_motor_large.mapping, "Large motor should be unmapped");
}
void test_command_controller_map_motors_retains_mappings() {
// Process two consecutive motor mapping commands
uint8_t *first_output = helper_run_command(&state, MM_COMMAND_ID, MM_PAYLOAD_MAP_BOTH_MOTORS, MM_PAYLOAD_SIZE);
uint8_t *second_output = helper_run_command(&state, MM_COMMAND_ID, MM_PAYLOAD_MAP_SMALL_MOTOR, MM_PAYLOAD_SIZE);
// Each new command should output the controller's previous motor mappings
TEST_ASSERT_EQUAL_HEX8_ARRAY_MESSAGE(MM_PAYLOAD_MAP_NO_MOTORS, first_output, MM_PAYLOAD_SIZE, "Motors should be unmapped before first command");
TEST_ASSERT_EQUAL_HEX8_ARRAY_MESSAGE(MM_PAYLOAD_MAP_BOTH_MOTORS, second_output, MM_PAYLOAD_SIZE, "Motors should both be mapped before second command");
} | 70.234043 | 153 | 0.834293 |
f9a68156bcaaf0055dbe55b6c47403e4e8fb06c4 | 27,910 | lua | Lua | MMOCoreORB/bin/scripts/object/custom_content/draft_schematic/droid/component/objects.lua | V-Fib/FlurryClone | 40e0ca7245ec31b3815eb6459329fd9e70f88936 | [
"Zlib",
"OpenSSL"
] | 18 | 2017-02-09T15:36:05.000Z | 2021-12-21T04:22:15.000Z | MMOCoreORB/bin/scripts/object/custom_content/draft_schematic/droid/component/objects.lua | V-Fib/FlurryClone | 40e0ca7245ec31b3815eb6459329fd9e70f88936 | [
"Zlib",
"OpenSSL"
] | 61 | 2016-12-30T21:51:10.000Z | 2021-12-10T20:25:56.000Z | MMOCoreORB/bin/scripts/object/custom_content/draft_schematic/droid/component/objects.lua | V-Fib/FlurryClone | 40e0ca7245ec31b3815eb6459329fd9e70f88936 | [
"Zlib",
"OpenSSL"
] | 71 | 2017-01-01T05:34:38.000Z | 2022-03-29T01:04:00.000Z | object_draft_schematic_droid_component_shared_armor_bio_cartridge = SharedDraftSchematicObjectTemplate:new {
clientTemplateFileName = "object/draft_schematic/droid/component/shared_armor_bio_cartridge.iff"
}
ObjectTemplates:addClientTemplate(object_draft_schematic_droid_component_shared_armor_bio_cartridge, "object/draft_schematic/droid/component/shared_armor_bio_cartridge.iff")
------------------------------------------------------------------------------------------------------------------------------------
object_draft_schematic_droid_component_shared_chassis_droid_8d8 = SharedDraftSchematicObjectTemplate:new {
clientTemplateFileName = "object/draft_schematic/droid/component/shared_chassis_droid_8d8.iff"
}
ObjectTemplates:addClientTemplate(object_draft_schematic_droid_component_shared_chassis_droid_8d8, "object/draft_schematic/droid/component/shared_chassis_droid_8d8.iff")
------------------------------------------------------------------------------------------------------------------------------------
object_draft_schematic_droid_component_shared_chassis_droid_asn_21 = SharedDraftSchematicObjectTemplate:new {
clientTemplateFileName = "object/draft_schematic/droid/component/shared_chassis_droid_asn_21.iff"
}
ObjectTemplates:addClientTemplate(object_draft_schematic_droid_component_shared_chassis_droid_asn_21, "object/draft_schematic/droid/component/shared_chassis_droid_asn_21.iff")
------------------------------------------------------------------------------------------------------------------------------------
object_draft_schematic_droid_component_shared_chassis_droid_battle = SharedDraftSchematicObjectTemplate:new {
clientTemplateFileName = "object/draft_schematic/droid/component/shared_chassis_droid_battle.iff"
}
ObjectTemplates:addClientTemplate(object_draft_schematic_droid_component_shared_chassis_droid_battle, "object/draft_schematic/droid/component/shared_chassis_droid_battle.iff")
------------------------------------------------------------------------------------------------------------------------------------
object_draft_schematic_droid_component_shared_chassis_droid_cww8 = SharedDraftSchematicObjectTemplate:new {
clientTemplateFileName = "object/draft_schematic/droid/component/shared_chassis_droid_cww8.iff"
}
ObjectTemplates:addClientTemplate(object_draft_schematic_droid_component_shared_chassis_droid_cww8, "object/draft_schematic/droid/component/shared_chassis_droid_cww8.iff")
------------------------------------------------------------------------------------------------------------------------------------
object_draft_schematic_droid_component_shared_chassis_droid_droideka = SharedDraftSchematicObjectTemplate:new {
clientTemplateFileName = "object/draft_schematic/droid/component/shared_chassis_droid_droideka.iff"
}
ObjectTemplates:addClientTemplate(object_draft_schematic_droid_component_shared_chassis_droid_droideka, "object/draft_schematic/droid/component/shared_chassis_droid_droideka.iff")
------------------------------------------------------------------------------------------------------------------------------------
object_draft_schematic_droid_component_shared_chassis_droid_dwarf_spider = SharedDraftSchematicObjectTemplate:new {
clientTemplateFileName = "object/draft_schematic/droid/component/shared_chassis_droid_dwarf_spider.iff"
}
ObjectTemplates:addClientTemplate(object_draft_schematic_droid_component_shared_chassis_droid_dwarf_spider, "object/draft_schematic/droid/component/shared_chassis_droid_dwarf_spider.iff")
------------------------------------------------------------------------------------------------------------------------------------
object_draft_schematic_droid_component_shared_chassis_droid_guardian_mark_2 = SharedDraftSchematicObjectTemplate:new {
clientTemplateFileName = "object/draft_schematic/droid/component/shared_chassis_droid_guardian_mark_2.iff"
}
ObjectTemplates:addClientTemplate(object_draft_schematic_droid_component_shared_chassis_droid_guardian_mark_2, "object/draft_schematic/droid/component/shared_chassis_droid_guardian_mark_2.iff")
------------------------------------------------------------------------------------------------------------------------------------
object_draft_schematic_droid_component_shared_chassis_droid_ins_444 = SharedDraftSchematicObjectTemplate:new {
clientTemplateFileName = "object/draft_schematic/droid/component/shared_chassis_droid_ins_444.iff"
}
ObjectTemplates:addClientTemplate(object_draft_schematic_droid_component_shared_chassis_droid_ins_444, "object/draft_schematic/droid/component/shared_chassis_droid_ins_444.iff")
------------------------------------------------------------------------------------------------------------------------------------
object_draft_schematic_droid_component_shared_chassis_droid_lin_demolition = SharedDraftSchematicObjectTemplate:new {
clientTemplateFileName = "object/draft_schematic/droid/component/shared_chassis_droid_lin_demolition.iff"
}
ObjectTemplates:addClientTemplate(object_draft_schematic_droid_component_shared_chassis_droid_lin_demolition, "object/draft_schematic/droid/component/shared_chassis_droid_lin_demolition.iff")
------------------------------------------------------------------------------------------------------------------------------------
object_draft_schematic_droid_component_shared_chassis_droid_magnaguard = SharedDraftSchematicObjectTemplate:new {
clientTemplateFileName = "object/draft_schematic/droid/component/shared_chassis_droid_magnaguard.iff"
}
ObjectTemplates:addClientTemplate(object_draft_schematic_droid_component_shared_chassis_droid_magnaguard, "object/draft_schematic/droid/component/shared_chassis_droid_magnaguard.iff")
------------------------------------------------------------------------------------------------------------------------------------
object_draft_schematic_droid_component_shared_chassis_droid_mark_iv_sentry = SharedDraftSchematicObjectTemplate:new {
clientTemplateFileName = "object/draft_schematic/droid/component/shared_chassis_droid_mark_iv_sentry.iff"
}
ObjectTemplates:addClientTemplate(object_draft_schematic_droid_component_shared_chassis_droid_mark_iv_sentry, "object/draft_schematic/droid/component/shared_chassis_droid_mark_iv_sentry.iff")
------------------------------------------------------------------------------------------------------------------------------------
object_draft_schematic_droid_component_shared_chassis_droid_mining = SharedDraftSchematicObjectTemplate:new {
clientTemplateFileName = "object/draft_schematic/droid/component/shared_chassis_droid_mining.iff"
}
ObjectTemplates:addClientTemplate(object_draft_schematic_droid_component_shared_chassis_droid_mining, "object/draft_schematic/droid/component/shared_chassis_droid_mining.iff")
------------------------------------------------------------------------------------------------------------------------------------
object_draft_schematic_droid_component_shared_chassis_droid_pit = SharedDraftSchematicObjectTemplate:new {
clientTemplateFileName = "object/draft_schematic/droid/component/shared_chassis_droid_pit.iff"
}
ObjectTemplates:addClientTemplate(object_draft_schematic_droid_component_shared_chassis_droid_pit, "object/draft_schematic/droid/component/shared_chassis_droid_pit.iff")
------------------------------------------------------------------------------------------------------------------------------------
object_draft_schematic_droid_component_shared_chassis_droid_spider = SharedDraftSchematicObjectTemplate:new {
clientTemplateFileName = "object/draft_schematic/droid/component/shared_chassis_droid_spider.iff"
}
ObjectTemplates:addClientTemplate(object_draft_schematic_droid_component_shared_chassis_droid_spider, "object/draft_schematic/droid/component/shared_chassis_droid_spider.iff")
------------------------------------------------------------------------------------------------------------------------------------
object_draft_schematic_droid_component_shared_chassis_droid_super_battle = SharedDraftSchematicObjectTemplate:new {
clientTemplateFileName = "object/draft_schematic/droid/component/shared_chassis_droid_super_battle.iff"
}
ObjectTemplates:addClientTemplate(object_draft_schematic_droid_component_shared_chassis_droid_super_battle, "object/draft_schematic/droid/component/shared_chassis_droid_super_battle.iff")
------------------------------------------------------------------------------------------------------------------------------------
object_draft_schematic_droid_component_shared_chassis_droid_union_sentry = SharedDraftSchematicObjectTemplate:new {
clientTemplateFileName = "object/draft_schematic/droid/component/shared_chassis_droid_union_sentry.iff"
}
ObjectTemplates:addClientTemplate(object_draft_schematic_droid_component_shared_chassis_droid_union_sentry, "object/draft_schematic/droid/component/shared_chassis_droid_union_sentry.iff")
------------------------------------------------------------------------------------------------------------------------------------
object_draft_schematic_droid_component_shared_combat_module_droideka_shield = SharedDraftSchematicObjectTemplate:new {
clientTemplateFileName = "object/draft_schematic/droid/component/shared_combat_module_droideka_shield.iff"
}
ObjectTemplates:addClientTemplate(object_draft_schematic_droid_component_shared_combat_module_droideka_shield, "object/draft_schematic/droid/component/shared_combat_module_droideka_shield.iff")
------------------------------------------------------------------------------------------------------------------------------------
object_draft_schematic_droid_component_shared_combat_module_electric_shocker = SharedDraftSchematicObjectTemplate:new {
clientTemplateFileName = "object/draft_schematic/droid/component/shared_combat_module_electric_shocker.iff"
}
ObjectTemplates:addClientTemplate(object_draft_schematic_droid_component_shared_combat_module_electric_shocker, "object/draft_schematic/droid/component/shared_combat_module_electric_shocker.iff")
------------------------------------------------------------------------------------------------------------------------------------
object_draft_schematic_droid_component_shared_combat_module_flame_jet = SharedDraftSchematicObjectTemplate:new {
clientTemplateFileName = "object/draft_schematic/droid/component/shared_combat_module_flame_jet.iff"
}
ObjectTemplates:addClientTemplate(object_draft_schematic_droid_component_shared_combat_module_flame_jet, "object/draft_schematic/droid/component/shared_combat_module_flame_jet.iff")
------------------------------------------------------------------------------------------------------------------------------------
object_draft_schematic_droid_component_shared_combat_module_rapid_discharge_batteries = SharedDraftSchematicObjectTemplate:new {
clientTemplateFileName = "object/draft_schematic/droid/component/shared_combat_module_rapid_discharge_batteries.iff"
}
ObjectTemplates:addClientTemplate(object_draft_schematic_droid_component_shared_combat_module_rapid_discharge_batteries, "object/draft_schematic/droid/component/shared_combat_module_rapid_discharge_batteries.iff")
------------------------------------------------------------------------------------------------------------------------------------
object_draft_schematic_droid_component_shared_combat_module_regenerative_plating = SharedDraftSchematicObjectTemplate:new {
clientTemplateFileName = "object/draft_schematic/droid/component/shared_combat_module_regenerative_plating.iff"
}
ObjectTemplates:addClientTemplate(object_draft_schematic_droid_component_shared_combat_module_regenerative_plating, "object/draft_schematic/droid/component/shared_combat_module_regenerative_plating.iff")
------------------------------------------------------------------------------------------------------------------------------------
object_draft_schematic_droid_component_shared_combat_module_torture_panel = SharedDraftSchematicObjectTemplate:new {
clientTemplateFileName = "object/draft_schematic/droid/component/shared_combat_module_torture_panel.iff"
}
ObjectTemplates:addClientTemplate(object_draft_schematic_droid_component_shared_combat_module_torture_panel, "object/draft_schematic/droid/component/shared_combat_module_torture_panel.iff")
------------------------------------------------------------------------------------------------------------------------------------
object_draft_schematic_droid_component_shared_combat_only_socket_bank = SharedDraftSchematicObjectTemplate:new {
clientTemplateFileName = "object/draft_schematic/droid/component/shared_combat_only_socket_bank.iff"
}
ObjectTemplates:addClientTemplate(object_draft_schematic_droid_component_shared_combat_only_socket_bank, "object/draft_schematic/droid/component/shared_combat_only_socket_bank.iff")
------------------------------------------------------------------------------------------------------------------------------------
object_draft_schematic_droid_component_shared_cybernetic_acid_resist_module_one_core = SharedDraftSchematicObjectTemplate:new {
clientTemplateFileName = "object/draft_schematic/droid/component/shared_cybernetic_acid_resist_module_one_core.iff"
}
ObjectTemplates:addClientTemplate(object_draft_schematic_droid_component_shared_cybernetic_acid_resist_module_one_core, "object/draft_schematic/droid/component/shared_cybernetic_acid_resist_module_one_core.iff")
------------------------------------------------------------------------------------------------------------------------------------
object_draft_schematic_droid_component_shared_cybernetic_acid_resist_module_three_core = SharedDraftSchematicObjectTemplate:new {
clientTemplateFileName = "object/draft_schematic/droid/component/shared_cybernetic_acid_resist_module_three_core.iff"
}
ObjectTemplates:addClientTemplate(object_draft_schematic_droid_component_shared_cybernetic_acid_resist_module_three_core, "object/draft_schematic/droid/component/shared_cybernetic_acid_resist_module_three_core.iff")
------------------------------------------------------------------------------------------------------------------------------------
object_draft_schematic_droid_component_shared_cybernetic_acid_resist_module_two_core = SharedDraftSchematicObjectTemplate:new {
clientTemplateFileName = "object/draft_schematic/droid/component/shared_cybernetic_acid_resist_module_two_core.iff"
}
ObjectTemplates:addClientTemplate(object_draft_schematic_droid_component_shared_cybernetic_acid_resist_module_two_core, "object/draft_schematic/droid/component/shared_cybernetic_acid_resist_module_two_core.iff")
------------------------------------------------------------------------------------------------------------------------------------
object_draft_schematic_droid_component_shared_cybernetic_action_stat_module_arm_leg = SharedDraftSchematicObjectTemplate:new {
clientTemplateFileName = "object/draft_schematic/droid/component/shared_cybernetic_action_stat_module_arm_leg.iff"
}
ObjectTemplates:addClientTemplate(object_draft_schematic_droid_component_shared_cybernetic_action_stat_module_arm_leg, "object/draft_schematic/droid/component/shared_cybernetic_action_stat_module_arm_leg.iff")
------------------------------------------------------------------------------------------------------------------------------------
object_draft_schematic_droid_component_shared_cybernetic_action_stat_module_forearm = SharedDraftSchematicObjectTemplate:new {
clientTemplateFileName = "object/draft_schematic/droid/component/shared_cybernetic_action_stat_module_forearm.iff"
}
ObjectTemplates:addClientTemplate(object_draft_schematic_droid_component_shared_cybernetic_action_stat_module_forearm, "object/draft_schematic/droid/component/shared_cybernetic_action_stat_module_forearm.iff")
------------------------------------------------------------------------------------------------------------------------------------
object_draft_schematic_droid_component_shared_cybernetic_action_stat_module_torso = SharedDraftSchematicObjectTemplate:new {
clientTemplateFileName = "object/draft_schematic/droid/component/shared_cybernetic_action_stat_module_torso.iff"
}
ObjectTemplates:addClientTemplate(object_draft_schematic_droid_component_shared_cybernetic_action_stat_module_torso, "object/draft_schematic/droid/component/shared_cybernetic_action_stat_module_torso.iff")
------------------------------------------------------------------------------------------------------------------------------------
object_draft_schematic_droid_component_shared_cybernetic_cold_resist_module_one_core = SharedDraftSchematicObjectTemplate:new {
clientTemplateFileName = "object/draft_schematic/droid/component/shared_cybernetic_cold_resist_module_one_core.iff"
}
ObjectTemplates:addClientTemplate(object_draft_schematic_droid_component_shared_cybernetic_cold_resist_module_one_core, "object/draft_schematic/droid/component/shared_cybernetic_cold_resist_module_one_core.iff")
------------------------------------------------------------------------------------------------------------------------------------
object_draft_schematic_droid_component_shared_cybernetic_cold_resist_module_three_core = SharedDraftSchematicObjectTemplate:new {
clientTemplateFileName = "object/draft_schematic/droid/component/shared_cybernetic_cold_resist_module_three_core.iff"
}
ObjectTemplates:addClientTemplate(object_draft_schematic_droid_component_shared_cybernetic_cold_resist_module_three_core, "object/draft_schematic/droid/component/shared_cybernetic_cold_resist_module_three_core.iff")
------------------------------------------------------------------------------------------------------------------------------------
object_draft_schematic_droid_component_shared_cybernetic_cold_resist_module_two_core = SharedDraftSchematicObjectTemplate:new {
clientTemplateFileName = "object/draft_schematic/droid/component/shared_cybernetic_cold_resist_module_two_core.iff"
}
ObjectTemplates:addClientTemplate(object_draft_schematic_droid_component_shared_cybernetic_cold_resist_module_two_core, "object/draft_schematic/droid/component/shared_cybernetic_cold_resist_module_two_core.iff")
------------------------------------------------------------------------------------------------------------------------------------
object_draft_schematic_droid_component_shared_cybernetic_electrical_resist_module_one_core = SharedDraftSchematicObjectTemplate:new {
clientTemplateFileName = "object/draft_schematic/droid/component/shared_cybernetic_electrical_resist_module_one_core.iff"
}
ObjectTemplates:addClientTemplate(object_draft_schematic_droid_component_shared_cybernetic_electrical_resist_module_one_core, "object/draft_schematic/droid/component/shared_cybernetic_electrical_resist_module_one_core.iff")
------------------------------------------------------------------------------------------------------------------------------------
object_draft_schematic_droid_component_shared_cybernetic_electrical_resist_module_three_core = SharedDraftSchematicObjectTemplate:new {
clientTemplateFileName = "object/draft_schematic/droid/component/shared_cybernetic_electrical_resist_module_three_core.iff"
}
ObjectTemplates:addClientTemplate(object_draft_schematic_droid_component_shared_cybernetic_electrical_resist_module_three_core, "object/draft_schematic/droid/component/shared_cybernetic_electrical_resist_module_three_core.iff")
------------------------------------------------------------------------------------------------------------------------------------
object_draft_schematic_droid_component_shared_cybernetic_electrical_resist_module_two_core = SharedDraftSchematicObjectTemplate:new {
clientTemplateFileName = "object/draft_schematic/droid/component/shared_cybernetic_electrical_resist_module_two_core.iff"
}
ObjectTemplates:addClientTemplate(object_draft_schematic_droid_component_shared_cybernetic_electrical_resist_module_two_core, "object/draft_schematic/droid/component/shared_cybernetic_electrical_resist_module_two_core.iff")
------------------------------------------------------------------------------------------------------------------------------------
object_draft_schematic_droid_component_shared_cybernetic_health_stat_module_arm_leg = SharedDraftSchematicObjectTemplate:new {
clientTemplateFileName = "object/draft_schematic/droid/component/shared_cybernetic_health_stat_module_arm_leg.iff"
}
ObjectTemplates:addClientTemplate(object_draft_schematic_droid_component_shared_cybernetic_health_stat_module_arm_leg, "object/draft_schematic/droid/component/shared_cybernetic_health_stat_module_arm_leg.iff")
------------------------------------------------------------------------------------------------------------------------------------
object_draft_schematic_droid_component_shared_cybernetic_health_stat_module_forearm = SharedDraftSchematicObjectTemplate:new {
clientTemplateFileName = "object/draft_schematic/droid/component/shared_cybernetic_health_stat_module_forearm.iff"
}
ObjectTemplates:addClientTemplate(object_draft_schematic_droid_component_shared_cybernetic_health_stat_module_forearm, "object/draft_schematic/droid/component/shared_cybernetic_health_stat_module_forearm.iff")
------------------------------------------------------------------------------------------------------------------------------------
object_draft_schematic_droid_component_shared_cybernetic_health_stat_module_torso = SharedDraftSchematicObjectTemplate:new {
clientTemplateFileName = "object/draft_schematic/droid/component/shared_cybernetic_health_stat_module_torso.iff"
}
ObjectTemplates:addClientTemplate(object_draft_schematic_droid_component_shared_cybernetic_health_stat_module_torso, "object/draft_schematic/droid/component/shared_cybernetic_health_stat_module_torso.iff")
------------------------------------------------------------------------------------------------------------------------------------
object_draft_schematic_droid_component_shared_cybernetic_heat_resist_module_one_core = SharedDraftSchematicObjectTemplate:new {
clientTemplateFileName = "object/draft_schematic/droid/component/shared_cybernetic_heat_resist_module_one_core.iff"
}
ObjectTemplates:addClientTemplate(object_draft_schematic_droid_component_shared_cybernetic_heat_resist_module_one_core, "object/draft_schematic/droid/component/shared_cybernetic_heat_resist_module_one_core.iff")
------------------------------------------------------------------------------------------------------------------------------------
object_draft_schematic_droid_component_shared_cybernetic_heat_resist_module_three_core = SharedDraftSchematicObjectTemplate:new {
clientTemplateFileName = "object/draft_schematic/droid/component/shared_cybernetic_heat_resist_module_three_core.iff"
}
ObjectTemplates:addClientTemplate(object_draft_schematic_droid_component_shared_cybernetic_heat_resist_module_three_core, "object/draft_schematic/droid/component/shared_cybernetic_heat_resist_module_three_core.iff")
------------------------------------------------------------------------------------------------------------------------------------
object_draft_schematic_droid_component_shared_cybernetic_heat_resist_module_two_core = SharedDraftSchematicObjectTemplate:new {
clientTemplateFileName = "object/draft_schematic/droid/component/shared_cybernetic_heat_resist_module_two_core.iff"
}
ObjectTemplates:addClientTemplate(object_draft_schematic_droid_component_shared_cybernetic_heat_resist_module_two_core, "object/draft_schematic/droid/component/shared_cybernetic_heat_resist_module_two_core.iff")
------------------------------------------------------------------------------------------------------------------------------------
object_draft_schematic_droid_component_shared_data_storage_module_7 = SharedDraftSchematicObjectTemplate:new {
clientTemplateFileName = "object/draft_schematic/droid/component/shared_data_storage_module_7.iff"
}
ObjectTemplates:addClientTemplate(object_draft_schematic_droid_component_shared_data_storage_module_7, "object/draft_schematic/droid/component/shared_data_storage_module_7.iff")
------------------------------------------------------------------------------------------------------------------------------------
object_draft_schematic_droid_component_shared_detonation_module_2 = SharedDraftSchematicObjectTemplate:new {
clientTemplateFileName = "object/draft_schematic/droid/component/shared_detonation_module_2.iff"
}
ObjectTemplates:addClientTemplate(object_draft_schematic_droid_component_shared_detonation_module_2, "object/draft_schematic/droid/component/shared_detonation_module_2.iff")
------------------------------------------------------------------------------------------------------------------------------------
object_draft_schematic_droid_component_shared_detonation_module_3 = SharedDraftSchematicObjectTemplate:new {
clientTemplateFileName = "object/draft_schematic/droid/component/shared_detonation_module_3.iff"
}
ObjectTemplates:addClientTemplate(object_draft_schematic_droid_component_shared_detonation_module_3, "object/draft_schematic/droid/component/shared_detonation_module_3.iff")
------------------------------------------------------------------------------------------------------------------------------------
object_draft_schematic_droid_component_shared_detonation_module_4 = SharedDraftSchematicObjectTemplate:new {
clientTemplateFileName = "object/draft_schematic/droid/component/shared_detonation_module_4.iff"
}
ObjectTemplates:addClientTemplate(object_draft_schematic_droid_component_shared_detonation_module_4, "object/draft_schematic/droid/component/shared_detonation_module_4.iff")
------------------------------------------------------------------------------------------------------------------------------------
object_draft_schematic_droid_component_shared_detonation_module_5 = SharedDraftSchematicObjectTemplate:new {
clientTemplateFileName = "object/draft_schematic/droid/component/shared_detonation_module_5.iff"
}
ObjectTemplates:addClientTemplate(object_draft_schematic_droid_component_shared_detonation_module_5, "object/draft_schematic/droid/component/shared_detonation_module_5.iff")
------------------------------------------------------------------------------------------------------------------------------------
object_draft_schematic_droid_component_shared_droid_dance_module = SharedDraftSchematicObjectTemplate:new {
clientTemplateFileName = "object/draft_schematic/droid/component/shared_droid_dance_module.iff"
}
ObjectTemplates:addClientTemplate(object_draft_schematic_droid_component_shared_droid_dance_module, "object/draft_schematic/droid/component/shared_droid_dance_module.iff")
------------------------------------------------------------------------------------------------------------------------------------
object_draft_schematic_droid_component_shared_hand_sample_module = SharedDraftSchematicObjectTemplate:new {
clientTemplateFileName = "object/draft_schematic/droid/component/shared_hand_sample_module.iff"
}
ObjectTemplates:addClientTemplate(object_draft_schematic_droid_component_shared_hand_sample_module, "object/draft_schematic/droid/component/shared_hand_sample_module.iff")
------------------------------------------------------------------------------------------------------------------------------------
object_draft_schematic_droid_component_shared_item_storage_module_7 = SharedDraftSchematicObjectTemplate:new {
clientTemplateFileName = "object/draft_schematic/droid/component/shared_item_storage_module_7.iff"
}
ObjectTemplates:addClientTemplate(object_draft_schematic_droid_component_shared_item_storage_module_7, "object/draft_schematic/droid/component/shared_item_storage_module_7.iff")
------------------------------------------------------------------------------------------------------------------------------------
| 69.600998 | 227 | 0.69545 |
654050d7cccb1b2c34b6283890ccaab142889563 | 48,459 | py | Python | lofti_gaia/lofti.py | logan-pearce/lofti_gaia | b88940553669a134a461bb052843afa0dad4d71f | [
"BSD-3-Clause"
] | 2 | 2020-05-06T07:39:56.000Z | 2020-07-23T16:39:55.000Z | lofti_gaia/lofti.py | logan-pearce/lofti_gaia | b88940553669a134a461bb052843afa0dad4d71f | [
"BSD-3-Clause"
] | null | null | null | lofti_gaia/lofti.py | logan-pearce/lofti_gaia | b88940553669a134a461bb052843afa0dad4d71f | [
"BSD-3-Clause"
] | 2 | 2020-07-25T15:43:52.000Z | 2021-05-18T20:20:55.000Z | import astropy.units as u
import numpy as np
from lofti_gaia.loftitools import *
from lofti_gaia.cFunctions import calcOFTI_C
#from loftitools import *
import pickle
import time
import matplotlib.pyplot as plt
# Astroquery throws some warnings we can ignore:
import warnings
warnings.filterwarnings("ignore")
'''This module obtaines measurements from Gaia EDR3 (Gaia DR2 is also available as a secondary option) and runs through the LOFTI Gaia/OFTI
wide stellar binary orbit fitting technique.
'''
class Fitter(object):
'''Initialize the Fitter object for the binary system, and compute observational constraints
to be used in the orbit fit. User must provide Gaia source ids, tuples of mass estimates for
both objects, specify the number of desired orbits in posterior sample. Fit will be
for object 2 relative to object 1.
Attributes are tuples of (value,uncertainty) unless otherwise indicated. Attributes
with astropy units are retrieved from Gaia archive, attributes without units are
computed from Gaia values. All relative values are for object 2 relative to object 1.
Args:
sourceid1, sourceid2 (int): Gaia source ids for the two objects, fit will be for motion of \
object 2 relative to object 1
mass1, mass2 (tuple, flt): tuple os mass estimate for object 1 and 2, of the form (value, uncertainty)
Norbits (int): Number of desired orbits in posterior sample. Default = 100000
results_filename (str): Filename for fit results files. If none, results will be written to files \
named FitResults.yr.mo.day.hr.min.s
astrometry (dict): User-supplied astrometric measurements. Must be dictionary or table or pandas dataframe with\
column names "sep,seperr,pa,paerr,dates" or "ra,raerr,dec,decerr,dates". May be same as the rv table. \
Sep, deltaRA, and deltaDEC must be in arcseconds, PA in degrees, dates in decimal years. \
Default = None
user_rv (dict): User-supplied radial velocity measurements. Must be dictionary or table or pandas dataframe with\
column names "rv,rverr,rv_dates". May be same as the astrometry table. Default = None.
catalog (str): name of Gaia catalog to query. Default = 'gaiaedr3.gaia_source'
ruwe1, ruwe2 (flt): RUWE value from Gaia archive
ref_epoch (flt): reference epoch in decimal years. For Gaia DR2 this is 2015.5, for Gaia EDR3 it is 2016.0
plx1, plx2 (flt): parallax from Gaia in mas
RA1, RA2 (flt): right ascension from Gaia; RA in deg, uncertainty in mas
Dec1, Dec2 (flt): declination from Gaia; Dec in deg, uncertainty in mas
pmRA1, pmRA2 (flt): proper motion in RA in mas yr^-1 from Gaia
pmDec1, pmDec2 (flt): proper motion in DEC in mas yr^-1 from Gaia
rv1, rv2 (flt, optional): radial velocity in km s^-1 from Gaia
rv (flt, optional): relative RV of 2 relative to 1, if both are present in Gaia
plx (flt): weighted mean parallax for the binary system in mas
distance (flt): distance of system in pc, computed from Gaia parallax using method \
of Bailer-Jones et. al 2018.
deltaRA, deltaDec (flt): relative separation in RA and Dec directions, in mas
pmRA, pmDec (flt): relative proper motion in RA/Dec directions in km s^-1
sep (flt): total separation vector in mas
pa (flt): postion angle of separation vector in degrees from North
sep_au (flt): separation in AU
sep_km (flt): separation in km
total_vel (flt): total velocity vector in km s^-1. If RV is available for both, \
this is the 3d velocity vector; if not it is just the plane of sky velocity.
total_planeofsky_vel (flt): total velocity in the plane of sky in km s^-1. \
In the absence of RV this is equivalent to the total velocity vector.
deltaGmag (flt): relative contrast in Gaia G magnitude. Does not include uncertainty.
inflateProperMOtionError (flt): an optional factor to mulitply default gaia proper motion error by.
Written by Logan Pearce, 2020
'''
def __init__(self, sourceid1, sourceid2, mass1, mass2, Norbits = 100000, \
results_filename = None,
astrometry = None,
user_rv = None,
catalog = 'gaiaedr3.gaia_source',
inflateProperMotionError=1
):
self.sourceid1 = sourceid1
self.sourceid2 = sourceid2
try:
self.mass1 = mass1[0]
self.mass1err = mass1[1]
self.mass2 = mass2[0]
self.mass2err = mass2[1]
self.mtot = [self.mass1 + self.mass2, np.sqrt((self.mass1err**2) + (self.mass2err**2))]
except:
raise ValueError('Masses must be tuples of (value,error), ex: mass1 = (1.0,0.05)')
self.Norbits = Norbits
if not results_filename:
self.results_filename = 'FitResults.'+time.strftime("%Y.%m.%d.%H.%M.%S")+'.txt'
self.stats_filename = 'FitResults.Stats.'+time.strftime("%Y.%m.%d.%H.%M.%S")+'.txt'
else:
self.results_filename = results_filename
self.stats_filename = results_filename+'.Stats.txt'
self.astrometry = False
# check if user supplied astrometry:
if astrometry is not None:
# if so, set astrometric flag to True:
self.astrometry = True
# store observation dates:
self.astrometric_dates = astrometry['dates']
# if in sep/pa, convert to ra/dec:
if 'sep' in astrometry:
try:
astr_ra = [MonteCarloIt([astrometry['sep'][i],astrometry['seperr'][i]]) * \
np.sin(np.radians(MonteCarloIt([astrometry['pa'][i],astrometry['paerr'][i]]))) \
for i in range(len(astrometry['sep']))]
astr_dec = [MonteCarloIt([astrometry['sep'][i],astrometry['seperr'][i]]) * \
np.cos(np.radians(MonteCarloIt([astrometry['pa'][i],astrometry['paerr'][i]]))) \
for i in range(len(astrometry['sep']))]
self.astrometric_ra = np.array([
[np.mean(astr_ra[i]) for i in range(len(astrometry['sep']))],
[np.std(astr_ra[i]) for i in range(len(astrometry['sep']))]
])
self.astrometric_dec = np.array([
[np.mean(astr_dec[i]) for i in range(len(astrometry['sep']))],
[np.std(astr_dec[i]) for i in range(len(astrometry['sep']))]
])
except:
raise ValueError('Astrometry keys not recognized. Please provide dictionary or table or pandas dataframe with\
column names "sep,seperr,pa,paerr,dates" or "ra,raerr,dec,decerr,dates"')
elif 'ra' in astrometry:
# else store the ra/dec as attributes:
try:
self.astrometric_ra = np.array([astrometry['ra'], astrometry['raerr']])
self.astrometric_dec = np.array([astrometry['dec'], astrometry['decerr']])
except:
raise ValueError('Astrometry keys not recognized. Please provide dictionary or table or pandas dataframe with\
column names "sep,seperr,pa,paerr,dates" or "ra,raerr,dec,decerr,dates"')
else:
raise ValueError('Astrometry keys not recognized. Please provide dictionary or table or pandas dataframe with\
column names "sep,seperr,pa,paerr,dates" or "ra,raerr,dec,decerr,dates"')
# Check if user supplied rv:
self.use_user_rv = False
if user_rv is not None:
# set user rv flag to true:
self.use_user_rv = True
try:
# set attributes; multiply rv by -1 due to difference in coordinate systems:
self.user_rv = np.array([user_rv['rv']*-1,user_rv['rverr']])
self.user_rv_dates = np.array(user_rv['rv_dates'])
except:
raise ValueError('RV keys not recognized. Please use column names "rv,rverr,rv_dates"')
self.catalog = catalog
# Get Gaia measurements, compute needed constraints, and add to object:
self.PrepareConstraints(catalog=self.catalog,inflateFactor=inflateProperMotionError)
def edr3ToICRF(self,pmra,pmdec,ra,dec,G):
''' Corrects for biases in proper motion. The function is from https://arxiv.org/pdf/2103.07432.pdf
Args:
pmra,pmdec (float): proper motion
ra, dec (float): right ascension and declination
G (float): G magnitude
Written by Sam Christian, 2021
'''
if G>=13:
return pmra , pmdec
import numpy as np
def sind(x):
return np.sin(np.radians(x))
def cosd(x):
return np.cos(np.radians(x))
table1="""
0.0 9.0 9.0 9.5 9.5 10.0 10.0 10.5 10.5 11.0 11.0 11.5 11.5 11.75 11.75 12.0 12.0 12.25 12.25 12.5 12.5 12.75 12.75 13.0
18.4 33.8 -11.3 14.0 30.7 -19.4 12.8 31.4 -11.8 13.6 35.7 -10.5 16.2 50.0 2.1 19.4 59.9 0.2 21.8 64.2 1.0 17.7 65.6 -1.9 21.3 74.8 2.1 25.7 73.6 1.0 27.3 76.6 0.5
34.9 68.9 -2.9 """
table1 = np.fromstring(table1,sep=" ").reshape((12,5)).T
Gmin = table1[0]
Gmax = table1[1]
#pick the appropriate omegaXYZ for the source’s magnitude:
omegaX = table1[2][(Gmin<=G)&(Gmax>G)][0]
omegaY = table1[3][(Gmin<=G)&(Gmax>G)][0]
omegaZ = table1[4][(Gmin<=G)&(Gmax>G)][0]
pmraCorr = -1*sind(dec)*cosd(ra)*omegaX -sind(dec)*sind(ra)*omegaY + cosd(dec)*omegaZ
pmdecCorr = sind(ra)*omegaX -cosd(ra)*omegaY
return pmra-pmraCorr/1000., pmdec-pmdecCorr/1000.
def PrepareConstraints(self, rv=False, catalog='gaiaedr3.gaia_source', inflateFactor=1.):
'''Retrieves parameters for both objects from Gaia EDR3 archive and computes system attriubtes,
and assigns them to the Fitter object class.
Args:
rv (bool): flag for handling the presence or absence of RV measurements for both objects \
in EDR3. Gets set to True if both objects have Gaia RV measurements. Default = False
catalog (str): name of Gaia catalog to query. Default = 'gaiaedr3.gaia_source'
inflateFactor (flt): Factor by which to inflate the errors on Gaia proper motions to \
account for improper uncertainty estimates. Default = 1.0
Written by Logan Pearce, 2020
'''
from astroquery.gaia import Gaia
deg_to_mas = 3600000.
mas_to_deg = 1./3600000.
# Retrieve astrometric solution from Gaia EDR3
job = Gaia.launch_job("SELECT * FROM "+catalog+" WHERE source_id = "+str(self.sourceid1))
j = job.get_results()
job = Gaia.launch_job("SELECT * FROM "+catalog+" WHERE source_id = "+str(self.sourceid2))
k = job.get_results()
if catalog == 'gaiadr2.gaia_source':
# Retrieve RUWE from RUWE catalog for both sources and add to object state:
job = Gaia.launch_job("SELECT * FROM gaiadr2.ruwe WHERE source_id = "+str(self.sourceid1))
jruwe = job.get_results()
job = Gaia.launch_job("SELECT * FROM gaiadr2.ruwe WHERE source_id = "+str(self.sourceid2))
kruwe = job.get_results()
self.ruwe1 = jruwe['ruwe'][0]
self.ruwe2 = kruwe['ruwe'][0]
else:
# EDR3 contains ruwe in the main catalog:
self.ruwe1 = j['ruwe'][0]
self.ruwe2 = k['ruwe'][0]
# Check RUWE for both objects and warn if too high:
if self.ruwe1>1.2 or self.ruwe2>1.2:
print('''WARNING: RUWE for one or more of your solutions is greater than 1.2. This indicates
that the source might be an unresolved binary or experiencing acceleration
during the observation. Orbit fit results may not be trustworthy.''')
# reference epoch:
self.ref_epoch = j['ref_epoch'][0]
# parallax:
self.plx1 = [j[0]['parallax']*u.mas, j[0]['parallax_error']*u.mas]
self.plx2 = [k[0]['parallax']*u.mas, k[0]['parallax_error']*u.mas]
# RA/DEC
self.RA1 = [j[0]['ra']*u.deg, j[0]['ra_error']*mas_to_deg*u.deg]
self.RA2 = [k[0]['ra']*u.deg, k[0]['ra_error']*mas_to_deg*u.deg]
self.Dec1 = [j[0]['dec']*u.deg, j[0]['dec_error']*mas_to_deg*u.deg]
self.Dec2 = [k[0]['dec']*u.deg, k[0]['dec_error']*mas_to_deg*u.deg]
# Proper motions
pmRACorrected1,pmDecCorrected1 = self.edr3ToICRF(j[0]['pmra'],j[0]['pmdec'],j[0]['ra'],j[0]['dec'],j[0]["phot_g_mean_mag"])
pmRACorrected2,pmDecCorrected2 = self.edr3ToICRF(k[0]['pmra'],k[0]['pmdec'],k[0]['ra'],k[0]['dec'],k[0]["phot_g_mean_mag"])
self.pmRA1 = [pmRACorrected1*u.mas/u.yr, j[0]['pmra_error']*u.mas/u.yr*inflateFactor]
self.pmRA2 = [pmRACorrected2*u.mas/u.yr, k[0]['pmra_error']*u.mas/u.yr*inflateFactor]
self.pmDec1 = [pmDecCorrected1*u.mas/u.yr, j[0]['pmdec_error']*u.mas/u.yr*inflateFactor]
self.pmDec2 = [pmDecCorrected2*u.mas/u.yr, k[0]['pmdec_error']*u.mas/u.yr*inflateFactor]
# See if both objects have RV's in DR2:
if catalog == 'gaiaedr3.gaia_source':
key = 'dr2_radial_velocity'
error_key = 'dr2_radial_velocity_error'
elif catalog == 'gaiadr2.gaia_source':
key = 'radial_velocity'
error_key = 'radial_velocity_error'
if type(k[0][key]) == np.float64 and type(j[0][key]) == np.float64 or type(k[0][key]) == np.float32 and type(j[0][key]) == np.float32:
rv = True
self.rv1 = [j[0][key]*u.km/u.s,j[0][error_key]*u.km/u.s]
self.rv2 = [k[0][key]*u.km/u.s,k[0][error_key]*u.km/u.s]
rv1 = MonteCarloIt(self.rv1)
rv2 = MonteCarloIt(self.rv2)
self.rv = [ -np.mean(rv2-rv1) , np.std(rv2-rv1) ] # km/s
# negative to relfect change in coordinate system from RV measurements to lofti
# pos RV = towards observer in this coord system
else:
self.rv = [0,0]
# weighted mean of parallax values:
plx = np.average([self.plx1[0].value,self.plx2[0].value], weights = [self.plx1[1].value,self.plx2[1].value])
plxerr = np.max([self.plx1[1].value,self.plx2[1].value])
self.plx = [plx,plxerr] # mas
self.distance = distance(*self.plx) # pc
# Compute separations of component 2 relative to 1:
r1 = MonteCarloIt(self.RA1)
r2 = MonteCarloIt(self.RA2)
d1 = MonteCarloIt(self.Dec1)
d2 = MonteCarloIt(self.Dec2)
ra = (r2*deg_to_mas - r1*deg_to_mas) * np.cos(np.radians(np.mean([self.Dec1[0].value,self.Dec2[0].value])))
dec = ((d2 - d1)*u.deg).to(u.mas).value
self.deltaRA = [np.mean(ra),np.std(ra)] # mas
self.deltaDec = [np.mean(dec),np.std(dec)] # mas
# compute relative proper motion:
pr1 = MonteCarloIt(self.pmRA1)
pr2 = MonteCarloIt(self.pmRA2)
pd1 = MonteCarloIt(self.pmDec1)
pd2 = MonteCarloIt(self.pmDec2)
pmRA = [np.mean(pr2 - pr1), np.std(pr2-pr1)] # mas/yr
pmDec = [np.mean(pd2 - pd1), np.std(pd2 - pd1)] # mas/yr
self.pmRA = masyr_to_kms(pmRA,self.plx) # km/s
self.pmDec = masyr_to_kms(pmDec,self.plx) # km/s
# Compute separation/position angle:
r, p = to_polar(r1,r2,d1,d2)
self.sep = tuple([np.mean(r).value, np.std(r).value]) # mas
self.pa = tuple([np.mean(p).value, np.std(p).value]) # deg
self.sep_au = tuple([((self.sep[0]/1000)*self.distance[0]), ((self.sep[1]/1000)*self.distance[0])])
self.sep_km = tuple([ self.sep_au[0]*u.au.to(u.km) , self.sep_au[1]*u.au.to(u.km)])
# compute total velocities:
if rv:
self.total_vel = [ add_in_quad([self.pmRA[0],self.pmDec[0],self.rv[0]]) ,
add_in_quad([self.pmRA[1],self.pmDec[1],self.rv[1]]) ] # km/s
self.total_planeofsky_vel = [ add_in_quad([self.pmRA[0],self.pmDec[0]]) ,
add_in_quad([self.pmRA[1],self.pmDec[1]]) ] # km/s
else:
self.total_vel = [ add_in_quad([self.pmRA[0],self.pmDec[0]]) ,
add_in_quad([self.pmRA[1],self.pmDec[1]]) ] # km/s
self.total_planeofsky_vel = self.total_vel.copy() # km/s
# compute deltamag:
self.deltaGmag = j[0]['phot_g_mean_mag'] - k[0]['phot_g_mean_mag']
class FitOrbit(object):
''' Object for performing an orbit fit. Takes attributes from Fitter class.
ex: orbits = FitOrbit(fitterobject)
Args:
fitterobject (Fitter object): Fitter object initialized from the Fitter class
write_stats (bool): If True, write out summary statistics of orbit sample at \
conclusion of fit. Default = True.
write_results (bool): If True, write out the fit results to a pickle file \
in addition to the text file created during the fit. Default = True.
deltaRA, deltaDec (flt): relative separation in RA and Dec directions, in mas
pmRA, pmDec (flt): relative proper motion in RA/Dec directions in km s^-1
rv (flt, optional): relative RV of 2 relative to 1, if both are present in Gaia EDR3
mtot_init (flt): initial total system mass in Msun from user input
distance (flt): distance of system in pc, computed from Gaia parallax using method of Bailer-Jones et. al 2018.
sep (flt): separation vector in mas
pa (flt): postion angle of separation vector in degrees from North
ref_epoch (flt): epoch of the measurement, 2016.0 for Gaia EDR3 and 2015.5 for Gaia DR2.
Norbits (int): number of desired orbit samples
write_stats (bool): if True, write summary of sample statistics to human-readable file at end of run. Default = True
write_results (bool): if True, write out current state of sample orbits in pickle file in periodic intervals during \
run, and again at the end of the run. RECOMMENDED. Default = True
results_filename (str): name of file for saving pickled results to disk. If not supplied, \
defaul name is FitResults.y.mo.d.h.m.s.pkl, saved in same directory as fit was run.
stats_filename (str): name of file for saving human-readable file of stats of sample results. If not supplied, \
defaul name is FitResults.Stats.y.mo.d.h.m.s.pkl, saved in same directory as fit was run.
run_time (flt): run time for the last fit. astropy units object
Written by Logan Pearce, 2020
'''
def __init__(self, fitterobject, write_stats = True, write_results = True, python_version=False, \
use_pm_cross_term = False, corr_coeff = None):
# establish fit parameters:
self.deltaRA = fitterobject.deltaRA
self.deltaDec = fitterobject.deltaDec
self.pmRA = fitterobject.pmRA
self.pmDec = fitterobject.pmDec
self.rv = fitterobject.rv
self.mtot_init = fitterobject.mtot
self.distance = fitterobject.distance
self.sep = fitterobject.sep
self.pa = fitterobject.pa
self.ref_epoch = fitterobject.ref_epoch
self.Norbits = fitterobject.Norbits
self.write_results = write_results
self.write_stats = write_stats
self.results_filename = fitterobject.results_filename
self.stats_filename = fitterobject.stats_filename
self.astrometry = fitterobject.astrometry
if self.astrometry:
self.astrometric_ra = fitterobject.astrometric_ra
self.astrometric_dec = fitterobject.astrometric_dec
self.astrometric_dates = fitterobject.astrometric_dates
self.use_user_rv = fitterobject.use_user_rv
if self.use_user_rv:
self.user_rv = fitterobject.user_rv
self.user_rv_dates = fitterobject.user_rv_dates
# run orbit fitter:
self.fitorbit(python_fitOFTI=python_version, use_pm_cross_term = use_pm_cross_term, corr_coeff = corr_coeff)
def fitorbit(self, save_results_every_X_loops = 100, python_fitOFTI=False, use_pm_cross_term = False, corr_coeff = None):
'''Run the OFTI fitting run on the Fitter object. Called when FitOrbit object
is created.
Args:
save_results_every_X_loops (int): on every Xth loop, save status of the \
orbit sample arrays to a pickle file, if write_results = True (Default)
python_fitOFTI (bool): If True, fit using python only without using C Kepler's equation solver. Default = False
use_pm_cross_term (bool): If True, include the proper motion correlation cross term in the Chi^2 computation \
Default = False
Written by Logan Pearce, 2020
'''
# write header:
print('Saving orbits in',self.results_filename)
k = open(self.results_filename, 'w')
output_file_header = '# sma [arcsec] period [yrs] orbit phase t_0 [yr] ecc incl [deg]\
argp [deg] lan [deg] m_tot [Msun] dist [pc] chi^2 ln(prob) ln(randn)'
k.write(output_file_header + "\n")
k.close()
import time as tm
########### Perform initial run to get initial chi-squared: #############
# Draw random orbits:
#parameters = a,T,const,to,e,i,w,O,m1,dist
numSamples = 10000
parameters_init = draw_samples(numSamples, self.mtot_init, self.distance, self.ref_epoch)
# Compute positions and velocities:
if(python_fitOFTI):
X,Y,Z,Xdot,Ydot,Zdot,Xddot,Yddot,Zddot,parameters=calc_OFTI(parameters_init,self.ref_epoch,self.sep,self.pa)
else:
returnArray = np.zeros((19,numSamples))
returnArray = calcOFTI_C(parameters_init,self.ref_epoch,self.sep,self.pa,returnArray.copy())
X,Y,Z,Xdot,Ydot,Zdot,Xddot,Yddot,Zddot = returnArray[0:9]
parameters = returnArray[9:]
# Compute chi squared:
if self.rv[0] != 0:
model = np.array([Y,X,Ydot,Xdot,Zdot])
data = np.array([self.deltaRA, self.deltaDec, self.pmRA, self.pmDec, self.rv])
else:
model = np.array([Y,X,Ydot,Xdot])
data = np.array([self.deltaRA, self.deltaDec, self.pmRA, self.pmDec])
chi2 = ComputeChi2(data,model)
if use_pm_cross_term:
chi2 -= ( 2 * corr_coeff * (data[2][0] - model[2]) * (data[3][0] - model[3]) ) / (data[2][1] * data[3][1])
if self.astrometry:
p = parameters.copy()
a,T,const,to,e,i,w,O,m1,dist = p[0],p[1],p[2],p[3],p[4],p[5],p[6],p[7],p[8],p[9]
chi2_astr = np.zeros(10000)
# Calculate predicted positions at astr observation dates for each orbit:
for j in range(self.astrometric_ra.shape[1]):
# for each date, compute XYZ for each 10000 trial orbit. We can
# skip scale and rotate because that was accomplished in the calc_OFTI call above.
X1,Y1,Z1,E1 = calc_XYZ(a,T,to,e,i,w,O,self.astrometric_dates[j])
# Place astrometry into data array where: data[0][0]=ra obs, data[0][1]=ra err, etc:
data = np.array([self.astrometric_ra[:,j], self.astrometric_dec[:,j]])
# place corresponding predicited positions at that date for each trial orbit in arcsec:
model = np.array([Y1*1000,X1*1000])
# compute chi2 for trial orbits at that date and add to the total chi2 sum:
chi2_astr += ComputeChi2(data,model)
chi2 = chi2 + chi2_astr
if self.use_user_rv:
p = parameters.copy()
a,T,const,to,e,i,w,O,m1,dist = p[0],p[1],p[2],p[3],p[4],p[5],p[6],p[7],p[8],p[9]
chi2_rv = np.zeros(10000)
for j in range(self.user_rv.shape[1]):
# compute ecc anomaly at that date:
X1,Y1,Z1,E1 = calc_XYZ(a,T,to,e,i,w,O,self.user_rv_dates[j])
# compute velocities at that ecc anom:
Xdot,Ydot,Zdot = calc_velocities(a,T,to,e,i,w,O,dist,E1)
# compute chi2:
chi2_rv += ComputeChi2(np.array([self.user_rv[:,j]]),np.array([Zdot]))
chi2 = chi2 + chi2_rv
print('inital chi min',np.nanmin(chi2))
self.chi_min = np.nanmin(chi2)
# Accept/reject:
accepted, lnprob, lnrand = AcceptOrReject(chi2,self.chi_min)
# count number accepted:
number_orbits_accepted = np.size(accepted)
# tack on chi2, log probability, log random unif number to parameters array:
parameters = np.concatenate((parameters,chi2[None,:],lnprob[None,:],lnrand[None,:]), axis = 0)
# transpose:
parameters=np.transpose(parameters)
# write results to file:
k = open(self.results_filename, 'a')
for params in parameters[accepted]:
string = ' '.join([str(p) for p in params])
k.write(string + "\n")
k.close()
###### start loop ########
# initialize:
loop_count = 0
start=tm.time()
while number_orbits_accepted < self.Norbits:
# Draw random orbits:
numSamples = 10000
parameters_init = draw_samples(numSamples, self.mtot_init, self.distance, self.ref_epoch)
# Compute positions and velocities and new parameters array with scaled and rotated values:
if(python_fitOFTI):
X,Y,Z,Xdot,Ydot,Zdot,Xddot,Yddot,Zddot,parameters=calc_OFTI(parameters_init,self.ref_epoch,self.sep,self.pa)
else:
returnArray = np.zeros((19,numSamples))
returnArray = calcOFTI_C(parameters_init,self.ref_epoch,self.sep,self.pa,returnArray.copy())
X,Y,Z,Xdot,Ydot,Zdot,Xddot,Yddot,Zddot = returnArray[0:9]
parameters = returnArray[9:]
returnArray = None
# compute chi2 for orbits using Gaia observations:
if self.rv[0] != 0:
model = np.array([Y,X,Ydot,Xdot,Zdot])
data = np.array([self.deltaRA, self.deltaDec, self.pmRA, self.pmDec, self.rv])
else:
model = np.array([Y,X,Ydot,Xdot])
data = np.array([self.deltaRA, self.deltaDec, self.pmRA, self.pmDec])
chi2 = ComputeChi2(data,model)
if use_pm_cross_term:
chi2 -= ( 2 * (data[2][0] - model[2]) * (data[3][0] - model[3]) ) / (data[2][1] * data[3][1])
# add user astrometry if given:
if self.astrometry:
p = parameters.copy()
a,T,const,to,e,i,w,O,m1,dist = p[0],p[1],p[2],p[3],p[4],p[5],p[6],p[7],p[8],p[9]
chi2_astr = np.zeros(10000)
# Calculate predicted positions at astr observation dates for each orbit:
for j in range(self.astrometric_ra.shape[1]):
# for each date, compute XYZ for each 10000 trial orbit. We can
# skip scale and rotate because that was accomplished in the calc_OFTI call above.
X1,Y1,Z1,E1 = calc_XYZ(a,T,to,e,i,w,O,self.astrometric_dates[j])
# Place astrometry into data array where: data[0][0]=ra obs, data[0][1]=ra err, etc:
data = np.array([self.astrometric_ra[:,j], self.astrometric_dec[:,j]])
# place corresponding predicited positions at that date for each trial orbit:
model = np.array([Y1*1000,X1*1000])
# compute chi2 for trial orbits at that date and add to the total chi2 sum:
chi2_astr += ComputeChi2(data,model)
chi2 = chi2 + chi2_astr
# add user rv if given:
if self.use_user_rv:
p = parameters.copy()
a,T,const,to,e,i,w,O,m1,dist = p[0],p[1],p[2],p[3],p[4],p[5],p[6],p[7],p[8],p[9]
chi2_rv = np.zeros(10000)
for j in range(self.user_rv.shape[1]):
# compute ecc anomaly at that date:
X1,Y1,Z1,E1 = calc_XYZ(a,T,to,e,i,w,O,self.user_rv_dates[j])
# compute velocities at that ecc anom:
Xdot,Ydot,Zdot = calc_velocities(a,T,to,e,i,w,O,dist,E1)
# compute chi2:
chi2_rv += ComputeChi2(np.array([self.user_rv[:,j]]),np.array([Zdot]))
chi2 = chi2 + chi2_rv
# Accept/reject:
accepted, lnprob, lnrand = AcceptOrReject(chi2,self.chi_min)
if np.size(accepted) == 0:
pass
else:
# count num accepted
p = parameters.copy()
a,T,const,to,e,i,w,O,m1,dist = p[0],p[1],p[2],p[3],p[4],p[5],p[6],p[7],p[8],p[9]
sampleResults = calc_XYZ(a,T,to,e,i/180*np.pi,w/180*np.pi,O/180*np.pi,2016.0)
number_orbits_accepted += np.size(accepted)
parameters = np.concatenate((parameters,chi2[None,:],lnprob[None,:],lnrand[None,:]), axis = 0)
parameters=np.transpose(parameters)
k = open(self.results_filename, 'a')
for params in parameters[accepted]:
string = ' '.join([str(p) for p in params])
k.write(string + "\n")
k.close()
if np.nanmin(chi2) < self.chi_min:
# If there is a new min chi2:
self.chi_min = np.nanmin(chi2)
#print('found new chi min:',self.chi_min)
# re-evaluate to accept/reject with new chi_min:
if number_orbits_accepted != 0:
dat = np.loadtxt(open(self.results_filename,"r"),delimiter=' ',ndmin=2)
lnprob = -(dat[:,10]-self.chi_min)/2.0
dat[:,11] = lnprob
accepted_retest = np.where(lnprob > dat[:,12])
q = open(self.results_filename, 'w')
q.write(output_file_header + "\n")
for data in dat[accepted_retest]:
string = ' '.join([str(d) for d in data])
q.write(string + "\n")
q.close()
dat2 = np.loadtxt(open(self.results_filename,"r"),delimiter=' ',ndmin=2)
number_orbits_accepted=dat2.shape[0]
loop_count += 1
#print('loop count',loop_count)
update_progress(number_orbits_accepted,self.Norbits)
# one last accept/reject with final chi_min value:
dat = np.loadtxt(open(self.results_filename,"r"),delimiter=' ',ndmin=2)
lnprob = -(dat[:,10]-self.chi_min)/2.0
dat[:,11] = lnprob
accepted_retest = np.where(lnprob > dat[:,12])
q = open(self.results_filename, 'w')
q.write(output_file_header + "\n")
for data in dat[accepted_retest]:
string = ' '.join([str(d) for d in data])
q.write(string + "\n")
q.close()
# when finished, upload results and store in object:
dat = np.loadtxt(open(self.results_filename,"r"),delimiter=' ',ndmin=2)
number_orbits_accepted=dat.shape[0]
print('Final Norbits:', number_orbits_accepted)
# intialise results object and store accepted orbits:
if self.rv[0] != 0:
self.results = Results(orbits = dat, limit_lan = False, limit_aop = False)
else:
self.results = Results(orbits = dat, limit_lan = True, limit_aop = False)
self.results.Update(self.results.orbits)
# pickle dump the results attribute:
if self.write_results:
self.results.SaveResults(self.results_filename.replace(".txt", ".pkl"), write_text_file = False)
stop = tm.time()
self.results.run_time = (stop - start)*u.s
# compute stats and write to file:
self.results.stats = Stats(orbits = self.results.orbits, write_to_file = self.write_stats, filename = self.stats_filename)
class Results(object):
'''A class for storing and manipulating the results of the orbit fit.
Args:
orbits (Norbits x 13 array): array of accepted orbits from \
OFTI fit in the same order as the following attributes
sma (1 x Norbits array): semi-major axis in arcsec
period (1 x Norbits array): period in years
orbit_fraction (1 x Norbits array): fraction of orbit past periastron \
passage the observation (2016) occured on. Values: [0,1)
t0 (1 x Norbits array): date of periastron passage in decimal years
ecc (1 x Norbits array): eccentricity
inc (1 x Norbits array): inclination relative to plane of the sky in deg
aop (1 x Norbits array): arguement of periastron in deg
lan (1 x Norbits array): longitude of ascending node in deg
mtot (1 x Norbits array): total system mass in Msun
distance (1 x Norbits array): distance to system in parsecs
chi2 (1 x Norbits array): chi^2 value for the orbit
lnprob (1 x Norbits array): log probability of orbit
lnrand (1 x Norbits array): log of random "dice roll" for \
orbit acceptance
limit_aop, limit_lan (bool): In the absence of radial velocity info, \
there is a degeneracy between arg of periastron and long of ascending \
node. Common practice is to limit one to the interval [0,180] deg. \
By default, lofti limits lan to this interval if rv = False. The user can \
choose to limit aop instead by setting limit_aop = True, limit_lan = False. \
The orbits[:,6] (aop) and orbits[:,7] (lan) arrays preserve the original values. \
Written by Logan Pearce, 2020
'''
def __init__(self, orbits = [], limit_aop = False, limit_lan = True):
self.orbits = orbits
self.limit_lan = limit_lan
self.limit_aop = limit_aop
def Update(self, orbits):
'''Take elements of the "orbits" attribute and populate
the orbital element attributes
Args:
orbits (arr): orbits array from Results class
Written by Logan Pearce, 2020
'''
self.sma = orbits[:,0]
self.period = orbits[:,1]
self.orbit_fraction = orbits[:,2]
self.t0 = orbits[:,3]
self.ecc = orbits[:,4]
self.inc = orbits[:,5]
self.aop = orbits[:,6]
if self.limit_aop:
self.aop = limit_to_180deg(self.aop)
self.lan = orbits[:,7] % 360
if self.limit_lan:
self.lan = limit_to_180deg(self.lan)
self.mtot = orbits[:,8]
self.distance = orbits[:,9]
self.chi2 = orbits[:,10]
self.lnprob = orbits[:,11]
self.lnrand = orbits[:,12]
def SaveResults(self, filename, write_text_file = False, text_filename = None):
'''Save the orbits and orbital parameters attributes in a pickle file
Args:
filename (str): filename for pickle file
write_text_file (bool): if True, also write out the accepted orbits to a \
human readable text file
text_filename (bool): if write_to_text = True, specifify filename for text file
Written by Logan Pearce, 2020
'''
pickle.dump(self, open( filename, "wb" ) )
# write results to file:
if write_text_file:
k = open(text_filename, 'a')
for params in self.orbits:
string = ' '.join([str(p) for p in params])
k.write(string + "\n")
k.close()
def LoadResults(self, filename, append = False):
'''Read in the orbits and orbital parameters attributes from a pickle file
Args:
filename (str): filename of pickle file to load
append (bool): if True, append read in orbit samples to another Results \
object. Default = False.
Written by Logan Pearce, 2020
'''
results_in = pickle.load( open( filename, "rb" ) )
if append == False:
self.orbits = results_in.orbits
self.Update(self.orbits)
else:
self.orbits = np.vstack((self.orbits,results_in.orbits))
self.Update(self.orbits)
# plotting results:
def PlotHists(self):
'''Plot 1-d histograms of orbital elements 'sma','ecc','inc','aop','lan','t0' from fit results.
Written by Logan Pearce, 2020
'''
if len(self.sma < 50):
bins = 50
else:
bins = 'fd'
fig = plt.figure(figsize=(30, 5.5))
params = np.array([self.sma,self.ecc,self.inc,self.aop,self.lan,self.t0])
names = np.array(['sma','ecc','inc','aop','lan','t0'])
for i in range(len(params)):
ax = plt.subplot2grid((1,len(params)), (0,i))
plt.hist(params[i],bins=bins,edgecolor='none',alpha=0.8)
plt.tick_params(axis='both', left=False, top=False, right=False, bottom=True, \
labelleft=False, labeltop=False, labelright=False, labelbottom=True)
plt.xticks(rotation=45, fontsize = 20)
plt.xlabel(names[i], fontsize = 25)
plt.tight_layout()
return fig
def PlotOrbits(self, color = True, colorbar = True, ref_epoch = 2016.0, size = 100, plot3d = False, cmap = 'viridis',xlim=False,ylim=False):
'''Plot a random selection of orbits from the sample in the plane of the sky.
Args:
color (bool): if True, plot orbit tracks using a colormap scale to orbit fraction (phase) \
past observation date (2015.5). If False, orbit tracks will be black. Default = True
colorbar (bool): if True and color = True, plot colorbar for orbit phase
ref_epoch (flt): reference epoch for drawing orbits. Default = 2015.5
size (int): Number of orbits to plot. Default = True
plot3d (bool): If True, return a plot of orbits in 3D space. Default = False
cmap (str): colormap for orbit phase plot
Written by Logan Pearce, 2020
'''
# Random selection of orbits to plot:
if len(self.sma) > size:
# if there are more orbits than desired size, randomly select orbits from
# the posterior sample:
ind = np.random.choice(range(0,len(self.sma)),replace=False,size=size)
else:
# if there are fewer orbits than desired size, take all of them:
ind = np.random.choice(range(0,len(self.sma)),replace=False,size=len(self.sma))
from numpy import tan, arctan, sqrt, cos, sin, arccos
# label for colormap axis:
colorlabel = 'Phase'
# create figure:
fig = plt.figure(figsize = (7.5, 6.))
plt.grid(ls=':')
# invert X axis for RA:
plt.gca().invert_xaxis()
if plot3d:
# Make 3d axis object:
ax = fig.add_subplot(111, projection='3d')
# plot central star:
ax.scatter(0,0,0,color='orange',marker='*',s=300,zorder=10)
ax.set_zlabel('Z (")',fontsize=20)
else:
# plot central star:
plt.scatter(0,0,color='orange',marker='*',s=300,zorder=10)
# For each orbit in the random selection from the posterior samples:
for a,T,to,e,i,w,O in zip(self.sma[ind],self.period[ind],self.t0[ind],self.ecc[ind],np.radians(self.inc[ind]),\
np.radians(self.aop[ind]),np.radians(self.lan[ind])):
# define an array of times along orbit:
times = np.linspace(ref_epoch,ref_epoch+T,5000)
X,Y,Z = np.array([]),np.array([]),np.array([])
E = np.array([])
# Compute X,Y,Z positions for each time:
for t in times:
n = (2*np.pi)/T
M = n*(t-to)
nextE = [danby_solve(eccentricity_anomaly, varM,vare, 0.001) for varM,vare in zip([M],[e])]
E = np.append(E,nextE)
r1 = a*(1.-e*cos(E))
f1 = sqrt(1.+e)*sin(E/2.)
f2 = sqrt(1.-e)*cos(E/2.)
f = 2.*np.arctan2(f1,f2)
r = (a*(1.-e**2))/(1.+(e*cos(f)))
X1 = r * ( cos(O)*cos(w+f) - sin(O)*sin(w+f)*cos(i) )
Y1 = r * ( sin(O)*cos(w+f) + cos(O)*sin(w+f)*cos(i) )
Z1 = r * sin(w+f) * sin(i)
X,Y,Z = np.append(X,X1),np.append(Y,Y1),np.append(Z,Z1)
# Plot the X,Y(Z) positions:
if not plot3d:
if color:
plt.scatter(Y,X,c=((times-ref_epoch)/T),cmap=cmap,s=3,lw=0)
plt.gca().set_aspect('equal', adjustable='datalim')
else:
plt.plot(Y,X, color='black',alpha=0.3)
plt.gca().set_aspect('equal', adjustable='datalim')
if plot3d:
from mpl_toolkits.mplot3d import Axes3D
if color:
ax.scatter(Y,X,Z,c=((times-ref_epoch)/T),cmap=cmap,s=3,lw=0)
else:
ax.plot(Y,X,Z, color='black',alpha=0.3)
# plot colorbar:
if not plot3d:
if color:
if colorbar == True:
cb = plt.colorbar().set_label(colorlabel, fontsize=20)
plt.gca().tick_params(labelsize=14)
plt.ylabel('Dec (")',fontsize=20)
plt.xlabel('RA (")',fontsize=20)
plt.gca().tick_params(labelsize=14)
if(xlim):
plt.xlim(xlim)
if(ylim):
plt.ylim(ylim)
return fig
def PlotSepPA(self, ref_epoch = 2016.0, size = 100, timespan = [20,20], orbitcolor = 'skyblue'):
'''Plot a random selection of orbits from the sample in separation and position angle as
a function of time.
Args:
ref_epoch (flt): reference epoch for drawing orbits. Default = 2015.5
size (int): Number of orbits to plot. Default = True
timespan (tuple, int): number of years before [0] and after [1] the ref epoch to \
plot sep and pa
orbitcolor (str): color to use to plot the orbits
Written by Logan Pearce, 2020
'''
# Random selection of orbits to plot:
if len(self.sma) > size:
# if there are more orbits than desired size, randomly select orbits from
# the posterior sample:
ind = np.random.choice(range(0,len(self.sma)),replace=False,size=size)
else:
# if there are fewer orbits than desired size, take all of them:
ind = np.random.choice(range(0,len(self.sma)),replace=False,size=len(self.sma))
from numpy import tan, arctan, sqrt, cos, sin, arccos
# make figure
fig = plt.figure(figsize = (8, 10))
# define subplots:
plt.subplot(2,1,1)
plt.gca().tick_params(labelsize=14)
plt.grid(ls=':')
# define times to compute sep/pa:
tmin,tmax = ref_epoch - timespan[0],ref_epoch + timespan[1]
t = np.linspace(tmin,tmax,2000)
date_ticks = np.arange(tmin,tmax,10)
# for each selected orbit from the sample:
for a,T,to,e,i,w,O in zip(self.sma[ind],self.period[ind],self.t0[ind],self.ecc[ind],np.radians(self.inc[ind]),\
np.radians(self.aop[ind]),np.radians(self.lan[ind])):
X = np.array([])
Y = np.array([])
# compute X,Y at each time point:
X1,Y1 = orbits_for_plotting(a,T,to,e,i,w,O,t)
X = np.append(X, X1)
Y = np.append(Y,Y1)
# compute sep:
r=np.sqrt((X**2)+(Y**2))
# plot sep in mas:
plt.plot(t,r*1000,color=orbitcolor,alpha=0.5)
plt.ylabel(r'$\rho$ (mas)',fontsize=20)
# next suplot:
plt.subplot(2,1,2)
plt.grid(ls=':')
# for each selected orbit from the sample:
for a,T,to,e,i,w,O in zip(self.sma[ind],self.period[ind],self.t0[ind],self.ecc[ind],np.radians(self.inc[ind]),\
np.radians(self.aop[ind]),np.radians(self.lan[ind])):
X = np.array([])
Y = np.array([])
X1,Y1 = orbits_for_plotting(a,T,to,e,i,w,O,t)
X = np.append(X, X1)
Y = np.append(Y,Y1)
# compute pa:
theta=np.arctan2(X,-Y)
theta=(np.degrees(theta)+270.)%360
# plot it:
plt.plot(t,theta,color=orbitcolor,alpha=0.5)
plt.ylabel(r'P.A. (deg)',fontsize=19)
plt.xlabel('Years',fontsize=19)
plt.gca().tick_params(labelsize=14)
plt.tight_layout()
return fig
class Stats(object):
'''A class for storing and manipulating the statistics of the results of the orbit fit.
For every parameter, there is a series of stats computed and saved as stats.param.stat
Examples:
stats.sma.mean = mean of semimajor axis
stats.ecc.ci68 = 68% confidence interval for eccentricity
stats.aop.std = standard deviation of arg of periastron
Args:
orbits (Norbits x 13 array): array of accepted orbits from \
OFTI fit in the same order as the following attributes
param.mean (flt): mean of parameter computed using np.mean
param.median (flt): np.median of parameter
param.mode (flt): mode of parameter
param.std (flt): standard deviation from np.std
param.ci68 (tuple,flt): 68% minimum credible interval of form (lower bound, upper bound)
param.ci95 (tuple,flt): 95% minimum credible interval
write_to_file (bool): If True, write stats to a human-readbale text file.
filename (str): filename for saving stats file. If not supplied, default \
name is FitResults.Stats.y.mo.d.h.m.s.pkl, saved in same directory as fit was run.
Written by Logan Pearce, 2020
'''
def __init__(self, orbits = [], write_to_file = False, filename = None):
self.orbits = orbits
# Compute stats on parameter arrays and save as attributes:
self.sma = StatsSubclass(self.orbits[:,0])
self.period = StatsSubclass(self.orbits[:,1])
self.orbit_fraction = StatsSubclass(self.orbits[:,2])
self.t0 = StatsSubclass(self.orbits[:,3])
self.ecc = StatsSubclass(self.orbits[:,4])
self.inc = StatsSubclass(self.orbits[:,5])
self.aop = StatsSubclass(self.orbits[:,6])
self.lan = StatsSubclass(self.orbits[:,7])
self.mtot = StatsSubclass(self.orbits[:,8])
self.distance = StatsSubclass(self.orbits[:,9])
if write_to_file:
params = np.array([self.sma,self.period,self.orbit_fraction,self.t0,self.ecc,self.inc,\
self.aop,self.lan,self.mtot,self.distance])
names = np.array(['sma','period','orbit fraction','t0','ecc','inc','aop','lan','mtot','distance'])
if not filename:
filename = 'FitResults.Stats.'+time.strftime("%Y.%m.%d.%H.%M.%S")+'.txt'
k = open(filename, 'w')
string = 'Parameter Mean Median Mode Std 68% Min Cred Int 95% Min Cred Int'
k.write(string + "\n")
for i in range(len(params)):
string = make_parameter_string(params[i],names[i])
k.write(string + "\n")
k.close()
class StatsSubclass(Stats):
'''Subclass for computing and storing statistics
Args:
array (arr): array for which to compute statistics
'''
def __init__(self, array):
self.mean,self.median,self.mode,self.std,self.ci68,self.ci95 = compute_statistics(array)
| 49.650615 | 170 | 0.585278 |
8e6041daeb52c576714a509e7a12f2c1a96c7b95 | 588 | asm | Assembly | MySource/sub.asm | mdabdullahibnaharun/Assembly-Language | a56500622b961c7ecf9690ad9d2136c3e05ea1f7 | [
"MIT"
] | null | null | null | MySource/sub.asm | mdabdullahibnaharun/Assembly-Language | a56500622b961c7ecf9690ad9d2136c3e05ea1f7 | [
"MIT"
] | null | null | null | MySource/sub.asm | mdabdullahibnaharun/Assembly-Language | a56500622b961c7ecf9690ad9d2136c3e05ea1f7 | [
"MIT"
] | null | null | null | .model
.stack
.data
.code
main proc
mov ah, 01h
int 21h
mov bl,al
mov ah, 01h
int 21h
mov cl, al
sub bl,cl
add bl,30h
mov dl,bl
mov ah , 02h
int 21h
main endp
end main | 14 | 25 | 0.202381 |
58a100ed8e9f8d32b7923ef8d954c81cbb190289 | 4,122 | swift | Swift | Sources/Sector.swift | adelang/DoomKit | f3cf3c7090c65d7e68e1f6e9dee70b5a7cf26cce | [
"MIT"
] | 1 | 2017-06-06T18:10:06.000Z | 2017-06-06T18:10:06.000Z | Sources/Sector.swift | adelang/DoomKit | f3cf3c7090c65d7e68e1f6e9dee70b5a7cf26cce | [
"MIT"
] | null | null | null | Sources/Sector.swift | adelang/DoomKit | f3cf3c7090c65d7e68e1f6e9dee70b5a7cf26cce | [
"MIT"
] | null | null | null | //
// Sector.swift
// DoomKit
//
// Created by Arjan de Lang on 26-12-14.
// Copyright (c) 2014 Blue Depths Media. All rights reserved.
//
import Foundation
import CoreGraphics
open class Sector: Equatable {
class Delegate {
}
open var floorHeight: Int16
open var ceilingHeight: Int16
open var floorTextureName: String
open var ceilingTextureName: String
open var lightLevel: Int16
open var type: Int16
open var tag: Int16
weak var map: Map?
open var sideDefs: [SideDef] {
get {
return map?.sideDefs.filter({$0.sector == self}) ?? []
}
}
open var loops: [[SideDef]] {
get {
var loops = [[SideDef]]()
var availableSideDefs = self.sideDefs.filter({$0.lineDef != nil})
tryNextStartingSideSef: while let startingSideDef = availableSideDefs.first {
availableSideDefs.removeFirst()
var loopSideDefs = [startingSideDef]
findNextLoopSegment: while true {
for sideDef in availableSideDefs {
if sideDef.startVertex == loopSideDefs.last?.endVertex {
// Add to loop and continue search
loopSideDefs.append(sideDef)
availableSideDefs.remove(at: availableSideDefs.index(of: sideDef)!)
if sideDef.endVertex == loopSideDefs.first?.startVertex {
// Loop complete
loops.append(loopSideDefs)
continue tryNextStartingSideSef
}
continue findNextLoopSegment
}
}
break findNextLoopSegment
}
}
return loops
}
}
open class func decodeSectorsFromLump(_ lump: Wad.Lump, forMap map: Map) -> [Sector] {
var sectors: [Sector] = []
if let data = lump.data {
for sectorDataStart in stride(from: 0, to: data.count, by: 26) {
var floorHeight: Int16 = 0
(data as NSData).getBytes(&floorHeight, range: NSMakeRange(sectorDataStart, 2))
var ceilingHeight: Int16 = 0
(data as NSData).getBytes(&ceilingHeight, range: NSMakeRange((sectorDataStart + 2), 2))
let floorTextureName = String(data: data.subdata(in: (sectorDataStart + 4 ..< sectorDataStart + 12)), encoding: .ascii)!.trimmingCharacters(in: CharacterSet(charactersIn: "\0"))
let ceilingTextureName = String(data: data.subdata(in: (sectorDataStart + 12 ..< sectorDataStart + 20)), encoding: .ascii)!.trimmingCharacters(in: CharacterSet(charactersIn: "\0"))
var lightLevel: Int16 = 0
(data as NSData).getBytes(&lightLevel, range: NSMakeRange((sectorDataStart + 20), 2))
var type: Int16 = 0
(data as NSData).getBytes(&type, range: NSMakeRange((sectorDataStart + 22), 2))
var tag: Int16 = 0
(data as NSData).getBytes(&tag, range: NSMakeRange((sectorDataStart + 24), 2))
sectors.append(Sector(floorHeight: floorHeight, ceilingHeight: ceilingHeight, floorTextureName: floorTextureName, ceilingTextureName: ceilingTextureName, lightLevel: lightLevel, type: type, tag: tag, map: map))
}
}
return sectors
}
open class func encodeSectorsToLump(_ sectors: [Sector]) -> Wad.Lump {
var data = Data()
for sector in sectors {
data.append(Data(bytes: §or.floorHeight, count: 2))
data.append(Data(bytes: §or.ceilingHeight, count: 2))
data.append(sector.floorTextureName.padding(toLength: 8, withPad: "\0", startingAt: 0).data(using: String.Encoding.ascii, allowLossyConversion: false)!)
data.append(sector.ceilingTextureName.padding(toLength: 8, withPad: "\0", startingAt: 0).data(using: String.Encoding.ascii, allowLossyConversion: false)!)
data.append(Data(bytes: §or.lightLevel, count: 2))
data.append(Data(bytes: §or.type, count: 2))
data.append(Data(bytes: §or.tag, count: 2))
}
return Wad.Lump(name: "SECTORS", data: data)
}
public init(floorHeight: Int16, ceilingHeight: Int16, floorTextureName: String, ceilingTextureName: String, lightLevel: Int16, type: Int16, tag: Int16, map: Map? = nil) {
self.floorHeight = floorHeight
self.ceilingHeight = ceilingHeight
self.floorTextureName = floorTextureName
self.ceilingTextureName = ceilingTextureName
self.lightLevel = lightLevel
self.type = type
self.tag = tag
self.map = map
}
}
public func ==(lhs: Sector, rhs: Sector) -> Bool {
return lhs === rhs
}
| 34.932203 | 214 | 0.703057 |
130734effe3c79d3f9f9c51ab4202b39a9ebd2a8 | 3,625 | dart | Dart | kuramba/lib/views/data_view.dart | Ibidukikije-Birambye/Kuramba | 4ba6788f263834b94d3b41f23f79e51ab43ae4a2 | [
"MIT"
] | 1 | 2021-04-03T10:13:31.000Z | 2021-04-03T10:13:31.000Z | kuramba/lib/views/data_view.dart | Ibidukikije-Birambye/Kuramba | 4ba6788f263834b94d3b41f23f79e51ab43ae4a2 | [
"MIT"
] | null | null | null | kuramba/lib/views/data_view.dart | Ibidukikije-Birambye/Kuramba | 4ba6788f263834b94d3b41f23f79e51ab43ae4a2 | [
"MIT"
] | 1 | 2021-03-24T15:46:08.000Z | 2021-03-24T15:46:08.000Z | import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
// import '../widgets/cards/question_card.dart';
import '../widgets/cards/question_category_card.dart';
import '../providers/question_catalog.dart';
class DataView extends StatelessWidget {
static const routeName = '/data_view';
final List<Map<String, dynamic>> _categories = [
{
'category': 'Living',
'color': Colors.blue,
},
{
'category': 'Consumption',
'color': Colors.pink,
},
{
'category': 'Nutrition',
'color': Colors.amber,
},
{
'category': 'Leisure',
'color': Colors.purple,
},
{
'category': 'Mobility',
'color': Colors.lightGreen,
},
{
'category': 'Traveling',
'color': Colors.red,
},
];
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Data'),
),
body: ChangeNotifierProvider<QuestionCatalog>(
create: (context) => QuestionCatalog(),
builder: (context, _) => FutureBuilder(
future: Provider.of<QuestionCatalog>(
context,
listen: false,
).fetchQuestionPreviews(),
builder: (
context,
snapshot,
) {
if (snapshot.connectionState == ConnectionState.waiting) {
return Center(
child: CircularProgressIndicator(),
);
} else {
final previews = Provider.of<QuestionCatalog>(
context,
listen: false,
).previews;
// List<ExpansionPanel> children = [];
// _categories.forEach(
// (category) {
// children.add(
// ExpansionPanel(
// headerBuilder: (BuildContext context, bool isOpen) =>
// Text(category['category']),
// body: ListView.builder(
// padding: const EdgeInsets.symmetric(horizontal: 10),
// shrinkWrap: true,
// itemCount: previews.length,
// itemBuilder: (BuildContext context, int index) {
// return QuestionCard(
// preview: previews[index],
// color: _categories[index]['color'],
// );
// },
// ),
// ),
// );
// },
// );
// return ExpansionPanelList(
// children: children,
// );
return ListView.separated(
padding: const EdgeInsets.all(20),
itemCount: _categories.length,
separatorBuilder: (BuildContext context, int index) =>
const SizedBox(height: 20),
itemBuilder: (BuildContext context, int index) {
return QuestionCategoryCard(
color: _categories[index]['color'],
category: _categories[index]['category'],
previews: previews
.where(
(preview) =>
preview.category ==
_categories[index]['category'],
)
.toList(),
);
},
);
}
},
),
),
);
}
}
| 31.25 | 79 | 0.444966 |
c89e2029d15d5f98820e59c49b05f3fb903a4448 | 8,591 | sql | SQL | sql/bjutoj.sql | suxiongye/bjutoj | 6552d69efbce14f13c9be466d4bfbbd8271f7a3d | [
"MIT"
] | null | null | null | sql/bjutoj.sql | suxiongye/bjutoj | 6552d69efbce14f13c9be466d4bfbbd8271f7a3d | [
"MIT"
] | null | null | null | sql/bjutoj.sql | suxiongye/bjutoj | 6552d69efbce14f13c9be466d4bfbbd8271f7a3d | [
"MIT"
] | null | null | null | # MySQL-Front 5.1 (Build 4.13)
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE */;
/*!40101 SET SQL_MODE='STRICT_TRANS_TABLES,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION' */;
/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES */;
/*!40103 SET SQL_NOTES='ON' */;
/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS */;
/*!40014 SET UNIQUE_CHECKS=0 */;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS */;
/*!40014 SET FOREIGN_KEY_CHECKS=0 */;
# Host: localhost Database: bjutoj
# ------------------------------------------------------
# Server version 5.5.28
DROP DATABASE IF EXISTS `bjutoj`;
CREATE DATABASE `bjutoj` /*!40100 DEFAULT CHARACTER SET utf8 */;
USE `bjutoj`;
#
# Source for table codes
#
DROP TABLE IF EXISTS `codes`;
CREATE TABLE `codes` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`pro_id` int(11) NOT NULL,
`user_id` int(11) NOT NULL,
`content` text COLLATE utf8_unicode_ci NOT NULL,
`status` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`remarks` text COLLATE utf8_unicode_ci,
`created_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
`updated_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
#
# Dumping data for table codes
#
LOCK TABLES `codes` WRITE;
/*!40000 ALTER TABLE `codes` DISABLE KEYS */;
INSERT INTO `codes` VALUES (1,1,2,'#include<stdio.h>\r\nint main()\r\n{\r\nint a, b;\r\nscanf(\"%d %d\",&a,&b);\r\nprintf(\"%d\",a+b);\r\nreturn 0;\r\n}','Waiting','','2015-04-16 12:44:34','2015-04-16 12:44:34');
/*!40000 ALTER TABLE `codes` ENABLE KEYS */;
UNLOCK TABLES;
#
# Source for table groups
#
DROP TABLE IF EXISTS `groups`;
CREATE TABLE `groups` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`permissions` text COLLATE utf8_unicode_ci,
`created_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
`updated_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
PRIMARY KEY (`id`),
UNIQUE KEY `groups_name_unique` (`name`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
#
# Dumping data for table groups
#
LOCK TABLES `groups` WRITE;
/*!40000 ALTER TABLE `groups` DISABLE KEYS */;
INSERT INTO `groups` VALUES (1,'Admin','{\"admin\":1}','2015-04-16 12:33:56','2015-04-16 12:33:56');
INSERT INTO `groups` VALUES (2,'Student','{\"student\":1}','2015-04-16 12:33:56','2015-04-16 12:33:56');
/*!40000 ALTER TABLE `groups` ENABLE KEYS */;
UNLOCK TABLES;
#
# Source for table migrations
#
DROP TABLE IF EXISTS `migrations`;
CREATE TABLE `migrations` (
`migration` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`batch` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
#
# Dumping data for table migrations
#
LOCK TABLES `migrations` WRITE;
/*!40000 ALTER TABLE `migrations` DISABLE KEYS */;
INSERT INTO `migrations` VALUES ('2015_04_12_090811_create_codes_table',1);
INSERT INTO `migrations` VALUES ('2015_04_12_090845_create_solves_table',1);
INSERT INTO `migrations` VALUES ('2015_04_12_090908_create_problems_table',1);
INSERT INTO `migrations` VALUES ('2012_12_06_225921_migration_cartalyst_sentry_install_users',2);
INSERT INTO `migrations` VALUES ('2012_12_06_225929_migration_cartalyst_sentry_install_groups',2);
INSERT INTO `migrations` VALUES ('2012_12_06_225945_migration_cartalyst_sentry_install_users_groups_pivot',2);
INSERT INTO `migrations` VALUES ('2012_12_06_225988_migration_cartalyst_sentry_install_throttle',2);
/*!40000 ALTER TABLE `migrations` ENABLE KEYS */;
UNLOCK TABLES;
#
# Source for table problems
#
DROP TABLE IF EXISTS `problems`;
CREATE TABLE `problems` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`title` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`content` text COLLATE utf8_unicode_ci NOT NULL,
`radio` float(8,2) NOT NULL,
`accepted` int(11) NOT NULL,
`submit` int(11) NOT NULL,
`inputcase` text COLLATE utf8_unicode_ci,
`outputcase` text COLLATE utf8_unicode_ci NOT NULL,
`timelimit` float(8,2) NOT NULL,
`memorylimit` int(11) NOT NULL,
`created_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
`updated_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
#
# Dumping data for table problems
#
LOCK TABLES `problems` WRITE;
/*!40000 ALTER TABLE `problems` DISABLE KEYS */;
INSERT INTO `problems` VALUES (1,'Test Problem','Input two number and return their sum',0,0,0,'1 2','3',1,1,'2015-04-16 12:43:02','2015-04-16 12:43:02');
/*!40000 ALTER TABLE `problems` ENABLE KEYS */;
UNLOCK TABLES;
#
# Source for table solves
#
DROP TABLE IF EXISTS `solves`;
CREATE TABLE `solves` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`user_id` int(11) NOT NULL,
`pro_id` int(11) NOT NULL,
`created_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
`updated_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
#
# Dumping data for table solves
#
LOCK TABLES `solves` WRITE;
/*!40000 ALTER TABLE `solves` DISABLE KEYS */;
/*!40000 ALTER TABLE `solves` ENABLE KEYS */;
UNLOCK TABLES;
#
# Source for table throttle
#
DROP TABLE IF EXISTS `throttle`;
CREATE TABLE `throttle` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`user_id` int(10) unsigned DEFAULT NULL,
`ip_address` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
`attempts` int(11) NOT NULL DEFAULT '0',
`suspended` tinyint(1) NOT NULL DEFAULT '0',
`banned` tinyint(1) NOT NULL DEFAULT '0',
`last_attempt_at` timestamp NULL DEFAULT NULL,
`suspended_at` timestamp NULL DEFAULT NULL,
`banned_at` timestamp NULL DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `throttle_user_id_index` (`user_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
#
# Dumping data for table throttle
#
LOCK TABLES `throttle` WRITE;
/*!40000 ALTER TABLE `throttle` DISABLE KEYS */;
INSERT INTO `throttle` VALUES (1,2,'::1',0,0,0,NULL,NULL,NULL);
/*!40000 ALTER TABLE `throttle` ENABLE KEYS */;
UNLOCK TABLES;
#
# Source for table users
#
DROP TABLE IF EXISTS `users`;
CREATE TABLE `users` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`username` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`password` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`solved` int(11) NOT NULL,
`submit` int(11) NOT NULL,
`permissions` text COLLATE utf8_unicode_ci,
`activated` tinyint(1) NOT NULL DEFAULT '0',
`activation_code` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
`activated_at` timestamp NULL DEFAULT NULL,
`last_login` timestamp NULL DEFAULT NULL,
`persist_code` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
`reset_password_code` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
`created_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
`updated_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
PRIMARY KEY (`id`),
UNIQUE KEY `users_username_unique` (`username`),
KEY `users_activation_code_index` (`activation_code`),
KEY `users_reset_password_code_index` (`reset_password_code`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
#
# Dumping data for table users
#
LOCK TABLES `users` WRITE;
/*!40000 ALTER TABLE `users` DISABLE KEYS */;
INSERT INTO `users` VALUES (1,'student','$2y$10$pq69mgfHQ7x75Wji61EW0u2fCTPRDJk3gX1HS81kBAHUrwy9g.lL.',0,0,NULL,1,NULL,NULL,NULL,NULL,NULL,'2015-04-16 12:33:56','2015-04-16 12:33:56');
INSERT INTO `users` VALUES (2,'teacher','$2y$10$b2UHqoNkR4mH03Jue5E/WOZuaLBuDsGpYNDnhO3UhcrvKNlqFp47m',0,1,NULL,1,NULL,NULL,'2015-04-16 12:34:56','$2y$10$jUI4FrlYeSg5rBzf9k8JLOwQBs4DUF9.1BLZNdrwQg3rRWbcCDNZu',NULL,'2015-04-16 12:33:56','2015-04-16 12:44:34');
/*!40000 ALTER TABLE `users` ENABLE KEYS */;
UNLOCK TABLES;
#
# Source for table users_groups
#
DROP TABLE IF EXISTS `users_groups`;
CREATE TABLE `users_groups` (
`user_id` int(10) unsigned NOT NULL,
`group_id` int(10) unsigned NOT NULL,
PRIMARY KEY (`user_id`,`group_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
#
# Dumping data for table users_groups
#
LOCK TABLES `users_groups` WRITE;
/*!40000 ALTER TABLE `users_groups` DISABLE KEYS */;
INSERT INTO `users_groups` VALUES (1,2);
INSERT INTO `users_groups` VALUES (2,1);
/*!40000 ALTER TABLE `users_groups` ENABLE KEYS */;
UNLOCK TABLES;
/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;
/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;
/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;
/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;
| 34.922764 | 259 | 0.729601 |
2f434dea6a29d22c0041330548eba675f0c1db9e | 648 | java | Java | java/src/main/java/leetcode/Problem83RemoveDuplicatesFromSortedList.java | jaredsburrows/Project-Euler | 032b60140ee33166df57e8723a532dc4bd7b0faf | [
"Apache-2.0"
] | 56 | 2016-04-21T13:17:55.000Z | 2022-03-13T16:32:37.000Z | java/src/main/java/leetcode/Problem83RemoveDuplicatesFromSortedList.java | jaredsburrows/Project-Euler | 032b60140ee33166df57e8723a532dc4bd7b0faf | [
"Apache-2.0"
] | 4 | 2016-06-09T04:33:18.000Z | 2019-06-09T22:44:14.000Z | java/src/main/java/leetcode/Problem83RemoveDuplicatesFromSortedList.java | jaredsburrows/Project-Euler | 032b60140ee33166df57e8723a532dc4bd7b0faf | [
"Apache-2.0"
] | 12 | 2016-11-30T19:09:17.000Z | 2022-01-26T22:35:34.000Z | package leetcode;
import leetcode.api.ListNode;
/**
* https://leetcode.com/problems/remove-duplicates-from-sorted-list
*/
public final class Problem83RemoveDuplicatesFromSortedList {
// Time - O(N), Space - O(1)
public ListNode deleteDuplicates(ListNode head) {
if (head == null || head.next == null) {
return head;
}
ListNode current = head;
while (current.next != null) {
if (current.val == current.next.val) {
current.next = current.next.next;
} else {
current = current.next;
}
}
return head;
}
}
| 23.142857 | 67 | 0.554012 |
93b306aff373950569900df0a1971a608dab5c91 | 32,119 | html | HTML | docs/a00005_source.html | basicx-StrgV/EasyLogger | c8366b3992f65c0f137a0ca0dba2218c7c90e884 | [
"MIT"
] | null | null | null | docs/a00005_source.html | basicx-StrgV/EasyLogger | c8366b3992f65c0f137a0ca0dba2218c7c90e884 | [
"MIT"
] | null | null | null | docs/a00005_source.html | basicx-StrgV/EasyLogger | c8366b3992f65c0f137a0ca0dba2218c7c90e884 | [
"MIT"
] | null | null | null | <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.9.1"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<title>BasicxLogger: JsonLogFile.cs Source File</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="dynsections.js"></script>
<link href="navtree.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="resize.js"></script>
<script type="text/javascript" src="navtreedata.js"></script>
<script type="text/javascript" src="navtree.js"></script>
<link href="search/search.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="search/searchdata.js"></script>
<script type="text/javascript" src="search/search.js"></script>
<link href="doxygen.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="top"><!-- do not remove this div, it is closed by doxygen! -->
<div id="titlearea">
<table cellspacing="0" cellpadding="0">
<tbody>
<tr style="height: 56px;">
<td id="projectlogo"><img alt="Logo" src="basicxLoggerIconMini.png"/></td>
<td id="projectalign" style="padding-left: 0.5em;">
<div id="projectname">BasicxLogger
 <span id="projectnumber">2.1.0</span>
</div>
</td>
</tr>
</tbody>
</table>
</div>
<!-- end header part -->
<!-- Generated by Doxygen 1.9.1 -->
<script type="text/javascript">
/* @license magnet:?xt=urn:btih:cf05388f2679ee054f2beb29a391d25f4e673ac3&dn=gpl-2.0.txt GPL-v2 */
var searchBox = new SearchBox("searchBox", "search",false,'Search','.html');
/* @license-end */
</script>
<script type="text/javascript" src="menudata.js"></script>
<script type="text/javascript" src="menu.js"></script>
<script type="text/javascript">
/* @license magnet:?xt=urn:btih:cf05388f2679ee054f2beb29a391d25f4e673ac3&dn=gpl-2.0.txt GPL-v2 */
$(function() {
initMenu('',true,false,'search.php','Search');
$(document).ready(function() { init_search(); });
});
/* @license-end */</script>
<div id="main-nav"></div>
</div><!-- top -->
<div id="side-nav" class="ui-resizable side-nav-resizable">
<div id="nav-tree">
<div id="nav-tree-contents">
<div id="nav-sync" class="sync"></div>
</div>
</div>
<div id="splitbar" style="-moz-user-select:none;"
class="ui-resizable-handle">
</div>
</div>
<script type="text/javascript">
/* @license magnet:?xt=urn:btih:cf05388f2679ee054f2beb29a391d25f4e673ac3&dn=gpl-2.0.txt GPL-v2 */
$(document).ready(function(){initNavTree('a00005_source.html',''); initResizable(); });
/* @license-end */
</script>
<div id="doc-content">
<!-- window showing the filter options -->
<div id="MSearchSelectWindow"
onmouseover="return searchBox.OnSearchSelectShow()"
onmouseout="return searchBox.OnSearchSelectHide()"
onkeydown="return searchBox.OnSearchSelectKey(event)">
</div>
<!-- iframe showing the search results (closed by default) -->
<div id="MSearchResultsWindow">
<iframe src="javascript:void(0)" frameborder="0"
name="MSearchResults" id="MSearchResults">
</iframe>
</div>
<div class="header">
<div class="headertitle">
<div class="title">JsonLogFile.cs</div> </div>
</div><!--header-->
<div class="contents">
<div class="fragment"><div class="line"><a name="l00001"></a><span class="lineno"> 1</span> <span class="comment">//--------------------------------------------------//</span></div>
<div class="line"><a name="l00002"></a><span class="lineno"> 2</span> <span class="comment">// Created by basicx-StrgV //</span></div>
<div class="line"><a name="l00003"></a><span class="lineno"> 3</span> <span class="comment">// https://github.com/basicx-StrgV/BasicxLogger //</span></div>
<div class="line"><a name="l00004"></a><span class="lineno"> 4</span> <span class="comment">//--------------------------------------------------//</span></div>
<div class="line"><a name="l00005"></a><span class="lineno"> 5</span> <span class="keyword">using</span> System;</div>
<div class="line"><a name="l00006"></a><span class="lineno"> 6</span> <span class="keyword">using</span> System.IO;</div>
<div class="line"><a name="l00007"></a><span class="lineno"> 7</span> <span class="keyword">using</span> System.Text;</div>
<div class="line"><a name="l00008"></a><span class="lineno"> 8</span> <span class="keyword">using</span> System.Text.Json;</div>
<div class="line"><a name="l00009"></a><span class="lineno"> 9</span> <span class="keyword">using</span> <a class="code" href="a00062.html">BasicxLogger</a>.<a class="code" href="a00067.html">Base</a>;</div>
<div class="line"><a name="l00010"></a><span class="lineno"> 10</span> <span class="keyword">using</span> <a class="code" href="a00062.html">BasicxLogger</a>.<a class="code" href="a00066.html">Models</a>;</div>
<div class="line"><a name="l00011"></a><span class="lineno"> 11</span>  </div>
<div class="line"><a name="l00012"></a><span class="lineno"><a class="line" href="a00064.html"> 12</a></span> <span class="keyword">namespace </span><a class="code" href="a00064.html">BasicxLogger.Files</a></div>
<div class="line"><a name="l00013"></a><span class="lineno"> 13</span> {</div>
<div class="line"><a name="l00017"></a><span class="lineno"><a class="line" href="a00087.html"> 17</a></span>  <span class="keyword">public</span> <span class="keyword">class </span><a class="code" href="a00087.html">JsonLogFile</a> : <a class="code" href="a00143.html">ILogFile</a></div>
<div class="line"><a name="l00018"></a><span class="lineno"> 18</span>  {</div>
<div class="line"><a name="l00022"></a><span class="lineno"><a class="line" href="a00087.html#a20b84923199b604fb576ddc4e3479390"> 22</a></span>  <span class="keyword">public</span> Encoding <a class="code" href="a00087.html#a20b84923199b604fb576ddc4e3479390">TextEncoding</a> { <span class="keyword">get</span>; <span class="keyword">set</span>; } = Encoding.UTF8;</div>
<div class="line"><a name="l00023"></a><span class="lineno"> 23</span>  </div>
<div class="line"><a name="l00027"></a><span class="lineno"><a class="line" href="a00087.html#a7bce630184811e5f175f1549f90dc95a"> 27</a></span>  <span class="keyword">public</span> <span class="keywordtype">string</span> <a class="code" href="a00087.html#a7bce630184811e5f175f1549f90dc95a">DirectoryName</a> { <span class="keyword">get</span> { <span class="keywordflow">return</span> _file.DirectoryName; } }</div>
<div class="line"><a name="l00028"></a><span class="lineno"> 28</span>  </div>
<div class="line"><a name="l00032"></a><span class="lineno"><a class="line" href="a00087.html#ad35c8e513f31acc59c3ccebb898b9556"> 32</a></span>  <span class="keyword">public</span> <span class="keywordtype">string</span> <a class="code" href="a00087.html#ad35c8e513f31acc59c3ccebb898b9556">FullName</a> { <span class="keyword">get</span> { <span class="keywordflow">return</span> _file.FullName; } }</div>
<div class="line"><a name="l00033"></a><span class="lineno"> 33</span>  </div>
<div class="line"><a name="l00037"></a><span class="lineno"><a class="line" href="a00087.html#afcaff1ad8fc304fdaed8fc56eefccbc6"> 37</a></span>  <span class="keyword">public</span> <span class="keywordtype">string</span> <a class="code" href="a00087.html#afcaff1ad8fc304fdaed8fc56eefccbc6">Extension</a> { <span class="keyword">get</span> { <span class="keywordflow">return</span> _file.Extension; } }</div>
<div class="line"><a name="l00038"></a><span class="lineno"> 38</span>  </div>
<div class="line"><a name="l00039"></a><span class="lineno"> 39</span>  </div>
<div class="line"><a name="l00040"></a><span class="lineno"> 40</span>  <span class="keyword">private</span> readonly FileInfo _file;</div>
<div class="line"><a name="l00041"></a><span class="lineno"> 41</span>  </div>
<div class="line"><a name="l00042"></a><span class="lineno"> 42</span>  </div>
<div class="line"><a name="l00048"></a><span class="lineno"><a class="line" href="a00087.html#afb269f21eef7c35ea2c750a3d1ba4cb0"> 48</a></span>  <span class="keyword">public</span> <a class="code" href="a00087.html#afb269f21eef7c35ea2c750a3d1ba4cb0">JsonLogFile</a>(<span class="keywordtype">string</span> directoryPath, <span class="keywordtype">string</span> fileName)</div>
<div class="line"><a name="l00049"></a><span class="lineno"> 49</span>  {</div>
<div class="line"><a name="l00050"></a><span class="lineno"> 50</span>  <span class="keywordflow">if</span> (!(directoryPath.EndsWith(<span class="stringliteral">"\\"</span>) || directoryPath.EndsWith(<span class="stringliteral">"/"</span>)))</div>
<div class="line"><a name="l00051"></a><span class="lineno"> 51</span>  {</div>
<div class="line"><a name="l00052"></a><span class="lineno"> 52</span>  directoryPath += <span class="charliteral">'/'</span>;</div>
<div class="line"><a name="l00053"></a><span class="lineno"> 53</span>  }</div>
<div class="line"><a name="l00054"></a><span class="lineno"> 54</span>  </div>
<div class="line"><a name="l00055"></a><span class="lineno"> 55</span>  _file = <span class="keyword">new</span> FileInfo(directoryPath + fileName.Split(<span class="charliteral">'.'</span>)[0].Trim() + <span class="stringliteral">".json"</span>);</div>
<div class="line"><a name="l00056"></a><span class="lineno"> 56</span>  }</div>
<div class="line"><a name="l00057"></a><span class="lineno"> 57</span>  </div>
<div class="line"><a name="l00065"></a><span class="lineno"><a class="line" href="a00087.html#adc72129519c46b689cdda4867e1a62a3"> 65</a></span>  <span class="keyword">public</span> <span class="keywordtype">void</span> <a class="code" href="a00087.html#adc72129519c46b689cdda4867e1a62a3">WriteToFile</a>(<a class="code" href="a00062.html#a0768f6cb40899c29cccd5471f354b2b5">LogTag</a> messageTag, <span class="keywordtype">string</span> timestamp, <span class="keywordtype">string</span> message, <span class="keywordtype">string</span> <span class="keywordtype">id</span> = <span class="stringliteral">""</span>)</div>
<div class="line"><a name="l00066"></a><span class="lineno"> 66</span>  {</div>
<div class="line"><a name="l00067"></a><span class="lineno"> 67</span>  <span class="keywordflow">try</span></div>
<div class="line"><a name="l00068"></a><span class="lineno"> 68</span>  {</div>
<div class="line"><a name="l00069"></a><span class="lineno"> 69</span>  <span class="keywordflow">if</span> (!Directory.Exists(_file.DirectoryName))</div>
<div class="line"><a name="l00070"></a><span class="lineno"> 70</span>  {</div>
<div class="line"><a name="l00071"></a><span class="lineno"> 71</span>  Directory.CreateDirectory(_file.DirectoryName);</div>
<div class="line"><a name="l00072"></a><span class="lineno"> 72</span>  }</div>
<div class="line"><a name="l00073"></a><span class="lineno"> 73</span>  </div>
<div class="line"><a name="l00074"></a><span class="lineno"> 74</span>  <span class="keywordflow">if</span> (!File.Exists(_file.FullName))</div>
<div class="line"><a name="l00075"></a><span class="lineno"> 75</span>  {</div>
<div class="line"><a name="l00076"></a><span class="lineno"> 76</span>  CreateJsonFile();</div>
<div class="line"><a name="l00077"></a><span class="lineno"> 77</span>  }</div>
<div class="line"><a name="l00078"></a><span class="lineno"> 78</span>  </div>
<div class="line"><a name="l00079"></a><span class="lineno"> 79</span>  <span class="keywordtype">string</span> fileContent = File.ReadAllText(_file.FullName);</div>
<div class="line"><a name="l00080"></a><span class="lineno"> 80</span>  </div>
<div class="line"><a name="l00081"></a><span class="lineno"> 81</span>  <a class="code" href="a00127.html">JsonLogModel<LogMessageModel></a> logFile = JsonSerializer.Deserialize<<a class="code" href="a00127.html">JsonLogModel<LogMessageModel></a>>(fileContent);</div>
<div class="line"><a name="l00082"></a><span class="lineno"> 82</span>  </div>
<div class="line"><a name="l00083"></a><span class="lineno"> 83</span>  <a class="code" href="a00131.html">LogMessageModel</a> newLogEntry = <span class="keyword">new</span> <a class="code" href="a00131.html">LogMessageModel</a>();</div>
<div class="line"><a name="l00084"></a><span class="lineno"> 84</span>  <span class="keywordflow">if</span> (!<span class="keywordtype">id</span>.Equals(<span class="stringliteral">""</span>))</div>
<div class="line"><a name="l00085"></a><span class="lineno"> 85</span>  {</div>
<div class="line"><a name="l00086"></a><span class="lineno"> 86</span>  newLogEntry.Id = id;</div>
<div class="line"><a name="l00087"></a><span class="lineno"> 87</span>  }</div>
<div class="line"><a name="l00088"></a><span class="lineno"> 88</span>  </div>
<div class="line"><a name="l00089"></a><span class="lineno"> 89</span>  newLogEntry.Timestamp = timestamp;</div>
<div class="line"><a name="l00090"></a><span class="lineno"> 90</span>  </div>
<div class="line"><a name="l00091"></a><span class="lineno"> 91</span>  <span class="keywordflow">if</span> (!messageTag.Equals(<a class="code" href="a00062.html#a0768f6cb40899c29cccd5471f354b2b5">LogTag</a>.none))</div>
<div class="line"><a name="l00092"></a><span class="lineno"> 92</span>  {</div>
<div class="line"><a name="l00093"></a><span class="lineno"> 93</span>  newLogEntry.Tag = messageTag.ToString();</div>
<div class="line"><a name="l00094"></a><span class="lineno"> 94</span>  }</div>
<div class="line"><a name="l00095"></a><span class="lineno"> 95</span>  </div>
<div class="line"><a name="l00096"></a><span class="lineno"> 96</span>  newLogEntry.Message = message;</div>
<div class="line"><a name="l00097"></a><span class="lineno"> 97</span>  </div>
<div class="line"><a name="l00098"></a><span class="lineno"> 98</span>  logFile.<a class="code" href="a00127.html#a42fff250a960eec93e84f0d7df68c61c">Entrys</a>.Add(newLogEntry);</div>
<div class="line"><a name="l00099"></a><span class="lineno"> 99</span>  </div>
<div class="line"><a name="l00100"></a><span class="lineno"> 100</span>  <span class="keywordtype">string</span> newFileContent = JsonSerializer.Serialize(logFile);</div>
<div class="line"><a name="l00101"></a><span class="lineno"> 101</span>  </div>
<div class="line"><a name="l00102"></a><span class="lineno"> 102</span>  FileStream fileWriter = File.OpenWrite(_file.FullName);</div>
<div class="line"><a name="l00103"></a><span class="lineno"> 103</span>  Utf8JsonWriter jsonWriter = <span class="keyword">new</span> Utf8JsonWriter(fileWriter, <span class="keyword">new</span> JsonWriterOptions { Indented = <span class="keyword">true</span> });</div>
<div class="line"><a name="l00104"></a><span class="lineno"> 104</span>  </div>
<div class="line"><a name="l00105"></a><span class="lineno"> 105</span>  JsonDocument jsonFile = JsonDocument.Parse(newFileContent);</div>
<div class="line"><a name="l00106"></a><span class="lineno"> 106</span>  </div>
<div class="line"><a name="l00107"></a><span class="lineno"> 107</span>  jsonFile.WriteTo(jsonWriter);</div>
<div class="line"><a name="l00108"></a><span class="lineno"> 108</span>  </div>
<div class="line"><a name="l00109"></a><span class="lineno"> 109</span>  jsonWriter.Flush();</div>
<div class="line"><a name="l00110"></a><span class="lineno"> 110</span>  </div>
<div class="line"><a name="l00111"></a><span class="lineno"> 111</span>  jsonWriter.Dispose();</div>
<div class="line"><a name="l00112"></a><span class="lineno"> 112</span>  </div>
<div class="line"><a name="l00113"></a><span class="lineno"> 113</span>  fileWriter.Close();</div>
<div class="line"><a name="l00114"></a><span class="lineno"> 114</span>  fileWriter.Dispose();</div>
<div class="line"><a name="l00115"></a><span class="lineno"> 115</span>  }</div>
<div class="line"><a name="l00116"></a><span class="lineno"> 116</span>  <span class="keywordflow">catch</span> (Exception e)</div>
<div class="line"><a name="l00117"></a><span class="lineno"> 117</span>  {</div>
<div class="line"><a name="l00118"></a><span class="lineno"> 118</span>  <span class="keywordflow">throw</span> e;</div>
<div class="line"><a name="l00119"></a><span class="lineno"> 119</span>  }</div>
<div class="line"><a name="l00120"></a><span class="lineno"> 120</span>  }</div>
<div class="line"><a name="l00121"></a><span class="lineno"> 121</span>  </div>
<div class="line"><a name="l00126"></a><span class="lineno"><a class="line" href="a00087.html#a31016df6f5a1f8b177e2e14b1238410c"> 126</a></span>  <span class="keyword">public</span> <span class="keywordtype">void</span> <a class="code" href="a00087.html#a31016df6f5a1f8b177e2e14b1238410c">WriteToFile<T></a>(T logObject)</div>
<div class="line"><a name="l00127"></a><span class="lineno"> 127</span>  {</div>
<div class="line"><a name="l00128"></a><span class="lineno"> 128</span>  <span class="keywordflow">try</span></div>
<div class="line"><a name="l00129"></a><span class="lineno"> 129</span>  {</div>
<div class="line"><a name="l00130"></a><span class="lineno"> 130</span>  <span class="keywordflow">if</span> (!Directory.Exists(_file.DirectoryName))</div>
<div class="line"><a name="l00131"></a><span class="lineno"> 131</span>  {</div>
<div class="line"><a name="l00132"></a><span class="lineno"> 132</span>  Directory.CreateDirectory(_file.DirectoryName);</div>
<div class="line"><a name="l00133"></a><span class="lineno"> 133</span>  }</div>
<div class="line"><a name="l00134"></a><span class="lineno"> 134</span>  </div>
<div class="line"><a name="l00135"></a><span class="lineno"> 135</span>  <span class="keywordflow">if</span> (!File.Exists(_file.FullName))</div>
<div class="line"><a name="l00136"></a><span class="lineno"> 136</span>  {</div>
<div class="line"><a name="l00137"></a><span class="lineno"> 137</span>  CreateJsonFile();</div>
<div class="line"><a name="l00138"></a><span class="lineno"> 138</span>  }</div>
<div class="line"><a name="l00139"></a><span class="lineno"> 139</span>  </div>
<div class="line"><a name="l00140"></a><span class="lineno"> 140</span>  <span class="keywordtype">string</span> fileContent = File.ReadAllText(_file.FullName);</div>
<div class="line"><a name="l00141"></a><span class="lineno"> 141</span>  </div>
<div class="line"><a name="l00142"></a><span class="lineno"> 142</span>  <a class="code" href="a00127.html">JsonLogModel<T></a> logFile = JsonSerializer.Deserialize<<a class="code" href="a00127.html">JsonLogModel<T></a>>(fileContent);</div>
<div class="line"><a name="l00143"></a><span class="lineno"> 143</span>  </div>
<div class="line"><a name="l00144"></a><span class="lineno"> 144</span>  logFile.<a class="code" href="a00127.html#a42fff250a960eec93e84f0d7df68c61c">Entrys</a>.Add(logObject);</div>
<div class="line"><a name="l00145"></a><span class="lineno"> 145</span>  </div>
<div class="line"><a name="l00146"></a><span class="lineno"> 146</span>  <span class="keywordtype">string</span> newFileContent = JsonSerializer.Serialize(logFile);</div>
<div class="line"><a name="l00147"></a><span class="lineno"> 147</span>  </div>
<div class="line"><a name="l00148"></a><span class="lineno"> 148</span>  FileStream fileWriter = File.OpenWrite(_file.FullName);</div>
<div class="line"><a name="l00149"></a><span class="lineno"> 149</span>  Utf8JsonWriter jsonWriter = <span class="keyword">new</span> Utf8JsonWriter(fileWriter, <span class="keyword">new</span> JsonWriterOptions { Indented = <span class="keyword">true</span> });</div>
<div class="line"><a name="l00150"></a><span class="lineno"> 150</span>  </div>
<div class="line"><a name="l00151"></a><span class="lineno"> 151</span>  JsonDocument jsonFile = JsonDocument.Parse(newFileContent);</div>
<div class="line"><a name="l00152"></a><span class="lineno"> 152</span>  </div>
<div class="line"><a name="l00153"></a><span class="lineno"> 153</span>  jsonFile.WriteTo(jsonWriter);</div>
<div class="line"><a name="l00154"></a><span class="lineno"> 154</span>  </div>
<div class="line"><a name="l00155"></a><span class="lineno"> 155</span>  jsonWriter.Flush();</div>
<div class="line"><a name="l00156"></a><span class="lineno"> 156</span>  </div>
<div class="line"><a name="l00157"></a><span class="lineno"> 157</span>  jsonWriter.Dispose();</div>
<div class="line"><a name="l00158"></a><span class="lineno"> 158</span>  </div>
<div class="line"><a name="l00159"></a><span class="lineno"> 159</span>  fileWriter.Close();</div>
<div class="line"><a name="l00160"></a><span class="lineno"> 160</span>  fileWriter.Dispose();</div>
<div class="line"><a name="l00161"></a><span class="lineno"> 161</span>  }</div>
<div class="line"><a name="l00162"></a><span class="lineno"> 162</span>  <span class="keywordflow">catch</span> (Exception e)</div>
<div class="line"><a name="l00163"></a><span class="lineno"> 163</span>  {</div>
<div class="line"><a name="l00164"></a><span class="lineno"> 164</span>  <span class="keywordflow">throw</span> e;</div>
<div class="line"><a name="l00165"></a><span class="lineno"> 165</span>  }</div>
<div class="line"><a name="l00166"></a><span class="lineno"> 166</span>  }</div>
<div class="line"><a name="l00167"></a><span class="lineno"> 167</span>  </div>
<div class="line"><a name="l00168"></a><span class="lineno"> 168</span>  <span class="keyword">private</span> <span class="keywordtype">void</span> CreateJsonFile()</div>
<div class="line"><a name="l00169"></a><span class="lineno"> 169</span>  {</div>
<div class="line"><a name="l00170"></a><span class="lineno"> 170</span>  <span class="keywordflow">try</span></div>
<div class="line"><a name="l00171"></a><span class="lineno"> 171</span>  {</div>
<div class="line"><a name="l00172"></a><span class="lineno"> 172</span>  <span class="keywordflow">if</span> (!File.Exists(_file.FullName))</div>
<div class="line"><a name="l00173"></a><span class="lineno"> 173</span>  {</div>
<div class="line"><a name="l00174"></a><span class="lineno"> 174</span>  File.WriteAllText(_file.FullName, <span class="stringliteral">"{ \"entrys\": []}"</span>);</div>
<div class="line"><a name="l00175"></a><span class="lineno"> 175</span>  }</div>
<div class="line"><a name="l00176"></a><span class="lineno"> 176</span>  }</div>
<div class="line"><a name="l00177"></a><span class="lineno"> 177</span>  <span class="keywordflow">catch</span> (Exception e)</div>
<div class="line"><a name="l00178"></a><span class="lineno"> 178</span>  {</div>
<div class="line"><a name="l00179"></a><span class="lineno"> 179</span>  <span class="keywordflow">throw</span> e;</div>
<div class="line"><a name="l00180"></a><span class="lineno"> 180</span>  }</div>
<div class="line"><a name="l00181"></a><span class="lineno"> 181</span>  }</div>
<div class="line"><a name="l00182"></a><span class="lineno"> 182</span>  }</div>
<div class="line"><a name="l00183"></a><span class="lineno"> 183</span> }</div>
<div class="ttc" id="aa00062_html"><div class="ttname"><a href="a00062.html">BasicxLogger</a></div><div class="ttdef"><b>Definition:</b> <a href="a00002_source.html#l00010">SqlServerDatabase.cs:11</a></div></div>
<div class="ttc" id="aa00062_html_a0768f6cb40899c29cccd5471f354b2b5"><div class="ttname"><a href="a00062.html#a0768f6cb40899c29cccd5471f354b2b5">BasicxLogger.LogTag</a></div><div class="ttdeci">LogTag</div><div class="ttdoc">Enum that contains the message tags, that can be used for logging</div><div class="ttdef"><b>Definition:</b> <a href="a00044_source.html#l00010">LogTag.cs:11</a></div></div>
<div class="ttc" id="aa00064_html"><div class="ttname"><a href="a00064.html">BasicxLogger.Files</a></div><div class="ttdef"><b>Definition:</b> <a href="a00005_source.html#l00012">JsonLogFile.cs:13</a></div></div>
<div class="ttc" id="aa00066_html"><div class="ttname"><a href="a00066.html">BasicxLogger.Models</a></div><div class="ttdef"><b>Definition:</b> <a href="a00035_source.html#l00008">JsonLogModel.cs:9</a></div></div>
<div class="ttc" id="aa00067_html"><div class="ttname"><a href="a00067.html">BasicxLogger.Base</a></div><div class="ttdef"><b>Definition:</b> <a href="a00050_source.html#l00005">ILogDatabase.cs:6</a></div></div>
<div class="ttc" id="aa00087_html"><div class="ttname"><a href="a00087.html">BasicxLogger.Files.JsonLogFile</a></div><div class="ttdoc">Class that represents a log file with the file extension .json</div><div class="ttdef"><b>Definition:</b> <a href="a00005_source.html#l00017">JsonLogFile.cs:18</a></div></div>
<div class="ttc" id="aa00087_html_a20b84923199b604fb576ddc4e3479390"><div class="ttname"><a href="a00087.html#a20b84923199b604fb576ddc4e3479390">BasicxLogger.Files.JsonLogFile.TextEncoding</a></div><div class="ttdeci">Encoding TextEncoding</div><div class="ttdoc">Gets or Sets the text encoding for the file</div><div class="ttdef"><b>Definition:</b> <a href="a00005_source.html#l00022">JsonLogFile.cs:22</a></div></div>
<div class="ttc" id="aa00087_html_a31016df6f5a1f8b177e2e14b1238410c"><div class="ttname"><a href="a00087.html#a31016df6f5a1f8b177e2e14b1238410c">BasicxLogger.Files.JsonLogFile.WriteToFile< T ></a></div><div class="ttdeci">void WriteToFile< T >(T logObject)</div><div class="ttdoc">Writes the given object to the log file</div><div class="ttdef"><b>Definition:</b> <a href="a00005_source.html#l00126">JsonLogFile.cs:126</a></div></div>
<div class="ttc" id="aa00087_html_a7bce630184811e5f175f1549f90dc95a"><div class="ttname"><a href="a00087.html#a7bce630184811e5f175f1549f90dc95a">BasicxLogger.Files.JsonLogFile.DirectoryName</a></div><div class="ttdeci">string DirectoryName</div><div class="ttdoc">Gets a string representing the directory's full path</div><div class="ttdef"><b>Definition:</b> <a href="a00005_source.html#l00027">JsonLogFile.cs:27</a></div></div>
<div class="ttc" id="aa00087_html_ad35c8e513f31acc59c3ccebb898b9556"><div class="ttname"><a href="a00087.html#ad35c8e513f31acc59c3ccebb898b9556">BasicxLogger.Files.JsonLogFile.FullName</a></div><div class="ttdeci">string FullName</div><div class="ttdoc">Gets the full path of the file</div><div class="ttdef"><b>Definition:</b> <a href="a00005_source.html#l00032">JsonLogFile.cs:32</a></div></div>
<div class="ttc" id="aa00087_html_adc72129519c46b689cdda4867e1a62a3"><div class="ttname"><a href="a00087.html#adc72129519c46b689cdda4867e1a62a3">BasicxLogger.Files.JsonLogFile.WriteToFile</a></div><div class="ttdeci">void WriteToFile(LogTag messageTag, string timestamp, string message, string id="")</div><div class="ttdoc">Writes a log message with the given data to the log file</div><div class="ttdef"><b>Definition:</b> <a href="a00005_source.html#l00065">JsonLogFile.cs:65</a></div></div>
<div class="ttc" id="aa00087_html_afb269f21eef7c35ea2c750a3d1ba4cb0"><div class="ttname"><a href="a00087.html#afb269f21eef7c35ea2c750a3d1ba4cb0">BasicxLogger.Files.JsonLogFile.JsonLogFile</a></div><div class="ttdeci">JsonLogFile(string directoryPath, string fileName)</div><div class="ttdoc">Initializes a new instance of the BasicxLogger.Files.JsonLogFile class</div><div class="ttdef"><b>Definition:</b> <a href="a00005_source.html#l00048">JsonLogFile.cs:48</a></div></div>
<div class="ttc" id="aa00087_html_afcaff1ad8fc304fdaed8fc56eefccbc6"><div class="ttname"><a href="a00087.html#afcaff1ad8fc304fdaed8fc56eefccbc6">BasicxLogger.Files.JsonLogFile.Extension</a></div><div class="ttdeci">string Extension</div><div class="ttdoc">Gets the string representing the extension part of the file</div><div class="ttdef"><b>Definition:</b> <a href="a00005_source.html#l00037">JsonLogFile.cs:37</a></div></div>
<div class="ttc" id="aa00127_html"><div class="ttname"><a href="a00127.html">BasicxLogger.Models.JsonLogModel</a></div><div class="ttdoc">Data model for the json log file</div><div class="ttdef"><b>Definition:</b> <a href="a00035_source.html#l00013">JsonLogModel.cs:14</a></div></div>
<div class="ttc" id="aa00127_html_a42fff250a960eec93e84f0d7df68c61c"><div class="ttname"><a href="a00127.html#a42fff250a960eec93e84f0d7df68c61c">BasicxLogger.Models.JsonLogModel.Entrys</a></div><div class="ttdeci">List< T > Entrys</div><div class="ttdoc">List of log messages</div><div class="ttdef"><b>Definition:</b> <a href="a00035_source.html#l00019">JsonLogModel.cs:19</a></div></div>
<div class="ttc" id="aa00131_html"><div class="ttname"><a href="a00131.html">BasicxLogger.Models.LogMessageModel</a></div><div class="ttdoc">Data model for one log message in a json log file</div><div class="ttdef"><b>Definition:</b> <a href="a00038_source.html#l00012">LogMessageModel.cs:13</a></div></div>
<div class="ttc" id="aa00143_html"><div class="ttname"><a href="a00143.html">BasicxLogger.Base.ILogFile</a></div><div class="ttdoc">Interface that represents a file for the FileLogger</div><div class="ttdef"><b>Definition:</b> <a href="a00053_source.html#l00012">ILogFile.cs:13</a></div></div>
</div><!-- fragment --></div><!-- contents -->
</div><!-- doc-content -->
<!-- start footer part -->
<div id="nav-path" class="navpath"><!-- id is needed for treeview function! -->
<ul>
<li class="navelem"><a class="el" href="dir_b2f33c71d4aa5e7af42a1ca61ff5af1b.html">source</a></li><li class="navelem"><a class="el" href="dir_925cbf1a02082bc0db71a948a17520b7.html">BasicxLogger</a></li><li class="navelem"><a class="el" href="dir_4b9d4dd8dd7e0f90ae3a29d1d5988f0f.html">Components</a></li><li class="navelem"><a class="el" href="dir_72c2f97103c017b6fc466aaf2cd88024.html">Files</a></li><li class="navelem"><b>JsonLogFile.cs</b></li>
<li class="footer">Generated by <a href="https://www.doxygen.org/index.html"><img class="footer" src="doxygen.svg" width="104" height="31" alt="doxygen"/></a> 1.9.1 </li>
</ul>
</div>
</body>
</html>
| 118.959259 | 642 | 0.648308 |
4a9b680fed62da20888011aff054427503770165 | 437 | html | HTML | quotes.html | agrim123/agrim123.github.io | d752049795e935d2c870391e9eef18721de88a78 | [
"MIT"
] | null | null | null | quotes.html | agrim123/agrim123.github.io | d752049795e935d2c870391e9eef18721de88a78 | [
"MIT"
] | null | null | null | quotes.html | agrim123/agrim123.github.io | d752049795e935d2c870391e9eef18721de88a78 | [
"MIT"
] | null | null | null | ---
layout: page
title: Quotes
permalink: /quotes/
description: "An list of quotes"
---
<blockquote>
“Always code as if the guy who ends up maintaining your code will be a violent psychopath who knows where you live” <br/>
- John Woods
</blockquote>
<blockquote>
"Every great developer you know got there by solving problems they were unqualified to solve until they actually did it."<br/>
- Patrick McKenzie
</blockquote>
| 25.705882 | 130 | 0.732265 |
53135f5c9e96df329ec5af6591c21779b2fc6cd5 | 778 | asm | Assembly | programs/oeis/057/A057356.asm | karttu/loda | 9c3b0fc57b810302220c044a9d17db733c76a598 | [
"Apache-2.0"
] | 1 | 2021-03-15T11:38:20.000Z | 2021-03-15T11:38:20.000Z | programs/oeis/057/A057356.asm | karttu/loda | 9c3b0fc57b810302220c044a9d17db733c76a598 | [
"Apache-2.0"
] | null | null | null | programs/oeis/057/A057356.asm | karttu/loda | 9c3b0fc57b810302220c044a9d17db733c76a598 | [
"Apache-2.0"
] | null | null | null | ; A057356: a(n) = floor(2*n/7).
; 0,0,0,0,1,1,1,2,2,2,2,3,3,3,4,4,4,4,5,5,5,6,6,6,6,7,7,7,8,8,8,8,9,9,9,10,10,10,10,11,11,11,12,12,12,12,13,13,13,14,14,14,14,15,15,15,16,16,16,16,17,17,17,18,18,18,18,19,19,19,20,20,20,20,21,21,21,22,22,22,22,23,23,23,24,24,24,24,25,25,25,26,26,26,26,27,27,27,28,28,28,28,29,29,29,30,30,30,30,31,31,31,32,32,32,32,33,33,33,34,34,34,34,35,35,35,36,36,36,36,37,37,37,38,38,38,38,39,39,39,40,40,40,40,41,41,41,42,42,42,42,43,43,43,44,44,44,44,45,45,45,46,46,46,46,47,47,47,48,48,48,48,49,49,49,50,50,50,50,51,51,51,52,52,52,52,53,53,53,54,54,54,54,55,55,55,56,56,56,56,57,57,57,58,58,58,58,59,59,59,60,60,60,60,61,61,61,62,62,62,62,63,63,63,64,64,64,64,65,65,65,66,66,66,66,67,67,67,68,68,68,68,69,69,69,70,70,70,70,71
mov $1,$0
mul $1,2
div $1,7
| 111.142857 | 716 | 0.638817 |
75ff8931c23c48ab92d5ce8ff12e190f13d47e68 | 2,034 | java | Java | ovata-cr-api/src/main/java/ch/ovata/cr/spi/store/Transaction.java | ovatacms/ovata-content-repository | 982feacbd031cdc8152a14cfd249d0e57c72e7c1 | [
"Apache-2.0"
] | null | null | null | ovata-cr-api/src/main/java/ch/ovata/cr/spi/store/Transaction.java | ovatacms/ovata-content-repository | 982feacbd031cdc8152a14cfd249d0e57c72e7c1 | [
"Apache-2.0"
] | 15 | 2021-01-02T17:11:25.000Z | 2022-03-08T21:12:10.000Z | ovata-cr-api/src/main/java/ch/ovata/cr/spi/store/Transaction.java | ovatacms/ovata-content-repository | 982feacbd031cdc8152a14cfd249d0e57c72e7c1 | [
"Apache-2.0"
] | null | null | null | /*
* $Id: Transaction.java 679 2017-02-25 10:28:00Z dani $
* Created on 12.01.2017, 19:00:00
*
* Copyright (c) 2017 by Ovata GmbH,
* All rights reserved.
*
* This software is the confidential and proprietary information
* of Ovata GmbH ("Confidential Information"). You
* shall not disclose such Confidential Information and shall use
* it only in accordance with the terms of the license agreement
* you entered into with Ovata GmbH.
*/
package ch.ovata.cr.spi.store;
import ch.ovata.cr.api.Session;
import java.util.Collection;
import java.util.Date;
import java.util.Optional;
/**
* Represents a transaction that was written to the backend store.
* @author dani
*/
public interface Transaction {
enum State { IN_FLIGHT, COMMITTED, ROLLED_BACK }
/**
* The session initiating this transaction
* @return the session
*/
Session getSession();
/**
* Retrieves the time this transaction was started
* @return the trx timestamp
*/
Date getStartTime();
/**
* Retrieves the time this transaction was committed
* @return the time this trx was committed
*/
Date getEndTime();
/**
* Name of the user that started this transaction
* @return name of the user
*/
String getUsername();
/**
* Name of the workspace affected by this transaction
* @return name of the workspace
*/
String getWorkspaceName();
/**
* Unique revision id of this transaction
* @return the revision id of this transaction
*/
long getRevision();
/**
* The list of affected nodes by this transaction
* @return list of affected nodes
*/
Collection<String> getAffectedNodeIds();
/**
* Retrieves the commit message for this transaction
* @return the commit message of the transaction
*/
Optional<String> getMessage();
/**
* Sets the state of the transaction object to "COMMITTED"
*/
void markCommitted();
}
| 24.804878 | 66 | 0.646509 |
96b570a6bb5f6da1263aa2fa29e41070fe745679 | 14,800 | ps1 | PowerShell | Posh-ACME/Public/New-PAOrder.ps1 | webprofusion-chrisc/Posh-ACME | c7d4c1ab154d94aa9da98aa5c0e97e26cf1fd027 | [
"MIT"
] | null | null | null | Posh-ACME/Public/New-PAOrder.ps1 | webprofusion-chrisc/Posh-ACME | c7d4c1ab154d94aa9da98aa5c0e97e26cf1fd027 | [
"MIT"
] | null | null | null | Posh-ACME/Public/New-PAOrder.ps1 | webprofusion-chrisc/Posh-ACME | c7d4c1ab154d94aa9da98aa5c0e97e26cf1fd027 | [
"MIT"
] | null | null | null | function New-PAOrder {
[CmdletBinding(SupportsShouldProcess,DefaultParameterSetName='FromScratch')]
[OutputType('PoshACME.PAOrder')]
param(
[Parameter(ParameterSetName='FromScratch',Mandatory,Position=0)]
[Parameter(ParameterSetName='ImportKey',Mandatory,Position=0)]
[string[]]$Domain,
[Parameter(ParameterSetName='FromCSR',Mandatory,Position=0)]
[string]$CSRPath,
[Parameter(ParameterSetName='FromScratch',Position=1)]
[ValidateScript({Test-ValidKeyLength $_ -ThrowOnFail})]
[string]$KeyLength='2048',
[Parameter(ParameterSetName='ImportKey',Mandatory)]
[string]$KeyFile,
[ValidateScript({Test-ValidFriendlyName $_ -ThrowOnFail})]
[string]$Name,
[ValidateScript({Test-ValidPlugin $_ -ThrowOnFail})]
[string[]]$Plugin,
[hashtable]$PluginArgs,
[ValidateRange(0, 3650)]
[int]$LifetimeDays,
[string[]]$DnsAlias,
[Parameter(ParameterSetName='FromScratch')]
[Parameter(ParameterSetName='ImportKey')]
[switch]$OCSPMustStaple,
[Parameter(ParameterSetName='FromScratch')]
[Parameter(ParameterSetName='ImportKey')]
[switch]$AlwaysNewKey,
[Parameter(ParameterSetName='FromScratch')]
[Parameter(ParameterSetName='ImportKey')]
[string]$FriendlyName,
[Parameter(ParameterSetName='FromScratch')]
[Parameter(ParameterSetName='ImportKey')]
[string]$PfxPass='poshacme',
[Parameter(ParameterSetName='FromScratch')]
[Parameter(ParameterSetName='ImportKey')]
[ValidateScript({Test-SecureStringNotNullOrEmpty $_ -ThrowOnFail})]
[securestring]$PfxPassSecure,
[Parameter(ParameterSetName='FromScratch')]
[Parameter(ParameterSetName='ImportKey')]
[switch]$Install,
[switch]$UseSerialValidation,
[int]$DnsSleep=120,
[int]$ValidationTimeout=60,
[string]$PreferredChain,
[switch]$Force
)
# Make sure we have an account configured
if (-not ($acct = Get-PAAccount)) {
try { throw "No ACME account configured. Run Set-PAAccount or New-PAAccount first." }
catch { $PSCmdlet.ThrowTerminatingError($_) }
}
# If using a pre-generated CSR, extract the details so we can generate expected parameters
if ('FromCSR' -eq $PSCmdlet.ParameterSetName) {
$CSRPath = $ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath($CSRPath)
$csrDetails = Get-CsrDetails $CSRPath
$Domain = $csrDetails.Domain
$KeyLength = $csrDetails.KeyLength
$OCSPMustStaple = New-Object Management.Automation.SwitchParameter($csrDetails.OCSPMustStaple)
}
# If importing a key, make sure it's valid so we can set the appropriate KeyLength
if ('ImportKey' -eq $PSCmdlet.ParameterSetName) {
$KeyFile = $ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath($KeyFile)
try {
$kLength = [string]::Empty
# we don't actually care about the key object, just the parsed length
$null = New-PAKey -KeyFile $KeyFile -ParsedLength ([ref]$kLength)
$KeyLength = $kLength
}
catch { $PSCmdlet.ThrowTerminatingError($_) }
}
# PfxPassSecure takes precedence over PfxPass if both are specified but we
# need the value in plain text. So we'll just take over the PfxPass variable
# to use for the rest of the function.
if ($PfxPassSecure) {
# throw a warning if they also specified PfxPass
if ('PfxPass' -in $PSBoundParameters.Keys) {
Write-Warning "PfxPass and PfxPassSecure were both specified. Using value from PfxPassSecure."
}
# override the existing PfxPass parameter
$PfxPass = [pscredential]::new('u',$PfxPassSecure).GetNetworkCredential().Password
$PSBoundParameters.PfxPass = $PfxPass
}
# check for an existing order
if ($Name) {
$order = Get-PAOrder -Name $Name
} else {
$order = Get-PAOrder -MainDomain $Domain[0]
# set the default Name to a filesystem friendly version of the first domain
$Name = $Domain[0].Replace('*','!')
}
# separate the SANs
$SANs = @($Domain | Where-Object { $_ -ne $Domain[0] })
# There's a chance we may be overwriting an existing order here. So check for
# confirmation if certain conditions are true
if (-not $Force) {
$oldDomains = (@($order.MainDomain) + @($order.SANs) | Sort-Object) -join ','
# skip confirmation if the Domains or KeyLength are different regardless
# of the original order status or if the order is pending but expired
if ( ($order -and ($KeyLength -ne $order.KeyLength -or
($oldDomains -ne ($Domain | Sort-Object) -join ',') -or
($order.status -eq 'pending' -and (Get-DateTimeOffsetNow) -gt ([DateTimeOffset]::Parse($order.expires))) ))) {
# do nothing
# confirm if previous order is still in progress
} elseif ($order -and $order.status -in 'pending','ready','processing') {
if (-not $PSCmdlet.ShouldContinue("Do you wish to overwrite?",
"Existing order with status $($order.status).")) { return }
# confirm if previous order not up for renewal
} elseif ($order -and $order.status -eq 'valid' -and
(Get-DateTimeOffsetNow) -lt ([DateTimeOffset]::Parse($order.RenewAfter))) {
if (-not $PSCmdlet.ShouldContinue("Do you wish to overwrite?",
"Existing order has not reached suggested renewal window.")) { return }
}
}
Write-Debug "Creating new $KeyLength order with domains: $($Domain -join ', ')"
# Force a key change if the KeyLength is different than the old order
if ($order -and $order.KeyLength -ne $KeyLength) {
$ForceNewKey = $true
}
# build the protected header for the request
$header = @{
alg = $acct.alg;
kid = $acct.location;
nonce = $script:Dir.nonce;
url = $script:Dir.newOrder;
}
# super lazy IPv4 address regex, but we just need to be able to
# distinguish from an FQDN
$reIPv4 = [regex]'^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$'
# build the payload object
$payload = @{identifiers=@()}
foreach ($d in $Domain) {
# IP identifiers (RFC8738) are an extension to the original ACME protocol
# https://tools.ietf.org/html/rfc8738
#
# So we have to distinguish between domain FQDNs and IPv4/v6 addresses
# and send the appropriate identifier type for each one. We don't care
# if the IP address entered is actually valid or not, only that it is
# parsable as an IP address and should be sent as one rather than a
# DNS name.
if ($d -match $reIPv4 -or $d -like '*:*') {
Write-Debug "$d identified as IP address. Attempting to parse."
$ip = [ipaddress]$d
$payload.identifiers += @{type='ip';value=$ip.ToString()}
}
else {
$payload.identifiers += @{type='dns';value=$d}
}
}
# add the requested certificate lifetime if specified
if ($LifetimeDays) {
$now = [DateTimeOffset]::UtcNow
$notBefore = $now.ToString('yyyy-MM-ddTHH:mm:ssZ', [Globalization.CultureInfo]::InvariantCulture)
$notAfter = $now.AddDays($LifetimeDays).ToString('yyyy-MM-ddTHH:mm:ssZ', [Globalization.CultureInfo]::InvariantCulture)
$payload.notBefore = $notBefore
$payload.notAfter = $notAfter
}
$payloadJson = $payload | ConvertTo-Json -Depth 5 -Compress
# send the request
try {
$response = Invoke-ACME $header $payloadJson $acct -EA Stop
} catch { throw }
# process the response
$order = $response.Content | ConvertFrom-Json
$order.PSObject.TypeNames.Insert(0,'PoshACME.PAOrder')
# fix any dates that may have been parsed by PSCore's JSON serializer
$order.expires = Repair-ISODate $order.expires
# add the location from the header
if ($response.Headers.ContainsKey('Location')) {
$location = $response.Headers['Location'] | Select-Object -First 1
Write-Debug "Adding location $location"
$order | Add-Member -MemberType NoteProperty -Name 'location' -Value $location
} else {
try { throw 'No Location header found in newOrder output' }
catch { $PSCmdlet.ThrowTerminatingError($_) }
}
# Make sure the returned order isn't a duplicate of one we already have a copy
# of locally. This can happen with Let's Encrypt when an existing order with the
# same identifiers is still in the 'pending' or 'ready' state.
$orderConflict = Get-PAOrder -List | Where-Object { $_.location -eq $location -and $_.Name -ne $Name }
if ($orderConflict) {
try { throw "ACME Server returned duplicate order details that match existing local order '$($orderConflict.Name)'" }
catch { $PSCmdlet.ThrowTerminatingError($_) }
}
# Per https://tools.ietf.org/html/rfc8555#section-7.1.3
# In the returned order object, there is no guarantee that the list of identifiers
# match the sequence they were submitted in. The list of authorizations may not match
# either. And the identifiers and authorizations may not even match each other's
# sequence.
#
# Unfortunately, things like DNS plugins and challenge aliases currently depend on
# the assumption that the sequence of identifiers and the sequence of authorizations
# all match the original sequence of the submitted domains. So we need to make sure
# that it's true until we refactor things so those assumptions aren't necessary anymore.
# set the order's identifiers to the original payload's identifiers since that was
# correct already
$order.identifiers = $payload.identifiers
# unfortunately, there's no way to know which authorization URL is for which identifier
# just by parsing it. So we need to query the details for each one in order to put them
# in the right order
$auths = Get-PAAuthorization $order.authorizations
for ($i=0; $i -lt $order.identifiers.Count; $i++) {
$auth = $auths | Where-Object { $_.fqdn -eq $order.identifiers[$i].value }
$order.authorizations[$i] = $auth.location
}
# make sure FriendlyName is non-empty
if ([String]::IsNullOrWhiteSpace($FriendlyName)) {
$FriendlyName = $Domain[0]
}
# add additional members we'll need for later
$order | Add-Member -NotePropertyMembers @{
MainDomain = $Domain[0]
SANs = $SANs
KeyLength = $KeyLength
CertExpires = $null
RenewAfter = $null
OCSPMustStaple = $OCSPMustStaple.IsPresent
Plugin = @('Manual')
DnsAlias = $null
DnsSleep = $DnsSleep
ValidationTimeout = $ValidationTimeout
FriendlyName = $FriendlyName
PfxPass = $PfxPass
Install = $Install.IsPresent
UseSerialValidation = $UseSerialValidation.IsPresent
PreferredChain = $PreferredChain
AlwaysNewKey = $AlwaysNewKey.IsPresent
LifetimeDays = $null
}
# override AlwaysNewKey if they're importing the private key
if ($order.AlwaysNewKey -and 'ImportKey' -eq $PSCmdlet.ParameterSetName) {
Write-Warning "AlwaysNewKey was disabled because private key was imported using the KeyFile parameter."
$order.AlwaysNewKey = $false
}
# make sure there's a certificate field for later
if ('certificate' -notin $order.PSObject.Properties.Name) {
$order | Add-Member 'certificate' $null
}
# add the CSR data if we have it
if ('FromCSR' -eq $PSCmdlet.ParameterSetName) {
$order | Add-Member 'CSRBase64Url' $csrDetails.Base64Url
}
# update other optional fields
if ('Plugin' -in $PSBoundParameters.Keys) {
$order.Plugin = @($Plugin)
}
if ('DnsAlias' -in $PSBoundParameters.Keys) {
$order.DnsAlias = @($DnsAlias)
}
if ('LifetimeDays' -in $PSBoundParameters.Keys) {
$order.LifetimeDays = $LifetimeDays
}
# add the Name and Folder properties
$order | Add-Member 'Name' $Name -Force
$order | Add-Member 'Folder' (Join-Path $acct.Folder $Name) -Force
# save it to memory and disk
$order.Name | Out-File (Join-Path $acct.Folder 'current-order.txt') -Force -EA Stop
$script:Order = $order
Update-PAOrder $order -SaveOnly
# export plugin args now that the order exists on disk
if ('PluginArgs' -in $PSBoundParameters.Keys) {
Export-PluginArgs -Order $order -PluginArgs $PluginArgs
}
# Make a local copy of the specified CSR file
if ('FromCSR' -eq $PSCmdlet.ParameterSetName) {
$csrDest = Join-Path $order.Folder 'request.csr'
if ($CSRPath -ne $csrDest) {
Copy-Item -Path $CSRPath -Destination $csrDest
}
}
# Determine whether to remove the old private key. This is necessary if it exists
# and we're using a CSR or it's explicitly requested or the new KeyLength doesn't match the old one.
$keyPath = Join-Path $order.Folder 'cert.key'
$removeOldKey = ( (Test-Path $keyPath -PathType Leaf) -and
($order.AlwaysNewKey -or $ForceNewKey -or 'FromCSR' -eq $PSCmdlet.ParameterSetName) )
# backup the old private key if necessary
if ($removeOldKey) {
Write-Verbose "Removing old private key"
$oldKey = Get-ChildItem $keyPath
$oldKey | Move-Item -Destination { "$($_.FullName).bak" } -Force
}
# backup any old certs/requests that might exist
$oldFiles = Get-ChildItem (Join-Path $order.Folder *) -Include cert.cer,cert.pfx,chain.cer,fullchain.cer,fullchain.pfx
$oldFiles | Move-Item -Destination { "$($_.FullName).bak" } -Force
# remove old chain files
Get-ChildItem (Join-Path $order.Folder 'chain*.cer') -Exclude chain.cer |
Remove-Item -Force
# Make a local copy of the private key if it was specified.
if ('ImportKey' -eq $PSCmdlet.ParameterSetName) {
if ($keyPath -ne $KeyFile) {
Copy-Item -Path $KeyFile -Destination $keyPath
}
}
return $order
}
| 42.651297 | 128 | 0.626622 |