hexsha
stringlengths
40
40
size
int64
5
1.05M
ext
stringclasses
98 values
lang
stringclasses
21 values
max_stars_repo_path
stringlengths
3
945
max_stars_repo_name
stringlengths
4
118
max_stars_repo_head_hexsha
stringlengths
40
78
max_stars_repo_licenses
sequencelengths
1
10
max_stars_count
int64
1
368k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
3
945
max_issues_repo_name
stringlengths
4
118
max_issues_repo_head_hexsha
stringlengths
40
78
max_issues_repo_licenses
sequencelengths
1
10
max_issues_count
int64
1
134k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
3
945
max_forks_repo_name
stringlengths
4
135
max_forks_repo_head_hexsha
stringlengths
40
78
max_forks_repo_licenses
sequencelengths
1
10
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
5
1.05M
avg_line_length
float64
1
1.03M
max_line_length
int64
2
1.03M
alphanum_fraction
float64
0
1
58152768a3c22b2d8fccf994b6192e8d8119e648
763
lua
Lua
gist/Lua/get_schema.lua
yatyricky/yatyricky.github.io
fab64b5f6a4dc9c3f29c3e14c2c166b00fd4875b
[ "MIT" ]
null
null
null
gist/Lua/get_schema.lua
yatyricky/yatyricky.github.io
fab64b5f6a4dc9c3f29c3e14c2c166b00fd4875b
[ "MIT" ]
3
2021-08-30T09:00:54.000Z
2022-01-25T02:16:46.000Z
gist/Lua/get_schema.lua
yatyricky/yatyricky.github.io
fab64b5f6a4dc9c3f29c3e14c2c166b00fd4875b
[ "MIT" ]
1
2017-06-11T07:28:06.000Z
2017-06-11T07:28:06.000Z
--nil, boolean, number, string, function, userdata, thread, and table local function get_schema(any) if any == nil then return "nil" end local t = type(any) if t == "string" then return "string" end if t == "number" then return "number" end if t == "function" then return "function" end if t == "nil" then return "nil" end if t == "boolean" then return "boolean" end if t == "userdata" then return "userdata" end if t == "thread" then return "thread" end for key, value in pairs(any) do end end -- primitive type -- table -- field1: string -- field2: number -- field3?: table
20.078947
70
0.520315
a3462df4b61dcee903194630e6d3b55d7e3b7013
7,811
h
C
Example/Source/Examples/Private/Renderer/Scene/Scene.h
cofenberg/unrimp
90310657f106eb83f3a9688329b78619255a1042
[ "MIT" ]
187
2015-11-02T21:27:57.000Z
2022-02-17T21:39:17.000Z
Example/Source/Examples/Private/Renderer/Scene/Scene.h
cofenberg/unrimp
90310657f106eb83f3a9688329b78619255a1042
[ "MIT" ]
null
null
null
Example/Source/Examples/Private/Renderer/Scene/Scene.h
cofenberg/unrimp
90310657f106eb83f3a9688329b78619255a1042
[ "MIT" ]
20
2015-11-04T19:17:01.000Z
2021-11-18T11:23:25.000Z
/*********************************************************\ * Copyright (c) 2012-2021 The Unrimp Team * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software * and associated documentation files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or * substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. \*********************************************************/ //[-------------------------------------------------------] //[ Header guard ] //[-------------------------------------------------------] #pragma once //[-------------------------------------------------------] //[ Includes ] //[-------------------------------------------------------] #include "Examples/Private/Framework/ExampleBase.h" #include <Renderer/Public/Core/Math/Transform.h> #include <Renderer/Public/DebugGui/DebugGuiHelper.h> #include <Renderer/Public/Resource/IResourceListener.h> //[-------------------------------------------------------] //[ Forward declarations ] //[-------------------------------------------------------] class IController; typedef struct ini_t ini_t; namespace DeviceInput { class InputManager; } namespace Renderer { class ImGuiLog; class SceneNode; class CameraSceneItem; class SunlightSceneItem; class DebugDrawSceneItem; class SkeletonMeshSceneItem; class CompositorWorkspaceInstance; } //[-------------------------------------------------------] //[ Global definitions ] //[-------------------------------------------------------] namespace Renderer { typedef uint32_t SceneResourceId; ///< POD scene resource identifier typedef uint32_t MaterialResourceId; ///< POD material resource identifier } //[-------------------------------------------------------] //[ Classes ] //[-------------------------------------------------------] /** * @brief * Scene example * * @remarks * Demonstrates: * - Compositor * - Scene * - Virtual reality (VR) */ class Scene final : public ExampleBase, public Renderer::IResourceListener { //[-------------------------------------------------------] //[ Public methods ] //[-------------------------------------------------------] public: /** * @brief * Default constructor */ Scene(); /** * @brief * Destructor */ virtual ~Scene() override; //[-------------------------------------------------------] //[ Public virtual ExampleBase methods ] //[-------------------------------------------------------] public: virtual void onInitialization() override; virtual void onDeinitialization() override; virtual void onUpdate() override; virtual void onDraw(Rhi::CommandBuffer& commandBuffer) override; [[nodiscard]] inline virtual bool doesCompleteOwnDrawing() const override { // This example wants complete control of the drawing return true; } //[-------------------------------------------------------] //[ Protected virtual Renderer::IResourceListener methods ] //[-------------------------------------------------------] protected: virtual void onLoadingStateChange(const Renderer::IResource& resource) override; //[-------------------------------------------------------] //[ Private methods ] //[-------------------------------------------------------] private: explicit Scene(const Scene&) = delete; Scene& operator=(const Scene&) = delete; void loadIni(); void saveIni(); void destroyIni(); void applyCurrentSettings(Rhi::IRenderTarget& mainRenderTarget); void createCompositorWorkspace(); void createDebugGui(Rhi::IRenderTarget& mainRenderTarget); void trySetCustomMaterialResource(); //[-------------------------------------------------------] //[ Private definitions ] //[-------------------------------------------------------] private: enum class Msaa { NONE, TWO, FOUR, EIGHT }; enum class Compositor { DEBUG, FORWARD, DEFERRED, VR }; enum class ShadowQuality { NONE, LOW, MEDIUM, HIGH, ULTRA, EPIC }; enum class TextureFiltering { POINT, BILINEAR, TRILINEAR, ANISOTROPIC_2, ANISOTROPIC_4, ANISOTROPIC_8, ANISOTROPIC_16 }; //[-------------------------------------------------------] //[ Private data ] //[-------------------------------------------------------] private: DeviceInput::InputManager* mInputManager; Renderer::ImGuiLog* mImGuiLog; Renderer::CompositorWorkspaceInstance* mCompositorWorkspaceInstance; bool mFirstFrame; Renderer::SceneResourceId mSceneResourceId; Renderer::MaterialResourceId mMaterialResourceId; Renderer::MaterialResourceId mCloneMaterialResourceId; bool mCustomMaterialResourceSet; IController* mController; bool mDebugDrawEnabled; // Crazy raw-pointers to point-of-interest scene stuff Renderer::CameraSceneItem* mCameraSceneItem; Renderer::SunlightSceneItem* mSunlightSceneItem; Renderer::SkeletonMeshSceneItem* mSkeletonMeshSceneItem; Renderer::DebugDrawSceneItem* mDebugDrawSceneItem; Renderer::SceneNode* mSceneNode; // States for runtime-editing Renderer::DebugGuiHelper::GizmoSettings mGizmoSettings; // Video bool mFullscreen; bool mCurrentFullscreen; float mResolutionScale; bool mUseVerticalSynchronization; bool mCurrentUseVerticalSynchronization; int mCurrentMsaa; // Graphics Compositor mInstancedCompositor; int mCurrentCompositor; ShadowQuality mShadowQuality; int mCurrentShadowQuality; bool mHighQualityRendering; bool mHighQualityLighting; bool mSoftParticles; int mCurrentTextureFiltering; int mNumberOfTopTextureMipmapsToRemove; int mNumberOfTopMeshLodsToRemove; int mTerrainTessellatedTriangleWidth; // Environment float mCloudsIntensity; float mWindSpeed; float mWetSurfaces[4]; // x=wet level, y=hole/cracks flood level, z=puddle flood level, w=rain intensity // Post processing bool mPerformFxaa; bool mPerformSharpen; bool mPerformChromaticAberration; bool mPerformOldCrtEffect; bool mPerformFilmGrain; bool mPerformSepiaColorCorrection; bool mPerformVignette; float mDepthOfFieldBlurrinessCutoff; // Selected material properties bool mUseEmissiveMap; float mAlbedoColor[3]; // Selected scene item float mRotationSpeed; bool mShowSkeleton; // Scene hot-reloading memory bool mHasCameraTransformBackup; Renderer::Transform mCameraTransformBackup; // Ini settings indices std::vector<char> mIniFileContent; // Defined here to avoid reallocations ini_t* mIni; int mMainWindowPositionSizeIniProperty; int mCameraPositionRotationIniProperty; int mOpenMetricsWindowIniProperty; int mDebugDrawEnabledIniProperty; };
30.996032
105
0.582768
1c1ef4a9304d44a86a668cf200832e0d321d8553
314
sql
SQL
multi-db-query-execution/run_multi_db_query_execution_function.sql
kumarreddyn/postgresql
e0ce7a20dd90d24a0b566493b30aa120bf97c856
[ "MIT" ]
null
null
null
multi-db-query-execution/run_multi_db_query_execution_function.sql
kumarreddyn/postgresql
e0ce7a20dd90d24a0b566493b30aa120bf97c856
[ "MIT" ]
null
null
null
multi-db-query-execution/run_multi_db_query_execution_function.sql
kumarreddyn/postgresql
e0ce7a20dd90d24a0b566493b30aa120bf97c856
[ "MIT" ]
null
null
null
--The query will run the 2 create table scripts on 3 databases (postgres,admin,qc) select multi_db_query_execution_function('postgres', 'postgres', 'postgres;admin;qc', ' create table temp_table1 (temp_table_id BIGINT not null primary key); create table temp_table2 (temp_table_id BIGINT not null primary key) ');
52.333333
86
0.796178
a38c2e5ce7bcee724d51ac8d91df6cad7da1a435
274
java
Java
src/main/java/com/github/startsmercury/noshades/functions/DarkeningBrightnessFunction.java
StartsMercury/NoShades
0fd9a8c96258fa09aa3e92f0538629f796670864
[ "MIT" ]
1
2021-09-08T23:09:06.000Z
2021-09-08T23:09:06.000Z
src/main/java/com/github/startsmercury/noshades/functions/DarkeningBrightnessFunction.java
StartsMercury/NoShades
0fd9a8c96258fa09aa3e92f0538629f796670864
[ "MIT" ]
4
2021-09-14T06:21:34.000Z
2021-10-05T10:53:59.000Z
src/main/java/com/github/startsmercury/noshades/functions/DarkeningBrightnessFunction.java
StartsMercury/noshades
0fd9a8c96258fa09aa3e92f0538629f796670864
[ "MIT" ]
null
null
null
package com.github.startsmercury.noshades.functions; public class DarkeningBrightnessFunction implements BrightnessFunction { @Override public float getBrightness(final float brightness, final float lightness) { return lightness * brightness + brightness; } }
30.444444
77
0.79562
f3fd0949970424b6ec572ede7287cd8b351b8122
1,596
dart
Dart
lib/modules/image/widgets/system_overlay_setter.dart
tommy351/eh-redux
c4bfaf4abee5795da7f649fe2b63597c288c71a1
[ "Apache-2.0" ]
110
2020-06-14T01:38:30.000Z
2022-03-15T09:38:55.000Z
lib/modules/image/widgets/system_overlay_setter.dart
tommy351/ehreader-flutter
c4bfaf4abee5795da7f649fe2b63597c288c71a1
[ "Apache-2.0" ]
23
2020-06-14T16:05:09.000Z
2021-07-31T14:13:20.000Z
lib/modules/image/widgets/system_overlay_setter.dart
tommy351/ehreader-flutter
c4bfaf4abee5795da7f649fe2b63597c288c71a1
[ "Apache-2.0" ]
11
2020-06-26T09:01:16.000Z
2021-11-29T04:47:56.000Z
import 'package:eh_redux/modules/image/store.dart'; import 'package:eh_redux/utils/firebase.dart'; import 'package:flutter/services.dart'; import 'package:flutter/widgets.dart'; import 'package:mobx/mobx.dart'; import 'package:provider/provider.dart'; class SystemOverlaySetter extends StatefulWidget { const SystemOverlaySetter({ Key key, @required this.child, }) : assert(child != null), super(key: key); final Widget child; @override _SystemOverlaySetterState createState() => _SystemOverlaySetterState(); } class _SystemOverlaySetterState extends State<SystemOverlaySetter> { ReactionDisposer _dispose; @override void initState() { super.initState(); final store = Provider.of<ImageStore>(context, listen: false); _hideOverlays(logEvent: false); _dispose = reaction<bool>((_) => store.navVisible, (visible) { if (visible) { _showOverlays(); } else { _hideOverlays(); } }); } @override void dispose() { _dispose(); _showOverlays(logEvent: false); super.dispose(); } @override Widget build(BuildContext context) { return widget.child; } void _hideOverlays({bool logEvent = true}) { SystemChrome.setEnabledSystemUIOverlays([]); if (logEvent) { analytics.logEvent(name: 'hide_view_screen_ui'); } } void _showOverlays({bool logEvent = true}) { SystemChrome.setEnabledSystemUIOverlays([ SystemUiOverlay.top, SystemUiOverlay.bottom, ]); if (logEvent) { analytics.logEvent(name: 'show_view_screen_ui'); } } }
22.166667
73
0.677318
a382e74c2cee4332ec1d54f9e8809a7b8248d8ac
2,690
java
Java
java/gradle.java/src/org/netbeans/modules/gradle/java/api/ProjectActions.java
ebresie/netbeans
ba6c0ad27b75f9cc363e082de8bd1b47891c09c6
[ "Apache-2.0" ]
1
2019-04-30T09:32:22.000Z
2019-04-30T09:32:22.000Z
java/gradle.java/src/org/netbeans/modules/gradle/java/api/ProjectActions.java
ebresie/netbeans
ba6c0ad27b75f9cc363e082de8bd1b47891c09c6
[ "Apache-2.0" ]
5
2020-04-28T13:09:06.000Z
2020-05-01T23:06:48.000Z
java/gradle.java/src/org/netbeans/modules/gradle/java/api/ProjectActions.java
ebresie/netbeans
ba6c0ad27b75f9cc363e082de8bd1b47891c09c6
[ "Apache-2.0" ]
1
2021-08-28T09:48:40.000Z
2021-08-28T09:48:40.000Z
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.netbeans.modules.gradle.java.api; import org.netbeans.api.extexecution.base.ExplicitProcessParameters; /** * Utilities and constants related to Gradle/Java project actions. * @author sdedic * @since 1.12 */ public final class ProjectActions { /** * Replaceable token for JVM arguments project property. Generates project property for NB Tooling Gradle plugin, if the extra JVM arguments are present, otherwise * generates an empty String. The token is interpolated in <code>action-mapping.xml</code> that can be customized by the user. This feature cooperates with * NetBeans Tooling Gradle plugin provided by org.netbeans.gradle module. * <div class="nonnormative"> * The token can be used in <code>action-mapping.xml</code> as followes: * {@codesnippet JavaExecTokenProviderTest.exampleActionMapping} * </div> * The Gradle Java project support consumes {@link ExplicitProcessParameters} from the action's context Lookup, and populates the replaceable token mapping. * <div class="nonnormative"> * The following code injects a specific system property to the VM configuration, and passes "hello Dolly" parameters to the application as main class' parameters. Project * actions can be invoked with custom parameters as in the following example: * {@codesnippet JavaExecTokenProviderTest#testExamplePassJvmAndArguments} * </div> */ public static String TOKEN_JAVAEXEC_JVMARGS = "javaExec.jvmArgs"; /** * Replaceable token for program parameters as a commandline option. Generates --args <i>&lt;parameter-list></i>, if the extra parameters are present, otherwise * generates an empty String. See {@link #TOKEN_JAVAEXEC_JVMARGS} for code examples. * @since 1.9 */ public static String TOKEN_JAVAEXEC_ARGS = "javaExec.args"; private ProjectActions() {} }
48.035714
175
0.744238
0dce8a7c1ccca50659189f60c486001100b1c306
2,791
cs
C#
PaintSample/Tools/Tool.cs
alternetsoft/alternet-ui-examples
bb63752dfa09d70aa439f75458169e4251b2d9da
[ "MIT" ]
4
2021-11-05T13:12:16.000Z
2021-12-22T08:14:02.000Z
PaintSample/Tools/Tool.cs
alternetsoft/alternet-ui-examples
bb63752dfa09d70aa439f75458169e4251b2d9da
[ "MIT" ]
null
null
null
PaintSample/Tools/Tool.cs
alternetsoft/alternet-ui-examples
bb63752dfa09d70aa439f75458169e4251b2d9da
[ "MIT" ]
null
null
null
using Alternet.UI; using System; namespace PaintSample { internal abstract class Tool { private Control? canvas; private Control? optionsControl; protected Tool(Document document, ISelectedColors selectedColors, UndoService undoService) { Document = document; SelectedColors = selectedColors; UndoService = undoService; } public Control? OptionsControl => optionsControl ??= CreateOptionsControl(); public abstract string Name { get; } protected Document Document { get; } protected ISelectedColors SelectedColors { get; } protected UndoService UndoService { get; } protected Control Canvas { get => canvas ?? throw new InvalidOperationException(); private set => canvas = value; } public void Activate(Control canvas) { if (this.canvas != null) throw new InvalidOperationException(); this.canvas = canvas; canvas.MouseDown += Canvas_MouseDown; canvas.MouseUp += Canvas_MouseUp; canvas.MouseMove += Canvas_MouseMove; canvas.MouseCaptureLost += Canvas_MouseCaptureLost; canvas.KeyDown += Canvas_KeyDown; } public void Deactivate() { if (canvas == null) throw new InvalidOperationException(); canvas.MouseDown -= Canvas_MouseDown; canvas.MouseUp -= Canvas_MouseUp; canvas.MouseMove -= Canvas_MouseMove; canvas.MouseCaptureLost -= Canvas_MouseCaptureLost; canvas.KeyDown -= Canvas_KeyDown; canvas = null; } protected virtual Control? CreateOptionsControl() => null; protected virtual void OnKeyDown(KeyEventArgs e) { } protected virtual void OnMouseCaptureLost() { } protected virtual void OnMouseMove(MouseEventArgs e) { } protected virtual void OnMouseUp(MouseButtonEventArgs e) { } protected virtual void OnMouseDown(MouseButtonEventArgs e) { } private void Canvas_KeyDown(object sender, KeyEventArgs e) { OnKeyDown(e); } private void Canvas_MouseCaptureLost(object? sender, EventArgs e) { OnMouseCaptureLost(); } private void Canvas_MouseMove(object sender, MouseEventArgs e) { OnMouseMove(e); } private void Canvas_MouseUp(object sender, MouseButtonEventArgs e) { OnMouseUp(e); } private void Canvas_MouseDown(object sender, MouseButtonEventArgs e) { OnMouseDown(e); } } }
26.580952
123
0.590828
c6e60b0ef37a415c9652bd72fb7d581a064ad1a0
21
py
Python
blendcollection/blendcollection/__init__.py
train-your-deblender/cutout-evaluation
79009552d1c9072696034fa31f71273975f35749
[ "BSD-3-Clause" ]
null
null
null
blendcollection/blendcollection/__init__.py
train-your-deblender/cutout-evaluation
79009552d1c9072696034fa31f71273975f35749
[ "BSD-3-Clause" ]
null
null
null
blendcollection/blendcollection/__init__.py
train-your-deblender/cutout-evaluation
79009552d1c9072696034fa31f71273975f35749
[ "BSD-3-Clause" ]
null
null
null
from .blends import *
21
21
0.761905
e238914475619ece3e1fdd31d09e367fe888205c
1,265
py
Python
examples/basics.py
johnaparker/numpipe
ad466de15913cee9140d48e2f0eebcd9d98dc735
[ "MIT" ]
3
2021-03-08T11:17:50.000Z
2022-01-17T11:50:44.000Z
examples/basics.py
johnaparker/numpipe
ad466de15913cee9140d48e2f0eebcd9d98dc735
[ "MIT" ]
4
2020-05-12T17:47:06.000Z
2021-03-25T13:43:27.000Z
examples/basics.py
johnaparker/numpipe
ad466de15913cee9140d48e2f0eebcd9d98dc735
[ "MIT" ]
null
null
null
from numpipe import scheduler, once import numpy as np import matplotlib.pyplot as plt ### Setup job = scheduler() ### Fast, shared code goes here x = np.linspace(0,1,10) ### Slow, sim-only code goes here and relevant data is written to file @job.cache def sim1(): """compute the square of x""" y = x**2 return {'y': y} @job.cache def sim2(): """compute the cube of x""" z = x**3 return {'z': z} @job.cache def sim3(): """construct a time-series""" for i in range(5): z = x*i + 1 yield {'time_series': z, 'time': i} yield once(xavg=np.average(x)) @job.cache def sim4(param): """sim depends on parameter""" x = np.array([1,2,3]) return {'y': param*x} @job.cache def sim5(): pass job.add(sim4, 'A', param=2) job.add(sim4, 'A', param=3) job.add(sim4, 'A', param=4) job.add(sim4, 'B', param=4) @job.plots def vis(): """visualize the data""" cache = job.load(sim1) plt.plot(x, cache.y) cache = job.load(sim2) plt.plot(x, cache.z) for name, cache in job.load(sim4): print(f'{name} instance has y = {cache.y} with param = {cache.args.param}') # with job.load(sim4, defer=True) as cache: plt.show() ### execute if __name__ == '__main__': job.run()
19.765625
83
0.592885
21bf256749f23afc328d7c18a0cc459eb38118c2
1,488
js
JavaScript
js/molview.js
tovganesh/mol-auto-view.js
db59fa47d108879a99b032022e0d0266f8065414
[ "MIT" ]
null
null
null
js/molview.js
tovganesh/mol-auto-view.js
db59fa47d108879a99b032022e0d0266f8065414
[ "MIT" ]
null
null
null
js/molview.js
tovganesh/mol-auto-view.js
db59fa47d108879a99b032022e0d0266f8065414
[ "MIT" ]
null
null
null
//inject angular file upload directives and service. angular.module('molview', []).config(function ($sceProvider) { $sceProvider.enabled(false); }) .controller('MolViewAppCtrl', function ($scope, $http) { $scope.molecule = ""; $scope.moleculeList = [ ]; $scope.addToMoleculeList = function () { if ($scope.molecule.trim() == "") return; $scope.moleculeList.push( { molecule: $scope.molecule, molFile: jsmeApplet.molFile(), molImage: btoa(jsmeApplet.getMolecularAreaGraphicsString()) } ); $scope.molecule = ""; $scope.moleculeName = ""; jsmeApplet.reset(); }; $scope.fetchMolecule = function () { var responsePromise = $http.get("http://cactus.nci.nih.gov/chemical/structure/" + $scope.molecule + "/sdf", {}); responsePromise.success(function (dataFromServer, status, headers, config) { jsmeApplet.reset(); jsmeApplet.readMolFile(dataFromServer); jsmeApplet.showInfo("Structure for: [" + $scope.molecule + "]") }); responsePromise.error(function (data, status, headers, config) { jsmeApplet.reset(); jsmeApplet.showInfo("Could not find structure for: [" + $scope.molecule + "]") }); } }); var jsmeApplet = null; function jsmeOnLoad() { if (jsmeApplet == null) { jsmeApplet = new JSApplet.JSME("JME", "350px", "330px"); } if (jsmeApplet != null) { jsmeApplet.showInfo(""); } }
28.075472
118
0.606855
f455047aa4029e4dcf449ce18eb40c466545f027
3,195
ts
TypeScript
src/main.ts
maasglobal/io-ts-from-json-schema
35597e354dd23709ff8431e40ab45ff76e2a2f44
[ "MIT" ]
21
2020-05-16T17:41:49.000Z
2021-10-29T23:59:21.000Z
src/main.ts
kiurchv/io-ts-from-json-schema
f95cd92c059a9f33c8a81bc25a518d5ffc1fefe0
[ "MIT" ]
8
2020-06-25T12:00:24.000Z
2021-08-23T11:45:28.000Z
src/main.ts
kiurchv/io-ts-from-json-schema
f95cd92c059a9f33c8a81bc25a518d5ffc1fefe0
[ "MIT" ]
6
2020-05-15T15:13:46.000Z
2021-09-06T17:33:05.000Z
#!/usr/bin/env node /* eslint-disable @typescript-eslint/explicit-module-boundary-types */ import * as crypto from 'crypto'; import * as fs from 'fs'; import { glob } from 'glob'; import * as path from 'path'; import * as stream from 'stream'; import * as yargs from 'yargs'; import { Args, iotsfjs } from './iotsfjs'; export const parser = (args: Array<string>) => { const { argv } = yargs(args) .option('inputFile', { type: 'string', demandOption: true }) .option('outputDir', { type: 'string', demandOption: true }) .option('strict', { type: 'boolean', default: false }) .option('maskNull', { type: 'boolean', default: false }) .option('emit', { type: 'boolean', default: true }) .option('base', { type: 'string', default: '' }) .option('import', { type: 'string', array: true, default: [] }) .option('importHashAlgorithm', { type: 'string', default: 'sha256', choices: crypto.getHashes(), hidden: true, }) .option('qed', { type: 'string', default: '.', hidden: true, }) .option('importHashLength', { type: 'number', default: 0, }) .help(); return argv; }; export const emit = (outputFile: string, lines: Generator<string, void, undefined>) => { function createParentDir(file: string) { const parentDir = path.dirname(file); if (fs.existsSync(parentDir)) { return; } createParentDir(parentDir); fs.mkdirSync(parentDir); } createParentDir(outputFile); const fd = fs.openSync(outputFile, 'w'); fs.writeFileSync(fd, ''); // eslint-disable-next-line fp/no-loops for (const line of lines) { fs.appendFileSync(fd, `${line}\n`); } fs.closeSync(fd); }; type Streams = { stderr: stream.Writable; stdout: stream.Writable; }; export const processFile = ( argv: ReturnType<typeof parser>, { stderr, stdout }: Streams, ) => { const inputSchema = JSON.parse(fs.readFileSync(path.resolve(argv.inputFile), 'utf-8')); const [documentURI] = ( inputSchema.$id ?? 'file://'.concat(path.resolve(argv.inputFile)) ).split('#'); if (documentURI.startsWith(argv.base) === false) { stderr.write(`Document URI ${documentURI} is outside of output base.\n`); } const args: Args = { ...argv, documentURI, }; const relativeP = documentURI.slice(argv.base.length); const outputFile = path.join(argv.outputDir, relativeP.split('.json').join('.ts')); const outputData = iotsfjs(inputSchema, args, stderr); if (argv.emit) { emit(outputFile, outputData); } stdout.write(argv.qed); }; type Process = Streams & { args: Array<string>; }; export function main({ args, stderr, stdout }: Process) { const { inputFile: inputGlob, ...commonArgs } = parser(args); const schemaFiles = glob.sync(inputGlob); stdout.write(`Converting ${schemaFiles.length} schema files from ${inputGlob}.\n`); schemaFiles.sort().forEach((inputFile) => { try { processFile({ ...commonArgs, inputFile }, { stderr, stdout }); } catch (e) { stderr.write(`iotsfjs crash while processing ${path.resolve(inputFile)}${'\n'}`); // eslint-disable-next-line fp/no-throw throw e; } }); }
27.543103
89
0.628169
75c2b187a7814712d9a55db91d537a090485eed7
944
css
CSS
src/pages/contact.css
mkilgus5750/personal-portfolio
c254282c8eea99e57964ffee33235de88a48b2f7
[ "MIT" ]
null
null
null
src/pages/contact.css
mkilgus5750/personal-portfolio
c254282c8eea99e57964ffee33235de88a48b2f7
[ "MIT" ]
null
null
null
src/pages/contact.css
mkilgus5750/personal-portfolio
c254282c8eea99e57964ffee33235de88a48b2f7
[ "MIT" ]
null
null
null
#name, #email, #message { border-radius: 10px; height: 30px; border: 1px solid rgb(138, 138, 138); width: 100%; margin-bottom: 10px; } #name:focus, #email:focus, #message:focus { border-color: lightblue; outline: none; box-shadow: 0 5px 10px rgba(226, 226, 226, 0.19), 0 3px 3px rgba(139, 139, 139, 0.23); } #message { height: 80px; } .send{ color: white; background-color: rgb(41, 14, 92); border: 3px solid white; font-weight: bold; padding: 1rem; } .Contact { width: 100%; margin: 0 auto; background-image: linear-gradient(to right, rgb(178, 111, 233), rgb(143, 205, 241), rgb(255, 255, 255)); background-repeat: no-repeat; background-size: cover; height: 100%; max-width: 1440px; } form { box-shadow: 0 10px 20px rgba(0,0,0,0.19), 0 6px 6px rgba(0,0,0,0.23); background-color: rgb(255, 255, 255); padding: 5%; margin: 100px; }
21.454545
109
0.601695
98162c84ef6a1b3622d56b94b1257d51f791adef
8,943
py
Python
odl-pipeline/lib/utils/processutils.py
rski/sdnvpn-mirror
6bb2eae86a0935443d8e65df0780c3df994a669b
[ "Apache-2.0" ]
null
null
null
odl-pipeline/lib/utils/processutils.py
rski/sdnvpn-mirror
6bb2eae86a0935443d8e65df0780c3df994a669b
[ "Apache-2.0" ]
null
null
null
odl-pipeline/lib/utils/processutils.py
rski/sdnvpn-mirror
6bb2eae86a0935443d8e65df0780c3df994a669b
[ "Apache-2.0" ]
null
null
null
# # Copyright (c) 2017 All rights reserved # This program and the accompanying materials # are made available under the terms of the Apache License, Version 2.0 # which accompanies this distribution, and is available at # # http://www.apache.org/licenses/LICENSE-2.0 # # import utils_log as log import os import six import re import signal import subprocess from time import sleep from threading import Thread try: from Queue import Queue except ImportError: from queue import Queue # python 3.x LOG = log.LOG LOG_LEVEL = log.LOG_LEVEL def _subprocess_setup(): # Python installs a SIGPIPE handler by default. This is usually not what # non-Python subprocesses expect. signal.signal(signal.SIGPIPE, signal.SIG_DFL) # NOTE(flaper87): The following globals are used by `mask_password` _SANITIZE_KEYS = ['adminPass', 'admin_pass', 'password', 'admin_password'] # NOTE(ldbragst): Let's build a list of regex objects using the list of # _SANITIZE_KEYS we already have. This way, we only have to add the new key # to the list of _SANITIZE_KEYS and we can generate regular expressions # for XML and JSON automatically. _SANITIZE_PATTERNS_2 = [] _SANITIZE_PATTERNS_1 = [] def mask_password(message, secret="***"): """Replace password with 'secret' in message. :param message: The string which includes security information. :param secret: value with which to replace passwords. :returns: The unicode value of message with the password fields masked. For example: >>> mask_password("'adminPass' : 'aaaaa'") "'adminPass' : '***'" >>> mask_password("'admin_pass' : 'aaaaa'") "'admin_pass' : '***'" >>> mask_password('"password" : "aaaaa"') '"password" : "***"' >>> mask_password("'original_password' : 'aaaaa'") "'original_password' : '***'" >>> mask_password("u'original_password' : u'aaaaa'") "u'original_password' : u'***'" """ try: message = six.text_type(message) except UnicodeDecodeError: # NOTE(jecarey): Temporary fix to handle cases where message is a # byte string. A better solution will be provided in Kilo. pass # NOTE(ldbragst): Check to see if anything in message contains any key # specified in _SANITIZE_KEYS, if not then just return the message since # we don't have to mask any passwords. if not any(key in message for key in _SANITIZE_KEYS): return message substitute = r'\g<1>' + secret + r'\g<2>' for pattern in _SANITIZE_PATTERNS_2: message = re.sub(pattern, substitute, message) substitute = r'\g<1>' + secret for pattern in _SANITIZE_PATTERNS_1: message = re.sub(pattern, substitute, message) return message class ProcessExecutionError(Exception): def __init__(self, stdout=None, stderr=None, exit_code=None, cmd=None, description=None): self.exit_code = exit_code self.stderr = stderr self.stdout = stdout self.cmd = cmd self.description = description if description is None: description = "Unexpected error while running command." if exit_code is None: exit_code = '-' message = ("%s\nCommand: %s\nExit code: %s\nStdout: %r\nStderr: %r" % (description, cmd, exit_code, stdout, stderr)) super(ProcessExecutionError, self).__init__(message) def enqueue_output(out, queue): for line in iter(out.readline, b''): queue.put(line) queue.put("##Finished##") out.close() def execute(cmd, **kwargs): """Helper method to shell out and execute a command through subprocess. Allows optional retry. :param cmd: Passed to subprocess.Popen. :type cmd: list - will be converted if needed :param process_input: Send to opened process. :type proces_input: string :param check_exit_code: Single bool, int, or list of allowed exit codes. Defaults to [0]. Raise :class:`ProcessExecutionError` unless program exits with one of these code. :type check_exit_code: boolean, int, or [int] :param delay_on_retry: True | False. Defaults to True. If set to True, wait a short amount of time before retrying. :type delay_on_retry: boolean :param attempts: How many times to retry cmd. :type attempts: int :param run_as_root: True | False. Defaults to False. If set to True, or as_root the command is prefixed by the command specified in the root_helper kwarg. execute this command. Defaults to false. :param shell: whether or not there should be a shell used to :type shell: boolean :param loglevel: log level for execute commands. :type loglevel: int. (Should be logging.DEBUG or logging.INFO) :param non_blocking Execute in background. :type non_blockig: boolean :returns: (stdout, (stderr, returncode)) from process execution :raises: :class:`UnknownArgumentError` on receiving unknown arguments :raises: :class:`ProcessExecutionError` """ process_input = kwargs.pop('process_input', None) check_exit_code = kwargs.pop('check_exit_code', [0]) ignore_exit_code = False attempts = kwargs.pop('attempts', 1) run_as_root = kwargs.pop('run_as_root', False) or kwargs.pop('as_root', False) shell = kwargs.pop('shell', False) loglevel = kwargs.pop('loglevel', LOG_LEVEL) non_blocking = kwargs.pop('non_blocking', False) if not isinstance(cmd, list): cmd = cmd.split(' ') if run_as_root: cmd = ['sudo'] + cmd if shell: cmd = ' '.join(cmd) if isinstance(check_exit_code, bool): ignore_exit_code = not check_exit_code check_exit_code = [0] elif isinstance(check_exit_code, int): check_exit_code = [check_exit_code] if kwargs: raise Exception(('Got unknown keyword args ' 'to utils.execute: %r') % kwargs) while attempts > 0: attempts -= 1 try: LOG.log(loglevel, ('Running cmd (subprocess): %s'), cmd) _PIPE = subprocess.PIPE # pylint: disable=E1101 if os.name == 'nt': preexec_fn = None close_fds = False else: preexec_fn = _subprocess_setup close_fds = True obj = subprocess.Popen(cmd, stdin=_PIPE, stdout=_PIPE, stderr=_PIPE, close_fds=close_fds, preexec_fn=preexec_fn, shell=shell) result = None if process_input is not None: result = obj.communicate(process_input) else: if non_blocking: queue = Queue() thread = Thread(target=enqueue_output, args=(obj.stdout, queue)) thread.deamon = True thread.start() # If you want to read this output later: # try: # from Queue import Queue, Empty # except ImportError: # from queue import Queue, Empty # python 3.x # try: line = q.get_nowait() # or q.get(timeout=.1) # except Empty: # print('no output yet') # else: # got line # ... do something with line return queue result = obj.communicate() obj.stdin.close() # pylint: disable=E1101 _returncode = obj.returncode # pylint: disable=E1101 LOG.log(loglevel, ('Result was %s') % _returncode) if not ignore_exit_code and _returncode not in check_exit_code: (stdout, stderr) = result sanitized_stdout = mask_password(stdout) sanitized_stderr = mask_password(stderr) raise ProcessExecutionError( exit_code=_returncode, stdout=sanitized_stdout, stderr=sanitized_stderr, cmd=(' '.join(cmd)) if isinstance(cmd, list) else cmd) (stdout, stderr) = result return stdout, (stderr, _returncode) except ProcessExecutionError: raise finally: sleep(0)
38.055319
76
0.576317
90e5e9ab93eca42d5f207e4849f7449fdd9da685
5,563
asm
Assembly
Transynther/x86/_processed/NONE/_zr_/i9-9900K_12_0xa0.log_141_98.asm
ljhsiun2/medusa
67d769b8a2fb42c538f10287abaf0e6dbb463f0c
[ "MIT" ]
9
2020-08-13T19:41:58.000Z
2022-03-30T12:22:51.000Z
Transynther/x86/_processed/NONE/_zr_/i9-9900K_12_0xa0.log_141_98.asm
ljhsiun2/medusa
67d769b8a2fb42c538f10287abaf0e6dbb463f0c
[ "MIT" ]
1
2021-04-29T06:29:35.000Z
2021-05-13T21:02:30.000Z
Transynther/x86/_processed/NONE/_zr_/i9-9900K_12_0xa0.log_141_98.asm
ljhsiun2/medusa
67d769b8a2fb42c538f10287abaf0e6dbb463f0c
[ "MIT" ]
3
2020-07-14T17:07:07.000Z
2022-03-21T01:12:22.000Z
.global s_prepare_buffers s_prepare_buffers: push %r12 push %r15 push %r8 push %rax push %rbp push %rcx push %rdi push %rsi lea addresses_D_ht+0x25c3, %r15 clflush (%r15) nop nop nop nop xor %rax, %rax movb $0x61, (%r15) nop nop nop dec %r8 lea addresses_WT_ht+0x4553, %rsi lea addresses_A_ht+0x19c33, %rdi inc %r12 mov $35, %rcx rep movsb nop nop nop nop and $23945, %rcx lea addresses_UC_ht+0x5553, %rsi cmp %r12, %r12 mov (%rsi), %r8d nop nop nop nop nop inc %r15 lea addresses_UC_ht+0x11553, %rbp nop nop xor %r15, %r15 vmovups (%rbp), %ymm0 vextracti128 $1, %ymm0, %xmm0 vpextrq $1, %xmm0, %r8 nop nop nop nop cmp $17115, %rax lea addresses_A_ht+0x8d3, %rsi lea addresses_A_ht+0x16783, %rdi nop nop nop inc %rax mov $20, %rcx rep movsw nop nop nop dec %r12 lea addresses_D_ht+0x5153, %rsi lea addresses_A_ht+0x3313, %rdi clflush (%rsi) nop nop add %r15, %r15 mov $22, %rcx rep movsw xor $64201, %rdi lea addresses_A_ht+0x3097, %rsi lea addresses_normal_ht+0x12153, %rdi clflush (%rsi) nop sub $50418, %r12 mov $98, %rcx rep movsb xor $34561, %rsi lea addresses_D_ht+0x1db53, %rax xor %r15, %r15 movl $0x61626364, (%rax) nop nop nop nop add %r15, %r15 lea addresses_WT_ht+0x8780, %rsi lea addresses_WC_ht+0x1a693, %rdi clflush (%rsi) nop nop nop nop sub %r8, %r8 mov $121, %rcx rep movsl nop nop nop add $1002, %rax lea addresses_WC_ht+0x7953, %rsi lea addresses_WC_ht+0x1b067, %rdi clflush (%rsi) nop add %r12, %r12 mov $87, %rcx rep movsb nop nop xor %r15, %r15 pop %rsi pop %rdi pop %rcx pop %rbp pop %rax pop %r8 pop %r15 pop %r12 ret .global s_faulty_load s_faulty_load: push %r10 push %r15 push %r8 push %rbx push %rcx push %rdi push %rdx // Store lea addresses_WC+0x1ce53, %r10 nop nop nop cmp $24414, %rbx mov $0x5152535455565758, %rdx movq %rdx, %xmm5 vmovups %ymm5, (%r10) xor $30118, %rcx // Store lea addresses_A+0x8253, %rdi nop nop nop nop nop and $21053, %r10 mov $0x5152535455565758, %r8 movq %r8, (%rdi) nop sub $45866, %rbx // Store lea addresses_D+0x11073, %rdx nop xor $54363, %r15 movb $0x51, (%rdx) nop nop nop nop xor %rbx, %rbx // Store mov $0x943, %rdi nop cmp %r10, %r10 movw $0x5152, (%rdi) nop nop nop nop cmp $8488, %rbx // Store lea addresses_UC+0xf553, %r8 nop and %rdx, %rdx mov $0x5152535455565758, %rcx movq %rcx, %xmm5 vmovups %ymm5, (%r8) nop nop nop nop nop cmp $1537, %rbx // Store mov $0xc17, %rcx clflush (%rcx) dec %r10 mov $0x5152535455565758, %r15 movq %r15, %xmm5 movups %xmm5, (%rcx) nop sub $6298, %rcx // Faulty Load lea addresses_A+0x9d53, %rcx nop nop nop nop sub $17274, %r15 mov (%rcx), %r10w lea oracles, %r8 and $0xff, %r10 shlq $12, %r10 mov (%r8,%r10,1), %r10 pop %rdx pop %rdi pop %rcx pop %rbx pop %r8 pop %r15 pop %r10 ret /* <gen_faulty_load> [REF] {'src': {'NT': False, 'same': True, 'congruent': 0, 'type': 'addresses_A', 'AVXalign': False, 'size': 4}, 'OP': 'LOAD'} {'OP': 'STOR', 'dst': {'NT': False, 'same': False, 'congruent': 5, 'type': 'addresses_WC', 'AVXalign': False, 'size': 32}} {'OP': 'STOR', 'dst': {'NT': False, 'same': False, 'congruent': 7, 'type': 'addresses_A', 'AVXalign': False, 'size': 8}} {'OP': 'STOR', 'dst': {'NT': False, 'same': False, 'congruent': 3, 'type': 'addresses_D', 'AVXalign': False, 'size': 1}} {'OP': 'STOR', 'dst': {'NT': False, 'same': False, 'congruent': 2, 'type': 'addresses_P', 'AVXalign': False, 'size': 2}} {'OP': 'STOR', 'dst': {'NT': False, 'same': False, 'congruent': 11, 'type': 'addresses_UC', 'AVXalign': False, 'size': 32}} {'OP': 'STOR', 'dst': {'NT': False, 'same': False, 'congruent': 1, 'type': 'addresses_P', 'AVXalign': False, 'size': 16}} [Faulty Load] {'src': {'NT': False, 'same': True, 'congruent': 0, 'type': 'addresses_A', 'AVXalign': False, 'size': 2}, 'OP': 'LOAD'} <gen_prepare_buffer> {'OP': 'STOR', 'dst': {'NT': False, 'same': False, 'congruent': 4, 'type': 'addresses_D_ht', 'AVXalign': False, 'size': 1}} {'src': {'same': False, 'congruent': 11, 'type': 'addresses_WT_ht'}, 'OP': 'REPM', 'dst': {'same': True, 'congruent': 4, 'type': 'addresses_A_ht'}} {'src': {'NT': False, 'same': False, 'congruent': 11, 'type': 'addresses_UC_ht', 'AVXalign': False, 'size': 4}, 'OP': 'LOAD'} {'src': {'NT': False, 'same': False, 'congruent': 10, 'type': 'addresses_UC_ht', 'AVXalign': False, 'size': 32}, 'OP': 'LOAD'} {'src': {'same': False, 'congruent': 7, 'type': 'addresses_A_ht'}, 'OP': 'REPM', 'dst': {'same': False, 'congruent': 3, 'type': 'addresses_A_ht'}} {'src': {'same': True, 'congruent': 9, 'type': 'addresses_D_ht'}, 'OP': 'REPM', 'dst': {'same': False, 'congruent': 6, 'type': 'addresses_A_ht'}} {'src': {'same': False, 'congruent': 1, 'type': 'addresses_A_ht'}, 'OP': 'REPM', 'dst': {'same': False, 'congruent': 10, 'type': 'addresses_normal_ht'}} {'OP': 'STOR', 'dst': {'NT': False, 'same': False, 'congruent': 9, 'type': 'addresses_D_ht', 'AVXalign': False, 'size': 4}} {'src': {'same': False, 'congruent': 0, 'type': 'addresses_WT_ht'}, 'OP': 'REPM', 'dst': {'same': False, 'congruent': 6, 'type': 'addresses_WC_ht'}} {'src': {'same': False, 'congruent': 8, 'type': 'addresses_WC_ht'}, 'OP': 'REPM', 'dst': {'same': False, 'congruent': 2, 'type': 'addresses_WC_ht'}} {'00': 141} 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 */
22.075397
422
0.647672
b0b628f835e24c6dec57b66bf8d5f70da3564481
2,344
py
Python
Scripts/Preprocessing/spectrogram.py
CotaCalin/AutomatedMusicTranscription
02ea0d2f48f614f8a929f687a112e8b309599d63
[ "MIT" ]
1
2019-12-18T16:06:49.000Z
2019-12-18T16:06:49.000Z
Scripts/Preprocessing/spectrogram.py
CotaCalin/AutomatedMusicTranscription
02ea0d2f48f614f8a929f687a112e8b309599d63
[ "MIT" ]
null
null
null
Scripts/Preprocessing/spectrogram.py
CotaCalin/AutomatedMusicTranscription
02ea0d2f48f614f8a929f687a112e8b309599d63
[ "MIT" ]
null
null
null
import matplotlib.pyplot as plt from scipy import signal from scipy.io import wavfile import os import sys import wave import pylab #from spectrogram2 import plotstft # Generate and plot a constant-Q power spectrum import matplotlib.pyplot as plt import numpy as np import librosa import librosa.display class SpectrogramBuilder(): def __init__(self, WavPath, DestinationPath): self.__wavPath = WavPath self.__wav_files = self.get_wavs() self.__destinationPath = DestinationPath def get_wavs(self): ret = [] for wav_file in os.listdir(self.__wavPath): if wav_file.endswith(".wav"): ret.append(os.path.join(self.__wavPath, wav_file)) return ret def build_spectrograms(self): for wavfile in self.__wav_files: self.graph_spectrogram(wavfile) pass def __build_spectrogram(self, filePath): sample_rate, samples = wavfile.read(filePath) frequencies, times, spectrogram = signal.spectrogram(samples, sample_rate) #print(spectrogram) color_tuple = spectrogram.transpose((1,0,2)).reshape((spectrogram.shape[0]*spectrogram.shape[1],spectrogram.shape[2]))/255.0 plt.pcolormesh(times, frequencies, color_tuple) plt.imshow(spectrogram) plt.ylabel('Frequency [Hz]') plt.xlabel('Time [sec]') plt.show() def graph_spectrogram(self, wav_file): pass # Q Transform y, sr = librosa.load(wav_file) C = np.abs(librosa.cqt(y, sr=sr)) librosa.display.specshow(librosa.amplitude_to_db(C, ref=np.max), sr=sr)#, x_axis='time', y_axis='cqt_hz') #plt.colorbar(format='%+2.0f dB') #plt.title('spectrogram of %r' % wav_file) #plt.tight_layout() fileName = 'spectrogram_{0}.png'.format(wav_file.split("\\")[-1]) plt.savefig(os.path.join(self.__destinationPath, fileName), bbox_inches="tight") plt.close('all') def get_wav_info(self, wav_file): wav = wave.open(wav_file, 'r') frames = wav.readframes(-1) sound_info = pylab.fromstring(frames, 'int16') frame_rate = wav.getframerate() wav.close() return sound_info, frame_rate
33.485714
133
0.62628
4588829cd976e87e2e778e0ee5bd16d32f80092a
448
py
Python
task_0.py
MutterPedro/chicago_bikeshare_project
22797c0c4d7f42dd613486d14eb53ee53d8f4724
[ "MIT" ]
null
null
null
task_0.py
MutterPedro/chicago_bikeshare_project
22797c0c4d7f42dd613486d14eb53ee53d8f4724
[ "MIT" ]
null
null
null
task_0.py
MutterPedro/chicago_bikeshare_project
22797c0c4d7f42dd613486d14eb53ee53d8f4724
[ "MIT" ]
null
null
null
def run(data_list): # Vamos verificar quantas linhas nós temos print("Número de linhas:") print(len(data_list)) # Imprimindo a primeira linha de data_list para verificar se funcionou. print("Linha 0: ") print(data_list[0]) # É o cabeçalho dos dados, para que possamos identificar as colunas. # Imprimindo a segunda linha de data_list, ela deveria conter alguns dados print("Linha 1: ") print(data_list[1])
32
78
0.696429
cd40cfe0cbd32e02c751e52163db3691227d8030
4,408
cs
C#
Wirehome.Core/Python/PythonScriptHost.cs
vmanthena/Wirehome.Core
a10a85f2b297cda03195d9f46f14732f055fe610
[ "Apache-2.0" ]
1
2019-10-10T03:48:15.000Z
2019-10-10T03:48:15.000Z
Wirehome.Core/Python/PythonScriptHost.cs
huangweiboy/Wirehome.Core
1a6c9d1d7a4acb044c27d0ddc5282e54a97bfabc
[ "Apache-2.0" ]
4
2022-02-13T20:07:53.000Z
2022-03-02T09:54:27.000Z
Wirehome.Core/Python/PythonScriptHost.cs
huangweiboy/Wirehome.Core
1a6c9d1d7a4acb044c27d0ddc5282e54a97bfabc
[ "Apache-2.0" ]
null
null
null
using System; using System.Collections.Generic; using System.Linq; using IronPython.Runtime; using Microsoft.Scripting; using Microsoft.Scripting.Hosting; using Wirehome.Core.Python.Exceptions; namespace Wirehome.Core.Python { public class PythonScriptHost { private readonly ScriptScope _scriptScope; private readonly IDictionary<string, object> _wirehomeWrapper; public PythonScriptHost(ScriptScope scriptScope, IDictionary<string, object> wirehomeWrapper) { _scriptScope = scriptScope ?? throw new ArgumentNullException(nameof(scriptScope)); _wirehomeWrapper = wirehomeWrapper ?? throw new ArgumentNullException(nameof(wirehomeWrapper)); } public void AddToWirehomeWrapper(string name, object value) { if (name == null) throw new ArgumentNullException(nameof(name)); _wirehomeWrapper.Add(name, value); } public void Compile(string scriptCode) { if (scriptCode == null) throw new ArgumentNullException(nameof(scriptCode)); lock (_scriptScope) { try { var source = _scriptScope.Engine.CreateScriptSourceFromString(scriptCode, SourceCodeKind.File); var compiledCode = source.Compile(); compiledCode.Execute(_scriptScope); } catch (Exception exception) { var details = _scriptScope.Engine.GetService<ExceptionOperations>().FormatException(exception); var message = "Error while initializing Python script host." + Environment.NewLine + details; throw new PythonProxyException(message, exception); } } } public void SetVariable(string name, object value) { if (name == null) throw new ArgumentNullException(nameof(name)); var pythonValue = PythonConvert.ToPython(value); lock (_scriptScope) { _scriptScope.SetVariable(name, pythonValue); } } public object GetVariable(string name) { if (name == null) throw new ArgumentNullException(nameof(name)); object pythonValue; lock (_scriptScope) { pythonValue = _scriptScope.GetVariable(name); } return PythonConvert.FromPython(pythonValue); } public bool FunctionExists(string name) { if (name == null) throw new ArgumentNullException(nameof(name)); lock (_scriptScope) { if (!_scriptScope.Engine.Operations.TryGetMember(_scriptScope, name, out var member)) { return false; } if (!(member is PythonFunction)) { return false; } } return true; } public object InvokeFunction(string name, params object[] parameters) { if (name == null) throw new ArgumentNullException(nameof(name)); object result; lock (_scriptScope) { if (!_scriptScope.Engine.Operations.TryGetMember(_scriptScope, name, out var member)) { throw new PythonProxyException($"Function '{name}' not found."); } if (!(member is PythonFunction function)) { throw new PythonProxyException($"Member '{name}' is no Python function."); } try { var pythonParameters = parameters.Select(PythonConvert.ToPython).ToArray(); result = _scriptScope.Engine.Operations.Invoke(function, pythonParameters); } catch (Exception exception) { var details = _scriptScope.Engine.GetService<ExceptionOperations>().FormatException(exception); var message = "Error while invoking function. " + Environment.NewLine + details; throw new PythonProxyException(message, exception); } } return PythonConvert.FromPython(result); } } }
33.907692
115
0.558757
63a6ad7c74149a5c2440e83d60c801dd4045c5f3
2,350
rs
Rust
sarpine/src/messages/srp_header.rs
Devolutions/sarpine-rs
a76da7a4203091c4b3a5a85cdae7673dd93920ad
[ "Apache-2.0", "MIT" ]
1
2020-12-30T10:54:11.000Z
2020-12-30T10:54:11.000Z
sarpine/src/messages/srp_header.rs
Devolutions/sarpine-rs
a76da7a4203091c4b3a5a85cdae7673dd93920ad
[ "Apache-2.0", "MIT" ]
null
null
null
sarpine/src/messages/srp_header.rs
Devolutions/sarpine-rs
a76da7a4203091c4b3a5a85cdae7673dd93920ad
[ "Apache-2.0", "MIT" ]
null
null
null
use std::io::{Read, Write, Error}; use byteorder::{WriteBytesExt, LittleEndian, ReadBytesExt, BigEndian}; use messages::{ wayknow_const::*, SRP_FLAG_MAC, SrpErr, Message, SRP_SIGNATURE }; pub struct SrpHeader { signature: u32, msg_type: u8, version: u8, flags: u16 } impl SrpHeader { pub fn new(msg_type: u8, add_mac_flag: bool, token_size: usize) -> Self { let mut flags = 0; if add_mac_flag { flags |= SRP_FLAG_MAC; } SrpHeader { signature: 0x00505253, msg_type, version: 6, //FIXME version flags, } } pub fn signature(&self) -> u32 { self.signature } pub fn has_mac(&self) -> bool { self.flags & SRP_FLAG_MAC != 0 } //FIXME SRP_FLAG_MAC pub fn validate_flags(&self, mac_expected: bool) -> Result<(), SrpErr> { if !self.has_mac() && mac_expected { return Err(SrpErr::Proto(format!( "SRD_FLAG_MAC must be set in message type {}", self.msg_type ))); } else if self.has_mac() && !mac_expected { return Err(SrpErr::Proto(format!( "SRD_FLAG_MAC must not be set in message type {}", self.msg_type ))); } Ok(()) } pub fn msg_type(&self) -> u8 { self.msg_type } } impl Message for SrpHeader { fn read_from<R: Read>(reader: &mut R) -> Result<Self, SrpErr> where Self: Sized, { let signature = reader.read_u32::<LittleEndian>()?; //println!("signature: {:02x?} vs {:02x?}", signature, SRP_SIGNATURE); if signature != SRP_SIGNATURE { return Err(SrpErr::InvalidSignature); } let msg_type = reader.read_u8()?; let version = reader.read_u8()?; let flags = reader.read_u16::<LittleEndian>()?; Ok(SrpHeader { signature, msg_type, version, flags, }) } fn write_to<W: Write>(&self, writer: &mut W) -> Result<(), SrpErr> { writer.write_u32::<LittleEndian>(self.signature)?; writer.write_u8(self.msg_type)?; writer.write_u8(self.version)?; writer.write_u16::<LittleEndian>(self.flags)?; Ok(()) } }
25.268817
78
0.534894
bb669d17bbf7071e3e832e9e57c745ee2172218d
663
cs
C#
src/MovieHub.MediaPlayerElement/Util/MediaPlayerUtil.cs
eadwinCode/MoviePlayer
1a273556a965a70a59909b436e06fbb9d324df37
[ "MIT" ]
5
2018-08-30T08:37:12.000Z
2022-03-13T22:38:39.000Z
src/MovieHub.MediaPlayerElement/Util/MediaPlayerUtil.cs
eadwintoochos/MoviePlayer
1a273556a965a70a59909b436e06fbb9d324df37
[ "MIT" ]
null
null
null
src/MovieHub.MediaPlayerElement/Util/MediaPlayerUtil.cs
eadwintoochos/MoviePlayer
1a273556a965a70a59909b436e06fbb9d324df37
[ "MIT" ]
3
2021-05-05T23:08:34.000Z
2022-03-13T22:38:58.000Z
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows.Threading; namespace MovieHub.MediaPlayerElement.Util { internal class MediaPlayerUtil { public static void ExecuteTimerAction(Action callback, long millisecond) { DispatcherTimer dispatcherTimer = new DispatcherTimer { Interval = TimeSpan.FromMilliseconds(millisecond) }; dispatcherTimer.Tick += (s, e) => { dispatcherTimer.Stop(); callback.Invoke(); }; dispatcherTimer.Start(); } } }
25.5
80
0.591252
05200fa92e3f10a9aa768dc2a561cf6711b6c155
8,942
css
CSS
src/index.css
martin-banks/virus-transmission-simulations
9a995a3e4c8ebd27a8338fed178fd62f233c4298
[ "MIT" ]
1
2021-05-02T09:12:48.000Z
2021-05-02T09:12:48.000Z
src/index.css
martin-banks/virus-transmission-simulations
9a995a3e4c8ebd27a8338fed178fd62f233c4298
[ "MIT" ]
null
null
null
src/index.css
martin-banks/virus-transmission-simulations
9a995a3e4c8ebd27a8338fed178fd62f233c4298
[ "MIT" ]
null
null
null
@import "./styles/global.css"; html, body { /* margin: 0; */ /* padding: 0; */ /* display: flex; */ justify-content: center; align-items: flex-start; /* width: 100vw; */ min-height: 100vh; font-family: sans-serif; } body { /* padding: 0; */ /* margin: 0; */ /* overflow: hidden; */ /* margin-bottom: 30px; */ position: relative; min-height: 100vh; } * { box-sizing: border-box; } #app { display: flex; flex-direction: column; min-height: 100vh; } header { position: absolute; display: flex; top: 0; left: 0; width: 100%; box-sizing: border-box; margin: 0; padding: 0; padding-top: 2rem; padding-left: 6rem; /* background: rgba(0,0,0, 0.5); */ justify-content: flex-start; } @media (prefers-color-scheme: dark) { header { /* background: rgba(0,0,0, 0.5) */ } } @media (prefers-color-scheme: light) { header { /* background: rgba(255,255,255, 0.5) */ } } .headerElement { /* outline: solid 1px lime; */ width: 100px; display: flex; align-items: center; justify-content: center; } .headerEndElement { outline: solid 1p pink; width: 100px; display: flex; align-items: center; justify-content: center; } .forkMe { position: relative; display: block; width: 40px; margin: 0 auto; overflow: hidden; } .logo__wrapper { position: relative; width: 100%; max-width: 150px; } .logo__box { position: absolute; top: 15%; left: 50%; width: 100%; height: 33%; border: solid 1px rgba(125, 125, 125, 0.4); transform: translateX(-50%); } .logo__corner { position: absolute; border: none; border-radius: 0px; border-color: darkred !important; box-sizing: content-box; width: 0.3rem; height: 0.3rem; padding: 0.3rem; transform: translate(-50%, -50%); opacity: 1; } .logo__corner.tl { left: 0; top: 0; border-top: solid 2px; border-right: none; border-bottom: none; border-left: solid 2px; } .logo__corner.tr { left: 100%; top: 0; border-top: solid 2px; border-right: solid 2px; border-bottom: none; border-left: none; } .logo__corner.br { left: 100%; top: 100%; border-top: none; border-right: solid 2px; border-bottom: solid 2px; border-left: none; } .logo__corner.bl { left: 0; top: 100%; border-top: none; border-right: none; border-bottom: solid 2px; border-left: solid 2px; } .logo__imageWrapper { position: relative; width: 110%; height: auto; left: 50%; transform: translateX(-30%); background-size: contain; background-repeat: no-repeat; } .logo__imageWrapper img { opacity: 0; width: 200px; max-width: 500px; } @media (prefers-color-scheme: dark) { .logo__imageWrapper { background-image: url(./files/images/signature.1.0.0-white.png); } } @media (prefers-color-scheme: light) { .logo__imageWrapper { background-image: url(./files/images/signature.1.0.0-black.png); } } main { padding: 3rem; /* margin-bottom: 3rem; */ } section { margin-bottom: 6rem; padding-bottom: 6rem; } section.title { display: block; max-width: 1000px; margin-left: auto; margin-right: auto; margin-bottom: 4rem; padding-top: 20rem; padding-bottom: 4rem; } section.title h1 { text-align: center; } section.title p { text-align: center; } section.mainStage { /* display: grid; */ display: flex; flex-wrap: wrap; max-width: 2000px; margin: 0 auto; /* min-height: 100vh; */ /* grid-template-columns: 300px 1fr; */ /* grid-template-columns: minmax(100px, 400px) 1fr minmax(100px, 400px); */ /* gap: 3rem; */ } .left { /* outline: solid 1px pink; */ /* padding-top: 10rem; */ /* padding: 10rem 2rem; */ /* overflow: auto; */ /* height: 100vh; */ /* background: rgba(255,255,255, 0.5) */ flex: 1 1 0; min-width: 250px; width: 20%; max-width: 350px; padding-right: 3rem; margin-bottom: 3rem; } .middle { display: block; flex: 1 1 0; min-width: 250px; width: 50%; margin-bottom: 3rem; } .right { /* border: solid 1px lime; */ /* height: 100vh; */ position: relative; flex: 1 1 0; min-width: 250px; width: 20%; max-width: 350px; padding-left: 3rem; margin-bottom: 3rem; } /* @media (prefers-color-scheme: dark) { .left { background: rgba(0,0,0, 0.5); } } @media (prefers-color-scheme: light) { .left { background: rgba(255,255,255, 0.5); } } */ #particleSystem { /* position: fixed; */ top: 0; right: 0; width: 100%; /* height: 100%; */ /* margin: 0 auto; */ margin: 0; padding: 0; background: black; border: solid 1px; overflow: hidden; border-radius: 1rem; } @media (prefers-color-scheme: dark) { #particleSystem { background: black; border-color: rgba(255,255,255, 0.15); box-shadow: 0 2px 24px -12px rgba(0,0,0, 1); } } @media (prefers-color-scheme: light) { #particleSystem { background: white; border-color: rgba(0,0,0, 0.1); box-shadow: 0 2px 24px -12px rgba(0,0,0, 0.4); } } canvas { /* position: absolute; */ display: block; top: 0; left: 0; /* width: 100%; */ } label, pre, code, button { font-size: 16px } h2 { font-size: 32px; } pre { padding-bottom: 20px; border-bottom: solid 1px lightgrey } pre, code { color: lightslategray; } /* #app { display: flex; position: relative; width: 100vw; max-width: 1200px; margin: 0 auto; flex-wrap: wrap; } */ /* Main display container */ .simulation { position: relative; display: block; width: 100%; flex: 1 1 0; } .chartContainer { position: relative; width: 100%; max-width: 800px; outline: solid 1px white; margin-bottom: 3rem; } .chartContainer hr.expectedDead { display: none; position: absolute; top: 0; left: 0; width: 100%; height: 0; border: none; border-top: solid 1px black; text-align: right; padding: 0; margin: 0; overflow: visible; } .chartContainer hr:after { content: "Expected max dead"; } .chart { width: 100%; height: 100px; display: flex; margin-bottom: 10px; background: lightblue; } .chart__bar { position: relative; /* display: flex; */ flex-direction: column; height: 100px; flex: 1 1 0; } .chart__bar--section { position: relative; flex: 1 1 0; min-height: 0px; width: 100%; margin: 0; } .chart__bar--section.healthy { background: none; } .chart__bar--section.infected { background: darkred; } .chart__bar--section.cured { background: seagreen; } .chart__bar--section.dead { background: black; } .controls { display: block; position: relative; flex: 1 1 0; max-width: 600px; margin-bottom: 30px; } .setting { border-bottom: solid 1px; padding-bottom: 20px; margin-bottom: 10px; border-color: rgba(150,150,150, 0.3) } .setting:last-of-type { border: none } input { width: 100%; } button { padding: 8px 20px; display: block; width: 100%; border-radius: 4px; } @media (prefers-color-scheme: dark) { button { border: solid 1px lightgrey; background: white; color: black; } } @media (prefers-color-scheme: light) { button { border: solid 1px black; background: black; color: white; } } /* button#start {} */ button#stop { display: none; background: darkred; color: white; border-color: tomato } section.signoff { display: block; text-align: center; max-width: 1400px; margin: 0 auto; margin-bottom: 4rem; padding: 3rem 0; } .stat__container { display: flex; } .stat__item { position: relative; flex: 1 1 0; } .stat__value { position: relative; width: 60%; margin: 0 auto; margin-bottom: 1rem; } .stat__item .circle { box-sizing: content-box; position: relative; width: 100%; height: 0; left: 50%; transform: translateX(-50%); padding-bottom: 100%; border-radius: 300px; border: solid 0.5rem rgba(255, 255, 255, 0.5); } .stat__item--normal .circle { background: steelblue; } .stat__item--infected .circle { background: tomato; } .stat__item--cured .circle { background: seagreen; } .stat__item--dead .circle { background: black; } .stat__item p { position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); text-align: center; margin: 0; font-family: dharma-gothic-e, sans-serif; font-size: 4rem; font-weight: 600; color: white; } h6.stat__label { text-align: center } footer { /* position: absolute; */ display: block; bottom: 0; width: 100%; padding: 2rem 0 2rem 0; margin-top: 3rem; text-align: center; border-top: solid 1px; align-self: flex-end; justify-self: flex-end; margin-top: auto } footer p { display: block; width: 100%; text-align: center; padding: 0; margin: 0; font-size: 1.5rem; } @media (prefers-color-scheme: dark) { footer { background: rgba(0,0,0, 1); border-color: rgba(255,255,255, 0.2) } } @media (prefers-color-scheme: light) { footer { background: rgba(255,255,255, 1); border-color: rgba(0,0,0, 0.2) } }
16.347349
77
0.628942
c68df5698b31113a103234e8e663273965653d6c
1,130
css
CSS
src/App.css
L4ll1p0p/2019NASA_Hachathon
2ef10aeb5f6e7464aaf8896d17724bcb766cc1d7
[ "MIT" ]
3
2019-10-20T05:02:04.000Z
2019-12-25T18:59:28.000Z
src/App.css
L4ll1p0p/2019NASA_Hachathon
2ef10aeb5f6e7464aaf8896d17724bcb766cc1d7
[ "MIT" ]
9
2021-03-02T00:43:40.000Z
2022-03-08T23:03:15.000Z
src/App.css
L4ll1p0p/2019NASA_Hachathon
2ef10aeb5f6e7464aaf8896d17724bcb766cc1d7
[ "MIT" ]
null
null
null
body { /*Account for the navbar*/ padding-top: 3.5rem; } .globe { width: 100%; height: calc(100vh - 3.5rem); background-color: black; } .overlayTools { position: absolute; top: 3.5rem; max-height: calc(100vh - 3.5rem); } .overlayCards { position: absolute; top: 3.5rem; left: 100px; max-height: calc(100vh - 3.5rem); } .card { background:rgba(255,255,255,0.7) !important; } .card-body { overflow-y: scroll; max-height: calc(100vh - 8rem); } .ha{ display:flex; flex-direction: column; justify-content:space-between; margin-left:1vw; /* position: absolute; */ width: 6vw; height:23vh; background:white; /* padding-bottom: 20%; */ } .hi{ margin-right:1vw; /* position: absolute; */ width: 100%; height:6vh; } .xixi{ width:100%; height:15%; font-size:30%; background:white; } .hihi{ margin-right:1vw; /* position: absolute; */ width: 70%; height:6vh; margin-left:12%; } .hihi2{ margin-right:1vw; /* position: absolute; */ width: 58%; height:5vh; margin-left:18%; }
16.142857
48
0.579646
b56790367c89ab158a33880a44184967ad63fcb1
2,607
rb
Ruby
spec/commands/create_student_teams_spec.rb
harmsk/teachers_pet
625d10ec0b3af58106e38f97c388ee7628d90ccd
[ "MIT" ]
102
2015-01-08T03:58:47.000Z
2021-05-13T23:29:06.000Z
spec/commands/create_student_teams_spec.rb
harmsk/teachers_pet
625d10ec0b3af58106e38f97c388ee7628d90ccd
[ "MIT" ]
34
2015-01-14T21:32:07.000Z
2016-12-11T17:35:02.000Z
spec/commands/create_student_teams_spec.rb
harmsk/teachers_pet
625d10ec0b3af58106e38f97c388ee7628d90ccd
[ "MIT" ]
44
2015-01-23T13:00:12.000Z
2021-09-04T00:55:34.000Z
require 'spec_helper' describe 'create_student_teams' do include CommandHelpers def stub_owners_only stub_get_json('https://testteacher:[email protected]/orgs/testorg/teams?per_page=100', [ { id: 101, name: 'Owners' } ]) end it "creates one team per student" do request_stubs = [] request_stubs << stub_owners_only student_usernames.each_with_index do |student, i| # Creates team request_stubs << stub_request(:post, 'https://testteacher:[email protected]/orgs/testorg/teams'). with(body: { name: student, permission: 'push' }.to_json).to_return(body: { id: i, name: student }.to_json) # Checks for existing team members # TODO No need to retrieve members for a new team request_stubs << stub_get_json("https://testteacher:[email protected]/teams/#{i}/members?per_page=100", []) # Add student to their team request_stubs << stub_request(:put, "https://testteacher:[email protected]/teams/#{i}/memberships/#{student}") end teachers_pet(:create_student_teams, organization: 'testorg', students: students_list_fixture_path, instructors: empty_list_fixture_path, username: 'testteacher', password: 'abc123' ) request_stubs.each do |request_stub| expect(request_stub).to have_been_requested.once end end it "creates teams for groups of students" do request_stubs = [] stub_owners_only # Creates team request_stubs << stub_request(:post, 'https://testteacher:[email protected]/orgs/testorg/teams'). with(body: { name: 'studentteam1', permission: 'push' }.to_json).to_return(body: { id: 1, name: 'studentteam1' }.to_json) # Checks for existing team members # TODO No need to retrieve members for a new team request_stubs << stub_get_json('https://testteacher:[email protected]/teams/1/members?per_page=100', []) %w(teststudent1 teststudent2).each do |student| # Add student to their team request_stubs << stub_request(:put, "https://testteacher:[email protected]/teams/1/memberships/#{student}") end teachers_pet(:create_student_teams, organization: 'testorg', students: fixture_path('teams'), instructors: empty_list_fixture_path, username: 'testteacher', password: 'abc123' ) request_stubs.each do |request_stub| expect(request_stub).to have_been_requested.once end end end
28.648352
120
0.655926
06eba3b3b7500771eb098d8bad9750c30b5066a1
2,581
py
Python
dehaze.py
rabauke/haze_remval
472010c0c2178725c070a050431a1b3f2315008f
[ "BSD-3-Clause" ]
6
2017-02-12T07:55:31.000Z
2019-05-20T08:37:28.000Z
dehaze.py
rabauke/haze_remval
472010c0c2178725c070a050431a1b3f2315008f
[ "BSD-3-Clause" ]
1
2017-02-12T18:16:54.000Z
2017-02-12T18:16:54.000Z
dehaze.py
rabauke/haze_remval
472010c0c2178725c070a050431a1b3f2315008f
[ "BSD-3-Clause" ]
3
2017-02-12T07:57:54.000Z
2019-12-15T02:55:59.000Z
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # # automatic haze removal as described in # # Kaiming He, Jian Sun, and Xiaoou Tang, »Single Image Haze Removal # Using Dark Channel Prior« in IEEE Transactions on Pattern Analysis # and Machine Intelligence, vol. 33, no. 12, 2341--2353 (2010) # DOI: 10.1109/TPAMI.2010.168 # # He K., Sun J., Tang X. (2010) Guided Image Filtering. In: Daniilidis K., # Maragos P., Paragios N. (eds) Computer Vision – ECCV 2010. ECCV 2010. # Lecture Notes in Computer Science, vol 6311. Springer, Berlin, Heidelberg import os import numpy as np from pylab import * from skimage import data, io, exposure, img_as_float # # first compile dehaze module with # python3 setup.py build_ext --inplace import dehaze image='images/forrest.jpg' image='images/city.jpg' image='images/landscape.jpg' # parameters # window size (positive integer) for determing the dark channel and the transition map w=4 # window size (positive integer) for guided filter w2=3*w # strength of the dahazing effect 0 <= stength <= 1 (is 0.95 in the original paper) strength=0.99 # gamma correction, algorithm should work in linear RGB space gamma=2.2 close('all') I=img_as_float(io.imread(image)) io.imshow(I) title('original image') xticks([]) yticks([]) tight_layout() show(False) I=I**gamma dark=dehaze.dark_channel(I, w) figure() imshow(dark, cmap='Greys') title('dark channel') xticks([]) yticks([]) tight_layout() show(False) haze_pixel=dark>=percentile(dark, 98) In=sum(I, axis=2)/3 # figure() # io.imshow(haze_pixel*In) # title('most hazy regions') # xticks([]) # yticks([]) # tight_layout() # show(False) #k0, k1=np.unravel_index(argmax(haze_pixel*In), In.shape) #A0=I[k0, k1, :] bright_pixel=In>=percentile(In[haze_pixel], 98) A0=mean(I[logical_and(haze_pixel, bright_pixel), :], axis=0) t=dehaze.transition_map(I, A0, w, strength) figure() imshow(t, cmap='Greys') title('transition map') xticks([]) yticks([]) tight_layout() show(False) t=dehaze.box_min(t, w) t=dehaze.guidedfilter(I, t, w2, 0.001) t[t<0.025]=0.025 figure() imshow(t, cmap='Greys') title('refined transition map') xticks([]) yticks([]) tight_layout() show(False) J=I/t[:, :, np.newaxis] - A0[np.newaxis, np.newaxis, :]/t[:, :, np.newaxis] + A0 # J=empty_like(I) # J[:, :, 0]=(I[:, :, 0]/t-A0[0]/t+A0[0]) # J[:, :, 1]=(I[:, :, 1]/t-A0[1]/t+A0[1]) # J[:, :, 2]=(I[:, :, 2]/t-A0[2]/t+A0[2]) J[J<0]=0 J[J>1]=1 J=J**(1/gamma) figure() imshow(J) title('haze-free image') xticks([]) yticks([]) tight_layout() show(False) name, ext=os.path.splitext(image) io.imsave(name+'_haze_free'+ext, J)
22.059829
86
0.686556
c0ba494bb53a5b473c5fd7a53582893d13e36e62
25,183
swift
Swift
plus-yizhidian-ios-tsauth-master/Thinksns Plus/FutureController/Common/TSPicturePreviewVC/View/TSPicturePreviewItem.swift
yunxin-dianbo-ios/dianboOC
e6f566d1599efb832bdaaebc622ce808aa85f9c7
[ "Apache-2.0" ]
null
null
null
plus-yizhidian-ios-tsauth-master/Thinksns Plus/FutureController/Common/TSPicturePreviewVC/View/TSPicturePreviewItem.swift
yunxin-dianbo-ios/dianboOC
e6f566d1599efb832bdaaebc622ce808aa85f9c7
[ "Apache-2.0" ]
null
null
null
plus-yizhidian-ios-tsauth-master/Thinksns Plus/FutureController/Common/TSPicturePreviewVC/View/TSPicturePreviewItem.swift
yunxin-dianbo-ios/dianboOC
e6f566d1599efb832bdaaebc622ce808aa85f9c7
[ "Apache-2.0" ]
1
2020-10-22T06:23:24.000Z
2020-10-22T06:23:24.000Z
// // TSPicturePreviewCell.swift // Thinksns Plus // // Created by GorCat on 17/3/4. // Copyright © 2017年 ZhiYiCX. All rights reserved. // import UIKit import Kingfisher import RealmSwift import AssetsLibrary /// cell 的代理方法 protocol TSPicturePreviewItemDelegate: class { /// 单击了 cell func itemDidSingleTaped(_ item: TSPicturePreviewItem) /// 长按 cell func itemDidLongPressed(_ item: TSPicturePreviewItem) /// 保存图片操作完成 func item(_ item: TSPicturePreviewItem, didSaveImage error: Error?) /// 购买了某张图 func itemFinishPaid(_ item: TSPicturePreviewItem) /// 保存图片 func itemSaveImage(item: TSPicturePreviewItem) } struct ImageIndicator: Indicator { let imageView: UIImageView = UIImageView() func startAnimatingView() { view.isHidden = false imageView.frame = view.bounds // 适配长图 let screenCenterY = UIScreen.main.bounds.height / 2 if viewCenter.y > screenCenterY { imageView.frame = CGRect(x: 0, y: screenCenterY - viewCenter.y, width: view.bounds.width, height: view.bounds.height) } imageView.startAnimating() } func stopAnimatingView() { view.isHidden = true imageView.stopAnimating() } var view: IndicatorView = UIView() init() { view.frame.size = CGSize(width: 40, height: 40) var images: [UIImage] = [] for index in 0...9 { let image = UIImage(named: "default_white0\(index)") if let image = image { images.append(image) } } for index in 0...9 { let image = UIImage(named: "default_white\(index)") if let image = image { images.append(image) } } imageView.animationImages = images imageView.animationDuration = Double(images.count * 4) / 30.0 imageView.animationRepeatCount = 0 imageView.backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.3) imageView.clipsToBounds = true imageView.layer.cornerRadius = 40 * 0.5 view.addSubview(imageView) } } class TSPicturePreviewItem: UIView, UIScrollViewDelegate { weak var superVC: TSPicturePreviewVC? /// 图片数据模型 var imageObject: TSImageObject? /// 滚动视图 private var scrollView = UIScrollView() private var imageContainerView = UIView() var progressButton: TSProgressButton? /// 购买按钮 var buttonForBuyRead: TSColorLumpButton = { let button = TSColorLumpButton.initWith(sizeType: .large) button.setTitle("购买查看", for: .normal) return button }() /// 成为会员按钮 var buttonForVIP: UIButton = { let button = UIButton(type: .custom) return button }() /// 图片视图 var imageView = UIImageView() /// 图片的位置 var imageViewFrame: CGRect { return imageContainerView.frame } /// 保存图片的开关 var canBeSave = false /// 代理 weak var delegate: TSPicturePreviewItemDelegate? /// 占位图 var placeholder: UIImage? /// 重绘大小的配置 internal var resizeProcessor: ResizingImageProcessor { let scale = UIScreen.main.scale let pictureSize = CGSize(width: imageView.frame.width * scale, height: imageView.frame.height * scale) return ResizingImageProcessor(referenceSize: pictureSize, mode: .aspectFill) } // 加载图片的网络请求头 internal let modifier = AnyModifier { request in var r = request if let authorization = TSCurrentUserInfo.share.accountToken?.token { r.setValue("Bearer " + authorization, forHTTPHeaderField: "Authorization") } return r } // MARK: - Lifecycle override init(frame: CGRect) { super.init(frame: frame) self.setUI() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) self.setUI() } // MARK: - Custom user interface private func setUI() { // scrollview scrollView.frame = self.bounds scrollView.bouncesZoom = true scrollView.maximumZoomScale = 2.5 scrollView.isMultipleTouchEnabled = true scrollView.delegate = self scrollView.scrollsToTop = false scrollView.showsHorizontalScrollIndicator = false scrollView.showsVerticalScrollIndicator = false scrollView.autoresizingMask = [.flexibleWidth, .flexibleHeight] scrollView.delaysContentTouches = false scrollView.canCancelContentTouches = true scrollView.alwaysBounceVertical = false if #available(iOS 11.0, *) { scrollView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentBehavior.never } // imageContainer imageContainerView.clipsToBounds = true imageContainerView.backgroundColor = UIColor.white // imageview imageView.clipsToBounds = true // 购买按钮 buttonForBuyRead.frame = CGRect(x: (UIScreen.main.bounds.width - 100) / 2, y: UIScreen.main.bounds.height - 35 - 65, width: 100, height: 35) buttonForBuyRead.addTarget(self, action: #selector(buyButtonTaped(_:)), for: .touchUpInside) buttonForBuyRead.isHidden = true // 成为会员按钮 buttonForVIP.frame = CGRect(x: (UIScreen.main.bounds.width - 190) / 2, y: buttonForBuyRead.frame.maxY + 15, width: 190, height: 17) buttonForVIP.addTarget(self, action: #selector(VIPButtonTaped(_:)), for: .touchUpInside) buttonForVIP.isHidden = true // gesture let singleTap = UITapGestureRecognizer(target: self, action: #selector(singleTap(_:))) let doubleTap = UITapGestureRecognizer(target: self, action: #selector(doubleTap(_:))) doubleTap.numberOfTapsRequired = 2 let longPress = UILongPressGestureRecognizer(target: self, action: #selector(longPress(_:))) longPress.minimumPressDuration = 0.3 longPress.require(toFail: doubleTap) singleTap.require(toFail: doubleTap) addGestureRecognizer(singleTap) addGestureRecognizer(doubleTap) addGestureRecognizer(longPress) addSubview(scrollView) addSubview(buttonForBuyRead) addSubview(buttonForVIP) scrollView.addSubview(imageContainerView) imageContainerView.addSubview(imageView) } // MARK: - Public /// 加载视图 func setInfo(_ object: TSImageObject, smallImage: UIImage?, loadGif: Bool = false) { /// 1.刷新布局 imageContainerView.frame = CGRect(x:0, y:0, width: frame.width, height: imageContainerView.bounds.height) let imageWidth = smallImage?.size.width ?? object.width let imageHeight = smallImage?.size.height ?? object.height if imageHeight / imageWidth > UIScreen.main.bounds.height / UIScreen.main.bounds.width { let height = floor(imageHeight / (imageWidth / UIScreen.main.bounds.width)) var originFrame = imageContainerView.frame originFrame.size.height = height imageContainerView.frame = originFrame } else { var height = imageHeight / imageWidth * frame.width if height < 1 || height.isNaN { height = frame.height } height = floor(height) var originFrame = imageContainerView.frame originFrame.size.height = height imageContainerView.frame = originFrame imageContainerView.center = CGPoint(x:self.imageContainerView.center.x, y:self.bounds.height / 2) } if imageContainerView.frame.height > frame.height && imageContainerView.frame.height - frame.height <= 1 { var originFrame = imageContainerView.frame originFrame.size.height = frame.height imageContainerView.frame = originFrame } scrollView.contentSize = CGSize(width: frame.width, height: max(imageContainerView.frame.height, frame.height)) scrollView.scrollRectToVisible(bounds, animated: false) scrollView.alwaysBounceVertical = imageContainerView.frame.height > frame.height imageView.frame = imageContainerView.bounds // 2.加载图片 imageObject = object canBeSave = false loadImage(placeholder: smallImage, loadGif: loadGif) // 1.判断图片是否需要付费 // 2.1 查看收费(下载收费,在长按后点击了“保存到手机相册”时,进行拦截) if object.type == "read" && object.paid.value == false { // 隐藏查看大图按钮 progressButton?.isHidden = true // 关闭保存图片的操作 canBeSave = false // 显示购买按钮 buttonForBuyRead.isHidden = false // 显示成为会员按钮 buttonForBuyRead.isHidden = false } // 兼容处理 // 如果只有图片,没有TSImageObject而是直接通过Image展示的情况,比如聊天列表查看大图 if object.storageIdentity == 0 { self.canBeSave = true } } /// 保存图片 func saveImage() { DispatchQueue.main.async { // 2. 如果不是下载付费,保存图片 guard let imageObject = self.imageObject else { return } // 1. 判断图片是否为下载付费 if imageObject.type == "download" && imageObject.paid.value == false { self.paidImage(isRead: false, payType: "download") return } // 如果是cacheKey 需要额外从缓存中读取 if imageObject.cacheKey.isEmpty == false { let webpCacheSerializer = WebpCacheSerializer() var tempData: Data = Data() if imageObject.mimeType == "image/jpeg" { if let data = ImageCache.default.retrieveImageInMemoryCache(forKey: imageObject.cacheKey)?.kf.jpegRepresentation(compressionQuality: 1.0) { tempData = data } else if let data = ImageCache.default.retrieveImageInDiskCache(forKey: imageObject.cacheKey)?.kf.jpegRepresentation(compressionQuality: 1.0) { tempData = data } } else if imageObject.mimeType == "image/gif" { if let data = ImageCache.default.retrieveImageInMemoryCache(forKey: imageObject.cacheKey, options: [.cacheSerializer(webpCacheSerializer)])?.kf.gifRepresentation() { tempData = data let library = ALAssetsLibrary() let metadata = ["UTI": kUTTypeGIF as! String] library.writeImageData(toSavedPhotosAlbum: data, metadata: metadata, completionBlock: { (URLString, error) in self.gifImageDidFinishSavingWithError(error: error) }) return } else if let data = ImageCache.default.retrieveImageInDiskCache(forKey: imageObject.cacheKey, options: [.cacheSerializer(webpCacheSerializer)])?.kf.gifRepresentation() { tempData = data } } else if imageObject.mimeType == "image/png" { if let data = ImageCache.default.retrieveImageInMemoryCache(forKey: imageObject.cacheKey, options: [.cacheSerializer(webpCacheSerializer)])?.kf.gifRepresentation() { tempData = data } else if let data = ImageCache.default.retrieveImageInDiskCache(forKey: imageObject.cacheKey, options: [.cacheSerializer(webpCacheSerializer)])?.kf.pngRepresentation() { tempData = data } } let image = UIImage(data: tempData) UIImageWriteToSavedPhotosAlbum(image!, self, #selector(self.image(_:didFinishSavingWithError:contextInfo:)), nil) } else { if imageObject.locCacheKey.isEmpty, let placeholder = self.placeholder { /// 直接保存placeHolder UIImageWriteToSavedPhotosAlbum(placeholder, self, #selector(self.image(_:didFinishSavingWithError:contextInfo:)), nil) return } let webpCacheSerializer = WebpCacheSerializer() let imageCacheKey = imageObject.locCacheKey ImageCache.default.retrieveImage(forKey: imageCacheKey, options: [.cacheSerializer(webpCacheSerializer)], completionHandler: { (image, _) in if imageObject.mimeType == "image/gif" { if let imageData = image?.kf.gifRepresentation() { let library = ALAssetsLibrary() let metadata = ["UTI": kUTTypeGIF as! String] library.writeImageData(toSavedPhotosAlbum: imageData, metadata: metadata, completionBlock: { (URLString, error) in self.gifImageDidFinishSavingWithError(error: error) }) } else { let indicator = TSIndicatorWindowTop(state: .loading, title: "请返回后重试!") indicator.show(timeInterval: TSIndicatorWindowTop.defaultShowTimeInterval) } } else if imageObject.mimeType == "image/jpeg" { UIImageWriteToSavedPhotosAlbum(image!, self, #selector(self.image(_:didFinishSavingWithError:contextInfo:)), nil) } else if imageObject.mimeType == "image/png" { UIImageWriteToSavedPhotosAlbum(image!, self, #selector(self.image(_:didFinishSavingWithError:contextInfo:)), nil) } }) } } } // MARK: - Private /// 加载图片 func loadImage(placeholder: UIImage?, forceToRefresh: Bool = false, loadGif: Bool = false) { self.placeholder = placeholder guard let imageObject = self.imageObject else { return } // 原图链接 var url = imageObject.storageIdentity.imageUrl() if imageObject.storageIdentity == 0 { /// 直接显示的图片,就不要拼接url /// url为空的时候,保存本地直接保存placeHolder的图片(直接传入的图片) url = "" } // 检查是否有原图链接 let have100Pic = ImageCache.default.imageCachedType(forKey: url).cached // 如果没有原图的缓存,就显示查看大图按钮 if !have100Pic && imageObject.storageIdentity > 0 && progressButton == nil { progressButton = TSProgressButton(sourceImageView: imageView, url: URL(string: url)!, superView: self) progressButton?.alpha = 0 } if imageObject.mimeType == "image/gif" { progressButton?.isHidden = true } if imageObject.isLongPic() { progressButton?.isHidden = true } // 拼接 url let originalSize = CGSize(width: imageObject.width, height: imageObject.height) var imageUrl: String if imageObject.paid.value == true { imageUrl = url.smallPicUrl(showingSize: imageView.frame.size, originalSize: originalSize) } else { // 付费图片加载原图 imageUrl = url.smallPicUrl(showingSize: .zero, originalSize: originalSize) } // gif图片加载原图 if imageObject.mimeType == "image/gif" { imageUrl = url.smallPicUrl(showingSize: .zero, originalSize: originalSize) } if imageObject.isLongPic() { imageUrl = url.smallPicUrl(showingSize: .zero, originalSize: originalSize) } /// 如果url是空的,说明当前时直接显示传入的image对象,就不去下载 if url.isEmpty { imageUrl = "" } if (imageObject.locCacheKey.isEmpty && imageObject.cacheKey.isEmpty) || forceToRefresh == true { downloadImage(imageUrl: imageUrl, forceToRefresh: forceToRefresh, loadGif: loadGif) } else { // 如果是cacheKey 需要额外从缓存中读取 if imageObject.cacheKey.isEmpty == false { let webpCacheSerializer = WebpCacheSerializer() var tempData: Data = Data() if imageObject.mimeType == "image/jpeg" { // 如果不是GIF的图片,就压缩一下,原始的二进制流不能直接上传,非iOS/macOS系统打不开 // 但是100%的转换图片会很大 if let data = ImageCache.default.retrieveImageInMemoryCache(forKey: imageObject.cacheKey)?.kf.jpegRepresentation(compressionQuality: 1.0) { tempData = data } else if let data = ImageCache.default.retrieveImageInDiskCache(forKey: imageObject.cacheKey)?.kf.jpegRepresentation(compressionQuality: 1.0) { tempData = data } } else if imageObject.mimeType == "image/gif" { if let data = ImageCache.default.retrieveImageInMemoryCache(forKey: imageObject.cacheKey, options: [.cacheSerializer(webpCacheSerializer)])?.kf.gifRepresentation() { let image = UIImage.sd_tz_animatedGIF(with: data) self.imageView.image = image return } else if let data = ImageCache.default.retrieveImageInDiskCache(forKey: imageObject.cacheKey, options: [.cacheSerializer(webpCacheSerializer)])?.kf.gifRepresentation() { tempData = data } } else if imageObject.mimeType == "image/png" { if let data = ImageCache.default.retrieveImageInMemoryCache(forKey: imageObject.cacheKey, options: [.cacheSerializer(webpCacheSerializer)])?.kf.gifRepresentation() { tempData = data } else if let data = ImageCache.default.retrieveImageInDiskCache(forKey: imageObject.cacheKey, options: [.cacheSerializer(webpCacheSerializer)])?.kf.pngRepresentation() { tempData = data } } let showImage = UIImage(data: tempData) self.imageView.image = showImage } else { let webpCacheSerializer = WebpCacheSerializer() ImageCache.default.retrieveImage(forKey: imageObject.locCacheKey, options: [.cacheSerializer(webpCacheSerializer)], completionHandler: { (image, _) in if imageObject.mimeType == "image/gif" { let imageData = image?.kf.gifRepresentation() let image = UIImage.sd_tz_animatedGIF(with: imageData) self.imageView.image = image } else if imageObject.mimeType == "image/jpeg" { self.imageView.image = image } else if imageObject.mimeType == "image/png" { self.imageView.image = image } }) } } } func downloadImage(imageUrl url: String, forceToRefresh: Bool = false, loadGif: Bool = false) { guard let imageUrl = URL(string: url) else { imageView.image = placeholder return } var options: KingfisherOptionsInfo = [.requestModifier(modifier)] if forceToRefresh { options.append(.forceRefresh) } if !loadGif { options.append(.onlyLoadFirstFrame) imageView.kf.indicatorType = .custom(indicator: ImageIndicator()) } else { imageView.kf.indicatorType = .none } imageView.kf.setImage(with: imageUrl, placeholder: placeholder, options: options, progressBlock: nil) { [weak self] (image, error, type, aUrl) in guard let weakself = self else { return } if let image = image { self?.changePictureFrame(image: image) } weakself.imageObject?.locCacheKey = url weakself.canBeSave = true } } func changePictureFrame(image: UIImage?) { imageContainerView.frame = CGRect(x:0, y:0, width: frame.width, height: imageContainerView.bounds.height) let imageWidth = image!.size.width let imageHeight = image!.size.height if imageHeight / imageWidth > UIScreen.main.bounds.height / UIScreen.main.bounds.width { let height = floor(imageHeight / (imageWidth / UIScreen.main.bounds.width)) var originFrame = imageContainerView.frame originFrame.size.height = height imageContainerView.frame = originFrame } else { var height = imageHeight / imageWidth * frame.width if height < 1 || height.isNaN { height = frame.height } height = floor(height) var originFrame = imageContainerView.frame originFrame.size.height = height imageContainerView.frame = originFrame imageContainerView.center = CGPoint(x:self.imageContainerView.center.x, y:self.bounds.height / 2) } if imageContainerView.frame.height > frame.height && imageContainerView.frame.height - frame.height <= 1 { var originFrame = imageContainerView.frame originFrame.size.height = frame.height imageContainerView.frame = originFrame } scrollView.contentSize = CGSize(width: frame.width, height: max(imageContainerView.frame.height, frame.height)) scrollView.scrollRectToVisible(bounds, animated: false) scrollView.alwaysBounceVertical = imageContainerView.frame.height > frame.height imageView.frame = imageContainerView.bounds } /// 发起图片购买的操作 func paidImage(isRead: Bool, payType: NSString) { guard let imageObject = imageObject else { return } TSPayTaskQueue.showImagePayAlertWith(imageObject: imageObject) { [weak self] (isSuccess, _) in guard let weakSelf = self else { return } guard isSuccess else { weakSelf.superVC?.dismiss() return } if payType == "download" { // 下载付费的类型,付费后直接保存 if weakSelf.canBeSave == true && weakSelf.delegate != nil { if weakSelf.canBeSave { weakSelf.delegate!.itemSaveImage(item: weakSelf) } } } else if payType == "read" { weakSelf.buttonForVIP.isHidden = true weakSelf.buttonForBuyRead.isHidden = true weakSelf.progressButton?.isHidden = false // 清理本地模糊的图片缓存 ImageCache.default.removeImage(forKey: imageObject.cacheKey) // 更新界面 weakSelf.loadImage(placeholder: UIImage.create(with: TSColor.inconspicuous.disabled, size: weakSelf.imageView.frame.size), forceToRefresh: true) } weakSelf.delegate?.itemFinishPaid(weakSelf) } } /// 完成了保存图片 func image(_ image: UIImage, didFinishSavingWithError error: Error?, contextInfo: UnsafeRawPointer) { if let delegate = delegate { delegate.item(self, didSaveImage: error) } } // GIF保存结果 func gifImageDidFinishSavingWithError(error: Error?) { if let delegate = delegate { delegate.item(self, didSaveImage: error) } } // MARK: - Button click /// 单击 cell func singleTap(_ gusture: UITapGestureRecognizer) { if let delegate = delegate { delegate.itemDidSingleTaped(self) } } /// 双击 cell func doubleTap(_ gusture: UITapGestureRecognizer) { if scrollView.zoomScale > 1.0 { // 状态还原 scrollView.setZoomScale(1.0, animated: true) } else { let touchPoint = gusture.location(in: imageView) let newZoomScale = scrollView.maximumZoomScale let xsize = frame.size.width / newZoomScale let ysize = frame.size.height / newZoomScale scrollView.zoom(to: CGRect(x: touchPoint.x - xsize / 2, y: touchPoint.y - ysize / 2, width: xsize, height: ysize), animated: true) } } /// 长按 cell func longPress(_ gusture: UILongPressGestureRecognizer) { if gusture.state == .began { if let delegate = delegate { if canBeSave { delegate.itemDidLongPressed(self) } } } } /// 点击了购买按钮 func buyButtonTaped(_ sender: TSColorLumpButton) { guard let imageObject = self.imageObject else { return } self.paidImage(isRead: true, payType: imageObject.type! as NSString) } /// 点击了成为会员按钮 func VIPButtonTaped(_ sender: UIButton) { // [长期注释] 成为会员 } // MARK: - Delegate // MARK: UIScrollViewDelegate func viewForZooming(in scrollView: UIScrollView) -> UIView? { return self.imageContainerView } func scrollViewDidZoom(_ scrollView: UIScrollView) { let offsetX = (scrollView.frame.width > scrollView.contentSize.width) ? (scrollView.frame.width - scrollView.contentSize.width) * 0.5 : 0.0 let offsetY = (scrollView.frame.height > scrollView.contentSize.height) ? (scrollView.frame.height - scrollView.contentSize.height) * 0.5 : 0.0 imageContainerView.center = CGPoint(x: scrollView.contentSize.width * 0.5 + offsetX, y: scrollView.contentSize.height * 0.5 + offsetY) } }
42.974403
190
0.603304
65423dba278bb088a675de4a2ee628101a3f5f26
1,057
css
CSS
VersionAlpha0.0.1/frontend/templates/css/input.css
GoranBotic/Water_Fern
d4f513315c0cd668b17529cc65271bf455b15adc
[ "MIT" ]
null
null
null
VersionAlpha0.0.1/frontend/templates/css/input.css
GoranBotic/Water_Fern
d4f513315c0cd668b17529cc65271bf455b15adc
[ "MIT" ]
null
null
null
VersionAlpha0.0.1/frontend/templates/css/input.css
GoranBotic/Water_Fern
d4f513315c0cd668b17529cc65271bf455b15adc
[ "MIT" ]
null
null
null
.inputxt { padding: 10px; border:1px solid #ccc; width:250px; } .assign-submit { background-color:#00abe5; border: 1px solid #00abe5; padding:12px; width: 100px; font-size: 17px; border-radius:5px; color:#fff; cursor: pointer; } .assign-submit:hover { border: 1px solid #0085b2; background-color: #0099ce; } .inputxt { padding: 10px; border:1px solid #ccc; width:250px; } .login-submit { background-color:#0099ce; border: 1px solid #0099ce; padding:8px; width: 250px; font-size: 17px; border-radius:5px; color:#fff; cursor: pointer; } .login-submit:hover { border: 1px solid #00abe5; background-color: #00abe5; } .login-inputxt { padding: 10px; border:1px solid #ccc; width:100%; background-color: rgba(255, 255, 255, 0.5); border-radius:2px; } /*.login-submit { background-color: rgba(0,137,185, 0.9); border:1px solid #0099ce; width:100%; border-radius:2px; padding: 10px; }*/
17.048387
47
0.598865
1a8884148e176fea46e77a0ad39d5188f10274f7
499
py
Python
LeetCode/HashTable/594. Longest Harmonious Subsequence.py
thehanemperor/LeetCode
8d120162657a1e29c3e821b51ac4121300fc7a12
[ "MIT" ]
null
null
null
LeetCode/HashTable/594. Longest Harmonious Subsequence.py
thehanemperor/LeetCode
8d120162657a1e29c3e821b51ac4121300fc7a12
[ "MIT" ]
null
null
null
LeetCode/HashTable/594. Longest Harmonious Subsequence.py
thehanemperor/LeetCode
8d120162657a1e29c3e821b51ac4121300fc7a12
[ "MIT" ]
null
null
null
# EASY # count each element in array and store in dict{} # loop through the array check if exist nums[i]+1 in dict{} class Solution: def findLHS(self, nums: List[int]) -> int: n = len(nums) appear = {} for i in range(n): appear[nums[i]] = appear.get(nums[i],0) + 1 result = 0 for k,v in appear.items(): if k+1 in appear: result = max(result,v+appear[k+1]) return result
26.263158
59
0.503006
457dbc05a2e8d6ee6cade52b45a93fc4a5c93b38
2,555
py
Python
smartlingApiSdk/Credentials.py
Smartling/api-sdk-python
85e937c3ad0abcf5022688a476ac2edb34ab33ac
[ "Apache-2.0" ]
8
2015-01-08T21:31:17.000Z
2021-01-07T07:50:31.000Z
smartlingApiSdk/Credentials.py
Smartling/api-sdk-python
85e937c3ad0abcf5022688a476ac2edb34ab33ac
[ "Apache-2.0" ]
8
2015-05-18T21:43:03.000Z
2020-05-19T06:12:17.000Z
smartlingApiSdk/Credentials.py
Smartling/api-sdk-python
85e937c3ad0abcf5022688a476ac2edb34ab33ac
[ "Apache-2.0" ]
14
2015-07-24T08:52:27.000Z
2022-03-05T06:36:45.000Z
#!/usr/bin/python # -*- coding: utf-8 -*- """ Copyright 2012-2021 Smartling, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this work except in compliance with the License. * You may obtain a copy of the License in the LICENSE file, or at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. """ import os class CredentialsNotSet(Exception): noKeyMessage = """ don't forget to set real MY_PROJECT_ID, MY_USER_IDENTIFIER, MY_USER_SECRET, MY_LOCALE in Credentials class or use environment variables: export SL_LOCALE=**-** export SL_USER_IDENTIFIER=****************************** export SL_USER_SECRET=******************************************************* #optional export SL_ACCOUNT_UID=******* #required only to list projects api call export SL_PROJECT_ID=******* #required for api calls `projects` and `project_details` """ def __init__(self, id, env): self.id = id self.env = env def getMessage(self): res = self.noKeyMessage if 'stg' == self.env: res = res.replace('SL_USER_IDENTIFIER=', 'SL_USER_IDENTIFIER_STG=') res = res.replace('SL_USER_SECRET=', 'SL_USER_SECRET_STG=') return res def __str__(self): return "Missing:" + self.id + self.getMessage() class Credentials(): MY_PROJECT_ID = "CHANGE_ME" MY_ACCOUNT_UID = "CHANGE_ME" MY_USER_IDENTIFIER = "CHANGE_ME" MY_USER_SECRET = "CHANGE_ME" MY_LOCALE ="CHANGE_ME" CREDS = ("PROJECT_ID", "ACCOUNT_UID", "USER_IDENTIFIER", "USER_SECRET", "LOCALE") OPTIONAL_CREDS = ("ACCOUNT_UID") def __init__(self, env='prod'): for id in self.CREDS: cred = "MY_"+id suffix = '' if env == 'stg' and id.startswith("USER_"): suffix = '_STG' value = getattr(self, cred + suffix, "CHANGE_ME") if "CHANGE_ME" == value: value = os.environ.get('SL_' + id + suffix, getattr(self, cred)) if "CHANGE_ME" == value and id not in self.OPTIONAL_CREDS: raise CredentialsNotSet('SL_' + id + suffix, env) setattr(self, cred, value)
34.066667
90
0.615656
1eb1d2d155823e1851c12bbc0f2be38e9ccbac68
2,672
ps1
PowerShell
scripts/windows-setup.ps1
kyranet/drakhtar
1d8d1ad84ae0fb953e813a761c17ff306ca5aac8
[ "MIT" ]
7
2019-05-05T14:58:12.000Z
2019-11-11T21:36:57.000Z
scripts/windows-setup.ps1
kyranet/drakhtar
1d8d1ad84ae0fb953e813a761c17ff306ca5aac8
[ "MIT" ]
17
2019-02-14T21:12:28.000Z
2019-05-13T23:28:26.000Z
scripts/windows-setup.ps1
kyranet/Drakhtar
1d8d1ad84ae0fb953e813a761c17ff306ca5aac8
[ "MIT" ]
1
2021-04-27T21:06:53.000Z
2021-04-27T21:06:53.000Z
# Set up the submodule so Drakhtar i18n and Telemetry is properly included in the project: git submodule init git submodule update # Define the hooks patch as $root/hooks over $root/.git/hooks so we can run our own hooks: git config core.hooksPath hooks $local:DependencyFolder = Join-Path -Path $(Split-Path $PSScriptRoot) -ChildPath "deps" $local:BaseDomain = "https://www.libsdl.org/" function Step-Download { [CmdletBinding()] param ( [string] $Output, [string] $UriPath ) process { $private:OutputDirectory = Join-Path -Path $DependencyFolder -ChildPath $Output if (Test-Path -Path $OutputDirectory) { Write-Host "Skipping [" -ForegroundColor Green -NoNewline Write-Host $Output -ForegroundColor Blue -NoNewline Write-Host "] as it already exists in [" -ForegroundColor Green -NoNewline Write-Host $OutputDirectory -ForegroundColor Blue -NoNewline Write-Host "]." -ForegroundColor Green } else { Write-Host "Downloading [" -ForegroundColor DarkGray -NoNewline Write-Host $Output -ForegroundColor Blue -NoNewline Write-Host "] into [" -ForegroundColor DarkGray -NoNewline Write-Host $OutputDirectory -ForegroundColor Blue -NoNewline Write-Host "]." -ForegroundColor DarkGray $private:DownloadUri = $BaseDomain + $UriPath $private:File = New-TemporaryFile Invoke-WebRequest -Uri $DownloadUri -OutFile $File $File | Expand-Archive -DestinationPath $DependencyFolder -Force $File | Remove-Item } } } function Remove-SafeItem([string] $Path) { if (Test-Path -Path $Path) { Write-Host "Deleting [" -ForegroundColor DarkGray -NoNewline Write-Host $Path -ForegroundColor Blue -NoNewline Write-Host "]." -ForegroundColor DarkGray Remove-Item $Path } } $private:Sdl2 = "SDL2-2.0.14" $private:Sdl2Ttf = "SDL2_ttf-2.0.15" $private:Sdl2Image = "SDL2_image-2.0.5" $private:Sdl2Mixer = "SDL2_mixer-2.0.4" # Download the dependencies: Step-Download -Output $Sdl2 -UriPath "release/SDL2-devel-2.0.14-VC.zip" Step-Download -Output $Sdl2Ttf -UriPath "projects/SDL_ttf/release/SDL2_ttf-devel-2.0.15-VC.zip" Step-Download -Output $Sdl2Image -UriPath "projects/SDL_image/release/SDL2_image-devel-2.0.5-VC.zip" Step-Download -Output $Sdl2Mixer -UriPath "projects/SDL_mixer/release/SDL2_mixer-devel-2.0.4-VC.zip" # Remove SDL2 TTF's zlib1.dll, as they are already included in SDL2 Image: Remove-SafeItem $(Join-Path -Path $DependencyFolder -ChildPath "$Sdl2Ttf/lib/x64/zlib1.dll") Remove-SafeItem $(Join-Path -Path $DependencyFolder -ChildPath "$Sdl2Ttf/lib/x86/zlib1.dll")
40.484848
100
0.708832
4cd6b45403ff81d6f14b0c573081af4df6b871ae
416
py
Python
app/util/shell/shell_client_factory.py
rsennewald/ClusterRunner
6cb351982462798d4e11ac1a80f8fef048503758
[ "Apache-2.0" ]
164
2015-01-06T05:54:46.000Z
2021-11-13T12:28:28.000Z
app/util/shell/shell_client_factory.py
rsennewald/ClusterRunner
6cb351982462798d4e11ac1a80f8fef048503758
[ "Apache-2.0" ]
393
2015-01-05T17:26:07.000Z
2022-03-21T10:42:06.000Z
app/util/shell/shell_client_factory.py
rsennewald/ClusterRunner
6cb351982462798d4e11ac1a80f8fef048503758
[ "Apache-2.0" ]
44
2015-01-23T22:06:03.000Z
2022-03-01T09:33:36.000Z
from app.util.network import Network from app.util.shell.local_shell_client import LocalShellClient from app.util.shell.remote_shell_client import RemoteShellClient class ShellClientFactory(object): @classmethod def create(cls, host, user): if Network.are_hosts_same(host, 'localhost'): return LocalShellClient(host, user) else: return RemoteShellClient(host, user)
32
64
0.735577
7b47d0eaf37647b925b31dde4ed4d55640aaa98e
316
rake
Ruby
lib/tasks/cache.rake
collectionspace/cspace-converter
5938729303aa42df7926116ab628cc0f1079c54f
[ "Ruby", "MIT" ]
1
2020-02-28T00:59:39.000Z
2020-02-28T00:59:39.000Z
lib/tasks/cache.rake
collectionspace/cspace-converter
5938729303aa42df7926116ab628cc0f1079c54f
[ "Ruby", "MIT" ]
169
2019-11-04T21:50:14.000Z
2021-09-27T20:36:05.000Z
lib/tasks/cache.rake
collectionspace/cspace-converter
5938729303aa42df7926116ab628cc0f1079c54f
[ "Ruby", "MIT" ]
4
2020-03-20T00:07:29.000Z
2020-06-12T17:42:09.000Z
namespace :cache do # bundle exec rake cache:download task :download => :environment do |t, args| cache_service = CacheService.new cache_service.download end # bundle exec rake cache:refresh task :refresh => :environment do cache_service = CacheService.new cache_service.refresh end end
22.571429
45
0.724684
07f28b139bd9acee7830703f8f63232919c37091
809
css
CSS
style.css
mpkahn/portfolio2
b9c5f42a0eebe0abb51e24a0bbe950a5b6d05479
[ "Unlicense" ]
null
null
null
style.css
mpkahn/portfolio2
b9c5f42a0eebe0abb51e24a0bbe950a5b6d05479
[ "Unlicense" ]
null
null
null
style.css
mpkahn/portfolio2
b9c5f42a0eebe0abb51e24a0bbe950a5b6d05479
[ "Unlicense" ]
null
null
null
.navbar-brand { font-weight: bold; } body { background-image: url(webb-dark.png); margin: 0; } h2 { font-family: Cambria, Cochin, Georgia, Times, 'Times New Roman', serif; color: rgb(29, 116, 116); padding: 1%; border-bottom: 1px solid rgb(189, 188, 188); font-weight: bold; } .mainCard { background-color: rgb(255, 255, 255); padding-bottom: 3%; margin-bottom: 10%; } .footer { position: fixed; left: 0; bottom: 0; width: 100%; height: 5%; background-color: #4b4b4b; color: rgb(255, 255, 255); text-align: center; } .card { text-align-last: center; margin:auto; } p { color: black; } .infoCard { padding-top: 5%; } .col-md-6 { padding-top:15px; } .vibeCard { margin-top: 15px; }
13.483333
75
0.563659
a914333e4f1d0380b7cbda4d6697a67b7f26f69d
610
css
CSS
docs/public/styles/extras.css
barelyhuman/rlayouts-new
c7e617219a3794bba7ce849eda41981f20c1e865
[ "MIT" ]
1
2021-02-19T01:31:49.000Z
2021-02-19T01:31:49.000Z
docs/public/styles/extras.css
barelyhuman/rlayouts-new
c7e617219a3794bba7ce849eda41981f20c1e865
[ "MIT" ]
4
2021-02-10T04:05:17.000Z
2021-02-19T01:31:35.000Z
docs/public/styles/extras.css
barelyhuman/rlayouts-new
c7e617219a3794bba7ce849eda41981f20c1e865
[ "MIT" ]
1
2021-02-10T21:49:14.000Z
2021-02-10T21:49:14.000Z
.list-style-none { list-style-type: none; } a { text-underline-offset: 4px; } .logo-holder { background-image: url("/assets/dark-logo.png"); background-position: center; background-size: contain; background-repeat: no-repeat; height: 74px; width: 74px; object-fit: contain; } .only-light { display: block; } .only-dark { display: none; } pre { font-size: 14px; line-height: 25.2px; } @media (prefers-color-scheme: dark) { .logo-holder { background-image: url("/assets/light-logo.png"); } .only-dark { display: block; } .only-light { display: none; } }
13.555556
52
0.631148
af627ee5fbe70f65af41e68dee91e0d2ce357ca2
1,047
rs
Rust
src/test/ui/consts/const-eval/issue-50814-2.rs
bpowers/rust
9f53c87b4b1f097e111c9525d60470ed22631018
[ "ECL-2.0", "Apache-2.0", "MIT-0", "MIT" ]
4
2019-09-26T13:28:01.000Z
2022-03-22T11:55:26.000Z
src/test/ui/consts/const-eval/issue-50814-2.rs
bpowers/rust
9f53c87b4b1f097e111c9525d60470ed22631018
[ "ECL-2.0", "Apache-2.0", "MIT-0", "MIT" ]
null
null
null
src/test/ui/consts/const-eval/issue-50814-2.rs
bpowers/rust
9f53c87b4b1f097e111c9525d60470ed22631018
[ "ECL-2.0", "Apache-2.0", "MIT-0", "MIT" ]
3
2018-07-02T03:07:01.000Z
2020-06-09T20:58:08.000Z
// Copyright 2018 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // 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. This file may not be copied, modified, or distributed // except according to those terms. trait C { const BOO: usize; } trait Foo<T> { const BAR: usize; } struct A<T>(T); impl<T: C> Foo<T> for A<T> { const BAR: usize = [5, 6, 7][T::BOO]; } fn foo<T: C>() -> &'static usize { &<A<T> as Foo<T>>::BAR //~ ERROR erroneous constant used //~| ERROR E0080 } impl C for () { const BOO: usize = 42; } impl C for u32 { const BOO: usize = 1; } fn main() { println!("{:x}", foo::<()>() as *const usize as usize); println!("{:x}", foo::<u32>() as *const usize as usize); println!("{:x}", foo::<()>()); println!("{:x}", foo::<u32>()); }
23.795455
68
0.61127
04e95bea0f0bae896acc5afac4f27b93b67dd503
2,384
swift
Swift
ios/Party Line/API/Events.swift
vsethu/DhanaSabha
0d6b28888f8d4abff538a8d0c694b346adacf34d
[ "BSD-2-Clause" ]
42
2021-03-10T17:40:56.000Z
2022-02-17T07:58:04.000Z
ios/Party Line/API/Events.swift
vsethu/DhanaSabha
0d6b28888f8d4abff538a8d0c694b346adacf34d
[ "BSD-2-Clause" ]
12
2021-09-03T16:52:36.000Z
2022-02-19T04:17:12.000Z
ios/Party Line/API/Events.swift
vsethu/DhanaSabha
0d6b28888f8d4abff538a8d0c694b346adacf34d
[ "BSD-2-Clause" ]
16
2021-03-10T17:41:09.000Z
2022-02-17T07:58:09.000Z
import Foundation import WebKit struct DemoCreatedRoomEvent: Decodable { let room: Room } struct DemoCreatedTokenEvent: Decodable { let token: String } struct DemoJoinedRoomEvent: Decodable { let room: Room } // https://docs.daily.co/reference#app-message struct AppMessageEvent: Decodable { let callFrameId: String let data: JSONValue let fromId: UUID } // https://docs.daily.co/reference#error struct ErrorEvent: Decodable { enum CodingKeys: String, CodingKey { case message = "errorMsg" } let message: String } // https://docs.daily.co/reference#joined-meeting struct JoinedMeetingEvent: Decodable { let participants: [String: Participant] } // https://docs.daily.co/reference#error struct ParticipantJoinedEvent: Decodable { let participant: Participant } // https://docs.daily.co/reference#participant-left struct ParticipantLeftEvent: Decodable { let participant: Participant } // https://docs.daily.co/reference#participant-updated struct ParticipantUpdatedEvent: Decodable { let participant: Participant } enum Event { case demoCreatedRoom(DemoCreatedRoomEvent) case demoCreatedToken(DemoCreatedTokenEvent) case demoJoinedRoom(DemoJoinedRoomEvent) case appMessage(AppMessageEvent) case error(ErrorEvent) case joinedMeeting(JoinedMeetingEvent) case participantJoined(ParticipantJoinedEvent) case participantLeft(ParticipantLeftEvent) case participantUpdated(ParticipantUpdatedEvent) } extension Event: CustomStringConvertible { var description: String { switch self { case .demoCreatedRoom(let event): return String(describing: event) case .demoCreatedToken(let event): return String(describing: event) case .demoJoinedRoom(let event): return String(describing: event) case .appMessage(let event): return String(describing: event) case .error(let event): return String(describing: event) case .joinedMeeting(let event): return String(describing: event) case .participantJoined(let event): return String(describing: event) case .participantLeft(let event): return String(describing: event) case .participantUpdated(let event): return String(describing: event) } } }
27.090909
54
0.704698
a36386abd39396786dc516a5f013c4473ae7078d
9,845
java
Java
src/main/java/mx/kenzie/magic/collection/MagicList.java
bluelhf/StableMagic
e5556c5ce9d7453b26e8fb34dc95822f35a26594
[ "MIT" ]
null
null
null
src/main/java/mx/kenzie/magic/collection/MagicList.java
bluelhf/StableMagic
e5556c5ce9d7453b26e8fb34dc95822f35a26594
[ "MIT" ]
null
null
null
src/main/java/mx/kenzie/magic/collection/MagicList.java
bluelhf/StableMagic
e5556c5ce9d7453b26e8fb34dc95822f35a26594
[ "MIT" ]
1
2021-06-07T15:08:56.000Z
2021-06-07T15:08:56.000Z
package mx.kenzie.magic.collection; import com.google.gson.Gson; import com.google.gson.JsonArray; import com.google.gson.JsonElement; import mx.kenzie.magic.magic.GenericCapture; import mx.kenzie.magic.magic.JsonMapper; import mx.kenzie.magic.magic.UnsafeModifier; import mx.kenzie.magic.note.Unsafe; import java.lang.reflect.Array; import java.util.*; import java.util.function.*; import java.util.stream.Collectors; /** * A specialised ArrayList wrapper with extra features for quick and easy use. * * @param <T> Collection type * @author Mackenzie */ public class MagicList<T> extends ArrayList<T> implements MagicArrayList<T> { protected UnsafeModifier modifier; public MagicList(int capacity) { super(capacity); } public MagicList(Collection<? extends T> collection) { super(collection); } public MagicList(Iterable<? extends T> iterable) { this(); for (T t : iterable) { this.add(t); } } public MagicList() { super(); } @SafeVarargs public MagicList(T... ts) { super(Arrays.asList(ts)); } public static MagicStringList ofWords(String string) { return new MagicStringList(string.split("\\s+")); } public static MagicStringList from(Iterable<?> iterable) { if (iterable == null) return new MagicStringList(); MagicStringList list = new MagicStringList(); for (Object element : iterable) { if (element != null) list.add(element.toString()); } return list; } public static <T, Q> MagicList<T> from(Iterable<Q> iterable, Function<Q, T> converter) { if (iterable == null || converter == null) return new MagicList<>(); MagicList<T> list = new MagicList<>(); for (Q element : iterable) { list.add(converter.apply(element)); } return list; } @SafeVarargs public static <T> MagicList<T> from(Collection<T>... collections) { MagicList<T> list = new MagicList<>(); for (Collection<T> collection : collections) { list.addAll(collection); } return list; } @SafeVarargs public static <T> MagicList<T> from(Iterable<T>... iterables) { MagicList<T> list = new MagicList<>(); for (Iterable<T> collection : iterables) { for (T thing : collection) { list.add(thing); } } return list; } @Override public MagicList<T> addAnd(T t) { this.add(t); return this; } @Override public MagicList<T> removeAnd(T t) { this.remove(t); return this; } @Override public MagicList<T> removeAnd(int index) { this.remove(index); return this; } @Override public MagicList<T> shuffleAnd() { this.shuffle(); return this; } @Override public MagicList<T> sort() { this.sort(null); return this; } @Override @SafeVarargs public final MagicList<T> stack(Collection<T>... collections) { for (Collection<T> ts : collections) { this.addAll(ts); } return this; } @Override @SafeVarargs public final MagicList<T> stack(T[]... arrays) { for (T[] ts : arrays) { this.addAll(ts); } return this; } @Override public MagicList<T> until(int until) { return from(0, until); } @Override public MagicList<T> from(int start) { return from(start, size()); } @Override public MagicList<T> from(int start, int end) { if (start < 0) throw new IllegalArgumentException("Start index must be >= 0!"); if (end > size()) throw new IllegalArgumentException("End index must not be greater than the list's size!"); return new MagicList<>(subList(start, end - 1)); } @Override public boolean removeUnless(Predicate<? super T> filter) { return this.removeIf(filter.negate()); } @Override public <R> MagicList<R> collect(Function<T, R> function) { MagicList<R> list = new MagicList<>(); for (T thing : this) { list.add(function.apply(thing)); } return list; } @Override public <U, R> MagicList<R> collect(BiFunction<T, U, R> function, U argument) { MagicList<R> list = new MagicList<>(); for (T thing : this) { list.add(function.apply(thing, argument)); } return list; } @Override public MagicList<T> filter(Predicate<T> function) { return this.stream().filter(function).collect(Collectors.toCollection(MagicList::new)); } @Override public <Q> MagicList<T> filterFind(Q sample, BiFunction<T, Q, Boolean> function) { return this.stream().filter(t -> function.apply(t, sample)).collect(Collectors.toCollection(MagicList::new)); } // public MagicMap<Integer, T> toIndexMap() { // return MagicMap.ofIndices(this); // } @Override public <Q> T filterFindFirst(Q sample, BiFunction<T, Q, Boolean> function) { return this.stream().filter(t -> function.apply(t, sample)).findFirst().orElse(null); } @Override public <Q> T filterFindLast(Q sample, BiFunction<T, Q, Boolean> function) { List<T> list = new ArrayList<>(this); Collections.reverse(list); return list.stream().filter(t -> function.apply(t, sample)).findFirst().orElse(null); } @Override public MagicList<T> forEachAnd(Consumer<? super T> action) { this.forEach(action); return this; } @Override public <Q> MagicList<T> forAllAnd(Q input, BiConsumer<? super T, Q> action) { forAll(input, action); return this; } @Override public <Q> MagicList<T> forAllAndR(Q input, BiConsumer<Q, T> action) { forAllR(input, action); return this; } @Override public <Q> MagicList<Q> castConvert(Class<Q> cls) { return castConvert(); } @Override @SuppressWarnings("unchecked") public <Q> MagicList<Q> castConvert() { MagicList<Q> list = new MagicList<>(); for (T thing : this) { list.add((Q) thing); } return list; } @Override public void shuffle() { Collections.shuffle(this); } @Override @Unsafe("Allows access to dangerous magical powers.") public MagicList<T> allowUnsafe() { modifier = UnsafeModifier.GENERIC; return this; } @Override @Unsafe public MagicList<T> deepCopy() { assert modifier != null; return this.collect(modifier::deepCopy); } @Override @Unsafe public MagicList<T> shallowCopy() { assert modifier != null; return this.collect(modifier::shallowCopy); } @Override @Unsafe("Object transformations are *very* dangerous.") @Deprecated public <Q> MagicList<Q> transform(Class<Q> target) { assert modifier != null; return this .collect(modifier::shallowCopy) .collect(modifier::transform, target); } @Override @Unsafe("What are you planning...") @Deprecated public long getMemoryAddress() { assert modifier != null; return modifier.getMemoryAddress(this); } public MagicList<T> reverseSort() { this.sort(Collections.reverseOrder()); return this; } @SuppressWarnings("unchecked") public MagicList<T>[] split(int size) { Object[] array = this.toArray(); List<MagicList<T>> lists = new ArrayList<>(); int count = 0; MagicList<T> list = new MagicList<>(); for (Object o : array) { count++; if (count > size) { lists.add(list); list = new MagicList<>(); count = 0; } list.add((T) o); } return (MagicList<T>[]) lists.toArray(new MagicList[0]); } public <R> MagicList<R> collectIgnoreNull(Function<T, R> function) { MagicList<R> list = new MagicList<>(); for (T thing : this) { if (thing == null) continue; R blob = function.apply(thing); if (blob != null) list.add(blob); } return list; } @SuppressWarnings("unchecked") public T[] toArray(Class<T> cls) { return super.toArray((T[]) Array.newInstance(cls, 0)); } public boolean removeDuplicates() { final int s = this.size(); Set<T> set = new HashSet<>(this); this.clear(); this.addAll(set); return s != this.size(); } @Override @SuppressWarnings("unchecked") public MagicList<T> clone() { try { return (MagicList<T>) super.clone(); } catch (Throwable ex) { // CloneNotSupportedException or ClassCastException if (modifier != null) return modifier.shallowCopy(this); return new MagicList<>(this); } } @Override public void sort(Comparator<? super T> c) { super.sort(c); } public MagicList<T> withoutDuplicates() { return new MagicList<>(new HashSet<>(this)); } @Override public Class<T> getComponentType() { return new GenericCapture<>(this).getType(); } public JsonArray toJsonStringArray() { return JsonMapper.MAPPER.toJsonStringArray(this); } public JsonArray toJsonArray(Function<T, JsonElement> converter) { return JsonMapper.MAPPER.toJsonArray(this, converter); } public JsonArray toJsonArray() { return JsonMapper.MAPPER.toJsonArray(this); } }
26.680217
117
0.58131
9d99fb0b1390e3dc7afb97b26268cf5b4d4f3186
1,657
swift
Swift
Sources/Jenga/DSL/DSLAutoTable.swift
lixiang1994/TableKit
0ac6721407fca10a13fb9dba5d5f7004662f4970
[ "MIT" ]
null
null
null
Sources/Jenga/DSL/DSLAutoTable.swift
lixiang1994/TableKit
0ac6721407fca10a13fb9dba5d5f7004662f4970
[ "MIT" ]
null
null
null
Sources/Jenga/DSL/DSLAutoTable.swift
lixiang1994/TableKit
0ac6721407fca10a13fb9dba5d5f7004662f4970
[ "MIT" ]
1
2022-03-28T09:21:13.000Z
2022-03-28T09:21:13.000Z
import UIKit // 快速列表使用此协议, 协议都有默认实现 controller 只需要实现tableContents即可 public protocol DSLAutoTable: DSLTable { var tableView: UITableView { get } func didLayoutTable() } private var TableViewKey: Void? private var TableKey: Void? public extension DSLAutoTable where Self: UIViewController { var tableView: UITableView { get { guard let value: UITableView = get(&TableViewKey) else { let temp = JengaEnvironment.provider.defaultTableView(with: .zero) set(retain: &TableViewKey, temp) return temp } return value } set { set(retain: &TableViewKey, newValue) } } var table: TableDirector { get { guard let value: TableDirector = get(&TableKey) else { let temp = TableDirector(tableView) set(retain: &TableKey, temp) return temp } return value } set { set(retain: &TableKey, newValue) } } func didLayoutTable() { view.addSubview(tableView) tableView.fillToSuperview() } } extension UIViewController { static let swizzled: Void = { do { let originalSelector = #selector(UIViewController.viewDidLoad) let swizzledSelector = #selector(UIViewController.jenga_viewDidLoad) swizzled_method(originalSelector, swizzledSelector) } } () @objc private func jenga_viewDidLoad() { jenga_viewDidLoad() (self as? DSLAutoTable)?.didLayoutTable() (self as? DSLTable)?.reloadTable() } }
26.301587
82
0.592637
7bdfa2ec3130d4e3e8222b483dd1c4cb342182f5
20,482
cpp
C++
Common/CoordinateSystem/CoordSysGeodeticTransformDef.cpp
achilex/MgDev
f7baf680a88d37659af32ee72b9a2046910b00d8
[ "PHP-3.0" ]
2
2017-04-19T01:38:30.000Z
2020-07-31T03:05:32.000Z
Common/CoordinateSystem/CoordSysGeodeticTransformDef.cpp
achilex/MgDev
f7baf680a88d37659af32ee72b9a2046910b00d8
[ "PHP-3.0" ]
null
null
null
Common/CoordinateSystem/CoordSysGeodeticTransformDef.cpp
achilex/MgDev
f7baf680a88d37659af32ee72b9a2046910b00d8
[ "PHP-3.0" ]
1
2021-12-29T10:46:12.000Z
2021-12-29T10:46:12.000Z
// // Copyright (C) 2004-2011 by Autodesk, Inc. // // This library is free software; you can redistribute it and/or // modify it under the terms of version 2.1 of the GNU Lesser // General Public License as published by the Free Software Foundation. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA // #include "GeometryCommon.h" #include "CoordSysCommon.h" #include "CriticalSection.h" #include "CoordSysGeodeticTransformation.h" #include "CoordSysGeodeticTransformDefParams.h" #include "CoordSysGeodeticStandaloneTransformDefParams.h" #include "CoordSysGeodeticAnalyticalTransformDefParams.h" #include "CoordSysGeodeticInterpolationTransformDefParams.h" #include "CoordSysGeodeticMultipleRegressionTransformDefParams.h" #include "CoordSysGeodeticTransformDef.h" #include "CoordSysTransform.h" //for CCoordinateSystemTransform #include "CoordSysUtil.h" //for CsDictionaryOpenMode #include "MentorDictionary.h" using namespace CSLibrary; #define CS_MAP_DEF_VARIABLE this->transformDefinition //needed by CoordSysMacro #include "CoordSysMacro.h" //for DEFINE_GET_SET_STRING and DEFINE_GET_SET_NUMERIC CCoordinateSystemGeodeticTransformDef::CCoordinateSystemGeodeticTransformDef(MgCoordinateSystemCatalog* pCatalog) : transformationDefType(0), transformDefinition(NULL), catalog(SAFE_ADDREF(pCatalog) /* make sure, we take a count on it */) { //have we been passed a non-null argument? CHECKNULL(this->catalog, L"CCoordinateSystemGeodeticTransformDef.ctor"); } CCoordinateSystemGeodeticTransformDef::~CCoordinateSystemGeodeticTransformDef() { this->ReleaseInstance(); } void CCoordinateSystemGeodeticTransformDef::ReleaseInstance() { if (NULL != this->transformDefinition) { CS_free(this->transformDefinition); this->transformDefinition = NULL; } this->transformationDefType = 0; } void CCoordinateSystemGeodeticTransformDef::Dispose() { delete this; } void CCoordinateSystemGeodeticTransformDef::Reset(INT32 transformationDefType) { INT32 transformationType; switch(transformationDefType) { case MgCoordinateSystemGeodeticTransformDefType::Standalone: case MgCoordinateSystemGeodeticTransformDefType::Analytical: case MgCoordinateSystemGeodeticTransformDefType::Interpolation: case MgCoordinateSystemGeodeticTransformDefType::MultipleRegression: transformationType = transformationDefType; break; default: throw new MgInvalidArgumentException(L"CCoordinateSystemGeodeticTransformDef.Reset", __LINE__, __WFILE__, NULL, L"", NULL); } //try creating a new [cs_GeodeticTransform_] instance before we wipe out our own stuff cs_GeodeticTransform_* newEmptyDef = (cs_GeodeticTransform_*)CS_malc(sizeof(cs_GeodeticTransform_)); if (NULL == newEmptyDef) //uses CS_malc which returns NULL in case allocation fails throw new MgOutOfMemoryException(L"CCoordinateSystemGeodeticTransformDef.Initialize", __LINE__, __WFILE__, NULL, L"", NULL); MG_TRY() //now, 0 our temp memory we've allocated memset ((void*)newEmptyDef, 0, sizeof(cs_GeodeticTransform_)); //ok - everything worked out so far; release this instance's information this->ReleaseInstance(); _ASSERT(NULL == this->transformDefinition); this->transformDefinition = newEmptyDef; newEmptyDef = NULL; //make sure, we don't free that one after we get a hold on the (no longer temp) memory this->transformationDefType = transformationType; MG_CATCH(L"CCoordinateSystemGeodeticTransformDef.Reset") if (NULL != newEmptyDef) //will have been set to NULL before CS_free(newEmptyDef); MG_THROW() } INT32 CCoordinateSystemGeodeticTransformDef::GetTransformationDefType(INT32 methodCode /* method code as read from the dictionary entry */) { INT32 transformationType; switch(methodCode) { //standalone/built-in methods; see information in cs_geodetic.h case cs_DTCMTH_NULLX: case cs_DTCMTH_WGS72: transformationType = MgCoordinateSystemGeodeticTransformDefType::Standalone; break; //multiple Regression methods case cs_DTCMTH_MULRG: case cs_DTCMTH_PLYNM: transformationType = MgCoordinateSystemGeodeticTransformDefType::MultipleRegression; break; //geocentric methods case cs_DTCMTH_3PARM: case cs_DTCMTH_MOLOD: case cs_DTCMTH_AMOLO: case cs_DTCMTH_GEOCT: case cs_DTCMTH_4PARM: case cs_DTCMTH_6PARM: case cs_DTCMTH_BURSA: case cs_DTCMTH_FRAME: case cs_DTCMTH_7PARM: case cs_DTCMTH_BDKAS: transformationType = MgCoordinateSystemGeodeticTransformDefType::Analytical; break; //grid file interpolation methods; if a transformation uses grid file(s), this is the actual //type - the ones below are the format of the grid file(s) being used. For example, //the dictionary does then contains something like //GRID_FILE: NTv2,FWD,.\Australia\Agd66\A66National(13.09.01).gsb case cs_DTCMTH_GFILE: transformationType = MgCoordinateSystemGeodeticTransformDefType::Interpolation; break; //the next entries are not expected; we're mapping them to the interpolation transformation type case cs_DTCMTH_CNTv1: case cs_DTCMTH_CNTv2: case cs_DTCMTH_FRNCH: case cs_DTCMTH_JAPAN: case cs_DTCMTH_ATS77: case cs_DTCMTH_OST97: case cs_DTCMTH_OST02: _ASSERT(false); transformationType = MgCoordinateSystemGeodeticTransformDefType::Interpolation; break; default: //invalid / unknown [methodCode] given; don't know how to proceed here throw new MgInvalidArgumentException(L"CCoordinateSystemGeodeticTransformDef.Initialize", __LINE__, __WFILE__, NULL, L"", NULL); } return transformationType; } void CCoordinateSystemGeodeticTransformDef::Initialize(const cs_GeodeticTransform_& transformDef) { //take the transformation type from the param we've been passed; we'll use that information to build the correct //parameter object later on INT32 transformationType = this->GetTransformationDefType(transformDef.methodCode); this->Reset(transformationType); *this->transformDefinition = transformDef; } MgCoordinateSystemGeodeticTransformation* CCoordinateSystemGeodeticTransformDef::CreateTransformation(bool createInverse) { VERIFY_INITIALIZED(L"CCoordinateSystemGeodeticTransformDef.CreateTransformation"); if (!this->IsValid()) throw new MgInvalidOperationException(L"CCoordinateSystemGeodeticTransformDef.CreateTransformation", __LINE__,__WFILE__, NULL, L"", NULL); //we don't take ownership of the transformation being returned but //will release [sourceDatum] and [targetDatum]; //new [CCoordinateSystemGeodeticTransformation] will have to ADDREF if needed return new CCoordinateSystemGeodeticTransformation(this->catalog, this, createInverse); } MgCoordinateSystemGeodeticTransformDef* CCoordinateSystemGeodeticTransformDef::CreateClone() { VERIFY_INITIALIZED(L"CCoordinateSystemGeodeticTransformDef.CreateClone"); Ptr<CCoordinateSystemGeodeticTransformDef> clonedTransformDef = new CCoordinateSystemGeodeticTransformDef(this->catalog.p); clonedTransformDef->Initialize(*this->transformDefinition); //unset the EPSG code; we've an editable instance now where we neither can guarantee the correctness of the EPSG code //nor is it currently supported by CsMap's NameMapper anyway clonedTransformDef->transformDefinition->epsgCode = 0; clonedTransformDef->transformDefinition->epsgVariation = 0; clonedTransformDef->transformDefinition->protect = 0; //unset the protection flag; otherwise the caller wouldn't be able to change any values return clonedTransformDef.Detach(); } void CCoordinateSystemGeodeticTransformDef::CopyTo(cs_GeodeticTransform_& transformDef) const { VERIFY_INITIALIZED(L"CCoordinateSystemGeodeticTransformDef.CopyTo"); //copy our values into the [cs_GeodeticTransform_] we've been passed here transformDef = *this->transformDefinition; } INT32 CCoordinateSystemGeodeticTransformDef::GetTransformDefType() { return this->transformationDefType; //can be None } MgCoordinateSystemGeodeticTransformDefParams* CCoordinateSystemGeodeticTransformDef::GetParameters() { VERIFY_INITIALIZED(L"CCoordinateSystemGeodeticTransformDef.GetParameters"); switch(this->transformationDefType) { case MgCoordinateSystemGeodeticTransformDefType::Standalone: return static_cast<MgCoordinateSystemGeodeticStandaloneTransformDefParams*>(new CCoordinateSystemGeodeticStandaloneTransformDefParams( this->transformDefinition->methodCode, this->IsProtected())); case MgCoordinateSystemGeodeticTransformDefType::Analytical: return static_cast<MgCoordinateSystemGeodeticAnalyticalTransformDefParams*>(new CCoordinateSystemGeodeticAnalyticalTransformDefParams( this->transformDefinition->parameters.geocentricParameters, this->transformDefinition->methodCode, this->IsProtected())); case MgCoordinateSystemGeodeticTransformDefType::Interpolation: return static_cast<MgCoordinateSystemGeodeticInterpolationTransformDefParams*>( new CCoordinateSystemGeodeticInterpolationTransformDefParams(this->transformDefinition->parameters.fileParameters, this->IsProtected())); case MgCoordinateSystemGeodeticTransformDefType::MultipleRegression: return static_cast<MgCoordinateSystemGeodeticMultipleRegressionTransformDefParams*>(new CCoordinateSystemGeodeticMultipleRegressionTransformDefParams( this->transformDefinition->parameters.dmaMulRegParameters, this->transformDefinition->methodCode, this->IsProtected())); default: //invalid state; why's that? _ASSERT(false); throw new MgInvalidOperationException(L"CCoordinateSystemGeodeticTransformDef.GetParameters", __LINE__, __WFILE__, NULL, L"", NULL); } } void CCoordinateSystemGeodeticTransformDef::SetParameters(MgCoordinateSystemGeodeticTransformDefParams* parameters) { VERIFY_INITIALIZED(L"CCoordinateSystemGeodeticTransformDef.SetParameters"); VERIFY_NOT_PROTECTED(L"CCoordinateSystemGeodeticTransformDef.SetParameters"); //first check, whether this is a NONE transformation definition; if so, ignore the parameter altogether and wipe out //this instance's parameter information to NULL if (MgCoordinateSystemGeodeticTransformDefType::None == this->transformationDefType) { memset(&this->transformDefinition->parameters, 0, sizeof(this->transformDefinition->parameters.sizeDetermination.unionSize)); return; } //otherwise: make sure, we've been passed non null paramaters... ENSURE_NOT_NULL(parameters, L"CCoordinateSystemGeodeticTransformDef.SetParameters"); INT32 paramsMethodCode = 0x0; //...and the parameters are actually of the correct type, i.e. match whatever we've stored in [this->transformationDefType] CCoordinateSystemGeodeticTransformDefParams* transformDefParams = NULL; CCoordinateSystemGeodeticMultipleRegressionTransformDefParams* mulRegParams = NULL; CCoordinateSystemGeodeticAnalyticalTransformDefParams* analyticalParams = NULL; CCoordinateSystemGeodeticStandaloneTransformDefParams* standaloneParams = NULL; switch(this->transformationDefType) { case MgCoordinateSystemGeodeticTransformDefType::Standalone: standaloneParams = dynamic_cast<CCoordinateSystemGeodeticStandaloneTransformDefParams*>(parameters); if (NULL != standaloneParams) { paramsMethodCode = standaloneParams->GetTransformationMethod(); transformDefParams = standaloneParams; } break; case MgCoordinateSystemGeodeticTransformDefType::Analytical: analyticalParams = dynamic_cast<CCoordinateSystemGeodeticAnalyticalTransformDefParams*>(parameters); if (NULL != analyticalParams) { paramsMethodCode = analyticalParams->GetTransformationMethod(); transformDefParams = analyticalParams; } break; case MgCoordinateSystemGeodeticTransformDefType::Interpolation: transformDefParams = dynamic_cast<CCoordinateSystemGeodeticInterpolationTransformDefParams*>(parameters); //the transformation method is "grid file"; the actual type doesn't matter as this //is specified through the [MgCoordinateSystemGeodeticInterpolationTransformDefParams] object; //such a transformation can use multiple grid files where each can have a different format paramsMethodCode = cs_DTCMTH_GFILE; break; case MgCoordinateSystemGeodeticTransformDefType::MultipleRegression: mulRegParams = dynamic_cast<CCoordinateSystemGeodeticMultipleRegressionTransformDefParams*>(parameters); if (NULL != mulRegParams) { paramsMethodCode = mulRegParams->GetTransformationMethod(); transformDefParams = mulRegParams; } break; default: _ASSERT(false); //why's that? break; } if (NULL == transformDefParams) throw new MgInvalidOperationException(L"CCoordinateSystemGeodeticTransformDef.SetParameters", __LINE__, __WFILE__, NULL, L"", NULL); //copy the values from the parameter we've been passed into our own [parameters] section transformDefParams->CopyTo(&this->transformDefinition->parameters); this->transformDefinition->methodCode = paramsMethodCode; } bool CCoordinateSystemGeodeticTransformDef::IsProtected() { VERIFY_INITIALIZED(L"CCoordinateSystemGeodeticTransformDef.IsProtected"); return (DICTIONARY_SYS_DEF == this->transformDefinition->protect); } bool CCoordinateSystemGeodeticTransformDef::IsValid() { if (NULL == this->transformDefinition) //an unitialized definition is always invalid return false; Ptr<MgCoordinateSystemGeodeticTransformDefParams> params = this->GetParameters(); if (NULL == params) return true; //this is a NULL transformation; this is valid if (!params->IsValid()) return false; CriticalClass.Enter(); int nNumErrs = CS_gxchk(this->transformDefinition, 0, NULL, 0); CriticalClass.Leave(); return (0 == nNumErrs); } //helper - don't delete bool CCoordinateSystemGeodeticTransformDef::IsEncrypted() { return false; } DEFINE_GET_SET_STRING(CCoordinateSystemGeodeticTransformDef,TransformName,this->transformDefinition->xfrmName) DEFINE_GET_SET_STRING(CCoordinateSystemGeodeticTransformDef,SourceDatum,this->transformDefinition->srcDatum) DEFINE_GET_SET_STRING(CCoordinateSystemGeodeticTransformDef,TargetDatum,this->transformDefinition->trgDatum) DEFINE_GET_SET_STRING(CCoordinateSystemGeodeticTransformDef,Group,this->transformDefinition->group) DEFINE_GET_SET_STRING(CCoordinateSystemGeodeticTransformDef,Description,this->transformDefinition->description) DEFINE_GET_SET_STRING(CCoordinateSystemGeodeticTransformDef,Source,this->transformDefinition->source) DEFINE_GET_SET_NUMERIC(CCoordinateSystemGeodeticTransformDef,EpsgCode,INT32,this->transformDefinition->epsgCode) DEFINE_GET_SET_NUMERIC(CCoordinateSystemGeodeticTransformDef,EpsgVariation,INT32,this->transformDefinition->epsgVariation) DEFINE_GET_SET_NUMERIC(CCoordinateSystemGeodeticTransformDef,InverseSupported,bool,this->transformDefinition->inverseSupported) DEFINE_GET_SET_NUMERIC(CCoordinateSystemGeodeticTransformDef,MaxIterations,INT32,this->transformDefinition->maxIterations) DEFINE_GET_SET_NUMERIC(CCoordinateSystemGeodeticTransformDef,ConvergenceValue,double,this->transformDefinition->cnvrgValue) DEFINE_GET_SET_NUMERIC(CCoordinateSystemGeodeticTransformDef,ErrorValue,double,this->transformDefinition->errorValue) DEFINE_GET_SET_NUMERIC(CCoordinateSystemGeodeticTransformDef,Accuracy,double,this->transformDefinition->accuracy) DEFINE_GET_SET_NUMERIC(CCoordinateSystemGeodeticTransformDef,RangeMinLongitude,double,this->transformDefinition->rangeMinLng) DEFINE_GET_SET_NUMERIC(CCoordinateSystemGeodeticTransformDef,RangeMaxLongitude,double,this->transformDefinition->rangeMaxLng) DEFINE_GET_SET_NUMERIC(CCoordinateSystemGeodeticTransformDef,RangeMinLatitude,double,this->transformDefinition->rangeMinLat) DEFINE_GET_SET_NUMERIC(CCoordinateSystemGeodeticTransformDef,RangeMaxLatitude,double,this->transformDefinition->rangeMaxLat) //***************************************************************************** UINT8* CCoordinateSystemGeodeticTransformDef::SerializeFrom(UINT8* pStream) { UINT8* pStreamIn=pStream; char *pBuf; assert(NULL != pStream); if (!pStream) { throw new MgInvalidArgumentException(L"MgCoordinateSystemGeodeticTransformDef.SerializeFrom", __LINE__, __WFILE__, NULL, L"", NULL); } // In case an exception gets thrown. INT32 previousType = this->transformationDefType; cs_GeodeticTransform_* previousTransformPtr = this->transformDefinition; cs_GeodeticTransform_* allocatedBlock = NULL; MG_TRY() UINT8 nVersion=pStreamIn[0]; if (kGxRelease0==nVersion) { pStreamIn++; //Read the def from the stream allocatedBlock = (cs_GeodeticTransform_*)CS_malc(sizeof(cs_GeodeticTransform_)); if (NULL == allocatedBlock) throw new MgOutOfMemoryException (L"MgCoordinateSystemGeodeticTransformDef.SerializeFrom", __LINE__, __WFILE__, NULL, L"", NULL); this->transformDefinition = allocatedBlock; pBuf = reinterpret_cast<char *>(this->transformDefinition); memcpy(pBuf, pStreamIn, sizeof(cs_GeodeticTransform_)); pStreamIn = pStreamIn + sizeof(cs_GeodeticTransform_); // The following function nwill throw if the mthodCode is not one known to the function. this->transformationDefType = GetTransformationDefType(this->transformDefinition->methodCode); // Verify the validity of the result. if (IsValid()) { // Yup! its OK. Release the copy of the previous definition. CS_free (previousTransformPtr); previousTransformPtr = 0; } else { // Nope! It's not valid, but not valid in such a way that would cause // an exception to be thrown. transformationDefinition cannot be // NULL at this point. throw new MgInvalidArgumentException(L"MgCoordinateSystemGeodeticTransformDef.SerializeFrom", __LINE__, __WFILE__, NULL, L"", NULL); } } MG_CATCH (L"MgCoordinateSystemGeodeticTransformDef.SerializeFrom") if (mgException != NULL) { //in case an exception was thrown, we simply free the allocated block //and reset what we had before; no matter whether this had been valid or not CS_free (allocatedBlock); allocatedBlock = NULL; this->transformationDefType = previousType; this->transformDefinition = previousTransformPtr; } MG_THROW () return pStreamIn; } //***************************************************************************** UINT8* CCoordinateSystemGeodeticTransformDef::SerializeTo(UINT8* pStream) { char *pBuf; UINT8* pStreamOut=pStream; MG_TRY() assert(NULL != pStream); if (!pStream) { throw new MgInvalidArgumentException(L"MgCoordinateSystemGeodeticTransformDef.SerializeTo", __LINE__, __WFILE__, NULL, L"", NULL); } //save the version pStreamOut[0]=kGxRelease0; pStreamOut++; pBuf = reinterpret_cast<char *>(this->transformDefinition); memcpy(pStreamOut, pBuf, sizeof(*this->transformDefinition)); pStreamOut = pStreamOut + sizeof(*this->transformDefinition); MG_CATCH_AND_THROW(L"MgCoordinateSystemGeodeticTransformDef.SerializeTo") return pStreamOut; } //***************************************************************************** UINT32 CCoordinateSystemGeodeticTransformDef::GetSizeSerialized() { //size of the structure and the verison number size_t size=sizeof(cs_GeodeticTransform_) + sizeof(UINT8); return static_cast<UINT32>(size); }
42.939203
158
0.761303
2dad96d444d20f8fa4c2af6a33def3317610ae34
381
asm
Assembly
oeis/106/A106665.asm
neoneye/loda-programs
84790877f8e6c2e821b183d2e334d612045d29c0
[ "Apache-2.0" ]
11
2021-08-22T19:44:55.000Z
2022-03-20T16:47:57.000Z
oeis/106/A106665.asm
neoneye/loda-programs
84790877f8e6c2e821b183d2e334d612045d29c0
[ "Apache-2.0" ]
9
2021-08-29T13:15:54.000Z
2022-03-09T19:52:31.000Z
oeis/106/A106665.asm
neoneye/loda-programs
84790877f8e6c2e821b183d2e334d612045d29c0
[ "Apache-2.0" ]
3
2021-08-22T20:56:47.000Z
2021-09-29T06:26:12.000Z
; A106665: Alternate paper-folding (or alternate dragon curve) sequence. ; Submitted by Jamie Morken(m3) ; 1,0,0,1,1,1,0,0,1,0,0,0,1,1,0,1,1,0,0,1,1,1,0,1,1,0,0,0,1,1,0,0,1,0,0,1,1,1,0,0,1,0,0,0,1,1,0,0,1,0,0,1,1,1,0,1,1,0,0,0,1,1,0,1,1,0,0,1,1,1,0,0,1,0,0,0,1,1,0,1,1,0,0,1,1,1,0,1,1,0,0,0,1,1,0,1,1,0,0,1 mul $0,3 add $0,3 lpb $0 mov $2,$0 div $0,4 gcd $0,$2 lpe div $0,2
29.307692
201
0.574803
b24d53bb89f4beb4973066bc5471161bcf19e331
16,926
swift
Swift
Firefly Fixture/Firefly Fixture/Geometry.swift
denisbohm/firefly-production-tools
30b06b42e339456f9412e4be6bfbc2bc2392ec77
[ "Apache-2.0" ]
1
2017-07-18T22:53:34.000Z
2017-07-18T22:53:34.000Z
Firefly Fixture/Firefly Fixture/Geometry.swift
denisbohm/firefly-production-tools
30b06b42e339456f9412e4be6bfbc2bc2392ec77
[ "Apache-2.0" ]
null
null
null
Firefly Fixture/Firefly Fixture/Geometry.swift
denisbohm/firefly-production-tools
30b06b42e339456f9412e4be6bfbc2bc2392ec77
[ "Apache-2.0" ]
null
null
null
// // Geometry.swift // Firefly Fixture // // Created by Denis Bohm on 1/31/17. // Copyright © 2017 Firefly Design LLC. All rights reserved. // import Foundation class Geometry { struct Point3D { let x: CGFloat let y: CGFloat let z: CGFloat init(x: CGFloat, y: CGFloat, z: CGFloat) { self.x = x self.y = y self.z = z } init(xy: NSPoint, z: CGFloat) { self.x = xy.x self.y = xy.y self.z = z } } class Path3D { var points: [Point3D] = [] } static func lastPoint(path: NSBezierPath) -> NSPoint { var first: NSPoint? = nil var last = NSPoint(x: 0, y: 0) for i in 0 ..< path.elementCount { var points: [NSPoint] = [NSPoint(x: 0, y: 0), NSPoint(x: 0, y: 0), NSPoint(x: 0, y: 0)] let kind = path.element(at: i, associatedPoints: &points) switch (kind) { case .moveToBezierPathElement: last = points[0] first = last case .lineToBezierPathElement: last = points[0] case .curveToBezierPathElement: last = points[2] case .closePathBezierPathElement: if let first = first { last = first } } } return last } static func firstPoint(path: NSBezierPath) -> NSPoint { for i in 0 ..< path.elementCount { var points: [NSPoint] = [NSPoint(x: 0, y: 0), NSPoint(x: 0, y: 0), NSPoint(x: 0, y: 0)] let kind = path.element(at: i, associatedPoints: &points) switch (kind) { case .moveToBezierPathElement: return points[0] default: break } } return NSPoint(x: 0, y: 0) } static func equal(point1: NSPoint, point2: NSPoint) -> Bool { return (point1.x == point2.x) && (point1.y == point2.y) } static func distance(point1: NSPoint, point2: NSPoint) -> CGFloat { let dx = point1.x - point2.x let dy = point1.y - point2.y return sqrt(dx * dx + dy * dy) } static func canCombine(path1: NSBezierPath, path2: NSBezierPath) -> Bool { let last1 = Geometry.lastPoint(path: path1) let first2 = Geometry.firstPoint(path: path2) return Geometry.equal(point1: last1, point2: first2) } static func combine(path1: NSBezierPath, path2: NSBezierPath) -> NSBezierPath { let newPath = NSBezierPath() for i in 0 ..< path1.elementCount { var points: [NSPoint] = [NSPoint(x: 0, y: 0), NSPoint(x: 0, y: 0), NSPoint(x: 0, y: 0)] let kind = path1.element(at: i, associatedPoints: &points) switch (kind) { case .moveToBezierPathElement: newPath.move(to: points[0]) case .lineToBezierPathElement: newPath.line(to: points[0]) case .curveToBezierPathElement: newPath.curve(to: points[2], controlPoint1: points[0], controlPoint2: points[1]) case .closePathBezierPathElement: newPath.close() } } for i in 0 ..< path2.elementCount { var points: [NSPoint] = [NSPoint(x: 0, y: 0), NSPoint(x: 0, y: 0), NSPoint(x: 0, y: 0)] let kind = path2.element(at: i, associatedPoints: &points) switch (kind) { case .moveToBezierPathElement: if i == 0 { newPath.line(to: points[0]) } else { newPath.move(to: points[0]) } case .lineToBezierPathElement: newPath.line(to: points[0]) case .curveToBezierPathElement: newPath.curve(to: points[2], controlPoint1: points[0], controlPoint2: points[1]) case .closePathBezierPathElement: newPath.close() } } return newPath } static func combine(paths: [NSBezierPath]) -> [NSBezierPath] { let path1 = paths[0] let path2 = paths[paths.count - 1] if canCombine(path1: path1, path2: path2) { var newPaths: [NSBezierPath] = [] let combined = combine(path1: path1, path2: path2) newPaths.append(combined) if paths.count > 2 { for i in 1 ... paths.count - 2 { newPaths.append(paths[i]) } } return newPaths } else if canCombine(path1: path2, path2: path1) { var newPaths: [NSBezierPath] = [] let combined = combine(path1: path2, path2: path1) for i in 1 ... paths.count - 2 { newPaths.append(paths[i]) } newPaths.append(combined) return newPaths } else { return paths } } static func sortByX(paths: [NSBezierPath]) -> [NSBezierPath] { return paths.sorted() { let p0 = firstPoint(path: $0) let p1 = firstPoint(path: $1) return p0.x < p1.x } } static func orderByY(paths: [NSBezierPath]) -> [NSBezierPath] { var sortedPaths: [NSBezierPath] = [] for path in paths { let first = firstPoint(path: path) let last = lastPoint(path: path) var sortedPath = path if last.y < first.y { sortedPath = path.reversed } sortedPaths.append(sortedPath) } return sortedPaths } static func join(path: NSBezierPath) -> NSBezierPath { let epsilon: CGFloat = 0.001; var last = NSPoint(x: 0.123456, y: 0.123456) let newPath = NSBezierPath() for i in 0 ..< path.elementCount { var points: [NSPoint] = [NSPoint(x: 0, y: 0), NSPoint(x: 0, y: 0), NSPoint(x: 0, y: 0)] let kind = path.element(at: i, associatedPoints: &points) switch (kind) { case .moveToBezierPathElement: let p0 = points[0] if (fabs(last.x - p0.x) > epsilon) || (fabs(last.y - p0.y) > epsilon) { newPath.move(to: p0) last = points[0] // NSLog(@"keeping move to %0.3f, %0.3f", points[0].x, points[0].y); } else { // NSLog(@"discarding move to %0.3f, %0.3f", points[0].x, points[0].y); } case .lineToBezierPathElement: let p0 = points[0] if (fabs(last.x - p0.x) > epsilon) || (fabs(last.y - p0.y) > epsilon) { newPath.line(to: p0) last = p0 } case .curveToBezierPathElement: newPath.curve(to: points[2], controlPoint1: points[0], controlPoint2: points[1]) last = points[2] case .closePathBezierPathElement: newPath.close() } } return newPath } static func intersection(p0_x: CGFloat, p0_y: CGFloat, p1_x: CGFloat, p1_y: CGFloat, p2_x: CGFloat, p2_y: CGFloat, p3_x: CGFloat, p3_y: CGFloat) -> NSPoint? { let s1_x = p1_x - p0_x let s1_y = p1_y - p0_y let s2_x = p3_x - p2_x let s2_y = p3_y - p2_y let s = (-s1_y * (p0_x - p2_x) + s1_x * (p0_y - p2_y)) / (-s2_x * s1_y + s1_x * s2_y) let t = ( s2_x * (p0_y - p2_y) - s2_y * (p0_x - p2_x)) / (-s2_x * s1_y + s1_x * s2_y) if (s >= 0) && (s <= 1) && (t >= 0) && (t <= 1) { let x = p0_x + (t * s1_x) let y = p0_y + (t * s1_y) return NSPoint(x: x, y: y) } return nil } static func intersection(p0: NSPoint, p1: NSPoint, x: CGFloat) -> NSPoint? { let big: CGFloat = 1e20 return intersection(p0_x: p0.x, p0_y: p0.y, p1_x: p1.x, p1_y: p1.y, p2_x: x, p2_y: -big, p3_x: x, p3_y: big) } static func slice(p0: CGPoint, p1: CGPoint, x0: CGFloat, x1: CGFloat) -> NSBezierPath { let newPath = NSBezierPath() if (p1.x <= x0) || (p0.x >= x1) { // line is completely outside slice area newPath.move(to: p0) newPath.line(to: p1) } else if (x0 <= p0.x) && (p1.x <= x1) { // line is completely inside slice area } else { // only handle horizontal line splitting if (p0.x < x0) && (p1.x > x0) && (p1.x <= x1) { // line only crosses x0 // split line at x0. keep left segment if let p = intersection(p0: p0, p1: p1, x: x0) { newPath.move(to: p0) newPath.line(to: p) } else { NSLog("should not happen") } } else if (p0.x < x0) && (p1.x > x1) { // line crosses both x0 and x1 // split line at x0 and x1. keep left and right segments if let pa = intersection(p0: p0, p1: p1, x: x0), let pb = intersection(p0: p0, p1: p1, x: x1) { newPath.move(to: p0) newPath.line(to: pa) newPath.move(to: pb) newPath.line(to: p1) } else { NSLog("should not happen") } } else if (x0 <= p0.x) && (p0.x < x1) && (x1 < p1.x) { // line only crosses x1 // split line at x1. keep right segment if let p = intersection(p0: p0, p1: p1, x: x1) { newPath.move(to: p) newPath.line(to: p1) } else { NSLog("should not happen") } } else { NSLog("should not happen") } } return newPath } static func slice(pa: CGPoint, pb: CGPoint, x0: CGFloat, x1: CGFloat) -> NSBezierPath { if pa.x < pb.x { return Geometry.slice(p0: pa, p1: pb, x0: x0, x1: x1) } else { let path = Geometry.slice(p0: pb, p1: pa, x0: x0, x1: x1) var subpaths = Geometry.segments(path: path) for i in 0 ..< subpaths.count { subpaths[i] = subpaths[i].reversed } subpaths.reverse() let reversed = NSBezierPath() for subpath in subpaths { reversed.append(subpath) } return reversed } } static func slice(path: NSBezierPath, x0: CGFloat, x1: CGFloat) -> NSBezierPath { var last = NSPoint(x: 0, y: 0) let newPath = NSBezierPath() for i in 0 ..< path.elementCount { var points: [NSPoint] = [NSPoint(x: 0, y: 0), NSPoint(x: 0, y: 0), NSPoint(x: 0, y: 0)] let kind = path.element(at: i, associatedPoints: &points) switch (kind) { case .moveToBezierPathElement: last = points[0] case .lineToBezierPathElement: let path = slice(pa: last, pb: points[0], x0: x0, x1: x1) if !path.isEmpty { newPath.append(path) last = lastPoint(path: path) } else { last = points[0] } case .curveToBezierPathElement: let p = points[2] if (p.x < x0) || (p.x > x1) { newPath.curve(to: points[2], controlPoint1: points[0], controlPoint2: points[1]) last = points[2] } case .closePathBezierPathElement: break } } return join(path: newPath) } static func segments(path: NSBezierPath) -> [NSBezierPath] { var paths: [NSBezierPath] = [] var newPath = NSBezierPath() for i in 0 ..< path.elementCount { var points: [NSPoint] = [NSPoint(x: 0, y: 0), NSPoint(x: 0, y: 0), NSPoint(x: 0, y: 0)] let kind = path.element(at: i, associatedPoints: &points) switch (kind) { case .moveToBezierPathElement: if !newPath.isEmpty { paths.append(newPath) newPath = NSBezierPath() } newPath.move(to: points[0]) case .lineToBezierPathElement: newPath.line(to: points[0]) case .curveToBezierPathElement: newPath.curve(to: points[2], controlPoint1: points[0], controlPoint2: points[1]) case .closePathBezierPathElement: newPath.close() break } } if !newPath.isEmpty { paths.append(newPath) } return paths } // Take two concentric continuous curves and split off the left and right segments (removing the segments in the middle). Return: // path - the complete path made by joining the resulting left and right segments (as two subpaths) // leftOuterPath - the left outer path with points from min y to max y // leftInnerPath - the left inner path with points from min y to max y // rightInnerPath - the right inner path with points from min y to max y // rightOuterPath - the right outer path with points from min y to max y static func split(path1: NSBezierPath, path2: NSBezierPath, x0: CGFloat, x1: CGFloat) -> (path: NSBezierPath, leftOuterPath: NSBezierPath, leftInnerPath: NSBezierPath, rightInnerPath: NSBezierPath, rightOuterPath: NSBezierPath) { let sliced1 = Geometry.slice(path: path1, x0: x0, x1: x1) let segments1 = Geometry.segments(path: Geometry.join(path: sliced1)) let segs1 = Geometry.combine(paths: segments1) let ordered1 = Geometry.orderByY(paths: segs1) let sorted1 = Geometry.sortByX(paths: ordered1) let sliced2 = Geometry.slice(path: path2, x0: x0, x1: x1) let segments2 = Geometry.segments(path: Geometry.join(path: sliced2)) let segs2 = Geometry.combine(paths: segments2) let ordered2 = Geometry.orderByY(paths: segs2) let sorted2 = Geometry.sortByX(paths: ordered2) let final = NSBezierPath() for i in 0 ..< sorted1.count { let a = sorted1[i].reversed let b = sorted2[i] let b0 = Geometry.firstPoint(path: b) a.line(to: b0) let path = Geometry.combine(paths: [a, b])[0] path.close() final.append(path) } return (path: final, leftOuterPath: sorted1[0], leftInnerPath: sorted2[0], rightInnerPath: sorted2[1], rightOuterPath: sorted1[1]) } static func bezierPathForWires(wires: [Board.Wire]) -> NSBezierPath { let epsilon = CGFloat(0.001) var remaining = wires let path = NSBezierPath() let current = remaining.removeFirst() // NSLog(@"+ %0.3f, %0.3f - %0.3f, %0.3f", current.x1, current.y1, current.x2, current.y2); path.append(current.bezierPath()) var cx = current.x2 var cy = current.y2 while remaining.count > 0 { var found = false for index in (0 ..< remaining.count).reversed() { let candidate = remaining[index] if ((fabs(candidate.x1 - cx) < epsilon) && (fabs(candidate.y1 - cy) < epsilon)) { // NSLog(@"> %0.3f, %0.3f - %0.3f, %0.3f", candidate.x1, candidate.y1, candidate.x2, candidate.y2); remaining.remove(at: index) path.append(candidate.bezierPath()) cx = candidate.x2 cy = candidate.y2 found = true break } if ((fabs(candidate.x2 - cx) < epsilon) && (fabs(candidate.y2 - cy) < epsilon)) { // NSLog(@"< %0.3f, %0.3f - %0.3f, %0.3f", candidate.x1, candidate.y1, candidate.x2, candidate.y2); remaining.remove(at: index) path.append(candidate.bezierPath().reversed) cx = candidate.x1 cy = candidate.y1 found = true break } } if (!found) { break; } } return Geometry.join(path: path) } }
39.271462
233
0.492201
d6a7bff37feb798e34273fd1294197dfd48d460f
3,560
sql
SQL
githubmysearch.sql
AmandaIvoniak/GitHubMySearch
0bf1ecbe6c009643ab5ae676b7977604cb038cd2
[ "MIT" ]
1
2020-01-15T01:06:15.000Z
2020-01-15T01:06:15.000Z
githubmysearch.sql
AmandaIvoniak/GitHubMySearch
0bf1ecbe6c009643ab5ae676b7977604cb038cd2
[ "MIT" ]
null
null
null
githubmysearch.sql
AmandaIvoniak/GitHubMySearch
0bf1ecbe6c009643ab5ae676b7977604cb038cd2
[ "MIT" ]
null
null
null
-- phpMyAdmin SQL Dump -- version 4.8.3 -- https://www.phpmyadmin.net/ -- -- Host: 127.0.0.1 -- Generation Time: 17-Jan-2020 às 07:17 -- Versão do servidor: 10.1.36-MariaDB -- versão do PHP: 7.2.11 SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; SET AUTOCOMMIT = 0; START TRANSACTION; SET time_zone = "+00:00"; /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!40101 SET NAMES utf8mb4 */; -- -- Database: `githubmysearch` -- CREATE DATABASE IF NOT EXISTS `githubmysearch` DEFAULT CHARACTER SET latin1 COLLATE latin1_swedish_ci; USE `githubmysearch`; -- -------------------------------------------------------- -- -- Estrutura da tabela `repository` -- CREATE TABLE `repository` ( `id_tablerepository` int(11) NOT NULL, `id_rep` int(11) NOT NULL, `name` varchar(255) NOT NULL, `description` varchar(255) NOT NULL, `stars` int(11) NOT NULL, `updateDate` date NOT NULL, `id_user` int(11) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -------------------------------------------------------- -- -- Estrutura da tabela `tags` -- CREATE TABLE `tags` ( `id_tag` int(11) NOT NULL, `name_tag` varchar(255) NOT NULL, `id_user` int(11) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -------------------------------------------------------- -- -- Estrutura da tabela `tagsrepository` -- CREATE TABLE `tagsrepository` ( `id_repositoryTag` int(11) NOT NULL, `id_tag` int(11) NOT NULL, `id_rep` int(11) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -------------------------------------------------------- -- -- Estrutura da tabela `users` -- CREATE TABLE `users` ( `id_user` int(11) NOT NULL, `name_user` varchar(225) NOT NULL, `email` varchar(225) NOT NULL, `password` varchar(225) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Indexes for dumped tables -- -- -- Indexes for table `repository` -- ALTER TABLE `repository` ADD PRIMARY KEY (`id_tablerepository`); -- -- Indexes for table `tags` -- ALTER TABLE `tags` ADD PRIMARY KEY (`id_tag`), ADD KEY `ids_tags_users` (`id_user`); -- -- Indexes for table `tagsrepository` -- ALTER TABLE `tagsrepository` ADD PRIMARY KEY (`id_repositoryTag`), ADD KEY `ids_tags_repository` (`id_tag`); -- -- Indexes for table `users` -- ALTER TABLE `users` ADD PRIMARY KEY (`id_user`); -- -- AUTO_INCREMENT for dumped tables -- -- -- AUTO_INCREMENT for table `repository` -- ALTER TABLE `repository` MODIFY `id_tablerepository` int(11) NOT NULL AUTO_INCREMENT; -- -- AUTO_INCREMENT for table `tags` -- ALTER TABLE `tags` MODIFY `id_tag` int(11) NOT NULL AUTO_INCREMENT; -- -- AUTO_INCREMENT for table `tagsrepository` -- ALTER TABLE `tagsrepository` MODIFY `id_repositoryTag` int(11) NOT NULL AUTO_INCREMENT; -- -- AUTO_INCREMENT for table `users` -- ALTER TABLE `users` MODIFY `id_user` int(11) NOT NULL AUTO_INCREMENT; -- -- Constraints for dumped tables -- -- -- Limitadores para a tabela `tags` -- ALTER TABLE `tags` ADD CONSTRAINT `ids_tags_users` FOREIGN KEY (`id_user`) REFERENCES `users` (`id_user`); -- -- Limitadores para a tabela `tagsrepository` -- ALTER TABLE `tagsrepository` ADD CONSTRAINT `ids_tags_repository` FOREIGN KEY (`id_tag`) REFERENCES `tags` (`id_tag`); COMMIT; /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
22.531646
102
0.66236
9d1b7102933367ab1878c79f6c1620944baffacb
143
ps1
PowerShell
Test-CMDRunAsWaitForExit.ps1
craiglandis/scripts
b50b8a532f5188a1a6716d82417e3c02ea9de553
[ "MIT" ]
1
2016-04-04T11:33:37.000Z
2016-04-04T11:33:37.000Z
Test-CMDRunAsWaitForExit.ps1
craiglandis/scripts
b50b8a532f5188a1a6716d82417e3c02ea9de553
[ "MIT" ]
null
null
null
Test-CMDRunAsWaitForExit.ps1
craiglandis/scripts
b50b8a532f5188a1a6716d82417e3c02ea9de553
[ "MIT" ]
1
2022-03-27T13:57:14.000Z
2022-03-27T13:57:14.000Z
$process = Start-Process -FilePath "$env:SystemRoot\System32\cmd.exe" -ArgumentList "/c echo foo" -PassThru -Verb RunAs $process.WaitForExit()
47.666667
119
0.762238
874dee4d2fc1b49048226f859c9a85c6bb003b38
969
swift
Swift
base-app-ios/presentation/foundation/SyncScreens.swift
FuckBoilerplate/base_app_ios
3d3ee8b9d0705b306547ab03487471cc930c6da5
[ "Apache-2.0" ]
20
2016-04-11T19:40:08.000Z
2021-03-03T13:24:42.000Z
base-app-ios/presentation/foundation/SyncScreens.swift
FuckBoilerplate/base_app_ios
3d3ee8b9d0705b306547ab03487471cc930c6da5
[ "Apache-2.0" ]
5
2016-09-19T15:18:29.000Z
2017-09-22T10:38:08.000Z
base-app-ios/presentation/foundation/SyncScreens.swift
FuckBoilerplate/base_app_ios
3d3ee8b9d0705b306547ab03487471cc930c6da5
[ "Apache-2.0" ]
2
2016-08-03T06:28:35.000Z
2016-08-10T16:49:09.000Z
// // SyncScreens.swift // base-app-ios // // Created by Roberto Frontado on 4/22/16. // Copyright © 2016 Roberto Frontado. All rights reserved. // protocol SyncScreensMatcher { func matchesTarget(_ key: String) -> Bool } class SyncScreens { private var pendingScreens: [String]! init() { pendingScreens = [] } func addScreen(screen: String) { if !pendingScreens.contains(screen) { pendingScreens.append(screen) } } func needToSync(matcher: SyncScreensMatcher) -> Bool { var needToSync = false var index = 0 for i in 0..<pendingScreens.count { if matcher.matchesTarget(pendingScreens[i]) { needToSync = true index = i break } } if needToSync { pendingScreens.removeObject(index) } return needToSync } }
20.617021
59
0.537668
93ddec0d7ef29478cefd9f597412262223794375
5,299
cs
C#
Events/ReadyEvent.cs
Erisa/MicrosoftBot
fbdda39f7fb95d747edded4a690e45155f85a43e
[ "MIT" ]
5
2020-08-06T03:45:49.000Z
2020-12-11T14:10:49.000Z
Events/ReadyEvent.cs
Erisa/MicrosoftBot
fbdda39f7fb95d747edded4a690e45155f85a43e
[ "MIT" ]
3
2020-12-03T00:50:30.000Z
2020-12-04T16:24:15.000Z
Events/ReadyEvent.cs
Erisa/MicrosoftBot
fbdda39f7fb95d747edded4a690e45155f85a43e
[ "MIT" ]
4
2020-08-20T18:00:34.000Z
2020-12-03T00:43:30.000Z
using static Cliptok.Program; namespace Cliptok.Events { public class ReadyEvent { public static async Task OnReady(DiscordClient client, ReadyEventArgs _) { Task.Run(async () => { client.Logger.LogInformation(CliptokEventID, "Logged in as {user}", $"{client.CurrentUser.Username}#{client.CurrentUser.Discriminator}"); if (cfgjson.ErrorLogChannelId == 0) { errorLogChannel = await client.GetChannelAsync(cfgjson.HomeChannel); } else { errorLogChannel = await client.GetChannelAsync(cfgjson.ErrorLogChannelId); await errorLogChannel.SendMessageAsync($"{cfgjson.Emoji.Connected} {discord.CurrentUser.Username} has connected to Discord!"); } if (cfgjson.UsernameAPILogChannel != 0) usernameAPILogChannel = await client.GetChannelAsync(cfgjson.UsernameAPILogChannel); if (cfgjson.MysteryLogChannelId == 0) mysteryLogChannel = errorLogChannel; else { Console.Write(cfgjson.MysteryLogChannelId); mysteryLogChannel = await client.GetChannelAsync(cfgjson.MysteryLogChannelId); } }); } public static async Task OnStartup(DiscordClient client) { logChannel = await discord.GetChannelAsync(cfgjson.LogChannel); userLogChannel = await discord.GetChannelAsync(cfgjson.UserLogChannel); badMsgLog = await discord.GetChannelAsync(cfgjson.InvestigationsChannelId); homeGuild = await discord.GetGuildAsync(cfgjson.ServerID); Tasks.PunishmentTasks.CheckMutesAsync(); Tasks.PunishmentTasks.CheckBansAsync(); Tasks.ReminderTasks.CheckRemindersAsync(); Tasks.RaidmodeTasks.CheckRaidmodeAsync(cfgjson.ServerID); string commitHash = ""; string commitMessage = ""; string commitTime = ""; if (File.Exists("CommitHash.txt")) { using var sr = new StreamReader("CommitHash.txt"); commitHash = sr.ReadToEnd(); } if (Environment.GetEnvironmentVariable("RAILWAY_GIT_COMMIT_SHA") != null) { commitHash = Environment.GetEnvironmentVariable("RAILWAY_GIT_COMMIT_SHA"); commitHash = commitHash[..Math.Min(commitHash.Length, 7)]; } if (string.IsNullOrWhiteSpace(commitHash)) { commitHash = "dev"; } if (File.Exists("CommitMessage.txt")) { using var sr = new StreamReader("CommitMessage.txt"); commitMessage = sr.ReadToEnd(); } if (Environment.GetEnvironmentVariable("RAILWAY_GIT_COMMIT_MESSAGE") != null) { commitMessage = Environment.GetEnvironmentVariable("RAILWAY_GIT_COMMIT_MESSAGE"); } if (string.IsNullOrWhiteSpace(commitMessage)) { commitMessage = "N/A (Only available when built with Docker)"; } if (File.Exists("CommitTime.txt")) { using var sr = new StreamReader("CommitTime.txt"); commitTime = sr.ReadToEnd(); } if (string.IsNullOrWhiteSpace(commitTime)) { commitTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss zzz"); } bool listSuccess = false; if (cfgjson.GitListDirectory != null && cfgjson.GitListDirectory != "") { ShellResult finishedShell = RunShellCommand($"cd Lists/{cfgjson.GitListDirectory} && git pull"); string result = Regex.Replace(finishedShell.result, "ghp_[0-9a-zA-Z]{36}", "ghp_REDACTED").Replace(Environment.GetEnvironmentVariable("CLIPTOK_TOKEN"), "REDACTED"); if (finishedShell.proc.ExitCode != 0) { listSuccess = false; client.Logger.LogError(eventId: CliptokEventID, "Error updating lists:\n{result}", result); } else { UpdateLists(); client.Logger.LogInformation(eventId: CliptokEventID, "Success updating lists:\n{result}", result); listSuccess = true; } } var cliptokChannel = await client.GetChannelAsync(cfgjson.HomeChannel); cliptokChannel.SendMessageAsync($"{cfgjson.Emoji.On} {discord.CurrentUser.Username} started successfully!\n\n" + $"**Version**: `{commitHash.Trim()}`\n" + $"**Version timestamp**: `{commitTime}`\n**Framework**: `{RuntimeInformation.FrameworkDescription}`\n" + $"**Platform**: `{RuntimeInformation.OSDescription}`\n" + $"**Library**: `DSharpPlus {discord.VersionString}`\n" + $"**List update success**: `{listSuccess}`\n\n" + $"Most recent commit message:\n" + $"```\n" + $"{commitMessage}\n" + $"```"); } } }
39.842105
180
0.558407
7512ae56eae03f07c5e23a2fff08e579e39e2531
11,601
css
CSS
Tpl/Goal/dedecms.css
Asher0802/Power
319416a5c86639985872d70d50057773a54c8762
[ "BSD-2-Clause" ]
null
null
null
Tpl/Goal/dedecms.css
Asher0802/Power
319416a5c86639985872d70d50057773a54c8762
[ "BSD-2-Clause" ]
null
null
null
Tpl/Goal/dedecms.css
Asher0802/Power
319416a5c86639985872d70d50057773a54c8762
[ "BSD-2-Clause" ]
null
null
null
 /*---------- base ---------*/ a{ color:#256EB1; text-decoration:none; } a:hover{ color:#ba2636; text-decoration:underline; } ul{ list-style:none; } input,select,button{ font:12px Verdana,Arial,Tahoma; vertical-align:middle; } .pright .infos_userinfo { margin-bottom: 0px; } .mt1{/* ( margin-top * 1 ) */ margin-top:8px; } .pright .mt1{ margin-top:0px; } .mt2{/* ( margin-top * 2 ) */ margin-top:16px; } .clear{ overflow:hidden; } .fs-12{ font-size:12px; } .fc-f60{ color:#F60; } .fc-f90{ color:#F90; } .clr{ clear:both; } .ipt-txt{ line-height:15px; padding:4px 5px; border-width:1px; border-style:solid; border-color:#666 #BBB #BBB #666; font-size:12px; margin-right:2px; } .nb{ line-height:20x; padding:1px 2px; border-width:1px; border-style:solid; border-color:#666 #BBB #BBB #666; font-size:12px; margin-right:2px } .btn-1{ width:56px; height:24px; border:none; background:url(../../Public/Images/comm/comm/comm-bt.gif) no-repeat; line-height:25px; letter-spacing:1px; cursor:pointer; overflow:hidden; color:#585858; } .btn-2{ width:70px; height:25px; border:none; background:url(../../Public/Images/comm/btn-bg2.gif) left top no-repeat; line-height:25px; overflow:hidden; color:#444; margin-right:2px; cursor:pointer; } /*---------- frame ---------*/ /*---------- frame : header ---------*/ .header{ width:100%; width:960px; margin:auto; overflow:hidden; } .header .header_top{ height:25px; line-height:25px; border-bottom:1px solid #DBDBDB; color:#676767; } .header .time{ float:left; padding-left:10px; } .header .toplinks{ float:right; } .header .toplinks a{ margin:0 5px; } .header .toplinks span{ margin-left:15px; } .header .toplinks span a{ margin:0 2px; } .header .search { overflow:hidden; } .header a{ color:#777; } .header a:hover{ color:#ff3333; text-decoration:none; } .header .top{ clear:both; overflow:hidden; margin-top:10px; } .header .title{ float:left; padding-left:10px; } .header .title h1 a{ width:216px; height:54px; display:block; overflow:hidden; } .header .banner{ width:500px; height:60px; float:left; margin-left:20px; overflow:hidden; } .header .banner img{ width:500px; height:60px; display:block; } .header .banner2{ width:200px; height:60px; float:left; margin-left:10px; overflow:hidden; } .header .banner2 img{ width:200px; height:60px; display:block; } .header .welcome{ float:right; margin-top:20px; padding-right:10px; color:#999; } .header .welcome a{ margin:0px 3px; } /*----- 新版导航菜单位置的样式 -------*/ .header .nav { } /*-------- 圆角模型 ---------*/ .module, .module .mid { overflow:hidden; } .module .top .t_l, .module .bottom .b_l { float:left; overflow:hidden; } .module .top .t_r, .module .bottom .b_r { float:right; overflow:hidden; } .module .top em { float:left; font-size:13px; font-weight:bold; font-family:Arial, Helvetica, sans-serif; margin-left: 5px; } .module .top em a:link, .module .top em a:visited { font-size:13px; font-weight:bold; } .module .top span { } .module .top strong { cursor:pointer; float:right; font-weight:normal; margin-right:4px; } .module .mid .m_l, .module .mid .m_r { overflow:hidden; } .module .mid .content { overflow:hidden; height:100%; clear: both; margin-right: 8px; margin-left: 8px; padding-top: 8px;/*padding-bottom: 10px;*/ } .module .top, .module .top .t_l, .module .top .t_r, .module .bottom, .module .bottom .b_l, .module .bottom .b_r { background-image: url("../../Public/Images/comm/comm/green_skin.png"); } /*------ 主色 -------*/ .blue .top { background-position: 0 -72px; background-repeat: repeat-x; height: 70px; } .blue .top .t_l { background-position: 0 0; background-repeat: no-repeat; height: 70px; width: 5px; } .blue .top .t_r { background-position: -6px 0; background-repeat: no-repeat; height: 70px; width: 5px; } /* --------- 导航 ----------------*/ .w963 { width:960px; } #navMenu { width:915px; overflow:hidden; height: 28px; padding:8px 0 0 15px; } #navMenu ul { float:left; height: 22px; } #navMenu ul li { float:left; height: 22px; margin-right: 10px; margin-left: -3px; padding-left: 10px; } #navMenu ul li a { color: #FFF; height: 22px; text-decoration:none; display: inline-block; position: relative; } #navMenu ul li span { cursor:pointer; display:inline-block; height:22px; line-height:20px; margin:0 0 0 5px; padding:0 5px 0 0; text-align:center; vertical-align:middle; font-weight:bold; color:#ebf5e9; } #navMenu ul li.hover { padding-top:0; } #navMenu ul li.hover a { background:url(../../Public/Images/comm/comm/green_skin.png) 0 -152px no-repeat; display: inline-block; position: relative; } #navMenu ul li.hover span { background:url(../../Public/Images/comm/comm/green_skin.png) no-repeat right top; cursor:pointer; display:inline-block; height:22px; line-height:20px; margin:0 0 0 5px; padding:0 5px 0 0; text-align:center; vertical-align:middle; } #navMenu ul li a.hover, #navMenu ul li a:hover { background:url(../../Public/Images/comm/comm/green_skin.png) 0 -152px no-repeat; text-decoration:none; display: inline-block; position: relative; } #navMenu ul li a.hover span, #navMenu ul li a:hover span { background:url(../../Public/Images/comm/comm/green_skin.png) no-repeat right top; cursor:pointer; display:inline-block; height:22px; line-height:20px; margin:0 0 0 5px; padding:0 5px 0 0; text-align:center; vertical-align:middle; } /*-------- 下拉菜单 --------------*/ .dropMenu { position:absolute; top: 0; z-index:100; width: 120px; visibility: hidden; filter: progid:DXImageTransform.Microsoft.Shadow(color=#CACACA, direction=135, strength=4); margin-top: -1px; border: 1px solid #93E1EB; border-top: 0px solid #3CA2DC; background-color: #FFF; background:url(../../Public/Images/comm/comm/mmenubg.gif); padding-top:6px; padding-bottom:6px; } .dropMenu li { margin-top:2px; margin-bottom:4px; padding-left:6px; } .dropMenu a { width: auto; display: block; color: black; padding: 2px 0 2px 1.2em; } * html .dropMenu a { width: 100%; } .dropMenu a:hover { color:red; text-decoration: underline; } /*------ //搜索框 ---------*/ .search-keyword { width:210px; height:18px; padding-top:2px; padding-left:6px; border:0px; border:#badaa1 solid 1px; background: #FFF; color:#444; } .search-submit { cursor:pointer; width:68px; height:22px; font-size:0px; color:#fafafa; border:0px; background:url(../../Public/Images/comm/comm/search-bt.gif) no-repeat; } .search-option { margin-left:3px; margin-right:3px; border:#badaa1 solid 1px; height:22px; } .w963 .search{ padding-left:10px; line-height:32px; } .w963 .form h4 { display:none; } .w963 .form { float:left; margin:0 10px 0 0; *margin:0 10px 0 0; _margin:5px 10px 0 0; } .w963 .tags { width:500px; overflow:hidden; } .w963 .tags h4 { float:left; margin-right: 6px; height:26px; font-size:12px; color:#777; } .w963 .tags li { float:left; margin-right: 6px; } .header .nav .end { } /*-- //End 导航菜单 --*/ /*---------- frame : channel-nav ---------*/ .channel-nav { margin-top:8px; padding-left:6px; height:24px; width:950px; overflow:hidden; } .channel-nav .sonnav { width:830px; line-height:26px; float:left; color:#256DB1; } .channel-nav .sonnav span { margin-right:10px; float:left; } .channel-nav .sonnav span a{ padding:0 4px; border:1px solid #BADAA1; height:22px; line-height:21px; background:url(../../Public/Images/comm/comm/channel_bg.png) repeat-x; display:inline-block; } .channel-nav .sonnav span a.thisclass{ border:1px solid #3aa21b; } .channel-nav .sonnav a { color:#428C5B; text-decoration:none; } .channel-nav .sonnav a:hover{ color:#287212; } .channel-nav .back{ display:block; height:22px; line-height:21px; padding-top:6px; padding-right:10px; padding-left:20px; letter-spacing:2px; float:right; background:url(../../Public/Images/comm/comm/ico-home.gif) 4px 10px no-repeat; } .channel-nav .back a{ color:#397CBE; } .channel-nav .back a:hover{ text-decoration:none; color:#777; } /*pic scroll ----------------------------------*/ .infiniteCarousel { width: 700px; position: relative; margin-left:auto; margin-right:auto; } .infiniteCarousel .wrapper { width: 640px; overflow: auto; height: 170px; margin: 0 30px; top: 0; } .infiniteCarousel ul a img { border:1px solid #E3E3E3; padding:2px; width:143px; height:106px; display:block; } .infiniteCarousel .wrapper ul { width: 625px; list-style-image:none; list-style-position:outside; list-style-type:none; margin:0; padding:0; top: 0; } .infiniteCarousel ul li { display:block; color:#6C6D61; float:left; padding: 10px 6px; height: 147px; width: 147px; text-align:center; } .infiniteCarousel ul li a, .infiniteCarousel ul li a:visited{ color:#6C6D61; } .infiniteCarousel .wrapper ul li a:hover{ text-decoration:underline; } .infiniteCarousel ul li a:hover img { border-color: #aaa; } .infiniteCarousel ul li a span{ display:block; line-height:17px; padding-top:6px; } .infiniteCarousel .arrow { display: block; height: 26px; width: 26px; text-indent: -999px; position: absolute; top: 70px; cursor: pointer; outline: 0; } .infiniteCarousel .forward { background:url(../../Public/Images/comm/green_skin.png) 0 -256px no-repeat; right: 0; } .infiniteCarousel .back { background:url(../../Public/Images/comm/green_skin.png) 0 -222px no-repeat; left: 0; } /*----------dedeinfolink ---------*/ #dedeinfolink { margin-bottom:6px; } #dedeinfolink tr td div { padding:0 5px; background:url(../../Public/Images/comm/white_bg.gif) repeat-x; margin-right:8px; } #dedeinfolink tr td { line-height:18px; } #dedeinfolink tr td.spline { font-size:1px; height:1px; line-height:1px; border-bottom:1px dashed #dedede; } #dedeinfolink tr td.iftitle { font-weight:bold; color:#428C5B; line-height:24px; border-bottom:1px dashed #dedede; } /*---------- frame : footer ---------*/ .footer{ width:960px; margin:auto; color:#999; text-align:center; margin-top:8px; padding-bottom:10px; border-top:1px solid #E5EFD6; padding-top:10px; } .footer .link{ text-align:center; padding:5px 0px; } .footer .link a{ margin:0px 5px; color:#666666; } .footer .powered{ font-size:10px; line-height:25px; } .footer .powered strong{ color:#690; } .footer .powered strong span{ color:#F93; } .footer .copyright{ color:#666666; line-height:23px; } /*换肤功能 ------------------------------------*/ #dedecms_skins{ float:right; padding:5px; width:120px; padding-right:0px; list-style:none; overflow:hidden; } #dedecms_skins li{ float:left; margin-right:5px; width:15px; height:15px; text-indent:-999px; overflow:hidden; display:block; cursor:pointer; background-image:url(../../Public/Images/comm/theme.gif); } #dedecms_skins_0{ background-position:0px 0px; } #dedecms_skins_1{ background-position:15px 0px; } #dedecms_skins_2{ background-position:35px 0px; } #dedecms_skins_3{ background-position:55px 0px; } #dedecms_skins_4{ background-position:75px 0px; } #dedecms_skins_5{ background-position:95px 0px; } #dedecms_skins_0.selected{ background-position:0px 15px !important; } #dedecms_skins_1.selected{ background-position:15px 15px !important; } #dedecms_skins_2.selected{ background-position:35px 15px !important; } #dedecms_skins_3.selected{ background-position:55px 15px !important; } #dedecms_skins_4.selected{ background-position:75px 15px !important; } #dedecms_skins_5.selected{ background-position:95px 15px !important; }
17.792945
113
0.676666
aef112e8c19ca4b48ea39b45c97397767a65f858
11,951
cs
C#
src/MQTTnet.TestApp.SimpleServer/Form1.cs
SeppPenner/MQTTnet.TestApp.SimpleServer
c9bc43a4aad8ae248663720629406e32166a870c
[ "MIT" ]
8
2020-01-15T16:50:28.000Z
2022-01-19T02:56:00.000Z
src/MQTTnet.TestApp.SimpleServer/Form1.cs
SeppPenner/MQTTnet.TestApp.SimpleServer
c9bc43a4aad8ae248663720629406e32166a870c
[ "MIT" ]
1
2020-05-12T13:42:18.000Z
2020-05-17T14:27:39.000Z
src/MQTTnet.TestApp.SimpleServer/Form1.cs
SeppPenner/MQTTnet.TestApp.SimpleServer
c9bc43a4aad8ae248663720629406e32166a870c
[ "MIT" ]
7
2020-02-15T10:44:46.000Z
2021-11-09T01:12:36.000Z
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="Form1.cs" company="Hämmer Electronics"> // Copyright (c) 2020 All rights reserved. // </copyright> // <summary> // The main form. // </summary> // -------------------------------------------------------------------------------------------------------------------- namespace MQTTnet.TestApp.SimpleServer { using System; using System.Text; using System.Timers; using System.Windows.Forms; using MQTTnet.Client.Connecting; using MQTTnet.Client.Disconnecting; using MQTTnet.Client.Options; using MQTTnet.Extensions.ManagedClient; using MQTTnet.Formatter; using MQTTnet.Protocol; using MQTTnet.Server; using Timer = System.Timers.Timer; /// <summary> /// The main form. /// </summary> public partial class Form1 : Form { /// <summary> /// The managed publisher client. /// </summary> private IManagedMqttClient managedMqttClientPublisher; /// <summary> /// The managed subscriber client. /// </summary> private IManagedMqttClient managedMqttClientSubscriber; /// <summary> /// The MQTT server. /// </summary> private IMqttServer mqttServer; /// <summary> /// The port. /// </summary> private string port = "1883"; /// <summary> /// Initializes a new instance of the <see cref="Form1"/> class. /// </summary> public Form1() { this.InitializeComponent(); var timer = new Timer { AutoReset = true, Enabled = true, Interval = 1000 }; timer.Elapsed += this.Timer_Elapsed; } /// <summary> /// Handles the publisher connected event. /// </summary> /// <param name="x">The MQTT client connected event args.</param> private static void OnPublisherConnected(MqttClientConnectedEventArgs x) { // ReSharper disable LocalizableElement MessageBox.Show("Connected", "ConnectHandler", MessageBoxButtons.OK, MessageBoxIcon.Information); } /// <summary> /// Handles the publisher disconnected event. /// </summary> /// <param name="x">The MQTT client disconnected event args.</param> private static void OnPublisherDisconnected(MqttClientDisconnectedEventArgs x) { // ReSharper disable LocalizableElement MessageBox.Show("Disconnected", "ConnectHandler", MessageBoxButtons.OK, MessageBoxIcon.Information); } /// <summary> /// The method that handles the button click to generate a message. /// </summary> /// <param name="sender">The sender.</param> /// <param name="e">The event args.</param> private void ButtonGeneratePublishedMessage_Click(object sender, EventArgs e) { var message = $"{{\"dt\":\"{DateTime.Now.ToLongDateString()} {DateTime.Now.ToLongTimeString()}\"}}"; this.TextBoxPublish.Text = message; } /// <summary> /// The method that handles the button click to publish a message. /// </summary> /// <param name="sender">The sender.</param> /// <param name="e">The event args.</param> private async void ButtonPublish_Click(object sender, EventArgs e) { try { var payload = Encoding.UTF8.GetBytes(this.TextBoxPublish.Text); var message = new MqttApplicationMessageBuilder() .WithTopic(this.TextBoxTopic.Text.Trim()).WithPayload(payload).WithQualityOfServiceLevel(MqttQualityOfServiceLevel.AtLeastOnce).WithRetainFlag().Build(); if (this.managedMqttClientPublisher != null) { await this.managedMqttClientPublisher.PublishAsync(message); } } catch (Exception ex) { MessageBox.Show(ex.Message, "Error Occurs", MessageBoxButtons.OK, MessageBoxIcon.Error); } } /// <summary> /// The method that handles the button click to start the publisher. /// </summary> /// <param name="sender">The sender.</param> /// <param name="e">The event args.</param> private async void ButtonPublisherStart_Click(object sender, EventArgs e) { var mqttFactory = new MqttFactory(); var tlsOptions = new MqttClientTlsOptions { UseTls = false, IgnoreCertificateChainErrors = true, IgnoreCertificateRevocationErrors = true, AllowUntrustedCertificates = true }; var options = new MqttClientOptions { ClientId = "ClientPublisher", ProtocolVersion = MqttProtocolVersion.V311, ChannelOptions = new MqttClientTcpOptions { Server = "localhost", Port = int.Parse(this.TextBoxPort.Text.Trim()), TlsOptions = tlsOptions } }; if (options.ChannelOptions == null) { throw new InvalidOperationException(); } options.CleanSession = true; options.KeepAlivePeriod = TimeSpan.FromSeconds(5); this.managedMqttClientPublisher = mqttFactory.CreateManagedMqttClient(); this.managedMqttClientPublisher.UseApplicationMessageReceivedHandler(this.HandleReceivedApplicationMessage); this.managedMqttClientPublisher.ConnectedHandler = new MqttClientConnectedHandlerDelegate(OnPublisherConnected); this.managedMqttClientPublisher.DisconnectedHandler = new MqttClientDisconnectedHandlerDelegate(OnPublisherDisconnected); await this.managedMqttClientPublisher.StartAsync( new ManagedMqttClientOptions { ClientOptions = options }); } /// <summary> /// The method that handles the button click to stop the publisher. /// </summary> /// <param name="sender">The sender.</param> /// <param name="e">The event args.</param> private async void ButtonPublisherStop_Click(object sender, EventArgs e) { if (this.managedMqttClientPublisher == null) { return; } await this.managedMqttClientPublisher.StopAsync(); this.managedMqttClientPublisher = null; } /// <summary> /// The method that handles the button click to start the server. /// </summary> /// <param name="sender">The sender.</param> /// <param name="e">The event args.</param> private async void ButtonServerStart_Click(object sender, EventArgs e) { if (this.mqttServer != null) { return; } var storage = new JsonServerStorage(); storage.Clear(); this.mqttServer = new MqttFactory().CreateMqttServer(); var options = new MqttServerOptions(); options.DefaultEndpointOptions.Port = int.Parse(this.TextBoxPort.Text); options.Storage = storage; options.EnablePersistentSessions = true; try { await this.mqttServer.StartAsync(options); } catch (Exception ex) { MessageBox.Show(ex.Message, "Error Occurs", MessageBoxButtons.OK, MessageBoxIcon.Error); await this.mqttServer.StopAsync(); this.mqttServer = null; } } /// <summary> /// The method that handles the button click to stop the server. /// </summary> /// <param name="sender">The sender.</param> /// <param name="e">The event args.</param> private async void ButtonServerStop_Click(object sender, EventArgs e) { if (this.mqttServer == null) { return; } await this.mqttServer.StopAsync(); this.mqttServer = null; } /// <summary> /// The method that handles the button click to start the subscriber. /// </summary> /// <param name="sender">The sender.</param> /// <param name="e">The event args.</param> private async void ButtonSubscriberStart_Click(object sender, EventArgs e) { var options = new ManagedMqttClientOptionsBuilder().WithAutoReconnectDelay(TimeSpan.FromSeconds(5)) .WithClientOptions(new MqttClientOptionsBuilder().WithClientId("ClientSubscriber").WithTcpServer("localhost", int.Parse(this.TextBoxPort.Text)).WithTls().Build()).Build(); this.managedMqttClientSubscriber = new MqttFactory().CreateManagedMqttClient(); this.managedMqttClientSubscriber.UseApplicationMessageReceivedHandler(this.HandleReceivedApplicationMessage); await this.managedMqttClientSubscriber.SubscribeAsync(new MqttTopicFilterBuilder().WithTopic(this.TextBoxTopic.Text.Trim()).Build()); await this.managedMqttClientSubscriber.StartAsync(options); } /// <summary> /// Handles the received application message event. /// </summary> /// <param name="eventArgs">The event args.</param> private void HandleReceivedApplicationMessage(MqttApplicationMessageReceivedEventArgs eventArgs) { var item = $"Timestamp: {DateTime.Now:O} | Topic: {eventArgs.ApplicationMessage.Topic} | Payload: {eventArgs.ApplicationMessage.ConvertPayloadToString()} | QoS: {eventArgs.ApplicationMessage.QualityOfServiceLevel}"; this.BeginInvoke((MethodInvoker)delegate { this.TextBoxSubscriber.Text = item + Environment.NewLine + this.TextBoxSubscriber.Text; }); } /// <summary> /// The method that handles the text changes in the text box. /// </summary> /// <param name="sender">The sender.</param> /// <param name="e">The event args.</param> private void TextBoxPort_TextChanged(object sender, EventArgs e) { // ReSharper disable once StyleCop.SA1126 if (int.TryParse(this.TextBoxPort.Text, out _)) { this.port = this.TextBoxPort.Text.Trim(); } else { this.TextBoxPort.Text = this.port; this.TextBoxPort.SelectionStart = this.TextBoxPort.Text.Length; this.TextBoxPort.SelectionLength = 0; } } /// <summary> /// The method that handles the timer events. /// </summary> /// <param name="sender">The sender.</param> /// <param name="e">The event args.</param> private void Timer_Elapsed(object sender, ElapsedEventArgs e) { this.BeginInvoke( (MethodInvoker)delegate { // Server this.TextBoxPort.Enabled = this.mqttServer == null; this.ButtonServerStart.Enabled = this.mqttServer == null; this.ButtonServerStop.Enabled = this.mqttServer != null; // Publisher this.ButtonPublisherStart.Enabled = this.managedMqttClientPublisher == null; this.ButtonPublisherStop.Enabled = this.managedMqttClientPublisher != null; // Subscriber this.ButtonSubscriberStart.Enabled = this.managedMqttClientSubscriber == null; this.ButtonSubscriberStop.Enabled = this.managedMqttClientSubscriber != null; }); } } }
39.055556
227
0.576437
da55fc3568c57d33da16b1440b6bd14f142d245f
1,997
php
PHP
views/show/type-coin/wmz.php
codetoansai/basic
11d36cb133cfe5ed5e542811e2317a793a9a6010
[ "BSD-3-Clause" ]
2
2017-09-11T08:59:08.000Z
2018-01-02T07:28:05.000Z
views/show/type-coin/wmz.php
codetoansai/basic
11d36cb133cfe5ed5e542811e2317a793a9a6010
[ "BSD-3-Clause" ]
null
null
null
views/show/type-coin/wmz.php
codetoansai/basic
11d36cb133cfe5ed5e542811e2317a793a9a6010
[ "BSD-3-Clause" ]
null
null
null
WMZ <br><br> <table> <tr> <th> Tên website </th> <th> Mức </th> <th> Giá mua </th> <th> Giá bán </th> </tr> <!-- <tr> <td> <a href="https://exchangeno1.com/" target="_blank">Exchangeno1.com</a> </td> <td> </td> <td> <p id="exchange_wmz_buy"></p> </td> <td> <p id="exchange_wmz_sell"></p> </td> </tr> --> <tr> <td> <a href="https://mmo4me.com/" target="_blank">Mmo4me.com</a> </td> <td> </td> <td> <p id="mmo4me_wmz_buy"></p> </td> <td> <p id="mmo4me_wmz_sell"></p> </td> </tr> <tr> <td> <a href="https://santienao.com/" target="_blank">Santienao.com</a> </td> <td> </td> <td> <p id="santienao_wmz_buy"></p> </td> <td> <p id="santienao_wmz_sell"></p> </td> </tr> <tr> <td> <a href="http://muabantienao.com/" target="_blank">Muabantienao.com</a> </td> <td> </td> <td> <p id="muabantienao_wmz_buy"></p> </td> <td> <p id="muabantienao_wmz_sell"></p> </td> </tr> <tr> <td> <a href="https://banwmz.com/" target="_blank">Banwmz.com</a> </td> <td> </td> <td> <p id="banwmz_wmz_buy"></p> </td> <td> <p id="banwmz_wmz_sell"></p> </td> </tr> <tr> <td> <a href="https://muatienao.com" target="_blank">Muatienao.com</a> </td> <td> </td> <td> <p id="muatienao_wmz_buy"></p> </td> <td> <p id="muatienao_wmz_sell"></p> </td> </tr> </table>
19.578431
83
0.356034
cc3f5b5ac9d64c31cc4845f0642f97c9da1cdfe5
3,019
rb
Ruby
test/mass_assignment_test.rb
kickstarter/mass_assignment
58a45e6a7edf5753b4cf9aa072b907bb6dad7c13
[ "MIT" ]
1
2019-06-17T19:03:03.000Z
2019-06-17T19:03:03.000Z
test/mass_assignment_test.rb
kickstarter/mass_assignment
58a45e6a7edf5753b4cf9aa072b907bb6dad7c13
[ "MIT" ]
null
null
null
test/mass_assignment_test.rb
kickstarter/mass_assignment
58a45e6a7edf5753b4cf9aa072b907bb6dad7c13
[ "MIT" ]
null
null
null
require File.dirname(__FILE__) + '/test_helper' class MassAssignmentTest < ActiveSupport::TestCase def setup @user = ProtectedUser.new @attributes = {"name" => "Bob", "email" => "[email protected]"} ActiveRecord::Base.logger = stub('debug' => true) end test "assigning nothing" do params = {} assert_nothing_raised do @user.assign(params[:user]) end end test "assigning a string" do params = {:user => "well this is embarrassing"} assert_nothing_raised do @user.assign(params[:user]) end end test "assigning attributes" do @user.assign(@attributes) assert_equal "Bob", @user.name assert_equal "[email protected]", @user.email end test "assigning protected attributes" do @user.assign(@attributes.merge(:role_id => 1)) assert_equal "Bob", @user.name assert_nil @user.role_id end test "overriding protected attributes" do @user.assign(@attributes.merge(:role_id => 1), [:name, :email, :role_id]) assert_equal "Bob", @user.name assert_equal 1, @user.role_id end test "assigning unallowed attributes" do @user.assign(@attributes.merge(:role_id => 1), [:name, :email]) assert_equal "Bob", @user.name assert_nil @user.role_id end test "nested assignment" do @user.assign(@attributes.merge(:friend_attributes => {:name => 'Joe', :role_id => 1}), [:name, :role_id, {:friend_attributes => [:name]}]) assert_equal "Joe", @user.friend.name assert_nil @user.friend.role_id end test "deep assignment" do @user.assign(@attributes.merge(:friend => {:name => 'Joe', :role_id => 1}), [:name, :role_id]) do |params| @user.friend.assign(params[:friend], [:name]) end assert_equal "Joe", @user.friend.name assert_nil @user.friend.role_id end end class MassAssignmentPolicyTest < ActiveSupport::TestCase def setup @attributes = {"name" => "Bob", "role_id" => 1} ActiveRecord::Base.logger = stub('debug' => true) end test "an open policy" do @user = OpenUser.new @user.assign(@attributes) assert_equal "Bob", @user.name assert_equal 1, @user.role_id end test "an overridden open policy" do @user = OpenUser.new @user.assign(@attributes, [:name]) assert_equal "Bob", @user.name assert_nil @user.role_id end test "a closed policy" do @user = ClosedUser.new @user.assign(@attributes) assert_nil @user.name assert_nil @user.role_id end test "an overridden closed policy" do @user = ClosedUser.new @user.assign(@attributes, [:name, :role_id]) assert_equal "Bob", @user.name assert_equal 1, @user.role_id end test "a semi-closed policy" do @user = SemiClosedUser.new @user.assign(@attributes) assert_equal "Bob", @user.name assert_nil @user.role_id end test "an overridden semi-closed policy" do @user = SemiClosedUser.new @user.assign(@attributes, [:name, :role_id]) assert_equal "Bob", @user.name assert_equal 1, @user.role_id end end
27.198198
142
0.663796
1a9f0f7f8e9c2606caf60ee7e335c8159e519659
4,611
py
Python
test.py
YuZiHanorz/stacked_capsule_autoencoders
b85fb1b8b4d4f385f137b865469a20271a234162
[ "Apache-2.0" ]
null
null
null
test.py
YuZiHanorz/stacked_capsule_autoencoders
b85fb1b8b4d4f385f137b865469a20271a234162
[ "Apache-2.0" ]
4
2020-07-22T02:50:01.000Z
2022-02-10T02:42:41.000Z
test.py
YuZiHanorz/stacked_capsule_autoencoders
b85fb1b8b4d4f385f137b865469a20271a234162
[ "Apache-2.0" ]
1
2021-02-22T21:40:17.000Z
2021-02-22T21:40:17.000Z
# coding=utf-8 # Copyright 2019 The Google Research Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. r"""Evaluation script.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import os.path as osp import pdb import sys import traceback from absl import flags from absl import logging from monty.collections import AttrDict import sklearn.cluster import tensorflow as tf from stacked_capsule_autoencoders.capsules.configs import data_config from stacked_capsule_autoencoders.capsules.configs import model_config from stacked_capsule_autoencoders.capsules.eval import cluster_classify from stacked_capsule_autoencoders.capsules.eval import collect_results from stacked_capsule_autoencoders.capsules.plot import make_tsne_plot from stacked_capsule_autoencoders.capsules.train import tools from stacked_capsule_autoencoders.capsules import capsule as _capsule from tensorflow.python.client import timeline flags.DEFINE_string('snapshot', '', 'Checkpoint file.') flags.DEFINE_string( 'tsne_figure_name', 'tsne.png', 'Filename for the TSNE ' 'figure. It will be saved in the checkpoint folder.') # These two flags are necessary for model loading. Don't change them! flags.DEFINE_string('dataset', 'mnist', 'Don\'t change!') flags.DEFINE_string('model', 'scae', 'Don\'t change!.') def main(_=None): FLAGS = flags.FLAGS # pylint: disable=invalid-name,redefined-outer-name config = FLAGS FLAGS.__dict__['config'] = config # Build the graph with tf.Graph().as_default(): dataset = tf.data.Dataset.from_tensors(tf.ones([32, 256])) dataset = dataset.repeat().batch(200) it = dataset.make_one_shot_iterator() data_batch = it.get_next() model = _capsule.ModelTest(config.n_obj_caps, 2, config.n_part_caps, n_caps_params=config.n_obj_caps_params, n_hiddens=128, learn_vote_scale=True, deformations=True, noise_type='uniform', noise_scale=4., similarity_transform=False) #data_dict = data_config.get(FLAGS) #trainset = data_dict.trainset #validset = data_dict.validset # Optimisation target #validset = tools.maybe_convert_dataset(validset) #trainset = tools.maybe_convert_dataset(trainset) #print(validset['image']) #print(trainset['image']) tensor = model(data_batch) sess = tf.Session() sess.run(tf.global_variables_initializer()) sess.run(tf.local_variables_initializer()) #saver = tf.train.Saver() #saver.restore(sess, FLAGS.snapshot) n_batches = 20 print('Collecting: 0/{}'.format(n_batches), end='') run_options = tf.RunOptions(trace_level=tf.RunOptions.FULL_TRACE) run_metadata = tf.RunMetadata() for i in range(n_batches): print('\rCollecting: {}/{}'.format(i + 1, n_batches), end='') if i == 10: print('') print('herehereherehere it starts') sess.run(tensor, options=run_options, run_metadata=run_metadata) tl = timeline.Timeline(run_metadata.step_stats) ctf = tl.generate_chrome_trace_format() print('herehereherehere it ends') with open('timeline.json', 'w') as f: f.write(ctf) print('') else: sess.run(tensor) if __name__ == '__main__': try: logging.set_verbosity(logging.INFO) tf.app.run() except Exception as err: # pylint: disable=broad-except FLAGS = flags.FLAGS last_traceback = sys.exc_info()[2] traceback.print_tb(last_traceback) print(err) pdb.post_mortem(last_traceback)
37.795082
77
0.64216
4a03169899f97c9d2ee9e678a479bdff5dfd23d2
3,194
h
C
src/UI/Components/Grid.h
davidspry/ensemble
cbb7bdcf8cc98db087ba8c6710a05dfb65f09135
[ "MIT" ]
1
2021-01-19T19:35:54.000Z
2021-01-19T19:35:54.000Z
src/UI/Components/Grid.h
davidspry/ensemble
cbb7bdcf8cc98db087ba8c6710a05dfb65f09135
[ "MIT" ]
null
null
null
src/UI/Components/Grid.h
davidspry/ensemble
cbb7bdcf8cc98db087ba8c6710a05dfb65f09135
[ "MIT" ]
null
null
null
// Ensemble // Created by David Spry on 20/12/20. #ifndef GRID_H #define GRID_H #include "Ensemble.h" /// @brief A grid of squares. class Grid: public UIComponent { public: Grid(): UIComponent(), SPACE(20) { grid.setFilled(false); grid.setStrokeWidth(2.0f); updateGridDimensions(); } void draw() override { if (shouldRedraw) { grid.clear(); shouldRedraw = false; const int t = margins.t; const int l = margins.l; const int r = margins.l + shape.w * SPACE; const int b = margins.t + shape.h * SPACE; for (size_t y = 0; y < shape.h + 1; ++y) { grid.moveTo(l - 1, t + y * SPACE); grid.lineTo(r + 1, t + y * SPACE); } for (size_t x = 0; x < shape.w + 1; ++x) { grid.moveTo(l + x * SPACE, t - 1); grid.lineTo(l + x * SPACE, b + 1); } grid.setColor(colours->gridColour); } grid.draw(origin.x, origin.y); } void setSize(const float width, const float height) override { UIComponent::setSize(width, height); updateGridDimensions(); } void setSizeFromCentre(const float width, const float height) override { UIComponent::setSizeFromCentre(width, height); updateGridDimensions(); } void setMargins(const int top, const int left, const int right, const int bottom) override { UIComponent::setMargins(top, left, right, bottom); updateGridDimensions(); } /// @brief Compute the position of a grid cell in pixels. /// @note The position of the centre of the grid cell is returned. /// @param row The cell's row index, beginning from 0. /// @param col The cell's column index, beginning from 0. /// @throw An exception will be thrown in the case where the given indices are out of range. const UIPoint<int> positionOfCell(uint row, uint col) const noexcept(false) { if (!(row < shape.h && col < shape.w)) { constexpr auto error = "The given cell position is out of range"; throw std::out_of_range(error); } const int x = (float) SPACE * ((float) row + 0.5f); const int y = (float) SPACE * ((float) col + 0.5f); return {x, y}; } /// @brief Return the size of the grid's cells in pixels. inline const int getGridCellSize() const noexcept { return static_cast<int>(SPACE); } /// @brief Return the grid's dimensions in rows and columns. inline const UISize<int>& getGridDimensions() const noexcept { return shape; } protected: /// @brief Update the grid's dimensions using its component size, margins, and cell spacing. inline void updateGridDimensions() { const int W = (size.w - margins.l - margins.r) / SPACE; const int H = (size.h - margins.t - margins.b) / SPACE; shape.set(W, H); } protected: ofPath grid; unsigned int SPACE; UISize <int> shape; }; #endif
25.758065
96
0.560426
0badae8f8d34c041b6ef21674ecf3a5fd5b2054e
2,136
hh
C++
2d/src/wall_2d.hh
softwarecapital/chr1shr.voro
122531fbe162ea9a94b7e96ee9d57d3957c337ca
[ "BSD-3-Clause-LBNL" ]
43
2019-09-29T01:14:25.000Z
2022-03-02T23:48:25.000Z
2d/src/wall_2d.hh
softwarecapital/chr1shr.voro
122531fbe162ea9a94b7e96ee9d57d3957c337ca
[ "BSD-3-Clause-LBNL" ]
15
2019-10-19T23:39:39.000Z
2021-12-30T22:03:51.000Z
2d/src/wall_2d.hh
softwarecapital/chr1shr.voro
122531fbe162ea9a94b7e96ee9d57d3957c337ca
[ "BSD-3-Clause-LBNL" ]
23
2019-10-19T23:40:57.000Z
2022-03-29T16:53:17.000Z
// Voro++, a 3D cell-based Voronoi library // // Author : Chris H. Rycroft (LBL / UC Berkeley) // Email : [email protected] // Date : August 30th 2011 /** \file wall_2d.hh * \brief Header file for the 2D derived wall classes. */ #ifndef VOROPP_WALL_2D_HH #define VOROPP_WALL_2D_HH #include "cell_2d.hh" #include "container_2d.hh" namespace voro { /** \brief A class representing a circular wall object. * * This class represents a circular wall object. */ struct wall_circle_2d : public wall_2d { public: /** Constructs a spherical wall object. * \param[in] w_id_ an ID number to associate with the wall for * neighbor tracking. * \param[in] (xc_,yc_) a position vector for the circle's * center. * \param[in] rc_ the radius of the circle. */ wall_circle_2d(double xc_,double yc_,double rc_,int w_id_=-99) : w_id(w_id_), xc(xc_), yc(yc_), rc(rc_) {} bool point_inside(double x,double y); template<class v_cell_2d> bool cut_cell_base(v_cell_2d &c,double x,double y); bool cut_cell(voronoicell_2d &c,double x,double y) {return cut_cell_base(c,x,y);} bool cut_cell(voronoicell_neighbor_2d &c,double x,double y) {return cut_cell_base(c,x,y);} private: const int w_id; const double xc,yc,rc; }; /** \brief A class representing a plane wall object. * * This class represents a single plane wall object. */ struct wall_plane_2d : public wall_2d { public: /** Constructs a plane wall object * \param[in] (xc_,yc_) a normal vector to the plane. * \param[in] ac_ a displacement along the normal vector. * \param[in] w_id_ an ID number to associate with the wall for * neighbor tracking. */ wall_plane_2d(double xc_,double yc_,double ac_,int w_id_=-99) : w_id(w_id_), xc(xc_), yc(yc_), ac(ac_) {} bool point_inside(double x,double y); template<class v_cell_2d> bool cut_cell_base(v_cell_2d &c,double x,double y); bool cut_cell(voronoicell_2d &c,double x,double y) {return cut_cell_base(c,x,y);} bool cut_cell(voronoicell_neighbor_2d &c,double x,double y) {return cut_cell_base(c,x,y);} private: const int w_id; const double xc,yc,ac; }; } #endif
32.363636
92
0.704588
25e0d88ba15a94fb14e8e4733f8c14045f64e175
2,736
cs
C#
QJ_FileCenter/Program.cs
wmlunge/QJ_FileCenter
7d6b129889c471ce59f6dcd4e64bd04f338ff01e
[ "Apache-2.0" ]
1
2020-09-15T07:47:20.000Z
2020-09-15T07:47:20.000Z
QJ_FileCenter/Program.cs
wmlunge/QJ_FileCenter
7d6b129889c471ce59f6dcd4e64bd04f338ff01e
[ "Apache-2.0" ]
null
null
null
QJ_FileCenter/Program.cs
wmlunge/QJ_FileCenter
7d6b129889c471ce59f6dcd4e64bd04f338ff01e
[ "Apache-2.0" ]
null
null
null
using glTech.Log4netWrapper; using Nancy.Hosting.Self; using QJ_FileCenter; using QJ_FileCenter.Domains; using QJ_FileCenter.Repositories; using QJFile.Data; using System; using System.Net; using System.ServiceProcess; namespace QJ_FileCenter { static class Program { /// <summary> /// The main entry point for the application. /// </summary> static void Main() { AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException; Logger.Initialize(PathUtil.GetLog4netPath()); Logger.LogError("开始"); string strAppType = CommonHelp.GetConfig("apptype","0"); if (strAppType == "0") { try { var hostConfiguration = new HostConfiguration { UrlReservations = new UrlReservations() { CreateAutomatically = true } }; string strIP = appsetingB.GetValueByKey("ip"); string port = appsetingB.GetValueByKey("port"); string url = string.Format("http://{0}:{1}", strIP, port); var rootPath = appsetingB.GetValueByKey("path"); var nancyHost = new NancyHost(new RestBootstrapper(), hostConfiguration, new Uri(url)); nancyHost.Start(); System.Console.WriteLine("文件中心服务开启,管理地址:" + url.ToString()); Console.ReadLine(); } catch (Exception ex) { Logger.LogError("启动NancyHost失败."); Logger.LogError4Exception(ex); } } else { if (!Environment.UserInteractive) { ServiceBase[] ServicesToRun; ServicesToRun = new ServiceBase[] { new QJ_FileCenterService() }; ServiceBase.Run(ServicesToRun); } else { QJ_FileCenterService service = new QJ_FileCenterService(); System.Threading.Thread.Sleep(System.Threading.Timeout.Infinite); // forces debug to keep VS running while we debug the service } } } private static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e) { if (e != null && e.ExceptionObject != null) { Logger.LogError("未捕获异常"); Logger.LogError4Exception((Exception)e.ExceptionObject); } } } }
34.632911
150
0.512061
215fa3f1667cfc223cefcd7739d631142cba5c40
1,659
js
JavaScript
src/components/home/line-list/component.js
halima0305/FormationINS
b2f458031abbafa6e910df12a5f3da2fcdbb83b9
[ "MIT" ]
null
null
null
src/components/home/line-list/component.js
halima0305/FormationINS
b2f458031abbafa6e910df12a5f3da2fcdbb83b9
[ "MIT" ]
5
2021-03-10T01:16:09.000Z
2022-02-26T21:00:39.000Z
src/components/home/line-list/component.js
halima0305/FormationINS
b2f458031abbafa6e910df12a5f3da2fcdbb83b9
[ "MIT" ]
1
2019-12-10T13:29:41.000Z
2019-12-10T13:29:41.000Z
import React, { useState, useEffect } from 'react'; import { PropTypes } from 'prop-types'; import Table from 'components/shared/table'; import { filterArray, sortArrayByKey } from 'utils/array-utils'; import { getDesignations } from 'utils/call-api'; import { Loader, Message } from 'semantic-ui-react'; const List = ({ search = '' }) => { const [list, setList] = useState([]); const [loading, setLoading] = useState(true); const [error, setError] = useState(undefined); useEffect(() => { getDesignations() .then(listAPI => { setList(listAPI); setLoading(false); }) .catch(errorAPI => { setError(errorAPI); setLoading(false); }); }, []); if (loading) return ( <Loader active inline="centered" size="massive"> {`Chargement en cours`} </Loader> ); if (error !== undefined) { return ( <Message icon="world" header="Problème avec l'API" negative content={error.message} /> ); } const sortedList = sortArrayByKey('designation')(list); const filteredArray = filterArray(sortedList)(search).map(a => ({ ...a, redList: a.redList ? 'Oui' : 'Non', })); const columns = [ { accessor: 'designation', label: 'Désignation' }, { accessor: 'phoneNumber', label: 'N° de téléphone', center: true }, { accessor: 'redList', label: 'Liste rouge', center: true }, { accessor: 'office', label: 'N° de bureau', center: true }, { accessor: 'observation', label: 'Commentaire' }, ]; return ( <Table columns={columns} data={filteredArray} options={['edit']} itemsPerPage={5} /> ); }; export default List; List.propTypes = { search: PropTypes.string.isRequired, };
24.397059
70
0.634117
f86a7801b2a926936d5fa3d2b8b8c648aa5670f5
1,723
kt
Kotlin
app/src/main/java/com/minseok/themeexample/MainActivity.kt
minseok-kr/Android-Theme-Example
464bf7ba7c03dea9412d39ec6b34372207828c3b
[ "MIT" ]
null
null
null
app/src/main/java/com/minseok/themeexample/MainActivity.kt
minseok-kr/Android-Theme-Example
464bf7ba7c03dea9412d39ec6b34372207828c3b
[ "MIT" ]
null
null
null
app/src/main/java/com/minseok/themeexample/MainActivity.kt
minseok-kr/Android-Theme-Example
464bf7ba7c03dea9412d39ec6b34372207828c3b
[ "MIT" ]
null
null
null
package com.minseok.themeexample import android.app.PictureInPictureParams import android.content.Context import android.content.SharedPreferences import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import androidx.annotation.StyleRes import androidx.databinding.DataBindingUtil import com.minseok.themeexample.databinding.ActivityMainBinding class MainActivity : AppCompatActivity() { private lateinit var binding: ActivityMainBinding override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setTheme(loadTheme().resId) binding = DataBindingUtil.setContentView(this, R.layout.activity_main) binding.init() } private fun ActivityMainBinding.init() { btnGreen.setOnClickListener { ThemeItem.Green.also { refreshTheme(it) } } btnYellow.setOnClickListener { ThemeItem.Yellow.also { refreshTheme(it) } } } private fun refreshTheme(item: ThemeItem) { saveTheme(item) setTheme(item.resId) recreate() } private fun saveTheme(theme: ThemeItem) { with(getSharedPreferenceEdit()) { putString("theme", theme.name) }.commit() } private fun loadTheme(): ThemeItem { return with(getSharedPreference()) { getString("theme", ThemeItem.Green.name)!! }.run { ThemeItem.valueOf(this) } } private fun getSharedPreference() = getSharedPreferences("theme-example", Context.MODE_PRIVATE) private fun getSharedPreferenceEdit() = getSharedPreference().edit() }
25.716418
78
0.656413
850eeb4f97397dd11a670960e925d9a6a455bd5a
231
cs
C#
iOS/XCharts.iOS/Implementation/Entries/PointEntry.cs
iXamDev/xcharts
b8f75628f388c6fbdef14f6d425e0b29e5541ded
[ "MIT" ]
null
null
null
iOS/XCharts.iOS/Implementation/Entries/PointEntry.cs
iXamDev/xcharts
b8f75628f388c6fbdef14f6d425e0b29e5541ded
[ "MIT" ]
null
null
null
iOS/XCharts.iOS/Implementation/Entries/PointEntry.cs
iXamDev/xcharts
b8f75628f388c6fbdef14f6d425e0b29e5541ded
[ "MIT" ]
null
null
null
using System; using XCharts.iOS.Abstract.Entries; namespace XCharts.iOS.Implementation.Entries { public class PointEntry : IPointEntry { public double Y { get; set; } public double X { get; set; } } }
19.25
44
0.65368
e4523a57de335a2e7452cfda50260fe370c24e67
1,833
sh
Shell
storage/scripts/displaywebpagescript.sh
IrisBroadcast/ophrys-signage
f7c4787794ab87960a0d07fb63e674c40bb88697
[ "BSD-3-Clause" ]
8
2019-11-12T18:51:10.000Z
2020-12-21T22:26:30.000Z
storage/scripts/displaywebpagescript.sh
IrisBroadcast/OphrysSignage
0bec692479d93d769e46a81eb46841daaf67f68a
[ "BSD-3-Clause" ]
4
2020-02-06T10:31:17.000Z
2020-02-26T20:55:41.000Z
storage/scripts/displaywebpagescript.sh
IrisBroadcast/OphrysSignage
0bec692479d93d769e46a81eb46841daaf67f68a
[ "BSD-3-Clause" ]
2
2020-02-06T10:34:15.000Z
2020-03-08T01:24:26.000Z
#!/bin/bash COMMONFILE=/usr/local/aloe/scripts/common.sh . $COMMONFILE STATEFILENODE="/usr/local/aloe/scripts/ophrys_state_node.json" function cleanChromium { PREFERENCES="/home/pi/.config/chromium/Default/Preferences" if [ -f $PREFERENCES ];then sed -i 's/"exit_type":"Crashed"/"exit_type":"Normal"/g' $PREFERENCES fi } function openUrl { DYNAMIC_URL=$(cat $STATEFILENODE | jq -r '.url') BROWSERPARAMETER=$(cat $STATEFILENODE | jq -r '.browserparameter') # check if this is boot or not - Show IP-adress if this is boot TMPSPLASH="/tmp/splash.png" if [ ! -f /tmp/online ];then sudo cp $GRAPHICSFOLDER/splash.png $TMPSPLASH IPv4=$(hostname -I) HOST=$(hostname) printf "convert -pointsize 40 -fill white -draw 'text 715,1000 \"IPv4: $IPv4\nHostname: $HOST\" ' /usr/local/aloe/graphics/embedip.png /usr/local/aloe/graphics/splash.png" > /tmp/temp sudo bash /tmp/temp sudo service lightdm restart sleep 10 ## Restore splashscreen to default if [ -f $TMPSPLASH ];then sudo cp $TMPSPLASH $GRAPHICSFOLDER/splash.png fi fi # Make sure state file exists if [ -e $STATEFILENODE ];then DYNAMIC_URL=$(cat $STATEFILENODE | jq -r '.url') BROWSERPARAMETER=$(cat $STATEFILENODE | jq -r '.browserparameter') else DYNAMIC_URL="http://localhost:82" BROWSERPARAMETER="" fi if [ -z "$DYNAMIC_URL" ];then DYNAMIC_URL="http://localhost:82" fi export DISPLAY=:0.0 chromium-browser $BROWSERPARAMETER --disable-site-isolation-trials --disable-web-security --user-data-dir=/tmp/temp/ --noerrdialogs --check-for-update-interval=1209600 --disable-session-crashed-bubble --disable-infobars --disable-restore-session-state --disable-features=TranslateUI --kiosk --disable-pinch --overscroll-history-navigation=0 --proxy-auto-detect $DYNAMIC_URL } cleanChromium openUrl
33.944444
374
0.716312
e2483d05b04196ef8f605e8147da7946db65efd3
4,011
py
Python
pineboolib/application/database/tests/test_pnconnection_manager.py
Aulla/pineboo
3ad6412d365a6ad65c3bb2bdc03f5798d7c37004
[ "MIT" ]
2
2017-12-10T23:06:16.000Z
2017-12-10T23:06:23.000Z
pineboolib/application/database/tests/test_pnconnection_manager.py
Aulla/pineboo
3ad6412d365a6ad65c3bb2bdc03f5798d7c37004
[ "MIT" ]
36
2017-11-05T21:13:47.000Z
2020-08-26T15:56:15.000Z
pineboolib/application/database/tests/test_pnconnection_manager.py
Aulla/pineboo
3ad6412d365a6ad65c3bb2bdc03f5798d7c37004
[ "MIT" ]
8
2017-11-05T15:56:31.000Z
2019-04-25T16:32:28.000Z
"""Test_pnconnection module.""" import unittest from pineboolib.loader.main import init_testing, finish_testing from pineboolib import application from pineboolib.application.database import pnsqlcursor from pineboolib.core.utils import logging import time LOGGER = logging.get_logger(__name__) USER_ID: str class TestPNConnectionManager(unittest.TestCase): """TestPNConnection Class.""" @classmethod def setUp(cls) -> None: """Ensure pineboo is initialized for testing.""" init_testing() def test_basic1(self) -> None: """Basic test 1.""" global USER_ID USER_ID = "usu0" application.PROJECT.set_session_function(self.user_id) conn_manager = application.PROJECT.conn_manager self.assertEqual(conn_manager.session_id(), USER_ID) cursor_1 = pnsqlcursor.PNSqlCursor("flfiles") # noqa: F841 self.assertEqual(conn_manager.session_id(), "usu0") self.assertEqual(conn_manager.active_pncursors(True), ["flfiles"]) def test_basic2(self) -> None: """Basic test 2.""" global USER_ID USER_ID = "usu1" conn_manager = application.PROJECT.conn_manager self.assertEqual(conn_manager.session_id(), "usu1") self.assertEqual(conn_manager.active_pncursors(True), []) cursor_1 = pnsqlcursor.PNSqlCursor("flfiles") # noqa: F841 self.assertEqual(conn_manager.active_pncursors(True), ["flfiles"]) self.assertTrue("flfiles" in conn_manager.active_pncursors(True, True)) USER_ID = "usu2" self.assertEqual(conn_manager.session_id(), "usu2") self.assertEqual(conn_manager.active_pncursors(True), []) cursor_2 = pnsqlcursor.PNSqlCursor("flfiles") # noqa: F841 cursor_3 = pnsqlcursor.PNSqlCursor("flareas") # noqa: F841 self.assertEqual(conn_manager.active_pncursors(True), ["flfiles", "flareas"]) self.assertTrue(len(conn_manager.active_pncursors(True, True)) > 2) USER_ID = "usu1" self.assertEqual(conn_manager.active_pncursors(True), ["flfiles"]) self.assertTrue(len(conn_manager.active_pncursors(True, True)) > 2) def test_basic3(self) -> None: """Basic test 3.""" from PyQt6 import QtWidgets # type: ignore[import] global USER_ID USER_ID = "test3" conn_manager = application.PROJECT.conn_manager self.assertEqual(application.PROJECT.conn_manager.session_id(), "test3") cur = pnsqlcursor.PNSqlCursor("flfiles") cur.select() time.sleep(1) pnsqlcursor.CONNECTION_CURSORS[application.PROJECT.conn_manager.session_id()].pop() while "flfiles" in conn_manager.active_pncursors(True): QtWidgets.QApplication.processEvents() while "flfiles" in conn_manager.active_pncursors(True): QtWidgets.QApplication.processEvents() cur = pnsqlcursor.PNSqlCursor("flfiles") cur.select() time.sleep(1) pnsqlcursor.CONNECTION_CURSORS[application.PROJECT.conn_manager.session_id()].pop() conn_manager.set_max_connections_limit(100) conn_manager.set_max_idle_connections(50) self.assertEqual(conn_manager.limit_connections, 100) self.assertEqual(conn_manager.connections_time_out, 50) while "flfiles" in conn_manager.active_pncursors(True): QtWidgets.QApplication.processEvents() def threaded_function(self) -> None: """Threaded function.""" try: cur = pnsqlcursor.PNSqlCursor("flfiles") cur.select() except Exception: time.sleep(1) pnsqlcursor.CONNECTION_CURSORS[application.PROJECT.conn_manager.session_id()].pop() def user_id(self) -> str: """Return user id.""" global USER_ID return USER_ID @classmethod def tearDown(cls) -> None: """Ensure test clear all data.""" finish_testing() if __name__ == "__main__": unittest.main()
34.282051
95
0.671154
b8c1e8bc0940e92910f3a4a51df3fc2ca0f74b12
1,018
h
C
src/main/cpp/include/segment/cubicsegment.h
Arctos6135/RobotPathfinder
8572f4790c7ba8af8096bf475a2da019d7c9ab86
[ "MIT" ]
12
2018-08-17T08:52:47.000Z
2020-01-29T11:17:31.000Z
src/main/cpp/include/segment/cubicsegment.h
Arctos6135/RobotPathfinder
8572f4790c7ba8af8096bf475a2da019d7c9ab86
[ "MIT" ]
38
2018-06-27T03:46:50.000Z
2020-01-02T05:56:52.000Z
src/main/cpp/include/segment/cubicsegment.h
Arctos6135/RobotPathfinder
8572f4790c7ba8af8096bf475a2da019d7c9ab86
[ "MIT" ]
null
null
null
#pragma once #include "splinesegment.h" namespace rpf { class CubicSegment : public SplineSegment { public: CubicSegment(const Vec2D &p0, const Vec2D &p1, const Vec2D &m0, const Vec2D &m1) : p0(p0), p1(p1), m0(m0), m1(m1) { } Vec2D at(double) const override; Vec2D deriv_at(double) const override; Vec2D second_deriv_at(double) const override; protected: static double basis0(double); static double basis1(double); static double basis2(double); static double basis3(double); static double basis_deriv0(double); static double basis_deriv1(double); static double basis_deriv2(double); static double basis_deriv3(double); static double basis_second_deriv0(double); static double basis_second_deriv1(double); static double basis_second_deriv2(double); static double basis_second_deriv3(double); Vec2D p0, p1, m0, m1; }; } // namespace rpf
29.085714
88
0.644401
bf8115a5ef12e4187e3bf26da305d9413026cf35
7,056
lua
Lua
rc-car/src/init.lua
henrythasler/nodemcu
e820be27e8f8feaa30ec0f9a26abcc3d740b61c2
[ "MIT" ]
1
2020-04-17T06:34:32.000Z
2020-04-17T06:34:32.000Z
rc-car/src/init.lua
henrythasler/nodemcu
e820be27e8f8feaa30ec0f9a26abcc3d740b61c2
[ "MIT" ]
1
2022-03-02T02:49:58.000Z
2022-03-02T02:49:58.000Z
rc-car/src/init.lua
henrythasler/nodemcu
e820be27e8f8feaa30ec0f9a26abcc3d740b61c2
[ "MIT" ]
1
2018-09-28T17:20:11.000Z
2018-09-28T17:20:11.000Z
-- Compile additional modules local files = { "webserver-request.lua", "webserver-header.lua", "webserver-websocket.lua" } for i, f in ipairs(files) do if file.exists(f) then print("Compiling:", f) node.compile(f) file.remove(f) collectgarbage() end end files = nil collectgarbage() local function compile_lua(filename) if file.exists(filename .. ".lua") then node.compile(filename .. ".lua") file.remove(filename .. ".lua") collectgarbage() return true else return false end end local function run_lc(filename) if file.exists(filename .. ".lc") then dofile(filename .. ".lc") return true else print("[init] - " .. filename .. ".lc not found.") return false end end local function start_runnables() for _, item in ipairs(cfg.runnables.active) do if pcall(run_lc, item) then print("[init] - started " .. item) else print("![init] - Error running " .. item) end end end local function wifi_monitor(config) local connected = false local retry = 0 tmr.alarm( 0, 2000, tmr.ALARM_AUTO, function() if wifi.sta.getip() == nil then print("[init] - Waiting for WiFi connection to '" .. cfg.wifi.ssid .. "'") retry = retry + 1 gpio.write(0, 1 - gpio.read(0)) if (retry > 10) then node.restart() end if connected == true then connected = false node.restart() end else print(string.format("[init] - %u Bytes free", node.heap())) gpio.write(0, 1) tmr.alarm( 3, 50, tmr.ALARM_SINGLE, function() gpio.write(0, 0) end ) if connected ~= true then connected = true gpio.write(0, 0) print("[init] - \tWiFi - connected") print("[init] - \tIP: " .. wifi.sta.getip()) print("[init] - \tHostname: " .. wifi.sta.gethostname()) print("[init] - \tChannel: " .. wifi.getchannel()) print("[init] - \tSignal Strength: " .. wifi.sta.getrssi()) mdns.register( cfg.hostname, {description = "CDC rocks", service = "http", port = 80, location = "Earth"} ) print("[init] - \tmDNS: " .. cfg.hostname .. ".local") start_runnables() end if cfg.ntp.server and (cfg.ntp.synced == false) and not cfg.ntp.inProgress then cfg.ntp.inProgress = true sntp.sync( cfg.ntp.server, function(sec, usec, server) local tm = rtctime.epoch2cal(rtctime.get()) local date = string.format( "%04d-%02d-%02d %02d:%02d:%02d", tm["year"], tm["mon"], tm["day"], tm["hour"], tm["min"], tm["sec"] ) print(string.format("[init] - ntp sync with %s ok: %s UTC/GMT", server, date)) cfg.ntp.synced = true cfg.ntp.inProgress = false end, function(err) print("[init] - ntp sync failed") cfg.ntp.synced = false cfg.ntp.inProgress = false end ) end end end ) end -- ### main part -- compile config file compile_lua("config") -- compile all user-scripts local l = file.list("^usr/.+(%.lua)$") for k, v in pairs(l) do if file.exists(k) then print("Compiling:", k) node.compile(k) --file.remove(k) -- do not remove file, might want to download into browser collectgarbage() end end -- load config from file if run_lc("config") == false then print("[init] - using default cfg") cfg = {} -- WIFI cfg.wifi = {} cfg.wifi.mode = wifi.SOFTAP cfg.wifi.ssid = "CDC" cfg.wifi.pwd = "00000000" cfg.wifi.auth = wifi.OPEN cfg.wifi.channel = 6 cfg.wifi.hidden = false cfg.wifi.max = 4 cfg.wifi.save = false cfg.net = {} cfg.net.ip = "192.168.1.1" cfg.net.netmask = "255.255.255.0" cfg.net.gateway = "192.168.1.1" -- nodemcu -- hostname: name of this nodemcu cfg.hostname = "car" -- Runnables cfg.runnables = {} cfg.runnables.sources = {"flashdaemon", "webserver", "MPU6050"} -- NTP -- cfg.ntp.server: IP address of NTP provider. Set to 'false' to disable sync cfg.ntp = {} cfg.ntp.server = false end cfg.runnables.active = {} cfg.ntp.synced = false -- build runnables for _, item in ipairs(cfg.runnables.sources) do print("[init] - preparing " .. item) local status, error = pcall(compile_lua, item) if status == true then table.insert(cfg.runnables.active, item) else print("[init] - Error compiling " .. item .. ": " .. error) end end -- setup general configuration wifi.sta.sethostname(cfg.hostname) -- setup GPIO gpio.mode(0, gpio.OUTPUT) -- LED, if mounted -- Set-up Wifi AP wifi.setmode(cfg.wifi.mode) if cfg.wifi.mode == wifi.SOFTAP then print("[init] - setting up SoftAP...") wifi.ap.config(cfg.wifi) wifi.ap.setip(cfg.net) mdns.register(cfg.hostname, {description = "CDC rocks", service = "http", port = 80, location = "Earth"}) wifi.eventmon.register( wifi.eventmon.AP_STACONNECTED, function(T) print("[init] - connected (" .. T.MAC .. ")") end ) wifi.eventmon.register( wifi.eventmon.AP_STADISCONNECTED, function(T) print("[init] - disconnected (" .. T.MAC .. ")") end ) tmr.alarm( 0, 2000, tmr.ALARM_AUTO, function() print(string.format("[init] - %u Bytes free", node.heap())) gpio.write(0, 1) tmr.alarm( 3, 50, tmr.ALARM_SINGLE, function() gpio.write(0, 0) end ) end ) start_runnables() elseif cfg.wifi.mode == wifi.STATION then print("[init] - Connecting to AP...") wifi.sta.config(cfg.wifi) wifi.sta.connect() wifi_monitor() end
28.682927
109
0.474773
382dc03c2c253452d5050acfd18bb0f00fa3cb7b
1,894
sql
SQL
models/double_entry_transactions/int_quickbooks__bill_double_entry.sql
alex-ilyichov/dbt_quickbooks
fbf24e691f7a3aebb9058b8d9301d4bef3c63b11
[ "Apache-2.0" ]
null
null
null
models/double_entry_transactions/int_quickbooks__bill_double_entry.sql
alex-ilyichov/dbt_quickbooks
fbf24e691f7a3aebb9058b8d9301d4bef3c63b11
[ "Apache-2.0" ]
null
null
null
models/double_entry_transactions/int_quickbooks__bill_double_entry.sql
alex-ilyichov/dbt_quickbooks
fbf24e691f7a3aebb9058b8d9301d4bef3c63b11
[ "Apache-2.0" ]
null
null
null
/* Table that creates a debit record to the specified expense account and credit record to accounts payable for each bill transaction. */ --To disable this model, set the using_bill variable within your dbt_project.yml file to False. {{ config(enabled=var('using_bill', True)) }} with bills as ( select * from {{ ref('stg_quickbooks__bill') }} ), bill_lines as ( select * from {{ ref('stg_quickbooks__bill_line') }} ), items as ( select * from {{ref('stg_quickbooks__item')}} ), bill_join as ( select bills.bill_id as transaction_id, bills.transaction_date, bill_lines.amount, -- case when bill_lines.account_expense_account_id is null and items.type = 'Inventory' -- then items.asset_account_id -- when bill_lines.account_expense_account_id is null and items.type != 'Inventory' -- then coalesce(items.expense_account_id, items.income_account_id) --Just switched these to test -- else bill_lines.account_expense_account_id -- end as payed_to_account_id, coalesce(bill_lines.account_expense_account_id, items.income_account_id, items.expense_account_id) as payed_to_account_id, bills.payable_account_id from bills inner join bill_lines on bills.bill_id = bill_lines.bill_id left join items on bill_lines.item_expense_item_id = items.item_id ), final as ( select transaction_id, transaction_date, amount, payed_to_account_id as account_id, 'debit' as transaction_type, 'bill' as transaction_source from bill_join union all select transaction_id, transaction_date, amount, payable_account_id as account_id, 'credit' as transaction_type, 'bill' as transaction_source from bill_join ) select * from final
27.852941
131
0.678458
ef8bbe347136c5738571a99893a96886c4f18480
2,728
h
C
src/saux/senc.h
timgates42/libsrt
cebf7cacf1125781b20a3e4a7ca10ad741d57cfb
[ "BSD-3-Clause" ]
564
2015-04-21T23:05:55.000Z
2022-03-18T20:43:29.000Z
src/saux/senc.h
viquiram/libsrt
acaf2f5e30fa5069c84b2863d30eed2d09b41bfb
[ "BSD-3-Clause" ]
32
2015-06-05T22:49:58.000Z
2021-07-22T18:05:18.000Z
src/saux/senc.h
viquiram/libsrt
acaf2f5e30fa5069c84b2863d30eed2d09b41bfb
[ "BSD-3-Clause" ]
51
2015-07-26T05:00:52.000Z
2022-03-14T15:41:52.000Z
#ifndef SENC_H #define SENC_H #ifdef __cplusplus extern "C" { #endif /* * senc.h * * Buffer encoding/decoding * * Copyright (c) 2015-2019 F. Aragon. All rights reserved. * Released under the BSD 3-Clause License (see the doc/LICENSE) * * Features (base64 and hex encoding/decoding): * * - Aliasing safe (input and output buffer can be the same). * - RFC 3548/4648 base 16 (hexadecimal) and 64 encoding/decoding. * - Fast (~1 GB/s on i5-3330 @3GHz -using one core- and gcc 4.8.2 -O2) * * Features (JSON and XML escape/unescape): * * - Aliasing safe. * - JSON escape subset of RFC 4627 * - XML escape subset of XML 1.0 W3C 26 Nov 2008 (4.6 Predefined Entities) * - Fast decoding (~1 GB/s on i5-3330 @3GHz -using one core-) * - "Fast" decoding (200-400 MB/s on "; there is room for optimization) * * Features (custom LZ77 implementation): * * - Encoding time complexity: O(n) * - Decoding time complexity: O(n) * * Observations: * - Tables take 288 bytes (could be reduced to 248 bytes -tweaking access * to b64d[]-, but it would require to increase the number of operations in * order to shift -and secure- access to that area, being code increase more * than those 40 bytes). */ #include "scommon.h" #define SDEBUG_LZ_STATS 0 typedef size_t (*srt_enc_f)(const uint8_t *s, size_t ss, uint8_t *o); typedef size_t (*srt_enc_f2)(const uint8_t *s, size_t ss, uint8_t *o, size_t known_sso); size_t senc_b64(const uint8_t *s, size_t ss, uint8_t *o); size_t sdec_b64(const uint8_t *s, size_t ss, uint8_t *o); size_t senc_hex(const uint8_t *s, size_t ss, uint8_t *o); size_t senc_HEX(const uint8_t *s, size_t ss, uint8_t *o); size_t sdec_hex(const uint8_t *s, size_t ss, uint8_t *o); size_t senc_esc_xml(const uint8_t *s, size_t ss, uint8_t *o, size_t known_sso); size_t sdec_esc_xml(const uint8_t *s, size_t ss, uint8_t *o); size_t senc_esc_json(const uint8_t *s, size_t ss, uint8_t *o, size_t known_sso); size_t sdec_esc_json(const uint8_t *s, size_t ss, uint8_t *o); size_t senc_esc_url(const uint8_t *s, size_t ss, uint8_t *o, size_t known_sso); size_t sdec_esc_url(const uint8_t *s, size_t ss, uint8_t *o); size_t senc_esc_dquote(const uint8_t *s, size_t ss, uint8_t *o, size_t known_sso); size_t sdec_esc_dquote(const uint8_t *s, size_t ss, uint8_t *o); size_t senc_esc_squote(const uint8_t *s, size_t ss, uint8_t *o, size_t known_sso); size_t sdec_esc_squote(const uint8_t *s, size_t ss, uint8_t *o); size_t senc_lz(const uint8_t *s, size_t ss, uint8_t *o); size_t senc_lzh(const uint8_t *s, size_t ss, uint8_t *o); size_t sdec_lz(const uint8_t *s, size_t ss, uint8_t *o); #define senc_b16 senc_HEX #define sdec_b16 sdec_hex #ifdef __cplusplus } /* extern "C" { */ #endif #endif /* SENC_H */
36.864865
88
0.722507
e77e5ad1aaee6167461a90cd3d3f275eda759b9f
2,334
php
PHP
application/views/mgm/login.php
Elang-cripto/ppdb2021
81e88b460dd18e1be432cbc8f57e07102abca114
[ "MIT" ]
1
2022-01-08T09:43:28.000Z
2022-01-08T09:43:28.000Z
application/views/panitia/login.php
Elang-cripto/ppdb2021
81e88b460dd18e1be432cbc8f57e07102abca114
[ "MIT" ]
1
2021-12-24T15:36:36.000Z
2021-12-24T15:36:36.000Z
application/views/panitia/login.php
Elang-cripto/ppdb2021
81e88b460dd18e1be432cbc8f57e07102abca114
[ "MIT" ]
1
2021-12-22T07:24:06.000Z
2021-12-22T07:24:06.000Z
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Login admin</title> <meta name="description" content="Custom Login Form Styling with CSS3" /> <meta name="keywords" content="css3, login, form, custom, input, submit, button, html5, placeholder" /> <meta name="author" content="Codrops" /> <link rel="shortcut icon" href="<?php echo base_url('') ?>asset/dist/img/logo.png" type="image/x-icon"> <link rel="stylesheet" type="text/css" href="<?php echo base_url(); ?>asset/login/css/style.css" /> <script src="<?php echo base_url(); ?>asset/login/js/modernizr.custom.63321.js"></script> <script src="<?php echo base_url(); ?>asset/plugins/sweetalert2/sweetalert211.js"></script> <!--[if lte IE 7]><style>.main{display:none;} .support-note .note-ie{display:block;}</style><![endif]--> <style> @import url(http://fonts.googleapis.com/css?family=Ubuntu:400,700); body { background: #563c55 url(<?php echo base_url(); ?>asset/login/images/blurred.jpg) no-repeat center top; -webkit-background-size: cover; -moz-background-size: cover; background-size: cover; } .container>header h1, .container>header h2 { color: black; text-shadow: 0 1px 1px rgba(0, 0, 0, 0.7); } </style> </head> <body> <div class="container"> <header> <h1> <strong> LOGIN ADMIN - PANITIA - MGM</strong> </h1> <h1>PPDB 2022</h1> <h2>MTS - MA - SMP - SMK AL AMIEN</h2> </header> <section class="main"> <form class="form-3" method="post" action="<?php echo base_url(); ?>auth/cek_admin"> <p class="clearfix"> <label for="username">Username</label> <input type="text" name="username" id="username" placeholder="Username" required> </p> <p class="clearfix"> <label for="password">Password</label> <input type="password" name="password" id="password" placeholder="Password" required> </p> <p class="clearfix"> <input type="checkbox" name="remember" id="remember"> <label for="remember">Remember me</label> </p> <p class="clearfix"> <input type="submit" name="submit" value="Sign in"> </p> </form>​ </section> </div> <?php $this->load->view('theme/ft_alert'); ?> </body> </html>
34.323529
105
0.650386
9855825d0806fc8a88ec4cd85e6ce9892f39460c
955
kt
Kotlin
dispatching-center/src/main/kotlin/com/qingzhu/dispatcher/domain/dto/StaffDto.kt
nedphae/contact-center
d8bce203206a5b5ebd99e50c1a08e88d3e2afa0d
[ "Apache-2.0" ]
19
2020-12-19T10:48:30.000Z
2022-03-19T13:29:32.000Z
dispatching-center/src/main/kotlin/com/qingzhu/dispatcher/domain/dto/StaffDto.kt
nedphae/contact-center
d8bce203206a5b5ebd99e50c1a08e88d3e2afa0d
[ "Apache-2.0" ]
1
2021-07-12T06:16:04.000Z
2021-12-18T07:53:55.000Z
dispatching-center/src/main/kotlin/com/qingzhu/dispatcher/domain/dto/StaffDto.kt
nedphae/contact-center
d8bce203206a5b5ebd99e50c1a08e88d3e2afa0d
[ "Apache-2.0" ]
5
2021-08-11T02:35:25.000Z
2022-03-15T02:45:27.000Z
package com.qingzhu.dispatcher.domain.dto import com.qingzhu.common.domain.shared.authority.StaffAuthority /** * 客服登录用户 * 替换现有系统的 user 用户表, * 使用 OAuth2 做用户认证 */ data class StaffDto( var id: Long? = null, /** 公司id */ val organizationId: Int, /** 用户名 */ val username: String, /** 密码 */ var password: String?, /** 角色 */ var role: StaffAuthority, // 所属分组 /** @ManyToOne */ var staffGroupId: Long, /** 实名 */ var realName: String, /** 昵称 */ var nickName: String, /** 头像 **/ var avatar: String?, /** 同时接待量(默认设置为8) */ var simultaneousService: Int = 8, // 工单 /** 每日上限 */ var maxTicketPerDay: Int = 999, /** 总上限 */ var maxTicketAllTime: Int = 999, /** 是否是机器人 0 机器人, 1人工 */ var staffType: Int = 1, /** 性别 */ var gender: Int = 0, /** 手机 */ var mobilePhone: String? = null, /** 个性签名 */ var personalizedSignature: String? = null )
21.222222
64
0.557068
f05a541ce7a92d396ae991bfe8f8af142b523af4
1,122
go
Go
data/resp.go
ShiningRush/droplet
f918c796df2a2a24b524d228e349619a24137361
[ "MIT" ]
5
2021-02-08T02:12:33.000Z
2022-01-25T02:33:59.000Z
data/resp.go
ShiningRush/droplet
f918c796df2a2a24b524d228e349619a24137361
[ "MIT" ]
8
2020-12-29T13:59:54.000Z
2022-03-18T02:14:41.000Z
data/resp.go
ShiningRush/droplet
f918c796df2a2a24b524d228e349619a24137361
[ "MIT" ]
9
2021-01-25T01:05:51.000Z
2021-11-03T00:53:37.000Z
package data import ( "fmt" "net/http" ) type Response struct { Code int `json:"code"` Message string `json:"message"` Data interface{} `json:"data"` RequestID string `json:"request_id"` } func (r *Response) Set(code int, msg string, data interface{}) { r.Code = code r.Message = msg r.Data = data } func (r *Response) SetReqID(reqId string) { r.RequestID = reqId } type SpecCodeResponse struct { Response StatusCode int `json:"-"` } func (r *SpecCodeResponse) GetStatusCode() int { return r.StatusCode } type FileResponse struct { Name string ContentType string Content []byte } func (r *FileResponse) Get() (name, contentType string, content []byte) { return r.Name, r.ContentType, r.Content } type RawResponse struct { StatusCode int Header http.Header Body []byte } func (rr *RawResponse) WriteRawResponse(rw http.ResponseWriter) error { for k, v := range rr.Header { rw.Header()[k] = v } rw.WriteHeader(rr.StatusCode) if _, err := rw.Write(rr.Body); err != nil { return fmt.Errorf("write body failed: %w", err) } return nil }
18.7
73
0.659537
f1a732f8fac13b7e4398ff9720a499da8384124f
249
rb
Ruby
qa/lib/gitlab/page/admin/dashboard.rb
nowkoai/test
7aca51cce41acd7ec4c393d1bb1185a4a2ca1d07
[ "MIT" ]
11,467
2015-01-01T02:37:54.000Z
2022-03-31T03:33:20.000Z
qa/lib/gitlab/page/admin/dashboard.rb
gitchinalab/gitchinalab
550440cc628181b1c4113909da701fb92aea08b6
[ "Apache-2.0" ]
2,862
2015-01-01T02:39:54.000Z
2022-01-03T16:58:41.000Z
qa/lib/gitlab/page/admin/dashboard.rb
Acidburn0zzz/gitlabhq
74015980b5259072bbf27b432b9b08fda9d27945
[ "MIT" ]
4,353
2015-01-01T09:03:52.000Z
2022-03-31T08:09:05.000Z
# frozen_string_literal: true module Gitlab module Page module Admin class Dashboard < Chemlab::Page path '/admin' h2 :users_in_license h2 :billable_users h3 :number_of_users end end end end
15.5625
37
0.62249
1955d0c6485db354c5500165fcb6a0af7ccad8cb
1,042
sh
Shell
lejos/nxt/AlphaRex.sh
alexc155/lego
bce271d6d4b62f320969edcc81f48ed8807b2201
[ "MIT" ]
null
null
null
lejos/nxt/AlphaRex.sh
alexc155/lego
bce271d6d4b62f320969edcc81f48ed8807b2201
[ "MIT" ]
null
null
null
lejos/nxt/AlphaRex.sh
alexc155/lego
bce271d6d4b62f320969edcc81f48ed8807b2201
[ "MIT" ]
null
null
null
JAVA_HOME="/Library/Java/JavaVirtualMachines/1.6.0.jdk/Contents/Home" cd src/main/java find . -name '*.class' -type f -delete find . -name '*.nxj' -type f -delete /Applications/leJOS_NXJ/bin/nxjc legomindstorms/nxt/Base.java legomindstorms/nxt/alpharex/Legs.java /Applications/leJOS_NXJ/bin/nxjlink -o legomindstorms/nxt/Legs.nxj legomindstorms.nxt.alpharex.Legs /Applications/leJOS_NXJ/bin/nxjupload legomindstorms/nxt/Legs.nxj /Applications/leJOS_NXJ/bin/nxjc legomindstorms/nxt/Base.java legomindstorms/nxt/alpharex/Arms.java /Applications/leJOS_NXJ/bin/nxjlink -o legomindstorms/nxt/Arms.nxj legomindstorms.nxt.alpharex.Arms /Applications/leJOS_NXJ/bin/nxjupload legomindstorms/nxt/Arms.nxj /Applications/leJOS_NXJ/bin/nxjc legomindstorms/nxt/Base.java legomindstorms/nxt/alpharex/Head.java /Applications/leJOS_NXJ/bin/nxjlink -o legomindstorms/nxt/Head.nxj legomindstorms.nxt.alpharex.Head /Applications/leJOS_NXJ/bin/nxjupload legomindstorms/nxt/Head.nxj find . -name '*.class' -type f -delete find . -name '*.nxj' -type f -delete
49.619048
99
0.8119
43d53313944848a45d822612644192be0677615f
1,657
ts
TypeScript
packages/reflow-core/src/execute.ts
Yamsafer/reflow
32fdb54c4cbd4ef63683d2dbdff0ea83d5486524
[ "MIT" ]
2
2019-05-15T21:15:48.000Z
2020-06-18T12:11:41.000Z
packages/reflow-core/src/execute.ts
Yamsafer/reflow
32fdb54c4cbd4ef63683d2dbdff0ea83d5486524
[ "MIT" ]
null
null
null
packages/reflow-core/src/execute.ts
Yamsafer/reflow
32fdb54c4cbd4ef63683d2dbdff0ea83d5486524
[ "MIT" ]
null
null
null
import * as path from 'path' import Duration from 'duration'; import {threadPool} from './thread-pool' import {analyzeCombination} from './analyze' const executeMatrix = function(matrix, config) { const { mocha: mochaConfig, jobDetails, flowDetails, connection, capability, customActions, } = config; const startTime = jobDetails.startTime; const numberOfThreads = jobDetails.numberOfThreads; const numberOfFlows = jobDetails.numberOfFlows; const pool = threadPool({ workerPath: path.join(__dirname, './worker.js'), threadsToSpawn: numberOfThreads, }); const sendToPool = combination => pool.send({ DAG: analyzeCombination(combination), combination, mochaConfig, jobDetails, flowDetails, connection, capability, customActions, }); matrix.forEach(sendToPool); let failures = 0; let errored = false; let done = false; pool .on('done', function(job, jobFailures) { failures += jobFailures; }) .on('error', function(job, error) { errored = true; console.log('Job errored:', error); throw error; }) .on('finished', function() { console.log('Everything done, shutting down the thread pool.'); const duration = new Duration(startTime, new Date()) console.log(`Finished All ${numberOfFlows} Flows in ${duration.toString(1, 1)}`); console.log(`${failures} total errors.`); pool.killAll(); done = true; }); process.on('exit', function() { if(!done) console.log('Exited before done') process.exit(+!!(errored || failures)); }) return pool } export default executeMatrix
24.731343
87
0.654798
451b14eb48641036a7adfcd26a796c949a6ca84c
1,982
go
Go
cli/flags.go
rizalgowandy/nice
a29cd3367b177355379f030ffe80a79f2f9db440
[ "MIT" ]
186
2021-09-20T06:05:43.000Z
2022-03-22T16:21:34.000Z
cli/flags.go
rizalgowandy/nice
a29cd3367b177355379f030ffe80a79f2f9db440
[ "MIT" ]
11
2021-09-25T13:14:08.000Z
2021-10-01T21:45:45.000Z
cli/flags.go
rizalgowandy/nice
a29cd3367b177355379f030ffe80a79f2f9db440
[ "MIT" ]
7
2021-09-20T06:28:49.000Z
2021-11-12T00:09:08.000Z
package cli type Flag struct { Value Value Short string Long string Usage Usager Necessary Necessary set bool defaultSaved bool defaultValue string defaultEmpty bool commandFlag bool // NOTE(SuperPaintman): // The first version had "Aliases" for flags. It's quite handy to have // (e.g. --dry and --dry-run) but at the same time makes API a bit // confusing because of duplication logic. // // I decided to remove aliases. It's not so commonly used feature and // developers can easely make a workaround if they need it. } func newFlag(value Value, opts FlagOptions) Flag { return Flag{ Value: value, Short: opts.Short, Long: opts.Long, Usage: opts.Usage, Necessary: opts.Necessary, commandFlag: opts.commandFlag, } } func (f *Flag) Type() string { if t, ok := f.Value.(Typer); ok { return t.Type() } return "" } func (f *Flag) Required() bool { return f.Necessary == Required } func (f *Flag) Set() bool { return f.set } func (f *Flag) MarkSet() { f.set = true } func (f *Flag) Default() (v string, empty bool) { if !f.defaultSaved { return "", true } return f.defaultValue, f.defaultEmpty } func (f *Flag) SaveDefault() { f.defaultValue = f.Value.String() if ev, ok := f.Value.(Emptier); ok { f.defaultEmpty = ev.Empty() } else { f.defaultEmpty = f.defaultValue == "" } f.defaultSaved = true } func (f *Flag) String() string { v := "Flag(" v += f.Type() if f.Short != "" { v += "," v += "-" + f.Short } if f.Long != "" { if v == "" { v += "," } else { v += "/" } v += "--" + f.Long } v += ")" return v } func Var(register Register, value Value, name string, options ...FlagOptionApplyer) error { var opts FlagOptions opts.applyName(name) opts.applyFlagOptions(options) return register.RegisterFlag(newFlag(value, opts)) } //go:generate python ./generate_flags.py //go:generate python ./generate_multi_flags.py
18.018182
91
0.627144
38d028d7390b5adb47b92a566ab157e523464b0d
15,173
php
PHP
html/Vidal_Associados/wp-content/plugins/contact-form-7/includes/classes.php
cesarbruschetta/php-sites-docker
be931c160640fb2d84535b3be5ad693f0c27be0f
[ "BSD-2-Clause" ]
null
null
null
html/Vidal_Associados/wp-content/plugins/contact-form-7/includes/classes.php
cesarbruschetta/php-sites-docker
be931c160640fb2d84535b3be5ad693f0c27be0f
[ "BSD-2-Clause" ]
2
2020-07-17T17:53:38.000Z
2021-05-10T00:59:21.000Z
html/Vidal_Associados/wp-content/plugins/contact-form-7/includes/classes.php
cesarbruschetta/php-sites-docker
be931c160640fb2d84535b3be5ad693f0c27be0f
[ "BSD-2-Clause" ]
null
null
null
<?php class WPCF7_ContactForm { var $initial = false; var $id; var $title; var $form; var $mail; var $mail_2; var $messages; var $additional_settings; var $unit_tag; var $responses_count = 0; var $scanned_form_tags; var $posted_data; var $uploaded_files; var $skip_mail = false; // Return true if this form is the same one as currently POSTed. function is_posted() { if ( ! isset( $_POST['_wpcf7_unit_tag'] ) || empty( $_POST['_wpcf7_unit_tag'] ) ) return false; if ( $this->unit_tag == $_POST['_wpcf7_unit_tag'] ) return true; return false; } /* Generating Form HTML */ function form_html() { $form = '<div class="wpcf7" id="' . $this->unit_tag . '">'; $url = wpcf7_get_request_uri(); if ( $frag = strstr( $url, '#' ) ) $url = substr( $url, 0, -strlen( $frag ) ); $url .= '#' . $this->unit_tag; $url = apply_filters( 'wpcf7_form_action_url', $url ); $url = esc_url_raw( $url ); $enctype = apply_filters( 'wpcf7_form_enctype', '' ); $form .= '<form action="' . $url . '" method="post" class="wpcf7-form"' . $enctype . '>' . "\n"; $form .= '<div style="display: none;">' . "\n"; $form .= '<input type="hidden" name="_wpcf7" value="' . esc_attr( $this->id ) . '" />' . "\n"; $form .= '<input type="hidden" name="_wpcf7_version" value="' . esc_attr( WPCF7_VERSION ) . '" />' . "\n"; $form .= '<input type="hidden" name="_wpcf7_unit_tag" value="' . esc_attr( $this->unit_tag ) . '" />' . "\n"; $form .= '</div>' . "\n"; $form .= $this->form_elements(); if ( ! $this->responses_count ) $form .= $this->form_response_output(); $form .= '</form>'; $form .= '</div>'; return $form; } function form_response_output() { $class = 'wpcf7-response-output'; $content = ''; if ( $this->is_posted() ) { // Post response output for non-AJAX if ( isset( $_POST['_wpcf7_mail_sent'] ) && $_POST['_wpcf7_mail_sent']['id'] == $this->id ) { if ( $_POST['_wpcf7_mail_sent']['ok'] ) { $class .= ' wpcf7-mail-sent-ok'; $content = $_POST['_wpcf7_mail_sent']['message']; } else { $class .= ' wpcf7-mail-sent-ng'; if ( $_POST['_wpcf7_mail_sent']['spam'] ) $class .= ' wpcf7-spam-blocked'; $content = $_POST['_wpcf7_mail_sent']['message']; } } elseif ( isset( $_POST['_wpcf7_validation_errors'] ) && $_POST['_wpcf7_validation_errors']['id'] == $this->id ) { $class .= ' wpcf7-validation-errors'; $content = $this->message( 'validation_error' ); } } else { $class .= ' wpcf7-display-none'; } $class = ' class="' . $class . '"'; return '<div' . $class . '>' . $content . '</div>'; } function validation_error( $name ) { if ( $this->is_posted() && $ve = $_POST['_wpcf7_validation_errors']['messages'][$name] ) return apply_filters( 'wpcf7_validation_error', '<span class="wpcf7-not-valid-tip-no-ajax">' . esc_html( $ve ) . '</span>', $name, $this ); return ''; } /* Form Elements */ function form_do_shortcode() { global $wpcf7_shortcode_manager; $form = $this->form; $form = $wpcf7_shortcode_manager->do_shortcode( $form ); $this->scanned_form_tags = $wpcf7_shortcode_manager->scanned_tags; if ( WPCF7_AUTOP ) $form = wpcf7_autop( $form ); return $form; } function form_scan_shortcode( $cond = null ) { global $wpcf7_shortcode_manager; if ( ! empty( $this->scanned_form_tags ) ) { $scanned = $this->scanned_form_tags; } else { $scanned = $wpcf7_shortcode_manager->scan_shortcode( $this->form ); $this->scanned_form_tags = $scanned; } if ( empty( $scanned ) ) return null; if ( ! is_array( $cond ) || empty( $cond ) ) return $scanned; for ( $i = 0, $size = count( $scanned ); $i < $size; $i++ ) { if ( is_string( $cond['type'] ) && ! empty( $cond['type'] ) ) { if ( $scanned[$i]['type'] != $cond['type'] ) { unset( $scanned[$i] ); continue; } } elseif ( is_array( $cond['type'] ) ) { if ( ! in_array( $scanned[$i]['type'], $cond['type'] ) ) { unset( $scanned[$i] ); continue; } } if ( is_string( $cond['name'] ) && ! empty( $cond['name'] ) ) { if ( $scanned[$i]['name'] != $cond['name'] ) { unset ( $scanned[$i] ); continue; } } elseif ( is_array( $cond['name'] ) ) { if ( ! in_array( $scanned[$i]['name'], $cond['name'] ) ) { unset( $scanned[$i] ); continue; } } } return array_values( $scanned ); } function form_elements() { $form = apply_filters( 'wpcf7_form_elements', $this->form_do_shortcode() ); // Response output $response_regex = '%\[\s*response\s*\]%'; $form = preg_replace_callback( $response_regex, array( &$this, 'response_replace_callback' ), $form ); return $form; } function response_replace_callback( $matches ) { $this->responses_count += 1; return $this->form_response_output(); } /* Validate */ function validate() { $fes = $this->form_scan_shortcode(); $result = array( 'valid' => true, 'reason' => array() ); foreach ( $fes as $fe ) { $result = apply_filters( 'wpcf7_validate_' . $fe['type'], $result, $fe ); } return $result; } /* Acceptance */ function accepted() { $accepted = true; return apply_filters( 'wpcf7_acceptance', $accepted ); } /* Akismet */ function akismet() { global $akismet_api_host, $akismet_api_port; if ( ! function_exists( 'akismet_http_post' ) || ! ( get_option( 'wordpress_api_key' ) || $wpcom_api_key ) ) return false; $akismet_ready = false; $author = $author_email = $author_url = $content = ''; $fes = $this->form_scan_shortcode(); foreach ( $fes as $fe ) { if ( ! is_array( $fe['options'] ) ) continue; if ( preg_grep( '%^akismet:author$%', $fe['options'] ) && '' == $author ) { $author = $_POST[$fe['name']]; $akismet_ready = true; } if ( preg_grep( '%^akismet:author_email$%', $fe['options'] ) && '' == $author_email ) { $author_email = $_POST[$fe['name']]; $akismet_ready = true; } if ( preg_grep( '%^akismet:author_url$%', $fe['options'] ) && '' == $author_url ) { $author_url = $_POST[$fe['name']]; $akismet_ready = true; } if ( '' != $content ) $content .= "\n\n"; $content .= $_POST[$fe['name']]; } if ( ! $akismet_ready ) return false; $c['blog'] = get_option( 'home' ); $c['user_ip'] = preg_replace( '/[^0-9., ]/', '', $_SERVER['REMOTE_ADDR'] ); $c['user_agent'] = $_SERVER['HTTP_USER_AGENT']; $c['referrer'] = $_SERVER['HTTP_REFERER']; $c['comment_type'] = 'contactform7'; if ( $permalink = get_permalink() ) $c['permalink'] = $permalink; if ( '' != $author ) $c['comment_author'] = $author; if ( '' != $author_email ) $c['comment_author_email'] = $author_email; if ( '' != $author_url ) $c['comment_author_url'] = $author_url; if ( '' != $content ) $c['comment_content'] = $content; $ignore = array( 'HTTP_COOKIE' ); foreach ( $_SERVER as $key => $value ) if ( ! in_array( $key, (array) $ignore ) ) $c["$key"] = $value; $query_string = ''; foreach ( $c as $key => $data ) $query_string .= $key . '=' . urlencode( stripslashes( $data ) ) . '&'; $response = akismet_http_post( $query_string, $akismet_api_host, '/1.1/comment-check', $akismet_api_port ); if ( 'true' == $response[1] ) return true; else return false; } /* Mail */ function mail() { $fes = $this->form_scan_shortcode(); foreach ( $fes as $fe ) { $name = $fe['name']; $pipes = $fe['pipes']; if ( empty( $name ) ) continue; $value = $_POST[$name]; if ( WPCF7_USE_PIPE && is_a( $pipes, 'WPCF7_Pipes' ) && ! $pipes->zero() ) { if ( is_array( $value) ) { $new_value = array(); foreach ( $value as $v ) { $new_value[] = $pipes->do_pipe( stripslashes( $v ) ); } $value = $new_value; } else { $value = $pipes->do_pipe( stripslashes( $value ) ); } } $this->posted_data[$name] = $value; } if ( $this->in_demo_mode() ) $this->skip_mail = true; do_action_ref_array( 'wpcf7_before_send_mail', array( &$this ) ); if ( $this->skip_mail ) return true; if ( $this->compose_and_send_mail( $this->mail ) ) { if ( $this->mail_2['active'] ) $this->compose_and_send_mail( $this->mail_2 ); return true; } return false; } function compose_and_send_mail( $mail_template ) { $regex = '/\[\s*([a-zA-Z_][0-9a-zA-Z:._-]*)\s*\]/'; $callback = array( &$this, 'mail_callback' ); $subject = preg_replace_callback( $regex, $callback, $mail_template['subject'] ); $sender = preg_replace_callback( $regex, $callback, $mail_template['sender'] ); $recipient = preg_replace_callback( $regex, $callback, $mail_template['recipient'] ); $additional_headers = preg_replace_callback( $regex, $callback, $mail_template['additional_headers'] ); if ( $mail_template['use_html'] ) { $callback_html = array( &$this, 'mail_callback_html' ); $body = preg_replace_callback( $regex, $callback_html, $mail_template['body'] ); } else { $body = preg_replace_callback( $regex, $callback, $mail_template['body'] ); } extract( apply_filters( 'wpcf7_mail_components', compact( 'subject', 'sender', 'body', 'recipient', 'additional_headers' ) ) ); $headers = "From: $sender\n"; if ( $mail_template['use_html'] ) $headers .= "Content-Type: text/html\n"; $headers .= trim( $additional_headers ) . "\n"; if ( $this->uploaded_files ) { $for_this_mail = array(); foreach ( $this->uploaded_files as $name => $path ) { if ( false === strpos( $mail_template['attachments'], "[${name}]" ) ) continue; $for_this_mail[] = $path; } return @wp_mail( $recipient, $subject, $body, $headers, $for_this_mail ); } else { return @wp_mail( $recipient, $subject, $body, $headers ); } } function mail_callback_html( $matches ) { return $this->mail_callback( $matches, true ); } function mail_callback( $matches, $html = false ) { if ( isset( $this->posted_data[$matches[1]] ) ) { $submitted = $this->posted_data[$matches[1]]; if ( is_array( $submitted ) ) $replaced = join( ', ', $submitted ); else $replaced = $submitted; if ( $html ) $replaced = esc_html( $replaced ); $replaced = apply_filters( 'wpcf7_mail_tag_replaced', $replaced, $submitted ); return stripslashes( $replaced ); } if ( $special = apply_filters( 'wpcf7_special_mail_tags', '', $matches[1] ) ) return $special; return $matches[0]; } /* Message */ function message( $status ) { $messages = $this->messages; $message = $messages[$status]; return apply_filters( 'wpcf7_display_message', $message ); } /* Additional settings */ function additional_setting( $name, $max = 1 ) { $tmp_settings = (array) explode( "\n", $this->additional_settings ); $count = 0; $values = array(); foreach ( $tmp_settings as $setting ) { if ( preg_match('/^([a-zA-Z0-9_]+)\s*:(.*)$/', $setting, $matches ) ) { if ( $matches[1] != $name ) continue; if ( ! $max || $count < (int) $max ) { $values[] = trim( $matches[2] ); $count += 1; } } } return $values; } function in_demo_mode() { $settings = $this->additional_setting( 'demo_mode', false ); foreach ( $settings as $setting ) { if ( in_array( $setting, array( 'on', 'true', '1' ) ) ) return true; } return false; } /* Upgrade */ function upgrade() { if ( ! isset( $this->mail['recipient'] ) ) $this->mail['recipient'] = get_option( 'admin_email' ); if ( ! is_array( $this->messages ) ) $this->messages = array(); foreach ( wpcf7_messages() as $key => $arr ) { if ( ! isset( $this->messages[$key] ) ) $this->messages[$key] = $arr['default']; } } /* Save */ function save() { global $wpdb, $wpcf7; $fields = array( 'title' => maybe_serialize( stripslashes_deep( $this->title ) ), 'form' => maybe_serialize( stripslashes_deep( $this->form ) ), 'mail' => maybe_serialize( stripslashes_deep( $this->mail ) ), 'mail_2' => maybe_serialize ( stripslashes_deep( $this->mail_2 ) ), 'messages' => maybe_serialize( stripslashes_deep( $this->messages ) ), 'additional_settings' => maybe_serialize( stripslashes_deep( $this->additional_settings ) ) ); if ( $this->initial ) { $result = $wpdb->insert( $wpcf7->contactforms, $fields ); if ( $result ) { $this->initial = false; $this->id = $wpdb->insert_id; do_action_ref_array( 'wpcf7_after_create', array( &$this ) ); } else { return false; // Failed to save } } else { // Update if ( ! (int) $this->id ) return false; // Missing ID $result = $wpdb->update( $wpcf7->contactforms, $fields, array( 'cf7_unit_id' => absint( $this->id ) ) ); if ( false !== $result ) { do_action_ref_array( 'wpcf7_after_update', array( &$this ) ); } else { return false; // Failed to save } } do_action_ref_array( 'wpcf7_after_save', array( &$this ) ); return true; // Succeeded to save } function copy() { $new = new WPCF7_ContactForm(); $new->initial = true; $new->title = $this->title . '_copy'; $new->form = $this->form; $new->mail = $this->mail; $new->mail_2 = $this->mail_2; $new->messages = $this->messages; $new->additional_settings = $this->additional_settings; return $new; } function delete() { global $wpdb, $wpcf7; if ( $this->initial ) return; $query = $wpdb->prepare( "DELETE FROM $wpcf7->contactforms WHERE cf7_unit_id = %d LIMIT 1", absint( $this->id ) ); $wpdb->query( $query ); $this->initial = true; $this->id = null; } } function wpcf7_contact_form( $id ) { global $wpdb, $wpcf7; $query = $wpdb->prepare( "SELECT * FROM $wpcf7->contactforms WHERE cf7_unit_id = %d", $id ); if ( ! $row = $wpdb->get_row( $query ) ) return false; // No data $contact_form = new WPCF7_ContactForm(); $contact_form->id = $row->cf7_unit_id; $contact_form->title = maybe_unserialize( $row->title ); $contact_form->form = maybe_unserialize( $row->form ); $contact_form->mail = maybe_unserialize( $row->mail ); $contact_form->mail_2 = maybe_unserialize( $row->mail_2 ); $contact_form->messages = maybe_unserialize( $row->messages ); $contact_form->additional_settings = maybe_unserialize( $row->additional_settings ); $contact_form->upgrade(); return $contact_form; } function wpcf7_contact_form_default_pack( $locale = null ) { global $l10n; if ( $locale && $locale != get_locale() ) { $mo_orig = $l10n['wpcf7']; unset( $l10n['wpcf7'] ); if ( 'en_US' != $locale ) { $mofile = wpcf7_plugin_path( 'languages/wpcf7-' . $locale . '.mo' ); if ( ! load_textdomain( 'wpcf7', $mofile ) ) { $l10n['wpcf7'] = $mo_orig; unset( $mo_orig ); } } } $contact_form = new WPCF7_ContactForm(); $contact_form->initial = true; $contact_form->title = __( 'Untitled', 'wpcf7' ); $contact_form->form = wpcf7_default_form_template(); $contact_form->mail = wpcf7_default_mail_template(); $contact_form->mail_2 = wpcf7_default_mail_2_template(); $contact_form->messages = wpcf7_default_messages_template(); if ( isset( $mo_orig ) ) $l10n['wpcf7'] = $mo_orig; return $contact_form; } ?>
25.760611
118
0.599618
8200f37b41b85df331035e7b571e289c05feb7c9
522
ps1
PowerShell
src/Functions/PoShMon.Configuration/Extensibility.ps1
HiltonGiesenow/PoShMon
770ce92b53ea0e9fc2b78e31e9e52b23da9c35b3
[ "MIT" ]
59
2017-01-04T01:27:18.000Z
2022-02-10T17:40:17.000Z
src/Functions/PoShMon.Configuration/Extensibility.ps1
HiltonGiesenow/PoShMon
770ce92b53ea0e9fc2b78e31e9e52b23da9c35b3
[ "MIT" ]
138
2016-12-31T20:07:38.000Z
2021-06-18T21:34:08.000Z
src/Functions/PoShMon.Configuration/Extensibility.ps1
HiltonGiesenow/PoShMon
770ce92b53ea0e9fc2b78e31e9e52b23da9c35b3
[ "MIT" ]
18
2017-01-28T10:16:49.000Z
2021-09-29T08:47:34.000Z
Function New-ExtensibilityConfig { [CmdletBinding()] param( [string[]]$ExtraTestFilesToInclude = @(), [string[]]$ExtraResolverFilesToInclude = @(), [string[]]$ExtraMergerFilesToInclude = @() ) return @{ TypeName = "PoShMon.ConfigurationItems.Extensibility" ExtraTestFilesToInclude = $ExtraTestFilesToInclude ExtraResolverFilesToInclude = $ExtraResolverFilesToInclude ExtraMergerFilesToInclude = $ExtraMergerFilesToInclude } }
32.625
70
0.657088
729ca522b6392c846046146e80552c77fbd1556c
3,708
sql
SQL
.documents/db script/adsf/query.sql
flash8627/icustom-boot
9605ade055bfbe4cc770ab4cd65b2dc9a59181ea
[ "Apache-2.0" ]
null
null
null
.documents/db script/adsf/query.sql
flash8627/icustom-boot
9605ade055bfbe4cc770ab4cd65b2dc9a59181ea
[ "Apache-2.0" ]
null
null
null
.documents/db script/adsf/query.sql
flash8627/icustom-boot
9605ade055bfbe4cc770ab4cd65b2dc9a59181ea
[ "Apache-2.0" ]
null
null
null
SELECT gh.forecast_header_id forecastheaderid, gh.pdt_type pdttype, gh.pdt_id pdtid, gh.supply_entity_id supplyentityid, gh.bucket_dimension bucketdimension, gh.forecast_dimension_code forecastdimensioncode, gh.forecast_status forecaststatus, gh.delete_flag deleteflag, gh.created_by createdby, gh.created_name creationusercn, gh.creation_date creationdate, gh.last_updated_by lastupdatedby, gh.last_updated_name lastupdateusercn, gh.last_update_date lastupdatedate, pd.pdt_large_code pdtlargecode, pd.pdt_large_name_cn pdtlargenamecn, pd.pdt_large_name_en pdtlargenameen, pd.pdt_large_uom pdtlargeuom, fd.forecast_dimension_desc_cn forecastdimensiondesccn, fd.forecast_dimension_desc_en forecastdimensiondescen, fd.forecast_dimension_category forecastdimensioncategory, fd.edit_flag editflag, fd.rate_flag rateflag, /*(SELECT t.area_org_name_cn FROM dsf_area_org_t t INNER JOIN dsf_demand_entity_t pt ON (t.area_org_code = pt.demand_entity_code AND upper(t.area_org_type) = upper(pt.demand_entity_type) AND t.enable_flag = 'Y' AND pt.enable_flag = 'Y') AND pt.demand_entity_id = de.demand_entity_id AND rownum = 1) areaorgname,*/ (select area_org_name_cn from (SELECT t.area_org_name_cn, pt.demand_entity_id FROM dsf_area_org_t t, dsf_demand_entity_t pt WHERE t.area_org_code = pt.demand_entity_code AND upper(t.area_org_type) = upper(pt.demand_entity_type) AND t.enable_flag = 'Y' AND pt.enable_flag = 'Y') aa where aa.demand_entity_id = de.demand_entity_id) areaorgname, de.demand_entity_id demandentityid, de.bg_code bgcode, de.demand_entity_type demandentitytype, de.demand_entity_code demandentitycode, po.lv0_org_code lv0orgcode, po.lv0_type_name lv0typename, po.lv0_org_name_cn lv0orgnamecn, po.lv0_org_name_en lv0orgnameen, po.lv1_org_code lv1orgcode, po.lv1_type_name lv1typename, po.lv1_org_name_cn lv1orgnamecn, po.lv1_org_name_en lv1orgnameen, po.lv2_org_code lv2orgcode, po.lv2_type_name lv2typename, po.lv2_org_name_cn lv2orgnamecn, po.lv2_org_name_en lv2orgnameen, po.lv3_org_code lv3orgcode, po.lv3_type_name lv3typename, po.lv3_org_name_cn lv3orgnamecn, po.lv3_org_name_en lv3orgnameen, po.lv4_org_code lv4orgcode, po.lv4_type_name lv4typename, po.lv4_org_name_cn lv4orgnamecn, po.lv4_org_name_en lv4orgnameen FROM dsf_forecast_region_header_t gh LEFT JOIN dsf_demand_entity_t de ON (gh.demand_entity_id = de.demand_entity_id AND de.enable_flag = 'Y') LEFT JOIN dsf_area_org_t ao ON (ao.area_org_code = de.demand_entity_code AND ao.area_org_type = 'REGION') LEFT JOIN dsf_pdt_large_t pd ON (pd.pdt_large_id = gh.pdt_id AND pd.enable_flag = 'Y') LEFT JOIN dsf_pdt_org_t po ON (po.pdt_org_id = pd.pdt_org_id AND po.enable_flag = 'Y') LEFT JOIN dsf_forecast_dimension_t fd ON (fd.forecast_dimension_code = gh.forecast_dimension_code AND fd.bg_code = '01' AND upper(fd.demand_entity_type) = upper('region') AND fd.bucket_dimension = 'Y')
38.625
76
0.649137
c4b89cd754ed4e145b5eb1a88a5604a2934d4aac
37,506
cpp
C++
src/method/method_schema_info.cpp
Yechan0815/cubrid
da09d9e60b583d0b7ce5f665429f397976728d99
[ "Apache-2.0", "BSD-3-Clause" ]
null
null
null
src/method/method_schema_info.cpp
Yechan0815/cubrid
da09d9e60b583d0b7ce5f665429f397976728d99
[ "Apache-2.0", "BSD-3-Clause" ]
null
null
null
src/method/method_schema_info.cpp
Yechan0815/cubrid
da09d9e60b583d0b7ce5f665429f397976728d99
[ "Apache-2.0", "BSD-3-Clause" ]
null
null
null
/* * * Copyright 2016 CUBRID Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ #include "method_schema_info.hpp" #include <algorithm> #include <cstring> #include <string> #include "dbtype_def.h" #include "dbi.h" #include "method_query_handler.hpp" #include "method_query_util.hpp" #include "trigger_manager.h" #include "work_space.h" #include "schema_manager.h" #include "language_support.h" namespace cubmethod { schema_info schema_info_handler::get_schema_info (int schema_type, std::string &arg1, std::string &arg2, int flag) { int error = NO_ERROR; schema_info info; switch (schema_type) { case SCH_CLASS: error = sch_class_info (info, arg1, flag, 0); break; case SCH_VCLASS: error = sch_class_info (info, arg1, flag, 1); break; case SCH_QUERY_SPEC: error = sch_queryspec (info, arg1); break; case SCH_ATTRIBUTE: error = sch_attr_info (info, arg1, arg2, flag, 0); break; case SCH_CLASS_ATTRIBUTE: error = sch_attr_info (info, arg1, arg2, flag, 1); break; case SCH_METHOD: error = sch_method_info (info, arg1, 0); break; case SCH_CLASS_METHOD: error = sch_method_info (info, arg1, 1); break; case SCH_METHOD_FILE: error = sch_methfile_info (info, arg1); break; case SCH_SUPERCLASS: error = sch_superclass (info, arg1, 1); break; case SCH_SUBCLASS: error = sch_superclass (info, arg1, 0); break; case SCH_CONSTRAINT: error = sch_constraint (info, arg1); break; case SCH_TRIGGER: error = sch_trigger (info, arg1, flag); break; case SCH_CLASS_PRIVILEGE: error = sch_class_priv (info, arg1, flag); break; case SCH_ATTR_PRIVILEGE: error = sch_attr_priv (info, arg1, arg2, flag); break; case SCH_DIRECT_SUPER_CLASS: error = sch_direct_super_class (info, arg1, flag); break; case SCH_PRIMARY_KEY: error = sch_primary_key (info, arg1); break; case SCH_IMPORTED_KEYS: error = sch_imported_keys (info, arg1); break; case SCH_EXPORTED_KEYS: error = sch_exported_keys_or_cross_reference (info, arg1, arg2, false); break; case SCH_CROSS_REFERENCE: error = sch_exported_keys_or_cross_reference (info, arg1, arg2, true); break; default: error = ER_FAILED; break; } if (error == NO_ERROR) { // TODO: what should I do here? info.schema_type = schema_type; } else { close_and_free_session (); // TODO: proper error code m_error_ctx.set_error (METHOD_CALLBACK_ER_SCHEMA_TYPE, NULL, __FILE__, __LINE__); } return info; } int schema_info_handler::execute_schema_info_query (std::string &sql_stmt) { lang_set_parser_use_client_charset (false); m_session = db_open_buffer (sql_stmt.c_str()); if (!m_session) { lang_set_parser_use_client_charset (true); m_error_ctx.set_error (db_error_code (), db_error_string (1), __FILE__, __LINE__); return ER_FAILED; } int stmt_id = db_compile_statement (m_session); if (stmt_id < 0) { close_and_free_session (); m_error_ctx.set_error (stmt_id, NULL, __FILE__, __LINE__); return ER_FAILED; } DB_QUERY_RESULT *result = NULL; int stmt_type = db_get_statement_type (m_session, stmt_id); lang_set_parser_use_client_charset (false); int num_result = db_execute_statement (m_session, stmt_id, &result); lang_set_parser_use_client_charset (true); if (num_result < 0) { close_and_free_session (); m_error_ctx.set_error (stmt_id, NULL, __FILE__, __LINE__); return ER_FAILED; } query_result &q_result = m_q_result; q_result.stmt_type = stmt_type; q_result.stmt_id = stmt_id; q_result.tuple_count = num_result; q_result.result = result; q_result.include_oid = false; // TODO: managing structure for schema info queries /* m_q_result.push_back (q_result); m_max_col_size = -1; m_current_result_index = 0; m_current_result = &m_q_result[m_current_result_index]; m_has_result_set = true; */ return num_result; } int schema_info_handler::sch_class_info (schema_info &info, std::string &class_name, int pattern_flag, int v_class_flag) { std::string schema_name; std::string class_name_only; std::size_t found; std::transform (class_name.begin(), class_name.end(), class_name.begin(), ::tolower); class_name_only = class_name; found = class_name.find ('.'); if (found != std::string::npos) { /* If the length is not correct, the username is invalid, so compare the entire class_name. */ if (found > 0 && found < DB_MAX_SCHEMA_LENGTH) { schema_name = class_name.substr (0, found); class_name_only = class_name.substr (found + 1); } } // *INDENT-OFF* std::string sql = "" "SELECT " "CASE " "WHEN is_system_class = 'NO' THEN LOWER (owner_name) || '.' || class_name " "ELSE class_name " "END AS unique_name, " "CAST ( " "CASE " "WHEN is_system_class = 'YES' THEN 0 " "WHEN class_type = 'CLASS' THEN 2 " "ELSE 1 " "END " "AS SHORT " "), " "comment " "FROM " "db_class " "WHERE 1 = 1 "; // *INDENT-ON* if (v_class_flag) { sql.append ("AND class_type = 'VCLASS' "); } if (pattern_flag & CLASS_NAME_PATTERN_MATCH) { if (!class_name_only.empty()) { /* AND class_name LIKE '%s' ESCAPE '%s' */ sql.append ("AND class_name LIKE '"); sql.append (class_name_only); sql.append ("' ESCAPE '"); sql.append (get_backslash_escape_string ()); sql.append ("' "); } } else { /* AND class_name = '%s' */ sql.append ("AND class_name = '"); sql.append (class_name_only); sql.append ("' "); } if (!schema_name.empty()) { /* AND owner_name = UPPER ('%s') */ sql.append ("AND owner_name = UPPER ('"); sql.append (schema_name); sql.append ("') "); } int num_result = execute_schema_info_query (sql); if (num_result < 0) { return num_result; } info.num_result = num_result; return NO_ERROR; } int schema_info_handler::sch_attr_info (schema_info &info, std::string &class_name, std::string &attr_name, int pattern_flag, int class_attr_flag) { std::string schema_name; std::string class_name_only; std::size_t found; std::transform (class_name.begin(), class_name.end(), class_name.begin(), ::tolower); std::transform (attr_name.begin(), attr_name.end(), attr_name.begin(), ::tolower); class_name_only = class_name; found = class_name.find ('.'); if (found != std::string::npos) { /* If the length is not correct, the username is invalid, so compare the entire class_name. */ if (found > 0 && found < DB_MAX_SCHEMA_LENGTH) { schema_name = class_name.substr (0, found); class_name_only = class_name.substr (found + 1); } } // *INDENT-OFF* std::string sql = "" "SELECT " "CASE " "WHEN ( " "SELECT b.is_system_class " "FROM db_class b " "WHERE b.class_name = a.class_name AND b.owner_name = a.owner_name " ") = 'NO' THEN LOWER (a.owner_name) || '.' || a.class_name " "ELSE a.class_name " "END AS unique_name, " "a.attr_name " "FROM " "db_attribute a " "WHERE 1 = 1 "; // *INDENT-ON* if (class_attr_flag) { sql.append ("AND a.attr_type = 'CLASS' "); } else { sql.append ("AND a.attr_type in {'INSTANCE', 'SHARED'} "); } if (pattern_flag & CLASS_NAME_PATTERN_MATCH) { if (!class_name_only.empty()) { /* AND class_name LIKE '%s' ESCAPE '%s' */ sql.append ("AND a.class_name LIKE '"); sql.append (class_name_only); sql.append ("' ESCAPE '"); sql.append (get_backslash_escape_string ()); sql.append ("' "); } } else { /* AND class_name = '%s' */ sql.append ("AND a.class_name = '"); sql.append (class_name_only); sql.append ("' "); } if (pattern_flag & ATTR_NAME_PATTERN_MATCH) { if (!attr_name.empty()) { /* AND a.attr_name LIKE '%s' ESCAPE '%s' */ sql.append ("AND a.attr_name LIKE '"); sql.append (attr_name); sql.append ("' ESCAPE '"); sql.append (get_backslash_escape_string ()); sql.append ("' "); } } else { /* AND a.attr_name = '%s' */ sql.append ("AND a.class_name = '"); sql.append (attr_name); sql.append ("' "); } if (!schema_name.empty()) { /* AND owner_name = UPPER ('%s') */ sql.append ("AND a.owner_name = UPPER ('"); sql.append (schema_name); sql.append ("') "); } sql.append ("ORDER BY a.class_name, a.def_order "); int num_result = execute_schema_info_query (sql); if (num_result < 0) { return num_result; } info.num_result = num_result; return NO_ERROR; } int schema_info_handler::sch_queryspec (schema_info &info, std::string &class_name) { std::string schema_name; std::string class_name_only; std::size_t found; std::transform (class_name.begin(), class_name.end(), class_name.begin(), ::tolower); class_name_only = class_name; found = class_name.find ('.'); if (found != std::string::npos) { /* If the length is not correct, the username is invalid, so compare the entire class_name. */ if (found > 0 && found < DB_MAX_SCHEMA_LENGTH) { schema_name = class_name.substr (0, found); class_name_only = class_name.substr (found + 1); } } std::string sql = "SELECT vclass_def FROM db_vclass WHERE unique_name = '"; sql.append (class_name_only); sql.append ("' "); if (!schema_name.empty()) { /* AND owner_name = UPPER ('%s') */ sql.append ("AND owner_name = UPPER ('"); sql.append (schema_name); sql.append ("') "); } int num_result = execute_schema_info_query (sql); if (num_result < 0) { return num_result; } info.num_result = num_result; return NO_ERROR; } int schema_info_handler::sch_method_info (schema_info &info, std::string &class_name, int flag) { DB_OBJECT *class_obj = db_find_class (class_name.c_str()); DB_METHOD *method_list; if (flag) { method_list = db_get_class_methods (class_obj); } else { method_list = db_get_methods (class_obj); } int num_method = 0; for (DB_METHOD *method = method_list; method; method = db_method_next (method)) { num_method++; } info.num_result = num_method; m_method_list = method_list; return NO_ERROR; } int schema_info_handler::sch_methfile_info (schema_info &info, std::string &class_name) { DB_OBJECT *class_obj = db_find_class (class_name.c_str()); DB_METHFILE *method_files = db_get_method_files (class_obj); int num_mf= 0; for (DB_METHFILE *mf = method_files; mf; mf = db_methfile_next (mf)) { num_mf++; } info.num_result = num_mf; m_method_files = method_files; return NO_ERROR; } int schema_info_handler::sch_superclass (schema_info &info, std::string &class_name, int flag) { int error = NO_ERROR; DB_OBJECT *class_obj = db_find_class (class_name.c_str()); DB_OBJLIST *obj_list = NULL; if (flag) { obj_list = db_get_superclasses (class_obj); } else { obj_list = db_get_subclasses (class_obj); } class_table ct; for (DB_OBJLIST *tmp = obj_list; tmp; tmp = tmp->next) { char *p = (char *) db_get_class_name (tmp->op); int cls_type = class_type (tmp->op); if (cls_type < 0) { error = cls_type; break; } ct.class_name.assign (p); ct.class_type = cls_type; m_obj_list.push_back (ct); } db_objlist_free (obj_list); info.num_result = m_obj_list.size (); return error; } int schema_info_handler::sch_constraint (schema_info &info, std::string &class_name) { DB_OBJECT *class_obj = db_find_class (class_name.c_str ()); DB_CONSTRAINT *constraint = db_get_constraints (class_obj); int num_const = 0; for (DB_CONSTRAINT *tmp_c = constraint; tmp_c; tmp_c = db_constraint_next (tmp_c)) { int type = db_constraint_type (tmp_c); switch (type) { case DB_CONSTRAINT_UNIQUE: case DB_CONSTRAINT_INDEX: case DB_CONSTRAINT_REVERSE_UNIQUE: case DB_CONSTRAINT_REVERSE_INDEX: { DB_ATTRIBUTE **attr = db_constraint_attributes (tmp_c); for (int i = 0; attr[i]; i++) { num_const++; } } default: break; } } info.num_result = num_const; m_constraint = constraint; return NO_ERROR; } int schema_info_handler::sch_trigger (schema_info &info, std::string &class_name, int flag) { int error = NO_ERROR; bool is_pattern_match = (flag & CLASS_NAME_PATTERN_MATCH) ? true : false; info.num_result = 0; if (class_name.empty () && !is_pattern_match) { return NO_ERROR; } DB_OBJLIST *tmp_trigger = NULL; if (db_find_all_triggers (&tmp_trigger) < 0) { return NO_ERROR; } int num_trig = 0; DB_OBJLIST *all_trigger = NULL; if (class_name.empty ()) { all_trigger = tmp_trigger; num_trig = db_list_length ((DB_LIST *) all_trigger); } else { std::string schema_name; DB_OBJECT *owner = NULL; std::string class_name_only = class_name; std::size_t found = class_name.find ('.'); if (found != std::string::npos) { /* If the length is not correct, the username is invalid, so compare the entire class_name. */ if (found > 0 && found < DB_MAX_SCHEMA_LENGTH) { schema_name = class_name.substr (0, found); /* If the user does not exist, compare the entire class_name. */ owner = db_find_user (schema_name.c_str ()); if (owner != NULL) { class_name_only = class_name.substr (found + 1); } } } DB_OBJLIST *tmp = NULL; for (tmp = tmp_trigger; tmp; tmp = tmp->next) { MOP tmp_obj = tmp->op; assert (tmp_obj != NULL); TR_TRIGGER *trigger = tr_map_trigger (tmp_obj, 1); if (trigger == NULL) { assert (er_errid () != NO_ERROR); error = er_errid (); break; } DB_OBJECT *obj_trigger_target = trigger->class_mop; assert (obj_trigger_target != NULL); const char *name_trigger_target = sm_get_ch_name (obj_trigger_target); if (name_trigger_target == NULL) { assert (er_errid () != NO_ERROR); error = er_errid (); break; } const char *only_name_trigger_target = name_trigger_target; /* If the user does not exist, compare the entire class_name. */ if (owner) { only_name_trigger_target = strchr (name_trigger_target, '.'); if (only_name_trigger_target) { only_name_trigger_target = only_name_trigger_target + 1; } else { assert (false); } /* If the owner is different from the specified owner, skip it. */ if (db_get_owner (tmp_obj) != owner) { continue; } } if (is_pattern_match) { if (str_like (std::string (name_trigger_target), class_name_only.c_str (), '\\') == 1) { error = ml_ext_add (&all_trigger, tmp_obj, NULL); if (error != NO_ERROR) { break; } num_trig++; } } else { if (strcmp (class_name_only.c_str (), name_trigger_target) == 0) { error = ml_ext_add (&all_trigger, tmp_obj, NULL); if (error != NO_ERROR) { break; } num_trig++; } } } if (tmp_trigger) { ml_ext_free (tmp_trigger); } if (error != NO_ERROR && all_trigger) { ml_ext_free (all_trigger); all_trigger = NULL; num_trig = 0; } } info.num_result = num_trig; m_all_trigger = all_trigger; return error; } int schema_info_handler::sch_class_priv (schema_info &info, std::string &class_name, int pat_flag) { int num_tuple = 0; unsigned int class_priv; if ((pat_flag & CLASS_NAME_PATTERN_MATCH) == 0) { if (!class_name.empty()) { DB_OBJECT *class_obj = db_find_class (class_name.c_str ()); if (class_obj != NULL) { if (db_get_class_privilege (class_obj, &class_priv) >= 0) { num_tuple = set_priv_table (m_priv_tbl, 0, (char *) db_get_class_name (class_obj), class_priv); } } } } else { std::string schema_name; DB_OBJECT *owner = NULL; std::string class_name_only = class_name; std::size_t found = class_name.find ('.'); if (found != std::string::npos) { /* If the length is not correct, the username is invalid, so compare the entire class_name. */ if (found > 0 && found < DB_MAX_SCHEMA_LENGTH) { schema_name = class_name.substr (0, found); /* If the user does not exist, compare the entire class_name. */ owner = db_find_user (schema_name.c_str ()); if (owner != NULL) { class_name_only = class_name.substr (found + 1); } } } DB_OBJLIST *obj_list = db_get_all_classes (); for (DB_OBJLIST *tmp = obj_list; tmp; tmp = tmp->next) { char *p = (char *) db_get_class_name (tmp->op); char *q = p; /* If the user does not exist, compare the entire class_name. */ if (owner && db_is_system_class (tmp->op) == FALSE) { /* p: unique_name, q: class_name */ q = strchr (p, '.'); if (q) { q = q + 1; } else { assert (false); } /* If the owner is different from the specified owner, skip it. */ if (db_get_owner (tmp->op) != owner) { continue; } } if (!class_name.empty() && str_like (std::string (q), class_name.c_str(), '\\') < 1) { continue; } if (db_get_class_privilege (tmp->op, &class_priv) >= 0) { num_tuple += set_priv_table (m_priv_tbl, num_tuple, (char *) db_get_class_name (tmp->op), class_priv); } } db_objlist_free (obj_list); } info.num_result = num_tuple; return NO_ERROR; } int schema_info_handler::sch_attr_priv (schema_info &info, std::string &class_name, std::string &attr_name_pat, int pat_flag) { int num_tuple = 0; DB_OBJECT *class_obj = db_find_class (class_name.c_str ()); if (class_obj == NULL) { info.num_result = num_tuple; return NO_ERROR; } unsigned int class_priv; if (db_get_class_privilege (class_obj, &class_priv) >= 0) { DB_ATTRIBUTE *attributes = db_get_attributes (class_obj); for (DB_ATTRIBUTE *attr = attributes; attr; attr = db_attribute_next (attr)) { char *attr_name = (char *) db_attribute_name (attr); if (pat_flag & ATTR_NAME_PATTERN_MATCH) { if (attr_name_pat.empty() == false && str_like (std::string (attr_name), attr_name_pat.c_str (), '\\') < 1) { continue; } } else { if (attr_name_pat.empty() == true || strcmp (attr_name, attr_name_pat.c_str ()) != 0) { continue; } } num_tuple += set_priv_table (m_priv_tbl, num_tuple, (char *) db_get_class_name (class_obj), class_priv); } } info.num_result = num_tuple; return NO_ERROR; } int schema_info_handler::sch_direct_super_class (schema_info &info, std::string &class_name, int pattern_flag) { std::string schema_name; std::string class_name_only; std::size_t found; std::transform (class_name.begin(), class_name.end(), class_name.begin(), ::tolower); class_name_only = class_name; found = class_name.find ('.'); if (found != std::string::npos) { /* If the length is not correct, the username is invalid, so compare the entire class_name. */ if (found > 0 && found < DB_MAX_SCHEMA_LENGTH) { schema_name = class_name.substr (0, found); class_name_only = class_name.substr (found + 1); } } // *INDENT-OFF* std::string sql = "" "SELECT " "CASE " "WHEN ( " "SELECT b.is_system_class " "FROM db_class b " "WHERE b.class_name = a.class_name AND b.owner_name = a.owner_name " ") = 'NO' THEN LOWER (a.owner_name) || '.' || a.class_name " "ELSE a.class_name " "END AS unique_name, " "CASE " "WHEN ( " "SELECT b.is_system_class " "FROM db_class b " "WHERE b.class_name = a.super_class_name AND b.owner_name = a.super_owner_name " ") = 'NO' THEN LOWER (a.super_owner_name) || '.' || a.super_class_name " "ELSE a.super_class_name " "END AS super_unique_name " "FROM " "db_direct_super_class a " "WHERE 1 = 1 "; // *INDENT-ON* if (pattern_flag & CLASS_NAME_PATTERN_MATCH) { if (!class_name_only.empty()) { /* AND class_name LIKE '%s' ESCAPE '%s' */ sql.append ("AND class_name LIKE '"); sql.append (class_name_only); sql.append ("' ESCAPE '"); sql.append (get_backslash_escape_string ()); sql.append ("' "); } } else { /* AND class_name = '%s' */ sql.append ("AND class_name = '"); sql.append (class_name_only); sql.append ("' "); } if (!schema_name.empty()) { /* AND owner_name = UPPER ('%s') */ sql.append ("AND owner_name = UPPER ('"); sql.append (schema_name); sql.append ("') "); } int num_result = execute_schema_info_query (sql); if (num_result < 0) { return num_result; } info.num_result = num_result; return NO_ERROR; } int schema_info_handler::sch_primary_key (schema_info &info, std::string &class_name) { std::string schema_name; std::string class_name_only; std::size_t found; int num_result = 0; int i; std::transform (class_name.begin(), class_name.end(), class_name.begin(), ::tolower); class_name_only = class_name; found = class_name.find ('.'); if (found != std::string::npos) { /* If the length is not correct, the username is invalid, so compare the entire class_name. */ if (found > 0 && found < DB_MAX_SCHEMA_LENGTH) { schema_name = class_name.substr (0, found); class_name_only = class_name.substr (found + 1); } } DB_OBJECT *class_object = db_find_class (class_name.c_str ()); if (class_object != NULL) { // *INDENT-OFF* std::string sql = "" "SELECT " "CASE " "WHEN ( " "SELECT c.is_system_class " "FROM db_class c " "WHERE c.class_name = a.class_name AND c.owner_name = a.owner_name " ") = 'NO' THEN LOWER (a.owner_name) || '.' || a.class_name " "ELSE a.class_name " "END AS unique_name, " "b.key_attr_name, " "b.key_order + 1, " "a.index_name " "FROM " "db_index a, " "db_index_key b " "WHERE " "a.index_name = b.index_name " "AND a.class_name = b.class_name " "AMD a.owner_name = b.owner_name " "AND a.is_primary_key = 'YES' " "AND a.class_name = '"; sql.append (class_name_only); sql.append ("' "); // *INDENT-ON* if (!schema_name.empty()) { /* AND owner_name = UPPER ('%s') */ sql.append ("AND owner_name = UPPER ('"); sql.append (schema_name); sql.append ("') "); } sql.append ("ORDER BY b.key_attr_name"); num_result = execute_schema_info_query (sql); if (num_result < 0) { return num_result; } } info.num_result = num_result; return NO_ERROR; } int schema_info_handler::sch_imported_keys (schema_info &info, std::string &fktable_name) { int error = NO_ERROR; int num_fk_info = 0, i = 0; DB_OBJECT *fktable_obj = db_find_class (fktable_name.c_str ()); if (fktable_obj == NULL) { /* The followings are possible situations. - A table matching fktable_name does not exist. - User has no * authorization on the table. - Other error we do not expect. In these cases, we will send an empty result. And * this rule is also applied to CCI_SCH_EXPORTED_KEYS and CCI_SCH_CROSS_REFERENCE. */ info.num_result = num_fk_info; return NO_ERROR; } for (DB_CONSTRAINT *fk_const = db_get_constraints (fktable_obj); fk_const != NULL; fk_const = db_constraint_next (fk_const)) { DB_CONSTRAINT_TYPE type = db_constraint_type (fk_const); if (type != DB_CONSTRAINT_FOREIGN_KEY) { continue; } SM_FOREIGN_KEY_INFO *fk_info = fk_const->fk_info; /* Find referenced table to get table name and columns. */ DB_OBJECT *pktable_obj = db_get_foreign_key_ref_class (fk_const); if (pktable_obj == NULL) { m_error_ctx.set_error (db_error_code (), db_error_string (1), __FILE__, __LINE__); return ER_FAILED; } const char *pktable_name = db_get_class_name (pktable_obj); if (pktable_name == NULL) { m_error_ctx.set_error (db_error_code (), db_error_string (1), __FILE__, __LINE__); return ER_FAILED; } DB_CONSTRAINT *pktable_cons = db_get_constraints (pktable_obj); error = db_error_code (); if (error != NO_ERROR) { m_error_ctx.set_error (db_error_code (), db_error_string (1), __FILE__, __LINE__); return ER_FAILED; } DB_CONSTRAINT *pk = db_constraint_find_primary_key (pktable_cons); if (pk == NULL) { m_error_ctx.set_error (ER_FK_REF_CLASS_HAS_NOT_PK, "Referenced class has no primary key.", __FILE__, __LINE__); return ER_FAILED; } const char *pk_name = db_constraint_name (pk); DB_ATTRIBUTE **pk_attr = db_constraint_attributes (pk); if (pk_attr == NULL) { m_error_ctx.set_error (ER_SM_INVALID_CONSTRAINT, "Primary key has no attribute.", __FILE__, __LINE__); return ER_FAILED; } DB_ATTRIBUTE **fk_attr = db_constraint_attributes (fk_const); if (fk_attr == NULL) { m_error_ctx.set_error (ER_SM_INVALID_CONSTRAINT, "Foreign key has no attribute.", __FILE__, __LINE__); return ER_FAILED; } for (i = 0; pk_attr[i] != NULL && fk_attr[i] != NULL; i++) { // TODO: not implemented yet /* fk_res = add_fk_info_result (fk_res, pktable_name, db_attribute_name (pk_attr[i]), fktable_name, db_attribute_name (fk_attr[i]), (short) i + 1, fk_info->update_action, fk_info->delete_action, fk_info->name, pk_name, FK_INFO_SORT_BY_PKTABLE_NAME); if (fk_res == NULL) m_error_ctx.set_error (METHOD_CALLBACK_ER_NO_MORE_MEMORY, NULL, __FILE__, __LINE__); { return ER_FAILED; } */ num_fk_info++; } /* pk_attr and fk_attr is null-terminated array. So, they should be null at this time. If one of them is not * null, it means that they have different number of attributes. */ assert (pk_attr[i] == NULL && fk_attr[i] == NULL); if (pk_attr[i] != NULL || fk_attr[i] != NULL) { m_error_ctx.set_error (ER_FK_NOT_MATCH_KEY_COUNT, "The number of keys of the foreign key is different from that of the primary key.", __FILE__, __LINE__); return ER_FAILED; } } info.num_result = num_fk_info; return NO_ERROR; } int schema_info_handler::sch_exported_keys_or_cross_reference (schema_info &info, std::string &pktable_name, std::string &fktable_name, bool find_cross_ref) { // TODO return NO_ERROR; } int schema_info_handler::class_type (DB_OBJECT *class_obj) { int error = db_is_system_class (class_obj); if (error < 0) { m_error_ctx.set_error (error, NULL, __FILE__, __LINE__); return ER_FAILED; } if (error > 0) { return 0; } error = db_is_vclass (class_obj); if (error < 0) { m_error_ctx.set_error (error, NULL, __FILE__, __LINE__); return ER_FAILED; } if (error > 0) { return 1; } return 2; } int schema_info_handler::set_priv_table (std::vector<priv_table> &pts, int index, char *name, unsigned int class_priv) { int grant_opt = class_priv >> 8; int priv_type = 1; int num_tuple = 0; for (int i = 0; i < 7; i++) { if (class_priv & priv_type) { priv_table pt; pt.class_name.assign (name); pt.priv = priv_type; if (grant_opt & priv_type) { pt.grant = 1; } else { pt.grant = 0; } pts.push_back (pt); num_tuple++; } priv_type <<= 1; } return num_tuple; } void schema_info_handler::close_and_free_session () { if (m_session) { db_close_session ((DB_SESSION *) (m_session)); } m_session = NULL; } std::vector<column_info> get_schema_table_meta () { column_info name (DB_TYPE_STRING, DB_TYPE_NULL, 0, DB_MAX_IDENTIFIER_LENGTH, lang_charset(), "NAME"); column_info type (DB_TYPE_SHORT, DB_TYPE_NULL, 0, 0, lang_charset(), "TYPE"); column_info remarks (DB_TYPE_STRING, DB_TYPE_NULL, 0, DB_MAX_CLASS_COMMENT_LENGTH, lang_charset(), "REMARKS"); return std::vector<column_info> {name, type, remarks}; } std::vector<column_info> get_schema_query_spec_meta () { column_info query_spec (DB_TYPE_STRING, DB_TYPE_NULL, 0, DB_MAX_IDENTIFIER_LENGTH, lang_charset(), "QUERY_SPEC"); return std::vector<column_info> {query_spec}; } std::vector<column_info> get_schema_attr_meta () { column_info attr_name (DB_TYPE_STRING, DB_TYPE_NULL, 0, DB_MAX_IDENTIFIER_LENGTH, lang_charset(), "ATTR_NAME"); column_info domain (DB_TYPE_SHORT, DB_TYPE_NULL, 0, 0, lang_charset(), "DOMAIN"); column_info scale (DB_TYPE_SHORT, DB_TYPE_NULL, 0, 0, lang_charset(), "SCALE"); column_info precision (DB_TYPE_INTEGER, DB_TYPE_NULL, 0, 0, lang_charset(), "PRECISION"); column_info indexed (DB_TYPE_SHORT, DB_TYPE_NULL, 0, 0, lang_charset(), "INDEXED"); column_info non_null (DB_TYPE_SHORT, DB_TYPE_NULL, 0, 0, lang_charset(), "NON_NULL"); column_info shared (DB_TYPE_SHORT, DB_TYPE_NULL, 0, 0, lang_charset(), "SHARED"); column_info unique (DB_TYPE_SHORT, DB_TYPE_NULL, 0, 0, lang_charset(), "UNIQUE"); column_info default_ (DB_TYPE_STRING, DB_TYPE_NULL, 0, DB_MAX_IDENTIFIER_LENGTH, lang_charset(), "DEFAULT"); column_info attr_order (DB_TYPE_INTEGER, DB_TYPE_NULL, 0, 0, lang_charset(), "ATTR_ORDER"); column_info class_name (DB_TYPE_STRING, DB_TYPE_NULL, 0, DB_MAX_IDENTIFIER_LENGTH, lang_charset(), "CLASS_NAME"); column_info source_class (DB_TYPE_STRING, DB_TYPE_NULL, 0, DB_MAX_IDENTIFIER_LENGTH, lang_charset(), "SOURCE_CLASS"); column_info is_key (DB_TYPE_SHORT, DB_TYPE_NULL, 0, 0, lang_charset(), "IS_KEY"); column_info remarks (DB_TYPE_STRING, DB_TYPE_NULL, 0, DB_MAX_CLASS_COMMENT_LENGTH, lang_charset(), "REMARKS"); return std::vector<column_info> {attr_name, domain, scale, precision, indexed, non_null, shared, unique, default_, attr_order, class_name, source_class, is_key, remarks}; } std::vector<column_info> get_schema_method_meta () { column_info name (DB_TYPE_STRING, DB_TYPE_NULL, 0, DB_MAX_IDENTIFIER_LENGTH, lang_charset(), "NAME"); column_info ret_domain (DB_TYPE_SHORT, DB_TYPE_NULL, 0, 0, lang_charset(), "RET_DOMAIN"); column_info arg_domain (DB_TYPE_STRING, DB_TYPE_NULL, 0, DB_MAX_IDENTIFIER_LENGTH, lang_charset(), "ARG_DOMAIN"); return std::vector<column_info> {name, ret_domain, arg_domain}; } std::vector<column_info> get_schema_methodfile_meta () { column_info met_file (DB_TYPE_STRING, DB_TYPE_NULL, 0, DB_MAX_IDENTIFIER_LENGTH, lang_charset(), "METHOD_FILE"); return std::vector<column_info> {met_file}; } std::vector<column_info> get_schema_superclasss_meta () { column_info class_name (DB_TYPE_STRING, DB_TYPE_NULL, 0, DB_MAX_IDENTIFIER_LENGTH, lang_charset(), "CLASS_NAME"); column_info type (DB_TYPE_SHORT, DB_TYPE_NULL, 0, 0, lang_charset(), "TYPE"); return std::vector<column_info> {class_name, type}; } std::vector<column_info> get_schema_constraint_meta () { column_info type (DB_TYPE_SHORT, DB_TYPE_NULL, 0, 0, lang_charset(), "TYPE"); column_info name (DB_TYPE_STRING, DB_TYPE_NULL, 0, DB_MAX_IDENTIFIER_LENGTH, lang_charset(), "NAME"); column_info attr_name (DB_TYPE_STRING, DB_TYPE_NULL, 0, DB_MAX_IDENTIFIER_LENGTH, lang_charset(), "ATTR_NAME"); column_info num_pages (DB_TYPE_INTEGER, DB_TYPE_NULL, 0, 0, lang_charset(), "NUM_PAGES"); column_info num_keys (DB_TYPE_INTEGER, DB_TYPE_NULL, 0, 0, lang_charset(), "NUM_KEYS"); column_info primary_key (DB_TYPE_SHORT, DB_TYPE_NULL, 0, 0, lang_charset(), "PRIMARY_KEY"); column_info key_order (DB_TYPE_SHORT, DB_TYPE_NULL, 0, 0, lang_charset(), "KEY_ORDER"); column_info asc_desc (DB_TYPE_STRING, DB_TYPE_NULL, 0, DB_MAX_IDENTIFIER_LENGTH, lang_charset(), "ASC_DESC"); return std::vector<column_info> {type, name, attr_name, num_pages, num_keys, primary_key, key_order, asc_desc}; } std::vector<column_info> get_schema_trigger_meta () { column_info name (DB_TYPE_STRING, DB_TYPE_NULL, 0, DB_MAX_IDENTIFIER_LENGTH, lang_charset(), "NAME"); column_info status (DB_TYPE_STRING, DB_TYPE_NULL, 0, DB_MAX_IDENTIFIER_LENGTH, lang_charset(), "STATUS"); column_info event (DB_TYPE_STRING, DB_TYPE_NULL, 0, DB_MAX_IDENTIFIER_LENGTH, lang_charset(), "EVENT"); column_info target_class (DB_TYPE_STRING, DB_TYPE_NULL, 0, DB_MAX_IDENTIFIER_LENGTH, lang_charset(), "TARGET_CLASS"); column_info target_attr (DB_TYPE_STRING, DB_TYPE_NULL, 0, DB_MAX_IDENTIFIER_LENGTH, lang_charset(), "TARGET_ATTR"); column_info action_time (DB_TYPE_STRING, DB_TYPE_NULL, 0, DB_MAX_IDENTIFIER_LENGTH, lang_charset(), "ACTION_TIME"); column_info action (DB_TYPE_STRING, DB_TYPE_NULL, 0, DB_MAX_IDENTIFIER_LENGTH, lang_charset(), "ACTION"); column_info priority (DB_TYPE_FLOAT, DB_TYPE_NULL, 0, 0, lang_charset(), "PRIORITY"); column_info condition_time (DB_TYPE_STRING, DB_TYPE_NULL, 0, DB_MAX_IDENTIFIER_LENGTH, lang_charset(), "CONDITION_TIME"); column_info condition (DB_TYPE_STRING, DB_TYPE_NULL, 0, DB_MAX_IDENTIFIER_LENGTH, lang_charset(), "CONDITION"); column_info remarks (DB_TYPE_STRING, DB_TYPE_NULL, 0, DB_MAX_CLASS_COMMENT_LENGTH, lang_charset(), "REMARKS"); return std::vector<column_info> {name, status, event, target_class, target_attr, action_time, action, priority, condition_time, condition, remarks}; } std::vector<column_info> get_schema_classpriv_meta () { column_info class_name (DB_TYPE_STRING, DB_TYPE_NULL, 0, DB_MAX_IDENTIFIER_LENGTH, lang_charset(), "CLASS_NAME"); column_info privilege (DB_TYPE_STRING, DB_TYPE_NULL, 0, 10, lang_charset(), "PRIVILEGE"); column_info grantable (DB_TYPE_STRING, DB_TYPE_NULL, 0, 5, lang_charset(), "GRANTABLE"); return std::vector<column_info> {class_name, privilege, grantable}; } std::vector<column_info> get_schema_attrpriv_meta () { column_info attr_name (DB_TYPE_STRING, DB_TYPE_NULL, 0, DB_MAX_IDENTIFIER_LENGTH, lang_charset(), "ATTR_NAME"); column_info privilege (DB_TYPE_STRING, DB_TYPE_NULL, 0, 10, lang_charset(), "PRIVILEGE"); column_info grantable (DB_TYPE_STRING, DB_TYPE_NULL, 0, 5, lang_charset(), "GRANTABLE"); return std::vector<column_info> {attr_name, privilege, grantable}; } std::vector<column_info> get_schema_directsuper_meta () { column_info class_name (DB_TYPE_STRING, DB_TYPE_NULL, 0, DB_MAX_IDENTIFIER_LENGTH, lang_charset(), "CLASS_NAME"); column_info super_class_name (DB_TYPE_STRING, DB_TYPE_NULL, 0, DB_MAX_IDENTIFIER_LENGTH, lang_charset(), "SUPER_CLASS_NAME"); return std::vector<column_info> {class_name, super_class_name}; } std::vector<column_info> get_schema_primarykey_meta () { column_info class_name (DB_TYPE_STRING, DB_TYPE_NULL, 0, DB_MAX_IDENTIFIER_LENGTH, lang_charset(), "CLASS_NAME"); column_info attr_name (DB_TYPE_STRING, DB_TYPE_NULL, 0, DB_MAX_IDENTIFIER_LENGTH, lang_charset(), "ATTR_NAME"); column_info num_keys (DB_TYPE_INTEGER, DB_TYPE_NULL, 0, 0, lang_charset(), "KEY_SEQ"); column_info key_name (DB_TYPE_STRING, DB_TYPE_NULL, 0, DB_MAX_IDENTIFIER_LENGTH, lang_charset(), "KEY_NAME"); return std::vector<column_info> {class_name, attr_name, num_keys, key_name}; } std::vector<column_info> get_schema_fk_info_meta () { column_info pktable_name (DB_TYPE_STRING, DB_TYPE_NULL, 0, DB_MAX_IDENTIFIER_LENGTH, lang_charset(), "PKTABLE_NAME"); column_info pkcolumn_name (DB_TYPE_STRING, DB_TYPE_NULL, 0, DB_MAX_IDENTIFIER_LENGTH, lang_charset(), "PKCOLUMN_NAME"); column_info fktable_name (DB_TYPE_STRING, DB_TYPE_NULL, 0, DB_MAX_IDENTIFIER_LENGTH, lang_charset(), "FKTABLE_NAME"); column_info fkcolumn_name (DB_TYPE_STRING, DB_TYPE_NULL, 0, DB_MAX_IDENTIFIER_LENGTH, lang_charset(), "FKCOLUMN_NAME"); column_info key_seq (DB_TYPE_SHORT, DB_TYPE_NULL, 0, 0, lang_charset(), "KEY_SEQ"); column_info update_rule (DB_TYPE_SHORT, DB_TYPE_NULL, 0, 0, lang_charset(), "UPDATE_RULE"); column_info delete_rule (DB_TYPE_SHORT, DB_TYPE_NULL, 0, 0, lang_charset(), "DELETE_RULE"); column_info fk_name (DB_TYPE_STRING, DB_TYPE_NULL, 0, DB_MAX_IDENTIFIER_LENGTH, lang_charset(), "FK_NAME"); column_info pk_name (DB_TYPE_STRING, DB_TYPE_NULL, 0, DB_MAX_IDENTIFIER_LENGTH, lang_charset(), "PK_NAME"); return std::vector<column_info> {pktable_name, pkcolumn_name, fktable_name, fkcolumn_name, key_seq, update_rule, delete_rule, fk_name, pk_name}; } }
29.43956
174
0.661174
301090c420513009b6fc25c447bc503c0276b665
1,431
sql
SQL
SQL/DB_Initial.sql
i-chi-li/micronaut-kotlin-blanco-sample
0fbff11f2495bac941eecbee4f4577d7ae9c2f98
[ "Apache-2.0" ]
null
null
null
SQL/DB_Initial.sql
i-chi-li/micronaut-kotlin-blanco-sample
0fbff11f2495bac941eecbee4f4577d7ae9c2f98
[ "Apache-2.0" ]
null
null
null
SQL/DB_Initial.sql
i-chi-li/micronaut-kotlin-blanco-sample
0fbff11f2495bac941eecbee4f4577d7ae9c2f98
[ "Apache-2.0" ]
null
null
null
CREATE DATABASE IF NOT EXISTS `sample00` DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci; USE `sample00`; CREATE TABLE IF NOT EXISTS `users` ( `user_id` INTEGER UNSIGNED NOT NULL, `user_name` VARCHAR(50) NOT NULL, `password` VARCHAR(50) NOT NULL, `email` VARCHAR(200), `created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, `updated_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, PRIMARY KEY (`user_id`) ); CREATE INDEX idx_users_user_name ON `users` (user_name); CREATE INDEX idx_users_password ON `users` (password); CREATE INDEX idx_users_email ON `users` (email); CREATE INDEX idx_users_created_at ON `users` (created_at); CREATE INDEX idx_users_updated_at ON `users` (updated_at); INSERT INTO `users` (user_id, user_name, password, email) SELECT 0, '桃太 郎', 'pass001', '[email protected]' FROM dual WHERE NOT EXISTS(SELECT * FROM users WHERE user_id = 0); INSERT INTO `users` (user_id, user_name, password, email) SELECT 1, 'い ぬ', 'pass002', NULL FROM dual WHERE NOT EXISTS(SELECT * FROM users WHERE user_id = 1); INSERT INTO `users` (user_id, user_name, password, email) SELECT 2, 'き じ', 'pass003', NULL FROM dual WHERE NOT EXISTS(SELECT * FROM users WHERE user_id = 2); INSERT INTO `users` (user_id, user_name, password, email) SELECT 3, 'さ る', 'pass004', NULL FROM dual WHERE NOT EXISTS(SELECT * FROM users WHERE user_id = 3);
34.071429
89
0.730957
8544a07e118e809520fc42d35de3a9255338a996
1,152
cs
C#
Assets/Scripts/Scriptables/ItemScriptable.cs
jackieateacat/full-project
c19110d126d3e629c75f5908c9ce39fe039c2e9e
[ "Unlicense" ]
null
null
null
Assets/Scripts/Scriptables/ItemScriptable.cs
jackieateacat/full-project
c19110d126d3e629c75f5908c9ce39fe039c2e9e
[ "Unlicense" ]
null
null
null
Assets/Scripts/Scriptables/ItemScriptable.cs
jackieateacat/full-project
c19110d126d3e629c75f5908c9ce39fe039c2e9e
[ "Unlicense" ]
6
2021-08-11T01:58:34.000Z
2021-08-20T19:30:25.000Z
using UnityEngine; [CreateAssetMenu(fileName = "NewItem", menuName = "Inventory System/Item")] public class ItemScriptable : ScriptableObject { [Tooltip("The Item Type defines how an item shall be grouped.")] [SerializeField] private ItemType itemType; [Tooltip("What is the name of this item? This is more specific than the Item Type.")] [SerializeField] private string itemName; [Tooltip("This short description can be used when the Player examines this item.")] [TextArea(5, 30)] [SerializeField] private string description; [Tooltip("How much one unit of this item weights.")] [SerializeField] private int weight; [Tooltip("How many of this item can be carried by the Player at once.")] [Range(1, 999)] [SerializeField] private int maxQuantity; [Tooltip("An icon to be represent this item in the Inventory.")] [SerializeField] private Sprite icon; public ItemType ItemType => itemType; public string ItemName => itemName; public string Description => description; public int Weight => weight; public int MaxQuantity => maxQuantity; public Sprite Icon => icon; }
36
89
0.710938
0d3422f7d5a3e05394ea29521ff7d1b7c1826c8f
3,401
h
C
MASProximity/Classes/MASProximityLoginDelegate.h
CAAPIM/iOS-MAS-Proximity
cb3784271de25851922b467f50140f43f3f2feb7
[ "MIT" ]
null
null
null
MASProximity/Classes/MASProximityLoginDelegate.h
CAAPIM/iOS-MAS-Proximity
cb3784271de25851922b467f50140f43f3f2feb7
[ "MIT" ]
null
null
null
MASProximity/Classes/MASProximityLoginDelegate.h
CAAPIM/iOS-MAS-Proximity
cb3784271de25851922b467f50140f43f3f2feb7
[ "MIT" ]
1
2021-11-11T19:23:15.000Z
2021-11-11T19:23:15.000Z
// // MASProximityLoginDelegate.h // MASFoundation // // Copyright (c) 2016 CA. All rights reserved. // // This software may be modified and distributed under the terms // of the MIT license. See the LICENSE file for details. // @import Foundation; #import <MASFoundation/MASFoundation.h> /** * The enumerated MASBLEServiceState that can indicate what is current status of Device BLE */ typedef NS_ENUM(NSInteger, MASBLEServiceState) { /** * Unknown */ MASBLEServiceStateUnknown = -1, /** * BLE Central started */ MASBLEServiceStateCentralStarted, /** * BLE Central stopped */ MASBLEServiceStateCentralStopped, /** * BLE Central a device detected */ MASBLEServiceStateCentralDeviceDetected, /** * BLE Central a device connected */ MASBLEServiceStateCentralDeviceConnected, /** * BLE Central a device disconnected */ MASBLEServiceStateCentralDeviceDisconnected, /** * BLE Central service discovered */ MASBLEServiceStateCentralServiceDiscovered, /** * BLE Central characteristic discovered */ MASBLEServiceStateCentralCharacteristicDiscovered, /** * BLE Central characteristic written */ MASBLEServiceStateCentralCharacteristicWritten, /** * BLE Central authorization succeeded */ MASBLEServiceStateCentralAuthorizationSucceeded, /** * BLE Central authorization failed */ MASBLEServiceStateCentralAuthorizationFailed, /** * BLE Peripheral subscribed */ MASBLEServiceStatePeripheralSubscribed, /** * BLE Peripheral unsubscribed */ MASBLEServiceStatePeripheralUnsubscribed, /** * BLE Peripheral started */ MASBLEServiceStatePeripheralStarted, /** * BLE Peripheral stopped */ MASBLEServiceStatePeripheralStopped, /** * BLE Peripheral session authorized */ MASBLEServiceStatePeripheralSessionAuthorized, /** * BLE Peripheral session notified */ MASBLEServiceStatePeripheralSessionNotified }; @protocol MASProximityLoginDelegate <NSObject> @required /** * SDK callback to this method for user consent to authorize proximity login. * * @param completion MASCompletionErrorBlock returns boolean of consent state and error if there is any * @param deviceName NSString of device name */ - (void)handleBLEProximityLoginUserConsent:(MASCompletionErrorBlock _Nullable)completion deviceName:(NSString *_Nonnull)deviceName; @optional /** * Notify the host application that the authorization code has been received from other device. * Alternatively, developers can subscribe notification, MASDeviceDidReceiveAuthorizationCodeFromProximityLoginNotification, to receive the authorization code. * * @param authorizationCode NSString of authorization code */ - (void)didReceiveAuthorizationCode:(NSString *_Nonnull)authorizationCode; /** * Notify the host application on the state of the BLE proximity login. * * @param state enumeration of MASBLEServiceState */ - (void)didReceiveBLEProximityLoginStateUpdate:(MASBLEServiceState)state; /** * Notify the host application on any error occured while proximity login * * @param error NSError of BLE proximity login error */ - (void)didReceiveProximityLoginError:(NSError *_Nonnull)error; @end
25.007353
160
0.71626
5d300fcbc8b3d333153f560939896bb5881e474e
247
hpp
C++
include/System/NonCopyable.hpp
Mac1512/engge
50c203c09b57c0fbbcdf6284c60886c8db471e07
[ "MIT" ]
null
null
null
include/System/NonCopyable.hpp
Mac1512/engge
50c203c09b57c0fbbcdf6284c60886c8db471e07
[ "MIT" ]
null
null
null
include/System/NonCopyable.hpp
Mac1512/engge
50c203c09b57c0fbbcdf6284c60886c8db471e07
[ "MIT" ]
null
null
null
#pragma once namespace ng { class NonCopyable { protected: NonCopyable() = default; ~NonCopyable() = default; private: NonCopyable(const NonCopyable &) = delete; NonCopyable &operator=(const NonCopyable &) = delete; }; } // namespace ng
17.642857
55
0.704453
f41e1d58276487ff4fae76db419d3653065d2a7a
1,957
cs
C#
src/tests/JIT/Regression/JitBlue/Runtime_56953/Runtime_56953.cs
pyracanda/runtime
72bee25ab532a4d0636118ec2ed3eabf3fd55245
[ "MIT" ]
9,402
2019-11-25T23:26:24.000Z
2022-03-31T23:19:41.000Z
src/tests/JIT/Regression/JitBlue/Runtime_56953/Runtime_56953.cs
pyracanda/runtime
72bee25ab532a4d0636118ec2ed3eabf3fd55245
[ "MIT" ]
37,522
2019-11-25T23:30:32.000Z
2022-03-31T23:58:30.000Z
src/tests/JIT/Regression/JitBlue/Runtime_56953/Runtime_56953.cs
pyracanda/runtime
72bee25ab532a4d0636118ec2ed3eabf3fd55245
[ "MIT" ]
3,629
2019-11-25T23:29:16.000Z
2022-03-31T21:52:28.000Z
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Runtime.CompilerServices; public class TestClass13 { // The test exposed a place where we were using uninitialized `gtUseNum` variable. public struct S1 { public byte byte_1; } public struct S2 { } public struct S3 { } public struct S5 { public struct S5_D1_F2 { public S1 s1_1; public ushort uint16_2; } } static ushort s_uint16_11 = 19036; static S2 s_s2_15 = new S2(); static S3 s_s3_16 = new S3(); static S5.S5_D1_F2 s_s5_s5_d1_f2_18 = new S5.S5_D1_F2(); static S5 s_s5_19 = new S5(); static int s_loopInvariant = 1; [MethodImpl(MethodImplOptions.NoInlining)] public ushort LeafMethod11() { unchecked { return s_s5_s5_d1_f2_18.uint16_2 <<= 15 | 4; } } public S3 Method4(ref S2 p_s2_0, S5.S5_D1_F2 p_s5_s5_d1_f2_1, S5.S5_D1_F2 p_s5_s5_d1_f2_2, ushort p_uint16_3, ref S5 p_s5_4, S5.S5_D1_F2 p_s5_s5_d1_f2_5, short p_int16_6) { unchecked { { } return s_s3_16; } } public void Method0() { unchecked { if ((s_uint16_11 %= s_s5_s5_d1_f2_18.uint16_2 <<= 15 | 4) < 15 + 4 - LeafMethod11()) { } else { } { } s_s3_16 = Method4(ref s_s2_15, s_s5_s5_d1_f2_18, s_s5_s5_d1_f2_18, LeafMethod11(), ref s_s5_19, s_s5_s5_d1_f2_18, 11592); return; } } public static int Main(string[] args) { try { TestClass13 objTestClass13 = new TestClass13(); objTestClass13.Method0(); } catch(Exception) { // ignore exceptions } return 100; } }
25.75
174
0.565662
ebcd8a52acd56eccadca95e643dc4d720f737821
3,665
css
CSS
assets/style.css
anthony9292/Anthony-Ndegwa-Portfolio
9eb2c86267e9b1b1af0920759fdee539ea22ec2c
[ "MIT" ]
null
null
null
assets/style.css
anthony9292/Anthony-Ndegwa-Portfolio
9eb2c86267e9b1b1af0920759fdee539ea22ec2c
[ "MIT" ]
null
null
null
assets/style.css
anthony9292/Anthony-Ndegwa-Portfolio
9eb2c86267e9b1b1af0920759fdee539ea22ec2c
[ "MIT" ]
null
null
null
@import url('http://fonts.googleapis.com/css?family=Poppins:200,300,400,500,600,700,800,900&display=swap'); * { margin: 0; padding: 0; box-sizing: border-box; font-family: sans-serif; } section{ padding: 100px; } /*HEADER SECTION*/ .banner { position: relative; min-height: 100vh; background: url(lightbulb.jpg); background-size: cover; background-position: right; justify-content: space-between; align-items: center; } .banner h2 { font-size: 3em; color: #FFF; font-weight: 500; line-height: 1.5em; } .banner h3 { font-size: 1.4em; color: #FFF; font-weight: 500; } .btn { position: relative; background: #2196f3; display: inline-block; color: #FFF; margin-top: 20px; padding: 10px 30px; font-size:18px; text-transform: uppercase; text-decoration: none; letter-spacing: 2px; font-weight: 500; } header { position :fixed; top: 0; left: 0; width: 100%; padding: 0px 10px; z-index: 1000; display: flex; justify-content: space-around; align-items: center; transition: 0.5s; } header.sticky { background: #FFF; padding: 20px 100px; box-shadow: 0 5px 20px rgba(0, 0, 0, 0.1); } header.sticky .logo { color: #111; } header .logo { color: rgb(255, 255, 255); font-size: 52px; text-transform: uppercase; text-decoration: none; font-weight:700; letter-spacing: 2px; } header ul { position: relative; display: flex; } header ul li { position: relative; list-style: none; } header ul li a { position: relative; display: inline-block; margin: 0 25px; color: #FFF; text-decoration: none; } header.sticky ul li a { color: #111; } .heading { width: 100%; text-align: center; margin-bottom: 30px; color: #111; } .content { display:flex; justify-content: space-between; } .heading h2 { font-weight: 600; font-size: 30px; } .contentBx { padding-right: 40px; } .contentBx h3 { font-size: 24px; margin-bottom: 10px; } .w50 { min-width: 60%; } img { max-width: 100%; } /* FILLER SECTION */ .filler{ background-color: #111; } .heading.white { color: #FFF; } .filler .content { display: flex; justify-content: center; flex-wrap: wrap; flex-direction: row; } .filler .content .fillerBx { padding: 40px 20px; background: #222; color: #FFF; max-width: 350px; margin: 20px; text-align: center; transition: 0.5s; } .filler .content .fillerBx:hover { background-color: #2196f3; } .filler .content .fillerBx img { max-width: 80px; filter: invert(1); } .filter .content .fillerBx h2 { font-size: 20px; font-weight: 600; } /* WORK SECTION */ .work .content { display: flex; justify-content: space-between; flex-wrap: wrap; } .work .content .workBx{ width: 20%; padding: 20px; } .work .content .workBx img { max-width: 100%; } #one { color: rgb(0, 0, 0); font-size: 12px; text-transform: uppercase; text-decoration: none; font-weight:50; letter-spacing: 2px; text-align: center; } /* REFERENCE SECTION */ .reference{ background: #ffffff; } .reference .content { display: flex; justify-content: space-between; flex-wrap:wrap ; } .reference .content .referenceBx { max-width: calc(50% - 40px); padding: 60px 40px; margin: 20px; background: rgb(0, 0, 0); } .reference .content .referenceBx p { color: #FFF; font-style: italic; font-size: 16px; font-weight: 300; } .reference .content .referenceBx h3 { margin-top: 40px; text-align: end; color: #FFF; font-weight: 600; font-size: 20px; line-height: 1em; } .reference .content .referenceBx h3 span { font-size: 14px; font-weight: 400; }
12.465986
108
0.643111
e441694e9b76e45731f288e94065a3bc96cd5532
4,100
cpp
C++
src/ScoreKeeperShared.cpp
MidflightDigital/stepmania
dbce5016978e5ab51aaa6a4fb21ef2c7ce68e52e
[ "MIT" ]
7
2019-01-06T01:09:55.000Z
2021-01-21T00:00:19.000Z
src/ScoreKeeperShared.cpp
MidflightDigital/stepmania
dbce5016978e5ab51aaa6a4fb21ef2c7ce68e52e
[ "MIT" ]
6
2020-07-29T17:45:36.000Z
2020-07-29T18:48:03.000Z
src/ScoreKeeperShared.cpp
MidflightDigital/stepmania
dbce5016978e5ab51aaa6a4fb21ef2c7ce68e52e
[ "MIT" ]
5
2019-01-06T01:48:34.000Z
2021-11-25T21:19:07.000Z
#include "global.h" #include "ScoreKeeperShared.h" #include "RageLog.h" #include "GameState.h" #include "PlayerState.h" using std::vector; /* In Routine, we have two Players, but the master one handles all of the scoring. The other * one will just receive misses for everything, and shouldn't do anything. */ ScoreKeeperShared::ScoreKeeperShared( PlayerState *pPlayerState, PlayerStageStats *pPlayerStageStats ) : ScoreKeeperNormal( pPlayerState, pPlayerStageStats ) { } void ScoreKeeperShared::Load( const vector<Song*> &apSongs, const vector<Steps*> &apSteps, const vector<AttackArray> &asModifiers ) { if( m_pPlayerState->m_PlayerNumber != GAMESTATE->GetMasterPlayerNumber() ) return; ScoreKeeperNormal::Load( apSongs, apSteps, asModifiers ); } // These ScoreKeepers don't get to draw. void ScoreKeeperShared::DrawPrimitives() { if( m_pPlayerState->m_PlayerNumber != GAMESTATE->GetMasterPlayerNumber() ) return; ScoreKeeperNormal::DrawPrimitives(); } void ScoreKeeperShared::Update( float fDelta ) { if( m_pPlayerState->m_PlayerNumber != GAMESTATE->GetMasterPlayerNumber() ) return; ScoreKeeperNormal::Update( fDelta ); } void ScoreKeeperShared::OnNextSong( int iSongInCourseIndex, const Steps* pSteps, const NoteData* pNoteData ) { if( m_pPlayerState->m_PlayerNumber != GAMESTATE->GetMasterPlayerNumber() ) return; ScoreKeeperNormal::OnNextSong( iSongInCourseIndex, pSteps, pNoteData ); } void ScoreKeeperShared::HandleTapScore( const TapNote &tn ) { if( m_pPlayerState->m_PlayerNumber != GAMESTATE->GetMasterPlayerNumber() ) return; ScoreKeeperNormal::HandleTapScore( tn ); } void ScoreKeeperShared::HandleTapRowScore( const NoteData &nd, int iRow ) { if( m_pPlayerState->m_PlayerNumber != GAMESTATE->GetMasterPlayerNumber() ) return; ScoreKeeperNormal::HandleTapRowScore( nd, iRow ); } void ScoreKeeperShared::HandleHoldScore( const TapNote &tn ) { if( m_pPlayerState->m_PlayerNumber != GAMESTATE->GetMasterPlayerNumber() ) return; ScoreKeeperNormal::HandleHoldScore( tn ); } void ScoreKeeperShared::HandleHoldActiveSeconds( float fMusicSecondsHeld ) { if( m_pPlayerState->m_PlayerNumber != GAMESTATE->GetMasterPlayerNumber() ) return; ScoreKeeperNormal::HandleHoldActiveSeconds( fMusicSecondsHeld ); } void ScoreKeeperShared::HandleHoldCheckpointScore( const NoteData &nd, int iRow, int iNumHoldsHeldThisRow, int iNumHoldsMissedThisRow ) { if( m_pPlayerState->m_PlayerNumber != GAMESTATE->GetMasterPlayerNumber() ) return; ScoreKeeperNormal::HandleHoldCheckpointScore( nd, iRow, iNumHoldsHeldThisRow, iNumHoldsMissedThisRow ); } void ScoreKeeperShared::HandleTapScoreNone() { if( m_pPlayerState->m_PlayerNumber != GAMESTATE->GetMasterPlayerNumber() ) return; ScoreKeeperNormal::HandleTapScoreNone(); } /* * (c) 2006-2010 Steve Checkoway, Glenn Maynard * All rights reserved. * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, and/or sell copies of the Software, and to permit persons to * whom the Software is furnished to do so, provided that the above * copyright notice(s) and this permission notice appear in all copies of * the Software and that both the above copyright notice(s) and this * permission notice appear in supporting documentation. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF * THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS * INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT * OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS * OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR * OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR * PERFORMANCE OF THIS SOFTWARE. */
35.964912
135
0.775366
a382a4d3319853878c06ae76512f3cce40c2ccf5
119
ts
TypeScript
src/react-app-env.d.ts
psyycker/react-translation
452c16e1d60903af505f79ba4878225e249b836f
[ "MIT" ]
3
2020-09-28T03:07:19.000Z
2022-01-20T21:53:26.000Z
src/react-app-env.d.ts
psyycker/react-translation
452c16e1d60903af505f79ba4878225e249b836f
[ "MIT" ]
2
2021-04-15T05:02:43.000Z
2022-01-20T21:53:14.000Z
src/react-app-env.d.ts
psyycker/react-translation
452c16e1d60903af505f79ba4878225e249b836f
[ "MIT" ]
null
null
null
interface Window { localChangeEvent: Event; translationChangeEvent: Event; translations: {}; locale: string; }
17
32
0.731092
b0e4e38713a94cf7ac5154340bae6129e8ee4b00
3,629
py
Python
src/unittest/python/parameter_load_tests.py
rspitler/infra-buddy
5ef0e20dfd6906f83459108cb767de38afbb7a2b
[ "Apache-2.0" ]
3
2018-03-31T09:09:40.000Z
2021-11-08T10:26:46.000Z
src/unittest/python/parameter_load_tests.py
rspitler/infra-buddy
5ef0e20dfd6906f83459108cb767de38afbb7a2b
[ "Apache-2.0" ]
2
2021-05-21T04:17:02.000Z
2021-06-01T18:49:26.000Z
src/unittest/python/parameter_load_tests.py
rspitler/infra-buddy
5ef0e20dfd6906f83459108cb767de38afbb7a2b
[ "Apache-2.0" ]
3
2020-10-12T23:00:58.000Z
2021-07-29T19:03:50.000Z
import json import os import tempfile from infra_buddy.aws import s3 from infra_buddy.aws.cloudformation import CloudFormationBuddy from infra_buddy.aws.s3 import S3Buddy from infra_buddy.commandline import cli from infra_buddy.context.deploy_ctx import DeployContext from infra_buddy.deploy.cloudformation_deploy import CloudFormationDeploy from infra_buddy.template.template import NamedLocalTemplate from infra_buddy.utility import helper_functions from testcase_parent import ParentTestCase class ParameterLoadTestCase(ParentTestCase): def tearDown(self): pass @classmethod def setUpClass(cls): super(ParameterLoadTestCase, cls).setUpClass() def test_parameter_transformation(self): ctx = DeployContext.create_deploy_context(application="dev-{}".format(self.run_random_word), role="cluster", environment="unit-test", defaults=self.default_config) try: template_dir = ParentTestCase._get_resource_path("parameter_load_tests/fargate") deploy = CloudFormationDeploy(ctx.stack_name, NamedLocalTemplate(template_dir), ctx) self.assertEqual(deploy.defaults['TASK_SOFT_MEMORY'], 512, 'Did not respect defaut') self.assertEqual(deploy.defaults['TASK_CPU'], 64, 'Did not respect defaut') ctx['USE_FARGATE'] = 'true' deploy = CloudFormationDeploy(ctx.stack_name, NamedLocalTemplate(template_dir), ctx) self.assertEqual(deploy.defaults['TASK_SOFT_MEMORY'], '512', 'Did not transform memory') self.assertEqual(deploy.defaults['TASK_CPU'], 256, 'Did not transform cpu') finally: pass def test_fargate_processing(self): ctx = DeployContext.create_deploy_context(application="dev-{}".format(self.run_random_word), role="cluster", environment="unit-test", defaults=self.default_config) ctx['USE_FARGATE'] = 'true' cpu_transforms = { 128: 256, 12: 256, 257: 512, 1023: 1024, 1024: 1024, 2000: 2048, 10000: 4096, } for to_transform, expected in cpu_transforms.items(): self.assertEqual(helper_functions.transform_fargate_cpu(ctx,to_transform), expected, 'Did not transform correctly') memory_transforms = { 128: '512', 12: '512', 257: '512', 1023: '1024', 1024: '1024', 2000: '2048', 10000: '10240', } for to_transform, expected in memory_transforms.items(): self.assertEqual(helper_functions.transform_fargate_memory(ctx,to_transform), expected, 'Did not transform correctly') valid_configurations = [ [256,'512'], [2048,'5120'], [1024,'2048'], ] invalid_configuration = [ [256,'5120'], [4096,'5120'] ] for config in valid_configurations: helper_functions._validate_fargate_resource_allocation(config[0],config[1],{}) for config in invalid_configuration: try: helper_functions._validate_fargate_resource_allocation(config[0],config[1],{}) self.fail("Failed to detect invalid fargate configuration - {} CPU {} Memory".format(config[0],config[1])) except: pass
40.775281
122
0.606779
b1465b16c1808ec61302cc1b8df78787a5b68743
476
py
Python
app/admin/controllers.py
RobinRheem/mememime
86b81cc3708d58a142229ebfe192c8234ae2fce2
[ "MIT" ]
null
null
null
app/admin/controllers.py
RobinRheem/mememime
86b81cc3708d58a142229ebfe192c8234ae2fce2
[ "MIT" ]
1
2021-04-30T20:57:05.000Z
2021-04-30T20:57:05.000Z
app/admin/controllers.py
cladup/objection
86b81cc3708d58a142229ebfe192c8234ae2fce2
[ "MIT" ]
null
null
null
from flask import Blueprint admin_page = Blueprint('admin', __name__) @admin_page.route('/admin/objects', methods=['GET']) def get(): """ FIXME: Create debug purpose file input UI """ return ''' <!doctype html> <title>Upload new File</title> <h1>Upload new File</h1> <form method=post enctype=multipart/form-data action=/api/v1/objects> <input type=file name=graphic_model> <input type=submit value=Upload> </form> '''
21.636364
73
0.642857
79bbd0e88d20bff77a51d24a9a465a14edf40e4a
4,885
php
PHP
app/controllers/NewsController.php
idmaximum/majProject
53897f8a0514578f095bfb42388ba52b2225c78f
[ "MIT" ]
null
null
null
app/controllers/NewsController.php
idmaximum/majProject
53897f8a0514578f095bfb42388ba52b2225c78f
[ "MIT" ]
null
null
null
app/controllers/NewsController.php
idmaximum/majProject
53897f8a0514578f095bfb42388ba52b2225c78f
[ "MIT" ]
null
null
null
<?php class NewsController extends BaseController { /* |-------------------------------------------------------------------------- | Default Home Controller |-------------------------------------------------------------------------- | | You may wish to use controllers instead of, or in addition to, Closure | based routes. That's great! Here is an example controller method to | get you started. To route to this controller, just add the route: | | Route::get('/', 'HomeController@showWelcome'); | */ public function newsList(){ function str_replace_text($word){ $strwordArr = array("#",":" ,"'","\'","-","%",":") ; $strCensor = "" ; foreach ($strwordArr as $value) { $word = str_replace($value,$strCensor ,$word); } $strwordArr_2 = array("(",")","/"," ") ; $strCensor_2 = "-" ; foreach ($strwordArr_2 as $value_2) { $word = str_replace($value_2,$strCensor_2 ,$word); } $word = str_replace("_","" ,$word); return ( $word) ; }#end fn $Selectnews = DB::table('movie_news') ->select('news_ID', 'news_title_en', 'news_abstract_en', 'news_imageThumb', 'news_datetime') ->where('news_publish' , '1') ->orderBy('orderBy', 'asc') ->paginate(6); return View::make('frontend.event_activity')-> with('rowNews', $Selectnews); } public function newsListTH(){ function str_replace_text($word){ $strwordArr = array("#",":" ,"'","\'","-","%",":") ; $strCensor = "" ; foreach ($strwordArr as $value) { $word = str_replace($value,$strCensor ,$word); } $strwordArr_2 = array("(",")","/"," ") ; $strCensor_2 = "-" ; foreach ($strwordArr_2 as $value_2) { $word = str_replace($value_2,$strCensor_2 ,$word); } $word = str_replace("_","" ,$word); return ( $word) ; }#end fn $Selectnews = DB::table('movie_news') ->select('news_ID', 'news_title_th', 'news_abstract_th', 'news_imageThumb', 'news_datetime') ->where('news_publish' , '1') ->orderBy('orderBy', 'asc') ->paginate(6); return View::make('frontendTH.event_activity')-> with('rowNews', $Selectnews); } public function newsDetail($id = null){ function str_replace_text($word){ $strwordArr = array("#",":" ,"'","\'","-","%",":") ; $strCensor = "" ; foreach ($strwordArr as $value) { $word = str_replace($value,$strCensor ,$word); } $strwordArr_2 = array("(",")","/"," ") ; $strCensor_2 = "-" ; foreach ($strwordArr_2 as $value_2) { $word = str_replace($value_2,$strCensor_2 ,$word); } $word = str_replace("_","" ,$word); return ( $word) ; } #end fn str $resultNews = DB::select("select news_ID, news_title_en, news_youtube, news_detail_th, news_detail_en, news_detail_cn, news_imageThumb,news_publish, news_datetime, news_abstract_en FROM movie_news WHERE news_ID = '$id'"); $resultNewsGallery = DB::select('select * FROM movie_image_gallery WHERE news_ID ='.$id); $resultNewsGalleryCount = DB::select('select count(*) as countGallery FROM movie_image_gallery WHERE news_ID ='.$id); return View::make('frontend.event_activitydetail')-> with('rowNews', $resultNews) -> with('rowNewsGallery', $resultNewsGallery) -> with('rowCountGallery', $resultNewsGalleryCount); } public function newsDetailTH($id = null){ function str_replace_text($word){ $strwordArr = array("#",":" ,"'","\'","-","%",":") ; $strCensor = "" ; foreach ($strwordArr as $value) { $word = str_replace($value,$strCensor ,$word); } $strwordArr_2 = array("(",")","/"," ") ; $strCensor_2 = "-" ; foreach ($strwordArr_2 as $value_2) { $word = str_replace($value_2,$strCensor_2 ,$word); } $word = str_replace("_","" ,$word); return ( $word) ; } #end fn str $resultNews = DB::select("select news_ID, news_title_th, news_youtube, news_detail_th, news_detail_en, news_detail_cn, news_imageThumb,news_publish, news_datetime, news_abstract_en FROM movie_news WHERE news_ID = '$id'"); $resultNewsGallery = DB::select('select * FROM movie_image_gallery WHERE news_ID ='.$id); $resultNewsGalleryCount = DB::select('select count(*) as countGallery FROM movie_image_gallery WHERE news_ID ='.$id); return View::make('frontendTH.event_activitydetail')-> with('rowNews', $resultNews) -> with('rowNewsGallery', $resultNewsGallery) -> with('rowCountGallery', $resultNewsGalleryCount); }#end fn }
34.160839
98
0.550051
43966555ded97378cbd733c474224f10bb95c78c
13,243
ts
TypeScript
app/frontend/src/app/pages/annotations/upload/upload.service.ts
antigenomics/vdjdb-web-private
9200cf0a6a7735c7052a805e95fe164ec0f7bdd2
[ "Apache-2.0" ]
6
2017-12-12T11:29:47.000Z
2021-04-10T09:05:35.000Z
app/frontend/src/app/pages/annotations/upload/upload.service.ts
antigenomics/vdjdb-web
5f30cbfd34739b5296d1b8036a5607c429df74cd
[ "Apache-2.0" ]
42
2017-12-12T15:14:45.000Z
2022-03-02T03:29:35.000Z
app/frontend/src/app/pages/annotations/upload/upload.service.ts
antigenomics/vdjdb-web-private
9200cf0a6a7735c7052a805e95fe164ec0f7bdd2
[ "Apache-2.0" ]
1
2018-06-04T20:27:43.000Z
2018-06-04T20:27:43.000Z
/* * Copyright 2017-2019 Bagaev Dmitry * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import { Injectable } from '@angular/core'; import * as gzip from 'gzip-js'; import { FileItemStatusErrorType } from 'pages/annotations/upload/item/file-item-status'; import { Observable, Observer } from 'rxjs'; import { SampleItem } from 'shared/sample/sample-item'; import { SampleTag } from 'shared/sample/sample-tag'; import { AnalyticsService } from 'utils/analytics/analytics.service'; import { LoggerService } from 'utils/logger/logger.service'; import { NotificationService } from 'utils/notifications/notification.service'; import { AnnotationsService, AnnotationsServiceEvents } from '../annotations.service'; import { FileItem } from './item/file-item'; export class UploadStatus { public progress: number; public loading: boolean; public error: string; constructor(progress: number, loading: boolean = true, error?: string) { this.progress = progress; this.loading = loading; this.error = error; } } @Injectable() export class UploadService { private static readonly FILE_UPLOAD_GOAL: string = 'file-upload-goal'; private static readonly FULL_PROGRESS: number = 100; private static readonly SUCCESS_HTTP_CODE: number = 200; private _uploadingCount: number = 0; private _files: FileItem[] = []; constructor(private logger: LoggerService, private annotationsService: AnnotationsService, private notifications: NotificationService, private analytics: AnalyticsService) { this.annotationsService.getEvents().subscribe((event: AnnotationsServiceEvents) => { switch (event) { case AnnotationsServiceEvents.SAMPLE_DELETED: this.updateErrors(); break; default: } }); } public addItems(files: FileList): void { /*tslint:disable:prefer-for-of */ for (let i = 0; i < files.length; ++i) { const file = new FileItem(files[ i ]); this._files.push(file); } this.updateErrors(); /*tslint:enable:prefer-for-of */ } public getAvailableSoftwareTypes(): string[] { return this.annotationsService.getAvailableSoftwareTypes(); } public getEvents(): Observable<AnnotationsServiceEvents> { return this.annotationsService.getEvents(); } public getItems(): FileItem[] { return this._files; } public isItemsEmpty(): boolean { return this._files.length === 0; } public isLoadingExist(): boolean { return this._files.some((item) => item.status.isLoading()); } public isReadyForUploadExist(): boolean { return this._files.some((item) => item.status.isReadyForUpload()); } public checkTagsAvailability(): void { this._files.forEach((file) => { if (file.tag !== undefined) { const index = this.annotationsService.getTags().indexOf(file.tag); if (index === -1) { file.tag = undefined; } } }); } public handleItemNameErrors(item: FileItem, baseName: string, from?: FileItem[]): boolean { item.status.setValidNameStatus(); item.status.setUniqueNameStatus(); let error = false; const testBaseName = SampleItem.isNameValid(baseName); const testBaseNameWithExtension = SampleItem.isNameValid(`${baseName}.${item.extension}`); if (!testBaseName || !testBaseNameWithExtension) { item.status.setInvalidNameStatus(); error = true; } const items = from ? from : this._files; const isSameNameExist = items .filter((f) => !(f.status.isRemoved() || f.status.isError())) .some((f) => f.baseName === baseName); if (isSameNameExist) { item.status.setDuplicateNameStatus(); error = true; } const userSamples = this.annotationsService.getSamples(); const isSameNameExistInUploaded = userSamples.some((sample) => sample.name === baseName); if (isSameNameExistInUploaded) { item.status.setDuplicateNameStatus(); error = true; } item.baseName = baseName; return error; } public handlePermissionsErrors(item: FileItem): boolean { const permissions = this.annotationsService.getUserPermissions(); if (!permissions.isUploadAllowed) { item.setErrorStatus('Uploading is not allowed for this account', FileItemStatusErrorType.UPLOAD_NOT_ALLOWED); return true; } if (permissions.maxFilesCount >= 0) { const waitingFilesLength = this._files.filter((_item) => _item.status.isWaiting()).length; const sampleFilesLength = this.annotationsService.getSamples().length; if ((waitingFilesLength + sampleFilesLength) > permissions.maxFilesCount) { item.setErrorStatus('Max files count limit have been exceeded', FileItemStatusErrorType.MAX_FILES_COUNT_LIMIT_EXCEEDED); return true; } } if (permissions.maxFileSize >= 0) { if (item.compressed && item.compressed.size < permissions.getMaxFileSizeInBytes()) { return false; } else if (item.getNativeFile().size >= permissions.getMaxFileSizeInBytes()) { item.setErrorStatus('Max file size limit have been exceeded', FileItemStatusErrorType.MAX_FILE_SIZE_LIMIT_EXCEEDED); return true; } } return false; } // noinspection JSMethodCanBeStatic public handleExtensionErrors(item: FileItem): boolean { if (FileItem.AVAILABLE_EXTENSIONS.indexOf(item.extension) === -1) { item.setErrorStatus('Invalid file extension', FileItemStatusErrorType.INVALID_FILE_EXTENSION); return true; } return false; } public updateErrors(): void { const checked: FileItem[] = []; const items = this._files.filter((item) => !(item.status.isRemoved() || item.status.isUploaded())); for (const item of items) { item.clearErrors(); const extensionErrors = this.handleExtensionErrors(item); if (!extensionErrors) { const permissionErrors = this.handlePermissionsErrors(item); if (!permissionErrors) { this.handleItemNameErrors(item, item.baseName, checked); } } checked.push(item); } this.annotationsService.fireEvent(AnnotationsServiceEvents.UPLOAD_SERVICE_STATE_REFRESHED); } public compress(item: FileItem): void { item.status.setCompressingStatus(); const reader = new FileReader(); reader.onload = (event: Event) => { const array = new Uint8Array((event.target as any).result); const gzippedByteArray = new Uint8Array(gzip.zip(array)); const gzippedBlob = new Blob([ gzippedByteArray ], { type: 'application/x-gzip' }); item.compressed = gzippedBlob; item.setExtension('gz'); this.updateErrors(); }; reader.readAsArrayBuffer(item.getNativeFile()); } public remove(item: FileItem): void { item.status.setRemovedStatus(); this.updateErrors(); } public uploadAll(): void { this._files .filter((item) => !item.status.beforeUploadError()) .forEach((item) => this.upload(item)); } public upload(file: FileItem): void { if (!this.annotationsService.getUserPermissions().isUploadAllowed) { this.notifications.error('Upload', 'Uploading is not allowed for this account'); return; } this.analytics.reachGoal(UploadService.FILE_UPLOAD_GOAL, file.getFileItemStats()); if (file.status.isReadyForUpload()) { file.status.setLoadingStatus(); this.fireUploadingStartEvent(); const uploader = this.createUploader(file); uploader.subscribe({ next: async (status: UploadStatus) => { if (status.loading === false) { if (status.progress === UploadService.FULL_PROGRESS && status.error === undefined) { const added = await this.annotationsService.addSample(file); if (added) { file.setUploadedStatus(); } else { file.setErrorStatus('Validating failed', FileItemStatusErrorType.VALIDATION_FAILED); } } else if (status.error !== undefined) { file.setErrorStatus(status.error, FileItemStatusErrorType.INTERNAL_ERROR); } this.fireUploadingEndedEvent(); } else { file.progress.next(status.progress); } }, error: (err: UploadStatus) => { file.setErrorStatus(err.error, FileItemStatusErrorType.INTERNAL_ERROR); this.fireUploadingEndedEvent(); } }); } } public isUploadedExist(): boolean { return this._files.some((item) => item.status.isUploaded()); } public clearUploaded(): void { this._files = this._files.filter((item) => !item.status.isUploaded()); this.annotationsService.fireEvent(AnnotationsServiceEvents.UPLOAD_SERVICE_STATE_REFRESHED); } public isRemovedExist(): boolean { return this._files.some((item) => item.status.isRemoved()); } public clearRemoved(): void { this._files = this._files.filter((item) => !item.status.isRemoved()); this.annotationsService.fireEvent(AnnotationsServiceEvents.UPLOAD_SERVICE_STATE_REFRESHED); } public isErroredExist(): boolean { return this._files.some((item) => item.status.isError()); } public clearErrored(): void { this._files = this._files.filter((item) => !item.status.isError()); this.annotationsService.fireEvent(AnnotationsServiceEvents.UPLOAD_SERVICE_STATE_REFRESHED); } public setDefaultSoftware(software: string): void { this._files .filter((item) => !(item.status.isError() || item.status.isRemoved() || item.status.isUploaded())) .forEach((item) => item.setSoftware(software)); } public setDefaultTag(tag: SampleTag): void { this._files .filter((item) => !(item.status.isError() || item.status.isRemoved() || item.status.isUploaded())) .forEach((item) => item.setTag(tag)); } private fireUploadingStartEvent(): void { this._uploadingCount += 1; this.annotationsService.fireEvent(AnnotationsServiceEvents.UPLOAD_SERVICE_UPLOAD_STARTED); } private fireUploadingEndedEvent(): void { this._uploadingCount -= 1; if (this._uploadingCount === 0) { this.annotationsService.fireEvent(AnnotationsServiceEvents.UPLOAD_SERVICE_UPLOAD_ENDED); } } private createUploader(file: FileItem): Observable<UploadStatus> { this.logger.debug('FileUploaderService: uploading file', `${file.baseName} (size: ${file.getNativeFile().size})`); return Observable.create((observer: Observer<UploadStatus>) => { const formData: FormData = new FormData(); formData.append('file', file.getUploadBlob()); formData.append('name', file.getUploadBlobName()); formData.append('software', file.software); const xhr = new XMLHttpRequest(); const progressEventListener = (progress: ProgressEvent) => { if (progress.lengthComputable) { const completed = Math.round(progress.loaded / progress.total * UploadService.FULL_PROGRESS); observer.next(new UploadStatus(completed, true)); } }; xhr.upload.addEventListener('progress', progressEventListener); const errorEventListener: EventListener = (error: Event) => { const request = error.target as XMLHttpRequest; this.logger.debug('FileUploaderService: error', error); observer.error(new UploadStatus(-1, false, request.responseText)); }; xhr.addEventListener('error', errorEventListener); xhr.upload.addEventListener('error', errorEventListener); const loadEventListener = (event: Event) => { const request = event.target as XMLHttpRequest; const status = request.status; this.logger.debug('FileUploaderService: load with status', status); if (status === UploadService.SUCCESS_HTTP_CODE) { observer.next(new UploadStatus(UploadService.FULL_PROGRESS, false)); observer.complete(); } else { const errorResponse = request.responseText; observer.error(new UploadStatus(-1, false, errorResponse)); } }; xhr.addEventListener('load', loadEventListener); const abortEventListener = () => { observer.error(new UploadStatus(-1, false, 'Aborted')); }; xhr.addEventListener('abort', abortEventListener); xhr.upload.addEventListener('abort', abortEventListener); const timeoutEventListener = () => { observer.error(new UploadStatus(-1, false, 'Timeout')); }; xhr.addEventListener('timeout', timeoutEventListener); xhr.upload.addEventListener('timeout', timeoutEventListener); xhr.open('POST', '/api/annotations/upload', true); xhr.send(formData); return () => xhr.abort(); }); } }
36.18306
128
0.67447
ddbd8448840de632bb0cf4a5b3451ab250f4578c
2,151
java
Java
common/src/main/java/marsh/town/brb/Mixins/UnGroup/SplitGrouped.java
SimGitHub5/BetterRecipeBook
a3188ec0b627dc64aff101bd6700e2f54ef9c903
[ "MIT" ]
9
2021-10-02T17:57:04.000Z
2022-03-19T03:22:07.000Z
common/src/main/java/marsh/town/brb/Mixins/UnGroup/SplitGrouped.java
SimGitHub5/BetterRecipeBook
a3188ec0b627dc64aff101bd6700e2f54ef9c903
[ "MIT" ]
30
2021-06-04T02:41:44.000Z
2022-03-03T02:00:40.000Z
common/src/main/java/marsh/town/brb/Mixins/UnGroup/SplitGrouped.java
SimGitHub5/BetterRecipeBook
a3188ec0b627dc64aff101bd6700e2f54ef9c903
[ "MIT" ]
6
2021-08-23T19:16:35.000Z
2021-12-18T15:56:34.000Z
package marsh.town.brb.Mixins.UnGroup; import com.google.common.collect.Lists; import marsh.town.brb.BetterRecipeBook; import net.minecraft.client.ClientRecipeBook; import net.minecraft.client.RecipeBookCategories; import net.minecraft.client.gui.screens.recipebook.RecipeCollection; import net.minecraft.stats.RecipeBook; import net.minecraft.world.item.crafting.Recipe; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; import org.spongepowered.asm.mixin.injection.callback.LocalCapture; import java.util.Collections; import java.util.List; import java.util.Map; @Mixin(ClientRecipeBook.class) public class SplitGrouped extends RecipeBook { @Shadow private Map<RecipeBookCategories, List<RecipeCollection>> collectionsByTab; @Inject(method = "getCollection", locals = LocalCapture.CAPTURE_FAILHARD, at = @At("RETURN"), cancellable = true) private void split(RecipeBookCategories category, CallbackInfoReturnable<List<RecipeCollection>> cir) { if (BetterRecipeBook.config.alternativeRecipes.noGrouped) { List<RecipeCollection> list = Lists.newArrayList(this.collectionsByTab.getOrDefault(category, Collections.emptyList())); List<RecipeCollection> list2 = Lists.newArrayList(list); for (RecipeCollection recipeResultCollection : list) { if (recipeResultCollection.getRecipes().size() > 1) { List<Recipe<?>> recipes = recipeResultCollection.getRecipes(); list2.remove(recipeResultCollection); for (Recipe<?> recipe : recipes) { RecipeCollection recipeResultCollection1 = new RecipeCollection(Collections.singletonList(recipe)); recipeResultCollection1.updateKnownRecipes(this); list2.add(recipeResultCollection1); } } } cir.setReturnValue(list2); } } }
44.8125
132
0.718271
ed6e6f951d5e08729dd5e82a84dd660c9d9fc02e
718
h
C
released_plugins/v3d_plugins/bigneuron_zhijiang_zn_bjut_fastmarching_spanningtree_vaa3d/global.h
zzhmark/vaa3d_tools
3ca418add85a59ac7e805d55a600b78330d7e53d
[ "MIT" ]
1
2021-12-27T19:14:03.000Z
2021-12-27T19:14:03.000Z
released_plugins/v3d_plugins/bigneuron_zhijiang_zn_bjut_fastmarching_spanningtree_vaa3d/global.h
zzhmark/vaa3d_tools
3ca418add85a59ac7e805d55a600b78330d7e53d
[ "MIT" ]
1
2016-12-03T05:33:13.000Z
2016-12-03T05:33:13.000Z
released_plugins/v3d_plugins/bigneuron_zhijiang_zn_bjut_fastmarching_spanningtree_vaa3d/global.h
zzhmark/vaa3d_tools
3ca418add85a59ac7e805d55a600b78330d7e53d
[ "MIT" ]
null
null
null
#ifndef GLOBAL_H #define GLOBAL_H #define GET_IND(x,y,z) (x) + (y) * sz_x + (z) * sz_xy #define GET_X(ind) ind % sz_x #define GET_Y(ind) (ind / sz_x) % sz_y #define GET_Z(ind) (ind / sz_xy) % sz_z #define DISTANCE(src,dst) \ sqrt(pow((GET_X(src) - GET_X(dst)) * 1.0,2.0)\ + pow((GET_Y(src) - GET_Y(dst)) * 1.0,2.0)\ + pow((GET_Z(src) - GET_Z(dst)) * 1.0,2.0));\ int sz_x = -1; int sz_y = -1; int sz_z = -1; int sz_total = -1; int sz_xy = -1; unsigned char bresh = 30; double coverRate = 1; string fileName; qint64 timeCost = 0; qint64 totalTimeCost = 0; qint64 lastTimeCost = 0; QElapsedTimer timer; int n1=0; double m=0; double mean=0; #endif // GLOBAL_H
21.757576
55
0.591922
ff4f3416b8a246203f7b0ae5f3a2505e4a5b91c1
21,907
py
Python
engine.py
craigvear/monks_mood
14864669830aca27393eb5e88d3d8cfb6b593846
[ "MIT" ]
null
null
null
engine.py
craigvear/monks_mood
14864669830aca27393eb5e88d3d8cfb6b593846
[ "MIT" ]
null
null
null
engine.py
craigvear/monks_mood
14864669830aca27393eb5e88d3d8cfb6b593846
[ "MIT" ]
null
null
null
"""main server script will sit onboard host and operate as Nebula --- its dynamic soul""" # -------------------------------------------------- # # Embodied AI Engine Prototype v0.10 # 2021/01/25 # # © Craig Vear 2020 # [email protected] # # Dedicated to Fabrizio Poltronieri # # -------------------------------------------------- from random import randrange from time import time from tensorflow.keras.models import load_model import pyaudio import numpy as np import concurrent.futures from random import random from time import sleep from pydub import AudioSegment from pydub.playback import play # -------------------------------------------------- # # instantiate an object for each neural net # # -------------------------------------------------- # v4 models were trained with 1st batch of Blue Haze datasets class MoveRNN: def __init__(self): print('MoveRNN initialization') self.move_rnn = load_model('models/EMR-v4_RNN_skeleton_data.nose.x.h5') def predict(self, in_val): # predictions and input with localval self.pred = self.move_rnn.predict(in_val) return self.pred class AffectRNN: def __init__(self): print('AffectRNN initialization') self.affect_rnn = load_model('models/EMR-v4_RNN_bitalino.h5') def predict(self, in_val): # predictions and input with localval self.pred = self.affect_rnn.predict(in_val) return self.pred class MoveAffectCONV2: def __init__(self): print('MoveAffectCONV2 initialization') self.move_affect_conv2 = load_model('models/EMR-v4_conv2D_move-affect.h5') def predict(self, in_val): # predictions and input with localval self.pred = self.move_affect_conv2.predict(in_val) return self.pred class AffectMoveCONV2: def __init__(self): print('AffectMoveCONV2 initialization') self.affect_move_conv2 = load_model('models/EMR-v4_conv2D_affect-move.h5') def predict(self, in_val): # predictions and input with localval self.pred = self.affect_move_conv2.predict(in_val) return self.pred # -------------------------------------------------- # # controls all thought-trains and affect responses # # -------------------------------------------------- class AiDataEngine(): def __init__(self, speed=1): print('building engine server') self.interrupt_bang = False # self.running = False # self.PORT = 8000 # self.IP_ADDR = "127.0.0.1" self.global_speed = speed self.rnd_stream = 0 # make a default dict for the engine self.datadict = {'move_rnn': 0, 'affect_rnn': 0, 'move_affect_conv2': 0, 'affect_move_conv2': 0, 'master_output': 0, 'user_in': 0, 'rnd_poetry': 0, 'rhythm_rnn': 0, 'affect_net': 0, 'self_awareness': 0, 'affect_decision': 0, 'rhythm_rate': 0.1} # name list for nets self.netnames = ['move_rnn', 'affect_rnn', 'move_affect_conv2', 'affect_move_conv2', 'self_awareness', # Net name for self-awareness 'master_output'] # input for self-awareness # names for affect listening self.affectnames = ['user_in', 'rnd_poetry', 'affect_net', 'self_awareness'] self.rhythm_rate = 0.1 self.affect_listen = 0 # fill with random values self.dict_fill() print(self.datadict) # instantiate nets as objects and make models self.move_net = MoveRNN() self.affect_net = AffectRNN() self.move_affect_net = MoveAffectCONV2() self.affect_move_net = AffectMoveCONV2() self.affect_perception = MoveAffectCONV2() # logging on/off switches self.net_logging = False self.master_logging = False self.streaming_logging = False self.affect_logging = False # -------------------------------------------------- # # prediction and rnd num gen zone # # -------------------------------------------------- # makes a prediction for a given net and defined input var def make_data(self): while True: # calc rhythmic intensity based on self-awareness factor & global speed intensity = self.datadict.get('self_awareness') self.rhythm_rate = (self.rhythm_rate * intensity) * self.global_speed self.datadict['rhythm_rate'] = self.rhythm_rate # get input vars from dict (NB not always self) in_val1 = self.get_in_val(0) # move RNN as input in_val2 = self.get_in_val(1) # affect RNN as input in_val3 = self.get_in_val(2) # move - affect as input in_val4 = self.get_in_val(1) # affect RNN as input # send in vals to net object for prediction pred1 = self.move_net.predict(in_val1) pred2 = self.affect_net.predict(in_val2) pred3 = self.move_affect_net.predict(in_val3) pred4 = self.affect_move_net.predict(in_val4) # special case for self awareness stream self_aware_input = self.get_in_val(5) # main movement as input self_aware_pred = self.affect_perception.predict(self_aware_input) if self.net_logging: print(f" 'move_rnn' in: {in_val1} predicted {pred1}") print(f" 'affect_rnn' in: {in_val2} predicted {pred2}") print(f" move_affect_conv2' in: {in_val3} predicted {pred3}") print(f" 'affect_move_conv2' in: {in_val4} predicted {pred4}") print(f" 'self_awareness' in: {self_aware_input} predicted {self_aware_pred}") # put predictions back into the dicts and master self.put_pred(0, pred1) self.put_pred(1, pred2) self.put_pred(2, pred3) self.put_pred(3, pred4) self.put_pred(4, self_aware_pred) # outputs a stream of random poetry rnd_poetry = random() self.datadict['rnd_poetry'] = random() if self.streaming_logging: print(f'random poetry = {rnd_poetry}') sleep(self.rhythm_rate) # function to get input value for net prediction from dictionary def get_in_val(self, which_dict): # get the current value and reshape ready for input for prediction input_val = self.datadict.get(self.netnames[which_dict]) input_val = np.reshape(input_val, (1, 1, 1)) return input_val # function to put prediction value from net into dictionary def put_pred(self, which_dict, pred): # randomly chooses one of te 4 predicted outputs out_pred_val = pred[0][randrange(4)] if self.master_logging: print(f"out pred val == {out_pred_val}, master move output == {self.datadict['master_output']}") # save to data dict and master move out ONLY 1st data self.datadict[self.netnames[which_dict]] = out_pred_val self.datadict['master_output'] = out_pred_val # fills the dictionary with rnd values for each key of data dictionary def dict_fill(self): for key in self.datadict.keys(): rnd = random() self.datadict[key] = rnd # -------------------------------------------------- # # affect and streaming methods # # -------------------------------------------------- # define which feed to listen to, and duration # and a course of affect response def affect(self): # daddy cycle = is the master running on? while True: if self.affect_logging: print('\t\t\t\t\t\t\t\t=========HIYA - DADDY cycle===========') # flag for breaking on big affect signal self.interrupt_bang = True # calc master cycle before a change master_cycle = randrange(6, 26) * self.global_speed loop_dur = time() + master_cycle if self.affect_logging: print(f" interrupt_listener: started! sleeping now for {loop_dur}...") # refill the dicts????? self.dict_fill() # child cycle - waiting for interrupt from master clock while time() < loop_dur: if self.affect_logging: print('\t\t\t\t\t\t\t\t=========Hello - child cycle 1 ===========') # if a major break out then go to Daddy cycle if not self.interrupt_bang: break # randomly pick an input stream for this cycle rnd = randrange(4) self.rnd_stream = self.affectnames[rnd] self.datadict['affect_decision'] = rnd print(self.rnd_stream) if self.affect_logging: print(self.rnd_stream) # hold this stream for 1-4 secs, unless interrupt bang end_time = time() + (randrange(1000, 4000) / 1000) if self.affect_logging: print('end time = ', end_time) # baby cycle 2 - own time loops while time() < end_time: if self.affect_logging: print('\t\t\t\t\t\t\t\t=========Hello - baby cycle 2 ===========') # go get the current value from dict affect_listen = self.datadict[self.rnd_stream] if self.affect_logging: print('current value =', affect_listen) # make the master output the current value of the stream self.datadict['master_output'] = affect_listen if self.master_logging: print(f'\t\t ============== master move output = {affect_listen}') # calc affect on behaviour # if input stream is LOUD then smash a random fill and break out to Daddy cycle... if affect_listen > 0.50: if self.affect_logging: print('interrupt > HIGH !!!!!!!!!') # A - refill dict with random self.dict_fill() # B - jumps out of this loop into daddy self.interrupt_bang = False if self.affect_logging: print('interrupt bang = ', self.interrupt_bang) # C break out of this loop, and next (cos of flag) break # if middle loud fill dict with random, all processes norm elif 0.20 < affect_listen < 0.49: if self.affect_logging: print('interrupt MIDDLE -----------') print('interrupt bang = ', self.interrupt_bang) # refill dict with random self.dict_fill() elif affect_listen <= 0.20: if self.affect_logging: print('interrupt LOW_______________') print('interrupt bang = ', self.interrupt_bang) # and wait for a cycle sleep(self.rhythm_rate) def parse_got_dict(self, got_dict): self.datadict['user_in'] = got_dict['mic_level'] # user change the overall speed of the engine self.global_speed = got_dict['speed'] # user change tempo of outputs and parsing self.rhythm_rate = got_dict['tempo'] # # stop start methods # def go(self): # # self.running = True # trio.run(self.flywheel) # print('I got here daddy') def quit(self): self.running = False """main client script controls microphone stream and organise all audio responses""" class Client: def __init__(self, library): self.running = True self.connected = False self.logging = False # is the robot connected self.robot_connected = True self.direction = 1 if self.robot_connected: # import robot scripts from arm.arm import Arm from robot.rerobot import Robot # instantiate arm comms self.arm_arm = Arm() # self.robot_robot.reset_arm() # prepare for movement # LED's ready fpr drawing self.arm_arm.led_blue() # get arm into draw mode self.arm_arm.draw_mode_status = True self.arm_arm.first_draw_move = True self.arm_arm.pen_drawing_status = False # goto position self.arm_arm.arm_reach_out() # instantiate robot comms self.robot_robot = Robot() # move gripper arm up for n in range(12): self.robot_robot.gripper_up() if library == 'jazz': self.audio_file_sax = AudioSegment.from_mp3('assets/alfie.mp3') self.audio_file_bass = AudioSegment.from_mp3('assets/bass.mp3') + 4 elif library == 'pop': self.audio_file_sax = AudioSegment.from_wav('assets/vocals.wav') self.audio_file_bass = AudioSegment.from_wav('assets/accompaniment.wav') # robot instrument vars # globs for sax self.pan_law_sax = -0.5 self.audio_file_len_ms_sax = self.audio_file_sax.duration_seconds * 1000 # globs for bass self.pan_law_bass = 0 self.audio_file_len_ms_bass = self.audio_file_bass.duration_seconds * 1000 # self.HOST = '127.0.0.1' # Client IP (this) # self.PORT = 8000 # Port to listen on (non-privileged ports are > 1023) self.CHUNK = 2 ** 11 self.RATE = 44100 self.p = pyaudio.PyAudio() self.stream = self.p.open(format=pyaudio.paInt16, channels=1, rate=self.RATE, input=True, frames_per_buffer=self.CHUNK) # build send data dict self.send_data_dict = {'mic_level': 0, 'speed': 1, 'tempo': 0.1 } # init got dict self.got_dict = {} # instantiate the server self.engine = AiDataEngine() # # set the ball rolling # self.main() def snd_listen(self): print("mic listener: started!") while True: data = np.frombuffer(self.stream.read(self.CHUNK,exception_on_overflow = False), dtype=np.int16) peak = np.average(np.abs(data)) * 2 if peak > 2000: bars = "#" * int(50 * peak / 2 ** 16) print("%05d %s" % (peak, bars)) self.send_data_dict['mic_level'] = peak / 30000 def terminate(self): self.stream.stop_stream() self.stream.close() self.p.terminate() def data_exchange(self): print("data exchange: started!") while True: # send self.send_data_dict self.engine.parse_got_dict(self.send_data_dict) # get self.datadict from engine self.got_dict = self.engine.datadict # sync with engine & stop freewheeling sleep_dur = self.got_dict['rhythm_rate'] # print('data exchange') sleep(sleep_dur) def engine(self): # set the engine off self.engine.go() def main(self): # snd_listen and client need dependent threads. # All other IO is ok as a single Trio thread inside self.client tasks = [self.engine.make_data, self.engine.affect, self.snd_listen, self.data_exchange, self.robot_sax, self.robot_bass] with concurrent.futures.ThreadPoolExecutor() as executor: futures = {executor.submit(task): task for task in tasks} def robot_sax(self): # make a serial port connection here print('im here SAX - sleeping for 3') sleep(3) # loop here # while self.running: # print('im here2') # while not self.improv_go: # print('im here3') # sleep(1) # print('sleeping robot') # then start improvisers while True: print('im here4') # grab raw data from engine stream raw_data_from_dict = self.got_dict['master_output'] rhythm_rate = self.got_dict['rhythm_rate'] print('sax', raw_data_from_dict, rhythm_rate) # add variability to the individual instrument rnd_dur_delta = random() rhythm_rate *= rnd_dur_delta * 8 print('sax', raw_data_from_dict, rhythm_rate) # make a sound & move bot self.make_sound('sax', raw_data_from_dict, rhythm_rate) print('making a new one') def robot_bass(self): # make a serial port connection here print('im here Bass - sleeping for 3') sleep(3) # loop here # while self.running: # print('im here2') # while not self.improv_go: # print('im here3') # sleep(1) # print('sleeping robot') # then start improvisers while True: print('im here4') # grab raw data from engine stream raw_data_from_dict = self.got_dict['master_output'] # trying different part of the dict raw_data_from_dict = self.got_dict['move_rnn'] rhythm_rate = self.got_dict['rhythm_rate'] print('bass', raw_data_from_dict, rhythm_rate) # add variability to the individual instrument rnd_dur_delta = random() * 4 rhythm_rate *= rnd_dur_delta print('bass', raw_data_from_dict, rhythm_rate) # make a sound & move bot self.make_sound('bass', raw_data_from_dict, rhythm_rate) print('making a new one') def make_sound(self, instrument, incoming_raw_data, rhythm_rate): # # temp random num gen # rnd = randrange(self.audio_dir_len) # print(self.audio_dir[rnd]) print('making sound') if instrument == 'sax': audio_file = self.audio_file_sax audio_file_len_ms = self.audio_file_len_ms_sax pan_law = self.pan_law_sax len_delta = random() * 1000 elif instrument == 'bass': audio_file = self.audio_file_bass audio_file_len_ms = self.audio_file_len_ms_bass pan_law = self.pan_law_bass len_delta = random() * 1000 # rescale incoming raw data audio_play_position = int(((incoming_raw_data - 0) / (1 - 0)) * (audio_file_len_ms - 0) + 0) duration = rhythm_rate * len_delta if duration < 0.1: duration = 0.1 end_point = audio_play_position + duration print(audio_play_position, end_point, duration) # make a sound from incoming data snippet = audio_file[audio_play_position: end_point] print('snippet') # pan snippet pan_snippet = snippet.pan(pan_law) print('pan') # move bot before making sound if self.robot_connected: if instrument == 'sax': self.move_robot(incoming_raw_data, duration) # get the robot to move with play(pan_snippet) print('play') # sleep(duration/ 1000) print('fininshed a play') def move_robot(self, incoming_data, duration): # top previous movements # self.robot_robot.gripper_stop() # self.robot_robot.paddle_stop() # self.robot_robot.stop() # which movement if duration > 0.2: # select a joint (1-16 % 4) # or move bot left or right (17) # or move gripper up or down (18) rnd_joint = randrange(22) rnd_direction = randrange(2) if rnd_direction == 1: direction = -20 else: direction = 20 rnd_speed = randrange(3, 15) rnd_speed *= 10 # move an arm joint if rnd_joint <= 15: joint = (rnd_joint % 4) + 1 self.arm_arm.move_joint_relative_speed(joint, direction, rnd_speed) # move the gripper elif rnd_joint == 16: if rnd_direction == 1: self.robot_robot.gripper_up() else: self.robot_robot.gripper_down() # or move the wheels elif rnd_joint == 17: if rnd_direction == 1: self.robot_robot.paddle_open() else: self.robot_robot.paddle_close() # or move the wheels elif rnd_joint >= 18: if rnd_direction == 1: self.robot_robot.step_forward() else: self.robot_robot.step_backward() if __name__ == '__main__': library = 'jazz' # library = 'pop' cl = Client(library) # set the ball rolling cl.main()
34.229688
110
0.540147
b928aa43518b91ff243097b44a7566b87d0929a8
7,984
css
CSS
public/css/back/edit.min.css
hansnataniel/ca
70e1be225596b5b81151abe0abd13cc74a812c61
[ "MIT" ]
null
null
null
public/css/back/edit.min.css
hansnataniel/ca
70e1be225596b5b81151abe0abd13cc74a812c61
[ "MIT" ]
null
null
null
public/css/back/edit.min.css
hansnataniel/ca
70e1be225596b5b81151abe0abd13cc74a812c61
[ "MIT" ]
null
null
null
.edit-item-content{padding:20px 0}.edit-form-group{position:relative;display:block;font-size:0;margin-bottom:15px}.edit-form-label,.edit-form-text{display:block;font-size:14px;color:#0d0f3b;position:relative}.edit-form-group:last-child{margin-bottom:0}.edit-form-label{width:150px;margin-bottom:5px}.edit-form-text{width:100%;height:40px;padding:0 10px;border:1px solid #d2d2d2;margin-right:10px;background:#fff;cursor:text!important}.edit-form-text:focus{border:1px solid #f7961f!important}.edit-form-note{position:relative;display:inline-block;vertical-align:top;font-size:12px;width:150px;color:#a1a1a1;padding:5px 0 0}.edit-form-note-custom{position:relative;display:block;margin-left:160px;margin-top:10px;line-height:20px;font-size:14px;color:#0d0f3b}.edit-form-image{position:relative;display:inline-block;margin-right:10px;width:150px}.edit-form-image-delete,.edit-form-image-loading,.edit-form-image-success{width:100%;height:30px;color:#fff;border:0;font-size:14px}.edit-form-image-loading{position:absolute;display:none;bottom:0;left:0;background:#535353}.edit-form-image-success{position:absolute;display:none;bottom:0;left:0;background:green}.edit-form-image-delete{position:relative;display:block;background:#0d0f3b;-webkit-transition:background .4s;-moz-transition:background .4s;-ms-transition:background .4s;transition:background .4s}.edit-button-item,.edit-form-image-delete:hover{-webkit-transition:background .4s;-moz-transition:background .4s;-ms-transition:background .4s}.edit-form-image-delete:hover{background:red!important;transition:background .4s}.edit-form-image img{position:relative;display:block;max-height:150px}.col-1>.edit-item-content .edit-form-label{position:relative;display:inline-block;vertical-align:top;font-size:14px;width:150px;color:#0d0f3b;margin-right:10px;top:10px}.col-1>.edit-item-content .edit-form-text{position:relative;display:inline-block;vertical-align:top;font-size:14px;height:40px;padding:0 10px;border:1px solid #d2d2d2;color:#0d0f3b;margin-right:10px;width:calc(100% - 200px)}.col-1>.edit-item-content .select2-container{margin-right:10px!important}.col-1>.edit-item-content .edit-form-note{position:relative;display:inline-block;vertical-align:top;font-size:12px;width:calc(100% - 620px);color:#d2d2d2;padding:0}.col-1>.edit-item-content .edit-form-text.large{max-width:450px}.col-1>.edit-item-content .edit-form-text.medium{max-width:350px}.col-1>.edit-item-content .edit-form-text.small{max-width:250px}.col-1>.edit-item-content .large-prepend{position:relative;display:inline-block;vertical-align:top;max-width:calc(450px - 50px)}.col-1>.edit-item-content .medium-prepend{position:relative;display:inline-block;vertical-align:top;max-width:calc(350px - 50px)}.col-1>.edit-item-content .small-prepend{position:relative;display:inline-block;vertical-align:top;max-width:calc(250px - 50px)}.large-prepend,.medium-prepend,.small-prepend{position:relative;display:inline-block;vertical-align:top;max-width:calc(100% - 50px);margin-right:0!important}.edit-button-item,.prepend-group{position:relative;margin-right:10px}.col-1>.edit-item-content .prepend-group{display:inline-block;vertical-align:top}.col-1>.edit-item-content .prepend-group.large{max-width:450px}.col-1>.edit-item-content .prepend-group.medium{max-width:350px}.col-1>.edit-item-content .prepend-group.small{max-width:250px}.prepend-group{display:block;font-size:0;width:100%}.prepend-group .edit-form-text{width:calc(100% - 50px)!important}.prepend-label{position:relative;display:inline-block;vertical-align:top;width:50px;height:40px;background:#f7961f;color:#fff;font-size:14px;text-align:center;line-height:40px}.col-1>.edit-item-content .cke_chrome{display:inline-block;max-width:calc(100% - 200px)}.col-1>.edit-item-content .edit-form-image{position:relative;display:inline-block;vertical-align:top;width:150px}.col-1>.edit-item-content .edit-form-image-delete{position:relative;display:block;width:100%;height:30px;background:#0d0f3b;color:#fff;border:0;font-size:14px}.col-1>.edit-item-content .edit-form-image img{position:relative;display:block;max-height:150px}.edit-button-group{position:relative;display:block;font-size:0}.edit-button-item{display:inline-block;vertical-align:top;width:150px;max-width:calc(50% - 5px);border:0;height:40px;background:#0d0f3b;color:#fff;font-size:14px;transition:background .4s}.edit-button-back,.edit-button-item:hover{background:#f7961f;-webkit-transition:background .4s;-moz-transition:background .4s;-ms-transition:background .4s}.edit-button-item:last-child{margin-right:0}.edit-button-item:hover{transition:background .4s}.edit-button-back{color:#fff;font-size:14px;padding-left:30px;width:auto;padding-right:15px;line-height:40px;height:40px;margin-bottom:20px;transition:background .4s}.edit-button-back:hover{background:#0d0f3b;-webkit-transition:background .4s;-moz-transition:background .4s;-ms-transition:background .4s;transition:background .4s}.edit-button-back:before{content:'';position:absolute;height:6px;width:6px;left:15px;top:17px;border-left:2px solid #fff;border-top:2px solid #fff;-webkit-transform:rotate(-45deg);-moz-transform:rotate(-45deg);-ms-transform:rotate(-45deg);transform:rotate(-45deg)}.reset{background:red!important}.area{resize:none;height:150px!important;padding:10px!important;font-size:14px}textarea.area:focus{border:1px solid #f7961f!important;outline:0}input.edit-form-text{padding:7px 10px;cursor:pointer}.edit-form-radio-group{position:relative;display:inline-block;vertical-align:top;font-size:0}.edit-form-radio-item{position:relative;display:block;font-size:0;margin-bottom:5px}.edit-form-radio,.edit-form-radio-label{display:inline-block;position:relative;vertical-align:top}.edit-form-radio{margin-right:5px;top:2px}.edit-form-radio-label{font-size:14px;color:#0d0f3b}.edit-form-text.image{display:inline-block!important;vertical-align:top;width:auto;padding:7px 10px!important;max-width:100%}.col-1>.edit-item-content .edit-form-text.image{width:auto}.page-item-error-container{position:relative;display:block}.page-item-error-item{position:relative;display:block;font-size:14px;line-height:24px;color:red;padding-left:40px;border-left:1px solid red;border-right:1px solid red}.page-item-error-item:before{content:'';position:absolute;left:25px;top:10px;width:5px;height:5px;border-radius:50%;background:red}.page-item-error-item:first-child{padding-top:15px;border-top:1px solid red}.page-item-error-item:first-child:before{top:25px}.page-item-error-item:last-child{margin-bottom:30px;padding-bottom:15px;border-bottom:1px solid red}.edit-last-edit{position:relative;display:block;margin-bottom:30px;padding:20px;border:1px solid #f7961f}.edit-last-edit-group{position:relative;display:block;margin-bottom:20px}.edit-last-edit-group:last-child{margin-bottom:0}.edit-last-edit-lastitle{position:relative;display:block;font-size:14px;font-weight:600;color:#f7961f;margin-bottom:5px}.edit-last-edit-item{position:relative;display:block;font-size:12px}.edit-last-edit-item span{position:relative;display:inline-block;vertical-align:top;line-height:20px;color:#0d0f3b}.edit-last-edit-item span:first-child{width:90px}.edit-last-edit-item span:last-child{color:#f7961f}@media screen and (max-width:1024px){.col-1>.edit-item-content .edit-form-text,.col-1>.edit-item-content .prepend-group{max-width:350px!important}.col-1>.edit-item-content .edit-form-note{width:calc(100% - 520px)}}@media screen and (max-width:768px){.edit-form-label{position:relative!important;display:block!important;top:0!important}.col-1>.edit-item-content .edit-form-text{max-width:none!important;width:100%}.col-1>.edit-item-content .cke_chrome{display:block!important;width:100%!important;max-width:none!important}.col-1>.edit-item-content .edit-form-note{width:100%;padding-top:5px}}@media screen and (max-width :500px){.edit-last-edit-item span{display:block;position:relative}.edit-last-edit-item span:nth-child(2){display:none}.edit-last-edit-item span:last-child{padding-bottom:5px}}
7,984
7,984
0.80511
5706a4a2119d033af67e43352f2fb3f212c8bfe4
471
js
JavaScript
src/containers/PopupContainer.js
euskal64500/Mastermind
089ee77c2dbe3811096e77763af3c98e8af03214
[ "MIT" ]
null
null
null
src/containers/PopupContainer.js
euskal64500/Mastermind
089ee77c2dbe3811096e77763af3c98e8af03214
[ "MIT" ]
null
null
null
src/containers/PopupContainer.js
euskal64500/Mastermind
089ee77c2dbe3811096e77763af3c98e8af03214
[ "MIT" ]
null
null
null
import { connect } from 'react-redux'; import { bindActionCreators } from 'redux'; import { closePopup } from '../actions'; import Popup from '../components/Popup'; const mapStateToProps = state => ({ visible: state.popup.show, type: state.popup.type }); const mapDispatchToProps = dispatch => bindActionCreators({ onClose: closePopup }, dispatch); const PopupContainer = connect( mapStateToProps, mapDispatchToProps, )(Popup); export default PopupContainer;
24.789474
93
0.734607
40b08ff332e17d548a2058fbc8a12d496e346078
7,276
rb
Ruby
lib/ruote/exp/fe_participant.rb
kennethkalmer/ruote
776cd89180c5ed59ef94f3d52d31f2296e0573c2
[ "MIT" ]
2
2016-05-08T17:52:28.000Z
2016-07-19T15:01:32.000Z
lib/ruote/exp/fe_participant.rb
kennethkalmer/ruote
776cd89180c5ed59ef94f3d52d31f2296e0573c2
[ "MIT" ]
null
null
null
lib/ruote/exp/fe_participant.rb
kennethkalmer/ruote
776cd89180c5ed59ef94f3d52d31f2296e0573c2
[ "MIT" ]
null
null
null
#-- # Copyright (c) 2005-2010, John Mettraux, [email protected] # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. # # Made in Japan. #++ require 'ruote/exp/condition' module Ruote::Exp # # The 'participant' expression is very special. It sits on the fence between # the engine and the external world. # # The participant expression is used to pass workitems to participants # from the engine. Those participants are bound at start time (usually) in # the engine via its register_participant method. # # Here's an example of two concurrent participant expressions in use : # # concurrence do # participant :ref => 'alice' # participant :ref => 'bob' # end # # Upon encountering the two expressions, the engine will lookup their name # in the participant map and hand the workitems to the participant instances # registered for those names. # # # == attributes passed as arguments # # All the attributes passed to a participant will be fed to the outgoing # workitem under a new 'params' field. # # Thus, with # # participant :ref => 'alice', :task => 'maw the lawn', :timeout => '2d' # # Alice will receive a workitem with a field params set to # # { :ref => 'alice', :task => 'maw the lawn', :timeout => '2d' } # # The fields named 'params' will be deleted before the workitems resumes # in the flow (with the engine replying to the parent expression of this # participant expression). # # # == simplified participant notation # # This process definition is equivalent to the one above. Less to write. # # concurrence do # participant 'alice' # bob # end # # Please note that 'bob' alone could stand for the participant 'bob' or # the subprocess named 'bob'. Subprocesses do take precedence over # participants (if there is a subprocess named 'bob' and a participant # named 'bob'. # # # == participant defined timeout # # Usually, timeouts are given for an expression in the process definition. # # participant 'alice', :timeout => '2d' # # where alice as two days to complete her task (send back the workitem). # # But it's OK for participant classes registered in the engine to provide # their own timeout value. The participant instance simply has to reply to # the #timeout method and provide a meaningful timeout value. # # Note however, that the process definition timeout (if any) will take # precedence over the participant specified one. # # # == asynchronous # # The expression will make sure to dispatch to the participant in an # asynchronous way. This means that the dispatch will occur in a dedicated # thread. # # Since the dispatching to the participant could take a long time and block # the engine for too long, this 'do thread' policy is used by default. # # If the participant itself replies to the method #do_not_thread and replies # positively to it, a new thread (or a next_tick) won't get used. This is # practical for tiny participants that don't do IO and reply immediately # (after a few operations). By default, BlockParticipant instances do not # thread. # class ParticipantExpression < FlowExpression #include FilterMixin # TODO names :participant # Should return true when the dispatch was successful. # h_reader :dispatched def apply # # determine participant h.participant_name = attribute(:ref) || attribute_text h.participant_name = h.participant_name.to_s if h.participant_name == '' raise ArgumentError.new("no participant name specified") end participant_info = @context.plist.lookup_info(h.participant_name) raise(ArgumentError.new( "no participant named #{h.participant_name.inspect}") ) if participant_info.nil? # # participant found, consider timeout schedule_timeout(participant_info) # # dispatch to participant h.applied_workitem['participant_name'] = h.participant_name h.applied_workitem['fields']['params'] = compile_atts persist_or_raise @context.storage.put_msg( 'dispatch', 'fei' => h.fei, 'participant_name' => h.participant_name, 'workitem' => h.applied_workitem, 'for_engine_worker?' => (participant_info.class != Array)) end def cancel (flavour) return reply_to_parent(h.applied_workitem) unless h.participant_name # no participant, reply immediately do_persist || return # # if do_persist returns false, it means we're operating on stale # data and cannot continue @context.storage.put_msg( 'dispatch_cancel', 'fei' => h.fei, 'participant_name' => h.participant_name, 'flavour' => flavour, 'workitem' => h.applied_workitem) end def reply (workitem) pa = @context.plist.lookup( workitem['participant_name'], :on_reply => true) pa.on_reply(Ruote::Workitem.new(workitem)) if pa super(workitem) end def reply_to_parent (workitem) workitem['fields'].delete('params') workitem['fields'].delete('dispatched_at') super(workitem) end protected # Once the dispatching work (done by the dispatch pool) is done, a # 'dispatched' msg is sent, we have to flag the participant expression # as 'dispatched' => true # # See http://groups.google.com/group/openwferu-users/browse_thread/thread/ff29f26d6b5fd135 # for the motivation. # def do_dispatched (msg) h.dispatched = true do_persist # let's not care if it fails... end # Overriden with an empty behaviour. The work is now done a bit later # via the #schedule_timeout method. # def consider_timeout end # Determines and schedules timeout if any. # # Note that process definition timeout has priority over participant # specified timeout. # def schedule_timeout (p_info) timeout = attribute(:timeout) || (p_info.timeout rescue nil) || (p_info.is_a?(Array) ? p_info.last['timeout'] : nil) do_schedule_timeout(timeout) end end end
30.316667
94
0.683342
da3f4233b0c02ea23ec586364f41d64c6c3c11fc
4,432
php
PHP
server/totara/competency/pathway/learning_plan/classes/external.php
woon5118/totara_ub
a38f8e5433c93d295f6768fb24e5eecefa8294cd
[ "PostgreSQL" ]
null
null
null
server/totara/competency/pathway/learning_plan/classes/external.php
woon5118/totara_ub
a38f8e5433c93d295f6768fb24e5eecefa8294cd
[ "PostgreSQL" ]
null
null
null
server/totara/competency/pathway/learning_plan/classes/external.php
woon5118/totara_ub
a38f8e5433c93d295f6768fb24e5eecefa8294cd
[ "PostgreSQL" ]
null
null
null
<?php /* * This file is part of Totara Learn * * Copyright (C) 2018 onwards Totara Learning Solutions LTD * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * @author Brendan Cox <[email protected]> * @author Riana Rossouw <[email protected]> * @package pathway_manual */ namespace pathway_learning_plan; use context_system; use totara_competency\achievement_configuration; use totara_competency\entity\competency; use totara_competency\entity\configuration_change; use totara_core\advanced_feature; class external extends \external_api { /** create */ public static function create_parameters() { return new \external_function_parameters( [ 'competency_id' => new \external_value(PARAM_INT, 'Competency id'), 'sortorder' => new \external_value(PARAM_INT, 'Sortorder'), 'actiontime' => new \external_value(PARAM_INT, 'Time user initiated the action. It is used to group changes done in single user action together'), ] ); } public static function create(int $competency_id, int $sortorder, string $action_time) { advanced_feature::require('competency_assignment'); require_capability('totara/hierarchy:updatecompetency', context_system::instance()); $competency = new competency($competency_id); $config = new achievement_configuration($competency); // Save history before making any changes - for now the action_time is used to ensure we do this only once per user 'Apply changes' action $config->save_configuration_history($action_time); $pathway = new learning_plan(); $pathway->set_competency($competency) ->set_sortorder($sortorder) ->save(); // Log the configuration change- for now the action_time is used to ensure we do this only once per user 'Apply changes' action configuration_change::add_competency_entry( $competency->id, configuration_change::CHANGED_CRITERIA, $action_time ); return $pathway->get_id(); } public static function create_returns() { return new \external_value(PARAM_INT, 'Pathway id'); } /** update */ public static function update_parameters() { return new \external_function_parameters( [ 'id' => new \external_value(PARAM_INT, 'Id of pathway'), 'sortorder' => new \external_value(PARAM_INT, 'Sortorder'), 'actiontime' => new \external_value(PARAM_INT, 'Time user initiated the action. It is used to group changes done in single user action together'), ] ); } public static function update(int $id, int $sortorder, string $action_time) { advanced_feature::require('competency_assignment'); require_capability('totara/hierarchy:updatecompetency', context_system::instance()); $pathway = learning_plan::fetch($id); $config = new achievement_configuration($pathway->get_competency()); // Save history before making any changes - for now the action_time is used to ensure we do this only once per user 'Apply changes' action $config->save_configuration_history($action_time); $pathway->set_sortorder($sortorder) ->save(); // Log the configuration change- for now the action_time is used to ensure we do this only once per user 'Apply changes' action configuration_change::add_competency_entry( $pathway->get_competency()->id, configuration_change::CHANGED_CRITERIA, $action_time ); return $pathway->get_id(); } public static function update_returns() { return new \external_value(PARAM_INT, 'Pathway id'); } }
39.927928
162
0.679377
8ea6ab88fba9fe9cb0cc3894072f9a809aeeab32
1,870
js
JavaScript
public/layuiadmin/json/layim/getList.js
gong86627/laravel
c6eb65cd0ba6f96fc60d017070afd9637d0fec1e
[ "MIT" ]
4
2019-06-24T00:38:16.000Z
2021-12-11T07:27:26.000Z
public/layuiadmin/json/layim/getList.js
gong86627/laravel
c6eb65cd0ba6f96fc60d017070afd9637d0fec1e
[ "MIT" ]
null
null
null
public/layuiadmin/json/layim/getList.js
gong86627/laravel
c6eb65cd0ba6f96fc60d017070afd9637d0fec1e
[ "MIT" ]
3
2021-11-18T13:33:47.000Z
2021-12-27T09:14:43.000Z
{ "code": 0 ,"msg": "" ,"data": { "mine": { "username": "测试名称" ,"id": "100000" ,"status": "online" ,"sign": "测试" ,"avatar": "" } ,"friend": [{ "groupname": "测试分组一" ,"id": 0 ,"list": [{ "username": "测试1" ,"id": "100001" ,"avatar": "" ,"sign": "测试内容1" ,"status": "online" },{ "username": "测试2" ,"id": "100001222" ,"sign": "测试内容2" ,"avatar": "" },{ "username": "测试3" ,"id": "10034001" ,"avatar": "" ,"sign": "" },{ "username": "测试4" ,"id": "168168" ,"avatar": "" ,"sign": "测试内容4" },{ "username": "测试5" ,"id": "666666" ,"avatar": "" ,"sign": "测试内容5" }] },{ "groupname": "测试分组二" ,"id": 1 ,"list": [{ "username": "测试6" ,"id": "121286" ,"avatar": "" ,"sign": "测试内容6" },{ "username": "测试7" ,"id": "108101" ,"avatar": "" ,"sign": "微电商达人" },{ "username": "测试8" ,"id": "12123454" ,"avatar": "" ,"sign": "测试内容8" },{ "username": "测试9" ,"id": "102101" ,"avatar": "" ,"sign": "" },{ "username": "测试10" ,"id": "3435343" ,"avatar": "" ,"sign": "" }] },{ "groupname": "测试分组三" ,"id": 2 ,"list": [{ "username": "测试11" ,"id": "76543" ,"avatar": "" ,"sign": "测试内容11" },{ "username": "测试12" ,"id": "4803920" ,"avatar": "" ,"sign": "测试内容12" }] }] ,"group": [{ "groupname": "测试群组一" ,"id": "101" ,"avatar": "" },{ "groupname": "测试群组二" ,"id": "102" ,"avatar": "" }] } }
19.479167
27
0.321925
b3e3dd62be804bfa406e7e432f989e2486499cd0
193
rs
Rust
src/test/ui/rfc-2632-const-trait-impl/const-check-fns-in-const-impl.rs
ohno418/rust
395a09c3dafe0c7838c9ca41d2b47bb5e79a5b6d
[ "ECL-2.0", "Apache-2.0", "MIT-0", "MIT" ]
2
2022-02-02T03:22:13.000Z
2022-02-13T18:52:37.000Z
src/test/ui/rfc-2632-const-trait-impl/const-check-fns-in-const-impl.rs
maxrovskyi/rust
51558ccb8e7cea87c6d1c494abad5451e5759979
[ "ECL-2.0", "Apache-2.0", "MIT-0", "MIT" ]
4
2022-03-10T11:13:37.000Z
2022-03-10T11:54:54.000Z
src/test/ui/rfc-2632-const-trait-impl/const-check-fns-in-const-impl.rs
maxrovskyi/rust
51558ccb8e7cea87c6d1c494abad5451e5759979
[ "ECL-2.0", "Apache-2.0", "MIT-0", "MIT" ]
1
2022-02-14T09:24:04.000Z
2022-02-14T09:24:04.000Z
#![feature(const_trait_impl)] struct S; trait T { fn foo(); } fn non_const() {} impl const T for S { fn foo() { non_const() } //~^ ERROR cannot call non-const fn } fn main() {}
12.0625
39
0.57513
a7b222a403c29eee83810c77d4c184002fa33f64
155
css
CSS
frontend/src/pages/Events.css
ecarlste/graphql-react-event-booking
b680a2188ce9bf1e760140246af84b18e01e2263
[ "MIT" ]
null
null
null
frontend/src/pages/Events.css
ecarlste/graphql-react-event-booking
b680a2188ce9bf1e760140246af84b18e01e2263
[ "MIT" ]
null
null
null
frontend/src/pages/Events.css
ecarlste/graphql-react-event-booking
b680a2188ce9bf1e760140246af84b18e01e2263
[ "MIT" ]
null
null
null
.events-control { text-align: center; border: 1px solid #01d1d1; padding: 3rem; margin: 2rem auto; width: 30rem; max-width: 80%; }
17.222222
30
0.6
dbf48d4d2af7aead576383e85872d32c022e27aa
2,215
php
PHP
src/Odnoklassniki/Provider.php
J2TeamNNL/Providers
14668d12fcbe65483027aa5d84e505b4d38cc611
[ "MIT" ]
1
2020-08-11T20:59:32.000Z
2020-08-11T20:59:32.000Z
src/Odnoklassniki/Provider.php
J2TeamNNL/Providers
14668d12fcbe65483027aa5d84e505b4d38cc611
[ "MIT" ]
null
null
null
src/Odnoklassniki/Provider.php
J2TeamNNL/Providers
14668d12fcbe65483027aa5d84e505b4d38cc611
[ "MIT" ]
null
null
null
<?php namespace SocialiteProviders\Odnoklassniki; use Illuminate\Support\Arr; use SocialiteProviders\Manager\OAuth2\AbstractProvider; use SocialiteProviders\Manager\OAuth2\User; class Provider extends AbstractProvider { /** * Unique Provider Identifier. */ public const IDENTIFIER = 'ODNOKLASSNIKI'; /** * {@inheritdoc} */ protected $scopes = ['VALUABLE_ACCESS', 'GET_EMAIL']; /** * {@inheritdoc} */ protected $scopeSeparator = ';'; /** * {@inheritdoc} */ protected function getAuthUrl($state) { return $this->buildAuthUrlFromBase('https://connect.ok.ru/oauth/authorize', $state); } /** * {@inheritdoc} */ protected function getTokenUrl() { return 'https://api.ok.ru/oauth/token.do'; } /** * {@inheritdoc} */ protected function getUserByToken($token) { $secretKey = md5($token.$this->clientSecret); $publicKey = app()['config']['services.odnoklassniki']['client_public']; $sign = 'application_key='.$publicKey.'format=jsonmethod=users.getCurrentUser'.$secretKey; $params = http_build_query([ 'method' => 'users.getCurrentUser', 'format' => 'json', 'application_key' => $publicKey, 'sig' => md5($sign), 'access_token' => $token, ]); $response = $this->getHttpClient()->get('https://api.odnoklassniki.ru/fb.do?'.$params); return json_decode($response->getBody()->getContents(), true); } /** * {@inheritdoc} */ protected function mapUserToObject(array $user) { return (new User())->setRaw($user)->map([ 'id' => Arr::get($user, 'uid'), 'nickname' => null, 'name' => Arr::get($user, 'name'), 'email' => Arr::get($user, 'email'), 'avatar' => Arr::get($user, 'pic_3'), ]); } /** * {@inheritdoc} */ protected function getTokenFields($code) { return array_merge(parent::getTokenFields($code), [ 'grant_type' => 'authorization_code', ]); } }
24.611111
98
0.542212
f76222e03985be79c3a25258d01113d9e082bfc4
1,764
rb
Ruby
lib/kennel/models/synthetic_test.rb
zdrve/kennel
0dd6746837fbe9a48e0130bb1409bd3ad89923e1
[ "MIT" ]
94
2017-12-09T09:48:30.000Z
2022-03-09T00:44:06.000Z
lib/kennel/models/synthetic_test.rb
zdrve/kennel
0dd6746837fbe9a48e0130bb1409bd3ad89923e1
[ "MIT" ]
71
2017-12-20T18:15:16.000Z
2022-03-24T18:05:32.000Z
lib/kennel/models/synthetic_test.rb
zdrve/kennel
0dd6746837fbe9a48e0130bb1409bd3ad89923e1
[ "MIT" ]
43
2017-12-09T01:01:10.000Z
2022-03-17T18:05:29.000Z
# frozen_string_literal: true module Kennel module Models class SyntheticTest < Record TRACKING_FIELD = :message DEFAULTS = { }.freeze READONLY_ATTRIBUTES = superclass::READONLY_ATTRIBUTES + [:status, :monitor_id] LOCATIONS = ["aws:ca-central-1", "aws:eu-north-1", "aws:eu-west-1", "aws:eu-west-3", "aws:eu-west-2", "aws:ap-south-1", "aws:us-west-2", "aws:us-west-1", "aws:sa-east-1", "aws:us-east-2", "aws:ap-northeast-1", "aws:ap-northeast-2", "aws:eu-central-1", "aws:ap-southeast-2", "aws:ap-southeast-1"].freeze settings :tags, :config, :message, :subtype, :type, :name, :locations, :options defaults( id: -> { nil }, tags: -> { @project.tags }, message: -> { "\n\n#{project.mention}" } ) def as_json return @as_json if @as_json locations = locations() data = { message: message, tags: tags, config: config, type: type, subtype: subtype, options: options, name: name, locations: locations == :all ? LOCATIONS : locations } if v = id data[:id] = v end @as_json = data end def self.api_resource "synthetics/tests" end def self.url(id) Utils.path_to_url "/synthetics/details/#{id}" end def self.parse_url(url) url[/\/synthetics\/details\/([a-z\d-]{11,})/, 1] # id format is 1ab-2ab-3ab end def self.normalize(expected, actual) super # tags come in a semi-random order and order is never updated expected[:tags]&.sort! actual[:tags].sort! ignore_default(expected, actual, DEFAULTS) end end end end
27.5625
308
0.559524
0dc544c02048e5d32a432ca9c075bdd7a7483d88
242
cs
C#
Peanuts.Net.Core/src/Persistence/IDocumentDao.cs
queoGmbH/peanuts
50d170bff470d2d9faa3e8a57a4ec123c4b8d407
[ "MIT" ]
5
2017-09-01T10:49:48.000Z
2021-02-22T20:31:55.000Z
Peanuts.Net.Core/src/Persistence/IDocumentDao.cs
queoGmbH/peanuts
50d170bff470d2d9faa3e8a57a4ec123c4b8d407
[ "MIT" ]
3
2017-11-01T14:08:07.000Z
2018-07-04T07:41:02.000Z
Peanuts.Net.Core/src/Persistence/IDocumentDao.cs
queoGmbH/peanuts
50d170bff470d2d9faa3e8a57a4ec123c4b8d407
[ "MIT" ]
4
2018-01-07T19:00:39.000Z
2021-02-26T19:41:36.000Z
using Com.QueoFlow.Peanuts.Net.Core.Domain.Documents; using Com.QueoFlow.Peanuts.Net.Core.Persistence.NHibernate; namespace Com.QueoFlow.Peanuts.Net.Core.Persistence { public interface IDocumentDao : IGenericDao<Document, int> { } }
34.571429
64
0.785124
b372ffef62affb5ef242405cae3add439db2480d
1,299
py
Python
cegs_portal/search/views/v1/search.py
ReddyLab/cegs-portal
a83703a3557167be328c24bfb866b6aa019ba059
[ "MIT" ]
null
null
null
cegs_portal/search/views/v1/search.py
ReddyLab/cegs-portal
a83703a3557167be328c24bfb866b6aa019ba059
[ "MIT" ]
null
null
null
cegs_portal/search/views/v1/search.py
ReddyLab/cegs-portal
a83703a3557167be328c24bfb866b6aa019ba059
[ "MIT" ]
null
null
null
from urllib.parse import unquote_plus from django.http import HttpResponseServerError from cegs_portal.search.errors import SearchResultsException from cegs_portal.search.forms import SearchForm from cegs_portal.search.json_templates.v1.search_results import ( search_results as sr_json, ) from cegs_portal.search.view_models.v1 import Search from cegs_portal.search.views.custom_views import TemplateJsonView class SearchView(TemplateJsonView): json_renderer = sr_json template = "search/v1/search_results.html" def request_options(self, request): options = super().request_options(request) options["search_query"] = request.GET["query"] options["facets"] = [int(facet) for facet in request.GET.getlist("facet", [])] return options def get(self, request, options, data): data["form"] = SearchForm() return super().get(request, options, data) def get_data(self, options): unquoted_search_query = unquote_plus(options["search_query"]) try: search_results = Search.search(unquoted_search_query, options["facets"]) except SearchResultsException as e: return HttpResponseServerError(e) search_results["query"] = options["search_query"] return search_results
34.184211
86
0.724403
e01960829d10854eed7df8ea889d72f22b59ba5b
46
h
C
lib/libc/wasi/libc-bottom-half/headers/private/stdarg.h
lukekras/zig
6f303c01f3e06fe8203563065ea32537f6eff456
[ "MIT" ]
12,718
2018-05-25T02:00:44.000Z
2022-03-31T23:03:51.000Z
lib/libc/wasi/libc-bottom-half/headers/private/stdarg.h
lukekras/zig
6f303c01f3e06fe8203563065ea32537f6eff456
[ "MIT" ]
8,483
2018-05-23T16:22:39.000Z
2022-03-31T22:18:16.000Z
lib/libc/wasi/libc-bottom-half/headers/private/stdarg.h
lukekras/zig
6f303c01f3e06fe8203563065ea32537f6eff456
[ "MIT" ]
1,400
2018-05-24T22:35:25.000Z
2022-03-31T21:32:48.000Z
#include_next <stdarg.h> #include <_/cdefs.h>
15.333333
24
0.717391
a2248ca28998ab50c512b8f62450395235a0f9b4
370
kt
Kotlin
compiler/fir/analysis-tests/testData/resolveWithStdlib/inference/plusAssignWithLambdaInRhs.kt
Mu-L/kotlin
5c3ce66e9979d2b3592d06961e181fa27fa88431
[ "ECL-2.0", "Apache-2.0" ]
45,293
2015-01-01T06:23:46.000Z
2022-03-31T21:55:51.000Z
compiler/fir/analysis-tests/testData/resolveWithStdlib/inference/plusAssignWithLambdaInRhs.kt
Seantheprogrammer93/kotlin
f7aabf03f89bdd39d9847572cf9e0051ea42c247
[ "ECL-2.0", "Apache-2.0" ]
3,386
2015-01-12T13:28:50.000Z
2022-03-31T17:48:15.000Z
compiler/fir/analysis-tests/testData/resolveWithStdlib/inference/plusAssignWithLambdaInRhs.kt
Seantheprogrammer93/kotlin
f7aabf03f89bdd39d9847572cf9e0051ea42c247
[ "ECL-2.0", "Apache-2.0" ]
6,351
2015-01-03T12:30:09.000Z
2022-03-31T20:46:54.000Z
// ISSUE: KT-39005 // !DUMP_CFG fun test() { val list: MutableList<(String) -> String> = null!! list += { it } } class A<T>(private val executor: ((T) -> Unit) -> Unit) fun <T> postpone(computation: () -> T): A<T> { val queue = mutableListOf<() -> Unit>() return A { resolve -> queue += { resolve(computation()) } } }
18.5
55
0.510811
2542031a30f69c3e0d7667d5ab1a32805e079356
2,353
js
JavaScript
src/components/Header.js
brightparagon/memo-react
56cdb5dd96cce46d6b50fb32caedbaae78476f3e
[ "MIT" ]
null
null
null
src/components/Header.js
brightparagon/memo-react
56cdb5dd96cce46d6b50fb32caedbaae78476f3e
[ "MIT" ]
null
null
null
src/components/Header.js
brightparagon/memo-react
56cdb5dd96cce46d6b50fb32caedbaae78476f3e
[ "MIT" ]
null
null
null
import React from 'react'; import { Link } from 'react-router'; import { Search } from 'components'; import ReactCSSTransitionGroup from 'react-addons-css-transition-group'; class Header extends React.Component { constructor(props) { super(props); // IMPLEMENT: CREATE A SEARCH STATUS this.state = { search: false }; this.toggleSearch = this.toggleSearch.bind(this); } toggleSearch() { this.setState({ search: !this.state.search }); } render() { const loginButton = ( <li> <Link to="/login"><i className="material-icons">vpn_key</i></Link> </li> ); const logoutButton = ( <li> <a onClick={this.props.onLogout}><i className="material-icons">lock_open</i></a> </li> ); return ( <div> <nav> <div className="nav-wrapper blue darken-1"> <Link to="/" className="brand-logo center">MEMOPAD</Link> <ul> <li><a onClick={this.toggleSearch}><i className="material-icons">search</i></a></li> </ul> <div className="right"> <ul> { this.props.isLoggedIn ? logoutButton : loginButton } </ul> </div> </div> </nav> <ReactCSSTransitionGroup transitionName="search" transitionEnterTimeout={300} transitionLeaveTimeout={300}> { /* IMPLEMENT: SHOW SEARCH WHEN SEARCH STATUS IS TRUE */} {this.state.search ? <Search onClose={this.toggleSearch} onSearch={this.props.onSearch} usernames={this.props.usernames}/> : undefined } </ReactCSSTransitionGroup> </div> ); } } Header.propTypes = { isLoggedIn: React.PropTypes.bool, onLogout: React.PropTypes.func, usernames: React.PropTypes.array }; Header.defaultProps = { isLoggedIn: false, onLogout: () => { console.error("logout function not defined");}, usernames: [] }; export default Header;
29.049383
127
0.494688