hexsha
stringlengths
40
40
size
int64
5
1.05M
ext
stringclasses
98 values
lang
stringclasses
21 values
max_stars_repo_path
stringlengths
3
945
max_stars_repo_name
stringlengths
4
118
max_stars_repo_head_hexsha
stringlengths
40
78
max_stars_repo_licenses
listlengths
1
10
max_stars_count
int64
1
368k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
3
945
max_issues_repo_name
stringlengths
4
118
max_issues_repo_head_hexsha
stringlengths
40
78
max_issues_repo_licenses
listlengths
1
10
max_issues_count
int64
1
134k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
3
945
max_forks_repo_name
stringlengths
4
135
max_forks_repo_head_hexsha
stringlengths
40
78
max_forks_repo_licenses
listlengths
1
10
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
5
1.05M
avg_line_length
float64
1
1.03M
max_line_length
int64
2
1.03M
alphanum_fraction
float64
0
1
ea858c9f026065f45fe1723db33e4e33754422f7
16,717
swift
Swift
ios/Classes/SwiftAuth0NativePlugin.swift
wmaikon/flutter_plugin_auth0_native
7e4c899e908f59d2344d1d0a2eff6b14d2d78f7a
[ "Apache-2.0" ]
null
null
null
ios/Classes/SwiftAuth0NativePlugin.swift
wmaikon/flutter_plugin_auth0_native
7e4c899e908f59d2344d1d0a2eff6b14d2d78f7a
[ "Apache-2.0" ]
null
null
null
ios/Classes/SwiftAuth0NativePlugin.swift
wmaikon/flutter_plugin_auth0_native
7e4c899e908f59d2344d1d0a2eff6b14d2d78f7a
[ "Apache-2.0" ]
null
null
null
import Auth0 import AuthenticationServices import Flutter import UIKit public class SwiftAuth0NativePlugin: NSObject, FlutterPlugin { private var credentialsEventSink: FlutterEventSink? = nil private var loggingEnabled = false private var credentialsManager: NotifyingCredentialsManager? = nil public static func register(with registrar: FlutterPluginRegistrar) { let channel = FlutterMethodChannel(name: "asia.ivity.flutter/auth0_native/methods", binaryMessenger: registrar.messenger()) let credentialsEventChannel = FlutterEventChannel(name: "asia.ivity.flutter/auth0_native/credentials", binaryMessenger: registrar.messenger()) let instance = SwiftAuth0NativePlugin() registrar.addMethodCallDelegate(instance, channel: channel) credentialsEventChannel.setStreamHandler(instance) } public func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) { switch call.method { case "initialize": handleInitialize(call, result) break case "login": handleLogin(call, result) break case "logout": handleLogout(call, result) break case "getCredentials": handleGetCredentials(result) break case "hasCredentials": handleHasCredentials(result) break case "passwordlessWithSMS": handlePasswordlessWithSMS(call, result) break case "loginWithPhoneNumber": handleLoginWithPhoneNumber(call, result) break case "passwordlessWithEmail": handlePasswordlessWithEmail(call, result) break case "loginWithEmail": handleLoginWithEmail(call, result) break case "signUpWithEmailAndPassword": handleSignUpWithEmailAndPassword(call, result) break case "signInWithApple": if #available(iOS 13.0, *) { handleSignInWithApple(call, result) } else { result(FlutterError(code: "unavailable", message: nil, details: nil)) } break default: result(FlutterMethodNotImplemented) break } } private func handleInitialize(_ call: FlutterMethodCall, _ result: @escaping FlutterResult) { guard let map: [String: Any] = call.arguments as? [String:Any] else { result(FlutterError(code: "invalid-params", message: nil, details: nil)) return } if let tmp = map["loggingEnabled"] as? Bool { self.loggingEnabled = tmp } self.credentialsManager = NotifyingCredentialsManager( authentication: Auth0.authentication(), listener: self ) result(nil) } private func handleLogin(_ call: FlutterMethodCall, _ result: @escaping FlutterResult) { guard let map: [String: Any] = call.arguments as? [String:Any] else { result(FlutterError(code: "invalid-params", message: nil, details: nil)) return } var webAuth = Auth0.webAuth().logging(enabled: loggingEnabled) if let audience = map["audience"] as? String { webAuth = webAuth.audience(audience) } if let connection = map["connection"] as? String { webAuth = webAuth.connection(connection) } if let scope = map["scope"] as? String { webAuth = webAuth.scope(scope) } if let parameters = map["parameters"] as? [String:String] { webAuth = webAuth.parameters(parameters) } webAuth.start { (auth0Result) in switch auth0Result { case .success(result: let c): self.credentialsManager?.store(credentials: c) result(mapCredentials(c)) break case .failure(error: let e): result(mapError(e)) break } } } private func handleLogout(_ call: FlutterMethodCall, _ result: @escaping FlutterResult) { guard let map: [String: Any] = call.arguments as? [String:Any] else { result(FlutterError(code: "invalid-params", message: nil, details: nil)) return } let localOnly = map["localOnly"] as? Bool ?? false if localOnly { self.credentialsManager?.clear() result(nil) return } var webAuth = Auth0.webAuth().logging(enabled: loggingEnabled) if let audience = map["audience"] as? String { webAuth = webAuth.audience(audience) } webAuth.clearSession(federated: true) { (successful) in self.credentialsManager?.clear() result(nil) } } private func handleGetCredentials(_ result: @escaping FlutterResult) { guard let manager = credentialsManager else { result(nil) return } manager.credentials(callback: { (error, credentials) in if let credentials = credentials { result(mapCredentials(credentials)) } else if let error = error { result(mapError(error)) } else { result(nil) } }) } private func handleHasCredentials(_ result: @escaping FlutterResult) { result(credentialsManager?.hasValid() ?? false) } private func handlePasswordlessWithSMS(_ call: FlutterMethodCall, _ result: @escaping FlutterResult) { guard let map: [String: Any] = call.arguments as? [String:Any] else { result(FlutterError(code: "invalid-params", message: nil, details: nil)) return } guard let phone = map["phone"] as? String, let passwordlessType = parsePasswordlessType(map["type"] as? String), let connection = map["connection"] as? String else { result(FlutterError(code: "invalid-params", message: nil, details: nil)) return } Auth0.authentication() .logging(enabled: self.loggingEnabled) .startPasswordless(phoneNumber: phone, type: passwordlessType, connection: connection) .start { (auth0Result) in switch auth0Result { case .success(result: _): result(nil) case .failure(error: let error): result(mapError(error)) } } } private func handleLoginWithPhoneNumber(_ call: FlutterMethodCall, _ result: @escaping FlutterResult) { guard let map: [String: Any] = call.arguments as? [String:Any] else { result(FlutterError(code: "invalid-params", message: nil, details: nil)) return } guard let phone = map["phone"] as? String, let code = map["code"] as? String else { result(FlutterError(code: "invalid-params", message: nil, details: nil)) return } let audience = map["audience"] as? String let scope = map["scope"] as? String let parameters = map["parameters"] as? [String:Any] ?? [:] Auth0.authentication() .logging(enabled: self.loggingEnabled) .login(phoneNumber: phone, code: code, audience: audience, scope: scope, parameters: parameters) .start { (auth0Result) in switch auth0Result { case .success(result: let credentials): self.credentialsManager?.store(credentials: credentials) result(mapCredentials(credentials)) case .failure(error: let error): result(mapError(error)) } } } private func handlePasswordlessWithEmail(_ call: FlutterMethodCall, _ result: @escaping FlutterResult) { guard let map: [String: Any] = call.arguments as? [String:Any] else { result(FlutterError(code: "invalid-params", message: nil, details: nil)) return } guard let email = map["email"] as? String, let passwordlessType = parsePasswordlessType(map["type"] as? String), let connection = map["connection"] as? String else { result(FlutterError(code: "invalid-params", message: nil, details: nil)) return } let parameters = map["parameters"] as? [String:Any] ?? [:] Auth0.authentication() .logging(enabled: self.loggingEnabled) .startPasswordless(email: email, type: passwordlessType, connection: connection, parameters: parameters) .start { (auth0Result) in switch auth0Result { case .success(result: _): result(nil) case .failure(error: let error): result(mapError(error)) } } } private func handleLoginWithEmail(_ call: FlutterMethodCall, _ result: @escaping FlutterResult) { guard let map: [String: Any] = call.arguments as? [String:Any] else { result(FlutterError(code: "invalid-params", message: nil, details: nil)) return } let email = map["email"] as! String; let code = map["code"] as? String; let password = map["password"] as? String; if (code == nil && password == nil) { result(FlutterError(code: "invalid-params", message: nil, details: nil)) return } let audience = map["audience"] as? String let scope = map["scope"] as? String let parameters = map["scope"] as? [String:Any] ?? [:] if(code != nil) { Auth0.authentication() .logging(enabled: self.loggingEnabled) .login(email: email, code: code!, audience: audience, scope: scope, parameters: parameters) .start { (auth0Result) in switch auth0Result { case .success(result: let credentials): self.credentialsManager?.store(credentials: credentials) result(mapCredentials(credentials)) case .failure(error: let error): result(mapError(error)) } } } else { Auth0.authentication() .logging(enabled: self.loggingEnabled) .login(usernameOrEmail: email, password: password!, realm: "Username-Password-Authentication", audience: audience, scope: scope, parameters: parameters) .start { (auth0Result) in switch auth0Result { case .success(result: let credentials): self.credentialsManager?.store(credentials: credentials) result(mapCredentials(credentials)) case .failure(error: let error): result(mapError(error)) } } } } private func handleSignUpWithEmailAndPassword(_ call: FlutterMethodCall, _ result: @escaping FlutterResult) { guard let map: [String: Any] = call.arguments as? [String:Any] else { result(FlutterError(code: "invalid-params", message: nil, details: nil)) return } let email = map["email"] as! String; let password = map["password"] as! String; // if (email == nil || password == nil) { // result(FlutterError(code: "invalid-params", message: nil, details: nil)) // return // } // let audience = map["audience"] as? String // let scope = map["scope"] as? String // let parameters = map["scope"] as? [String:Any] ?? [:] Auth0.authentication() .logging(enabled: self.loggingEnabled) .createUser(email: email, password: password, connection: "Username-Password-Authentication") .start { (auth0Result) in switch auth0Result { case .success(result: let databaseUser): self.handleLoginWithEmail(call, result) case .failure(error: let error): result(mapError(error)) } } } private var siwaCall: FlutterMethodCall? = nil private var siwaResult: FlutterResult? = nil @available(iOS 13.0, *) private func handleSignInWithApple(_ call: FlutterMethodCall, _ result: @escaping FlutterResult) { guard let _ : [String: Any] = call.arguments as? [String:Any] else { result(FlutterError(code: "invalid-params", message: nil, details: nil)) return } siwaCall = call siwaResult = result // Create the authorization request let request = ASAuthorizationAppleIDProvider().createRequest() // Set scopes request.requestedScopes = [.email, .fullName] // Setup a controller to display the authorization flow let controller = ASAuthorizationController(authorizationRequests: [request]) // Set delegates to handle the flow response. controller.delegate = self // controller.presentationContextProvider = self // Action controller.performRequests() } public func application(_ application: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool { return Auth0.resumeAuth(url, options: options) } } @available(iOS 13.0, *) extension SwiftAuth0NativePlugin : ASAuthorizationControllerDelegate { public func authorizationController(controller: ASAuthorizationController, didCompleteWithAuthorization authorization: ASAuthorization) { guard let call = siwaCall, let result = siwaResult else { // Nothing we can do. return } guard let map: [String: Any] = call.arguments as? [String:Any] else { result(FlutterError(code: "invalid-params", message: nil, details: nil)) return } guard let appleIDCredential = authorization.credential as? ASAuthorizationAppleIDCredential, let authorizationCode = appleIDCredential.authorizationCode, let authCode = String(data: authorizationCode, encoding: .utf8) else { result(FlutterError(code: "apple-login", message: "", details: "")) return } let audience = map["audience"] as? String let scope = map["scope"] as? String // Auth0 Token Exchange Auth0 .authentication() .login(appleAuthorizationCode: authCode, fullName: appleIDCredential.fullName, scope: scope, audience: audience) .start { result in switch result { case .success(let credentials): self.credentialsManager?.store(credentials: credentials) self.siwaResult?(mapCredentials(credentials)) case .failure(let error): self.siwaResult?(mapError(error)) } self.siwaResult = nil } } // Handle authorization failure public func authorizationController(controller: ASAuthorizationController, didCompleteWithError error: Error) { self.siwaResult?(mapError(error)) self.siwaResult = nil } } extension SwiftAuth0NativePlugin : FlutterStreamHandler { public func onListen(withArguments arguments: Any?, eventSink events: @escaping FlutterEventSink) -> FlutterError? { self.credentialsEventSink = events if let cm = self.credentialsManager { cm.credentials(withScope: nil) { (error, credentials) in events(mapCredentials(credentials)) } } return nil } public func onCancel(withArguments arguments: Any?) -> FlutterError? { self.credentialsEventSink = nil return nil } } extension SwiftAuth0NativePlugin : OnCredentialsChangedListener { func onCredentialsChanged(credentials: Credentials?) { self.credentialsEventSink?(mapCredentials(credentials)) } }
38.166667
168
0.573787
2f6440f681d9748d1c3cb4954563fe742fb863b8
445
cs
C#
EmitMapper/MappingConfiguration/MappingOperations/MappingOperationDelegates.cs
itdos/Dos.Common
a8447365390d94982a797bfc28852b19851a1147
[ "MIT" ]
48
2015-04-27T01:41:09.000Z
2021-03-29T04:25:26.000Z
EmitMapper/MappingConfiguration/MappingOperations/MappingOperationDelegates.cs
PuGuihong/Dos.Common
a8447365390d94982a797bfc28852b19851a1147
[ "MIT" ]
1
2018-03-09T04:16:04.000Z
2018-03-09T04:16:04.000Z
EmitMapper/MappingConfiguration/MappingOperations/MappingOperationDelegates.cs
PuGuihong/Dos.Common
a8447365390d94982a797bfc28852b19851a1147
[ "MIT" ]
45
2015-09-29T14:28:45.000Z
2021-12-06T01:34:25.000Z
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace EmitMapper.MappingConfiguration.MappingOperations { public delegate TResult NullSubstitutor<TResult>(object state); public delegate TResult TargetConstructor<TResult>(); public delegate TResult ValueConverter<TValue, TResult>(TValue value, object state); public delegate TValue ValuesPostProcessor<TValue>(TValue value, object state); }
34.230769
85
0.813483
4a64c7b718b60a0923bcbdfa9506bbb0662e211d
6,398
cs
C#
Assets/Asset Packs/Devion Games/Inventory System/Scripts/Editor/Inspectors/Settings/SavingLoadingInspector.cs
jlarnett/WinstonLakeV2
f4cbd8b5f627f1674d70ce0a23e87264f3297979
[ "MIT" ]
null
null
null
Assets/Asset Packs/Devion Games/Inventory System/Scripts/Editor/Inspectors/Settings/SavingLoadingInspector.cs
jlarnett/WinstonLakeV2
f4cbd8b5f627f1674d70ce0a23e87264f3297979
[ "MIT" ]
null
null
null
Assets/Asset Packs/Devion Games/Inventory System/Scripts/Editor/Inspectors/Settings/SavingLoadingInspector.cs
jlarnett/WinstonLakeV2
f4cbd8b5f627f1674d70ce0a23e87264f3297979
[ "MIT" ]
null
null
null
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEditor; using UnityEditor.AnimatedValues; using UnityEngine.Events; using System.Linq; using System; namespace DevionGames.InventorySystem.Configuration { [CustomEditor(typeof(SavingLoading))] public class SavingLoadingInspector : Editor { private SerializedProperty m_Script; private SerializedProperty m_AutoSave; private AnimBool m_ShowSave; private SerializedProperty m_Provider; private AnimBool m_ShowMySQL; private SerializedProperty m_SavingKey; private SerializedProperty m_SavingRate; private SerializedProperty m_ServerAdress; private SerializedProperty m_SaveScript; private SerializedProperty m_LoadScript; protected virtual void OnEnable() { this.m_Script = serializedObject.FindProperty("m_Script"); this.m_AutoSave = serializedObject.FindProperty("autoSave"); this.m_ShowSave = new AnimBool(this.m_AutoSave.boolValue); this.m_ShowSave.valueChanged.AddListener(new UnityAction(Repaint)); this.m_Provider = serializedObject.FindProperty("provider"); this.m_ShowMySQL = new AnimBool(this.m_Provider.enumValueIndex == 1); this.m_ShowMySQL.valueChanged.AddListener(new UnityAction(Repaint)); this.m_SavingKey = serializedObject.FindProperty("savingKey"); this.m_SavingRate = serializedObject.FindProperty("savingRate"); this.m_ServerAdress = serializedObject.FindProperty("serverAdress"); this.m_SaveScript = serializedObject.FindProperty("saveScript"); this.m_LoadScript = serializedObject.FindProperty("loadScript"); } public override void OnInspectorGUI() { EditorGUI.BeginDisabledGroup(true); EditorGUILayout.PropertyField(this.m_Script); EditorGUI.EndDisabledGroup(); serializedObject.Update(); EditorGUILayout.PropertyField(this.m_AutoSave); this.m_ShowSave.target = this.m_AutoSave.boolValue; if (EditorGUILayout.BeginFadeGroup(this.m_ShowSave.faded)) { EditorGUI.indentLevel = EditorGUI.indentLevel + 1; EditorGUILayout.PropertyField(this.m_SavingKey); EditorGUILayout.PropertyField(this.m_SavingRate); EditorGUILayout.PropertyField(m_Provider); this.m_ShowMySQL.target = m_Provider.enumValueIndex == 1; if (EditorGUILayout.BeginFadeGroup(this.m_ShowMySQL.faded)) { EditorGUILayout.PropertyField(this.m_ServerAdress); EditorGUILayout.PropertyField(this.m_SaveScript); EditorGUILayout.PropertyField(this.m_LoadScript); } EditorGUILayout.EndFadeGroup(); EditorGUI.indentLevel = EditorGUI.indentLevel - 1; } EditorGUILayout.EndFadeGroup(); GUILayout.Space(2f); EditorTools.Seperator(); string data = PlayerPrefs.GetString("SavedKeys"); if (!string.IsNullOrEmpty(data)) { string[] keys = data.Split(';').Distinct().ToArray(); Array.Reverse(keys); ArrayUtility.Remove<string>(ref keys, ""); ArrayUtility.Remove<string>(ref keys, string.Empty); bool state = EditorPrefs.GetBool("SavedData", false); bool foldout = EditorGUILayout.Foldout(state, "Saved Data " + keys.Length.ToString(), true); if (foldout != state) { EditorPrefs.SetBool("SavedData", foldout); } if (foldout) { EditorGUI.indentLevel += 1; if (keys.Length == 0) { GUILayout.BeginHorizontal(); GUILayout.Space(16f); GUILayout.BeginVertical(); GUILayout.Label("No data saved on this device!"); GUILayout.EndVertical(); GUILayout.EndHorizontal(); } for (int i = 0; i < keys.Length; i++) { string key = keys[i]; if (!string.IsNullOrEmpty(key)) { state = EditorPrefs.GetBool(key, false); GUILayout.BeginHorizontal(); foldout = EditorGUILayout.Foldout(state, key, true); Rect rect = GUILayoutUtility.GetLastRect(); if (Event.current.type == EventType.MouseDown && Event.current.button == 1 && rect.Contains(Event.current.mousePosition)) { GenericMenu menu = new GenericMenu(); menu.AddItem(new GUIContent("Delete"), false, delegate () { PlayerPrefs.DeleteKey(key); PlayerPrefs.SetString("SavedKeys", data.Replace(key, "")); }); menu.ShowAsContext(); } GUILayout.EndHorizontal(); if (foldout != state) { EditorPrefs.SetBool(key, foldout); } if (foldout) { GUILayout.BeginHorizontal(); GUILayout.Space(16f * 2f); GUILayout.BeginVertical(); GUILayout.Label(PlayerPrefs.GetString(key), EditorStyles.wordWrappedLabel); GUILayout.EndVertical(); GUILayout.EndHorizontal(); } } } EditorGUI.indentLevel -= 1; } } serializedObject.ApplyModifiedProperties(); } } }
42.370861
149
0.526883
96b8a5da8739ead9429f2db1c6fe6073638d688b
399
cc
C++
vasya_the_hipster.cc
maximilianbrine/github-slideshow
76e4d6a7e57da61f1ddca4d8aa8bc5d2fd78bea1
[ "MIT" ]
null
null
null
vasya_the_hipster.cc
maximilianbrine/github-slideshow
76e4d6a7e57da61f1ddca4d8aa8bc5d2fd78bea1
[ "MIT" ]
3
2021-01-04T18:33:39.000Z
2021-01-04T19:37:21.000Z
vasya_the_hipster.cc
maximilianbrine/github-slideshow
76e4d6a7e57da61f1ddca4d8aa8bc5d2fd78bea1
[ "MIT" ]
null
null
null
#include <iostream> int main() { int a, b, r; std::cin >> a >> b; if (a == b) { std::cout << a << " 0" << std::endl; return 0; } else if ( a > b ) { std::cout << b << " "; } else if ( a < b ) { std::cout << a << " "; } r = abs(a - b); if (r > 1) { std::cout << r/2; } else { std::cout << 0; } return 0; }
18.136364
44
0.333333
07327a027d32649c1d081169479856c9ea5e790d
131
kt
Kotlin
compiler/testData/cli/jvm/modulesWithDependencyCycleA.kt
Mu-L/kotlin
5c3ce66e9979d2b3592d06961e181fa27fa88431
[ "ECL-2.0", "Apache-2.0" ]
151
2019-11-06T03:32:39.000Z
2022-03-25T15:06:58.000Z
compiler/testData/cli/jvm/modulesWithDependencyCycleA.kt
Mu-L/kotlin
5c3ce66e9979d2b3592d06961e181fa27fa88431
[ "ECL-2.0", "Apache-2.0" ]
3
2020-07-27T00:44:27.000Z
2021-12-30T20:21:23.000Z
compiler/testData/cli/jvm/modulesWithDependencyCycleA.kt
Mu-L/kotlin
5c3ce66e9979d2b3592d06961e181fa27fa88431
[ "ECL-2.0", "Apache-2.0" ]
69
2019-11-18T10:25:35.000Z
2021-12-27T14:15:47.000Z
package a import b.* class A class X(val y: Y? = null) class Z : Y() fun topLevelA1() { topLevelB() } fun topLevelA2() {}
8.733333
25
0.59542
9d242682d1bbdf5bb6e575f53bc24056abaf3a11
3,240
asm
Assembly
externals/mpir-3.0.0/mpn/x86_64w/k8/mul_2.asm
JaminChan/eos_win
c03e57151cfe152d0d3120abb13226f4df74f37e
[ "MIT" ]
12
2021-09-29T14:50:06.000Z
2022-03-31T15:01:21.000Z
externals/mpir-3.0.0/mpn/x86_64w/k8/mul_2.asm
JaminChan/eos_win
c03e57151cfe152d0d3120abb13226f4df74f37e
[ "MIT" ]
15
2021-12-24T22:53:49.000Z
2021-12-25T10:03:13.000Z
LibSource/mpir/mpn/x86_64w/k8/mul_2.asm
ekzyis/CrypTool-2
1af234b4f74486fbfeb3b3c49228cc36533a8c89
[ "Apache-2.0" ]
10
2021-10-17T19:46:51.000Z
2022-03-18T02:57:57.000Z
; PROLOGUE(mpn_mul_2) ; X86_64 mpn_mul_2 ; ; Copyright 2008 Jason Moxham ; ; Windows Conversion Copyright 2008 Brian Gladman ; ; This file is part of the MPIR Library. ; The MPIR Library is free software; you can redistribute it and/or modify ; it under the terms of the GNU Lesser General Public License as published ; by the Free Software Foundation; either version 2.1 of the License, or (at ; your option) any later version. ; The MPIR 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 the MPIR Library; see the file COPYING.LIB. If not, write ; to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, ; Boston, MA 02110-1301, USA. ; ; mp_limb_t mpn_mul_2(mp_ptr, mp_ptr, mp_size_t, mp_limb_t) ; rax rdi rsi rdx rcx ; rax rcx rdx r8 r9 %include "yasm_mac.inc" %define reg_save_list rsi, rdi, rbx BITS 64 FRAME_PROC mpn_mul_2, 0, reg_save_list mov rax, r8 mov r8, [r9] lea rsi, [rdx+rax*8-24] lea rdi, [rcx+rax*8-24] mov rcx, [r9+8] mov rbx, 3 sub rbx, rax mov r10, 0 mov rax, [rsi+rbx*8] mul r8 mov r11, rax mov r9, rdx cmp rbx, 0 jge .2 xalign 16 .1: mov rax, [rsi+rbx*8] mov [rdi+rbx*8], r11 mul rcx add r9, rax adc r10, rdx mov r11, 0 mov rax, [rsi+rbx*8+8] mul r8 add r9, rax mov rax, [rsi+rbx*8+8] adc r10, rdx adc r11, 0 mul rcx add r10, rax mov [rdi+rbx*8+8], r9 adc r11, rdx mov rax, [rsi+rbx*8+16] mul r8 mov r9, 0 add r10, rax mov rax, [rsi+rbx*8+16] adc r11, rdx mov [rdi+rbx*8+16], r10 mov r10, 0 adc r9, 0 mul rcx add r11, rax mov rax, [rsi+rbx*8+24] adc r9, rdx mul r8 add r11, rax adc r9, rdx adc r10, 0 add rbx, 3 jnc .1 .2: mov rax, [rsi+rbx*8] mov [rdi+rbx*8], r11 mul rcx add r9, rax adc r10, rdx cmp rbx, 1 ja .5 je .4 .3: mov r11, 0 mov rax, [rsi+rbx*8+8] mul r8 add r9, rax mov rax, [rsi+rbx*8+8] adc r10, rdx adc r11, 0 mul rcx add r10, rax mov [rdi+rbx*8+8], r9 adc r11, rdx mov rax, [rsi+rbx*8+16] mul r8 mov r9, 0 add r10, rax mov rax, [rsi+rbx*8+16] adc r11, rdx mov [rdi+rbx*8+16], r10 adc r9, 0 mul rcx add r11, rax adc r9, rdx mov [rdi+rbx*8+24], r11 mov rax, r9 EXIT_PROC reg_save_list xalign 16 .4: mov r11, 0 mov rax, [rsi+rbx*8+8] mul r8 add r9, rax mov rax, [rsi+rbx*8+8] adc r10, rdx adc r11, 0 mul rcx add r10, rax mov [rdi+rbx*8+8], r9 adc r11, rdx mov [rdi+rbx*8+16], r10 mov rax, r11 EXIT_PROC reg_save_list xalign 16 .5: mov [rdi+rbx*8+8], r9 mov rax, r10 .6: END_PROC reg_save_list end
22.816901
77
0.571605
80d6be005cc41941e36fa41e5c4aa5cc8654d05f
3,094
cpp
C++
clang-tools-extra/clangd/FSProvider.cpp
medismailben/llvm-project
e334a839032fe500c3bba22bf976ab7af13ce1c1
[ "Apache-2.0" ]
34
2020-01-31T17:50:00.000Z
2022-02-16T20:19:29.000Z
clang-tools-extra/clangd/FSProvider.cpp
medismailben/llvm-project
e334a839032fe500c3bba22bf976ab7af13ce1c1
[ "Apache-2.0" ]
14
2020-02-03T23:39:51.000Z
2021-07-20T16:24:25.000Z
clang-tools-extra/clangd/FSProvider.cpp
medismailben/llvm-project
e334a839032fe500c3bba22bf976ab7af13ce1c1
[ "Apache-2.0" ]
6
2021-02-08T16:57:07.000Z
2022-01-13T11:32:34.000Z
//===--- FSProvider.cpp - VFS provider for ClangdServer -------------------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// #include "FSProvider.h" #include "llvm/ADT/STLExtras.h" #include "llvm/ADT/SmallString.h" #include "llvm/ADT/StringRef.h" #include "llvm/Support/Path.h" #include "llvm/Support/VirtualFileSystem.h" #include <memory> namespace clang { namespace clangd { namespace { /// Always opens files in the underlying filesystem as "volatile", meaning they /// won't be memory-mapped. Memory-mapping isn't desirable for clangd: /// - edits to the underlying files change contents MemoryBuffers owned by // SourceManager, breaking its invariants and leading to crashes /// - it locks files on windows, preventing edits class VolatileFileSystem : public llvm::vfs::ProxyFileSystem { public: explicit VolatileFileSystem(llvm::IntrusiveRefCntPtr<FileSystem> FS) : ProxyFileSystem(std::move(FS)) {} llvm::ErrorOr<std::unique_ptr<llvm::vfs::File>> openFileForRead(const llvm::Twine &InPath) override { llvm::SmallString<128> Path; InPath.toVector(Path); auto File = getUnderlyingFS().openFileForRead(Path); if (!File) return File; // Try to guess preamble files, they can be memory-mapped even on Windows as // clangd has exclusive access to those and nothing else should touch them. llvm::StringRef FileName = llvm::sys::path::filename(Path); if (FileName.startswith("preamble-") && FileName.endswith(".pch")) return File; return std::unique_ptr<VolatileFile>(new VolatileFile(std::move(*File))); } private: class VolatileFile : public llvm::vfs::File { public: VolatileFile(std::unique_ptr<llvm::vfs::File> Wrapped) : Wrapped(std::move(Wrapped)) { assert(this->Wrapped); } virtual llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> getBuffer(const llvm::Twine &Name, int64_t FileSize, bool RequiresNullTerminator, bool /*IsVolatile*/) override { return Wrapped->getBuffer(Name, FileSize, RequiresNullTerminator, /*IsVolatile=*/true); } llvm::ErrorOr<llvm::vfs::Status> status() override { return Wrapped->status(); } llvm::ErrorOr<std::string> getName() override { return Wrapped->getName(); } std::error_code close() override { return Wrapped->close(); } private: std::unique_ptr<File> Wrapped; }; }; } // namespace llvm::IntrusiveRefCntPtr<llvm::vfs::FileSystem> clang::clangd::RealFileSystemProvider::getFileSystem() const { // Avoid using memory-mapped files. // FIXME: Try to use a similar approach in Sema instead of relying on // propagation of the 'isVolatile' flag through all layers. return new VolatileFileSystem( llvm::vfs::createPhysicalFileSystem().release()); } } // namespace clangd } // namespace clang
36.833333
80
0.676471
4ba85a745ef18cb8d0ceb8b5c5c38d1f5a624d24
590
go
Go
scaffold/url_file_loader.go
PM-Connect/pitch
94f0b395e604245defca22be45c794dab26b1e7f
[ "MIT" ]
null
null
null
scaffold/url_file_loader.go
PM-Connect/pitch
94f0b395e604245defca22be45c794dab26b1e7f
[ "MIT" ]
null
null
null
scaffold/url_file_loader.go
PM-Connect/pitch
94f0b395e604245defca22be45c794dab26b1e7f
[ "MIT" ]
1
2021-02-05T14:47:41.000Z
2021-02-05T14:47:41.000Z
package scaffold import ( "io/ioutil" "net/http" "time" yaml "gopkg.in/yaml.v2" ) var urlClient = &http.Client{ Timeout: time.Second * 10, } // URLFileLoader is responsible for returning Scaffolds from yaml files at a remote URL. type URLFileLoader struct { } // Get returns a Scaffold from a given yaml file. func (l *URLFileLoader) Get(source string) (scaffold Scaffold, err error) { response, err := urlClient.Get(source) if err != nil { return } buf, err := ioutil.ReadAll(response.Body) if err != nil { return } err = yaml.Unmarshal(buf, &scaffold) return }
15.945946
88
0.691525
83ef4ca6a4e401bfa08a5d76fa766896b7962f30
1,859
java
Java
zh-common/src/main/java/com/zhenghao/admin/common/config/JWTConfig.java
zhaozhenghao1993/zh-admin
3b49857cd70a01e173eae836f23db2f8d61fa5d4
[ "MIT" ]
6
2019-04-23T00:58:06.000Z
2021-12-18T15:24:30.000Z
zh-common/src/main/java/com/zhenghao/admin/common/config/JWTConfig.java
zhaozhenghao1993/zh-admin
3b49857cd70a01e173eae836f23db2f8d61fa5d4
[ "MIT" ]
28
2019-08-05T11:27:02.000Z
2021-12-21T17:11:06.000Z
zh-common/src/main/java/com/zhenghao/admin/common/config/JWTConfig.java
zhaozhenghao1993/zh-admin
3b49857cd70a01e173eae836f23db2f8d61fa5d4
[ "MIT" ]
3
2020-08-07T00:51:35.000Z
2021-09-03T17:39:42.000Z
package com.zhenghao.admin.common.config; import com.zhenghao.admin.common.jwt.JWTTokenProcessor; import com.zhenghao.admin.common.jwt.RsaKeyHelper; import com.zhenghao.admin.common.jwt.RsaKeyManager; import com.zhenghao.admin.common.properties.JWTProperties; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import java.io.IOException; import java.security.NoSuchAlgorithmException; import java.security.spec.InvalidKeySpecException; /** * 🙃 * 🙃 JWT 配置类 * 🙃 * * @author:zhaozhenghao * @Email :736720794@qq.com * @date :2019/01/18 23:51 * KeyConfig.java */ /*@Configuration @EnableConfigurationProperties(JWTProperties.class)*/ public class JWTConfig { private final JWTProperties jwtProperties; public JWTConfig(JWTProperties jwtProperties) { this.jwtProperties = jwtProperties; } /** * RSA 公钥密钥配置 * * @return * @throws NoSuchAlgorithmException * @throws IOException * @throws InvalidKeySpecException */ @Bean public RsaKeyManager rsaKeyManager() throws NoSuchAlgorithmException, IOException, InvalidKeySpecException { RsaKeyHelper rsaKeyHelper = new RsaKeyHelper(); RsaKeyManager rsaKeyManager = new RsaKeyManager(); rsaKeyManager.setPublicKey(rsaKeyHelper.loadPublicKey(jwtProperties.getPublicKeyPath())); rsaKeyManager.setPrivateKey(rsaKeyHelper.loadPrivateKey(jwtProperties.getPrivateKeyPath())); return rsaKeyManager; } /** * 注入 JWT TOKEN 处理器 * @param rsaKeyManager * @return */ @Bean public JWTTokenProcessor jwtTokenProcessor(RsaKeyManager rsaKeyManager) { return new JWTTokenProcessor(jwtProperties.getExpire(), rsaKeyManager); } }
29.507937
112
0.745024
682a82e3b732e0028652c08e51e262461e95c383
4,136
html
HTML
pages/ejercicio1.html
chrisWO92/Ejercicios_Formularios
9769be30ff09de318aed4c86d885a6820256906b
[ "MIT" ]
null
null
null
pages/ejercicio1.html
chrisWO92/Ejercicios_Formularios
9769be30ff09de318aed4c86d885a6820256906b
[ "MIT" ]
null
null
null
pages/ejercicio1.html
chrisWO92/Ejercicios_Formularios
9769be30ff09de318aed4c86d885a6820256906b
[ "MIT" ]
null
null
null
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <script src="https://kit.fontawesome.com/c4657e955b.js" crossorigin="anonymous"></script> <link rel="stylesheet" href="../css/style.css"> <link rel="preconnect" href="https://fonts.googleapis.com"> <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin> <link href="https://fonts.googleapis.com/css2?family=Yaldevi:wght@500&display=swap" rel="stylesheet"> <title>Ejercicio 1</title> </head> <body> <div class="container"> <header> <i class="fas fa-ad"></i> <h2>Ejercicio Formulario 1</h2> <nav> <ul class="menu"> <li><a href="../index.html">Home</a></li> <li><a href="https://oscarmaestre.github.io/lenguajes_marcas/ejercicios/formularios/anexo_formularios.html#formulario-1" target="__blank">Ejercicio_1</a></li> </ul> </nav> </header> <main> <form action="#" method="POST" target="__blank"> <fieldset> <legend>Rellenar</legend> <div class="opcion_radio"> <input type="radio" id="inglesID" name="ingles" value="Inglés"> <label for="inglesID">Inglés</label> </div> <div class="opcion_radio"> <input type="radio" id="alemanID" name="aleman" value="Alemán"> <label for="alemanID">Alemán</label> </div> <div class="opcion_radio"> <input type="radio" id="francesID" name="frances" value="Francés"> <label for="francesID">Francés</label> </div> <select name="conector" id="conectorID"> <option value="USB">USB</option> <option value="paralelo">Paralelo</option> <option value="PS2">PS2</option> </select> <div class="input_text"> <label for="nombreID">Nombre</label> <input type="text" id="nombreID" name="nombre"> </div> <div class="input_text"> <label for="apellidoID">Apellido</label> <input type="text" id="apellidoID" name="apellido"> </div> </fieldset> <fieldset> <legend>Indique sus preferencias por favor</legend> <select name="sexo" id="sexoID" multiple="multiple"> <option value="hombre">Hombre</option> <option value="mujer">Mujer</option> </select> <div class="opcion_checkbox"> <input type="checkbox" name="sexohombrename" value="sexohombre"> <label for="sexohombrename">Hombre</label> </div> <div class="opcion_checkbox"> <input type="checkbox" name="sexomujername" value="sexohmujer"> <label for="sexomujername">Mujer</label> </div> <div class="opcion_checkbox"> <label for="fecha">Eliga la fecha</label> <input type="date" id="fechaID" name="fecha"> </div> </fieldset> </form> </main> <footer> <ul class="menu"> <li><a href="../index.html">Home</a></li> <li><a href="https://oscarmaestre.github.io/lenguajes_marcas/ejercicios/formularios/anexo_formularios.html#formulario-1" target="__blank">Ejercicio_1</a></li> </ul> </footer> </div> </body> </html>
38.296296
140
0.477756
594969b27db974436b583785bf6ac9ece6ab9514
491
hh
C++
src/gltf/Accessor.hh
CarpeNecopinum/ReFAKS
b98e392ed41e29718fcaacbcc60cb6648a1149b2
[ "MIT" ]
null
null
null
src/gltf/Accessor.hh
CarpeNecopinum/ReFAKS
b98e392ed41e29718fcaacbcc60cb6648a1149b2
[ "MIT" ]
null
null
null
src/gltf/Accessor.hh
CarpeNecopinum/ReFAKS
b98e392ed41e29718fcaacbcc60cb6648a1149b2
[ "MIT" ]
null
null
null
#pragma once #include <cstdlib> #include <vector> #include <string> namespace gltf { struct Accessor { enum class ComponentType : uint { BYTE = 5120, UNSIGNED_BYTE = 5121, SHORT = 5122, UNSIGNED_SHORT = 5123, UNSIGNED_INT = 5124, FLOAT = 5126 }; size_t bufferView; size_t byteOffset; ComponentType componentType; size_t count; std::vector<double> max; std::vector<double> min; std::string type; }; }
16.931034
37
0.606925
6933a35de20c004593d18a9e3b03509c731b7f8d
1,305
sql
SQL
modules/boonex/plyr/install/sql/enable.sql
flexsocialbox/una
4502c7f7c0fc83313c032cec58242b32cbb3a8cd
[ "MIT" ]
173
2016-11-26T22:53:24.000Z
2022-03-16T12:49:07.000Z
modules/boonex/plyr/install/sql/enable.sql
flexsocialbox/una
4502c7f7c0fc83313c032cec58242b32cbb3a8cd
[ "MIT" ]
3,273
2016-09-20T05:40:15.000Z
2022-03-31T08:50:46.000Z
modules/boonex/plyr/install/sql/enable.sql
flexsocialbox/una
4502c7f7c0fc83313c032cec58242b32cbb3a8cd
[ "MIT" ]
127
2016-09-29T20:56:14.000Z
2022-03-19T01:24:41.000Z
-- Settings SET @iTypeOrder = (SELECT MAX(`order`) FROM `sys_options_types` WHERE `group` = 'modules'); INSERT INTO `sys_options_types` (`group`, `name`, `caption`, `icon`, `order`) VALUES ('modules', 'bx_plyr', '_bx_plyr_adm_stg_cpt_type', 'bx_plyr@modules/boonex/plyr/|std-icon.svg', IF(NOT ISNULL(@iTypeOrder), @iTypeOrder + 1, 1)); SET @iTypeId = LAST_INSERT_ID(); INSERT INTO `sys_options_categories` (`type_id`, `name`, `caption`, `order` ) VALUES (@iTypeId, 'bx_plyr_general', '_bx_plyr_adm_stg_cpt_category_general', 1); SET @iCategId = LAST_INSERT_ID(); INSERT INTO `sys_options` (`name`, `value`, `category_id`, `caption`, `type`, `extra`, `check`, `check_error`, `order`) VALUES ('bx_plyr_option_controls', 'play-large,play,progress,current-time,mute,volume,captions,settings,pip,airplay,fullscreen', @iCategId, '_bx_plyr_option_controls', 'text', '', '', '', 10), ('bx_plyr_option_settings', 'captions,quality,speed,loop', @iCategId, '_bx_plyr_option_settings', 'text', '', '', '', 20); -- Editor INSERT INTO `sys_objects_player` (`object`, `title`, `skin`, `override_class_name`, `override_class_file`) VALUES ('bx_plyr', 'Plyr', '', 'BxPlyrPlayer', 'modules/boonex/plyr/classes/BxPlyrPlayer.php'); UPDATE `sys_options` SET `value` = 'bx_plyr' WHERE `name` = 'sys_player_default';
54.375
185
0.711877
2f028afe58a5fc36347ed0866be9522cb185ae9c
4,187
java
Java
pdfbox/src/main/java/org/apache/pdfbox/pdmodel/graphics/pattern/tiling/ColoredTilingContext.java
jmkgreen/pdfbox
a9c2fa4ee2b594e13100e75e5506897a145d6158
[ "Apache-2.0" ]
null
null
null
pdfbox/src/main/java/org/apache/pdfbox/pdmodel/graphics/pattern/tiling/ColoredTilingContext.java
jmkgreen/pdfbox
a9c2fa4ee2b594e13100e75e5506897a145d6158
[ "Apache-2.0" ]
null
null
null
pdfbox/src/main/java/org/apache/pdfbox/pdmodel/graphics/pattern/tiling/ColoredTilingContext.java
jmkgreen/pdfbox
a9c2fa4ee2b594e13100e75e5506897a145d6158
[ "Apache-2.0" ]
1
2021-09-17T05:44:50.000Z
2021-09-17T05:44:50.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.apache.pdfbox.pdmodel.graphics.pattern.tiling; import java.awt.PaintContext; import java.awt.color.ColorSpace; import java.awt.image.ColorModel; import java.awt.image.Raster; import java.awt.image.WritableRaster; import java.util.Arrays; import org.apache.pdfbox.pdmodel.common.PDRectangle; /** * This class represents the PaintContext of an axial shading. * */ public class ColoredTilingContext implements PaintContext { private ColorModel outputColorModel; private Raster tilingImage; private int xstep; private int ystep; private int lowerLeftX; private int lowerLeftY; /** * Constructor creates an instance to be used for fill operations. * * @param cm the colormodel to be used * @param image the tiling image * @param xStep horizontal spacing between pattern cells * @param yStep vertical spacing between pattern cells * @param bBox bounding box of the tiling image * */ public ColoredTilingContext(ColorModel cm, Raster image, int xStep, int yStep, PDRectangle bBox) { outputColorModel = cm; tilingImage = image; xstep = Math.abs(xStep); ystep = Math.abs(yStep); lowerLeftX = (int) bBox.getLowerLeftX(); lowerLeftY = (int) bBox.getLowerLeftY(); } /** * {@inheritDoc} */ public void dispose() { outputColorModel = null; tilingImage = null; } /** * {@inheritDoc} */ public ColorModel getColorModel() { return outputColorModel; } /** * {@inheritDoc} */ public Raster getRaster(int x, int y, int w, int h) { // get underlying colorspace ColorSpace cs = getColorModel().getColorSpace(); // number of color components including alpha channel int numComponents = cs.getNumComponents() + 1; // all the data, plus alpha channel int[] imgData = new int[w * h * (numComponents)]; // array holding the processed pixels int[] pixel = new int[numComponents]; // for each device coordinate for (int j = 0; j < h; j++) { for (int i = 0; i < w; i++) { // figure out what pixel we are at relative to the image int xloc = (x + i) - lowerLeftX; int yloc = (y + j) - lowerLeftY; xloc %= xstep; yloc %= ystep; if (xloc < 0) { xloc = xstep + xloc; } if (yloc < 0) { yloc = ystep + yloc; } // check if we are inside the image if (xloc < tilingImage.getWidth() && yloc < tilingImage.getHeight()) { tilingImage.getPixel(xloc, yloc, pixel); } else { Arrays.fill(pixel, 0); } int base = (j * w + i) * numComponents; for (int c = 0; c < numComponents; c++) { imgData[base + c] = pixel[c]; } } } WritableRaster raster = getColorModel().createCompatibleWritableRaster(w, h); raster.setPixels(0, 0, w, h, imgData); return raster; } }
30.562044
100
0.580368
7f2a720a52639b9e33f1025d36e570f7bd214b5c
13,333
rs
Rust
identity-account/src/storage/stronghold.rs
Critical94/identity.rs
e5a5653ec6823d210adee9e2ad1827c0815af9f5
[ "Apache-2.0" ]
226
2020-08-24T08:18:35.000Z
2022-03-30T20:28:05.000Z
identity-account/src/storage/stronghold.rs
Critical94/identity.rs
e5a5653ec6823d210adee9e2ad1827c0815af9f5
[ "Apache-2.0" ]
333
2020-09-01T03:25:39.000Z
2022-03-31T15:20:21.000Z
identity-account/src/storage/stronghold.rs
Critical94/identity.rs
e5a5653ec6823d210adee9e2ad1827c0815af9f5
[ "Apache-2.0" ]
57
2020-11-06T12:11:09.000Z
2022-03-10T10:43:52.000Z
// Copyright 2020-2021 IOTA Stiftung // SPDX-License-Identifier: Apache-2.0 use core::ops::RangeFrom; use crypto::keys::slip10::Chain; use futures::future; use futures::stream; use futures::stream::BoxStream; use futures::StreamExt; use futures::TryStreamExt; use hashbrown::HashSet; use identity_core::convert::FromJson; use identity_core::convert::ToJson; use identity_core::crypto::PrivateKey; use identity_core::crypto::PublicKey; use identity_did::verification::MethodType; use iota_stronghold::Location; use iota_stronghold::SLIP10DeriveInput; use std::convert::TryFrom; use std::io; use std::path::Path; use std::sync::Arc; use crate::error::Error; use crate::error::Result; use crate::events::Commit; use crate::events::Event; use crate::events::EventData; use crate::identity::IdentityId; use crate::identity::IdentityIndex; use crate::identity::IdentitySnapshot; use crate::storage::Storage; use crate::stronghold::default_hint; use crate::stronghold::Snapshot; use crate::stronghold::Store; use crate::stronghold::Vault; use crate::types::Generation; use crate::types::KeyLocation; use crate::types::Signature; use crate::utils::derive_encryption_key; use crate::utils::EncryptionKey; // name of the metadata store const META: &str = "$meta"; // event concurrency limit const ECL: usize = 8; // ============================================================================= // ============================================================================= #[derive(Debug)] pub struct Stronghold { snapshot: Arc<Snapshot>, } impl Stronghold { pub async fn new<'a, T, U>(snapshot: &T, password: U) -> Result<Self> where T: AsRef<Path> + ?Sized, U: Into<Option<&'a str>>, { let snapshot: Snapshot = Snapshot::new(snapshot); if let Some(password) = password.into() { snapshot.load(derive_encryption_key(password)).await?; } Ok(Self { snapshot: Arc::new(snapshot), }) } fn store(&self, name: &str) -> Store<'_> { self.snapshot.store(name, &[]) } fn vault(&self, id: IdentityId) -> Vault<'_> { self.snapshot.vault(&fmt_id(id), &[]) } } #[async_trait::async_trait] impl Storage for Stronghold { async fn set_password(&self, password: EncryptionKey) -> Result<()> { self.snapshot.set_password(password).await } async fn flush_changes(&self) -> Result<()> { self.snapshot.save().await } async fn key_new(&self, id: IdentityId, location: &KeyLocation) -> Result<PublicKey> { let vault: Vault<'_> = self.vault(id); let public: PublicKey = match location.method() { MethodType::Ed25519VerificationKey2018 => generate_ed25519(&vault, location).await?, MethodType::MerkleKeyCollection2021 => todo!("[Stronghold::key_new] Handle MerkleKeyCollection2021"), }; Ok(public) } async fn key_insert(&self, id: IdentityId, location: &KeyLocation, private_key: PrivateKey) -> Result<PublicKey> { let vault = self.vault(id); vault .insert(location_skey(location), private_key.as_ref(), default_hint(), &[]) .await?; match location.method() { MethodType::Ed25519VerificationKey2018 => retrieve_ed25519(&vault, location).await, MethodType::MerkleKeyCollection2021 => todo!("[Stronghold::key_insert] Handle MerkleKeyCollection2021"), } } async fn key_get(&self, id: IdentityId, location: &KeyLocation) -> Result<PublicKey> { let vault: Vault<'_> = self.vault(id); match location.method() { MethodType::Ed25519VerificationKey2018 => retrieve_ed25519(&vault, location).await, MethodType::MerkleKeyCollection2021 => todo!("[Stronghold::key_get] Handle MerkleKeyCollection2021"), } } async fn key_del(&self, id: IdentityId, location: &KeyLocation) -> Result<()> { let vault: Vault<'_> = self.vault(id); match location.method() { MethodType::Ed25519VerificationKey2018 => { vault.delete(location_seed(location), false).await?; vault.delete(location_skey(location), false).await?; // TODO: Garbage Collection (?) } MethodType::MerkleKeyCollection2021 => todo!("[Stronghold::key_del] Handle MerkleKeyCollection2021"), } Ok(()) } async fn key_sign(&self, id: IdentityId, location: &KeyLocation, data: Vec<u8>) -> Result<Signature> { let vault: Vault<'_> = self.vault(id); match location.method() { MethodType::Ed25519VerificationKey2018 => sign_ed25519(&vault, data, location).await, MethodType::MerkleKeyCollection2021 => todo!("[Stronghold::key_sign] Handle MerkleKeyCollection2021"), } } async fn key_exists(&self, id: IdentityId, location: &KeyLocation) -> Result<bool> { let vault: Vault<'_> = self.vault(id); match location.method() { MethodType::Ed25519VerificationKey2018 => vault.exists(location_skey(location)).await, MethodType::MerkleKeyCollection2021 => todo!("[Stronghold::key_exists] Handle MerkleKeyCollection2021"), } } async fn index(&self) -> Result<IdentityIndex> { // Load the metadata actor let store: Store<'_> = self.store(META); // Read the index from the snapshot let data: Vec<u8> = store.get(location_index()).await?; // No index data (new snapshot) if data.is_empty() { return Ok(IdentityIndex::new()); } // Deserialize and return Ok(IdentityIndex::from_json_slice(&data)?) } async fn set_index(&self, index: &IdentityIndex) -> Result<()> { // Load the metadata actor let store: Store<'_> = self.store(META); // Serialize the index let json: Vec<u8> = index.to_json_vec()?; // Write the index to the snapshot store.set(location_index(), json, None).await?; Ok(()) } async fn snapshot(&self, id: IdentityId) -> Result<Option<IdentitySnapshot>> { // Load the chain-specific store let store: Store<'_> = self.store(&fmt_id(id)); // Read the event snapshot from the stronghold snapshot let data: Vec<u8> = store.get(location_snapshot()).await?; // No snapshot data found if data.is_empty() { return Ok(None); } // Deserialize and return Ok(Some(IdentitySnapshot::from_json_slice(&data)?)) } async fn set_snapshot(&self, id: IdentityId, snapshot: &IdentitySnapshot) -> Result<()> { // Load the chain-specific store let store: Store<'_> = self.store(&fmt_id(id)); // Serialize the state snapshot let json: Vec<u8> = snapshot.to_json_vec()?; // Write the state snapshot to the stronghold snapshot store.set(location_snapshot(), json, None).await?; Ok(()) } async fn append(&self, id: IdentityId, commits: &[Commit]) -> Result<()> { fn encode(commit: &Commit) -> Result<(Generation, Vec<u8>)> { Ok((commit.sequence(), commit.event().to_json_vec()?)) } let store: Store<'_> = self.store(&fmt_id(id)); let future: _ = stream::iter(commits.iter().map(encode)) .into_stream() .and_then(|(index, json)| store.set(location_event(index), json, None)) .try_for_each_concurrent(ECL, |()| future::ready(Ok(()))); // Write all events to the snapshot future.await?; Ok(()) } async fn stream(&self, id: IdentityId, index: Generation) -> Result<BoxStream<'_, Result<Commit>>> { let name: String = fmt_id(id); let range: RangeFrom<u32> = (index.to_u32() + 1)..; let stream: BoxStream<'_, Result<Commit>> = stream::iter(range) .map(Generation::from) .map(Ok) // ================================ // Load the event from the snapshot // ================================ .and_then(move |index| { let name: String = name.clone(); let snap: Arc<Snapshot> = Arc::clone(&self.snapshot); async move { let location: Location = location_event(index); let store: Store<'_> = snap.store(&name, &[]); let event: Vec<u8> = store.get(location).await?; Ok((index, event)) } }) // ================================ // Parse the event // ================================ .try_filter_map(move |(index, json)| async move { if json.is_empty() { Err(Error::EventNotFound) } else { let event: Event = Event::from_json_slice(&json)?; let commit: Commit = Commit::new(id, index, event); Ok(Some(commit)) } }) // ================================ // Downcast to "traditional" stream // ================================ .into_stream() // ================================ // Bail on any invalid event // ================================ .take_while(|event| future::ready(event.is_ok())) // ================================ // Create a boxed stream // ================================ .boxed(); Ok(stream) } async fn purge(&self, id: IdentityId) -> Result<()> { type PurgeSet = (Generation, HashSet<KeyLocation>); async fn fold(mut output: PurgeSet, commit: Commit) -> Result<PurgeSet> { if let EventData::MethodCreated(_, method) = commit.event().data() { output.1.insert(method.location().clone()); } let gen_a: u32 = commit.sequence().to_u32(); let gen_b: u32 = output.0.to_u32(); Ok((Generation::from_u32(gen_a.max(gen_b)), output.1)) } // Load the chain-specific store/vault let store: Store<'_> = self.store(&fmt_id(id)); let vault: Vault<'_> = self.vault(id); // Scan the event stream and collect a set of all key locations let output: (Generation, HashSet<KeyLocation>) = self .stream(id, Generation::new()) .await? .try_fold((Generation::new(), HashSet::new()), fold) .await?; // Remove the state snapshot store.del(location_snapshot()).await?; // Remove all events for index in 0..output.0.to_u32() { store.del(location_event(Generation::from_u32(index))).await?; } // Remove all keys for location in output.1 { match location.method() { MethodType::Ed25519VerificationKey2018 => { vault.delete(location_seed(&location), false).await?; vault.delete(location_skey(&location), false).await?; } MethodType::MerkleKeyCollection2021 => { todo!("[Stronghold::purge] Handle MerkleKeyCollection2021") } } } Ok(()) } async fn published_generation(&self, id: IdentityId) -> Result<Option<Generation>> { let store: Store<'_> = self.store(&fmt_id(id)); let bytes = store.get(location_published_generation()).await?; if bytes.is_empty() { return Ok(None); } let le_bytes: [u8; 4] = <[u8; 4]>::try_from(bytes.as_ref()).map_err(|_| { io::Error::new( io::ErrorKind::InvalidData, format!( "expected to read 4 bytes as the published generation, found {} instead", bytes.len() ), ) })?; let gen = Generation::from_u32(u32::from_le_bytes(le_bytes)); Ok(Some(gen)) } async fn set_published_generation(&self, id: IdentityId, index: Generation) -> Result<()> { let store: Store<'_> = self.store(&fmt_id(id)); store .set(location_published_generation(), index.to_u32().to_le_bytes(), None) .await?; Ok(()) } } async fn generate_ed25519(vault: &Vault<'_>, location: &KeyLocation) -> Result<PublicKey> { // Generate a SLIP10 seed as the private key vault .slip10_generate(location_seed(location), default_hint(), None) .await?; let chain: Chain = Chain::from_u32_hardened(vec![0, 0, 0]); let seed: SLIP10DeriveInput = SLIP10DeriveInput::Seed(location_seed(location)); // Use the SLIP10 seed to derive a child key vault .slip10_derive(chain, seed, location_skey(location), default_hint()) .await?; // Retrieve the public key of the derived child key retrieve_ed25519(vault, location).await } async fn retrieve_ed25519(vault: &Vault<'_>, location: &KeyLocation) -> Result<PublicKey> { vault .ed25519_public_key(location_skey(location)) .await .map(|public| public.to_vec().into()) } async fn sign_ed25519(vault: &Vault<'_>, payload: Vec<u8>, location: &KeyLocation) -> Result<Signature> { let public_key: PublicKey = retrieve_ed25519(vault, location).await?; let signature: [u8; 64] = vault.ed25519_sign(payload, location_skey(location)).await?; Ok(Signature::new(public_key, signature.into())) } fn location_index() -> Location { Location::generic("$index", Vec::new()) } fn location_snapshot() -> Location { Location::generic("$snapshot", Vec::new()) } fn location_event(index: Generation) -> Location { Location::generic(format!("$event:{}", index), Vec::new()) } fn location_seed(location: &KeyLocation) -> Location { Location::generic(fmt_key("$seed", location), Vec::new()) } fn location_skey(location: &KeyLocation) -> Location { Location::generic(fmt_key("$skey", location), Vec::new()) } fn location_published_generation() -> Location { Location::generic("$published_generation", Vec::new()) } fn fmt_key(prefix: &str, location: &KeyLocation) -> Vec<u8> { format!( "{}:{}:{}:{}", prefix, location.integration_generation(), location.diff_generation(), location.fragment(), ) .into_bytes() } fn fmt_id(id: IdentityId) -> String { format!("$identity:{}", id) }
30.23356
116
0.624316
c43b655e66bc9ad993b471a9e9ff58915641cb59
4,021
h
C
include/seccomp_bpf_utils.h
Muli-M/libpledge-openbsd
b8b7de0f9027003693bb6391a5347389cde5259d
[ "0BSD" ]
5
2017-05-10T12:02:48.000Z
2022-01-10T02:10:16.000Z
include/seccomp_bpf_utils.h
Muli-M/libpledge-openbsd
b8b7de0f9027003693bb6391a5347389cde5259d
[ "0BSD" ]
1
2017-04-23T17:47:22.000Z
2017-10-19T18:30:23.000Z
include/seccomp_bpf_utils.h
Muli-M/libpledge-openbsd
b8b7de0f9027003693bb6391a5347389cde5259d
[ "0BSD" ]
2
2017-05-10T12:02:50.000Z
2020-04-03T03:46:13.000Z
#define _OFFSET_NR offsetof(struct seccomp_data, nr) #define _OFFSET_ARCH offsetof(struct seccomp_data, arch) #define _OFFSET_ARG(idx) offsetof(struct seccomp_data, args[(idx)]) #if __BYTE_ORDER == __LITTLE_ENDIAN #define _LO_ARG(idx) \ _OFFSET_ARG((idx)) #elif __BYTE_ORDER == __BIG_ENDIAN #define _LO_ARG(idx) \ _OFFSET_ARG((idx)) + sizeof(__u32) #else #error "Unknown endianness" #endif #if __BYTE_ORDER == __LITTLE_ENDIAN # define ENDIAN(_lo, _hi) _lo, _hi # define _HI_ARG(idx) \ _OFFSET_ARG((idx)) + sizeof(__u32) #elif __BYTE_ORDER == __BIG_ENDIAN # define ENDIAN(_lo, _hi) _hi, _lo # define _HI_ARG(idx) \ _OFFSET_ARG((idx)) #else # error "Unknown endianness" #endif union arg64 { struct byteorder { __u32 ENDIAN(lo, hi); } u32; __u64 u64; }; #define _LOAD_SYSCALL_NR do { \ *fp = (struct sock_filter)BPF_STMT(BPF_LD+BPF_W+BPF_ABS, _OFFSET_NR); \ fp++; \ } while (0) #define _LOAD_ARCH do { \ *fp = (struct sock_filter)BPF_STMT(BPF_LD+BPF_W+BPF_ABS, _OFFSET_ARCH);\ fp++; \ } while (0) #define _ARG32(idx) do { \ *fp = (struct sock_filter)BPF_STMT(BPF_LD+BPF_W+BPF_ABS, _LO_ARG(idx));\ fp++; \ } while (0) #define _ARG64(idx) do { \ *fp = (struct sock_filter)BPF_STMT(BPF_LD+BPF_W+BPF_ABS, _LO_ARG(idx));\ fp++; \ *fp = (struct sock_filter)BPF_STMT(BPF_ST, 0); \ fp++; \ *fp = (struct sock_filter)BPF_STMT(BPF_LD+BPF_W+BPF_ABS, _HI_ARG(idx));\ fp++; \ *fp = (struct sock_filter)BPF_STMT(BPF_ST, 1); \ fp++; \ } while (0) #define _JUMP_EQ(v, t, f) do { \ *fp = (struct sock_filter)BPF_JUMP(BPF_JMP+BPF_JEQ+BPF_K, \ (v), (t), (f)); \ fp++; \ } while (0) #define _JUMP_SET(v, t, f) do { \ *fp = (struct sock_filter)BPF_JUMP(BPF_JMP+BPF_JSET+BPF_K, \ (v), (t), (f)); \ fp++; \ } while (0) #define _JUMP_EQ64(val, jt, jf) do { \ *fp = (struct sock_filter)BPF_JUMP(BPF_JMP+BPF_JEQ+BPF_K, \ ((union arg64){.u64 = (val)}).u32.hi, 0, (jf)); \ fp++; \ *fp = (struct sock_filter)BPF_STMT(BPF_LD+BPF_MEM, 0); \ fp++; \ *fp = (struct sock_filter)BPF_JUMP(BPF_JMP+BPF_JEQ+BPF_K, \ ((union arg64){.u64 = (val)}).u32.lo, (jt), (jf)); \ fp++; \ } while (0) #define _JUMP(j) do { \ *fp = (struct sock_filter)BPF_JUMP(BPF_JMP+BPF_JA, (j), 0xFF, 0xFF), \ fp++; \ } while (0) #define _RET(v) do { \ *fp = (struct sock_filter)BPF_STMT(BPF_RET+BPF_K, (v)); \ fp++; \ } while (0) #define _END len-1-(fp-fprog->filter)-1
42.776596
80
0.386471
759010f7e3fe04c5e3f7ee1e519ee171808647d7
1,685
h
C
LCNetworking/LCSessionManager.h
mlcldh/LCNetworking
d3c916c5561badbd6d58adb398a13283eae8d766
[ "MIT" ]
null
null
null
LCNetworking/LCSessionManager.h
mlcldh/LCNetworking
d3c916c5561badbd6d58adb398a13283eae8d766
[ "MIT" ]
null
null
null
LCNetworking/LCSessionManager.h
mlcldh/LCNetworking
d3c916c5561badbd6d58adb398a13283eae8d766
[ "MIT" ]
null
null
null
// // LCSessionManager.h // Lottery // // Created by menglingchao on 2019/9/8. // Copyright © 2019 MengLingchao. All rights reserved. // #import <Foundation/Foundation.h> /***/ @interface LCSessionManager : NSObject /***/ @property (readonly, nonatomic, strong) NSURLSession *session; /***/ + (instancetype)sharedInstance; /***/ - (instancetype)initWithSessionConfiguration:(NSURLSessionConfiguration *)configuration; /***/ - (NSURLSessionDataTask *)dataTaskWithRequestBlock:(void (^)(NSMutableURLRequest *request))requestBlock completionHandler:(void (^)(NSURLResponse *response, id responseObject, NSError * error))completionHandler; /**上传 @param fileURL 某个本地路径 */ - (NSURLSessionUploadTask *)uploadTaskWithRequestBlock:(void (^)(NSMutableURLRequest *request))requestBlock fromFile:(NSURL *)fileURL completionHandler:(void (^)(NSData * data, NSURLResponse * response, NSError * error))completionHandler; /**上传 @param bodyData 上传的data */ - (NSURLSessionUploadTask *)uploadTaskWithRequestBlock:(void (^)(NSMutableURLRequest *request))requestBlock fromData:(NSData *)bodyData completionHandler:(void (^)(NSData * data, NSURLResponse * response, NSError * error))completionHandler; /**下载*/ - (NSURLSessionDownloadTask *)downloadTaskWithRequestBlock:(void (^)(NSMutableURLRequest *request))requestBlock completionHandler:(void (^)(NSURL * location, NSURLResponse * response, NSError * error))completionHandler; /**断点续传下载 @param resumeData 上次暂停后的数据 */ - (NSURLSessionDownloadTask *)downloadTaskWithResumeData:(NSData *)resumeData completionHandler:(void (^)(NSURL * location, NSURLResponse * response, NSError * error))completionHandler; @end
40.119048
240
0.753709
54a9e96315ec1e6f0e63646c77e48e47676d467b
1,763
swift
Swift
Example/swiftArch/demo/StyleTableDemoVC.swift
SumiaFish/swiftArch
0e7b8de134e12f9cd0917417be06757dc5526bc4
[ "MIT" ]
288
2018-05-17T04:39:16.000Z
2022-03-30T05:48:13.000Z
Example/swiftArch/demo/StyleTableDemoVC.swift
YKHahahaha/swiftArch
c69515305eba44a7693b9c71926365b6cabf99ca
[ "MIT" ]
9
2018-05-28T01:13:13.000Z
2020-01-01T14:14:38.000Z
Example/swiftArch/demo/StyleTableDemoVC.swift
YKHahahaha/swiftArch
c69515305eba44a7693b9c71926365b6cabf99ca
[ "MIT" ]
30
2018-04-24T06:28:48.000Z
2022-02-24T05:50:28.000Z
// // StyleTableDemoVC.swift // swiftArch // // Created by czq on 2018/5/9. // Copyright © 2018年 czq. All rights reserved. // import UIKit import swiftArch import MJRefresh class StyleTableDemoVC: UIViewController { let tableView=StateTableView() let emptyView=UserStyleTableEmptyView() override func viewDidLoad() { super.viewDidLoad() self.view.addSubview(tableView) self.tableView.snp.makeConstraints { (make) in make.left.right.top.bottom.equalToSuperview() } emptyView.button.onTap { //我的tableview已经在empty和error上加入了点击会触发下beginRefresh //但是你依然可以在emptyView上添加你想要的View比如按钮, 点击之后的事件 和我的点击重新加载不冲突 [weak self] in self?.view.makeToast("去添加") } self.tableView.setEmptyiew(view:emptyView )//这里采用自定义的emptyview self.tableView.setRefreshHeader(refreshHeader: MJRefreshNormalHeader())//采用自定义的下拉刷新 self.tableView.setUpState() self.tableView.setLoadMoreCallback { [weak self] in if let strongSelf = self{ strongSelf.tableView.endLoadMore() } } self.tableView.setRefreshCallback { [weak self] in if let strongSelf = self{ strongSelf.tableView.showLoading()//页面没数据的时候要showloading比较友好 DispatchQueue.main.asyncAfter(deadline: .now() + 2) { strongSelf.tableView.endRefresh() strongSelf.tableView.showContent() } } } self.tableView.showEmpty() } deinit { print("StyleTableDemoVC deinit") } }
27.123077
91
0.578559
c4c3093c75c363de258756bfde0c4d02e7cf2b88
1,441
lua
Lua
scripts/zones/Yhoator_Jungle/npcs/qm2.lua
zircon-tpl/topaz
dc2f7e68e5ed84274976e8a787c29fe03eecc382
[ "FTL" ]
1
2021-10-30T11:30:33.000Z
2021-10-30T11:30:33.000Z
scripts/zones/Yhoator_Jungle/npcs/qm2.lua
zircon-tpl/topaz
dc2f7e68e5ed84274976e8a787c29fe03eecc382
[ "FTL" ]
2
2020-07-01T04:11:03.000Z
2020-07-02T03:54:24.000Z
scripts/zones/Yhoator_Jungle/npcs/qm2.lua
zircon-tpl/topaz
dc2f7e68e5ed84274976e8a787c29fe03eecc382
[ "FTL" ]
1
2020-07-01T05:31:49.000Z
2020-07-01T05:31:49.000Z
----------------------------------- -- Area: Yhoator Jungle -- NPC: ??? Used for Norg quest "Stop Your Whining" -- !pos -94.073 -0.999 22.295 124 ----------------------------------- local ID = require("scripts/zones/Yhoator_Jungle/IDs") require("scripts/globals/keyitems") require("scripts/globals/quests") ----------------------------------- function onTrade(player,npc,trade) end function onTrigger(player,npc) local StopWhining = player:getQuestStatus(OUTLANDS,tpz.quest.id.outlands.STOP_YOUR_WHINING) if StopWhining == QUEST_ACCEPTED and not player:hasKeyItem(tpz.ki.BARREL_OF_OPOOPO_BREW) and player:hasKeyItem(tpz.ki.EMPTY_BARREL) then player:messageSpecial(ID.text.TREE_CHECK) player:addKeyItem(tpz.ki.BARREL_OF_OPOOPO_BREW) --Filled Barrel player:messageSpecial(ID.text.KEYITEM_OBTAINED,tpz.ki.BARREL_OF_OPOOPO_BREW) player:delKeyItem(tpz.ki.EMPTY_BARREL) --Empty Barrel elseif StopWhining == QUEST_ACCEPTED and player:hasKeyItem(tpz.ki.BARREL_OF_OPOOPO_BREW) then player:messageSpecial(ID.text.TREE_FULL) --Already have full barrel else player:messageSpecial(ID.text.NOTHING_OUT_OF_ORDINARY) end end function onEventUpdate(player,csid,option) end function onEventFinish(player,csid,option) if csid == 1 then player:addKeyItem(tpz.ki.SEA_SERPENT_STATUE) player:messageSpecial(ID.text.KEYITEM_OBTAINED,tpz.ki.SEA_SERPENT_STATUE) end end
38.945946
140
0.70576
664bc1f0a292f456b0058ac20a6a337248a4dce6
5,321
swift
Swift
MemeGen/CoreDataStackManager.swift
jdbateman/MemeGen
5a482c4a8e744282038051a68173e2eef2ac7f98
[ "MIT" ]
null
null
null
MemeGen/CoreDataStackManager.swift
jdbateman/MemeGen
5a482c4a8e744282038051a68173e2eef2ac7f98
[ "MIT" ]
null
null
null
MemeGen/CoreDataStackManager.swift
jdbateman/MemeGen
5a482c4a8e744282038051a68173e2eef2ac7f98
[ "MIT" ]
null
null
null
// // CoreDataStackManager.swift // FavoriteActors // // Created by Jason on 3/10/15. // Copyright (c) 2015 Udacity. All rights reserved. // import Foundation import CoreData /** * The CoreDataStackManager contains the code that was previously living in the * AppDelegate in Lesson 3. Apple puts the code in the AppDelegate in many of their * Xcode templates. But they put it in a convenience class like this in sample code * like the "Earthquakes" project. * */ private let SQLITE_FILE_NAME = "MyPracticeCoreDataApp.sqlite" class CoreDataStackManager { // MARK: - Shared Instance /** * This class variable provides an easy way to get access * to a shared instance of the CoreDataStackManager class. */ class func sharedInstance() -> CoreDataStackManager { struct Static { static let instance = CoreDataStackManager() } return Static.instance } // MARK: - The Core Data stack. The code has been moved, unaltered, from the AppDelegate. lazy var applicationDocumentsDirectory: NSURL = { println("Instantiating the applicationDocumentsDirectory property") let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask) return urls[urls.count-1] as! NSURL }() lazy var managedObjectModel: NSManagedObjectModel = { // The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model. println("Instantiating the managedObjectModel property") let modelURL = NSBundle.mainBundle().URLForResource("Model", withExtension: "momd")! return NSManagedObjectModel(contentsOfURL: modelURL)! }() /** * The Persistent Store Coordinator is an object that the Context uses to interact with the underlying file system. Usually * the persistent store coordinator object uses an SQLite database file to save the managed objects. But it is possible to * configure it to use XML or other formats. * * Typically you will construct your persistent store manager exactly like this. It needs two pieces of information in order * to be set up: * * - The path to the sqlite file that will be used. Usually in the documents directory * - A configured Managed Object Model. See the next property for details. */ lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator? = { // The persistent store coordinator for the application. This implementation creates and return a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail. // Create the coordinator and store println("Instantiating the persistentStoreCoordinator property") var coordinator: NSPersistentStoreCoordinator? = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel) let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent(SQLITE_FILE_NAME) println("sqlite path: \(url.path!)") var error: NSError? = nil if coordinator!.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil, error: &error) == nil { coordinator = nil // Report any error we got. let dict = NSMutableDictionary() dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data" dict[NSLocalizedFailureReasonErrorKey] = "There was an error creating or loading the application's saved data." dict[NSUnderlyingErrorKey] = error error = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict as [NSObject : AnyObject]) // Left in for development development. NSLog("Unresolved error \(error), \(error!.userInfo)") abort() } return coordinator }() lazy var managedObjectContext: NSManagedObjectContext? = { println("Instantiating the managedObjectContext property") // Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail. let coordinator = self.persistentStoreCoordinator if coordinator == nil { return nil } var managedObjectContext = NSManagedObjectContext() managedObjectContext.persistentStoreCoordinator = coordinator return managedObjectContext }() // MARK: - Core Data Saving support func saveContext () { if let context = self.managedObjectContext { var error: NSError? = nil if context.hasChanges { if !context.save(&error) { NSLog("Unresolved error \(error), \(error!.userInfo)") abort() } } } } }
40.930769
290
0.667356
acedb594477650180ca18ddd4458f8d5ebb10e98
2,869
cpp
C++
main.cpp
jacob-baines/fuzzface
c2c405c1e21079325fde1e58951ab956055d91f7
[ "MIT" ]
9
2016-10-06T14:09:41.000Z
2022-03-29T04:32:37.000Z
main.cpp
jacob-baines/fuzzface
c2c405c1e21079325fde1e58951ab956055d91f7
[ "MIT" ]
null
null
null
main.cpp
jacob-baines/fuzzface
c2c405c1e21079325fde1e58951ab956055d91f7
[ "MIT" ]
4
2018-04-11T20:13:07.000Z
2020-08-31T05:46:19.000Z
#include <string> #include <cstdio> #include <iostream> #include <boost/cstdint.hpp> #include <boost/filesystem.hpp> #include <boost/lexical_cast.hpp> #include "fuzzface.hpp" /* Checks to make sure the command line params are present and valid. Also, initializes srand here. */ bool validateInput(int argc, char* argv[], std::string& p_rootDirectory, boost::asio::ip::address& p_ipAddress, boost::uint16_t& p_port, int& p_seedValue) { //currently we need argc to be 2 or 3 if (argc < 4 || argc > 5) { return false; } p_rootDirectory.assign(argv[1]); if (!boost::filesystem::is_directory(p_rootDirectory)) { std::cerr << p_rootDirectory << " is not a directory." << std::endl; return false; } try { p_ipAddress.from_string(argv[2]); } catch (std::exception&) { std::cerr << "Failed to convert the IP address paramater to a IPv4 or" " IPv6 address." << std::endl; return false; } try { p_port = boost::lexical_cast<boost::uint16_t>(argv[3]); } catch (std::exception&) { std::cerr << "Failed to convert port value to a 16 bit integer" << std::endl; return false; } // use the seed provided or generate a new one if (argc == 5) { try { p_seedValue = boost::lexical_cast<int>(argv[4]); } catch (std::exception& e) { std::cerr << "Failed to convert seed parameter value to an integer." << std::endl; return false; } } else { p_seedValue = std::time(NULL); } srand(p_seedValue); return true; } int main(int argc, char* argv[]) { //expected command line params int seedValue = 0; boost::uint16_t port = 0; std::string rootDirectory; boost::asio::ip::address ipAddress; if (!validateInput(argc, argv, rootDirectory, ipAddress, port, seedValue)) { std::cout << "Usage: ./fuzzface <directory> <server ip> <server port>" " [optional seed]" << std::endl; return EXIT_FAILURE; } FuzzFace pcapFuzzer; try { pcapFuzzer.connect(ipAddress, port); } catch (std::exception& e) { std::cerr << "Failed to connect the server: " << e.what() << std::endl; return EXIT_FAILURE; } try { pcapFuzzer.processFiles(rootDirectory); } catch (std::exception& e) { std::cerr << "Shutting down. Error while processing: " << e.what() << std::endl; } pcapFuzzer.printStats(); std::cout << "\nYour seed was: " << seedValue << std::endl; return 0; }
23.908333
80
0.538515
35fac2fc1696de3f9db49313434d49f6ce1010f5
876
sql
SQL
ORACLE_SQL/RHOMICOM_FUNCTIONS/ACCB/552_ACCB.GET_ACCB_SRC_DOC_NUM.sql
rhomicom-systems-tech-gh/Rhomicom-DB-Scripts
ac36d96a5883097a1f0c86909cb516e456f154f9
[ "MIT" ]
1
2022-01-12T06:39:23.000Z
2022-01-12T06:39:23.000Z
ORACLE_SQL/RHOMICOM_FUNCTIONS/ACCB/552_ACCB.GET_ACCB_SRC_DOC_NUM.sql
rhomicom-systems-tech-gh/Rhomicom-DB-Scripts
ac36d96a5883097a1f0c86909cb516e456f154f9
[ "MIT" ]
null
null
null
ORACLE_SQL/RHOMICOM_FUNCTIONS/ACCB/552_ACCB.GET_ACCB_SRC_DOC_NUM.sql
rhomicom-systems-tech-gh/Rhomicom-DB-Scripts
ac36d96a5883097a1f0c86909cb516e456f154f9
[ "MIT" ]
1
2020-12-19T15:27:29.000Z
2020-12-19T15:27:29.000Z
/* Formatted on 10/3/2014 3:57:47 PM (QP5 v5.126.903.23003) */ -- FUNCTION: APLAPPS.GET_SRC_DOC_NUM(BIGINT, CHARACTER VARYING) --DROP FUNCTION APLAPPS.GET_ACCB_SRC_DOC_NUM; CREATE OR REPLACE FUNCTION APLAPPS.GET_ACCB_SRC_DOC_NUM (P_SRCDOCID NUMBER, P_SRCDOCTYPE VARCHAR2) RETURN VARCHAR2 AS L_RESULT VARCHAR2 (200) := ''; BEGIN IF P_SRCDOCTYPE LIKE '%Supplier%' THEN SELECT PYBLS_INVC_NUMBER INTO L_RESULT FROM ACCB.ACCB_PYBLS_INVC_HDR WHERE PYBLS_INVC_HDR_ID = P_SRCDOCID AND PYBLS_INVC_TYPE = P_SRCDOCTYPE; ELSE SELECT RCVBLS_INVC_NUMBER INTO L_RESULT FROM ACCB.ACCB_RCVBLS_INVC_HDR WHERE RCVBLS_INVC_HDR_ID = P_SRCDOCID AND RCVBLS_INVC_TYPE = P_SRCDOCTYPE; END IF; RETURN L_RESULT; END;
31.285714
80
0.646119
7038ba129355a3513834a60dbac2318018ffa8e2
381
cs
C#
BinaryAnalyzer/BinaryAnalyzer/Attribute/HandlerAttribute.cs
tylearymf/.Net_BinaryAnalyzer
f6e4bf21ef13db87b5dfcc7afd7cfb754e2e6e4a
[ "MIT" ]
2
2020-06-05T00:14:14.000Z
2021-04-04T13:14:12.000Z
BinaryAnalyzer/BinaryAnalyzer/Attribute/HandlerAttribute.cs
tylearymf/.Net_BinaryAnalyzer
f6e4bf21ef13db87b5dfcc7afd7cfb754e2e6e4a
[ "MIT" ]
null
null
null
BinaryAnalyzer/BinaryAnalyzer/Attribute/HandlerAttribute.cs
tylearymf/.Net_BinaryAnalyzer
f6e4bf21ef13db87b5dfcc7afd7cfb754e2e6e4a
[ "MIT" ]
1
2021-04-04T13:14:15.000Z
2021-04-04T13:14:15.000Z
using BinaryAnalyzer.Struct; using System; using System.Collections.Generic; using System.Text; namespace BinaryAnalyzer.Attribute { class HandlerAttribute : System.Attribute { public RecordTypeEnumeration RecordType { set; get; } public HandlerAttribute(RecordTypeEnumeration recordType) { RecordType = recordType; } } }
21.166667
65
0.692913
c3fd0ceee56c2f9ae837d850fc667412656c9453
473
go
Go
cron/run_one.go
czl0325/Lottery-go
099a9093d98a4ad3534d26527f843de1e276bbb3
[ "Apache-2.0" ]
8
2019-10-22T02:33:26.000Z
2021-08-02T10:23:49.000Z
cron/run_one.go
czl0325/Lottery-go
099a9093d98a4ad3534d26527f843de1e276bbb3
[ "Apache-2.0" ]
null
null
null
cron/run_one.go
czl0325/Lottery-go
099a9093d98a4ad3534d26527f843de1e276bbb3
[ "Apache-2.0" ]
3
2019-11-09T06:40:37.000Z
2021-02-27T15:42:19.000Z
package cron import ( "Lottery-go/comm" "Lottery-go/services" "log" ) func ConfigueAppOneCron() { } // 重置所有奖品的发奖计划 // 每5分钟执行一次 func resetAllGiftPrizeData() { giftService := services.NewGiftService() list := giftService.GetAll(false) nowTime := comm.NowUnix() for _, gift := range list { if gift.PrizeTime != 0 && (gift.PrizeData == "" || gift.PrizeEnd <= nowTime) { // 立即执行 log.Println("crontab start utils.ResetGiftPrizeData giftInfo=", gift) } } }
18.192308
80
0.674419
761fb2ffb84e84f2313b596e1bf8d4df576f56da
401
go
Go
pkg/trigger/date-before.go
schoenenberg/mail-organizer
dcdff89878d738189815f0e84753b37e16762bc2
[ "MIT" ]
1
2021-07-28T13:56:07.000Z
2021-07-28T13:56:07.000Z
pkg/trigger/date-before.go
schoenenberg/mail-organizer
dcdff89878d738189815f0e84753b37e16762bc2
[ "MIT" ]
null
null
null
pkg/trigger/date-before.go
schoenenberg/mail-organizer
dcdff89878d738189815f0e84753b37e16762bc2
[ "MIT" ]
null
null
null
package trigger import ( "errors" "time" "github.com/emersion/go-imap" ) type DateBefore string func (s DateBefore) Evaluate(msg imap.Message) (bool, error) { if msg.Envelope != nil { dur, err := time.ParseDuration(string(s)) if err != nil { return false, err } return msg.Envelope.Date.Add(dur).Before(time.Now()), nil } else { return false, errors.New("envelope missing") } }
17.434783
62
0.670823
c3aa8b73356a2c9c4da783eff961d3b35d6b081c
374
dart
Dart
first_app/lib/EnglishWords.dart
PSLoveYSJ/PSFlutter
59039fab46c3e77ea0fbc5c701657287e256c650
[ "Apache-2.0" ]
1
2019-08-08T03:27:06.000Z
2019-08-08T03:27:06.000Z
first_app/lib/EnglishWords.dart
PSLoveYSJ/PSFlutter
59039fab46c3e77ea0fbc5c701657287e256c650
[ "Apache-2.0" ]
null
null
null
first_app/lib/EnglishWords.dart
PSLoveYSJ/PSFlutter
59039fab46c3e77ea0fbc5c701657287e256c650
[ "Apache-2.0" ]
null
null
null
import 'package:english_words/english_words.dart' as prefix0; import 'package:flutter/material.dart'; class EnglishWords extends StatelessWidget { @override Widget build(BuildContext context) { final wordPair = new prefix0.WordPair.random(); return Padding( padding: const EdgeInsets.all(8.0), child: new Text(wordPair.toString()), ); } }
23.375
61
0.71123
419131becfe211167225ec3a742962cb7aae0e7c
491
swift
Swift
Sources/photon/API/Responses/User.swift
krad/photon
60e4f8b7040f8703083fab142ac6adf977c18329
[ "MIT" ]
null
null
null
Sources/photon/API/Responses/User.swift
krad/photon
60e4f8b7040f8703083fab142ac6adf977c18329
[ "MIT" ]
null
null
null
Sources/photon/API/Responses/User.swift
krad/photon
60e4f8b7040f8703083fab142ac6adf977c18329
[ "MIT" ]
null
null
null
import Foundation #if os(iOS) import UIKit #endif public struct User: Codable { public var userID: String public var username: String? public var firstName: String? public var lastName: String? public var createdAt: Date? enum CodingKeys: String, CodingKey { case userID case username case firstName case lastName case createdAt } #if os(iOS) public var image: UIImage? = nil #endif }
17.535714
40
0.610998
29c769695bf319754a74d74d3d8aee05e7293a25
368
sql
SQL
resources/sql/migrations.sql
reallinfo/coast
be4224429eed46528e68ae21446aab245435e3c1
[ "MIT" ]
null
null
null
resources/sql/migrations.sql
reallinfo/coast
be4224429eed46528e68ae21446aab245435e3c1
[ "MIT" ]
null
null
null
resources/sql/migrations.sql
reallinfo/coast
be4224429eed46528e68ae21446aab245435e3c1
[ "MIT" ]
null
null
null
-- name: create-table create table if not exists schema_migrations ( id text, created_at timestamp with time zone default now() ); -- name: migrations select id from schema_migrations order by created_at -- name: insert insert into schema_migrations (id) values (:id) returning * -- name: delete delete from schema_migrations where id = :id returning *
14.153846
51
0.73913
9c6724fa30d0477df5c56ae23d03c51d79c90d27
237
js
JavaScript
migrations/1_deploy_contracts.js
jackykwandesign/DiceGameSolidity
c317d18fccd47abd10f05af84f4d38195b389f72
[ "MIT" ]
null
null
null
migrations/1_deploy_contracts.js
jackykwandesign/DiceGameSolidity
c317d18fccd47abd10f05af84f4d38195b389f72
[ "MIT" ]
null
null
null
migrations/1_deploy_contracts.js
jackykwandesign/DiceGameSolidity
c317d18fccd47abd10f05af84f4d38195b389f72
[ "MIT" ]
null
null
null
const RandomMachine = artifacts.require("RandomMachine"); const DiceGame = artifacts.require("DiceGame"); module.exports = function(deployer) { deployer.deploy(RandomMachine); // deployer.deploy(DiceGame, RandomMachine.address); };
29.625
57
0.767932
0a43960076bd38e5279d6ea85b048d7625a64462
7,089
asm
Assembly
Transynther/x86/_processed/NONE/_xt_/i7-7700_9_0x48_notsx.log_21829_94.asm
ljhsiun2/medusa
67d769b8a2fb42c538f10287abaf0e6dbb463f0c
[ "MIT" ]
9
2020-08-13T19:41:58.000Z
2022-03-30T12:22:51.000Z
Transynther/x86/_processed/NONE/_xt_/i7-7700_9_0x48_notsx.log_21829_94.asm
ljhsiun2/medusa
67d769b8a2fb42c538f10287abaf0e6dbb463f0c
[ "MIT" ]
1
2021-04-29T06:29:35.000Z
2021-05-13T21:02:30.000Z
Transynther/x86/_processed/NONE/_xt_/i7-7700_9_0x48_notsx.log_21829_94.asm
ljhsiun2/medusa
67d769b8a2fb42c538f10287abaf0e6dbb463f0c
[ "MIT" ]
3
2020-07-14T17:07:07.000Z
2022-03-21T01:12:22.000Z
.global s_prepare_buffers s_prepare_buffers: push %r10 push %r11 push %r13 push %r14 push %r8 push %rax push %rbx push %rcx push %rdi push %rsi lea addresses_D_ht+0xdf04, %rax clflush (%rax) nop nop sub %rbx, %rbx movl $0x61626364, (%rax) nop nop nop inc %r11 lea addresses_WT_ht+0x11b84, %r8 dec %r10 mov (%r8), %r14d dec %r14 lea addresses_A_ht+0x12d84, %rbx nop nop sub $50887, %r14 mov $0x6162636465666768, %rax movq %rax, %xmm0 vmovups %ymm0, (%rbx) nop nop nop dec %r10 lea addresses_D_ht+0x6004, %rsi lea addresses_A_ht+0x2014, %rdi nop nop nop nop nop xor $60643, %r11 mov $12, %rcx rep movsw nop nop nop xor $56006, %rbx lea addresses_WC_ht+0x187e4, %rsi add %rax, %rax mov $0x6162636465666768, %r14 movq %r14, %xmm1 and $0xffffffffffffffc0, %rsi vmovaps %ymm1, (%rsi) nop nop sub $20429, %r10 pop %rsi pop %rdi pop %rcx pop %rbx pop %rax pop %r8 pop %r14 pop %r13 pop %r11 pop %r10 ret .global s_faulty_load s_faulty_load: push %r11 push %r13 push %r15 push %rbp push %rcx push %rdi push %rdx push %rsi // REPMOV lea addresses_D+0xe384, %rsi lea addresses_PSE+0xe84, %rdi nop nop nop dec %r15 mov $7, %rcx rep movsb sub %rcx, %rcx // REPMOV lea addresses_A+0x9cc4, %rsi lea addresses_A+0x1db84, %rdi clflush (%rdi) nop nop nop dec %r11 mov $127, %rcx rep movsw nop nop nop nop nop add $61663, %rsi // Load lea addresses_UC+0x5384, %rbp nop nop sub $64301, %rdx mov (%rbp), %si cmp %r11, %r11 // REPMOV lea addresses_A+0x17c44, %rsi lea addresses_WT+0x9d84, %rdi nop nop nop add $12262, %r13 mov $5, %rcx rep movsq nop nop nop add $11733, %r11 // Store lea addresses_WT+0x18184, %r15 nop nop nop nop cmp $63550, %rbp mov $0x5152535455565758, %rdx movq %rdx, %xmm4 vmovups %ymm4, (%r15) nop nop nop nop nop and %rdi, %rdi // Load lea addresses_A+0x1db84, %rsi nop and $21563, %r15 mov (%rsi), %rcx add $48047, %rdx // Load lea addresses_RW+0x1d984, %r13 nop nop nop nop xor $20416, %rdi movups (%r13), %xmm2 vpextrq $0, %xmm2, %r11 nop nop and $19353, %rcx // Faulty Load lea addresses_A+0x1db84, %rsi nop nop sub %r11, %r11 mov (%rsi), %dx lea oracles, %rdi and $0xff, %rdx shlq $12, %rdx mov (%rdi,%rdx,1), %rdx pop %rsi pop %rdx pop %rdi pop %rcx pop %rbp pop %r15 pop %r13 pop %r11 ret /* <gen_faulty_load> [REF] {'OP': 'LOAD', 'src': {'same': False, 'NT': False, 'AVXalign': True, 'size': 16, 'type': 'addresses_A', 'congruent': 0}} {'dst': {'same': False, 'congruent': 6, 'type': 'addresses_PSE'}, 'OP': 'REPM', 'src': {'same': False, 'congruent': 9, 'type': 'addresses_D'}} {'dst': {'same': True, 'congruent': 0, 'type': 'addresses_A'}, 'OP': 'REPM', 'src': {'same': False, 'congruent': 5, 'type': 'addresses_A'}} {'OP': 'LOAD', 'src': {'same': False, 'NT': False, 'AVXalign': True, 'size': 2, 'type': 'addresses_UC', 'congruent': 2}} {'dst': {'same': True, 'congruent': 9, 'type': 'addresses_WT'}, 'OP': 'REPM', 'src': {'same': False, 'congruent': 2, 'type': 'addresses_A'}} {'dst': {'same': False, 'NT': False, 'AVXalign': False, 'size': 32, 'type': 'addresses_WT', 'congruent': 8}, 'OP': 'STOR'} {'OP': 'LOAD', 'src': {'same': True, 'NT': False, 'AVXalign': False, 'size': 8, 'type': 'addresses_A', 'congruent': 0}} {'OP': 'LOAD', 'src': {'same': False, 'NT': False, 'AVXalign': False, 'size': 16, 'type': 'addresses_RW', 'congruent': 6}} [Faulty Load] {'OP': 'LOAD', 'src': {'same': True, 'NT': False, 'AVXalign': False, 'size': 2, 'type': 'addresses_A', 'congruent': 0}} <gen_prepare_buffer> {'dst': {'same': False, 'NT': False, 'AVXalign': False, 'size': 4, 'type': 'addresses_D_ht', 'congruent': 6}, 'OP': 'STOR'} {'OP': 'LOAD', 'src': {'same': False, 'NT': False, 'AVXalign': False, 'size': 4, 'type': 'addresses_WT_ht', 'congruent': 11}} {'dst': {'same': False, 'NT': False, 'AVXalign': False, 'size': 32, 'type': 'addresses_A_ht', 'congruent': 9}, 'OP': 'STOR'} {'dst': {'same': True, 'congruent': 4, 'type': 'addresses_A_ht'}, 'OP': 'REPM', 'src': {'same': False, 'congruent': 6, 'type': 'addresses_D_ht'}} {'dst': {'same': False, 'NT': False, 'AVXalign': True, 'size': 32, 'type': 'addresses_WC_ht', 'congruent': 3}, 'OP': 'STOR'} {'35': 21829} 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 */
33.28169
2,999
0.654253
ea9dd8053e14dba78460f45510255d2a1d768deb
11,604
dart
Dart
lib/components/header/component.search.dart
GrougalQatal/dashboard
33af9a845be4c4abf912e9cdc7da5dd31ed656a7
[ "MIT" ]
null
null
null
lib/components/header/component.search.dart
GrougalQatal/dashboard
33af9a845be4c4abf912e9cdc7da5dd31ed656a7
[ "MIT" ]
null
null
null
lib/components/header/component.search.dart
GrougalQatal/dashboard
33af9a845be4c4abf912e9cdc7da5dd31ed656a7
[ "MIT" ]
null
null
null
import 'dart:async'; import 'package:admin/Repository/api.user.dart'; import 'package:admin/constants.dart'; import 'package:admin/controllers/controller.dashboardsearch.dart'; import 'package:admin/helpers/helper.ui.dart'; import 'package:admin/screens/user/screen.user.dart'; import 'package:flutter/material.dart'; import 'package:flutter_smart_dialog/flutter_smart_dialog.dart'; class SearchField extends StatelessWidget { // This stream will activate the lateral expansion sheet that will show for example // the user data when you search for him static final StreamController<Map<String, dynamic>> isSearchingStream = StreamController.broadcast(); SearchField({ Key? key, }) : super(key: key); dispose() { isSearchingStream.close(); } @override Widget build(BuildContext context) { return Container( padding: const EdgeInsets.symmetric(horizontal: 5.0), margin: const EdgeInsets.symmetric(vertical: defaultPadding, horizontal: defaultPadding), decoration: BoxDecoration( borderRadius: BorderRadius.circular(20.0), color: Colors.white ), child: DropdownButton<String>( // elevation: 1, underline: Container(), itemHeight: null, onChanged: (x){}, hint: Text( "Search", maxLines: 1, overflow: TextOverflow.clip, ), alignment: Alignment.center, icon: Icon(Icons.search), value: null, items: [ DropdownMenuItem( enabled: false, value: "", child: _SearchAndResultsPanel(), ) ], ), ); } } /// Idk why but the DropDownButton isn't recognizing the setState call, so, the inner /// component is never updated. The solution for the problem was to create a new class /// with its own state, so it's independent of the DropDownButton. class _SearchAndResultsPanel extends StatefulWidget { final _controller = DashBoardSearchController(); _SearchAndResultsPanel({ Key? key }) : super(key: key); @override State<_SearchAndResultsPanel> createState() => _SearchAndResultsPanelState(); } class _SearchAndResultsPanelState extends State<_SearchAndResultsPanel> { late final TextEditingController ciController; late final TextEditingController nameController; late final TextEditingController surnameController; late final List<Map<String, dynamic>> users; // List of searched users late List<Map<String, dynamic>> careers; // a list of all the careers of the selected faculty late Map<String, dynamic> selectedCareer; late Map<String, dynamic> selectedFaculty; late bool shouldBlockFields; // Block non cedula fields // Since search results are gonna be showed here, this variable // will control when to show the search panel or the results late bool showSearchPanel; @override void dispose() { super.dispose(); } @override void initState() { users = []; careers = []; shouldBlockFields = false; showSearchPanel = true; ciController = TextEditingController(); // cedula de identidad nameController = TextEditingController(); surnameController = TextEditingController(); selectedFaculty = Map<String, dynamic>(); selectedCareer = Map<String, dynamic>(); // if cedula is registered then it's not necessary to input the name // or career of the student, so let's block them. ciController.addListener((){ setState(() { shouldBlockFields = ciController.text.trim().isNotEmpty; }); }); super.initState(); } @override Widget build(BuildContext context) { final size = MediaQuery.of(context).size; // This is positioned relative to screen size, so other components should do the // same or this will case overlaps return Container( child: Column( children: showSearchPanel? _getSearchPanel(Size(size.width * 0.35, size.height)): _searchResultPanel(context, Size(size.width * 0.35, size.height)) ), ); } /// Creates a new custom input field according to defined /// interface styles Widget _getInputField( bool isEnable, String title, String placeholder, Size size, TextEditingController controller ) { return AnimatedContainer( duration: Duration(milliseconds: 250), width: size.width, height: isEnable? size.height * 0.1:0, child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Expanded( flex: 2, child: Text("$title: ") ), Expanded( flex: 7, child: TextField( style: TextStyle(color: isEnable? null: Colors.transparent), enabled: isEnable, controller: controller, decoration: InputDecoration( fillColor: secondaryColor, filled: true, border: !isEnable? InputBorder.none: OutlineInputBorder( borderSide: BorderSide( color: Colors.grey[300]! ), borderRadius: const BorderRadius.all(Radius.circular(10)), ), ) ), ) ], ), ); } /// Creates a panel that allows user to search for students according /// to a full name or an identification (cedula). You can't input a cedula and /// a full name at the same time. [size] referes to the size of this component, /// not the screen size. List<Widget> _getSearchPanel(Size size) { return <Widget>[ _getInputField(true, "Cédula", "0000000000", size, ciController), _getInputField(!shouldBlockFields, "Nombres", "0000000000", size, nameController), _getInputField(!shouldBlockFields, "Apellidos", "0000000000", size, surnameController), Padding( padding: const EdgeInsets.all(8.0), child: Row( crossAxisAlignment: CrossAxisAlignment.center, mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: [ MaterialButton( onPressed: ()async{ if(!validateFields()) { SmartDialog.showToast( "Rellene los campos con la información solicitada", time: Duration(seconds: 3) ); return; } SmartDialog.showLoading(msg: 'Cargando datos, por favor espere'); final queryUsers = await widget._controller.searchUser( cedula: ciController.text, fullName: nameController.text + " " + surnameController.text, ); SmartDialog.dismiss(); // Cleaning up previous results users.clear(); users.addAll(queryUsers); // if(queryUsers.length == 1 && ciController.text.isNotEmpty) { // Navigator.pushNamed(context, '/User', arguments: users.first); // } setState(() { showSearchPanel = false; }); }, child: Text("Buscar"), color: Colors.green[900], textColor: Colors.white, ), MaterialButton( color: Colors.green[900], onPressed: () => Navigator.of(context) .pushNamed('/Faculties'), child: Text('Facultades',style: TextStyle(color: secondaryColor),), ), ], ), ) ]; } List<Widget> _searchResultPanel(BuildContext mainContext, Size size) { List<Widget> content = [ ListTile( title: Text("Mostrando resultados de búsqueda"), leading: IconButton( icon: Icon(Icons.arrow_back), onPressed: () { setState(() { showSearchPanel = true; }); } ), ), users.isEmpty?Container( width: size.width, height: size.height * 0.5, child: Center( child: Text("Ningún usuario coincide con los criterios de búsqueda") ) ):_getResultTable(users, size) ]; return content; } Widget _getResultTable(List<Map<String, dynamic>> userRecords, Size size) { const header = [ "Cédula", "Correo", "Nombre", "F. Nacimiento" ]; return PaginatedDataTable( columnSpacing: 10.0, showCheckboxColumn: false, rowsPerPage: 5, source: _TalbeRow(context, userRecords, size), horizontalMargin: 5.0, columns: List<DataColumn>.from(header.map((head){ return DataColumn(label: Text(head)); })) ); } bool validateFields() { return ciController.text.trim().isNotEmpty || nameController.text.trim().isNotEmpty || surnameController.text.trim().isNotEmpty ; } } /// Creates a new row format for a PaginatedDataTable. In /// this scenario [context] should be a MaterialPage context, /// you can't use a context provided by, for example, FutureBuilder, /// StreamBuilder, or any builder context that does not directly /// belong to a material page. /// class _TalbeRow extends DataTableSource { final List<Map<String, dynamic>> userRecords; final Size size; final BuildContext context; _TalbeRow(this.context, this.userRecords, this.size); @override DataRow? getRow(int index) { if(index > userRecords.length - 1) return null; return DataRow.byIndex( onSelectChanged: (_){ UIHelper().showLateralSheet( context, backgroundColor: Colors.green[900]!, foregroundColor: Colors.white, title: 'Mostrando datos de usuario', content: FutureBuilder<Map<String,dynamic>>( future: APIUser().fetchUserData(userRecords[index]['id_paciente'].toString()), builder: (context, snapshot) { if(!snapshot.hasData) { return UserScreen( user: {}, isLoading: !snapshot.hasData ); } final Map<String, dynamic> data = snapshot.data!; data.addAll({'cedula': userRecords[index]['cedula']}); return UserScreen( user: snapshot.data! ); } ) ); }, index: index, cells: [ DataCell( SizedBox( width: size.width*0.15, child: Text( userRecords[index]['cedula'] ?? "N/A", maxLines: 2, overflow: TextOverflow.ellipsis, ) ) ), DataCell( SizedBox( width: size.width*0.3, child: Text( userRecords[index]['correo_institucional'] ?? "N/A", maxLines: 2, overflow: TextOverflow.ellipsis, ) ) ), DataCell( SizedBox( width: size.width*0.35, child: Text( '${userRecords[index]['apellidos']} ${userRecords[index]['nombres']}', maxLines: 2, overflow: TextOverflow.ellipsis, ) ) ), DataCell( SizedBox( width: size.width*0.2, child: Text( userRecords[index]['fecha_nacimiento'] ?? "N/A", maxLines: 2, overflow: TextOverflow.ellipsis, ) ) ), ] ); } @override bool get isRowCountApproximate => false; @override int get rowCount => userRecords.length; @override int get selectedRowCount => 0; // para no complicarse la existencia :) }
28.581281
103
0.596088
e50c820550d65948de598e80ecef3aa6fdcdcf2c
15,973
html
HTML
index.html
mono-developer/RSMaker
ef11345a6b1cb5deb2fb5a9f218bc795a88c6440
[ "MIT" ]
null
null
null
index.html
mono-developer/RSMaker
ef11345a6b1cb5deb2fb5a9f218bc795a88c6440
[ "MIT" ]
null
null
null
index.html
mono-developer/RSMaker
ef11345a6b1cb5deb2fb5a9f218bc795a88c6440
[ "MIT" ]
null
null
null
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:fb="http://ogp.me/ns/fb#" lang="de"> <head> <link rel="shortcut icon" href="icons/favicon.ico"> <link rel="apple-touch-icon" sizes="152x152" href="icons/apple-touch-icon.png"> <link rel="icon" type="image/png" href="icons/favicon-96x96.png" sizes="96x96"> <link rel="icon" type="image/png" sizes="32x32" href="icons/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="16x16" href="icons/favicon-16x16.png"> <link rel="manifest" href="icons/site.webmanifest"> <link rel="mask-icon" href="icons/safari-pinned-tab.svg" color="#5bbad5"> <meta name="msapplication-TileColor" content="#da532c"> <meta name="theme-color" content="#ffffff"> <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" /> <meta charset="UTF-8"> <meta name="description" content="farmshops.eu ist eine Übersichtskarte von Hofläden, Märkten, Essensautomaten und anderen Direktvermarktern aus der DACH-Region (Deutschland, Österreich, Schweiz). Die Karte erhält alle ihre Daten von Openstreetmap, bereitet sie optisch auf und unterstützt die Pflege der Daten indem sie fehlende Werte sichtbar macht und direkt auf den entsprechenden Ort auf OSM und in andere Kartendienste verlinkt." /> <meta name="keywords" content="Hofladen, Hofläden, Bauernladen, Direktvermarkter, Verkauf ab Hof, Karte, Map, Farmshops, Bauernladen, Openstreetmap, Lokales Essen, Milchautomat, Eierautomat, Essensautomat, Open Knowledge, Freies Wissen, OKFN, Code for Karlsruhe, Code for Germany, Deutschland, Schweiz, Österreich" /> <link href="css/leaflet.css" type="text/css" rel=stylesheet> <link rel="stylesheet" href="css/leaflet-sidebar.css" /> <link rel="stylesheet" href="css/MarkerCluster.css" /> <link rel="stylesheet" href="css/fontawesome-all.min.css" /> <link rel="stylesheet" href="css/L.Control.Locate.min.css" /> <link href="css/style.css" type="text/css" rel=stylesheet> <title>farmshops.eu - Hofläden, Märkte, Automaten und andere Direktvermarkter</title> <meta property="og:image" content="https://raw.githubusercontent.com/CodeforKarlsruhe/direktvermarkter/master/img/direktvermarkter.png" /> <meta name="twitter:image:src" content="https://raw.githubusercontent.com/CodeforKarlsruhe/direktvermarkter/master/img/direktvermarkter.png" /> <meta name="country" content="Germany"> <meta name="country" content="Austria"> <meta name="country" content="Switzerland"> </head> <body> <script src="data/farmshopGeoJson.js"></script> <div id="sidebar" class="sidebar collapsed"> <!-- Nav tabs --> <div class="sidebar-tabs"> <ul role="tablist"> <li> <a href="#home" role="tab" alt="info" title="Was ist das hier und wie pflege ich die Daten?">&#9776;</a> </li> </ul> <ul role="tablist"> <li> <a href="#info" role="tab" alt="i" title="Impressum und Datenschutz">&#8505;</a> </li> <li> <a href="https://github.com/CodeforKarlsruhe/direktvermarkter" role="tab" target="_blank" rel="noopener"> <img width="20px" style="padding-top: 8px;" margin-top="5px" src="img/github.svg" alt="Github" title="Repository auf Github.com"> </a> </li> <li> <a href="https://codefor.de/" target="_blank" rel="noopener" role="tab"> <img width="25px" style="padding-top: 8px;" src="img/okfnde.png" alt="ok lab" title="Code for Germany - eine Initiative von der Open Knowledge Foundation Germany"> </i> </a> </li> </ul> </div> <!-- Tab panes --> <div class="sidebar-content"> <div class="sidebar-pane" id="home"> <h1 class="sidebar-header"> farmshops.eu - Direktvermarkter-Karte <span class="sidebar-close"></span> </h1> <h3>Was ist das hier?</h3> <p>Diese Karte zeigt Direktvermarkter wie z.B. Hofläden, Wochenmärkte und Milch,- Eier- oder Essensautomaten, die auf <a href="https://www.openstreetmap.org" target="_blank" rel="noopener">openstreetmap.org</a> eingetragen sind und bereitet die Daten optisch auf. Fehlende Daten oder neue Höfe kann man direkt auf OpenStreetMap eintragen. Die Daten werden von dort regelmäßig abgeglichen. </p> <h3>Ich habe fehlende oder falsche Daten, wo kann ich die eintragen?</h3> <p> Alle Daten stammen von <a href="https://www.openstreetmap.org" target="_blank" rel="noopener">openstreetmap.org</a>. Es gibt zwei Möglichkeiten neue Orte einzutragen: <p> <a href="https://openstreetmap.org" target="_blank" rel="noopener" class="button">Auf OSM bearbeiten</a> <br>(Login notwendig)</p> <p> <a href="./contribute/index.html" class="button">Eintrag Vorschlagen</a> <br>(ohne Login möglich, erfahrene Mapper tragen die Daten für Dich ein. <a href="https://ent8r.github.io/NotesReview/?query=farmshops.eu&limit=100&start=true&map=6%2F50.7990%2F12.2168" target="_blank" rel="noopener">Hier findest Du alle unbearbeiteten Vorschläge</a>.)</p> <p> </p> </table> <p> <h3>Welche Einträge von Openstreetmap werden hier angezeigt?</h3> <p>Nur Orte mit folgenden Tags werden überhaupt angezeigt:</p> <p> <img src="img/h-pin2.png" alt="" style="width:100%; max-width: 40px;"> <a href="https://wiki.openstreetmap.org/wiki/DE:Tag:shop%3Dfarm" target="_blank" rel="noopener">shop=farm </a>für Hofläden und Direktvermarkter aller Art</p> <p> <img src="img/a-pin2.png" alt="" style="width:100%; max-width: 40px;"> <a href="https://wiki.openstreetmap.org/wiki/DE:Tag:amenity%3Dvending_machine" target="_blank" rel="noopener">amenity=vending_machine</a> für Verkaufsautomaten, jedoch nur mit: <ul> <li> <a href="https://wiki.openstreetmap.org/wiki/Tag:vending%3Dfood" target="_blank" rel="noopener">vending=food</a> Für Essen</li> <li> <a href="https://wiki.openstreetmap.org/wiki/Tag:vending%3Dmilk" target="_blank" rel="noopener">vending=milk</a> Für Milchautomaten</li> <li>Außerdem auch die vending-Einträge: eggs, tomatoes, cheese, sausages, potatoes, noodles, meat, honey, fruits</li> <li>Man kann auch mehrere angebotene Waren kombinieren, z.B. <i>vending=eggs;sausages;vegetables;cheese</i> </li> uvm. </ul> </p> <p> <img src="img/m-pin2.png" alt="" style="width:100%; max-width: 40px;"> <a href="https://wiki.openstreetmap.org/wiki/DE:Tag:amenity=marketplace" target="_blank" rel="noopener">amenity=marketplace</a> für Wochenmärkte</p> <p>Von all diesen Orte werden falls vorhanden alle weiteren Daten wie die Adresse oder die Öfnungszeiten im Popup angezeigt, wobei unbekante Tags in der Tabelle landen und teilweise Begriffe übersetzt werden.</p> <p>Folgende Tags werden im Popup formatiert dargestellt:</p> <p> <img src="img/popupbeispiel.png" style="width:100%; max-width: 300px;" alt=""> </p> <br> Offnungszeiten werden im <a href="https://wiki.openstreetmap.org/wiki/DE:Key:opening_hours#.C3.96ffnungszeiten_f.C3.BCr_Ulm.2C_Neu-Ulm_.26_Umgebung" target="_blank" rel="noopener">Openstreetmap-Format</a> angezeigt. Darunter findet man einen grünen oder roten Text der angibt, ob die Einrichtung im Moment offen oder geschlossen ist. Jedoch werden Öffnungszeiten momentan nur ausgewertet, wenn sie keine (länderspezifischen) Schulferien enthalten. </p> <p> <h3>Wie häufig werden die Daten abgeglichen und welchen Stand haben sie jetzt gerade?</h3> Momentan werden die Daten mit <a href="https://github.com/CodeforKarlsruhe/direktvermarkter/blob/master/update_data.js" target="_blank" rel="noopener">einem Script</a> manuell in regelmäßigen Abständen&#8482; abgeglichen. Ein automatischer Abgleich ist geplant. <p> <script> document.write(lastUpdate); </script> </p> </p> <p> <h3>Wie erreiche ich euch?</h3> <ul> <li>Auf der Webseite von <a href="https://codefor.de/karlsruhe/">Code for Karlsruhe</a> gibt es Kontaktdaten und Infos zu den regelmäßigen Treffen. </li> <li>Den Quellcode und technische Planung gibt es auf <a href="https://github.com/CodeforKarlsruhe/direktvermarkter" target="_blank" rel="noopener">GitHub</a> </li> <li>Für generelle Fragen kann man eine Mail an <a href="mailto:farmshops@posteo.eu">farmshops@posteo.eu</a> schreiben.</li> <li> <a href="http://stefan.grotz.me/" target="_blank" rel="noopener">Stefan Grotz</a> koordiniert das Projekt und kann auch direkt angeschrieben werden.</li> </ul> </p> <p> <h3>Was gibt es für verwandte Projekte?</h3> Folgende Seiten könnten für Nutzer dieser Seite auch interessant sein: <p> <ul> <li>Genaue Daten zu Wochenmärkten findet man bequem für viele Städte auf <a href="https://wo-ist-markt.de" target="_blank" rel="noopener">wo-ist-markt.de</a>. </li> <li>Kräuter und andere öffentlich zugängliche Nahrungsmittel findet man auf <a href="https://mundraub.org/" target="_blank" rel="noopener">mundraub.org</a> </li> <li>Bei <a href="https://marktschwaermer.de/de" target="_blank" rel="noopener"> Marktschwärmer/Food Assembly</a> organisieren sich Kunden und bestellen als Gruppe bei regionalen Erzeuger.</li> </ul> </p> </div> <div class="sidebar-pane" id="info"> <h1 class="sidebar-header">Impressum und Datenschutz <span class="sidebar-close"></span> </h1> <img src="img/codeforkarlsruhe.png" alt="Logo Code for Karlsruhe" width="200px" style="display: block;margin-left: auto;margin-right: auto"> <p> <strong>farmshops.eu</strong> ist ein Projekt von <a href="https://codefor.de/karlsruhe/" target="_blank" rel="noopener">Code for Karlsruhe</a>. Die Karte bereitet Daten von Openstreetmap optisch auf und hilft bei der Pflege.</p> <p> Diese Seite befindet sich momentan noch im Aufbau, ein ausführlicheres Impressum folgt bald. <br> Kontakt: <a href="mailto:farmshops@posteo.eu">farmshops@posteo.eu</a> </p> <h2>Copyright</h2> <p>Die Karte selbst steht unter einer MIT Lizenz und der Quellcodde ist auf Github zu finden.</p> <p>Die Icons auf der Karte stehen unter der Creative Commons CCBY und wurden an den Rändern leicht beschnitten. <ul> <li>Der Bauernhof Icon ist von Nociconist erstellt <a href="https://thenounproject.com/icon/1549496/#">Mehr Informationen zum Icon bei the noun project</a> </li> <li>Das Automaten-Icon wurde von Ben Davis erstellt <a href="https://thenounproject.com/icon/909556/#">Mehr Informationen zum Icon bei the noun project </a> </li> <li>Das Markt-Icon wurde von İsmail Nural erstellt <a href="https://thenounproject.com/icon/195153/#">Mehr Informationen zum Icon bei the noun project </a> </li> </ul> <p> <h2>Datenschutz</h2> Wir speichern keinerlei Daten über unsere Benutzer und erheben keine Statistik über die Zugriffe und speichern soweit möglich alle Abhängigkeiten auf dem eigenen Server. <p>Folgende externe Anbieter werden u.U. beim Aufruf der Seite angesprochen: </p> <ul> <li>Die Seite ist auf den Servern von github.com gehostet.</li> <li>Die Karten im Hintergrund werden von folgenden Servern gezogen: <ul> <li>maps.wikimedia.org (Standardeinstellung)</li> <li>tile.openstreetmap.org (Openstreetmap Optik)</li> <li>server.arcgisonline.com/ (Satelitenbild)</li> </ul> </li> <li>Es werden die Suchstatistiken von Google, Bing und Yandex ausgewertet, die jedoch komplett anonymisiert sind.</li> <li>Die auf der Karte angezeigten Daten stammen von Openstreetmap und dürfen nur öffentlich zugängliche Daten enthalten. Falls in diesen Datenbestand sensible oder geschützte Daten auftauchen löschen wir diese nach Kenntnissnahme natürlich sofort aus dieser Webseite und helfen darüber hinaus gerne dabei diese aus den Datenbestand von OSM zu löschen. Siehe dazu auch die <a href="https://wiki.openstreetmap.org/wiki/DE:Datenschutz">Datenschutzbestimmungen von Openstreetmap</a> </li> </ul> </p> </p> </div> </div> </div> <div id="map" class="sidebar-map"></div> <script src="js/leaflet.js"></script> <script src="js/leaflet.permalink.min.js"></script> <script src="js/jquery-3.3.1.js"></script> <link rel="stylesheet" href="css/leaflet.extra-markers.min.css"> <script src="js/leaflet.extra-markers.min.js"></script> <script src="js/leaflet.markercluster.js"></script> <script src="js/leaflet-sidebar.js"></script> <script src="js/L.Control.Locate.min.js"></script> <script src="js/opening_hours+deps.min.js"></script> <script src="js/popupcontent.js"></script> <script src="js/direktvermarkter.js"></script> </body> </html>
65.195918
467
0.558255
dcf69c4467c4a7d0ef45201bd357fe971687c06a
1,944
swift
Swift
RAGVersionNumber/Classes/AppStoreLookup/AppStoreLookupResultParser.swift
raginmari/RAGVersionNumber
58eaf86b08c9bb7a55ca1c62caa4f058d4532422
[ "MIT" ]
null
null
null
RAGVersionNumber/Classes/AppStoreLookup/AppStoreLookupResultParser.swift
raginmari/RAGVersionNumber
58eaf86b08c9bb7a55ca1c62caa4f058d4532422
[ "MIT" ]
null
null
null
RAGVersionNumber/Classes/AppStoreLookup/AppStoreLookupResultParser.swift
raginmari/RAGVersionNumber
58eaf86b08c9bb7a55ca1c62caa4f058d4532422
[ "MIT" ]
null
null
null
// // AppStoreLookupResultParser.swift // Pods // // Created by Reimar Twelker on 12.10.17. // // import Foundation typealias JSONObject = [String: Any] public protocol AppStoreLookupResultParsing { /// Parses a version string from the given iTunes lookup JSON object. /// /// - Parameter fromJSON: a JSON dictionary received from an iTunes lookup request /// - Returns: the version string in the given JSON /// - Throws: AppStoreLookupResultParserError if the JSON is of an unsupported format or the version string cannot be found func parseVersionString(fromJSON: [String: Any]) throws -> String } class AppStoreLookupResultParser: AppStoreLookupResultParsing { private enum JSONKeys { static let resultCount = "resultCount" static let results = "results" static let version = "version" } func parseVersionString(fromJSON jsonObject: [String: Any]) throws -> String { guard !jsonObject.isEmpty else { throw AppStoreLookupResultParserError.unsupportedFormat } guard let numberOfResults = jsonObject[JSONKeys.resultCount] as? NSNumber else { throw AppStoreLookupResultParserError.unsupportedFormat } guard let resultsArray = jsonObject[JSONKeys.results] as? Array<JSONObject> else { throw AppStoreLookupResultParserError.unsupportedFormat } guard numberOfResults.intValue > 0 else { throw AppStoreLookupResultParserError.notFound } guard numberOfResults.intValue < 2 else { throw AppStoreLookupResultParserError.notUnique } let result = resultsArray[0]; guard let versionString = result[JSONKeys.version] as? String else { throw AppStoreLookupResultParserError.unsupportedFormat } return versionString } }
31.354839
127
0.664609
5be68d3ebb511e3fd46e39a0b7c564c9422cf514
1,437
cs
C#
Blazor.Mvvm/src/Blazor.Mvvm.Core/ViewModels/ViewModelBase.cs
enisn/Blazor.Mvvm
7ec71b78a33e2652e9bc3f68c2243e877f4886ae
[ "MIT" ]
null
null
null
Blazor.Mvvm/src/Blazor.Mvvm.Core/ViewModels/ViewModelBase.cs
enisn/Blazor.Mvvm
7ec71b78a33e2652e9bc3f68c2243e877f4886ae
[ "MIT" ]
null
null
null
Blazor.Mvvm/src/Blazor.Mvvm.Core/ViewModels/ViewModelBase.cs
enisn/Blazor.Mvvm
7ec71b78a33e2652e9bc3f68c2243e877f4886ae
[ "MIT" ]
1
2021-08-17T03:03:26.000Z
2021-08-17T03:03:26.000Z
using Blazor.Mvvm.Core.Abstractions.Binding; using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Runtime.CompilerServices; using System.Text; using System.Threading.Tasks; namespace Blazor.Mvvm.Core.ViewModels { public class ViewModelBase : QueryBinderBase, INotifyPropertyChanged, IViewModelBase { private bool isBusy; public bool IsBusy { get => isBusy; set => SetProperty(ref isBusy, value); } // Observer Pattern public event PropertyChangedEventHandler PropertyChanged; public virtual Task InitializeAsync() { return Task.CompletedTask; } /// <summary> /// Raises <see cref="PropertyChanged"/> event with called member name. /// </summary> /// <param name="memberName">Caller member name.</param> public void OnPropertyChanged([CallerMemberName]string memberName = null) => PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(memberName)); protected bool SetProperty<T>(ref T backingStore, T value, [CallerMemberName]string propertyName = "", Action onChanged = null) { if (EqualityComparer<T>.Default.Equals(backingStore, value)) return false; backingStore = value; onChanged?.Invoke(); OnPropertyChanged(propertyName); return true; } } }
32.659091
157
0.665275
0583cdddec6daa23c7e993cf7c3b11932e9a7929
10,517
kt
Kotlin
MarqueeViewLib/src/main/java/com/libs/nelson/marqueeviewlib/MarqueeView.kt
nelson1110/MarqueeView
3b3afb33b55825876a0aa040c561c43fd9ee766d
[ "Apache-2.0" ]
5
2018-06-28T06:12:04.000Z
2020-06-24T14:24:47.000Z
MarqueeViewLib/src/main/java/com/libs/nelson/marqueeviewlib/MarqueeView.kt
nelson1110/MarqueeView
3b3afb33b55825876a0aa040c561c43fd9ee766d
[ "Apache-2.0" ]
null
null
null
MarqueeViewLib/src/main/java/com/libs/nelson/marqueeviewlib/MarqueeView.kt
nelson1110/MarqueeView
3b3afb33b55825876a0aa040c561c43fd9ee766d
[ "Apache-2.0" ]
1
2018-06-28T02:47:29.000Z
2018-06-28T02:47:29.000Z
package com.libs.nelson.marqueeviewlib import android.animation.Animator import android.animation.ValueAnimator import android.content.Context import android.support.v7.widget.LinearLayoutCompat import android.util.AttributeSet import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.LinearLayout class MarqueeView : ViewGroup { private val mMaxWidth = Integer.MAX_VALUE private val mMaxHeight = Integer.MAX_VALUE private val DIRTY_TAG = "DIRTY" private var mItemLayout = -1 private var mOrientation = LinearLayout.VERTICAL private var mIsReverse = false private var mAnimatorRunnable: AnimatorRunnable? = null private var mAnimationPercent = 0f private var mDefaultAnimationDuration = 1000L private var mDefaultItemStayDuration = 1000L private var mAdapter: MarqueeView.MarqueeViewAdapter? = null private val mItemViewCache = ArrayList<View>() constructor(context: Context?) : this(context, null) constructor(context: Context?, attrs: AttributeSet?) : this(context, attrs, 0) constructor(context: Context?, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr) { val a = context?.obtainStyledAttributes( attrs, R.styleable.MarqueeView, defStyleAttr, 0) val index = a?.getInt(R.styleable.MarqueeView_orientation, -1) index?.let { if (index >= 0) { setOrientation(index) } } val animatorDuration = a?.getInt(R.styleable.MarqueeView_animator_duration, 1000) val stayDuration = a?.getInt(R.styleable.MarqueeView_stay_duration, 1000) animatorDuration?.let { mDefaultAnimationDuration = it.toLong() } stayDuration?.let { mDefaultItemStayDuration = it.toLong() } a?.getBoolean(R.styleable.MarqueeView_reverse_animator, false)?.let { mIsReverse = it } a?.recycle() } override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) { super.onMeasure(widthMeasureSpec, heightMeasureSpec) val childCount = childCount val widthSize = View.MeasureSpec.getSize(widthMeasureSpec) val heightSize = View.MeasureSpec.getSize(heightMeasureSpec) val ps = paddingStart val pe = paddingEnd val pt = paddingTop val pb = paddingBottom var childMaxWidth = 0 var childMaxHeight = 0 var child: View for (i in 0 until childCount) { child = getChildAt(i) if (child.visibility == View.GONE) { continue } child.measure(View.MeasureSpec.makeMeasureSpec(widthSize - ps - pe, MeasureSpec.getMode(widthMeasureSpec)), View.MeasureSpec.makeMeasureSpec(heightSize - pt - pb, View.MeasureSpec.getMode(heightMeasureSpec))) childMaxWidth = Math.max(childMaxWidth, child.measuredWidth) childMaxHeight = Math.max(childMaxHeight, child.measuredHeight) } val width = resolveAdjustedSize(childMaxWidth + ps + pe, mMaxWidth, widthMeasureSpec) val height = resolveAdjustedSize(childMaxHeight + pt + pb, mMaxHeight, heightMeasureSpec) val finalWidthSpec = View.MeasureSpec.makeMeasureSpec(width, View.MeasureSpec.getMode(widthMeasureSpec)) val finalHeightSpec = View.MeasureSpec.makeMeasureSpec(height, View.MeasureSpec.getMode(heightMeasureSpec)) setMeasuredDimension(finalWidthSpec, finalHeightSpec) } private fun resolveAdjustedSize(desiredSize: Int, maxSize: Int, measureSpec: Int): Int { var result = desiredSize val specMode = View.MeasureSpec.getMode(measureSpec) val specSize = View.MeasureSpec.getSize(measureSpec) when (specMode) { View.MeasureSpec.UNSPECIFIED -> /* Parent says we can be as big as we want. Just don't be larger than max size imposed on ourselves. */ result = Math.min(desiredSize, maxSize) View.MeasureSpec.AT_MOST -> // Parent says we can be as big as we want, up to specSize. // Don't be larger than specSize, and don't be larger than // the max size imposed on ourselves. result = Math.min(Math.min(desiredSize, specSize), maxSize) View.MeasureSpec.EXACTLY -> // No choice. Do what we are told. result = specSize } return result } override fun onLayout(changed: Boolean, l: Int, t: Int, r: Int, b: Int) { if (childCount == 0) { return } if (childCount == 1) { val child = getChildAt(0) child.layout(paddingLeft, paddingTop, paddingLeft + child.measuredWidth, paddingTop + child.measuredHeight) return } var child0 = getChildAt(0) var child1 = getChildAt(1) if (mIsReverse) { child1 = getChildAt(0) child0 = getChildAt(1) } if (mOrientation == LinearLayout.VERTICAL) { child0.layout(paddingLeft, paddingTop - (child0.measuredHeight * mAnimationPercent).toInt() , paddingLeft + child0.measuredWidth, paddingTop + child0.measuredHeight - (child0.measuredHeight * mAnimationPercent).toInt()) child1.layout(paddingLeft, paddingTop + child0.measuredHeight - (child1.measuredHeight * mAnimationPercent).toInt(), paddingLeft + child1.measuredWidth, paddingTop + child0.measuredHeight + child1.measuredHeight - (child1.measuredHeight * mAnimationPercent).toInt()) } else { child0.layout(paddingLeft - (child0.measuredWidth * mAnimationPercent).toInt(), paddingTop, paddingLeft + child0.measuredWidth - (child0.measuredWidth * mAnimationPercent).toInt(), paddingTop + child0.measuredHeight) child1.layout(paddingLeft + child0.measuredWidth - (child0.measuredWidth * mAnimationPercent).toInt(), paddingTop, paddingLeft + child0.measuredWidth + child1.measuredWidth - (child1.measuredWidth * mAnimationPercent).toInt(), paddingTop + child1.measuredHeight) } } fun setOrientation(@LinearLayoutCompat.OrientationMode orientation: Int) { if (mOrientation != orientation) { mOrientation = orientation requestLayout() } } inner class AnimatorRunnable : Runnable { private val valueAnimator = ValueAnimator.ofFloat(0f, 1f) private var currentPosition = 0 override fun run() { mAdapter?.let { valueAnimator.duration = 0 valueAnimator.addUpdateListener { animation -> val normalPercent = animation.animatedValue.toString().toFloat() mAnimationPercent = if (mIsReverse) { 1 - normalPercent } else { normalPercent } requestLayout() } valueAnimator.addListener(object : Animator.AnimatorListener { override fun onAnimationRepeat(animation: Animator?) { } override fun onAnimationCancel(animation: Animator?) { currentPosition = 0 } override fun onAnimationEnd(animation: Animator?) { if (childCount > 1) { removeViewAt(0) } currentPosition++ if (currentPosition >= it.getItemCount()) { currentPosition = 0 } valueAnimator.start() } override fun onAnimationStart(animation: Animator?) { valueAnimator.startDelay = mDefaultItemStayDuration valueAnimator.duration = mDefaultAnimationDuration for (i in 0 until childCount) { val item = getChildAt(i) item?.let { if (item.tag == DIRTY_TAG) { removeView(item) } } } if (currentPosition < it.getItemCount()) { addView(getItemView(it.getItemLayout(), currentPosition)) } } }) if (!valueAnimator.isStarted) { valueAnimator.start() } } } fun stop() { removeCallbacks(this) if (valueAnimator.isStarted) { valueAnimator.cancel() } valueAnimator.removeAllListeners() valueAnimator.removeAllUpdateListeners() for (i in 0 until childCount) { getChildAt(i).tag = DIRTY_TAG } } } private fun reset() { mAnimatorRunnable?.stop() mAnimationPercent = 0f mAnimatorRunnable = AnimatorRunnable() mItemViewCache.clear() } override fun onAttachedToWindow() { super.onAttachedToWindow() reset() post(mAnimatorRunnable) } override fun onDetachedFromWindow() { super.onDetachedFromWindow() mAnimatorRunnable?.stop() } private fun getItemView(layout: Int, position: Int): View { if (layout != mItemLayout) { mItemViewCache.clear() removeAllViews() mItemLayout = layout } var finalItem: View? = mItemViewCache.find { it.parent == null } finalItem ?: let { val itemView = LayoutInflater.from(context).inflate(layout, this, false) mItemViewCache.add(itemView) finalItem = itemView } mAdapter?.onBindItemView(finalItem!!, position) return finalItem!! } fun setAdapter(adapter: MarqueeViewAdapter) { mAdapter = adapter reset() } abstract class MarqueeViewAdapter { abstract fun getItemLayout(): Int abstract fun onBindItemView(itemView: View, position: Int) abstract fun getItemCount(): Int } }
36.265517
220
0.589427
9c20d98581f06c7c397e8cc7399cd45a54e35bb2
413
hpp
C++
include/game.hpp
berkobra/2048-cli
f8798055dc5e01898f8feaf696c6365df233355c
[ "MIT" ]
2
2019-09-06T16:46:31.000Z
2019-09-14T18:15:09.000Z
include/game.hpp
berkobra/2048-cli
f8798055dc5e01898f8feaf696c6365df233355c
[ "MIT" ]
2
2017-08-04T10:59:39.000Z
2017-08-04T11:04:06.000Z
include/game.hpp
berkobra/2048-cli
f8798055dc5e01898f8feaf696c6365df233355c
[ "MIT" ]
1
2019-09-06T16:46:38.000Z
2019-09-06T16:46:38.000Z
#ifndef GAME_H #define GAME_H #include "grid.hpp" #include "view.hpp" #include "controller.hpp" //const unsigned game_size = 4; //const unsigned win_condition = 2048; extern const unsigned game_size; extern const unsigned win_condition; class Game { public: Game(); ~Game(); void run(); private: Grid grid; Controller controller; View view; bool isWon(); bool isLost(); }; #endif /* GAME_H */
15.296296
38
0.697337
42e8b7367e127c55199891e817faaa872b1f6894
302
asm
Assembly
programs/oeis/180/A180447.asm
karttu/loda
9c3b0fc57b810302220c044a9d17db733c76a598
[ "Apache-2.0" ]
null
null
null
programs/oeis/180/A180447.asm
karttu/loda
9c3b0fc57b810302220c044a9d17db733c76a598
[ "Apache-2.0" ]
null
null
null
programs/oeis/180/A180447.asm
karttu/loda
9c3b0fc57b810302220c044a9d17db733c76a598
[ "Apache-2.0" ]
null
null
null
; A180447: n appears 3n+1 times. ; 0,1,1,1,1,2,2,2,2,2,2,2,3,3,3,3,3,3,3,3,3,3,4,4,4,4,4,4,4,4,4,4,4,4,4,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,8,8,8,8,8,8,8,8,8,8,8,8,8 lpb $0,1 sub $0,1 add $1,3 trn $0,$1 lpe div $1,3
30.2
211
0.516556
dffe348cb24f4dc58dcf30188a6225e605cf359e
337
dart
Dart
fluid_clock/test/test_utils.dart
gilmarsquinelato/fluid_clock
64ce3be8cf6ad1010b2de7f8857f4d18a9e2d03a
[ "BSD-3-Clause" ]
null
null
null
fluid_clock/test/test_utils.dart
gilmarsquinelato/fluid_clock
64ce3be8cf6ad1010b2de7f8857f4d18a9e2d03a
[ "BSD-3-Clause" ]
null
null
null
fluid_clock/test/test_utils.dart
gilmarsquinelato/fluid_clock
64ce3be8cf6ad1010b2de7f8857f4d18a9e2d03a
[ "BSD-3-Clause" ]
null
null
null
import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; void testSemantics(WidgetTester tester, String label, String value) { final finder = find.bySemanticsLabel(label); expect(finder, findsOneWidget); final widget = tester.widget<Semantics>(finder); expect(widget.properties.value, value); }
30.636364
69
0.777448
bb446abdf3c94a80c0e891a472f54dcbfbf81163
257
swift
Swift
tests/language-behaviour/compounds/00241-nested-single-compound.swift
ketancmaheshwari/swift-k
ec4f2acbf122536b1b09f77251cb0d00b508251c
[ "Apache-2.0" ]
99
2015-02-02T23:08:37.000Z
2021-09-26T18:28:28.000Z
tests/language-behaviour/compounds/00241-nested-single-compound.swift
ketancmaheshwari/swift-k
ec4f2acbf122536b1b09f77251cb0d00b508251c
[ "Apache-2.0" ]
8
2015-02-04T22:00:08.000Z
2019-01-02T17:02:39.000Z
tests/language-behaviour/compounds/00241-nested-single-compound.swift
ketancmaheshwari/swift-k
ec4f2acbf122536b1b09f77251cb0d00b508251c
[ "Apache-2.0" ]
26
2015-05-27T04:24:55.000Z
2022-03-12T12:37:09.000Z
type file; app (file t) greeting(string m) { echo m stdout=@filename(t); } (file first) compound() { first = greeting("f"); } (file first) compoundB() { first = compound(); } file a <"00241-nested-single-compound.out">; a = compoundB();
12.85
44
0.607004
0bb224e01ebd658b05fd1ae3164a24c7e6a95713
1,137
py
Python
baybars/timber.py
dkanarek12/baybars
72f4cff706c11d25ce537cf0fed61bc3ef89da30
[ "Apache-2.0" ]
9
2018-10-16T19:20:35.000Z
2020-06-02T13:27:29.000Z
baybars/timber.py
dkanarek12/baybars
72f4cff706c11d25ce537cf0fed61bc3ef89da30
[ "Apache-2.0" ]
10
2018-07-29T08:56:18.000Z
2019-03-21T18:31:15.000Z
baybars/timber.py
dkanarek12/baybars
72f4cff706c11d25ce537cf0fed61bc3ef89da30
[ "Apache-2.0" ]
9
2018-07-29T08:59:53.000Z
2019-12-31T07:50:57.000Z
# Copyright 2018 Jet.com # # 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 logging import sys def get_logger(name): logger = logging.getLogger(name) stream_stdout = logging.StreamHandler(sys.stdout) stream_stdout.setLevel(logging.INFO) stream_stderr = logging.StreamHandler(sys.stderr) stream_stderr.setLevel(logging.ERROR) formatter = logging.Formatter('[baybars][%(name)s][%(asctime)s][%(levelname)s]:%(message)s') stream_stdout.setFormatter(formatter) stream_stderr.setFormatter(formatter) logger.addHandler(stream_stdout) logger.addHandler(stream_stderr) logger.setLevel(logging.INFO) return logger
33.441176
94
0.769569
7ec35ede6f01f11920b7d91af5f6fbab6f72b950
1,034
swift
Swift
SketchyCodeTests/Helpers.swift
Raizlabs/SketchyCode
999fd6ee14ab192cc4487939c7ffb7e352faea25
[ "MIT" ]
10
2017-05-31T16:20:34.000Z
2018-06-14T11:59:09.000Z
SketchyCodeTests/Helpers.swift
Rightpoint/SketchyCode
999fd6ee14ab192cc4487939c7ffb7e352faea25
[ "MIT" ]
4
2017-05-31T16:26:43.000Z
2017-09-21T00:34:11.000Z
SketchyCodeTests/Helpers.swift
Raizlabs/SketchyCode
999fd6ee14ab192cc4487939c7ffb7e352faea25
[ "MIT" ]
3
2017-05-31T16:20:35.000Z
2018-06-15T09:33:28.000Z
// // Helpers.swift // SketchyCode // // Created by Brian King on 9/19/17. // Copyright © 2017 Brian King. All rights reserved. // import XCTest struct GenericTestFailure: Error { let description: String } extension Optional { struct UnexpectedNil: Error {} struct InvalidCast: Error {} func unwrapped(file: StaticString = #file, line: UInt = #line) throws -> Wrapped { guard case .some(let value) = self else { XCTFail("Unexpected nil", file: file, line: line) throw UnexpectedNil() } return value } func unwrapped<T>(as type: T.Type, file: StaticString = #file, line: UInt = #line) throws -> T { guard case .some(let value) = self else { XCTFail("Unexpected nil", file: file, line: line) throw UnexpectedNil() } guard let typedValue = value as? T else { XCTFail("Unable to cast to \(type)", file: file, line: line) throw InvalidCast() } return typedValue } }
26.512821
100
0.592843
2f18cd363b53c207f5bc02ad3c6dd37a83182aaf
649
java
Java
src/main/java/com/chuhelan/netex/service/OrderService.java
SSF-Team/NeTEx
d2ef31dc52ba9fe096839c7c76d1a6591e33463d
[ "MIT" ]
1
2021-05-24T02:13:19.000Z
2021-05-24T02:13:19.000Z
src/main/java/com/chuhelan/netex/service/OrderService.java
SSF-Team/NeTEx
d2ef31dc52ba9fe096839c7c76d1a6591e33463d
[ "MIT" ]
null
null
null
src/main/java/com/chuhelan/netex/service/OrderService.java
SSF-Team/NeTEx
d2ef31dc52ba9fe096839c7c76d1a6591e33463d
[ "MIT" ]
null
null
null
package com.chuhelan.netex.service; import com.chuhelan.netex.domain.Order; import com.chuhelan.netex.domain.OrderUser; import com.chuhelan.netex.domain.User; public interface OrderService { public Order getOrder(String id); public void deleteOrder(String id); public void assignCourier(String oid, Integer cid); public void CreateOrder(String id, Integer createID, OrderUser sender, OrderUser delivery, String marks, String type); public Order[] getOrderByType(User user, String type); public void checkOrder(String OrderID); public Order[] getOrderNotSend(Integer uid); public void checkPassOrder(String oid); }
36.055556
122
0.768875
4ac06ff1749a4d4e195f97b90865c1a6c829eb40
147
cs
C#
Source/Container/Machine.Container/IStartable.cs
abombss/machine
9f5e3d3e7c06ff088bc2e4c9af0e0310cd6257b0
[ "MIT" ]
1
2016-05-08T16:10:57.000Z
2016-05-08T16:10:57.000Z
Source/Container/Machine.Container/IStartable.cs
benlovell/machine
5e01d6ca81909d12d6e9f7c4e72e0ee4242d23b1
[ "MIT" ]
null
null
null
Source/Container/Machine.Container/IStartable.cs
benlovell/machine
5e01d6ca81909d12d6e9f7c4e72e0ee4242d23b1
[ "MIT" ]
1
2021-07-13T07:20:53.000Z
2021-07-13T07:20:53.000Z
using System; using System.Collections.Generic; namespace Machine.Container { public interface IStartable { void Start(); } }
13.363636
34
0.673469
d28623fb3f910197047dbeadbc4dfa7220c6ae17
2,384
php
PHP
tests/Fibonacci/FibonacciTest.php
rudragoudpatil/tdd
e6977b0609d146aeab2801dead49186290d553bd
[ "MIT" ]
null
null
null
tests/Fibonacci/FibonacciTest.php
rudragoudpatil/tdd
e6977b0609d146aeab2801dead49186290d553bd
[ "MIT" ]
null
null
null
tests/Fibonacci/FibonacciTest.php
rudragoudpatil/tdd
e6977b0609d146aeab2801dead49186290d553bd
[ "MIT" ]
null
null
null
<?php /** * Created by PhpStorm. * User: techjini * Date: 27/9/18 * Time: 3:55 PM */ namespace Fibonacci; use AppBundle\Fibonacci\Fibonacci; use PHPUnit\Framework\TestCase; class FibonacciTest extends TestCase { public function testFibanocciZero() { //Arrange $expectedValue = 0; $fibanocciTestInstance = new Fibonacci(); //Act $actualValue = $fibanocciTestInstance->getFibanocciResult(0); //Assert $this->assertSame($expectedValue, $actualValue); } public function testFibanocciOne() { //Arrange $expectedValue = 1; $fibanocciTestInstance = new Fibonacci(); //Act $actualValue = $fibanocciTestInstance->getFibanocciResult(1); //Assert $this->assertSame($expectedValue, $actualValue); } public function testFibanocciTwo() { //Arrange $expectedValue = 2; $fibanocciTestInstance = new Fibonacci(); //Act $actualValue = $fibanocciTestInstance->getFibanocciResult(2); //Assert $this->assertSame($expectedValue, $actualValue); } public function testFibanocciThree() { //Arrange $expectedValue = 4; $fibanocciTestInstance = new Fibonacci(); //Act $actualValue = $fibanocciTestInstance->getFibanocciResult(3); //Assert $this->assertSame($expectedValue, $actualValue); } public function testFibanocciFour() { //Arrange $expectedValue = 7; $fibanocciTestInstance = new Fibonacci(); //Act $actualValue = $fibanocciTestInstance->getFibanocciResult(4); //Assert $this->assertSame($expectedValue, $actualValue); } public function testFibanocciFive() { //Arrange $expectedValue = 12; $fibanocciTestInstance = new Fibonacci(); //Act $actualValue = $fibanocciTestInstance->getFibanocciResult(5); //Assert $this->assertSame($expectedValue, $actualValue); } public function testFibanocciSix() { //Arrange $expectedValue = 20; $fibanocciTestInstance = new Fibonacci(); //Act $actualValue = $fibanocciTestInstance->getFibanocciResult(6); //Assert $this->assertSame($expectedValue, $actualValue); } }
22.280374
69
0.603607
85d69c0044f6999556991fb7057a70751b935e47
146
js
JavaScript
components/SectionContainer.js
zhuganglie/nextblog
fb0c4e61d5814e4ee524e1d288e84e675fb32fb2
[ "MIT" ]
null
null
null
components/SectionContainer.js
zhuganglie/nextblog
fb0c4e61d5814e4ee524e1d288e84e675fb32fb2
[ "MIT" ]
null
null
null
components/SectionContainer.js
zhuganglie/nextblog
fb0c4e61d5814e4ee524e1d288e84e675fb32fb2
[ "MIT" ]
null
null
null
export default function SectionContainer({ children }) { return <div className="flex flex-col mx-auto h-screen min-h-screen">{children}</div> }
36.5
86
0.739726
80b0d33677c54d453ba6086956f5c54a59034191
2,507
java
Java
sample-service/src/main/java/cc/before30/home/sample/service/order/OrderMapper.java
before30/grpcex
d247fc77b2c994674aaa2fb01feb0cf7651a5da0
[ "MIT" ]
null
null
null
sample-service/src/main/java/cc/before30/home/sample/service/order/OrderMapper.java
before30/grpcex
d247fc77b2c994674aaa2fb01feb0cf7651a5da0
[ "MIT" ]
null
null
null
sample-service/src/main/java/cc/before30/home/sample/service/order/OrderMapper.java
before30/grpcex
d247fc77b2c994674aaa2fb01feb0cf7651a5da0
[ "MIT" ]
null
null
null
package cc.before30.home.sample.service.order; import cc.before30.home.sample.domain.order.Order; import cc.before30.home.sample.domain.order.OrderLineItem; import cc.before30.home.sample.domain.order.OrderOption; import cc.before30.home.sample.domain.order.OrderOptionGroup; import cc.before30.home.sample.domain.shop.Menu; import cc.before30.home.sample.domain.shop.MenuRepository; import cc.before30.home.sample.domain.shop.Shop; import cc.before30.home.sample.domain.shop.ShopRepository; import org.springframework.stereotype.Component; import java.util.stream.Collectors; import static java.util.stream.Collectors.toList; /** * OrderMapper * * @author before30 * @since 2019-06-23 */ @Component public class OrderMapper { private MenuRepository menuRepository; private ShopRepository shopRepository; public OrderMapper(MenuRepository menuRepository, ShopRepository shopRepository) { this.menuRepository = menuRepository; this.shopRepository = shopRepository; } public Order mapFrom(Cart cart) { Shop shop = shopRepository.findById(cart.getShopId()) .orElseThrow(IllegalArgumentException::new); return new Order( cart.getUserId(), shop.getId(), cart.getCartLineItem() .stream() .map(this::toOrderLineItem) .collect(toList())); } private OrderLineItem toOrderLineItem(Cart.CartLineItem cartLineItem) { Menu menu = menuRepository.findById(cartLineItem.getMenuId()) .orElseThrow(IllegalArgumentException::new); return new OrderLineItem( menu.getId(), cartLineItem.getName(), cartLineItem.getCount(), cartLineItem.getGroups() .stream() .map(this::toOrderOptionGroup) .collect(Collectors.toList())); } private OrderOptionGroup toOrderOptionGroup(Cart.CartOptionGroup cartOptionGroup) { return new OrderOptionGroup( cartOptionGroup.getName(), cartOptionGroup.getOptions() .stream() .map(this::toOrderOption) .collect(Collectors.toList())); } private OrderOption toOrderOption(Cart.CartOption cartOption) { return new OrderOption( cartOption.getName(), cartOption.getPrice()); } }
32.986842
87
0.641803
87481592efe501b4ef18b7147674896bf4acabc7
546
asm
Assembly
programs/oeis/207/A207166.asm
jmorken/loda
99c09d2641e858b074f6344a352d13bc55601571
[ "Apache-2.0" ]
1
2021-03-15T11:38:20.000Z
2021-03-15T11:38:20.000Z
programs/oeis/207/A207166.asm
jmorken/loda
99c09d2641e858b074f6344a352d13bc55601571
[ "Apache-2.0" ]
null
null
null
programs/oeis/207/A207166.asm
jmorken/loda
99c09d2641e858b074f6344a352d13bc55601571
[ "Apache-2.0" ]
null
null
null
; A207166: Number of n X 5 0..1 arrays avoiding 0 0 0 and 1 0 1 horizontally and 0 0 1 and 1 0 1 vertically. ; 13,169,624,1612,3445,6513,11284,18304,28197,41665,59488,82524,111709,148057,192660,246688,311389,388089,478192,583180,704613,844129,1003444,1184352,1388725,1618513,1875744,2162524,2481037,2833545,3222388,3649984 mov $2,$0 mov $0,1 mul $0,$2 add $0,2 mov $3,$2 mul $3,2 add $3,3 lpb $0 sub $0,1 sub $1,$1 sub $1,$4 add $1,1 sub $4,$0 lpe mov $0,$3 mul $0,-3 add $1,1 pow $1,2 add $1,$3 add $1,$0 sub $1,3 mul $1,13 add $1,13
20.222222
213
0.679487
4ff608dfce1feda202f32570862e0208330de5d7
50,293
dart
Dart
lib/Widget/DashBorad/dashboard_list_item_widget.dart
Pratyush12345/Sales-App
b09148fe58314ba613b55b60d66e1e4bf5c90812
[ "Apache-2.0" ]
null
null
null
lib/Widget/DashBorad/dashboard_list_item_widget.dart
Pratyush12345/Sales-App
b09148fe58314ba613b55b60d66e1e4bf5c90812
[ "Apache-2.0" ]
null
null
null
lib/Widget/DashBorad/dashboard_list_item_widget.dart
Pratyush12345/Sales-App
b09148fe58314ba613b55b60d66e1e4bf5c90812
[ "Apache-2.0" ]
null
null
null
import 'package:flutter/material.dart'; import 'package:pozitive/Core/AppConstact/appConstant.dart'; import 'package:pozitive/Core/AppConstact/appString.dart'; import 'package:pozitive/Core/AppConstact/assetApp.dart'; import 'package:pozitive/Core/AppConstact/sizeConfig.dart'; import 'package:pozitive/Core/Model/Api/Group-Refresh-Req-Requote.dart'; import 'package:pozitive/Core/Model/Api/Refresh-RequestQuoteCredential.dart'; import 'package:pozitive/Core/Model/QuotationHistory_Pop-up.dart'; import 'package:pozitive/Core/Model/dashBoardDetailsDataModel.dart'; import 'package:pozitive/Core/Model/user.dart'; import 'package:pozitive/Core/ViewModel/dashboardViewModels/dashboard_list_item_viewmodel.dart'; import 'package:pozitive/Core/baseview.dart'; import 'package:pozitive/Pages/Group-Quotation/Group_quotation_page.dart'; import 'package:pozitive/Pages/ViewQuotationIndividual/ViewQuotation_page.dart'; //import 'package:custom_switch/custom_switch.dart'; import 'package:pozitive/Core/enums/view_state.dart'; import 'package:pozitive/Util/theme.dart'; import 'package:provider/provider.dart'; import 'package:pozitive/Pages/quotation_history_group_screen.dart'; import '../customswitch.dart'; import '../shapePopUp.dart'; import 'package:flutter/src/cupertino/button.dart'; import 'package:font_awesome_flutter/font_awesome_flutter.dart'; import 'package:pozitive/Widget/CustomPopUpMenuButton.dart'; class DashBoardListItemWidget extends StatefulWidget { final int index; final Lstgetdetail lstDetail; final String type; final String quoteId; final String title; final List<String> validUpToMsg; final String status; final DashBoardDetailDataModel dashBoardDetailDataModel; DashBoardListItemWidget({ this.lstDetail, this.index, this.type, this.quoteId, this.title, this.validUpToMsg, this.status, this.dashBoardDetailDataModel, }); @override _DashBoardListItemWidgetState createState() => _DashBoardListItemWidgetState(); } getDropDown() {} class _DashBoardListItemWidgetState extends State<DashBoardListItemWidget> { final ThemeApp themeApp = ThemeApp(); @override Widget build(BuildContext context) { User user = Provider.of<User>(context); return user.accountId != null ? BaseView<DashBoardItemViewModel>( onModelReady: (model) => model.getValidUptoMsg(widget.title), builder: (context, model, child) { if (model.state == ViewState.BUSY) { return AppConstant.circularProgressIndicator(); } return Column( children: <Widget>[ Container( color: widget.index.isOdd ? Colors.white : Color.fromRGBO(237, 243, 231, 1), child: Padding( padding: EdgeInsets.only( top: MediaQuery.of(context).size.height * 0.01, bottom: MediaQuery.of(context).size.height * 0.01), child: Row( children: <Widget>[ Expanded( flex: 1, child: Padding( padding: SizeConfig.innersidepadding, child: Text( widget.type == 'Individual' ? widget.lstDetail.intId.toString() : widget.lstDetail.intGroupId .toString(), style: TextStyle( color: Colors.black, fontSize: MediaQuery.of(context).size.width * 0.029), textAlign: TextAlign.start), )), Expanded( flex: 1, child: InkWell( child: Text( widget.type == 'Individual' ? (widget.lstDetail.businessName == null ? widget.lstDetail.strGroupname : widget.lstDetail.businessName) : (widget.lstDetail.businessName == null ? widget.lstDetail.businessName : widget.lstDetail.strGroupname), style: TextStyle( color: Colors.black, fontSize: MediaQuery.of(context).size.width * 0.029), textAlign: TextAlign.start), // onTap: () { // setState(() { // print(widget.lstDetail.validMsg.toString()); // }); // }, ), ), // Padding( // padding: EdgeInsets.only(left: 30), // ), widget.lstDetail.bteShowRefreshbutton == 1 && (widget.dashBoardDetailDataModel .bIsRestrictRefresh == false || (widget.dashBoardDetailDataModel .bIsRestrictRefresh == true && widget.lstDetail.dteQuotedDate .compareTo(widget .dashBoardDetailDataModel .dteRestrictRefreshDate) == -1)) ? CupertinoButton( // onPressed: () { // setState(() { // widget.viewlist[widget.index]["click"] = // !widget.viewlist[widget.index]["click"]; // }); // }, minSize: 16, padding: EdgeInsets.zero, // color: Colors.green, child: Icon( FontAwesomeIcons.syncAlt, color: Colors.black, size: 18, ), ) : Container(), Expanded( flex: 1, child: Row( mainAxisAlignment: MainAxisAlignment.end, children: <Widget>[ InkWell( child: Row( children: [ Image.asset( AppAssets.view, scale: 13, ), Text( AppString.view, style: TextStyle( fontWeight: FontWeight.bold, fontSize: MediaQuery.of(context) .size .width * 0.027, color: themeApp.purplecolor), ), ], ), onTap: () { if (widget.type.toLowerCase() == AppString.indvidual.toLowerCase()) { Navigator.push( context, MaterialPageRoute( builder: (context) => ViewQuotationPage( quoteID: widget .lstDetail.intId .toString(), title: widget.title, ))); } else { Navigator.of(context).push( new MaterialPageRoute( builder: (context) => GroupQuotationPagesTab( groupID: widget .lstDetail.intGroupId .toString(), quoteId: widget.quoteId, title: widget.title, status: widget.status, ))); print(widget.lstDetail.intGroupId); } }, ), Transform.scale( scale: .8, child: CustomSwitch( value: model.viewDetails, onChanged: (val) { model.onChangeDetailsValue( val, user.accountId, widget.type, widget.lstDetail.intId.toString(), context); setState(() { model.viewDetails = val; }); }, ), ), // Spacer(), Transform.scale( scale: .9, child: SizedBox( width: MediaQuery.of(context).size.width * .06, child: PopupMenuButton<QuotationPopupMenu>( padding: EdgeInsets.only(bottom: 0.5), color: Colors.deepPurple, shape: CustomRoundedRectangleBorders( borderHeight: MediaQuery.of(context).size.height * .05, borderRadius: BorderRadius.circular(15), ), onSelected: (val) { if (widget.type.toLowerCase() == AppString.indvidual.toLowerCase()) { if (val.history == AppString.MOVE_TO_QUOTED) { model.onMoveToQuote( user.accountId.toString(), widget.lstDetail.intId .toString(), widget.type, context); } if (val.history == AppString.REFRESH) { model.refreshReQuote( RefreshReQuoteCrential( accountId: user.accountId, quoteId: widget .lstDetail.intId .toString(), flagFrom: "manual", fuel: "Electricity", termType: "2")); if (model.success) { AppConstant.showSuccessToast( context, "Refresh"); } else { AppConstant.showFailToast( context, "Can't Refresh"); } } if (val.history == AppString.QUOTED_HISTORY) { model.getRequestQuoteHistoryDetails( user.accountId, widget.lstDetail.intId .toString(), widget.type, context); // Navigator.of(context).push( // new MaterialPageRoute( // builder: (context) => // QuotationHistoryScreen(), // ), // ); } } if (widget.type.toLowerCase() == AppString.group.toLowerCase()) { if (val.history == AppString.REFRESH) { model.groupRefreshReQuote( GroupRefreshReQuoteCrential( accountId: user.accountId, quoteId: widget.lstDetail.intId .toString(), )); if (model.success) { AppConstant.showSuccessToast( context, "Group Refresh"); } else { AppConstant.showFailToast( context, "Can't Refresh"); } } } if (val.history == AppString.MOVE_TO_QUOTED_Group) { model.onMoveToQuoteGroup( user.accountId.toString(), widget.type, widget.lstDetail.intGroupId .toString(), context); } if (val.history == AppString.QUOTED_HISTORY) { // if (type.toLowerCase() == // AppString.indvidual // .toLowerCase()) { // // model.getRequestQuoteHistoryDetails( // // user.accountId, // // lstDetail.intId.toString(), // // type, // // context); // Navigator.of(context).push( // new MaterialPageRoute( // builder: (context) => // ViewQuotationPage( // quoteID: lstDetail.intId // .toString(), // ), // ), // ); // } //here // on tap of view history if (widget.type.toLowerCase() == AppString.group.toLowerCase()) { model .getRequestQuoteHistoryGroupDetails( user.accountId, widget.lstDetail.intGroupId .toString(), widget.type, context); Navigator.of(context).push( new MaterialPageRoute( builder: (context) => QuotationHistoryGroupScreen( widget.index, widget.lstDetail.intGroupId .toString(), widget.type, ), // index, // '16141', // type), ), ); } } }, // itemBuilder: (BuildContext context) { // // return Column( // // // // ); // // }, itemBuilder: (BuildContext context) { return model.quotationHistory .map((quotationHistory) { return PopupMenuItem< QuotationPopupMenu>( value: quotationHistory, child: SizedBox( width: 500, child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Text( quotationHistory.history ?? // // ('${widget.lstDetail.validMsg ?? 'VALID UP TO'.split('-')[0]}' + // // '\n${widget.lstDetail.validMsg.substring(12)}') ?? ('${widget.lstDetail.validMsg.substring(0, 11)}' + '\n${widget.lstDetail.validMsg.substring(12, 31)}') ?? '', // ('${widget.lstDetail.validMsg ?? 'Valid Up To'}') ?? // 'Valid Up To', style: TextStyle( color: Colors.white, ), ), SizedBox( height: MediaQuery.of(context).size.height * 0.005, ), Container( width: 200, height: 1, color: Colors.white, ), SizedBox( height: MediaQuery.of(context).size.height * 0.002, ), Text( ('${widget.lstDetail.validMsg.substring(0, 11)}' + '\n${widget.lstDetail.validMsg.substring(12, 31)}'), style: TextStyle( color: Colors.white, ), ), SizedBox( height: MediaQuery.of(context).size.height * 0.005, ), Container( width: 200, height: 1, color: Colors.white, ), SizedBox( height: MediaQuery.of(context).size.height * 0.004, ), widget.lstDetail.bteShowRefreshbutton == 1 && (widget.dashBoardDetailDataModel .bIsRestrictRefresh == false || (widget.dashBoardDetailDataModel .bIsRestrictRefresh == true && widget.lstDetail.dteQuotedDate .compareTo(widget .dashBoardDetailDataModel .dteRestrictRefreshDate) == -1)) ? Row( children: [ CupertinoButton( onPressed: () async{ var res = await model.refreshGroup( accountId: user.accountId, grpId: widget.lstDetail.intGroupId.toString() ); if(res['status'] == "1"){ AppConstant.showSuccessToast( context, "Refresh "+res['msg']); } else{ AppConstant.showFailToast( context, "Refresh "+res['msg']); } }, minSize: 16, padding: EdgeInsets.zero, // color: Colors.green, child: Icon( FontAwesomeIcons.syncAlt, color: Colors.white, size: 18, ), ), SizedBox( width: MediaQuery.of(context).size.width * .02, ), Text( "Refresh", style: TextStyle( color: Colors.white, ), ), ], ) : Container(), ], ), ), ); }).toList(); }, ), ), ), ], ), ) ], ), ), ), model.viewDetails ? Container( decoration: BoxDecoration( color: Color.fromRGBO(243, 249, 237, 1), border: Border.all( color: Colors.grey.withOpacity(.5))), child: Column( crossAxisAlignment: CrossAxisAlignment.center, mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ Padding( padding: EdgeInsets.only( bottom: MediaQuery.of(context).size.height * 0.01, top: MediaQuery.of(context).size.height * 0.01), child: Row( crossAxisAlignment: CrossAxisAlignment.center, mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ SizedBox( child: Text(AppString.status, textAlign: TextAlign.end, style: TextStyle( color: Colors.black, fontWeight: FontWeight.bold, fontSize: MediaQuery.of(context) .size .width * 0.027, )), width: MediaQuery.of(context).size.width * 0.46, ), SizedBox( width: MediaQuery.of(context).size.width * .03, ), SizedBox( width: MediaQuery.of(context).size.width * 0.46, child: Text( model.quoteListItemDetails.strStatus .toString(), style: TextStyle( color: Colors.black, fontSize: MediaQuery.of(context) .size .width * 0.027))) ], ), ), Padding( padding: EdgeInsets.only( bottom: MediaQuery.of(context).size.height * 0.01, top: MediaQuery.of(context).size.height * 0.01), child: Row( crossAxisAlignment: CrossAxisAlignment.center, mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ SizedBox( width: MediaQuery.of(context).size.width * 0.46, child: Text(AppString.timer, textAlign: TextAlign.end, style: TextStyle( color: Colors.black, fontWeight: FontWeight.bold, fontSize: MediaQuery.of(context) .size .width * 0.027))), SizedBox( width: MediaQuery.of(context).size.width * .03, ), SizedBox( width: MediaQuery.of(context).size.width * 0.46, child: Text( model.quoteListItemDetails.termType .toString(), style: TextStyle( color: Colors.black, fontSize: MediaQuery.of(context) .size .width * 0.027))) ], ), ), Padding( padding: EdgeInsets.only( bottom: MediaQuery.of(context).size.height * 0.01, top: MediaQuery.of(context).size.height * 0.01), child: Row( crossAxisAlignment: CrossAxisAlignment.center, mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ SizedBox( width: MediaQuery.of(context).size.width * 0.46, child: Text(AppString.no, textAlign: TextAlign.end, style: TextStyle( color: Colors.black, fontWeight: FontWeight.bold, fontSize: MediaQuery.of(context) .size .width * 0.027))), SizedBox( width: MediaQuery.of(context).size.width * .03, ), SizedBox( width: MediaQuery.of(context).size.width * 0.46, child: Text( widget.type == AppString.group ? "G${model.quoteListItemDetails.quoteid}" : "I${model.quoteListItemDetails.quoteid}", style: TextStyle( color: Colors.black, fontSize: MediaQuery.of(context) .size .width * 0.027))) ], ), ), Padding( padding: EdgeInsets.only( bottom: MediaQuery.of(context).size.height * 0.01, top: MediaQuery.of(context).size.height * 0.01), child: Row( crossAxisAlignment: CrossAxisAlignment.center, mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ SizedBox( width: MediaQuery.of(context).size.width * 0.46, child: Text(AppString.partnerName, textAlign: TextAlign.end, style: TextStyle( color: Colors.black, fontWeight: FontWeight.bold, fontSize: MediaQuery.of(context) .size .width * 0.027)), ), SizedBox( width: MediaQuery.of(context).size.width * .03, ), SizedBox( width: MediaQuery.of(context).size.width * 0.46, child: Text( widget.lstDetail.strBrokername, style: TextStyle( color: Colors.black, fontSize: MediaQuery.of(context) .size .width * 0.027))) ], ), ), Padding( padding: EdgeInsets.only( bottom: MediaQuery.of(context).size.height * 0.01, top: MediaQuery.of(context).size.height * 0.01), child: Row( crossAxisAlignment: CrossAxisAlignment.center, mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ SizedBox( width: MediaQuery.of(context).size.width * 0.46, child: Text("Last Access", textAlign: TextAlign.end, style: TextStyle( color: Colors.black, fontSize: MediaQuery.of(context) .size .width * 0.027, fontWeight: FontWeight.bold))), SizedBox( width: MediaQuery.of(context).size.width * .03, ), SizedBox( width: MediaQuery.of(context).size.width * 0.46, child: Text( widget.lstDetail.strLastAccess, style: TextStyle( color: Colors.black, fontSize: MediaQuery.of(context) .size .width * 0.027))) ], ), ), Padding( padding: EdgeInsets.only( bottom: MediaQuery.of(context).size.height * 0.01, top: MediaQuery.of(context).size.height * 0.01), child: Row( crossAxisAlignment: CrossAxisAlignment.center, mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ SizedBox( width: MediaQuery.of(context).size.width * 0.46, child: Text(AppString.businessName, textAlign: TextAlign.end, style: TextStyle( color: Colors.black, fontWeight: FontWeight.bold, fontSize: MediaQuery.of(context) .size .width * 0.027))), SizedBox( width: MediaQuery.of(context).size.width * .03, ), SizedBox( width: MediaQuery.of(context).size.width * 0.46, child: Text( model.quoteListItemDetails .businessName, style: TextStyle( color: Colors.black, fontSize: MediaQuery.of(context) .size .width * 0.027))) ], ), ), Padding( padding: EdgeInsets.only( bottom: MediaQuery.of(context).size.height * 0.01, top: MediaQuery.of(context).size.height * 0.01), child: Row( crossAxisAlignment: CrossAxisAlignment.center, mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ SizedBox( width: MediaQuery.of(context).size.width * 0.46, child: Text(AppString.requiredByDate, textAlign: TextAlign.end, style: TextStyle( color: Colors.black, fontSize: MediaQuery.of(context) .size .width * 0.027, fontWeight: FontWeight.bold))), SizedBox( width: MediaQuery.of(context).size.width * .03, ), SizedBox( width: MediaQuery.of(context).size.width * 0.46, child: Text( model.quoteListItemDetails .requiredByDate, style: TextStyle( color: Colors.black, fontSize: MediaQuery.of(context) .size .width * 0.027))) ], ), ), Padding( padding: EdgeInsets.only( bottom: MediaQuery.of(context).size.height * 0.01, top: MediaQuery.of(context).size.height * 0.01), child: Row( crossAxisAlignment: CrossAxisAlignment.center, mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ SizedBox( width: MediaQuery.of(context).size.width * 0.46, child: Text( AppString.createdRerequestedDate, textAlign: TextAlign.end, style: TextStyle( color: Colors.black, fontSize: MediaQuery.of(context) .size .width * 0.027, fontWeight: FontWeight.bold))), SizedBox( width: MediaQuery.of(context).size.width * .03, ), SizedBox( width: MediaQuery.of(context).size.width * 0.46, child: Text( model.quoteListItemDetails .quotedDate, style: TextStyle( color: Colors.black, fontSize: MediaQuery.of(context) .size .width * 0.027))) ], ), ) ], ), ) : Container() ], ); }, ) : Scaffold( body: Center( child: CircularProgressIndicator(), ), ); } } //recent update 9-1-21
57.874568
126
0.251546
0c5e67c7f0ee9be484091dec2354339fe7a58988
609
asm
Assembly
oeis/055/A055831.asm
neoneye/loda-programs
84790877f8e6c2e821b183d2e334d612045d29c0
[ "Apache-2.0" ]
11
2021-08-22T19:44:55.000Z
2022-03-20T16:47:57.000Z
oeis/055/A055831.asm
neoneye/loda-programs
84790877f8e6c2e821b183d2e334d612045d29c0
[ "Apache-2.0" ]
9
2021-08-29T13:15:54.000Z
2022-03-09T19:52:31.000Z
oeis/055/A055831.asm
neoneye/loda-programs
84790877f8e6c2e821b183d2e334d612045d29c0
[ "Apache-2.0" ]
3
2021-08-22T20:56:47.000Z
2021-09-29T06:26:12.000Z
; A055831: T(n,n-4), where T is the array in A055830. ; 5,15,31,54,85,125,175,236,309,395,495,610,741,889,1055,1240,1445,1671,1919,2190,2485,2805,3151,3524,3925,4355,4815,5306,5829,6385,6975,7600,8261,8959,9695,10470,11285,12141,13039,13980,14965,15995,17071,18194,19365,20585,21855,23176,24549,25975,27455,28990,30581,32229,33935,35700,37525,39411,41359,43370,45445,47585,49791,52064,54405,56815,59295,61846,64469,67165,69935,72780,75701,78699,81775,84930,88165,91481,94879,98360,101925,105575,109311,113134,117045,121045,125135,129316,133589,137955 mov $2,$0 add $0,6 bin $0,3 mul $2,5 sub $0,$2 sub $0,15
60.9
496
0.775041
8609c5fa6ac3199cbd1bd74d86abacf8d69f65a8
3,259
java
Java
src/main/java/a08_dynamic_programming/PaintHouseIII.java
codebycase/algorithms
4dc74805de58999d6b8739b48ee94608357d1868
[ "Apache-2.0" ]
1
2020-06-19T11:42:23.000Z
2020-06-19T11:42:23.000Z
src/main/java/a08_dynamic_programming/PaintHouseIII.java
codebycase/algorithms-java
ae2c134f62273306ec3b8f1f40c7ca4225868415
[ "Apache-2.0" ]
null
null
null
src/main/java/a08_dynamic_programming/PaintHouseIII.java
codebycase/algorithms-java
ae2c134f62273306ec3b8f1f40c7ca4225868415
[ "Apache-2.0" ]
null
null
null
package a08_dynamic_programming; /** * * There is a row of m houses in a small city, each house must be painted with one of the n colors * (labeled from 1 to n), some houses that have been painted last summer should not be painted * again. * * A neighborhood is a maximal group of continuous houses that are painted with the same color. * * For example: houses = [1,2,2,3,3,2,1,1] contains 5 neighborhoods [{1}, {2,2}, {3,3}, {2}, {1,1}]. * * Given an array houses, an m x n matrix cost and an integer target where: * * houses[i]: is the color of the house i, and 0 if the house is not painted yet. <br> * cost[i][j]: is the cost of paint the house i with the color j + 1. <br> * Return the minimum cost of painting all the remaining houses in such a way that there are exactly * target neighborhoods. If it is not possible, return -1. <br> * * <pre> * Example 1: * * Input: houses = [0,0,0,0,0], cost = [[1,10],[10,1],[10,1],[1,10],[5,1]], m = 5, n = 2, target = 3 * Output: 9 * Explanation: Paint houses of this way [1,2,2,1,1] * This array contains target = 3 neighborhoods, [{1}, {2,2}, {1,1}]. * Cost of paint all houses (1 + 1 + 1 + 1 + 5) = 9. * </pre> * * https://leetcode.com/problems/paint-house-iii/ */ public class PaintHouseIII { public int minCost(int[] houses, int[][] costs, int target) { int[][][] memo = new int[costs.length][target + 1][costs[0].length + 1]; return minCost(houses, costs, 0, -1, target, memo); } public int minCost(int[] houses, int[][] costs, int currentHouse, int prevColor, int target, int[][][] memo) { if (currentHouse >= houses.length) return target == 0 ? 0 : -1; if (target < 0) return -1; if (prevColor != -1 && memo[currentHouse][target][prevColor] != 0) { return memo[currentHouse][target][prevColor]; } int minCost = -1; int currentColor = houses[currentHouse]; if (currentColor == 0) { // Try out all different colors for (int chosenColor = 1; chosenColor <= costs[currentHouse].length; chosenColor++) { int nextCost = minCost(houses, costs, currentHouse + 1, chosenColor, target - (chosenColor == prevColor ? 0 : 1), memo); // If chosenColor can reach target eventually if (nextCost != -1) { nextCost = (currentColor != 0 ? 0 : costs[currentHouse][chosenColor - 1]) + nextCost; minCost = minCost == -1 ? nextCost : Math.min(minCost, nextCost); } } } else { int nextCost = minCost(houses, costs, currentHouse + 1, currentColor, target - (currentColor == prevColor ? 0 : 1), memo); minCost = minCost == -1 ? nextCost : Math.min(minCost, nextCost); } if (prevColor != -1) { memo[currentHouse][target][prevColor] = minCost; } return minCost; } public static void main(String[] args) { PaintHouseIII solution = new PaintHouseIII(); int[] houses = { 0, 0, 0, 0, 0 }; int[][] costs = { { 1, 10 }, { 10, 1 }, { 10, 1 }, { 1, 10 }, { 5, 1 } }; System.out.println(solution.minCost(houses, costs, 3)); houses = new int[] { 0, 2, 1, 2, 0 }; costs = new int[][] { { 1, 10 }, { 10, 1 }, { 10, 1 }, { 1, 10 }, { 5, 1 } }; System.out.println(solution.minCost(houses, costs, 3)); } }
40.7375
128
0.606628
75ff753f3c24958e0092159808901ed30f2e37a5
1,659
java
Java
WebOCR/src/main/java/org/webocr/model/InvoiceItem.java
samindaperamuna/webocr
0d533b1ef8ea0d1e2ef2ddc327e90ccd81f6e915
[ "MIT" ]
1
2020-07-23T22:47:26.000Z
2020-07-23T22:47:26.000Z
WebOCR/src/main/java/org/webocr/model/InvoiceItem.java
samindaperamuna/webocr
0d533b1ef8ea0d1e2ef2ddc327e90ccd81f6e915
[ "MIT" ]
null
null
null
WebOCR/src/main/java/org/webocr/model/InvoiceItem.java
samindaperamuna/webocr
0d533b1ef8ea0d1e2ef2ddc327e90ccd81f6e915
[ "MIT" ]
null
null
null
package org.webocr.model; import java.io.Serializable; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.ManyToOne; import javax.persistence.Table; @Entity @Table(name = "invoice_items") public class InvoiceItem implements Serializable { @Id @Column(name = "item_id") @GeneratedValue(strategy = GenerationType.AUTO) private long itemId; @Column(name = "list_pos") private int listPos; @Column(name = "item_name") private String itemName; private int qty; private float price; @Column(name = "total_price") private float totalPrice; @ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL) private Invoice invoice; public InvoiceItem() { } public InvoiceItem(int listPos) { this.listPos = listPos; } public int getListPos() { return listPos; } public void setListPos(int listPos) { this.listPos = listPos; } public String getItemName() { return itemName; } public void setItemName(String itemName) { this.itemName = itemName; } public int getQty() { return qty; } public void setQty(int qty) { this.qty = qty; } public float getPrice() { return price; } public void setPrice(float price) { this.price = price; } public float getTotalPrice() { return totalPrice; } public void setTotalPrice(float totalPrice) { this.totalPrice = totalPrice; } }
19.068966
65
0.691983
25977d5b66591ede2dd98a5754664fb79472e09e
9,509
asm
Assembly
src/rect.asm
JoeyCluett/game-jam-beat-the-boredom
1a5a28c35bded76b1b7cb842a9c7059cc07a4773
[ "Unlicense" ]
null
null
null
src/rect.asm
JoeyCluett/game-jam-beat-the-boredom
1a5a28c35bded76b1b7cb842a9c7059cc07a4773
[ "Unlicense" ]
1
2020-04-12T00:43:27.000Z
2020-04-13T22:08:29.000Z
src/rect.asm
JoeyCluett/game-jam-beat-the-boredom
1a5a28c35bded76b1b7cb842a9c7059cc07a4773
[ "Unlicense" ]
null
null
null
; ; as per the System-V ABI, registers are allocated in the order: ; rdi, rsi, rdx, rcx, r8, r9 ; ; just some stuff its nice to have globally global sdl_rect_a global sdl_rect_b global screen global screen_format global draw_rect_a global draw_rect_b global draw_tree global draw_stage extern ticks extern linearmap extern SDL_FillRect extern SDL_GetTicks extern filledPolygonColor ; part of the SDL_gfxPrimitives extern filledTrigonColor ; ... extern filledCircleColor ; ... extern lineColor ; ... extern color_lut_begin extern green extern brown extern gray extern yellow extern white extern silver extern gold extern black %define rect_a_X(v) mov [sdl_rect_a + 0], word v %define rect_a_Y(v) mov [sdl_rect_a + 2], word v %define rect_a_W(v) mov [sdl_rect_a + 4], word v %define rect_a_H(v) mov [sdl_rect_a + 6], word v %define rect_b_X(v) mov [sdl_rect_b + 0], word v %define rect_b_Y(v) mov [sdl_rect_b + 2], word v %define rect_b_W(v) mov [sdl_rect_b + 4], word v %define rect_b_H(v) mov [sdl_rect_b + 6], word v section .bss ; a single SDL_Rect is 8 bytes. save space for a few sdl_rect_a: resb 8 sdl_rect_b: resb 8 ; SDL_Surface ptr screen: resq 1 screen_format: resq 1 section .data align 16 ; tree data : x y x y x y t1: dw 0, 30, -4, 20, 4, 20 t2: dw -2, 20, 2, 20, -7, 10 t3: dw 2, 20, -7, 10, 7, 10 t4: dw -5, 10, 5, 10, -10, 0 t5: dw 5, 10, -10, 0, 10, 0 t_none: ; road data : x y x y x y road1: dw 350, 300, 450, 300, 300, 600 road2: dw 450, 300, 300, 600, 500, 600 r_none: _320: dd 320.0 _550: dd 550.0 _615: dd 615.0 _250: dd 250.0 _185: dd 185.0 align 16 draw_tree: push rbp mov rbp, rsp ; rdi : x ; rsi : y ; edx : color ; need some space for locals sub rsp, 64 ; store our arguments where we can get them easily mov qword [rsp + 16], rdi ; X mov qword [rsp + 24], rsi ; Y mov qword [rsp + 32], rdx ; color ; ; filledTrigonColor ; rdi : SDL_Surface ptr ; rsi : x1 ; rdx : y1 ; rcx : x2 ; r8 : y2 ; r9 : x3 ; push : y3 ; push : color ; (no padding needed) ; remove stack args after subroutine returns ; ; preserve that which needs preservation mov qword [rsp + 40], r14 mov qword [rsp + 48], r13 mov r14, qword t1 ; point to first triangle coord array draw_tree_loop: movsx rsi, word [r14 + 0] ; x1 movsx rdx, word [r14 + 2] ; y1 movsx rcx, word [r14 + 4] ; x2 movsx r8, word [r14 + 6] ; y2 movsx r9, word [r14 + 8] ; x3 <- last register arg to filledTrigonColor movsx r13, word [r14 + 10] ; y3 <- needs to be placed on the stack add r14, 12 ; advance to next triangle ; r14 is callee preserved ; y coords need to be negated neg rdx neg r8 neg r13 ; multiply everything by 2 shl rsi, 1 shl rdx, 1 shl rcx, 1 shl r8, 1 shl r9, 1 shl r13, 1 ; optimization... now thats a word I havent heard in a long time ; fetch the offset from its local storage mov r10, qword [rsp + 16] ; tmp Xoffset mov r11, qword [rsp + 24] ; tmp Yoffset add rsi, r10 ; x1 + Xoff add rdx, r11 ; y1 + Yoff add rcx, r10 ; x2 + Xoff add r8, r11 ; y2 + Yoff add r9, r10 ; x3 + Xoff add r13, r11 ; y3 + Yoff mov rdi, [screen] ; SDL_Surface ptr ; remaining arguments are passed on the stack in right-to-left ; order (so last arg is pushed first) push qword [rsp + 32] ; fetch and push the color (last argument) push r13 ; y3, needs to be on the stack (penultimate argument) call filledTrigonColor add rsp, 16 ; destroy temorary arguments to filledTrigonColor (y3 and color) cmp r14, t_none ; end of triangles jne draw_tree_loop ; loop through all triangles ; need to draw brown trunk of tree mov r10, qword [rsp + 16] ; X mov r11, qword [rsp + 24] ; Y sub r10, 4 ; apply small x offset to base inc r11 ; apply small y offset to base ; SDL_Rect describing the tree trunk rect_a_X(r10w) rect_a_Y(r11w) rect_a_H(10) rect_a_W(8) mov edi, dword [brown + 0] call draw_rect_a ; restore certain registers mov r14, qword [rsp + 40] mov r13, qword [rsp + 48] mov rsp, rbp pop rbp ret align 16 draw_stage: sub rsp, 24 ; set the background rect_b_X(0) rect_b_Y(0) rect_b_H(600) rect_b_W(800) mov edi, dword [gray] call draw_rect_b ; rdi, rsi, rdx, rcx, r8, r9 ; draw the sunrise mov rdi, [screen] mov si, 400 mov dx, 375 mov cx, 150 mov r8d, dword [gold + 4] call filledCircleColor ; draw the foreground rect_b_X(0) rect_b_Y(300) rect_b_H(300) rect_b_W(800) mov edi, dword [silver] call draw_rect_b ; draw the road in the center mov rdi, [screen] movsx rsi, word [road1 + 0] ; x1 movsx rdx, word [road1 + 2] ; y1 movsx rcx, word [road1 + 4] ; x2 movsx r8, word [road1 + 6] ; y2 movsx r9, word [road1 + 8] ; x3 <- last register arg to filledTrigonColor movsx r13, word [road1 + 10] ; y3 <- needs to be placed on the stack push qword [black + 4] ; color push r13 ; y3 call filledTrigonColor add rsp, 16 ; readjust stack ; second triangle for road mov rdi, [screen] movsx rsi, word [road2 + 0] ; x1 movsx rdx, word [road2 + 2] ; y1 movsx rcx, word [road2 + 4] ; x2 movsx r8, word [road2 + 6] ; y2 movsx r9, word [road2 + 8] ; x3 <- last register arg to filledTrigonColor movsx r13, word [road2 + 10] ; y3 <- needs to be placed on the stack push qword [black + 4] ; color push r13 ; y3 call filledTrigonColor add rsp, 16 ; readjust stack ; draw lines on the side of the road ; ; lineColor() ; rdi : SDL_Surface ptr ; rsi : x1 ; rdx : y1 ; rcx : x2 ; r8 : y2 ; r9 : color ; ; left hand line mov rdi, [screen] mov si, 360 ; x1 mov dx, 300 ; y1 (centerline) mov cx, 320 ; x2 mov r8w, 600 ; y2 (bottom) mov r9d, [white + 4] call lineColor ; right hand line mov rdi, [screen] mov si, 440 ; x1 mov dx, 300 ; y1 (centerline) mov cx, 480 ; x2 mov r8w, 600 ; y2 (bottom) mov r9d, [white + 4] call lineColor ; calculate the offset used to draw the center lines in the road mov eax, [ticks] shr eax, 3 ; divide by 8 xor edx, edx ; yeah...division on AMD64 is not pretty mov ebx, 80 ; setup the divisor (because there is no div imm) div ebx ; eax=quotient, edx=remainder mov eax, edx ; overwrite the quotient with le remainder add eax, 300 ; start in the center ; draw a bunch of lines in the center of the road mov qword [rsp], rax add rax, 400 ; enough for 4 lines mov qword [rsp + 8], rax ; used for loop termination later mov rax, [rsp] ; get correct offset value center_line_loop: rect_b_X(398) rect_b_Y(ax) rect_b_H(50) rect_b_W(4) mov edi, [white] call draw_rect_b mov rax, qword [rsp] ; restore rax add rax, 80 ; go to next iteration mov qword [rsp], rax ; update stored loop value cmp rax, qword [rsp + 8] ; test against termination value jne center_line_loop ; repeat until termination ; draw some trees! xor rdi, rdi ; offset=0 xor rsi, rsi ; left=0 call draw_tree_w_offset mov rdi, 160 ; offset=160 xor rsi, rsi ; left=0 call draw_tree_w_offset mov rdi, 80 ; offset=80 mov rsi, 1 ; right=1 call draw_tree_w_offset mov rdi, 240 ; offset=240 mov rsi, 1 ; right=1 call draw_tree_w_offset add rsp, 24 ret align 16 draw_tree_w_offset: sub rsp, 8 ; ; rdi : local offset ; rsi : 0=left, 1=right ; mov eax, [ticks] shr eax, 3 add eax, edi ; given deg offset from 'normal' xor edx, edx ; need to zero this register mov ebx, 320 ; divisor div ebx ; eax=quotient, edx=remainder mov eax, edx ; get the remainder cmp rsi, 0 jne map_right_side ; use linearmap to place trees at correct places cvtsi2ss xmm0, eax ; x xorps xmm1, xmm1 ; x_begin, place 0.0f in xmm1 movss xmm2, [_320] ; x_end, 300 movss xmm3, [_250] ; y_begin movss xmm4, [_185] ; y_end call linearmap jmp mapping_done map_right_side: cvtsi2ss xmm0, eax ; x xorps xmm1, xmm1 ; x_begin, place 0.0f in xmm1 movss xmm2, [_320] ; x_end, 300 movss xmm3, [_550] ; y_begin movss xmm4, [_615] ; y_end call linearmap mapping_done: ; place x,y,color and call draw_tree cvttss2si edi, xmm0 ; mapped value is in xmm0 mov esi, eax ; y add esi, 300 ; y+300 to put in bottom half of screen mov edx, [green + 4] ; this is useless but i dont want to rewrite draw_tree call draw_tree add rsp, 8 ret align 16 draw_rect_a: ; quick way to align stack sub rsp, 8 ; ; rdi : color of rectangle ; mov rdx, rdi mov rdi, [screen] mov rsi, sdl_rect_a call SDL_FillRect add rsp, 8 ret align 16 draw_rect_b: sub rsp, 8 mov rdx, rdi mov rdi, [screen] mov rsi, sdl_rect_b call SDL_FillRect add rsp, 8 ret
24.382051
80
0.603428
6ca54f5bdb01862d7cee3730ff92edba05586fa8
1,872
go
Go
game/dan/handler/dan_upgrade.go
linminglu/Fgame
2c0f60dffd8d6b42ad2b3d2e0a6344f4f88ec4d5
[ "MIT" ]
null
null
null
game/dan/handler/dan_upgrade.go
linminglu/Fgame
2c0f60dffd8d6b42ad2b3d2e0a6344f4f88ec4d5
[ "MIT" ]
null
null
null
game/dan/handler/dan_upgrade.go
linminglu/Fgame
2c0f60dffd8d6b42ad2b3d2e0a6344f4f88ec4d5
[ "MIT" ]
2
2021-08-31T03:41:01.000Z
2021-11-07T15:04:51.000Z
package handler import ( "fgame/fgame/common/codec" uipb "fgame/fgame/common/codec/pb/ui" "fgame/fgame/common/dispatch" "fgame/fgame/common/lang" "fgame/fgame/core/session" "fgame/fgame/game/dan/pbutil" playerdan "fgame/fgame/game/dan/player" "fgame/fgame/game/player" playerlogic "fgame/fgame/game/player/logic" "fgame/fgame/game/player/types" "fgame/fgame/game/processor" gamesession "fgame/fgame/game/session" log "github.com/Sirupsen/logrus" ) func init() { processor.Register(codec.MessageType(uipb.MessageType_CS_DAN_UPGRADE_TYPE), dispatch.HandlerFunc(handleDanUpgrade)) } //处理食丹升级 func handleDanUpgrade(s session.Session, msg interface{}) error { log.Debug("dan:处理食丹升级消息") gcs := gamesession.SessionInContext(s.Context()) pl := gcs.Player() tpl := pl.(player.Player) err := danUpgrade(tpl) if err != nil { log.WithFields( log.Fields{ "playerId": pl.GetId(), "error": err, }).Error("dan:处理食丹升级消息,错误") return err } log.WithFields( log.Fields{ "playerId": pl.GetId(), }).Debug("dan:处理食丹升级消息完成") return nil } //处理食丹升级的逻辑 func danUpgrade(pl player.Player) (err error) { danManager := pl.GetPlayerDataManager(types.PlayerDanDataManagerType).(*playerdan.PlayerDanDataManager) flag := danManager.CheckFullLevel() if flag { log.WithFields(log.Fields{ "playerId": pl.GetId(), }).Warn("dan:当前食丹等级已达最高级,无法再升级") playerlogic.SendSystemMessage(pl, lang.DanLevelReachedLimit) return } //校验已食用的丹药数 flag = danManager.IfEatEnough() if !flag { log.WithFields(log.Fields{ "playerId": pl.GetId(), }).Warn("dan:当前食用丹药进度未满,无法升级") playerlogic.SendSystemMessage(pl, lang.DanUseIsNotEnough) return } flag = danManager.Upgrade() if !flag { panic("dan:食丹升级应该是成功的") } danInfo := danManager.GetDanInfo() scDanUpgrade := pbuitl.BuildSCDanUpgrade(danInfo.LevelId) pl.SendMsg(scDanUpgrade) return }
23.696203
116
0.725427
98589241301efa7e59b6232cac7f75cc85bee3cb
870
html
HTML
app/templates/core/index.html
open-iot-stack/open-iot-web
c8a28f7da081fddeec8a5178d10c2877db23401e
[ "MIT" ]
null
null
null
app/templates/core/index.html
open-iot-stack/open-iot-web
c8a28f7da081fddeec8a5178d10c2877db23401e
[ "MIT" ]
null
null
null
app/templates/core/index.html
open-iot-stack/open-iot-web
c8a28f7da081fddeec8a5178d10c2877db23401e
[ "MIT" ]
null
null
null
{% extends "layout_no_login.html" %} {% block body %} <center><h1 class="small-3">Wink Login</h1></center> <div class="small-3 large-3 large-centered columns small-centered"> <div class="login-box"> <div class="row"> <div class="large-12 columns"> <form action="/login" method="post"> <div class="row"> <div class="large-12 columns"> <input type="text" name="username" placeholder="Username" /> </div> </div> <div class="row"> <div class="large-12 columns"> <input type="password" name="password" placeholder="Password" /> </div> </div> <div class="row"> <div class="large-12 large-centered columns"> <input type="submit" class="button expand" value="Log In"/> </div> </div> </form> </div> </div> </div> </div> {% endblock %}
27.1875
77
0.558621
31a56861b20b398c80de8ba9baf35ee9ad3be8e6
6,129
asm
Assembly
Transynther/x86/_processed/AVXALIGN/_st_/i7-7700_9_0xca_notsx.log_21829_1617.asm
ljhsiun2/medusa
67d769b8a2fb42c538f10287abaf0e6dbb463f0c
[ "MIT" ]
9
2020-08-13T19:41:58.000Z
2022-03-30T12:22:51.000Z
Transynther/x86/_processed/AVXALIGN/_st_/i7-7700_9_0xca_notsx.log_21829_1617.asm
ljhsiun2/medusa
67d769b8a2fb42c538f10287abaf0e6dbb463f0c
[ "MIT" ]
1
2021-04-29T06:29:35.000Z
2021-05-13T21:02:30.000Z
Transynther/x86/_processed/AVXALIGN/_st_/i7-7700_9_0xca_notsx.log_21829_1617.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 %r8 push %rbp push %rbx push %rcx push %rdi push %rdx lea addresses_A_ht+0x17e04, %rdi nop nop nop nop nop sub %rdx, %rdx movb $0x61, (%rdi) add %rbx, %rbx lea addresses_WT_ht+0x417c, %rcx nop nop nop nop nop sub $31343, %r12 movb $0x61, (%rcx) nop nop nop add $16218, %rdx lea addresses_A_ht+0x12abc, %rdi nop nop nop nop nop cmp %rbp, %rbp mov $0x6162636465666768, %rdx movq %rdx, %xmm6 movups %xmm6, (%rdi) nop nop nop nop add %rbp, %rbp lea addresses_WC_ht+0xdd3c, %rdi cmp $7638, %r8 vmovups (%rdi), %ymm6 vextracti128 $0, %ymm6, %xmm6 vpextrq $0, %xmm6, %rbx nop nop nop cmp %rbx, %rbx lea addresses_D_ht+0x33fc, %r8 sub $6765, %rbp movl $0x61626364, (%r8) nop nop nop nop nop add %r12, %r12 lea addresses_UC_ht+0x97bc, %r12 nop cmp $32225, %rbp mov (%r12), %rbx nop nop nop cmp %rdx, %rdx lea addresses_normal_ht+0x1d14, %r8 nop sub %rbx, %rbx mov $0x6162636465666768, %rcx movq %rcx, %xmm2 movups %xmm2, (%r8) xor %r8, %r8 pop %rdx pop %rdi pop %rcx pop %rbx pop %rbp pop %r8 pop %r12 ret .global s_faulty_load s_faulty_load: push %r10 push %r12 push %r13 push %r14 push %r15 push %rbx push %rsi // Store lea addresses_normal+0x6980, %r12 nop nop add %r15, %r15 mov $0x5152535455565758, %r10 movq %r10, (%r12) nop nop nop and %rbx, %rbx // Store lea addresses_WC+0x106bc, %rbx clflush (%rbx) nop nop nop nop nop xor %rsi, %rsi movl $0x51525354, (%rbx) cmp $55417, %r10 // Faulty Load lea addresses_D+0x18ebc, %r15 clflush (%r15) nop and %r12, %r12 movb (%r15), %r13b lea oracles, %rsi and $0xff, %r13 shlq $12, %r13 mov (%rsi,%r13,1), %r13 pop %rsi pop %rbx pop %r15 pop %r14 pop %r13 pop %r12 pop %r10 ret /* <gen_faulty_load> [REF] {'src': {'NT': False, 'AVXalign': False, 'size': 4, 'congruent': 0, 'same': False, 'type': 'addresses_D'}, 'OP': 'LOAD'} {'dst': {'NT': False, 'AVXalign': False, 'size': 8, 'congruent': 1, 'same': False, 'type': 'addresses_normal'}, 'OP': 'STOR'} {'dst': {'NT': False, 'AVXalign': False, 'size': 4, 'congruent': 8, 'same': False, 'type': 'addresses_WC'}, 'OP': 'STOR'} [Faulty Load] {'src': {'NT': False, 'AVXalign': True, 'size': 1, 'congruent': 0, 'same': True, 'type': 'addresses_D'}, 'OP': 'LOAD'} <gen_prepare_buffer> {'dst': {'NT': False, 'AVXalign': False, 'size': 1, 'congruent': 3, 'same': False, 'type': 'addresses_A_ht'}, 'OP': 'STOR'} {'dst': {'NT': False, 'AVXalign': False, 'size': 1, 'congruent': 6, 'same': False, 'type': 'addresses_WT_ht'}, 'OP': 'STOR'} {'dst': {'NT': False, 'AVXalign': False, 'size': 16, 'congruent': 10, 'same': False, 'type': 'addresses_A_ht'}, 'OP': 'STOR'} {'src': {'NT': False, 'AVXalign': False, 'size': 32, 'congruent': 7, 'same': False, 'type': 'addresses_WC_ht'}, 'OP': 'LOAD'} {'dst': {'NT': True, 'AVXalign': False, 'size': 4, 'congruent': 6, 'same': False, 'type': 'addresses_D_ht'}, 'OP': 'STOR'} {'src': {'NT': False, 'AVXalign': True, 'size': 8, 'congruent': 6, 'same': False, 'type': 'addresses_UC_ht'}, 'OP': 'LOAD'} {'dst': {'NT': False, 'AVXalign': False, 'size': 16, 'congruent': 3, 'same': False, 'type': 'addresses_normal_ht'}, 'OP': 'STOR'} {'36': 21829} 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 */
38.30625
2,999
0.655246
26843403313a00768c98f407760ae25b56806669
4,098
swift
Swift
KCD/ShipMasterDetailWindowController.swift
masakih/KCD
fa6a0a0b51735ab1f9a4caef2dc9bad3ec09bd9e
[ "BSD-2-Clause" ]
null
null
null
KCD/ShipMasterDetailWindowController.swift
masakih/KCD
fa6a0a0b51735ab1f9a4caef2dc9bad3ec09bd9e
[ "BSD-2-Clause" ]
null
null
null
KCD/ShipMasterDetailWindowController.swift
masakih/KCD
fa6a0a0b51735ab1f9a4caef2dc9bad3ec09bd9e
[ "BSD-2-Clause" ]
null
null
null
// // ShipMasterDetailWindowController.swift // KCD // // Created by Hori,Masaki on 2017/01/05. // Copyright © 2017年 Hori,Masaki. All rights reserved. // import Cocoa final class ShipMasterDetailWindowController: NSWindowController { @objc let managedObjectContext = ServerDataStore.default.context @objc let fleetManager: FleetManager = { return AppDelegate.shared.fleetManager ?? FleetManager() }() let specNames = [ "id", "name", "shortTypeName", "slot_0", "slot_1", "slot_2", "slot_3", "slot_4", "onslot_0", "onslot_1", "onslot_2", "onslot_3", "onslot_4", "leng", "slot_ex", "sakuteki_0", "sakuteki_1" ] @IBOutlet private var shipController: NSArrayController! @IBOutlet private var fleetMemberController: NSArrayController! @IBOutlet private var deckController: NSArrayController! @IBOutlet private weak var decksView: NSTableView! @IBOutlet private weak var shipsView: NSTableView! @IBOutlet private weak var fleetMemberView: NSTableView! @IBOutlet private weak var sally: NSTextField! override var windowNibName: NSNib.Name { return .nibName(instanceOf: self) } @objc dynamic var selectedDeck: Deck? { didSet { fleetShips = selectedDeck?[0...6] ?? [] } } @objc dynamic var fleetShips: [Ship] = [] @objc dynamic var selectedShip: Ship? { didSet { buildSpec() } } @objc dynamic var spec: [[String: Any]] = [] @objc dynamic var equipments: NSArray? private func buildSpec() { guard let selectedShip = selectedShip else { return } spec = specNames.compactMap { key -> [String: Any]? in guard let v = selectedShip.value(forKeyPath: key) else { return nil } return ["name": key, "value": v] } equipments = selectedShip.equippedItem.array as NSArray? } @IBAction func applySally(_ sender: AnyObject?) { let store = ServerDataStore.oneTimeEditor() store.sync { guard let selectedShip = self.selectedShip else { return } guard let ship = store.exchange(selectedShip) else { return } // // ship.sally_area = sally.integerValue as NSNumber let eq = ship.equippedItem.array let slotId = self.sally.integerValue let pos = min(4, eq.count) if eq.count > 4 { ship.equippedItem = NSOrderedSet(array: Array(eq.dropLast())) } if let slotItem = store.slotItem(by: slotId) { ship.setItem(slotId, to: pos) ship.equippedItem = NSOrderedSet(array: ship.equippedItem.array + [slotItem]) } store.save(errorHandler: {_ in}) } } } extension ShipMasterDetailWindowController: NSTableViewDelegate { func tableViewSelectionDidChange(_ notification: Notification) { guard let tableView = notification.object as? NSTableView else { return } let controller = [ (shipsView, shipController), (fleetMemberView, fleetMemberController), (decksView, deckController) ] .lazy .filter { $0.0 == tableView } .flatMap { $0.1 } .first if let selectedObjects = controller?.selectedObjects as? [Ship] { selectedShip = selectedObjects.first } else if let selectedObjects = controller?.selectedObjects as? [Deck] { selectedDeck = selectedObjects.first } } }
28.859155
93
0.537823
2f0e9a1c54c1d0ae144fe058454bf5c0d25a9445
4,888
java
Java
modules/core/src/test/java/org/apache/ignite/spi/loadbalancing/roundrobin/GridRoundRobinTestUtils.java
DirectXceriD/gridgain
093e512a9147e266f83f6fe1cf088c0b037b501c
[ "Apache-2.0", "CC0-1.0" ]
1
2019-03-11T08:52:37.000Z
2019-03-11T08:52:37.000Z
modules/core/src/test/java/org/apache/ignite/spi/loadbalancing/roundrobin/GridRoundRobinTestUtils.java
DirectXceriD/gridgain
093e512a9147e266f83f6fe1cf088c0b037b501c
[ "Apache-2.0", "CC0-1.0" ]
null
null
null
modules/core/src/test/java/org/apache/ignite/spi/loadbalancing/roundrobin/GridRoundRobinTestUtils.java
DirectXceriD/gridgain
093e512a9147e266f83f6fe1cf088c0b037b501c
[ "Apache-2.0", "CC0-1.0" ]
null
null
null
/* * GridGain Community Edition Licensing * Copyright 2019 GridGain Systems, Inc. * * Licensed under the Apache License, Version 2.0 (the "License") modified with Commons Clause * Restriction; 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. * * Commons Clause Restriction * * The Software is provided to you by the Licensor under the License, as defined below, subject to * the following condition. * * Without limiting other conditions in the License, the grant of rights under the License will not * include, and the License does not grant to you, the right to Sell the Software. * For purposes of the foregoing, “Sell” means practicing any or all of the rights granted to you * under the License to provide to third parties, for a fee or other consideration (including without * limitation fees for hosting or consulting/ support services related to the Software), a product or * service whose value derives, entirely or substantially, from the functionality of the Software. * Any license notice or attribution required by the License must also include this Commons Clause * License Condition notice. * * For purposes of the clause above, the “Licensor” is Copyright 2019 GridGain Systems, Inc., * the “License” is the Apache License, Version 2.0, and the Software is the GridGain Community * Edition software provided with this notice. */ package org.apache.ignite.spi.loadbalancing.roundrobin; import java.util.List; import java.util.UUID; import org.apache.ignite.GridTestJob; import org.apache.ignite.cluster.ClusterNode; import org.apache.ignite.compute.ComputeTaskSession; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; /** * Helper class for balancer tests. */ class GridRoundRobinTestUtils { /** * Performs two full cycles by round robin routine for check correct order. * * @param spi Load balancing SPI. * @param allNodes Topology nodes. * @param orderedNodes Balancing nodes. * @param ses Task session. */ static void checkCyclicBalancing(RoundRobinLoadBalancingSpi spi, List<ClusterNode> allNodes, List<UUID> orderedNodes, ComputeTaskSession ses) { ClusterNode firstNode = spi.getBalancedNode(ses, allNodes, new GridTestJob()); int startIdx = firstBalancedNodeIndex(firstNode, orderedNodes); // Two full cycles by round robin routine. for (int i = 0; i < allNodes.size() * 2; i++) { int actualIdx = (startIdx + i + 1) % allNodes.size(); ClusterNode nextNode = spi.getBalancedNode(ses, allNodes, new GridTestJob()); assertEquals("Balancer returns node out of order", nextNode.id(), orderedNodes.get(actualIdx)); } } /** * Performs two full cycles by round robin routine for check correct order. * Switches between two task sessions by turns. * * @param spi Load balancing SPI. * @param allNodes Topology nodes. * @param orderedNodes Balancing nodes. * @param ses1 First task session. * @param ses2 Second task session. */ static void checkCyclicBalancing(RoundRobinLoadBalancingSpi spi, List<ClusterNode> allNodes, List<UUID> orderedNodes, ComputeTaskSession ses1, ComputeTaskSession ses2) { ClusterNode firstNode = spi.getBalancedNode(ses1, allNodes, new GridTestJob()); int startIdx = firstBalancedNodeIndex(firstNode, orderedNodes); // Two full cycles by round robin routine. for (int i = 0; i < allNodes.size() * 2; i++) { int actualIdx = (startIdx + i + 1) % allNodes.size(); ClusterNode nextNode = spi.getBalancedNode(i % 2 == 0 ? ses1 : ses2, allNodes, new GridTestJob()); assertEquals("Balancer returns node out of order", nextNode.id(), orderedNodes.get(actualIdx)); } } /** * @param firstNode First node which was return by balancer. * @param orderedNodes Balancing nodes. * @return Index of first node which was return by balancer. */ static int firstBalancedNodeIndex(ClusterNode firstNode, List<UUID> orderedNodes) { int startIdx = -1; for (int i = 0; i < orderedNodes.size(); i++) { if (firstNode.id() == orderedNodes.get(i)) startIdx = i; } assertTrue("Can't find position of first balanced node", startIdx >= 0); return startIdx; } }
41.07563
110
0.696195
9c250e31505b92ecdfc72e2c14dc90224a9f34ee
3,828
js
JavaScript
resources/js/components/admin/Feedback/Feedback.js
mostafa711994/GradProjectOCR
f24f30dbea4e38b8e593f41d9e9500569274ca72
[ "MIT" ]
null
null
null
resources/js/components/admin/Feedback/Feedback.js
mostafa711994/GradProjectOCR
f24f30dbea4e38b8e593f41d9e9500569274ca72
[ "MIT" ]
null
null
null
resources/js/components/admin/Feedback/Feedback.js
mostafa711994/GradProjectOCR
f24f30dbea4e38b8e593f41d9e9500569274ca72
[ "MIT" ]
null
null
null
import React, {Component} from 'react'; import '../adminShared.css'; import Topbar from "../Topbar/Topbar"; import Sidebar from "../Sidebar/Sidebar"; import axios from "axios"; class Feedback extends Component{ state = { feedback: [], } componentDidMount() { let obj = JSON.parse(sessionStorage.getItem('user')); if (obj && obj.api_token) { axios.get('http://127.0.0.1:8000/api/admin/feedback') .then(response => { this.setState({feedback: response.data}); console.log(response); }) } } render(){ return ( <div id="wrapper"> <Sidebar/> <div id="content-wrapper" className="d-flex flex-column"> <div id="content"> <Topbar/> <div className="container-fluid"> <div className="card shadow mb-4"> <div className="card-header py-3"> <h6 className="m-0 font-weight-bold text-primary">feedback</h6> </div> <div className="card-body"> <div className="table-responsive"> <table className="table table-bordered" id="dataTable" width="100%" cellSpacing="0"> <thead> <tr> <th>id</th> <th>name</th> <th>email</th> <th>message</th> </tr> </thead> <tfoot> <tr> <th>id</th> <th>name</th> <th>email</th> <th>message</th> </tr> </tfoot> <tbody> { this.state.feedback.map(feedback => { return ( <tr key={feedback.id}> <td>{feedback.id}</td> <td>{feedback.name}</td> <td>{feedback.email}</td> <td>{feedback.message}</td> </tr> ) }) } </tbody> </table> </div> </div> </div> </div> </div> </div> </div> ); } } export default Feedback;
32.717949
107
0.246343
49a958b40c6e4bce0b22ee7bf34f145d03766905
971
html
HTML
RujelEduPlan/Components/EduPeriodSelector.wo/EduPeriodSelector.html
baywind/rujel
d7ae2ab6ce1409c45c1c9fcf0c31e1162cdf675a
[ "BSD-3-Clause" ]
5
2015-12-21T16:55:26.000Z
2016-11-18T08:02:49.000Z
RujelEduPlan/Components/EduPeriodSelector.wo/EduPeriodSelector.html
baywind/rujel
d7ae2ab6ce1409c45c1c9fcf0c31e1162cdf675a
[ "BSD-3-Clause" ]
null
null
null
RujelEduPlan/Components/EduPeriodSelector.wo/EduPeriodSelector.html
baywind/rujel
d7ae2ab6ce1409c45c1c9fcf0c31e1162cdf675a
[ "BSD-3-Clause" ]
3
2016-02-25T22:58:26.000Z
2019-05-08T05:42:14.000Z
<webobject name = "Form"> <table><thead> <tr> <td colspan = "3"><strong><webobject name = "TypeTitle"/>:</strong> <webobject name = "TypeSelector"/></td> </tr> </thead><webobject name = "HasType"> <tbody><tr> <th colspan = "2" align = "left"><webobject name = "BeginTitle"/></th> <th><webobject name = "WeeksTitle"/></th> </tr><webobject name = "Periods"> <tr><td><webobject name = "BeginField"/></td> <td><webobject name = "Name"/></td> <td style = "color:#666666;"><webobject name = "Weeks"/></td> </tr></webobject> </tbody> <tfoot> <tr><th align = "left" colspan = "2" style = "white-space:nowrap;"><webobject name = "EndOfYear"/>: <webobject name = "EndField"/></th> <th style = "color:#666666;"><webobject name = "Weeks"/></th> </tr> <tr> <td colspan = "3" align = "center"><webobject name = "Save"/></td> </tr></tfoot></webobject> </table></webobject><webobject name = "HasChanges"> <script type = "text/javascript"> hasChanges=true; </script> </webobject>
33.482759
99
0.629248
165128db7fb54a7c8d8b08cc3a0f2f9a44cf2350
257
h
C
TFFiPhone/EMProjectTableViewController.h
ATOM27/TFFiPhone
4fce8348977df4b6064ed72f692820a164f78562
[ "MIT" ]
null
null
null
TFFiPhone/EMProjectTableViewController.h
ATOM27/TFFiPhone
4fce8348977df4b6064ed72f692820a164f78562
[ "MIT" ]
null
null
null
TFFiPhone/EMProjectTableViewController.h
ATOM27/TFFiPhone
4fce8348977df4b6064ed72f692820a164f78562
[ "MIT" ]
null
null
null
// // EMProjectTableViewController.h // TFFiPhone // // Created by Eugene Mekhedov on 15.05.17. // Copyright © 2017 Eugene Mekhedov. All rights reserved. // #import <UIKit/UIKit.h> @interface EMProjectTableViewController : UITableViewController @end
18.357143
63
0.743191
70d02e2eb9d60913f0a46603e8a178d46ef4abb6
683
swift
Swift
Roulette/Roulette/Sources/Foundations/UI/IntrinsicCollectionView.swift
thomas-sivilay/roulette-iso
a9986736ba50d1a8eda5a15ce5f1452a10de4ec5
[ "MIT" ]
1
2020-01-15T10:14:53.000Z
2020-01-15T10:14:53.000Z
Roulette/Roulette/Sources/Foundations/UI/IntrinsicCollectionView.swift
thomas-sivilay/roulette-iso
a9986736ba50d1a8eda5a15ce5f1452a10de4ec5
[ "MIT" ]
null
null
null
Roulette/Roulette/Sources/Foundations/UI/IntrinsicCollectionView.swift
thomas-sivilay/roulette-iso
a9986736ba50d1a8eda5a15ce5f1452a10de4ec5
[ "MIT" ]
null
null
null
// // IntrinsicCollectionView.swift // Roulette // // Created by Thomas Sivilay on 6/28/17. // Copyright © 2017 Thomas Sivilay. All rights reserved. // import UIKit final class IntrinsicCollectionView: UICollectionView { // MARK: - Nested fileprivate enum Constant { enum UI { static let width = UIScreen.main.bounds.size.width } } // MARK: - Properties override var contentSize: CGSize { didSet { self.invalidateIntrinsicContentSize() } } override var intrinsicContentSize: CGSize { return CGSize(width: Constant.UI.width, height: contentSize.height) } }
20.69697
75
0.617862
2ea179e152255cd16992b44c9dc7c4d9d93f2722
101
sql
SQL
BuildDeps/deps/db/test/scr038/data/char_length.sql
krugercoin-project/krugercoin0.6.3
c77cf64429ea45767a3fd067e27caf38782a21d5
[ "MIT" ]
66
2017-09-29T07:09:59.000Z
2020-01-12T06:45:08.000Z
BuildDeps/deps/db/test/scr038/data/char_length.sql
krugercoin-project/krugercoin0.6.3
c77cf64429ea45767a3fd067e27caf38782a21d5
[ "MIT" ]
8
2017-03-10T16:13:36.000Z
2021-03-03T07:22:35.000Z
BuildDeps/deps/db/test/scr038/data/char_length.sql
krugercoin-project/krugercoin0.6.3
c77cf64429ea45767a3fd067e27caf38782a21d5
[ "MIT" ]
26
2017-06-06T05:20:40.000Z
2020-01-18T01:17:35.000Z
CREATE DATABASE numismatics; CREATE TABLE table1 (att_int INT(8) PRIMARY KEY, att_char CHAR(2));
20.2
48
0.752475
eaa464970d241bfbe3703662f7d6b9d6207f8e77
166
sql
SQL
Src/CTS.W.150501/CTS.W.150501.Models/Resources/Dao/Client/MainDao_GetItemRelated.sql
ctsoftvn/cts-w-1505-01
bff529baeaf042f1ef4fa433f79f19d4703e6d0b
[ "Apache-2.0" ]
null
null
null
Src/CTS.W.150501/CTS.W.150501.Models/Resources/Dao/Client/MainDao_GetItemRelated.sql
ctsoftvn/cts-w-1505-01
bff529baeaf042f1ef4fa433f79f19d4703e6d0b
[ "Apache-2.0" ]
null
null
null
Src/CTS.W.150501/CTS.W.150501.Models/Resources/Dao/Client/MainDao_GetItemRelated.sql
ctsoftvn/cts-w-1505-01
bff529baeaf042f1ef4fa433f79f19d4703e6d0b
[ "Apache-2.0" ]
null
null
null
select * from [MAItems] where [ItemCd] != @ItemCd and [CategoryCd] = @CategoryCd and [LocaleCd] = @LocaleCd and [DeleteFlag] = 0 order by UpdateDate desc
18.444444
57
0.668675
5dc046a0c90e2d3219c1877a1ca5b63a7eff4cb3
795
go
Go
ydt1363/client_ac.go
Wolzy/pub
91f36d816288a29bab595b27994db4b06c7cdfad
[ "BSD-2-Clause" ]
null
null
null
ydt1363/client_ac.go
Wolzy/pub
91f36d816288a29bab595b27994db4b06c7cdfad
[ "BSD-2-Clause" ]
null
null
null
ydt1363/client_ac.go
Wolzy/pub
91f36d816288a29bab595b27994db4b06c7cdfad
[ "BSD-2-Clause" ]
null
null
null
package gYDT1363 // 获取交流配电系统的浮点数 func (this *Client) GetACFloat(addr int) (int, error) { return this.getData(addr, Cid1AC, Cid2GetFloat, "FF", 2) } // 获取交流配电系统的整形数 func (this *Client) GetACFixed(addr int) (int, error) { return this.getData(addr, Cid1AC, Cid2GetFixed, "FF", 2) } // 获取交流配电系统的状态量 func (this *Client) GetACState(addr int) (int, error) { return this.getData(addr, Cid1AC, Cid2GetState, "FF", 2) } // 获取交流配电系统的告警量 func (this *Client) GetACWarn(addr int) (int, error) { return this.getData(addr, Cid1AC, Cid2GetWarn, "FF", 2) } // 获取设备版本 func (this *Client) GetVersion(addr int) (int, error) { return this.getData(addr, Cid1AC, Cid2GetVer, "", 0) } // 获取设备地址 func (this *Client) GetAddress(addr int) (int, error) { return this.getData(addr, Cid1AC, Cid2GetAddr, "", 0) }
24.090909
57
0.69434
70bc2512e407c7f757049df268d840f4c29fa8d5
1,653
cs
C#
Source/Script/Core/Field/FieldLabel.cs
noveosportnoy/ublockly
1f4fe699d3f7253535e95b4596f31628f93ccaae
[ "Apache-2.0" ]
87
2018-01-19T05:24:24.000Z
2022-03-31T03:50:33.000Z
Source/Script/Core/Field/FieldLabel.cs
noveosportnoy/ublockly
1f4fe699d3f7253535e95b4596f31628f93ccaae
[ "Apache-2.0" ]
34
2018-01-22T05:36:59.000Z
2021-11-19T01:13:10.000Z
Source/Script/Core/Field/FieldLabel.cs
noveosportnoy/ublockly
1f4fe699d3f7253535e95b4596f31628f93ccaae
[ "Apache-2.0" ]
32
2018-07-06T09:08:24.000Z
2022-03-12T07:05:18.000Z
/**************************************************************************** Copyright 2016 sophieml1989@gmail.com Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ****************************************************************************/ using Newtonsoft.Json.Linq; using UnityEngine; namespace UBlockly { public sealed class FieldLabel : Field { [FieldCreator(FieldType = "field_label")] private static FieldLabel CreateFromJson(JObject json) { string fieldName = json["name"].IsString() ? json["name"].ToString() : "FIELDNAME_DEFAULT"; var text = json["text"].IsString() ? Utils.ReplaceMessageReferences(json["text"].ToString()) : ""; return new FieldLabel(fieldName, text); } /// <summary> /// Class for a non-editable field. /// </summary> /// <param name="fieldName">The unique name of the field, usually defined in json block.</param> /// <param name="text">The initial content of the field</param> public FieldLabel(string fieldName, string text) : base(fieldName) { this.SetValue(text); } } }
36.733333
110
0.60859
7df98c4ced4025cc0febddbb7965cb327d34222a
4,738
sql
SQL
zeus.sql
irisroyaltyf/zeus
591cfc2d373af53ad819fb31d03b2a226cb2ffe3
[ "Apache-2.0" ]
3
2020-07-08T02:55:29.000Z
2021-04-22T00:36:22.000Z
zeus.sql
irisroyaltyf/zeus
591cfc2d373af53ad819fb31d03b2a226cb2ffe3
[ "Apache-2.0" ]
1
2021-02-18T14:03:29.000Z
2021-02-18T14:03:29.000Z
zeus.sql
irisroyaltyf/zeus
591cfc2d373af53ad819fb31d03b2a226cb2ffe3
[ "Apache-2.0" ]
4
2020-07-08T07:40:29.000Z
2021-08-14T01:19:59.000Z
-- MySQL dump 10.13 Distrib 5.7.30, for Linux (x86_64) -- -- Host: localhost Database: zeus -- ------------------------------------------------------ -- Server version 5.7.30-0ubuntu0.16.04.1 /*!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 utf8 */; /*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */; /*!40103 SET TIME_ZONE='+00:00' */; /*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */; /*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */; /*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */; /*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */; -- -- Table structure for table `zeus_collected` -- DROP TABLE IF EXISTS `zeus_collected`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `zeus_collected` ( `id` int(11) NOT NULL AUTO_INCREMENT, `url` varchar(1024) NOT NULL, `url_md5` varchar(32) NOT NULL, `publish_type` varchar(45) NOT NULL, `task_id` int(11) NOT NULL, `target` varchar(1024) DEFAULT NULL, `des` varchar(1024) DEFAULT NULL, `status` tinyint(4) NOT NULL DEFAULT '1' COMMENT '1 成功 2 失败', `gmt_create` bigint(20) NOT NULL, `title_md5` varchar(32) NOT NULL DEFAULT '', PRIMARY KEY (`id`), KEY `idx_url_md5` (`url_md5`), KEY `idx_title_md5` (`title_md5`), KEY `idx_gmt` (`gmt_create`), KEY `idx_task` (`task_id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='采集内容'; /*!40101 SET character_set_client = @saved_cs_client */; -- -- Table structure for table `zeus_config` -- DROP TABLE IF EXISTS `zeus_config`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `zeus_config` ( `id` int(11) NOT NULL AUTO_INCREMENT, `cname` varchar(45) NOT NULL, `ctype` tinyint(4) DEFAULT NULL COMMENT '1. 直接类型\n2. 数组类型', `cdata` mediumtext, `gmt_create` bigint(20) DEFAULT NULL, `gmt_modified` bigint(20) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; /*!40101 SET character_set_client = @saved_cs_client */; -- -- Table structure for table `zeus_crawler_rule` -- DROP TABLE IF EXISTS `zeus_crawler_rule`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `zeus_crawler_rule` ( `id` int(10) unsigned NOT NULL AUTO_INCREMENT, `c_name` varchar(45) DEFAULT NULL, `type` int(11) DEFAULT NULL, `config` mediumtext, `gmt_create` bigint(20) NOT NULL, `gmt_modified` bigint(20) NOT NULL, `task_id` int(11) NOT NULL DEFAULT '0', PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; /*!40101 SET character_set_client = @saved_cs_client */; -- -- Table structure for table `zeus_publish_rule` -- DROP TABLE IF EXISTS `zeus_publish_rule`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `zeus_publish_rule` ( `id` int(11) NOT NULL AUTO_INCREMENT, `p_name` varchar(45) DEFAULT NULL, `type` int(11) DEFAULT NULL, `config` mediumtext, `gmt_create` bigint(20) NOT NULL, `gmt_modified` bigint(20) NOT NULL, `task_id` int(11) NOT NULL DEFAULT '0', PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; /*!40101 SET character_set_client = @saved_cs_client */; -- -- Table structure for table `zeus_task` -- DROP TABLE IF EXISTS `zeus_task`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `zeus_task` ( `id` int(11) NOT NULL AUTO_INCREMENT, `t_name` varchar(45) NOT NULL, `group_id` int(11) DEFAULT NULL, `t_module` varchar(45) DEFAULT NULL, `t_auto` tinyint(4) NOT NULL, `last_caiji` bigint(20) NOT NULL DEFAULT '0', `t_config` mediumtext, `gmt_create` bigint(20) NOT NULL, `gmt_modified` bigint(20) NOT NULL, `cron` varchar(64) DEFAULT NULL, `status` int(11) NOT NULL DEFAULT '0', PRIMARY KEY (`id`), UNIQUE KEY `unq_t_name` (`t_name`,`group_id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; /*!40101 SET character_set_client = @saved_cs_client */; /*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */; /*!40101 SET SQL_MODE=@OLD_SQL_MODE */; /*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */; /*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */; /*!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 */; /*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */; -- Dump completed on 2020-07-09 15:44:42
35.358209
83
0.704306
7044e64a04c6b12fbf0fe0a1b7a84f92e73c1b3f
4,647
asm
Assembly
Transynther/x86/_processed/NONE/_xt_/i7-8650U_0xd2_notsx.log_4533_290.asm
ljhsiun2/medusa
67d769b8a2fb42c538f10287abaf0e6dbb463f0c
[ "MIT" ]
9
2020-08-13T19:41:58.000Z
2022-03-30T12:22:51.000Z
Transynther/x86/_processed/NONE/_xt_/i7-8650U_0xd2_notsx.log_4533_290.asm
ljhsiun2/medusa
67d769b8a2fb42c538f10287abaf0e6dbb463f0c
[ "MIT" ]
1
2021-04-29T06:29:35.000Z
2021-05-13T21:02:30.000Z
Transynther/x86/_processed/NONE/_xt_/i7-8650U_0xd2_notsx.log_4533_290.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: ret .global s_faulty_load s_faulty_load: push %r10 push %r11 push %r12 push %r13 push %r9 push %rcx push %rdx // Load lea addresses_WT+0x1e737, %rdx nop nop add $65368, %r9 mov (%rdx), %r10 nop nop nop xor %r11, %r11 // Store lea addresses_D+0x17cf7, %r12 nop nop nop nop and %r13, %r13 movl $0x51525354, (%r12) add %r9, %r9 // Store lea addresses_WC+0x144d7, %rcx nop nop nop nop nop cmp $24479, %rdx movw $0x5152, (%rcx) nop nop nop nop cmp %r10, %r10 // Store lea addresses_PSE+0xb269, %r9 nop nop nop nop nop cmp %r11, %r11 movw $0x5152, (%r9) nop add $50120, %r9 // Faulty Load lea addresses_UC+0xd8f7, %r11 xor $63565, %rdx movb (%r11), %cl lea oracles, %r9 and $0xff, %rcx shlq $12, %rcx mov (%r9,%rcx,1), %rcx pop %rdx pop %rcx pop %r9 pop %r13 pop %r12 pop %r11 pop %r10 ret /* <gen_faulty_load> [REF] {'OP': 'LOAD', 'src': {'type': 'addresses_UC', 'size': 2, 'AVXalign': True, 'NT': False, 'congruent': 0, 'same': True}} {'OP': 'LOAD', 'src': {'type': 'addresses_WT', 'size': 8, 'AVXalign': False, 'NT': False, 'congruent': 6, 'same': False}} {'OP': 'STOR', 'dst': {'type': 'addresses_D', 'size': 4, 'AVXalign': False, 'NT': False, 'congruent': 10, 'same': False}} {'OP': 'STOR', 'dst': {'type': 'addresses_WC', 'size': 2, 'AVXalign': False, 'NT': True, 'congruent': 5, 'same': False}} {'OP': 'STOR', 'dst': {'type': 'addresses_PSE', 'size': 2, 'AVXalign': False, 'NT': False, 'congruent': 1, 'same': False}} [Faulty Load] {'OP': 'LOAD', 'src': {'type': 'addresses_UC', 'size': 1, 'AVXalign': False, 'NT': False, 'congruent': 0, 'same': True}} <gen_prepare_buffer> {'37': 4533} 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 */
49.43617
2,999
0.654401
83cf107a860a65ece452ef14600cf982084f8c99
508
java
Java
JavaServer/src/main/java/com/example/springboot/dataModel/MarketInfo.java
SamYuan1990/CreditCardConsumptionforCOVID-19
2022a5fdd26c14dd1f45bb8d07c3ad0085b817bb
[ "Unlicense" ]
null
null
null
JavaServer/src/main/java/com/example/springboot/dataModel/MarketInfo.java
SamYuan1990/CreditCardConsumptionforCOVID-19
2022a5fdd26c14dd1f45bb8d07c3ad0085b817bb
[ "Unlicense" ]
2
2021-05-11T08:09:59.000Z
2021-05-11T08:40:31.000Z
JavaServer/src/main/java/com/example/springboot/dataModel/MarketInfo.java
SamYuan1990/CreditCardConsumptionforCOVID-19
2022a5fdd26c14dd1f45bb8d07c3ad0085b817bb
[ "Unlicense" ]
null
null
null
package com.example.springboot.dataModel; public class MarketInfo implements Comparable<MarketInfo> { public String Branch; public String City; public boolean equals(MarketInfo i){ return this.City.equals(i.City) & this.Branch.equals(i.Branch); } @Override public int compareTo(MarketInfo i) { if(this.equals(i)){ return 0; } return 1; } @Override public String toString(){ return this.Branch+":"+this.City; } }
21.166667
71
0.620079
e91e7fb992eeafaa1703d3955b7b349de52b323f
1,564
rb
Ruby
lib/theoj/journal.rb
xuanxu/theoj
1c823090618d38598176205463fab94ffcfbc15e
[ "MIT" ]
null
null
null
lib/theoj/journal.rb
xuanxu/theoj
1c823090618d38598176205463fab94ffcfbc15e
[ "MIT" ]
null
null
null
lib/theoj/journal.rb
xuanxu/theoj
1c823090618d38598176205463fab94ffcfbc15e
[ "MIT" ]
null
null
null
require_relative "journals_data" module Theoj class Journal attr_accessor :data attr_accessor :doi_prefix attr_accessor :url attr_accessor :name attr_accessor :alias attr_accessor :launch_date def initialize(custom_data = {}) set_data custom_data end def current_year data[:current_year] || Time.new.year end def current_volume data[:current_volume] || (Time.new.year - (launch_year - 1)) end def current_issue data[:current_issue] || (1 + ((Time.new.year * 12 + Time.new.month) - (launch_year * 12 + launch_month))) end def paper_id_from_issue(review_issue_id) id = "%05d" % review_issue_id "#{@alias}.#{id}" end def paper_doi_for_id(paper_id) "#@doi_prefix/#{paper_id}" end def reviews_repository_url(issue_id=nil) reviews_url = "https://github.com/#{data[:reviews_repository]}" if issue_id reviews_url += "/issues/" + issue_id.to_s end reviews_url end private def set_data(custom_data) @data = default_data.merge(custom_data) @doi_prefix = data[:doi_prefix] @url = data[:url] @name = data[:name] @alias = data[:alias] @launch_date = data[:launch_date] end def default_data Theoj::JOURNALS_DATA[:joss] end def parsed_launch_date @parsed_launch_date ||= Time.parse(data[:launch_date]) end def launch_year parsed_launch_date.year end def launch_month parsed_launch_date.month end end end
21.424658
111
0.640665
f53dcc17bd06f5504256474b427c2cddb21af260
1,331
cpp
C++
libs/core/src/periodic_runnable.cpp
devjsc/ledger
5681480faf6e2aeee577f149c17745d6ab4d4ab3
[ "Apache-2.0" ]
1
2019-09-11T09:46:04.000Z
2019-09-11T09:46:04.000Z
libs/core/src/periodic_runnable.cpp
devjsc/ledger
5681480faf6e2aeee577f149c17745d6ab4d4ab3
[ "Apache-2.0" ]
null
null
null
libs/core/src/periodic_runnable.cpp
devjsc/ledger
5681480faf6e2aeee577f149c17745d6ab4d4ab3
[ "Apache-2.0" ]
1
2019-09-19T12:38:46.000Z
2019-09-19T12:38:46.000Z
//------------------------------------------------------------------------------ // // Copyright 2018-2019 Fetch.AI Limited // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //------------------------------------------------------------------------------ #include "core/periodic_runnable.hpp" namespace fetch { namespace core { PeriodicRunnable::PeriodicRunnable(Duration const &period) : last_executed_{Clock::now()} , interval_{period} {} bool PeriodicRunnable::IsReadyToExecute() const { return (Clock::now() - last_executed_) >= interval_; } void PeriodicRunnable::Execute() { // call the periodic function Periodically(); last_executed_ = Clock::now(); } char const *PeriodicRunnable::GetId() const { return "PeriodicRunnable"; } } // namespace core } // namespace fetch
27.163265
80
0.630353
d48e89f70b9b14df9906f8cf9d568e7d44b55639
2,036
swift
Swift
iOS-11-by-Examples/MapKit/MapKitViewController.swift
digitallysavvy/iOS-11-by-Examples
c61f7e0bb017ec920025a17f8e8c15ca98236c7a
[ "MIT" ]
3,620
2017-06-19T02:59:59.000Z
2022-03-23T09:52:53.000Z
iOS-11-by-Examples/MapKit/MapKitViewController.swift
bshayerr/iOS-11-by-Examples
20c8516e2ffc5110223686fb122ba47cc654f625
[ "MIT" ]
21
2017-06-26T00:47:59.000Z
2019-05-31T17:24:10.000Z
iOS-11-by-Examples/MapKit/MapKitViewController.swift
bshayerr/iOS-11-by-Examples
20c8516e2ffc5110223686fb122ba47cc654f625
[ "MIT" ]
388
2017-06-22T04:30:37.000Z
2021-12-12T21:57:28.000Z
// // MapKitViewController.swift // iOS-11-by-Examples // // Created by Artem Novichkov on 08/08/2017. // Copyright © 2017 Artem Novichkov. All rights reserved. // import UIKit import MapKit class MapKitViewController: UIViewController { let annotations: [EmojiAnnotation] = { let clown = EmojiAnnotation(title: "🤡", color: .brown, type: .good, coordinate: CLLocationCoordinate2DMake(54.98, 73.30)) let developer = EmojiAnnotation(title: "👨🏻‍💻", color: .red, type: .good, coordinate: CLLocationCoordinate2DMake(54.98, 73.301)) let shit = EmojiAnnotation(title: "💩", color: .gray, type: .bad, coordinate: CLLocationCoordinate2DMake(54.98, 73.305)) return [clown, developer, shit] }() @IBOutlet weak var mapView: MKMapView! override func viewDidLoad() { super.viewDidLoad() let coordinate = CLLocationCoordinate2DMake(54.98, 73.32) let coordinateRegion = MKCoordinateRegionMakeWithDistance(coordinate, 5000, 5000) mapView.setRegion(coordinateRegion, animated: true) //New map type mapView.mapType = .mutedStandard mapView.delegate = self mapView.register(MarkerAnnotationView.self, forAnnotationViewWithReuseIdentifier: MKMapViewDefaultAnnotationViewReuseIdentifier) mapView.addAnnotations(annotations) } } extension MapKitViewController: MKMapViewDelegate { func mapView(_ mapView: MKMapView, clusterAnnotationForMemberAnnotations memberAnnotations: [MKAnnotation]) -> MKClusterAnnotation { let test = MKClusterAnnotation(memberAnnotations: memberAnnotations) test.title = "Emojis" test.subtitle = nil return test } }
35.103448
136
0.591356
80db1f1b4817abe5b36b59bc830ae9cc0255beac
3,262
java
Java
argos-collector-service/src/test/java/com/argosnotary/argos/collector/ArtifactCollectorTypeTest.java
argosnotary/argos-collector
179b0e76cac270416a04589b8ceca07e8197e06d
[ "Apache-2.0" ]
null
null
null
argos-collector-service/src/test/java/com/argosnotary/argos/collector/ArtifactCollectorTypeTest.java
argosnotary/argos-collector
179b0e76cac270416a04589b8ceca07e8197e06d
[ "Apache-2.0" ]
null
null
null
argos-collector-service/src/test/java/com/argosnotary/argos/collector/ArtifactCollectorTypeTest.java
argosnotary/argos-collector
179b0e76cac270416a04589b8ceca07e8197e06d
[ "Apache-2.0" ]
null
null
null
/* * Copyright (C) 2020 Argos Notary Coöperatie UA * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.argosnotary.argos.collector; import com.argosnotary.argos.collector.xldeploy.XLDeploySpecificationAdapter; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import javax.validation.ConstraintViolation; import javax.validation.Path; import javax.validation.Validator; import java.util.Collections; import java.util.Set; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.hasSize; import static org.hamcrest.core.Is.is; import static org.hamcrest.core.IsInstanceOf.instanceOf; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; @ExtendWith(MockitoExtension.class) class ArtifactCollectorTypeTest { private static final String PATH = "path"; private static final String MESSAGE = "message"; private ArtifactCollectorType artifactCollectorType = ArtifactCollectorType.XLDEPLOY; @Mock private Path propertyPath; @Mock private Validator validator; @Mock private ConstraintViolation constraintViolation; @Mock private SpecificationAdapter specificationAdapter; @Test void createSpecificationAdapter() { SpecificationAdapter collectorTypeSpecificationAdapter = artifactCollectorType.createSpecificationAdapter(Collections.emptyMap()); assertThat(collectorTypeSpecificationAdapter, instanceOf(XLDeploySpecificationAdapter.class)); } @Test void validateWithConstraintViolationsShouldThrowException() { when(constraintViolation.getMessage()).thenReturn(MESSAGE); when(constraintViolation.getPropertyPath()).thenReturn(propertyPath); when(propertyPath.toString()).thenReturn(PATH); when(validator.validate(any())).thenReturn(Set.of(constraintViolation)); ArtifactCollectorValidationException artifactCollectorValidationException = assertThrows(ArtifactCollectorValidationException.class, () -> artifactCollectorType.validate(specificationAdapter, validator)); assertThat(artifactCollectorValidationException.getValidationMessages(), hasSize(1)); assertThat(artifactCollectorValidationException.getValidationMessages().get(0), is(PATH + " : " + MESSAGE)); } @Test void validate() { when(validator.validate(any())).thenReturn(Collections.emptySet()); artifactCollectorType.validate(specificationAdapter, validator); verify(validator).validate(any()); } }
40.775
140
0.772532
04033b0ae55f80e4975723edf7e59bff2f3d5eb2
1,109
js
JavaScript
importer/generateInput.js
it-spectre-ru/react-movies
622422248be2584d810d630ddad8af8d93a2f655
[ "MIT" ]
null
null
null
importer/generateInput.js
it-spectre-ru/react-movies
622422248be2584d810d630ddad8af8d93a2f655
[ "MIT" ]
null
null
null
importer/generateInput.js
it-spectre-ru/react-movies
622422248be2584d810d630ddad8af8d93a2f655
[ "MIT" ]
null
null
null
let promise = require('bluebird'); let csv = require('fast-csv'); let path = require('path'); let fs = require('fs'); let jsonfile = require('jsonfile'); function readData() { return new Promise(function (resolve, reject) { let result = []; var filePath = path.join(__dirname, 'data', 'imdb_list.csv'); var fileReader = fs.createReadStream(filePath); csv .fromStream(fileReader, {headers: true}) .on('data', function (data) { result.push({ id: data.const, title: data.Title }); }) .on('error', function (err) { console.log(err); }) .on('end', function () { resolve(result); }); }); } readData() .then((data) => { let filePath = path.join(__dirname, 'data', 'input.json'); return jsonfile.writeFileSync(filePath, data); }) .then(() => { console.log('Input file was generated!'); }) .catch((err) => { console.log(err); });
26.404762
69
0.490532
810fa5183369919f18ca55cb219d95f067b8f6e3
508
go
Go
ch4/task/task4-1/main.go
dongxiem/gopl-Note
13c1b31387dec1a88042e1daeefff4fd2f1f0ab9
[ "MIT" ]
null
null
null
ch4/task/task4-1/main.go
dongxiem/gopl-Note
13c1b31387dec1a88042e1daeefff4fd2f1f0ab9
[ "MIT" ]
null
null
null
ch4/task/task4-1/main.go
dongxiem/gopl-Note
13c1b31387dec1a88042e1daeefff4fd2f1f0ab9
[ "MIT" ]
null
null
null
// 练习 4.1: 编写一个函数,计算两个SHA256哈希码中不同bit的数目。(参考2.6.2节的PopCount函数。) package main import ( "crypto/sha256" "fmt" ) func main() { sha1 := sha256.Sum256([]byte("123")) sha2 := sha256.Sum256([]byte("456")) fmt.Println(sha1, sha2) n := SHA256Count(sha1, sha2) fmt.Println("不同的数目是:", n) } // SHA256Count : 计算两个SHA256哈希码中不同bit的数目 func SHA256Count(shaOne, shaTwo [32]byte) int { var difference int for i := 0; i < len(shaOne); i++ { if shaTwo[i] != shaOne[i] { difference++ } } return difference }
18.142857
63
0.655512
c276f4ff3aeb918003e589a9ba6a0e957b7d7efb
229
swift
Swift
Core/Pay/OpenPayItem.swift
CreatorWilliam/OpenKit
7bd2db1273bb82970009adbbca826e191dc86a41
[ "MIT" ]
null
null
null
Core/Pay/OpenPayItem.swift
CreatorWilliam/OpenKit
7bd2db1273bb82970009adbbca826e191dc86a41
[ "MIT" ]
null
null
null
Core/Pay/OpenPayItem.swift
CreatorWilliam/OpenKit
7bd2db1273bb82970009adbbca826e191dc86a41
[ "MIT" ]
1
2020-08-18T12:03:52.000Z
2020-08-18T12:03:52.000Z
// // OpenPayItem.swift // OpenWithPayKit // // Created by William Lee on 2018/11/12. // Copyright © 2018 William Lee. All rights reserved. // import Foundation struct OpenPayItem { var alipayItem: AlipayPayItem? }
14.3125
54
0.689956
66cc0f788f0515f562cd8fb2eace1427f063c0bf
698
sql
SQL
_install/02-create-tables.sql
Krivodanov/mvc
aba87673476a32cf319175c286509d39e58e3071
[ "MIT" ]
1
2020-01-22T05:10:37.000Z
2020-01-22T05:10:37.000Z
_install/02-create-tables.sql
Krivodanov/MVC-template
aba87673476a32cf319175c286509d39e58e3071
[ "MIT" ]
1
2020-01-15T05:57:46.000Z
2020-01-15T05:57:46.000Z
_install/02-create-tables.sql
Krivodanov/MVC-template
aba87673476a32cf319175c286509d39e58e3071
[ "MIT" ]
null
null
null
-- phpMyAdmin SQL Dump -- version 4.5.5.1 -- http://www.phpmyadmin.net -- -- Host: 127.0.0.1 -- Generation Time: Nov 09, 2019 at 09:16 PM -- Server version: 5.7.11 -- PHP Version: 5.6.19 -- -- Table structure for table `users` -- CREATE TABLE `users` ( `id` int(11) NOT NULL AUTO_INCREMENT, `name` text COLLATE utf8_unicode_ci NOT NULL, `email` text COLLATE utf8_unicode_ci NOT NULL, `password` text COLLATE utf8_unicode_ci NOT NULL, `sessid` text COLLATE utf8_unicode_ci, `created_at` timestamp NULL DEFAULT NULL, `updated_at` timestamp NULL DEFAULT NULL, PRIMARY KEY (`id`), UNIQUE KEY `id` (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=31 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
30.347826
79
0.716332
af7c0f5c1778485e21b24e30ad75aa6ec9f9dd1b
3,409
rb
Ruby
app/controllers/workspaces_controller.rb
bornio/chorus
dddee70821d9f37bf8fca919ddc41f7204c689dd
[ "Apache-2.0" ]
null
null
null
app/controllers/workspaces_controller.rb
bornio/chorus
dddee70821d9f37bf8fca919ddc41f7204c689dd
[ "Apache-2.0" ]
null
null
null
app/controllers/workspaces_controller.rb
bornio/chorus
dddee70821d9f37bf8fca919ddc41f7204c689dd
[ "Apache-2.0" ]
1
2020-11-11T08:20:09.000Z
2020-11-11T08:20:09.000Z
class WorkspacesController < ApplicationController wrap_parameters :exclude => [] def index if params[:user_id] user = User.find(params[:user_id]) workspaces = user.workspaces.workspaces_for(current_user) else workspaces = Workspace.workspaces_for(current_user) end workspaces = workspaces.active if params[:active] present paginate(workspaces.includes([:owner, :archiver, {:sandbox => {:database => :gpdb_instance}}]).order("lower(name) ASC")), :presenter_options => {:show_latest_comments => params[:show_latest_comments] == 'true'} end def create workspace = current_user.owned_workspaces.build(params[:workspace]) Workspace.transaction do workspace.save! workspace.public ? Events::PublicWorkspaceCreated.by(current_user).add(:workspace => workspace) : Events::PrivateWorkspaceCreated.by(current_user).add(:workspace => workspace) end present workspace, :status => :created end def show workspace = Workspace.find(params[:id]) authorize! :show, workspace present workspace, :presenter_options => {:show_latest_comments => params[:show_latest_comments] == 'true'} end def update workspace = Workspace.find(params[:id]) original_archived = workspace.archived?.to_s attributes = params[:workspace] attributes[:archiver] = current_user if attributes[:archived] == 'true' workspace.attributes = attributes authorize! :update, workspace Workspace.transaction do if attributes[:schema_name] create_schema = true begin if attributes[:database_name] gpdb_instance = GpdbInstance.find(attributes[:instance_id]) database = gpdb_instance.create_database(attributes[:database_name], current_user) create_schema = false if attributes[:schema_name] == "public" else database = GpdbDatabase.find(attributes[:database_id]) end GpdbSchema.refresh(database.gpdb_instance.account_for_user!(current_user), database) if create_schema workspace.sandbox = database.create_schema(attributes[:schema_name], current_user) else workspace.sandbox = database.schemas.find_by_name(attributes[:schema_name]) end rescue Exception => e raise ApiValidationError.new(database ? :schema : :database, :generic, {:message => e.message}) end end create_workspace_events(workspace, original_archived) workspace.save! end present workspace end private def create_workspace_events(workspace, original_archived) if workspace.public_changed? workspace.public ? Events::WorkspaceMakePublic.by(current_user).add(:workspace => workspace) : Events::WorkspaceMakePrivate.by(current_user).add(:workspace => workspace) end if params[:workspace][:archived].present? && params[:workspace][:archived] != original_archived workspace.archived? ? Events::WorkspaceArchived.by(current_user).add(:workspace => workspace) : Events::WorkspaceUnarchived.by(current_user).add(:workspace => workspace) end if workspace.sandbox_id_changed? && workspace.sandbox Events::WorkspaceAddSandbox.by(current_user).add( :sandbox_schema => workspace.sandbox, :workspace => workspace ) end end end
37.461538
222
0.688178
be7431810413f774ac537a59699e2f2838b52781
445
swift
Swift
Algoritmos/Semana5-2.playground/Pages/Untitled Page 3.xcplaygroundpage/Contents.swift
fernandorazon/SwiftAlgorithms
2d64aa6a407d08309d5ed30a340690d7e838fd87
[ "MIT" ]
null
null
null
Algoritmos/Semana5-2.playground/Pages/Untitled Page 3.xcplaygroundpage/Contents.swift
fernandorazon/SwiftAlgorithms
2d64aa6a407d08309d5ed30a340690d7e838fd87
[ "MIT" ]
null
null
null
Algoritmos/Semana5-2.playground/Pages/Untitled Page 3.xcplaygroundpage/Contents.swift
fernandorazon/SwiftAlgorithms
2d64aa6a407d08309d5ed30a340690d7e838fd87
[ "MIT" ]
null
null
null
//: [Previous](@previous) import UIKit //Una clase siempre necesita constructores y una estructura no class Alumno { var numCuenta: String init(numCuenta: String){ self.numCuenta = numCuenta } deinit { print() } } class Ingenieria: Alumno { } struct Profesor { var numEmpleo: String } var marduk = Profesor(numEmpleo: "000") var parrita = Alumno(numCuenta: "55555")
11.710526
62
0.611236
9c61a25d9d0514b94c6a4b5e4c8810ac27f06c67
5,113
cpp
C++
OSkernel/abstract-machine/apps/fceux/src/boards/8237.cpp
vocaltract/ProjectsDemonstration
5930ea2bd225d1e04a5bdb056d0f1c0744a6fe8c
[ "BSD-3-Clause" ]
null
null
null
OSkernel/abstract-machine/apps/fceux/src/boards/8237.cpp
vocaltract/ProjectsDemonstration
5930ea2bd225d1e04a5bdb056d0f1c0744a6fe8c
[ "BSD-3-Clause" ]
null
null
null
OSkernel/abstract-machine/apps/fceux/src/boards/8237.cpp
vocaltract/ProjectsDemonstration
5930ea2bd225d1e04a5bdb056d0f1c0744a6fe8c
[ "BSD-3-Clause" ]
null
null
null
/* FCE Ultra - NES/Famicom Emulator * * Copyright notice for this file: * Copyright (C) 2011 CaH4e3 * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * * Super Game (Sugar Softec) protected mapper * Pocahontas 2 (Unl) [U][!], etc. * TODO: 9in1 LION KING HANGS! */ #include "mapinc.h" #include "mmc3.h" static uint8 cmdin; static uint8 regperm[8][8] = { { 0, 1, 2, 3, 4, 5, 6, 7 }, { 0, 2, 6, 1, 7, 3, 4, 5 }, { 0, 5, 4, 1, 7, 2, 6, 3 }, // unused { 0, 6, 3, 7, 5, 2, 4, 1 }, { 0, 2, 5, 3, 6, 1, 7, 4 }, { 0, 1, 2, 3, 4, 5, 6, 7 }, // empty { 0, 1, 2, 3, 4, 5, 6, 7 }, // empty { 0, 1, 2, 3, 4, 5, 6, 7 }, // empty }; static uint8 adrperm[8][8] = { { 0, 1, 2, 3, 4, 5, 6, 7 }, { 3, 2, 0, 4, 1, 5, 6, 7 }, { 0, 1, 2, 3, 4, 5, 6, 7 }, // unused { 5, 0, 1, 2, 3, 7, 6, 4 }, { 3, 1, 0, 5, 2, 4, 6, 7 }, { 0, 1, 2, 3, 4, 5, 6, 7 }, // empty { 0, 1, 2, 3, 4, 5, 6, 7 }, // empty { 0, 1, 2, 3, 4, 5, 6, 7 }, // empty }; static void UNL8237CW(uint32 A, uint8 V) { if (EXPREGS[0] & 0x40) setchr1(A, ((EXPREGS[1] & 0xc) << 6) | (V & 0x7F) | ((EXPREGS[1] & 0x20) << 2)); else setchr1(A, ((EXPREGS[1] & 0xc) << 6) | V); } static void UNL8237PW(uint32 A, uint8 V) { if (EXPREGS[0] & 0x40) { uint8 sbank = (EXPREGS[1] & 0x10); if (EXPREGS[0] & 0x80) { uint8 bank = ((EXPREGS[1] & 3) << 4) | (EXPREGS[0] & 0x7) | (sbank >> 1); if (EXPREGS[0] & 0x20) setprg32(0x8000, bank >> 1); else{ setprg16(0x8000, bank); setprg16(0xC000, bank); } } else setprg8(A, ((EXPREGS[1] & 3) << 5) | (V & 0x0F) | sbank); } else { if (EXPREGS[0] & 0x80) { uint8 bank = ((EXPREGS[1] & 3) << 4) | (EXPREGS[0] & 0xF); if (EXPREGS[0] & 0x20) setprg32(0x8000, bank >> 1); else{ setprg16(0x8000, bank); setprg16(0xC000, bank); } } else setprg8(A, ((EXPREGS[1] & 3) << 5) | (V & 0x1F)); } } static void UNL8237ACW(uint32 A, uint8 V) { if (EXPREGS[0] & 0x40) setchr1(A, ((EXPREGS[1] & 0xE) << 7) | (V & 0x7F) | ((EXPREGS[1] & 0x20) << 2)); else setchr1(A, ((EXPREGS[1] & 0xE) << 7) | V); } static void UNL8237APW(uint32 A, uint8 V) { if (EXPREGS[0] & 0x40) { uint8 sbank = (EXPREGS[1] & 0x10); if (EXPREGS[0] & 0x80) { uint8 bank = ((EXPREGS[1] & 3) << 4) | ((EXPREGS[1] & 8) << 3) | (EXPREGS[0] & 0x7) | (sbank >> 1); if (EXPREGS[0] & 0x20) { // FCEU_printf("8000:%02X\n",bank>>1); setprg32(0x8000, bank >> 1); } else { // FCEU_printf("8000-C000:%02X\n",bank); setprg16(0x8000, bank); setprg16(0xC000, bank); } } else { // FCEU_printf("%04x:%02X\n",A,((EXPREGS[1]&3)<<5)|((EXPREGS[1]&8)<<4)|(V&0x0F)|sbank); setprg8(A, ((EXPREGS[1] & 3) << 5) | ((EXPREGS[1] & 8) << 4) | (V & 0x0F) | sbank); } } else { if (EXPREGS[0] & 0x80) { uint8 bank = ((EXPREGS[1] & 3) << 4) | ((EXPREGS[1] & 8) << 3) | (EXPREGS[0] & 0xF); if (EXPREGS[0] & 0x20) { // FCEU_printf("8000:%02X\n",(bank>>1)&0x07); setprg32(0x8000, bank >> 1); } else { // FCEU_printf("8000-C000:%02X\n",bank&0x0F); setprg16(0x8000, bank); setprg16(0xC000, bank); } } else { // FCEU_printf("%04X:%02X\n",A,(((EXPREGS[1]&3)<<5)|((EXPREGS[1]&8)<<4)|(V&0x1F))&0x1F); setprg8(A, ((EXPREGS[1] & 3) << 5) | ((EXPREGS[1] & 8) << 4) | (V & 0x1F)); } } } static DECLFW(UNL8237Write) { uint8 dat = V; uint8 adr = adrperm[EXPREGS[2]][((A >> 12) & 6) | (A & 1)]; uint16 addr = (adr & 1) | ((adr & 6) << 12) | 0x8000; if (adr < 4) { if (!adr) dat = (dat & 0xC0) | (regperm[EXPREGS[2]][dat & 7]); MMC3_CMDWrite(addr, dat); } else MMC3_IRQWrite(addr, dat); } static DECLFW(UNL8237ExWrite) { switch (A) { case 0x5000: EXPREGS[0] = V; FixMMC3PRG(MMC3_cmd); break; case 0x5001: EXPREGS[1] = V; FixMMC3PRG(MMC3_cmd); FixMMC3CHR(MMC3_cmd); break; case 0x5007: EXPREGS[2] = V; break; } } static void UNL8237Power(void) { EXPREGS[0] = EXPREGS[2] = 0; EXPREGS[1] = 3; GenMMC3Power(); SetWriteHandler(0x8000, 0xFFFF, UNL8237Write); SetWriteHandler(0x5000, 0x7FFF, UNL8237ExWrite); } void UNL8237_Init(CartInfo *info) { GenMMC3_Init(info, 256, 256, 0, 0); cwrap = UNL8237CW; pwrap = UNL8237PW; info->Power = UNL8237Power; AddExState(EXPREGS, 3, 0, "EXPR"); AddExState(&cmdin, 1, 0, "CMDI"); } void UNL8237A_Init(CartInfo *info) { GenMMC3_Init(info, 256, 256, 0, 0); cwrap = UNL8237ACW; pwrap = UNL8237APW; info->Power = UNL8237Power; AddExState(EXPREGS, 3, 0, "EXPR"); AddExState(&cmdin, 1, 0, "CMDI"); }
29.385057
102
0.570702
17b1f59dc1ccbc3a19eb07f2fb0269c6c7ee3f05
2,973
cs
C#
source/Playnite/Database/Collections/CompletionStatusesCollection.cs
grnassar/Playnite
c2a2138fa4bb233734b7e1f71b1f444bbb7ee0de
[ "MIT" ]
4,203
2017-04-29T16:57:20.000Z
2022-03-31T14:12:39.000Z
source/Playnite/Database/Collections/CompletionStatusesCollection.cs
grnassar/Playnite
c2a2138fa4bb233734b7e1f71b1f444bbb7ee0de
[ "MIT" ]
2,639
2017-03-28T20:37:25.000Z
2022-03-31T15:02:21.000Z
source/Playnite/Database/Collections/CompletionStatusesCollection.cs
grnassar/Playnite
c2a2138fa4bb233734b7e1f71b1f444bbb7ee0de
[ "MIT" ]
510
2017-03-28T19:48:08.000Z
2022-03-29T23:08:17.000Z
using LiteDB; using Playnite.SDK; using Playnite.SDK.Models; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Playnite.Database { public class CompletionStatusSettings { [BsonId(false)] public int Id { get; set; } = 0; public Guid DefaultStatus { get; set; } public Guid PlayedStatus { get; set; } } public class CompletionStatusesCollection : ItemCollection<CompletionStatus> { private readonly GameDatabase db; private LiteCollection<CompletionStatusSettings> settingsCollection; private LiteCollection<CompletionStatusSettings> SettingsCollection { get { if (settingsCollection == null) { settingsCollection = liteDb.GetCollection<CompletionStatusSettings>(); } return settingsCollection; } } public CompletionStatusesCollection(GameDatabase database, LiteDB.BsonMapper mapper) : base(mapper, type: GameDatabaseCollection.CompletionStatuses) { db = database; } public CompletionStatusSettings GetSettings() { if (SettingsCollection.Count() == 0) { var settings = new CompletionStatusSettings(); SettingsCollection.Insert(settings); return settings; } else { return SettingsCollection.FindAll().First(); } } public void SetSettings(CompletionStatusSettings settings) { settings.Id = 0; SettingsCollection.Upsert(settings); } public static void MapLiteDbEntities(LiteDB.BsonMapper mapper) { mapper.Entity<CompletionStatus>().Id(a => a.Id, false); } private void RemoveUsage(Guid statusId) { foreach (var game in db.Games.Where(a => a.CompletionStatusId == statusId)) { game.CompletionStatusId = Guid.Empty; db.Games.Update(game); } } public override bool Remove(CompletionStatus itemToRemove) { RemoveUsage(itemToRemove.Id); return base.Remove(itemToRemove); } public override bool Remove(Guid id) { RemoveUsage(id); return base.Remove(id); } public override bool Remove(IEnumerable<CompletionStatus> itemsToRemove) { if (itemsToRemove.HasItems()) { foreach (var item in itemsToRemove) { RemoveUsage(item.Id); } } return base.Remove(itemsToRemove); } } }
28.864078
157
0.54255
fbcba33e70a5bc5260b3326e3a6b8793cc72df79
263
h
C
node_modules/lzz-gyp/lzz-source/gram_FileStatPtr.h
SuperDizor/dizornator
9f57dbb3f6af80283b4d977612c95190a3d47900
[ "ISC" ]
3
2019-09-18T16:44:33.000Z
2021-03-29T13:45:27.000Z
node_modules/lzz-gyp/lzz-source/gram_FileStatPtr.h
SuperDizor/dizornator
9f57dbb3f6af80283b4d977612c95190a3d47900
[ "ISC" ]
null
null
null
node_modules/lzz-gyp/lzz-source/gram_FileStatPtr.h
SuperDizor/dizornator
9f57dbb3f6af80283b4d977612c95190a3d47900
[ "ISC" ]
2
2019-03-29T01:06:38.000Z
2019-09-18T16:44:34.000Z
// gram_FileStatPtr.h // #ifndef LZZ_gram_FileStatPtr_h #define LZZ_gram_FileStatPtr_h #include "util_BPtr.h" #define LZZ_INLINE inline namespace gram { class FileStat; } namespace gram { typedef util::BPtr <FileStat> FileStatPtr; } #undef LZZ_INLINE #endif
14.611111
44
0.779468
b78925a2a1c4566e831580ce99c22105e7d70d1b
845
sql
SQL
data/test/sql/b78925a2a1c4566e831580ce99c22105e7d70d1b122.sql
aliostad/deep-learning-lang-detection
d6b031f3ebc690cf2ffd0ae1b08ffa8fb3b38a62
[ "MIT" ]
84
2017-10-25T15:49:21.000Z
2021-11-28T21:25:54.000Z
data/test/sql/b78925a2a1c4566e831580ce99c22105e7d70d1b122.sql
vassalos/deep-learning-lang-detection
cbb00b3e81bed3a64553f9c6aa6138b2511e544e
[ "MIT" ]
5
2018-03-29T11:50:46.000Z
2021-04-26T13:33:18.000Z
data/test/sql/b78925a2a1c4566e831580ce99c22105e7d70d1b122.sql
vassalos/deep-learning-lang-detection
cbb00b3e81bed3a64553f9c6aa6138b2511e544e
[ "MIT" ]
24
2017-11-22T08:31:00.000Z
2022-03-27T01:22:31.000Z
DROP TABLE adnet_registrations; CREATE TABLE adnet_registrations( registration_date date SORTKEY DISTKEY, registration_adnet character varying(128), days_ago integer, num_registrations bigint ); GRANT SELECT ON adnet_registrations TO GROUP READ_ONLY; GRANT ALL ON adnet_registrations TO GROUP READ_WRITE; GRANT ALL ON adnet_registrations TO GROUP SCHEMA_MANAGER; drop TABLE adnet_registrations_tmp_data; CREATE TABLE adnet_registrations_tmp_data( registration_date date SORTKEY DISTKEY, registration_adnet character varying(128), num_registrations bigint ); GRANT SELECT ON adnet_registrations_tmp_data TO GROUP READ_ONLY; GRANT ALL ON adnet_registrations_tmp_data TO GROUP READ_WRITE; GRANT ALL ON adnet_registrations_tmp_data TO GROUP SCHEMA_MANAGER; --doesn't need maintaining as it's completely rebuilt every time.
29.137931
66
0.835503
b13204dae7d712c129673b2adc9e5983ff9d21fb
280
css
CSS
styles.css
nikz99/electron-angular-stub
2ad38de11e0a04b0f7205fe86471365586e1ad53
[ "CC0-1.0", "MIT" ]
null
null
null
styles.css
nikz99/electron-angular-stub
2ad38de11e0a04b0f7205fe86471365586e1ad53
[ "CC0-1.0", "MIT" ]
null
null
null
styles.css
nikz99/electron-angular-stub
2ad38de11e0a04b0f7205fe86471365586e1ad53
[ "CC0-1.0", "MIT" ]
null
null
null
html{ margin:0px; padding:0px; } body{ text-align: center; margin:0px; position:absolute; padding:0px; margin:1px; border:1px solid #DDD; } #drag-region{ position:absolute; -webkit-app-region: drag; }
14.736842
31
0.528571
4438fdae5a6e514b6d9194432377b770fab02e97
1,561
ps1
PowerShell
automatic/geogebra-geometry/update.ps1
TheCakeIsNaOH/Chocolatey-Packages-2
b2fa8d3d9286b28690754b496737483e5ed9c1f5
[ "MIT" ]
10
2019-07-10T11:16:44.000Z
2021-03-21T14:30:43.000Z
automatic/geogebra-geometry/update.ps1
TheCakeIsNaOH/Chocolatey-Packages-2
b2fa8d3d9286b28690754b496737483e5ed9c1f5
[ "MIT" ]
42
2019-07-16T17:55:09.000Z
2022-02-25T18:09:07.000Z
automatic/geogebra-geometry/update.ps1
TheCakeIsNaOH/Chocolatey-Packages-2
b2fa8d3d9286b28690754b496737483e5ed9c1f5
[ "MIT" ]
40
2019-07-26T15:08:54.000Z
2022-03-23T01:45:10.000Z
import-module au [Net.ServicePointManager]::SecurityProtocol = [System.Net.SecurityProtocolType]::Tls12 function global:au_BeforeUpdate { Get-RemoteFiles -NoSuffix -Purge } function global:au_GetLatest { $url = get-redirectedurl https://download.geogebra.org/package/windows-geometry $regex = 'GeoGebraGeometry-Windows-Installer-(?<Version>[\d\-]+).exe' $url -match $regex | Out-Null return @{ Version = $matches.Version -replace '-', '.' URL32 = 'https://download.geogebra.org/installers/6.0/geometry/GeoGebraGeometry-Windows-Installer-' + $matches.Version + '.exe' } } function global:au_SearchReplace { @{ "legal\VERIFICATION.txt" = @{ "(?i)(x32: ).*" = "`${1}$($Latest.URL32)" "(?i)(x64: ).*" = "`${1}$($Latest.URL32)" "(?i)(checksum type:\s+).*" = "`${1}$($Latest.ChecksumType32)" "(?i)(checksum32:).*" = "`${1} $($Latest.Checksum32)" "(?i)(checksum64:).*" = "`${1} $($Latest.Checksum32)" } "tools\chocolateyinstall.ps1" = @{ "(?i)(^\s*[$]file\s*=\s*')(.*)'" = "`$1$($Latest.FileName32)'" } } } if ($MyInvocation.InvocationName -ne '.') { # run the update only if script is not sourced try { update -ChecksumFor none } catch { $ignore = 'The request was aborted: Could not create SSL/TLS secure channel.' if ($_ -match $ignore) { Write-Host $ignore; 'ignore' } else { throw $_ } } }
38.073171
135
0.547726
280103af5f5d3298e896457d13f27176870b7562
6,251
cpp
C++
cpp/src/example_libxtreemfs/example_replication.cpp
chrkl/xtreemfs
528951b7f0c1858379bebeafee40bc7f7ce94783
[ "Apache-2.0" ]
270
2015-01-03T22:15:03.000Z
2022-03-14T03:45:59.000Z
cpp/src/example_libxtreemfs/example_replication.cpp
chrkl/xtreemfs
528951b7f0c1858379bebeafee40bc7f7ce94783
[ "Apache-2.0" ]
84
2015-01-05T10:14:40.000Z
2022-03-10T21:11:13.000Z
cpp/src/example_libxtreemfs/example_replication.cpp
chrkl/xtreemfs
528951b7f0c1858379bebeafee40bc7f7ce94783
[ "Apache-2.0" ]
59
2015-03-07T23:53:19.000Z
2022-02-22T07:33:13.000Z
/* * Copyright (c) 2011 by Michael Berlin, Zuse Institute Berlin * * Licensed under the BSD License, see LICENSE file for details. * */ #include <cstring> #include <iostream> #include <list> #include <string> #include "libxtreemfs/client.h" #include "libxtreemfs/file_handle.h" #include "libxtreemfs/options.h" #include "libxtreemfs/volume.h" #include "libxtreemfs/xtreemfs_exception.h" #include "pbrpc/RPC.pb.h" // xtreemfs::pbrpc::UserCredentials #include "xtreemfs/MRC.pb.h" // xtreemfs::pbrpc::Stat using namespace std; int main(int argc, char* argv[]) { // Every operation is executed in the context of a given user and his groups. // The UserCredentials object does store this information and is currently // (08/2011) *only* evaluated by the MRC (although the protocol requires to // send user_credentials to DIR and OSD, too). xtreemfs::pbrpc::UserCredentials user_credentials; user_credentials.set_username("example_libxtreemfs"); user_credentials.add_groups("example_libxtreemfs"); // Class which allows to change options of the library. xtreemfs::Options options; try { options.ParseCommandLine(argc, argv); } catch(const xtreemfs::XtreemFSException& e) { cout << "Invalid parameters found, error: " << e.what() << endl << endl; return 1; } xtreemfs::Client* client = NULL; xtreemfs::FileHandle* file = NULL; int return_code = 0; try { // Create a new instance of a client using the DIR service at // localhost because we need extended priviliges. // This requires the DIR with etc/xos/xtreemfs/dirconfig.test, // an OSD with osdconfig.test, an OSD with osdconfig2.test and // an MRC with mrcconfig.test, all of them on localhost. client = xtreemfs::Client::CreateClient( "localhost:32638", user_credentials, NULL, // No SSL options. options); // Start the client (a connection to the DIR service will be setup). client->Start(); // setup the auth object xtreemfs::pbrpc::Auth auth = xtreemfs::pbrpc::Auth::default_instance(); auth.set_auth_type(xtreemfs::pbrpc::AUTH_NONE); // Create a new volume named 'demo'. xtreemfs::pbrpc::Volumes *volumes = client->ListVolumes("localhost:32636", auth); bool has_volume = false; for(int i = 0; i < volumes->volumes_size() && !has_volume; ++i) { has_volume = volumes->volumes(i).name().compare("demo") == 0; } if(has_volume) { client->DeleteVolume("localhost:32636", auth, user_credentials, "demo"); } client->CreateVolume("localhost:32636", auth, user_credentials, "demo"); // Open the volume. xtreemfs::Volume *volume = NULL; volume = client->OpenVolume("demo", NULL, // No SSL options. options); // Open a file. file = volume->OpenFile(user_credentials, "/example_replication.txt", static_cast<xtreemfs::pbrpc::SYSTEM_V_FCNTL>( xtreemfs::pbrpc::SYSTEM_V_FCNTL_H_O_CREAT | xtreemfs::pbrpc::SYSTEM_V_FCNTL_H_O_TRUNC | xtreemfs::pbrpc::SYSTEM_V_FCNTL_H_O_RDWR), 511); // = 777 Octal. // Write to file. cout << "Writing the string\n" "\n" "\t\"Replication Example.\"\n" "\n" "to the file example_replication.txt..." << endl; char write_buf[] = "Replication Example."; file->Write(reinterpret_cast<const char*>(&write_buf), sizeof(write_buf), 0); cout << endl << "Closing /example_replication.txt... "; file->Close(); file = NULL; cout << "ok!" << endl; // mark the file as read-only cout << endl << "Marking /example_replication.txt read only... "; volume->SetReplicaUpdatePolicy(user_credentials, "/example_replication.txt", "ronly"); cout << "ok!" << endl; // list replica(s) and their OSD(s) // we expect one replica and one OSD here because we created a new volume above xtreemfs::pbrpc::Replicas* replicas = volume->ListReplicas(user_credentials, "/example_replication.txt"); const int repls = replicas->replicas_size(); cout << endl << repls << " replica(s) for /example_replication.txt:" << endl; for(int i = 0; i < repls; ++i) { xtreemfs::pbrpc::Replica replica = replicas->replicas(i); const int osds = replica.osd_uuids_size(); cout << "\t" << osds << " OSD(s) for replica " << i << ":"; for(int j = 0; j < osds; ++j) { cout << " " << replica.osd_uuids(j); } cout << endl; } // grab one suitable OSD which we can use for manual replication of the file list<string> osd_uuids; volume->GetSuitableOSDs(user_credentials, "/example_replication.txt", 1, &osd_uuids); // replicate to second OSD if available if(osd_uuids.size() > 0) { string osd_uuid = osd_uuids.front(); cout << endl << "Replicating to suitable OSD " << osd_uuid << "... "; // add replication xtreemfs::pbrpc::Replica replica; replica.add_osd_uuids(osd_uuid); // read-only files have partial replication by default, we want full replica.set_replication_flags(xtreemfs::pbrpc::REPL_FLAG_FULL_REPLICA | xtreemfs::pbrpc::REPL_FLAG_STRATEGY_RAREST_FIRST); xtreemfs::pbrpc::StripingPolicy *striping = new xtreemfs::pbrpc::StripingPolicy; striping->set_type(xtreemfs::pbrpc::STRIPING_POLICY_RAID0); striping->set_stripe_size(128); striping->set_width(1); replica.set_allocated_striping_policy(striping); volume->AddReplica(user_credentials, "/example_replication.txt", replica); cout << "ok!" << endl; } else { cout << endl << "No second OSD found for replication." << endl; } } catch(const xtreemfs::XtreemFSException& e) { cout << "An error occurred:\n" << e.what() << endl; return_code = 1; } if (file != NULL) { // Close the file (no need to delete it, see documentation volume.h). file->Close(); } if (client != NULL) { // Shutdown() does also invoke a volume->Close(). client->Shutdown(); delete client; } return return_code; }
36.343023
124
0.636058
5dbd0e58807b3db3da9d6d391c25f77998151595
19,784
go
Go
rpc/notifications/notifications.go
konradreiche/engine
42933c15f66aaaab6ed52cbe68ea521f479eb33c
[ "MIT" ]
1
2020-10-08T21:07:16.000Z
2020-10-08T21:07:16.000Z
rpc/notifications/notifications.go
october93/engine
4fdfd55c3ae079401c064c4933d4a264b84d54c8
[ "MIT" ]
null
null
null
rpc/notifications/notifications.go
october93/engine
4fdfd55c3ae079401c064c4933d4a264b84d54c8
[ "MIT" ]
null
null
null
package notifications import ( "database/sql" "fmt" "math" "regexp" "strconv" "strings" "time" "github.com/october93/engine/kit/globalid" "github.com/october93/engine/model" "github.com/october93/engine/store" "github.com/pkg/errors" ) const andText = " and " type NotificationUser interface { DisplayName() string } type Notifications struct { store *store.Store systemProfileImage string unitsPerCoin int64 } var ErrNotificationEmpty = errors.New("Notification Empty") func formatName(name string, anon bool) string { r := name if anon { r = "!" + r } return "**" + r + "**" } func emphasize(t string) string { return fmt.Sprintf("**%v**", t) } func formatNames(users []NotificationUser) string { // "Bob", "Bob and Joe", "Bob, Joe, and 2 others" text text := "" numUsers := len(users) if numUsers >= 1 { text = emphasize(users[0].DisplayName()) } if numUsers >= 2 { if numUsers == 2 { text += andText } else { text += ", " } text += emphasize(users[1].DisplayName()) } if numUsers >= 3 { text += fmt.Sprintf(", and %v other", numUsers-2) } // turns "other" into "others" for 4+ boosters if numUsers >= 4 { text += "s" } return text } func NewNotifications(store *store.Store, systemProfileImage string, unitsPerCoin int64) *Notifications { return &Notifications{ store: store, systemProfileImage: systemProfileImage, unitsPerCoin: unitsPerCoin, } } func (ns *Notifications) ExportNotification(n *model.Notification) (*model.ExportedNotification, error) { switch n.Type { case model.CommentType: return ns.exportCommentNotification(n) case model.MentionType: return ns.exportMentionNotification(n) case model.BoostType: return ns.exportBoostNotification(n) case model.InviteAcceptedType: return ns.exportInviteAcceptedNotification(n) case model.AnnouncementType: return ns.exportAnnouncementNotification(n) case model.IntroductionType: return ns.exportIntroductionNotification(n) case model.FollowType: return ns.exportFollowNotification(n) case model.NewInvitesType: return ns.exportNewInvitesNotification(n) case model.CoinsReceivedType: return ns.exportCoinsReceivedNotification(n) case model.PopularPostType: return ns.exportPopularPostNotification(n) case model.FirstPostActivityType: return ns.exportFirstPostActivityNotification(n) case model.LeaderboardRankType: return ns.exportLeaderboardRankNotification(n) } return nil, errors.New("Export Notification Unknown Type Error") } func (ns *Notifications) exportPopularPostNotification(n *model.Notification) (*model.ExportedNotification, error) { notification := &model.ExportedNotification{ ID: n.ID, UserID: n.UserID, ImagePath: ns.systemProfileImage, Message: `💥 BOOM! Your recent posts got lot of attention, here's an extra 20 coins.`, Timestamp: n.CreatedAt.Unix(), Type: n.Type, Action: model.OpenWalletAction, } if n.SeenAt.Valid { notification.Seen = n.SeenAt.Time.Before(time.Now().UTC()) } if n.OpenedAt.Valid { notification.Opened = n.OpenedAt.Time.Before(time.Now().UTC()) } return notification, nil } func (ns *Notifications) exportFirstPostActivityNotification(n *model.Notification) (*model.ExportedNotification, error) { notification := &model.ExportedNotification{ ID: n.ID, UserID: n.UserID, ImagePath: ns.systemProfileImage, Message: `👀 Your posts are starting to get some attention! Here’s an extra 10 coins, post more great stuff!`, Timestamp: n.CreatedAt.Unix(), Type: n.Type, Action: model.OpenWalletAction, } if n.SeenAt.Valid { notification.Seen = n.SeenAt.Time.Before(time.Now().UTC()) } if n.OpenedAt.Valid { notification.Opened = n.OpenedAt.Time.Before(time.Now().UTC()) } return notification, nil } func numberWithOrdinal(n int) string { withOrd := strconv.Itoa(n) if strings.HasSuffix(withOrd, "11") || strings.HasSuffix(withOrd, "12") || strings.HasSuffix(withOrd, "13") { withOrd += "th" } else if strings.HasSuffix(withOrd, "1") { withOrd += "st" } else if strings.HasSuffix(withOrd, "2") { withOrd += "nd" } else if strings.HasSuffix(withOrd, "3") { withOrd += "rd" } else { withOrd += "th" } return withOrd } func (ns *Notifications) exportLeaderboardRankNotification(n *model.Notification) (*model.ExportedNotification, error) { notifData, err := ns.store.GetLeaderboardNotificationExportData(n.ID) if err != nil && errors.Cause(err) == sql.ErrNoRows { return nil, ErrNotificationEmpty } else if err != nil { return nil, err } message := "🏅 You made the leaderboard on October today! You earned 10 Coins 💰💰💰. Think you can make the top 10 today?" if notifData.Rank == 1 { message = "🥇 Wow, you were the #1 top contributor on October yesterday! You earned 100 Coins 💰💰💰. Can you defend your position?" } else if notifData.Rank == 2 { message = "🥈 Game on! You made it to the runner-up slot on the leaderboard. You earned 50 Coins 💰💰. Can you make it to the top spot today?" } else if notifData.Rank == 3 { message = "🥉 Woo! You made third place on the leaderboard yesterday. You earned 30 Coins 💰💰💰. Can you make it to the top spot today?" } else if notifData.Rank > 3 && notifData.Rank <= 10 { message = fmt.Sprintf("🏅 Wow, you were the %v top contributor on October yesterday! You earned 20 Coins 💰💰💰. Can you hit the Top 3 today?", numberWithOrdinal(int(notifData.Rank))) } notification := &model.ExportedNotification{ ID: n.ID, UserID: n.UserID, ImagePath: ns.systemProfileImage, Message: message, Timestamp: n.CreatedAt.Unix(), Type: n.Type, Action: model.NavigateToAction, ActionData: map[string]string{ "mobileRouteName": "leaderboard", "webRouteName": "leaderboard", }, } if n.SeenAt.Valid { notification.Seen = n.SeenAt.Time.Before(time.Now().UTC()) } if n.OpenedAt.Valid { notification.Opened = n.OpenedAt.Time.Before(time.Now().UTC()) } return notification, nil } func (ns *Notifications) exportCoinsReceivedNotification(n *model.Notification) (*model.ExportedNotification, error) { var message string var pluralizedCoins string notifData, err := ns.store.GetCoinsReceivedNotificationData(n) if err != nil { return nil, err } coinAmount := int64(math.Floor(float64(notifData.CoinsReceived) / float64(ns.unitsPerCoin))) if coinAmount > 1 { pluralizedCoins = fmt.Sprintf("%v Coins", coinAmount) } else { pluralizedCoins = "a Coin" } if !notifData.LastRewardedOn.Valid { // send a kickoff notification message = fmt.Sprintf("You got %v from your past posts and reactions!", pluralizedCoins) } else { // send a regular daily notification message = fmt.Sprintf("You got %v from your activity yesterday!", pluralizedCoins) } notification := &model.ExportedNotification{ ID: n.ID, UserID: n.UserID, ImagePath: ns.systemProfileImage, Message: message, Timestamp: n.CreatedAt.Unix(), Type: n.Type, Action: model.OpenWalletAction, ActionData: map[string]string{}, } if n.SeenAt.Valid { notification.Seen = n.SeenAt.Time.Before(time.Now().UTC()) } if n.OpenedAt.Valid { notification.Opened = n.OpenedAt.Time.Before(time.Now().UTC()) } return notification, nil } func (ns *Notifications) exportNewInvitesNotification(n *model.Notification) (*model.ExportedNotification, error) { if n.Type != model.NewInvitesType { return nil, errors.New("wrong notification type") } notification := &model.ExportedNotification{ ID: n.ID, UserID: n.UserID, ImagePath: ns.systemProfileImage, Message: `You’ve received new invites to October. Invite someone awesome!`, Timestamp: n.CreatedAt.Unix(), Type: n.Type, Action: model.OpenInvitesAction, ActionData: map[string]string{}, } if n.SeenAt.Valid { notification.Seen = n.SeenAt.Time.Before(time.Now().UTC()) } if n.OpenedAt.Valid { notification.Opened = n.OpenedAt.Time.Before(time.Now().UTC()) } return notification, nil } func (ns *Notifications) exportCommentNotification(n *model.Notification) (*model.ExportedNotification, error) { notifData, err := ns.store.GetCommentExportData(n) if errors.Cause(err) != sql.ErrNoRows && err != nil { return nil, err } else if errors.Cause(err) == sql.ErrNoRows || len(notifData.Comments) <= 0 { return nil, ErrNotificationEmpty } latestComment := notifData.Comments[0] // "Bob", "Bob and Joe", "Bob, Joe, and 2 others" text nU := make([]NotificationUser, len(notifData.Comments)) for i, v := range notifData.Comments { nU[i] = NotificationUser(v) } commentersText := formatNames(nU) // your post or someone else's also := " also" ownerName := notifData.PosterName + "'s" if notifData.RootOwnerID == n.UserID { also = "" ownerName = "your" } if notifData.RootOwnerID == latestComment.AuthorID && !latestComment.IsAnonymous && !notifData.RootIsAnonymous { also = "" ownerName = "their" } // ": 'Content'" text sanitized := sanitizeAndTruncateContent(notifData.CardContent, 80) nonWhitespaceRegex := regexp.MustCompile(`[^\s]+`) postTail := "." if nonWhitespaceRegex.FindStringIndex(sanitized) != nil { postTail = fmt.Sprintf(`: "%v"`, sanitized) } message := fmt.Sprintf("%v%v commented on %v post%v", commentersText, also, ownerName, postTail) actionData := map[string]string{ "threadRootID": notifData.ThreadRootID.String(), "commentCardID": notifData.LatestCommentID.String(), "commentCardUsername": latestComment.AuthorUsername, } if notifData.LatestCommentParentID != globalid.Nil && notifData.LatestCommentParentID != notifData.ThreadRootID { actionData["parentCommentID"] = notifData.LatestCommentParentID.String() } eNotif := model.ExportedNotification{ ID: n.ID, UserID: n.UserID, ImagePath: latestComment.ImagePath, Message: message, Timestamp: latestComment.Timestamp.Unix(), Type: n.Type, Action: model.OpenThreadAction, ActionData: actionData, } if n.SeenAt.Valid { eNotif.Seen = n.SeenAt.Time.Before(time.Now().UTC()) } if n.OpenedAt.Valid { eNotif.Opened = n.OpenedAt.Time.Before(time.Now().UTC()) } return &eNotif, nil } func (ns *Notifications) exportBoostNotification(n *model.Notification) (*model.ExportedNotification, error) { notifData, err := ns.store.GetLikeNotificationExportData(n) if errors.Cause(err) != sql.ErrNoRows && err != nil { return nil, err } else if errors.Cause(err) == sql.ErrNoRows || len(notifData.Boosts) <= 0 { return nil, ErrNotificationEmpty } latestBoost := notifData.Boosts[0] // "Bob", "Bob and Joe", "Bob, Joe, and 2 others" text nU := make([]NotificationUser, len(notifData.Boosts)) for i, v := range notifData.Boosts { nU[i] = NotificationUser(v) } boostersText := formatNames(nU) postOrComment := "post" if notifData.IsComment { postOrComment = "comment" } sanitized := sanitizeAndTruncateContent(notifData.CardContent, 80) nonWhitespaceRegex := regexp.MustCompile(`[^\s]+`) postTail := "." if nonWhitespaceRegex.FindStringIndex(sanitized) != nil { postTail = fmt.Sprintf(`: "%v"`, sanitized) } message := fmt.Sprintf(`%v liked your %v%v`, boostersText, postOrComment, postTail) actionData := map[string]string{ "threadRootID": notifData.ThreadRootID.String(), } if notifData.IsComment { actionData["commentCardID"] = n.TargetID.String() actionData["commentCardUsername"] = notifData.AuthorUsername if notifData.ThreadReplyID != globalid.Nil && notifData.ThreadReplyID != notifData.ThreadRootID { actionData["parentCommentID"] = notifData.ThreadReplyID.String() } } eNotif := model.ExportedNotification{ ID: n.ID, UserID: n.UserID, ImagePath: latestBoost.ImagePath, Message: message, Timestamp: latestBoost.Timestamp.Unix(), Type: n.Type, Action: model.OpenThreadAction, ActionData: actionData, } if n.SeenAt.Valid { eNotif.Seen = n.SeenAt.Time.Before(time.Now().UTC()) } if n.OpenedAt.Valid { eNotif.Opened = n.OpenedAt.Time.Before(time.Now().UTC()) } return &eNotif, nil } func (ns *Notifications) exportMentionNotification(notif *model.Notification) (*model.ExportedNotification, error) { // get datas notifData, err := ns.store.GetMentionExportData(notif) if err != nil { return nil, err } taggerName := formatName(notifData.Name, notifData.IsAnonymous) notifPicture := notifData.ImagePath messageTail := "tagged you in a post." if notifData.InComment { messageTail = "mentioned you in a comment." } message := fmt.Sprintf("%v %v", taggerName, messageTail) actionData := map[string]string{ "threadRootID": notifData.ThreadRoot.String(), } if notifData.InComment { actionData["commentCardID"] = notifData.InCard.String() actionData["commentCardUsername"] = notifData.InCardAuthorUsername } if notifData.ThreadReply != globalid.Nil && notifData.ThreadRoot != notifData.ThreadReply { actionData["parentCommentID"] = notifData.ThreadReply.String() } eNotif := model.ExportedNotification{ ID: notif.ID, UserID: notif.UserID, ImagePath: notifPicture, Message: message, Timestamp: notif.CreatedAt.Unix(), Type: notif.Type, Action: model.OpenThreadAction, ActionData: actionData, } if notif.SeenAt.Valid { eNotif.Seen = notif.SeenAt.Time.Before(time.Now().UTC()) } if notif.OpenedAt.Valid { eNotif.Opened = notif.OpenedAt.Time.Before(time.Now().UTC()) } return &eNotif, nil } func (ns *Notifications) exportAnnouncementNotification(n *model.Notification) (*model.ExportedNotification, error) { if n.Type != model.AnnouncementType { return nil, errors.New("Bad Announcement Notification Format ") } announcement, err := ns.store.GetAnnouncementForNotification(n) if err != nil { return nil, err } user, err := ns.store.GetUser(announcement.UserID) if err != nil { return nil, err } message := announcement.Message if len(message) == 0 { card, err := ns.store.GetCard(announcement.CardID) if err != nil { return nil, err } content := sanitizeAndTruncateContent(card.Content, 80) message = fmt.Sprintf(`**%v** posted a new card "%v""`, user.DisplayName, content) } eNotif := model.ExportedNotification{ ID: n.ID, UserID: n.UserID, ImagePath: user.ProfileImagePath, Message: message, Timestamp: announcement.CreatedAt.Unix(), Type: n.Type, } if announcement.CardID != globalid.Nil { eNotif.ShowOnCardID = announcement.CardID eNotif.Action = model.OpenThreadAction eNotif.ActionData = map[string]string{ "threadRootID": announcement.CardID.String(), } } if n.SeenAt.Valid { eNotif.Seen = n.SeenAt.Time.Before(time.Now().UTC()) } if n.OpenedAt.Valid { eNotif.Opened = n.OpenedAt.Time.Before(time.Now().UTC()) } return &eNotif, nil } func (ns *Notifications) exportInviteAcceptedNotification(n *model.Notification) (*model.ExportedNotification, error) { if n.Type != model.InviteAcceptedType { return nil, errors.New("Bad invite accepted Notification Format ") } user, err := ns.store.GetUser(n.TargetID) if err != nil { return nil, err } message := fmt.Sprintf(`**%v** accepted your invitation to October.`, user.DisplayName) eNotif := model.ExportedNotification{ ID: n.ID, UserID: n.UserID, ImagePath: user.ProfileImagePath, Message: message, Timestamp: n.CreatedAt.Unix(), Type: n.Type, Action: model.OpenUserProfileAction, ActionData: map[string]string{ "username": user.Username, "id": user.ID.String(), }, } if n.SeenAt.Valid { eNotif.Seen = n.SeenAt.Time.Before(time.Now().UTC()) } if n.OpenedAt.Valid { eNotif.Opened = n.OpenedAt.Time.Before(time.Now().UTC()) } return &eNotif, nil } func (ns *Notifications) exportIntroductionNotification(n *model.Notification) (*model.ExportedNotification, error) { if n.Type != model.IntroductionType { return nil, errors.New("bad introduction notification format") } notification := &model.ExportedNotification{ ID: n.ID, UserID: n.UserID, Timestamp: n.CreatedAt.Unix(), Type: n.Type, Action: model.OpenUserProfileAction, } if n.TargetID != globalid.Nil { inviter, err := ns.store.GetUser(n.TargetID) if err != nil { return nil, err } notification.ImagePath = inviter.ProfileImagePath notification.Message = fmt.Sprintf(`You were invited to October by **%v**!`, inviter.DisplayName) notification.ActionData = map[string]string{ "username": inviter.Username, "id": inviter.ID.String(), } } else { user, err := ns.store.GetUser(n.UserID) if err != nil { return nil, err } notification.ImagePath = ns.systemProfileImage notification.Message = "You joined October!" notification.ActionData = map[string]string{ "username": user.Username, "id": user.ID.String(), } } if n.SeenAt.Valid { notification.Seen = n.SeenAt.Time.Before(time.Now().UTC()) } if n.OpenedAt.Valid { notification.Opened = n.OpenedAt.Time.Before(time.Now().UTC()) } return notification, nil } func (ns *Notifications) exportFollowNotification(n *model.Notification) (*model.ExportedNotification, error) { notifData, err := ns.store.GetFollowExportData(n) if errors.Cause(err) != sql.ErrNoRows && err != nil { return nil, err } else if errors.Cause(err) == sql.ErrNoRows || len(notifData.Followers) <= 0 { return nil, ErrNotificationEmpty } latestFollow := notifData.Followers[0] // "Bob", "Bob and Joe", "Bob, Joe, and 2 others" text nU := make([]NotificationUser, len(notifData.Followers)) for i, v := range notifData.Followers { nU[i] = NotificationUser(v) } followersText := formatNames(nU) message := fmt.Sprintf("%v followed you.", followersText) eNotif := model.ExportedNotification{ ID: n.ID, UserID: n.UserID, ImagePath: latestFollow.ImagePath, Message: message, Timestamp: n.UpdatedAt.Unix(), Type: n.Type, Action: model.OpenUserProfileAction, ActionData: map[string]string{ "username": latestFollow.Username, "id": latestFollow.ID.String(), }, } if n.SeenAt.Valid { eNotif.Seen = n.SeenAt.Time.Before(time.Now().UTC()) } if n.OpenedAt.Valid { eNotif.Opened = n.OpenedAt.Time.Before(time.Now().UTC()) } return &eNotif, nil } // TODO (konrad): Regular expressions that do not contain any meta characters (things // like `\d`) are just regular strings. Using the `regexp` with such // expressions is unnecessarily complex and slow. Functions from the // `bytes` and `strings` packages should be used instead. func sanitizeAndTruncateContent(content string, length int) string { removeURL := regexp.MustCompile(`(http|ftp|https)://([\w_-]+(?:(?:\.[\w_-]+)+))([\w.,@?^=%&:/~+#-]*[\w@?^=%&/~+#-])?`) removeImageAndLink := regexp.MustCompile(`[!]?\[[^\]]*\]\([^)]*\)`) removeLinkBlockTags := regexp.MustCompile("%%%\n") // nolint: megacheck removeInlineHeaders := regexp.MustCompile(`#+\s+`) // nolint: megacheck removeNewlines := regexp.MustCompile("\n") // nolint: megacheck removeSoftbreaks := regexp.MustCompile("%n") // nolint: megacheck removeTrailingWhitespace := regexp.MustCompile(`\s+$`) content = removeURL.ReplaceAllString(content, "") content = removeImageAndLink.ReplaceAllString(content, "") content = removeLinkBlockTags.ReplaceAllString(content, "") content = removeInlineHeaders.ReplaceAllString(content, "") content = removeNewlines.ReplaceAllString(content, " ") content = removeSoftbreaks.ReplaceAllString(content, " ") content = removeTrailingWhitespace.ReplaceAllString(content, "") if len(content) < length || length == 0 { return content } return content[0:length] + "..." }
28.30329
181
0.698898
9f8ecec20953ec5fc816bc61a51c40055a185b2a
1,620
sql
SQL
etc/sql/insert.sql
PQTran/SimplyTutorServerApp
590c46b2e2a404947f362e8c9460835f289c9660
[ "Apache-2.0" ]
null
null
null
etc/sql/insert.sql
PQTran/SimplyTutorServerApp
590c46b2e2a404947f362e8c9460835f289c9660
[ "Apache-2.0" ]
null
null
null
etc/sql/insert.sql
PQTran/SimplyTutorServerApp
590c46b2e2a404947f362e8c9460835f289c9660
[ "Apache-2.0" ]
null
null
null
-- insert static data after evolution runs -- must update on schema change INSERT INTO role VALUES (1, 'Admin', NULL), (2, 'User', 'A regular user who uses this application'); INSERT INTO user VALUES (1, 'ptranx23@gmail.com', 'Paul', 'Tran', 'ptranx23', NULL, NULL, 1), (2, 'sharonsun@gmail.com', 'Sharon', 'Sun', 'sharonsun', NULL, NULL, 2); INSERT INTO institute VALUES (1, 'Paul''s Tutoring Services'), (2, 'Sharon''s Private Lessons'); INSERT INTO course VALUES (1, 'Integral Calculus', 'difficult preparation for mathematical examination', 1, 1), (2, 'Mandarin Singing', NULL, 1, 1), (3, 'Beginner Mandarin Chinese', NULL, 2, 2); INSERT INTO enrollment (user_id, course_id) VALUES (1, 3), (2, 1), (2, 2); INSERT INTO assignment VALUES (1, 'calculus review', NULL, 1), (2, 'riemann sums', 'adding area under graph', 1), (3, 'chinese vocab ch1', NULL, 3); INSERT INTO question VALUES (1, 'what is a derivative?', 1, 1), (2, 'what is an integral?', 1, 1), (3, 'what is the derivative of x^2?', 5, 2), (4, 'translate: hello', 10, 3); INSERT INTO question_choice VALUES (1, 'a way to view area', 1, 0, 1), (2, 'change in graph', 2, 1, 1), (3, '1 / slope', 3, 0, 1), (4, 'true', 1, 0, 2), (5, 'false', 2, 1, 2), (6, 'log(x^2)', 1, 0, 3), (7, 'x', 2, 0, 3), (8, '2x^3', 3, 0, 3), (9, '2x', 4, 1, 3), (10, 'wo bu zhi dao', 1, 0, 4), (11, 'zai jian', 2, 0, 4), (12, 'nihao', 3, 1, 4);
31.153846
92
0.52716
e50340fdea92f5afc1fa6d5a6757e308758e95d6
1,147
swift
Swift
PokespeareApp/Modules/Favourites/FavouritesProtocols.swift
matteogazzato/PokespeareSDK
189d89247727c58c315e11f929bf76aedd5796a6
[ "MIT" ]
null
null
null
PokespeareApp/Modules/Favourites/FavouritesProtocols.swift
matteogazzato/PokespeareSDK
189d89247727c58c315e11f929bf76aedd5796a6
[ "MIT" ]
null
null
null
PokespeareApp/Modules/Favourites/FavouritesProtocols.swift
matteogazzato/PokespeareSDK
189d89247727c58c315e11f929bf76aedd5796a6
[ "MIT" ]
null
null
null
// // FavouritesProtocols.swift // PokespeareSDK // // Created Matteo Gazzato on 10/02/21. // Copyright © 2021 Matteo Gazzato. All rights reserved. // import Foundation import UIKit protocol FavouritesViewProtocol: AnyObject { func updateUI() } protocol FavouritesInteractorProtocol: AnyObject { func retrieveFavs() } protocol FavouritesWireframeProtocol: AnyObject { func module() -> FavouritesViewController func dismiss(_ vc: FavouritesViewProtocol) func present(pokemonInfoViewController pokemonInfoVc: PokemonInfoViewController, fromViewController vc: UIViewController) } protocol FavouritesEventHandler: AnyObject { func onViewDidLoad() func onViewDidAppear() func onDismiss() func onFavouriteSelected(atIndex index: Int) } protocol FavouritesDataProvider: AnyObject { var favs: [Pokemon] { get set } } protocol FavouritesInteractorOutput: AnyObject { func onFavsRetrieved(_ favs: [Pokemon]) } protocol FavouritesDelegate: AnyObject { // Add FavouritesDelegate definition } protocol FavouritesNetworkManagerProtocol: AnyObject { // Add FavouritesNetworkManagerProtocol definition }
23.895833
125
0.775937
0d5212849225f9311643d656a5b5a1721452e1af
306
asm
Assembly
s2/sfx-original/C2 - Water Warning.asm
Cancer52/flamedriver
9ee6cf02c137dcd63e85a559907284283421e7ba
[ "0BSD" ]
9
2017-10-09T20:28:45.000Z
2021-06-29T21:19:20.000Z
s2/sfx-original/C2 - Water Warning.asm
Cancer52/flamedriver
9ee6cf02c137dcd63e85a559907284283421e7ba
[ "0BSD" ]
12
2018-08-01T13:52:20.000Z
2022-02-21T02:19:37.000Z
s2/sfx-original/C2 - Water Warning.asm
Cancer52/flamedriver
9ee6cf02c137dcd63e85a559907284283421e7ba
[ "0BSD" ]
2
2018-02-17T19:50:36.000Z
2019-10-30T19:28:06.000Z
Sound42_WaterWarning_Header: smpsHeaderStartSong 2 smpsHeaderVoice Sound3F_40_42_Voices smpsHeaderTempoSFX $01 smpsHeaderChanSFX $01 smpsHeaderSFXChannel cFM5, Sound42_WaterWarning_FM5, $0C, $08 ; FM5 Data Sound42_WaterWarning_FM5: smpsSetvoice $00 dc.b nA4, $08, nA4, $25 smpsStop
21.857143
62
0.781046
5983ca8fe6961ac27c1f19cf881255b7097272d7
28,397
cxx
C++
main/ucb/source/ucp/ext/ucpext_content.cxx
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
[ "Apache-2.0" ]
679
2015-01-06T06:34:58.000Z
2022-03-30T01:06:03.000Z
main/ucb/source/ucp/ext/ucpext_content.cxx
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
[ "Apache-2.0" ]
102
2017-11-07T08:51:31.000Z
2022-03-17T12:13:49.000Z
main/ucb/source/ucp/ext/ucpext_content.cxx
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
[ "Apache-2.0" ]
331
2015-01-06T11:40:55.000Z
2022-03-14T04:07:51.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. * *************************************************************/ #include "precompiled_ext.hxx" #include "ucpext_content.hxx" #include "ucpext_content.hxx" #include "ucpext_provider.hxx" #include "ucpext_resultset.hxx" /** === begin UNO includes === **/ #include <com/sun/star/beans/PropertyAttribute.hpp> #include <com/sun/star/beans/XPropertyAccess.hpp> #include <com/sun/star/lang/IllegalAccessException.hpp> #include <com/sun/star/sdbc/XRow.hpp> #include <com/sun/star/ucb/XCommandInfo.hpp> #include <com/sun/star/ucb/XPersistentPropertySet.hpp> #include <com/sun/star/io/XOutputStream.hpp> #include <com/sun/star/io/XActiveDataSink.hpp> #include <com/sun/star/ucb/OpenCommandArgument2.hpp> #include <com/sun/star/ucb/OpenMode.hpp> #include <com/sun/star/ucb/UnsupportedDataSinkException.hpp> #include <com/sun/star/ucb/UnsupportedOpenModeException.hpp> #include <com/sun/star/ucb/OpenCommandArgument2.hpp> #include <com/sun/star/ucb/OpenMode.hpp> #include <com/sun/star/ucb/XDynamicResultSet.hpp> #include <com/sun/star/lang/IllegalAccessException.hpp> #include <com/sun/star/deployment/XPackageInformationProvider.hpp> /** === end UNO includes === **/ #include <ucbhelper/contentidentifier.hxx> #include <ucbhelper/propertyvalueset.hxx> #include <ucbhelper/cancelcommandexecution.hxx> #include <ucbhelper/content.hxx> #include <tools/diagnose_ex.h> #include <comphelper/string.hxx> #include <comphelper/componentcontext.hxx> #include <rtl/ustrbuf.hxx> #include <rtl/uri.hxx> #include <algorithm> //...................................................................................................................... namespace ucb { namespace ucp { namespace ext { //...................................................................................................................... /** === begin UNO using === **/ using ::com::sun::star::uno::Reference; using ::com::sun::star::uno::XInterface; using ::com::sun::star::uno::UNO_QUERY; using ::com::sun::star::uno::UNO_QUERY_THROW; using ::com::sun::star::uno::UNO_SET_THROW; using ::com::sun::star::uno::Exception; using ::com::sun::star::uno::RuntimeException; using ::com::sun::star::uno::Any; using ::com::sun::star::uno::makeAny; using ::com::sun::star::uno::Sequence; using ::com::sun::star::uno::Type; using ::com::sun::star::lang::XMultiServiceFactory; using ::com::sun::star::ucb::XContentIdentifier; using ::com::sun::star::ucb::IllegalIdentifierException; using ::com::sun::star::ucb::XContent; using ::com::sun::star::ucb::XCommandEnvironment; using ::com::sun::star::ucb::Command; using ::com::sun::star::ucb::CommandAbortedException; using ::com::sun::star::beans::Property; using ::com::sun::star::lang::IllegalArgumentException; using ::com::sun::star::beans::PropertyValue; using ::com::sun::star::ucb::OpenCommandArgument2; using ::com::sun::star::ucb::XDynamicResultSet; using ::com::sun::star::ucb::UnsupportedOpenModeException; using ::com::sun::star::io::XOutputStream; using ::com::sun::star::io::XActiveDataSink; using ::com::sun::star::io::XInputStream; using ::com::sun::star::ucb::UnsupportedDataSinkException; using ::com::sun::star::ucb::UnsupportedCommandException; using ::com::sun::star::sdbc::XRow; using ::com::sun::star::beans::XPropertySet; using ::com::sun::star::beans::PropertyChangeEvent; using ::com::sun::star::lang::IllegalAccessException; using ::com::sun::star::ucb::CommandInfo; using ::com::sun::star::deployment::XPackageInformationProvider; /** === end UNO using === **/ namespace OpenMode = ::com::sun::star::ucb::OpenMode; namespace PropertyAttribute = ::com::sun::star::beans::PropertyAttribute; //================================================================================================================== //= helper //================================================================================================================== namespace { //-------------------------------------------------------------------------------------------------------------- ::rtl::OUString lcl_compose( const ::rtl::OUString& i_rBaseURL, const ::rtl::OUString& i_rRelativeURL ) { ENSURE_OR_RETURN( i_rBaseURL.getLength(), "illegal base URL", i_rRelativeURL ); ::rtl::OUStringBuffer aComposer( i_rBaseURL ); if ( i_rBaseURL.getStr()[ i_rBaseURL.getLength() - 1 ] != '/' ) aComposer.append( sal_Unicode( '/' ) ); aComposer.append( i_rRelativeURL ); return aComposer.makeStringAndClear(); } //-------------------------------------------------------------------------------------------------------------- struct SelectPropertyName : public ::std::unary_function< Property, ::rtl::OUString > { const ::rtl::OUString& operator()( const Property& i_rProperty ) const { return i_rProperty.Name; } }; } //================================================================================================================== //= Content //================================================================================================================== //------------------------------------------------------------------------------------------------------------------ Content::Content( const Reference< XMultiServiceFactory >& i_rORB, ::ucbhelper::ContentProviderImplHelper* i_pProvider, const Reference< XContentIdentifier >& i_rIdentifier ) :Content_Base( i_rORB, i_pProvider, i_rIdentifier ) ,m_eExtContentType( E_UNKNOWN ) ,m_aIsFolder() ,m_aContentType() ,m_sExtensionId() ,m_sPathIntoExtension() { const ::rtl::OUString sURL( getIdentifier()->getContentIdentifier() ); if ( denotesRootContent( sURL ) ) { m_eExtContentType = E_ROOT; } else { const ::rtl::OUString sRelativeURL( sURL.copy( ContentProvider::getRootURL().getLength() ) ); const sal_Int32 nSepPos = sRelativeURL.indexOf( '/' ); if ( ( nSepPos == -1 ) || ( nSepPos == sRelativeURL.getLength() - 1 ) ) { m_eExtContentType = E_EXTENSION_ROOT; } else { m_eExtContentType = E_EXTENSION_CONTENT; } } if ( m_eExtContentType != E_ROOT ) { const ::rtl::OUString sRootURL = ContentProvider::getRootURL(); m_sExtensionId = sURL.copy( sRootURL.getLength() ); const sal_Int32 nNextSep = m_sExtensionId.indexOf( '/' ); if ( nNextSep > -1 ) { m_sPathIntoExtension = m_sExtensionId.copy( nNextSep + 1 ); m_sExtensionId = m_sExtensionId.copy( 0, nNextSep ); } m_sExtensionId = Content::decodeIdentifier( m_sExtensionId ); } } //------------------------------------------------------------------------------------------------------------------ Content::~Content() { } //------------------------------------------------------------------------------------------------------------------ ::rtl::OUString SAL_CALL Content::getImplementationName() throw( RuntimeException ) { return ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "org.openoffice.comp.ucp.ext.Content" ) ); } //------------------------------------------------------------------------------------------------------------------ Sequence< ::rtl::OUString > SAL_CALL Content::getSupportedServiceNames() throw( RuntimeException ) { Sequence< ::rtl::OUString > aServiceNames(2); aServiceNames[0] = ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.ucb.Content" ) ); aServiceNames[1] = ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.ucb.ExtensionContent" ) ); return aServiceNames; } //------------------------------------------------------------------------------------------------------------------ ::rtl::OUString SAL_CALL Content::getContentType() throw( RuntimeException ) { impl_determineContentType(); return *m_aContentType; } //------------------------------------------------------------------------------------------------------------------ Any SAL_CALL Content::execute( const Command& aCommand, sal_Int32 /* CommandId */, const Reference< XCommandEnvironment >& i_rEvironment ) throw( Exception, CommandAbortedException, RuntimeException ) { Any aRet; if ( aCommand.Name.equalsAsciiL( RTL_CONSTASCII_STRINGPARAM( "getPropertyValues" ) ) ) { Sequence< Property > Properties; if ( !( aCommand.Argument >>= Properties ) ) { ::ucbhelper::cancelCommandExecution( makeAny( IllegalArgumentException( ::rtl::OUString(), *this, -1 ) ), i_rEvironment ); // unreachable } aRet <<= getPropertyValues( Properties, i_rEvironment ); } else if ( aCommand.Name.equalsAsciiL( RTL_CONSTASCII_STRINGPARAM( "setPropertyValues" ) ) ) { Sequence< PropertyValue > aProperties; if ( !( aCommand.Argument >>= aProperties ) ) { ::ucbhelper::cancelCommandExecution( makeAny( IllegalArgumentException( ::rtl::OUString(), *this, -1 ) ), i_rEvironment ); // unreachable } if ( !aProperties.getLength() ) { ::ucbhelper::cancelCommandExecution( makeAny( IllegalArgumentException( ::rtl::OUString(), *this, -1 ) ), i_rEvironment ); // unreachable } aRet <<= setPropertyValues( aProperties, i_rEvironment ); } else if ( aCommand.Name.equalsAsciiL( RTL_CONSTASCII_STRINGPARAM( "getPropertySetInfo" ) ) ) { // implemented by base class. aRet <<= getPropertySetInfo( i_rEvironment ); } else if ( aCommand.Name.equalsAsciiL( RTL_CONSTASCII_STRINGPARAM( "getCommandInfo" ) ) ) { // implemented by base class. aRet <<= getCommandInfo( i_rEvironment ); } else if ( aCommand.Name.equalsAsciiL( RTL_CONSTASCII_STRINGPARAM( "open" ) ) ) { OpenCommandArgument2 aOpenCommand; if ( !( aCommand.Argument >>= aOpenCommand ) ) { ::ucbhelper::cancelCommandExecution( makeAny( IllegalArgumentException( ::rtl::OUString(), *this, -1 ) ), i_rEvironment ); // unreachable } sal_Bool bOpenFolder = ( ( aOpenCommand.Mode == OpenMode::ALL ) || ( aOpenCommand.Mode == OpenMode::FOLDERS ) || ( aOpenCommand.Mode == OpenMode::DOCUMENTS ) ); if ( bOpenFolder && impl_isFolder() ) { Reference< XDynamicResultSet > xSet = new ResultSet( m_xSMgr, this, aOpenCommand, i_rEvironment ); aRet <<= xSet; } if ( aOpenCommand.Sink.is() ) { const ::rtl::OUString sPhysicalContentURL( getPhysicalURL() ); ::ucbhelper::Content aRequestedContent( sPhysicalContentURL, i_rEvironment ); aRet = aRequestedContent.executeCommand( ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "open" ) ), makeAny( aOpenCommand ) ); } } else { ::ucbhelper::cancelCommandExecution( makeAny( UnsupportedCommandException( ::rtl::OUString(), *this ) ), i_rEvironment ); // unreachable } return aRet; } //------------------------------------------------------------------------------------------------------------------ void SAL_CALL Content::abort( sal_Int32 ) throw( RuntimeException ) { } //------------------------------------------------------------------------------------------------------------------ ::rtl::OUString Content::encodeIdentifier( const ::rtl::OUString& i_rIdentifier ) { return ::rtl::Uri::encode( i_rIdentifier, rtl_UriCharClassRegName, rtl_UriEncodeIgnoreEscapes, RTL_TEXTENCODING_UTF8 ); } //------------------------------------------------------------------------------------------------------------------ ::rtl::OUString Content::decodeIdentifier( const ::rtl::OUString& i_rIdentifier ) { return ::rtl::Uri::decode( i_rIdentifier, rtl_UriDecodeWithCharset, RTL_TEXTENCODING_UTF8 ); } //------------------------------------------------------------------------------------------------------------------ bool Content::denotesRootContent( const ::rtl::OUString& i_rContentIdentifier ) { const ::rtl::OUString sRootURL( ContentProvider::getRootURL() ); if ( i_rContentIdentifier == sRootURL ) return true; // the root URL contains only two trailing /, but we also recognize 3 of them as denoting the root URL if ( i_rContentIdentifier.match( sRootURL ) && ( i_rContentIdentifier.getLength() == sRootURL.getLength() + 1 ) && ( i_rContentIdentifier[ i_rContentIdentifier.getLength() - 1 ] == '/' ) ) return true; return false; } //------------------------------------------------------------------------------------------------------------------ ::rtl::OUString Content::getParentURL() { const ::rtl::OUString sRootURL( ContentProvider::getRootURL() ); switch ( m_eExtContentType ) { case E_ROOT: // don't have a parent return sRootURL; case E_EXTENSION_ROOT: // our parent is the root itself return sRootURL; case E_EXTENSION_CONTENT: { const ::rtl::OUString sURL = m_xIdentifier->getContentIdentifier(); // cut the root URL ENSURE_OR_BREAK( sURL.match( sRootURL, 0 ), "illegal URL structure - no root" ); ::rtl::OUString sRelativeURL( sURL.copy( sRootURL.getLength() ) ); // cut the extension ID const ::rtl::OUString sSeparatedExtensionId( encodeIdentifier( m_sExtensionId ) + ::rtl::OUString( sal_Unicode( '/' ) ) ); ENSURE_OR_BREAK( sRelativeURL.match( sSeparatedExtensionId ), "illegal URL structure - no extension ID" ); sRelativeURL = sRelativeURL.copy( sSeparatedExtensionId.getLength() ); // cut the final slash (if any) ENSURE_OR_BREAK( sRelativeURL.getLength(), "illegal URL structure - ExtensionContent should have a level below the extension ID" ); if ( sRelativeURL.getStr()[ sRelativeURL.getLength() - 1 ] == '/' ) sRelativeURL = sRelativeURL.copy( 0, sRelativeURL.getLength() - 1 ); // remove the last segment const sal_Int32 nLastSep = sRelativeURL.lastIndexOf( '/' ); sRelativeURL = sRelativeURL.copy( 0, nLastSep != -1 ? nLastSep : 0 ); ::rtl::OUStringBuffer aComposer; aComposer.append( sRootURL ); aComposer.append( sSeparatedExtensionId ); aComposer.append( sRelativeURL ); return aComposer.makeStringAndClear(); } default: OSL_ENSURE( false, "Content::getParentURL: unhandled case!" ); break; } return ::rtl::OUString(); } //------------------------------------------------------------------------------------------------------------------ Reference< XRow > Content::getArtificialNodePropertyValues( const Reference< XMultiServiceFactory >& i_rORB, const Sequence< Property >& i_rProperties, const ::rtl::OUString& i_rTitle ) { // note: empty sequence means "get values of all supported properties". ::rtl::Reference< ::ucbhelper::PropertyValueSet > xRow = new ::ucbhelper::PropertyValueSet( i_rORB ); const sal_Int32 nCount = i_rProperties.getLength(); if ( nCount ) { Reference< XPropertySet > xAdditionalPropSet; const Property* pProps = i_rProperties.getConstArray(); for ( sal_Int32 n = 0; n < nCount; ++n ) { const Property& rProp = pProps[ n ]; // Process Core properties. if ( rProp.Name.equalsAsciiL( RTL_CONSTASCII_STRINGPARAM( "ContentType" ) ) ) { xRow->appendString ( rProp, ContentProvider::getArtificialNodeContentType() ); } else if ( rProp.Name.equalsAsciiL( RTL_CONSTASCII_STRINGPARAM( "Title" ) ) ) { xRow->appendString ( rProp, i_rTitle ); } else if ( rProp.Name.equalsAsciiL( RTL_CONSTASCII_STRINGPARAM( "IsDocument" ) ) ) { xRow->appendBoolean( rProp, sal_False ); } else if ( rProp.Name.equalsAsciiL( RTL_CONSTASCII_STRINGPARAM( "IsFolder" ) ) ) { xRow->appendBoolean( rProp, sal_True ); } else { // append empty entry. xRow->appendVoid( rProp ); } } } else { // Append all Core Properties. xRow->appendString ( Property( ::rtl::OUString::createFromAscii( "ContentType" ), -1, getCppuType( static_cast< const ::rtl::OUString * >( 0 ) ), PropertyAttribute::BOUND | PropertyAttribute::READONLY ), ContentProvider::getArtificialNodeContentType() ); xRow->appendString ( Property( ::rtl::OUString::createFromAscii( "Title" ), -1, getCppuType( static_cast< const ::rtl::OUString * >( 0 ) ), PropertyAttribute::BOUND | PropertyAttribute::READONLY ), i_rTitle ); xRow->appendBoolean( Property( ::rtl::OUString::createFromAscii( "IsDocument" ), -1, getCppuBooleanType(), PropertyAttribute::BOUND | PropertyAttribute::READONLY ), sal_False ); xRow->appendBoolean( Property( ::rtl::OUString::createFromAscii( "IsFolder" ), -1, getCppuBooleanType(), PropertyAttribute::BOUND | PropertyAttribute::READONLY ), sal_True ); } return Reference< XRow >( xRow.get() ); } //------------------------------------------------------------------------------------------------------------------ ::rtl::OUString Content::getPhysicalURL() const { ENSURE_OR_RETURN( m_eExtContentType != E_ROOT, "illegal call", ::rtl::OUString() ); // create an ucb::XContent for the physical file within the deployed extension const ::comphelper::ComponentContext aContext( m_xSMgr ); const Reference< XPackageInformationProvider > xPackageInfo( aContext.getSingleton( "com.sun.star.deployment.PackageInformationProvider" ), UNO_QUERY_THROW ); const ::rtl::OUString sPackageLocation( xPackageInfo->getPackageLocation( m_sExtensionId ) ); if ( m_sPathIntoExtension.getLength() == 0 ) return sPackageLocation; return lcl_compose( sPackageLocation, m_sPathIntoExtension ); } //------------------------------------------------------------------------------------------------------------------ Reference< XRow > Content::getPropertyValues( const Sequence< Property >& i_rProperties, const Reference< XCommandEnvironment >& i_rEnv ) { ::osl::Guard< ::osl::Mutex > aGuard( m_aMutex ); switch ( m_eExtContentType ) { case E_ROOT: return getArtificialNodePropertyValues( m_xSMgr, i_rProperties, ContentProvider::getRootURL() ); case E_EXTENSION_ROOT: return getArtificialNodePropertyValues( m_xSMgr, i_rProperties, m_sExtensionId ); case E_EXTENSION_CONTENT: { const ::rtl::OUString sPhysicalContentURL( getPhysicalURL() ); ::ucbhelper::Content aRequestedContent( sPhysicalContentURL, i_rEnv ); // translate the property request Sequence< ::rtl::OUString > aPropertyNames( i_rProperties.getLength() ); ::std::transform( i_rProperties.getConstArray(), i_rProperties.getConstArray() + i_rProperties.getLength(), aPropertyNames.getArray(), SelectPropertyName() ); const Sequence< Any > aPropertyValues = aRequestedContent.getPropertyValues( aPropertyNames ); const ::rtl::Reference< ::ucbhelper::PropertyValueSet > xValueRow = new ::ucbhelper::PropertyValueSet( m_xSMgr ); sal_Int32 i=0; for ( const Any* value = aPropertyValues.getConstArray(); value != aPropertyValues.getConstArray() + aPropertyValues.getLength(); ++value, ++i ) { xValueRow->appendObject( aPropertyNames[i], *value ); } return xValueRow.get(); } default: OSL_ENSURE( false, "Content::getPropertyValues: unhandled case!" ); break; } OSL_ENSURE( false, "Content::getPropertyValues: unreachable!" ); return NULL; } //------------------------------------------------------------------------------------------------------------------ Sequence< Any > Content::setPropertyValues( const Sequence< PropertyValue >& i_rValues, const Reference< XCommandEnvironment >& /* xEnv */) { ::osl::ClearableGuard< osl::Mutex > aGuard( m_aMutex ); Sequence< Any > aRet( i_rValues.getLength() ); Sequence< PropertyChangeEvent > aChanges( i_rValues.getLength() ); PropertyChangeEvent aEvent; aEvent.Source = static_cast< cppu::OWeakObject * >( this ); aEvent.Further = sal_False; aEvent.PropertyHandle = -1; const PropertyValue* pValues = i_rValues.getConstArray(); const sal_Int32 nCount = i_rValues.getLength(); for ( sal_Int32 n = 0; n < nCount; ++n, ++pValues ) { // all our properties are read-only ... aRet[ n ] <<= IllegalAccessException( ::rtl::OUString::createFromAscii( "property is read-only." ), *this ); } return aRet; } //------------------------------------------------------------------------------------------------------------------ Sequence< CommandInfo > Content::getCommands( const Reference< XCommandEnvironment > & /*xEnv*/ ) { sal_uInt32 nCommandCount = 5; static const CommandInfo aCommandInfoTable[] = { /////////////////////////////////////////////////////////////// // Mandatory commands /////////////////////////////////////////////////////////////// CommandInfo( ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "getCommandInfo" ) ), -1, getCppuVoidType() ), CommandInfo( ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "getPropertySetInfo" ) ), -1, getCppuVoidType() ), CommandInfo( ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "getPropertyValues" ) ), -1, getCppuType( static_cast< Sequence< Property > * >( 0 ) ) ), CommandInfo( ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "setPropertyValues" ) ), -1, getCppuType( static_cast< Sequence< PropertyValue > * >( 0 ) ) ) /////////////////////////////////////////////////////////////// // Optional standard commands /////////////////////////////////////////////////////////////// , CommandInfo( ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "open" ) ), -1, getCppuType( static_cast< OpenCommandArgument2 * >( 0 ) ) ) }; return Sequence< CommandInfo >( aCommandInfoTable, nCommandCount ); } //------------------------------------------------------------------------------------------------------------------ Sequence< Property > Content::getProperties( const Reference< XCommandEnvironment > & /*xEnv*/ ) { static Property aProperties[] = { Property( ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "ContentType" ) ), -1, getCppuType( static_cast< const ::rtl::OUString * >( 0 ) ), PropertyAttribute::BOUND | PropertyAttribute::READONLY ), Property( ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "IsDocument" ) ), -1, getCppuBooleanType(), PropertyAttribute::BOUND | PropertyAttribute::READONLY ), Property( ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "IsFolder" ) ), -1, getCppuBooleanType(), PropertyAttribute::BOUND | PropertyAttribute::READONLY ), Property( ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "Title" ) ), -1, getCppuType( static_cast< const ::rtl::OUString * >( 0 ) ), PropertyAttribute::BOUND | PropertyAttribute::READONLY ) }; return Sequence< Property >( aProperties, sizeof( aProperties ) / sizeof( aProperties[0] ) ); } //------------------------------------------------------------------------------------------------------------------ bool Content::impl_isFolder() { if ( !!m_aIsFolder ) return *m_aIsFolder; bool bIsFolder = false; try { Sequence< Property > aProps(1); aProps[0].Name = ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "IsFolder" ) ); Reference< XRow > xRow( getPropertyValues( aProps, NULL ), UNO_SET_THROW ); bIsFolder = xRow->getBoolean(1); } catch( const Exception& ) { DBG_UNHANDLED_EXCEPTION(); } m_aIsFolder.reset( bIsFolder ); return *m_aIsFolder; } //------------------------------------------------------------------------------------------------------------------ void Content::impl_determineContentType() { if ( !!m_aContentType ) return; m_aContentType.reset( ContentProvider::getArtificialNodeContentType() ); if ( m_eExtContentType == E_EXTENSION_CONTENT ) { try { Sequence< Property > aProps(1); aProps[0].Name = ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "ContentType" ) ); Reference< XRow > xRow( getPropertyValues( aProps, NULL ), UNO_SET_THROW ); m_aContentType.reset( xRow->getString(1) ); } catch( const Exception& ) { DBG_UNHANDLED_EXCEPTION(); } } } //...................................................................................................................... } } } // namespace ucp::ext //......................................................................................................................
42.383582
143
0.518998
75529421296f7a6e7cda6b9d82490b6d3648cbf6
4,053
h
C
src/poly/schedule_pass/reschedule.h
KnowingNothing/akg-test
114d8626b824b9a31af50a482afc07ab7121862b
[ "Apache-2.0" ]
286
2020-06-23T06:40:44.000Z
2022-03-30T01:27:49.000Z
src/poly/schedule_pass/reschedule.h
KnowingNothing/akg-test
114d8626b824b9a31af50a482afc07ab7121862b
[ "Apache-2.0" ]
10
2020-07-31T03:26:59.000Z
2021-12-27T15:00:54.000Z
src/poly/schedule_pass/reschedule.h
KnowingNothing/akg-test
114d8626b824b9a31af50a482afc07ab7121862b
[ "Apache-2.0" ]
30
2020-07-17T01:04:14.000Z
2021-12-27T14:05:19.000Z
/** * Copyright 2019 Huawei Technologies Co., Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef POLY_RESCHEDULE_H_ #define POLY_RESCHEDULE_H_ #include "poly/schedule_pass.h" namespace akg { namespace ir { namespace poly { struct PointBandInfo { isl::multi_union_pw_aff mupa; size_t n_member{0}; bool permutable{false}; std::vector<bool> coincident; std::unordered_map<unsigned int, std::unordered_map<std::string, isl::pw_aff>> pa_list_map; }; // data structure for recording tile band data struct TileBandData { // flag indicating whether L0 tiled bool l0_tiled; // mark node of the tile band, if any isl::schedule_node mark; // mark node of conv_gemm, if any isl::schedule_node gemm_mark; // members of tile band unsigned int n_member; // schedule mupa isl::multi_union_pw_aff mupa; // permutable bool permutable; // coincident std::vector<bool> coincident; // ast build options isl::union_set ast_build_options; }; class Reschedule : public SchedulePass { public: Reschedule(ScopInfo &scop_info, PassInfo &pass_info) : scop_info_(scop_info), pass_info_(pass_info) { pass_name_ = __FUNCTION__; }; ~Reschedule() {} virtual isl::schedule Run(isl::schedule sch); isl::schedule RescheduleSerializeSccs(const isl::union_set &active_domain, const bool need_dist) const; private: static bool IsL1OrUbMark(const isl::schedule_node &node); static bool IsL0OrUbL0Mark(const isl::schedule_node &node); void CollectTileBandData(const isl::schedule_node &node, TileBandData *tile_band_data); static isl::schedule_node RetrieveTileBandData(isl::schedule_node node, TileBandData *tile_band_data); static isl::schedule_node RetrieveNodeList(isl::schedule_node node, const std::vector<isl::schedule_node> &node_list); static isl::schedule_node RetrieveAstBuildOptions(isl::schedule_node node, const isl::union_set &options); bool ValidateReorderedSchedule(const isl::schedule &new_schedule); isl::schedule_node TryRestoreStmtOrder(const isl::schedule_node &node, const std::vector<isl::id> &filter_total_order, const std::vector<std::vector<isl::id>> &filter_partial_order); isl::schedule_node ReschedulePreserveFilterOrder(const isl::schedule_node &node, const isl::union_set &active_domain, const bool need_dist); static PointBandInfo SavePointBand(const isl::schedule_node &node); static isl::schedule_node SetPointBandInfo(isl::schedule_node node, const PointBandInfo &point_band_info); static isl::schedule_node RestorePointBandInfo(isl::schedule_node node, const PointBandInfo &point_band_info); isl::schedule_node RescheduleSchTree(const isl::schedule_node &root); isl::schedule_node RescheduleInnerBand(const isl::schedule_node &root); void Dump(); private: ScopInfo &scop_info_; PassInfo &pass_info_; // for recording L1/UB tile band build options std::vector<isl::union_set> l1_build_options_; // for recording L0 tile band build options std::vector<isl::union_set> l0_build_options_; // for recording nodes along the path from root to L1/UB band std::vector<isl::schedule_node> node_list_0_; // for recording nodes along the path from L1/UB band to L0/UBL0 band std::vector<isl::schedule_node> node_list_1_; // for recording nodes along the path from L0/UBL0 band to point band std::vector<isl::schedule_node> node_list_2_; }; } // namespace poly } // namespace ir } // namespace akg #endif // POLY_RESCHEDULE_H_
38.235849
120
0.746607
f01a75f5202b2a67529c1984f10926191041214e
9,865
py
Python
1D_CNN.py
alex386/EEGPatternRecognition
d84085880baa9172a7cfd73b2737b93472394f3e
[ "MIT" ]
null
null
null
1D_CNN.py
alex386/EEGPatternRecognition
d84085880baa9172a7cfd73b2737b93472394f3e
[ "MIT" ]
null
null
null
1D_CNN.py
alex386/EEGPatternRecognition
d84085880baa9172a7cfd73b2737b93472394f3e
[ "MIT" ]
1
2019-02-25T18:24:37.000Z
2019-02-25T18:24:37.000Z
# -*- coding: utf-8 -*- """ Created on Tue Nov 13 12:55:47 2018 @name: CSVMachLearn.py @description: 1D CNN using CSV vector for machine learning @author: Aleksander Dawid """ from __future__ import absolute_import, division, print_function import matplotlib.pyplot as plt from matplotlib.lines import Line2D from sklearn.decomposition import PCA import numpy as np import tensorflow as tf import tensorflow.contrib.eager as tfe from tensorflow import set_random_seed tf.enable_eager_execution() set_random_seed(0) nrds='S0' #============================================================================== # Global parameters #============================================================================== total_dataset_fp="D:\\AI_experiments\\CSV\\"+nrds+"\\DAT"+nrds+".csv" pathlog="D:\\AI_experiments\\CSV\\"+nrds+"\\"+nrds+"pub.log" pathimg="D:\\AI_experiments\\CSV\\"+nrds+"\\IMG" num_epochs = 1001 # number of epochs lrate=2e-5 # learning rate test_procent=0.2 # procentage of test_dataset learn_batch_size=32 # batch size print("Local copy of the dataset file: {}".format(total_dataset_fp)) print("TensorFlow version: {}".format(tf.VERSION)) print("Eager execution: {}".format(tf.executing_eagerly())) #============================================================================== # Methods #============================================================================== def ChangeBatchSize(dataset,bsize): dataset=dataset.apply(tf.data.experimental.unbatch()) dataset=dataset.batch(batch_size=bsize) return dataset def pack_features_vector(features, labels): """Pack the features into a single array.""" features = tf.stack(list(features.values()), axis=1) return features, labels with open(total_dataset_fp) as f: content = f.readlines() grup=content[0].split(',') print(grup[1]) f_size=int(grup[1])-1 #number of points in data vector print("Vector size: "+str(f_size)) filtr1=32 filtr_size1=5 filtr2=32 filtr_size2=5 filtr3=64 filtr_size3=5 filtr4=64 filtr_size4=4 DenseLast=4096 filtr5=512 filtr_size5=5 def create_model(): model = tf.keras.models.Sequential([ tf.keras.layers.Reshape((f_size,1), input_shape=(None,f_size),name='x'), tf.keras.layers.Conv1D(filters=filtr1,kernel_size=filtr_size1,strides=1, kernel_initializer='random_uniform',activation=tf.nn.relu,padding='same',name='Conv1'), tf.keras.layers.MaxPooling1D(pool_size=filtr_size1, strides=2, padding='same', name='pool1'), tf.keras.layers.Conv1D(filters=filtr2,kernel_size=filtr_size2,strides=1, padding='same',name='Conv2',activation=tf.nn.relu, kernel_initializer='random_uniform'), tf.keras.layers.MaxPooling1D(pool_size=filtr_size2, strides=2, padding='same', name='pool2'), tf.keras.layers.Conv1D(filters=filtr3,kernel_size=filtr_size3,strides=1, padding='same',name='Conv3',activation=tf.nn.relu, kernel_initializer='random_uniform'), tf.keras.layers.MaxPooling1D(pool_size=filtr_size3, strides=2, padding='same', name='pool3'), tf.keras.layers.Conv1D(filters=filtr4,kernel_size=filtr_size4,strides=1, padding='same',name='Conv4',activation=tf.nn.relu, kernel_initializer='random_uniform'), tf.keras.layers.MaxPooling1D(pool_size=filtr_size4, strides=2, padding='same', name='pool4'), tf.keras.layers.GlobalMaxPool1D(), #size of last filter tf.keras.layers.Dense(DenseLast, activation=tf.nn.relu,name='fir'), # input shape required tf.keras.layers.Dense(256, activation=tf.nn.relu,name='mod_up'), tf.keras.layers.Dense(3,name='y_pred'), #output layer ]) model.compile(optimizer=tf.train.AdamOptimizer(), loss=tf.keras.losses.sparse_categorical_crossentropy, metrics=['accuracy']) return model def loss(model, x, y): y_ = model(x) #print(y) #print(y_) return tf.losses.sparse_softmax_cross_entropy(labels=y, logits=y_) def grad(model, inputs, targets): with tf.GradientTape() as tape: loss_value = loss(model, inputs, targets) #print(loss_value) return loss_value, tape.gradient(loss_value, model.trainable_variables) mapcolor=['red','green','blue'] # column order in CSV file column_names = [] for a in range(0,f_size): column_names.append(str(a)) column_names.append('signal') print(len(column_names)) feature_names = column_names[:-1] label_name = column_names[-1] #class_names = ['Left','Right','NONE'] class_names = ['LIP','JAW','NONE'] batch_size = 200000 #train_dataset = tf.data.experimental.make_csv_dataset( # total_dataset_fp, # batch_size, # column_names=column_names, # label_name=label_name, # num_epochs=1, # shuffle=False) #train_dataset = train_dataset.map(pack_features_vector) total_dataset = tf.data.experimental.make_csv_dataset( total_dataset_fp, batch_size, column_names=column_names, label_name=label_name, num_epochs=1, shuffle=True) features, labels = next(iter(total_dataset)) setsize=float(str(labels.shape[0])) ts_size=setsize*test_procent tr_size=setsize-ts_size print("Total_CSV_size: "+str(setsize) ) print("Train_size: "+str(tr_size) ) print("Test_size: "+str(ts_size) ) total_dataset = total_dataset.map(pack_features_vector) total_dataset=ChangeBatchSize(total_dataset,tr_size) #============================================================================== #Split dataset into train_dataset and test_dataset. #============================================================================== i=0 for (parts, labels) in total_dataset: if(i==0): k1 = parts l1 = labels else: k2 = parts l2 = labels i=i+1 train_dataset = tf.data.Dataset.from_tensors((k1, l1)) train_dataset = ChangeBatchSize(train_dataset,learn_batch_size) test_dataset = tf.data.Dataset.from_tensors((k2, l2)) test_dataset = ChangeBatchSize(test_dataset,ts_size) #============================================================================== # Create model object #============================================================================== model=create_model() model.summary() optimizer = tf.train.AdamOptimizer(learning_rate=lrate) global_step = tf.train.get_or_create_global_step() legend_elements = [Line2D([0], [0], marker='o', color='w', label=class_names[0],markerfacecolor='r', markersize=10), Line2D([0], [0], marker='o', color='w', label=class_names[1],markerfacecolor='g', markersize=10), Line2D([0], [0], marker='o', color='w', label=class_names[2],markerfacecolor='b', markersize=10)] # keep results for plotting train_loss_results = [] train_accuracy_results = [] np.set_printoptions(threshold=np.nan) #============================================================================== # Make machine learning process #============================================================================== old_loss=1000 for epoch in range(num_epochs): epoch_loss_avg = tfe.metrics.Mean() epoch_accuracy = tfe.metrics.Accuracy() # Training loop - using batches of 32 for x, y in train_dataset: # Optimize the model #print(str(type(x))) #print(str(x.shape)) loss_value, grads = grad(model, x, y) optimizer.apply_gradients(zip(grads, model.variables), global_step) # Track progress epoch_loss_avg(loss_value) # add current batch loss # compare predicted label to actual label epoch_accuracy(tf.argmax(model(x), axis=1, output_type=tf.int32), y) # end epoch train_loss_results.append(epoch_loss_avg.result()) train_accuracy_results.append(epoch_accuracy.result()) if epoch % 5 == 0: test_accuracy = tfe.metrics.Accuracy() for (x, y) in test_dataset: logits = model(x) prediction = tf.argmax(logits, axis=1, output_type=tf.int32) test_accuracy(prediction, y) X=logits.numpy() Y=y.numpy() PCA(copy=True, iterated_power='auto', n_components=2, random_state=None, svd_solver='auto', tol=0.0, whiten=False) X = PCA(n_components=2).fit_transform(X) arrcolor = [] for cl in Y: arrcolor.append(mapcolor[cl]) plt.scatter(X[:, 0], X[:, 1], s=40, c=arrcolor) #plt.show() imgfile="{:s}\\epoch{:03d}.png".format(pathimg,epoch) plt.title("{:.3%}".format(test_accuracy.result())) plt.legend(handles=legend_elements, loc='upper right') plt.savefig(imgfile) plt.close() new_loss=epoch_loss_avg.result() accur=epoch_accuracy.result() test_acc=test_accuracy.result() msg="Epoch {:03d}: Loss: {:.6f}, Accuracy: {:.3%}, Test: {:.3%}".format(epoch,new_loss,accur,test_acc) msg2 = "{0} {1:.6f} {2:.6f} {3:.6f} \n".format(epoch,accur,test_acc,new_loss) print(msg) if new_loss>old_loss: break file = open(pathlog,"a"); file.write(msg2) file.close(); old_loss=epoch_loss_avg.result() #============================================================================== # Save trained model to disk #============================================================================== model.compile(optimizer=tf.train.AdamOptimizer(), loss=tf.keras.losses.sparse_categorical_crossentropy, metrics=['accuracy']) filepath="csvsignal.h5" tf.keras.models.save_model( model, filepath, overwrite=True, include_optimizer=True ) print("Model csvsignal.h5 saved to disk")
32.557756
166
0.604055
745a324de06cff11af864c3bb1c5f323317bfc94
105,189
html
HTML
trope_list/tropes/DoubleStandardRapeDivineOnMortal.html
jwzimmer/tv-tropes
44442b66286eaf2738fc5d863d175d4577da97f4
[ "MIT" ]
1
2021-01-02T00:19:20.000Z
2021-01-02T00:19:20.000Z
trope_list/tropes/DoubleStandardRapeDivineOnMortal.html
jwzimmer/tv-tropes
44442b66286eaf2738fc5d863d175d4577da97f4
[ "MIT" ]
6
2020-11-17T00:44:19.000Z
2021-01-22T18:56:28.000Z
trope_list/tropes/DoubleStandardRapeDivineOnMortal.html
jwzimmer/tv-tropes
44442b66286eaf2738fc5d863d175d4577da97f4
[ "MIT" ]
5
2021-01-02T00:19:15.000Z
2021-08-05T16:02:08.000Z
<!DOCTYPE html> <html> <head lang="en"> <meta content="IE=edge" http-equiv="X-UA-Compatible"/> <meta content="text/html; charset=utf-8" http-equiv="Content-Type"/> <title>Double Standard: Rape, Divine on Mortal - TV Tropes</title> <meta content="The Double Standard: Rape, Divine on Mortal trope as used in popular culture. Gods are powerful, and back in the old days they generally considered morality …" name="description"/> <link href="https://tvtropes.org/pmwiki/pmwiki.php/Main/DoubleStandardRapeDivineOnMortal" rel="canonical"/> <link href="/img/icons/favicon.ico" rel="shortcut icon" type="image/x-icon"/> <meta content="summary_large_image" name="twitter:card"/> <meta content="@tvtropes" name="twitter:site"/> <meta content="@tvtropes" name="twitter:owner"/> <meta content="Double Standard: Rape, Divine on Mortal - TV Tropes" name="twitter:title"/> <meta content="The Double Standard: Rape, Divine on Mortal trope as used in popular culture. Gods are powerful, and back in the old days they generally considered morality …" name="twitter:description"/> <meta content="https://static.tvtropes.org/pmwiki/pub/images/Wonderlla_7526.png" name="twitter:image:src"/> <meta content="TV Tropes" property="og:site_name"/> <meta content="en_US" property="og:locale"/> <meta content="https://www.facebook.com/tvtropes" property="article:publisher"/> <meta content="Double Standard: Rape, Divine on Mortal - TV Tropes" property="og:title"/> <meta content="website" property="og:type"/> <meta content="https://tvtropes.org/pmwiki/pmwiki.php/Main/DoubleStandardRapeDivineOnMortal" property="og:url"/> <meta content="https://static.tvtropes.org/pmwiki/pub/images/Wonderlla_7526.png" property="og:image"/> <meta content="Gods are powerful, and back in the old days they generally considered morality to be a quaint little custom that was not their style. When they weren't partying up at Mount Olympus or playing Russian Roulette with thunderbolts, the Greek Gods …" property="og:description"/> <link href="/img/icons/apple-icon-57x57.png" rel="apple-touch-icon" sizes="57x57" type="image/png"/> <link href="/img/icons/apple-icon-60x60.png" rel="apple-touch-icon" sizes="60x60" type="image/png"/> <link href="/img/icons/apple-icon-72x72.png" rel="apple-touch-icon" sizes="72x72" type="image/png"/> <link href="/img/icons/apple-icon-76x76.png" rel="apple-touch-icon" sizes="76x76" type="image/png"/> <link href="/img/icons/apple-icon-114x114.png" rel="apple-touch-icon" sizes="114x114" type="image/png"/> <link href="/img/icons/apple-icon-120x120.png" rel="apple-touch-icon" sizes="120x120" type="image/png"/> <link href="/img/icons/apple-icon-144x144.png" rel="apple-touch-icon" sizes="144x144" type="image/png"/> <link href="/img/icons/apple-icon-152x152.png" rel="apple-touch-icon" sizes="152x152" type="image/png"/> <link href="/img/icons/apple-icon-180x180.png" rel="apple-touch-icon" sizes="180x180" type="image/png"/> <link href="/img/icons/favicon-16x16.png" rel="icon" sizes="16x16" type="image/png"/> <link href="/img/icons/favicon-32x32.png" rel="icon" sizes="32x32" type="image/png"/> <link href="/img/icons/favicon-96x96.png" rel="icon" sizes="96x96" type="image/png"/> <link href="/img/icons/favicon-192x192.png" rel="icon" sizes="192x192" type="image/png"/> <meta content="width=device-width, initial-scale=1" id="viewport" name="viewport"/> <script> var propertag = {}; propertag.cmd = []; </script> <link href="/design/assets/bundle.css?rev=c58d8df02f09262390bbd03db7921fc35c6af306" rel="stylesheet"/> <script> function object(objectId) { if (document.getElementById && document.getElementById(objectId)) { return document.getElementById(objectId); } else if (document.all && document.all(objectId)) { return document.all(objectId); } else if (document.layers && document.layers[objectId]) { return document.layers[objectId]; } else { return false; } } // JAVASCRIPT COOKIES CODE: for getting and setting user viewing preferences var cookies = { create: function (name, value, days2expire, path) { var date = new Date(); date.setTime(date.getTime() + (days2expire * 24 * 60 * 60 * 1000)); var expires = date.toUTCString(); document.cookie = name + '=' + value + ';' + 'expires=' + expires + ';' + 'path=' + path + ';'; }, createWithExpire: function(name, value, expires, path) { document.cookie = name + '=' + value + ';' + 'expires=' + expires + ';' + 'path=' + path + ';'; }, read: function (name) { var cookie_value = "", current_cookie = "", name_expr = name + "=", all_cookies = document.cookie.split(';'), n = all_cookies.length; for (var i = 0; i < n; i++) { current_cookie = all_cookies[i].trim(); if (current_cookie.indexOf(name_expr) === 0) { cookie_value = current_cookie.substring(name_expr.length, current_cookie.length); break; } } return cookie_value; }, update: function (name, val) { this.create(name, val, 300, "/"); }, remove: function (name) { document.cookie = name + "=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/"; } }; function updateUserPrefs() { //GENERAL: detect and set browser, if not cookied (will be treated like a user-preference and added to the #user-pref element) if( !cookies.read('user-browser') ){ var broswer = ''; if(navigator.userAgent.match(/iPhone/i) || navigator.userAgent.match(/iPod/i) ){ browser = 'iOS'; } else if (/Opera[\/\s](\d+\.\d+)/.test(navigator.userAgent)) { browser = 'opera'; } else if (/MSIE (\d+\.\d+);/.test(navigator.userAgent)) { browser = 'MSIE'; } else if (/Navigator[\/\s](\d+\.\d+)/.test(navigator.userAgent)) { browser = 'netscape'; } else if (/Chrome[\/\s](\d+\.\d+)/.test(navigator.userAgent)) { browser = 'chrome'; } else if (/Safari[\/\s](\d+\.\d+)/.test(navigator.userAgent)) { browser = 'safari'; /Version[\/\s](\d+\.\d+)/.test(navigator.userAgent); browserVersion = new Number(RegExp.$1); } else if (/Firefox[\/\s](\d+\.\d+)/.test(navigator.userAgent)) { browser = 'firefox'; } else { browser = 'internet_explorer'; } cookies.create('user-browser',browser,1,'/'); document.getElementById('user-prefs').classList.add('browser-' + browser); } else { document.getElementById('user-prefs').classList.add('browser-' + cookies.read('user-browser')); } //update user preference settings if (cookies.read('wide-load') !== '') document.getElementById('user-prefs').classList.add('wide-load'); if (cookies.read('night-vision') !== '') document.getElementById('user-prefs').classList.add('night-vision'); if (cookies.read('sticky-header') !== '') document.getElementById('user-prefs').classList.add('sticky-header'); if (cookies.read('show-spoilers') !== '') document.getElementById('user-prefs').classList.add('show-spoilers'); if (cookies.read('folders-open') !== '') document.getElementById('user-prefs').classList.add('folders-open'); if (cookies.read('lefthand-sidebar') !== '') document.getElementById('user-prefs').classList.add('lefthand-sidebar'); if (cookies.read('highlight-links') !== '') document.getElementById('user-prefs').classList.add('highlight-links'); if (cookies.read('forum-gingerbread') !== '') document.getElementById('user-prefs').classList.add('forum-gingerbread'); if (cookies.read('shared-avatars') !== '') document.getElementById('user-prefs').classList.add('shared-avatars'); if (cookies.read('new-search') !== '') document.getElementById('user-prefs').classList.add('new-search'); if (cookies.read('stop-auto-play-video') !== '') document.getElementById('user-prefs').classList.add('stop-auto-play-video'); //desktop view on mobile if (cookies.read('desktop-on-mobile') !== ''){ document.getElementById('user-prefs').classList.add('desktop-on-mobile'); var viewport = document.querySelector("meta[name=viewport]"); viewport.setAttribute('content', 'width=1000'); } } function updateDesktopPrefs() { if (cookies.read('wide-load') !== '') document.getElementById('sidebar-toggle-wideload').classList.add('active'); if (cookies.read('night-vision') !== '') document.getElementById('sidebar-toggle-nightvision').classList.add('active'); if (cookies.read('sticky-header') !== '') document.getElementById('sidebar-toggle-stickyheader').classList.add('active'); if (cookies.read('show-spoilers') !== '') document.getElementById('sidebar-toggle-showspoilers').classList.add('active'); } function updateMobilePrefs() { if (cookies.read('show-spoilers') !== '') document.getElementById('mobile-toggle-showspoilers').classList.add('active'); if (cookies.read('night-vision') !== '') document.getElementById('mobile-toggle-nightvision').classList.add('active'); if (cookies.read('sticky-header') !== '') document.getElementById('mobile-toggle-stickyheader').classList.add('active'); if (cookies.read('highlight-links') !== '') document.getElementById('mobile-toggle-highlightlinks').classList.add('active'); } if (document.cookie.indexOf("scroll0=") < 0) { // do nothing } else { console.log('ads removed by scroll.com'); var adsRemovedWith = 'scroll'; var style = document.createElement('style'); style.innerHTML = '#header-ad, .proper-ad-unit, .square_ad, .sb-ad-unit { display: none !important; } '; document.head.appendChild(style); } </script> <script type="text/javascript"> var tvtropes_config = { astri_stream_enabled : "", is_logged_in : "", handle : "", get_astri_stream : "", revnum : "c58d8df02f09262390bbd03db7921fc35c6af306", img_domain : "https://static.tvtropes.org", adblock : "1", adblock_url : "propermessage.io", pause_editing : "0", pause_editing_msg : "", pause_site_changes : "" }; </script> <script type="text/javascript"> (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){ (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o), m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m) })(window,document,'script','//www.google-analytics.com/analytics.js','ga'); ga('create', 'UA-3821842-1', 'auto'); ga('send', 'pageview'); </script> </head> <body class=""> <i id="user-prefs"></i> <script>updateUserPrefs();</script> <div id="fb-root"></div> <div id="modal-box"></div> <header class="headroom-element" id="main-header-bar"> <div id="main-header-bar-inner"> <span class="header-spacer" id="header-spacer-left"></span> <a class="mobile-menu-toggle-button tablet-on" href="#mobile-menu" id="main-mobile-toggle"><span></span><span></span><span></span></a> <a class="no-dev" href="/" id="main-header-logoButton"></a> <span class="header-spacer" id="header-spacer-right"></span> <nav class="tablet-off" id="main-header-nav"> <a href="/pmwiki/pmwiki.php/Main/Tropes">Tropes</a> <a href="/pmwiki/pmwiki.php/Main/Media">Media</a> <a class="nav-browse" href="/pmwiki/browse.php">Browse</a> <a href="/pmwiki/index_report.php">Indexes</a> <a href="/pmwiki/topics.php">Forums</a> <a class="nav-browse" href="/pmwiki/recent_videos.php">Videos</a> </nav> <div id="main-header-bar-right"> <div class="font-xs mobile-off" id="signup-login-box"> <a class="hover-underline bold" data-modal-target="signup" href="/pmwiki/login.php">Join</a> <a class="hover-underline bold" data-modal-target="login" href="/pmwiki/login.php">Login</a> </div> <div class="mobile-on inline" id="signup-login-mobileToggle"> <a data-modal-target="login" href="/pmwiki/login.php"><i class="fa fa-user"></i></a> </div> <div id="search-box"> <form action="/pmwiki/search_result.php" class="search"> <input class="search-box" name="q" placeholder="Search" required="" type="text" value=""/> <input class="submit-button" type="submit" value=""/> <input name="search_type" type="hidden" value="article"/> <input name="page_type" type="hidden" value="all"/> <input name="cx" type="hidden" value="partner-pub-6610802604051523:amzitfn8e7v"/> <input name="cof" type="hidden" value="FORID:10"/> <input name="ie" type="hidden" value="ISO-8859-1"/> <input name="siteurl" type="hidden" value=""/> <input name="ref" type="hidden" value=""/> <input name="ss" type="hidden" value=""/> </form> <a class="mobile-on mobile-search-toggle close-x" href="#close-search"><i class="fa fa-close"></i></a> </div> <div id="random-box"> <a class="button-random-trope" href="/pmwiki/pmwiki.php/Main/VisitByDivorcedDad" onclick="ga('send', 'event', 'button', 'click', 'random trope');" rel="nofollow"></a> <a class="button-random-media" href="/pmwiki/pmwiki.php/Creator/PaulVerhoeven" onclick="ga('send', 'event', 'button', 'click', 'random media');" rel="nofollow"></a> </div> </div> </div> <div class="tablet-on" id="mobile-menu"><div class="mobile-menu-options"> <div class="nav-wrapper"> <a class="xl" href="/pmwiki/pmwiki.php/Main/Tropes">Tropes</a> <a class="xl" href="/pmwiki/pmwiki.php/Main/Media">Media</a> <a class="xl" href="/pmwiki/browse.php">Browse</a> <a class="xl" href="/pmwiki/index_report.php">Indexes</a> <a class="xl" href="/pmwiki/topics.php">Forums</a> <a class="xl" href="/pmwiki/recent_videos.php">Videos</a> <a href="/pmwiki/query.php?type=att">Ask The Tropers</a> <a href="/pmwiki/query.php?type=tf">Trope Finder</a> <a href="/pmwiki/query.php?type=ykts">You Know That Show...</a> <a href="/pmwiki/tlp_activity.php">Trope Launch Pad</a> <a data-click-toggle="active" href="#tools">Tools <i class="fa fa-chevron-down"></i></a> <div class="tools-dropdown mobile-dropdown-linkList"> <a href="/pmwiki/cutlist.php">Cut List</a> <a href="/pmwiki/changes.php">New Edits</a> <a href="/pmwiki/recent_edit_reasons.php">Edit Reasons</a> <a href="/pmwiki/launches.php">Launches</a> <a href="/pmwiki/img_list.php">Images List</a> <a href="/pmwiki/crown_activity.php">Crowner Activity</a> <a href="/pmwiki/no_types.php">Un-typed Pages</a> <a href="/pmwiki/page_type_audit.php">Recent Page Type Changes</a> </div> <a data-click-toggle="active" href="#hq">Tropes HQ <i class="fa fa-chevron-down"></i></a> <div class="tools-dropdown mobile-dropdown-linkList"> <a href="/pmwiki/about.php">About Us</a> <a href="/pmwiki/contact.php">Contact Us</a> <a href="mailto:advertising@proper.io">Advertise</a> <a href="/pmwiki/dmca.php">DMCA Notice</a> <a href="/pmwiki/privacypolicy.php">Privacy Policy</a> </div> <a href="/pmwiki/ad-free-subscribe.php">Go Ad-Free</a> <div class="toggle-switches"> <ul class="mobile-menu display-toggles"> <li>Show Spoilers <div class="display-toggle show-spoilers" id="mobile-toggle-showspoilers"></div></li> <li>Night Vision <div class="display-toggle night-vision" id="mobile-toggle-nightvision"></div></li> <li>Sticky Header <div class="display-toggle sticky-header" id="mobile-toggle-stickyheader"></div></li> <li>Highlight Links <div class="display-toggle highlight-links" id="mobile-toggle-highlightlinks"></div></li> </ul> <script>updateMobilePrefs();</script> </div> </div> </div> </div> </header> <div class="mobile-on" id="homepage-introBox-mobile"> <a href="/"><img class="logo-small" src="/images/logo-white-big.png"/></a> <form action="/pmwiki/search_result.php" class="search" style="margin:10px -5px -6px -5px;"> <input class="search-box" name="q" placeholder="Search" required="" type="text" value=""/> <input class="submit-button" type="submit" value=""/> <input name="search_type" type="hidden" value="article"/> <input name="page_type" type="hidden" value="all"/> <input name="cx" type="hidden" value="partner-pub-6610802604051523:amzitfn8e7v"/> <input name="cof" type="hidden" value="FORID:10"/> <input name="ie" type="hidden" value="ISO-8859-1"/> <input name="siteurl" type="hidden" value=""/> <input name="ref" type="hidden" value=""/> <input name="ss" type="hidden" value=""/> </form> </div> <div class="ad" id="header-ad-wrapper"> <div id="header-ad"> <div class="ad-size-970x90 atf_banner"> <div class="proper-ad-unit"> <div id="proper-ad-tvtropes_ad_1"> <script>propertag.cmd.push(function() { proper_display('tvtropes_ad_1'); });</script> </div> </div> </div> </div> </div> <div id="main-container"> <div class="action-bar mobile-off" id="action-bar-top"> <div class="action-bar-right"> <p>Follow TV Tropes</p> <a class="button-fb" href="https://www.facebook.com/TVTropes"> <i class="fa fa-facebook"></i></a> <a class="button-tw" href="https://www.twitter.com/TVTropes"> <i class="fa fa-twitter"></i></a> <a class="button-re" href="https://www.reddit.com/r/TVTropes"> <i class="fa fa-reddit-alien"></i></a> </div> <nav class="actions-wrapper" itemscope="" itemtype="http://schema.org/SiteNavigationElement"> <ul class="page-actions" id="top_main_list"> <li class="link-edit"> <a class="article-edit-button" data-modal-target="login" href="/pmwiki/pmwiki.php/Main/DoubleStandardRapeDivineOnMortal?action=edit" rel="nofollow"> <i class="fa fa-pencil"></i> Edit Page</a></li><li class="link-related"><a href="/pmwiki/relatedsearch.php?term=Main/DoubleStandardRapeDivineOnMortal"> <i class="fa fa-share-alt"></i> Related</a></li><li class="link-history"><a href="/pmwiki/article_history.php?article=Main.DoubleStandardRapeDivineOnMortal"> <i class="fa fa-history"></i> History</a></li><li class="link-discussion"><a href="/pmwiki/remarks.php?trope=Main.DoubleStandardRapeDivineOnMortal"> <i class="fa fa-comment"></i> Discussion</a></li> </ul> <button class="nav__dropdown-toggle" id="top_more_button" onclick="toggle_more_menu('top');" type="button">More</button> <ul class="more_menu hidden_more_list" id="top_more_list"> <li class="link-todo tuck-always more_list_item"><a data-modal-target="login" href="#todo"><i class="fa fa-check-circle"></i> To Do</a></li><li class="link-pageSource tuck-always more_list_item"><a data-modal-target="login" href="/pmwiki/pmwiki.php/Main/DoubleStandardRapeDivineOnMortal?action=source" rel="nofollow" target="_blank"><i class="fa fa-code"></i> Page Source</a></li> </ul> </nav> <div class="WikiWordModalStub"></div> <div class="ImgUploadModalStub" data-page-type="Article"></div> <div class="login-alert" style="display: none;"> You need to <a href="/pmwiki/login.php" style="color:#21A0E8">login</a> to do this. <a href="/pmwiki/login.php?tab=register_account" style="color:#21A0E8">Get Known</a> if you don't have an account </div> </div> <div class="page-Article" id="main-content"> <article class="with-sidebar" id="main-entry"> <input id="groupname-hidden" type="hidden" value="Main"/> <input id="title-hidden" type="hidden" value="DoubleStandardRapeDivineOnMortal"/> <input id="article_id" type="hidden" value="341332"/> <input id="logged_in" type="hidden" value="false"/> <p class="hidden" id="current_url">http://tvtropes.org/pmwiki/pmwiki.php/Main/DoubleStandardRapeDivineOnMortal</p> <meta content="" itemprop="datePublished"/> <meta content="" itemprop="articleSection"/> <meta content="" itemprop="image"/> <a class="watch-button" data-modal-target="login" href="#watch">Follow<span>ing</span></a> <h1 class="entry-title" itemprop="headline"> Double Standard: Rape, Divine on Mortal </h1> <script type="application/ld+json"> { "@context": "https://schema.org", "@type": "BreadcrumbList", "itemListElement": [{ "@type": "ListItem", "position": 1, "name": "tvtropes.org", "item": "https://tvtropes.org" },{ "@type": "ListItem", "position": 2, "name": "Tropes", "item": "https://tvtropes.org/pmwiki/pmwiki.php/Main/Tropes" },{ "@type": "ListItem", "position": 3, "name": "Double Standard: Rape, Divine on Mortal" }] } </script> <a class="mobile-actionbar-toggle mobile-on" data-click-toggle="active" href="#mobile-actions-toggle" id="mobile-actionbar-toggle"> <p class="tiny-off">Go To</p><span></span><span></span><span></span><i class="fa fa-pencil"></i></a> <nav class="mobile-actions-wrapper mobile-on" id="mobile-actions-bar"></nav> <div class="modal fade hidden-until-active" id="editLockModal"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <button aria-label="Close" class="close" data-dismiss="modal" type="button"> <span aria-hidden="true">×</span></button> <h4 class="modal-title">Edit Locked</h4> </div> <div class="modal-body"> <div class="row"> <div class="body"> <div class="danger troper_locked_message"></div> </div> </div> </div> </div> </div> </div> <nav class="body-options" itemscope="" itemtype="http://schema.org/SiteNavigationElement"> <ul class="subpage-links"> <li> <a class="subpage-link curr-subpage" href="/pmwiki/pmwiki.php/Main/DoubleStandardRapeDivineOnMortal" title="The Main page"> <span class="wrapper"><span class="spi main-page"></span>Main</span></a> </li> <li> <a class="subpage-link" href="/pmwiki/pmwiki.php/Laconic/DoubleStandardRapeDivineOnMortal" title="The Laconic page"> <span class="wrapper"><span class="spi laconic-icon"></span>Laconic</span></a> </li> <li> <a class="subpage-link" href="/pmwiki/pmwiki.php/PlayingWith/DoubleStandardRapeDivineOnMortal" title="The PlayingWith page"> <span class="wrapper">PlayingWith</span></a> </li> <li class="create-subpage dropdown"> <a aria-expanded="false" class="dropdown-toggle" data-toggle="dropdown" href="javascript:void(0);" role="button"> <span class="wrapper">Create New <i class="fa fa-plus-circle"></i></span> </a> <select onchange="this.options[this.selectedIndex].value &amp;&amp; (window.location = this.options[this.selectedIndex].value);"> <option value="">- Create New -</option> <option value="/pmwiki/pmwiki.php/Analysis/DoubleStandardRapeDivineOnMortal?action=edit">Analysis</option> <option value="/pmwiki/pmwiki.php/Characters/DoubleStandardRapeDivineOnMortal?action=edit">Characters</option> <option value="/pmwiki/pmwiki.php/FanficRecs/DoubleStandardRapeDivineOnMortal?action=edit">FanficRecs</option> <option value="/pmwiki/pmwiki.php/FanWorks/DoubleStandardRapeDivineOnMortal?action=edit">FanWorks</option> <option value="/pmwiki/pmwiki.php/Fridge/DoubleStandardRapeDivineOnMortal?action=edit">Fridge</option> <option value="/pmwiki/pmwiki.php/Haiku/DoubleStandardRapeDivineOnMortal?action=edit">Haiku</option> <option value="/pmwiki/pmwiki.php/Headscratchers/DoubleStandardRapeDivineOnMortal?action=edit">Headscratchers</option> <option value="/pmwiki/pmwiki.php/ImageLinks/DoubleStandardRapeDivineOnMortal?action=edit">ImageLinks</option> <option value="/pmwiki/pmwiki.php/Quotes/DoubleStandardRapeDivineOnMortal?action=edit">Quotes</option> <option value="/pmwiki/pmwiki.php/Recap/DoubleStandardRapeDivineOnMortal?action=edit">Recap</option> <option value="/pmwiki/pmwiki.php/ReferencedBy/DoubleStandardRapeDivineOnMortal?action=edit">ReferencedBy</option> <option value="/pmwiki/pmwiki.php/Synopsis/DoubleStandardRapeDivineOnMortal?action=edit">Synopsis</option> <option value="/pmwiki/pmwiki.php/Timeline/DoubleStandardRapeDivineOnMortal?action=edit">Timeline</option> <option value="/pmwiki/pmwiki.php/Trivia/DoubleStandardRapeDivineOnMortal?action=edit">Trivia</option> <option value="/pmwiki/pmwiki.php/WMG/DoubleStandardRapeDivineOnMortal?action=edit">WMG</option> <option value="/pmwiki/pmwiki.php/YMMV/DoubleStandardRapeDivineOnMortal?action=edit">YMMV</option> </select> </li> </ul> </nav> <div class="article-content retro-folders" id="main-article"> <p> </p><div class="quoteright" style="width:338px;"><a class="twikilink" href="/pmwiki/pmwiki.php/Webcomic/TheNonAdventuresOfWonderella" title="/pmwiki/pmwiki.php/Webcomic/TheNonAdventuresOfWonderella"><div class="lazy_load_img_box" style="padding-top:68.64%"><img alt="https://static.tvtropes.org/pmwiki/pub/images/Wonderlla_7526.png" border="0" class="embeddedimage" height="232" src="https://static.tvtropes.org/pmwiki/pub/images/Wonderlla_7526.png" width="338"/></div></a></div> <p> </p><div class="proper-ad-unit mobile-ad square_ad"><h6 class="ad-caption">Advertisement:</h6><div id="proper-ad-tvtropes_mobile_ad_1"><script>propertag.cmd.push(function() { proper_display('tvtropes_mobile_ad_1'); })</script></div></div><p>Gods are powerful, and back in the old days they generally considered morality to be a <a class="twikilink" href="/pmwiki/pmwiki.php/Main/JerkassGods" title="/pmwiki/pmwiki.php/Main/JerkassGods">quaint little custom that was not their style</a>. When they weren't partying up at Mount Olympus or playing Russian Roulette with thunderbolts, the <a class="twikilink" href="/pmwiki/pmwiki.php/Myth/ClassicalMythology" title="/pmwiki/pmwiki.php/Myth/ClassicalMythology">Greek Gods</a> could be found making out with mortals, resulting in the birth of <a class="twikilink" href="/pmwiki/pmwiki.php/Main/SemiDivine" title="/pmwiki/pmwiki.php/Main/SemiDivine">demigods</a>. Unfortunately, they often didn't wait for consent, or indeed even care. This comes from two rationales: </p><p></p><ul><li> <strong><a class="twikilink" href="/pmwiki/pmwiki.php/Main/ValuesDissonance" title="/pmwiki/pmwiki.php/Main/ValuesDissonance">Values Dissonance</a></strong>: Personal attention from a super-being you worship? Getting to become the mother of a demigod? Consent? Someone somewhere at some time might say the mortal was a rape victim but the mortal in this position would be deeply offended by the accusation. They may not have been told beforehand but would have consented anyway. </li><li> <strong><a class="twikilink" href="/pmwiki/pmwiki.php/Main/MightMakesRight" title="/pmwiki/pmwiki.php/Main/MightMakesRight">Might Makes Right</a></strong>: The attention is not appreciated but the gods can treat the mortals in whatever way they please because they have <a class="twikilink" href="/pmwiki/pmwiki.php/Main/OmniscientMoralityLicense" title="/pmwiki/pmwiki.php/Main/OmniscientMoralityLicense">Omniscient Morality License</a> or simply because they are strong enough to get away with it. </li></ul><div class="proper-ad-unit mobile-ad square_ad"><h6 class="ad-caption">Advertisement:</h6><div id="proper-ad-tvtropes_mobile_ad_2"><script>propertag.cmd.push(function() { proper_display('tvtropes_mobile_ad_2'); })</script></div></div><p>In myth, there are <a class="twikilink" href="/pmwiki/pmwiki.php/Main/ContinuitySnarl" title="/pmwiki/pmwiki.php/Main/ContinuitySnarl">conflicting accounts</a> of many of these examples. A story of a god's relationship with a mortal woman can be interpreted in one way as a sexual predator assaulting a woman, and in another as a game being played by two lovers, <a class="twikilink" href="/pmwiki/pmwiki.php/Main/DependingOnTheWriter" title="/pmwiki/pmwiki.php/Main/DependingOnTheWriter">Depending on the Writer</a> and the interpreter. In addition, some ancient Greek sources don't differentiate seduction and rape, leading to interpretations that all gods never had consent, even in stories where the god is the one seduced. </p><p>There were many ways in which the gods of old would "know" desirable mortals. These can generally be divided into two types: </p><ul><li> <strong>Direct</strong>: The divinity explicitly rapes or ravishes the mortal. Sometimes the god <a class="twikilink" href="/pmwiki/pmwiki.php/Main/BedTrick" title="/pmwiki/pmwiki.php/Main/BedTrick">disguised himself so that the woman thought she was sleeping with her husband</a>. Sometimes it was just outright rape. You name it, Zeus/Jupiter did it, and many other gods and goddesses did so as well. </li><div class="proper-ad-unit mobile-ad square_ad"><h6 class="ad-caption">Advertisement:</h6><div id="proper-ad-tvtropes_mobile_ad_3"><script>propertag.cmd.push(function() { proper_display('tvtropes_mobile_ad_3'); })</script></div></div><li> <strong>Indirect</strong>: The divinity impregnates the mortal in a manner that does not appear to involve conventional intercourse. One popular method was to do it as a cloud of shimmery mist. </li></ul><p>In case you're wondering, mortal women were <em>far</em> from being the only targets of not-so-holy intentions of the gods; many goddesses — and not a few gods, for that matter — were known for doing the same thing to mortal men. </p><p>This trope applies not just to gods, but also to demigods and others with <a class="twikilink" href="/pmwiki/pmwiki.php/Main/DivineParentage" title="/pmwiki/pmwiki.php/Main/DivineParentage">Divine Parentage</a>. <a class="twikilink" href="/pmwiki/pmwiki.php/Main/ValuesDissonance" title="/pmwiki/pmwiki.php/Main/ValuesDissonance">It is a staple of</a> <a class="twikilink" href="/pmwiki/pmwiki.php/Myth/GreekMythology" title="/pmwiki/pmwiki.php/Myth/GreekMythology">Greek Mythology</a>. Nowadays, it's mostly a <a class="twikilink" href="/pmwiki/pmwiki.php/Main/ForgottenTrope" title="/pmwiki/pmwiki.php/Main/ForgottenTrope">Forgotten Trope</a>. See also <a class="twikilink" href="/pmwiki/pmwiki.php/Main/DoubleStandardRapeSciFi" title="/pmwiki/pmwiki.php/Main/DoubleStandardRapeSciFi">Double Standard: Rape, Sci-Fi</a>. When the relationship is less one-sided, that's <a class="twikilink" href="/pmwiki/pmwiki.php/Main/DivineDate" title="/pmwiki/pmwiki.php/Main/DivineDate">Divine Date</a>. </p><p></p><hr/><h2><a class="twikilink" href="/pmwiki/pmwiki.php/Myth/ClassicalMythology" title="/pmwiki/pmwiki.php/Myth/ClassicalMythology">ZEUS, God of Horndogs</a></h2> <p>Zeus has one of the largest if not <em>the</em> largest number of "relationships" of this kind of any deity in world history. It should come as no surprise, then, that <a class="twikilink" href="/pmwiki/pmwiki.php/UsefulNotes/TheMoonsOfJupiter" title="/pmwiki/pmwiki.php/UsefulNotes/TheMoonsOfJupiter"> The Moons of Jupiter</a>—of which there are at least <em>67</em>—are named for his lovers (including "lovers") and descendants. We should note that all of his "relationships" with women produced children—generally sons, and most especially heroes. Many of these went on to become kings and ancestors of the peoples of Greece, so <a class="twikilink" href="/pmwiki/pmwiki.php/Main/JustSoStory" title="/pmwiki/pmwiki.php/Main/JustSoStory">one really gets to thinking</a>... Although, one good quality he had was that he never abandoned these children and often acted like a <a class="twikilink" href="/pmwiki/pmwiki.php/Main/PapaWolf" title="/pmwiki/pmwiki.php/Main/PapaWolf">Papa Wolf</a> in some cases. (The fact that he and his siblings overthrew his cruel father, who had done the same to his <em>worse</em> grandfather, may have motivated him not to be neglectful.) </p><p>Historians believe that a major part of Zeus <a class="twikilink" href="/pmwiki/pmwiki.php/Main/ReallyGetsAround" title="/pmwiki/pmwiki.php/Main/ReallyGetsAround">going after so many women</a> was that when the ancient Greeks conquered their neighbors, they tended to conflate the local gods with Zeus and to turn those gods' consorts into Zeus's lovers. Others believe that the Grecians believed it because frankly, life can get pretty boring when you're an invulnerable god with nothing to do but drink ambrosia and throw around thunderbolts all day. </p><p></p><div class="folderlabel" onclick="toggleAllFolders();">    open/close all folders  </div> <p></p><div class="folderlabel" onclick="togglefolder('folder0');">    Track Record </div><div class="folder" id="folder0" isfolder="true" style="display:block;"> <ul><li> Io had it particularly rough. While she was willingly seduced by Zeus, their tryst was almost discovered by Hera. To keep Hera from finding out, Zeus <a class="twikilink" href="/pmwiki/pmwiki.php/Main/BalefulPolymorph" title="/pmwiki/pmwiki.php/Main/BalefulPolymorph">turned her into a cow</a>, which Hera then forced him to present to her as a gift. Hermes helped Io escape and she fled to Egypt, pursued by a fly that Hera sent to sting her. Once there she finally turned back into a human and became queen. Also, <a class="twikilink" href="/pmwiki/pmwiki.php/Main/JustSoStory" title="/pmwiki/pmwiki.php/Main/JustSoStory">this is why women have periods</a>. </li><li> Zeus was enamored of Europa and decided to seduce her, but he knew better than to reveal himself outright. He transformed himself into a tame white bull and mixed in with her father's herds. While Europa and her helpers were gathering flowers, she saw the bull, caressed his flanks, and eventually got onto his back. Zeus took that opportunity and ran to the sea and swam, with her on his back, to the island of Crete. He then revealed his true identity, bestowing upon Europa great gifts and honours and crowned her as the first queen of Crete. They had three sons—whether as triplets or in succession is unclear—named Minos, Rhadamanthys, and Serpedon, who were adopted by the King of Crete; Rhadamanthys became king but was kicked out by or fled from Minos, who founded the Cretan royal line. Minos' (There were two) granddaughter-in-law would eventually give birth to the Minotaur. </li><li> An indirect example: Danae was locked underground by her father Acrisius of Argos, to stop her having the son that was prophesied to kill him. Zeus appeared to Danae as a shower of gold, conceiving the hero Perseus. Acrisius then put both Danae and her son <a class="twikilink" href="/pmwiki/pmwiki.php/Main/GirlInABox" title="/pmwiki/pmwiki.php/Main/GirlInABox">in a chest</a> and threw them into the sea. This didn't work; Perseus went on to become King of Mycenae, <em>accidentally</em> kill his grandfather, and found the royal lines of Argos and Tiryns. (Mycenae would be lost to the Atreides shortly after Perseus' reign.) </li><li> To father Heracles, Zeus had sex with Alcmene <a class="twikilink" href="/pmwiki/pmwiki.php/Main/BedTrick" title="/pmwiki/pmwiki.php/Main/BedTrick">in the guise of her husband Amphitryon</a>. Heracles legendarily founded or was an ancestor to about half the royal and noble houses of Greece. </li><li> Callisto, daughter of a king named Lycaon, was a virgin follower of Artemis, fell in with Zeus and was willingly impregnated by him. Depending on the version of the story you hear, one of the goddesses Zeus pissed off (some say Hera, for his cheating, and others Artemis, for tricking her acolyte) turned Callisto into a bear either immediately after Zeus was found out (in which case Arcas was born while his mother was a bear) or after Lycaon lured the grown Arcas to some kind of festival. In either case, Lycaon ends up turned into the first werewolf, Arcas inherits his grandfather's kingdom (renamed Arcadia for his trouble), and runs into his transformed mother while out hunting. Zeus then transforms him into a bear to keep him from killing his mom, and then throws both Arcas and Callisto into the sky by the tail, stretching the tails and turning the now-ursine mother and son into constellations. <a class="twikilink" href="/pmwiki/pmwiki.php/Main/JustSoStory" title="/pmwiki/pmwiki.php/Main/JustSoStory">This is why Ursa Major and Ursa Minor look like bears with unusually long tails</a>. <ul><li> Later stories state that Zeus <a class="twikilink" href="/pmwiki/pmwiki.php/Main/ShapeShiftersDoItForAChange" title="/pmwiki/pmwiki.php/Main/ShapeShiftersDoItForAChange">took the guise of Artemis</a>. Somehow she got pregnant from this, producing the hunter Arcas. </li></ul></li><li> Antiope was seduced by Zeus after he took the form of a satyr. As she was carried away shortly thereafter by the hero-king Epopeus of Syceon, she gave birth to two sons: Amphion, son of Zeus, and Zeuthos, son of Epopeus, who went on to found Thebes. <ul><li> There are no sources that state that she was unwilling nor asleep when she was seduced. </li></ul></li><li> Semele, mother of Dionysus, was said to have been fed a potion by Zeus that impregnated her with a divine child. Shortly after the impregnation Semele was <a class="twikilink" href="/pmwiki/pmwiki.php/Main/YouCannotGraspTheTrueForm" title="/pmwiki/pmwiki.php/Main/YouCannotGraspTheTrueForm">incinerated</a>. Zeus took Dionysus, sewed him into his thigh<span class="notelabel" onclick="togglenote('note0iqtj');"><sup>note </sup></span><span class="inlinefolder" id="note0iqtj" isnote="true" onclick="togglenote('note0iqtj');" style="cursor:pointer;font-size:smaller;display:none;">Or possibly his scrotum. "Thigh" was a common euphemism for "ballsack" in the Eastern Mediterranean; <a class="twikilink" href="/pmwiki/pmwiki.php/Literature/TheBible" title="/pmwiki/pmwiki.php/Literature/TheBible">The Bible</a> uses it, too.</span> and delivered him on term. </li><li> He had sex with Eurymedusa by turning both of them into ants. The result was King Myrmidon (whose name means "Ant"), who ruled the city of Phythya and was the eponymous ancestor of the Myrmidon people, including Achilles. </li><li> Helen of Troy and her brothers were conceived when Zeus seduced their willing mother Leda. <ul><li> Later stories state that Zeus did this in the form of a swan. The details of the birth are not well described, but apparently it involved the babies along with their half siblings Castor and Clytemnestra hatching from eggs. Leda of course was the Queen of Sparta, and the marriage of her daughters to the Atreids Menelaos and Agamemnon gave them great legitimacy. </li></ul></li><li> Zeus abducted the beautiful prince Ganymede in the form of an eagle so that Ganymede could become his <a class="twikilink" href="/pmwiki/pmwiki.php/Main/Uke" title="/pmwiki/pmwiki.php/Main/Uke">eromenos</a> and personal cup bearer. <a class="twikilink" href="/pmwiki/pmwiki.php/Main/JustSoStory" title="/pmwiki/pmwiki.php/Main/JustSoStory">Ganymede was made into the constellation Aquarius</a> so that Hera couldn't hurt him. </li><li> Zeus's relationship with Persephone in some obscure myths is in interesting case, not least because she was the only one of Zeus's immortal daughters to have been on the receiving end of such actions. This is probably because most of Zeus's other immortal daughters were either Hera's daughters as well, and thus harder to get at without Hera knowing, or proficient enough fighters that they could have held him off, like Athena and Artemis. Persephone was impregnated at least two times by her father, at least once when she was still a young Kore on Olympus (because Zagreus was killed in the war against the Titans) and at least once after she had married Hades, using the <a class="twikilink" href="/pmwiki/pmwiki.php/Main/BedTrick" title="/pmwiki/pmwiki.php/Main/BedTrick">Bed Trick</a> on her (and conceiving Melinoe, minor goddess of madness and night terrors, in the process). <ul><li> Note, however, that Zeus's rapes of Persephone were played for drama and horror, the children resulting from them being disturbing and tragic, if not outright monstrous, rather than heroic, subtly deriding Zeus's incest. However, when Zeus did the same thing to other mortal women — some of whom were even his daughters and granddaughters — the trysts produce beautiful heroes. So the <a class="twikilink" href="/pmwiki/pmwiki.php/Main/DoubleStandard" title="/pmwiki/pmwiki.php/Main/DoubleStandard">Double Standard</a> was still in effect, but Persephone, as a goddess, was on a higher level than mortal women and was thus supposed to be above such treatment (and, indeed, Zeus often defended most of his immortal lovers and wives from rape by any other male but himself). </li><li> Given that Zeus was also sometimes portrayed as having an incarnation in the underworld that was closely identified with Hades, we can read here that Zeus and Hades were essentially two representations of the same god. Furthermore the title Zeus Kronion was a title that not only applied to Zeus, but to Hades as well. The Orphics seemed to regard and portray Hades and Plouton as two different gods. The book details the funerary poem of Theophile, noting that there was a clear distinction between the use of the names ‘Hades’ and ‘Plouton’. Theophile is buried as a bride of Plouton. The poem makes sure to mention that it is Hades, not Plouton who abducted the maiden (Funerary procedures of unwed maidens often portrayed them as the brides of Hades and the girls themselves were represented as being Persephone), but she later goes to the bed of Plouton. The Orphics worshipped Pluto as the saviour and judge of the dead as Zeus Chthónios, with the Orphic’s assuming that Zeus had an embodiment in the Underworld. This is exemplified by the Orphic tablet of Thurii, where it details Persephone’s abduction by Zeus, who then fathers Dionysus. The idea of defining Zeus as Hades has been present in Ancient Greek literature from Homer to Nonnos. Hence the Orphics stating Zeus Kronion tricking Persephone by disguising as Plouton, was just a reference to Hades having a role that links him to both Zeus and Plouton in the Orphics. Hence it's entirely possible that Melinoe's true parentage regards her as the daughter of Hades, rather than being a daughter of Zeus. </li><li> The Followers of Orpheus were trying to overshadow the older and vastly superior Eleusian Mysteries, so they rewrote the stories, the changing of the myths is noticeable due to the large amount of <a class="twikilink" href="/pmwiki/pmwiki.php/Main/ParentalIncest" title="/pmwiki/pmwiki.php/Main/ParentalIncest">Parental Incest</a> that occurs in them. Several cases in point have Nyx be raped by her father Phanes, Rhea be raped and impregnated by Zeus, resulting in Persephone's birth (Apparently Demeter and Rhea were the same deity to the Orphics) and Persephone bearing Zagreus. <a class="urllink" href="https://archive.org/details/SibyllineHymns_201711">But the Sibylline Oracles have two hymns reffering to Melinoe being the daughter of Hades and Persephone.<img height="12" src="https://static.tvtropes.org/pmwiki/pub/external_link.gif" style="border:none;" width="12"/></a> </li></ul></li></ul></div> <hr/><h2>Direct Examples:</h2> <p></p><div class="folderlabel" onclick="togglefolder('folder1');">    Anime and Manga </div><div class="folder" id="folder1" isfolder="true" style="display:block;"> <ul><li> In <em><a class="twikilink" href="/pmwiki/pmwiki.php/Manga/Berserk" title="/pmwiki/pmwiki.php/Manga/Berserk">Berserk</a></em>, Griffith undergoes a horrific transformation to become the <a class="twikilink" href="/pmwiki/pmwiki.php/Main/SatanicArchetype" title="/pmwiki/pmwiki.php/Main/SatanicArchetype">godlike entity Femto</a>, and his very first action was to rape his former comrade Casca. Now, a few brave fans - some of which are <a class="twikilink" href="/pmwiki/pmwiki.php/Main/DracoInLeatherPants" title="/pmwiki/pmwiki.php/Main/DracoInLeatherPants">very diehard Griffith fans</a> - have tried to explain or even justify Griffith's actions, one of which falls into the <a class="twikilink" href="/pmwiki/pmwiki.php/Main/OmniscientMoralityLicense" title="/pmwiki/pmwiki.php/Main/OmniscientMoralityLicense">Omniscient Morality License</a> rationale, since Griffith <span class="spoiler" title="you can set spoilers visible by default on your profile"> subsequently used the body of Casca's demonically corrupted child as a vessel to reincarnate himself into the physical world in two years time.</span> Of course, there are a LOT of holes in this theory, ranging from the very rules of causality in the <em>Berserk</em> mythos, to the very <a class="twikilink" href="/pmwiki/pmwiki.php/Main/ColdBloodedTorture" title="/pmwiki/pmwiki.php/Main/ColdBloodedTorture">sadistic and humiliating degree</a> of the rape itself, so it's safest to say that Griffith did what he did <a class="twikilink" href="/pmwiki/pmwiki.php/Main/ForTheEvulz" title="/pmwiki/pmwiki.php/Main/ForTheEvulz">For the Evulz</a>. </li><li> Despite being <a class="twikilink" href="/pmwiki/pmwiki.php/Main/GenderFlip" title="/pmwiki/pmwiki.php/Main/GenderFlip">Gender Flipped</a>, the story of a drunken Quetzalcoatl (better known in series as Lucoa) forcing herself on her sister (see below for full details) is kept completely intact in <em><a class="twikilink" href="/pmwiki/pmwiki.php/Manga/MissKobayashisDragonMaid" title="/pmwiki/pmwiki.php/Manga/MissKobayashisDragonMaid">Miss Kobayashi's Dragon Maid</a></em>. </li></ul></div> <p></p><div class="folderlabel" onclick="togglefolder('folder2');">    Comic Books </div><div class="folder" id="folder2" isfolder="true" style="display:block;"> <ul><li> Inverted in <em><a class="twikilink" href="/pmwiki/pmwiki.php/ComicBook/TheSandman" title="/pmwiki/pmwiki.php/ComicBook/TheSandman">The Sandman</a></em>: a struggling writer keeps Calliope (the muse of epic poetry) prisoner so as to keep finding inspiration and regularly rapes her, justifying it as her not being human. His punishment is that he ends up overflowing with ideas for his next novels, unable to remember a single one. </li><li> Subverted during <a class="twikilink" href="/pmwiki/pmwiki.php/Creator/GeorgePerez" title="/pmwiki/pmwiki.php/Creator/GeorgePerez">George Pérez</a>'s run of <a class="twikilink" href="/pmwiki/pmwiki.php/Franchise/WonderWoman" title="/pmwiki/pmwiki.php/Franchise/WonderWoman">Wonder Woman</a>. Pan<span class="notelabel" onclick="togglenote('note1xukx');"><sup>note </sup></span><span class="inlinefolder" id="note1xukx" isnote="true" onclick="togglenote('note1xukx');" style="cursor:pointer;font-size:smaller;display:none;">Well, <em>actually</em> a <a class="twikilink" href="/pmwiki/pmwiki.php/Main/Mole" title="/pmwiki/pmwiki.php/Main/Mole">Mole</a> sent by <a class="twikilink" href="/pmwiki/pmwiki.php/Characters/GLOtherVillains" title="/pmwiki/pmwiki.php/Characters/GLOtherVillains">the Manhunters</a></span> managed to focus Zeus' attentions on Wonder Woman, still a naive young woman. Zeus put <a class="urllink" href="https://multiframe.files.wordpress.com/2015/04/screen-shot-2015-04-03-at-1-56-37-pm.png">rather direct moves on Wonder Woman<img height="12" src="https://static.tvtropes.org/pmwiki/pub/external_link.gif" style="border:none;" width="12"/></a><small>◊</small>, got royally pissed off when she refused, and attempted to rape her — in front of her mother Hippolyta no less. Despite the fact that Diana and Hippolyta both worship Zeus as the head of the Greek pantheon, they both call him out. <div class="indent"><strong>Wonder Woman:</strong> Please, Lord Zeus — do not force yourself upon me! Though I live to serve you — I am not your <em><strong>toy</strong></em>! <br/><strong>Hippolyta</strong>: Your cruel son Heracles showed me such "respect"...I shall not allow his father to trifle thus with my only daughter! </div></li><li> <em><a class="twikilink" href="/pmwiki/pmwiki.php/ComicBook/AgeOfBronze" title="/pmwiki/pmwiki.php/ComicBook/AgeOfBronze">Age of Bronze</a></em>: As the point of the comic is "<a class="twikilink" href="/pmwiki/pmwiki.php/UsefulNotes/TheTrojanWar" title="/pmwiki/pmwiki.php/UsefulNotes/TheTrojanWar">The Trojan War</a> minus divine interference", several deconstructions occur: <ul><li> Helen's mother Leda was supposedly seduced by Zeus in the form of a swan. In fact, she's just insane. </li><li> Cassandra's curse of disbelieved prophecy came, not from refusing Apollo's advances, but from the fact that she and her brother were raped (as children) in Apollo's temple, the pedophile jeeringly claiming no one would believe them. </li><li> Most sons and daughters of gods are actually normal humans with "son/daughter of the god" being a title bestowed upon priests and priestesses. </li></ul></li><li> According to one issue of <em><a class="twikilink" href="/pmwiki/pmwiki.php/ComicBook/Hellblazer" title="/pmwiki/pmwiki.php/ComicBook/Hellblazer">Hellblazer</a></em>, the conception of Jesus was carried out by having the Archangel Gabriel rape Mary. He didn't particularly enjoy the experience, which makes him vulnerable to Ellie seducing him later. </li></ul></div> <p></p><div class="folderlabel" onclick="togglefolder('folder3');">    Fan Works </div><div class="folder" id="folder3" isfolder="true" style="display:block;"> <ul><li> In the <em><a class="twikilink" href="/pmwiki/pmwiki.php/ComicBook/XMen" title="/pmwiki/pmwiki.php/ComicBook/XMen">X-Men</a></em> <a class="twikilink" href="/pmwiki/pmwiki.php/Main/CrackFic" title="/pmwiki/pmwiki.php/Main/CrackFic">Crack Fic</a> <em><a class="urllink" href="https://www.fanfiction.net/s/10081442/4/Shuffle-or-Boogie">Shuffle or Boogie<img height="12" src="https://static.tvtropes.org/pmwiki/pub/external_link.gif" style="border:none;" width="12"/></a></em>, it's revealed that the Phoenix Force possessed Jean Grey's body so it could sleep with Scott. Of the several people present, only Jean herself objects to this <span class="notelabel" onclick="togglenote('note2lcl5');"><sup>note </sup></span><span class="inlinefolder" id="note2lcl5" isnote="true" onclick="togglenote('note2lcl5');" style="cursor:pointer;font-size:smaller;display:none;">and Scott never finds out about it</span>. </li><li> <em><a class="urllink" href="https://www.fanfiction.net/s/12506800/3/The-Unrelenting-Frozen-Seas-The-Trials">The Unrelenting Frozen Seas: The Trials<img height="12" src="https://static.tvtropes.org/pmwiki/pub/external_link.gif" style="border:none;" width="12"/></a></em> uses this as backstory for <a class="twikilink" href="/pmwiki/pmwiki.php/Main/ChildByRape" title="/pmwiki/pmwiki.php/Main/ChildByRape">Jackson Overland</a>: his godly mother Khione took a fancy to the demigod Jamie Overland, so she kept him frozen in her palace, awakening him for one hour at times to have her way with him. The guy was left broken and traumatized, which contributed to his suicide after she let him go. Even the other gods are repulsed by what Khione did, more particularly Apollo - as Jamie was his son - but Khione was never punished for it. </li><li> <a class="twikilink" href="/pmwiki/pmwiki.php/Main/Inverted" title="/pmwiki/pmwiki.php/Main/Inverted">Inverted</a> or played with in <a class="twikilink" href="/pmwiki/pmwiki.php/Franchise/Tron" title="/pmwiki/pmwiki.php/Franchise/Tron">TRON</a>: <a class="urllink" href="http://archiveofourown.org/works/1144855/chapters/2317686">Invasion<img height="12" src="https://static.tvtropes.org/pmwiki/pub/external_link.gif" style="border:none;" width="12"/></a> (a loose adaptation of <em><a class="twikilink" href="/pmwiki/pmwiki.php/VideoGame/TronTwoPointOh" title="/pmwiki/pmwiki.php/VideoGame/TronTwoPointOh">TRON 2.0</a></em>). Mercury (Program) corners Jet (User) and interrogates him, at first threatening his life, and then changing tactics. Jet sees little option but to comply with her wishes. Mercury didn't <em>know</em> what Jet was at the time, and mistook his energy patterns for agreement. </li></ul></div> <p></p><div class="folderlabel" onclick="togglefolder('folder4');">    Films </div><div class="folder" id="folder4" isfolder="true" style="display:block;"> <ul><li> Toyed with in the French movie <em><a class="twikilink" href="/pmwiki/pmwiki.php/Film/Immortal" title="/pmwiki/pmwiki.php/Film/Immortal">Immortal</a></em> which involves the Egyptian god Horus forcing himself on <span class="spoiler" title="you can set spoilers visible by default on your profile">the only woman on Earth able to bear his child</span> using mind control. The guy whose body he possessed to do this was less than pleased, and it remains a bitter point of their love triangle (since the possessed guy starts falling for her). Horus himself states he doesn't see it as rape after getting an earful from Nikopol, and when further pressed on it points out that he's <a class="twikilink" href="/pmwiki/pmwiki.php/Main/AboveGoodAndEvil" title="/pmwiki/pmwiki.php/Main/AboveGoodAndEvil">Above Good and Evil</a>. <span class="spoiler" title="you can set spoilers visible by default on your profile">At the end, she bears Horus' child, allowing him to cheat his fellow gods, and Nikopol goes to see her again.</span> </li></ul></div> <p></p><div class="folderlabel" onclick="togglefolder('folder5');">    Literature </div><div class="folder" id="folder5" isfolder="true" style="display:block;"> <ul><li> In <em><a class="twikilink" href="/pmwiki/pmwiki.php/Literature/FafhrdAndTheGrayMouser" title="/pmwiki/pmwiki.php/Literature/FafhrdAndTheGrayMouser">Fafhrd and the Gray Mouser</a></em>, Mouser got raped by the Goddess of Pain (<a class="twikilink" href="/pmwiki/pmwiki.php/Main/DoubleStandardRapeFemaleOnMale" title="/pmwiki/pmwiki.php/Main/DoubleStandardRapeFemaleOnMale">which he sort-of enjoyed</a>). She's a goddess—what are you going to do? Complain? </li><li> In <em><a class="twikilink" href="/pmwiki/pmwiki.php/Literature/TheHouseOfNight" title="/pmwiki/pmwiki.php/Literature/TheHouseOfNight">The House of Night</a></em>, despite the fact that Kalona radiates Darkness, females of all ages are still pretty keen on him. Even when the fact that he has raped women before is mentioned, it is conveniently ignored. Probably helps that Kalona has a <a class="twikilink" href="/pmwiki/pmwiki.php/Main/BrainwashedAndCrazy" title="/pmwiki/pmwiki.php/Main/BrainwashedAndCrazy">Brainwashed and Crazy</a> effect on people. </li><li> Menandore has her way with Udinaas against his will in <em><a class="twikilink" href="/pmwiki/pmwiki.php/Literature/MidnightTides" title="/pmwiki/pmwiki.php/Literature/MidnightTides">Midnight Tides</a></em>, making use of the <a class="twikilink" href="/pmwiki/pmwiki.php/Main/MightMakesRight" title="/pmwiki/pmwiki.php/Main/MightMakesRight">Might Makes Right</a> approach. The resulting child plays a big role later in the <em><a class="twikilink" href="/pmwiki/pmwiki.php/Literature/MalazanBookOfTheFallen" title="/pmwiki/pmwiki.php/Literature/MalazanBookOfTheFallen">Malazan Book of the Fallen</a></em> series. </li><li> Subverted in the sixth volume of <em><a class="twikilink" href="/pmwiki/pmwiki.php/LightNovel/TheUnexploredSummonBloodSign" title="/pmwiki/pmwiki.php/LightNovel/TheUnexploredSummonBloodSign">The Unexplored Summon://Blood-Sign</a></em>. Kyousuke is incapacitated for 24 hours after losing a battle, during which <span class="spoiler" title="you can set spoilers visible by default on your profile"><a class="twikilink" href="/pmwiki/pmwiki.php/Main/EldritchAbomination" title="/pmwiki/pmwiki.php/Main/EldritchAbomination">the White Queen</a> is allowed to do whatever she wants with him</span>. After waking up and vaguely remembering what happened, he's horrified and nearly breaks down. </li><li> Discussed and criticized often in <em><a class="twikilink" href="/pmwiki/pmwiki.php/Literature/TheCampHalfBloodSeries" title="/pmwiki/pmwiki.php/Literature/TheCampHalfBloodSeries">The Camp Half-Blood Series</a>.</em> One example comes from <em>Percy Jackson's Greek Gods</em>. <div class="indent"><strong>Percy</strong>: Men couldn't go around violating women without their consent! That was [the gods'] job! </div></li></ul></div> <p></p><div class="folderlabel" onclick="togglefolder('folder6');">    Religion and Mythology </div><div class="folder" id="folder6" isfolder="true" style="display:block;"> <ul><li> <a class="twikilink" href="/pmwiki/pmwiki.php/Main/OlderThanDirt" title="/pmwiki/pmwiki.php/Main/OlderThanDirt">Older Than Dirt</a>: As king, <a class="twikilink" href="/pmwiki/pmwiki.php/Literature/TheEpicOfGilgamesh" title="/pmwiki/pmwiki.php/Literature/TheEpicOfGilgamesh">Gilgamesh</a> (who was '<a class="twikilink" href="/pmwiki/pmwiki.php/Main/UnevenHybrid" title="/pmwiki/pmwiki.php/Main/UnevenHybrid">two thirds</a>' a god) made it a rule that <a class="twikilink" href="/pmwiki/pmwiki.php/Main/DroitDuSeigneur" title="/pmwiki/pmwiki.php/Main/DroitDuSeigneur">all women who were about to get married had to have sex with him first</a>. This pissed off his subjects, and the gods sent Enkidu to wrestle Gilgamesh and give him an outlet for his pent up energy (and yes, we do realize that <a class="twikilink" href="/pmwiki/pmwiki.php/Main/HoYay" title="/pmwiki/pmwiki.php/Main/HoYay">can be taken in more ways than one</a>, which was in the original myth too). </li><li> When Hatshepsut was staking her claim for King of Egypt she said that she was actually the son of Ra who had slept with her mother in the guise of Thutmose II (her real father). Therefore in the context of the story, Hatshepsut's mum thought she was having sex with her husband when really it was Ra. <ul><li> Just to make it weirder: this was actually the standard conception story for the Pharaohs, it's just that normally, a boy was begotten. This meant that it was, in fact, quite possible that any woman married to a Pharaoh was hoping for this to happen: this, and not birth order, supposedly determined whom the heir was. </li></ul></li><li> The moon goddess Selene placed the lovely youth Endymion into an eternal sleep so that he could be immortal, then <a class="twikilink" href="/pmwiki/pmwiki.php/Main/DudeShesLikeInAComa" title="/pmwiki/pmwiki.php/Main/DudeShesLikeInAComa">used him</a> to father fifty daughters. </li><li> Happens to Odysseus in <em><a class="twikilink" href="/pmwiki/pmwiki.php/Literature/TheOdyssey" title="/pmwiki/pmwiki.php/Literature/TheOdyssey">The Odyssey</a></em>. After Circe had turned all his men into animals, Odysseus attacked her with his sword. She was surprised by this, but laughed at his futile attempt to fight and made him her lover. Afterwards his men were turned back into people and they all quite happily spent a year feasting on her island. The alternate myth has Odysseus raping Circe (on the advice of Hermes) after using a magic plant to become immune to her powers. </li><li> (<a class="twikilink" href="/pmwiki/pmwiki.php/Creator/Ovid" title="/pmwiki/pmwiki.php/Creator/Ovid">Ovid</a>, in particular), was rather fond of changing myths to include this trope. <ul><li> In his stories, Poseidon raped a virgin priestess of Athena named Medusa within the goddess' own temple. Medusa was <a class="twikilink" href="/pmwiki/pmwiki.php/Main/DisproportionateRetribution" title="/pmwiki/pmwiki.php/Main/DisproportionateRetribution">transformed into a Gorgon by Athena</a> as punishment. Poseidon wasn't punished at all. Presumably a case of <a class="twikilink" href="/pmwiki/pmwiki.php/Main/MightMakesRight" title="/pmwiki/pmwiki.php/Main/MightMakesRight">Might Makes Right</a>, seeing as Poseidon was second only to Zeus in power. </li><li> Poseidon raped Caenis who had sworn to remain a virgin. As a reparation, he made her invulnerable and allowed her to make a wish. She begged him to turn her into a man so she would never suffer such humiliation again. She then changed her name to Caeneus. <ul><li> However in the original story by Hesiod, Poseidon's union with Medusa (Who was born a gorgon) was consensual, occurring in a beautiful meadow. </li></ul></li></ul></li><li> Theseus, who defeated the Minotaur and became King of Athens, has an interesting parentage: Poseidon seduced his mother Aethra on the same night that she lay with her husband Aegeus, which in the Greek understanding gave him two fathers, one divine, and one mortal. This allowed the Athenian royals to both claim an unbroken line of succession (as Aegeus, in the legend, was part of the original Athenian royal line) and descent from Poseidon (which <a class="twikilink" href="/pmwiki/pmwiki.php/Main/JustSoStory" title="/pmwiki/pmwiki.php/Main/JustSoStory">explained Athens' dominance of the sea lanes</a>). </li><li> Tyro, spouse of Cretheus, was in love with the river god Enipeus. Poseidon took his form, seduced Tyro then revealed himself to her. Their children are Neleus and Pelias. </li><li> In some versions of the <a class="twikilink" href="/pmwiki/pmwiki.php/Main/CassandraTruth" title="/pmwiki/pmwiki.php/Main/CassandraTruth">myth of Cassandra</a>, the curse that no one would believe her prophecies came about when she refused Apollo's advances. Mind you, the gift of prophecy was something he gave her in an attempt to make her consent, so arguably Apollo was nicer about this than the norm. <ul><li> Another version says that Cassandra held out from having sex with Apollo until he promised her the gift of prophecy. Upon receiving this gift, Cassandra refused Apollo <em>again,</em> and this time, furious, Apollo added the caveat that no one would believe her. </li></ul></li><li> Because of her insatiable lust, Eos kidnapped many handsome young men as her lovers. At least one object of her affection was married when she snatched him away, and was rather vocal about his desire to be returned to his wife. </li><li> Many stories say that Pan had a divine father, usually attributing this to Hermes, and that it happened this way, although it seems no two myths can agree on who the mother was. (Penelope and Dryope are the two names that come up most.) One myth even suggests Hermes raped said mother in the form of a goat. <a class="twikilink" href="/pmwiki/pmwiki.php/Main/BestialityIsDepraved" title="/pmwiki/pmwiki.php/Main/BestialityIsDepraved">(Ew...)</a> </li><li> In some versions of the myth, Dionysus fell in love with Ariadne and forced Theseus, Ariadne's lover, to abandon her on Naxos, where he picked her up and made her his wife. Ariadne's own feelings on the whole matter are never discussed, but Theseus was so devastated he forgot to change the sail on his ship from black to white. This caused his father's suicide, since the black sail was supposed to mean Theseus was killed by the Minoatur. <ul><li> However in the original story, Theseus abandoned her because he only agreed to marry her in exchange for her clue (the spool of wool). Dionysus later rescued her and myths sustain the fact that Ariadne certainly loved him (Dionysus). </li></ul></li><li> Calypso keeps Odysseus as her lover for seven years, despite his clear desire to return to his wife in Ithaca. Ultimately subverted, when Zeus intervenes and forces Calypso to release her captive. </li><li> Inverted in the myth explaining the name of the Areopagus: the first trial held there was when Poseidon prosecuted Ares for killing his son Halirrhothios. Depending on the myth, Ares' defence was either that Halirrhothios <a class="twikilink" href="/pmwiki/pmwiki.php/Main/Revenge" title="/pmwiki/pmwiki.php/Main/Revenge">had raped</a> his daughter Alcippe, or that he was <a class="twikilink" href="/pmwiki/pmwiki.php/Main/AttemptedRape" title="/pmwiki/pmwiki.php/Main/AttemptedRape">trying to do so</a>. </li><li> Also inverted in all the myths where a fleeing woman gets <a class="twikilink" href="/pmwiki/pmwiki.php/Main/BalefulPolymorph" title="/pmwiki/pmwiki.php/Main/BalefulPolymorph">transformed</a> into something in order to escape rape: Daphne into a laurel fleeing from Apollo, or Cornix into a crow fleeing from Neptune, for instance. </li><li> In Roman myth, Rhea Silvia was a Vestal Virgin who claimed she was violently raped by Mars, god of war. As a result, she conceived twins, Romulus and Remus. Since she was a Vestal Virgin, she couldn't very well raise them, and so <a class="twikilink" href="/pmwiki/pmwiki.php/Main/ParentalAbandonment" title="/pmwiki/pmwiki.php/Main/ParentalAbandonment">she left them on a hillside</a>, where they were raised by <a class="twikilink" href="/pmwiki/pmwiki.php/Main/WildChild" title="/pmwiki/pmwiki.php/Main/WildChild">a she-wolf</a>. <span class="notelabel" onclick="togglenote('note3wezi');"><sup>note </sup></span><span class="inlinefolder" id="note3wezi" isnote="true" onclick="togglenote('note3wezi');" style="cursor:pointer;font-size:smaller;display:none;"> Depending on your translation, this may be a <em>literal</em> <a class="twikilink" href="/pmwiki/pmwiki.php/Main/RaisedByWolves" title="/pmwiki/pmwiki.php/Main/RaisedByWolves">wolf</a>, or it could mean that the babies were found by a <a class="twikilink" href="/pmwiki/pmwiki.php/Main/HookerWithAHeartOfGold" title="/pmwiki/pmwiki.php/Main/HookerWithAHeartOfGold">prostitute.</a> </span> Long story short, <a class="twikilink" href="/pmwiki/pmwiki.php/Main/JustSoStory" title="/pmwiki/pmwiki.php/Main/JustSoStory">this is how Rome was founded</a>. <ul><li> In the original story Rhea was forced to become a Vestal Virgin but willingly entered the bed of Mars and her children were taken from her and abandoned. </li></ul></li></ul><ul><li> <a class="twikilink" href="/pmwiki/pmwiki.php/Myth/AztecMythology" title="/pmwiki/pmwiki.php/Myth/AztecMythology">Aztec Mythology</a> gives us an interesting example in the story of legendary priest-king Ce Acatl Topiltzin, who is taken to be an earthly incarnation of the creator god Quetzalcoatl in most versions of the myth. Quetzalcoatl's brother and eternal rival Tezcatlipoca decided it would be fun to humiliate him, so he tricked Quetzalcoatl into thinking he was old and decrepit. Tezcatlipoca offered him a potion that would restore his youth. Little did he know, the potion of youth was actually just alcohol. Desperate, he chugged the whole thing, getting himself completely wasted. Amorous in his drunkenness, he forced himself on the closest beautiful woman he could find... and the next morning, he woke up in bed with his own sister. The twist here comes in that unlike most gods who've committed rape, he felt incredibly ashamed and horrified at his act, feeling that he had defiled not only his sister but his own self. The following day, he resigned from his position as king, built himself a bonfire and burned himself to death. </li><li> In <a class="twikilink" href="/pmwiki/pmwiki.php/Myth/NorseMythology" title="/pmwiki/pmwiki.php/Myth/NorseMythology">Norse Mythology</a>, Odin raped Rindr so that she would give birth to Vali, who would avenge Baldur's death at the hands of Hoder. He tried to sleep with her the normal way, but she turned him down twice, so he cast a spell on her to drive her crazy, then disguised himself as a healer woman, tied her to the bed and had his way with her. </li></ul></div> <p></p><div class="folderlabel" onclick="togglefolder('folder7');">    Theatre </div><div class="folder" id="folder7" isfolder="true" style="display:block;"> <ul><li> In Shakespeare's <em><a class="twikilink" href="/pmwiki/pmwiki.php/Theatre/AMidsummerNightsDream" title="/pmwiki/pmwiki.php/Theatre/AMidsummerNightsDream">A Midsummer Night's Dream</a></em>, Bottom is the victim of a supernatural practical joke, and has the head of a donkey. Titania, the fairy queen, is the victim of another practical joke, dosed with a love potion, and forced to fall desperately in love with the next thing she sees. That would be the aforementioned Bottom. As soon as love-mad Titania casts eyes on Bottom, she wants him. Bottom, (who's having a bad day) decides to head home, not realizing that she's a fairy queen, and fairy queens aren't used to hearing the word "No". The scene of her capturing Bottom is never played as anything but hilarity, not say, kidnapping and sexual slavery. </li><li> Possibly happens in the play <em><a class="twikilink" href="/pmwiki/pmwiki.php/Theatre/AngelsInAmerica" title="/pmwiki/pmwiki.php/Theatre/AngelsInAmerica">Angels in America</a></em>. It <a class="twikilink" href="/pmwiki/pmwiki.php/Main/OrWasItADream" title="/pmwiki/pmwiki.php/Main/OrWasItADream">may or may not be a dream or vision</a> when the Angel appears before Prior, but he claims this is what she did to him, not to mention that she <a class="twikilink" href="/pmwiki/pmwiki.php/Main/OurAngelsAreDifferent" title="/pmwiki/pmwiki.php/Main/OurAngelsAreDifferent">had eight vaginas</a>. He seems rather blasé when talking about it, especially given he's in love with someone else and gay, but then, the hell he's put through in the first act is most likely much worse. </li></ul></div> <p></p><div class="folderlabel" onclick="togglefolder('folder8');">    Video Games </div><div class="folder" id="folder8" isfolder="true" style="display:block;"> <ul><li> In <em><a class="twikilink" href="/pmwiki/pmwiki.php/VideoGame/EverQuest" title="/pmwiki/pmwiki.php/VideoGame/EverQuest">EverQuest</a></em>, Innoruuk, the God of Hate, disguised himself as a regular dark elf male and impregnated a woman on the night of the Blood Moon festival that the dark elves celebrate every so often. Ceremony states that the female is supposed to ritually kill her mate as a sacrifice in Innoruuk's name if they have sex on that night. Of course, Innoruuk could spare a mortal body of some random dark elf, but the woman eventually gave birth to Lanys T'Vyl, Innoruuk's daughter and future Demi-Goddess of Strife. </li></ul></div> <p></p><div class="folderlabel" onclick="togglefolder('folder9');">    Web Comics </div><div class="folder" id="folder9" isfolder="true" style="display:block;"> <ul><li> <em><a class="urllink" href="http://sunfall.thewebcomic.com/">Sunfall<img height="12" src="https://static.tvtropes.org/pmwiki/pub/external_link.gif" style="border:none;" width="12"/></a></em> (NSFW) is centered around demigods who have various issues because of this. The protagonist thinks that her father only sired her to get the perfect oracle for the world. Truth is, the entire pantheon seduces/fucks with hot babes on a regular basis, underage girls included. </li><li> Averted in <a class="urllink" href="http://a-gnosis.deviantart.com/art/The-Family-Party-9-514405772">this<img height="12" src="https://static.tvtropes.org/pmwiki/pub/external_link.gif" style="border:none;" width="12"/></a> webcomic, where Ganymede seems quite happy with his job as cupbearer, and Zeus concerned about his emotional wellbeing. The webcomic tones Zeus' and other gods' rapeyness down quite a lot, in general, probably to avoid <a class="twikilink" href="/pmwiki/pmwiki.php/Main/ValuesDissonance" title="/pmwiki/pmwiki.php/Main/ValuesDissonance">Values Dissonance</a>. </li><li> <em><a class="twikilink" href="/pmwiki/pmwiki.php/Webcomic/HashtagBlessed" title="/pmwiki/pmwiki.php/Webcomic/HashtagBlessed">#Blessed</a></em>: Subverted. Despite the dubious consent of Joanna initially accepting the contract to date seven gods, she is the one who holds all the power and can set all the rules. </li></ul></div> <p></p><h2>Indirect Examples:</h2> <p></p><div class="folderlabel" onclick="togglefolder('folder10');">    Literature </div><div class="folder" id="folder10" isfolder="true" style="display:block;"> <ul><li> In one of <a class="twikilink" href="/pmwiki/pmwiki.php/Creator/TerryPratchett" title="/pmwiki/pmwiki.php/Creator/TerryPratchett">Terry Pratchett</a>'s <a class="twikilink" href="/pmwiki/pmwiki.php/Literature/Discworld" title="/pmwiki/pmwiki.php/Literature/Discworld">Discworld</a> novels, a woman is mentioned as being a hemidemisemi goddess, as an ancestress of hers was impregnated by the god Io (no relation to the Greek) in the form of a <em>vase of flowers</em>. </li></ul></div> <p></p><div class="folderlabel" onclick="togglefolder('folder11');">    Live-Action TV </div><div class="folder" id="folder11" isfolder="true" style="display:block;"> <ul><li> For <a class="twikilink" href="/pmwiki/pmwiki.php/Main/MaybeMagicMaybeMundane" title="/pmwiki/pmwiki.php/Main/MaybeMagicMaybeMundane">a certain definition of "divine"</a>, <span class="spoiler" title="you can set spoilers visible by default on your profile"> Ben Sisko's</span> backstory on <em><a class="twikilink" href="/pmwiki/pmwiki.php/Series/StarTrekDeepSpaceNine" title="/pmwiki/pmwiki.php/Series/StarTrekDeepSpaceNine">Star Trek: Deep Space Nine</a></em> counts. His mother was possessed or influenced somehow— the exact mechanics aren't elaborated upon— by the Prophets / wormhole aliens (<a class="twikilink" href="/pmwiki/pmwiki.php/Main/SufficientlyAdvancedAliens" title="/pmwiki/pmwiki.php/Main/SufficientlyAdvancedAliens">Sufficiently Advanced Aliens</a> and/or gods depending on who you ask) to marry his father. Once she'd given birth to their Chosen One, they freed her from their influence, and she promptly left his father. The father, who loved her deeply, was heartbroken and never knew that there had been anything problematic or unnatural about their relationship. It's probable that, being <a class="twikilink" href="/pmwiki/pmwiki.php/Main/StarfishAliens" title="/pmwiki/pmwiki.php/Main/StarfishAliens">Starfish Aliens</a> who do not experience linear time as we do and appear puzzled about many things about the human experience that we take for granted, <a class="twikilink" href="/pmwiki/pmwiki.php/Main/ValuesDissonance" title="/pmwiki/pmwiki.php/Main/ValuesDissonance">it never occurred to the Prophets / wormhole aliens</a> <a class="twikilink" href="/pmwiki/pmwiki.php/Main/BlueAndOrangeMorality" title="/pmwiki/pmwiki.php/Main/BlueAndOrangeMorality">that there was anything morally wrong with doing this</a>. The depth of the moral <a class="twikilink" href="/pmwiki/pmwiki.php/Main/Squick" title="/pmwiki/pmwiki.php/Main/Squick">squick</a> involved is never fully explored by the characters, either, and nobody ever gives them a <a class="twikilink" href="/pmwiki/pmwiki.php/Main/WhatTheHellHero" title="/pmwiki/pmwiki.php/Main/WhatTheHellHero">What the Hell, Hero?</a> about it, making it a case of <a class="twikilink" href="/pmwiki/pmwiki.php/Main/FridgeHorror" title="/pmwiki/pmwiki.php/Main/FridgeHorror">Fridge Horror</a> for the audience. </li></ul></div> <p></p><div class="folderlabel" onclick="togglefolder('folder12');">    Religion and Mythology </div><div class="folder" id="folder12" isfolder="true" style="display:block;"> <ul><li> <a class="twikilink" href="/pmwiki/pmwiki.php/Main/RapeByProxy" title="/pmwiki/pmwiki.php/Main/RapeByProxy">A very indirect example</a>: when King Minos of Crete (yes, the one, mentioned above, born to Europa after her rape/seduction by Zeus in the form of a bull) refused to sacrifice a prize white bull for Poseidon (bulls were a theme on Crete, it seems), Poseidon punishes him by making Minos' wife Pasiphae fall in love with the bull. She had a wooden cow made and climbed inside so the bull would have sex with her. She then later gave birth to a <a class="twikilink" href="/pmwiki/pmwiki.php/Main/HalfHumanHybrid" title="/pmwiki/pmwiki.php/Main/HalfHumanHybrid">half human/half bull creature</a> that became the Minotaur. <ul><li> Another version is that love was inspired by Aphrodite who wanted to punish Pasiphae because <a class="twikilink" href="/pmwiki/pmwiki.php/Main/MisplacedRetribution" title="/pmwiki/pmwiki.php/Main/MisplacedRetribution">the latter's father, Helios, revealed to husband Hephaestos her affair with Ares.</a> </li></ul></li><li> <a class="twikilink" href="/pmwiki/pmwiki.php/Myth/CelticMythology" title="/pmwiki/pmwiki.php/Myth/CelticMythology">Cuchulain</a> was conceived this way allegedly. His mother Deichtine assisted Lugh's wife in labor. For her reward, Lugh impregnated <em>her</em>. </li><li> According to the Tupi people of the Amazon area of present day Brazil, the sun was outraged when early human society was dominated by women. It caused sap from the curura (or puruman) tree to spray on the breast of a virgin named Ceucy, impregnating her with Jurapari (or Jurupari). He declared war on women and tore down the matriarchy. After his victory, Jurapari set up feasts in which the secrets of men's rule were passed down through the generations. Any women attending were put to death, Ceucy being their first victim. In some versions of the legend, one day Jurupari will find a woman worthy of him and from that day forward, the sexes will be equal. <ul><li> In other South American regions, Jurupari is the name of a man-eating spirit of the palm tree. It's unclear how the two myths relate. </li></ul></li><li> In some Native American tales from the Pacific Northwest, <a class="twikilink" href="/pmwiki/pmwiki.php/Main/TheTrickster" title="/pmwiki/pmwiki.php/Main/TheTrickster">Raven</a> impregnates a chieftain's daughter by turning into a pine needle floating in the water and letting her drink him. Slightly different than most in that the resulting child is Raven himself in disguise, not his offspring. <ul><li> Which is also how Etain ends up being reborn as a human in <a class="twikilink" href="/pmwiki/pmwiki.php/Myth/CelticMythology" title="/pmwiki/pmwiki.php/Myth/CelticMythology">Celtic Mythology</a>, though in her case it was with a butterfly and a chalice of wine. </li><li> Also seen in an ancient Egyptian myth. A humble hermit's god-given trophy wife is proposed to by the pharaoh. The pharaoh kills her husband so that he won't come after her. The husband is reincarnated through several forms, taunting his murderous ex each time. Eventually, he's reincarnated as a tree and the wife orders the pharaoh to chop it down. She watches the tree being felled and a splinter from the lumberjack's axe flies into her mouth and impregnates her with her vindictive ex. The baby born is crown prince, because the pharaoh assumes it's his. Decades later, when the pharaoh dies and ex-hubby takes the throne, his first royal order is to have his ex-wife (now also his mother) executed for killing him. Just goes to show revenge is a dish best served cold. </li></ul></li><li> The story of <a class="twikilink" href="/pmwiki/pmwiki.php/UsefulNotes/Jesus" title="/pmwiki/pmwiki.php/UsefulNotes/Jesus">Jesus</a>' birth from <a class="twikilink" href="/pmwiki/pmwiki.php/Literature/TheFourGospels" title="/pmwiki/pmwiki.php/Literature/TheFourGospels">The Four Gospels</a> is sometimes accused of being this, but ultimately <a class="twikilink" href="/pmwiki/pmwiki.php/Main/AvertedTrope" title="/pmwiki/pmwiki.php/Main/AvertedTrope">averts</a>, as Mary agrees to give birth to Christ in the Book of Luke, which records the <a class="twikilink" href="/pmwiki/pmwiki.php/Main/ArchangelGabriel" title="/pmwiki/pmwiki.php/Main/ArchangelGabriel">Archangel Gabriel</a> telling Mary she is going to conceive and bear a son, and Mary is happy about this, saying, "Behold, I am the handmaid of the Lord. May it be done to me according to your word."<span class="notelabel" onclick="togglenote('note47l79');"><sup>note </sup></span><span class="inlinefolder" id="note47l79" isnote="true" onclick="togglenote('note47l79');" style="cursor:pointer;font-size:smaller;display:none;">Although Mary was likely fairly young at the time of conception, <a class="twikilink" href="/pmwiki/pmwiki.php/Main/ValuesDissonance" title="/pmwiki/pmwiki.php/Main/ValuesDissonance">and hence would likely not be legally allowed to decide such things for herself in our time</a>, there was no such legal age restriction on the books in her time. Remember, back in <a class="twikilink" href="/pmwiki/pmwiki.php/Main/BibleTimes" title="/pmwiki/pmwiki.php/Main/BibleTimes">Bible Times</a>, there <em>was</em> no concept of <a class="twikilink" href="/pmwiki/pmwiki.php/Main/SocietyMarchesOn" title="/pmwiki/pmwiki.php/Main/SocietyMarchesOn">"adolescence" as we have it today</a>; you were either a child or an adult, and the delineation was mostly made along lines of <em>physical</em> maturity (e.g. when a girl had her first period or a boy had his first wet dream). Then too, God is not indicated to have had <em>sex</em> with Mary in any physical sense of the word, <a class="twikilink" href="/pmwiki/pmwiki.php/Main/MysticalPregnancy" title="/pmwiki/pmwiki.php/Main/MysticalPregnancy">just miraculously placed Jesus in her womb to grow</a>, which was to make a point of His divinity that it could make a virgin give birth. (This was also back before sperm donation became a commonly known practice.) Moreover, compare His waiting for her acceptance (explicitly stated in Luke 1:38) before actually making her pregnant with her society's expectation that she was to be little more than <a class="twikilink" href="/pmwiki/pmwiki.php/Main/BabyFactory" title="/pmwiki/pmwiki.php/Main/BabyFactory">a passive vessel for childbearing to her husband</a> whether that was what <em>she</em> wanted or not, and it's downright <a class="twikilink" href="/pmwiki/pmwiki.php/Main/FairForItsDay" title="/pmwiki/pmwiki.php/Main/FairForItsDay">Fair for Its Day</a>.</span> </li><li> <a class="twikilink" href="/pmwiki/pmwiki.php/Myth/NorseMythology" title="/pmwiki/pmwiki.php/Myth/NorseMythology">Norse Mythology</a> doesn't skimp on this version either. Freyr, God of Fertility and Sexuality, got his Giantess wife Gerth by sending over a servant to threaten her loved ones until she consented. Joke's on him, though—during <a class="twikilink" href="/pmwiki/pmwiki.php/Main/TheEndOfTheWorldAsWeKnowIt" title="/pmwiki/pmwiki.php/Main/TheEndOfTheWorldAsWeKnowIt">Ragnarok</a>, the sword he gave the servant so he could do his job turned out to be crucial, and without it, he forfeited his life. Schoolar Sigurður Nordal believed it was that very sword with which Surtr will do him in. </li></ul></div> <p></p><div class="folderlabel" onclick="togglefolder('folder13');">    Web Comics </div><div class="folder" id="folder13" isfolder="true" style="display:block;"> <ul><li> <em><a class="twikilink" href="/pmwiki/pmwiki.php/Webcomic/SomethingPositive" title="/pmwiki/pmwiki.php/Webcomic/SomethingPositive">Something*Positive</a></em> <a class="urllink" href="http://somethingpositive.net/sp10212011.shtml">alludes to this<img height="12" src="https://static.tvtropes.org/pmwiki/pub/external_link.gif" style="border:none;" width="12"/></a>: <div class="indent"><strong>Vanessa</strong>: I should have known better than to <a class="twikilink" href="/pmwiki/pmwiki.php/Main/IssueDrift" title="/pmwiki/pmwiki.php/Main/IssueDrift">use social issues as a plot</a> after PeeJee's Greek myth themed RPG. <br/><strong>Davan</strong>: Hey! If a woman is a victim of sexual assault from a god's golden rain storm she has the right to make whatever choice that's best for her. <br/><strong>Donna</strong>: <a class="twikilink" href="/pmwiki/pmwiki.php/Main/GoodGirlsAvoidAbortion" title="/pmwiki/pmwiki.php/Main/GoodGirlsAvoidAbortion">Life begins at rainfall!</a> </div></li></ul></div> <hr/><em><a class="twikilink" href="/pmwiki/pmwiki.php/WebVideo/AutoTuneTheNews" title="/pmwiki/pmwiki.php/WebVideo/AutoTuneTheNews">Well, obviously we have a rapist on</a> <a class="twikilink" href="/pmwiki/pmwiki.php/Myth/ClassicalMythology" title="/pmwiki/pmwiki.php/Myth/ClassicalMythology">Mount Olympus</a>. <a class="twikilink" href="/pmwiki/pmwiki.php/Main/MemeticMutation" title="/pmwiki/pmwiki.php/Main/MemeticMutation">He's climbin' in yo' windows, he's snatchin' yo' people up, tryin' to rape 'em.</a> <a class="twikilink" href="/pmwiki/pmwiki.php/Main/DepravedBisexual" title="/pmwiki/pmwiki.php/Main/DepravedBisexual">So y'all need to hide ya' kids, hide ya' wife, and hide ya' husband, 'cause they rapin' e'rybody out here.</a></em> <p> </p><hr/> </div> <div class="square_ad footer-article-ad main_2" data-isolated="1"></div> <div class="section-links" itemscope="" itemtype="http://schema.org/SiteNavigationElement"> <div class="titles"> <div><h3 class="text-center text-uppercase">Previous</h3></div> <div><h3 class="text-center text-uppercase">Index</h3></div> <div><h3 class="text-center text-uppercase">Next</h3></div> </div> <div class="links"> <ul> <li> <a href="/pmwiki/pmwiki.php/Main/DivineRanks">Divine Ranks</a> </li> <li> <a href="/pmwiki/pmwiki.php/Main/GodTropes">God Tropes</a> </li> <li> <a href="/pmwiki/pmwiki.php/Main/DragonsAreDivine">Dragons Are Divine</a> </li> </ul> <ul> <li> <a href="/pmwiki/pmwiki.php/Main/DontLookAtMe">Don't Look At Me</a> </li> <li> <a href="/pmwiki/pmwiki.php/Main/SexualHarassmentAndRapeTropes">Sexual Harassment and Rape Tropes</a> </li> <li> <a href="/pmwiki/pmwiki.php/Main/DoubleStandardRapeFemaleOnFemale">Double Standard: Rape, Female on Female</a> </li> </ul> <ul> <li> <a href="/pmwiki/pmwiki.php/Main/Dominatrix">Dominatrix</a> </li> <li> <a href="/pmwiki/pmwiki.php/Main/OlderThanDirt">Older Than Dirt</a> </li> <li> <a href="/pmwiki/pmwiki.php/Main/DraconicAbomination">Draconic Abomination</a> </li> </ul> <ul> <li> <a href="/pmwiki/pmwiki.php/Main/DoubleEntendre">Double Entendre</a> </li> <li> <a href="/pmwiki/pmwiki.php/NoRealLife/SexSexualityAndRapeTropes">NoRealLife/Sex, Sexuality, and Rape Tropes</a> </li> <li> <a href="/pmwiki/pmwiki.php/Main/DoubleStandardRapeFemaleOnFemale">Double Standard: Rape, Female on Female</a> </li> </ul> <ul> <li> <a href="/pmwiki/pmwiki.php/Main/DivineRanks">Divine Ranks</a> </li> <li> <a href="/pmwiki/pmwiki.php/Main/ReligionTropes">Religion Tropes</a> </li> <li> <a href="/pmwiki/pmwiki.php/Main/EverybodyHatesHades">Everybody Hates Hades</a> </li> </ul> <ul> <li> <a href="/pmwiki/pmwiki.php/Main/DoNotAdjustYourSet">Do Not Adjust Your Set</a> </li> <li> <a href="/pmwiki/pmwiki.php/ImageSource/Webcomics">ImageSource/Webcomics</a> </li> <li> <a href="/pmwiki/pmwiki.php/Main/DroppedABridgeOnHim">Dropped a Bridge on Him</a> </li> </ul> </div> </div> <div class="outer_ads_by_salon_wrapper" id="exco_player_insert_div"> </div> </article> <div id="main-content-sidebar"><div class="sidebar-item display-options"> <ul class="sidebar display-toggles"> <li>Show Spoilers <div class="display-toggle show-spoilers" id="sidebar-toggle-showspoilers"></div></li> <li>Night Vision <div class="display-toggle night-vision" id="sidebar-toggle-nightvision"></div></li> <li>Sticky Header <div class="display-toggle sticky-header" id="sidebar-toggle-stickyheader"></div></li> <li>Wide Load <div class="display-toggle wide-load" id="sidebar-toggle-wideload"></div></li> </ul> <script>updateDesktopPrefs();</script> </div> <div class="sidebar-item ad sb-ad-unit"> <div class="proper-ad-unit"> <div id="proper-ad-tvtropes_ad_2"> <script>propertag.cmd.push(function() { proper_display('tvtropes_ad_2'); });</script> </div> </div></div> <div class="sidebar-item quick-links" itemtype="http://schema.org/SiteNavigationElement"> <p class="sidebar-item-title" data-title="Important Links">Important Links</p> <div class="padded"> <a href="/pmwiki/query.php?type=att">Ask The Tropers</a> <a href="/pmwiki/query.php?type=tf">Trope Finder</a> <a href="/pmwiki/query.php?type=ykts">You Know That Show...</a> <a href="/pmwiki/tlp_activity.php">Trope Launch Pad</a> <a href="/pmwiki/review_activity.php">Reviews</a> <a data-modal-target="login" href="/pmwiki/lbs.php">Live Blogs</a> <a href="/pmwiki/ad-free-subscribe.php">Go Ad Free!</a> </div> </div> <div class="sidebar-item sb-ad-unit"> <div class="sidebar-section"> <div class="square_ad ad-size-300x600 ad-section text-center"> <div class="proper-ad-unit"> <div id="proper-ad-tvtropes_ad_3"> <script>propertag.cmd.push(function() { proper_display('tvtropes_ad_3'); });</script> </div> </div> </div> </div> </div> <div class="sidebar-item"> <p class="sidebar-item-title" data-title="Crucial Browsing">Crucial Browsing</p> <ul class="padded font-s" itemscope="" itemtype="http://schema.org/SiteNavigationElement"> <li><a data-click-toggle="active" href="javascript:void(0);">Genre</a> <ul> <li><a href="/pmwiki/pmwiki.php/Main/ActionAdventureTropes" title="Main/ActionAdventureTropes">Action Adventure</a></li> <li><a href="/pmwiki/pmwiki.php/Main/ComedyTropes" title="Main/ComedyTropes">Comedy</a></li> <li><a href="/pmwiki/pmwiki.php/Main/CommercialsTropes" title="Main/CommercialsTropes">Commercials</a></li> <li><a href="/pmwiki/pmwiki.php/Main/CrimeAndPunishmentTropes" title="Main/CrimeAndPunishmentTropes">Crime &amp; Punishment</a></li> <li><a href="/pmwiki/pmwiki.php/Main/DramaTropes" title="Main/DramaTropes">Drama</a></li> <li><a href="/pmwiki/pmwiki.php/Main/HorrorTropes" title="Main/HorrorTropes">Horror</a></li> <li><a href="/pmwiki/pmwiki.php/Main/LoveTropes" title="Main/LoveTropes">Love</a></li> <li><a href="/pmwiki/pmwiki.php/Main/NewsTropes" title="Main/NewsTropes">News</a></li> <li><a href="/pmwiki/pmwiki.php/Main/ProfessionalWrestling" title="Main/ProfessionalWrestling">Professional Wrestling</a></li> <li><a href="/pmwiki/pmwiki.php/Main/SpeculativeFictionTropes" title="Main/SpeculativeFictionTropes">Speculative Fiction</a></li> <li><a href="/pmwiki/pmwiki.php/Main/SportsStoryTropes" title="Main/SportsStoryTropes">Sports Story</a></li> <li><a href="/pmwiki/pmwiki.php/Main/WarTropes" title="Main/WarTropes">War</a></li> </ul> </li> <li><a data-click-toggle="active" href="javascript:void(0);">Media</a> <ul> <li><a href="/pmwiki/pmwiki.php/Main/Media" title="Main/Media">All Media</a></li> <li><a href="/pmwiki/pmwiki.php/Main/AnimationTropes" title="Main/AnimationTropes">Animation (Western)</a></li> <li><a href="/pmwiki/pmwiki.php/Main/Anime" title="Main/Anime">Anime</a></li> <li><a href="/pmwiki/pmwiki.php/Main/ComicBookTropes" title="Main/ComicBookTropes">Comic Book</a></li> <li><a href="/pmwiki/pmwiki.php/Main/FanFic" title="FanFic/FanFics">Fan Fics</a></li> <li><a href="/pmwiki/pmwiki.php/Main/Film" title="Main/Film">Film</a></li> <li><a href="/pmwiki/pmwiki.php/Main/GameTropes" title="Main/GameTropes">Game</a></li> <li><a href="/pmwiki/pmwiki.php/Main/Literature" title="Main/Literature">Literature</a></li> <li><a href="/pmwiki/pmwiki.php/Main/MusicAndSoundEffects" title="Main/MusicAndSoundEffects">Music And Sound Effects</a></li> <li><a href="/pmwiki/pmwiki.php/Main/NewMediaTropes" title="Main/NewMediaTropes">New Media</a></li> <li><a href="/pmwiki/pmwiki.php/Main/PrintMediaTropes" title="Main/PrintMediaTropes">Print Media</a></li> <li><a href="/pmwiki/pmwiki.php/Main/Radio" title="Main/Radio">Radio</a></li> <li><a href="/pmwiki/pmwiki.php/Main/SequentialArt" title="Main/SequentialArt">Sequential Art</a></li> <li><a href="/pmwiki/pmwiki.php/Main/TabletopGames" title="Main/TabletopGames">Tabletop Games</a></li> <li><a href="/pmwiki/pmwiki.php/UsefulNotes/Television" title="Main/Television">Television</a></li> <li><a href="/pmwiki/pmwiki.php/Main/Theater" title="Main/Theater">Theater</a></li> <li><a href="/pmwiki/pmwiki.php/Main/VideogameTropes" title="Main/VideogameTropes">Videogame</a></li> <li><a href="/pmwiki/pmwiki.php/Main/Webcomics" title="Main/Webcomics">Webcomics</a></li> </ul> </li> <li><a data-click-toggle="active" href="javascript:void(0);">Narrative</a> <ul> <li><a href="/pmwiki/pmwiki.php/Main/UniversalTropes" title="Main/UniversalTropes">Universal</a></li> <li><a href="/pmwiki/pmwiki.php/Main/AppliedPhlebotinum" title="Main/AppliedPhlebotinum">Applied Phlebotinum</a></li> <li><a href="/pmwiki/pmwiki.php/Main/CharacterizationTropes" title="Main/CharacterizationTropes">Characterization</a></li> <li><a href="/pmwiki/pmwiki.php/Main/Characters" title="Main/Characters">Characters</a></li> <li><a href="/pmwiki/pmwiki.php/Main/CharactersAsDevice" title="Main/CharactersAsDevice">Characters As Device</a></li> <li><a href="/pmwiki/pmwiki.php/Main/Dialogue" title="Main/Dialogue">Dialogue</a></li> <li><a href="/pmwiki/pmwiki.php/Main/Motifs" title="Main/Motifs">Motifs</a></li> <li><a href="/pmwiki/pmwiki.php/Main/NarrativeDevices" title="Main/NarrativeDevices">Narrative Devices</a></li> <li><a href="/pmwiki/pmwiki.php/Main/Paratext" title="Main/Paratext">Paratext</a></li> <li><a href="/pmwiki/pmwiki.php/Main/Plots" title="Main/Plots">Plots</a></li> <li><a href="/pmwiki/pmwiki.php/Main/Settings" title="Main/Settings">Settings</a></li> <li><a href="/pmwiki/pmwiki.php/Main/Spectacle" title="Main/Spectacle">Spectacle</a></li> </ul> </li> <li><a data-click-toggle="active" href="javascript:void(0);">Other Categories</a> <ul> <li><a href="/pmwiki/pmwiki.php/Main/BritishTellyTropes" title="Main/BritishTellyTropes">British Telly</a></li> <li><a href="/pmwiki/pmwiki.php/Main/TheContributors" title="Main/TheContributors">The Contributors</a></li> <li><a href="/pmwiki/pmwiki.php/Main/CreatorSpeak" title="Main/CreatorSpeak">Creator Speak</a></li> <li><a href="/pmwiki/pmwiki.php/Main/Creators" title="Main/Creators">Creators</a></li> <li><a href="/pmwiki/pmwiki.php/Main/DerivativeWorks" title="Main/DerivativeWorks">Derivative Works</a></li> <li><a href="/pmwiki/pmwiki.php/Main/LanguageTropes" title="Main/LanguageTropes">Language</a></li> <li><a href="/pmwiki/pmwiki.php/Main/LawsAndFormulas" title="Main/LawsAndFormulas">Laws And Formulas</a></li> <li><a href="/pmwiki/pmwiki.php/Main/ShowBusiness" title="Main/ShowBusiness">Show Business</a></li> <li><a href="/pmwiki/pmwiki.php/Main/SplitPersonalityTropes" title="Main/SplitPersonalityTropes">Split Personality</a></li> <li><a href="/pmwiki/pmwiki.php/Main/StockRoom" title="Main/StockRoom">Stock Room</a></li> <li><a href="/pmwiki/pmwiki.php/Main/TropeTropes" title="Main/TropeTropes">Trope</a></li> <li><a href="/pmwiki/pmwiki.php/Main/Tropes" title="Main/Tropes">Tropes</a></li> <li><a href="/pmwiki/pmwiki.php/Main/TruthAndLies" title="Main/TruthAndLies">Truth And Lies</a></li> <li><a href="/pmwiki/pmwiki.php/Main/TruthInTelevision" title="Main/TruthInTelevision">Truth In Television</a></li> </ul> </li> <li><a data-click-toggle="active" href="javascript:void(0);">Topical Tropes</a> <ul> <li><a href="/pmwiki/pmwiki.php/Main/BetrayalTropes" title="Main/BetrayalTropes">Betrayal</a></li> <li><a href="/pmwiki/pmwiki.php/Main/CensorshipTropes" title="Main/CensorshipTropes">Censorship</a></li> <li><a href="/pmwiki/pmwiki.php/Main/CombatTropes" title="Main/CombatTropes">Combat</a></li> <li><a href="/pmwiki/pmwiki.php/Main/DeathTropes" title="Main/DeathTropes">Death</a></li> <li><a href="/pmwiki/pmwiki.php/Main/FamilyTropes" title="Main/FamilyTropes">Family</a></li> <li><a href="/pmwiki/pmwiki.php/Main/FateAndProphecyTropes" title="Main/FateAndProphecyTropes">Fate And Prophecy</a></li> <li><a href="/pmwiki/pmwiki.php/Main/FoodTropes" title="Main/FoodTropes">Food</a></li> <li><a href="/pmwiki/pmwiki.php/Main/HolidayTropes" title="Main/HolidayTropes">Holiday</a></li> <li><a href="/pmwiki/pmwiki.php/Main/MemoryTropes" title="Main/MemoryTropes">Memory</a></li> <li><a href="/pmwiki/pmwiki.php/Main/MoneyTropes" title="Main/MoneyTropes">Money</a></li> <li><a href="/pmwiki/pmwiki.php/Main/MoralityTropes" title="Main/MoralityTropes">Morality</a></li> <li><a href="/pmwiki/pmwiki.php/Main/PoliticsTropes" title="Main/PoliticsTropes">Politics</a></li> <li><a href="/pmwiki/pmwiki.php/Main/ReligionTropes" title="Main/ReligionTropes">Religion</a></li> <li><a href="/pmwiki/pmwiki.php/Main/SchoolTropes" title="Main/SchoolTropes">School</a></li> </ul> </li> </ul> </div> <div class="sidebar-item showcase"> <p class="sidebar-item-title" data-title="Community Showcase">Community Showcase <a class="bubble float-right hover-blue" href="/pmwiki/showcase.php">More</a></p> <p class="community-showcase"> <a href="https://sharetv.com/shows/echo_chamber" onclick="trackOutboundLink('https://sharetv.com/shows/echo_chamber');" target="_blank"> <img alt="" class="lazy-image" data-src="/images/communityShowcase-echochamber.jpg"/></a> <a href="/pmwiki/pmwiki.php/Webcomic/TwistedTropes"> <img alt="" class="lazy-image" data-src="/img/howlandsc-side.jpg"/></a> </p> </div> <div class="sidebar-item sb-ad-unit" id="stick-cont"> <div class="sidebar-section" id="stick-bar"> <div class="square_ad ad-size-300x600 ad-section text-center"> <div class="proper-ad-unit"> <div id="proper-ad-tvtropes_ad_4"> <script>propertag.cmd.push(function() { proper_display('tvtropes_ad_4'); });</script> </div> </div> </div> </div> </div> </div> </div> <div class="action-bar tablet-off" id="action-bar-bottom"> <a class="scroll-to-top dead-button" href="#top-of-page" onclick="$('html, body').animate({scrollTop : 0},500);">Top</a> </div> </div> <div class="proper-ad-unit ad-sticky"> <div id="proper-ad-tvtropes_sticky_ad"> <script>propertag.cmd.push(function() { proper_display('tvtropes_sticky_ad'); });</script> </div> </div> <footer id="main-footer"> <div id="main-footer-inner"> <div class="footer-left"> <a class="img-link" href="/"><img alt="TV Tropes" class="lazy-image" data-src="/img/tvtropes-footer-logo.png" title="TV Tropes"/></a> <form action="index.html" class="navbar-form newsletter-signup validate modal-replies" data-ajax-get="/ajax/subscribe_email.php" id="cse-search-box-mobile" name="" role=""> <button class="btn-submit newsletter-signup-submit-button" id="subscribe-btn" type="submit"><i class="fa fa-paper-plane"></i></button> <input class="form-control" id="subscription-email" name="q" placeholder="Subscribe" size="31" type="text" validate-type="email" value=""/> </form> <ul class="social-buttons"> <li><a class="btn fb" href="https://www.facebook.com/tvtropes" onclick="_gaq.push(['_trackEvent', 'btn-social-icon', 'click', 'btn-facebook']);" target="_blank"><i class="fa fa-facebook"></i></a></li> <li><a class="btn tw" href="https://www.twitter.com/tvtropes" onclick="_gaq.push(['_trackEvent', 'btn-social-icon', 'click', 'btn-twitter']);" target="_blank"><i class="fa fa-twitter"></i></a> </li> <li><a class="btn rd" href="https://www.reddit.com/r/tvtropes" onclick="_gaq.push(['_trackEvent', 'btn-social-icon', 'click', 'btn-reddit']);" target="_blank"><i class="fa fa-reddit-alien"></i></a></li> </ul> </div> <hr/> <ul class="footer-menu" itemscope="" itemtype="http://schema.org/SiteNavigationElement"> <li><h4 class="footer-menu-header">TVTropes</h4></li> <li><a href="/pmwiki/pmwiki.php/Main/Administrivia">About TVTropes</a></li> <li><a href="/pmwiki/pmwiki.php/Administrivia/TheGoalsOfTVTropes">TVTropes Goals</a></li> <li><a href="/pmwiki/pmwiki.php/Administrivia/TheTropingCode">Troping Code</a></li> <li><a href="/pmwiki/pmwiki.php/Administrivia/TVTropesCustoms">TVTropes Customs</a></li> <li><a href="/pmwiki/pmwiki.php/JustForFun/TropesOfLegend">Tropes of Legend</a></li> <li><a href="/pmwiki/ad-free-subscribe.php">Go Ad-Free</a></li> </ul> <hr/> <ul class="footer-menu" itemscope="" itemtype="http://schema.org/SiteNavigationElement"> <li><h4 class="footer-menu-header">Community</h4></li> <li><a href="/pmwiki/query.php?type=att">Ask The Tropers</a></li> <li><a href="/pmwiki/tlp_activity.php">Trope Launch Pad</a></li> <li><a href="/pmwiki/query.php?type=tf">Trope Finder</a></li> <li><a href="/pmwiki/query.php?type=ykts">You Know That Show</a></li> <li><a data-modal-target="login" href="/pmwiki/lbs.php">Live Blogs</a></li> <li><a href="/pmwiki/review_activity.php">Reviews</a></li> <li><a href="/pmwiki/topics.php">Forum</a></li> </ul> <hr/> <ul class="footer-menu" itemscope="" itemtype="http://schema.org/SiteNavigationElement"> <li><h4 class="footer-menu-header">Tropes HQ</h4></li> <li><a href="/pmwiki/about.php">About Us</a></li> <li><a href="/pmwiki/contact.php">Contact Us</a></li> <li><a href="/pmwiki/dmca.php">DMCA Notice</a></li> <li><a href="/pmwiki/privacypolicy.php">Privacy Policy</a></li> </ul> </div> <div class="text-center gutter-top gutter-bottom tablet-on" id="desktop-on-mobile-toggle"> <a href="/pmwiki/switchDeviceCss.php?mobileVersion=1" rel="nofollow">Switch to <span class="txt-desktop">Desktop</span><span class="txt-mobile">Mobile</span> Version</a> </div> <div class="legal"> <p>TVTropes is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported License. <br/>Permissions beyond the scope of this license may be available from <a href="mailto:thestaff@tvtropes.org" rel="cc:morePermissions" xmlns:cc="http://creativecommons.org/ns#"> thestaff@tvtropes.org</a>.</p> <br/> <div class="privacy_wrapper"> </div> </div> </footer> <style> div.fc-ccpa-root { position: absolute !important; bottom: 93px !important; margin: auto !important; width: 100% !important; z-index: 9999 !important; } .fc-ccpa-root .fc-dns-dialog .fc-dns-link p{ outline: none !important; text-decoration: underline !important; font-size: .7em !important; font-family: sans-serif !important; } .fc-ccpa-root .fc-dns-dialog .fc-dns-link .fc-button-background { background: none !important; } </style> <div class="full-screen" id="_pm_videoViewer"> <a class="close" href="#close" id="_pm_videoViewer-close"></a> <div class="_pmvv-body"> <div class="_pmvv-vidbox"> <video class="video-js vjs-default-skin vjs-16-9" data-video-id="" id="overlay-video-player-box"> </video> <div class="_pmvv-vidbox-desc"> <h1 id="overlay-title"></h1> <p class="_pmvv-vidbox-descTxt" id="overlay-descrip"> </p> <div class="rating-row" data-video-id=""> <input name="is_logged_in" type="hidden" value="0"/> <p>How well does it match the trope?</p> <div id="star-rating-group"> <div class="trope-rate"> <input id="lamp5" name="rate" type="radio" value="5"/> <label for="lamp5" title="Absolutely"></label> <input id="lamp4" name="rate" type="radio" value="4"/> <label for="lamp4" title="Yes"></label> <input id="lamp3" name="rate" type="radio" value="3"/> <label for="lamp3" title="Kind of"></label> <input id="lamp2" name="rate" type="radio" value="2"/> <label for="lamp2" title="Not really"></label> <input id="lamp1" name="rate" type="radio" value="1"/> <label for="lamp1" title="No"></label> </div> <div id="star-rating-total"> </div> </div> </div> <div class="example-media-row"> <div class="example-overlay"> <p>Example of:</p> <div id="overlay-trope"> / </div> </div> <div class="media-sources-overlay example-overlay"> <p>Media sources:</p> <div id="overlay-media"> / </div> </div> </div> <p class="_pmvv-vidbox-stats text-right font-s" style="padding-top:8px; border-top: solid 1px rgba(255,255,255,0.2)"> <a class="float-right" data-modal-target="login" href="#video-feedback">Report</a> </p> </div> </div> </div> </div> <script type="text/javascript"> window.special_ops = { member : 'no', isolated : 1, tags : ['unknown'] }; </script> <script type="text/javascript"> var cleanCreativeEnabled = ""; var donation = ""; var live_ads = "1"; var img_domain = "https://static.tvtropes.org"; var snoozed = cookies.read('snoozedabm'); var snoozable = ""; if (adsRemovedWith) { live_ads = 0; } var elem = document.createElement('script'); elem.async = true; elem.src = '/design/assets/bundle.js?rev=c58d8df02f09262390bbd03db7921fc35c6af306'; elem.onload = function() { } document.getElementsByTagName('head')[0].appendChild(elem); </script> <script type="text/javascript"> function send_analytics_event(user_type, donation){ // if(user_type == 'uncached' || user_type == 'cached'){ // ga('send', 'event', 'caching', 'load', user_type, {'nonInteraction': 1}); // return; // } var event_name = user_type; if(donation == 'true'){ event_name += "_donation" }else if(typeof(valid_user) == 'undefined'){ event_name += "_blocked" }else if(valid_user == true){ event_name += "_unblocked"; }else{ event_name = "_unknown" } ga('send', 'event', 'ads', 'load', event_name, {'nonInteraction': 1}); } send_analytics_event("guest", "false"); </script> </body> </html>
107.886154
2,965
0.723365
3970dfba72a3e05b7d4d35b1e535ddd731ae09fb
91
tab
SQL
examples/test_cheap_fuel_blend/inputs/fuels.tab
Janie115/gridpath
83b4bb497fc06ef20a67ab773a2c59e57cde895f
[ "Apache-2.0" ]
null
null
null
examples/test_cheap_fuel_blend/inputs/fuels.tab
Janie115/gridpath
83b4bb497fc06ef20a67ab773a2c59e57cde895f
[ "Apache-2.0" ]
null
null
null
examples/test_cheap_fuel_blend/inputs/fuels.tab
Janie115/gridpath
83b4bb497fc06ef20a67ab773a2c59e57cde895f
[ "Apache-2.0" ]
1
2021-12-21T20:44:21.000Z
2021-12-21T20:44:21.000Z
FUELS co2_intensity_tons_per_mmbtu Coal 0.09552 Cheap_Fuel 0.05306 Gas 0.05306 Uranium 0.0
15.166667
34
0.846154
61c7eca515901d84c0e426002f62792683779b74
41
dart
Dart
lib/src/services/version1/service.dart
pip-services-users/pip-services-activities-dart
7cd0e26bb540d16eaff0efe8446ea307fb7fe04a
[ "MIT" ]
null
null
null
lib/src/services/version1/service.dart
pip-services-users/pip-services-activities-dart
7cd0e26bb540d16eaff0efe8446ea307fb7fe04a
[ "MIT" ]
null
null
null
lib/src/services/version1/service.dart
pip-services-users/pip-services-activities-dart
7cd0e26bb540d16eaff0efe8446ea307fb7fe04a
[ "MIT" ]
1
2021-11-11T18:36:51.000Z
2021-11-11T18:36:51.000Z
export './ActivitiesHttpServiceV1.dart';
20.5
40
0.804878
1c8372d2dfbf963f5cc28e588044c05694290d46
177
css
CSS
src/templates/mystyle.css
timtinlong/McHacks2021
596724850161558771c753381737d898533e8705
[ "MIT" ]
null
null
null
src/templates/mystyle.css
timtinlong/McHacks2021
596724850161558771c753381737d898533e8705
[ "MIT" ]
null
null
null
src/templates/mystyle.css
timtinlong/McHacks2021
596724850161558771c753381737d898533e8705
[ "MIT" ]
null
null
null
<style> .content { max-width: 500px; margin: auto; } </style> form { background-color: lightblue; } h1 { color: navy; margin-left: 20px; } h2 { font-size: 16px; }
9.315789
30
0.60452
ec2c4efac924ea3db2ff90586c3abb3615448ffa
1,961
dart
Dart
lib/src/palette.dart
albemala/colourlovers-api-dart
f391c370c15297683c754a90950d284f4e739931
[ "MIT" ]
1
2022-01-06T15:51:09.000Z
2022-01-06T15:51:09.000Z
lib/src/palette.dart
albemala/colourlovers-api-dart
f391c370c15297683c754a90950d284f4e739931
[ "MIT" ]
null
null
null
lib/src/palette.dart
albemala/colourlovers-api-dart
f391c370c15297683c754a90950d284f4e739931
[ "MIT" ]
null
null
null
import 'package:json_annotation/json_annotation.dart'; part 'palette.g.dart'; @JsonSerializable() class ClPalette { /// Unique id for this Palette int? id; /// Title / Name of the Palette String? title; /// Username of the Palette's creator String? userName; /// Number of views this Palette has received int? numViews; /// Number of votes this Palette has received int? numVotes; /// Number of comments this Palette has received int? numComments; /// Number of hearts this Palette has double? numHearts; /// This Palette's rank on COLOURlovers.com int? rank; /// Date this Palette was created DateTime? dateCreated; /// List of Colors within this Palette List<String>? colors; /// This Palette's Color's widths. Ranges from 0.0 to 1.0 List<double>? colorWidths; /// This Palette's description String? description; /// This Palette's COLOURlovers.com URL String? url; /// Link to a png version of this Palette String? imageUrl; /// Link to a COLOURlovers.com badge for this Palette String? badgeUrl; /// This Palette's COLOURlovers.com API URL String? apiUrl; ClPalette({ this.id, this.title, this.userName, this.numViews, this.numVotes, this.numComments, this.numHearts, this.rank, this.dateCreated, this.colors, this.colorWidths, this.description, this.url, this.imageUrl, this.badgeUrl, this.apiUrl, }); factory ClPalette.fromJson(Map<String, dynamic> json) => _$ClPaletteFromJson(json); Map<String, dynamic> toJson() => _$ClPaletteToJson(this); @override String toString() { return 'ClPalette{id: $id, title: $title, userName: $userName, numViews: $numViews, numVotes: $numVotes, numComments: $numComments, numHearts: $numHearts, rank: $rank, dateCreated: $dateCreated, colors: $colors, description: $description, url: $url, imageUrl: $imageUrl, badgeUrl: $badgeUrl, apiUrl: $apiUrl}'; } }
23.626506
314
0.686894
05d55824315aebf6ea2526b2e436a53c70e1745c
1,722
html
HTML
build/MySQL/attackQueries/informationGathering.html
hrskrs/SQLInjectionWiki
a60f8cd207c3c14ed60ef4016c4b20da9e128122
[ "BSD-3-Clause" ]
1
2021-06-08T18:27:40.000Z
2021-06-08T18:27:40.000Z
build/MySQL/attackQueries/informationGathering.html
hrskrs/SQLInjectionWiki
a60f8cd207c3c14ed60ef4016c4b20da9e128122
[ "BSD-3-Clause" ]
null
null
null
build/MySQL/attackQueries/informationGathering.html
hrskrs/SQLInjectionWiki
a60f8cd207c3c14ed60ef4016c4b20da9e128122
[ "BSD-3-Clause" ]
1
2021-11-14T16:00:16.000Z
2021-11-14T16:00:16.000Z
<h3 id="information-gathering">Information Gathering</h3> <p id="informationGathering" class="injectionDescription"></p> <p>* Requires privileged user</p> <table class="table table-striped table-hover"> <thead> <tr> <th>Description</th> <th align="left">Query</th> </tr> </thead> <tbody> <tr> <td>Version</td> <td>SELECT @@version</td> </tr> <tr> <td>Users</td> <td>SELECT user FROM mysql.user<br>SELECT user();<br>SELECT system_user()<br>* SELECT Super_priv FROM mysql.user WHERE user= 'root' LIMIT 1,1</td> </tr> <tr> <td>Current Database</td> <td>SELECT database()</td> </tr> <tr> <td>Databases</td> <td>SELECT schema_name FROM information_schema.schemata<br></td> </tr> <tr> <td>Tables</td> <td>SELECT table_schema,table_name FROM information_schema.tables</td> </tr> <tr> <td>Columns</td> <td>SELECT table_schema, table_name, column_name FROM information_schema.columns</td> </tr> <tr> <td>Number of Columns</td> <td>SELECT * FROM USERS ORDER BY 1<br><br><em>Increase 1 until query returns false, previous number was the amount of columns</em></td> </tr> <tr> <td>DBA Accounts</td> <td>SELECT host, user FROM mysql.user WHERE Super_priv = 'Y'</td> </tr> <tr> <td>Password Hashes</td> <td>SELECT host, user, password FROM mysql.user</td> </tr> <tr> <td>Schema</td> <td>SELECT schema()</td> </tr> <tr> <td>Path to Data</td> <td>SELECT @@datadir</td> </tr> <tr> <td>Read Files</td> <td>* SELECT LOAD_FILE('/etc/passwd')</td> </tr> </tbody> </table>
26.492308
152
0.583624
80b5cec7786c8dc6686f99b9d064959cf7431ea8
889
java
Java
public/java/src/uk/ac/ox/well/cortexjdk/commands/simulate/generators/SnvGenerator.java
mcveanlab/CortexJDK
eee7e4e6ea60e5309e33502c1337bfb6685f54f8
[ "Apache-2.0" ]
5
2017-08-18T18:29:09.000Z
2020-01-30T22:10:07.000Z
public/java/src/uk/ac/ox/well/cortexjdk/commands/simulate/generators/SnvGenerator.java
mcveanlab/CortexJDK
eee7e4e6ea60e5309e33502c1337bfb6685f54f8
[ "Apache-2.0" ]
5
2017-08-19T02:11:06.000Z
2019-05-27T07:50:04.000Z
public/java/src/uk/ac/ox/well/cortexjdk/commands/simulate/generators/SnvGenerator.java
mcveanlab/CortexJDK
eee7e4e6ea60e5309e33502c1337bfb6685f54f8
[ "Apache-2.0" ]
5
2017-09-14T02:42:59.000Z
2019-04-19T19:15:11.000Z
package uk.ac.ox.well.cortexjdk.commands.simulate.generators; import java.util.Random; public class SnvGenerator implements VariantGenerator { private int seqIndex; public SnvGenerator(int seqIndex) { this.seqIndex = seqIndex; } @Override public String getType() { return "SNV"; } @Override public int getSeqIndex() { return seqIndex; } @Override public GeneratedVariant permute(String seq, int posIndex, Random rng, int length) { final char[] bases = { 'A', 'C', 'G', 'T' }; char base; do { base = bases[rng.nextInt(bases.length)]; } while (base == Character.toUpperCase(seq.charAt(posIndex)) || base == Character.toLowerCase(seq.charAt(posIndex))); return new GeneratedVariant(getType(), getSeqIndex(), posIndex, seq.substring(posIndex, posIndex + 1), String.valueOf(base)); } }
29.633333
133
0.655793
148b872c8db1aa2b8f34b2da6f3596ca9cad75a3
655
sql
SQL
openGaussBase/testcase/KEYWORDS/specific/Opengauss_Function_Keyword_Specific_Case0029.sql
opengauss-mirror/Yat
aef107a8304b94e5d99b4f1f36eb46755eb8919e
[ "MulanPSL-1.0" ]
null
null
null
openGaussBase/testcase/KEYWORDS/specific/Opengauss_Function_Keyword_Specific_Case0029.sql
opengauss-mirror/Yat
aef107a8304b94e5d99b4f1f36eb46755eb8919e
[ "MulanPSL-1.0" ]
null
null
null
openGaussBase/testcase/KEYWORDS/specific/Opengauss_Function_Keyword_Specific_Case0029.sql
opengauss-mirror/Yat
aef107a8304b94e5d99b4f1f36eb46755eb8919e
[ "MulanPSL-1.0" ]
null
null
null
-- @testpoint:opengauss关键字specific(非保留),作为表空间名 --关键字不带引号,创建成功 drop tablespace if exists specific; CREATE TABLESPACE specific RELATIVE LOCATION 'hdfs_tablespace/hdfs_tablespace_1'; drop tablespace specific; --关键字带双引号,创建成功 drop tablespace if exists "specific"; CREATE TABLESPACE "specific" RELATIVE LOCATION 'hdfs_tablespace/hdfs_tablespace_1'; drop tablespace "specific"; --关键字带单引号,合理报错 drop tablespace if exists 'specific'; CREATE TABLESPACE 'specific' RELATIVE LOCATION 'hdfs_tablespace/hdfs_tablespace_1'; --关键字带反引号,合理报错 drop tablespace if exists `specific`; CREATE TABLESPACE `specific` RELATIVE LOCATION 'hdfs_tablespace/hdfs_tablespace_1';
29.772727
84
0.815267
c14f60ad77844e7dc49af5e0aa1b0d0ce0452633
5,508
dart
Dart
lib/src/clients/DirectClient.dart
Dvoikin/pip-services3-rpc-dart
884877de059e219bfb62896344a4181f0d36c1fa
[ "MIT" ]
null
null
null
lib/src/clients/DirectClient.dart
Dvoikin/pip-services3-rpc-dart
884877de059e219bfb62896344a4181f0d36c1fa
[ "MIT" ]
null
null
null
lib/src/clients/DirectClient.dart
Dvoikin/pip-services3-rpc-dart
884877de059e219bfb62896344a4181f0d36c1fa
[ "MIT" ]
null
null
null
import 'dart:async'; import 'package:pip_services3_commons/pip_services3_commons.dart'; import 'package:pip_services3_components/pip_services3_components.dart'; /// Abstract client that calls controller directly in the same memory space. /// /// It is used when multiple microservices are deployed in a single container (monolyth) /// and communication between them can be done by direct calls rather then through /// the network. /// /// ### Configuration parameters ### /// /// - [dependencies]: /// - [controller]: override controller descriptor /// /// ### References ### /// /// - [\*:logger:\*:\*:1.0] (optional) [ILogger] components to pass log messages /// - [\*:counters:\*:\*:1.0] (optional) [ICounters] components to pass collected measurements /// - [\*:controller:\*:\*:1.0] controller to call business methods /// /// ### Example ### /// /// class MyDirectClient extends DirectClient<IMyController> implements IMyClient { /// /// public MyDirectClient(): super() { /// /// dependencyResolver.put('controller', Descriptor( /// "mygroup", "controller", "*", "*", "*")); /// } /// ... /// /// Future<MyData> getData(String correlationId, String id) async { /// var timing = instrument(correlationId, 'myclient.get_data'); /// try { /// var result = await controller.getData(correlationId, id) /// timing.endTiming(); /// return result; /// } catch (err){ /// timing.endTiming(); /// instrumentError(correlationId, 'myclient.get_data', err, reerror=true); /// }); /// } /// ... /// } /// /// var client = MyDirectClient(); /// client.setReferences(References.fromTuples([ /// Descriptor("mygroup","controller","default","default","1.0"), controller /// ])); /// /// var result = await client.getData("123", "1") /// ... abstract class DirectClient<T> implements IConfigurable, IReferenceable, IOpenable { /// The controller reference. T controller; /// The open flag. bool opened = true; /// The logger. var logger = CompositeLogger(); /// The performance counters var counters = CompositeCounters(); /// The dependency resolver to get controller reference. var dependencyResolver = DependencyResolver(); /// Creates a new instance of the client. DirectClient() { dependencyResolver.put('controller', 'none'); } /// Configures component by passing configuration parameters. /// /// - [config] configuration parameters to be set. @override void configure(ConfigParams config) { dependencyResolver.configure(config); } /// Sets references to dependent components. /// /// - [references] references to locate the component dependencies. @override void setReferences(IReferences references) { logger.setReferences(references); counters.setReferences(references); dependencyResolver.setReferences(references); controller = dependencyResolver.getOneRequired<T>('controller'); } /// Adds instrumentation to log calls and measure call time. /// It returns a Timing object that is used to end the time measurement. /// /// - [correlationId] (optional) transaction id to trace execution through call chain. /// - [name] a method name. /// Returns Timing object to end the time measurement. Timing instrument(String correlationId, String name) { logger.trace(correlationId, 'Calling %s method', [name]); counters.incrementOne(name + '.call_count'); return counters.beginTiming(name + '.call_time'); } /// Adds instrumentation to error handling. /// /// - [correlationId] (optional) transaction id to trace execution through call chain. /// - [name] a method name. /// - [err] an occured error /// - [result] (optional) an execution result /// - [reerror] flag for rethrow exception void instrumentError(String correlationId, String name, err, [bool reerror = false]) { if (err != null) { logger.error(correlationId, ApplicationException().wrap(err), 'Failed to call %s method', [name]); counters.incrementOne(name + '.call_errors'); if (reerror != null && reerror == true) { throw err; } } } /// Checks if the component is opened. /// /// Returns true if the component has been opened and false otherwise. @override bool isOpen() { return opened; } /// Opens the component. /// /// - [correlationId] (optional) transaction id to trace execution through call chain. /// Returns Future that receives error or null no errors occured. @override Future open(String correlationId) async { if (opened) { return null; } if (controller == null) { var err = ConnectionException( correlationId, 'NOcontroller', 'Controller reference is missing'); throw err; } opened = true; logger.info(correlationId, 'Opened direct client'); } /// Closes component and frees used resources. /// /// - [correlationId] (optional) transaction id to trace execution through call chain. /// Return Future that receives null no errors occured. /// Throw error @override Future close(String correlationId) async { if (opened) { logger.info(correlationId, 'Closed direct client'); } opened = false; } }
32.210526
100
0.631808