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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
f407d94ae3f53623958bedc7490d9fe4719a221b | 527 | asm | Assembly | PRG/levels/Hills/W5HBA.asm | narfman0/smb3_pp1 | 38a58adafff67a403591e38875e9fae943a5fe76 | [
"Unlicense"
] | null | null | null | PRG/levels/Hills/W5HBA.asm | narfman0/smb3_pp1 | 38a58adafff67a403591e38875e9fae943a5fe76 | [
"Unlicense"
] | null | null | null | PRG/levels/Hills/W5HBA.asm | narfman0/smb3_pp1 | 38a58adafff67a403591e38875e9fae943a5fe76 | [
"Unlicense"
] | null | null | null | ; Original address was $ACB5
; World 5 Hammer Bro ground battle A
.word $0000 ; Alternate level layout
.word $0000 ; Alternate object layout
.byte LEVEL1_SIZE_01 | LEVEL1_YSTART_170
.byte LEVEL2_BGPAL_00 | LEVEL2_OBJPAL_08 | LEVEL2_XSTART_18 | LEVEL2_UNUSEDFLAG
.byte LEVEL3_TILESET_00 | LEVEL3_VSCROLL_LOCKED
.byte LEVEL4_BGBANK_INDEX(19) | LEVEL4_INITACT_NOTHING
.byte LEVEL5_BGM_BATTLE | LEVEL5_TIME_200
.byte $40, $00, $0E, $53, $00, $0C, $57, $0C, $0B, $32, $07, $16, $36, $07, $16, $9A
.byte $00, $80, $0F, $FF
| 40.538462 | 85 | 0.726755 |
16249bd892a443f14082230000d7fd95377399da | 249 | h | C | release/src/linux/linux/include/asm-m68k/hdreg.h | enfoTek/tomato.linksys.e2000.nvram-mod | 2ce3a5217def49d6df7348522e2bfda702b56029 | [
"FSFAP"
] | 80 | 2015-01-02T10:14:04.000Z | 2021-06-07T06:29:49.000Z | release/src/linux/linux/include/asm-m68k/hdreg.h | unforgiven512/tomato | 96f09fab4929c6ddde5c9113f1b2476ad37133c4 | [
"FSFAP"
] | 9 | 2015-05-14T11:03:12.000Z | 2018-01-04T07:12:58.000Z | release/src/linux/linux/include/asm-m68k/hdreg.h | unforgiven512/tomato | 96f09fab4929c6ddde5c9113f1b2476ad37133c4 | [
"FSFAP"
] | 69 | 2015-01-02T10:45:56.000Z | 2021-09-06T07:52:13.000Z | /*
* linux/include/asm-m68k/hdreg.h
*
* Copyright (C) 1994-1996 Linus Torvalds & authors
*/
#ifndef _M68K_HDREG_H
#define _M68K_HDREG_H
typedef unsigned int q40ide_ioreg_t;
typedef unsigned char * ide_ioreg_t;
#endif /* _M68K_HDREG_H */
| 17.785714 | 53 | 0.726908 |
7ab5864d760ce6ce4db4e20384f8a984e4dd9f83 | 649 | asm | Assembly | oeis/083/A083222.asm | neoneye/loda-programs | 84790877f8e6c2e821b183d2e334d612045d29c0 | [
"Apache-2.0"
] | 11 | 2021-08-22T19:44:55.000Z | 2022-03-20T16:47:57.000Z | oeis/083/A083222.asm | neoneye/loda-programs | 84790877f8e6c2e821b183d2e334d612045d29c0 | [
"Apache-2.0"
] | 9 | 2021-08-29T13:15:54.000Z | 2022-03-09T19:52:31.000Z | oeis/083/A083222.asm | neoneye/loda-programs | 84790877f8e6c2e821b183d2e334d612045d29c0 | [
"Apache-2.0"
] | 3 | 2021-08-22T20:56:47.000Z | 2021-09-29T06:26:12.000Z | ; A083222: a(n) = (4*5^n + (-5)^n)/5.
; Submitted by Jon Maiga
; 1,3,25,75,625,1875,15625,46875,390625,1171875,9765625,29296875,244140625,732421875,6103515625,18310546875,152587890625,457763671875,3814697265625,11444091796875,95367431640625,286102294921875,2384185791015625,7152557373046875,59604644775390625,178813934326171875,1490116119384765625,4470348358154296875,37252902984619140625,111758708953857421875,931322574615478515625,2793967723846435546875,23283064365386962890625,69849193096160888671875,582076609134674072265625,1746229827404022216796875
mov $1,$0
gcd $0,2
mul $0,2
add $0,1
mov $2,5
pow $2,$1
mul $0,$2
sub $0,5
div $0,5
add $0,1
| 43.266667 | 491 | 0.828968 |
2a12320ebb7b7baea6b9e7a6de5c603ead214fed | 378 | html | HTML | UnderConstruction.html | Arshad-J-H/Arshad-J-H.github.io | 5f63678cbab5b155d85d9d904336471804d3905b | [
"Apache-2.0"
] | null | null | null | UnderConstruction.html | Arshad-J-H/Arshad-J-H.github.io | 5f63678cbab5b155d85d9d904336471804d3905b | [
"Apache-2.0"
] | null | null | null | UnderConstruction.html | Arshad-J-H/Arshad-J-H.github.io | 5f63678cbab5b155d85d9d904336471804d3905b | [
"Apache-2.0"
] | null | null | null | <!DOCTYPE html>
<html>
<head>
<title>JokeOpedia</title>
<link rel="stylesheet" type="text/css" href="UnderConstruction.css">
</head>
<body>
<p><em><strong>Due to an issue the files were not working properly so i am trying to rebuild the website and you will see that there will be a new look to the web!</strong></em></p>
<img src="Under.png">
</body>
</html>
| 31.5 | 182 | 0.674603 |
1420361e9b2643a74ab8f7318eab95ec72e96165 | 316 | css | CSS | web/assets/vendor/metis-canvas/metis-canvas-theme.css | hugo-clems/mi-siteweb | a9f1a842e80d0e37180eec3223ccef5096e9353d | [
"MIT"
] | 32 | 2017-05-02T03:12:54.000Z | 2018-10-11T04:06:07.000Z | dist/metis-canvas-theme.css | metisadmin/metis-canvas | 1cf49efcd1179c2f10e603a1acf2c63aa3e2b0b9 | [
"MIT"
] | 371 | 2020-03-04T21:51:56.000Z | 2022-03-31T20:59:11.000Z | dist/metis-canvas-theme.css | metisadmin/metis-canvas | 1cf49efcd1179c2f10e603a1acf2c63aa3e2b0b9 | [
"MIT"
] | 14 | 2017-06-16T02:57:49.000Z | 2018-06-17T01:31:45.000Z | /**
* metis-canvas v1.0.1
* Homepage : https://github.com/metisadmin/metis-canvas
* Author : Osman Nuri Okumuş <onokumus@gmail.com> (https://github.com/onokumus)
* Copyright 2016
* Licensed under MIT
*/
.canvas:not([class*="bg-"]) {
background: #fff;
}
.bg-transparent {
background-color: rgba(0, 0, 0, 0.8);
}
| 21.066667 | 79 | 0.670886 |
b9c266a66e0c02f7cc15ff10c1d317cc696f438f | 1,824 | h | C | ZxPlugins-tests/Classes/Prueba/ZPluginsSampleLayer.h | dgzornoza/ZxPlugins | e1dd9deefecfcc35ace8dd1c599b1393ed29fc1a | [
"MIT"
] | null | null | null | ZxPlugins-tests/Classes/Prueba/ZPluginsSampleLayer.h | dgzornoza/ZxPlugins | e1dd9deefecfcc35ace8dd1c599b1393ed29fc1a | [
"MIT"
] | null | null | null | ZxPlugins-tests/Classes/Prueba/ZPluginsSampleLayer.h | dgzornoza/ZxPlugins | e1dd9deefecfcc35ace8dd1c599b1393ed29fc1a | [
"MIT"
] | null | null | null | #ifndef __ZPLUGIN_SAMPLE_LAYER_H__
#define __ZPLUGIN_SAMPLE_LAYER_H__
#include "cocos2d.h"
#include "cocos\ui\CocosGUI.h"
#include "LayerBase.h"
/**
*@brief Clase con la capa para el ejemplo del articulo dedicado a los plugins para acceder a codigo nativo de las plataformas
* http://discuss.cocos2d-x.org/t/wp8-cocos2dx-and-xaml/4886/6
* http://www.cocos2d-x.org/wiki/How_to_integrate_third_SDK
* http://stackoverflow.com/questions/17304386/how-does-one-make-function-calls-or-trigger-events-from-a-native-component-into
* http://discuss.cocos2d-x.org/t/share-iap-for-windows-phone-8/12701/10
* http://discuss.cocos2d-x.org/t/wp8-c-call-c-function-with-param/11302/2
*/
class ZPluginsSampleLayer : public LayerBase
{
public:
/** Destructor por defecto de la clase */
virtual ~ZPluginsSampleLayer(void);
/**
* Macro que sera desplegada en un metodo estatico 'create' para crear e inicializar la instancia de la clase.
* La instancia de la clase debe ser creada invocando el metodo 'ZPluginsSampleLayer::create()'
*/
CREATE_FUNC(ZPluginsSampleLayer);
// se hace uso de la macro de cocos2dx para definir el acceso de metodos heredados
// con la finalidad de no violar el principio de sustitucion de Liskov y usar el mismo modificador de las clases base)
CC_CONSTRUCTOR_ACCESS:
/**
* Metodo sobreescrito que sera invocado para inicializar la instancia de la clase.
* @return True si se puede ha inicializado correctamente, false en caso contrario
*/
virtual bool init() override;
protected:
/** Constructor por defecto de la clase (protegido para evitar que se creen instancias desde fuera de la clase, deben crearse mediante el metodo 'ZPluginsSampleLayer::create()')*/
ZPluginsSampleLayer(void);
void _createTestButton(cocos2d::ui::Layout* _layout);
};
#endif // __ZPLUGIN_SAMPLE_LAYER_H__
| 34.415094 | 180 | 0.771382 |
6189df8ae2a869515b8cf5204b2ab575953207b2 | 563 | css | CSS | data/usercss/93368.user.css | 33kk/uso-archive | 2c4962d1d507ff0eaec6dcca555efc531b37a9b4 | [
"MIT"
] | 118 | 2020-08-28T19:59:28.000Z | 2022-03-26T16:28:40.000Z | data/usercss/93368.user.css | 33kk/uso-archive | 2c4962d1d507ff0eaec6dcca555efc531b37a9b4 | [
"MIT"
] | 38 | 2020-09-02T01:08:45.000Z | 2022-01-23T02:47:24.000Z | data/usercss/93368.user.css | 33kk/uso-archive | 2c4962d1d507ff0eaec6dcca555efc531b37a9b4 | [
"MIT"
] | 21 | 2020-08-19T01:12:43.000Z | 2022-03-15T21:55:17.000Z | /* ==UserStyle==
@name clean 9gag
@namespace USO Archive
@author rendle
@description `clean 9gag - no ads, no social buttons, deleted some buttons`
@version 20130925.13.56
@license NO-REDISTRIBUTION
@preprocessor uso
==/UserStyle== */
@-moz-document domain("9gag.com") {
section#sidebar,
.section-nav,
.post-action-2,
.post-afterbar,
.notification,
.upload,
.banner-block,
.what-to-read-next,
footer
{
display: none !important;
}
header#top-nav .nav-wrap,
.page
{
width: 600px !important;
}
} | 17.59375 | 78 | 0.637655 |
39cccb6cd7164f1c2ac0886944d6354bfd5445f5 | 1,816 | js | JavaScript | lib/min/plugins/sammy.oauth2-0.7.4.min.js | davgit/sammy | b7019809302c87ea07f2d454d9c28855ea441cdf | [
"MIT"
] | 1 | 2019-06-27T11:54:24.000Z | 2019-06-27T11:54:24.000Z | lib/min/plugins/sammy.oauth2-latest.min.js | davgit/sammy | b7019809302c87ea07f2d454d9c28855ea441cdf | [
"MIT"
] | null | null | null | lib/min/plugins/sammy.oauth2-latest.min.js | davgit/sammy | b7019809302c87ea07f2d454d9c28855ea441cdf | [
"MIT"
] | null | null | null | // -- Sammy.js -- /plugins/sammy.oauth2.js
// http://sammyjs.org
// Version: 0.7.4
// Built: 2013-01-27 13:34:14 -0500
(function(e){typeof define=="function"&&define.amd?define(["jquery","sammy"],e):(window.Sammy=window.Sammy||{}).OAuth2=e(window.jQuery,window.Sammy)})(function(e,t){return t.OAuth2=function(t){function n(e){var t=e.match(/#(.*)$/)[1],n=t.split("&"),r={},i,s=n.length;for(i=0;i<s;i+=1){var o=n[i].split("=");r[o[0]]=o[1].replace(/\+/g," ")}return r}t.use("JSON"),this.authorize="/oauth/authorize",this.helper("requireOAuth",function(e){if(!this.app.getAccessToken())return this.redirect(this.app.authorize+"?state="+escape(this.path)),!1;e&&e.apply(this)}),this.helper("loseAccessToken",function(){this.app.loseAccessToken()}),this.requireOAuth=function(e){this.before(e||{},function(e){return e.requireOAuth()})},this.getAccessToken=function(){return this.session("oauth.token")},this.setAccessToken=function(e){this.session("oauth.token",e),this.trigger("oauth.connected")},this.loseAccessToken=function(){this.session("oauth.token",null),this.trigger("oauth.disconnected")},e(document).ajaxSend(function(e,n){var r=t.getAccessToken();r&&n.setRequestHeader("Authorization","OAuth "+r)});var r;this.bind("run",function(e,t){r=t.start_url||"#",this.app.getAccessToken()&&this.trigger("oauth.connected")}),this.before(/#(access_token=|[^\\].*\&access_token=)/,function(e){var t=n(e.path);return this.app.setAccessToken(t.access_token),e.redirect(t.state.length===0?this.app.start_url:unescape(t.state)),!1}).get(/#(access_token=|[^\\].*\&access_token=)/,function(e){}),this.before(/#(error=|[^\\].*\&error=)/,function(e){var t=n(e.path),r=t.error_description||"Access denined";return e.trigger("oauth.denied",{code:t.error,message:r}),!1}).get(/#(error=|[^\\].*\&error=)/,function(e){})},t.OAuth2}); | 363.2 | 1,697 | 0.695485 |
e58e68350c9933e65f66e326b9dbd63449bbe9f7 | 184 | ts | TypeScript | cli/index.ts | tbjgolden/media-query-fns | 637f1b0bbb6d39b5b4df31f9d536fcf215464765 | [
"MIT"
] | 1 | 2022-03-28T00:10:42.000Z | 2022-03-28T00:10:42.000Z | cli/index.ts | tbjgolden/media-query-fns | 637f1b0bbb6d39b5b4df31f9d536fcf215464765 | [
"MIT"
] | 1 | 2022-03-22T11:02:13.000Z | 2022-03-22T11:02:13.000Z | cli/index.ts | tbjgolden/media-query-fns | 637f1b0bbb6d39b5b4df31f9d536fcf215464765 | [
"MIT"
] | null | null | null | #!/usr/bin/env node
import { hello } from "src/compile";
const [_cmd, _fileName, ...args] = process.argv;
const arg = args.join(" ");
if (arg !== "") {
console.log(hello(arg));
}
| 16.727273 | 48 | 0.597826 |
0a853345c41281d1c78daa337b26c4e3d081dfbf | 771 | kt | Kotlin | app/src/main/java/com/vaibhav/notesappcompose/data/repo/collection/CollectionRepo.kt | EtsTest-AndroidApps/NotesX | 4ca9e9dac6d209a52ac74db1dbfb61943f601580 | [
"MIT"
] | 6 | 2021-04-23T13:22:33.000Z | 2022-01-18T08:04:26.000Z | app/src/main/java/com/vaibhav/notesappcompose/data/repo/collection/CollectionRepo.kt | EtsTest-AndroidApps/NotesX | 4ca9e9dac6d209a52ac74db1dbfb61943f601580 | [
"MIT"
] | 1 | 2021-04-23T07:48:01.000Z | 2021-04-23T13:28:01.000Z | app/src/main/java/com/vaibhav/notesappcompose/data/repo/collection/CollectionRepo.kt | EtsTest-AndroidApps/NotesX | 4ca9e9dac6d209a52ac74db1dbfb61943f601580 | [
"MIT"
] | 2 | 2022-02-11T01:30:03.000Z | 2022-03-04T18:25:02.000Z | package com.vaibhav.notesappcompose.data.repo.collection
import androidx.lifecycle.LiveData
import com.vaibhav.notesappcompose.data.models.entity.Collection
import com.vaibhav.notesappcompose.util.Resource
interface CollectionRepo {
//network calls
suspend fun addCollection(userId: Int, collection: Collection): Resource<Collection>
suspend fun fetchCollections(userId: Long): Resource<List<Collection>>
suspend fun deleteCollection(collection: Collection): Resource<Collection>
//local calls
suspend fun saveCollectionIntoDatabase(collection: List<Collection>)
suspend fun deleteAllFromDatabase()
fun getAllCollections(query: String): LiveData<List<Collection>>
suspend fun deleteCollectionFromDb(collection: Collection)
} | 29.653846 | 88 | 0.796368 |
164a33323bc9be004418d76fc1a037fdd75e8f69 | 1,761 | h | C | SEGANKU/eagle.h | mangostaniko/cg15-seganku | 83d603f52e072cf12f08908b94dae3a86577ef84 | [
"Apache-2.0"
] | null | null | null | SEGANKU/eagle.h | mangostaniko/cg15-seganku | 83d603f52e072cf12f08908b94dae3a86577ef84 | [
"Apache-2.0"
] | null | null | null | SEGANKU/eagle.h | mangostaniko/cg15-seganku | 83d603f52e072cf12f08908b94dae3a86577ef84 | [
"Apache-2.0"
] | null | null | null | #ifndef EAGLE_H
#define EAGLE_H
#define GLM_SWIZZLE
#define GLM_FORCE_RADIANS
#include <btBulletDynamicsCommon.h>
#include <glm/gtx/vector_angle.hpp>
#include "geometry.h"
enum EagleState
{
CIRCLING = 0,
ATTACKING = 1,
RETREATING = 2
};
class Eagle : public Geometry
{
// PHYSICS
btCollisionShape *playerShape;
btRigidBody *playerBody;
btDefaultMotionState *motionState;
// GAMEPLAY
// all durations given in seconds
const float EAT_RADIUS = 1.0f;
const float TARGET_DEFENSE_REACH_RADIUS = 13.0f;
const float ATTACK_WAIT_TIME_MIN = 15.0f; // min time after which eagle will attempt to attack player
const float ATTACK_WAIT_TIME_MAX = 25.0f; // max time after which eagle will attempt to attack player
glm::mat4 eagleInitTransform;
EagleState state = CIRCLING;
float totalTimePassed = 0;
float timeSinceLastAttack = 0;
float timeIntervalToNextAttack = ATTACK_WAIT_TIME_MIN;
glm::vec3 targetPos;
bool targetHidden = false;
bool targetDefenseActive = false;
public:
Eagle(const glm::mat4 &matrix, const std::string &filePath);
~Eagle();
virtual void update(float timeDelta, const glm::vec3 &targetPos_, bool targetHidden_, bool targetDefenseActive_);
/**
* @brief return the current state of behaviour of the eagle
* @return the current state of behaviour of the eagle
*/
EagleState getState();
/**
* @brief check whether the target is in TARGET_DEFENSE_REACH_RADIUS of the eagle
* @return whether the target is in TARGET_DEFENSE_REACH_RADIUS of the eagle
*/
bool isInTargetDefenseReach();
/**
* @brief check whether the target is in EAT_RADIUS of the eagle
* @return whether the target is in EAT_RADIUS of the eagle
*/
bool isTargetEaten();
void resetEagle();
private:
};
#endif // EAGLE_H
| 23.48 | 114 | 0.750142 |
0140b06f9b781e4f1eaa58f5af279747ff164e79 | 7,045 | swift | Swift | Parasol/DataController.swift | KoalicjaOtwartyKrakow/Parasol | d32bf7f6a5f1c8b1430fafc7ddcaae6e191f154c | [
"MIT"
] | null | null | null | Parasol/DataController.swift | KoalicjaOtwartyKrakow/Parasol | d32bf7f6a5f1c8b1430fafc7ddcaae6e191f154c | [
"MIT"
] | null | null | null | Parasol/DataController.swift | KoalicjaOtwartyKrakow/Parasol | d32bf7f6a5f1c8b1430fafc7ddcaae6e191f154c | [
"MIT"
] | null | null | null | //
// DataController.swift
// Parasol
//
// Created by Daniel Banasik on 27/02/2022.
//
import Foundation
import CoreLocation
//Shared Instance
let DC = DataController.sharedInstance
class DataController: NSObject, CLLocationManagerDelegate {
#if PRODUCTION
let post = "https://cu2kg3w6c1.execute-api.eu-west-1.amazonaws.com/prod/apartments"
let get = "https://cu2kg3w6c1.execute-api.eu-west-1.amazonaws.com/prod/apartments"
let count = "https://cu2kg3w6c1.execute-api.eu-west-1.amazonaws.com/prod/apartments/count"
let contract = "https://cu2kg3w6c1.execute-api.eu-west-1.amazonaws.com/prod/doc/contract"
#else
let post = "https://cu2kg3w6c1.execute-api.eu-west-1.amazonaws.com/dev/apartments"
let get = "https://cu2kg3w6c1.execute-api.eu-west-1.amazonaws.com/dev/apartments"
let count = "https://cu2kg3w6c1.execute-api.eu-west-1.amazonaws.com/dev/apartments/count"
let contract = "https://cu2kg3w6c1.execute-api.eu-west-1.amazonaws.com/dev/doc/contract"
#endif
let wolontariusz = "https://easy-housing-volontires.auth.eu-west-1.amazoncognito.com/oauth2/authorize?client_id=38cr6bi1ntb3cj2mgdgbp85al9&response_type=token&scope=email+openid+phone&redirect_uri=parasol://"
var reachability: Reachability? = Reachability()!
let locationManager = CLLocationManager()
let geocoder = CLGeocoder()
var myPlacemark : CLPlacemark! = nil
class var sharedInstance : DataController {
struct Singleton {
static let instance = DataController()
}
return Singleton.instance
}
var requestHandlers = [String: RequestHandler]()
let semaphore = DispatchSemaphore(value: 1)
override init() {
super.init()
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
}
func getLocation(){
// Create a CLLocationManager and assign a delegate
locationManager.requestLocation()
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
if let location = locations.first {
geocoder.reverseGeocodeLocation(location) { (placemarks, error) in
// Process Response
self.processResponse(withPlacemarks: placemarks, error: error)
}
}
}
private func processResponse(withPlacemarks placemarks: [CLPlacemark]?, error: Error?) {
// Update View
if let error = error {
DLog("Unable to Reverse Geocode Location (\(error))")
DLog("Unable to Find Address for Location")
} else {
if let placemarks = placemarks, let placemark = placemarks.first {
myPlacemark = placemark
NotificationCenter.default.post(name: NSNotification.Name("updateFromLocation"), object: nil)
DLog(placemark.compactAddress)
} else {
DLog("No Matching Addresses Found")
}
}
}
func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
}
func locationManager(
_ manager: CLLocationManager,
didChangeAuthorization status: CLAuthorizationStatus
) {
if status == .notDetermined {
locationManager.requestWhenInUseAuthorization()
}
}
func registerRequestHandler( _ requestObj:RequestHandler, for url:String){
semaphore.wait()
self.requestHandlers[url] = requestObj
semaphore.signal()
}
func getContractUrl(handleCompletion: @escaping AppCompletionHandler ) {
let requestObj = RequestHandler()
let url = self.contract
self.registerRequestHandler(requestObj, for:url)
requestObj.get("contract", url: url, allowUIAnimations: false) {
(_ rUrl: String, _ code: Int, _ message: String, _ responseObj: AnyObject?) in
if code.isSuccess {
}else{
}
handleCompletion(rUrl, code, message, responseObj as AnyObject?)
}
}
func getStats(handleCompletion: @escaping AppCompletionHandler ) {
let requestObj = RequestHandler()
let url = self.count
self.registerRequestHandler(requestObj, for:url)
requestObj.get("count", url: url, allowUIAnimations: false) {
(_ rUrl: String, _ code: Int, _ message: String, _ responseObj: AnyObject?) in
if code.isSuccess {
}else{
}
handleCompletion(rUrl, code, message, responseObj as AnyObject?)
}
}
func getAll(handleCompletion: @escaping AppCompletionHandler ) {
let requestObj = RequestHandler()
let url = self.get
self.registerRequestHandler(requestObj, for:url)
requestObj.get("all", url: url, allowUIAnimations: false) {
(_ rUrl: String, _ code: Int, _ message: String, _ responseObj: AnyObject?) in
if code.isSuccess {
}else{
}
handleCompletion(rUrl, code, message, responseObj as AnyObject?)
}
}
func sendNewChataWith(params: Dictionary<String, Any>, handleCompletion: @escaping AppDataCompletionHandler) {
let requestObj = RequestHandler()
let url = self.post
self.registerRequestHandler(requestObj, for:url)
requestObj.post("chata post", url: url, allowUIAnimations: false, parameters: params) {
(_ rUrl: String, _ code: Int, _ message: String, _ responseObj: AnyObject?) in
if code.isSuccess {
}else{
}
handleCompletion(rUrl, code, message, responseObj as? Data)
}
}
func sendChataUpdateWith(params: Dictionary<String, Any>, handleCompletion: @escaping AppDataCompletionHandler) {
let requestObj = RequestHandler()
let url = self.post
self.registerRequestHandler(requestObj, for:url)
requestObj.put("chata update", url: url, allowUIAnimations: false, parameters: params) {
(_ rUrl: String, _ code: Int, _ message: String, _ responseObj: AnyObject?) in
if code.isSuccess {
}else{
}
handleCompletion(rUrl, code, message, responseObj as? Data)
}
}
/*
new GET endpoint to list volonteers:
https://cu2kg3w6c1.execute-api.eu-west-1.amazonaws.com/dev/fundation
New Post endpoint to confirm volunteer:
https://cu2kg3w6c1.execute-api.eu-west-1.amazonaws.com/dev/fundation/volonteerconfirm
*/
}
| 34.033816 | 212 | 0.603549 |
d7329e3347867add205f9287e2b84601f34ce7c7 | 8,007 | kt | Kotlin | buildSrc/src/main/kotlin/com/almarai/gradle/dependencies/Dependencies.kt | mohammed-uzair/almarai-easy-pick | 347b7efc7e454e12fd629944a07db128de730cb3 | [
"Apache-2.0"
] | null | null | null | buildSrc/src/main/kotlin/com/almarai/gradle/dependencies/Dependencies.kt | mohammed-uzair/almarai-easy-pick | 347b7efc7e454e12fd629944a07db128de730cb3 | [
"Apache-2.0"
] | null | null | null | buildSrc/src/main/kotlin/com/almarai/gradle/dependencies/Dependencies.kt | mohammed-uzair/almarai-easy-pick | 347b7efc7e454e12fd629944a07db128de730cb3 | [
"Apache-2.0"
] | null | null | null | package com.almarai.gradle.dependencies
//region
const val Dependencies_Version_Kotlin = "1.5.20"
const val Dependencies_Kotlin =
"org.jetbrains.kotlin:kotlin-stdlib:$Dependencies_Version_Kotlin"
const val Dependencies_Kotlin_Reflect =
"org.jetbrains.kotlin:kotlin-reflect:$Dependencies_Version_Kotlin"
const val Dependencies_Plugin_Gradle = "com.android.tools.build:gradle:4.2.2"
//const val Dependencies_Plugin_Kotlin_Gradle = kotlin("gradle-plugin", "1.3.72")
public const val Dependencies_Plugin_Library = "com.android.library"
const val Dependencies_Plugin_Android = "android"
const val Dependencies_Plugin_My_Custom = "my-plugin"
const val Dependencies_Plugin_Kotlin_Android = "kotlin-android"
const val Dependencies_Plugin_Kotlin_Android_Extensions = "kotlin-android-extensions"
const val Dependencies_Plugin_Jdk_Library = "stdlib-jdk8"
//Android
const val Dependencies_Android_Kotlin_Extensions = "androidx.core:core-ktx:1.6.0"
const val Dependencies_Android_AppCompat = "androidx.appcompat:appcompat:1.1.0"
const val Dependencies_Android_Activity = "androidx.activity:activity-ktx:1.2.0-beta01"
const val Dependencies_Android_Fragment = "androidx.fragment:fragment-ktx:1.3.0-alpha02"
const val Dependencies_Android_Constraint_Layout =
"androidx.constraintlayout:constraintlayout:2.0.0-beta8"
const val Dependencies_Android_Legacy_support = "androidx.legacy:legacy-support-v4:1.0.0"
const val Dependencies_Android_Preference = "androidx.preference:preference:1.1.1"
const val Dependencies_Android_Annotations = "androidx.annotation:annotation:1.1.0"
const val Dependencies_Android_Material = "com.google.android.material:material:1.3.0-alpha02"
const val Dependencies_Android_Recycler_View = "androidx.recyclerview:recyclerview:1.2.0-alpha05"
const val Dependencies_Android_Paging = "androidx.paging:paging-runtime-ktx:2.1.2"
private const val Dependencies_Version_Lifecycle = "2.4.0-alpha01"
private const val Dependencies_Version_Lifecycle_Extensions = "2.2.0"
//const val Dependencies_Lifecycle =
const val Dependencies_Lifecycle_Runtime =
"androidx.lifecycle:lifecycle-runtime-ktx:2.4.0-alpha02"
// "androidx.lifecycle:lifecycle-runtime:$Dependencies_Version_Lifecycle"
const val Dependencies_Lifecycle_LiveData =
"androidx.lifecycle:lifecycle-livedata-ktx:$Dependencies_Version_Lifecycle"
const val Dependencies_Lifecycle_ViewModel =
"androidx.lifecycle:lifecycle-viewmodel-ktx:$Dependencies_Version_Lifecycle"
const val Dependencies_Lifecycle_Extensions =
"androidx.lifecycle:lifecycle-extensions:$Dependencies_Version_Lifecycle_Extensions"
const val Dependencies_Lifecycle_Arch_Extensions = "android.arch.lifecycle:extensions:1.1.1"
const val Dependencies_Lifecycle_Common = "android.arch.lifecycle:common-java8:1.1.1"
// jetpack navigation components
private const val Dependencies_Version_Navigation = "2.3.0"
const val Dependencies_Navigation =
"androidx.navigation:navigation-ui-ktx:$Dependencies_Version_Navigation"
const val Dependencies_Navigation_Runtime =
"androidx.navigation:navigation-runtime:$Dependencies_Version_Navigation"
const val Dependencies_Navigation_Fragment_Kotlin_Extensions =
"androidx.navigation:navigation-fragment-ktx:$Dependencies_Version_Navigation"
//Coroutines
private const val Dependencies_Version_Coroutines = "1.4.0"
const val Dependencies_Coroutines_Core =
"org.jetbrains.kotlinx:kotlinx-coroutines-core:$Dependencies_Version_Coroutines"
const val Dependencies_Coroutines_Android =
"org.jetbrains.kotlinx:kotlinx-coroutines-android:$Dependencies_Version_Coroutines"
/*SDP Library - Use to auto adjust the views for all screen sizes*, only in portrait mode
url {@link "https://github.com/intuit/sdp"}*/
private const val Dependencies_Version_Sdp = "1.0.6"
const val Dependencies_Sdp = "com.intuit.sdp:sdp-android:$Dependencies_Version_Sdp"
//Retrofit
private const val Dependencies_Version_Retrofit = "2.9.0"
const val Dependencies_Retrofit = "com.squareup.retrofit2:retrofit:$Dependencies_Version_Retrofit"
const val Dependencies_Retrofit_Moshi_Converter =
"com.squareup.retrofit2:converter-moshi:$Dependencies_Version_Retrofit"
const val Dependencies_Retrofit_Logging = "com.squareup.okhttp3:logging-interceptor:4.2.1"
const val Dependencies_PolymorphicJsonAdapterFactory = "com.squareup.moshi:moshi-adapters:1.8.0"
//DI - Hilt
private const val Dependencies_Version_Hilt = "2.37"
const val Dependencies_Hilt = "com.google.dagger:hilt-android:$Dependencies_Version_Hilt"
const val Dependencies_Hilt_Annotation_Processor =
"com.google.dagger:hilt-android-compiler:$Dependencies_Version_Hilt"
const val Dependencies_Hilt_Android_ViewModel =
"androidx.hilt:hilt-lifecycle-viewmodel:1.0.0-alpha03"
const val Dependencies_Hilt_Android_Annotation_Processor =
"androidx.hilt:hilt-compiler:1.0.0"
//Room
private const val Dependencies_Version_Room = "2.2.5"
const val Dependencies_Room = "androidx.room:room-runtime:$Dependencies_Version_Room"
const val Dependencies_Room_Compiler = "androidx.room:room-compiler:$Dependencies_Version_Room"
// optional - Kotlin Extensions and Coroutines support for Room
const val Dependencies_Room_Testing = "androidx.room:room-ktx:$Dependencies_Version_Room"
//Firebase
private const val Dependencies_Version_Firestore = "21.5.0"
private const val Dependencies_Version_Firebase = "17.4.4"
private const val Dependencies_Version_Firebase_Crashlytics = "17.1.1"
private const val Dependencies_Version_Firebase_Storage = "19.1.1"
const val Dependencies_Firestore =
"com.google.firebase:firebase-firestore:$Dependencies_Version_Firestore"
const val Dependencies_Firebase_Storage =
"com.google.firebase:firebase-storage-ktx:$Dependencies_Version_Firebase_Storage"
const val Dependencies_Firestore_Kotlin_Extensions =
"com.google.firebase:firebase-firestore-ktx:$Dependencies_Version_Firestore"
const val Dependencies_Firebase_Core =
"com.google.firebase:firebase-core:$Dependencies_Version_Firebase"
const val Dependencies_Firebase_Analytics =
"com.google.firebase:firebase-analytics-ktx:$Dependencies_Version_Firebase"
const val Dependencies_Firebase_Crashlytics =
"com.google.firebase:firebase-crashlytics:$Dependencies_Version_Firebase_Crashlytics"
//region Others Dependencies
//Animations - Lottie
private const val Dependencies_Version_Lottie = "3.4.1"
const val Dependencies_Lottie = "com.airbnb.android:lottie:$Dependencies_Version_Lottie"
//Chart - MP Chart
private const val Dependencies_Version_Mp_Chart = "v3.1.0"
const val Dependencies_Mp_Chart = "com.github.PhilJay:MPAndroidChart:$Dependencies_Version_Mp_Chart"
//Network Communication - Volley
private const val Dependencies_Version_Volley = "1.1.1"
const val Dependencies_Volley = "com.android.volley:volley:$Dependencies_Version_Volley"
//Barcode
private const val Dependencies_Version_Ml_Kit = "16.1.0"
private const val Dependencies_Version_Ml_Kit_Barcode_Scanning = "16.0.1"
//On Device Text Translation
private const val Dependencies_Version_Ml_Kit_On_Device_Text_Translation = "16.1.1"
// Barcode model
const val Dependencies_Ml_Kit_Barcode_Scanning =
"com.google.mlkit:barcode-scanning:$Dependencies_Version_Ml_Kit_Barcode_Scanning"
const val Dependencies_Ml_Kit_On_Device_Text_Translation =
"com.google.mlkit:translate:$Dependencies_Version_Ml_Kit_On_Device_Text_Translation"
// Object feature and model
const val Dependencies_Ml_Kit_Object_Detection =
"com.google.mlkit:object-detection:$Dependencies_Version_Ml_Kit"
// Custom model
const val Dependencies_Ml_Kit_Detection_Custom =
"com.google.mlkit:object-detection-custom:$Dependencies_Version_Ml_Kit"
private const val Dependencies_Version_Guava = "29.0-jre"
const val Dependencies_Guava = "com.google.guava:guava:$Dependencies_Version_Guava"
// Leak Canary
private const val Dependencies_Version_Leak_Canary = "2.0-alpha-3"
const val Dependencies_Leak_Canary =
"com.squareup.leakcanary:leakcanary-android:$Dependencies_Version_Leak_Canary"
//endregion | 48.23494 | 100 | 0.831023 |
747cd1585beb875691608ccaa295cedbf28219f7 | 2,443 | lua | Lua | luci-app-autoupdate/luasrc/model/cbi/autoupdate.lua | teasiu/lede-other-apps | f14c37b1e464d018b10f1d67ede9f14cc5ed4c82 | [
"MIT"
] | null | null | null | luci-app-autoupdate/luasrc/model/cbi/autoupdate.lua | teasiu/lede-other-apps | f14c37b1e464d018b10f1d67ede9f14cc5ed4c82 | [
"MIT"
] | null | null | null | luci-app-autoupdate/luasrc/model/cbi/autoupdate.lua | teasiu/lede-other-apps | f14c37b1e464d018b10f1d67ede9f14cc5ed4c82 | [
"MIT"
] | null | null | null | require("luci.sys")
m=Map("autoupdate",translate("AutoUpdate"),translate("AutoUpdate LUCI supports one-click firmware upgrade and scheduled upgrade"))
s=m:section(TypedSection,"login","")
s.addremove=false
s.anonymous=true
o = s:option(Flag, "enable", translate("Enable AutoUpdate"),translate("Automatically update firmware during the specified time"))
o.default = 0
o.optional = false
week=s:option(ListValue,"week",translate("xWeek Day"))
week:value(7,translate("Everyday"))
week:value(1,translate("Monday"))
week:value(2,translate("Tuesday"))
week:value(3,translate("Wednesday"))
week:value(4,translate("Thursday"))
week:value(5,translate("Friday"))
week:value(6,translate("Saturday"))
week:value(0,translate("Sunday"))
week.default=0
hour=s:option(Value,"hour",translate("xHour"))
hour.datatype = "range(0,23)"
hour.rmempty = false
pass=s:option(Value,"minute",translate("xMinute"))
pass.datatype = "range(0,59)"
pass.rmempty = false
local github_url = luci.sys.exec("grep Github= /etc/openwrt_info | cut -c8-100")
o=s:option(Value,"github",translate("Github Url"))
o.default=github_url
luci.sys.call ( "/usr/share/autoupdate/Check_Update.sh > /dev/null")
local cloud_version = luci.sys.exec("cat /tmp/cloud_version")
local current_version = luci.sys.exec("grep CURRENT_Version= /etc/openwrt_info | cut -c17-100")
local current_model = luci.sys.exec("grep DEFAULT_Device= /etc/openwrt_info | cut -c16-100")
local firmware_type = luci.sys.exec("grep Firmware_Type= /etc/openwrt_info | cut -c15-100")
button_upgrade_firmware = s:option (Button, "_button_upgrade_firmware", translate("Upgrade to Latested Version"),
translatef("Please wait patiently after clicking Do Upgrade button") .. "<br><br>当前版本: " .. current_version .. "<br>云端版本: " .. cloud_version.. "<br>固件格式: " .. firmware_type)
button_upgrade_firmware.inputtitle = translate ("Do Upgrade")
button_upgrade_firmware.write = function()
luci.sys.call ("bash /bin/AutoUpdate.sh -u > /dev/null")
end
button_upgrade_firmware_proxy = s:option (Button, "_button_upgrade_firmware_proxy", translate("Upgrade to Latested Version"),translate("Upgrade with [FastGit] Proxy"))
button_upgrade_firmware_proxy.inputtitle = translate ("Do Upgrade")
button_upgrade_firmware_proxy.write = function()
luci.sys.call ("bash /bin/AutoUpdate.sh -up > /dev/null")
end
local e=luci.http.formvalue("cbi.apply")
if e then
io.popen("/etc/init.d/autoupdate restart")
end
m.reset = false
return m | 40.04918 | 173 | 0.753582 |
3d2bc37d73e7ea50b39159caafed7e2aa42e5a2c | 5,358 | go | Go | metadata/pdetraderequest.go | DrakenTech/incognito-chain | 6e0ff12707aaa0d22ab990fe9b9aab821b4b4a81 | [
"MIT"
] | 1 | 2020-07-22T06:32:36.000Z | 2020-07-22T06:32:36.000Z | metadata/pdetraderequest.go | hoang-incognito/incognito-chain | 6e0ff12707aaa0d22ab990fe9b9aab821b4b4a81 | [
"MIT"
] | null | null | null | metadata/pdetraderequest.go | hoang-incognito/incognito-chain | 6e0ff12707aaa0d22ab990fe9b9aab821b4b4a81 | [
"MIT"
] | 1 | 2020-04-20T10:48:03.000Z | 2020-04-20T10:48:03.000Z | package metadata
import (
"bytes"
"encoding/base64"
"encoding/json"
"errors"
"reflect"
"strconv"
"github.com/incognitochain/incognito-chain/common"
"github.com/incognitochain/incognito-chain/database"
"github.com/incognitochain/incognito-chain/wallet"
)
// PDETradeRequest - privacy dex trade
type PDETradeRequest struct {
TokenIDToBuyStr string
TokenIDToSellStr string
SellAmount uint64 // must be equal to vout value
MinAcceptableAmount uint64
TradingFee uint64
TraderAddressStr string
MetadataBase
}
type PDETradeRequestAction struct {
Meta PDETradeRequest
TxReqID common.Hash
ShardID byte
}
type TokenPoolValueOperation struct {
Operator string
Value uint64
}
type PDETradeAcceptedContent struct {
TraderAddressStr string
TokenIDToBuyStr string
ReceiveAmount uint64
Token1IDStr string
Token2IDStr string
Token1PoolValueOperation TokenPoolValueOperation
Token2PoolValueOperation TokenPoolValueOperation
ShardID byte
RequestedTxID common.Hash
}
func NewPDETradeRequest(
tokenIDToBuyStr string,
tokenIDToSellStr string,
sellAmount uint64,
minAcceptableAmount uint64,
tradingFee uint64,
traderAddressStr string,
metaType int,
) (*PDETradeRequest, error) {
metadataBase := MetadataBase{
Type: metaType,
}
pdeTradeRequest := &PDETradeRequest{
TokenIDToBuyStr: tokenIDToBuyStr,
TokenIDToSellStr: tokenIDToSellStr,
SellAmount: sellAmount,
MinAcceptableAmount: minAcceptableAmount,
TradingFee: tradingFee,
TraderAddressStr: traderAddressStr,
}
pdeTradeRequest.MetadataBase = metadataBase
return pdeTradeRequest, nil
}
func (pc PDETradeRequest) ValidateTxWithBlockChain(
txr Transaction,
bcr BlockchainRetriever,
shardID byte,
db database.DatabaseInterface,
) (bool, error) {
// NOTE: verify supported tokens pair as needed
return true, nil
}
func (pc PDETradeRequest) ValidateSanityData(bcr BlockchainRetriever, txr Transaction) (bool, bool, error) {
// Note: the metadata was already verified with *transaction.TxCustomToken level so no need to verify with *transaction.Tx level again as *transaction.Tx is embedding property of *transaction.TxCustomToken
if txr.GetType() == common.TxCustomTokenPrivacyType && reflect.TypeOf(txr).String() == "*transaction.Tx" {
return true, true, nil
}
keyWallet, err := wallet.Base58CheckDeserialize(pc.TraderAddressStr)
if err != nil {
return false, false, NewMetadataTxError(IssuingRequestNewIssuingRequestFromMapEror, errors.New("TraderAddressStr incorrect"))
}
traderAddr := keyWallet.KeySet.PaymentAddress
if len(traderAddr.Pk) == 0 {
return false, false, errors.New("Wrong request info's trader address")
}
if !txr.IsCoinsBurning(bcr) {
return false, false, errors.New("Must send coin to burning address")
}
if (pc.SellAmount + pc.TradingFee) != txr.CalculateTxValue() {
return false, false, errors.New("Total of selling amount and trading fee should be equal to the tx value")
}
if !bytes.Equal(txr.GetSigPubKey()[:], traderAddr.Pk[:]) {
return false, false, errors.New("TraderAddress incorrect")
}
_, err = common.Hash{}.NewHashFromStr(pc.TokenIDToBuyStr)
if err != nil {
return false, false, NewMetadataTxError(IssuingRequestNewIssuingRequestFromMapEror, errors.New("TokenIDToBuyStr incorrect"))
}
tokenIDToSell, err := common.Hash{}.NewHashFromStr(pc.TokenIDToSellStr)
if err != nil {
return false, false, NewMetadataTxError(IssuingRequestNewIssuingRequestFromMapEror, errors.New("TokenIDToSellStr incorrect"))
}
if !bytes.Equal(txr.GetTokenID()[:], tokenIDToSell[:]) {
return false, false, errors.New("Wrong request info's token id, it should be equal to tx's token id.")
}
if txr.GetType() == common.TxNormalType && pc.TokenIDToSellStr != common.PRVCoinID.String() {
return false, false, errors.New("With tx normal privacy, the tokenIDStr should be PRV, not custom token.")
}
if txr.GetType() == common.TxCustomTokenPrivacyType && pc.TokenIDToSellStr == common.PRVCoinID.String() {
return false, false, errors.New("With tx custome token privacy, the tokenIDStr should not be PRV, but custom token.")
}
return true, true, nil
}
func (pc PDETradeRequest) ValidateMetadataByItself() bool {
return pc.Type == PDETradeRequestMeta
}
func (pc PDETradeRequest) Hash() *common.Hash {
record := pc.MetadataBase.Hash().String()
record += pc.TokenIDToBuyStr
record += pc.TokenIDToSellStr
record += pc.TraderAddressStr
record += strconv.FormatUint(pc.SellAmount, 10)
record += strconv.FormatUint(pc.MinAcceptableAmount, 10)
record += strconv.FormatUint(pc.TradingFee, 10)
// final hash
hash := common.HashH([]byte(record))
return &hash
}
func (pc *PDETradeRequest) BuildReqActions(tx Transaction, bcr BlockchainRetriever, shardID byte) ([][]string, error) {
actionContent := PDETradeRequestAction{
Meta: *pc,
TxReqID: *tx.Hash(),
ShardID: shardID,
}
actionContentBytes, err := json.Marshal(actionContent)
if err != nil {
return [][]string{}, err
}
actionContentBase64Str := base64.StdEncoding.EncodeToString(actionContentBytes)
action := []string{strconv.Itoa(PDETradeRequestMeta), actionContentBase64Str}
return [][]string{action}, nil
}
func (pc *PDETradeRequest) CalculateSize() uint64 {
return calculateSize(pc)
}
| 31.704142 | 206 | 0.747667 |
5df2afea8a24531ca9651bf282a44b40c2f30ab2 | 13,276 | h | C | INC/resource.h | gtoffoli/iperlogo | 568fd89addbd90c35cdc7b2620705faa6f488f8e | [
"Apache-2.0"
] | null | null | null | INC/resource.h | gtoffoli/iperlogo | 568fd89addbd90c35cdc7b2620705faa6f488f8e | [
"Apache-2.0"
] | null | null | null | INC/resource.h | gtoffoli/iperlogo | 568fd89addbd90c35cdc7b2620705faa6f488f8e | [
"Apache-2.0"
] | null | null | null | //{{NO_DEPENDENCIES}}
// Microsoft Developer Studio generated include file.
// Used by Iperlogo.rc
//
#define IDR_MAINFRAME 2
#define ID_PEN 3
#define IDRESET 3
#define IDALL 3
#define IDREGISTER 3
#define IDS_STRING3 3
#define IDS_VERSION 3
#define ID_BK 4
#define IDSELECTION 4
#define ID_FILL 5
#define IDCANCE 6
#define IDD_ABOUTBOX 100
#define IDD_IPERLOGO_FORM 101
#define IDD_LINE_DIALOG 102
#define IDD_BROWSER_DIALOGBAR 103
#define IDR_TURTLE 104
#define IDD_MODELESS 105
#define IDD_MODAL 106
#define IDB_BITMAP16 107
#define IDB_BITMAP16M 108
#define IDB_BITMAP256 109
#define IDD_INPUT 110
#define IDD_KEYBOARD 111
#define IDR_EDITOR 114
#define IDR_WEB 115
#define IDD_TURTLE_STATUS 116
#define IDR_TURTLE_OBJ 116
#define IDD_ACTIVE_AREA 117
#define IDD_MAIN_STATUS 118
#define IDD_WELCOME 119
#define IDD_SELPROC 120
#define IDD_TURTLE_NEW 121
#define IDB_BITMAP1 121
#define IDD_REGISTER 122
#define IDB_BITMAP2 123
#define IDD_USAGE 123
#define IDB_BITMAP3 124
#define IDD_PALETTE 124
#define IDR_ACCELERATOR1 126
#define IDD_DIALOG1 134
#define IDD_SELGLOSS 135
#define IDR_TOOLBAR1 145
#define IDD_NMUI 150
#define IDC_LIST1 1000
#define IDC_EDIT1 1001
#define IDC_EXEC 1002
#define IDC_TRACE 1003
#define IDC_PAUSE 1004
#define IDC_LINE_EDIT 1004
#define IDC_EXEC2 1004
#define IDC_HALT 1005
#define IDC_RESET 1006
#define IDC_YELD 1007
#define IDC_PEN_STATU 1007
#define IDC_WIN_STATUS 1007
#define IDC_STATUS 1008
#define IDC_PEN_CONTACT1 1008
#define IDC_PEN_STATUS 1008
#define IDC_PEN_WIDTH1 1009
#define IDC_PEN_STYLE1 1010
#define IDC_PEN_CONTACT2 1011
#define IDC_PEN_STYLE2 1012
#define IDC_AREA_YHIGH 1012
#define IDC_PEN_WIDTH2 1013
#define IDC_AREA_YLOW 1013
#define IDC_YHIGH 1014
#define IDC_NODES_STATUS 1014
#define IDC_FONT_SIZE1 1015
#define IDC_YLOW 1015
#define IDC_FONT_WEIGHT1 1016
#define IDC_XLOW 1016
#define IDC_FONT_NAME2 1017
#define IDC_AREA_XLOW 1017
#define IDC_FONT_WEIGHT2 1018
#define IDC_XHIGH 1018
#define IDC_FONT_SIZE2 1019
#define IDC_AREA_XHIGH 1019
#define IDC_PEN_FONT 1020
#define IDC_TURTLE_POS1 1021
#define IDC_TURTLE_HEADING1 1022
#define IDC_TURTLE_VISIBILITY1 1023
#define IDC_WIN_POS 1023
#define IDC_TURTLE_POSX 1024
#define IDC_TURTLE_VISIBILITY2 1025
#define IDC_TURTLE_HEADING2 1026
#define IDC_PEN_TURTLE 1027
#define IDC_COLOR_PEN1 1028
#define IDC_COLOR_FLOOD1 1029
#define IDC_COLOR_SCREEN1 1030
#define IDC_COLOR_PENG 1031
#define IDC_NODES_TOTAL 1032
#define IDC_TURTLE_HEADING3 1032
#define IDC_WIN_DIM 1032
#define IDC_NODES_USED 1033
#define IDC_WIN_POSX 1033
#define IDC_PEN_COLOR 1034
#define IDC_WIN_MODE 1034
#define IDC_TURTLE_POSY 1035
#define IDC_COLOR_PENR 1036
#define IDC_COLOR_PENB 1037
#define IDC_COLOR_FLOODG 1038
#define IDC_COLOR_FLOODR 1039
#define IDC_COLOR_FLOODB 1040
#define IDC_COLOR_SCREENG 1041
#define IDC_COLOR_SCREENR 1042
#define IDC_COLOR_SCREENB 1043
#define IDC_NODES_FREE 1044
#define IDC_WIN_POSY 1044
#define IDC_NODES_TOTAL2 1045
#define IDC_WIN_DIMX 1045
#define IDC_NODES_USED2 1046
#define IDC_WIN_DIMY 1046
#define IDC_NODES_FREE2 1047
#define IDC_VIEW_YLOW 1047
#define IDC_VIEW_YHIGH2 1048
#define IDC_OPTIONS_STATUS 1049
#define IDC_VIEW_YLOW2 1049
#define IDC_OPTIONS_CASE 1050
#define IDC_VIEW_XLOW 1050
#define IDC_OPTIONS_TRACE 1051
#define IDC_VIEW_XLOW2 1051
#define IDC_OPTIONS_BOH 1052
#define IDC_VIEW_XHIGH 1052
#define IDC_VIEW_XHIGH2 1053
#define IDC_VIEW_YHIGH 1054
#define IDC_VIEW_STATUS 1055
#define IDC_VIEW_PIXEL 1056
#define IDC_VIEW_PIXELX 1057
#define IDC_SELPROC 1057
#define IDC_VIEW_PIXELY 1058
#define IDC_TURTLE_NAME2 1059
#define IDC_VIEW_NAME 1061
#define IDC_VIEW_NAME2 1062
#define IDC_RICHEDIT1 1063
#define IDC_EDIT_CODE 1064
#define IDC_TEXT_CODE 1065
#define IDC_TEXT_STATUS 1066
#define IDC_TEXT_COMPANY 1067
#define IDC_EDIT_COMPANY 1068
#define IDC_TEXT_NAME 1069
#define IDC_EDIT_NAME 1070
#define IDC_TEXT_SERIAL 1071
#define IDC_EDIT_SERIAL 1072
#define IDC_TEXT_ACCESS 1073
#define IDC_EDIT_ACCESS 1074
#define IDC_TEXT_TIMES 1075
#define IDC_TEXT_TOTAL 1076
#define IDC_TEXT_LAST 1077
#define IDC_EDIT_TOTAL 1078
#define IDC_EDIT_LAST 1079
#define IDC_EDIT_TIMES 1081
#define IDC_SET 1083
#define IDC_EDIT2 1084
#define ID_GO 1086
#define IDC_LIST_CAT 1088
#define IDC_LIST_ENV 1089
#define IDC_STATIC_INI 1090
#define IDC_STATIC_CAT 1091
#define IDC_STATIC_ENV 1092
#define IDC_TEXT_INI 1093
#define IDC_CHECK_NOALIAS 1094
#define IDC_VIEW_MODE2 1095
#define IDC_CHECK_SUPERLOGO 1096
#define IDC_WIEW_WIN 1096
#define IDC_CHECK_IPERLOGO 1097
#define IDC_NM_IPADDRESS 1097
#define ID_ZOOM_IN 32771
#define ID_IMPORTSYMBOL 32775
#define ID_ZOOM_OUT 32780
#define ID_ZOOM_NORMAL 32781
#define ID_BITMAP_NEW 32783
#define ID_BITMAP_LOAD 32784
#define ID_BITMAP_SAVE 32785
#define ID_BITMAP_SAVEAS 32786
#define ID_BITMAP_PRINT 32788
#define ID_PRINT_SETUP 32789
#define ID_BITMAP_ACTIVEAREA 32790
#define ID_FILE_EDIT 32791
#define ID_FILE_ERASE 32792
#define ID_FILE_LOAD 32793
#define ID_EDIT_SELECTALL 32795
#define ID_EDIT_DELETE 32796
#define ID_SEARCH_FIND 32797
#define ID_SEARCH_FINDNEXT 32798
#define ID_FILE_EXIT 32799
#define ID_FILE_EXECANDEXIT 32800
#define ID_SEARCH_REPLACE 32801
#define ID_SET_FONT 32802
#define ID_HELP_EDITOR 32804
#define ID_HELP_TOPIC 32805
#define ID_TEST_SELECTION 32806
#define ID_TEST_ALL 32807
#define ID_HELP_TUTORIAL 32808
#define ID_HELP_DEMO 32809
#define ID_HELP_EXAMPLES 32810
#define ID_HELP_RELEASE 32811
#define ID_SET_PENSIZE 32812
#define ID_SET_PENCOLOR 32813
#define ID_SET_FLOODCOLOR 32814
#define ID_SET_SCREENCOLOR 32815
#define ID_WINDOWS_NEW 32816
#define ID_WINDOWS_TURTLE 32816
#define ID_TURTLESTATUS_SHOW 32817
#define ID_TURTLESTATUS_REFRESH 32818
#define ID_TURTLESTATUS_HIDE 32819
#define ID_WINDOWS_WINDOW 32821
#define ID_W_2 32822
#define ID_W_3 32823
#define ID_W_4 32824
#define ID_W_5 32825
#define ID_W_6 32826
#define ID_W_7 32827
#define ID_W_8 32828
#define ID_W_9 32829
#define ID_W_10 32830
#define ID_FILE_PRINTSETUP 32831
#define ID_OPTION_SHOWSTATE 32832
#define ID_OPTION_TRACE 32833
#define ID_EXEC 32834
#define ID_OPTION_SHOWSTATUS 32835
#define ID_HELP_SEARCH 32836
#define ID_VIEW_CENTER 32837
#define ID_HELP_TURTLE 32838
#define ID_FILE_SAVEAS 32839
#define ID_FILESAVE 32840
#define ID_WINDOWS_EDITOR 32841
#define ID_FILE_EDITPROC 32842
#define ID_FILE_CLEAR 32844
#define ID_HALT 32845
#define ID_PAUSE 32846
#define ID_OPTION_FONT 32847
#define ID_OPTION_CASE 32848
#define ID_IMPOSTA_SPESSOREPENNA 32851
#define ID_SET_PENPLUS 32853
#define ID_SET_PENMINUS 32854
#define ID_OPTION_ECO 32856
#define ID_OPTION_PROMPT 32857
#define ID_OPTION_ECOINT 32858
#define ID_MENUITEM32859 32859
#define ID_SELECT_TURTLE 32860
#define ID_REGISTER 32861
#define ID_SELECT 32862
#define ID_EDIT_SELECT 32863
#define ID_SET_PALETTE 32864
#define ID_OPTION_PROFILE 32865
#define ID_EDIT_FILL 32866
#define ID_EDIT_RIEMPI 32866
#define ID_EDIT_SELECTAREA 32867
#define ID_WINDOWS_PLAYER 32872
#define ID_WINDOWS_BROWSER 32873
#define ID_W_11 32874
#define ID_W_12 32875
#define ID_W_13 32876
#define ID_W_14 32877
#define ID_W_15 32878
#define ID_W_16 32879
#define ID_W_17 32880
#define ID_W_18 32881
#define ID_W_19 32882
#define ID_W_20 32883
#define ID_HELP_BROWSER 32884
#define ID_FILE_PRINT2 32885
#define ID_FILE_NEW2 32886
#define ID_NAVIGATE_BACK 32887
#define ID_NAVIGATE_STOP 32888
#define ID_NAVIGATE_RELOAD 32889
#define ID_FILE_GO 32890
#define ID_NAVIGATE_HOME 32891
#define ID_NAVIGATE_FORWARD 32892
#define ID_VIEW_FONTS_SMALLEST 32896
#define ID_VIEW_FONTS_SMALL 32897
#define ID_VIEW_FONTS_MEDIUM 32898
#define ID_VIEW_FONTS_LARGE 32899
#define ID_VIEW_FONTS_LARGEST 32900
#define ID_SELECT_EDITOR 32901
#define ID_SELECT_BROWSER 32902
#define ID_BUTTON32904 32904
#define ID_HELP_GLOSSARY 32905
#define ID_EDIT_TAGLIA 32906
#define ID_EDIT_COPIA 32907
#define ID_EDIT_INCOLLA 32908
#define ID_EDIT_BUTTA 32909
#define ID_IL_SYMBOL_LOAD 32911
#define ID_IL_EDGE_CREATE 32912
#define ID_IL_EDGE_INVERT 32913
// Next default values for new objects
//
#ifdef APSTUDIO_INVOKED
#ifndef APSTUDIO_READONLY_SYMBOLS
#define _APS_NEXT_RESOURCE_VALUE 153
#define _APS_NEXT_COMMAND_VALUE 32914
#define _APS_NEXT_CONTROL_VALUE 1097
#define _APS_NEXT_SYMED_VALUE 101
#endif
#endif
| 44.106312 | 53 | 0.529 |
506427d6866c4ac51acb39651455b12131fc83fd | 698 | go | Go | logger.go | htdvisser/slash | 774db45437af066688de4a62bc64042fca087dd5 | [
"Apache-2.0"
] | 2 | 2019-03-29T15:25:09.000Z | 2020-02-07T06:57:13.000Z | logger.go | htdvisser/slash | 774db45437af066688de4a62bc64042fca087dd5 | [
"Apache-2.0"
] | null | null | null | logger.go | htdvisser/slash | 774db45437af066688de4a62bc64042fca087dd5 | [
"Apache-2.0"
] | null | null | null | package slash
import (
"context"
)
// Logger is the logger interface used by the slash command Router.
type Logger interface {
Print(v ...interface{})
Printf(format string, v ...interface{})
}
type logContextKeyType struct{}
var logContextKey logContextKeyType
func newContextWithLogger(ctx context.Context, logger Logger) context.Context {
return context.WithValue(ctx, logContextKey, logger)
}
type noopLogger struct{}
func (noopLogger) Print(_ ...interface{}) {}
func (noopLogger) Printf(_ string, _ ...interface{}) {}
func loggerFromContext(ctx context.Context) Logger {
if logger, ok := ctx.Value(logContextKey).(Logger); ok {
return logger
}
return noopLogger{}
}
| 21.8125 | 79 | 0.727794 |
b592e2ae474b5f225a8e99c065ec89b95b51aa6a | 3,336 | rs | Rust | vitup/src/builders/helpers/vote_plan.rs | input-output-hk/vit-testing | 71e77212cd1e7c1833b656a925b614c67a4c9fb8 | [
"MIT"
] | 4 | 2021-03-14T00:34:22.000Z | 2021-07-19T12:48:56.000Z | vitup/src/builders/helpers/vote_plan.rs | input-output-hk/vit-testing | 71e77212cd1e7c1833b656a925b614c67a4c9fb8 | [
"MIT"
] | 25 | 2021-01-25T11:31:53.000Z | 2022-03-31T06:15:06.000Z | vitup/src/builders/helpers/vote_plan.rs | input-output-hk/vit-testing | 71e77212cd1e7c1833b656a925b614c67a4c9fb8 | [
"MIT"
] | 6 | 2021-01-22T13:41:03.000Z | 2022-03-16T14:56:14.000Z | use crate::config::VitStartParameters;
use crate::config::VoteBlockchainTime;
use chain_impl_mockchain::testing::scenario::template::VotePlanDef;
use chain_impl_mockchain::testing::scenario::template::{ProposalDefBuilder, VotePlanDefBuilder};
use chain_impl_mockchain::vote::PayloadType;
pub use jormungandr_lib::interfaces::Initial;
use jormungandr_testing_utils::testing::network::WalletAlias;
use std::iter;
pub struct VitVotePlanDefBuilder {
split_by: usize,
fund_name: Option<String>,
vote_phases: VoteBlockchainTime,
committee_wallet: Option<WalletAlias>,
options: u8,
parameters: Option<VitStartParameters>,
}
impl VitVotePlanDefBuilder {
pub fn new(vote_phases: VoteBlockchainTime) -> Self {
Self {
vote_phases,
split_by: 255,
fund_name: None,
committee_wallet: None,
parameters: None,
options: 0,
}
}
pub fn options(mut self, options: u8) -> Self {
self.options = options;
self
}
pub fn split_by(mut self, split_by: usize) -> Self {
self.split_by = split_by;
self
}
pub fn fund_name(mut self, fund_name: String) -> Self {
self.fund_name = Some(fund_name);
self
}
pub fn with_committee(mut self, committe_wallet: WalletAlias) -> Self {
self.committee_wallet = Some(committe_wallet);
self
}
pub fn with_parameters(mut self, parameters: VitStartParameters) -> Self {
self.parameters = Some(parameters);
self
}
pub fn build(self) -> Vec<VotePlanDef> {
let fund_name = self.fund_name.as_ref().expect("fund name not defined");
let parameters = self
.parameters
.as_ref()
.expect("parameters are not defined");
iter::from_fn(|| {
Some(
ProposalDefBuilder::new(
chain_impl_mockchain::testing::VoteTestGen::external_proposal_id(),
)
.options(self.options)
.action_off_chain()
.clone(),
)
})
.take(parameters.proposals as usize)
.collect::<Vec<ProposalDefBuilder>>()
.chunks(self.split_by)
.into_iter()
.enumerate()
.map(|(index, x)| {
let vote_plan_name = {
if index == 0 {
fund_name.to_string()
} else {
format!("{}_{}", fund_name, index)
}
};
let mut vote_plan_builder = VotePlanDefBuilder::new(&vote_plan_name);
vote_plan_builder.owner(
self.committee_wallet
.as_ref()
.expect("committee wallet not defined"),
);
if parameters.private {
vote_plan_builder.payload_type(PayloadType::Private);
}
vote_plan_builder.vote_phases(
self.vote_phases.vote_start,
self.vote_phases.tally_start,
self.vote_phases.tally_end,
);
x.to_vec().iter_mut().for_each(|proposal| {
vote_plan_builder.with_proposal(proposal);
});
vote_plan_builder.build()
})
.collect()
}
}
| 30.054054 | 96 | 0.565348 |
71440ba287886ee3ce18f41bbf99c45c782c5023 | 2,188 | ts | TypeScript | src/state/reducers/imgLibrary/imgLibraryReducer.ts | janisdd/basic-board-game-editor | c53f6149b6d74d66c0ce542c01418df1f96bce98 | [
"MIT"
] | null | null | null | src/state/reducers/imgLibrary/imgLibraryReducer.ts | janisdd/basic-board-game-editor | c53f6149b6d74d66c0ce542c01418df1f96bce98 | [
"MIT"
] | 4 | 2018-07-02T12:20:11.000Z | 2021-03-08T23:54:02.000Z | src/state/reducers/imgLibrary/imgLibraryReducer.ts | janisdd/basic-board-game-editor | c53f6149b6d74d66c0ce542c01418df1f96bce98 | [
"MIT"
] | null | null | null | import {Action} from "redux";
import { ImgStorage} from "../../../externalStorage/imgStorage";
import {notExhaustive} from "../_notExhausiveHelper";
import {replaceProperty, replacePropertyByGuid} from "../../../helpers/functionHelpers";
import {ImageAssetSurrogate} from "../../../types/world";
export type State = ReadonlyArray<ImageAssetSurrogate>
//the real imgs are stored in src/externalStorage/imgStorage.ts
export const initial: State = []
export interface ActionBase extends Action {
readonly type: ActionType
}
export enum ActionType {
ADD_img = 'imgLibraryReducer_ADD_img',
REMOVE_img = 'imgLibraryReducer_REMOVE_img',
SET_imgDisplayIndex = 'imgLibraryReducer_SET_imgDisplayIndex',
RESET = 'imgLibraryReducer_RESET',
}
export interface ADD_imgAction extends ActionBase {
readonly type: ActionType.ADD_img
readonly imgSurrogate: ImageAssetSurrogate
}
export interface REMOVE_imgAction extends ActionBase {
readonly type: ActionType.REMOVE_img
readonly imgSurrogateGuid: string
}
export interface SET_imgDisplayIndexAction extends ActionBase {
readonly type: ActionType.SET_imgDisplayIndex
readonly imgSurrogateGuid: string
readonly imgDisplayIndex: number
}
export interface ResetAction extends ActionBase {
readonly type: ActionType.RESET
}
export type AllActions =
ResetAction
| ADD_imgAction
| REMOVE_imgAction
| SET_imgDisplayIndexAction
export function reducer(state: State = initial, action: AllActions): State {
switch (action.type) {
case ActionType.REMOVE_img:
//remove real img & surrogate
ImgStorage.removeImg(action.imgSurrogateGuid)
return state.filter(p => p.guid !== action.imgSurrogateGuid)
case ActionType.ADD_img: {
//the img itself should be added already to the img storage
return state.concat(action.imgSurrogate)
}
case ActionType.SET_imgDisplayIndex:
return replacePropertyByGuid(state, action.imgSurrogateGuid, (el => {
return {
...el,
displayIndex: action.imgDisplayIndex
}
}))
case ActionType.RESET:
return initial
default:
notExhaustive(action)
return state
}
}
| 23.276596 | 88 | 0.738117 |
3eb0ee330194fd1c2ffd4e2fe222e92ab9825a6a | 2,110 | h | C | Simulation/src/simulation/Simulation.h | fg-netzwerksicherheit/EvolutionaryNetworkOptimizer | fdca004ba33a0d891f7d82f32999ec7d07a041f9 | [
"Apache-2.0"
] | null | null | null | Simulation/src/simulation/Simulation.h | fg-netzwerksicherheit/EvolutionaryNetworkOptimizer | fdca004ba33a0d891f7d82f32999ec7d07a041f9 | [
"Apache-2.0"
] | null | null | null | Simulation/src/simulation/Simulation.h | fg-netzwerksicherheit/EvolutionaryNetworkOptimizer | fdca004ba33a0d891f7d82f32999ec7d07a041f9 | [
"Apache-2.0"
] | null | null | null | /*
* Simulation.h
*
* Created on: Mar 22, 2017
* Author: Kiet Vo
*/
#ifndef SIMULATION_SIMULATION_H_
#define SIMULATION_SIMULATION_H_
#define SI_LOWER_RSS 1024 * 1024 * 100
#include "../Si_Type.h"
namespace simul {
/**
* \defgroup simulation Simulation
*/
/**
* \ingroup simulation
* \brief A partial wrapper of the ns-3's simulator and acts as a controller for the simulations.
*
* Only one object of this type can be valid at a time and so are its events.
*
* \see Simulation::SetUpNetworks()
*/
class Simulation {
private:
set<NodePtr> parsedNodeList;
vector<NetworkPtr> networkList;
ns3::NetDeviceContainer globalDevices;
vector<EventPtr> eventList;
void Flush();
vector<NetworkPtr> ConstructNetwork(set<EdgePtr> edgeList);
NetworkPtr ConstructP2P(EdgePtr initialEdge, set<EdgePtr>& edgeList);
NetworkPtr ConstructWifi(EdgePtr initialEdge, set<EdgePtr>& edgeList);
// valid checker group
static Simulation * configuredObjectID;
void SetValidToRunBit(bool isValid);
bool IsValidToRun();
protected:
set<EdgePtr> globalEdgeList;
public:
Simulation();
virtual ~Simulation();
void AddEdge(EdgePtr edge);
void AddEdges(SetPtr<EdgePtr> edges);
NodePtr GetNode(string ID);
ns3::NetDeviceContainer FindDevicesFromNode(NodePtr node);
void SetUpNetworks();
template<class DerivedEvent, class ...Args>
weak_ptr<Event> CreateEvent(Args&&...args);
void Run(double duration);
void Run();
static void EnableAllLogComponents();
static void EnableAllLogComponents(enum ns3::LogLevel level);
static void DisableAllLogComponents();
static void DisableAllLogComponents(enum ns3::LogLevel level);
};
/**
* \brief Create an event and associate it with this simulation object.
*
* \param args list of parameters for a specific event's constructor.
*/
template<class DerivedEvent, class ...Args>
weak_ptr<Event> Simulation::CreateEvent(Args&&...args) {
EventPtr event = shared_ptr<Event>(new DerivedEvent(forward<Args>(args)...));
eventList.push_back(event);
return weak_ptr<Event>(event);
}
} /* namespace simul */
#endif /* SIMULATION_SIMULATION_H_ */
| 23.186813 | 97 | 0.745024 |
7c4533e8fb8ef82c00729b2e037b09ed11641ef2 | 47 | lua | Lua | luastyle/tests/test_sources/table_no_check_raw.lua | burre/py-lua-style | 43f16a6d56341755f1fbafbf2b945af2630e8e44 | [
"MIT"
] | 18 | 2018-02-11T17:23:04.000Z | 2022-03-13T04:43:14.000Z | luastyle/tests/test_sources/table_no_check_raw.lua | burre/py-lua-style | 43f16a6d56341755f1fbafbf2b945af2630e8e44 | [
"MIT"
] | 3 | 2018-02-12T01:32:19.000Z | 2020-01-09T12:00:09.000Z | luastyle/tests/test_sources/table_no_check_raw.lua | burre/py-lua-style | 43f16a6d56341755f1fbafbf2b945af2630e8e44 | [
"MIT"
] | 1 | 2019-05-22T15:47:56.000Z | 2019-05-22T15:47:56.000Z | local inline_table = {'1' , '2' , '3' , '4'}
| 23.5 | 46 | 0.446809 |
78bb5396482e67c97767ce03b796e225d59074cd | 70 | sql | SQL | DB - CRUD/Find5BestPaidEmployees.sql | diMItuR10/CSharp-Databases | 42a9af739b6872eca9663b02a90bb848c7bead6c | [
"MIT"
] | null | null | null | DB - CRUD/Find5BestPaidEmployees.sql | diMItuR10/CSharp-Databases | 42a9af739b6872eca9663b02a90bb848c7bead6c | [
"MIT"
] | null | null | null | DB - CRUD/Find5BestPaidEmployees.sql | diMItuR10/CSharp-Databases | 42a9af739b6872eca9663b02a90bb848c7bead6c | [
"MIT"
] | null | null | null | SELECT TOP(5) FirstName, LastName
FROM Employees
ORDER BY Salary DESC | 23.333333 | 34 | 0.814286 |
8754099e672e8330e96d277abd7c1de56127c476 | 3,434 | swift | Swift | Marvel/Sources/Presentation/CharacterDetail/ViewModels/ComicsViewModel.swift | drogel/Marvel | d97db33dda9bbc119bd7243415cadf7570e29ad0 | [
"Unlicense"
] | null | null | null | Marvel/Sources/Presentation/CharacterDetail/ViewModels/ComicsViewModel.swift | drogel/Marvel | d97db33dda9bbc119bd7243415cadf7570e29ad0 | [
"Unlicense"
] | null | null | null | Marvel/Sources/Presentation/CharacterDetail/ViewModels/ComicsViewModel.swift | drogel/Marvel | d97db33dda9bbc119bd7243415cadf7570e29ad0 | [
"Unlicense"
] | 1 | 2022-02-11T11:40:16.000Z | 2022-02-11T11:40:16.000Z | //
// ComicsViewModel.swift
// Marvel
//
// Created by Diego Rogel on 5/2/22.
//
import Combine
import Foundation
protocol ComicsViewModelProtocol: ViewModel {
var comicCellModelsPublisher: AnyPublisher<[ComicCellModel], Never> { get }
func willDisplayComicCell(at indexPath: IndexPath) async
}
class ComicsViewModel: ComicsViewModelProtocol {
var comicCellModelsPublisher: AnyPublisher<[ComicCellModel], Never> {
$publishedComicCellModels.eraseToAnyPublisher()
}
@Published private var publishedComicCellModels: [ComicCellModel]
private let comicsFetcher: FetchComicsUseCase
private let characterID: Int
private let imageURLBuilder: ImageURLBuilder
private let pager: Pager
init(comicsFetcher: FetchComicsUseCase, characterID: Int, imageURLBuilder: ImageURLBuilder, pager: Pager) {
self.comicsFetcher = comicsFetcher
self.characterID = characterID
self.imageURLBuilder = imageURLBuilder
self.pager = pager
publishedComicCellModels = []
}
func start() async {
await loadComics(with: startingQuery)
}
func willDisplayComicCell(at indexPath: IndexPath) async {
guard shouldLoadMore(at: indexPath) else { return }
await loadMore()
}
}
private extension ComicsViewModel {
var startingQuery: FetchComicsQuery {
query(atOffset: 0)
}
func shouldLoadMore(at indexPath: IndexPath) -> Bool {
pager.isAtEndOfCurrentPageWithMoreContent(indexPath.row)
}
func query(atOffset offset: Int) -> FetchComicsQuery {
FetchComicsQuery(characterID: characterID, offset: offset)
}
func loadMore() async {
await loadComics(with: query(atOffset: publishedComicCellModels.count))
}
func loadComics(with query: FetchComicsQuery) async {
do {
let contentPage = try await comicsFetcher.fetch(query: query)
handleSuccess(with: contentPage)
} catch {
return
}
}
func handleSuccess(with contentPage: ContentPage<Comic>) {
guard let comicsCellData = mapToCells(comics: contentPage.contents) else { return }
pager.update(currentPage: contentPage)
publishedComicCellModels += comicsCellData
}
func mapToCells(comics: [Comic]) -> [ComicCellModel]? {
comics.compactMap(comicCell)
}
func comicCell(from comic: Comic) -> ComicCellModel? {
let imageURL = buildImageURL(from: comic)
let title = buildTitle(from: comic.title)
let issueNumber = buildIssueNumber(from: comic.issueNumber)
let identifier = String(comic.identifier)
return ComicCellModel(identifier: identifier, title: title, issueNumber: issueNumber, imageURL: imageURL)
}
func buildTitle(from title: String) -> String {
removeIssueNumber(from: title)
}
func buildIssueNumber(from issueNumber: Int) -> String {
let issueNumberString = String(issueNumber)
return String(format: "issue_number %@".localized, issueNumberString)
}
func buildImageURL(from comic: Comic) -> URL? {
imageURLBuilder.buildURL(from: comic.image, variant: .portraitLarge)
}
func removeIssueNumber(from comicTitle: String) -> String {
comicTitle
.replacingOccurrences(of: #"\s#\d*"#, with: "", options: .regularExpression)
.trimmingCharacters(in: .whitespaces)
}
}
| 31.796296 | 113 | 0.685498 |
cb677942e35ef3d037016d9ca134a70338aab7a1 | 9,125 | go | Go | types/sk-netlink.pb.go | YLonely/criuimages | 49cefe40898f930c1bd4e9c4f5ab6f66d1a0c69b | [
"Apache-2.0"
] | null | null | null | types/sk-netlink.pb.go | YLonely/criuimages | 49cefe40898f930c1bd4e9c4f5ab6f66d1a0c69b | [
"Apache-2.0"
] | null | null | null | types/sk-netlink.pb.go | YLonely/criuimages | 49cefe40898f930c1bd4e9c4f5ab6f66d1a0c69b | [
"Apache-2.0"
] | 1 | 2021-12-15T19:23:38.000Z | 2021-12-15T19:23:38.000Z | // Code generated by protoc-gen-go. DO NOT EDIT.
// versions:
// protoc-gen-go v1.25.0
// protoc v3.13.0
// source: sk-netlink.proto
package types
import (
proto "github.com/golang/protobuf/proto"
protoreflect "google.golang.org/protobuf/reflect/protoreflect"
protoimpl "google.golang.org/protobuf/runtime/protoimpl"
reflect "reflect"
sync "sync"
)
const (
// Verify that this generated code is sufficiently up-to-date.
_ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion)
// Verify that runtime/protoimpl is sufficiently up-to-date.
_ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20)
)
// This is a compile-time assertion that a sufficiently up-to-date version
// of the legacy proto package is being used.
const _ = proto.ProtoPackageIsVersion4
type NetlinkSkEntry struct {
state protoimpl.MessageState
sizeCache protoimpl.SizeCache
unknownFields protoimpl.UnknownFields
Id *uint32 `protobuf:"varint,1,req,name=id" json:"id,omitempty"`
Ino *uint32 `protobuf:"varint,2,req,name=ino" json:"ino,omitempty"`
Protocol *uint32 `protobuf:"varint,3,req,name=protocol" json:"protocol,omitempty"`
State *uint32 `protobuf:"varint,4,req,name=state" json:"state,omitempty"`
Flags *uint32 `protobuf:"varint,6,req,name=flags" json:"flags,omitempty"`
Portid *uint32 `protobuf:"varint,7,req,name=portid" json:"portid,omitempty"`
Groups []uint32 `protobuf:"varint,8,rep,name=groups" json:"groups,omitempty"`
DstPortid *uint32 `protobuf:"varint,9,req,name=dst_portid,json=dstPortid" json:"dst_portid,omitempty"`
DstGroup *uint32 `protobuf:"varint,10,req,name=dst_group,json=dstGroup" json:"dst_group,omitempty"`
Fown *FownEntry `protobuf:"bytes,11,req,name=fown" json:"fown,omitempty"`
Opts *SkOptsEntry `protobuf:"bytes,12,req,name=opts" json:"opts,omitempty"`
NsId *uint32 `protobuf:"varint,13,opt,name=ns_id,json=nsId" json:"ns_id,omitempty"`
}
func (x *NetlinkSkEntry) Reset() {
*x = NetlinkSkEntry{}
if protoimpl.UnsafeEnabled {
mi := &file_sk_netlink_proto_msgTypes[0]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
}
func (x *NetlinkSkEntry) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*NetlinkSkEntry) ProtoMessage() {}
func (x *NetlinkSkEntry) ProtoReflect() protoreflect.Message {
mi := &file_sk_netlink_proto_msgTypes[0]
if protoimpl.UnsafeEnabled && x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use NetlinkSkEntry.ProtoReflect.Descriptor instead.
func (*NetlinkSkEntry) Descriptor() ([]byte, []int) {
return file_sk_netlink_proto_rawDescGZIP(), []int{0}
}
func (x *NetlinkSkEntry) GetId() uint32 {
if x != nil && x.Id != nil {
return *x.Id
}
return 0
}
func (x *NetlinkSkEntry) GetIno() uint32 {
if x != nil && x.Ino != nil {
return *x.Ino
}
return 0
}
func (x *NetlinkSkEntry) GetProtocol() uint32 {
if x != nil && x.Protocol != nil {
return *x.Protocol
}
return 0
}
func (x *NetlinkSkEntry) GetState() uint32 {
if x != nil && x.State != nil {
return *x.State
}
return 0
}
func (x *NetlinkSkEntry) GetFlags() uint32 {
if x != nil && x.Flags != nil {
return *x.Flags
}
return 0
}
func (x *NetlinkSkEntry) GetPortid() uint32 {
if x != nil && x.Portid != nil {
return *x.Portid
}
return 0
}
func (x *NetlinkSkEntry) GetGroups() []uint32 {
if x != nil {
return x.Groups
}
return nil
}
func (x *NetlinkSkEntry) GetDstPortid() uint32 {
if x != nil && x.DstPortid != nil {
return *x.DstPortid
}
return 0
}
func (x *NetlinkSkEntry) GetDstGroup() uint32 {
if x != nil && x.DstGroup != nil {
return *x.DstGroup
}
return 0
}
func (x *NetlinkSkEntry) GetFown() *FownEntry {
if x != nil {
return x.Fown
}
return nil
}
func (x *NetlinkSkEntry) GetOpts() *SkOptsEntry {
if x != nil {
return x.Opts
}
return nil
}
func (x *NetlinkSkEntry) GetNsId() uint32 {
if x != nil && x.NsId != nil {
return *x.NsId
}
return 0
}
var File_sk_netlink_proto protoreflect.FileDescriptor
var file_sk_netlink_proto_rawDesc = []byte{
0x0a, 0x10, 0x73, 0x6b, 0x2d, 0x6e, 0x65, 0x74, 0x6c, 0x69, 0x6e, 0x6b, 0x2e, 0x70, 0x72, 0x6f,
0x74, 0x6f, 0x12, 0x05, 0x74, 0x79, 0x70, 0x65, 0x73, 0x1a, 0x0a, 0x6f, 0x70, 0x74, 0x73, 0x2e,
0x70, 0x72, 0x6f, 0x74, 0x6f, 0x1a, 0x0a, 0x66, 0x6f, 0x77, 0x6e, 0x2e, 0x70, 0x72, 0x6f, 0x74,
0x6f, 0x1a, 0x0d, 0x73, 0x6b, 0x2d, 0x6f, 0x70, 0x74, 0x73, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f,
0x22, 0xd5, 0x02, 0x0a, 0x10, 0x6e, 0x65, 0x74, 0x6c, 0x69, 0x6e, 0x6b, 0x5f, 0x73, 0x6b, 0x5f,
0x65, 0x6e, 0x74, 0x72, 0x79, 0x12, 0x0e, 0x0a, 0x02, 0x69, 0x64, 0x18, 0x01, 0x20, 0x02, 0x28,
0x0d, 0x52, 0x02, 0x69, 0x64, 0x12, 0x10, 0x0a, 0x03, 0x69, 0x6e, 0x6f, 0x18, 0x02, 0x20, 0x02,
0x28, 0x0d, 0x52, 0x03, 0x69, 0x6e, 0x6f, 0x12, 0x1a, 0x0a, 0x08, 0x70, 0x72, 0x6f, 0x74, 0x6f,
0x63, 0x6f, 0x6c, 0x18, 0x03, 0x20, 0x02, 0x28, 0x0d, 0x52, 0x08, 0x70, 0x72, 0x6f, 0x74, 0x6f,
0x63, 0x6f, 0x6c, 0x12, 0x14, 0x0a, 0x05, 0x73, 0x74, 0x61, 0x74, 0x65, 0x18, 0x04, 0x20, 0x02,
0x28, 0x0d, 0x52, 0x05, 0x73, 0x74, 0x61, 0x74, 0x65, 0x12, 0x1b, 0x0a, 0x05, 0x66, 0x6c, 0x61,
0x67, 0x73, 0x18, 0x06, 0x20, 0x02, 0x28, 0x0d, 0x42, 0x05, 0xd2, 0x3f, 0x02, 0x08, 0x01, 0x52,
0x05, 0x66, 0x6c, 0x61, 0x67, 0x73, 0x12, 0x16, 0x0a, 0x06, 0x70, 0x6f, 0x72, 0x74, 0x69, 0x64,
0x18, 0x07, 0x20, 0x02, 0x28, 0x0d, 0x52, 0x06, 0x70, 0x6f, 0x72, 0x74, 0x69, 0x64, 0x12, 0x16,
0x0a, 0x06, 0x67, 0x72, 0x6f, 0x75, 0x70, 0x73, 0x18, 0x08, 0x20, 0x03, 0x28, 0x0d, 0x52, 0x06,
0x67, 0x72, 0x6f, 0x75, 0x70, 0x73, 0x12, 0x1d, 0x0a, 0x0a, 0x64, 0x73, 0x74, 0x5f, 0x70, 0x6f,
0x72, 0x74, 0x69, 0x64, 0x18, 0x09, 0x20, 0x02, 0x28, 0x0d, 0x52, 0x09, 0x64, 0x73, 0x74, 0x50,
0x6f, 0x72, 0x74, 0x69, 0x64, 0x12, 0x1b, 0x0a, 0x09, 0x64, 0x73, 0x74, 0x5f, 0x67, 0x72, 0x6f,
0x75, 0x70, 0x18, 0x0a, 0x20, 0x02, 0x28, 0x0d, 0x52, 0x08, 0x64, 0x73, 0x74, 0x47, 0x72, 0x6f,
0x75, 0x70, 0x12, 0x25, 0x0a, 0x04, 0x66, 0x6f, 0x77, 0x6e, 0x18, 0x0b, 0x20, 0x02, 0x28, 0x0b,
0x32, 0x11, 0x2e, 0x74, 0x79, 0x70, 0x65, 0x73, 0x2e, 0x66, 0x6f, 0x77, 0x6e, 0x5f, 0x65, 0x6e,
0x74, 0x72, 0x79, 0x52, 0x04, 0x66, 0x6f, 0x77, 0x6e, 0x12, 0x28, 0x0a, 0x04, 0x6f, 0x70, 0x74,
0x73, 0x18, 0x0c, 0x20, 0x02, 0x28, 0x0b, 0x32, 0x14, 0x2e, 0x74, 0x79, 0x70, 0x65, 0x73, 0x2e,
0x73, 0x6b, 0x5f, 0x6f, 0x70, 0x74, 0x73, 0x5f, 0x65, 0x6e, 0x74, 0x72, 0x79, 0x52, 0x04, 0x6f,
0x70, 0x74, 0x73, 0x12, 0x13, 0x0a, 0x05, 0x6e, 0x73, 0x5f, 0x69, 0x64, 0x18, 0x0d, 0x20, 0x01,
0x28, 0x0d, 0x52, 0x04, 0x6e, 0x73, 0x49, 0x64, 0x42, 0x25, 0x5a, 0x23, 0x67, 0x69, 0x74, 0x68,
0x75, 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x59, 0x4c, 0x6f, 0x6e, 0x65, 0x6c, 0x79, 0x2f, 0x63,
0x72, 0x69, 0x75, 0x69, 0x6d, 0x61, 0x67, 0x65, 0x73, 0x2f, 0x74, 0x79, 0x70, 0x65, 0x73,
}
var (
file_sk_netlink_proto_rawDescOnce sync.Once
file_sk_netlink_proto_rawDescData = file_sk_netlink_proto_rawDesc
)
func file_sk_netlink_proto_rawDescGZIP() []byte {
file_sk_netlink_proto_rawDescOnce.Do(func() {
file_sk_netlink_proto_rawDescData = protoimpl.X.CompressGZIP(file_sk_netlink_proto_rawDescData)
})
return file_sk_netlink_proto_rawDescData
}
var file_sk_netlink_proto_msgTypes = make([]protoimpl.MessageInfo, 1)
var file_sk_netlink_proto_goTypes = []interface{}{
(*NetlinkSkEntry)(nil), // 0: types.netlink_sk_entry
(*FownEntry)(nil), // 1: types.fown_entry
(*SkOptsEntry)(nil), // 2: types.sk_opts_entry
}
var file_sk_netlink_proto_depIdxs = []int32{
1, // 0: types.netlink_sk_entry.fown:type_name -> types.fown_entry
2, // 1: types.netlink_sk_entry.opts:type_name -> types.sk_opts_entry
2, // [2:2] is the sub-list for method output_type
2, // [2:2] is the sub-list for method input_type
2, // [2:2] is the sub-list for extension type_name
2, // [2:2] is the sub-list for extension extendee
0, // [0:2] is the sub-list for field type_name
}
func init() { file_sk_netlink_proto_init() }
func file_sk_netlink_proto_init() {
if File_sk_netlink_proto != nil {
return
}
file_opts_proto_init()
file_fown_proto_init()
file_sk_opts_proto_init()
if !protoimpl.UnsafeEnabled {
file_sk_netlink_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} {
switch v := v.(*NetlinkSkEntry); i {
case 0:
return &v.state
case 1:
return &v.sizeCache
case 2:
return &v.unknownFields
default:
return nil
}
}
}
type x struct{}
out := protoimpl.TypeBuilder{
File: protoimpl.DescBuilder{
GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
RawDescriptor: file_sk_netlink_proto_rawDesc,
NumEnums: 0,
NumMessages: 1,
NumExtensions: 0,
NumServices: 0,
},
GoTypes: file_sk_netlink_proto_goTypes,
DependencyIndexes: file_sk_netlink_proto_depIdxs,
MessageInfos: file_sk_netlink_proto_msgTypes,
}.Build()
File_sk_netlink_proto = out.File
file_sk_netlink_proto_rawDesc = nil
file_sk_netlink_proto_goTypes = nil
file_sk_netlink_proto_depIdxs = nil
}
| 34.433962 | 108 | 0.693151 |
861c857b461954ab8c61f5194c4a45405941d4ae | 2,528 | rs | Rust | rust-by-example/18-error_handling/src/bin/18_5_0_iterate.rs | tetsuyainfra/playground-rust | 62adbeb32bba9a05a684b08ef4f422f36e9010c4 | [
"MIT"
] | null | null | null | rust-by-example/18-error_handling/src/bin/18_5_0_iterate.rs | tetsuyainfra/playground-rust | 62adbeb32bba9a05a684b08ef4f422f36e9010c4 | [
"MIT"
] | null | null | null | rust-by-example/18-error_handling/src/bin/18_5_0_iterate.rs | tetsuyainfra/playground-rust | 62adbeb32bba9a05a684b08ef4f422f36e9010c4 | [
"MIT"
] | null | null | null | // filter_map() : 関数を呼んでフィルタを適用した結果がNoneなら取り除く
// collect() : イテレーションを途中で終了して、Resutl<Vec<T>, E>にして返す
// (ので、Errは一つだし、イテレーションが途中で終わる)
// partition() : 実行結果を成功と失敗に分けて返す
// Iterating over Results
// An Iter::map operation might fail, for example:
fn main1() {
let strings = vec!["tofu", "93", "18"];
let numbers: Vec<_> = strings.into_iter().map(|s| s.parse::<i32>()).collect();
println!("Results1: {:?}", numbers);
}
// Let's step through strategies for handling this.
// Ignore the failed items with filter_map()
// filter_map calls a function and filters out the results that are None.
fn main2() {
let strings = vec!["tofu", "93", "18"]; // [93, 18]
let numbers: Vec<_> = strings
.into_iter()
.map(|s| s.parse::<i32>())
.filter_map(Result::ok)
.collect();
println!("Results2: {:?}", numbers);
}
// Fail the entire operation with collect()
// Result implements FromIter so that a vector of results (Vec<Result<T, E>>) can be turned into a result with a vector (Result<Vec<T>, E>). Once an Result::Err is found, the iteration will terminate.
fn main3() {
let strings = vec!["tofu", "93", "18"]; // -> Result::Errが帰ってくる
let numbers: Result<Vec<_>, _> = strings.into_iter().map(|s| s.parse::<i32>()).collect();
println!("Results3: {:?}", numbers);
}
fn main3_2() {
let strings = vec!["93", "tofu", "93", "18"]; // -> Result::Errが帰ってくる
let numbers: Result<Vec<_>, _> = strings.into_iter().map(|s| s.parse::<i32>()).collect();
println!("Results3_2: {:?}", numbers);
}
// Collect all valid values and failures with partition()
fn main4() {
let strings = vec!["tofu", "93", "18"]; // (Err, Vec<i32>)になる
let (numbers, errors): (Vec<_>, Vec<_>) = strings
.into_iter()
.map(|s| s.parse::<i32>())
.partition(Result::is_ok);
println!("Numbers4: {:?}", numbers);
println!("Errors4: {:?}", errors);
}
// When you look at the results,
// you'll note that everything is still wrapped in Result.
// A little more boilerplate is needed for this.
fn main4_2() {
let strings = vec!["tofu", "93", "18"];
let (numbers, errors): (Vec<_>, Vec<_>) = strings
.into_iter()
.map(|s| s.parse::<i32>())
.partition(Result::is_ok);
let numbers: Vec<_> = numbers.into_iter().map(Result::unwrap).collect();
let errors: Vec<_> = errors.into_iter().map(Result::unwrap_err).collect();
println!("Numbers42: {:?}", numbers);
println!("Errors42: {:?}", errors);
}
fn main() {
main1();
main2();
main3();
main3_2(); // add
main4();
main4_2();
}
| 32.831169 | 200 | 0.620253 |
7a826e707179281ceb508ca87be2cbd35bc786c5 | 325 | jbuilder | Ruby | app/views/games/game_session_questions.json.jbuilder | learric/ChalkboardClassroomAdminPortal | 6414b683b6a385c787168916c67203f79aea8a78 | [
"Apache-2.0"
] | null | null | null | app/views/games/game_session_questions.json.jbuilder | learric/ChalkboardClassroomAdminPortal | 6414b683b6a385c787168916c67203f79aea8a78 | [
"Apache-2.0"
] | null | null | null | app/views/games/game_session_questions.json.jbuilder | learric/ChalkboardClassroomAdminPortal | 6414b683b6a385c787168916c67203f79aea8a78 | [
"Apache-2.0"
] | null | null | null | # json.questions @questions
json.questions do
json.array! @questions do |questions|
answer_list = [questions.incorrect_one, questions.incorrect_two, questions.incorrect_three, questions.correct_answer]
json.category questions.category
json.firstLine questions.first_line
json.answers answer_list
end
end | 29.545455 | 121 | 0.790769 |
61251c7c84a4a6954cd43625a8678f28ca13e636 | 1,338 | css | CSS | app/component/musicFolder/style.css | AlexRogalskiy/player-template | b00a66f08736eb154fc0eeeeed83606bdd0037b6 | [
"MIT"
] | 10 | 2018-04-11T15:56:47.000Z | 2021-02-04T14:22:17.000Z | app/component/musicFolder/style.css | renhongl/aiting | ffa89fd291f03243f507d1930caafa65662c2d48 | [
"MIT"
] | 1 | 2021-04-17T19:00:33.000Z | 2021-04-17T19:00:33.000Z | app/component/musicFolder/style.css | AlexRogalskiy/player-template | b00a66f08736eb154fc0eeeeed83606bdd0037b6 | [
"MIT"
] | 1 | 2018-06-20T06:33:38.000Z | 2018-06-20T06:33:38.000Z | .musicFolder{
width: 20%;
height: 100%;
}
.smallWindow{
width: 100%;
height: 69px;
background: #fff;
cursor: pointer;
border-top: 1px solid #cebaba;
position: relative;
}
.folderList{
width: 100%;
background: #fff;
height: 430px;
}
.folderList .intro{
height: 30px;
line-height: 30px;
padding-left: 10px;
font-size: 15px;
font-weight: bold;
}
.folderList .paiHangBang{
background: #fff;
height: 30px;
line-height: 30px;
padding-left: 15px;
color: grey;
border-left: 3px solid #fff;
font-size: 13px;
}
.folderList .paiHangBang:hover{
color: #000;
cursor: pointer;
}
.folderList .selected{
background: #f1efef;
height: 30px;
line-height: 30px;
padding-left: 15px;
color: #272525;
border-left: 3px solid #e6245a;
}
.smallWindow img{
width: 40%;
height: 100%;
display: inline-block;
float: left;
}
.smallWindow span{
display: inline-block;
margin-left: 5px;
margin-top: 6px;
width: 55%;
font-size: 12px;
overflow: hidden;
height: 30px;
text-overflow: ellipsis;
white-space: nowrap;
}
.fa-expand{
display: none;
position: absolute;
z-index: 1;
color: #d0cdcd;
top: 0;
left: 0;
font-size: 65px;
margin: 3px;
opacity: 0.8;
} | 16.317073 | 35 | 0.59716 |
5fe1fbed063bc8c835b05883b075ea63eebf25f3 | 1,943 | swift | Swift | Example/Tests/ServicesTests.swift | nberthelot/ToolBox | 26f7c7570b096f45539bb347b3c4eeb5b87768fb | [
"MIT"
] | 6 | 2018-08-28T13:50:28.000Z | 2018-11-16T15:10:52.000Z | Example/Tests/ServicesTests.swift | nberthelot/ToolBox | 26f7c7570b096f45539bb347b3c4eeb5b87768fb | [
"MIT"
] | null | null | null | Example/Tests/ServicesTests.swift | nberthelot/ToolBox | 26f7c7570b096f45539bb347b3c4eeb5b87768fb | [
"MIT"
] | 3 | 2018-09-07T08:27:31.000Z | 2018-12-07T11:23:15.000Z | //
// ServicesTests.swift
// ToolBox_Tests
//
// Created by Berthelot Nicolas on 05/09/2018.
// Copyright © 2018 CocoaPods. All rights reserved.
//
import XCTest
import ToolBox
protocol ServiceTestProtocol: TBServiceProtocol {
var value : Int { get }
}
protocol ServiceUserProtocol: TBServiceProtocol {
var name: String { get }
}
protocol ServiceSocialProtocol: TBServiceProtocol {
var userName: String { get }
}
// SERVICES
final class ServiceUser: TBBaseService, ServiceUserProtocol {
var name: String { return "nicolas" }
}
final class ServiceUser2: TBBaseService, ServiceUserProtocol {
var name: String = ""
required init() {
super.init()
self.name = "tom"
}
}
final class ServiceSocial: TBBaseService, ServiceSocialProtocol {
var userName: String {
return retrieveService(type: ServiceUserProtocol.self).name
}
}
final class Service1: TBBaseService, ServiceTestProtocol {
var value: Int { return 1 }
}
final class Service2: TBBaseService, ServiceTestProtocol {
var value: Int { return 2 }
}
class ServicesTests: XCTestCase {
func testService() {
TBServices.add(Service1.self, for: ServiceTestProtocol.self)
XCTAssert(TBServices.retrieve(type: ServiceTestProtocol.self).value == 1)
TBServices.add(Service2.self, for: ServiceTestProtocol.self)
XCTAssert(TBServices.retrieve(type: ServiceTestProtocol.self).value == 2)
TBServices.add(ServiceUser2.self, for: ServiceUserProtocol.self)
TBServices.add(ServiceUser.self, for: ServiceUserProtocol.self, dependencies: nil)
TBServices.add(ServiceSocial.self,
for: ServiceSocialProtocol.self,
dependencies: [(protocol: ServiceUserProtocol.self, serviceType: ServiceUser2.self)])
XCTAssert(TBServices.retrieve(type: ServiceSocialProtocol.self).userName == "tom")
XCTAssert(TBServices.retrieve(type: ServiceUserProtocol.self).name == "nicolas")
}
}
| 26.616438 | 104 | 0.726197 |
0b8ab81b9a756ab917e11852711a0c75ca7514c2 | 6,676 | py | Python | src/explore.py | dngo13/enpm808x_inspection_robot | 41f598d97d6526d4e85d1b738cd0bf1bce781b08 | [
"MIT"
] | null | null | null | src/explore.py | dngo13/enpm808x_inspection_robot | 41f598d97d6526d4e85d1b738cd0bf1bce781b08 | [
"MIT"
] | null | null | null | src/explore.py | dngo13/enpm808x_inspection_robot | 41f598d97d6526d4e85d1b738cd0bf1bce781b08 | [
"MIT"
] | 2 | 2021-12-05T23:39:56.000Z | 2021-12-06T17:54:54.000Z | #!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""*******************************************************************************
* MIT License
* Copyright (c) Charu Sharma 2021
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* * Neither the name of the copyright holder nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
********************************************************************************"""
"""
* @file explore.py
* @author Charu Sharma
* @date 12/14/2021
* @version 1.0
*
* @brief Main source file
*
* @section DESCRIPTION
*
* file to let the bot explore to the target locations and sending confirmation flag when reached
*
"""
#!/usr/bin/env python
#importing Libraries
import rospy
import math
import tf
from geometry_msgs.msg import Twist, Point
from sensor_msgs.msg import LaserScan
from tf.transformations import euler_from_quaternion
from enpm808x_inspection_robot.msg import location, flag_array, flag
rospy.init_node("move_robot")
pub = rospy.Publisher("cmd_vel", Twist, queue_size=1)
# create another publisher for location
# rospy.init_node('location_node')
# loc_pub = rospy.Publisher('location', array, queue_size=1)
loc_pub = rospy.Publisher('/flag', flag_array, queue_size=1)
rate = rospy.Rate(1)
velocity_msg = Twist()
rate = rospy.Rate(4)
tf_listener = tf.TransformListener()
parent_frame = 'odom'
child_frame = 'base_footprint'
k_h_gain = 1
k_v_gain = 1
distance_to_goal = 0.0
# locations = location()
flagged = flag()
flagged_arrays = flag_array()
flagged.check = "false"
try:
tf_listener.waitForTransform(parent_frame, child_frame, rospy.Time(), rospy.Duration(1.0))
except (tf.Exception, tf.ConnectivityException, tf.LookupException):
rospy.loginfo("Cannot find transform between {p} and {c}".format(p=parent_frame, c=child_frame))
rospy.signal_shutdown("tf Exception")
def get_odom_data():
# Get the current pose of the robot from the /odom topic
try:
(trans, rot) = tf_listener.lookupTransform(parent_frame, child_frame, rospy.Time(0))
rotation = euler_from_quaternion(rot)
except (tf.Exception, tf.ConnectivityException, tf.LookupException):
rospy.loginfo("TF Exception")
return
return Point(*trans), rotation[2]
def compute_distance(x1, y1, x2, y2):
return math.sqrt((x2 - x1)**2 + (y2 - y1)**2)
def go_to_goal(goal_x, goal_y):
global velocity_msg
(position, rotation) = get_odom_data()
last_rotation = 0
# locations.loc_x = position.x
# locations.loc_y = position.y
distance_to_goal = compute_distance(position.x, position.y, goal_x, goal_y)
while distance_to_goal > 0.05:
(position, rotation) = get_odom_data()
x_start = position.x
y_start = position.y
rospy.loginfo("x = {0}, y = {1}".format(x_start, y_start))
angle_to_goal = math.atan2(goal_y - y_start, goal_x - x_start)
if angle_to_goal < -math.pi / 4 or angle_to_goal > math.pi / 4:
if 0 > goal_y > y_start:
angle_to_goal = -2 * math.pi + angle_to_goal
elif 0 <= goal_y < y_start:
angle_to_goal = 2 * math.pi + angle_to_goal
if last_rotation > math.pi - 0.1 and rotation <= 0:
rotation = 2 * math.pi + rotation
elif last_rotation < -math.pi + 0.1 and rotation > 0:
rotation = -2 * math.pi + rotation
velocity_msg.angular.z = k_v_gain * angle_to_goal - rotation
distance_to_goal = compute_distance(position.x, position.y, goal_x, goal_y)
velocity_msg.linear.x = min(k_h_gain * distance_to_goal, 0.2)
if velocity_msg.angular.z > 0:
velocity_msg.angular.z = min(velocity_msg.angular.z, 0.6)
else:
velocity_msg.angular.z = max(velocity_msg.angular.z, -0.6)
last_rotation = rotation
sub = rospy.Subscriber('scan', LaserScan, sensor_callback)
pub = rospy.Publisher("cmd_vel", Twist, queue_size=1)
pub.publish(velocity_msg)
rate.sleep()
velocity_msg.linear.x = 0.0
velocity_msg.angular.z = 0.0
pub.publish(velocity_msg)
rate.sleep()
def sensor_callback(msg):
front = msg.ranges[0]
left = msg.ranges[90]
right = msg.ranges[270]
def read_scan():
rospy.Subscriber("scan", LaserScan, sensor_callback)
rospy.spin()
# while not rospy.is_shutdown():
# loc_pub.publish(arrays.loc)
if __name__ == "__main__":
action = ""
go_to_goal(-3, -1)
flagged.check = 'true'
print("The robot has reached the Chiller")
print("Commencing the pressure Detection")
# print("locations.loc_x = ", locations.loc_x)
# print("locations.loc_y = ", locations.loc_y)
flagged.check = 'false'
go_to_goal(0, 3)
print("The robot has reached the Boiler")
print("Commencing the pressure Detection")
# locations.loc_x = 0.0
# locations.loc_y = 3.0
# send message for boiler
go_to_goal(1, 3)
print("The robot has reached the Air Handling Units")
print("Commencing the pressure Detection")
# send message to AHU
# arrays.id.insert(0,flag)
while not rospy.is_shutdown():
loc_pub.publish(flagged_arrays.id)
flagged_arrays.id.insert(0,flagged)
rate.sleep()
exit() | 34.061224 | 100 | 0.673457 |
478a056c1f8c7829647ccd43563ceec08f230018 | 840 | html | HTML | manuscript/page-1806/body.html | marvindanig/orlando-furioso | b29dcc3441ca6836d3e3d2b58bb4dce21acf8f2e | [
"BlueOak-1.0.0",
"CC-BY-4.0",
"Unlicense"
] | null | null | null | manuscript/page-1806/body.html | marvindanig/orlando-furioso | b29dcc3441ca6836d3e3d2b58bb4dce21acf8f2e | [
"BlueOak-1.0.0",
"CC-BY-4.0",
"Unlicense"
] | null | null | null | manuscript/page-1806/body.html | marvindanig/orlando-furioso | b29dcc3441ca6836d3e3d2b58bb4dce21acf8f2e | [
"BlueOak-1.0.0",
"CC-BY-4.0",
"Unlicense"
] | null | null | null | <div class="leaf flex"><div class="inner justify"><pre class="no-indent ">Belly, and breast, and naked flesh expose;
And so diseased and troubled is his brain,
That none, and least himself, the champion knows,
Nebuchadnezzar whilom to such pain
God in his vengeance doomed, as story shows;
Sent, for seven years, of savage fury full,
To feed on grass and hay, like slavering bull.</pre><h5>LXVI</h5><pre>"But yet, because the Christian paladine
Has sinned against his heavenly Maker less,
He only for three months, by will divine,
Is doomed to cleanse himself of his excess.
Nor yet with other scope did your design
Of wending hither the Redeemer bless,
But that through us the mode you should explore,
Orlando's missing senses to restore.</pre><h5>LXVII</h5><pre class=" ">" `Tis true to journey further ye will need,
</pre></div> </div> | 56 | 117 | 0.758333 |
fd8b59eee822d4bae61da38402bc927464eafd32 | 3,400 | c | C | mud/battle/shield.c | shentino/simud | 644b7d4f56bf8d4695442b8efcfd56e0a561fe21 | [
"Apache-2.0"
] | 3 | 2015-07-18T00:19:51.000Z | 2016-02-20T17:25:37.000Z | mud/battle/shield.c | shentino/simud | 644b7d4f56bf8d4695442b8efcfd56e0a561fe21 | [
"Apache-2.0"
] | 2 | 2021-03-04T19:24:03.000Z | 2021-03-08T10:17:34.000Z | mud/battle/shield.c | shentino/simud | 644b7d4f56bf8d4695442b8efcfd56e0a561fe21 | [
"Apache-2.0"
] | 2 | 2015-12-22T06:16:53.000Z | 2016-11-18T16:32:50.000Z | #include <battle.h>
#include <item.h>
#include <object.h>
#include <saveload.h>
#include <condition.h>
int base_ac; // general armour class (applies to all types)
mapping ac_mod; // armour class. ex (["edged":3, "blunt":-5])
int cursed;
// Object editor information.
string shield_info() {
return "base_ac\nac_mod\n";
}
ICON( '[', 7, 1 )
/****************************** Queries ****************************/
/** Return the armour class of this object. If called with a string
* parameter, then one particular ac is returned (ie, query_ac("fire")
* returns the armour's fire ac).
*
* If called without any parameters and there are any modifiers defined, the
* object's entire ac mapping is returned. Otherwise, the base ac is returned.
*/
varargs mixed query_ac(string param) {
mapping temp = copy(ac_mod);
string str;
if (param)
return ac_mod[param]+base_ac;
if (sizeof(ac_mod)) {
foreach (str: ac_mod)
temp[str] = ac_mod[str] + base_ac;
return temp;
} else {
return base_ac;
}
}
int query_base_ac() { return base_ac; }
varargs mixed query_ac_mod(string param) {
if (param)
return ac_mod[param];
return ac_mod;
}
string query_armour_type() { return "shield"; }
int query_cursed() { return cursed; }
/******************************* Sets *******************************/
set_cursed(int x) {
if (x >= 0)
cursed = x;
}
void set_base_ac(int x) { base_ac = x; }
varargs void set_ac_mod(mixed one, int two) {
if (mappingp(one))
ac_mod = copy(one);
else if (stringp(one))
ac_mod[one] = two;
}
/** Laziness method for declaring base ac and ac modifiers in one shot. This
* function takes several different possible sets of parameters and does
* various wierd and unholy things to armour class depending on the sort of
* input you give it.
*
* set_ac( "fire",3 )
* Would set the fire ac of the object to 3. This means that if the object
* already has a base ac of 2, it would set ac_mod["fire"] to 1, or if the
* base were 5, it would set the modifier to -2. Note that changing the base
* ac afterward will affect the specific ac's set in the modifier mapping.
*
* set_ac( (["fire":3,"ice":2]) )
* Would set the ac modifier mapping to the mapping given. No change is
* made to base ac.
*
* set_ac( 3 )
* This sets the base ac to 3. No changes are maded the the mod mapping.
*
* set_ac( (["fire":3]), 5 )
* This is perhaps the most efficient way to set armour class. It sets the
* base ac to 5 and then sets the fire ac to 3 (by setting the modifier to
* -2).
*/
varargs void set_ac(mixed one, int two) {
string str;
if (!one)
return;
if (intp(one)) {
base_ac = one;
} else if (mappingp(one)) {
if (two) {
base_ac = two;
foreach(str: one)
ac_mod[str] = base_ac - one[str];
} else {
ac_mod = copy(one);
}
} else if (stringp(one) && two) {
ac_mod[one] = two - base_ac;
}
}
/****************************** Other *******************************/
create() {
::create();
ac_mod = ([]);
base_ac = 0;
/* OBJEDIT { */
set_gettable( 1 );
set_droppable( 1 );
set_holdable( 1 );
set_type( "shield" );
/* } OBJEDIT */
}
/// \return True, indicating that this object is armour.
int query_armour() { return 1; }
/// \return True, indicating that this object is a shield.
int query_shield() { return 1; }
| 26.153846 | 78 | 0.61 |
b33a04bca6e6604ce7056e32268b1bdde2e7c7ac | 1,678 | swift | Swift | MemeMe/MemeController.swift | BoostCamp/MemeMe_Henry | 0a5891d273f6c71b0fb3b6b9b448d627dd7a89a7 | [
"MIT"
] | null | null | null | MemeMe/MemeController.swift | BoostCamp/MemeMe_Henry | 0a5891d273f6c71b0fb3b6b9b448d627dd7a89a7 | [
"MIT"
] | null | null | null | MemeMe/MemeController.swift | BoostCamp/MemeMe_Henry | 0a5891d273f6c71b0fb3b6b9b448d627dd7a89a7 | [
"MIT"
] | null | null | null | //
// MemeController.swift
// MemeMe
//
// Created by JUNYEONG.YOO on 1/25/17.
// Copyright © 2017 Boostcamp. All rights reserved.
//
import Foundation
import UIKit
struct MemeController {
private static var appDelegate: AppDelegate {
return UIApplication.shared.delegate as! AppDelegate
}
// Returns number of memed images
static func count() -> Int {
return appDelegate.memes.count
}
// Add a new memed image to the array
static func insert(_ meme: Meme) {
appDelegate.memes.append(meme)
RealmController.insert(meme)
}
// Get a memed image from the array
static func select(at index: Int) -> Meme {
return appDelegate.memes[index]
}
// Update a memed image
static func update(at index: Int, _ updatedMeme: Meme) {
let oldMeme = appDelegate.memes[index]
appDelegate.memes[index] = updatedMeme
RealmController.update(old: oldMeme, updated: updatedMeme)
}
// Delete a memed image
static func delete(at index: Int) {
let deletedMeme: Meme = appDelegate.memes.remove(at: index)
// Delete images from document directory
let documentDirectory = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as String
let documentURL = URL(fileURLWithPath: documentDirectory)
let originalImageURL = documentURL.appendingPathComponent(deletedMeme.originalImageName)
let memedImageURL = documentURL.appendingPathComponent(deletedMeme.memedImageName)
do {
try FileManager.default.removeItem(at: originalImageURL)
try FileManager.default.removeItem(at: memedImageURL)
} catch {
print("Could not delete image from document directory")
}
RealmController.delete(deletedMeme)
}
}
| 27.064516 | 117 | 0.747318 |
4dac4dfd2aea8b0fb8825fb0e5f804d959967d51 | 6,834 | html | HTML | howdoiplay/src/components/tips/htmlTips/timbersaw.html | saitejam12/HowDoIPlay-REDO | 2d0707fea4f403bf7de4fe914f9ffab1985a309f | [
"MIT"
] | null | null | null | howdoiplay/src/components/tips/htmlTips/timbersaw.html | saitejam12/HowDoIPlay-REDO | 2d0707fea4f403bf7de4fe914f9ffab1985a309f | [
"MIT"
] | null | null | null | howdoiplay/src/components/tips/htmlTips/timbersaw.html | saitejam12/HowDoIPlay-REDO | 2d0707fea4f403bf7de4fe914f9ffab1985a309f | [
"MIT"
] | null | null | null | <div class="hero hero-timbersaw" data-patch="684">
<div class="herotitle">
<span class="portrait"
><span class="portrait-frame"
><span class="portrait-frame-inner"
><img
class="portrait-img"
width="256"
height="144"
src="data:image/jpeg;base64,/9j/4AAQSkZJRgABAQEAAQABAAD/2wBDAAICAgICAgICAgICAgICAwQDAgIDBAUEBAQEBAUGBQUFBQUFBgYHBwgHBwYJCQoKCQkMDAwMDAwMDAwMDAwMDAz/2wBDAQMDAwUEBQkGBgkNCwkLDQ8ODg4ODw8MDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAz/wAARCAAbADADAREAAhEBAxEB/8QAGgABAAIDAQAAAAAAAAAAAAAACAYHAgUJA//EADIQAAAFAwMBBQUJAAAAAAAAAAECAwQFBgcRABIhMQgTFCJRI0FCUmEVJENTYnGBkaH/xAAcAQACAgIDAAAAAAAAAAAAAAAEBgMFAgcAAQj/xAApEQACAgEDBAAFBQAAAAAAAAABAgADBAURIQYSEzEUIiQyQTNhYnGB/9oADAMBAAIRAxEAPwDknboqDBwo6fsViCbgD45/jStq6XWJtVHvp26ihy1wmUnEOalq6QawUM77hynhwUhec/NzjReEGNC9x5ErtSsQZTGsfKYm7Mxbu0bcszOREnBtE3iTkj5YgG73YYo+4301aLWzepT5Hc3sRB01ehka5jqqYOqI0Wj9RM5GjtMPZGAu03xZ5xrG3Gc87SOvgep7XLq6UZUjc+uWbSFdrzahEDRzc+5FUBIADgogHXdqPxB0KvxI/IanDJ7gXVYQc8yC5tBMQYT1MHBSoKXV/CN+YQPl1SZOMwU49h+RvzGHEyhkEE/dN12f4eoK8nlZlRJuhDR5gImBiZLv6e4NRdQamumY52+8+phpuM2dZ/ERrXBdUZB0jMou2bKAq6JbA6jplqUExcFx0HjWpemsvUV1RLO4tS52ZT+I4ZtVfibuADAcGGKzd2SVJXScbWcm5m4t63ErOMciUyQnwOMZ+uNem8CtFftB4iP8V5bB3S33LyhGM6xc95DxqCcqCbxqqkUDlTE3BDgI+g9dFnJVCeRC17Wbj1Nb2pn9v7flawsegKsjUyJHiHglfZJgIBgwkz+kNLmqN5disjNVaOQw5lVWAZspyu4Vk4BMrSfVCMnzlDhZJQSYEQ9QA2qxE84+b8SuywcN90k2sYozb2wFnTbtNssKgqeIVEAMO0MiURHoOtZdY5e2cAQSI4dOBUr3MP19LikuHKsIBq7FqtGFM3drGHymMXOQEQ/fTL03gNh0G2wb78iQ9Q5lWTYEpP8AcplFg5hysJOJWHxscfInLngxR9dOteZ2MDFVE5/edKbYtLJ33o1SeroyUZX0E3AjtsQ4JC67rGw2AxuHIaNsFeQwbfYxgxKK7KzzsYNu0XTc0zq6FcOyOfCSTbbEGVHOES7dof1qDOUVwZ6CLNoieyvamoquqqA+x5NnHyDFwRyiitjartAvlEREPTSqNapou8Le2hep6O7Y/lPoQa088eNqImfDu3KGHHHdnMX19B1ZZdNbWKSoP+RdqdhvzK4b+0XUOp5zmMIic3IiOjF4kstGBKUafkMlKOOmgLf1hOGTW1BCjVjDJS+7XWfYybdp2l5pIBaIvtTEKde2G8pT/cj9Qz8Oj9Xc+BTvDAPqpKeyi6cozCB0XC6RwW4MQwgP+a1Lr4+srMbdt8E7z//Z"
data-src="./assets/media/heroes/large/shredder.jpg"
alt="Timbersaw"/></span></span></span
><span class="name">Timbersaw</span>
</div>
<div class="tips">
<h1>Tips</h1>
<ul>
<li>Whirling Death can be activated while you're mid-Timber Chain.</li>
<li>
Be generous when targeting Timber Chain. It's okay to sacrifice ~50
range to ensure you aren't airballing chains.
</li>
<li>
The Chain gives a very small slice of vision as it travels and gives 400
ground vision for a split second once it reaches max distance. You can
use this to quickly scout inside the Rosh pit if you don't want to spend
Chakram for vision.
</li>
<li>
If you Eul's yourself after casting Timber Chain, you'll fly up and the
Cyclone will get canceled once the Chain hits a tree. Use this to dodge
enemies who may try to cancel your Chain cast with stuns.
</li>
<li>
Using Blink Dagger immediately after casting Timber Chain allows you to
change your angle of approach to a targeted tree. You can use this to
get Chain damage on an enemy and still quickly return to safety. You can
also toss a Chain, blink into a creep wave and Whirling Death, and
promptly fly out.
</li>
<li>
You can cast Chakram before Timber Chain connects or during the travel
time to cut down on the Chakram cast animation. Timber will start the
animation for Chakram as soon as he's in range of wherever you targeted
it. Shift+queueing Chakram after casting Chain is the guaranteed fastest
way to do this.
</li>
<li>
Your goal in lane is to find the minimum amount of creep aggro you need
to draw to keep Reactive Armor working at its cap.
</li>
<li>
Go into the jungle and tank a few neutrals to build up Reactive Armor
stacks before a gank/dive.
</li>
<li>
An enemy can receive the burst damage from the Chakram once when it
flies out and once when it's coming back. So if it looks like an enemy
is about to escape the AoE of the Chakram, just return it while they're
still in it. The extra passthrough damage will be more useful than a few
more milliseconds of slow.
</li>
<li>The lower an enemy's HP, the greater the Chakram slow will be.</li>
<li>Timbersaw is disarmed when a Chakram is out.</li>
<li>
Learn the trees on the map. There are many unique juke paths that only
Timber can take advantage of thanks to his skill set.
</li>
<li>
When escaping late game, try carving out paths with Chakram before
Timber Chaining. Timber Chaining into a deforested area could buy you a
few seconds of fog.
</li>
<li>
If you're building a Bloodstone and you already have Arcane Boots, don't
buy another Arcane Orb for the Soul Booster, just disassemble your
Arcanes.
</li>
</ul>
<h1>Counters</h1>
<ul>
<li>
Don't stand next to trees when laning against or escaping from Timber.
The distance you're saving by hugging the treeline won't matter when he
purely damages your ass.
</li>
<li>
Timbersaw hates being silenced, especially if he has a Chakram out
because that means he literally can't do anything.
</li>
<li>Timbersaw cannot Timber Chain when rooted.</li>
<li>
Breaking Timbersaw will stop him from gaining new Reactive Armor stacks.
</li>
<li>
Spirit Vessel can help mitigate the HP regen Timber gains from Reactive
Armor, but existing stacks will remain.
</li>
<li>
Chakram has a fairly slow travel time, so it's usually worth sacrificing
some positioning if it means you can sidestep the saw when he's chasing
you.
</li>
<li>
You can disable Timbersaw mid-Chain to stop him from moving. If your
team has a shortage of stuns, save them for when you see his Chain come
out. That way Chain goes on cooldown, but he won't go anywhere.
</li>
<li>
Be mindful when right click harassing him in lane. Often times, Timber's
prefer the Reactive stacks. Ideally you want to harass him with magic
damage exclusively, if possible.
</li>
<li>
If you're a strength hero, Whirling Death's primary attribute loss
debuff will make you extremely vulnerable in lane.
</li>
</ul>
<div class="video-wrapper">
<iframe
width="672"
height="420"
src="//www.youtube.com/embed/eAKxEni6b9k"
frameborder="0"
allowfullscreen
></iframe>
</div>
</div>
</div>
| 52.569231 | 1,669 | 0.712321 |
0ed29bfeba1cc0d6896fe3877e8653c26d1867f8 | 18,138 | c | C | src/linux/arch/arm/mm/init.c | wangyan98/linux-lib | f98bbaec0d696b948935939b2d613cd15cd6105f | [
"MIT"
] | 21 | 2021-01-22T06:47:38.000Z | 2022-03-20T14:24:29.000Z | src/linux/arch/arm/mm/init.c | wangyan98/linux-lib | f98bbaec0d696b948935939b2d613cd15cd6105f | [
"MIT"
] | 1 | 2021-08-07T07:14:45.000Z | 2021-08-07T08:24:23.000Z | src/linux/arch/arm/mm/init.c | wangyan98/linux-lib | f98bbaec0d696b948935939b2d613cd15cd6105f | [
"MIT"
] | 12 | 2021-01-22T14:59:28.000Z | 2022-02-22T04:03:31.000Z | /*
* linux/arch/arm/mm/init.c
*
* Copyright (C) 1995-2005 Russell King
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*/
#include <linux/kernel.h>
#include <linux/errno.h>
#include <linux/swap.h>
#include <linux/init.h>
#include <linux/bootmem.h>
#include <linux/mman.h>
#include <linux/nodemask.h>
#include <linux/initrd.h>
#include <linux/sort.h>
#include <linux/highmem.h>
#include <linux/gfp.h>
#include <asm/mach-types.h>
#include <asm/sections.h>
#include <asm/setup.h>
#include <asm/sizes.h>
#include <asm/tlb.h>
#include <asm/fixmap.h>
#include <asm/mach/arch.h>
#include <asm/mach/map.h>
#include "mm.h"
static unsigned long phys_initrd_start __initdata = 0;
static unsigned long phys_initrd_size __initdata = 0;
static int __init early_initrd(char *p)
{
unsigned long start, size;
char *endp;
start = memparse(p, &endp);
if (*endp == ',') {
size = memparse(endp + 1, NULL);
phys_initrd_start = start;
phys_initrd_size = size;
}
return 0;
}
early_param("initrd", early_initrd);
static int __init parse_tag_initrd(const struct tag *tag)
{
printk(KERN_WARNING "ATAG_INITRD is deprecated; "
"please update your bootloader.\n");
phys_initrd_start = __virt_to_phys(tag->u.initrd.start);
phys_initrd_size = tag->u.initrd.size;
return 0;
}
__tagtable(ATAG_INITRD, parse_tag_initrd);
static int __init parse_tag_initrd2(const struct tag *tag)
{
phys_initrd_start = tag->u.initrd.start;
phys_initrd_size = tag->u.initrd.size;
return 0;
}
__tagtable(ATAG_INITRD2, parse_tag_initrd2);
/*
* This keeps memory configuration data used by a couple memory
* initialization functions, as well as show_mem() for the skipping
* of holes in the memory map. It is populated by arm_add_memory().
*/
struct meminfo meminfo;
void show_mem(void)
{
int free = 0, total = 0, reserved = 0;
int shared = 0, cached = 0, slab = 0, node, i;
struct meminfo * mi = &meminfo;
printk("Mem-info:\n");
show_free_areas();
for_each_online_node(node) {
for_each_nodebank (i,mi,node) {
struct membank *bank = &mi->bank[i];
unsigned int pfn1, pfn2;
struct page *page, *end;
pfn1 = bank_pfn_start(bank);
pfn2 = bank_pfn_end(bank);
page = pfn_to_page(pfn1);
end = pfn_to_page(pfn2 - 1) + 1;
do {
total++;
if (PageReserved(page))
reserved++;
else if (PageSwapCache(page))
cached++;
else if (PageSlab(page))
slab++;
else if (!page_count(page))
free++;
else
shared += page_count(page) - 1;
page++;
} while (page < end);
}
}
printk("%d pages of RAM\n", total);
printk("%d free pages\n", free);
printk("%d reserved pages\n", reserved);
printk("%d slab pages\n", slab);
printk("%d pages shared\n", shared);
printk("%d pages swap cached\n", cached);
}
static void __init find_node_limits(int node, struct meminfo *mi,
unsigned long *min, unsigned long *max_low, unsigned long *max_high)
{
int i;
*min = -1UL;
*max_low = *max_high = 0;
for_each_nodebank(i, mi, node) {
struct membank *bank = &mi->bank[i];
unsigned long start, end;
start = bank_pfn_start(bank);
end = bank_pfn_end(bank);
if (*min > start)
*min = start;
if (*max_high < end)
*max_high = end;
if (bank->highmem)
continue;
if (*max_low < end)
*max_low = end;
}
}
/*
* FIXME: We really want to avoid allocating the bootmap bitmap
* over the top of the initrd. Hopefully, this is located towards
* the start of a bank, so if we allocate the bootmap bitmap at
* the end, we won't clash.
*/
static unsigned int __init
find_bootmap_pfn(int node, struct meminfo *mi, unsigned int bootmap_pages)
{
unsigned int start_pfn, i, bootmap_pfn;
start_pfn = PAGE_ALIGN(__pa(_end)) >> PAGE_SHIFT;
bootmap_pfn = 0;
for_each_nodebank(i, mi, node) {
struct membank *bank = &mi->bank[i];
unsigned int start, end;
start = bank_pfn_start(bank);
end = bank_pfn_end(bank);
if (end < start_pfn)
continue;
if (start < start_pfn)
start = start_pfn;
if (end <= start)
continue;
if (end - start >= bootmap_pages) {
bootmap_pfn = start;
break;
}
}
if (bootmap_pfn == 0)
BUG();
return bootmap_pfn;
}
static int __init check_initrd(struct meminfo *mi)
{
int initrd_node = -2;
#ifdef CONFIG_BLK_DEV_INITRD
unsigned long end = phys_initrd_start + phys_initrd_size;
/*
* Make sure that the initrd is within a valid area of
* memory.
*/
if (phys_initrd_size) {
unsigned int i;
initrd_node = -1;
for (i = 0; i < mi->nr_banks; i++) {
struct membank *bank = &mi->bank[i];
if (bank_phys_start(bank) <= phys_initrd_start &&
end <= bank_phys_end(bank))
initrd_node = bank->node;
}
}
if (initrd_node == -1) {
printk(KERN_ERR "INITRD: 0x%08lx+0x%08lx extends beyond "
"physical memory - disabling initrd\n",
phys_initrd_start, phys_initrd_size);
phys_initrd_start = phys_initrd_size = 0;
}
#endif
return initrd_node;
}
static inline void map_memory_bank(struct membank *bank)
{
#ifdef CONFIG_MMU
struct map_desc map;
map.pfn = bank_pfn_start(bank);
map.virtual = __phys_to_virt(bank_phys_start(bank));
map.length = bank_phys_size(bank);
map.type = MT_MEMORY;
create_mapping(&map);
#endif
}
static void __init bootmem_init_node(int node, struct meminfo *mi,
unsigned long start_pfn, unsigned long end_pfn)
{
unsigned long boot_pfn;
unsigned int boot_pages;
pg_data_t *pgdat;
int i;
/*
* Map the memory banks for this node.
*/
for_each_nodebank(i, mi, node) {
struct membank *bank = &mi->bank[i];
if (!bank->highmem)
map_memory_bank(bank);
}
/*
* Allocate the bootmem bitmap page.
*/
boot_pages = bootmem_bootmap_pages(end_pfn - start_pfn);
boot_pfn = find_bootmap_pfn(node, mi, boot_pages);
/*
* Initialise the bootmem allocator for this node, handing the
* memory banks over to bootmem.
*/
node_set_online(node);
pgdat = NODE_DATA(node);
init_bootmem_node(pgdat, boot_pfn, start_pfn, end_pfn);
for_each_nodebank(i, mi, node) {
struct membank *bank = &mi->bank[i];
if (!bank->highmem)
free_bootmem_node(pgdat, bank_phys_start(bank), bank_phys_size(bank));
}
/*
* Reserve the bootmem bitmap for this node.
*/
reserve_bootmem_node(pgdat, boot_pfn << PAGE_SHIFT,
boot_pages << PAGE_SHIFT, BOOTMEM_DEFAULT);
}
static void __init bootmem_reserve_initrd(int node)
{
#ifdef CONFIG_BLK_DEV_INITRD
pg_data_t *pgdat = NODE_DATA(node);
int res;
res = reserve_bootmem_node(pgdat, phys_initrd_start,
phys_initrd_size, BOOTMEM_EXCLUSIVE);
if (res == 0) {
initrd_start = __phys_to_virt(phys_initrd_start);
initrd_end = initrd_start + phys_initrd_size;
} else {
printk(KERN_ERR
"INITRD: 0x%08lx+0x%08lx overlaps in-use "
"memory region - disabling initrd\n",
phys_initrd_start, phys_initrd_size);
}
#endif
}
static void __init bootmem_free_node(int node, struct meminfo *mi)
{
unsigned long zone_size[MAX_NR_ZONES], zhole_size[MAX_NR_ZONES];
unsigned long min, max_low, max_high;
int i;
find_node_limits(node, mi, &min, &max_low, &max_high);
/*
* initialise the zones within this node.
*/
memset(zone_size, 0, sizeof(zone_size));
/*
* The size of this node has already been determined. If we need
* to do anything fancy with the allocation of this memory to the
* zones, now is the time to do it.
*/
zone_size[0] = max_low - min;
#ifdef CONFIG_HIGHMEM
zone_size[ZONE_HIGHMEM] = max_high - max_low;
#endif
/*
* For each bank in this node, calculate the size of the holes.
* holes = node_size - sum(bank_sizes_in_node)
*/
memcpy(zhole_size, zone_size, sizeof(zhole_size));
for_each_nodebank(i, mi, node) {
int idx = 0;
#ifdef CONFIG_HIGHMEM
if (mi->bank[i].highmem)
idx = ZONE_HIGHMEM;
#endif
zhole_size[idx] -= bank_pfn_size(&mi->bank[i]);
}
/*
* Adjust the sizes according to any special requirements for
* this machine type.
*/
arch_adjust_zones(node, zone_size, zhole_size);
free_area_init_node(node, zone_size, min, zhole_size);
}
#ifndef CONFIG_SPARSEMEM
int pfn_valid(unsigned long pfn)
{
struct meminfo *mi = &meminfo;
unsigned int left = 0, right = mi->nr_banks;
do {
unsigned int mid = (right + left) / 2;
struct membank *bank = &mi->bank[mid];
if (pfn < bank_pfn_start(bank))
right = mid;
else if (pfn >= bank_pfn_end(bank))
left = mid + 1;
else
return 1;
} while (left < right);
return 0;
}
EXPORT_SYMBOL(pfn_valid);
static void arm_memory_present(struct meminfo *mi, int node)
{
}
#else
static void arm_memory_present(struct meminfo *mi, int node)
{
int i;
for_each_nodebank(i, mi, node) {
struct membank *bank = &mi->bank[i];
memory_present(node, bank_pfn_start(bank), bank_pfn_end(bank));
}
}
#endif
static int __init meminfo_cmp(const void *_a, const void *_b)
{
const struct membank *a = _a, *b = _b;
long cmp = bank_pfn_start(a) - bank_pfn_start(b);
return cmp < 0 ? -1 : cmp > 0 ? 1 : 0;
}
void __init bootmem_init(void)
{
struct meminfo *mi = &meminfo;
unsigned long min, max_low, max_high;
int node, initrd_node;
sort(&mi->bank, mi->nr_banks, sizeof(mi->bank[0]), meminfo_cmp, NULL);
/*
* Locate which node contains the ramdisk image, if any.
*/
initrd_node = check_initrd(mi);
max_low = max_high = 0;
/*
* Run through each node initialising the bootmem allocator.
*/
for_each_node(node) {
unsigned long node_low, node_high;
find_node_limits(node, mi, &min, &node_low, &node_high);
if (node_low > max_low)
max_low = node_low;
if (node_high > max_high)
max_high = node_high;
/*
* If there is no memory in this node, ignore it.
* (We can't have nodes which have no lowmem)
*/
if (node_low == 0)
continue;
bootmem_init_node(node, mi, min, node_low);
/*
* Reserve any special node zero regions.
*/
if (node == 0)
reserve_node_zero(NODE_DATA(node));
/*
* If the initrd is in this node, reserve its memory.
*/
if (node == initrd_node)
bootmem_reserve_initrd(node);
/*
* Sparsemem tries to allocate bootmem in memory_present(),
* so must be done after the fixed reservations
*/
arm_memory_present(mi, node);
}
/*
* sparse_init() needs the bootmem allocator up and running.
*/
sparse_init();
/*
* Now free memory in each node - free_area_init_node needs
* the sparse mem_map arrays initialized by sparse_init()
* for memmap_init_zone(), otherwise all PFNs are invalid.
*/
for_each_node(node)
bootmem_free_node(node, mi);
high_memory = __va((max_low << PAGE_SHIFT) - 1) + 1;
/*
* This doesn't seem to be used by the Linux memory manager any
* more, but is used by ll_rw_block. If we can get rid of it, we
* also get rid of some of the stuff above as well.
*
* Note: max_low_pfn and max_pfn reflect the number of _pages_ in
* the system, not the maximum PFN.
*/
max_low_pfn = max_low - PHYS_PFN_OFFSET;
max_pfn = max_high - PHYS_PFN_OFFSET;
}
static inline int free_area(unsigned long pfn, unsigned long end, char *s)
{
unsigned int pages = 0, size = (end - pfn) << (PAGE_SHIFT - 10);
for (; pfn < end; pfn++) {
struct page *page = pfn_to_page(pfn);
ClearPageReserved(page);
init_page_count(page);
__free_page(page);
pages++;
}
if (size && s)
printk(KERN_INFO "Freeing %s memory: %dK\n", s, size);
return pages;
}
static inline void
free_memmap(int node, unsigned long start_pfn, unsigned long end_pfn)
{
struct page *start_pg, *end_pg;
unsigned long pg, pgend;
/*
* Convert start_pfn/end_pfn to a struct page pointer.
*/
start_pg = pfn_to_page(start_pfn - 1) + 1;
end_pg = pfn_to_page(end_pfn);
/*
* Convert to physical addresses, and
* round start upwards and end downwards.
*/
pg = PAGE_ALIGN(__pa(start_pg));
pgend = __pa(end_pg) & PAGE_MASK;
/*
* If there are free pages between these,
* free the section of the memmap array.
*/
if (pg < pgend)
free_bootmem_node(NODE_DATA(node), pg, pgend - pg);
}
/*
* The mem_map array can get very big. Free the unused area of the memory map.
*/
static void __init free_unused_memmap_node(int node, struct meminfo *mi)
{
unsigned long bank_start, prev_bank_end = 0;
unsigned int i;
/*
* [FIXME] This relies on each bank being in address order. This
* may not be the case, especially if the user has provided the
* information on the command line.
*/
for_each_nodebank(i, mi, node) {
struct membank *bank = &mi->bank[i];
bank_start = bank_pfn_start(bank);
if (bank_start < prev_bank_end) {
printk(KERN_ERR "MEM: unordered memory banks. "
"Not freeing memmap.\n");
break;
}
/*
* If we had a previous bank, and there is a space
* between the current bank and the previous, free it.
*/
if (prev_bank_end && prev_bank_end != bank_start)
free_memmap(node, prev_bank_end, bank_start);
prev_bank_end = bank_pfn_end(bank);
}
}
/*
* mem_init() marks the free areas in the mem_map and tells us how much
* memory is free. This is done after various parts of the system have
* claimed their memory after the kernel image.
*/
void __init mem_init(void)
{
unsigned long reserved_pages, free_pages;
int i, node;
#ifndef CONFIG_DISCONTIGMEM
max_mapnr = pfn_to_page(max_pfn + PHYS_PFN_OFFSET) - mem_map;
#endif
/* this will put all unused low memory onto the freelists */
for_each_online_node(node) {
pg_data_t *pgdat = NODE_DATA(node);
free_unused_memmap_node(node, &meminfo);
if (pgdat->node_spanned_pages != 0)
totalram_pages += free_all_bootmem_node(pgdat);
}
#ifdef CONFIG_SA1111
/* now that our DMA memory is actually so designated, we can free it */
totalram_pages += free_area(PHYS_PFN_OFFSET,
__phys_to_pfn(__pa(swapper_pg_dir)), NULL);
#endif
#ifdef CONFIG_HIGHMEM
/* set highmem page free */
for_each_online_node(node) {
for_each_nodebank (i, &meminfo, node) {
unsigned long start = bank_pfn_start(&meminfo.bank[i]);
unsigned long end = bank_pfn_end(&meminfo.bank[i]);
if (start >= max_low_pfn + PHYS_PFN_OFFSET)
totalhigh_pages += free_area(start, end, NULL);
}
}
totalram_pages += totalhigh_pages;
#endif
reserved_pages = free_pages = 0;
for_each_online_node(node) {
for_each_nodebank(i, &meminfo, node) {
struct membank *bank = &meminfo.bank[i];
unsigned int pfn1, pfn2;
struct page *page, *end;
pfn1 = bank_pfn_start(bank);
pfn2 = bank_pfn_end(bank);
page = pfn_to_page(pfn1);
end = pfn_to_page(pfn2 - 1) + 1;
do {
if (PageReserved(page))
reserved_pages++;
else if (!page_count(page))
free_pages++;
page++;
} while (page < end);
}
}
/*
* Since our memory may not be contiguous, calculate the
* real number of pages we have in this system
*/
printk(KERN_INFO "Memory:");
num_physpages = 0;
for (i = 0; i < meminfo.nr_banks; i++) {
num_physpages += bank_pfn_size(&meminfo.bank[i]);
printk(" %ldMB", bank_phys_size(&meminfo.bank[i]) >> 20);
}
printk(" = %luMB total\n", num_physpages >> (20 - PAGE_SHIFT));
printk(KERN_NOTICE "Memory: %luk/%luk available, %luk reserved, %luK highmem\n",
nr_free_pages() << (PAGE_SHIFT-10),
free_pages << (PAGE_SHIFT-10),
reserved_pages << (PAGE_SHIFT-10),
totalhigh_pages << (PAGE_SHIFT-10));
#define MLK(b, t) b, t, ((t) - (b)) >> 10
#define MLM(b, t) b, t, ((t) - (b)) >> 20
#define MLK_ROUNDUP(b, t) b, t, DIV_ROUND_UP(((t) - (b)), SZ_1K)
printk(KERN_NOTICE "Virtual kernel memory layout:\n"
" vector : 0x%08lx - 0x%08lx (%4ld kB)\n"
" fixmap : 0x%08lx - 0x%08lx (%4ld kB)\n"
#ifdef CONFIG_MMU
" DMA : 0x%08lx - 0x%08lx (%4ld MB)\n"
#endif
" vmalloc : 0x%08lx - 0x%08lx (%4ld MB)\n"
" lowmem : 0x%08lx - 0x%08lx (%4ld MB)\n"
#ifdef CONFIG_HIGHMEM
" pkmap : 0x%08lx - 0x%08lx (%4ld MB)\n"
#endif
" modules : 0x%08lx - 0x%08lx (%4ld MB)\n"
" .init : 0x%p" " - 0x%p" " (%4d kB)\n"
" .text : 0x%p" " - 0x%p" " (%4d kB)\n"
" .data : 0x%p" " - 0x%p" " (%4d kB)\n",
MLK(UL(CONFIG_VECTORS_BASE), UL(CONFIG_VECTORS_BASE) +
(PAGE_SIZE)),
MLK(FIXADDR_START, FIXADDR_TOP),
#ifdef CONFIG_MMU
MLM(CONSISTENT_BASE, CONSISTENT_END),
#endif
MLM(VMALLOC_START, VMALLOC_END),
MLM(PAGE_OFFSET, (unsigned long)high_memory),
#ifdef CONFIG_HIGHMEM
MLM(PKMAP_BASE, (PKMAP_BASE) + (LAST_PKMAP) *
(PAGE_SIZE)),
#endif
MLM(MODULES_VADDR, MODULES_END),
MLK_ROUNDUP(__init_begin, __init_end),
MLK_ROUNDUP(_text, _etext),
MLK_ROUNDUP(_data, _edata));
#undef MLK
#undef MLM
#undef MLK_ROUNDUP
/*
* Check boundaries twice: Some fundamental inconsistencies can
* be detected at build time already.
*/
#ifdef CONFIG_MMU
BUILD_BUG_ON(VMALLOC_END > CONSISTENT_BASE);
BUG_ON(VMALLOC_END > CONSISTENT_BASE);
BUILD_BUG_ON(TASK_SIZE > MODULES_VADDR);
BUG_ON(TASK_SIZE > MODULES_VADDR);
#endif
#ifdef CONFIG_HIGHMEM
BUILD_BUG_ON(PKMAP_BASE + LAST_PKMAP * PAGE_SIZE > PAGE_OFFSET);
BUG_ON(PKMAP_BASE + LAST_PKMAP * PAGE_SIZE > PAGE_OFFSET);
#endif
if (PAGE_SIZE >= 16384 && num_physpages <= 128) {
extern int sysctl_overcommit_memory;
/*
* On a machine this small we won't get
* anywhere without overcommit, so turn
* it on by default.
*/
sysctl_overcommit_memory = OVERCOMMIT_ALWAYS;
}
}
void free_initmem(void)
{
#ifdef CONFIG_HAVE_TCM
extern char *__tcm_start, *__tcm_end;
totalram_pages += free_area(__phys_to_pfn(__pa(__tcm_start)),
__phys_to_pfn(__pa(__tcm_end)),
"TCM link");
#endif
if (!machine_is_integrator() && !machine_is_cintegrator())
totalram_pages += free_area(__phys_to_pfn(__pa(__init_begin)),
__phys_to_pfn(__pa(__init_end)),
"init");
}
#ifdef CONFIG_BLK_DEV_INITRD
static int keep_initrd;
void free_initrd_mem(unsigned long start, unsigned long end)
{
if (!keep_initrd)
totalram_pages += free_area(__phys_to_pfn(__pa(start)),
__phys_to_pfn(__pa(end)),
"initrd");
}
static int __init keepinitrd_setup(char *__unused)
{
keep_initrd = 1;
return 1;
}
__setup("keepinitrd", keepinitrd_setup);
#endif
| 24.248663 | 81 | 0.683813 |
93ed520296402f283ef5d70ea32352b78e0b54f5 | 4,557 | rs | Rust | src/io.rs | cloudcrate/rust_mysql_common | bfd9d27ed3b3170de6d5bd71f64f7d41a5910abe | [
"Apache-2.0",
"MIT"
] | null | null | null | src/io.rs | cloudcrate/rust_mysql_common | bfd9d27ed3b3170de6d5bd71f64f7d41a5910abe | [
"Apache-2.0",
"MIT"
] | null | null | null | src/io.rs | cloudcrate/rust_mysql_common | bfd9d27ed3b3170de6d5bd71f64f7d41a5910abe | [
"Apache-2.0",
"MIT"
] | null | null | null | // Copyright (c) 2017 Anatoly Ikorsky
//
// Licensed under the Apache License, Version 2.0
// <LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0> or the MIT
// license <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. All files in the project carrying such notice may not be copied,
// modified, or distributed except according to those terms.
use crate::value::Value;
use byteorder::{LittleEndian as LE, ReadBytesExt, WriteBytesExt};
use std::io;
pub trait ReadMysqlExt: ReadBytesExt {
/// Reads MySql's length-encoded integer.
fn read_lenenc_int(&mut self) -> io::Result<u64> {
match self.read_u8()? {
x if x < 0xfc => Ok(x as u64),
0xfc => self.read_uint::<LE>(2),
0xfd => self.read_uint::<LE>(3),
0xfe => self.read_uint::<LE>(8),
0xff => Err(io::Error::new(
io::ErrorKind::Other,
"Invalid length-encoded integer value",
)),
_ => unreachable!(),
}
}
}
pub trait WriteMysqlExt: WriteBytesExt {
/// Writes MySql's length-encoded integer.
fn write_lenenc_int(&mut self, x: u64) -> io::Result<u64> {
if x < 251 {
self.write_u8(x as u8)?;
Ok(1)
} else if x < 65_536 {
self.write_u8(0xFC)?;
self.write_uint::<LE>(x, 2)?;
Ok(3)
} else if x < 16_777_216 {
self.write_u8(0xFD)?;
self.write_uint::<LE>(x, 3)?;
Ok(4)
} else {
self.write_u8(0xFE)?;
self.write_uint::<LE>(x, 8)?;
Ok(9)
}
}
/// Writes MySql's length-encoded string.
fn write_lenenc_str(&mut self, bytes: &[u8]) -> io::Result<u64> {
let written = self.write_lenenc_int(bytes.len() as u64)?;
self.write_all(bytes)?;
Ok(written + bytes.len() as u64)
}
/// Writes MySql's value in binary value format.
fn write_bin_value(&mut self, value: &Value) -> io::Result<u64> {
match *value {
Value::NULL => Ok(0),
Value::Bytes(ref x) => self.write_lenenc_str(&x[..]),
Value::Int(x) => {
self.write_i64::<LE>(x)?;
Ok(8)
}
Value::UInt(x) => {
self.write_u64::<LE>(x)?;
Ok(8)
}
Value::Float(x) => {
self.write_f64::<LE>(x)?;
Ok(8)
}
Value::Date(0u16, 0u8, 0u8, 0u8, 0u8, 0u8, 0u32) => {
self.write_u8(0u8)?;
Ok(1)
}
Value::Date(y, m, d, 0u8, 0u8, 0u8, 0u32) => {
self.write_u8(4u8)?;
self.write_u16::<LE>(y)?;
self.write_u8(m)?;
self.write_u8(d)?;
Ok(5)
}
Value::Date(y, m, d, h, i, s, 0u32) => {
self.write_u8(7u8)?;
self.write_u16::<LE>(y)?;
self.write_u8(m)?;
self.write_u8(d)?;
self.write_u8(h)?;
self.write_u8(i)?;
self.write_u8(s)?;
Ok(8)
}
Value::Date(y, m, d, h, i, s, u) => {
self.write_u8(11u8)?;
self.write_u16::<LE>(y)?;
self.write_u8(m)?;
self.write_u8(d)?;
self.write_u8(h)?;
self.write_u8(i)?;
self.write_u8(s)?;
self.write_u32::<LE>(u)?;
Ok(12)
}
Value::Time(_, 0u32, 0u8, 0u8, 0u8, 0u32) => {
self.write_u8(0u8)?;
Ok(1)
}
Value::Time(neg, d, h, m, s, 0u32) => {
self.write_u8(8u8)?;
self.write_u8(if neg { 1u8 } else { 0u8 })?;
self.write_u32::<LE>(d)?;
self.write_u8(h)?;
self.write_u8(m)?;
self.write_u8(s)?;
Ok(9)
}
Value::Time(neg, d, h, m, s, u) => {
self.write_u8(12u8)?;
self.write_u8(if neg { 1u8 } else { 0u8 })?;
self.write_u32::<LE>(d)?;
self.write_u8(h)?;
self.write_u8(m)?;
self.write_u8(s)?;
self.write_u32::<LE>(u)?;
Ok(13)
}
}
}
}
impl<T> ReadMysqlExt for T where T: ReadBytesExt {}
impl<T> WriteMysqlExt for T where T: WriteBytesExt {}
| 33.507353 | 76 | 0.450296 |
fb0518785fa55237acc639a348464e837aa449df | 2,705 | c | C | src/codec_utils/F1AP/Flows-Mapped-To-DRB-Item.c | tanmayg14/o-du-l2 | 60d14257f866aab93574d57cceecad4859670f82 | [
"Apache-2.0",
"CC-BY-4.0"
] | 9 | 2020-10-13T06:37:10.000Z | 2022-03-05T17:57:52.000Z | src/codec_utils/F1AP/Flows-Mapped-To-DRB-Item.c | wineslab/colosseum-scope-e2 | f0457b39e03cadb2a93523bc73ccc2d056f2188b | [
"Apache-2.0",
"CC-BY-4.0"
] | null | null | null | src/codec_utils/F1AP/Flows-Mapped-To-DRB-Item.c | wineslab/colosseum-scope-e2 | f0457b39e03cadb2a93523bc73ccc2d056f2188b | [
"Apache-2.0",
"CC-BY-4.0"
] | 7 | 2020-09-29T09:56:01.000Z | 2022-03-24T10:50:32.000Z | /*
* Generated by asn1c-0.9.29 (http://lionet.info/asn1c)
* From ASN.1 module "F1AP-IEs"
* found in "F1.asn1"
* `asn1c -D ./out -fcompound-names -fno-include-deps -findirect-choice -gen-PER -no-gen-example`
*/
#include "Flows-Mapped-To-DRB-Item.h"
#include "ProtocolExtensionContainer.h"
asn_TYPE_member_t asn_MBR_Flows_Mapped_To_DRB_Item_1[] = {
{ ATF_NOFLAGS, 0, offsetof(struct Flows_Mapped_To_DRB_Item, qoSFlowIdentifier),
(ASN_TAG_CLASS_CONTEXT | (0 << 2)),
-1, /* IMPLICIT tag at current level */
&asn_DEF_QoSFlowIdentifier,
0,
{ 0, 0, 0 },
0, 0, /* No default value */
"qoSFlowIdentifier"
},
{ ATF_NOFLAGS, 0, offsetof(struct Flows_Mapped_To_DRB_Item, qoSFlowLevelQoSParameters),
(ASN_TAG_CLASS_CONTEXT | (1 << 2)),
-1, /* IMPLICIT tag at current level */
&asn_DEF_QoSFlowLevelQoSParameters,
0,
{ 0, 0, 0 },
0, 0, /* No default value */
"qoSFlowLevelQoSParameters"
},
{ ATF_POINTER, 1, offsetof(struct Flows_Mapped_To_DRB_Item, iE_Extensions),
(ASN_TAG_CLASS_CONTEXT | (2 << 2)),
-1, /* IMPLICIT tag at current level */
&asn_DEF_ProtocolExtensionContainer_4624P50,
0,
{ 0, 0, 0 },
0, 0, /* No default value */
"iE-Extensions"
},
};
static const int asn_MAP_Flows_Mapped_To_DRB_Item_oms_1[] = { 2 };
static const ber_tlv_tag_t asn_DEF_Flows_Mapped_To_DRB_Item_tags_1[] = {
(ASN_TAG_CLASS_UNIVERSAL | (16 << 2))
};
static const asn_TYPE_tag2member_t asn_MAP_Flows_Mapped_To_DRB_Item_tag2el_1[] = {
{ (ASN_TAG_CLASS_CONTEXT | (0 << 2)), 0, 0, 0 }, /* qoSFlowIdentifier */
{ (ASN_TAG_CLASS_CONTEXT | (1 << 2)), 1, 0, 0 }, /* qoSFlowLevelQoSParameters */
{ (ASN_TAG_CLASS_CONTEXT | (2 << 2)), 2, 0, 0 } /* iE-Extensions */
};
asn_SEQUENCE_specifics_t asn_SPC_Flows_Mapped_To_DRB_Item_specs_1 = {
sizeof(struct Flows_Mapped_To_DRB_Item),
offsetof(struct Flows_Mapped_To_DRB_Item, _asn_ctx),
asn_MAP_Flows_Mapped_To_DRB_Item_tag2el_1,
3, /* Count of tags in the map */
asn_MAP_Flows_Mapped_To_DRB_Item_oms_1, /* Optional members */
1, 0, /* Root/Additions */
-1, /* First extension addition */
};
asn_TYPE_descriptor_t asn_DEF_Flows_Mapped_To_DRB_Item = {
"Flows-Mapped-To-DRB-Item",
"Flows-Mapped-To-DRB-Item",
&asn_OP_SEQUENCE,
asn_DEF_Flows_Mapped_To_DRB_Item_tags_1,
sizeof(asn_DEF_Flows_Mapped_To_DRB_Item_tags_1)
/sizeof(asn_DEF_Flows_Mapped_To_DRB_Item_tags_1[0]), /* 1 */
asn_DEF_Flows_Mapped_To_DRB_Item_tags_1, /* Same as above */
sizeof(asn_DEF_Flows_Mapped_To_DRB_Item_tags_1)
/sizeof(asn_DEF_Flows_Mapped_To_DRB_Item_tags_1[0]), /* 1 */
{ 0, 0, SEQUENCE_constraint },
asn_MBR_Flows_Mapped_To_DRB_Item_1,
3, /* Elements count */
&asn_SPC_Flows_Mapped_To_DRB_Item_specs_1 /* Additional specs */
};
| 36.554054 | 98 | 0.72902 |
b1df3e19c459a39b4bccbc7bcf194776c3d6f984 | 1,135 | c | C | oven/UI.c | Mr-Bossman/oven | 3b1829fb05c69d219692128413d0311c6d33f9ab | [
"MIT"
] | null | null | null | oven/UI.c | Mr-Bossman/oven | 3b1829fb05c69d219692128413d0311c6d33f9ab | [
"MIT"
] | null | null | null | oven/UI.c | Mr-Bossman/oven | 3b1829fb05c69d219692128413d0311c6d33f9ab | [
"MIT"
] | null | null | null | #include "UI.h"
#include "common.h"
#include "menus.h"
#include "temp_control.h"
static bool C = true;
static uint16_t getTemp(){
if(C)
return menu2("Enter Temp *C:",475,100);
else
return ((menu2("Enter Temp *F:",885,215)-32)*5)/9;
}
static int16_t getTempRise(){
if(C)
return menu3("Enter *C/S:",500,-500,2);
else
return ((menu3("Enter *F/S:",900,-900,2))*5)/9;
}
static uint16_t getTime(){
return menu2("Enter Time S:",240,10);
}
void Options(struct tempC * data){
for(uint8_t i = 0; i < 6;i++){
uint8_t option = menu1("Select an option:\n>Set target temp...\n Set rise time...\n Set temp...\n C or F...\n Start...",5);
switch (option){
case 0:{
data[i].stableTemp = false;
data[i].temp = getTemp();
data[i].rise = getTempRise();
continue;
}
case 1:{
data[i].stableTemp = false;
data[i].times = getTime();
data[i].rise = getTempRise();
continue;
}
case 2:{
data[i].stableTemp = true;
data[i].times = getTime();
data[i].temp = getTemp();
continue;
}
case 3:{
C ^= true;
continue;
}
case 4:{
break;
}
}
break;
}
} | 19.912281 | 125 | 0.577974 |
f84891c261269988fb824d2bc61e0261222963e8 | 2,308 | swift | Swift | Sources/PixelKit/PIX/PIXs/Effects/Single/Kaleidoscope/KaleidoscopePIX.swift | hexagons/PixelKit | 1a75b92fdad606be2493a8e8ceff21d4e318daec | [
"MIT"
] | 554 | 2019-05-10T23:26:39.000Z | 2020-10-07T17:57:11.000Z | Sources/PixelKit/PIX/PIXs/Effects/Single/Kaleidoscope/KaleidoscopePIX.swift | anton-hexagons/Pixels | 9b8dd63e88adde20a242f4a6fa8d78f6f1a4ce21 | [
"MIT"
] | 15 | 2019-05-23T12:23:22.000Z | 2020-09-26T00:03:27.000Z | Sources/PixelKit/PIX/PIXs/Effects/Single/Kaleidoscope/KaleidoscopePIX.swift | hexagons/PixelKit | 1a75b92fdad606be2493a8e8ceff21d4e318daec | [
"MIT"
] | 41 | 2019-05-22T12:00:36.000Z | 2020-10-12T17:44:55.000Z | //
// KaleidoscopePIX.swift
// PixelKit
//
// Created by Anton Heestand on 2018-08-18.
// Open Source - MIT License
//
import Foundation
import CoreGraphics
import RenderKit
import Resolution
final public class KaleidoscopePIX: PIXSingleEffect, PIXViewable {
public typealias Model = KaleidoscopePixelModel
private var model: Model {
get { singleEffectModel as! Model }
set { singleEffectModel = newValue }
}
override public var shaderName: String { return "effectSingleKaleidoscopePIX" }
// MARK: - Public Properties
@LiveInt("divisions", range: 2...24) public var divisions: Int = 12
@LiveBool("mirror") public var mirror: Bool = true
@LiveFloat("rotation", range: -0.5...0.5, increment: 0.125) public var rotation: CGFloat = 0.0
@LivePoint("position") public var position: CGPoint = .zero
// MARK: - Property Helpers
public override var liveList: [LiveWrap] {
[_divisions, _mirror, _rotation, _position]
}
override public var values: [Floatable] {
[divisions, mirror, rotation, position]
}
// MARK: - Life Cycle -
public init(model: Model) {
super.init(model: model)
}
public required init() {
let model = Model()
super.init(model: model)
}
// MARK: - Live Model
public override func modelUpdateLive() {
super.modelUpdateLive()
divisions = model.divisions
mirror = model.mirror
rotation = model.rotation
position = model.position
super.modelUpdateLiveDone()
}
public override func liveUpdateModel() {
super.liveUpdateModel()
model.divisions = divisions
model.mirror = mirror
model.rotation = rotation
model.position = position
super.liveUpdateModelDone()
}
}
public extension NODEOut {
func pixKaleidoscope(divisions: Int = 12, mirror: Bool = true) -> KaleidoscopePIX {
let kaleidoscopePix = KaleidoscopePIX()
kaleidoscopePix.name = ":kaleidoscope:"
kaleidoscopePix.input = self as? PIX & NODEOut
kaleidoscopePix.divisions = divisions
kaleidoscopePix.mirror = mirror
return kaleidoscopePix
}
}
| 25.644444 | 98 | 0.62695 |
061434c1a85ca89780d099024e65961cdf44ad89 | 2,760 | kt | Kotlin | plot-builder-portable/src/commonMain/kotlin/jetbrains/datalore/plot/builder/assemble/geom/PointDataAccess.kt | IKrukov-HORIS/lets-plot | b772e4abcc4c715ef3c3a2e3db55abd4044f863f | [
"MIT"
] | 768 | 2019-11-28T14:09:46.000Z | 2022-03-30T18:19:28.000Z | plot-builder-portable/src/commonMain/kotlin/jetbrains/datalore/plot/builder/assemble/geom/PointDataAccess.kt | IKrukov-HORIS/lets-plot | b772e4abcc4c715ef3c3a2e3db55abd4044f863f | [
"MIT"
] | 240 | 2019-12-04T20:15:03.000Z | 2022-03-30T17:12:23.000Z | plot-builder-portable/src/commonMain/kotlin/jetbrains/datalore/plot/builder/assemble/geom/PointDataAccess.kt | IKrukov-HORIS/lets-plot | b772e4abcc4c715ef3c3a2e3db55abd4044f863f | [
"MIT"
] | 43 | 2019-12-05T13:45:32.000Z | 2022-03-31T21:27:00.000Z | /*
* Copyright (c) 2019. JetBrains s.r.o.
* Use of this source code is governed by the MIT license that can be found in the LICENSE file.
*/
package jetbrains.datalore.plot.builder.assemble.geom
import jetbrains.datalore.plot.base.Aes
import jetbrains.datalore.plot.base.DataFrame
import jetbrains.datalore.plot.base.Scale
import jetbrains.datalore.plot.base.interact.MappedDataAccess
import jetbrains.datalore.plot.base.scale.ScaleUtil.labelByBreak
import jetbrains.datalore.plot.builder.VarBinding
import jetbrains.datalore.plot.builder.assemble.TypedScaleMap
import jetbrains.datalore.plot.common.data.SeriesUtil.ensureApplicableRange
internal class PointDataAccess(
private val data: DataFrame,
bindings: Map<Aes<*>, VarBinding>,
scaleMap: TypedScaleMap
) : MappedDataAccess {
private val scaleByAes: (Aes<*>) -> Scale<*> = { scaleMap[it] }
private val myBindings: Map<Aes<*>, VarBinding> = bindings.toMap()
private val myFormatters = HashMap<Aes<*>, (Any?) -> String>()
override fun isMapped(aes: Aes<*>) = myBindings.containsKey(aes)
override fun getOriginalValue(aes: Aes<*>, index: Int): Any? {
require(isMapped(aes)) { "Not mapped: $aes" }
val binding = myBindings.getValue(aes)
val scale = getScale(aes)
return binding.variable
.let { variable -> data.getNumeric(variable)[index] }
.let { value -> scale.transform.applyInverse(value) }
}
override fun getMappedDataValue(aes: Aes<*>, index: Int): String {
val originalValue = getOriginalValue(aes, index)
return formatter(aes).invoke(originalValue)
}
override fun getMappedDataLabel(aes: Aes<*>): String = getScale(aes).name
private fun getScale(aes: Aes<*>): Scale<*> {
return scaleByAes(aes)
}
private fun formatter(aes: Aes<*>): (Any?) -> String {
val scale = getScale(aes)
return myFormatters.getOrPut(aes, defaultValue = { createFormatter(aes, scale) })
}
private fun createFormatter(aes: Aes<*>, scale: Scale<*>): (Any?) -> String {
if (scale.isContinuousDomain) {
// only 'stat' or 'transform' vars here
val domain = myBindings
.getValue(aes)
.variable
.run(data::range)
.run(::ensureApplicableRange)
// Use the scale's default formatter (the 'format' parameter does not apply to tooltips)
val formatter = scale.getBreaksGenerator().defaultFormatter(domain, 100)
return { value -> value?.let { formatter.invoke(it) } ?: "n/a" }
} else {
val labelsMap = labelByBreak(scale)
return { value -> value?.let { labelsMap[it] } ?: "n/a" }
}
}
}
| 37.297297 | 100 | 0.652536 |
ee8158e713cf803f457a8a5c2ef50b92026c5615 | 8,872 | kt | Kotlin | fintechplatform-ui/src/main/java/com/fintechplatform/ui/enterprise/documents/EnterpriseDocumentsFragment.kt | DWAplatform/fintech-platform-sdk-android | 498bfbdfd00724ae24d7efc01e9af0b2a8cb58b0 | [
"MIT"
] | null | null | null | fintechplatform-ui/src/main/java/com/fintechplatform/ui/enterprise/documents/EnterpriseDocumentsFragment.kt | DWAplatform/fintech-platform-sdk-android | 498bfbdfd00724ae24d7efc01e9af0b2a8cb58b0 | [
"MIT"
] | null | null | null | fintechplatform-ui/src/main/java/com/fintechplatform/ui/enterprise/documents/EnterpriseDocumentsFragment.kt | DWAplatform/fintech-platform-sdk-android | 498bfbdfd00724ae24d7efc01e9af0b2a8cb58b0 | [
"MIT"
] | 2 | 2019-06-27T05:37:21.000Z | 2021-05-11T12:54:03.000Z | package com.fintechplatform.ui.enterprise.documents
import android.Manifest
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Bundle
import android.os.Environment
import android.provider.MediaStore
import android.support.v4.app.ActivityCompat
import android.support.v4.app.Fragment
import android.support.v7.app.AppCompatActivity
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.fintechplatform.api.enterprise.models.EnterpriseDocType
import com.fintechplatform.ui.R
import com.fintechplatform.ui.alert.AlertHelpers
import com.fintechplatform.ui.enterprise.documents.di.EnterpriseDocumentsViewComponent
import com.fintechplatform.ui.enterprise.documents.dialog.EnterpriseDocTypeDialog
import com.fintechplatform.ui.models.DataAccount
import kotlinx.android.synthetic.main.fragment_enterprise_documents.*
import kotlinx.android.synthetic.main.fragment_enterprise_documents.view.*
import java.io.File
import java.io.IOException
import java.text.SimpleDateFormat
import java.util.*
import javax.inject.Inject
open class EnterpriseDocumentsFragment: Fragment(), EnterpriseDocumentsContract.View {
@Inject
lateinit var presenter: EnterpriseDocumentsContract.Presenter
@Inject
lateinit var alertHelper: AlertHelpers
val PICK_DOCUMENT_PAGES = 110
var navigation: EnterpriseDocumentsContract.Navigation? = null
open fun createEnterpriseDocumentsViewComponent(context: Context, view: EnterpriseDocumentsContract.View, hostName: String, dataAccount: DataAccount) : EnterpriseDocumentsViewComponent {
return EnterpriseDocumentsUI.Builder.buildEnterpriseDocumentsViewComponent(context, view, hostName, dataAccount)
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
val view = inflater.inflate(R.layout.fragment_enterprise_documents, container, false)
arguments?.getString("hostname")?.let { hostname ->
arguments?.getParcelable<DataAccount>("dataAccount")?.let { dataAccount ->
createEnterpriseDocumentsViewComponent(context, this, hostname, dataAccount).inject(this)
}
}
view.backwardButton.setOnClickListener { presenter.onAbort() }
view.confirmButton.setOnClickListener { presenter.onConfirm() }
view.insertPage.setOnClickListener { presenter.onInsertPages() }
view.docTypePicker.setOnClickListener { showDockTypeDialog() }
return view
}
override fun onViewCreated(view: View?, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
presenter.initializate()
}
override fun onResume() {
super.onResume()
presenter.onRefresh()
}
override fun onAttach(context: Context?) {
super.onAttach(context)
(context as? EnterpriseDocumentsContract.Navigation)?.let {
navigation = it
}?: Log.e(EnterpriseDocumentsFragment::class.java.canonicalName, "EnterpriseDocumentsContract.Navigation must be implemented in your Activity!!")
}
override fun onDetach() {
super.onDetach()
navigation = null
}
private fun showDockTypeDialog() {
val dialog = EnterpriseDocTypeDialog.newInstance()
dialog.show(activity.supportFragmentManager, DIALOG_REQUEST)
}
override fun setAbortText() {
backwardButton.text = resources.getString(R.string.abort)
}
override fun enableConfirmButton(isEnable: Boolean) {
confirmButton.isEnabled = isEnable
}
override fun showWaiting() {
activityIndicator.visibility = View.VISIBLE
}
override fun hideWaiting() {
activityIndicator.visibility = View.GONE
}
override fun showTokenExpiredWarning() {
alertHelper.tokenExpired(context) { _, _ ->
navigation?.backFromEnterpriseDocuments()
}
}
override fun showGenericError() {
alertHelper.internalError(context).show()
}
override fun setNumberPages(number: Int) {
fileIcon.visibility = View.GONE
numberPages.text = number.toString()
}
override fun setDocTypeSelected(docType: EnterpriseDocType) {
docTypePickerText.text = docType.toString()
}
var photoPath: String? = null
override fun goToCamera() {
Intent(MediaStore.ACTION_IMAGE_CAPTURE).also { takePictureIntent ->
takePictureIntent.resolveActivity(activity.packageManager)?.also {
// Create the File where the photo should go
val photoFile = try {
// Create an image file name
val timeStamp: String = SimpleDateFormat("yyyyMMdd").format(Date())
val storageDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES)
/** fixme
* https://developer.android.com/reference/android/os/Environment.html#getExternalStoragePublicDirectory(java.lang.String)
*
* This method was deprecated in API level 29.
* To improve user privacy, direct access to shared/external storage devices is deprecated.
* When an app targets Build.VERSION_CODES.Q, the path returned from this method is no longer directly accessible to apps.
* Apps can continue to access content stored on shared/external storage by migrating to alternatives such as Context#getExternalFilesDir(String), MediaStore, or Intent#ACTION_OPEN_DOCUMENT.
*/
Log.d("File path created", storageDir.absolutePath)
File.createTempFile(
"IMG_${timeStamp}",
".jpg",
storageDir
).apply {
photoPath = absolutePath
//galleryAddPic(absolutePath)
Log.d("photo path:", photoPath)
}
} catch (ex: IOException) {
null
}
photoFile?.also {
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(it))
startActivityForResult(takePictureIntent, PICK_DOCUMENT_PAGES)
}
}
}
}
override fun goBack() {
navigation?.backFromEnterpriseDocuments()
}
override fun checkCameraPermission() {
if (ActivityCompat.checkSelfPermission(context,
Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED ||
ActivityCompat.checkSelfPermission(context,
Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(activity,
arrayOf(Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE),
PICK_DOCUMENT_PAGES)
return
}
}
override fun onActivityResult(requestCode: Int, resultCode: Int, optData: Intent?) {
super.onActivityResult(requestCode, resultCode, optData)
if(requestCode == PICK_DOCUMENT_PAGES && resultCode == AppCompatActivity.RESULT_OK){
presenter.onPictureTaken(File(photoPath), 0)
}
}
override fun onRequestPermissionsResult(requestCode: Int,
permissions: Array<String>, grantResults: IntArray) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
if (requestCode == PICK_DOCUMENT_PAGES ) {
var cameraok = false
var externalstorage = false
for (i in grantResults.indices) {
if (grantResults[i] >= 0) {
if (permissions[i] == Manifest.permission.CAMERA) {
cameraok = true
}
if (permissions[i] == Manifest.permission.WRITE_EXTERNAL_STORAGE) {
externalstorage = true
}
}
}
// fromPermissions = true
// permissionsOk = cameraok && externalstorage
}
}
companion object {
const val DIALOG_REQUEST = "docType_request"
fun newInstance(hostName: String, dataAccount: DataAccount): EnterpriseDocumentsFragment{
val frag = EnterpriseDocumentsFragment()
val args = Bundle()
args.putString("hostname", hostName)
args.putParcelable("dataAccount", dataAccount)
frag.arguments = args
return frag
}
}
} | 38.742358 | 210 | 0.654418 |
166be5edfbeb00d6931468abd256f572dc8dd89c | 53 | ts | TypeScript | packages/sdk-utils/types/index.d.ts | DreamBox2020/shippo | b7e102ce782493eac029ef0cfd911fe93aac8cdc | [
"MIT"
] | 50 | 2020-10-21T01:01:39.000Z | 2022-01-25T06:37:27.000Z | packages/sdk-utils/types/index.d.ts | DreamBox2020/shippo | b7e102ce782493eac029ef0cfd911fe93aac8cdc | [
"MIT"
] | 1 | 2021-08-19T09:16:35.000Z | 2021-08-19T23:02:41.000Z | packages/sdk-utils/types/index.d.ts | DreamBox2020/shippo | b7e102ce782493eac029ef0cfd911fe93aac8cdc | [
"MIT"
] | 11 | 2021-08-19T10:13:11.000Z | 2022-03-26T04:08:39.000Z | export * from './request';
export * from './checks';
| 17.666667 | 26 | 0.622642 |
746dfc2f5db9673ddbaea2177802ed0722257207 | 251 | h | C | PrivateFrameworks/iWorkImport.framework/TPGilliganCompatibilityDelegate.h | shaojiankui/iOS10-Runtime-Headers | 6b0d842bed0c52c2a7c1464087b3081af7e10c43 | [
"MIT"
] | 36 | 2016-04-20T04:19:04.000Z | 2018-10-08T04:12:25.000Z | PrivateFrameworks/iWorkImport.framework/TPGilliganCompatibilityDelegate.h | shaojiankui/iOS10-Runtime-Headers | 6b0d842bed0c52c2a7c1464087b3081af7e10c43 | [
"MIT"
] | null | null | null | PrivateFrameworks/iWorkImport.framework/TPGilliganCompatibilityDelegate.h | shaojiankui/iOS10-Runtime-Headers | 6b0d842bed0c52c2a7c1464087b3081af7e10c43 | [
"MIT"
] | 10 | 2016-06-16T02:40:44.000Z | 2019-01-15T03:31:45.000Z | /* Generated by RuntimeBrowser
Image: /System/Library/PrivateFrameworks/iWorkImport.framework/iWorkImport
*/
@interface TPGilliganCompatibilityDelegate : TPBaseCompatibilityDelegate
- (Class)exporterClassForType:(id)arg1 options:(id)arg2;
@end
| 25.1 | 77 | 0.816733 |
754aebc6503e2ab305296e76cf9b9049ec25886c | 25,740 | c | C | extern/gtk/gtk/gtkfilechooserdialog.c | PableteProgramming/download | 013e35bb5c085e5dfdb57a3a0a39cdf2fd3064b8 | [
"MIT"
] | null | null | null | extern/gtk/gtk/gtkfilechooserdialog.c | PableteProgramming/download | 013e35bb5c085e5dfdb57a3a0a39cdf2fd3064b8 | [
"MIT"
] | null | null | null | extern/gtk/gtk/gtkfilechooserdialog.c | PableteProgramming/download | 013e35bb5c085e5dfdb57a3a0a39cdf2fd3064b8 | [
"MIT"
] | null | null | null | /* -*- Mode: C; c-file-style: "gnu"; tab-width: 8 -*- */
/* GTK - The GIMP Toolkit
* gtkfilechooserdialog.c: File selector dialog
* Copyright (C) 2003, Red Hat, Inc.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library. If not, see <http://www.gnu.org/licenses/>.
*/
#include "config.h"
#include "gtkfilechooserdialog.h"
#include "gtkfilechooserprivate.h"
#include "gtkfilechooserwidget.h"
#include "gtkfilechooserwidgetprivate.h"
#include "gtkfilechooserutils.h"
#include "gtksizerequest.h"
#include "gtktypebuiltins.h"
#include "gtkintl.h"
#include "gtksettings.h"
#include "gtktogglebutton.h"
#include "gtkheaderbar.h"
#include "gtkdialogprivate.h"
#include "gtklabel.h"
#include "gtkfilechooserentry.h"
#include "gtkbox.h"
#include <stdarg.h>
/**
* GtkFileChooserDialog:
*
* `GtkFileChooserDialog` is a dialog suitable for use with
* “File Open” or “File Save” commands.
*
* 
*
* This widget works by putting a [class@Gtk.FileChooserWidget]
* inside a [class@Gtk.Dialog]. It exposes the [iface@Gtk.FileChooser]
* interface, so you can use all of the [iface@Gtk.FileChooser] functions
* on the file chooser dialog as well as those for [class@Gtk.Dialog].
*
* Note that `GtkFileChooserDialog` does not have any methods of its
* own. Instead, you should use the functions that work on a
* [iface@Gtk.FileChooser].
*
* If you want to integrate well with the platform you should use the
* [class@Gtk.FileChooserNative] API, which will use a platform-specific
* dialog if available and fall back to `GtkFileChooserDialog`
* otherwise.
*
* ## Typical usage
*
* In the simplest of cases, you can the following code to use
* `GtkFileChooserDialog` to select a file for opening:
*
* ```c
* static void
* on_open_response (GtkDialog *dialog,
* int response)
* {
* if (response == GTK_RESPONSE_ACCEPT)
* {
* GtkFileChooser *chooser = GTK_FILE_CHOOSER (dialog);
*
* g_autoptr(GFile) file = gtk_file_chooser_get_file (chooser);
*
* open_file (file);
* }
*
* gtk_window_destroy (GTK_WINDOW (dialog));
* }
*
* // ...
* GtkWidget *dialog;
* GtkFileChooserAction action = GTK_FILE_CHOOSER_ACTION_OPEN;
*
* dialog = gtk_file_chooser_dialog_new ("Open File",
* parent_window,
* action,
* _("_Cancel"),
* GTK_RESPONSE_CANCEL,
* _("_Open"),
* GTK_RESPONSE_ACCEPT,
* NULL);
*
* gtk_widget_show (dialog);
*
* g_signal_connect (dialog, "response",
* G_CALLBACK (on_open_response),
* NULL);
* ```
*
* To use a dialog for saving, you can use this:
*
* ```c
* static void
* on_save_response (GtkDialog *dialog,
* int response)
* {
* if (response == GTK_RESPONSE_ACCEPT)
* {
* GtkFileChooser *chooser = GTK_FILE_CHOOSER (dialog);
*
* g_autoptr(GFile) file = gtk_file_chooser_get_file (chooser);
*
* save_to_file (file);
* }
*
* gtk_window_destroy (GTK_WINDOW (dialog));
* }
*
* // ...
* GtkWidget *dialog;
* GtkFileChooser *chooser;
* GtkFileChooserAction action = GTK_FILE_CHOOSER_ACTION_SAVE;
*
* dialog = gtk_file_chooser_dialog_new ("Save File",
* parent_window,
* action,
* _("_Cancel"),
* GTK_RESPONSE_CANCEL,
* _("_Save"),
* GTK_RESPONSE_ACCEPT,
* NULL);
* chooser = GTK_FILE_CHOOSER (dialog);
*
* if (user_edited_a_new_document)
* gtk_file_chooser_set_current_name (chooser, _("Untitled document"));
* else
* gtk_file_chooser_set_file (chooser, existing_filename);
*
* gtk_widget_show (dialog);
*
* g_signal_connect (dialog, "response",
* G_CALLBACK (on_save_response),
* NULL);
* ```
*
* ## Setting up a file chooser dialog
*
* There are various cases in which you may need to use a `GtkFileChooserDialog`:
*
* - To select a file for opening, use %GTK_FILE_CHOOSER_ACTION_OPEN.
*
* - To save a file for the first time, use %GTK_FILE_CHOOSER_ACTION_SAVE,
* and suggest a name such as “Untitled” with
* [method@Gtk.FileChooser.set_current_name].
*
* - To save a file under a different name, use %GTK_FILE_CHOOSER_ACTION_SAVE,
* and set the existing file with [method@Gtk.FileChooser.set_file].
*
* - To choose a folder instead of a filem use %GTK_FILE_CHOOSER_ACTION_SELECT_FOLDER.
*
* In general, you should only cause the file chooser to show a specific
* folder when it is appropriate to use [method@Gtk.FileChooser.set_file],
* i.e. when you are doing a “Save As” command and you already have a file
* saved somewhere.
* ## Response Codes
*
* `GtkFileChooserDialog` inherits from [class@Gtk.Dialog], so buttons that
* go in its action area have response codes such as %GTK_RESPONSE_ACCEPT and
* %GTK_RESPONSE_CANCEL. For example, you could call
* [ctor@Gtk.FileChooserDialog.new] as follows:
*
* ```c
* GtkWidget *dialog;
* GtkFileChooserAction action = GTK_FILE_CHOOSER_ACTION_OPEN;
*
* dialog = gtk_file_chooser_dialog_new ("Open File",
* parent_window,
* action,
* _("_Cancel"),
* GTK_RESPONSE_CANCEL,
* _("_Open"),
* GTK_RESPONSE_ACCEPT,
* NULL);
* ```
*
* This will create buttons for “Cancel” and “Open” that use predefined
* response identifiers from [enum@Gtk.ResponseType]. For most dialog
* boxes you can use your own custom response codes rather than the
* ones in [enum@Gtk.ResponseType], but `GtkFileChooserDialog` assumes that
* its “accept”-type action, e.g. an “Open” or “Save” button,
* will have one of the following response codes:
*
* - %GTK_RESPONSE_ACCEPT
* - %GTK_RESPONSE_OK
* - %GTK_RESPONSE_YES
* - %GTK_RESPONSE_APPLY
*
* This is because `GtkFileChooserDialog` must intercept responses and switch
* to folders if appropriate, rather than letting the dialog terminate — the
* implementation uses these known response codes to know which responses can
* be blocked if appropriate.
*
* To summarize, make sure you use a predefined response code
* when you use `GtkFileChooserDialog` to ensure proper operation.
*/
typedef struct _GtkFileChooserDialogPrivate GtkFileChooserDialogPrivate;
typedef struct _GtkFileChooserDialogClass GtkFileChooserDialogClass;
struct _GtkFileChooserDialog
{
GtkDialog parent_instance;
};
struct _GtkFileChooserDialogClass
{
GtkDialogClass parent_class;
};
struct _GtkFileChooserDialogPrivate
{
GtkWidget *widget;
GtkSizeGroup *buttons;
/* for use with GtkFileChooserEmbed */
gboolean response_requested;
gboolean search_setup;
gboolean has_entry;
};
static void gtk_file_chooser_dialog_dispose (GObject *object);
static void gtk_file_chooser_dialog_set_property (GObject *object,
guint prop_id,
const GValue *value,
GParamSpec *pspec);
static void gtk_file_chooser_dialog_get_property (GObject *object,
guint prop_id,
GValue *value,
GParamSpec *pspec);
static void gtk_file_chooser_dialog_notify (GObject *object,
GParamSpec *pspec);
static void gtk_file_chooser_dialog_realize (GtkWidget *widget);
static void gtk_file_chooser_dialog_map (GtkWidget *widget);
static void gtk_file_chooser_dialog_unmap (GtkWidget *widget);
static void gtk_file_chooser_dialog_size_allocate (GtkWidget *widget,
int width,
int height,
int baseline);
static void gtk_file_chooser_dialog_activate_response (GtkWidget *widget,
const char *action_name,
GVariant *parameters);
static void response_cb (GtkDialog *dialog,
int response_id);
static void setup_save_entry (GtkFileChooserDialog *dialog);
G_DEFINE_TYPE_WITH_CODE (GtkFileChooserDialog, gtk_file_chooser_dialog, GTK_TYPE_DIALOG,
G_ADD_PRIVATE (GtkFileChooserDialog)
G_IMPLEMENT_INTERFACE (GTK_TYPE_FILE_CHOOSER,
_gtk_file_chooser_delegate_iface_init))
static void
gtk_file_chooser_dialog_class_init (GtkFileChooserDialogClass *class)
{
GObjectClass *gobject_class = G_OBJECT_CLASS (class);
GtkWidgetClass *widget_class = GTK_WIDGET_CLASS (class);
gobject_class->dispose = gtk_file_chooser_dialog_dispose;
gobject_class->set_property = gtk_file_chooser_dialog_set_property;
gobject_class->get_property = gtk_file_chooser_dialog_get_property;
gobject_class->notify = gtk_file_chooser_dialog_notify;
widget_class->realize = gtk_file_chooser_dialog_realize;
widget_class->map = gtk_file_chooser_dialog_map;
widget_class->unmap = gtk_file_chooser_dialog_unmap;
widget_class->size_allocate = gtk_file_chooser_dialog_size_allocate;
_gtk_file_chooser_install_properties (gobject_class);
/* Bind class to template
*/
gtk_widget_class_set_template_from_resource (widget_class,
"/org/gtk/libgtk/ui/gtkfilechooserdialog.ui");
gtk_widget_class_bind_template_child_private (widget_class, GtkFileChooserDialog, widget);
gtk_widget_class_bind_template_child_private (widget_class, GtkFileChooserDialog, buttons);
gtk_widget_class_bind_template_callback (widget_class, response_cb);
/**
* GtkFileChooserDialog|response.activate:
*
* Activate the default response of the dialog.
*/
gtk_widget_class_install_action (widget_class, "response.activate", NULL, gtk_file_chooser_dialog_activate_response);
}
static void
gtk_file_chooser_dialog_init (GtkFileChooserDialog *dialog)
{
GtkFileChooserDialogPrivate *priv = gtk_file_chooser_dialog_get_instance_private (dialog);
priv->response_requested = FALSE;
gtk_widget_init_template (GTK_WIDGET (dialog));
gtk_dialog_set_use_header_bar_from_setting (GTK_DIALOG (dialog));
_gtk_file_chooser_set_delegate (GTK_FILE_CHOOSER (dialog),
GTK_FILE_CHOOSER (priv->widget));
}
static GtkWidget *
get_accept_action_widget (GtkDialog *dialog,
gboolean sensitive_only)
{
int response[] = {
GTK_RESPONSE_ACCEPT,
GTK_RESPONSE_OK,
GTK_RESPONSE_YES,
GTK_RESPONSE_APPLY
};
int i;
GtkWidget *widget;
for (i = 0; i < G_N_ELEMENTS (response); i++)
{
widget = gtk_dialog_get_widget_for_response (dialog, response[i]);
if (widget)
{
if (!sensitive_only)
return widget;
if (gtk_widget_is_sensitive (widget))
return widget;
}
}
return NULL;
}
static gboolean
is_accept_response_id (int response_id)
{
return (response_id == GTK_RESPONSE_ACCEPT ||
response_id == GTK_RESPONSE_OK ||
response_id == GTK_RESPONSE_YES ||
response_id == GTK_RESPONSE_APPLY);
}
static void
gtk_file_chooser_dialog_activate_response (GtkWidget *widget,
const char *action_name,
GVariant *parameters)
{
GtkFileChooserDialog *dialog = GTK_FILE_CHOOSER_DIALOG (widget);
GtkFileChooserDialogPrivate *priv = gtk_file_chooser_dialog_get_instance_private (dialog);
GtkWidget *button;
priv->response_requested = TRUE;
button = get_accept_action_widget (GTK_DIALOG (dialog), TRUE);
if (button)
{
gtk_widget_activate (button);
return;
}
priv->response_requested = FALSE;
}
static void
gtk_file_chooser_dialog_dispose (GObject *object)
{
GtkFileChooserDialogPrivate *priv = gtk_file_chooser_dialog_get_instance_private (GTK_FILE_CHOOSER_DIALOG (object));
g_clear_pointer ((GtkWidget **)&priv->widget, gtk_widget_unparent);
G_OBJECT_CLASS (gtk_file_chooser_dialog_parent_class)->dispose (object);
}
static void
gtk_file_chooser_dialog_set_property (GObject *object,
guint prop_id,
const GValue *value,
GParamSpec *pspec)
{
GtkFileChooserDialogPrivate *priv = gtk_file_chooser_dialog_get_instance_private (GTK_FILE_CHOOSER_DIALOG (object));
g_object_set_property (G_OBJECT (priv->widget), pspec->name, value);
}
static void
gtk_file_chooser_dialog_get_property (GObject *object,
guint prop_id,
GValue *value,
GParamSpec *pspec)
{
GtkFileChooserDialogPrivate *priv = gtk_file_chooser_dialog_get_instance_private (GTK_FILE_CHOOSER_DIALOG (object));
g_object_get_property (G_OBJECT (priv->widget), pspec->name, value);
}
static void
gtk_file_chooser_dialog_notify (GObject *object,
GParamSpec *pspec)
{
if (strcmp (pspec->name, "action") == 0)
setup_save_entry (GTK_FILE_CHOOSER_DIALOG (object));
if (G_OBJECT_CLASS (gtk_file_chooser_dialog_parent_class)->notify)
G_OBJECT_CLASS (gtk_file_chooser_dialog_parent_class)->notify (object, pspec);
}
static void
add_button (GtkWidget *button, gpointer data)
{
GtkFileChooserDialog *dialog = data;
GtkFileChooserDialogPrivate *priv = gtk_file_chooser_dialog_get_instance_private (dialog);
if (GTK_IS_BUTTON (button))
gtk_size_group_add_widget (priv->buttons, button);
}
static gboolean
translate_subtitle_to_visible (GBinding *binding,
const GValue *from_value,
GValue *to_value,
gpointer user_data)
{
const char *subtitle = g_value_get_string (from_value);
g_value_set_boolean (to_value, subtitle != NULL);
return TRUE;
}
static void
setup_search (GtkFileChooserDialog *dialog)
{
GtkFileChooserDialogPrivate *priv = gtk_file_chooser_dialog_get_instance_private (dialog);
gboolean use_header;
GtkWidget *child;
if (priv->search_setup)
return;
priv->search_setup = TRUE;
g_object_get (dialog, "use-header-bar", &use_header, NULL);
if (use_header)
{
GtkWidget *button;
GtkWidget *header;
GtkWidget *box;
GtkWidget *label;
button = gtk_toggle_button_new ();
gtk_widget_set_focus_on_click (button, FALSE);
gtk_widget_set_valign (button, GTK_ALIGN_CENTER);
gtk_button_set_icon_name (GTK_BUTTON (button), "edit-find-symbolic");
gtk_widget_show (button);
header = gtk_dialog_get_header_bar (GTK_DIALOG (dialog));
gtk_header_bar_pack_end (GTK_HEADER_BAR (header), button);
g_object_bind_property (button, "active",
priv->widget, "search-mode",
G_BINDING_BIDIRECTIONAL);
if (!priv->has_entry)
{
box = gtk_box_new (GTK_ORIENTATION_VERTICAL, 0);
gtk_widget_set_valign (box, GTK_ALIGN_CENTER);
label = gtk_label_new (NULL);
gtk_widget_set_halign (label, GTK_ALIGN_CENTER);
gtk_label_set_single_line_mode (GTK_LABEL (label), TRUE);
gtk_label_set_ellipsize (GTK_LABEL (label), PANGO_ELLIPSIZE_END);
gtk_label_set_width_chars (GTK_LABEL (label), 5);
gtk_widget_add_css_class (label, "title");
gtk_widget_set_parent (label, box);
g_object_bind_property (dialog, "title",
label, "label",
G_BINDING_SYNC_CREATE);
label = gtk_label_new (NULL);
gtk_widget_set_halign (label, GTK_ALIGN_CENTER);
gtk_label_set_single_line_mode (GTK_LABEL (label), TRUE);
gtk_label_set_ellipsize (GTK_LABEL (label), PANGO_ELLIPSIZE_END);
gtk_widget_add_css_class (label, "subtitle");
gtk_widget_set_parent (label, box);
g_object_bind_property (priv->widget, "subtitle",
label, "label",
G_BINDING_SYNC_CREATE);
g_object_bind_property_full (priv->widget, "subtitle",
label, "visible",
G_BINDING_SYNC_CREATE,
translate_subtitle_to_visible,
NULL, NULL, NULL);
gtk_header_bar_set_title_widget (GTK_HEADER_BAR (header), box);
}
for (child = gtk_widget_get_first_child (header);
child != NULL;
child = gtk_widget_get_next_sibling (child))
add_button (child, dialog);
}
}
static void
setup_save_entry (GtkFileChooserDialog *dialog)
{
GtkFileChooserDialogPrivate *priv = gtk_file_chooser_dialog_get_instance_private (dialog);
gboolean use_header;
GtkFileChooserAction action;
gboolean need_entry;
GtkWidget *header;
g_object_get (dialog,
"use-header-bar", &use_header,
"action", &action,
NULL);
if (!use_header)
return;
header = gtk_dialog_get_header_bar (GTK_DIALOG (dialog));
need_entry = action == GTK_FILE_CHOOSER_ACTION_SAVE;
if (need_entry && !priv->has_entry)
{
GtkWidget *box;
GtkWidget *label;
GtkWidget *entry;
box = gtk_box_new (GTK_ORIENTATION_HORIZONTAL, 0);
label = gtk_label_new_with_mnemonic (_("_Name"));
entry = _gtk_file_chooser_entry_new (FALSE, FALSE);
g_object_set (label, "margin-start", 6, "margin-end", 6, NULL);
g_object_set (entry, "margin-start", 6, "margin-end", 6, NULL);
gtk_label_set_mnemonic_widget (GTK_LABEL (label), entry);
gtk_box_append (GTK_BOX (box), label);
gtk_box_append (GTK_BOX (box), entry);
gtk_header_bar_set_title_widget (GTK_HEADER_BAR (header), box);
gtk_file_chooser_widget_set_save_entry (GTK_FILE_CHOOSER_WIDGET (priv->widget), entry);
}
else if (!need_entry && priv->has_entry)
{
gtk_header_bar_set_title_widget (GTK_HEADER_BAR (header), NULL);
gtk_file_chooser_widget_set_save_entry (GTK_FILE_CHOOSER_WIDGET (priv->widget), NULL);
}
priv->has_entry = need_entry;
}
static void
ensure_default_response (GtkFileChooserDialog *dialog)
{
GtkWidget *widget;
widget = get_accept_action_widget (GTK_DIALOG (dialog), TRUE);
if (widget)
gtk_window_set_default_widget (GTK_WINDOW (dialog), widget);
}
static void
gtk_file_chooser_dialog_realize (GtkWidget *widget)
{
GtkFileChooserDialog *dialog = GTK_FILE_CHOOSER_DIALOG (widget);
GSettings *settings;
int width, height;
settings = _gtk_file_chooser_get_settings_for_widget (widget);
g_settings_get (settings, SETTINGS_KEY_WINDOW_SIZE, "(ii)", &width, &height);
if (width != 0 && height != 0)
gtk_window_set_default_size (GTK_WINDOW (dialog), width, height);
GTK_WIDGET_CLASS (gtk_file_chooser_dialog_parent_class)->realize (widget);
}
static void
gtk_file_chooser_dialog_map (GtkWidget *widget)
{
GtkFileChooserDialog *dialog = GTK_FILE_CHOOSER_DIALOG (widget);
GtkFileChooserDialogPrivate *priv = gtk_file_chooser_dialog_get_instance_private (dialog);
setup_search (dialog);
setup_save_entry (dialog);
ensure_default_response (dialog);
gtk_file_chooser_widget_initial_focus (GTK_FILE_CHOOSER_WIDGET (priv->widget));
GTK_WIDGET_CLASS (gtk_file_chooser_dialog_parent_class)->map (widget);
}
static void
save_dialog_geometry (GtkFileChooserDialog *dialog)
{
GtkWindow *window;
GSettings *settings;
int old_width, old_height;
int width, height;
settings = _gtk_file_chooser_get_settings_for_widget (GTK_WIDGET (dialog));
window = GTK_WINDOW (dialog);
gtk_window_get_default_size (window, &width, &height);
g_settings_get (settings, SETTINGS_KEY_WINDOW_SIZE, "(ii)", &old_width, &old_height);
if (old_width != width || old_height != height)
g_settings_set (settings, SETTINGS_KEY_WINDOW_SIZE, "(ii)", width, height);
g_settings_apply (settings);
}
static void
gtk_file_chooser_dialog_unmap (GtkWidget *widget)
{
GtkFileChooserDialog *dialog = GTK_FILE_CHOOSER_DIALOG (widget);
save_dialog_geometry (dialog);
GTK_WIDGET_CLASS (gtk_file_chooser_dialog_parent_class)->unmap (widget);
}
static void
gtk_file_chooser_dialog_size_allocate (GtkWidget *widget,
int width,
int height,
int baseline)
{
GTK_WIDGET_CLASS (gtk_file_chooser_dialog_parent_class)->size_allocate (widget,
width,
height,
baseline);
if (gtk_widget_is_drawable (widget))
save_dialog_geometry (GTK_FILE_CHOOSER_DIALOG (widget));
}
/* We do a signal connection here rather than overriding the method in
* class_init because GtkDialog::response is a RUN_LAST signal. We want *our*
* handler to be run *first*, regardless of whether the user installs response
* handlers of his own.
*/
static void
response_cb (GtkDialog *dialog,
int response_id)
{
GtkFileChooserDialogPrivate *priv = gtk_file_chooser_dialog_get_instance_private (GTK_FILE_CHOOSER_DIALOG (dialog));
/* Act only on response IDs we recognize */
if (is_accept_response_id (response_id) &&
!priv->response_requested &&
!gtk_file_chooser_widget_should_respond (GTK_FILE_CHOOSER_WIDGET (priv->widget)))
{
g_signal_stop_emission_by_name (dialog, "response");
}
priv->response_requested = FALSE;
}
static GtkWidget *
gtk_file_chooser_dialog_new_valist (const char *title,
GtkWindow *parent,
GtkFileChooserAction action,
const char *first_button_text,
va_list varargs)
{
GtkWidget *result;
const char *button_text = first_button_text;
int response_id;
result = g_object_new (GTK_TYPE_FILE_CHOOSER_DIALOG,
"title", title,
"action", action,
NULL);
if (parent)
gtk_window_set_transient_for (GTK_WINDOW (result), parent);
while (button_text)
{
response_id = va_arg (varargs, int);
gtk_dialog_add_button (GTK_DIALOG (result), button_text, response_id);
button_text = va_arg (varargs, const char *);
}
return result;
}
/**
* gtk_file_chooser_dialog_new:
* @title: (nullable): Title of the dialog
* @parent: (nullable): Transient parent of the dialog
* @action: Open or save mode for the dialog
* @first_button_text: (nullable): text to go in the first button
* @...: response ID for the first button, then additional (button, id) pairs, ending with %NULL
*
* Creates a new `GtkFileChooserDialog`.
*
* This function is analogous to [ctor@Gtk.Dialog.new_with_buttons].
*
* Returns: a new `GtkFileChooserDialog`
*/
GtkWidget *
gtk_file_chooser_dialog_new (const char *title,
GtkWindow *parent,
GtkFileChooserAction action,
const char *first_button_text,
...)
{
GtkWidget *result;
va_list varargs;
va_start (varargs, first_button_text);
result = gtk_file_chooser_dialog_new_valist (title, parent, action,
first_button_text,
varargs);
va_end (varargs);
return result;
}
| 34.783784 | 119 | 0.629643 |
0edc5c372d4510af2ff58bb3607a8527a05c242e | 1,520 | ts | TypeScript | src/commons/ArrayCollection.ts | prishedko/algorithms-ts | a4355a3c4f74cb188488bae34827316c3c581f8e | [
"MIT"
] | 5 | 2017-11-02T09:25:07.000Z | 2020-08-30T15:57:32.000Z | src/commons/ArrayCollection.ts | prishedko/algorithms-ts | a4355a3c4f74cb188488bae34827316c3c581f8e | [
"MIT"
] | null | null | null | src/commons/ArrayCollection.ts | prishedko/algorithms-ts | a4355a3c4f74cb188488bae34827316c3c581f8e | [
"MIT"
] | null | null | null | import { CommonsAPI } from './api'
import { ArrayIterator } from './ArrayIterator'
import Collection = CommonsAPI.Collection
import CollectionIterator = CommonsAPI.CollectionIterator
/**
* Implementation of <tt>Collection</tt> that uses an array to store elements. Can either copy given array or reuse it -
* this behavior is defined by <tt>copyArray</tt> parameter of the constructor.
*/
export class ArrayCollection<E> implements Collection<E> {
private array: E[]
constructor(from: E[] = [], copyArray: boolean = true) {
if (copyArray) {
this.array = [...from]
} else {
this.array = from
}
}
map<T>(f: (e: E) => T): Collection<T> {
return new ArrayCollection(this.array.map(f), false)
}
filter(p: (e: E) => boolean): Collection<E> {
return new ArrayCollection(this.array.filter(p), false)
}
forEach(f: (e: E) => void): void {
this.array.forEach(f)
}
reduce<A>(r: (accumulator: A, currentElement: E) => A, initialValue: A): A {
return this.array.reduce(r, initialValue)
}
size(): number {
return this.array.length
}
find(p: (e: E) => boolean): E | undefined {
return this.array.find(p)
}
every(p: (e: E) => boolean): boolean {
return this.array.every(p)
}
some(p: (e: E) => boolean): boolean {
return this.array.some(p)
}
iterator(): CollectionIterator<E> {
return new ArrayIterator(this.array)
}
}
| 26.206897 | 120 | 0.596711 |
3cece4175c5a0536a09ba5585d3b03e185b907d5 | 3,869 | lua | Lua | 6_setup/additional_files/zh/mm8/zh_update/Scripts/Core/dump.lua | might-and-magic/mm678_i18n | ddc37c743ac37169908641dcd5328a7ccae5138f | [
"MIT"
] | 17 | 2020-02-25T14:37:23.000Z | 2022-02-21T15:33:09.000Z | 6_setup/additional_files/zh/mm8/zh_update/Scripts/Core/dump.lua | might-and-magic/mm678_i18n | ddc37c743ac37169908641dcd5328a7ccae5138f | [
"MIT"
] | 1 | 2022-01-09T02:14:56.000Z | 2022-02-13T10:08:11.000Z | 6_setup/additional_files/zh/mm8/zh_update/Scripts/Core/dump.lua | might-and-magic/mm678_i18n | ddc37c743ac37169908641dcd5328a7ccae5138f | [
"MIT"
] | 3 | 2020-10-06T20:38:13.000Z | 2021-02-17T02:11:17.000Z | DumpLimit = 10000
local _KNOWNGLOBALS = dump, structs
local Keywords = {}
do
local t = {"and", "break", "do", "else", "elseif", "end", "false", "for", "function", "if", "in", "local", "nil", "not", "or", "repeat", "return", "then", "true", "until", "while", "goto"}
for k, v in pairs(t) do
Keywords[v] = k
end
end
-- Mostly for debugging and expirimenting. Shows 't', expanding all tables in it up to the 'depth' level.
function dump(t, depth, exact)
local buf = {}
local bufn = 0
local ShowN
local tables = {}
local ptrs = {}
local ShowTable
depth = depth and depth * 2 or math.huge
local function Write(str)
bufn = bufn + 1
buf[bufn] = str
end
local function mystring(v)
if type(v) == "number" then
if v ~= v then
return "0/0"
elseif v == 1/0 then
return "1/0"
elseif v == -1/0 then
return "-1/0"
end
end
return tostring(v)
end
local function Key(v)
if type(v) == "string" then
if not v:match("^[%a_][%w_]*$") or exact and Keywords[v] then
v = ("[%q]"):format(v)
end
return v..' = '
elseif v == nil then
return ""
elseif type(v) == "table" then
tables[v] = tables[v] or false -- when shown needs address added
end
return '['..mystring(v)..'] = '
end
local function Val(v)
if type(v) == "string" then
if exact then
return ("%q"):format(v)
end
return '"'..v..'"'
else
return mystring(v)
end
end
local function FindSameStruct(v)
local ptr = v["?ptr"]
local class = structs.class(v)
local same = ptrs[ptr]
while same and class ~= structs.class(same) do
same = ptrs[same]
end
return same
end
local function ShowVal(k, v, space)
if bufn ~= ShowN then
buf[bufn] = buf[bufn]..','
end
if type(v) == "table" then
local n = tables[v]
local SameStruct = not n and structs and FindSameStruct(v)
if SameStruct then
n = tables[SameStruct]
if n then
v = SameStruct
end
end
if not n then -- not already shown
if #space < depth then
Write(("%s%s{"):format(space, Key(k)))
if n == false then -- needs address added
tables[v] = 0
buf[bufn] = buf[bufn].." -- "..Val(v)
else
tables[v] = bufn
end
if structs then
local ptr = v["?ptr"]
if ptr then
ptrs[v] = ptrs[ptr]
ptrs[ptr] = v
end
end
ShowTable(v, space)
return Write(space.."}")
else
tables[v] = false -- when shown needs address added
end
elseif n ~= 0 then -- address not already added
tables[v] = 0
buf[n] = buf[n].." -- "..Val(v)
end
if SameStruct then
return Write(("%s%sclone %s"):format(space, Key(k), Val(v)))
end
end
Write(("%s%s%s"):format(space, Key(k), Val(v)))
end
local function ShowArray(t, space)
-- local i = 1
for k, v in t do
ShowVal(nil, v, space)
-- if k == i then
-- ShowVal(nil, v, space)
-- i = i + 1
-- else
-- ShowVal(k, v, space)
-- end
end
end
local function ShowStruct(t, space)
for k, v in structs.enum(t) do
ShowVal(k, v, space)
end
end
function ShowTable(t, space)
if bufn > DumpLimit then
return Write(space.." ...")
end
ShowN = bufn
space = space.." "
if not structs or not pcall(ShowStruct, t, space) and not pcall(ShowArray, t, space) then -- !!!
local i = 1
for k, v in sortpairs(t) do
if k == i then
i, k = i + 1, nil
elseif k == i + 1 then
ShowVal(nil, nil, space)
i, k = i + 2, nil
elseif k == i + 2 then
ShowVal(nil, nil, space)
ShowVal(nil, nil, space)
i, k = i + 3, nil
end
ShowVal(k, v, space)
end
end
end
if type(t) == "table" and depth ~= 0 then
Write("{")
tables[t] = bufn
local ptr = t["?ptr"]
if ptr then
ptrs[ptr] = t
end
ShowTable(t, "")
Write("}")
else
Write(Val(t))
end
return table.concat(buf, "\n")
end
| 21.494444 | 189 | 0.571207 |
383a22f74ab91f98abcaf1a4bb165b868bd1782e | 11,822 | asm | Assembly | src/rng.asm | NobodyNada/sm_practice_hack | d232ffea256b82748aaa4f5677ede66dfa3c6e9e | [
"Unlicense"
] | null | null | null | src/rng.asm | NobodyNada/sm_practice_hack | d232ffea256b82748aaa4f5677ede66dfa3c6e9e | [
"Unlicense"
] | null | null | null | src/rng.asm | NobodyNada/sm_practice_hack | d232ffea256b82748aaa4f5677ede66dfa3c6e9e | [
"Unlicense"
] | null | null | null | ; ----------------
; Phantoon hijacks
; ----------------
{
; Intro
if !FEATURE_PAL
org $A7D4DD
else
org $A7D4A9
endif
JSL hook_phantoon_init
NOP
BNE $3D
; 1st pattern
if !FEATURE_PAL
org $A7D5DA
else
org $A7D5A6
endif
JSL hook_phantoon_1st_rng
BRA $10
; 2nd pattern
if !FEATURE_PAL
org $A7D0B0
else
org $A7D07C
endif
JSL hook_phantoon_2nd_rng
BRA $0F
; Phantoon eye close timer
if !FEATURE_PAL
org $A7D098
else
org $A7D064
endif
JSL hook_phantoon_eyeclose
; Phantoon flame pattern
if !FEATURE_PAL
org $A7D00A
else
org $A7CFD6
endif
JSL hook_phantoon_flame_pattern
}
; --------------
; Botwoon hijack
; --------------
{
if !FEATURE_PAL
org $B39953
else
org $B39943
endif
; $B3:9943 22 11 81 80 JSL $808111[$80:8111]
JSL hook_botwoon_rng
}
; ---------------
; Draygon hijacks
; ---------------
{
if !FEATURE_PAL
org $A58AEC
else
org $A58ADC
endif
JSR hook_draygon_rng_left
if !FEATURE_PAL
org $A589AD
else
org $A5899D
endif
JSR hook_draygon_rng_right
}
; ----------------
; Crocomire hijack
; ----------------
{
if !FEATURE_PAL
org $A48763
else
org $A48753
endif
JSR hook_crocomire_rng
}
; -------------
; Kraid hijacks
; -------------
{
if !FEATURE_PAL
org $A7BDF3
else
org $A7BDBF
endif
JSR hook_kraid_rng
if !FEATURE_PAL
org $A7AA7F
else
org $A7AA69
endif
JMP kraid_intro_skip
kraid_intro_skip_return:
}
; -----------------
; "Set rng" hijacks
; -----------------
{
; $A3:AB0C A9 25 00 LDA #$0025
; $A3:AB0F 8D E5 05 STA $05E5 [$7E:05E5]
; $A3:AB12 22 11 81 80 JSL $808111[$80:8111]
if !FEATURE_PAL
org $A3AB2E
else
org $A3AB12
endif
JSL hook_hopper_set_rng
; $A2:B588 A9 11 00 LDA #$0011
; $A2:B58B 8D E5 05 STA $05E5 [$7E:05E5]
if !FEATURE_PAL
org $A2B5A0
else
org $A2B588
endif
JSL hook_lavarocks_set_rng
NOP #2
; $A8:B798 A9 17 00 LDA #$0017
; $A8:B79B 8D E5 05 STA $05E5 [$7E:05E5]
if !FEATURE_PAL
org $A8B7A8
else
org $A8B798
endif
JSL hook_beetom_set_rng
NOP #2
}
; -----
; Hooks
; -----
org $83B000
print pc, " rng start"
hook_hopper_set_rng:
{
LDA #$0001 : STA !ram_room_has_set_rng
JML $808111
}
hook_lavarocks_set_rng:
{
LDA #$0001 : STA !ram_room_has_set_rng
LDA #$0011 : STA !CACHED_RANDOM_NUMBER
RTL
}
hook_beetom_set_rng:
{
LDA #$0001 : STA !ram_room_has_set_rng
LDA #$0017 : STA !CACHED_RANDOM_NUMBER
RTL
}
; Patch to the following code (which waits a few frames
; before spawning flames in a circle)
; $A7:D4A9 DE B0 0F DEC $0FB0,x[$7E:0FB0] ; decrement timer
; $A7:D4AC F0 02 BEQ $02 [$D4B0] ; if zero, proceed
; $A7:D4AE 10 3D BPL $3D [$D4ED] ; else, return
hook_phantoon_init:
{
LDA !sram_cutscenes
AND !CUTSCENE_FAST_PHANTOON
BNE .skip_cutscene
DEC $0FB0,X
RTL
.skip_cutscene:
; get rid of the return address
PLA ; pop 2 bytes
PHP ; push 1
PLA ; pop 2 (for a total of 3 bytes popped)
; start boss music & fade-in animation
if !FEATURE_PAL
JML $A7D543
else
JML $A7D50F
endif
}
; Table of Phantoon pattern durations & directions
; bit 0 is direction, remaining bits are duration
; Note that later entries in the table will tend to occur slightly more often.
phan_pattern_table:
dw $003C<<1|1 ; fast left
dw $003C<<1|0 ; fast right
dw $0168<<1|1 ; mid left
dw $0168<<1|0 ; mid right
dw $02D0<<1|1 ; slow left
dw $02D0<<1|0 ; slow right
; Patch to the following code, to determine Phantoon's first-round direction and pattern
; $A7:D5A6 AD B6 05 LDA $05B6 [$7E:05B6] ; Frame counter
; $A7:D5A9 4A LSR A
; $A7:D5AA 29 03 00 AND #$0003
; $A7:D5AD 0A ASL A
; $A7:D5AE A8 TAY
; $A7:D5AF B9 53 CD LDA $CD53,y[$A7:CD59] ; Number of frames to figure-8
; $A7:D5B2 8D E8 0F STA $0FE8 [$7E:0FE8]
; $A7:D5B5 22 11 81 80 JSL $808111[$80:8111] ; RNG
; $A7:D5B9 89 01 00 BIT #$0001 ; Sets Z for left pattern, !Z for right
hook_phantoon_1st_rng:
{
LDA !ram_phantoon_rng_round_1
; If set to all-on or all-off, don't mess with RNG.
BEQ .no_manip
CMP #$003F
BNE choose_phantoon_pattern
.no_manip:
LDA !FRAME_COUNTER
LSR A
AND #$0003
ASL A
TAY
if !FEATURE_PAL
LDA $CD87,Y
else
LDA $CD53,Y
endif
STA $0FE8
JSL $808111
BIT #$0001
RTL
}
; Patch to the following code, to determine Phantoon's second-round direction and pattern
; Also affects patterns during Phantoon's invisible phase
; $A7:D07C 22 11 81 80 JSL $808111[$80:8111]
; $A7:D080 29 07 00 AND #$0007
; $A7:D083 0A ASL A
; $A7:D084 A8 TAY
; $A7:D085 B9 53 CD LDA $CD53,y[$A7:CD5B]
; $A7:D088 8D E8 0F STA $0FE8 [$7E:0FE8]
; $A7:D08B AD B6 05 LDA $05B6 [$7E:05B6]
; $A7:D08E 89 01 00 BIT #$0001
hook_phantoon_2nd_rng:
{
LDA !ram_phantoon_rng_round_2
; If set to all-on or all-off, don't mess with RNG.
BEQ .no_manip
CMP #$003F
BNE choose_phantoon_pattern
.no_manip:
JSL $808111
AND #$0007
ASL A
TAY
if !FEATURE_PAL
LDA $CD87,Y
else
LDA $CD53,Y
endif
STA $0FE8
; Intentional fallthrough to invert logic
}
hook_phantoon_invert:
{
LDA !ram_phantoon_rng_inverted : BEQ .vanilla_inverted
CMP #$0001 : BEQ .inverted
CMP #$0002 : BEQ .not_inverted
; Random
LDA !CACHED_RANDOM_NUMBER : BIT #$0080
RTL
.inverted
LDA #$0000 : BIT #$0001
RTL
.not_inverted
LDA #$0001 : BIT #$0001
RTL
.vanilla_inverted
LDA !FRAME_COUNTER : BIT #$0001
RTL
}
; Selects a Phantoon pattern from a bitmask (passed in A).
choose_phantoon_pattern:
{
PHX ; push enemy index
PHA ; push pattern mask
; get random number in range 0-7
JSL $808111
AND #$0007
TAX
; play a game of eeny-meeny-miny-moe with the enabled patterns
; X = number of enabled patterns to find before stopping
; Y = index in phan_pattern_table of pattern currently being checked
; A = bitmask of enabled patterns
.reload:
LDA $01,S ; reload pattern mask
LDY #$0006 ; number of patterns (decremented immediately to index of last pattern)
.loop:
DEY
LSR
BCC .skip
; Pattern index Y is enabled
DEX ; is this the last one?
BMI .done
BRA .loop ; no, keep looping
.skip:
; Pattern Y is not enabled, try the next pattern
BEQ .reload ; if we've tried all the patterns, start over
BRA .loop
.done:
; We've found the pattern to use.
PLA ; we don't need the pattern mask anymore
TYA : ASL : TAX
LDA.l phan_pattern_table,X
PLX ; pop enemy index
; Check if Phantoon is in the round 2 AI state
LDY $0FB2
if !FEATURE_PAL
CPY #$D716
else
CPY #$D6E2
endif
BNE .round1
; Save the pattern timer, check the direction,
; and set Phantoon's starting point and pattern index.
LSR
STA $0FE8
BCS .round2left
; Right pattern
LDA #$0088
LDY #$00D0
BRA .round2done
.round2left
LDA #$018F
LDY #$0030
.round2done
STA $0FA8 ; Index into figure-8 movement table
STY $0F7A ; X position
LDA #$0060
STA $0F7E ; Y position
BRA hook_phantoon_invert
.round1
; Save the pattern timer and check the direction
LSR
STA $0FE8
BCS .round1left
; Round 1 right pattern
SEP #$02
RTL
.round1left:
REP #$02
RTL
}
hook_phantoon_eyeclose:
{
LDA !ram_phantoon_rng_eyeclose : BEQ .no_manip
DEC : ASL ; return with 0-slow, 2-mid, 4-fast
RTL
.no_manip
LDA !CACHED_RANDOM_NUMBER
AND #$0007 : ASL ; overwritten code
RTL
}
hook_phantoon_flame_pattern:
{
JSL $808111 ; Trying to preserve the number of RNG calls being done in the frame
LDA !ram_phantoon_rng_flames : TAY
LDA !ram_phantoon_rng_next_flames : STA !ram_phantoon_rng_flames
TYA : STA !ram_phantoon_rng_next_flames : BEQ .no_manip
DEC
RTL
.no_manip
LDA !CACHED_RANDOM_NUMBER
RTL
}
hook_botwoon_rng:
{
JSL $808111 ; Trying to preserve the number of RNG calls being done in the frame
LDA !ram_botwoon_rng : BEQ .no_manip
RTL
.no_manip
LDA !CACHED_RANDOM_NUMBER
RTL
}
print pc, " rng end"
warnpc $83B400 ; custompresets.asm
org $A4F700
print pc, " crocomire rng start"
hook_crocomire_rng:
{
LDA !ram_crocomire_rng : BEQ .no_manip
DEC : BEQ .step
LDA #$0000 ; return with <400 for swipe
RTS
.step
LDA #$0400 ; return with 400+ for step
RTS
.no_manip
LDA !CACHED_RANDOM_NUMBER
RTS
}
print pc, " crocomire rng end"
org $A5FA00
print pc, " draygon rng start"
hook_draygon_rng_left:
{
LDA !ram_draygon_rng_left : BEQ .no_manip
DEC ; return with 1-swoop or 0-goop
RTS
.no_manip
LDA !CACHED_RANDOM_NUMBER
RTS
}
hook_draygon_rng_right:
{
LDA !ram_draygon_rng_right : BEQ .no_manip
DEC ; return with 1-swoop or 0-goop
RTS
.no_manip
LDA !CACHED_RANDOM_NUMBER
RTS
}
print pc, " draygon rng end"
; This is actually for preset support instead of RNG
; Keep Ceres Ridley enemy alive even if the main boss flag is set
if !FEATURE_PAL
org $A6A10C
else
org $A6A0FC
endif
LSR : BCC $0F
CPX #$0006 : BEQ $0A
LDA $0F86
if !FEATURE_PAL
org $A6A302
else
org $A6A2F2
endif
JMP ceres_ridley_draw_metroid
if !FEATURE_PAL
org $A6A371
else
org $A6A361
endif
dw ridley_init_hook
; Fix ceres ridley door instruction list to keep door visible when skipping ridley fight
if !FEATURE_PAL
org $A6F533
dw $F64F, ridley_ceres_door_original_instructions
else
org $A6F55C
dw $F678, ridley_ceres_door_original_instructions
endif
dw $80ED, ridley_ceres_door_escape_instructions
; Lock ceres ridley door if timer not started or if boss not dead
if !FEATURE_PAL
org $A6F641
else
org $A6F66A
endif
LDA $0943 : BEQ $F6
LDA $7ED82E
org $A6FEC0
print pc, " ridley rng start"
ridley_init_hook:
{
LDA $079B : CMP #$E0B5 : BNE .continue
LDA $7ED82E : BIT #$0001 : BEQ .continue
; Ceres Ridley is already dead, so skip to the escape
; We do need to mark Ceres Ridley alive
; to keep the door locked until the timer starts
AND #$FFFE : STA $7ED82E
; Clear out the room main asm so it doesn't also trigger the escape
STZ $07DF
; Set up the escape timer routine
LDA #$0001 : STA $093F
LDA #$E0E6 : STA $0A5A
; Jump to the escape
if !FEATURE_PAL
LDA #$AB47
else
LDA #$AB37
endif
STA $0FA8
JMP ($0FA8)
.continue
if !FEATURE_PAL
LDA #$A387
else
LDA #$A377
endif
STA $0FA8
JMP ($0FA8)
}
ceres_ridley_draw_metroid:
{
LDA $7ED82E : BIT #$0001 : BNE .end
LDA $093F : BNE .end
if !FEATURE_PAL
JSR $BF2A
else
JSR $BF1A
endif
.end
if !FEATURE_PAL
JMP $A30A
else
JMP $A2FA
endif
}
ridley_ceres_door_original_instructions:
if !FEATURE_PAL
dw $F67D
dw #$0002, $F9EA
dw $F641, $F533
dw $F687
dw $80ED, $F56F
else
dw $F6A6
dw #$0002, $FA13
dw $F66A, $F55C
dw $F6B0
dw $80ED, $F598
endif
ridley_ceres_door_escape_instructions:
if !FEATURE_PAL
dw $F687
dw #$0002, $F9EA
dw $F641, $F533
dw $80ED, $F56F
else
dw $F6B0
dw #$0002, $FA13
dw $F66A, $F55C
dw $80ED, $F598
endif
print pc, " ridley rng end"
org $A7FFB6
print pc, " kraid rng start"
hook_kraid_rng:
{
LDA !ram_kraid_rng : BEQ .no_manip
DEC : DEC ; return -1 (laggy) or 0 (laggier)
RTS
.no_manip
LDA !CACHED_RANDOM_NUMBER
RTS
}
kraid_intro_skip:
LDA !sram_cutscenes : AND !CUTSCENE_FAST_KRAID : BEQ .noSkip
LDA #$0001
JMP kraid_intro_skip_return
.noSkip
if !FEATURE_PAL
LDA #$00FA
else
LDA #$012C
endif
JMP kraid_intro_skip_return
print pc, " kraid rng end"
| 18.076453 | 89 | 0.645576 |
26591042a7360a93572b43865e6016d6880988a4 | 3,052 | swift | Swift | FlickrApp/FullScreenImageViewController.swift | 54lihaoxin/flickr_app | 4ce5991658b0836ee3e294cc2d5202c6d61443a6 | [
"BSD-3-Clause"
] | null | null | null | FlickrApp/FullScreenImageViewController.swift | 54lihaoxin/flickr_app | 4ce5991658b0836ee3e294cc2d5202c6d61443a6 | [
"BSD-3-Clause"
] | null | null | null | FlickrApp/FullScreenImageViewController.swift | 54lihaoxin/flickr_app | 4ce5991658b0836ee3e294cc2d5202c6d61443a6 | [
"BSD-3-Clause"
] | null | null | null | //
// FullScreenImageViewController.swift
// FlickrApp
//
// Created by Haoxin Li on 3/2/19.
// Copyright © 2019 Haoxin Li. All rights reserved.
//
import UIKit
final class FullScreenImageViewController: UIViewController {
private enum Dimension {
static let dismissButtonDimension: CGFloat = 44
static let dismissButtonPadding: CGFloat = 32
}
private enum Font {
static let dismissButtonFont = UIFont.systemFont(ofSize: 32)
}
private let imageURL: URL
private lazy var dismissButton: UIButton = {
let button = UIButton(frame: .zero)
button.addTarget(self, action: #selector(dismissView), for: .touchUpInside)
button.titleLabel?.font = Font.dismissButtonFont
button.setTitle("x", for: .normal)
return button
}()
private lazy var imageView: UIImageView = {
let imageView = UIImageView(frame: .zero)
imageView.contentMode = .scaleAspectFit
return imageView
}()
required init?(coder aDecoder: NSCoder) {
fatalError()
}
init(imageURL: URL) {
self.imageURL = imageURL
super.init(nibName: nil, bundle: nil)
modalPresentationStyle = .fullScreen
modalTransitionStyle = .crossDissolve
}
override func viewDidLoad() {
super.viewDidLoad()
setUp()
imageView.loadImage(fromURL: imageURL)
}
static func presentImage(imageURL: URL, fromViewController presentingViewController: UIViewController) {
presentingViewController.present(FullScreenImageViewController(imageURL: imageURL), animated: true, completion: nil)
}
}
// MARK: - private
private extension FullScreenImageViewController {
func setUp() {
setUpImageView()
setUpDismissButton()
}
func setUpImageView() {
view.addSubview(imageView)
imageView.translatesAutoresizingMaskIntoConstraints = false
imageView.topAnchor.constraint(equalTo: view.topAnchor).isActive = true
imageView.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true
imageView.trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true
imageView.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true
}
func setUpDismissButton() {
view.addSubview(dismissButton)
dismissButton.translatesAutoresizingMaskIntoConstraints = false
dismissButton.widthAnchor.constraint(equalToConstant: Dimension.dismissButtonDimension).isActive = true
dismissButton.heightAnchor.constraint(equalToConstant: Dimension.dismissButtonDimension).isActive = true
dismissButton.trailingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.trailingAnchor, constant: -Dimension.dismissButtonPadding).isActive = true
dismissButton.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor, constant: -Dimension.dismissButtonPadding).isActive = true
}
@objc func dismissView() {
dismiss(animated: true, completion: nil)
}
}
| 33.911111 | 156 | 0.708716 |
bcb6c30e62d92cc962398193bc651ffff6a6b0a5 | 4,209 | js | JavaScript | src/components/textField/styles.js | jampack/ice-cube | 1e02e66e21e4338cb9a43abe38adc2cb998fadb3 | [
"MIT"
] | 1 | 2021-09-03T12:11:46.000Z | 2021-09-03T12:11:46.000Z | src/components/textField/styles.js | jampack/ice-cube | 1e02e66e21e4338cb9a43abe38adc2cb998fadb3 | [
"MIT"
] | 10 | 2021-07-14T17:29:05.000Z | 2022-01-02T14:35:26.000Z | src/components/textField/styles.js | jampack/ice-cube | 1e02e66e21e4338cb9a43abe38adc2cb998fadb3 | [
"MIT"
] | null | null | null | import theme from 'styled-theming';
import styled from 'styled-components';
import {
fontColor,
placeholderColor,
floatingLabelBackgroundColor,
labelTransform,
labelFontColor,
borderColor,
calcBorderUnderColor,
} from '../../lib/CommonStyles';
const focusedBorderColor = theme('mode', {
dark: ({ theme: { textField } }) => textField.focusedBorderColor.dark,
light: ({ theme: { textField } }) => textField.focusedBorderColor.light,
});
export const Input = styled.input`
box-sizing: border-box;
`;
export const BorderUnder = styled.span`
position: absolute;
box-sizing: border-box;
bottom: 0;
left: 0;
width: 0;
height: 1px;
`;
export const LabelUnder = styled.span`
font-size: ${({ theme: { textField } }) => textField.labelFontSize};
font-family: ${({ theme: { textField } }) => textField.labelFontFamily};
font-weight: ${({ theme: { textField } }) => textField.labelFontWeight};
color: ${(p) => labelFontColor('textField', p)};
`;
export const Label = styled.label`
display: block;
padding-left: ${({ theme: { textField } }) => textField.defaultLabelPaddingLeft};
margin-bottom: 5px;
font-size: ${({ theme: { textField } }) => textField.labelFontSize};
font-family: ${({ theme: { textField } }) => textField.labelFontFamily};
font-weight: ${({ theme: { textField } }) => textField.labelFontWeight};
color: ${(p) => labelFontColor('textField', p)};
`;
export const TextField = styled.div`
position: relative;
width: ${({ block }) => (block ? '100%' : 'max-content')};
${Input} {
height: ${({ theme: { textField } }) => textField.height};
width: ${({ theme: { textField }, ...p }) => (p.block ? '100%' : textField.width)};
padding: ${({ theme: { textField } }) => `${textField.paddingY} ${textField.paddingX}`};
font-size: ${({ theme: { textField } }) => textField.fontSize};
font-family: ${({ theme: { textField } }) => textField.fontFamily};
font-weight: ${({ theme: { textField } }) => textField.fontWeight};
color: ${(p) => (p.disabled ? p.theme.textField.disabledColor : fontColor('textField', p))};
background-color: ${({ theme: { textField }, ...p }) => (p.filled ? '#f0f0f0' : textField.backgroundColor)};
border: ${(p) =>
p.underlined || p.filled
? 'none'
: `${p.theme.textField.borderWidth} solid ${
p.disabled ? p.theme.textField.disabledColor : borderColor('textField', p)
}`};
border-bottom: ${(p) =>
p.underlined || p.filled ? `${p.theme.textField.borderWidth} solid ${borderColor('textField', p)}` : ''};
border-radius: ${({ theme: { textField }, ...p }) => (p.underlined || p.filled ? '0' : textField.borderRadius)};
outline: none;
::placeholder {
color: ${(p) => (p.outlined || p.underlined || p.filled ? 'transparent' : placeholderColor('textField', p))};
opacity: 1; /* Firefox */
}
}
${LabelUnder} {
display: flex;
position: absolute;
margin: ${({ theme: { textField } }) => `${textField.floatingLabelMarginTop} 0`};
padding: ${({ theme: { textField } }) => `0 ${textField.floatingLabelPaddingX}`};
align-items: center;
top: 0;
left: 0;
transition: all 0.3s;
transform-origin: 0 0;
background: none;
pointer-events: none;
}
${/* sc-sel */ Input}.valid + ${/* sc-sel */ LabelUnder},
${/* sc-sel */ Input}:focus + ${/* sc-sel */ LabelUnder} {
transform: ${(p) => labelTransform('textField', p)};
background: ${(p) => floatingLabelBackgroundColor('textField', p)};
left: ${({ theme: { textField } }) => textField.floatingLabelMarginLeft};
padding: 0 3px;
}
${/* sc-sel */ Input}:focus {
&::placeholder {
color: ${(p) => placeholderColor('textField', p)};
}
~ ${BorderUnder} {
width: 100%;
transition: 0.3s width linear;
height: 0;
border: ${(p) => (p.underlined || p.filled ? `1px solid ${calcBorderUnderColor('textField', p)}` : 'none')};
}
}
${/* sc-sel */ Input}:focus {
color: #284b63;
border-color: ${(p) => (!p.underlined && !p.filled ? focusedBorderColor : '')};
}
${/* sc-sel */ Input}:focus + ${/* sc-sel */ LabelUnder} {
color: #284b63;
}
`;
| 33.404762 | 116 | 0.597054 |
0a8ddcf00115f7c3e9ad0382376499688a9d83bd | 273 | sql | SQL | posda/posdatools/queries/sql/CloseImportEvent.sql | UAMS-DBMI/PosdaTools | 7d33605da1b88e4787a1368dbecaffda1df95e5b | [
"Apache-2.0"
] | 6 | 2019-01-17T15:47:44.000Z | 2022-02-02T16:47:25.000Z | posda/posdatools/queries/sql/CloseImportEvent.sql | UAMS-DBMI/PosdaTools | 7d33605da1b88e4787a1368dbecaffda1df95e5b | [
"Apache-2.0"
] | 23 | 2016-06-08T21:51:36.000Z | 2022-03-02T08:11:44.000Z | posda/posdatools/queries/sql/CloseImportEvent.sql | UAMS-DBMI/PosdaTools | 7d33605da1b88e4787a1368dbecaffda1df95e5b | [
"Apache-2.0"
] | null | null | null | -- Name: CloseImportEvent
-- Schema: posda_files
-- Columns: []
-- Args: ['export_event_id']
-- Tags: ['export_event']
-- Description: Enter close import_event in export_event
--
update export_event set
destination_import_event_closed = true
where
export_event_id = ? | 22.75 | 57 | 0.739927 |
4b3e727c120bec54a395c41752be317ff710375b | 3,664 | swift | Swift | Sources/GEOSwift/GEOS/WKTConvertible.swift | andreacremaschi/GEOS.swift | 8a993d6c2aa3ed4eb19ffc9456a19d1da188c7af | [
"MIT"
] | null | null | null | Sources/GEOSwift/GEOS/WKTConvertible.swift | andreacremaschi/GEOS.swift | 8a993d6c2aa3ed4eb19ffc9456a19d1da188c7af | [
"MIT"
] | null | null | null | Sources/GEOSwift/GEOS/WKTConvertible.swift | andreacremaschi/GEOS.swift | 8a993d6c2aa3ed4eb19ffc9456a19d1da188c7af | [
"MIT"
] | null | null | null | import Foundation
import geos
public protocol WKTConvertible {
/// Serializes the `WKTConvertible` to a WKT string representation using the geos-default configuration
/// options for `trim` and `roundingPrecision`.
/// - Returns: A WKT string representation of the `WKTConvertible`.
func wkt() throws -> String
/// Serializes the `WKTConvertible` to a WKT string representation
/// - Parameters:
/// - trim: If `true`, digits after the decimal point that are unnecessary for lossless round-tripping
/// are removed.
/// - roundingPrecision: If `trim` is `true`, determines the maximum number of digits after the decimal
/// point. If `trim` is false, determines the number of digits after the decimal point. Pass a
/// negative value to default to the rounding precision determined by the underlying precision model.
/// - Returns: A WKT string representation of the `WKTConvertible`.
func wkt(trim: Bool, roundingPrecision: Int32) throws -> String
}
protocol WKTConvertibleInternal: WKTConvertible, GEOSObjectConvertible {}
extension WKTConvertibleInternal {
public func wkt() throws -> String {
let context = try GEOSContext()
let writer = try WKTWriter(
context: context,
trim: .geosDefault,
roundingPrecision: .geosDefault)
return try writer.write(self)
}
public func wkt(trim: Bool, roundingPrecision: Int32) throws -> String {
let context = try GEOSContext()
let writer = try WKTWriter(
context: context,
trim: .custom(trim),
roundingPrecision: .custom(roundingPrecision))
return try writer.write(self)
}
}
extension Point: WKTConvertible, WKTConvertibleInternal {}
extension LineString: WKTConvertible, WKTConvertibleInternal {}
extension Polygon.LinearRing: WKTConvertible, WKTConvertibleInternal {}
extension Polygon: WKTConvertible, WKTConvertibleInternal {}
extension MultiPoint: WKTConvertible, WKTConvertibleInternal {}
extension MultiLineString: WKTConvertible, WKTConvertibleInternal {}
extension MultiPolygon: WKTConvertible, WKTConvertibleInternal {}
extension GeometryCollection: WKTConvertible, WKTConvertibleInternal {}
extension Geometry: WKTConvertible, WKTConvertibleInternal {}
private final class WKTWriter {
private let context: GEOSContext
private let writer: OpaquePointer
init(context: GEOSContext,
trim: Trim,
roundingPrecision: RoundingPrecision) throws {
guard let writer = GEOSWKTWriter_create_r(context.handle) else {
throw GEOSError.libraryError(errorMessages: context.errors)
}
self.context = context
self.writer = writer
if case let .custom(value) = trim {
GEOSWKTWriter_setTrim_r(context.handle, writer, value ? 1 : 0)
}
if case let .custom(value) = roundingPrecision {
GEOSWKTWriter_setRoundingPrecision_r(context.handle, writer, value)
}
}
deinit {
GEOSWKTWriter_destroy_r(context.handle, writer)
}
func write(_ geometry: GEOSObjectConvertible) throws -> String {
let geosObject = try geometry.geosObject(with: context)
guard let chars = GEOSWKTWriter_write_r(context.handle, writer, geosObject.pointer) else {
throw GEOSError.libraryError(errorMessages: context.errors)
}
defer { chars.deallocate() }
return String(cString: chars)
}
enum Trim {
case geosDefault
case custom(Bool)
}
enum RoundingPrecision {
case geosDefault
case custom(Int32)
}
}
| 37.387755 | 109 | 0.691321 |
9becaa58ddd4450f75fef4aa32b21f041029529d | 1,280 | swift | Swift | FunctionalReactiveAwesome/API.swift | ashfurrow/FunctionalReactiveAwesome | b9166f3c4c89ba055fb729b2fd7f928353f8e4f9 | [
"MIT"
] | 62 | 2015-06-12T06:24:06.000Z | 2021-04-18T01:29:59.000Z | FunctionalReactiveAwesome/API.swift | ashfurrow/FunctionalReactiveAwesome | b9166f3c4c89ba055fb729b2fd7f928353f8e4f9 | [
"MIT"
] | null | null | null | FunctionalReactiveAwesome/API.swift | ashfurrow/FunctionalReactiveAwesome | b9166f3c4c89ba055fb729b2fd7f928353f8e4f9 | [
"MIT"
] | 4 | 2015-09-04T10:42:53.000Z | 2016-04-17T00:38:10.000Z | import Foundation
import Moya
import RxSwift
enum API {
case Signup(email: String, password: String)
case Friends
}
extension API: MoyaPath, MoyaTarget {
var path: String {
switch self {
case .Signup(let email, let password):
return "/signup"
case .Friends:
return "/friends"
}
}
var baseURL: NSURL {
return NSURL(string: "http://example.com")!
}
var method: Moya.Method {
switch self {
case .Signup(_, _):
return .POST
default:
return .GET
}
}
var parameters: [String: AnyObject] {
return [:]
}
var sampleData: NSData {
switch self{
case .Signup(let email, _):
return ("Welcome, \(email)!" as NSString).dataUsingEncoding(NSUTF8StringEncoding)!
case .Friends:
return friendsData
}
}
}
let stubbedBehavior: MoyaProvider<API>.MoyaStubbedBehavior = { target -> Moya.StubbedBehavior in
return .Delayed(seconds: 1)
}
let api = RxMoyaProvider<API>(stubResponses: true, stubBehavior: stubbedBehavior)
let friendsData = NSArray(array: ["Alloy", "Laura", "Orta", "Sarah"]).componentsJoinedByString(",").dataUsingEncoding(NSUTF8StringEncoding)!
| 23.703704 | 140 | 0.602344 |
5cfe5d6cac2bb2f45568f25d04dc3acb2acb8303 | 420 | css | CSS | docs/css/master.css | blakelucey/pyziabm | b4e62aa036233e58d7b44b654c375baf57ffc2d3 | [
"BSD-3-Clause"
] | 35 | 2017-11-27T13:10:42.000Z | 2021-09-13T13:39:55.000Z | docs/css/master.css | blakelucey/pyziabm | b4e62aa036233e58d7b44b654c375baf57ffc2d3 | [
"BSD-3-Clause"
] | 2 | 2017-10-10T20:28:49.000Z | 2021-09-06T14:59:13.000Z | docs/css/master.css | blakelucey/pyziabm | b4e62aa036233e58d7b44b654c375baf57ffc2d3 | [
"BSD-3-Clause"
] | 23 | 2017-08-28T18:29:09.000Z | 2022-03-20T01:59:26.000Z | body {
font-family: 'Montserrat';
}
header {
height: 100px;
background-color: #1a18ce;
border-bottom: 2px #2aafea solid;
padding: 10px;
margin-bottom: 0;
}
header h1 {
margin: 0px;
color: white;
font-size: xx-large;
text-align: center;
}
header h3 {
margin: 10px;
color: white;
font-size: large;
text-align: center;
}
h2 {
color: black;
font-size: x-large;
text-align: left;
}
| 13.125 | 36 | 0.628571 |
dd6a29cf085de89a1078d72a130fc8ff97ceb89d | 1,883 | go | Go | src/assorted/interface_value_type.go | devak23/go | 19023b6a412c97824362e8a600062f7869f32fb5 | [
"MIT"
] | null | null | null | src/assorted/interface_value_type.go | devak23/go | 19023b6a412c97824362e8a600062f7869f32fb5 | [
"MIT"
] | null | null | null | src/assorted/interface_value_type.go | devak23/go | 19023b6a412c97824362e8a600062f7869f32fb5 | [
"MIT"
] | null | null | null | // How do we know what specific object is being held by the interface pointer?
package assorted
import (
"fmt"
"strconv"
)
// define an object
type Human struct {
name string
age int
}
// define an empty interface (which is implemented by everyone!)
type Element interface{}
// define a custom type called List which is nothing but an array of
// objects that implement the Element interface
type List []Element
// define a toString() sorta method for the object
func (h Human) String() string {
return "(name: " + h.name + "- age: " + strconv.Itoa(h.age) + " years)"
}
// the main function
func InterfaceValueTypeMain() {
list := make(List, 3)
list[0] = 1 // an int
list[1] = "Hello" // a string
list[2] = Human{"Dennis", 37}
determineTypeUsingIf(list)
determineTypeUsingSwitch(list)
}
func determineTypeUsingIf(list List) {
fmt.Println("---------------USING IF-------------")
for index, element := range list {
if value, ok := element.(int); ok {
fmt.Printf("list[%d] is an int and it's value is %d\n", index, value)
} else if value, ok := element.(string); ok {
fmt.Printf("list[%d] is a string and it's value is %s\n", index, value)
} else if value, ok := element.(Human); ok {
fmt.Printf("list[%d] is a Human object and it's value is %s\n", index, value)
} else {
fmt.Printf("list[%d] is a weird one!", index)
}
}
}
func determineTypeUsingSwitch(list List) {
fmt.Println("---------------USING SWITCH-------------")
for index, element := range list {
switch value := element.(type) {
case int:
fmt.Printf("list[%d] is an int and it's value is %d\n", index, value)
case string:
fmt.Printf("list[%d] is a string and it's value is %s\n", index, value)
case Human:
fmt.Printf("list[%d] is a Human object and it's value is %s\n", index, value)
default:
fmt.Printf("list[%d] is a weird one!", index)
}
}
}
| 27.691176 | 80 | 0.640998 |
22b72053e04ccc5fa1bed1e55b0477ec72b0eb1e | 279 | lua | Lua | MMOCoreORB/bin/scripts/object/custom_content/tangible/item/beast/converted_kliknik_decoration.lua | V-Fib/FlurryClone | 40e0ca7245ec31b3815eb6459329fd9e70f88936 | [
"Zlib",
"OpenSSL"
] | 18 | 2017-02-09T15:36:05.000Z | 2021-12-21T04:22:15.000Z | MMOCoreORB/bin/scripts/object/custom_content/tangible/item/beast/converted_kliknik_decoration.lua | V-Fib/FlurryClone | 40e0ca7245ec31b3815eb6459329fd9e70f88936 | [
"Zlib",
"OpenSSL"
] | 61 | 2016-12-30T21:51:10.000Z | 2021-12-10T20:25:56.000Z | MMOCoreORB/bin/scripts/object/custom_content/tangible/item/beast/converted_kliknik_decoration.lua | V-Fib/FlurryClone | 40e0ca7245ec31b3815eb6459329fd9e70f88936 | [
"Zlib",
"OpenSSL"
] | 71 | 2017-01-01T05:34:38.000Z | 2022-03-29T01:04:00.000Z | object_tangible_item_beast_converted_kliknik_decoration = object_tangible_item_beast_shared_converted_kliknik_decoration:new {
}
ObjectTemplates:addTemplate(object_tangible_item_beast_converted_kliknik_decoration, "object/tangible/item/beast/converted_kliknik_decoration.iff")
| 46.5 | 147 | 0.913978 |
df9839c88c981c0aa33b8780d0bc86452bd5f103 | 2,589 | swift | Swift | Tests/CryptoTests/BCryptTests.swift | mcdappdev/crypto | fb45f5b0654b5af81943a2b3b2a31f76fdba8fa6 | [
"MIT"
] | null | null | null | Tests/CryptoTests/BCryptTests.swift | mcdappdev/crypto | fb45f5b0654b5af81943a2b3b2a31f76fdba8fa6 | [
"MIT"
] | null | null | null | Tests/CryptoTests/BCryptTests.swift | mcdappdev/crypto | fb45f5b0654b5af81943a2b3b2a31f76fdba8fa6 | [
"MIT"
] | null | null | null | import XCTest
@testable import Crypto
class BCryptTests: XCTestCase {
static let allTests = [
("testVersion", testVersion),
("testFail", testFail),
("testInvalidSalt", testInvalidSalt),
("testVerify", testVerify),
("testNotVerify", testNotVerify),
("testInvalidCost", testInvalidCost)
]
func testVersion() throws {
let digest = try BCrypt.hash("foo", cost: 6)
XCTAssert(digest.hasPrefix("$2b$06$"))
}
func testFail() throws {
let digest = try BCrypt.hash("foo", cost: 6)
let res = try BCrypt.verify("bar", created: digest)
XCTAssertEqual(res, false)
}
func testInvalidCost() throws {
XCTAssertThrowsError(try BCrypt.hash("foo", cost: 2))
}
func testInvalidSalt() throws {
do {
_ = try BCrypt.verify("", created: "foo")
XCTFail("Should have failed")
} catch let error as CryptoError {
print(error)
}
}
func testVerify() throws {
for (desired, message) in tests {
let result = try BCrypt.verify(message, created: desired)
XCTAssert(result, "\(message): did not match \(desired)")
}
}
func testNotVerify() throws {
let testCase = tests.first!
let message = "vapor_" + testCase.value
let shouldNotMatch = testCase.key
let result = try BCrypt.verify(message, created: shouldNotMatch)
XCTAssertFalse(result, "\(shouldNotMatch): matched \(message)")
}
}
let tests = [
"$2a$05$CCCCCCCCCCCCCCCCCCCCC.E5YPO9kmyuRGyh0XouQYb4YMJKvyOeW" : "U*U",
"$2a$05$CCCCCCCCCCCCCCCCCCCCC.VGOzA784oUp/Z0DY336zx7pLYAy0lwK" : "U*U*",
"$2a$05$XXXXXXXXXXXXXXXXXXXXXOAcXxm9kjPGEMsLznoKqmqw7tc8WCx4a" : "U*U*U",
"$2a$05$abcdefghijklmnopqrstuu5s2v8.iXieOjg/.AySBTTZIIVFJeBui" :
"0123456789abcdefghijklmnopqrstuvwxyz" +
"ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789" +
"chars after 72 are ignored",
"$2a$04$TI13sbmh3IHnmRepeEFoJOkVZWsn5S1O8QOwm8ZU5gNIpJog9pXZm" : "vapor",
"$2y$11$kHM/VXmCVsGXDGIVu9mD8eY/uEYI.Nva9sHgrLYuLzr0il28DDOGO" : "Vapor3",
"$2a$06$DCq7YPn5Rq63x1Lad4cll.TV4S6ytwfsfvkgY8jIucDrjc8deX1s." : "",
"$2a$06$m0CrhHm10qJ3lXRY.5zDGO3rS2KdeeWLuGmsfGlMfOxih58VYVfxe" : "a",
"$2a$06$If6bvum7DFjUnE9p2uDeDu0YHzrHM6tf.iqN8.yx.jNN1ILEf7h0i" : "abc",
"$2a$06$.rCVZVOThsIa97pEDOxvGuRRgzG64bvtJ0938xuqzv18d3ZpQhstC" : "abcdefghijklmnopqrstuvwxyz",
"$2a$06$fPIsBO8qRqkjj273rfaOI.HtSV9jLDpTbZn782DC6/t7qT67P6FfO" : "~!@#$%^&*() ~!@#$%^&*()PNBFRD",
]
| 36.985714 | 106 | 0.648127 |
8a369a2a5245aecd331504e5e38094972a53ac0b | 3,375 | rs | Rust | benches/generators/mod.rs | nharring-adjacent/drain-flow | dfb79f0a7019c2b21e78e9951b98d00a141f1bfa | [
"Apache-2.0"
] | null | null | null | benches/generators/mod.rs | nharring-adjacent/drain-flow | dfb79f0a7019c2b21e78e9951b98d00a141f1bfa | [
"Apache-2.0"
] | null | null | null | benches/generators/mod.rs | nharring-adjacent/drain-flow | dfb79f0a7019c2b21e78e9951b98d00a141f1bfa | [
"Apache-2.0"
] | null | null | null | // Copyright Nicholas Harring. All rights reserved.
//
// This program is free software: you can redistribute it and/or modify it under
// the terms of the Server Side Public License, version 1, as published by MongoDB, Inc.
// This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
// without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
// See the Server Side Public License for more details. You should have received a copy of the
// Server Side Public License along with this program.
// If not, see <http://www.mongodb.com/licensing/server-side-public-license>.
use std::collections::HashMap;
use anyhow::Error;
use serde_derive::{Deserialize, Serialize};
use tinytemplate::TinyTemplate;
#[derive(Serialize, Deserialize)]
pub(crate) enum RecordTemplate {
JSON(JSON),
NGINXAccess(NGINXAccess),
Qmail(Qmail),
Sendmail(Sendmail),
SlowQuery(SlowQuery),
Syslog(Syslog),
}
#[derive(Serialize, Deserialize)]
pub(crate) struct JSON {
pub event_type: String,
pub callsite: String,
pub app_name: String,
pub headers: HashMap<String, String>,
}
#[derive(Serialize, Deserialize)]
pub(crate) struct NGINXAccess {
pub ts: String,
pub client: String,
pub method: String,
pub status: usize,
pub bytes: usize,
pub path: String,
}
#[derive(Serialize, Deserialize)]
pub(crate) struct Qmail;
#[derive(Serialize, Deserialize)]
pub(crate) struct Sendmail {
pub ts: String,
pub remote: String,
pub status: usize,
pub message: String,
}
#[derive(Serialize, Deserialize)]
pub(crate) struct SlowQuery {
pub ts: String,
pub db: String,
pub op: String,
pub duration: String,
pub index: String,
pub scanned: usize,
pub found: usize,
}
#[derive(Serialize, Deserialize)]
pub(crate) struct Syslog {
pub ts: String,
pub facility: String,
pub severity: String,
}
const NGINX_TEMPLATE: &'static str = "{ foo }";
const QMAIL_TEMPLATE: &'static str = "{ foo }";
const SENDMAIL_TEMPLATE: &'static str =
"{ ts } Sent to { remote } with status: { status }, remote said { message }";
const SLOW_QUERY_TEMPLATE: &'static str = "{ foo }";
const SYSLOG_TEMPLATE: &'static str = "{ foo }";
pub(crate) struct LogGenerator<'a> {
tiny: TinyTemplate<'a>,
}
impl<'a> LogGenerator<'_> {
pub fn new() -> Result<Self, Error> {
let mut tt = TinyTemplate::new();
tt.add_template("nginx", NGINX_TEMPLATE)?;
tt.add_template("qmail", QMAIL_TEMPLATE)?;
tt.add_template("sendmail", SENDMAIL_TEMPLATE)?;
tt.add_template("slowquery", SLOW_QUERY_TEMPLATE)?;
tt.add_template("syslog", SYSLOG_TEMPLATE)?;
Ok(Self { tiny: tt })
}
pub(crate) fn make_record(&self, template: RecordTemplate) -> String {
match template {
RecordTemplate::JSON(j) => serde_json::to_string(&j).expect(""),
RecordTemplate::NGINXAccess(n) => self.tiny.render("nginx", &n).expect(""),
RecordTemplate::Qmail(q) => self.tiny.render("qmail", &q).expect(""),
RecordTemplate::Sendmail(s) => self.tiny.render("sendmail", &s).expect(""),
RecordTemplate::SlowQuery(sq) => self.tiny.render("slowquery", &sq).expect(""),
RecordTemplate::Syslog(s) => self.tiny.render("syslog", &s).expect(""),
}
}
}
| 31.542056 | 94 | 0.665185 |
7444676716b6d61520899f694b13de8644e6b573 | 9,148 | rs | Rust | src/lib.rs | animalsiknow/hyper-openssl | 2fa0c082f4088e75ef9601ddc2a0632b5693b586 | [
"Apache-2.0",
"MIT"
] | null | null | null | src/lib.rs | animalsiknow/hyper-openssl | 2fa0c082f4088e75ef9601ddc2a0632b5693b586 | [
"Apache-2.0",
"MIT"
] | null | null | null | src/lib.rs | animalsiknow/hyper-openssl | 2fa0c082f4088e75ef9601ddc2a0632b5693b586 | [
"Apache-2.0",
"MIT"
] | null | null | null | //! Hyper SSL support via OpenSSL.
#![warn(missing_docs)]
#![doc(html_root_url = "https://docs.rs/hyper-openssl/0.7")]
#![feature(type_alias_impl_trait)]
extern crate antidote;
extern crate bytes;
extern crate futures;
extern crate hyper;
extern crate linked_hash_set;
pub extern crate openssl;
extern crate tokio_io;
extern crate tokio_openssl;
#[macro_use]
extern crate lazy_static;
#[cfg(test)]
extern crate tokio;
use antidote::Mutex;
use bytes::{Buf, BufMut};
use hyper::client::connect::{Connect, Connected, Destination};
#[cfg(feature = "runtime")]
use hyper::client::HttpConnector;
use openssl::error::ErrorStack;
use openssl::ex_data::Index;
use openssl::ssl::{
ConnectConfiguration, Ssl, SslConnector, SslConnectorBuilder, SslMethod, SslSessionCacheMode,
};
use std::error::Error;
use std::fmt::Debug;
use std::future::Future;
use std::io;
use std::pin::Pin;
use std::sync::Arc;
use std::task::{Context, Poll};
use tokio_io::{AsyncRead, AsyncWrite};
use tokio_openssl::SslStream;
use cache::{SessionCache, SessionKey};
mod cache;
#[cfg(test)]
mod test;
lazy_static! {
// The unwrap here isn't great but this only fails on OOM
static ref KEY_INDEX: Index<Ssl, SessionKey> = Ssl::new_ex_index().unwrap();
}
#[derive(Clone)]
struct Inner {
ssl: SslConnector,
cache: Arc<Mutex<SessionCache>>,
callback: Option<
Arc<
dyn Fn(&mut ConnectConfiguration, &Destination) -> Result<(), ErrorStack> + Sync + Send,
>,
>,
}
impl Inner {
fn setup_ssl(&self, destination: &Destination) -> Result<ConnectConfiguration, ErrorStack> {
let mut conf = self.ssl.configure()?;
if let Some(ref callback) = self.callback {
callback(&mut conf, destination)?;
}
let key = SessionKey {
host: destination.host().to_string(),
port: destination.port().unwrap_or(443),
};
if let Some(session) = self.cache.lock().get(&key) {
unsafe {
conf.set_session(&session)?;
}
}
conf.set_ex_data(*KEY_INDEX, key);
Ok(conf)
}
}
/// A Connector using OpenSSL to support `http` and `https` schemes.
#[derive(Clone)]
pub struct HttpsConnector<T> {
http: T,
inner: Inner,
}
#[cfg(feature = "runtime")]
impl HttpsConnector<HttpConnector> {
/// Creates a a new `HttpsConnector` using default settings.
///
/// The Hyper `HttpConnector` is used to perform the TCP socket connection. ALPN is configured to support both
/// HTTP/2 and HTTP/1.1.
///
/// Requires the `runtime` Cargo feature.
pub fn new() -> Result<HttpsConnector<HttpConnector>, ErrorStack> {
let mut http = HttpConnector::new();
http.enforce_http(false);
let mut ssl = SslConnector::builder(SslMethod::tls())?;
// avoid unused_mut warnings when building against OpenSSL 1.0.1
ssl = ssl;
#[cfg(ossl102)]
ssl.set_alpn_protos(b"\x02h2\x08http/1.1")?;
HttpsConnector::with_connector(http, ssl)
}
}
impl<T> HttpsConnector<T>
where
T: Connect,
T::Transport: Debug + Sync + Send,
{
/// Creates a new `HttpsConnector`.
///
/// The session cache configuration of `ssl` will be overwritten.
pub fn with_connector(
http: T,
mut ssl: SslConnectorBuilder,
) -> Result<HttpsConnector<T>, ErrorStack> {
let cache = Arc::new(Mutex::new(SessionCache::new()));
ssl.set_session_cache_mode(SslSessionCacheMode::CLIENT);
ssl.set_new_session_callback({
let cache = cache.clone();
move |ssl, session| {
if let Some(key) = ssl.ex_data(*KEY_INDEX) {
cache.lock().insert(key.clone(), session);
}
}
});
ssl.set_remove_session_callback({
let cache = cache.clone();
move |_, session| cache.lock().remove(session)
});
Ok(HttpsConnector {
http,
inner: Inner {
ssl: ssl.build(),
cache,
callback: None,
},
})
}
/// Registers a callback which can customize the configuration of each connection.
pub fn set_callback<F>(&mut self, callback: F)
where
F: Fn(&mut ConnectConfiguration, &Destination) -> Result<(), ErrorStack>
+ 'static
+ Sync
+ Send,
{
self.inner.callback = Some(Arc::new(callback));
}
}
impl<T> Connect for HttpsConnector<T>
where
T: Connect,
T::Transport: Debug + Sync + Send,
{
type Transport = MaybeHttpsStream<T::Transport>;
type Error = Box<dyn Error + Sync + Send>;
type Future = ConnectFuture<T>;
fn connect(&self, destination: Destination) -> Self::Future {
let tls_setup = if destination.scheme() == "https" {
Some((self.inner.clone(), destination.clone()))
} else {
None
};
let conn = self.http.connect(destination);
// TODO: why does Connect requires its future to be Unpin? For now lets just pin box it.
Box::pin(connect::<T>(conn, tls_setup))
}
}
type ConnectFuture<T: Connect> = impl Future<
Output = Result<(MaybeHttpsStream<T::Transport>, Connected), Box<dyn Error + Sync + Send>>,
> + Unpin
+ Send;
async fn connect<T>(
conn: T::Future,
tls_setup: Option<(Inner, Destination)>,
) -> Result<(MaybeHttpsStream<T::Transport>, Connected), Box<dyn Error + Sync + Send>>
where
T: Connect,
T::Transport: Debug + Sync + Send,
{
let (stream, mut connected) = match conn.await {
Ok((stream, connected)) => (stream, connected),
Err(error) => return Err(error.into()),
};
match tls_setup {
Some((inner, destination)) => {
let ssl = inner.setup_ssl(&destination)?;
let handshake = tokio_openssl::connect(ssl, destination.host(), stream);
let stream = handshake.await?;
// avoid unused_mut warnings on OpenSSL 1.0.1
connected = connected;
#[cfg(ossl102)]
{
if let Some(b"h2") = stream.ssl().selected_alpn_protocol() {
connected = connected.negotiated_h2();
}
}
return Ok((MaybeHttpsStream::Https(stream), connected));
}
None => return Ok((MaybeHttpsStream::Http(stream), connected)),
}
}
/// A stream which may be wrapped with TLS.
pub enum MaybeHttpsStream<T> {
/// A raw HTTP stream.
Http(T),
/// An SSL-wrapped HTTP stream.
Https(SslStream<T>),
}
impl<T> AsyncRead for MaybeHttpsStream<T>
where
T: AsyncRead + AsyncWrite + Unpin,
{
unsafe fn prepare_uninitialized_buffer(&self, buf: &mut [u8]) -> bool {
match *self {
MaybeHttpsStream::Http(ref s) => s.prepare_uninitialized_buffer(buf),
MaybeHttpsStream::Https(ref s) => s.prepare_uninitialized_buffer(buf),
}
}
fn poll_read(
mut self: Pin<&mut Self>,
cx: &mut Context,
buf: &mut [u8],
) -> Poll<io::Result<usize>> {
match *self {
MaybeHttpsStream::Http(ref mut s) => Pin::new(s).poll_read(cx, buf),
MaybeHttpsStream::Https(ref mut s) => Pin::new(s).poll_read(cx, buf),
}
}
fn poll_read_buf<B: BufMut>(
mut self: Pin<&mut Self>,
cx: &mut Context,
buf: &mut B,
) -> Poll<io::Result<usize>>
where
B: BufMut,
{
match *self {
MaybeHttpsStream::Http(ref mut s) => Pin::new(s).poll_read_buf(cx, buf),
MaybeHttpsStream::Https(ref mut s) => Pin::new(s).poll_read_buf(cx, buf),
}
}
}
impl<T> AsyncWrite for MaybeHttpsStream<T>
where
T: AsyncRead + AsyncWrite + Unpin,
{
fn poll_write(
mut self: Pin<&mut Self>,
cx: &mut Context,
buf: &[u8],
) -> Poll<io::Result<usize>> {
match *self {
MaybeHttpsStream::Http(ref mut s) => Pin::new(s).poll_write(cx, buf),
MaybeHttpsStream::Https(ref mut s) => Pin::new(s).poll_write(cx, buf),
}
}
fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll<io::Result<()>> {
match *self {
MaybeHttpsStream::Http(ref mut s) => Pin::new(s).poll_flush(cx),
MaybeHttpsStream::Https(ref mut s) => Pin::new(s).poll_flush(cx),
}
}
fn poll_shutdown(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll<io::Result<()>> {
match *self {
MaybeHttpsStream::Http(ref mut s) => Pin::new(s).poll_shutdown(cx),
MaybeHttpsStream::Https(ref mut s) => Pin::new(s).poll_shutdown(cx),
}
}
fn poll_write_buf<B: Buf>(
mut self: Pin<&mut Self>,
cx: &mut Context,
buf: &mut B,
) -> Poll<io::Result<usize>>
where
Self: Sized,
{
match *self {
MaybeHttpsStream::Http(ref mut s) => Pin::new(s).poll_write_buf(cx, buf),
MaybeHttpsStream::Https(ref mut s) => Pin::new(s).poll_write_buf(cx, buf),
}
}
}
| 28.5875 | 114 | 0.586686 |
7bb8cec34bd9f9043d1adc4d10a1c893954772b1 | 482 | kt | Kotlin | app/src/main/java/org/simple/clinic/home/help/HelpScreenEvent.kt | santhosh2108/simple-android | 053da3671e125b72b35eee80bd80784986ca9bd8 | [
"MIT"
] | 186 | 2018-08-06T11:52:10.000Z | 2022-03-24T06:41:43.000Z | app/src/main/java/org/simple/clinic/home/help/HelpScreenEvent.kt | santhosh2108/simple-android | 053da3671e125b72b35eee80bd80784986ca9bd8 | [
"MIT"
] | 1,162 | 2018-07-17T05:01:25.000Z | 2022-03-31T17:46:39.000Z | app/src/main/java/org/simple/clinic/home/help/HelpScreenEvent.kt | santhosh2108/simple-android | 053da3671e125b72b35eee80bd80784986ca9bd8 | [
"MIT"
] | 88 | 2018-09-17T13:17:34.000Z | 2022-03-24T05:40:05.000Z | package org.simple.clinic.home.help
import org.simple.clinic.help.HelpPullResult
import org.simple.clinic.widgets.UiEvent
import java.util.Optional
sealed class HelpScreenEvent : UiEvent
object HelpScreenTryAgainClicked : HelpScreenEvent() {
override val analyticsName: String = "Help Screen:Try Again Clicked"
}
data class HelpContentLoaded(val helpContent: Optional<String>) : HelpScreenEvent()
data class HelpSyncPullResult(val result: HelpPullResult) : HelpScreenEvent()
| 30.125 | 83 | 0.817427 |
0ef2379619a4f1a9f0bacb629a1d1b7fa4f5b0b6 | 55 | h | C | imgui-binding/src/main/native/_common.h | perrymacmurray/imgui-java | 4d679fe220f567caf2a6a41d33cd2f3c7225ef28 | [
"Apache-2.0"
] | 245 | 2019-12-29T21:02:12.000Z | 2022-03-30T09:31:22.000Z | imgui-binding/src/main/native/_common.h | abvadabra/imgui-java | 6bb046c43303f871318963df83e393063137c824 | [
"Apache-2.0"
] | 103 | 2020-01-26T06:29:54.000Z | 2022-03-30T17:08:31.000Z | imgui-binding/src/main/native/_common.h | abvadabra/imgui-java | 6bb046c43303f871318963df83e393063137c824 | [
"Apache-2.0"
] | 55 | 2020-01-03T09:58:01.000Z | 2022-03-24T13:06:04.000Z | #pragma once
#include "_base.h"
#include "_binding.h"
| 11 | 21 | 0.709091 |
b1c555e7196d8acaf8fcbda10517779d1981b4e1 | 352 | c | C | test/set/test2.c | coriolanus/libhhash | 84fa2ddd969525d8d92329bda9e9b9457ebc3ddd | [
"MIT"
] | 33 | 2015-08-14T16:35:39.000Z | 2022-02-12T22:51:35.000Z | test/set/test2.c | coriolanus/libhhash | 84fa2ddd969525d8d92329bda9e9b9457ebc3ddd | [
"MIT"
] | null | null | null | test/set/test2.c | coriolanus/libhhash | 84fa2ddd969525d8d92329bda9e9b9457ebc3ddd | [
"MIT"
] | 7 | 2015-07-21T14:48:50.000Z | 2016-05-17T00:13:57.000Z | #include <stdlib.h>
#include <hhash.h>
#include <hhset.h>
#include "test.h"
int main(void) {
ulong n = 16;
ulong m = 0;
HHSet *S = hhsetnew(n, NULL, NULL);
for (ulong i = 0; i < 30; ++i) {
ulong x = rand() + 1;
if (!hhsetget(S, x)) {
test(hhsetput(S, x));
++m;
}
}
test(S->T->m == m);
hhsetfree(S);
return 0;
}
| 16.761905 | 37 | 0.505682 |
3e960b332b162ee54d0ce3889977fb5b58e0d33a | 658 | c | C | 3360-OS/examples/pipes/pipes.c | isaacdejesus/fall2020 | 4c154a2c2a2161d37d467af439113da0f0c23b28 | [
"Apache-2.0"
] | null | null | null | 3360-OS/examples/pipes/pipes.c | isaacdejesus/fall2020 | 4c154a2c2a2161d37d467af439113da0f0c23b28 | [
"Apache-2.0"
] | null | null | null | 3360-OS/examples/pipes/pipes.c | isaacdejesus/fall2020 | 4c154a2c2a2161d37d467af439113da0f0c23b28 | [
"Apache-2.0"
] | null | null | null | #include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <string.h>
#include <stdlib.h>
int main(void)
{
int fd[2], nbytes;
pid_t childpid;
char string[25];
char readbuffer[80];
pipe(fd);
if((childpid = fork()) == -1)
{
perror("fork");
exit(1);
}
if(childpid == 0)
{
close(fd[0]);
strcpy(string, "Hello from child");
write(fd[1], string, (strlen(string)+1));
_exit(0);
}
else
{
close(fd[1]);
nbytes = read(fd[0], readbuffer, sizeof(readbuffer));
printf("Received String: %s\n", readbuffer);
}
return(0);
}
| 17.315789 | 61 | 0.515198 |
fe8d3dbe2adad903f50d67c05908e3dda4cb4bc0 | 33 | kt | Kotlin | plugins/kotlin/refIndex/tests/testData/compilerIndex/functions/topLevel/operators/set/Implicit.kt | 06needhamt/intellij-community | 63d7b8030e4fdefeb4760e511e289f7e6b3a5c5b | [
"Apache-2.0"
] | null | null | null | plugins/kotlin/refIndex/tests/testData/compilerIndex/functions/topLevel/operators/set/Implicit.kt | 06needhamt/intellij-community | 63d7b8030e4fdefeb4760e511e289f7e6b3a5c5b | [
"Apache-2.0"
] | null | null | null | plugins/kotlin/refIndex/tests/testData/compilerIndex/functions/topLevel/operators/set/Implicit.kt | 06needhamt/intellij-community | 63d7b8030e4fdefeb4760e511e289f7e6b3a5c5b | [
"Apache-2.0"
] | null | null | null | fun test() {
42[42, ""] = 3
} | 11 | 18 | 0.363636 |
85b9860ed6fcf687c1e0ab0478a2d950977b6d4d | 4,838 | rs | Rust | src/emulator.rs | jffjs/wasmboy | 471fe54b9372ee5694b27d55d7504b239ce77199 | [
"Apache-2.0",
"MIT"
] | null | null | null | src/emulator.rs | jffjs/wasmboy | 471fe54b9372ee5694b27d55d7504b239ce77199 | [
"Apache-2.0",
"MIT"
] | null | null | null | src/emulator.rs | jffjs/wasmboy | 471fe54b9372ee5694b27d55d7504b239ce77199 | [
"Apache-2.0",
"MIT"
] | null | null | null | use crate::{
cartridge::Cartridge, cpu::CPU, gpu::GPU, io_device::IoDevice, mmu::MMU, timer::Timer,
utils::test_bit,
};
use num::{FromPrimitive, ToPrimitive};
use std::ops::{BitAnd, BitOr, Not};
use std::rc::Rc;
use wasm_bindgen::prelude::*;
#[wasm_bindgen]
pub struct Emulator {
cpu: CPU,
gpu: Rc<GPU>,
mmu: MMU,
timer: Rc<Timer>,
}
#[wasm_bindgen]
impl Emulator {
#[wasm_bindgen(constructor)]
pub fn new(rom: &[u8]) -> Emulator {
let cart = Cartridge::new(rom);
let timer = Rc::new(Timer::new());
let gpu = Rc::new(GPU::new());
let mut mmu = MMU::new(cart, timer.clone(), gpu.clone());
let mut cpu = CPU::new();
cpu.post_bios();
mmu.post_bios();
Emulator {
cpu,
gpu: gpu.clone(),
mmu,
timer: timer.clone(),
}
}
#[wasm_bindgen]
pub fn frame(&mut self, screen: &mut [u8]) {
// (144 scanlines + 10-line vblank) * 114 M-cycles
const M_CYCLES: u32 = (144 + 10) * 114;
let fclock = self.cpu.clock_m() + M_CYCLES;
while self.cpu.clock_m() < fclock {
self.cpu.exec(&mut self.mmu);
let mut interrupts: Vec<IntFlag> = Vec::new();
if let Some(timer_int) = self.timer.inc(self.cpu.m()) {
interrupts.push(timer_int);
}
let mut gpu_interrupts = self.gpu.execute(self.cpu.m(), screen);
interrupts.append(&mut gpu_interrupts);
self.check_interrupts();
}
}
#[wasm_bindgen]
pub fn run(&mut self) {
self.cpu.stop = false;
}
#[wasm_bindgen]
pub fn pause(&mut self) {
self.cpu.stop = true;
}
fn check_interrupts(&mut self) {
if self.cpu.ime {
let iflag = self.mmu.iflag();
let enabled = self.mmu.ie();
if iflag > 0 {
for int in IntFlag::priority().into_iter() {
let int_requested = enabled & iflag;
if let Some(int_val) = int.to_u8() {
if int & int_requested == int_val {
self.cpu.handle_interrupt(int, &mut self.mmu);
}
}
}
}
}
}
#[wasm_bindgen]
pub fn dbg_step(&mut self, screen: &mut [u8]) {
if !self.cpu.halted() {
self.cpu.exec(&mut self.mmu);
}
// Run interrupt routine
self.check_interrupts();
let interrupts = self.gpu.execute(self.cpu.m(), screen);
for int in interrupts {
if int == IntFlag::Vblank {
// TODO: add screen render hook here
}
self.mmu.set_iflag(int);
}
if let Some(timer_int) = self.timer.inc(self.cpu.m()) {
self.mmu.set_iflag(timer_int);
}
}
#[wasm_bindgen]
pub fn dbg_cpu_snapshot(&self) -> JsValue {
JsValue::from_serde(&self.cpu).unwrap()
}
#[wasm_bindgen]
pub fn dbg_mem_snapshot(&self, addr: usize, length: usize) -> Box<[u8]> {
let mut snapshot = Vec::new();
for i in 0..length {
let byte = self.mmu.read_byte((addr + i) as u16);
snapshot.push(byte);
}
snapshot.into_boxed_slice()
}
pub fn dbg_tile_data(&self, tile_num: u8) -> Box<[u8]> {
self.gpu.dbg_tile(tile_num).into_boxed_slice()
}
}
#[derive(Clone, Copy, Debug, PartialEq, ToPrimitive)]
pub enum IntFlag {
Vblank = 0x1,
LCDC = 0x2,
TimerOverflow = 0x4,
SerialIO = 0x8,
JoyPad = 0x10,
}
impl IntFlag {
fn priority() -> Vec<IntFlag> {
vec![
IntFlag::Vblank,
IntFlag::LCDC,
IntFlag::TimerOverflow,
IntFlag::SerialIO,
IntFlag::JoyPad,
]
}
}
impl BitAnd<u8> for IntFlag {
type Output = u8;
fn bitand(self, other: u8) -> u8 {
other & self.to_u8().unwrap()
}
}
impl BitOr<u8> for IntFlag {
type Output = u8;
fn bitor(self, other: u8) -> u8 {
other | self.to_u8().unwrap()
}
}
impl Not for IntFlag {
type Output = u8;
fn not(self) -> u8 {
!(self.to_u8().unwrap())
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_int_flag() {
assert_eq!(!IntFlag::Vblank, 0xfe);
assert_eq!(!IntFlag::LCDC, 0xfd);
assert_eq!(!IntFlag::TimerOverflow, 0xfb);
assert_eq!(!IntFlag::SerialIO, 0xf7);
assert_eq!(!IntFlag::JoyPad, 0xef);
assert_eq!(IntFlag::Vblank & 0xff, 0x1);
assert_eq!(IntFlag::LCDC & 0xff, 0x2);
assert_eq!(IntFlag::TimerOverflow & 0xff, 0x4);
assert_eq!(IntFlag::SerialIO & 0xff, 0x8);
assert_eq!(IntFlag::JoyPad & 0xff, 0x10);
}
}
| 25.734043 | 90 | 0.52253 |
07efeb113a27653efba839899ea86427e46aedab | 1,202 | h | C | GxShareProj/ExtraFile/MethodExt/MethodExt.h | gxatios/GxShareProj | d6465b5549bde17efcc0f27931d7b066ab855a68 | [
"MIT"
] | null | null | null | GxShareProj/ExtraFile/MethodExt/MethodExt.h | gxatios/GxShareProj | d6465b5549bde17efcc0f27931d7b066ab855a68 | [
"MIT"
] | null | null | null | GxShareProj/ExtraFile/MethodExt/MethodExt.h | gxatios/GxShareProj | d6465b5549bde17efcc0f27931d7b066ab855a68 | [
"MIT"
] | null | null | null | //
// MethodExt.h
// AVDemo
//
// Created by iOS-iMac on 2018/3/9.
// Copyright © 2018年 iOS-iMac. All rights reserved.
//
#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>
#import <CommonCrypto/CommonCrypto.h>
@interface MethodExt : NSObject
+ (UIColor *) colorWithHexString: (NSString *) stringToConvert;
+ (UIImage*) createImageWithColor: (UIColor*) color;
+ (UIImage *) createImageWithColor:(UIColor *) color andRect:(CGRect)rect andCornerRadius:(float)radius;
+(BOOL)isValitString:(NSString *)testStr;
+ (BOOL)validateUserName:(NSString *)name; // 用户名
+ (BOOL)validatePhoneNum:(NSString *)name; // 11位数字手机号
+ (BOOL)judgeIdentityStringValid:(NSString *)identityString; // 身份证号
+ (BOOL)validateBarCode:(NSString *)code; // 条形码 数字字母
+(NSString *)dateToString:(NSDate*)date;
+(NSString *)dateToMinuteString:(NSDate*)date;
+(NSDate *)strToDate:(NSString*)dateStr;
+ (NSDate *)tomorrowDay:(NSDate *)aDate after:(NSInteger)num;
+ (NSString *)arrayToJSONString:(NSArray *)array;
+ (NSString *)dictionaryToJSONString:(NSDictionary *)dictionary;
+(void)callPhoneMethod:(NSString*)phoneNum;
+ (NSString *)encrypt3DES:(NSString *)src key:(NSString *)key;
+ (NSString*)getDivceSize;
@end
| 30.820513 | 104 | 0.731281 |
9c53cd6d4440d67055228f5c49aa9268b413d160 | 4,542 | swift | Swift | MBIngressKit/MBIngressKit/Services/Network/BffUserRouter.swift | Daimler/MBSDK-IngressKit-iOS | 66c65db24971df56c077631baffdd3027d9f74ab | [
"MIT"
] | 2 | 2019-09-23T03:53:27.000Z | 2021-09-21T23:37:35.000Z | MBIngressKit/MBIngressKit/Services/Network/BffUserRouter.swift | Daimler/MBSDK-IngressKit-iOS | 66c65db24971df56c077631baffdd3027d9f74ab | [
"MIT"
] | null | null | null | MBIngressKit/MBIngressKit/Services/Network/BffUserRouter.swift | Daimler/MBSDK-IngressKit-iOS | 66c65db24971df56c077631baffdd3027d9f74ab | [
"MIT"
] | 1 | 2021-08-23T02:44:31.000Z | 2021-08-23T02:44:31.000Z | //
// Copyright © 2019 MBition GmbH. All rights reserved.
//
import Foundation
import MBNetworkKit
enum BffUserRouter: EndpointRouter {
case adaptionValues(accessToken: String, dict: [String: Any]?)
case biometric(accessToken: String, dict: [String: Any]?)
case create(countryCode: String, locale: String, dict: [String: Any]?)
case delete(accessToken: String)
case exist(dict: [String: Any]?)
case get(accessToken: String)
case update(accessToken: String, dict: [String: Any]?)
case updateUnitPreferences(accessToken: String, dict: [String: Any]?)
case verification(accessToken: String, scanReference: String)
// MARK: Properties
var baseURL: String {
guard let urlProvider = IngressKit.bffProvider?.urlProvider else {
fatalError("This is a placeholder implementation. Please implement your own bffProvider or use the implementation from MBMobileSDK")
}
return urlProvider.baseUrl
}
var httpHeaders: [String: String]? {
guard let headerParamProvider = IngressKit.bffProvider?.headerParamProvider else {
fatalError("This is a placeholder implementation. Please implement your own headerParamProvider or use the implementation from MBMobileSDK")
}
var headers = headerParamProvider.defaultHeaderParams
switch self {
case .adaptionValues(let accessToken, _):
headers[headerParamProvider.authorizationHeaderParamKey] = accessToken
headers[headerParamProvider.countryCodeHeaderParamKey] = IngressKit.countryCode
case .biometric(let accessToken, _):
headers[headerParamProvider.authorizationHeaderParamKey] = accessToken
case .create(let countryCode, let locale, _):
headers[headerParamProvider.countryCodeHeaderParamKey] = countryCode
headers[headerParamProvider.localeHeaderParamKey] = locale
case .delete(let accessToken):
headers[headerParamProvider.authorizationHeaderParamKey] = accessToken
headers[headerParamProvider.countryCodeHeaderParamKey] = IngressKit.countryCode
case .exist:
break
case .get(let accessToken):
headers[headerParamProvider.authorizationHeaderParamKey] = accessToken
case .update(let accessToken, _):
headers[headerParamProvider.authorizationHeaderParamKey] = accessToken
headers[headerParamProvider.countryCodeHeaderParamKey] = IngressKit.countryCode
case .updateUnitPreferences(let accessToken, _):
headers[headerParamProvider.authorizationHeaderParamKey] = accessToken
case .verification(let accessToken, _):
headers[headerParamProvider.authorizationHeaderParamKey] = accessToken
}
return headers
}
var method: HTTPMethodType {
switch self {
case .adaptionValues: return .put
case .biometric: return .post
case .create: return .post
case .delete: return .delete
case .exist: return .post
case .get: return .get
case .update: return .put
case .updateUnitPreferences: return .put
case .verification: return .post
}
}
var path: String {
let ciamId = "self"
switch self {
case .adaptionValues: return "/user/adaptionValues"
case .biometric: return "/user/biometric"
case .create: return "user"
case .delete: return "user/\(ciamId)"
case .exist: return "login"
case .get: return "user/\(ciamId)"
case .update: return "user/\(ciamId)"
case .updateUnitPreferences: return "user/unitpreferences"
case .verification: return "user/verification"
}
}
var parameters: [String: Any]? {
return nil
}
var parameterEncoding: ParameterEncodingType {
return .json
}
var cachePolicy: URLRequest.CachePolicy? {
return nil
}
var bodyParameters: [String: Any]? {
switch self {
case .adaptionValues(_, let dict): return dict
case .biometric(_, let dict): return dict
case .create(_, _, let dict): return dict
case .delete: return nil
case .exist(let dict): return dict
case .get: return nil
case .update(_, let dict): return dict
case .updateUnitPreferences(_, let dict): return dict
case .verification(_, let scanReference): return ["scanReference": scanReference]
}
}
var bodyEncoding: ParameterEncodingType {
return self.parameterEncoding
}
var timeout: TimeInterval {
return IngressKit.bffProvider?.urlProvider.requestTimeout ?? IngressKit.defaultRequestTimeout
}
}
| 36.336 | 143 | 0.700352 |
12a5bcbbf5c471aed9eebcba7f255668238f979a | 33,411 | h | C | termsrv/newclient/core/sl.h | npocmaka/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 17 | 2020-11-13T13:42:52.000Z | 2021-09-16T09:13:13.000Z | termsrv/newclient/core/sl.h | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 2 | 2020-10-19T08:02:06.000Z | 2020-10-19T08:23:18.000Z | termsrv/newclient/core/sl.h | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 14 | 2020-11-14T09:43:20.000Z | 2021-08-28T08:59:57.000Z | /****************************************************************************/
/* sl.h */
/* */
/* Security Layer class */
/* */
/* Copyright (C) 1997-1999 Microsoft Corporation */
/****************************************************************************/
#ifndef _H_SL
#define _H_SL
extern "C" {
#include <adcgdata.h>
#include <at120ex.h>
}
#include "cd.h"
#include "nl.h"
#include "cchan.h"
#include "objs.h"
#include "capienc.h"
#define SL_DBG_INIT_CALLED 0x00001
#define SL_DBG_INIT_DONE 0x00002
#define SL_DBG_TERM_CALLED 0x00004
#define SL_DBG_TERM_DONE 0x00008
#define SL_DBG_CONNECT_CALLED 0x00010
#define SL_DBG_CONNECT_DONE 0x00020
#define SL_DBG_DISCONNECT_CALLED 0x00040
#define SL_DBG_DISCONNECT_DONE1 0x00080
#define SL_DBG_DISCONNECT_DONE2 0x00100
#define SL_DBG_ONINIT_CALLED 0x00200
#define SL_DBG_ONINIT_DONE1 0x00400
#define SL_DBG_ONINIT_DONE2 0x00800
#define SL_DBG_ONDISC_CALLED 0x01000
#define SL_DBG_ONDISC_DONE1 0x02000
#define SL_DBG_ONDISC_DONE2 0x04000
#define SL_DBG_ONTERM_CALLED 0x08000
#define SL_DBG_ONTERM_DONE1 0x10000
#define SL_DBG_ONTERM_DONE2 0x20000
#define SL_DBG_TERM_DONE1 0x40000
extern DWORD g_dwSLDbgStatus;
#define SL_DBG_SETINFO(x) g_dwSLDbgStatus |= x;
/****************************************************************************/
/* Protocol type(s) */
/****************************************************************************/
#define SL_PROTOCOL_T128 NL_PROTOCOL_T128
/****************************************************************************/
/* Network transport types. */
/****************************************************************************/
#define SL_TRANSPORT_TCP NL_TRANSPORT_TCP
#ifdef DC_LOOPBACK
/****************************************************************************/
/* Loopback testing constants */
/****************************************************************************/
/****************************************************************************/
/* Test string: Put two pad bytes at the front, since MG will overwrite */
/* these with a length field on the server. Check only subsequent parts of */
/* the string. */
/* Ensure that the whole thing is a multiple of 4 bytes (including the null */
/* terminator) to avoid padding inconsistencies. */
/****************************************************************************/
#define SL_LB_RETURN_STRING \
{'L','o','o','p','b','a','c','k',' ','t','e','s','t',' '}
#define SL_LB_RETURN_STRING_SIZE 14
#define SL_LB_STR_CORRUPT_LENGTH 2
#define SL_LB_STRING_SIZE \
(SL_LB_STR_CORRUPT_LENGTH + SL_LB_RETURN_STRING_SIZE)
#define SL_LB_HDR_SIZE sizeof(SL_LB_PACKET)
#define SL_LB_SIZE_INC 1
#define SL_LB_MAX_PACKETS 6000
#define SL_LB_MAX_SIZE 4000
#define SL_LB_MIN_SIZE (SL_LB_HDR_SIZE + SL_LB_SIZE_INC)
#endif /* DC_LOOPBACK */
/****************************************************************************/
/* Structure: SL_BUFHND */
/* */
/* Description: Buffer Handle */
/****************************************************************************/
typedef NL_BUFHND SL_BUFHND;
typedef SL_BUFHND DCPTR PSL_BUFHND;
/****************************************************************************/
/* Structure: SL_CALLBACKS */
/* */
/* Description: list of callbacks passed to SL_Init(). */
/****************************************************************************/
typedef NL_CALLBACKS SL_CALLBACKS;
typedef SL_CALLBACKS DCPTR PSL_CALLBACKS;
//
// For internal functions
//
/****************************************************************************/
/* Constants */
/****************************************************************************/
/****************************************************************************/
/* Multiplier to turn a default string format byte count into a Unicode */
/* string byte count. */
/* For 32-bit, the default is Unicode, so the multiplier is a NOP, ie 1. */
/* For 16-bit, the default is ANSI, so multiply by 2 to give Unicode */
/* (assumes security package names always use single byte chars). */
/****************************************************************************/
#ifdef UNICODE
#define SL_DEFAULT_TO_UNICODE_FACTOR 1
#else
#define SL_DEFAULT_TO_UNICODE_FACTOR 2
#endif
/****************************************************************************/
/* States */
/****************************************************************************/
#define SL_STATE_TERMINATED 0
#define SL_STATE_INITIALIZING 1
#define SL_STATE_INITIALIZED 2
#define SL_STATE_NL_CONNECTING 3
#define SL_STATE_SL_CONNECTING 4
#define SL_STATE_LICENSING 5
#define SL_STATE_CONNECTED 6
#define SL_STATE_DISCONNECTING 7
#define SL_STATE_TERMINATING 8
#define SL_NUMSTATES 9
/****************************************************************************/
/* Events */
/****************************************************************************/
#define SL_EVENT_SL_INIT 0
#define SL_EVENT_SL_TERM 1
#define SL_EVENT_SL_CONNECT 2
#define SL_EVENT_SL_DISCONNECT 3
#define SL_EVENT_SL_SENDPACKET 4
#define SL_EVENT_SL_GETBUFFER 5
#define SL_EVENT_ON_INITIALIZED 6
#define SL_EVENT_ON_TERMINATING 7
#define SL_EVENT_ON_CONNECTED 8
#define SL_EVENT_ON_DISCONNECTED 9
#define SL_EVENT_ON_RECEIVED_SEC_PACKET 10
#define SL_EVENT_ON_RECEIVED_LIC_PACKET 11
#define SL_EVENT_ON_RECEIVED_DATA_PACKET 12
#define SL_EVENT_ON_BUFFERAVAILABLE 13
#define SL_NUMEVENTS 14
/****************************************************************************/
/* Values in the state table */
/****************************************************************************/
#define SL_TABLE_OK 0
#define SL_TABLE_WARN 1
#define SL_TABLE_ERROR 2
/****************************************************************************/
/* Macros */
/****************************************************************************/
/****************************************************************************/
/* SL_CHECK_STATE - check SL is in the right state for an event. */
/****************************************************************************/
#define SL_CHECK_STATE(event) \
{ \
TRC_DBG((TB, _T("Test event %s in state %s"), \
slEvent[event], slState[_SL.state])); \
if (slStateTable[event][_SL.state] != SL_TABLE_OK) \
{ \
if (slStateTable[event][_SL.state] == SL_TABLE_WARN) \
{ \
TRC_ALT((TB, _T("Unusual event %s in state %s"), \
slEvent[event], slState[_SL.state])); \
} \
else \
{ \
TRC_ABORT((TB, _T("Invalid event %s in state %s"), \
slEvent[event], slState[_SL.state])); \
} \
DC_QUIT; \
} \
}
/****************************************************************************/
/* SL_SET_STATE - set the SL state */
/****************************************************************************/
#define SL_SET_STATE(newstate) \
{ \
TRC_NRM((TB, _T("Set state from %s to %s"), \
slState[_SL.state], slState[newstate])); \
_SL.state = newstate; \
}
#ifdef DC_LOOPBACK
/****************************************************************************/
/* Loopback testing structures and functions */
/****************************************************************************/
/**STRUCT+*******************************************************************/
/* Structure: SL_LB_PACKET */
/* */
/* Description: template for building up the packet to be sent */
/****************************************************************************/
typedef struct tagSL_LB_PACKET
{
DCUINT8 testString[SL_LB_STRING_SIZE]; /* multiple of 4 bytes */
DCUINT32 sequenceNumber; /* Chosen to ensure data begins on word */
/* boundary */
} SL_LB_PACKET, DCPTR PSL_LB_PACKET;
/**STRUCT-*******************************************************************/
/**STRUCT+*******************************************************************/
/* Structure: SL_LB_Q_ELEMENT */
/* */
/* Description: Elements in sent and received queues of loopback packets */
/****************************************************************************/
typedef struct tagSL_LB_Q_ELEMENT SL_LB_Q_ELEMENT, DCPTR PSL_LB_Q_ELEMENT;
struct tagSL_LB_Q_ELEMENT
{
PSL_LB_PACKET pCurrent;
SL_LB_Q_ELEMENT *pNext;
};
/**STRUCT-*******************************************************************/
#endif //DC_LOOPBACK
//
// Data
//
/****************************************************************************/
/* Structure: SL_GLOBAL_DATA */
/* */
/* Description: Security Layer global data */
/****************************************************************************/
typedef struct tagSL_GLOBAL_DATA
{
/************************************************************************/
/* List of callbacks to the Core */
/************************************************************************/
SL_CALLBACKS callbacks;
/************************************************************************/
/* Flags and State information */
/************************************************************************/
DCUINT state;
/************************************************************************/
/* Encryption flags and data. */
/************************************************************************/
DCBOOL encrypting;
DCBOOL encryptionEnabled;
DCBOOL decryptFailed;
DCUINT32 encryptionMethodsSupported;
DCUINT32 encryptionMethodSelected;
DCUINT32 encryptionLevel;
RANDOM_KEYS_PAIR keyPair;
DCUINT32 keyLength;
DCUINT32 encryptCount; // reset every 4K packets
DCUINT32 totalEncryptCount; // cumulative count
DCUINT8 startEncryptKey[MAX_SESSION_KEY_SIZE];
DCUINT8 currentEncryptKey[MAX_SESSION_KEY_SIZE];
struct RC4_KEYSTRUCT rc4EncryptKey;
DCUINT32 decryptCount; // reset every 4K packets
DCUINT32 totalDecryptCount; // cumulative count
DCUINT8 startDecryptKey[MAX_SESSION_KEY_SIZE];
DCUINT8 currentDecryptKey[MAX_SESSION_KEY_SIZE];
struct RC4_KEYSTRUCT rc4DecryptKey;
DCUINT8 macSaltKey[MAX_SESSION_KEY_SIZE];
/************************************************************************/
/* Server certificate and public key data */
/************************************************************************/
PDCUINT8 pbCertificate;
DCUINT cbCertificate;
PHydra_Server_Cert pServerCert;
PDCUINT8 pbServerPubKey;
DCUINT32 cbServerPubKey;
#ifdef USE_LICENSE
/************************************************************************/
/* License Manager handle */
/************************************************************************/
HANDLE hLicenseHandle;
#endif //USE_LICENSE
/************************************************************************/
/* ID of MCS broadcast channel */
/************************************************************************/
DCUINT channelID;
/************************************************************************/
/* User data to be passed to the Core (saved in SLOnConnected() and */
/* passed to Core's OnReceived callback by SLOnPacketReceived()) */
/************************************************************************/
PDCUINT8 pSCUserData;
DCUINT SCUserDataLength;
/************************************************************************/
/* User data to be passed to the Server (saved in SLInitSecurity() and */
/* passed to NL_Connect() by SL_Connect()). */
/************************************************************************/
PDCUINT8 pCSUserData;
DCUINT CSUserDataLength;
/************************************************************************/
/* Disconnection reason code. This may be used to override the NL */
/* disconnection reason code. */
/************************************************************************/
DCUINT disconnectErrorCode;
/************************************************************************/
/* Server version (once connected) */
/************************************************************************/
DCUINT32 serverVersion;
//
// Safe checksum enabled
//
BOOL fEncSafeChecksumCS;
BOOL fEncSafeChecksumSC;
CAPIData SLCapiData;
} SL_GLOBAL_DATA, DCPTR PSL_GLOBAL_DATA;
/****************************************************************************/
/* SL State Table */
/****************************************************************************/
static unsigned slStateTable[SL_NUMEVENTS][SL_NUMSTATES]
= {
/********************************************************************/
/* This is not a state table in the strict sense. It simply shows */
/* which events are valid in which states. It is not used to drive */
/* _SL. */
/* */
/* Values mean */
/* - 0 event OK in this state. */
/* - 1 warning - event should not occur in this state, but does in */
/* some race conditions - ignore it. */
/* - 2 error - event should not occur in ths state at all. */
/* */
/* These values are hard-coded here in order to make the table */
/* readable. They correspond to the constants SL_TABLE_OK, */
/* SL_TABLE_WARN & SL_TABLE_ERROR. */
/* */
/* SL may enter Initialized state after issuing a Disconnect */
/* reqeest, but before the OnDisconnected indication is received. */
/* In this state, the Sender thread may issue SL_GetBuffer or */
/* SL_Disconnect (as it has not yet received the OnDisconnected */
/* callback). */
/* Also, if the security exchange fails, we can enter Initialized */
/* state before the NL is disconnected, and so could receive */
/* packets from the network. */
/* */
/* When SL is in Disconnecting state, the Sender Thread may still */
/* issue GetBuffer and SendPacket calls. If disconnect is */
/* requested during security exchange, then packets may be received */
/* (until OnDisconnected is called). */
/* Also, may get OnConnected in Disconnecting state if a Disconnect */
/* is before the connection is complete (cross-over). */
/* */
/* Terminated */
/* | Initializing */
/* | | Initialized */
/* | | | NL Connecting */
/* | | | | SL Connecting */
/* | | | | | Licensing */
/* | | | | | | Connected */
/* | | | | | | | Disconnecting */
/* | | | | | | | | Terminating */
/********************************************************************/
{ 0, 2, 2, 2, 2, 2, 2, 2, 2}, /* SL_Init */
{ 2, 0, 0, 0, 0, 0, 0, 0, 2}, /* SL_Term */
{ 2, 2, 0, 2, 2, 2, 2, 2, 2}, /* SL_Connect */
{ 2, 2, 1, 0, 0, 0, 0, 1, 2}, /* SL_Disconnect */
{ 2, 2, 1, 2, 0, 0, 0, 1, 2}, /* SL_SendPacket */
{ 2, 2, 1, 1, 1, 0, 0, 1, 2}, /* SL_GetBuffer */
{ 2, 0, 2, 2, 2, 2, 2, 2, 2}, /* SL_OnInitialized */
{ 2, 2, 2, 2, 2, 2, 2, 2, 0}, /* SL_OnTerminating */
{ 2, 2, 2, 0, 2, 2, 2, 1, 2}, /* SL_OnConnected */
{ 2, 2, 1, 0, 0, 0, 0, 0, 0}, /* SL_OnDisconnected*/
{ 2, 2, 1, 2, 0, 2, 2, 1, 2}, /* SL_OnPktRec(Sec) */
{ 2, 2, 1, 2, 2, 0, 2, 1, 2}, /* SL_OnPktRec(Lic) */
{ 2, 2, 1, 1, 2, 2, 0, 1, 2}, /* SL_OnPktRec(Data)*/
{ 1, 1, 1, 1, 0, 0, 0, 0, 1} /* SL_OnBufferAvail */
};
#ifdef DC_DEBUG
/****************************************************************************/
/* State and event descriptions (debug build only) */
/****************************************************************************/
static const DCTCHAR slState[SL_NUMSTATES][25]
//#ifdef DC_DEFINE_GLOBAL_DATA
= {
_T("SL_STATE_TERMINATED"),
_T("SL_STATE_INITIALIZING"),
_T("SL_STATE_INITIALIZED"),
_T("SL_STATE_NL_CONNECTING"),
_T("SL_STATE_SL_CONNECTING"),
_T("SL_STATE_LICENSING"),
_T("SL_STATE_CONNECTED"),
_T("SL_STATE_DISCONNECTING"),
_T("SL_STATE_TERMINATING")
}
//#endif /* DC_DEFINE_GLOBAL_DATA */
;
static const DCTCHAR slEvent[SL_NUMEVENTS][35]
//#ifdef DC_DEFINE_GLOBAL_DATA
= {
_T("SL_EVENT_SL_INIT"),
_T("SL_EVENT_SL_TERM"),
_T("SL_EVENT_SL_CONNECT"),
_T("SL_EVENT_SL_DISCONNECT"),
_T("SL_EVENT_SL_SENDPACKET"),
_T("SL_EVENT_SL_GETBUFFER"),
_T("SL_EVENT_ON_INITIALIZED"),
_T("SL_EVENT_ON_TERMINATING"),
_T("SL_EVENT_ON_CONNECTED"),
_T("SL_EVENT_ON_DISCONNECTED"),
_T("SL_EVENT_ON_RECEIVED_SEC_PACKET"),
_T("SL_EVENT_ON_RECEIVED_LIC_PACKET"),
_T("SL_EVENT_ON_RECEIVED_DATA_PACKET"),
_T("SL_EVENT_ON_BUFFERAVAILABLE")
}
//#endif /* DC_DEFINE_GLOBAL_DATA */
;
#endif /* DC_DEBUG */
class CUI;
class CUH;
class CRCV;
class CCD;
class CSND;
class CCC;
class CIH;
class COR;
class CSP;
class CNL;
class CMCS;
class CTD;
class CCO;
class CCLX;
class CLic;
class CChan;
class CSL
{
public:
CSL(CObjs* objs);
~CSL();
public:
//
// API
//
DCVOID DCAPI SL_Init(PSL_CALLBACKS pCallbacks);
DCVOID DCAPI SL_Term(DCVOID);
DCVOID DCAPI SL_Connect(BOOL bInitateConnect,
PDCTCHAR pServerAddress,
DCUINT transportType,
PDCTCHAR pProtocolName,
PDCUINT8 pUserData,
DCUINT userDataLength);
DCVOID DCAPI SL_Disconnect(DCVOID);
DCVOID DCAPI SL_SendPacket(PDCUINT8 pData,
DCUINT dataLen,
DCUINT flags,
SL_BUFHND bufHandle,
DCUINT userID,
DCUINT channel,
DCUINT priority);
void DCAPI SL_SendFastPathInputPacket(BYTE FAR *, unsigned, unsigned,
SL_BUFHND);
DCBOOL DCAPI SL_GetBufferRtl(DCUINT dataLen,
PPDCUINT8 pBuffer,
PSL_BUFHND pBufHandle);
DCBOOL DCAPI SL_GetBufferDbg(DCUINT dataLen,
PPDCUINT8 pBuffer,
PSL_BUFHND pBufHandle,
PDCTCHAR pCaller);
/****************************************************************************/
/* Debug and retail versions of SL_GetBuffer */
/****************************************************************************/
#ifdef DC_DEBUG
#define SL_GetBuffer(dataLen, pBuffer, pBufHandle) \
SL_GetBufferDbg(dataLen, pBuffer, pBufHandle, trc_fn)
#else
#define SL_GetBuffer(dataLen, pBuffer, pBufHandle) \
SL_GetBufferRtl(dataLen, pBuffer, pBufHandle)
#endif
DCVOID DCAPI SL_FreeBuffer(SL_BUFHND bufHandle);
DCVOID DCAPI SL_SendSecurityPacket(PDCVOID pData,
DCUINT dataLength);
EXPOSE_CD_NOTIFICATION_FN(CSL, SL_SendSecurityPacket);
DCVOID DCAPI SL_SendSecInfoPacket(PDCVOID pData,
DCUINT dataLength);
EXPOSE_CD_NOTIFICATION_FN(CSL, SL_SendSecInfoPacket);
DCVOID DCAPI SL_EnableEncryption(ULONG_PTR pEnableEncryption);
EXPOSE_CD_SIMPLE_NOTIFICATION_FN(CSL, SL_EnableEncryption);
/****************************************************************************/
/* Loopback testing */
/****************************************************************************/
#ifdef DC_LOOPBACK
DCVOID DCAPI SL_LoopBack(DCBOOL start);
DCVOID DCAPI SL_LoopbackLoop(DCUINT ignored);
#endif /* DC_LOOPBACK */
public:
//
// Data members
//
SL_GLOBAL_DATA _SL;
public:
/****************************************************************************/
/* Callbacks from NL (passed on NL_Init()) */
/****************************************************************************/
DCVOID DCCALLBACK SL_OnInitialized(DCVOID);
DCVOID DCCALLBACK SL_OnTerminating(DCVOID);
DCVOID DCCALLBACK SL_OnConnected(DCUINT channelID,
PDCVOID pUserData,
DCUINT userDataLength,
DCUINT32 serverVersion);
DCVOID DCCALLBACK SL_OnDisconnected(DCUINT reason);
HRESULT DCCALLBACK SL_OnPacketReceived(PDCUINT8 pData,
DCUINT dataLen,
DCUINT flags,
DCUINT channelID,
DCUINT priority);
DCVOID DCCALLBACK SL_OnBufferAvailable(DCVOID);
HRESULT DCAPI SL_OnFastPathOutputReceived(BYTE FAR *, unsigned,
BOOL, BOOL);
//
// Immediately drop the link
//
HRESULT SL_DropLinkImmediate(UINT reason);
//
// Static inline versions
//
static void DCCALLBACK SL_StaticOnInitialized(PVOID inst)
{
((CSL*)inst)->SL_OnInitialized();
}
static void DCCALLBACK SL_StaticOnTerminating(PVOID inst)
{
((CSL*)inst)->SL_OnTerminating();
}
static void DCCALLBACK SL_StaticOnConnected(
PVOID inst,
unsigned channelID,
PVOID pUserData,
unsigned userDataLength,
UINT32 serverVersion)
{
((CSL*)inst)->SL_OnConnected( channelID, pUserData, userDataLength, serverVersion);
}
static void DCCALLBACK SL_StaticOnDisconnected(PVOID inst, unsigned reason)
{
((CSL*)inst)->SL_OnDisconnected( reason);
}
static HRESULT DCCALLBACK SL_StaticOnPacketReceived(
PVOID inst,
BYTE *pData,
unsigned dataLen,
unsigned flags,
unsigned channelID,
unsigned priority)
{
return ((CSL*)inst)->SL_OnPacketReceived(pData, dataLen, flags, channelID, priority);
}
static void DCCALLBACK SL_StaticOnBufferAvailable(PVOID inst)
{
((CSL*)inst)->SL_OnBufferAvailable();
}
DCVOID DCAPI SLIssueDisconnectedCallback(ULONG_PTR reason);
EXPOSE_CD_SIMPLE_NOTIFICATION_FN( CSL, SLIssueDisconnectedCallback);
DCVOID DCAPI SLSetReasonAndDisconnect(ULONG_PTR reason);
EXPOSE_CD_SIMPLE_NOTIFICATION_FN( CSL, SLSetReasonAndDisconnect);
DCVOID DCAPI SLLicenseData(PDCVOID pData, DCUINT dataLen);
EXPOSE_CD_NOTIFICATION_FN( CSL, SLLicenseData);
DCVOID DCAPI SL_SetEncSafeChecksumCS(ULONG_PTR f)
{
_SL.fEncSafeChecksumCS = (BOOL)f;
}
EXPOSE_CD_SIMPLE_NOTIFICATION_FN(CSL, SL_SetEncSafeChecksumCS);
BOOL SL_GetEncSafeChecksumCS()
{
return _SL.fEncSafeChecksumCS;
}
DCVOID DCAPI SL_SetEncSafeChecksumSC(BOOL f)
{
_SL.fEncSafeChecksumSC = f;
}
BOOL SL_GetEncSafeChecksumSC()
{
return _SL.fEncSafeChecksumSC;
}
private:
/****************************************************************************/
/* Internal functions */
/****************************************************************************/
DCVOID DCINTERNAL SLInitSecurity(DCVOID);
DCVOID DCINTERNAL SLInitCSUserData(DCVOID);
DCVOID DCINTERNAL SLSendSecInfoPacket(DCVOID);
DCBOOL DCINTERNAL SLSendSecurityPacket(PDCUINT8 serverPublicKey,
DCUINT32 serverPublicKeyLen);
HRESULT DCINTERNAL SLReceivedDataPacket(PDCUINT8 pData,
DCUINT dataLen,
DCUINT flags,
DCUINT channelID,
DCUINT priority);
DCBOOL DCINTERNAL SLDecryptRedirectionPacket(PDCUINT8 *ppData,
DCUINT *pdataLen);
DCBOOL DCINTERNAL SL_DecryptHelper(PDCUINT8 pData,
DCUINT *pdataLen);
DCVOID DCINTERNAL SLReceivedSecPacket(PDCUINT8 pData,
DCUINT dataLen,
DCUINT flags,
DCUINT channelID,
DCUINT priority);
DCVOID DCINTERNAL SLReceivedLicPacket(PDCUINT8 pData,
DCUINT dataLen,
DCUINT flags,
DCUINT channelID,
DCUINT priority);
DCVOID DCINTERNAL SLFreeConnectResources(DCVOID);
DCVOID DCINTERNAL SLFreeInitResources(DCVOID);
DCBOOL DCINTERNAL SLValidateServerCert( PDCUINT8 pbCert,
DCUINT32 cbCert,
CERT_TYPE * pCertType );
#ifdef DC_LOOPBACK
DCVOID DCINTERNAL SLLoopbackSendPacket(PDCUINT8 pData,
DCUINT dataLen,
SL_BUFHND bufHandle,
PDCUINT8 pRefData);
DCVOID DCINTERNAL SLLBQueueAdd(PSL_LB_PACKET pPacket,
PSL_LB_Q_ELEMENT pRoot);
PSL_LB_Q_ELEMENT DCINTERNAL SLLBQueueRemove(PSL_LB_Q_ELEMENT pRoot);
DCVOID DCINTERNAL SLLBPacketCheck(PDCUINT8 pData, DCUINT dataLen);
#endif /* DC_LOOPBACK */
DCBOOL DCINTERNAL SLGetComputerAddressW(PDCUINT8 szBuff);
BOOL
SLComputeHMACVerifier(
PBYTE pCookie, //IN - the shared secret
LONG cbCookieLen, //IN - the shared secret len
PBYTE pRandom, //IN - the session random
LONG cbRandomLen, //IN - the session random len
PBYTE pVerifier, //OUT- the verifier
LONG cbVerifierLen //IN - the verifier buffer length
);
private:
CUT* _pUt;
CUI* _pUi;
CNL* _pNl;
CUH* _pUh;
CRCV* _pRcv;
CCD* _pCd;
CSND* _pSnd;
CCC* _pCc;
CIH* _pIh;
COR* _pOr;
CSP* _pSp;
CMCS* _pMcs;
CTD* _pTd;
CCO* _pCo;
CCLX* _pClx;
CLic* _pLic;
CChan* _pChan;
private:
CObjs* _pClientObjects;
BOOL _fSLInitComplete;
};
#endif // _H_SL
| 43.617493 | 94 | 0.382389 |
650bd2653086235614c46bb1b73a337dfc0ba477 | 6,046 | py | Python | vintage_commands.py | ktuan89/Vintage | 81f178043d1dad4ec9bd50ad4db2df9ef994f098 | [
"MIT",
"Unlicense"
] | null | null | null | vintage_commands.py | ktuan89/Vintage | 81f178043d1dad4ec9bd50ad4db2df9ef994f098 | [
"MIT",
"Unlicense"
] | null | null | null | vintage_commands.py | ktuan89/Vintage | 81f178043d1dad4ec9bd50ad4db2df9ef994f098 | [
"MIT",
"Unlicense"
] | null | null | null | import sublime, sublime_plugin
import os
#import subprocess
def is_legal_path_char(c):
# XXX make this platform-specific?
return c not in " \n\"|*<>{}[]()"
def move_while_path_character(view, start, is_at_boundary, increment=1):
while True:
if not is_legal_path_char(view.substr(start)):
break
start = start + increment
if is_at_boundary(start):
break
return start
class ViOpenFileUnderSelectionCommand(sublime_plugin.TextCommand):
def run(self, edit):
#sel = self.view.sel()[0]
region = self.view.sel()[0]
"""if not sel.empty():
file_name = self.view.substr(sel)
else:
caret_pos = self.view.sel()[0].begin()
current_line = self.view.line(caret_pos)
left = move_while_path_character(
self.view,
caret_pos,
lambda x: x < current_line.begin(),
increment=-1)
right = move_while_path_character(
self.view,
caret_pos,
lambda x: x > current_line.end(),
increment=1)
file_name = self.view.substr(sublime.Region(left + 1, right))"""
if region.empty():
line = self.view.line(region)
file_name = self.view.substr(line)
else:
file_name = self.view.substr(region)
"""file_name = os.path.join(os.path.dirname(self.view.file_name()),
file_name)"""
if file_name.endswith(":"):
file_name = file_name[0:-1]
if os.path.exists(file_name):
self.view.window().open_file(file_name)
class CopyCurrentWord(sublime_plugin.TextCommand):
def run(self, edit):
for region in self.view.sel():
if region.empty():
sublime.set_clipboard(self.view.substr(self.view.word(region.begin())))
class OpenFileInXcode(sublime_plugin.TextCommand):
def run(self, edit):
if self.view.file_name() is not None:
#print self.view.file_name()
#subprocess.call(["open", "-a", "/Applications/Xcode.app", self.view.file_name()])
os.system("open -a /Applications/Xcode.app '" + self.view.file_name() + "'")
class ViSaveAndExit(sublime_plugin.WindowCommand):
def run(self):
self.window.run_command('save')
self.window.run_command('close')
if len(self.window.views()) == 0:
self.window.run_command('close')
#class MoveFocusedViewToBeginning(sublime_plugin.EventListener):
# def on_activated(self, view):
# view.window().set_view_index(view, 0, 0)
class ExtendedSwitcherHaha(sublime_plugin.WindowCommand):
# declarations
open_files = []
open_views = []
window = []
settings = []
# lets go
def run(self, list_mode):
print "Here here here"
# self.view.insert(edit, 0, "Hello, World!")
self.open_files = []
self.open_views = []
self.window = sublime.active_window()
self.settings = sublime.load_settings('ExtendedSwitcher.sublime-settings')
for f in self.getViews(list_mode):
# if skip the current active is enabled do not add the current file it for selection
if self.settings.get('skip_current_file') == True:
if f.id() == self.window.active_view().id():
continue
self.open_views.append(f) # add the view object
file_name = f.file_name() # get the full path
if file_name:
if f.is_dirty():
file_name += self.settings.get('mark_dirty_file_char') # if there are any unsaved changes to the file
if self.settings.get('show_full_file_path') == True:
self.open_files.append(os.path.basename(file_name) + ' - ' + os.path.dirname(file_name))
else:
self.open_files.append(os.path.basename(file_name))
else:
self.open_files.append("Untitled")
if self.check_for_sorting() == True:
self.sort_files()
self.window.show_quick_panel(self.open_files, self.tab_selected) # show the file list
# display the selected open file
def tab_selected(self, selected):
if selected > -1:
self.window.focus_view(self.open_views[selected])
return selected
# sort the files for display in alphabetical order
def sort_files(self):
open_files = self.open_files
open_views = []
open_files.sort()
for f in open_files:
for fv in self.open_views:
if fv.file_name():
f = f.replace(" - " + os.path.dirname(fv.file_name()),'')
if (f == os.path.basename(fv.file_name())) or (f == os.path.basename(fv.file_name())+self.settings.get('mark_dirty_file_char')):
open_views.append(fv)
self.open_views.remove(fv)
if f == "Untitled" and not fv.file_name():
open_views.append(fv)
self.open_views.remove(fv)
self.open_views = open_views
# flags for sorting
def check_for_sorting(self):
if self.settings.has("sort"):
return self.settings.get("sort", False)
def getViews(self, list_mode):
views = []
# get only the open files for the active_group
if list_mode == "active_group":
views = self.window.views_in_group(self.window.active_group())
# get all open view if list_mode is window or active_group doesnt not have any files open
if (list_mode == "window") or (len(views) < 1):
views = self.window.views()
return views
| 35.775148 | 148 | 0.561528 |
4f8da357def16952b60ee962980520b117479d93 | 65 | sql | SQL | test/JDBC/input/functions/sys-schema-name.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 | test/JDBC/input/functions/sys-schema-name.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 | test/JDBC/input/functions/sys-schema-name.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 | SELECT * FROM sys.schema_name()
GO
SELECT sys.schema_name()
GO
| 10.833333 | 32 | 0.738462 |
969e7e51ee8e2abcd2b80cd5563c8bf2dff26f63 | 6,408 | html | HTML | blogs/2018062722-The-Power-of-Social-Media.html | EdLab/memory | bc14ae93c4e129d1aa77a8783e55dca5c0ee486c | [
"MIT"
] | null | null | null | blogs/2018062722-The-Power-of-Social-Media.html | EdLab/memory | bc14ae93c4e129d1aa77a8783e55dca5c0ee486c | [
"MIT"
] | null | null | null | blogs/2018062722-The-Power-of-Social-Media.html | EdLab/memory | bc14ae93c4e129d1aa77a8783e55dca5c0ee486c | [
"MIT"
] | null | null | null | <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta
name="viewport"
content="width=device-width, initial-scale=1, shrink-to-fit=no"
/>
<meta name="description" content="" />
<meta name="author" content="" />
<title>The Power of Social Media | EdLab Blog</title>
<!-- Bootstrap core CSS -->
<link
rel="stylesheet"
href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css"
integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh"
crossorigin="anonymous"
/>
<!-- Custom styles for this template -->
<link href="../css/styles.css" rel="stylesheet" />
</head>
<body>
<!-- Navigation -->
<nav class="navbar navbar-expand-lg navbar-dark bg-dark fixed-top">
<div class="container">
<a class="navbar-brand" href="/">EdLab Archive</a>
<button
class="navbar-toggler"
type="button"
data-toggle="collapse"
data-target="#navbarResponsive"
aria-controls="navbarResponsive"
aria-expanded="false"
aria-label="Toggle navigation"
>
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarResponsive">
<ul class="navbar-nav ml-auto">
<li class="nav-item active">
<a class="nav-link" href="../blogs">Blogs</a>
</li>
<li class="nav-item">
<a class="nav-link " href="../profiles">Profiles</a>
</li>
<li class="nav-item ">
<a class="nav-link" href="../events">Events</a>
</li>
<li class="nav-item ">
<a class="nav-link" href="../projects">Projects</a>
</li>
</ul>
</div>
</div>
</nav>
<!-- Page Content -->
<div class="container content">
<div class="row">
<!-- Post Content Column -->
<div class="col-lg-8">
<div class="back-link">
<a href="./"> < back to list</a>
</div>
<!-- Title -->
<h1 class="mt-4">The Power of Social Media </h1>
<p class="lead">
SambaDou
</p>
<hr />
<!-- Date/Time -->
<p>
June 27, 2018
</p>
<hr />
<!-- Post Content -->
<p>
<p class="MsoNormal" style="margin:0in 0in 0.0001pt;">I have been a social media user for some time now. However, I never thought one of my professors would use social media (i.e. Twitter) for review a day before the exam. It was very helpful as many people participated, asked questions and it was a perfect way to study for an exam. In this <a href="https://www.npr.org/sections/ed/2018/01/26/579955559/teach-students-to-use-social-media-the-right-way-and-the-possibilities-are-endle" target="_blank" data-saferedirecturl="https://www.google.com/url?hl=en&q=https://www.npr.org/sections/ed/2018/01/26/579955559/teach-students-to-use-social-media-the-right-way-and-the-possibilities-are-endle&source=gmail&ust=1530240651658000&usg=AFQjCNE-ALSqtw6v43t-UWAk-vsNhd3cRQ">NPR piece</a>, the author talks about a teacher who wanted to show her students how fast information can be spread on the Internet and the power of social media. To demonstrate, the teacher and her students posted something on Twitter and asked people to retweet or reply to the post with their location. They expected about a 1,000 retweets, but after few days, there were 227,000 retweets.</p><p class="MsoNormal" style="margin:0in 0in 0.0001pt;"><span style="background-image:initial;background-position:initial;background-size:initial;background-repeat:initial;background-attachment:initial;background-origin:initial;background-clip:initial;"> </span></p><p class="MsoNormal" style="margin:0in 0in 0.0001pt;">The author believes that social media can be helpful when it’s being used the right way. She uses the same methods my professor was using with us to post assignments and as a forum for students to tweet questions or thoughts on a specific lesson. However, it can also cause issues such as keeping social media interactions between students and teachers appropriate.<span style="background-image:initial;background-position:initial;background-size:initial;background-repeat:initial;background-attachment:initial;background-origin:initial;background-clip:initial;"></span></p><p class="MsoNormal" style="margin:0in 0in 0.0001pt;"><span style="background-image:initial;background-position:initial;background-size:initial;background-repeat:initial;background-attachment:initial;background-origin:initial;background-clip:initial;"> </span></p><p class="MsoNormal" style="margin:0in 0in 0.0001pt;">Teachers have a different perspective on interacting with their students on social media. Some teachers avoid interacting with their students on social media because they feel like it’s too personal while others make the most of it. Some teachers use a dedicated hashtag to keep the students updated on classroom notes and homework assignments because they believe students check their social media accounts more than their school email.</p>
</p>
</div>
</div>
</div>
<!-- Footer -->
<footer class="py-5 bg-dark">
<div class="container">
<p class="m-0 text-center text-white">
Copyright © EdLab 2019 <script>new Date().getFullYear()>2019&&document.write("-"+new Date().getFullYear());</script>
</p>
</div>
<!-- /.container -->
</footer>
<!-- Bootstrap core JavaScript -->
<script
src="https://code.jquery.com/jquery-3.4.1.slim.min.js"
integrity="sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n"
crossorigin="anonymous"
></script>
<script
src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js"
integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo"
crossorigin="anonymous"
></script>
<script
src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js"
integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6"
crossorigin="anonymous"
></script>
</body>
</html>
| 53.848739 | 2,842 | 0.657928 |
dde98c3f791acaa29fe35bbe74233526f80de09f | 11,917 | lua | Lua | script/gui_settings_window.lua | eduran84/Train_Alerts | 0b25aaf0a645055f1d7c809e89d245fc0f1dfd2b | [
"MIT"
] | null | null | null | script/gui_settings_window.lua | eduran84/Train_Alerts | 0b25aaf0a645055f1d7c809e89d245fc0f1dfd2b | [
"MIT"
] | 1 | 2019-05-08T10:24:36.000Z | 2019-05-09T10:05:55.000Z | script/gui_settings_window.lua | eduran84/Train_Alerts | 0b25aaf0a645055f1d7c809e89d245fc0f1dfd2b | [
"MIT"
] | null | null | null | -- load modules
local EGM_Frame = require(defs.pathes.modules.EGM_Frame)
--localize functions and variables
local pairs, tonumber, floor, log2 = pairs, tonumber, math.floor, log2
local register_ui, unregister_ui = util.register_ui, util.unregister_ui
local raise_private_event = raise_private_event
local names = defs.names
local styles = names.styles
local element_names = names.gui.elements
local offset = defs.constants.timeout_offset
local col2state = {
-1,
defines.train_state.wait_signal,
defines.train_state.wait_station,
defines.train_state.no_path,
defines.train_state.manual_control,
defines.train_state.no_schedule,
}
-- localize access to relevant global variables
local tsm
local data = {
frames = {},
tables = {},
table_rows = {},
ui_elements = {},
}
-- UI functions --
local function build_frame(pind)
if debug_mode then
log2("Creating settings window for player", game.players[pind].name)
end
local frame = EGM_Frame.build(
game.players[pind].gui.center,
{
name = element_names.setting_frame,
caption = {"tral.setting-frame-caption"},
direction = "vertical",
style = styles.alert_window_frame
}
)
frame.style.maximal_height = defs.constants.setting_frame_max_height
register_ui(
data.ui_elements,
EGM_Frame.add_button(frame, {
type = "sprite-button",
style = styles.title_button,
sprite = "utility/close_white",
}),
{name = "close_window"}
)
frame.visible = false
local flow = EGM_Frame.get_flow(frame) -- content flow of this frame
flow.add{
type = "label",
caption = {"tral.ignore-explainer-1"},
style = styles.helper_label,
}
flow.add{
type = "label",
caption = {"tral.ignore-explainer-2"},
style = styles.helper_label,
}
local header_frame = flow.add{
type = "frame",
style = styles.table_header_frame,
}
local spritelist = {
[2] = "item/rail-signal",
[3] = "item/train-stop",
[4] = names.sprites.no_path,
[5] = "utility/show_player_names_in_map_view",
[6] = names.sprites.no_schedule,
}
header_frame.add{
type = "label",
style = "caption_label",
caption = {"tral.settings-col-header-1"}
}.style.width = defs.constants.id_label_width
header_frame.style.vertical_align = "center"
for i = 2, 6 do
local icon = header_frame.add{type = "flow", style = styles.image_flow}.add{
type = "sprite",
sprite = spritelist[i],
tooltip = {"tral.settings-col-header-tt-"..i}
}
end
local table = flow.add{
type = "frame",
style = styles.table_body_frame,
}.add{
type = "scroll-pane",
style = styles.table_pane,
vertical_scroll_policy = "auto-and-reserve-space",
horizontal_scroll_policy = "never",
}
return frame, table
end
local add_train_to_list -- defined later
local function reset(pind)
if debug_mode then
log2("Resetting settings window for player #", pind, "\n", debug.traceback())
else
log2("Resetting settings window for player #", pind)
end
local frame = data.frames[pind]
if frame and frame.valid then
unregister_ui(data.ui_elements, frame)
frame.destroy()
end
frame = game.players[pind].gui.center[element_names.setting_frame]
if frame and frame.valid then
unregister_ui(data.ui_elements, frame)
frame.destroy()
end
data.ui_elements[pind] = nil
for _, table_row in pairs(data.table_rows) do
table_row[pind] = nil
end
data.frames[pind], data.tables[pind] = build_frame(pind)
for train_id, train_data in pairs(tsm.ignored_trains) do
add_train_to_list({train_id = train_id}, pind)
end
end
local function get_frame(pind)
local frame = data.frames[pind]
if frame and frame.valid then return frame end
reset(pind)
return data.frames[pind]
end
local function get_table(pind)
local table = data.tables[pind]
if table and table.valid then return table end
reset(pind)
return data.tables[pind]
end
local function open(pind)
local frame = get_frame(pind)
frame.visible = true
game.players[pind].opened = frame
end
do
local label_def = {type = "label", style = styles.id_label, caption = ""}
local textbox_def = {}
for i = 2, 6 do
textbox_def[i] = {type = "text-box", style = styles.textbox_valid, text = ""}
end
add_train_to_list = function(event, pind)
local train_id = event.train_id
if train_id and (pind or not(data.table_rows[train_id])) then
data.table_rows[train_id] = data.table_rows[train_id] or {}
local label_action = {name = "train_label_clicked", train_id = train_id}
label_def.caption = train_id
local timeout_values = tsm.ignored_trains[train_id].timeout_values or shared.train_state_monitor.timeout_values
local players
if pind then
players = {[pind] = true}
else
players = game.players
end
for i = 2, 6 do
local timeout = timeout_values[col2state[i]]
textbox_def[i].text = timeout >= 0 and (timeout - offset) / 60 or -1
end
local textbox_action = {name = "timeout_text_changed", train_id = train_id}
for pind in pairs(players) do
local flow = get_table(pind).add{
type = "flow",
direction = "horizontal",
style = styles.table_row_flow
}
data.table_rows[train_id][pind] = {flow = flow, invalid_count = 0, was_valid = {}}
local flow_add = flow.add
register_ui(data.ui_elements, flow_add(label_def), label_action)
for _, tb in pairs(textbox_def) do
local box = flow_add(tb)
register_ui(data.ui_elements, box, textbox_action)
data.table_rows[train_id][pind].was_valid[box.index] = true
end
register_ui(
data.ui_elements,
flow_add{
type = "sprite-button",
sprite = "utility/confirm_slot",
style = "slot_button",
tooltip = {"tral.settings-apply-tt"},
},
{name = "confirm_timeouts", train_id = train_id}
)
register_ui(
data.ui_elements,
flow_add{
type = "sprite-button",
sprite = "utility/set_bar_slot",
style = "slot_button",
tooltip = {"tral.settings-reset-tt"},
},
{name = "reset_timeouts", train_id = train_id}
)
end
end
if not pind and event.player_index then open(event.player_index) end
end
end
local function remove_train_from_list(event)
local train_id = event.train_id
local train = tsm.ignored_trains[train_id].train
tsm.ignored_trains[train_id] = nil
if data.table_rows[train_id] then
for pind in pairs(game.players) do
local row = data.table_rows[train_id][pind].flow
unregister_ui(data.ui_elements, row)
if row and row.valid then row.destroy() end
end
data.table_rows[train_id] = nil
if train and train.valid then
raise_private_event(defs.events.on_timeouts_modified, {train = train, force = true})
end
end
end
-- event handlers --
local gui_actions = {}
function gui_actions.close_window(event, action)
get_frame(event.player_index).visible = false
end
function gui_actions.train_label_clicked(event, action)
local train_id = action.train_id
if event.button == 2 and tsm.ignored_trains[train_id] then --LMB
util.train.open_train_gui(event.player_index, tsm.ignored_trains[train_id].train)
local frame = get_frame(event.player_index)
frame.visible = true
else
event.train_id = train_id
remove_train_from_list(event)
end
end
function gui_actions.timeout_text_changed(event, action)
local box = event.element
local num = tonumber(box.text)
local player_data = data.table_rows[action.train_id][event.player_index]
local was_valid = player_data.was_valid[box.index]
local is_valid = num and num == floor(num) and num >= -1
if is_valid and not was_valid then -- turned valid
box.style = styles.textbox_valid
player_data.invalid_count = player_data.invalid_count - 1
player_data.was_valid[box.index] = is_valid
if player_data.invalid_count == 0 then
box.parent.children[7].enabled = true -- children[7] is the checkmark button
end
elseif not is_valid and was_valid then -- turned invalid
box.style = styles.textbox_invalid
player_data.invalid_count = player_data.invalid_count + 1
box.parent.children[7].enabled = false
player_data.was_valid[box.index] = is_valid
end
end
function gui_actions.confirm_timeouts(event, action)
local train_id = action.train_id
local flow = event.element.parent
tsm.ignored_trains[train_id].timeout_values = {}
for i = 2, 6 do
local timeout = tonumber(flow.children[i].text)
if timeout >= 0 then
timeout = timeout * 60 + offset
end
tsm.ignored_trains[train_id].timeout_values[col2state[i]] = timeout
end
if debug_mode then log2("New timeouts:", tsm.ignored_trains[train_id].timeout_values) end
raise_private_event(defs.events.on_timeouts_modified, {train = tsm.ignored_trains[train_id].train, force = true})
for pind, player in pairs(game.players) do
if pind ~= event.player_index then
gui_actions.reset_timeouts({player_index = pind, element = event.element}, {train_id = train_id})
end
end
end
gui_actions.reset_timeouts = function(event, action)
local timeout_values = tsm.ignored_trains[action.train_id].timeout_values
or shared.train_state_monitor.timeout_values
local flow = event.element.parent
local player_data = data.table_rows[action.train_id][event.player_index]
for i = 2, 6 do
local timeout = timeout_values[col2state[i]]
local box = flow.children[i]
box.text = timeout >=0 and (timeout - offset) / 60 or -1
box.style = styles.textbox_valid
player_data.invalid_count = player_data.invalid_count - 1
player_data.was_valid[box.index] = true
end
end
local on_gui_input = function(event)
local element = event.element
if not (element and element.valid) then return end
local player_data = data.ui_elements[event.player_index]
if not player_data then return end
local action = player_data[element.index]
if action then
if debug_mode then log2("event:", event, "\nplayer data:", player_data, "action:", action) end
gui_actions[action.name](event, action)
return true
end
end
local function on_gui_closed(event)
if event.element and event.element.name == element_names.setting_frame then
get_frame(event.player_index).visible = false
elseif event.entity and event.entity.type == "locomotive" then
local frame = get_frame(event.player_index)
if frame.visible then
game.players[event.player_index].opened = frame
end
end
end
local function on_player_created(event)
reset(event.player_index)
end
-- public module API --
local events =
{
[defines.events.on_gui_click] = on_gui_input,
[defines.events.on_gui_text_changed] = on_gui_input,
[defines.events.on_player_created] = on_player_created,
[defines.events.on_gui_closed] = on_gui_closed,
}
local private_events =
{
[defs.events.on_train_ignored] = add_train_to_list,
[defs.events.on_train_does_not_exist] = remove_train_from_list,
}
local gui_settings_window = {}
function gui_settings_window.on_init()
global.gui_settings_window = global.gui_settings_window or data
tsm = global.train_state_monitor
for pind in pairs(game.players) do
on_player_created({player_index = pind})
end
end
function gui_settings_window.on_load()
data = global.gui_settings_window
tsm = global.train_state_monitor
end
function gui_settings_window.get_events()
return events
end
function gui_settings_window.get_private_events()
return private_events
end
function gui_settings_window.on_configuration_changed(data)
if data.mod_changes[defs.names.mod_name] then
for pind in pairs(game.players) do
reset(pind)
end
end
end
return gui_settings_window | 31.278215 | 117 | 0.703113 |
4d4f6bcb8cdb1aceeb7b755afbfdd8068347d2d9 | 324 | asm | Assembly | oeis/254/A254157.asm | neoneye/loda-programs | 84790877f8e6c2e821b183d2e334d612045d29c0 | [
"Apache-2.0"
] | 11 | 2021-08-22T19:44:55.000Z | 2022-03-20T16:47:57.000Z | oeis/254/A254157.asm | neoneye/loda-programs | 84790877f8e6c2e821b183d2e334d612045d29c0 | [
"Apache-2.0"
] | 9 | 2021-08-29T13:15:54.000Z | 2022-03-09T19:52:31.000Z | oeis/254/A254157.asm | neoneye/loda-programs | 84790877f8e6c2e821b183d2e334d612045d29c0 | [
"Apache-2.0"
] | 3 | 2021-08-22T20:56:47.000Z | 2021-09-29T06:26:12.000Z | ; A254157: a(n) = binomial(3*n,n)^n.
; Submitted by Jon Maiga
; 1,3,225,592704,60037250625,244217432431215243,40928832685064366701940736,287432029715751041166252933120000000,85609985515193235253656684862285741981771256961,1091210761769150876962680951989752349788052377750396728515625
mov $2,$0
mul $0,3
bin $0,$2
pow $0,$2
| 36 | 221 | 0.833333 |
b88cb0728a4afe21410be5687a439bd5d05ea3d0 | 326 | html | HTML | Web8.html | julalber/Addiction-Dreamweaver-Project | 0d987a1e8d684d31094971f5777c1f99d4800938 | [
"MIT"
] | null | null | null | Web8.html | julalber/Addiction-Dreamweaver-Project | 0d987a1e8d684d31094971f5777c1f99d4800938 | [
"MIT"
] | null | null | null | Web8.html | julalber/Addiction-Dreamweaver-Project | 0d987a1e8d684d31094971f5777c1f99d4800938 | [
"MIT"
] | null | null | null | <!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>T</title>
<link href="style.css" rel="stylesheet" type="text/css">
</head>
<body>
<img src="Images/Web8BG.png" width="1366" height="768" alt=""/>
<a href="Web9.html" target="_blank">
<img src="Images/Web8Text.png" class="Web8Text" alt=""/>
</a>
</body>
</html>
| 18.111111 | 63 | 0.638037 |
7e7bd3fbb335518ba48d3ab666291f431cb1c3b0 | 606 | swift | Swift | PhotoSelector/PhotoSelector/PhotoSelectorViewController/UIImage+Category.swift | kingka/PhotoSelector | 66515a21804b392ca06df2f455112e150189097c | [
"MIT"
] | null | null | null | PhotoSelector/PhotoSelector/PhotoSelectorViewController/UIImage+Category.swift | kingka/PhotoSelector | 66515a21804b392ca06df2f455112e150189097c | [
"MIT"
] | null | null | null | PhotoSelector/PhotoSelector/PhotoSelectorViewController/UIImage+Category.swift | kingka/PhotoSelector | 66515a21804b392ca06df2f455112e150189097c | [
"MIT"
] | null | null | null | //
// UIImage+Category.swift
// PhotoSelector
//
// Created by Imanol on 16/5/24.
// Copyright © 2016年 imanol. All rights reserved.
//
import UIKit
extension UIImage
{
func imageWithWidth(width : CGFloat)-> UIImage
{
let height = width * size.height/size.width
let currentSize = CGSize(width: width, height: height)
UIGraphicsBeginImageContext(currentSize)
drawInRect(CGRect(origin: CGPointZero, size: currentSize))
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage
}
}
| 24.24 | 66 | 0.673267 |
6f7043fe782925cf183580c88d6ba0d3f9e5aff7 | 1,070 | rs | Rust | src/core.rs | Shadlock0133/type-plugs | 2457b0f54f7ede9187148c7bf7a85405c3821522 | [
"MIT"
] | null | null | null | src/core.rs | Shadlock0133/type-plugs | 2457b0f54f7ede9187148c7bf7a85405c3821522 | [
"MIT"
] | null | null | null | src/core.rs | Shadlock0133/type-plugs | 2457b0f54f7ede9187148c7bf7a85405c3821522 | [
"MIT"
] | null | null | null | #[allow(non_camel_case_types, bare_trait_objects)]
pub struct forall_t;
macro_rules! plug {
($t1:ty [ $t2:ty ]) => {
<$t1 as Plug<$t2>>::result_t
};
}
macro_rules! unplug {
($t:ty, $v:ident) => {
<$t as Unplug>::$v
};
}
pub struct Concrete<M: Unplug + Plug<A>, A> {
pub unwrap: plug!(M[A]),
}
impl<M: Unplug + Plug<A>, A> Clone for Concrete<M, A>
where
plug!(M[A]): Clone + Unplug<F = M, A = A>,
{
fn clone(&self) -> Self {
Concrete::of(self.unwrap.clone())
}
}
impl<M: Unplug + Plug<A>, A> Concrete<M, A> {
pub fn of<MA: Unplug<F = M, A = A> + Plug<A>>(x: MA) -> Self
where
M: Plug<A, result_t = MA>,
{
Concrete { unwrap: x }
}
}
pub trait Unplug: Sized {
type F: Unplug + Plug<Self::A>;
type A;
}
pub trait Plug<A>: Sized {
type result_t: Plug<A> + Unplug;
}
impl<M: Plug<A> + Plug<B> + Unplug, A, B> Plug<B> for Concrete<M, A> {
type result_t = Concrete<M, B>;
}
impl<M: Plug<A> + Unplug, A> Unplug for Concrete<M, A> {
type F = M;
type A = A;
}
| 19.454545 | 70 | 0.535514 |
afa0473f947844533982f6a7e0e8af82a4012cb7 | 528 | rb | Ruby | bot.rb | S-H-GAMELINKS/face_under_construction | 2c7ac94462a4686bd716a8136f09328671ad6d98 | [
"MIT"
] | null | null | null | bot.rb | S-H-GAMELINKS/face_under_construction | 2c7ac94462a4686bd716a8136f09328671ad6d98 | [
"MIT"
] | null | null | null | bot.rb | S-H-GAMELINKS/face_under_construction | 2c7ac94462a4686bd716a8136f09328671ad6d98 | [
"MIT"
] | null | null | null | load_paths = Dir["/vendor/bundle/ruby/2.5.0/gems/2.5.0/**/lib"]
$LOAD_PATH.unshift(*load_paths)
require "dotenv"
require "json"
require 'mastodon'
Dotenv.env
def lambda_handler(event:, context:)
client = Mastodon::REST::Client.new(base_url: ENV["MASTODON_URL"], bearer_token: ENV["MASTODON_ACCESS_TOKEN"])
client.hashtag_timeline("顔面工事", :limit => 5000).each do |toot|
if !toot.reblogged? then
response = client.reblog(toot.id)
response = client.favourite(toot.id)
end
end
end
| 25.142857 | 112 | 0.679924 |
5f5fd90edd5834c2aafbd5f673b240c0274dbf97 | 7,203 | ts | TypeScript | src/websocket/recorder.ts | one-dev-man/vosk-stream | d9f93d3a3ec4817792d7ef4359746b8dcdf870cc | [
"Apache-2.0"
] | null | null | null | src/websocket/recorder.ts | one-dev-man/vosk-stream | d9f93d3a3ec4817792d7ef4359746b8dcdf870cc | [
"Apache-2.0"
] | null | null | null | src/websocket/recorder.ts | one-dev-man/vosk-stream | d9f93d3a3ec4817792d7ef4359746b8dcdf870cc | [
"Apache-2.0"
] | null | null | null | import { Listener } from "../utils/listener.class";
type RECORD_EVENTS = "start" | "data" | "stop";
export class Record_ extends Listener {
#type: string;
#stream: MediaStream | null = null;
#media_recorder: MediaRecorder | null = null;
#recorder: Recorder | null;
#chunks: Array<Blob> | null = null;
#blob: Blob | null = null;
#blob_callbacks: Array<Function> = new Array<Function>();
#stopped = true;
#request_data_interval: any = null;
constructor({ type, recorder=null }: { type: string, recorder?: Recorder | null }) {
super();
this.#type = type;
this.#recorder = recorder;
this.recorder?.records.add(this);
}
//
get type() { return this.#type; }
get stream() { return this.#stream; }
get media_recorder() { return this.#media_recorder; }
get recorder() { return this.#recorder; }
get stopped() { return this.#stopped; }
//
on(event: RECORD_EVENTS, callback: Function) { return super.on(event, callback); }
once(event: RECORD_EVENTS, callback: Function) { return super.once(event, callback); }
removeListener(event: RECORD_EVENTS, callback: Function): void { return super.removeListener(event, callback); }
removeListeners(event: RECORD_EVENTS): void { return super.removeListeners(event); }
off(event: RECORD_EVENTS, callback?: Function): void { return super.off(event, callback); }
callEvent(event: RECORD_EVENTS, ...args: any) { return super.callEvent(event, ...args); }
//
setStreamRate(ms: number) {
clearInterval(this.#request_data_interval);
this.#request_data_interval = setInterval(() => { this.media_recorder?.requestData(); }, ms);
}
//
async start() {
this.#stopped = false;
this.#chunks = new Array<Blob>();
this.#stream = await navigator.mediaDevices.getUserMedia({
video: false,
audio: {
echoCancellation: true,
noiseSuppression: true,
channelCount: 1,
sampleRate: 16000
}
});
this.#media_recorder = new MediaRecorder(this.#stream);
if(this.media_recorder) {
this.media_recorder.addEventListener("dataavailable", async (e: any) => {
if(!e.data) return;
if(e.data.size == 0) return;
this.#chunks?.push(e.data);
this.callEvent("data", await e.data.arrayBuffer());
});
this.media_recorder.start();
this.setStreamRate(500);
this.callEvent("start");
return true;
}
return false;
}
stop() {
return new Promise((resolve, reject) => {
if(this.media_recorder && this.stream) {
if(this.media_recorder.state != "inactive") {
this.media_recorder.addEventListener("stop", (e: any) => {
this.#blob = new Blob(this.#chunks as any, { type: this.type });
this.#blob_callbacks.forEach(cb => { cb(); });
let bcbl = this.#blob_callbacks.length;
for(let i = 0; i < bcbl; ++i) { this.#blob_callbacks.shift(); }
let stream_tracks = this.stream?.getTracks();
stream_tracks?.forEach(track => {
track.stop();
});
clearInterval(this.#request_data_interval);
this.#stopped = true;
this.callEvent("stop");
resolve(true);
});
this.media_recorder.stop();
}
}
});
}
//
async blob(): Promise<Blob> {
return new Promise((resolve, reject) => {
if(this.#blob instanceof Blob) { resolve(this.#blob); }
else { this.#blob_callbacks.push(() => {
if(this.#blob instanceof Blob) { resolve(this.#blob); }
}); }
})
}
async base64() {
let blob = await this.blob();
let file = new File([blob], "record", { type: this.type });
let file_buffer = (await (file.stream() as any).getReader().read()).value;
return buffer2b64(file_buffer);
}
async datauri() {
return "data:"+this.type+";base64,"+(await this.base64());
}
//
remove() {
this.recorder?.records.remove(this);
}
}
class RecordList {
#list = new Array<Record_>();
constructor() {
}
//
get(index: number) {
return this.#list[index];
}
add(record: Record_) {
if(!this.#list.includes(record)) { this.#list.push(record); }
}
remove(record: Record_ | number) {
let index = record instanceof Record_ ? this.#list.indexOf(record) : record;
if(index > -1 && index < this.#list.length) {
let a = new Array<Record_>(), b = new Array<Record_>();
for(let i = 0; i < index; ++i) { a.push(this.#list[i]); }
for(let i = index+1; i < this.#list.length; ++i) { b.push(this.#list[i]); }
this.#list = a.concat(b);
}
}
all(): ReadonlyArray<Record_> {
let result = new Array<Record_>();
for(let i = 0; i < this.#list.length; ++i) { result.push(this.#list[i]); }
return result;
}
clear() {
this.#list = new Array<Record_>();
}
}
export class Recorder {
static Record = Record_
//
#records = new RecordList();
constructor() {
}
//
get records() { return this.#records; }
//
record(options?: { type?: string } | undefined) {
let record = new Record_({ type: options?.type || "audio/wav", recorder: this });
return record;
}
stop() {
this.records.all().forEach(record => {
record.stop();
});
}
clear() {
this.stop();
this.records.clear();
}
}
function buffer2b64(arrayBuffer: ArrayLike<any> | ArrayBufferLike | Uint8Array) { let base64 = ''; let encodings = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; let bytes = new Uint8Array(arrayBuffer); let byteLength = bytes.byteLength; let byteRemainder = byteLength % 3; let mainLength = byteLength - byteRemainder; let a, b, c, d; let chunk; for (let i = 0; i < mainLength; i = i + 3) { chunk = (bytes[i] << 16) | (bytes[i + 1] << 8) | bytes[i + 2]; a = (chunk & 16515072) >> 18; b = (chunk & 258048) >> 12; c = (chunk & 4032) >> 6; d = chunk & 63; base64 += encodings[a] + encodings[b] + encodings[c] + encodings[d]; } if (byteRemainder == 1) { chunk = bytes[mainLength]; a = (chunk & 252) >> 2; b = (chunk & 3) << 4; base64 += encodings[a] + encodings[b] + '=='; } else if (byteRemainder == 2) { chunk = (bytes[mainLength] << 8) | bytes[mainLength + 1]; a = (chunk & 64512) >> 10; b = (chunk & 1008) >> 4; c = (chunk & 15) << 2; base64 += encodings[a] + encodings[b] + encodings[c] + '='; } return base64; }
try { window ? window["Recorder"] = Recorder : null; } catch(e) {} | 30.138075 | 1,034 | 0.537693 |
16b61509a05bd8640bfa9ab470784813e7dfbfa2 | 1,301 | ts | TypeScript | __tests__/exports/index.test.ts | BlackGlory/iterable-operator | d1b6c54baf019d0a7922c94e804d877a723b1436 | [
"MIT"
] | 2 | 2020-03-03T16:37:42.000Z | 2021-12-25T08:01:08.000Z | __tests__/exports/index.test.ts | BlackGlory/iterable-operator | d1b6c54baf019d0a7922c94e804d877a723b1436 | [
"MIT"
] | 11 | 2020-02-23T15:34:49.000Z | 2021-12-24T18:19:45.000Z | __tests__/exports/index.test.ts | BlackGlory/iterable-operator | d1b6c54baf019d0a7922c94e804d877a723b1436 | [
"MIT"
] | null | null | null | import * as Index from '@src/index'
test('Index', () => {
const expectedExports: string[] = [
'chunkAsync'
, 'chunkByAsync'
, 'chunkBy'
, 'chunk'
, 'concatAsync'
, 'concat'
, 'dropAsync'
, 'dropRightAsync'
, 'dropRight'
, 'dropUntilAsync'
, 'dropUntil'
, 'drop'
, 'filterAsync'
, 'filter'
, 'flattenAsync'
, 'flattenByAsync'
, 'flattenBy'
, 'flattenDeepAsync'
, 'flattenDeep'
, 'flatten'
, 'mapAsync'
, 'map'
, 'repeatAsync'
, 'repeat'
, 'sliceAsync'
, 'slice'
, 'splitAsync'
, 'splitByAsync'
, 'splitBy'
, 'split'
, 'takeAsync'
, 'takeRightAsync'
, 'takeRight'
, 'takeUntilAsync'
, 'takeUntil'
, 'take'
, 'tapAsync'
, 'tap'
, 'toAsyncIterable'
, 'transformAsync'
, 'transform'
, 'uniqAsync'
, 'uniqByAsync'
, 'uniqBy'
, 'uniq'
, 'zipAsync'
, 'zip'
, 'consume'
, 'eachAsync'
, 'each'
, 'everyAsync'
, 'every'
, 'findAsync'
, 'find'
, 'firstAsync'
, 'first'
, 'includesAsync'
, 'includes'
, 'matchAsync'
, 'match'
, 'reduceAsync'
, 'reduce'
, 'someAsync'
, 'some'
, 'lastAsync'
, 'last'
, 'toArrayAsync'
, 'toArray'
, 'toSetAsync'
, 'toSet'
].sort()
const actualExports = Object.keys(Index).sort()
expect(actualExports).toEqual(expectedExports)
})
| 15.865854 | 49 | 0.568793 |
6f4047a6a8d838d59664816ae6a57df66f975cdb | 1,820 | kt | Kotlin | arrow-libs/core/arrow-core-data/src/main/kotlin/arrow/typeclasses/MonadFilter.kt | clojj/arrow | 5eae605bbaeb2b911f69a5bccf3fa45c42578416 | [
"Apache-2.0"
] | null | null | null | arrow-libs/core/arrow-core-data/src/main/kotlin/arrow/typeclasses/MonadFilter.kt | clojj/arrow | 5eae605bbaeb2b911f69a5bccf3fa45c42578416 | [
"Apache-2.0"
] | null | null | null | arrow-libs/core/arrow-core-data/src/main/kotlin/arrow/typeclasses/MonadFilter.kt | clojj/arrow | 5eae605bbaeb2b911f69a5bccf3fa45c42578416 | [
"Apache-2.0"
] | null | null | null | package arrow.typeclasses
import arrow.Kind
import arrow.KindDeprecation
import arrow.core.Option
import kotlin.coroutines.startCoroutine
@Deprecated(KindDeprecation)
interface MonadFilter<F> : Monad<F>, FunctorFilter<F> {
override val fx: MonadFilterFx<F>
get() = object : MonadFilterFx<F> {
override val MF: MonadFilter<F> = this@MonadFilter
}
fun <A> empty(): Kind<F, A>
override fun <A, B> Kind<F, A>.filterMap(f: (A) -> Option<B>): Kind<F, B> =
this.flatMap { a -> f(a).fold({ empty<B>() }, { just(it) }) }
@Deprecated(
"`bindingFilter` is getting renamed to `fx` for consistency with the Arrow Fx system. Use the Fx extensions for comprehensions",
ReplaceWith("fx.monadFilter(c)")
)
fun <B> bindingFilter(c: suspend MonadFilterSyntax<F>.() -> B): Kind<F, B> {
val continuation = MonadFilterContinuation<F, B>(this)
val wrapReturn: suspend MonadFilterSyntax<F>.() -> Kind<F, B> = { just(c()) }
wrapReturn.startCoroutine(continuation, continuation)
return continuation.returnedMonad()
}
}
interface MonadFilterFx<F> : MonadFx<F> {
val MF: MonadFilter<F>
override val M: Monad<F> get() = MF
/**
* Entry point for monad bindings which enables for comprehension. The underlying impl is based on coroutines.
* A coroutine is initiated and inside [MonadContinuation] suspended yielding to [flatMap]. Once all the flatMap binds are completed
* the underlying monad is returned from the act of executing the coroutine
*/
fun <A> monadFilter(c: suspend MonadFilterSyntax<F>.() -> A): Kind<F, A> {
val continuation = MonadFilterContinuation<F, A>(MF)
val wrapReturn: suspend MonadFilterSyntax<F>.() -> Kind<F, A> = { just(c()) }
wrapReturn.startCoroutine(continuation, continuation)
return continuation.returnedMonad()
}
}
| 37.142857 | 134 | 0.698352 |
18cb4b75a976356df2df75380059b5b2a764b00e | 1,025 | rb | Ruby | lib/pacer/pipe/block_filter_pipe.rb | rjurney/pacer | ee6f2d237efce0ea0b54adcf3ed62c6cc14dc166 | [
"BSD-3-Clause"
] | 1 | 2019-03-07T16:32:26.000Z | 2019-03-07T16:32:26.000Z | lib/pacer/pipe/block_filter_pipe.rb | rjurney/pacer | ee6f2d237efce0ea0b54adcf3ed62c6cc14dc166 | [
"BSD-3-Clause"
] | null | null | null | lib/pacer/pipe/block_filter_pipe.rb | rjurney/pacer | ee6f2d237efce0ea0b54adcf3ed62c6cc14dc166 | [
"BSD-3-Clause"
] | null | null | null | module Pacer::Pipes
class BlockFilterPipe < AbstractPipe
field_reader :starts
def initialize(back, block, invert = false)
super()
@back = back
@block = block
@graph = back.graph
@invert = invert
@exts = @back.extensions + [Pacer::Extensions::BlockFilterElement]
@is_element = @graph.element_type?(back.element_type) if @graph
end
def processNextStart()
while raw_element = starts.next
if @is_element
extended_element = raw_element.add_extensions(@exts)
extended_element.back = @back
extended_element.graph = @back.graph
ok = @block.call extended_element
else
ok = @block.call raw_element
end
ok = !ok if @invert
return raw_element if ok
end
raise Pacer::NoSuchElementException
rescue NativeException => e
if e.cause.getClass == Pacer::NoSuchElementException.getClass
raise e.cause
else
raise e
end
end
end
end
| 26.282051 | 72 | 0.622439 |
3be8cf6d37372152a82834c8b302600f5ae7e411 | 455 | h | C | Native/Blackberry-Cascades/pushCollector/src/pushwoosh/request/PWApplicationEventRequest.h | robertrumney/pushwoosh-sdk-samples | 55ccad683de8cec2f751ff1778045d04b9621c7e | [
"MIT"
] | 1 | 2022-02-08T14:01:20.000Z | 2022-02-08T14:01:20.000Z | Native/Blackberry-Cascades/pushCollector/src/pushwoosh/request/PWApplicationEventRequest.h | robertrumney/pushwoosh-sdk-samples | 55ccad683de8cec2f751ff1778045d04b9621c7e | [
"MIT"
] | null | null | null | Native/Blackberry-Cascades/pushCollector/src/pushwoosh/request/PWApplicationEventRequest.h | robertrumney/pushwoosh-sdk-samples | 55ccad683de8cec2f751ff1778045d04b9621c7e | [
"MIT"
] | null | null | null | //
// PWApplicationEventRequest
// Pushwoosh SDK
// (c) Pushwoosh 2014
//
#include "PWRequest.h"
class PWApplicationEventRequest : public PWRequest
{
QString goal;
int count;
public:
PWApplicationEventRequest(const QString & appId, const QString & goal, int count = -1)
: PWRequest(appId),
goal(goal),
count(count)
{}
virtual QString methodName()const;
virtual QVariantMap requestDictionary()const;
};
| 18.958333 | 90 | 0.672527 |
7f1dd8b81c003e8be59e8917028334f52da5d4b2 | 3,131 | go | Go | crypto/mac/aes_cmac128_test.go | hmmftg/libiso | 3bccda00850e31e1c814371a8458f43f0e5f77fc | [
"Apache-2.0"
] | 33 | 2015-06-05T10:17:49.000Z | 2020-02-23T09:27:24.000Z | crypto/mac/aes_cmac128_test.go | hmmftg/libiso | 3bccda00850e31e1c814371a8458f43f0e5f77fc | [
"Apache-2.0"
] | 8 | 2017-08-07T10:29:26.000Z | 2020-04-22T09:00:32.000Z | crypto/mac/aes_cmac128_test.go | hmmftg/libiso | 3bccda00850e31e1c814371a8458f43f0e5f77fc | [
"Apache-2.0"
] | 17 | 2016-11-05T04:26:43.000Z | 2020-04-22T04:19:26.000Z | package mac
import (
"bytes"
"encoding/hex"
"testing"
)
//test vectors
//http://csrc.nist.gov/publications/nistpubs/800-38B/Updated_CMAC_Examples.pdf
/*
--------------------------------------------------
Subkey Generation
K 2b7e1516 28aed2a6 abf71588 09cf4f3c
AES-128(key,0) 7df76b0c 1ab899b3 3e42f047 b91b546f
K1 fbeed618 35713366 7c85e08f 7236a8de
K2 f7ddac30 6ae266cc f90bc11e e46d513b
--------------------------------------------------
--------------------------------------------------
Example 1: len = 0
M <empty string>
AES-CMAC bb1d6929 e9593728 7fa37d12 9b756746
--------------------------------------------------
Example 2: len = 16
M 6bc1bee2 2e409f96 e93d7e11 7393172a
AES-CMAC 070a16b4 6b4d4144 f79bdd9d d04a287c
--------------------------------------------------
Example 3: len = 40
M 6bc1bee2 2e409f96 e93d7e11 7393172a
ae2d8a57 1e03ac9c 9eb76fac 45af8e51
30c81c46 a35ce411
AES-CMAC dfa66747 de9ae630 30ca3261 1497c827
--------------------------------------------------
Example 4: len = 64
M 6bc1bee2 2e409f96 e93d7e11 7393172a
ae2d8a57 1e03ac9c 9eb76fac 45af8e51
30c81c46 a35ce411 e5fbc119 1a0a52ef
f69f2445 df4f9b17 ad2b417b e66c3710
AES-CMAC 51f0bebf 7e3b9d92 fc497417 79363cfe
--------------------------------------------------
*/
func Test_AesCmac(t *testing.T) {
key, _ := hex.DecodeString("2b7e151628aed2a6abf7158809cf4f3c")
message := make([]byte, 0)
expectedMac, _ := hex.DecodeString("bb1d6929e95937287fa37d129b756746")
mac := AesCmac128(key, message)
if !bytes.Equal(mac, expectedMac) {
t.Fail()
}
}
func Test_AesCmac_Example2(t *testing.T) {
key, _ := hex.DecodeString("2b7e151628aed2a6abf7158809cf4f3c")
message, _ := hex.DecodeString("6bc1bee22e409f96e93d7e117393172a")
expectedMac, _ := hex.DecodeString("070a16b46b4d4144f79bdd9dd04a287c")
mac := AesCmac128(key, message)
if !bytes.Equal(mac, expectedMac) {
t.Fail()
}
}
func Test_AesCmac_Example3(t *testing.T) {
key, _ := hex.DecodeString("2b7e151628aed2a6abf7158809cf4f3c")
message, _ := hex.DecodeString("6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e5130c81c46a35ce411")
expectedMac, _ := hex.DecodeString("dfa66747de9ae63030ca32611497c827")
mac := AesCmac128(key, message)
if !bytes.Equal(mac, expectedMac) {
t.Logf("%s!=%s", hex.EncodeToString(mac), hex.EncodeToString(expectedMac))
t.Fail()
}
}
func Test_AesCmac_Example4(t *testing.T) {
key, _ := hex.DecodeString("2b7e151628aed2a6abf7158809cf4f3c")
message, _ := hex.DecodeString("6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e5130c81c46a35ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710")
expectedMac, _ := hex.DecodeString("51f0bebf7e3b9d92fc49741779363cfe")
mac := AesCmac128(key, message)
if !bytes.Equal(mac, expectedMac) {
t.Logf("%s!=%s", hex.EncodeToString(mac), hex.EncodeToString(expectedMac))
t.Fail()
}
}
| 30.398058 | 163 | 0.624082 |
93dedba4090e7ef4208aad08c2ec3a4a55dd351c | 588 | swift | Swift | StreamBaseExample/Message.swift | WildDogTeam/demo-ios-streambase | a7472943a5a485f78e61df7562017435b732eff3 | [
"MIT"
] | 1 | 2016-12-29T07:02:57.000Z | 2016-12-29T07:02:57.000Z | StreamBaseExample/Message.swift | WildDogTeam/demo-ios-streambase | a7472943a5a485f78e61df7562017435b732eff3 | [
"MIT"
] | null | null | null | StreamBaseExample/Message.swift | WildDogTeam/demo-ios-streambase | a7472943a5a485f78e61df7562017435b732eff3 | [
"MIT"
] | null | null | null | //
// Message.swift
// StreamBaseExample
//
// Created by IMacLi on 15/11/2.
// Copyright © 2015年 liwuyang. All rights reserved.
//
import Foundation
import Wilddog
class Message : BaseItem {
var text: String?
var username: String?
override func update(dict: [String : AnyObject]?) {
super.update(dict)
text = dict?["text"] as? String
username = dict?["username"] as? String
}
override var dict: [String: AnyObject] {
var d = super.dict
d["text"] = text
d["username"] = username
return d
}
} | 20.275862 | 55 | 0.586735 |
d0274d881e4cc47d03e3929e46cd03d3f1833e0c | 566 | rb | Ruby | test/helpers/reactions_helper_test.rb | qutorial/vulnswatch | 3f555b381e2ded6461cb802c0075501338bc8e86 | [
"MIT"
] | 4 | 2017-07-19T10:01:08.000Z | 2021-01-18T06:24:06.000Z | test/helpers/reactions_helper_test.rb | qutorial/vulnswatch | 3f555b381e2ded6461cb802c0075501338bc8e86 | [
"MIT"
] | 42 | 2017-07-19T13:51:26.000Z | 2018-02-14T11:22:35.000Z | test/helpers/reactions_helper_test.rb | qutorial/vulnswatch | 3f555b381e2ded6461cb802c0075501338bc8e86 | [
"MIT"
] | 3 | 2018-04-11T11:17:00.000Z | 2018-08-01T02:45:20.000Z | require 'test_helper'
class ReactionsHelperTest < ActiveSupport::TestCase
include ReactionsHelper
test "status to integer index works" do
(1..4).each do |n|
res = status_to_integer_index(n)
assert res.class == Integer
assert n == (res + 1)
end
(1..4).each do |n|
res = status_to_integer_index(n.to_s)
assert res.class == Integer
assert n == (res + 1)
end
assert status_to_integer_index(0).nil?
assert status_to_integer_index(5).nil?
assert status_to_integer_index(nil).nil?
end
end
| 20.214286 | 51 | 0.651943 |
c151dd71f5e76a8c0d17f3d86aa2475884e45586 | 847 | rs | Rust | trans/src/impls/tuples.rs | fizruk/trans-gen | 9a5b4635b39a18e9844a4bf40e8ca582fc3ffca2 | [
"MIT"
] | null | null | null | trans/src/impls/tuples.rs | fizruk/trans-gen | 9a5b4635b39a18e9844a4bf40e8ca582fc3ffca2 | [
"MIT"
] | 60 | 2020-04-18T20:25:33.000Z | 2021-02-25T14:36:53.000Z | trans/src/impls/tuples.rs | fizruk/trans-gen | 9a5b4635b39a18e9844a4bf40e8ca582fc3ffca2 | [
"MIT"
] | 2 | 2020-04-18T16:52:27.000Z | 2021-02-12T09:25:41.000Z | use super::*;
macro_rules! impl_for_tuple {
($($name:ident),*) => {
#[allow(non_snake_case, unused_variables)]
impl<$($name: Trans),*> Trans for ($($name,)*) {
fn create_schema(_version: &Version) -> Schema {
todo!()
}
fn read_from(reader: &mut dyn std::io::Read, version: &Version) -> std::io::Result<Self> {
Ok(($(<$name as Trans>::read_from(reader, version)?,)*))
}
fn write_to(&self, writer: &mut dyn std::io::Write, version: &Version) -> std::io::Result<()> {
let ($($name,)*) = self;
$($name.write_to(writer, version)?;)*
Ok(())
}
}
};
}
impl_for_tuple!();
impl_for_tuple!(A);
impl_for_tuple!(A, B);
impl_for_tuple!(A, B, C);
impl_for_tuple!(A, B, C, D);
| 31.37037 | 107 | 0.492326 |
fd8226b2b9f7673d4e5338d36ff98453e9d99c5e | 3,938 | swift | Swift | Tests/OperationsTests/OperationsTests.swift | dreymonde/Operations | d069c90f405898b5ad3ee3250597065522ebf2f2 | [
"MIT"
] | 1 | 2018-03-06T12:32:44.000Z | 2018-03-06T12:32:44.000Z | Tests/OperationsTests/OperationsTests.swift | dreymonde/Operations | d069c90f405898b5ad3ee3250597065522ebf2f2 | [
"MIT"
] | null | null | null | Tests/OperationsTests/OperationsTests.swift | dreymonde/Operations | d069c90f405898b5ad3ee3250597065522ebf2f2 | [
"MIT"
] | null | null | null | //
// OperationsTests.swift
// Operations
//
// Created by Oleg Dreyman on 3/6/18.
// Copyright © 2018 Operations. All rights reserved.
//
import Foundation
import XCTest
import Operations
class AsyncPutOperation : AsyncOperation {
let number: Int
let put: (Int) -> ()
init(number: Int, put: @escaping (Int) -> ()) {
self.number = number
self.put = put
super.init()
self.name = "put-\(number)"
}
deinit {
print("Deinit", name ?? "UNK")
}
override func execute() {
print(number, "Running")
DispatchQueue.global(qos: .utility).asyncAfter(deadline: .now() + 0.5) {
guard !self.isCancelled else {
self.finish()
return
}
self.put(self.number)
self.finish()
}
}
override func willFinish() {
print(number, "Finishing...")
}
override func didFinish() {
print(number, "Finished")
}
}
class OperationsTests: XCTestCase {
func testExample() {
// This is an example of a functional test case.
// Use XCTAssert and related functions to verify your tests produce the correct results.
//// XCTAssertEqual(Operations().text, "Hello, World!")
}
func testArray() {
var ar: [Int] = []
let queue = CustomOperationQueue()
.logging()
queue.name = "test-array"
let put1 = AsyncPutOperation(number: 1, put: { ar.append($0) })
put1.completionBlock = {
print("Block 1")
}
let put2 = AsyncPutOperation(number: 2, put: { ar.append($0) })
let obsF = put1.observe(\.isFinished, options: [.old, .new]) { (_, change) in
print("OP1", "isFinished", change.oldValue!, change.newValue!)
}
let obsE = put1.observe(\.isExecuting, options: [.old, .new]) { (_, change) in
print("OP1", "isExecuting", change.oldValue!, change.newValue!)
}
let obsC = put1.observe(\.isCancelled, options: [.old, .new]) { (_, change) in
print("OP1", "isCancelled", change.oldValue!, change.newValue!)
}
put2.addDependency(put1)
let obsR = put2.observe(\.isReady, options: [.old, .new]) { (_, change) in
print("OP2", "isReady", change.oldValue!, change.newValue!)
}
unwarn(obsF, obsE, obsC, obsR)
let expectation = self.expectation(description: "waiting on put2")
put2.completionBlock = {
print(ar)
expectation.fulfill()
}
queue.addOperation(put1)
queue.addOperation(put2)
waitForExpectations(timeout: 5.0)
XCTAssertEqual(ar, [1, 2])
}
func testAsyncBlock() {
let queue = CustomOperationQueue()
.logging()
queue.name = "test-async-block"
var str: String?
let block = AsyncBlockOperation { finish in
DispatchQueue.global(qos: .background).asyncAfter(deadline: .now() + 0.2, execute: {
str = "Hey"
finish()
})
}
let expectation = self.expectation(description: "block")
block.completionBlock = {
expectation.fulfill()
}
queue.addOperation(block)
waitForExpectations(timeout: 5.0)
XCTAssertEqual(str, "Hey")
}
func testCancel() {
let queue = OperationQueue(name: "test-cancel")
let op = BlockOperation {
print("so-so")
}
op.cancel()
let expectation = self.expectation(description: "on cancelled")
op.completionBlock = {
expectation.fulfill()
}
queue.addOperation(op)
waitForExpectations(timeout: 5.0)
}
static var allTests = [
("testExample", testExample),
]
}
func unwarn(_ obj: Any...) {
return
}
| 28.955882 | 96 | 0.548502 |
0ad23f182d1ebd0067404ddec5597ba4a7a95f60 | 338 | kt | Kotlin | cat-facts-persistence-postgresql/src/main/kotlin/com/danielbostwick/catfacts/persistence/postgresql/schema/CatFactAccountsSchema.kt | bostwick/cat-facts | b9194a44b2c1cf606a2e7f4d1a7a6257c598885c | [
"MIT"
] | null | null | null | cat-facts-persistence-postgresql/src/main/kotlin/com/danielbostwick/catfacts/persistence/postgresql/schema/CatFactAccountsSchema.kt | bostwick/cat-facts | b9194a44b2c1cf606a2e7f4d1a7a6257c598885c | [
"MIT"
] | null | null | null | cat-facts-persistence-postgresql/src/main/kotlin/com/danielbostwick/catfacts/persistence/postgresql/schema/CatFactAccountsSchema.kt | bostwick/cat-facts | b9194a44b2c1cf606a2e7f4d1a7a6257c598885c | [
"MIT"
] | null | null | null | package com.danielbostwick.catfacts.persistence.postgresql.schema
object CatFactAccountsSchema {
const val TABLE_NAME = "cat_fact_accounts"
const val COLUMN_ID = "id"
const val COLUMN_NAME = "name"
const val COLUMN_CREATED_AT = "created_at"
const val QUERY_PARAM_ID = "id"
const val QUERY_PARAM_NAME = "name"
}
| 26 | 65 | 0.739645 |
5f57acb96495fc1d0d6eb6802d14e642eac6d100 | 162 | sql | SQL | database/seeds/sql/01_datum_type.sql | human-nature-lab/trellis-api | f90e8dfc1c50a92cf3b6cbcb59812cd9ef13e2d8 | [
"MIT"
] | 1 | 2019-07-19T13:12:17.000Z | 2019-07-19T13:12:17.000Z | database/seeds/sql/01_datum_type.sql | human-nature-lab/trellis-api | f90e8dfc1c50a92cf3b6cbcb59812cd9ef13e2d8 | [
"MIT"
] | 6 | 2019-09-06T14:15:11.000Z | 2021-07-21T16:02:18.000Z | database/seeds/sql/01_datum_type.sql | human-nature-lab/trellis-api | f90e8dfc1c50a92cf3b6cbcb59812cd9ef13e2d8 | [
"MIT"
] | 1 | 2020-11-06T03:31:17.000Z | 2020-11-06T03:31:17.000Z | INSERT IGNORE INTO `datum_type` (`id`, `name`, `created_at`, `updated_at`, `deleted_at`)
VALUES
('0','default','2017-02-28 15:05:32','2017-02-28 15:05:32',NULL); | 54 | 88 | 0.666667 |
cf82a874561a6d5f14e32c6804c6e4e08240fe33 | 1,242 | css | CSS | src/assets/fonts/fonts.css | tbone1020/TeebkenWedding2019 | 24e1933fc52865d65f588b7692567d05c849d3b2 | [
"MIT"
] | null | null | null | src/assets/fonts/fonts.css | tbone1020/TeebkenWedding2019 | 24e1933fc52865d65f588b7692567d05c849d3b2 | [
"MIT"
] | null | null | null | src/assets/fonts/fonts.css | tbone1020/TeebkenWedding2019 | 24e1933fc52865d65f588b7692567d05c849d3b2 | [
"MIT"
] | null | null | null | @font-face {
font-family: 'MicrosoftYiBaiti';
src: url('Microsoft-Yi-Baiti.eot');
src: url('Microsoft-Yi-Baiti.eot?#iefix') format('embedded-opentype'),
url('Microsoft-Yi-Baiti.woff2') format('woff2'),
url('Microsoft-Yi-Baiti.woff') format('woff'),
url('Microsoft-Yi-Baiti.ttf') format('truetype'),
url('Microsoft-Yi-Baiti.svg#Microsoft-Yi-Baiti') format('svg');
font-weight: normal;
font-style: normal;
}
@font-face {
font-family: 'LOVES';
src: url('LOVES-REG.eot');
src: url('LOVES-REG.eot?#iefix') format('embedded-opentype'),
url('LOVES-REG.woff2') format('woff2'),
url('LOVES-REG.woff') format('woff'),
url('LOVES-REG.ttf') format('truetype'),
url('LOVES-REG.svg#LOVES-REG') format('svg');
font-weight: normal;
font-style: normal;
}
@font-face {
font-family: 'Oh_Samantha';
src: url('OhSamantha.eot');
src: url('OhSamantha.eot?#iefix') format('embedded-opentype'),
url('OhSamantha.woff2') format('woff2'),
url('OhSamantha.woff') format('woff'),
url('OhSamantha.ttf') format('truetype'),
url('OhSamantha.svg#OhSamantha') format('svg');
font-weight: normal;
font-style: normal;
}
| 33.567568 | 74 | 0.615942 |
38b01f0ecd491baee140757774cf5622f4137287 | 18,938 | h | C | Labyrint/labyrinti1/Classes/Native/mscorlib_System_Collections_ObjectModel_Collection_521435221MethodDeclarations.h | mimietti/Labyball | c4b03f5b5d5ec1a1cae5831d22391bc2a171230f | [
"MIT"
] | null | null | null | Labyrint/labyrinti1/Classes/Native/mscorlib_System_Collections_ObjectModel_Collection_521435221MethodDeclarations.h | mimietti/Labyball | c4b03f5b5d5ec1a1cae5831d22391bc2a171230f | [
"MIT"
] | 23 | 2016-07-21T13:03:02.000Z | 2016-10-03T12:43:01.000Z | Labyrint/labyrinti1/Classes/Native/mscorlib_System_Collections_ObjectModel_Collection_521435221MethodDeclarations.h | mimietti/Labyball | c4b03f5b5d5ec1a1cae5831d22391bc2a171230f | [
"MIT"
] | 1 | 2019-09-08T17:32:17.000Z | 2019-09-08T17:32:17.000Z | #pragma once
#include "il2cpp-config.h"
#ifndef _MSC_VER
# include <alloca.h>
#else
# include <malloc.h>
#endif
#include <stdint.h>
#include <assert.h>
#include <exception>
// System.Collections.ObjectModel.Collection`1<System.Int32>
struct Collection_1_t521435221;
// System.Array
struct Il2CppArray;
// System.Collections.IEnumerator
struct IEnumerator_t287207039;
// System.Object
struct Il2CppObject;
// System.Int32[]
struct Int32U5BU5D_t1809983122;
// System.Collections.Generic.IEnumerator`1<System.Int32>
struct IEnumerator_1_t35553939;
// System.Collections.Generic.IList`1<System.Int32>
struct IList_1_t718939805;
#include "codegen/il2cpp-codegen.h"
#include "mscorlib_System_Array2840145358.h"
#include "mscorlib_System_Object837106420.h"
// System.Void System.Collections.ObjectModel.Collection`1<System.Int32>::.ctor()
extern "C" void Collection_1__ctor_m3332792406_gshared (Collection_1_t521435221 * __this, const MethodInfo* method);
#define Collection_1__ctor_m3332792406(__this, method) (( void (*) (Collection_1_t521435221 *, const MethodInfo*))Collection_1__ctor_m3332792406_gshared)(__this, method)
// System.Boolean System.Collections.ObjectModel.Collection`1<System.Int32>::System.Collections.Generic.ICollection<T>.get_IsReadOnly()
extern "C" bool Collection_1_System_Collections_Generic_ICollectionU3CTU3E_get_IsReadOnly_m149220001_gshared (Collection_1_t521435221 * __this, const MethodInfo* method);
#define Collection_1_System_Collections_Generic_ICollectionU3CTU3E_get_IsReadOnly_m149220001(__this, method) (( bool (*) (Collection_1_t521435221 *, const MethodInfo*))Collection_1_System_Collections_Generic_ICollectionU3CTU3E_get_IsReadOnly_m149220001_gshared)(__this, method)
// System.Void System.Collections.ObjectModel.Collection`1<System.Int32>::System.Collections.ICollection.CopyTo(System.Array,System.Int32)
extern "C" void Collection_1_System_Collections_ICollection_CopyTo_m62423470_gshared (Collection_1_t521435221 * __this, Il2CppArray * ___array0, int32_t ___index1, const MethodInfo* method);
#define Collection_1_System_Collections_ICollection_CopyTo_m62423470(__this, ___array0, ___index1, method) (( void (*) (Collection_1_t521435221 *, Il2CppArray *, int32_t, const MethodInfo*))Collection_1_System_Collections_ICollection_CopyTo_m62423470_gshared)(__this, ___array0, ___index1, method)
// System.Collections.IEnumerator System.Collections.ObjectModel.Collection`1<System.Int32>::System.Collections.IEnumerable.GetEnumerator()
extern "C" Il2CppObject * Collection_1_System_Collections_IEnumerable_GetEnumerator_m2147163581_gshared (Collection_1_t521435221 * __this, const MethodInfo* method);
#define Collection_1_System_Collections_IEnumerable_GetEnumerator_m2147163581(__this, method) (( Il2CppObject * (*) (Collection_1_t521435221 *, const MethodInfo*))Collection_1_System_Collections_IEnumerable_GetEnumerator_m2147163581_gshared)(__this, method)
// System.Int32 System.Collections.ObjectModel.Collection`1<System.Int32>::System.Collections.IList.Add(System.Object)
extern "C" int32_t Collection_1_System_Collections_IList_Add_m1139865888_gshared (Collection_1_t521435221 * __this, Il2CppObject * ___value0, const MethodInfo* method);
#define Collection_1_System_Collections_IList_Add_m1139865888(__this, ___value0, method) (( int32_t (*) (Collection_1_t521435221 *, Il2CppObject *, const MethodInfo*))Collection_1_System_Collections_IList_Add_m1139865888_gshared)(__this, ___value0, method)
// System.Boolean System.Collections.ObjectModel.Collection`1<System.Int32>::System.Collections.IList.Contains(System.Object)
extern "C" bool Collection_1_System_Collections_IList_Contains_m3868443296_gshared (Collection_1_t521435221 * __this, Il2CppObject * ___value0, const MethodInfo* method);
#define Collection_1_System_Collections_IList_Contains_m3868443296(__this, ___value0, method) (( bool (*) (Collection_1_t521435221 *, Il2CppObject *, const MethodInfo*))Collection_1_System_Collections_IList_Contains_m3868443296_gshared)(__this, ___value0, method)
// System.Int32 System.Collections.ObjectModel.Collection`1<System.Int32>::System.Collections.IList.IndexOf(System.Object)
extern "C" int32_t Collection_1_System_Collections_IList_IndexOf_m835690360_gshared (Collection_1_t521435221 * __this, Il2CppObject * ___value0, const MethodInfo* method);
#define Collection_1_System_Collections_IList_IndexOf_m835690360(__this, ___value0, method) (( int32_t (*) (Collection_1_t521435221 *, Il2CppObject *, const MethodInfo*))Collection_1_System_Collections_IList_IndexOf_m835690360_gshared)(__this, ___value0, method)
// System.Void System.Collections.ObjectModel.Collection`1<System.Int32>::System.Collections.IList.Insert(System.Int32,System.Object)
extern "C" void Collection_1_System_Collections_IList_Insert_m3185815019_gshared (Collection_1_t521435221 * __this, int32_t ___index0, Il2CppObject * ___value1, const MethodInfo* method);
#define Collection_1_System_Collections_IList_Insert_m3185815019(__this, ___index0, ___value1, method) (( void (*) (Collection_1_t521435221 *, int32_t, Il2CppObject *, const MethodInfo*))Collection_1_System_Collections_IList_Insert_m3185815019_gshared)(__this, ___index0, ___value1, method)
// System.Void System.Collections.ObjectModel.Collection`1<System.Int32>::System.Collections.IList.Remove(System.Object)
extern "C" void Collection_1_System_Collections_IList_Remove_m974436701_gshared (Collection_1_t521435221 * __this, Il2CppObject * ___value0, const MethodInfo* method);
#define Collection_1_System_Collections_IList_Remove_m974436701(__this, ___value0, method) (( void (*) (Collection_1_t521435221 *, Il2CppObject *, const MethodInfo*))Collection_1_System_Collections_IList_Remove_m974436701_gshared)(__this, ___value0, method)
// System.Boolean System.Collections.ObjectModel.Collection`1<System.Int32>::System.Collections.ICollection.get_IsSynchronized()
extern "C" bool Collection_1_System_Collections_ICollection_get_IsSynchronized_m2226720956_gshared (Collection_1_t521435221 * __this, const MethodInfo* method);
#define Collection_1_System_Collections_ICollection_get_IsSynchronized_m2226720956(__this, method) (( bool (*) (Collection_1_t521435221 *, const MethodInfo*))Collection_1_System_Collections_ICollection_get_IsSynchronized_m2226720956_gshared)(__this, method)
// System.Object System.Collections.ObjectModel.Collection`1<System.Int32>::System.Collections.ICollection.get_SyncRoot()
extern "C" Il2CppObject * Collection_1_System_Collections_ICollection_get_SyncRoot_m1611895278_gshared (Collection_1_t521435221 * __this, const MethodInfo* method);
#define Collection_1_System_Collections_ICollection_get_SyncRoot_m1611895278(__this, method) (( Il2CppObject * (*) (Collection_1_t521435221 *, const MethodInfo*))Collection_1_System_Collections_ICollection_get_SyncRoot_m1611895278_gshared)(__this, method)
// System.Boolean System.Collections.ObjectModel.Collection`1<System.Int32>::System.Collections.IList.get_IsFixedSize()
extern "C" bool Collection_1_System_Collections_IList_get_IsFixedSize_m3301566991_gshared (Collection_1_t521435221 * __this, const MethodInfo* method);
#define Collection_1_System_Collections_IList_get_IsFixedSize_m3301566991(__this, method) (( bool (*) (Collection_1_t521435221 *, const MethodInfo*))Collection_1_System_Collections_IList_get_IsFixedSize_m3301566991_gshared)(__this, method)
// System.Boolean System.Collections.ObjectModel.Collection`1<System.Int32>::System.Collections.IList.get_IsReadOnly()
extern "C" bool Collection_1_System_Collections_IList_get_IsReadOnly_m283416330_gshared (Collection_1_t521435221 * __this, const MethodInfo* method);
#define Collection_1_System_Collections_IList_get_IsReadOnly_m283416330(__this, method) (( bool (*) (Collection_1_t521435221 *, const MethodInfo*))Collection_1_System_Collections_IList_get_IsReadOnly_m283416330_gshared)(__this, method)
// System.Object System.Collections.ObjectModel.Collection`1<System.Int32>::System.Collections.IList.get_Item(System.Int32)
extern "C" Il2CppObject * Collection_1_System_Collections_IList_get_Item_m3908747253_gshared (Collection_1_t521435221 * __this, int32_t ___index0, const MethodInfo* method);
#define Collection_1_System_Collections_IList_get_Item_m3908747253(__this, ___index0, method) (( Il2CppObject * (*) (Collection_1_t521435221 *, int32_t, const MethodInfo*))Collection_1_System_Collections_IList_get_Item_m3908747253_gshared)(__this, ___index0, method)
// System.Void System.Collections.ObjectModel.Collection`1<System.Int32>::System.Collections.IList.set_Item(System.Int32,System.Object)
extern "C" void Collection_1_System_Collections_IList_set_Item_m4165470978_gshared (Collection_1_t521435221 * __this, int32_t ___index0, Il2CppObject * ___value1, const MethodInfo* method);
#define Collection_1_System_Collections_IList_set_Item_m4165470978(__this, ___index0, ___value1, method) (( void (*) (Collection_1_t521435221 *, int32_t, Il2CppObject *, const MethodInfo*))Collection_1_System_Collections_IList_set_Item_m4165470978_gshared)(__this, ___index0, ___value1, method)
// System.Void System.Collections.ObjectModel.Collection`1<System.Int32>::Add(T)
extern "C" void Collection_1_Add_m513293673_gshared (Collection_1_t521435221 * __this, int32_t ___item0, const MethodInfo* method);
#define Collection_1_Add_m513293673(__this, ___item0, method) (( void (*) (Collection_1_t521435221 *, int32_t, const MethodInfo*))Collection_1_Add_m513293673_gshared)(__this, ___item0, method)
// System.Void System.Collections.ObjectModel.Collection`1<System.Int32>::Clear()
extern "C" void Collection_1_Clear_m738925697_gshared (Collection_1_t521435221 * __this, const MethodInfo* method);
#define Collection_1_Clear_m738925697(__this, method) (( void (*) (Collection_1_t521435221 *, const MethodInfo*))Collection_1_Clear_m738925697_gshared)(__this, method)
// System.Void System.Collections.ObjectModel.Collection`1<System.Int32>::ClearItems()
extern "C" void Collection_1_ClearItems_m2652056865_gshared (Collection_1_t521435221 * __this, const MethodInfo* method);
#define Collection_1_ClearItems_m2652056865(__this, method) (( void (*) (Collection_1_t521435221 *, const MethodInfo*))Collection_1_ClearItems_m2652056865_gshared)(__this, method)
// System.Boolean System.Collections.ObjectModel.Collection`1<System.Int32>::Contains(T)
extern "C" bool Collection_1_Contains_m2782156403_gshared (Collection_1_t521435221 * __this, int32_t ___item0, const MethodInfo* method);
#define Collection_1_Contains_m2782156403(__this, ___item0, method) (( bool (*) (Collection_1_t521435221 *, int32_t, const MethodInfo*))Collection_1_Contains_m2782156403_gshared)(__this, ___item0, method)
// System.Void System.Collections.ObjectModel.Collection`1<System.Int32>::CopyTo(T[],System.Int32)
extern "C" void Collection_1_CopyTo_m1777007897_gshared (Collection_1_t521435221 * __this, Int32U5BU5D_t1809983122* ___array0, int32_t ___index1, const MethodInfo* method);
#define Collection_1_CopyTo_m1777007897(__this, ___array0, ___index1, method) (( void (*) (Collection_1_t521435221 *, Int32U5BU5D_t1809983122*, int32_t, const MethodInfo*))Collection_1_CopyTo_m1777007897_gshared)(__this, ___array0, ___index1, method)
// System.Collections.Generic.IEnumerator`1<T> System.Collections.ObjectModel.Collection`1<System.Int32>::GetEnumerator()
extern "C" Il2CppObject* Collection_1_GetEnumerator_m3889801162_gshared (Collection_1_t521435221 * __this, const MethodInfo* method);
#define Collection_1_GetEnumerator_m3889801162(__this, method) (( Il2CppObject* (*) (Collection_1_t521435221 *, const MethodInfo*))Collection_1_GetEnumerator_m3889801162_gshared)(__this, method)
// System.Int32 System.Collections.ObjectModel.Collection`1<System.Int32>::IndexOf(T)
extern "C" int32_t Collection_1_IndexOf_m2763113893_gshared (Collection_1_t521435221 * __this, int32_t ___item0, const MethodInfo* method);
#define Collection_1_IndexOf_m2763113893(__this, ___item0, method) (( int32_t (*) (Collection_1_t521435221 *, int32_t, const MethodInfo*))Collection_1_IndexOf_m2763113893_gshared)(__this, ___item0, method)
// System.Void System.Collections.ObjectModel.Collection`1<System.Int32>::Insert(System.Int32,T)
extern "C" void Collection_1_Insert_m3156706768_gshared (Collection_1_t521435221 * __this, int32_t ___index0, int32_t ___item1, const MethodInfo* method);
#define Collection_1_Insert_m3156706768(__this, ___index0, ___item1, method) (( void (*) (Collection_1_t521435221 *, int32_t, int32_t, const MethodInfo*))Collection_1_Insert_m3156706768_gshared)(__this, ___index0, ___item1, method)
// System.Void System.Collections.ObjectModel.Collection`1<System.Int32>::InsertItem(System.Int32,T)
extern "C" void Collection_1_InsertItem_m268913667_gshared (Collection_1_t521435221 * __this, int32_t ___index0, int32_t ___item1, const MethodInfo* method);
#define Collection_1_InsertItem_m268913667(__this, ___index0, ___item1, method) (( void (*) (Collection_1_t521435221 *, int32_t, int32_t, const MethodInfo*))Collection_1_InsertItem_m268913667_gshared)(__this, ___index0, ___item1, method)
// System.Boolean System.Collections.ObjectModel.Collection`1<System.Int32>::Remove(T)
extern "C" bool Collection_1_Remove_m3171030830_gshared (Collection_1_t521435221 * __this, int32_t ___item0, const MethodInfo* method);
#define Collection_1_Remove_m3171030830(__this, ___item0, method) (( bool (*) (Collection_1_t521435221 *, int32_t, const MethodInfo*))Collection_1_Remove_m3171030830_gshared)(__this, ___item0, method)
// System.Void System.Collections.ObjectModel.Collection`1<System.Int32>::RemoveAt(System.Int32)
extern "C" void Collection_1_RemoveAt_m1030559638_gshared (Collection_1_t521435221 * __this, int32_t ___index0, const MethodInfo* method);
#define Collection_1_RemoveAt_m1030559638(__this, ___index0, method) (( void (*) (Collection_1_t521435221 *, int32_t, const MethodInfo*))Collection_1_RemoveAt_m1030559638_gshared)(__this, ___index0, method)
// System.Void System.Collections.ObjectModel.Collection`1<System.Int32>::RemoveItem(System.Int32)
extern "C" void Collection_1_RemoveItem_m1129991734_gshared (Collection_1_t521435221 * __this, int32_t ___index0, const MethodInfo* method);
#define Collection_1_RemoveItem_m1129991734(__this, ___index0, method) (( void (*) (Collection_1_t521435221 *, int32_t, const MethodInfo*))Collection_1_RemoveItem_m1129991734_gshared)(__this, ___index0, method)
// System.Int32 System.Collections.ObjectModel.Collection`1<System.Int32>::get_Count()
extern "C" int32_t Collection_1_get_Count_m3869459574_gshared (Collection_1_t521435221 * __this, const MethodInfo* method);
#define Collection_1_get_Count_m3869459574(__this, method) (( int32_t (*) (Collection_1_t521435221 *, const MethodInfo*))Collection_1_get_Count_m3869459574_gshared)(__this, method)
// T System.Collections.ObjectModel.Collection`1<System.Int32>::get_Item(System.Int32)
extern "C" int32_t Collection_1_get_Item_m2458374268_gshared (Collection_1_t521435221 * __this, int32_t ___index0, const MethodInfo* method);
#define Collection_1_get_Item_m2458374268(__this, ___index0, method) (( int32_t (*) (Collection_1_t521435221 *, int32_t, const MethodInfo*))Collection_1_get_Item_m2458374268_gshared)(__this, ___index0, method)
// System.Void System.Collections.ObjectModel.Collection`1<System.Int32>::set_Item(System.Int32,T)
extern "C" void Collection_1_set_Item_m3157889703_gshared (Collection_1_t521435221 * __this, int32_t ___index0, int32_t ___value1, const MethodInfo* method);
#define Collection_1_set_Item_m3157889703(__this, ___index0, ___value1, method) (( void (*) (Collection_1_t521435221 *, int32_t, int32_t, const MethodInfo*))Collection_1_set_Item_m3157889703_gshared)(__this, ___index0, ___value1, method)
// System.Void System.Collections.ObjectModel.Collection`1<System.Int32>::SetItem(System.Int32,T)
extern "C" void Collection_1_SetItem_m390251762_gshared (Collection_1_t521435221 * __this, int32_t ___index0, int32_t ___item1, const MethodInfo* method);
#define Collection_1_SetItem_m390251762(__this, ___index0, ___item1, method) (( void (*) (Collection_1_t521435221 *, int32_t, int32_t, const MethodInfo*))Collection_1_SetItem_m390251762_gshared)(__this, ___index0, ___item1, method)
// System.Boolean System.Collections.ObjectModel.Collection`1<System.Int32>::IsValidItem(System.Object)
extern "C" bool Collection_1_IsValidItem_m2147223385_gshared (Il2CppObject * __this /* static, unused */, Il2CppObject * ___item0, const MethodInfo* method);
#define Collection_1_IsValidItem_m2147223385(__this /* static, unused */, ___item0, method) (( bool (*) (Il2CppObject * /* static, unused */, Il2CppObject *, const MethodInfo*))Collection_1_IsValidItem_m2147223385_gshared)(__this /* static, unused */, ___item0, method)
// T System.Collections.ObjectModel.Collection`1<System.Int32>::ConvertItem(System.Object)
extern "C" int32_t Collection_1_ConvertItem_m3291275611_gshared (Il2CppObject * __this /* static, unused */, Il2CppObject * ___item0, const MethodInfo* method);
#define Collection_1_ConvertItem_m3291275611(__this /* static, unused */, ___item0, method) (( int32_t (*) (Il2CppObject * /* static, unused */, Il2CppObject *, const MethodInfo*))Collection_1_ConvertItem_m3291275611_gshared)(__this /* static, unused */, ___item0, method)
// System.Void System.Collections.ObjectModel.Collection`1<System.Int32>::CheckWritable(System.Collections.Generic.IList`1<T>)
extern "C" void Collection_1_CheckWritable_m1613158233_gshared (Il2CppObject * __this /* static, unused */, Il2CppObject* ___list0, const MethodInfo* method);
#define Collection_1_CheckWritable_m1613158233(__this /* static, unused */, ___list0, method) (( void (*) (Il2CppObject * /* static, unused */, Il2CppObject*, const MethodInfo*))Collection_1_CheckWritable_m1613158233_gshared)(__this /* static, unused */, ___list0, method)
// System.Boolean System.Collections.ObjectModel.Collection`1<System.Int32>::IsSynchronized(System.Collections.Generic.IList`1<T>)
extern "C" bool Collection_1_IsSynchronized_m1502211019_gshared (Il2CppObject * __this /* static, unused */, Il2CppObject* ___list0, const MethodInfo* method);
#define Collection_1_IsSynchronized_m1502211019(__this /* static, unused */, ___list0, method) (( bool (*) (Il2CppObject * /* static, unused */, Il2CppObject*, const MethodInfo*))Collection_1_IsSynchronized_m1502211019_gshared)(__this /* static, unused */, ___list0, method)
// System.Boolean System.Collections.ObjectModel.Collection`1<System.Int32>::IsFixedSize(System.Collections.Generic.IList`1<T>)
extern "C" bool Collection_1_IsFixedSize_m2538202804_gshared (Il2CppObject * __this /* static, unused */, Il2CppObject* ___list0, const MethodInfo* method);
#define Collection_1_IsFixedSize_m2538202804(__this /* static, unused */, ___list0, method) (( bool (*) (Il2CppObject * /* static, unused */, Il2CppObject*, const MethodInfo*))Collection_1_IsFixedSize_m2538202804_gshared)(__this /* static, unused */, ___list0, method)
| 133.366197 | 298 | 0.831133 |
3bf0f8e2e91c55d347f5b8bea68c97b8eb936561 | 321 | asm | Assembly | programs/oeis/004/A004966.asm | neoneye/loda | afe9559fb53ee12e3040da54bd6aa47283e0d9ec | [
"Apache-2.0"
] | 22 | 2018-02-06T19:19:31.000Z | 2022-01-17T21:53:31.000Z | programs/oeis/004/A004966.asm | neoneye/loda | afe9559fb53ee12e3040da54bd6aa47283e0d9ec | [
"Apache-2.0"
] | 41 | 2021-02-22T19:00:34.000Z | 2021-08-28T10:47:47.000Z | programs/oeis/004/A004966.asm | neoneye/loda | afe9559fb53ee12e3040da54bd6aa47283e0d9ec | [
"Apache-2.0"
] | 5 | 2021-02-24T21:14:16.000Z | 2021-08-09T19:48:05.000Z | ; A004966: a(n) = ceiling(n*phi^11), where phi is the golden ratio, A001622.
; 0,200,399,598,797,996,1195,1394,1593,1792,1991,2190,2389,2588,2787,2986,3185,3384,3583,3782,3981,4180,4379,4578,4777,4976,5175,5374,5573,5772,5971,6170,6369,6568,6767
mov $1,$0
trn $1,1
mov $2,$0
sub $0,$1
lpb $2
add $0,199
sub $2,1
lpe
| 26.75 | 168 | 0.697819 |
bcaa88ec1d5cfba9123381cd5c24f3224e6e9979 | 1,204 | js | JavaScript | devsrc/src/js/actions/heights.js | jios325/lan-smart-cancun | 4572f2524f4f54a532da9acc6c7e233a54410744 | [
"MIT"
] | null | null | null | devsrc/src/js/actions/heights.js | jios325/lan-smart-cancun | 4572f2524f4f54a532da9acc6c7e233a54410744 | [
"MIT"
] | null | null | null | devsrc/src/js/actions/heights.js | jios325/lan-smart-cancun | 4572f2524f4f54a532da9acc6c7e233a54410744 | [
"MIT"
] | null | null | null | $(document).ready(function () {
//llama funciones de alturas en primer load
if ($(window).width() >= 1024) { //desktop
removeHeightHomeHeader()
}
else{
heightHomeHeader()
}
//llama funciones de alturas en resize de ventana
$(window).resize(function () {
if ($(window).width() >= 1024) { // de escritorio a mobile
removeHeightHomeHeader()
}
else { // pasa de mobile a escritorio
heightHomeHeader()
}
}).resize()
//fix de chrome
function calcVH($class) {
var vH = Math.max(document.documentElement.clientHeight, window.innerHeight || 0);
document.getElementById($class).setAttribute("style", "height:" + vH + "px;");
}
function removeH($class){
document.getElementById($class).removeAttribute("style");
}
function heightHomeHeader(){
if($('#main-section-home').length){
calcVH('main-section-home');
window.addEventListener('onorientationchange', calcVH, true);
}
}
function removeHeightHomeHeader(){
if($('#main-section-home').length){
removeH('main-section-home');
}
}
}) | 30.1 | 88 | 0.580565 |
9c17af81f507506a8af9ca5bdc9472e6e5b59742 | 389 | js | JavaScript | src/components/palette/palette.data.js | codeselfstudy/focus_timer | 74446ddb1cf8ead8367c4a3ae21cdd750f2ed6df | [
"BSD-3-Clause"
] | 1 | 2020-03-31T21:54:34.000Z | 2020-03-31T21:54:34.000Z | src/components/palette/palette.data.js | codeselfstudy/focus_timer | 74446ddb1cf8ead8367c4a3ae21cdd750f2ed6df | [
"BSD-3-Clause"
] | 2 | 2020-03-31T19:38:34.000Z | 2020-04-01T03:12:03.000Z | src/components/palette/palette.data.js | codeselfstudy/focus_timer | 74446ddb1cf8ead8367c4a3ae21cdd750f2ed6df | [
"BSD-3-Clause"
] | null | null | null | import { mapColorsToObj } from "./palette.utils";
export const colorsList = [
"#cbcdc0",
"#513146",
"#833e39",
"#e39ea3",
"#014c76",
"#ac352d",
"#596781",
"#edba83",
"#745342",
"#fdc101",
"#e4d0b5",
"#659655",
"#ba6137",
"#2a1921",
"#3e8dac",
];
// this might not be necessary
export const colors = mapColorsToObj(colorsList);
| 16.913043 | 49 | 0.542416 |
e04acbd15cc155a9bc1c7803839e9bb5ab6ef9fd | 2,683 | swift | Swift | Sources/ImportSanitizerCore/SanitizerProcess/SanitizerProcess.swift | SketchK/ImportSanitizer | 1151d9f6f53eba335b1480636528c0c38a02b71a | [
"RSA-MD"
] | 39 | 2021-03-25T12:48:13.000Z | 2022-03-30T12:31:19.000Z | Sources/ImportSanitizerCore/SanitizerProcess/SanitizerProcess.swift | SketchK/ImportSanitizer | 1151d9f6f53eba335b1480636528c0c38a02b71a | [
"RSA-MD"
] | 1 | 2022-01-19T08:13:44.000Z | 2022-01-19T08:13:44.000Z | Sources/ImportSanitizerCore/SanitizerProcess/SanitizerProcess.swift | SketchK/ImportSanitizer | 1151d9f6f53eba335b1480636528c0c38a02b71a | [
"RSA-MD"
] | 5 | 2021-03-25T12:48:15.000Z | 2022-03-30T12:31:23.000Z | //
// SanitizerProcess.swift
// ImportSanitizerCore
//
// Created by SketchK on 2020/12/23.
//
import Foundation
import Files
protocol SanitizerProcess {
var mode : FixMode { get set }
var reference: HeaderMapTable { get set }
var target : ProjectSourceFiles { get set }
var needOverwrite: Bool { get set }
var result: [Description] {get set}
mutating func check(importSyntax: ImportSyntax, in file: File) throws-> Bool
mutating func fix(importSyntax: ImportSyntax,
in content: String,
with file: File ) throws -> String
}
extension SanitizerProcess {
mutating func shouldIgnore(_ importSyntax: ImportSyntax, in file: File) -> Bool {
// 1 获取 MapTable 中对应 header 的 pod 名称
guard let headerName = importSyntax.headerName,
let podNames = self.reference.mapTable[String(headerName)] else {
// 没有找到相应的头文件信息说明, 可能是引用了某些特殊的系统文件
return true
}
guard podNames.count == 1 else {
// 说明有同名的头文件, 此时不做修复, 应当提醒开发者手动修改
let syntax = headerName.trimmingCharacters(in: .whitespacesAndNewlines)
let eType = SyntaxErrorType.duplicatedHeaderFile.rawValue
let sType = SolutionType.manually.rawValue
let solution = "\(syntax) 同时属于以下组件 \(podNames), 需要明确使用的组件"
let description = Description(syntax: syntax, fileName: file.name, filePath: file.path, errorType: eType, soulution: solution)
self.result.append(description)
print("错误类型为[\(eType)], 修复方式为[\(sType)], 错误语句为[\(syntax)], 解决方案为 \(solution), 问题发生在 \(file.name) 中".likeValuableSentence(.error))
return true
}
return false
}
mutating func isValidate(_ importSyntax: ImportSyntax, in file: File) -> Bool {
// 判断引用的头文件是否为非 .h 类型的文件,例如引入了某个 .m 的文件
guard let last = importSyntax.headerName?.split(separator: ".").last, String(last) != "m" else {
// 说明引入了一个 .m 文件, 此时不做修复(没法保证 .h 文件一定存在), 应当提醒开发者手动修改
let syntax = importSyntax.raw.trimmingCharacters(in: .whitespacesAndNewlines)
let eType = SyntaxErrorType.implementationFile.rawValue
let sType = SolutionType.manually.rawValue
let solution = "删除 \(syntax) 并引入对应的 .h 文件"
let description = Description(syntax: syntax, fileName: file.name, filePath: file.path, errorType: eType, soulution: solution)
self.result.append(description)
print("错误类型为[\(eType)], 修复方式为[\(sType)], 错误语句为[\(syntax)], 解决方案为 \(solution), 问题发生在 \(file.name) 中".likeValuableSentence(.error))
return false
}
return true
}
}
| 43.274194 | 141 | 0.642192 |
1438bd4ae5692e44b4f0ee8c5db06cc98157b0da | 1,693 | css | CSS | public/stylesheets/backend/imprime.css | haroldoramirez/biblioteca | bf99aa33d8febe7053cdbe33c324a68eee477449 | [
"Apache-2.0"
] | 6 | 2017-02-13T23:19:20.000Z | 2017-05-24T17:40:46.000Z | public/stylesheets/backend/imprime.css | haroldoramirez/biblioteca | bf99aa33d8febe7053cdbe33c324a68eee477449 | [
"Apache-2.0"
] | 39 | 2017-05-24T14:28:10.000Z | 2020-06-05T12:54:40.000Z | public/stylesheets/backend/imprime.css | haroldoramirez/biblioteca | bf99aa33d8febe7053cdbe33c324a68eee477449 | [
"Apache-2.0"
] | 1 | 2016-09-05T07:23:24.000Z | 2016-09-05T07:23:24.000Z | /********************************************************/
/* Manual Biblioteca Digital */
/* imprime.css - Folha de Estilo para Impressão */
/********************************************************/
@media print {
.visible-print {
display: inherit !important;
}
.hidden-print {
display: none !important;
}
article {
margin-top: 0;
margin-right: 1cm;
margin-bottom: 0;
margin-left: 1cm;
page-break-after: always;
}
header {
text-align: right;
font-size: 10px;
}
section {
/*height: 22cm*/
height: 26.7cm;
}
footer {
font-size: 10px;
}
table {
text-align: center;
width: 100%
}
p {
text-align: justify;
font-size: 14px;
}
img {
max-width: 100%;
}
.firstpage h1,.firstpage h2 {
text-align: center;
padding: 10px 0 5px 0;
}
.page h1 {
padding: -2px;
}
.topo_imgs {
margin-top: 40px;
margin-bottom: 50px;
text-align: center;
}
.border {
border: solid 1px #000000;
}
.small {
width: 30px;
}
.indice {
width: 100%;
}
.indice tr {
border-bottom: solid 1px #000000;
}
.indice .ind1 {
width: 90px;
text-align: left;
}
.indice .ind2 {
text-align: left;
}
.indice .ind3 {
width: 50px;
text-align: right;
}
li.nolist {
list-style: none;
}
.img-thumbnail div {
border: 0;
padding: 1px;
}
.img-thumbnail p {
font-size: 10px;
}
} | 19.686047 | 58 | 0.435322 |
1e218a581066361612a504c4587c59d3fd0f9ab1 | 24,237 | css | CSS | out/_next/static/css/7b6ffe6367c06c4c4b39.css | gieyazka/home-isolation | e984a0d7d80a2281c4839c34635b8b07adbb7a48 | [
"MIT"
] | 1 | 2022-03-09T00:05:54.000Z | 2022-03-09T00:05:54.000Z | out/_next/static/css/7b6ffe6367c06c4c4b39.css | gieyazka/home-isolation | e984a0d7d80a2281c4839c34635b8b07adbb7a48 | [
"MIT"
] | 64 | 2021-08-19T03:17:57.000Z | 2022-03-31T00:04:12.000Z | out/_next/static/css/7b6ffe6367c06c4c4b39.css | gieyazka/home-isolation | e984a0d7d80a2281c4839c34635b8b07adbb7a48 | [
"MIT"
] | null | null | null | @font-face{font-display:swap;font-family:Raleway VF;font-weight:100 900;src:url(/_next/static/media/Raleway-Variable.942638e66612b31fad1b924a405a29ba.ttf) format("truetype")}@font-face{font-display:swap;font-family:Raleway-ExtraLight;font-weight:200;src:url(/_next/static/media/Raleway-ExtraLight.18e9b7b36143a965037ef79bbc403cac.ttf) format("truetype")}@font-face{font-display:swap;font-family:Raleway-Light;font-weight:300;src:url(/_next/static/media/Raleway-Light.f25e9b3a1fc8e48e53f51de9838c95fa.ttf) format("truetype")}@font-face{font-display:swap;font-family:Raleway-Regular;font-weight:400;src:url(/_next/static/media/Raleway-Regular.9ade142e81dd8d55cd3265c1529bef5e.ttf) format("truetype")}@font-face{font-display:swap;font-family:Raleway-Medium;font-weight:500;src:url(/_next/static/media/Raleway-Medium.1af9f1e9f3fd4766df83e545c2f6fcdb.ttf) format("truetype")}@font-face{font-display:swap;font-family:Raleway-SemiBold;font-weight:600;src:url(/_next/static/media/Raleway-SemiBold.243af299ad3631bfc36924b497f3831f.ttf) format("truetype")}
/*! tailwindcss v2.2.4 | MIT License | https://tailwindcss.com */
/*! modern-normalize v1.1.0 | MIT License | https://github.com/sindresorhus/modern-normalize */html{-moz-tab-size:4;tab-size:4;line-height:1.15;-webkit-text-size-adjust:100%}body{font-family:system-ui,-apple-system,Segoe UI,Roboto,Helvetica,Arial,sans-serif,Apple Color Emoji,Segoe UI Emoji}hr{height:0;color:inherit}abbr[title]{-webkit-text-decoration:underline dotted;text-decoration:underline dotted}b,strong{font-weight:bolder}code,kbd,pre,samp{font-family:ui-monospace,SFMono-Regular,Consolas,Liberation Mono,Menlo,monospace;font-size:1em}small{font-size:80%}sub,sup{font-size:75%;line-height:0;position:relative;vertical-align:baseline}sub{bottom:-.25em}sup{top:-.5em}table{text-indent:0;border-color:inherit}button,input,optgroup,select,textarea{font-family:inherit;font-size:100%;line-height:1.15;margin:0}button,select{text-transform:none}[type=button],[type=submit],button{-webkit-appearance:button}legend{padding:0}progress{vertical-align:baseline}summary{display:list-item}blockquote,dd,dl,figure,h1,h2,h3,h4,h5,h6,hr,p,pre{margin:0}button{background-image:none}fieldset,ol,ul{margin:0;padding:0}ol,ul{list-style:none}html{font-family:ui-sans-serif,system-ui,-apple-system,BlinkMacSystemFont,Segoe UI,Roboto,Helvetica Neue,Arial,Noto Sans,sans-serif,Apple Color Emoji,Segoe UI Emoji,Segoe UI Symbol,Noto Color Emoji;line-height:1.5}body{font-family:inherit;line-height:inherit}*,:after,:before{box-sizing:border-box;border:0 solid}hr{border-top-width:1px}img{border-style:solid}textarea{resize:vertical}input::-webkit-input-placeholder,textarea::-webkit-input-placeholder{opacity:1;color:#9ca3af}input:-ms-input-placeholder,textarea:-ms-input-placeholder{opacity:1;color:#9ca3af}input::placeholder,textarea::placeholder{opacity:1;color:#9ca3af}[role=button],button{cursor:pointer}table{border-collapse:collapse}h1,h2,h3,h4,h5,h6{font-size:inherit;font-weight:inherit}a{color:inherit;text-decoration:inherit}button,input,optgroup,select,textarea{padding:0;line-height:inherit;color:inherit}code,kbd,pre,samp{font-family:ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,Liberation Mono,Courier New,monospace}audio,canvas,embed,iframe,img,object,svg,video{display:block;vertical-align:middle}img,video{max-width:100%;height:auto}*,:after,:before{--tw-border-opacity:1;border-color:rgba(229,231,235,var(--tw-border-opacity))}.static{position:static}.absolute{position:absolute}.z-0{z-index:0}.z-10{z-index:10}.z-50{z-index:50}.m-1{margin:.25rem}.mx-6{margin-left:1.5rem;margin-right:1.5rem}.mx-auto{margin-left:auto;margin-right:auto}.mt-1{margin-top:.25rem}.mt-2{margin-top:.5rem}.mt-3{margin-top:.75rem}.mt-4{margin-top:1rem}.mt-12{margin-top:3rem}.mt-auto{margin-top:auto}.mr-4{margin-right:1rem}.mr-auto{margin-right:auto}.mb-auto{margin-bottom:auto}.ml-4{margin-left:1rem}.ml-auto{margin-left:auto}.block{display:block}.flex{display:flex}.table{display:table}.hidden{display:none}.h-0{height:0}.h-4{height:1rem}.h-10{height:2.5rem}.h-11{height:2.75rem}.h-16{height:4rem}.h-24{height:6rem}.h-32{height:8rem}.h-0\.5{height:.125rem}.h-2\/4{height:50%}.h-3\/4{height:75%}.h-2\/5{height:40%}.h-full{height:100%}.h-20vw{height:20vw}.w-11{width:2.75rem}.w-32{width:8rem}.w-56{width:14rem}.w-2\/3{width:66.666667%}.w-1\/4{width:25%}.w-10\/12{width:83.333333%}.w-11\/12{width:91.666667%}.w-full{width:100%}.w-screen{width:100vw}.translate-x-2\/4{--tw-translate-x:50%}.translate-y-2\/4{--tw-translate-y:50%}@-webkit-keyframes spin{to{-webkit-transform:rotate(1turn);transform:rotate(1turn)}}@keyframes spin{to{-webkit-transform:rotate(1turn);transform:rotate(1turn)}}@-webkit-keyframes ping{75%,to{-webkit-transform:scale(2);transform:scale(2);opacity:0}}@keyframes ping{75%,to{-webkit-transform:scale(2);transform:scale(2);opacity:0}}@-webkit-keyframes pulse{50%{opacity:.5}}@keyframes pulse{50%{opacity:.5}}@-webkit-keyframes bounce{0%,to{-webkit-transform:translateY(-25%);transform:translateY(-25%);-webkit-animation-timing-function:cubic-bezier(.8,0,1,1);animation-timing-function:cubic-bezier(.8,0,1,1)}50%{-webkit-transform:none;transform:none;-webkit-animation-timing-function:cubic-bezier(0,0,.2,1);animation-timing-function:cubic-bezier(0,0,.2,1)}}@keyframes bounce{0%,to{-webkit-transform:translateY(-25%);transform:translateY(-25%);-webkit-animation-timing-function:cubic-bezier(.8,0,1,1);animation-timing-function:cubic-bezier(.8,0,1,1)}50%{-webkit-transform:none;transform:none;-webkit-animation-timing-function:cubic-bezier(0,0,.2,1);animation-timing-function:cubic-bezier(0,0,.2,1)}}.flex-row{flex-direction:row}.flex-col{flex-direction:column}.flex-wrap{flex-wrap:wrap}.items-end{align-items:flex-end}.items-center{align-items:center}.justify-end{justify-content:flex-end}.justify-center{justify-content:center}.justify-between{justify-content:space-between}.justify-around{justify-content:space-around}.overflow-y-scroll{overflow-y:scroll}.whitespace-nowrap{white-space:nowrap}.rounded-md{border-radius:.375rem}.rounded-lg{border-radius:.5rem}.rounded-xl{border-radius:.75rem}.rounded-2xl{border-radius:1rem}.rounded-full{border-radius:9999px}.border-4{border-width:4px}.border{border-width:1px}.border-b{border-bottom-width:1px}.border-black{--tw-border-opacity:1;border-color:rgba(0,0,0,var(--tw-border-opacity))}.border-gray-400{--tw-border-opacity:1;border-color:rgba(156,163,175,var(--tw-border-opacity))}.bg-black{--tw-bg-opacity:1;background-color:rgba(0,0,0,var(--tw-bg-opacity))}.bg-white{--tw-bg-opacity:1;background-color:rgba(255,255,255,var(--tw-bg-opacity))}.bg-blue-600{--tw-bg-opacity:1;background-color:rgba(37,99,235,var(--tw-bg-opacity))}.object-cover{object-fit:cover}.p-2{padding:.5rem}.px-1{padding-left:.25rem;padding-right:.25rem}.px-2{padding-left:.5rem;padding-right:.5rem}.px-4{padding-left:1rem;padding-right:1rem}.px-8{padding-left:2rem;padding-right:2rem}.px-9{padding-left:2.25rem;padding-right:2.25rem}.py-2{padding-top:.5rem;padding-bottom:.5rem}.py-4{padding-top:1rem;padding-bottom:1rem}.pt-2{padding-top:.5rem}.pt-4{padding-top:1rem}.pr-4{padding-right:1rem}.pl-4{padding-left:1rem}.text-center{text-align:center}.text-right{text-align:right}.text-base{font-size:1rem;line-height:1.5rem}.text-lg{font-size:1.125rem}.text-lg,.text-xl{line-height:1.75rem}.text-xl{font-size:1.25rem}.text-2xl{font-size:1.5rem;line-height:2rem}.text-3xl{font-size:1.875rem;line-height:2.25rem}.text-6xl{font-size:3.75rem;line-height:1}.font-normal{font-weight:400}.font-semibold{font-weight:600}.font-bold{font-weight:700}.tracking-wide{letter-spacing:.025em}.text-black{--tw-text-opacity:1;color:rgba(0,0,0,var(--tw-text-opacity))}.text-white{--tw-text-opacity:1;color:rgba(255,255,255,var(--tw-text-opacity))}.text-gray-500{--tw-text-opacity:1;color:rgba(107,114,128,var(--tw-text-opacity))}.text-gray-800{--tw-text-opacity:1;color:rgba(31,41,55,var(--tw-text-opacity))}.opacity-40{opacity:.4}*,:after,:before{--tw-shadow:0 0 transparent}.shadow{--tw-shadow:0 1px 3px 0 rgba(0,0,0,0.1),0 1px 2px 0 rgba(0,0,0,0.06)}.shadow,.shadow-inner{box-shadow:var(--tw-ring-offset-shadow,0 0 transparent),var(--tw-ring-shadow,0 0 transparent),var(--tw-shadow)}.shadow-inner{--tw-shadow:inset 0 2px 4px 0 rgba(0,0,0,0.06)}*,:after,:before{--tw-ring-inset:var(--tw-empty,/*!*/ /*!*/);--tw-ring-offset-width:0px;--tw-ring-offset-color:#fff;--tw-ring-color:rgba(59,130,246,0.5);--tw-ring-offset-shadow:0 0 transparent;--tw-ring-shadow:0 0 transparent}.filter{--tw-blur:var(--tw-empty,/*!*/ /*!*/);--tw-brightness:var(--tw-empty,/*!*/ /*!*/);--tw-contrast:var(--tw-empty,/*!*/ /*!*/);--tw-grayscale:var(--tw-empty,/*!*/ /*!*/);--tw-hue-rotate:var(--tw-empty,/*!*/ /*!*/);--tw-invert:var(--tw-empty,/*!*/ /*!*/);--tw-saturate:var(--tw-empty,/*!*/ /*!*/);--tw-sepia:var(--tw-empty,/*!*/ /*!*/);--tw-drop-shadow:var(--tw-empty,/*!*/ /*!*/);-webkit-filter:var(--tw-blur) var(--tw-brightness) var(--tw-contrast) var(--tw-grayscale) var(--tw-hue-rotate) var(--tw-invert) var(--tw-saturate) var(--tw-sepia) var(--tw-drop-shadow);filter:var(--tw-blur) var(--tw-brightness) var(--tw-contrast) var(--tw-grayscale) var(--tw-hue-rotate) var(--tw-invert) var(--tw-saturate) var(--tw-sepia) var(--tw-drop-shadow)}:root{--shadow:0 4px 9px 0 rgba(82,79,79,0.1);--border:1px solid rgba(0,0,0,0.1);--border-radius:20px;--content-max-width:1100px;--content-padding:1rem;--button-padding:14px 22px;--button-radius:5px;--button-font-size:16px;--button-font-weight:500;--icon-size:30px}html{--background-color:#f5f5f7;--highlight-color:#fff;--primary-block-color:#1a9ca6;--secondary-block-color:#fff;--primary-text-color:#fff;--secondary-text-color:#3a3a3c;--button-background:#e5e5ea;--button-hover:#e1e1e6;--header-height:calc(var(--header-navigation-height) + var(--offline-notification-height) + var(--header-spacing) + env(safe-area-inset-top));--header-spacing:0px;--header-navigation-height:70px;--status-bar-highlight-color:#ef4444;--offline-notification-height:0px;--header-items-height:calc(60px + env(safe-area-inset-bottom));--footer-content-height:20px;--footer-height:calc(var(--footer-content-height) + 2 * var(--content-padding));--sidebar-width:300px}@media(min-width:768px){html{--header-spacing:10px;--header-items-height:0px}}@media(max-width:767px){html{--footer-content-height:40px}}html.dark-mode{--background-color:#1c1c1e;--highlight-color:#0a84ff;--primary-block-color:#2c2c2e;--secondary-block-color:#8e8e93;--primary-text-color:#fff;--secondary-text-color:#f2f2f7;--button-background:#3a3a3a;--button-hover:#3b3b3d}html.offline{--offline-notification-height:30px}body{background-color:var(--primary-block-color);color:var(--primary-text-color);font-size:12px;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale;margin:0;font-family:Raleway,sans-serif}@supports(font-variation-settings:normal){body{font-family:Raleway VF,sans-serif}}#__next{background-color:var(--background-color)}main{margin:0 auto;max-width:var(--content-max-width);min-height:calc(100vh - var(--header-items-height) - var(--header-height) - var(--footer-height) - 2 * var(--content-padding));padding:calc(var(--header-height) + var(--content-padding)) var(--content-padding) var(--content-padding) var(--content-padding)}ul{list-style:none;margin:0;padding:0}h1{font-size:36px;font-weight:500}a{color:var(--primary-text-color);text-decoration:none}button{background-color:transparent;border:0 initial;border-color:initial;color:inherit;cursor:pointer;font:inherit;outline:0;outline-color:initial;outline-style:none;outline-width:0;padding:0}@media (min-width:768px){.md\:h-8vw{height:8vw}}@media (min-width:1024px){.lg\:flex{display:flex}.lg\:w-1\/3{width:33.333333%}.lg\:w-2\/12{width:16.666667%}.lg\:w-11\/12{width:91.666667%}.lg\:justify-end{justify-content:flex-end}.lg\:px-0{padding-left:0;padding-right:0}.lg\:px-2{padding-left:.5rem;padding-right:.5rem}.lg\:py-2{padding-top:.5rem;padding-bottom:.5rem}.lg\:text-left{text-align:left}}@media (min-width:1280px){.xl\:w-full{width:100%}}@-webkit-keyframes Icon_placeholderAnimation__10Ups{0%{background-position:-1200px 0}to{background-position:1200px 0}}@keyframes Icon_placeholderAnimation__10Ups{0%{background-position:-1200px 0}to{background-position:1200px 0}}.Icon_icon__1HKm4{display:inline-block;height:var(--icon-size);width:var(--icon-size)}.Icon_loader__2i9l8{border-radius:50%;-webkit-animation:Icon_placeholderAnimation__10Ups 2s linear infinite;animation:Icon_placeholderAnimation__10Ups 2s linear infinite;background-image:linear-gradient(90deg,rgba(0,0,0,.08) 0,rgba(0,0,0,.15) 15%,rgba(0,0,0,.08) 30%);background-size:1200px 100%}.Items_items__3XxFg{align-items:center;display:flex;flex-flow:row;justify-content:flex-end;list-style:none;padding:0}@media(max-width:767px){.Items_items__3XxFg{background-color:var(--primary-block-color);bottom:0;box-shadow:var(--shadow);box-sizing:border-box;height:var(--header-items-height);justify-content:space-evenly;left:0;padding:1rem 1rem max(env(safe-area-inset-bottom),1rem);position:fixed;width:100vw}}.Items_items__3XxFg a{color:var(--primary-text-color);font-weight:500}.Items_items__3XxFg>li{border-radius:20px;font-size:18px;margin:0 5px;padding:10px 20px;transition:background-color .2s}@media(min-width:768px){.Items_items__3XxFg>li:last-child{margin:0 0 0 5px}}.Items_active__25BJ4{--background-color:rgba(0,0,0,0.05);background-color:var(--background-color)}html.dark-mode .Items_active__25BJ4{--background-color:hsla(0,0%,100%,0.05)}.Items_active__25BJ4>a{color:var(--highlight-color)}.Logo_logo__3z1BE a{align-items:center;color:var(--primary-text-color);display:flex;font-size:44px;font-weight:500}@-webkit-keyframes ThemeToggler_moveIn__U3-hm{0%{-webkit-transform:translateX(-200%);transform:translateX(-200%)}to{-webkit-transform:translateX(0);transform:translateX(0)}}@keyframes ThemeToggler_moveIn__U3-hm{0%{-webkit-transform:translateX(-200%);transform:translateX(-200%)}to{-webkit-transform:translateX(0);transform:translateX(0)}}@-webkit-keyframes ThemeToggler_moveOut__2aokW{0%{-webkit-transform:translateX(0);transform:translateX(0)}to{-webkit-transform:translateX(200%);transform:translateX(200%)}}@keyframes ThemeToggler_moveOut__2aokW{0%{-webkit-transform:translateX(0);transform:translateX(0)}to{-webkit-transform:translateX(200%);transform:translateX(200%)}}.ThemeToggler_statusBarHighlight__IrriK{background-color:var(--status-bar-highlight-color);height:env(safe-area-inset-top);left:0;margin:0;position:fixed;top:0;width:100vw}html.dark-mode .ThemeToggler_statusBarHighlight__IrriK{display:none}.ThemeToggler_themeToggler__1r-_m{align-items:center;border:var(--border);border-radius:50%;display:flex;height:50px;justify-content:center;overflow:hidden;padding:6px;position:relative;width:50px}.ThemeToggler_themeTogglerIcon__2v4tZ{--icon-size:30px;fill:transparent;position:absolute}.ThemeToggler_themeTogglerSettings__1mvAF{display:flex;flex-flow:column;position:absolute;padding:var(--content-padding);top:calc(var(--header-navigation-height) - 5px);left:50%;opacity:0;-webkit-transform:translateX(-50%) scale(0);transform:translateX(-50%) scale(0);box-sizing:border-box;background-color:var(--primary-block-color);border-radius:var(--border-radius);box-shadow:var(--shadow);transition-duration:.2s;transition-property:opacity,-webkit-transform;transition-property:transform,opacity;transition-property:transform,opacity,-webkit-transform;transition-timing-function:ease-in-out}.ThemeToggler_themeTogglerSettings__1mvAF>li{display:flex;flex-flow:row;align-items:center;gap:10px}.ThemeToggler_themeTogglerSettings__1mvAF>li:not(:first-child){margin:var(--content-padding) 0 0}.ThemeToggler_themeTogglerSettings__1mvAF label{white-space:nowrap}.ThemeToggler_themeTogglerSettingsOpen__1drM1 .ThemeToggler_themeTogglerSettings__1mvAF{opacity:1;-webkit-transform:translateX(-50%) scale(1);transform:translateX(-50%) scale(1)}.ThemeToggler_themeTogglerWrapper__3JMNW{align-items:center;display:flex;height:100%;margin:0 0 0 1rem;position:relative}@media(max-width:1023px){.ThemeToggler_themeTogglerWrapper__3JMNW:hover .ThemeToggler_themeTogglerSettings__1mvAF{opacity:1;-webkit-transform:translateX(-50%) scale(1);transform:translateX(-50%) scale(1)}}html.dark-mode .ThemeToggler_themeToggler__1r-_m>:first-child{-webkit-animation-name:ThemeToggler_moveIn__U3-hm;animation-name:ThemeToggler_moveIn__U3-hm}html.dark-mode .ThemeToggler_themeToggler__1r-_m>:last-child{-webkit-animation-name:ThemeToggler_moveOut__2aokW;animation-name:ThemeToggler_moveOut__2aokW}.ThemeToggler_themeToggler__1r-_m>:first-child,.ThemeToggler_themeToggler__1r-_m>:last-child{-webkit-animation-duration:.5s;animation-duration:.5s;-webkit-animation-fill-mode:forwards;animation-fill-mode:forwards;-webkit-animation-iteration-count:initial;animation-iteration-count:1;-webkit-animation-timing-function:ease-in-out;animation-timing-function:ease-in-out}.ThemeToggler_themeToggler__1r-_m>:first-child{-webkit-animation-name:ThemeToggler_moveOut__2aokW;animation-name:ThemeToggler_moveOut__2aokW}.ThemeToggler_themeToggler__1r-_m>:last-child{-webkit-animation-name:ThemeToggler_moveIn__U3-hm;animation-name:ThemeToggler_moveIn__U3-hm}.Header_header__-Uzh_{--header-color:var(--primary-block-color);background-color:var(--header-color);box-shadow:var(--shadow);color:var(--primary-text-color);display:flex;flex-flow:column;height:var(--header-navigation-height);left:0;padding:env(safe-area-inset-top) 0 0;position:fixed;top:0;width:100vw;z-index:10}@media(min-width:768px){.Header_header__-Uzh_{--header-color:hsla(0,0%,100%,0.8);-webkit-backdrop-filter:saturate(50%) blur(20px);backdrop-filter:saturate(50%) blur(20px);border-radius:calc(var(--header-navigation-height) / 2);box-sizing:border-box;left:50%;margin:0 auto;max-width:var(--content-max-width);padding:0 var(--content-padding);top:calc(var(--header-spacing) / 2 + var(--offline-notification-height));-webkit-transform:translateX(-50%);transform:translateX(-50%);width:calc(100vw - var(--content-padding) * 2)}html.dark-mode .Header_header__-Uzh_{--header-color:rgba(44,44,46,0.8)}}.Header_header__-Uzh_ nav{box-sizing:border-box;height:var(--header-navigation-height);margin:0 auto;max-width:var(--content-max-width);padding:0 var(--content-padding);width:100%}@media(min-width:768px){.Header_header__-Uzh_ nav{display:grid;grid-column-gap:50px;grid-template-columns:1fr 1fr}}.Header_headerControls__3voY0{align-items:center;display:flex;height:100%}@media(max-width:767px){.Header_headerControls__3voY0{justify-content:space-between}}.Header_offline__14MD7{align-items:center;background-color:#edde5d;box-shadow:var(--shadow);color:#000;display:none;font-size:15px;justify-content:center;min-height:var(--offline-notification-height);position:fixed;top:0;width:100%;z-index:10}@media(max-width:767px){.Header_offline__14MD7{top:var(--header-navigation-height)}}.Header_offlineIcon__3kqIF{--icon-size:20px;margin:0 5px}html.offline .Header_offline__14MD7{display:flex}.Footer_footer__2BvtZ{background-color:var(--primary-block-color);box-sizing:border-box;display:flex;flex-wrap:wrap;font-size:16px;font-weight:500;justify-content:center;padding:var(--content-padding) var(--content-padding) calc(var(--header-items-height) + var(--content-padding));width:100vw}.Footer_footer__2BvtZ p{display:inline-block;margin:0 10px}.Footer_footer__2BvtZ a{color:var(--secondary-text-color);font-size:17px;font-weight:600}@-webkit-keyframes Notification_fadeInLeft__1y4vm{0%{opacity:0;-webkit-transform:translateX(-200px);transform:translateX(-200px)}to{opacity:1;-webkit-transform:translateX(0);transform:translateX(0)}}@keyframes Notification_fadeInLeft__1y4vm{0%{opacity:0;-webkit-transform:translateX(-200px);transform:translateX(-200px)}to{opacity:1;-webkit-transform:translateX(0);transform:translateX(0)}}@-webkit-keyframes Notification_fadeOutRight__1XjzJ{0%{opacity:1;-webkit-transform:translateX(0);transform:translateX(0)}to{opacity:0;-webkit-transform:translateX(200px);transform:translateX(200px)}}@keyframes Notification_fadeOutRight__1XjzJ{0%{opacity:1;-webkit-transform:translateX(0);transform:translateX(0)}to{opacity:0;-webkit-transform:translateX(200px);transform:translateX(200px)}}.Notification_notification__1d_Hc{--notification-vertical-padding:1rem;--notification-horizontal-padding:3rem;--notification-padding:var(--notification-vertical-padding) var(--notification-horizontal-padding);-webkit-animation-duration:var(--animation-duration);animation-duration:var(--animation-duration);-webkit-animation-timing-function:ease-in-out;animation-timing-function:ease-in-out;background-color:var(--primary-block-color);border-radius:5px;box-shadow:var(--shadow);color:var(--primary-text-color);display:block;margin:0 0 10px;padding:var(--notification-padding);position:relative;will-change:opacity,transform}.Notification_notification__1d_Hc:last-child{margin:0}.Notification_notification__1d_Hc p{font-size:16px;font-weight:500;margin:0;text-align:center}.Notification_notification__1d_Hc button{--size:20px;height:var(--size);position:absolute;right:calc(var(--notification-horizontal-padding) / 2 - var(--size) / 2);top:50%;-webkit-transform:translateY(-50%);transform:translateY(-50%);width:var(--size)}.Notification_notification__1d_Hc button:after,.Notification_notification__1d_Hc button:before{--rotation:0deg;background-color:var(--primary-text-color);border-radius:1px;content:"";display:block;height:var(--size);left:50%;position:absolute;top:0;-webkit-transform:translateX(-50%) rotate(var(--rotation));transform:translateX(-50%) rotate(var(--rotation));width:2px}.Notification_notification__1d_Hc button:before{--rotation:45deg}.Notification_notification__1d_Hc button:after{--rotation:-45deg}.Notification_notificationOpen__28pqS{-webkit-animation-name:Notification_fadeInLeft__1y4vm;animation-name:Notification_fadeInLeft__1y4vm}.Notification_notificationClose__2kdrL{-webkit-animation-name:Notification_fadeOutRight__1XjzJ;animation-name:Notification_fadeOutRight__1XjzJ}.NotificationList_notificationList__1DGw8{--animation-duration:0;display:flex;flex-flow:column;left:50%;max-width:300px;position:fixed;top:calc(var(--header-height) + var(--content-padding));-webkit-transform:translateX(-50%);transform:translateX(-50%);z-index:100}@media(max-width:767px){.NotificationList_notificationList__1DGw8{bottom:calc(var(--header-items-height) + var(--content-padding));padding:0 var(--content-padding);top:auto;width:100vw}}.Loginpage_wrapper__1fWbd{padding:var(--header-height) 0 0}.Loginpage_wrapper__1fWbd,html.dark-mode .Loginpage_wrapper__1fWbd{background-color:#1a9ca6!important}.Loginpage_landing__2JreH{--primary-text-color:#f2f2f7;--secondary-text-color:#f3f3f7;display:grid;grid-column-gap:20px;grid-template-columns:1fr auto;grid-template-rows:auto 1fr;margin:0 auto;max-width:var(--content-max-width);padding:var(--content-padding)}@media(max-width:767px){.Loginpage_landing__2JreH{grid-template-columns:auto}}.Loginpage_landingText__35xOi{margin:0 auto;max-width:650px;text-align:center}.Loginpage_landingText__35xOi h1,.Loginpage_landingText__35xOi p{color:var(--primary-text-color);font-weight:600}.Loginpage_landingText__35xOi p{font-size:20px;font-weight:500}.Loginpage_landingNavigationWrapper__1SWyT{display:block;margin:1rem auto 0;text-align:center}@media(max-width:767px){.Loginpage_landingNavigationWrapper__1SWyT{grid-row:3}}.Loginpage_landingNavigationWrapper__1SWyT a{--button-font-weight:600;--button-background:#000;--button-hover:#000;background-color:var(--button-background);border:1px solid var(--button-background);border-radius:var(--button-radius);color:var(--primary-text-color);cursor:pointer;display:inline-block;font-size:var(--button-font-size);font-weight:var(--button-font-weight);padding:var(--button-padding);width:auto}.Loginpage_landingNavigationWrapper__1SWyT a:hover{border:1px solid var(--button-hover);background-color:var(--button-hover)}.Loginpage_landingNavigationWrapper__1SWyT p{color:var(--secondary-text-color);font-size:16px;font-weight:500}.Loginpage_landingImage__1Uuk_{display:block;margin:0 auto;width:-webkit-fit-content;width:-moz-fit-content;width:fit-content}@media(min-width:768px){.Loginpage_landingImage__1Uuk_{grid-column:2;grid-row:1/span 2}} | 4,847.4 | 23,122 | 0.791146 |
6b4f835140c8101fde4d669fef28609df28a0a44 | 1,841 | h | C | mbed-client/mbed-protocol-manager/mbed-protocol-manager/protoman_layer_coap.h | micgur01/pelion-client-lite | 7b72273a293fbc75757d3e59dd306a80111d3eff | [
"Apache-2.0"
] | 2 | 2020-02-12T14:26:35.000Z | 2020-06-19T06:43:18.000Z | mbed-client/mbed-protocol-manager/mbed-protocol-manager/protoman_layer_coap.h | micgur01/pelion-client-lite | 7b72273a293fbc75757d3e59dd306a80111d3eff | [
"Apache-2.0"
] | 2 | 2021-10-21T11:14:50.000Z | 2022-01-04T12:47:54.000Z | mbed-client/mbed-protocol-manager/mbed-protocol-manager/protoman_layer_coap.h | micgur01/pelion-client-lite | 7b72273a293fbc75757d3e59dd306a80111d3eff | [
"Apache-2.0"
] | 3 | 2021-03-03T16:01:21.000Z | 2022-02-03T16:45:50.000Z | /*
* PackageLicenseDeclared: Apache-2.0
* Copyright (c) 2017-2018 ARM Limited
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef PROTOMAN_LAYER_COAP_H
#define PROTOMAN_LAYER_COAP_H
#include "stdlib.h"
#include "mbed-coap/sn_coap_header.h"
#include "mbed-coap/sn_coap_protocol.h"
#include "mbed-protocol-manager/protoman.h"
#ifdef __cplusplus
extern "C" {
#endif // __cplusplus
#define PROTOMAN_IO_COAP 127
struct protoman_io_coap_s {
struct protoman_io_header_s header; /* Must be first as protoman_io_bytes_s will be casted to protoman_io_header_s */
sn_coap_hdr_s *coap_header;
};
struct protoman_layer_coap_s {
struct protoman_layer_s layer; /* must be first element */
struct coap_s *coap;
uint32_t coap_time; /* TODO: this timer needs complete overhaul */
uint8_t coap_time_interval; /* TODO: this timer needs complete overhaul */
sn_coap_hdr_s *rx_coap_hdr;
sn_coap_hdr_s *resend_coap_hdr;
sn_nsdl_addr_s dummy_addr;
};
void protoman_add_layer_coap(struct protoman_s *protoman, struct protoman_layer_s *layer);
sn_coap_options_list_s *protoman_coap_alloc_options(protoman_layer_id_t id, sn_coap_hdr_s *header);
void protoman_coap_free_msg_mem(protoman_layer_id_t id, sn_coap_hdr_s *header);
#ifdef __cplusplus
}
#endif // __cplusplus
#endif // PROTOMAN_LAYER_COAP_H
| 31.20339 | 121 | 0.770234 |
8ce03437364816a0f931d839755fc005374414e7 | 1,217 | kt | Kotlin | buildSrc/src/main/kotlin/com/github/turansky/yfiles/correction/CollectionHacks.kt | Turansky/api-js-to-kotlin | 88fba6ad40c4e5bf94a02feccd2331102704bca4 | [
"Apache-2.0"
] | 24 | 2019-10-23T15:47:50.000Z | 2022-02-20T15:16:24.000Z | buildSrc/src/main/kotlin/com/github/turansky/yfiles/correction/CollectionHacks.kt | Turansky/api-js-to-kotlin | 88fba6ad40c4e5bf94a02feccd2331102704bca4 | [
"Apache-2.0"
] | null | null | null | buildSrc/src/main/kotlin/com/github/turansky/yfiles/correction/CollectionHacks.kt | Turansky/api-js-to-kotlin | 88fba6ad40c4e5bf94a02feccd2331102704bca4 | [
"Apache-2.0"
] | 2 | 2020-10-16T07:16:09.000Z | 2020-11-11T20:33:03.000Z | package com.github.turansky.yfiles.correction
import com.github.turansky.yfiles.ICOLLECTION
import com.github.turansky.yfiles.JS_ANY
import com.github.turansky.yfiles.JS_OBJECT
import org.json.JSONObject
private fun collection(generic: String): String =
"$ICOLLECTION<$generic>"
private val DEFAULT_COLLECTIONS = setOf(
collection(JS_ANY),
collection(JS_OBJECT)
)
internal fun applyCollectionHacks(source: Source) {
source.types(
"PathRequest",
"IEdgeData"
).flatMap {
sequenceOf(
it.property("sourcePortCandidates"),
it.property("targetPortCandidates")
)
}.forEach { it.fixTypeGeneric("yfiles.layout.PortCandidate") }
source.type("PartitionGrid")
.flatMap(METHODS)
.single { it[ID] == "PartitionGrid-method-createCellSpanId(yfiles.collections.ICollection,yfiles.collections.ICollection)" }
.apply {
firstParameter.fixTypeGeneric("yfiles.layout.RowDescriptor")
secondParameter.fixTypeGeneric("yfiles.layout.ColumnDescriptor")
}
}
private fun JSONObject.fixTypeGeneric(generic: String) {
require(get(TYPE) in DEFAULT_COLLECTIONS)
set(TYPE, collection(generic))
}
| 29.682927 | 132 | 0.706656 |
00193633cc55eae004045743fd95eca2bbe45ea9 | 22,875 | swift | Swift | FlappyHaru/FlappyHaru/GameScene.swift | wangchaodong/FlappyHaru | bcdf3eabcf546c88aecfba77e4f4a9f19212ca65 | [
"MIT"
] | null | null | null | FlappyHaru/FlappyHaru/GameScene.swift | wangchaodong/FlappyHaru | bcdf3eabcf546c88aecfba77e4f4a9f19212ca65 | [
"MIT"
] | null | null | null | FlappyHaru/FlappyHaru/GameScene.swift | wangchaodong/FlappyHaru | bcdf3eabcf546c88aecfba77e4f4a9f19212ca65 | [
"MIT"
] | null | null | null | //
// GameScene.swift
// FlappyHaru
//
// Created by devil wang on 6/4/16.
// Copyright (c) 2016 devil wang. All rights reserved.
//
import SpriteKit
enum ImageLayer: CGFloat {
case backGround
case roadBlcok
case frontGround
case gameRole
case UI
}
struct physicsLayer {
static let zero: UInt32 = 0 //0
static let gameRole: UInt32 = 0b1 //1
static let gameBlock: UInt32 = 0b10 //2
static let gameGround: UInt32 = 0b100 //4
}
enum gameStatus {
case mainMenu
case teach
case play
case falldown
case showScore
case end
}
class GameScene: SKScene, SKPhysicsContactDelegate {
let learningUrl = "http://hollylee.red"
let appStoreUrl = "http://google.com"
let groundCount = 2
let groundMoveSpeed = -150.0
//重力速度 和 上飞速度
let gravity: CGFloat = -800//-700//-1500
let flySpeed: CGFloat = 250//200//400.0
let kBottomMin: CGFloat = 0.1
let kBottomMax: CGFloat = 0.6
let kConstance: CGFloat = 3.5
let kFirstAddBlocktime: NSTimeInterval = 1.75
let kEachAddBlocktime: NSTimeInterval = 1.5
let ktopBlank: CGFloat = 20.0
let knumFont = "AmericanTypewriter-Bold"
var scoreLabel: SKLabelNode!
var currentScore = 0
let kAnimedelay = 0.3
var roleSpeed = CGPoint.zero
let worldNode = SKNode()
var gameStartPoint: CGFloat = 0
var gameHeight: CGFloat = 0
let gameRole = SKSpriteNode(imageNamed: "harusmall")
let gameCap = SKSpriteNode(imageNamed: "cap")
var lastUpdateTime: NSTimeInterval = 0
var dt: NSTimeInterval = 0
let dingSound = SKAction.playSoundFileNamed("ding.wav", waitForCompletion: false)
let flySound = SKAction.playSoundFileNamed("flapping.wav", waitForCompletion: false)
let crashSound = SKAction.playSoundFileNamed("whack.wav", waitForCompletion: false)
let fallSound = SKAction.playSoundFileNamed("falling.wav", waitForCompletion: false)
let hitgroundSound = SKAction.playSoundFileNamed("hitGround.wav", waitForCompletion: false)
let popSound = SKAction.playSoundFileNamed("pop.wav", waitForCompletion: false)
let coinSound = SKAction.playSoundFileNamed("coin.wav", waitForCompletion: false)
var hitBlock = false
var hitGround = false
var currentStatus: gameStatus = .play
override func didMoveToView(view: SKView) {
//关闭重力
physicsWorld.gravity = CGVectorMake(0, 0)
//设置代理
physicsWorld.contactDelegate = self
addChild(worldNode)
// switchtoTeach()
switchtoMainmenu()
}
// MARK: setting bg fg
func setMainMenu() {
//logo
let logo = SKSpriteNode(imageNamed: "Logo")
logo.position = CGPoint(x: size.width/2, y: size.height*0.8)
logo.name = "mainmenu"
logo.zPosition = ImageLayer.UI.rawValue
worldNode.addChild(logo)
// start game btn
let startBtn = SKSpriteNode(imageNamed: "Button")
startBtn.position = CGPoint(x: size.width*0.25, y: size.height*0.25)
startBtn.name = "mainmenu"
startBtn.zPosition = ImageLayer.UI.rawValue
worldNode.addChild(startBtn)
let play = SKSpriteNode(imageNamed: "Play")
play.position = CGPoint.zero
startBtn.addChild(play)
// rate Btn
let rateBtn = SKSpriteNode(imageNamed: "Button")
rateBtn.position = CGPoint(x: size.width*0.75, y: size.height*0.25)
rateBtn.name = "mainmenu"
rateBtn.zPosition = ImageLayer.UI.rawValue
worldNode.addChild(rateBtn)
let rate = SKSpriteNode(imageNamed: "Rate")
rate.position = CGPoint.zero
rateBtn.addChild(rate)
// learnBtn
let learnBtn = SKSpriteNode(imageNamed: "button_learn")
learnBtn.position = CGPoint(x: size.width*0.5, y: learnBtn.size.height/2 + ktopBlank)
learnBtn.name = "mainmenu"
learnBtn.zPosition = ImageLayer.UI.rawValue
worldNode.addChild(learnBtn)
//learnBtn anime
let biggeranime = SKAction.scaleTo(1.02, duration: 0.75)
biggeranime.timingMode = .EaseInEaseOut
let smalleranime = SKAction.scaleTo(0.98, duration: 0.75)
biggeranime.timingMode = .EaseInEaseOut
learnBtn.runAction(SKAction.repeatActionForever(SKAction.sequence([
biggeranime,
smalleranime
])))
}
func setBackGround() {
let bg = SKSpriteNode(imageNamed: "Background")
bg.anchorPoint = CGPoint(x: 0.5, y: 1.0)
bg.position = CGPoint(x: size.width/2, y: size.height)
bg.zPosition = ImageLayer.backGround.rawValue
worldNode.addChild(bg)
gameStartPoint = size.height - bg.size.height
gameHeight = bg.size.height
let leftdown = CGPoint(x: 0, y: gameStartPoint)
let rightdown = CGPoint(x: size.width, y: gameStartPoint)
self.physicsBody = SKPhysicsBody(edgeFromPoint: leftdown, toPoint: rightdown)
self.physicsBody?.categoryBitMask = physicsLayer.gameGround
self.physicsBody?.collisionBitMask = 0
self.physicsBody?.contactTestBitMask = physicsLayer.gameRole
}
func setFrontground() {
for i in 0..<groundCount {
let fg = SKSpriteNode(imageNamed: "Ground")
fg.anchorPoint = CGPoint(x: 0, y: 1.0)
fg.position = CGPoint(x: 0 + CGFloat(i) * fg.size.width, y: gameStartPoint)
fg.zPosition = ImageLayer.frontGround.rawValue
fg.name = "前景"
worldNode.addChild(fg)
}
}
func setScoreLabel() {
scoreLabel = SKLabelNode(fontNamed: knumFont)
scoreLabel.fontColor = SKColor.greenColor()
scoreLabel.position = CGPoint(x: size.width/2, y: size.height-ktopBlank)
scoreLabel.verticalAlignmentMode = .Top
scoreLabel.text = "0"
scoreLabel.zPosition = ImageLayer.UI.rawValue
worldNode.addChild(scoreLabel)
}
func setScorePlate() {
if currentScore > getHeightesScore() {
setHeightestScore(currentScore)
}
let scorePlate = SKSpriteNode(imageNamed: "ScoreCard")
scorePlate.position = CGPoint(x: size.width/2, y: size.height/2)
scorePlate.zPosition = ImageLayer.UI.rawValue
worldNode.addChild(scorePlate)
let currentSLabel = SKLabelNode(fontNamed: knumFont)
currentSLabel.fontColor = SKColor.redColor()
currentSLabel.position = CGPoint(x: -scorePlate.size.width/4, y: -scorePlate.size.height/3)
currentSLabel.text = "\(currentScore)"
currentSLabel.zPosition = ImageLayer.UI.rawValue
scorePlate.addChild(currentSLabel)
let heightestSLabel = SKLabelNode(fontNamed: knumFont)
heightestSLabel.fontColor = SKColor.redColor()
heightestSLabel.position = CGPoint(x: scorePlate.size.width/4, y: -scorePlate.size.height/3)
heightestSLabel.text = "\(getHeightesScore())"
heightestSLabel.zPosition = ImageLayer.UI.rawValue
scorePlate.addChild(heightestSLabel)
let gameOver = SKSpriteNode(imageNamed: "GameOver")
gameOver.position = CGPoint(x: size.width/2, y: size.height/2+scorePlate.size.height/2+ktopBlank+gameOver.size.height/2)
gameOver.zPosition = ImageLayer.UI.rawValue
worldNode.addChild(gameOver)
let okBtn = SKSpriteNode(imageNamed: "Button")
okBtn.position = CGPoint(x: size.width/4, y: size.height/2-scorePlate.size.height/2-ktopBlank-okBtn.size.height/2)
okBtn.zPosition = ImageLayer.UI.rawValue
worldNode.addChild(okBtn)
let ok = SKSpriteNode(imageNamed: "OK")
ok.position = CGPoint.zero
ok.zPosition = ImageLayer.UI.rawValue
okBtn.addChild(ok)
let shareBtn = SKSpriteNode(imageNamed: "ButtonRight")
shareBtn.position = CGPoint(x: size.width/4*3, y: size.height/2-scorePlate.size.height/2-ktopBlank-okBtn.size.height/2)
shareBtn.zPosition = ImageLayer.UI.rawValue
worldNode.addChild(shareBtn)
let share = SKSpriteNode(imageNamed: "Share")
share.position = CGPoint.zero
share.zPosition = ImageLayer.UI.rawValue
shareBtn.addChild(share)
gameOver.setScale(0)
gameOver.alpha = 0
let animationS = SKAction.group([
SKAction.fadeInWithDuration(kAnimedelay),
SKAction.scaleTo(1, duration: kAnimedelay)
])
animationS.timingMode = .EaseInEaseOut
gameOver.runAction(SKAction.sequence([
SKAction.waitForDuration(kAnimedelay),
animationS,
popSound
]))
scorePlate.position = CGPoint(x: size.width/2, y: -scorePlate.size.height/2)
let moveup = SKAction.moveTo(CGPoint(x: size.width/2, y: size.height/2), duration: kAnimedelay)
moveup.timingMode = .EaseInEaseOut
scorePlate.runAction(SKAction.sequence([
SKAction.waitForDuration(kAnimedelay*2),
moveup,
popSound
]))
okBtn.alpha = 0
shareBtn.alpha = 0
let fadeanime = SKAction.sequence([
SKAction.waitForDuration(kAnimedelay*3),
SKAction.fadeInWithDuration(kAnimedelay),
popSound,
SKAction.runBlock(switchtoEnding)
])
okBtn.runAction(fadeanime)
shareBtn.runAction(fadeanime)
}
// func playSound() {
// let path = NSBundle.mainBundle().URLForResource("flapping", withExtension: "wav")
//
// sound = try? AVAudioPlayer(contentsOfURL: path!)
// sound.play()
// }
func setRole()
{
gameRole.position = CGPoint(x: size.width * 0.2, y: gameHeight * 0.4 + gameStartPoint)
gameRole.zPosition = ImageLayer.gameRole.rawValue
let offsetX = gameRole.size.width * gameRole.anchorPoint.x
let offsetY = gameRole.size.height * gameRole.anchorPoint.y
let path = CGPathCreateMutable()
CGPathMoveToPoint(path, nil, 0 - offsetX, 0 - offsetY)
CGPathAddLineToPoint(path, nil, 4 - offsetX, 6 - offsetY)
CGPathAddLineToPoint(path, nil, 6 - offsetX, 16 - offsetY)
CGPathAddLineToPoint(path, nil, 5 - offsetX, 23 - offsetY)
CGPathAddLineToPoint(path, nil, 15 - offsetX, 22 - offsetY)
CGPathAddLineToPoint(path, nil, 19 - offsetX, 18 - offsetY)
CGPathAddLineToPoint(path, nil, 18 - offsetX, 8 - offsetY)
CGPathAddLineToPoint(path, nil, 20 - offsetX, 5 - offsetY)
CGPathAddLineToPoint(path, nil, 19 - offsetX, 1 - offsetY)
CGPathCloseSubpath(path)
gameRole.physicsBody = SKPhysicsBody(polygonFromPath: path)
gameRole.physicsBody?.categoryBitMask = physicsLayer.gameRole
gameRole.physicsBody?.collisionBitMask = 0
gameRole.physicsBody?.contactTestBitMask = physicsLayer.gameBlock | physicsLayer.gameGround
worldNode.addChild(gameRole)
}
func setRoleCap()
{
gameCap.position = CGPoint(x: 10 - gameCap.size.width/2, y: 20 - gameCap.size.height/2)
gameRole.addChild(gameCap)
}
func setteach() {
let teach = SKSpriteNode(imageNamed: "Tutorial1")
teach.position = CGPoint(x: size.width/2, y: gameHeight*0.4+gameStartPoint)
teach.name = "teach"
teach.zPosition = ImageLayer.UI.rawValue
worldNode.addChild(teach)
let ready = SKSpriteNode(imageNamed: "Ready")
ready.position = CGPoint(x: size.width/2, y: gameHeight*0.7+gameStartPoint)
ready.name = "teach"
ready.zPosition = ImageLayer.UI.rawValue
worldNode.addChild(ready)
}
// MARK: 游戏流程
func createRoadBlock(imgname: String) -> SKSpriteNode {
let roadblock = SKSpriteNode(imageNamed: imgname)
roadblock.zPosition = ImageLayer.roadBlcok.rawValue
roadblock.userData = NSMutableDictionary()
let offsetX = roadblock.size.width * roadblock.anchorPoint.x
let offsetY = roadblock.size.height * roadblock.anchorPoint.y
let path = CGPathCreateMutable()
CGPathMoveToPoint(path, nil, 4 - offsetX, 1 - offsetY)
CGPathAddLineToPoint(path, nil, 4 - offsetX, 311 - offsetY)
CGPathAddLineToPoint(path, nil, 48 - offsetX, 310 - offsetY)
CGPathAddLineToPoint(path, nil, 48 - offsetX, 1 - offsetY)
CGPathCloseSubpath(path)
roadblock.physicsBody = SKPhysicsBody(polygonFromPath: path)
roadblock.physicsBody?.categoryBitMask = physicsLayer.gameBlock
roadblock.physicsBody?.collisionBitMask = 0
roadblock.physicsBody?.contactTestBitMask = physicsLayer.gameRole
return roadblock
}
func addRoadBlock() {
let bottomBlock = createRoadBlock("CactusBottom")
bottomBlock.name = "bottomBlock"
let starX = size.width + bottomBlock.size.width/2
let minY = (gameStartPoint - bottomBlock.size.height/2) + gameHeight * kBottomMin
let maxY = (gameStartPoint - bottomBlock.size.height/2) + gameHeight * kBottomMax
bottomBlock.position = CGPointMake(starX, CGFloat.random(min: minY, max:maxY))
worldNode.addChild(bottomBlock)
let topBlock = createRoadBlock("CactusTop")
topBlock.name = "topBlock"
topBlock.zRotation = CGFloat(180).degreesToRadians()
topBlock.position = CGPointMake(starX, bottomBlock.position.y + bottomBlock.size.height/2 + topBlock.size.height/2 + gameRole.size.height * kConstance)
worldNode.addChild(topBlock)
let xMoveDistance = -(size.width + bottomBlock.size.width)
let movingDuration = xMoveDistance / CGFloat(groundMoveSpeed)
let movingActions = SKAction.sequence([
SKAction.moveByX(xMoveDistance, y: 0, duration: NSTimeInterval(movingDuration))
])
bottomBlock.runAction(movingActions)
topBlock.runAction(movingActions)
}
func AddBlockLoop() {
let firstDelay = SKAction.waitForDuration(kFirstAddBlocktime)
let rebornBlock = SKAction.runBlock(addRoadBlock)
let eachRebornDelay = SKAction.waitForDuration(kEachAddBlocktime)
let RebornActions = SKAction.sequence([rebornBlock,eachRebornDelay])
let RebornLoop = SKAction.repeatActionForever(RebornActions)
let AllAction = SKAction.sequence([firstDelay, RebornLoop])
runAction(AllAction, withKey: "reborn")
}
func stopAddBlock() {
removeActionForKey("reborn")
worldNode.enumerateChildNodesWithName("bottomBlock") { (node, _) in
node.removeAllActions()
}
worldNode.enumerateChildNodesWithName("topBlock") { (node, _) in
node.removeAllActions()
}
}
func gameRoleFly() {
roleSpeed = CGPoint(x: 0, y: flySpeed)
gameCapAction()
//播放音效
runAction(flySound)
}
func gameCapAction() {
let moveup = SKAction.moveByX(0, y: 12, duration: 0.15)
moveup.timingMode = .EaseInEaseOut
let movedown = moveup.reversedAction()
gameCap.runAction(SKAction.sequence([moveup,movedown]))
}
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
guard let click = touches.first else {
return
}
let clickpoint = click.locationInNode(self)
switch currentStatus {
case .mainMenu:
if clickpoint.y < size.height * 0.15 {
toLearning()
}
else if clickpoint.x < size.width/2 {
switchtoTeach()
}
else {
toRating()
}
break
case .teach:
switchtoPlay()
break
case .play:
//主角飞
gameRoleFly()
break
case .falldown:
break
case .showScore:
break
case .end:
switchToNewGame()
break
}
}
//MARK: Update
override func update(currentTime: NSTimeInterval) {
if lastUpdateTime > 0 {
dt = currentTime - lastUpdateTime
} else {
dt = 0
}
lastUpdateTime = currentTime
switch currentStatus {
case .mainMenu:
break
case .teach:
break
case .play:
updateFrontGround()
updateGameRole()
detectHitBlock()
detecHitGround()
updateScore()
break
case .falldown:
updateGameRole()
detecHitGround()
break
case .showScore:
break
case .end:
break
}
// updateGameRole()
// updateFrontGround()
// detectHitObject()
}
func updateGameRole()
{
let acceleration = CGPoint(x: 0, y: gravity)
roleSpeed = roleSpeed + acceleration * CGFloat(dt)
gameRole.position = gameRole.position + roleSpeed * CGFloat(dt)
//碰到地面 停止
if gameRole.position.y - gameRole.size.height/2 < gameStartPoint {
gameRole.position = CGPoint(x: gameRole.position.x, y: gameStartPoint + gameRole.size.height/2)
}
}
func updateFrontGround() {
worldNode.enumerateChildNodesWithName("前景") { (sknode, _) in
if let fg = sknode as? SKSpriteNode {
let groundSpeed = CGPoint(x: self.groundMoveSpeed, y: 0)
fg.position = fg.position + groundSpeed * CGFloat(self.dt)
if fg.position.x < -fg.size.width {
fg.position = fg.position + CGPoint(x: fg.size.width * CGFloat(self.groundCount), y: 0)
}
}
}
}
//撞击block
func detectHitBlock() {
if hitBlock {
hitBlock = false
switchToFalldown()
}
}
//撞击地面
func detecHitGround() {
if hitGround {
hitGround = false
roleSpeed = CGPoint.zero
gameRole.zRotation = CGFloat(-90).degreesToRadians()
// gameRole.position = CGPoint(x: gameRole.position.x, y: gameStartPoint + gameRole.size.width/2)
runAction(hitgroundSound)
switchToShowScore()
}
}
func updateScore() {
worldNode.enumerateChildNodesWithName("topBlock") { (node, _) in
if let block = node as? SKSpriteNode {
if let hadpass = block.userData?["hadpass"] as? NSNumber {
if hadpass.boolValue {
return //已经计算一次得分
}
}
if self.gameRole.position.x > block.position.x + block.size.width/2 {
self.currentScore = self.currentScore + 1
self.scoreLabel.text = "\(self.currentScore)"
self.runAction(self.coinSound)
block.userData?["hadpass"] = NSNumber(bool: true)
}
}
}
}
//MARK: 游戏状态
func switchToFalldown() {
currentStatus = .falldown
runAction(SKAction.sequence([
crashSound,
SKAction.waitForDuration(0.1),
fallSound
]))
gameRole.removeAllActions()
stopAddBlock()
}
func switchToShowScore() {
currentStatus = .showScore
gameRole.removeAllActions()
stopAddBlock()
// NSNotificationCenter.defaultCenter().postNotificationName(MyNotification.showGameSceneNoti, object: nil)
setScorePlate()
}
func switchToNewGame() {
runAction(popSound)
let newgame = GameScene.init(size: size)
let switchTransition = SKTransition.fadeWithColor(SKColor.greenColor(), duration: 0.1)
view?.presentScene(newgame, transition: switchTransition)
}
func switchtoEnding() {
currentStatus = .end
}
func switchtoTeach() {
currentStatus = .teach
// setBackGround()
// setFrontground()
// setRole()
// setRoleCap()
// addRoadBlock()
worldNode.enumerateChildNodesWithName("mainmenu") { (node, _) in
node.runAction(SKAction.sequence([
SKAction.fadeOutWithDuration(0.05),
SKAction.removeFromParent()
]))
}
setScoreLabel()
setteach()
}
func switchtoPlay() {
currentStatus = .play
worldNode.enumerateChildNodesWithName("teach") { (node, _) in
node.runAction(SKAction.sequence([
SKAction.fadeOutWithDuration(0.05),
SKAction.removeFromParent()
]))
}
AddBlockLoop()
gameRoleFly()
}
func switchtoMainmenu() {
currentStatus = .mainMenu
setBackGround()
setFrontground()
setRole()
setRoleCap()
setMainMenu()
}
// MARK: 分数
// 最高分
func getHeightesScore() -> Int {
return NSUserDefaults.standardUserDefaults().integerForKey("heightestScore")
}
func setHeightestScore(score: Int) {
NSUserDefaults.standardUserDefaults().setInteger(score, forKey: "heightestScore")
NSUserDefaults.standardUserDefaults().synchronize()
}
//MARK: physics
func didBeginContact(contact: SKPhysicsContact) {
let beenContact = contact.bodyA.categoryBitMask == physicsLayer.gameRole ? contact.bodyB : contact.bodyA
if beenContact.categoryBitMask == physicsLayer.gameGround {
hitGround = true
}
if beenContact.categoryBitMask == physicsLayer.gameBlock {
hitBlock = true
NSLog("aaa")
}
}
//MARK: ELSE
func toLearning() {
openUrl(learningUrl)
}
func toRating() {
openUrl(appStoreUrl)
}
func openUrl(url:String) {
let nsurl = NSURL(string: url)
UIApplication.sharedApplication().openURL(nsurl!)
}
}
| 33.394161 | 159 | 0.595322 |
70a6f97ff8776b4c8b735cb9bda49dbb04bea69a | 269 | h | C | COS2614/Assignments/Assignment 3/itemwriter.h | ziyaadfredericks/university | 0c9612921b417e6b428a34a84d3012bd07281dd0 | [
"MIT"
] | null | null | null | COS2614/Assignments/Assignment 3/itemwriter.h | ziyaadfredericks/university | 0c9612921b417e6b428a34a84d3012bd07281dd0 | [
"MIT"
] | null | null | null | COS2614/Assignments/Assignment 3/itemwriter.h | ziyaadfredericks/university | 0c9612921b417e6b428a34a84d3012bd07281dd0 | [
"MIT"
] | null | null | null | #ifndef ITEMWRITER_H
#define ITEMWRITER_H
#include "item.h"
#include <QString>
#include <QFile>
class ItemWriter
{
private:
QFile outputFile;
public:
ItemWriter(QString fname);
void writeItem(const Item & i);
~ItemWriter();
};
#endif // ITEMWRITER_H
| 14.157895 | 35 | 0.702602 |
07cd793dc19e30f94e0db5a6884a4521ae513656 | 2,350 | kt | Kotlin | net.akehurst.language.editor/agl-editor-ace/src/jsMain/kotlin/AglTokenizerAce.kt | dhakehurst/net.akehurst.language.editor | 4545320435da906da859f2b583bb7ca0281c6482 | [
"Apache-2.0"
] | 3 | 2020-11-03T09:49:42.000Z | 2021-02-14T01:56:19.000Z | net.akehurst.language.editor/agl-editor-ace/src/jsMain/kotlin/AglTokenizerAce.kt | dhakehurst/net.akehurst.language.editor | 4545320435da906da859f2b583bb7ca0281c6482 | [
"Apache-2.0"
] | 1 | 2021-10-07T11:14:48.000Z | 2021-10-07T11:14:48.000Z | net.akehurst.language.editor/agl-editor-ace/src/jsMain/kotlin/AglTokenizerAce.kt | dhakehurst/net.akehurst.language.editor | 4545320435da906da859f2b583bb7ca0281c6482 | [
"Apache-2.0"
] | null | null | null | /**
* Copyright (C) 2020 Dr. David H. Akehurst (http://dr.david.h.akehurst.net)
*
* 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 net.akehurst.language.editor.ace
import net.akehurst.language.api.sppt.SPPTLeaf
import net.akehurst.language.editor.common.AglComponents
import net.akehurst.language.editor.common.AglStyleHandler
import net.akehurst.language.editor.common.AglTokenizer
class AglBackgroundTokenizer(
tok: ace.Tokenizer,
ed: ace.Editor
) : ace.BackgroundTokenizer(tok, ed) {
}
class AglLineStateAce(
val lineNumber: Int,
val leftOverText: String
) : ace.LineState {
}
class AglTokenAce(
styles: Array<String>,
override val value: String,
override val line: Int,
column: Int
) : ace.Token {
override val type = styles.joinToString(".")
override var start = column
}
class AglLineTokensAce(
override val state: ace.LineState,
override val tokens: Array<ace.Token>
) : ace.LineTokens {}
class AglTokenizerAce(
val agl: AglComponents,
val aglStyleHandler: AglStyleHandler
) : ace.Tokenizer {
val aglTokenizer = AglTokenizer(agl)
// --- ace.Ace.Tokenizer ---
override fun getLineTokens(line: String, pState: ace.LineState?, row: Int): ace.LineTokens {
val sppt = this.agl.sppt
val state = if (null == pState) AglLineStateAce(0, "") else pState as AglLineStateAce
return if (null == sppt) {
this.getLineTokensByScan(line, state, row)
} else {
this.getLineTokensByParse(line, state, row)
}
}
fun getLineTokensByScan(line: String, state: AglLineStateAce, row: Int): ace.LineTokens {
TODO()
}
fun getLineTokensByParse(line: String, state: AglLineStateAce, row: Int): ace.LineTokens {
TODO()
}
} | 30.128205 | 96 | 0.682553 |