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
1284087eb62ef9fdb52a34fbd449dbcf9724ecc5
2,092
cs
C#
EasySecureModbus_Demo_Server/Program.cs
georgemakrakis/EasyModbusTCP.NET
11320c3d8a0608644e4c685394b6185f4b427b57
[ "Unlicense" ]
null
null
null
EasySecureModbus_Demo_Server/Program.cs
georgemakrakis/EasyModbusTCP.NET
11320c3d8a0608644e4c685394b6185f4b427b57
[ "Unlicense" ]
null
null
null
EasySecureModbus_Demo_Server/Program.cs
georgemakrakis/EasyModbusTCP.NET
11320c3d8a0608644e4c685394b6185f4b427b57
[ "Unlicense" ]
null
null
null
using EasyModbusSecure; using System; using System.Collections.Generic; namespace EasySecureModbus_Demo_Server { class Program { static void Main(string[] args) { Program application = new Program(); application.startServer(args[0]); // For now we pass only the password, later can be cert path as well } public void startServer(string certPass) { //convert that to use CLI argument List<ValueTuple<string, List<byte>>> roles = new List<ValueTuple<string, List<byte>>> { //ValueTuple.Create("Maintainer", (byte)0x01), ValueTuple.Create("Operator", new List<byte> { (byte)0x01, (byte)0x0F } ), ValueTuple.Create("Engineer", new List<byte> { (byte)0x01 }) }; ModbusSecureServerAuthZ modbusServer = new ModbusSecureServerAuthZ("..\\..\\certs2\\server.pfx", certPass, true, roles); //ModbusSecureServer modbusServer = new ModbusSecureServer("..\\..\\certs2\\server.pfx", certPass, true, roles); //ModbusSecureServer modbusServer = new ModbusSecureServer("..\\..\\certs\\server.pfx", certPass, false); modbusServer.FunctionCode1AuthZDisabled = false; modbusServer.LogFileFilename = "..\\..\\logs\\ServerLogs.txt"; modbusServer.Listen(); modbusServer.HoldingRegistersChanged += new ModbusSecureServer.HoldingRegistersChangedHandler(holdingRegistersChanged); modbusServer.CoilsChanged += new ModbusSecureServer.CoilsChangedHandler(coilsChanged); Console.ReadKey(); modbusServer.StopListening(); } public static void holdingRegistersChanged(int startingAddress, int quantity) { Console.WriteLine(startingAddress); Console.WriteLine(quantity); } public static void coilsChanged(int startingAddress, int quantity) { Console.WriteLine(startingAddress); Console.WriteLine(quantity); } } }
40.230769
132
0.627151
ddaac6800f2fecf127f32cbe6fc572bb713ed97b
3,806
java
Java
unused/mine/packages/org.cakelab.blender.fileviewer-src-0.0.10/src-dna/org/blender/dna/GaussianBlurVars.java
sirivus/studioonline
536cb4f3f8a8640821a47c0bdbef3877fe2e6f7a
[ "MIT" ]
null
null
null
unused/mine/packages/org.cakelab.blender.fileviewer-src-0.0.10/src-dna/org/blender/dna/GaussianBlurVars.java
sirivus/studioonline
536cb4f3f8a8640821a47c0bdbef3877fe2e6f7a
[ "MIT" ]
null
null
null
unused/mine/packages/org.cakelab.blender.fileviewer-src-0.0.10/src-dna/org/blender/dna/GaussianBlurVars.java
sirivus/studioonline
536cb4f3f8a8640821a47c0bdbef3877fe2e6f7a
[ "MIT" ]
null
null
null
package org.blender.dna; import java.io.IOException; import org.cakelab.blender.io.block.Block; import org.cakelab.blender.io.block.BlockTable; import org.cakelab.blender.nio.CFacade; import org.cakelab.blender.nio.CMetaData; import org.cakelab.blender.nio.CPointer; /** * Generated facet for DNA struct type 'GaussianBlurVars'. * * <h3>Class Documentation</h3> * */ @CMetaData(size32=8, size64=8) public class GaussianBlurVars extends CFacade { /** * This is the sdna index of the struct GaussianBlurVars. * <p> * It is required when allocating a new block to store data for GaussianBlurVars. * </p> * @see {@link org.cakelab.blender.io.dna.internal.StructDNA} * @see {@link org.cakelab.blender.io.block.BlockTable#allocate} */ public static final int __DNA__SDNA_INDEX = 326; /** * Field descriptor (offset) for struct member 'size_x'. * <h3>Pointer Arithmetics</h3> * <p> * This is how you get a reference on the corresponding field in the struct: * </p> * <pre> * GaussianBlurVars gaussianblurvars = ...; * CPointer&lt;Object&gt; p = gaussianblurvars.__dna__addressof(GaussianBlurVars.__DNA__FIELD__size_x); * CPointer&lt;Float&gt; p_size_x = p.cast(new Class[]{Float.class}); * </pre> * <h3>Metadata</h3> * <ul> * <li>Field: 'size_x'</li> * <li>Signature: 'float'</li> * <li>Actual Size (32bit/64bit): 4/4</li> * </ul> */ public static final long[] __DNA__FIELD__size_x = new long[]{0, 0}; /** * Field descriptor (offset) for struct member 'size_y'. * <h3>Pointer Arithmetics</h3> * <p> * This is how you get a reference on the corresponding field in the struct: * </p> * <pre> * GaussianBlurVars gaussianblurvars = ...; * CPointer&lt;Object&gt; p = gaussianblurvars.__dna__addressof(GaussianBlurVars.__DNA__FIELD__size_y); * CPointer&lt;Float&gt; p_size_y = p.cast(new Class[]{Float.class}); * </pre> * <h3>Metadata</h3> * <ul> * <li>Field: 'size_y'</li> * <li>Signature: 'float'</li> * <li>Actual Size (32bit/64bit): 4/4</li> * </ul> */ public static final long[] __DNA__FIELD__size_y = new long[]{4, 4}; public GaussianBlurVars(long __address, Block __block, BlockTable __blockTable) { super(__address, __block, __blockTable); } protected GaussianBlurVars(GaussianBlurVars that) { super(that.__io__address, that.__io__block, that.__io__blockTable); } /** * Get method for struct member 'size_x'. * @see #__DNA__FIELD__size_x */ public float getSize_x() throws IOException { if ((__io__pointersize == 8)) { return __io__block.readFloat(__io__address + 0); } else { return __io__block.readFloat(__io__address + 0); } } /** * Set method for struct member 'size_x'. * @see #__DNA__FIELD__size_x */ public void setSize_x(float size_x) throws IOException { if ((__io__pointersize == 8)) { __io__block.writeFloat(__io__address + 0, size_x); } else { __io__block.writeFloat(__io__address + 0, size_x); } } /** * Get method for struct member 'size_y'. * @see #__DNA__FIELD__size_y */ public float getSize_y() throws IOException { if ((__io__pointersize == 8)) { return __io__block.readFloat(__io__address + 4); } else { return __io__block.readFloat(__io__address + 4); } } /** * Set method for struct member 'size_y'. * @see #__DNA__FIELD__size_y */ public void setSize_y(float size_y) throws IOException { if ((__io__pointersize == 8)) { __io__block.writeFloat(__io__address + 4, size_y); } else { __io__block.writeFloat(__io__address + 4, size_y); } } /** * Instantiates a pointer on this instance. */ public CPointer<GaussianBlurVars> __io__addressof() { return new CPointer<GaussianBlurVars>(__io__address, new Class[]{GaussianBlurVars.class}, __io__block, __io__blockTable); } }
26.615385
123
0.691014
38e2ac21e8cad803442afec66935cdec4bb75f8a
2,121
php
PHP
protected/modules/mobileapp/controllers/IndexController.php
sumandinda007/Test_FoodokuWeb
9225bbc0fefad83b025e6d4f58eb6983e8ce6c6f
[ "Apache-2.0" ]
null
null
null
protected/modules/mobileapp/controllers/IndexController.php
sumandinda007/Test_FoodokuWeb
9225bbc0fefad83b025e6d4f58eb6983e8ce6c6f
[ "Apache-2.0" ]
null
null
null
protected/modules/mobileapp/controllers/IndexController.php
sumandinda007/Test_FoodokuWeb
9225bbc0fefad83b025e6d4f58eb6983e8ce6c6f
[ "Apache-2.0" ]
null
null
null
<?php if (!isset($_SESSION)) { session_start(); } class IndexController extends CController { public $layout='layout'; public function beforeAction(CAction $action) { if (Yii::app()->controller->module->require_login){ if(!Yii::app()->functions->isAdminLogin()){ $this->redirect(Yii::app()->createUrl('/admin/noaccess')); Yii::app()->end(); } } return true; } public function actionIndex(){ $this->redirect(Yii::app()->createUrl('/mobileapp/index/settings')); } public function actionSettings() { $country_list=require_once('CountryCode.php'); $mobile_country_list=getOptionA('mobile_country_list'); if (!empty($mobile_country_list)){ $mobile_country_list=json_decode($mobile_country_list); } else $mobile_country_list=array(); $default_image=AddonMobileApp::getImage(getOptionA('mobile_default_image_not_available')); $this->render('settings',array( 'country_list'=>$country_list, 'default_image_url'=>$default_image, 'mobile_country_list'=>$mobile_country_list )); } public function actionPushLogs() { $this->render('pushlogs',array( )); } public function actionregistereddevice() { $this->render('registered_device',array( )); } public function actionPushHelp() { $this->render('pushhelp',array( )); } public function actionPush() { if ( $res=AddonMobileApp::getDeviceByID($_GET['id'])){ $this->render('push_form',array( 'data'=>$res )); } else $this->render('error',array( 'msg'=>t("cannot find records") )); } public function actionBroadcast() { $this->render('broadcast-list',array( )); } public function actionBroadcastNew() { $this->render('broadcast-new',array( )); } public function actionbroadcastdetails() { if ( AddonMobileApp::getBroadcast($_GET['id'])){ $this->render('broadcast-details',array( )); } else $this->render('error',array( 'msg'=>t("cannot find records") )); } public function actiontranslation() { $this->render('translation',array( )); } } /*end class*/
21.642857
92
0.646393
24bdd88663072e13c09ca7f0ff82bf3c5626499b
3,302
php
PHP
modules/homefeatured/translations/nl.php
denisu08/site03-app
9cdedc4bc124bed77d9fbf1873c1575695d8c892
[ "MIT" ]
null
null
null
modules/homefeatured/translations/nl.php
denisu08/site03-app
9cdedc4bc124bed77d9fbf1873c1575695d8c892
[ "MIT" ]
null
null
null
modules/homefeatured/translations/nl.php
denisu08/site03-app
9cdedc4bc124bed77d9fbf1873c1575695d8c892
[ "MIT" ]
null
null
null
<?php global $_MODULE; $_MODULE = array(); $_MODULE['<{homefeatured}prestashop>homefeatured_5d17bf499a1b9b2e816c99eebf0153a9'] = 'Aanbevolen producten op de homepage'; $_MODULE['<{homefeatured}prestashop>homefeatured_6d37ec35b5b6820f90394e5ee49e8cec'] = 'Toont aanbevolen producten in de centrale kolom van uw homepagina.'; $_MODULE['<{homefeatured}prestashop>homefeatured_fddb8a1881e39ad11bfe0d0aca5becc3'] = 'Het aantal producten is niet geldig. U moet een positief nummer ingeven.'; $_MODULE['<{homefeatured}prestashop>homefeatured_c284a59996a4e984b30319999a7feb1d'] = 'De categorie ID is niet geldig. Selecteer een bestaande categorie ID.'; $_MODULE['<{homefeatured}prestashop>homefeatured_fd2608d329d90e9a49731393427d0a5a'] = 'Ongeldige waarde voor de "randomize" vlag.'; $_MODULE['<{homefeatured}prestashop>homefeatured_6af91e35dff67a43ace060d1d57d5d1a'] = 'Instellingen bijgewerkt'; $_MODULE['<{homefeatured}prestashop>homefeatured_f4f70727dc34561dfde1a3c529b6205c'] = 'Instellingen'; $_MODULE['<{homefeatured}prestashop>homefeatured_abc877135a96e04fc076becb9ce6fdfa'] = 'Om producten toe te voegen op uw homepagina moet u deze toevoegen in de overeenkomstige categorie (standaard: "Home").'; $_MODULE['<{homefeatured}prestashop>homefeatured_d44168e17d91bac89aab3f38d8a4da8e'] = 'Aantal producten om getoond te worden'; $_MODULE['<{homefeatured}prestashop>homefeatured_1b73f6b70a0fcd38bbc6a6e4b67e3010'] = 'Geef het aantal producten dat U wilt tonen op uw homepage (standaard: 8).'; $_MODULE['<{homefeatured}prestashop>homefeatured_b773a38d8c456f7b24506c0e3cd67889'] = 'Categorie van waaruit de producten gekozen moeten worden om te worden weergegeven'; $_MODULE['<{homefeatured}prestashop>homefeatured_0db2d53545e2ee088cfb3f45e618ba68'] = 'Kies de categorie ID van de producten die u wilt weergeven op de homepagina (standaard: 2 voor "Home").'; $_MODULE['<{homefeatured}prestashop>homefeatured_49417670345173e7b95018b7bf976fc7'] = 'Willekeurig aanbevolen producten tonen'; $_MODULE['<{homefeatured}prestashop>homefeatured_3c12c1068fb0e02fe65a6c4fc40bc29a'] = 'Inschakelen als u wilt dat de producten willekeurig worden weergegeven (Standaard: Nee).'; $_MODULE['<{homefeatured}prestashop>homefeatured_93cba07454f06a4a960172bbd6e2a435'] = 'Ja'; $_MODULE['<{homefeatured}prestashop>homefeatured_bafd7322c6e97d25b6299b5d6fe8920b'] = 'Nee'; $_MODULE['<{homefeatured}prestashop>homefeatured_c9cc8cce247e49bae79f15173ce97354'] = 'Opslaan'; $_MODULE['<{homefeatured}prestashop>homefeatured_ca7d973c26c57b69e0857e7a0332d545'] = 'Aanbevolen producten'; $_MODULE['<{homefeatured}prestashop>homefeatured_03c2e7e41ffc181a4e84080b4710e81e'] = 'Nieuw'; $_MODULE['<{homefeatured}prestashop>homefeatured_d3da97e2d9aee5c8fbe03156ad051c99'] = 'Meer'; $_MODULE['<{homefeatured}prestashop>homefeatured_4351cfebe4b61d8aa5efa1d020710005'] = 'Bekijken'; $_MODULE['<{homefeatured}prestashop>homefeatured_2d0f6b8300be19cf35e89e66f0677f95'] = 'In winkelwagen'; $_MODULE['<{homefeatured}prestashop>homefeatured_e0e572ae0d8489f8bf969e93d469e89c'] = 'Geen aanbevolen producten'; $_MODULE['<{homefeatured}prestashop>tab_2cc1943d4c0b46bfcf503a75c44f988b'] = 'Populair'; $_MODULE['<{homefeatured}prestashop>homefeatured_d505d41279039b9a68b0427af27705c6'] = 'Er zijn momenteel geen aanbevolen producten.'; return $_MODULE;
97.117647
207
0.825257
3894c182bcfaeb52bb3fe59354d80a6d911974b5
947
php
PHP
GroupBundle/DependencyInjection/Configuration.php
open-orchestra/open-orchestra-cms-bundle
f19cf5a617b24d5860308b47ec381bbe525f3da6
[ "Apache-2.0" ]
8
2015-04-02T08:04:46.000Z
2018-08-22T08:14:20.000Z
GroupBundle/DependencyInjection/Configuration.php
open-orchestra/open-orchestra-cms-bundle
f19cf5a617b24d5860308b47ec381bbe525f3da6
[ "Apache-2.0" ]
1,441
2015-04-02T13:23:40.000Z
2018-05-28T07:42:19.000Z
GroupBundle/DependencyInjection/Configuration.php
open-orchestra/open-orchestra-cms-bundle
f19cf5a617b24d5860308b47ec381bbe525f3da6
[ "Apache-2.0" ]
10
2015-04-11T21:49:48.000Z
2017-10-31T13:21:00.000Z
<?php namespace OpenOrchestra\GroupBundle\DependencyInjection; use Symfony\Component\Config\Definition\Builder\TreeBuilder; use Symfony\Component\Config\Definition\ConfigurationInterface; /** * Class Configuration */ class Configuration implements ConfigurationInterface { /** * {@inheritDoc} */ public function getConfigTreeBuilder() { $treeBuilder = new TreeBuilder(); $rootNode = $treeBuilder->root('open_orchestra_group'); $rootNode->children() ->arrayNode('facades') ->addDefaultsIfNotSet() ->children() ->scalarNode('group')->defaultValue('OpenOrchestra\GroupBundle\Facade\GroupFacade')->end() ->scalarNode('group_collection')->defaultValue('OpenOrchestra\GroupBundle\Facade\GroupCollectionFacade')->end() ->end() ->end() ->end(); return $treeBuilder; } }
27.852941
131
0.626188
9e1642b1759fc61769f01a14e2160a7607d9ab3d
284
cs
C#
Source/ConsoleGameEngine/Components/EntityIdentifier.cs
phoenix-iv/ConsoleGameEngine
b68eb1c3e85b9586720ee2319bc1998cb57b1723
[ "MIT" ]
null
null
null
Source/ConsoleGameEngine/Components/EntityIdentifier.cs
phoenix-iv/ConsoleGameEngine
b68eb1c3e85b9586720ee2319bc1998cb57b1723
[ "MIT" ]
3
2022-03-26T07:58:17.000Z
2022-03-29T12:23:52.000Z
Source/ConsoleGameEngine/Components/EntityIdentifier.cs
phoenix-iv/ConsoleGameEngine
b68eb1c3e85b9586720ee2319bc1998cb57b1723
[ "MIT" ]
null
null
null
namespace ConsoleGameEngine.Components { /// <summary> /// Contains data to uniquely identify an entity. /// </summary> public struct EntityIdentifier { /// <summary> /// The ID of the entity. /// </summary> public int Id; } }
20.285714
53
0.552817
0a96e499aa17d92d4b1d14e9e67bf7e180b00ba0
3,816
cs
C#
MobileClient/iForgotMyWallet/iForgotMyWallet.Android/Activities/BaseActivity.cs
bochackathon-fintech/iForgotMyWallet
7d60fffb16c78740c34aa88dd306a93f85872dc6
[ "Apache-2.0" ]
null
null
null
MobileClient/iForgotMyWallet/iForgotMyWallet.Android/Activities/BaseActivity.cs
bochackathon-fintech/iForgotMyWallet
7d60fffb16c78740c34aa88dd306a93f85872dc6
[ "Apache-2.0" ]
null
null
null
MobileClient/iForgotMyWallet/iForgotMyWallet.Android/Activities/BaseActivity.cs
bochackathon-fintech/iForgotMyWallet
7d60fffb16c78740c34aa88dd306a93f85872dc6
[ "Apache-2.0" ]
null
null
null
 using System; using System.Collections.Generic; using System.Linq; using System.Text; using Android.App; using Android.Content; using Android.OS; using Android.Runtime; using Android.Support.V7.App; using Android.Views; using Android.Widget; using Toolbar = Android.Support.V7.Widget.Toolbar; using Fragment = Android.Support.V4.App.Fragment; using FragmentTransaction = Android.Support.V4.App.FragmentTransaction; using ThemedDialog = Android.Support.V7.App.AlertDialog; using iForgotMyWallet.Core; using AndroidHUD; namespace iForgotMyWallet.Android { [Activity] public abstract class BaseActivity <TViewModel> : AppCompatActivity where TViewModel : BaseViewModel, new() { protected TViewModel ViewModel { get; private set; } public Context _Context; public Toolbar toolbar; #region Life Cycle protected override void OnCreate (Bundle savedInstanceState) { base.OnCreate (savedInstanceState); ViewModel = new TViewModel (); _Context = this; } protected override void OnResume () { base.OnResume (); RegisterEvents (); } protected override void OnPause () { UnregisterEvents (); base.OnPause (); } protected override void OnDestroy () { base.OnDestroy (); UnregisterEvents (); } public virtual void InitInterfaceViews (int Layout) { SetContentView (Layout); toolbar = FindViewById<Toolbar> (Resource.Id.Toolbar); SetSupportActionBar (toolbar); toolbar.Title = "iForgotMyWallet"; } public virtual void RegisterEvents () { ViewModel.IsBusyChanged += ViewModel_IsBusyChanged; } public virtual void UnregisterEvents () { ViewModel.IsBusyChanged -= ViewModel_IsBusyChanged; } #endregion #region Fragment Managment public void InflateFragment<T> () where T : Fragment, new() { FragmentTransaction ft = SupportFragmentManager.BeginTransaction (); RemoveFragments (ft); Fragment fragment = new T (); SupportFragmentManager.BeginTransaction ().Add (Resource.Id.FragmentContainer, fragment).CommitNow (); } public void InflateFragment (Fragment fragment) { FragmentTransaction ft = SupportFragmentManager.BeginTransaction (); RemoveFragments (ft); SupportFragmentManager.BeginTransaction ().Add (Resource.Id.FragmentContainer, fragment).CommitNow (); } public void RemoveFragments (FragmentTransaction ft) { if (SupportFragmentManager.Fragments != null) foreach (Fragment item in SupportFragmentManager.Fragments) ft.Remove (item).CommitNow (); } public int FragmentsCount () { var tmp = SupportFragmentManager.Fragments; if (tmp != null && tmp.Any ()) return tmp.Count; return 0; } public Fragment GetActiveFragment () { return SupportFragmentManager.Fragments.Last (); } #endregion #region Loading HUD public void ShowHUD (string Caption) { RunOnUiThread (() => { try { AndHUD.Shared.Show (_Context, Caption, -1, MaskType.Clear); } catch (Exception e) { Console.WriteLine (e); } }); } public void HideHUD () { RunOnUiThread (() => { try { if (AndHUD.Shared.CurrentDialog != null) AndHUD.Shared.CurrentDialog.Hide (); } catch (Exception e) { Console.WriteLine (e); } }); } #endregion #region Event Handlers void ViewModel_IsBusyChanged (object sender, EventArgs e) { if (ViewModel.IsBusy) ShowHUD ("Loading, please wait..."); else HideHUD (); } #endregion #region Alerts public void ShowAlertOK (String Message) { ThemedDialog.Builder alert = new ThemedDialog.Builder (_Context); alert.SetTitle ("Menu Pick"); alert.SetMessage (Message); alert.SetPositiveButton ("OK", (senderAlert, args) => { }); Dialog dialog = alert.Create (); dialog.Show (); } #endregion } }
20.73913
108
0.698899
2bad95268b946e07989c4451d83aa183c71c801b
1,016
swift
Swift
Examples/HUISurface/HUISurface/HUI Parameter Wrapper.swift
orchetect/MIDIKitControlSurfaces
ed0ba9021223796bc4d27173994ca87d93b347d6
[ "MIT" ]
2
2022-01-04T09:46:30.000Z
2022-01-25T20:53:23.000Z
Examples/HUISurface/HUISurface/HUI Parameter Wrapper.swift
orchetect/MIDIKitControlSurfaces
ed0ba9021223796bc4d27173994ca87d93b347d6
[ "MIT" ]
4
2021-07-22T00:49:56.000Z
2021-07-22T01:06:38.000Z
Examples/HUISurface/HUISurface/HUI Parameter Wrapper.swift
orchetect/MIDIKitControlSurfaces
ed0ba9021223796bc4d27173994ca87d93b347d6
[ "MIT" ]
null
null
null
// // HUI Parameter Wrapper.swift // HUISurface // MIDIKitControlSurfaces • https://github.com/orchetect/MIDIKitControlSurfaces // import Foundation import SwiftUI import MIDIKitControlSurfaces extension MIDI.HUI.Parameter { /// Because SwiftUI is a literal garbage and wants to crash constantly for no reason. /// The workaround is to make a class wrapper for MIDI.HUI.Parameter instance storage in a SwiftUI View. That prevents SwiftUI from attempting to compare the stored enum instance when recalculating the view during runtime and resulting in inexplicable crashes. /// /// References: /// - [SwiftUI Crash in AG::LayoutDescriptor::compare](https://noahgilmore.com/blog/swiftui-equatable-crash/) /// - [Twitter Thread](https://twitter.com/orchetect/status/1416871188723224577) class Wrapper { let wrapped: MIDI.HUI.Parameter init(_ wrapped: MIDI.HUI.Parameter) { self.wrapped = wrapped } } }
33.866667
264
0.692913
ff46ca24080ab0810407048c3d1846f6a22a1d51
5,103
py
Python
modules/utils/python/monitor_phy_param.py
aravindraja93/mesh_com
ee2d2887cfb153e2a49644d4692c8e494cd51952
[ "BSD-3-Clause" ]
4
2021-03-17T12:12:02.000Z
2022-01-24T11:55:50.000Z
modules/utils/python/monitor_phy_param.py
aravindraja93/mesh_com
ee2d2887cfb153e2a49644d4692c8e494cd51952
[ "BSD-3-Clause" ]
53
2021-03-11T06:40:15.000Z
2022-03-25T13:44:57.000Z
modules/utils/python/monitor_phy_param.py
aravindraja93/mesh_com
ee2d2887cfb153e2a49644d4692c8e494cd51952
[ "BSD-3-Clause" ]
6
2021-03-10T13:24:32.000Z
2022-03-09T11:28:36.000Z
import argparse import getopt import sys import datetime import time import subprocess from time import sleep from threading import Thread from getmac import get_mac_address from netaddr import * import yaml import serial import re def is_csi_supported(): global csi_type global debug global serial_port global csi_max_records no_csi_record = 0 print(csi_type) if (csi_type == 'nexmon'): soc_version_cmd = "cat /proc/cpuinfo | grep 'Revision' | awk '{print $3}'" proc = subprocess.Popen(soc_version_cmd, stdout=subprocess.PIPE, shell=True) soc_version = proc.communicate()[0].decode('utf-8').strip() if debug: print("SOC VERSION:"+soc_version) if ((soc_version == 'a020d3') or (soc_version == 'b03114')): print("RPI nexmon CSI is supported, SOC VERSION:"+soc_version) return 1 else: return 0 elif (csi_type == 'esp'): filepath = "/var/log/" filename = "esp_csi_data-%m_%d_%Y_%H_%M_%S.txt" ser=serial.Serial('/dev/' + serial_port, 115200, timeout=1) ser.flush() while True: try: data = ser.readline().decode('utf-8') if re.search('CSI', data): with open(filepath+filename, "a") as f: f.write(data) no_csi_record += 1 if (no_csi_record == csi_max_record): ser.close() break except: break return 0 else: return 0; def capture_raw_csi(): global interface global mac_addr_filter global channel global bandwidth global debug #Get CSI extractor filter csi_filter_cmd = "makecsiparams -c " + str(channel) + '\/' + str(bandwidth) + " -C 1 -N 1 -m " + mac_addr_filter + " -b 0x88" if debug: print(csi_filter_cmd) proc = subprocess.Popen(csi_filter_cmd, stdout=subprocess.PIPE, shell=True) filter_conf_resp = proc.communicate()[0].decode('utf-8').strip() if debug: print(filter_conf_resp) #Configure CSI extractor csi_ext_cmd = "nexutil -I" + interface + " -s500 -b -l34 -v"+filter_conf_resp proc = subprocess.Popen(csi_ext_cmd, stdout=subprocess.PIPE, shell=True) if debug: print(csi_ext_cmd) en_monitor_mode_cmd = "iw phy `iw dev " + interface + " info | gawk '/wiphy/ {printf \"phy\" $2}'` interface add mon0 type monitor && ifconfig mon0 up" proc = subprocess.Popen(en_monitor_mode_cmd, stdout=subprocess.PIPE, shell=True) if debug: print(en_monitor_mode_cmd) #Make sure injector is generating unicast traffic to mac_addr_filter #destination, Start tcpdump to capture the CSI dump_cmd = "tcpdump -G 60 -i " + interface + " dst port 5500 -w csi-%m_%d_%Y_%H_%M_%S.pcap" proc = subprocess.Popen(dump_cmd, stdout=subprocess.PIPE, shell=True) def get_mac_oui(): mac = EUI(get_mac_address(interface)) oui = mac.oui print(oui.registration().address) return oui def get_rssi(): global interface cmd = "iw dev " + interface + " station dump | grep 'signal:' | awk '{print $2}'" proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, shell=True) rssi = proc.communicate()[0].decode('utf-8') return rssi def log_rssi(): global rssi_mon_interval global debug fn_suffix=str(datetime.datetime.now().strftime('%m_%d_%Y_%H_%M_%S')) log_file_path = '/var/log/' log_file_name = 'rssi'+fn_suffix+'.txt' while True: f = open(log_file_path+log_file_name, 'a') rssi_sta = get_rssi() if debug: print(rssi_sta) f.write(str(time.time())+' '+rssi_sta) f.close() sleep(rssi_mon_interval) if __name__=='__main__': # Construct the argument parser phy_cfg = argparse.ArgumentParser() # Add the arguments to the parser phy_cfg.add_argument("-r", "--rssi_period", required=True, help="RSSI monitoring period Ex: 5 (equals to 5 sec)") phy_cfg.add_argument("-i", "--interface", required=True) args = phy_cfg.parse_args() # Get the physical parameter monitoring configuration print('> Loading yaml conf... ') conf = yaml.safe_load(open("phy_param.conf", 'r')) debug = conf['debug'] rssi_mon_interval = conf['rssi_poll_interval'] csi_type = conf['csi_format'] interface = conf['interface'] capture_rssi = conf['rssi'] capture_csi = conf['csi'] mac_addr_filter = conf['mac_addr_filter'] channel = conf['channel'] bandwidth = conf['bandwidth'] serial_port = conf['serial_port'] csi_max_records = conf['csi_max_records'] #populate args rssi_mon_interval = int(args.rssi_period) interface = args.interface # Capture CSI with type defined in config file if capture_csi: val = is_csi_supported() if (val == 1): Thread(target=capture_raw_csi).start() # Capture RSSI if enabled in config file if capture_rssi: Thread(target=log_rssi).start()
32.503185
155
0.629238
e2ce54f32272884d0e530dc16ff5f54bf6fe663b
117
py
Python
dotloop/account.py
spentaur/dotloop-python
5374ab5f5e16f9b826438a9c4f051a4be53d433b
[ "MIT" ]
null
null
null
dotloop/account.py
spentaur/dotloop-python
5374ab5f5e16f9b826438a9c4f051a4be53d433b
[ "MIT" ]
null
null
null
dotloop/account.py
spentaur/dotloop-python
5374ab5f5e16f9b826438a9c4f051a4be53d433b
[ "MIT" ]
1
2021-07-28T14:28:17.000Z
2021-07-28T14:28:17.000Z
from .bases import DotloopObject class Account(DotloopObject): def get(self): return self.fetch('get')
16.714286
32
0.692308
8d92fe7db2b5ed7c9875792766c34b518f886964
1,154
js
JavaScript
project1web/js/navbar.js
Uirfan/project1
8081e57cc97ec57a5d84f95def12039ec2101c6a
[ "Unlicense" ]
null
null
null
project1web/js/navbar.js
Uirfan/project1
8081e57cc97ec57a5d84f95def12039ec2101c6a
[ "Unlicense" ]
null
null
null
project1web/js/navbar.js
Uirfan/project1
8081e57cc97ec57a5d84f95def12039ec2101c6a
[ "Unlicense" ]
null
null
null
function includeNavbar() { let aab; if(localStorage.getItem("userId")){ aab='<li" class="nav-item"><a onclick="signout()" id="signOut" class="nav-link active" role="button" aria-current="page">Sign Out</a></li>'}; document.body.innerHTML += `<nav class="navbar navbar-expand-lg navbar-dark bg-dark "> <div class="container-fluid "> <a class="navbar-brand" href="#"> <img src="img/logo.png" width="27" height="35" alt="" loading="lazy" /> Clan Business Mullet</a> <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation" > <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse " id="navbarSupportedContent"> <ul class="navbar-nav me-auto mb-2 mb-lg-0 "> <li class="nav-item"> <a class="nav-link active" aria-current="page" href="#">Home</a> </li> `+ aab + ` </ul> </div> </div> </nav>` }
32.971429
144
0.586655
18a42476f72ef9f89c1af1e6b166e2a933639752
2,309
ts
TypeScript
packages/router/__tests__/Link.ts
corpusculejs/corpuscule
c5ae95f97386dd5e915ab9729f8a452ed22835eb
[ "MIT" ]
35
2018-12-18T09:10:42.000Z
2020-11-25T19:46:30.000Z
packages/router/__tests__/Link.ts
corpusculejs/corpuscule
c5ae95f97386dd5e915ab9729f8a452ed22835eb
[ "MIT" ]
54
2018-06-05T12:15:27.000Z
2020-09-06T21:53:52.000Z
packages/router/__tests__/Link.ts
corpusculejs/corpuscule
c5ae95f97386dd5e915ab9729f8a452ed22835eb
[ "MIT" ]
null
null
null
import {waitForMutationObserverChange} from '../../../test/utils'; import {Link} from '../src'; describe('@corpuscule/router', () => { describe('Link', () => { const waitForDocumentUpdate = () => waitForMutationObserverChange(document.body, {childList: true, subtree: true}); let historyPushStateSpy: jasmine.Spy; let historyStateSpy: jasmine.Spy; let link: Link; afterEach(() => { document.body.innerHTML = ''; // tslint:disable-line:no-inner-html }); afterAll(() => { historyStateSpy.and.callThrough(); historyPushStateSpy.and.callThrough(); }); beforeEach(() => { link = document.createElement('a', {is: Link.is}) as Link; link.href = '/test'; historyPushStateSpy = spyOn(history, 'pushState'); historyStateSpy = spyOnProperty(history, 'state').and.returnValue('/test'); }); it("accessible through 'document.createElement'", () => { expect(link).toEqual(jasmine.any(Link)); }); it('dispatches PopStateEvent with current history state by click', async done => { const promise = waitForDocumentUpdate(); document.body.appendChild(link); await promise; const listener = (e: PopStateEvent) => { expect(e.state).toEqual({data: undefined, path: '/test'}); window.removeEventListener('popstate', listener); done(); }; window.addEventListener('popstate', listener); link.click(); }); it('prevents default action for a anchor element', async done => { const promise = waitForDocumentUpdate(); document.body.appendChild(link); await promise; link.addEventListener('click', e => { expect(e.defaultPrevented).toBeTruthy(); done(); }); link.click(); }); it('allows changing the context for the link', async done => { const data = {}; const promise = waitForDocumentUpdate(); document.body.appendChild(link); await promise; const listener = (e: PopStateEvent) => { expect(e.state).toEqual({data, path: '/test'}); window.removeEventListener('popstate', listener); done(); }; window.addEventListener('popstate', listener); link.contextData = data; link.click(); }); }); });
26.848837
86
0.608489
63d5dc6bc63cbf330f1a3550d53f26ec9ed6a5d7
33
sh
Shell
client/compile_run.sh
dhiogoboza/galileo-adc-pwm-controller
997d8b0eb1479c7d7377a6e9a2ee15762eab105d
[ "MIT" ]
null
null
null
client/compile_run.sh
dhiogoboza/galileo-adc-pwm-controller
997d8b0eb1479c7d7377a6e9a2ee15762eab105d
[ "MIT" ]
null
null
null
client/compile_run.sh
dhiogoboza/galileo-adc-pwm-controller
997d8b0eb1479c7d7377a6e9a2ee15762eab105d
[ "MIT" ]
null
null
null
ant java -jar dist/ChartLine.jar
11
28
0.787879
4cf976d1544de7996e62a196f83f943511138b0c
583
py
Python
code/show_graph.py
Holdmedve/Breathalyzer
d5c531472c3bb2a92a67a8b5895fe551698c6364
[ "MIT" ]
null
null
null
code/show_graph.py
Holdmedve/Breathalyzer
d5c531472c3bb2a92a67a8b5895fe551698c6364
[ "MIT" ]
null
null
null
code/show_graph.py
Holdmedve/Breathalyzer
d5c531472c3bb2a92a67a8b5895fe551698c6364
[ "MIT" ]
1
2019-11-18T19:35:43.000Z
2019-11-18T19:35:43.000Z
import matplotlib import matplotlib.pyplot as plt from matplotlib import pyplot from matplotlib import dates import datetime myFile = open("dataBase.txt","r") s = myFile.readline() l = [x.split(',') for x in s.split('\t')] l.pop(-1) X = [] Y = [] for i in l: X.append(i[0]) Y.append(int(i[1])) X2 = list(map(datetime.datetime.strptime, X, len(X)*['%Y-%m-%d %H:%M:%S'])) formatter = dates.DateFormatter('%Y-%m-%d %H:%M:%S') pyplot.plot( X2, Y, '-' ) ax = pyplot.gcf().axes[0] ax.xaxis.set_major_formatter(formatter) pyplot.gcf().autofmt_xdate(rotation=25) pyplot.show()
21.592593
75
0.656947
b05286fcaaf825b5c5d5b6067ff8a0d8e078f22f
2,580
py
Python
src/robot/result/rerunmerger.py
ldtri0209/robotframework
6bc11a350cbaf5d0801cc5431f32cc1435bb65df
[ "ECL-2.0", "Apache-2.0" ]
4
2016-01-13T13:48:28.000Z
2021-09-05T07:14:07.000Z
src/robot/result/rerunmerger.py
ldtri0209/robotframework
6bc11a350cbaf5d0801cc5431f32cc1435bb65df
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
src/robot/result/rerunmerger.py
ldtri0209/robotframework
6bc11a350cbaf5d0801cc5431f32cc1435bb65df
[ "ECL-2.0", "Apache-2.0" ]
2
2018-01-18T22:00:17.000Z
2018-07-26T10:53:00.000Z
# Copyright 2008-2014 Nokia Solutions and Networks # # 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. from robot.model import SuiteVisitor class ReRunMerger(SuiteVisitor): def __init__(self, result): self.root = result.suite self.current = None def merge(self, merged): merged.suite.visit(self) def start_suite(self, suite): try: if not self.current: self.current = self._find_root(suite) else: self.current = self._find(self.current.suites, suite.name) except ValueError: self._report_ignored(suite) return False def _find_root(self, suite): if self.root.name != suite.name: raise ValueError return self.root def _find(self, items, name): for item in items: if item.name == name: return item raise ValueError def _report_ignored(self, item, test=False): from robot.output import LOGGER type = 'suite' if not test else 'test' LOGGER.error("Merged %s '%s' is ignored because it is not found from " "original result." % (type, item.longname)) def end_suite(self, suite): self.current = self.current.parent def visit_test(self, test): try: old = self._find(self.current.tests, test.name) except ValueError: self._report_ignored(test, test=True) else: test.message = self._create_merge_message(test, old) index = self.current.tests.index(old) self.current.tests[index] = test def _create_merge_message(self, new, old): return '\n'.join(['Test has been re-run and results replaced.', '- - -', 'New status: %s' % new.status, 'New message: %s' % new.message, '- - -', 'Old status: %s' % old.status, 'Old message: %s' % old.message])
34.4
78
0.587984
6aff9b65488736884c76d3d8a4276f03d614f552
11,966
c
C
kernel/lge/msm8226/arch/arm/mach-msm/board-msm7627a-storage.c
Uswer/LineageOS-14.1_jag3gds
6fe76987fad4fca7b3c08743b067d5e79892e77f
[ "Apache-2.0" ]
1
2020-06-01T10:53:47.000Z
2020-06-01T10:53:47.000Z
kernel/lge/msm8226/arch/arm/mach-msm/board-msm7627a-storage.c
Uswer/LineageOS-14.1_jag3gds
6fe76987fad4fca7b3c08743b067d5e79892e77f
[ "Apache-2.0" ]
1
2020-05-28T13:06:06.000Z
2020-05-28T13:13:15.000Z
kernel/lge/msm8226/arch/arm/mach-msm/board-msm7627a-storage.c
Uswer/LineageOS-14.1_jag3gds
6fe76987fad4fca7b3c08743b067d5e79892e77f
[ "Apache-2.0" ]
null
null
null
/* Copyright (c) 2011-2012, The Linux Foundation. All rights reserved. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 and * only version 2 as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * */ #include <linux/kernel.h> #include <linux/regulator/consumer.h> #include <linux/gpio.h> #include <asm/mach-types.h> #include <asm/mach/mmc.h> #include <mach/gpiomux.h> #include <mach/board.h> #include "devices.h" #include "pm.h" #include "board-msm7627a.h" #if (defined(CONFIG_MMC_MSM_SDC1_SUPPORT)\ || defined(CONFIG_MMC_MSM_SDC2_SUPPORT)\ || defined(CONFIG_MMC_MSM_SDC3_SUPPORT)\ || defined(CONFIG_MMC_MSM_SDC4_SUPPORT)) #define MAX_SDCC_CONTROLLER 4 static unsigned long vreg_sts, gpio_sts; struct sdcc_gpio { struct msm_gpio *cfg_data; uint32_t size; struct msm_gpio *sleep_cfg_data; }; /** * Due to insufficient drive strengths for SDC GPIO lines some old versioned * SD/MMC cards may cause data CRC errors. Hence, set optimal values * for SDC slots based on timing closure and marginality. SDC1 slot * require higher value since it should handle bad signal quality due * to size of T-flash adapters. */ static struct msm_gpio sdc1_cfg_data[] = { {GPIO_CFG(51, 1, GPIO_CFG_OUTPUT, GPIO_CFG_PULL_UP, GPIO_CFG_14MA), "sdc1_dat_3"}, {GPIO_CFG(52, 1, GPIO_CFG_OUTPUT, GPIO_CFG_PULL_UP, GPIO_CFG_14MA), "sdc1_dat_2"}, {GPIO_CFG(53, 1, GPIO_CFG_OUTPUT, GPIO_CFG_PULL_UP, GPIO_CFG_14MA), "sdc1_dat_1"}, {GPIO_CFG(54, 1, GPIO_CFG_OUTPUT, GPIO_CFG_PULL_UP, GPIO_CFG_14MA), "sdc1_dat_0"}, {GPIO_CFG(55, 1, GPIO_CFG_OUTPUT, GPIO_CFG_PULL_UP, GPIO_CFG_14MA), "sdc1_cmd"}, {GPIO_CFG(56, 1, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_14MA), "sdc1_clk"}, }; static struct msm_gpio sdc2_cfg_data[] = { {GPIO_CFG(62, 2, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_8MA), "sdc2_clk"}, {GPIO_CFG(63, 2, GPIO_CFG_OUTPUT, GPIO_CFG_PULL_UP, GPIO_CFG_10MA), "sdc2_cmd"}, {GPIO_CFG(64, 2, GPIO_CFG_OUTPUT, GPIO_CFG_PULL_UP, GPIO_CFG_10MA), "sdc2_dat_3"}, {GPIO_CFG(65, 2, GPIO_CFG_OUTPUT, GPIO_CFG_PULL_UP, GPIO_CFG_10MA), "sdc2_dat_2"}, {GPIO_CFG(66, 2, GPIO_CFG_OUTPUT, GPIO_CFG_PULL_UP, GPIO_CFG_10MA), "sdc2_dat_1"}, {GPIO_CFG(67, 2, GPIO_CFG_OUTPUT, GPIO_CFG_PULL_UP, GPIO_CFG_10MA), "sdc2_dat_0"}, }; static struct msm_gpio sdc2_sleep_cfg_data[] = { {GPIO_CFG(62, 0, GPIO_CFG_INPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA), "sdc2_clk"}, {GPIO_CFG(63, 0, GPIO_CFG_INPUT, GPIO_CFG_PULL_UP, GPIO_CFG_2MA), "sdc2_cmd"}, {GPIO_CFG(64, 0, GPIO_CFG_INPUT, GPIO_CFG_PULL_UP, GPIO_CFG_2MA), "sdc2_dat_3"}, {GPIO_CFG(65, 0, GPIO_CFG_INPUT, GPIO_CFG_PULL_UP, GPIO_CFG_2MA), "sdc2_dat_2"}, {GPIO_CFG(66, 0, GPIO_CFG_INPUT, GPIO_CFG_PULL_UP, GPIO_CFG_2MA), "sdc2_dat_1"}, {GPIO_CFG(67, 0, GPIO_CFG_INPUT, GPIO_CFG_PULL_UP, GPIO_CFG_2MA), "sdc2_dat_0"}, }; static struct msm_gpio sdc3_cfg_data[] = { {GPIO_CFG(88, 1, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_8MA), "sdc3_clk"}, {GPIO_CFG(89, 1, GPIO_CFG_OUTPUT, GPIO_CFG_PULL_UP, GPIO_CFG_10MA), "sdc3_cmd"}, {GPIO_CFG(90, 1, GPIO_CFG_OUTPUT, GPIO_CFG_PULL_UP, GPIO_CFG_10MA), "sdc3_dat_3"}, {GPIO_CFG(91, 1, GPIO_CFG_OUTPUT, GPIO_CFG_PULL_UP, GPIO_CFG_10MA), "sdc3_dat_2"}, {GPIO_CFG(92, 1, GPIO_CFG_OUTPUT, GPIO_CFG_PULL_UP, GPIO_CFG_10MA), "sdc3_dat_1"}, {GPIO_CFG(93, 1, GPIO_CFG_OUTPUT, GPIO_CFG_PULL_UP, GPIO_CFG_10MA), "sdc3_dat_0"}, #ifdef CONFIG_MMC_MSM_SDC3_8_BIT_SUPPORT {GPIO_CFG(19, 3, GPIO_CFG_OUTPUT, GPIO_CFG_PULL_UP, GPIO_CFG_10MA), "sdc3_dat_7"}, {GPIO_CFG(20, 3, GPIO_CFG_OUTPUT, GPIO_CFG_PULL_UP, GPIO_CFG_10MA), "sdc3_dat_6"}, {GPIO_CFG(21, 3, GPIO_CFG_OUTPUT, GPIO_CFG_PULL_UP, GPIO_CFG_10MA), "sdc3_dat_5"}, {GPIO_CFG(108, 3, GPIO_CFG_OUTPUT, GPIO_CFG_PULL_UP, GPIO_CFG_10MA), "sdc3_dat_4"}, #endif }; static struct msm_gpio sdc4_cfg_data[] = { {GPIO_CFG(19, 1, GPIO_CFG_OUTPUT, GPIO_CFG_PULL_UP, GPIO_CFG_10MA), "sdc4_dat_3"}, {GPIO_CFG(20, 1, GPIO_CFG_OUTPUT, GPIO_CFG_PULL_UP, GPIO_CFG_10MA), "sdc4_dat_2"}, {GPIO_CFG(21, 1, GPIO_CFG_OUTPUT, GPIO_CFG_PULL_UP, GPIO_CFG_10MA), "sdc4_dat_1"}, {GPIO_CFG(107, 1, GPIO_CFG_OUTPUT, GPIO_CFG_PULL_UP, GPIO_CFG_10MA), "sdc4_cmd"}, {GPIO_CFG(108, 1, GPIO_CFG_OUTPUT, GPIO_CFG_PULL_UP, GPIO_CFG_10MA), "sdc4_dat_0"}, {GPIO_CFG(109, 1, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_8MA), "sdc4_clk"}, }; static struct sdcc_gpio sdcc_cfg_data[] = { { .cfg_data = sdc1_cfg_data, .size = ARRAY_SIZE(sdc1_cfg_data), }, { .cfg_data = sdc2_cfg_data, .size = ARRAY_SIZE(sdc2_cfg_data), .sleep_cfg_data = sdc2_sleep_cfg_data, }, { .cfg_data = sdc3_cfg_data, .size = ARRAY_SIZE(sdc3_cfg_data), }, { .cfg_data = sdc4_cfg_data, .size = ARRAY_SIZE(sdc4_cfg_data), }, }; static int gpio_sdc1_hw_det = 85; static void gpio_sdc1_config(void) { if (machine_is_msm7627a_qrd1() || machine_is_msm7627a_evb() || machine_is_msm8625_evb() || machine_is_msm7627a_qrd3() || machine_is_msm8625_qrd7()) gpio_sdc1_hw_det = 42; } static struct regulator *sdcc_vreg_data[MAX_SDCC_CONTROLLER]; static int msm_sdcc_setup_gpio(int dev_id, unsigned int enable) { int rc = 0; struct sdcc_gpio *curr; curr = &sdcc_cfg_data[dev_id - 1]; if (!(test_bit(dev_id, &gpio_sts)^enable)) return rc; if (enable) { set_bit(dev_id, &gpio_sts); rc = msm_gpios_request_enable(curr->cfg_data, curr->size); if (rc) pr_err("%s: Failed to turn on GPIOs for slot %d\n", __func__, dev_id); } else { clear_bit(dev_id, &gpio_sts); if (curr->sleep_cfg_data) { rc = msm_gpios_enable(curr->sleep_cfg_data, curr->size); msm_gpios_free(curr->sleep_cfg_data, curr->size); return rc; } msm_gpios_disable_free(curr->cfg_data, curr->size); } return rc; } static int msm_sdcc_setup_vreg(int dev_id, unsigned int enable) { int rc = 0; struct regulator *curr = sdcc_vreg_data[dev_id - 1]; if (test_bit(dev_id, &vreg_sts) == enable) return 0; if (!curr) return -ENODEV; if (IS_ERR(curr)) return PTR_ERR(curr); if (enable) { set_bit(dev_id, &vreg_sts); rc = regulator_enable(curr); if (rc) pr_err("%s: could not enable regulator: %d\n", __func__, rc); } else { clear_bit(dev_id, &vreg_sts); rc = regulator_disable(curr); if (rc) pr_err("%s: could not disable regulator: %d\n", __func__, rc); } return rc; } static uint32_t msm_sdcc_setup_power(struct device *dv, unsigned int vdd) { int rc = 0; struct platform_device *pdev; pdev = container_of(dv, struct platform_device, dev); rc = msm_sdcc_setup_gpio(pdev->id, !!vdd); if (rc) goto out; rc = msm_sdcc_setup_vreg(pdev->id, !!vdd); out: return rc; } #ifdef CONFIG_MMC_MSM_SDC1_SUPPORT static unsigned int msm7627a_sdcc_slot_status(struct device *dev) { int status; status = gpio_tlmm_config(GPIO_CFG(gpio_sdc1_hw_det, 2, GPIO_CFG_INPUT, GPIO_CFG_PULL_UP, GPIO_CFG_8MA), GPIO_CFG_ENABLE); if (status) pr_err("%s:Failed to configure tlmm for GPIO %d\n", __func__, gpio_sdc1_hw_det); status = gpio_request(gpio_sdc1_hw_det, "SD_HW_Detect"); if (status) { pr_err("%s:Failed to request GPIO %d\n", __func__, gpio_sdc1_hw_det); } else { status = gpio_direction_input(gpio_sdc1_hw_det); if (!status) { if (machine_is_msm7627a_qrd1() || machine_is_msm7627a_evb() || machine_is_msm8625_evb() || machine_is_msm7627a_qrd3() || machine_is_msm8625_qrd7()) status = !gpio_get_value(gpio_sdc1_hw_det); else status = gpio_get_value(gpio_sdc1_hw_det); } gpio_free(gpio_sdc1_hw_det); } return status; } static struct mmc_platform_data sdc1_plat_data = { .ocr_mask = MMC_VDD_28_29, .translate_vdd = msm_sdcc_setup_power, .mmc_bus_width = MMC_CAP_4_BIT_DATA, .msmsdcc_fmin = 144000, .msmsdcc_fmid = 24576000, .msmsdcc_fmax = 49152000, .status = msm7627a_sdcc_slot_status, .irq_flags = IRQF_TRIGGER_RISING | IRQF_TRIGGER_FALLING, }; #endif #ifdef CONFIG_MMC_MSM_SDC2_SUPPORT static struct mmc_platform_data sdc2_plat_data = { /* * SDC2 supports only 1.8V, claim for 2.85V range is just * for allowing buggy cards who advertise 2.8V even though * they can operate at 1.8V supply. */ .ocr_mask = MMC_VDD_28_29 | MMC_VDD_165_195, .translate_vdd = msm_sdcc_setup_power, .mmc_bus_width = MMC_CAP_4_BIT_DATA, .sdiowakeup_irq = MSM_GPIO_TO_INT(66), .msmsdcc_fmin = 144000, .msmsdcc_fmid = 24576000, .msmsdcc_fmax = 49152000, #ifdef CONFIG_MMC_MSM_SDC2_DUMMY52_REQUIRED .dummy52_required = 1, #endif }; #endif #ifdef CONFIG_MMC_MSM_SDC3_SUPPORT static struct mmc_platform_data sdc3_plat_data = { .ocr_mask = MMC_VDD_28_29, .translate_vdd = msm_sdcc_setup_power, #ifdef CONFIG_MMC_MSM_SDC3_8_BIT_SUPPORT .mmc_bus_width = MMC_CAP_8_BIT_DATA, #else .mmc_bus_width = MMC_CAP_4_BIT_DATA, #endif .msmsdcc_fmin = 144000, .msmsdcc_fmid = 24576000, .msmsdcc_fmax = 49152000, .nonremovable = 1, }; #endif #if (defined(CONFIG_MMC_MSM_SDC4_SUPPORT)\ && !defined(CONFIG_MMC_MSM_SDC3_8_BIT_SUPPORT)) static struct mmc_platform_data sdc4_plat_data = { .ocr_mask = MMC_VDD_28_29, .translate_vdd = msm_sdcc_setup_power, .mmc_bus_width = MMC_CAP_4_BIT_DATA, .msmsdcc_fmin = 144000, .msmsdcc_fmid = 24576000, .msmsdcc_fmax = 49152000, }; #endif static int __init mmc_regulator_init(int sdcc_no, const char *supply, int uV) { int rc; BUG_ON(sdcc_no < 1 || sdcc_no > 4); sdcc_no--; sdcc_vreg_data[sdcc_no] = regulator_get(NULL, supply); if (IS_ERR(sdcc_vreg_data[sdcc_no])) { rc = PTR_ERR(sdcc_vreg_data[sdcc_no]); pr_err("%s: could not get regulator \"%s\": %d\n", __func__, supply, rc); goto out; } rc = regulator_set_voltage(sdcc_vreg_data[sdcc_no], uV, uV); if (rc) { pr_err("%s: could not set voltage for \"%s\" to %d uV: %d\n", __func__, supply, uV, rc); goto reg_free; } return rc; reg_free: regulator_put(sdcc_vreg_data[sdcc_no]); out: sdcc_vreg_data[sdcc_no] = NULL; return rc; } void __init msm7627a_init_mmc(void) { /* eMMC slot */ #ifdef CONFIG_MMC_MSM_SDC3_SUPPORT /* There is no eMMC on SDC3 for QRD3 based devices */ if (!(machine_is_msm7627a_qrd3() || machine_is_msm8625_qrd7())) { if (mmc_regulator_init(3, "emmc", 3000000)) return; /* * On 7x25A FFA data CRC errors are seen, which are * probably due to the proximity of SIM card and eMMC. * Hence, reducing the clock to 24.7Mhz from 49Mhz. */ if (machine_is_msm7625a_ffa()) sdc3_plat_data.msmsdcc_fmax = sdc3_plat_data.msmsdcc_fmid; msm_add_sdcc(3, &sdc3_plat_data); } #endif /* Micro-SD slot */ #ifdef CONFIG_MMC_MSM_SDC1_SUPPORT gpio_sdc1_config(); if (mmc_regulator_init(1, "mmc", 2850000)) return; /* 8x25 EVT do not use hw detector */ if (!((machine_is_msm8625_evt() || machine_is_qrd_skud_prime()))) sdc1_plat_data.status_irq = MSM_GPIO_TO_INT(gpio_sdc1_hw_det); if (machine_is_msm8625_evt() || machine_is_qrd_skud_prime()) sdc1_plat_data.status = NULL; msm_add_sdcc(1, &sdc1_plat_data); #endif /* SDIO WLAN slot */ #ifdef CONFIG_MMC_MSM_SDC2_SUPPORT if (mmc_regulator_init(2, "smps3", 1800000)) return; msm_add_sdcc(2, &sdc2_plat_data); #endif /* Not Used */ #if (defined(CONFIG_MMC_MSM_SDC4_SUPPORT)\ && !defined(CONFIG_MMC_MSM_SDC3_8_BIT_SUPPORT)) /* There is no SDC4 for QRD3/7 based devices */ if (!(machine_is_msm7627a_qrd3() || machine_is_msm8625_qrd7())) { if (mmc_regulator_init(4, "smps3", 1800000)) return; msm_add_sdcc(4, &sdc4_plat_data); } #endif } #endif
28.903382
77
0.718118
571367a81b9e4d87e1fdea76936ca930022e59a2
1,579
js
JavaScript
dist/scripts/scripts.d1427be3.js
nicholas-araujo/admiral-ackbar
a714e2586a65dfad9063b3b2e8f305dfa545dc0d
[ "MIT" ]
null
null
null
dist/scripts/scripts.d1427be3.js
nicholas-araujo/admiral-ackbar
a714e2586a65dfad9063b3b2e8f305dfa545dc0d
[ "MIT" ]
null
null
null
dist/scripts/scripts.d1427be3.js
nicholas-araujo/admiral-ackbar
a714e2586a65dfad9063b3b2e8f305dfa545dc0d
[ "MIT" ]
null
null
null
"use strict";angular.module("admiralAckbarApp",["ngAnimate","ngCookies","ngResource","ngRoute","ngSanitize","ngTouch","ui.sortable"]).config(["$routeProvider",function(a){a.when("/",{templateUrl:"views/main.html",controller:"MainCtrl",controllerAs:"main"}).when("/about",{templateUrl:"views/about.html",controller:"AboutCtrl",controllerAs:"about"}).otherwise({redirectTo:"/"})}]),angular.module("admiralAckbarApp").controller("MainCtrl",["$scope",function(a){a.todos=[],a.addTodo=function(){a.todos.push(a.todo),a.todo=""},a.removeTodo=function(b){a.todos.splice(b,1)}}]),angular.module("admiralAckbarApp").controller("AboutCtrl",function(){this.awesomeThings=["HTML5 Boilerplate","AngularJS","Karma"]}),angular.module("admiralAckbarApp").run(["$templateCache",function(a){a.put("views/about.html","<p>This is the about view.</p>"),a.put("views/main.html",'<div class="container"> <h2>My To Do List</h2> <!-- Todos input --> <form role="form" ng-submit="addTodo()"> <div class="row"> <div class="input-group"> <input type="text" ng-model="todo" placeholder="What needs to be done?" class="form-control"> <span class="input-group-btn"> <input type="submit" class="btn btn-primary" value="Add"> </span> </div> </div> </form> <!-- Todos list --> <div ui-sortable ng-model="todos"> <p class="input-group" ng-repeat="todo in todos" style="padding:5px 10px; cursor: move"> <input type="text" ng-model="todo" class="form-control"> <span class="input-group-btn"> <button class="btn btn-danger" ng-click="removeTodo($index)" aria-label="Remove">X</button> </span> </p> </div> </div>')}]);
1,579
1,579
0.702343
e25c2f098c222158d0ee6825add7b899d782bb53
1,408
sh
Shell
kud/tests/ovn4nfv.sh
malsbat/multicloud-k8s
d1d93073946cb9420b02a2a416fae773262b0836
[ "Apache-2.0" ]
31
2018-10-02T14:52:36.000Z
2021-11-14T20:38:55.000Z
kud/tests/ovn4nfv.sh
malsbat/multicloud-k8s
d1d93073946cb9420b02a2a416fae773262b0836
[ "Apache-2.0" ]
3
2019-02-26T23:03:07.000Z
2019-05-13T16:21:24.000Z
kud/tests/ovn4nfv.sh
malsbat/multicloud-k8s
d1d93073946cb9420b02a2a416fae773262b0836
[ "Apache-2.0" ]
31
2019-01-15T19:51:25.000Z
2022-02-08T14:47:57.000Z
#!/bin/bash ############################################################################## # Copyright (c) 2018 # All rights reserved. This program and the accompanying materials # are made available under the terms of the Apache License, Version 2.0 # which accompanies this distribution, and is available at # http://www.apache.org/licenses/LICENSE-2.0 ############################################################################## set -o errexit set -o nounset set -o pipefail source _common.sh source _common_test.sh source _functions.sh csar_id=a1c5b53e-d7ab-11e8-85b7-525400e8c29a # Setup populate_CSAR_ovn4nfv $csar_id pushd ${CSAR_DIR}/${csar_id} for net in ovn-priv-net ovn-port-net; do echo "Create OVN Network $net network" kubectl apply -f $net.yaml done kubectl apply -f onap-ovn4nfvk8s-network.yaml setup $ovn4nfv_deployment_name # Test deployment_pod=$(kubectl get pods | grep $ovn4nfv_deployment_name | awk '{print $1}') echo "===== $deployment_pod details =====" kubectl exec -it $deployment_pod -- ip a ovn_nic=$(kubectl exec -it $deployment_pod -- ip a ) if [[ $ovn_nic != *"net3"* ]]; then echo "The $deployment_pod pod doesn't contain the net3 nic" exit 1 else echo "Test Completed!" fi # Teardown teardown $ovn4nfv_deployment_name for net in ovn-priv-net ovn-port-net; do echo "Delete OVN Network $net network" kubectl delete -f $net.yaml done popd
27.607843
86
0.65483
641997811050b0aed6a3f6fb18dc335d239c52c4
15,931
py
Python
resolwe/permissions/models.py
genialis/resolwe
64ab124e5898ffd28c13c7104d32a2f4bdee55c9
[ "Apache-2.0" ]
27
2015-12-07T18:29:12.000Z
2022-03-16T08:01:47.000Z
resolwe/permissions/models.py
genialis/resolwe
64ab124e5898ffd28c13c7104d32a2f4bdee55c9
[ "Apache-2.0" ]
681
2015-12-01T11:52:24.000Z
2022-03-21T07:43:37.000Z
resolwe/permissions/models.py
genialis/resolwe
64ab124e5898ffd28c13c7104d32a2f4bdee55c9
[ "Apache-2.0" ]
28
2015-12-01T08:32:57.000Z
2021-12-14T00:04:16.000Z
"""Permission storage model.""" import logging from enum import IntEnum from functools import reduce from typing import List, Optional, Union from django.conf import settings from django.contrib.auth import get_user_model from django.contrib.auth.models import Group, User from django.db import models, transaction logger = logging.getLogger(__name__) PermissionList = List["Permission"] UserOrGroup = Union[User, Group] # Get and store the anonymous user for later use to avoid hits to the database. ANONYMOUS_USER = None def get_anonymous_user() -> User: """Get the anonymous user. Note that is the actual user object with username specified in setting ANONYMOUS_USER_NAME or id specified in setting ANONYMOUS_USER_ID. The later setting has precedence. Store the computed value into global variable get_anonymous_user() to avoid querying the database every time. :raises django.core.exceptions.ObjectDoesNotExist: when anonymous user could not be found. :raises RuntimeError: when setting ANONYMOUS_USER_NAME could not be found. """ # Return the cached value in production. During testing the anonymous user # will be recreated several times with different id. from resolwe.test.utils import is_testing global ANONYMOUS_USER if ANONYMOUS_USER is not None and not is_testing: return ANONYMOUS_USER anonymous_user_id = getattr(settings, "ANONYMOUS_USER_ID", None) anonymous_username = getattr(settings, "ANONYMOUS_USER_NAME", None) create_arguments = {"is_active": True, "email": "", "username": "public"} filters = None if anonymous_user_id is not None: filters = {"id": anonymous_user_id} create_arguments["id"] = anonymous_user_id elif anonymous_username is not None: filters = {User.USERNAME_FIELD: anonymous_username} create_arguments["username"] = anonymous_username if filters: try: return get_user_model().objects.get(**filters) except User.DoesNotExist: # Resolve circular import. if is_testing(): return get_user_model().objects.create(**create_arguments) else: raise raise RuntimeError("No ANONYMOUS_USER_ID/ANONYMOUS_USER_NAME setting found.") class Permission(IntEnum): """Enum that describes all possible permissions on Resolwe objects. The permissions on Resolwe objects are ordered linearly so they can be mapped to natural numbers. Permissions that are mapped to lower numbers are implicitely included in the permissions mapped to a higher number. Whenever dealing with permissions (reading, setting...) it is necessary to use this enum. The instances of Permission class are iterable and iterating over an instance P returs all permissions that are lower or equal to P, ordered from bottom to top. """ # Possible permission levels. They must be orded from bottom to top since # methods bellow rely on the ordering. NONE = 0 VIEW = 1 EDIT = 2 SHARE = 4 OWNER = 8 @staticmethod def from_name(permission_name: str) -> "Permission": """Get the permission from permission name. :returns: Permission object when permission_name is the name of the permission and highest permission if permission_name is 'ALL'. :raises KeyError: when permission name is not known. """ if permission_name == "ALL": return Permission.highest() return Permission[permission_name.upper()] @staticmethod def highest() -> "Permission": """Return the highest permission.""" return list(Permission)[-1] def __iter__(self): """Iterate through permission in increasing order. When iterating over permission instance the permissions included in the current one (including permission itself) are returned (in increasing order). The permission Permission.NONE is excluded from the listing. """ for permission in Permission: if 0 < permission.value <= self.value: yield permission def __reversed__(self): """Iterate through permissions in decreasing order. When iterating over permission instance the permissions included in the current one (including permission itself) are returned (in decreasing order). The permission Permission.NONE is excluded from the listing. """ for permission in reversed(Permission): if 0 < permission.value <= self.value: yield permission def __str__(self) -> str: """Get the string representation of the permission. This is used in serialization so it must be equal to 'view', 'edit', 'share' and 'owner'. """ return self.name.lower() class PermissionModel(models.Model): """Store a permission for a singe user/group on permission group. Exactly one of fields user/group must be non-null. """ #: permission value value = models.PositiveSmallIntegerField() #: user this permission belongs to user = models.ForeignKey( get_user_model(), related_name="model_permissions", on_delete=models.CASCADE, null=True, ) #: group this permission belongs to group = models.ForeignKey( Group, related_name="model_permissions", on_delete=models.CASCADE, null=True ) #: permission group this permission belongs to permission_group = models.ForeignKey( "PermissionGroup", on_delete=models.CASCADE, related_name="permissions" ) class Meta: """Define constraints enforced on the model. The tripple (value, permission_group, user/group) must be unique. """ constraints = [ models.UniqueConstraint( fields=["permission_group", "value", "user"], name="one_permission_per_user", condition=models.Q(user__isnull=False), ), models.UniqueConstraint( fields=["permission_group", "value", "group"], name="one_permission_per_group", condition=models.Q(group__isnull=False), ), models.CheckConstraint( check=models.Q(user__isnull=False, group__isnull=True) | models.Q(user__isnull=True, group__isnull=False), name="exactly_one_of_user_group_must_be_set", ), ] @property def permission(self) -> Permission: """Return the permission object associated with this instance.""" return Permission(self.value) @property def permissions(self) -> PermissionList: """Return the permission objects associated with this instance.""" return list(self.permission) def __str__(self) -> str: """Get the string representation used for debugging.""" return ( f"PermissionModel({self.id}, {Permission(self.permission)}, " f"user: {self.user}, group: {self.group})" ) class PermissionGroup(models.Model): """Group of objecs that have the same permissions. Example: a container and all its contents have same permission group. """ def __str__(self) -> str: """Return the string representation used for debugging purposes.""" return f"PermissionGroup({self.id}, {self.permissions.all()})" @transaction.atomic def set_permission(self, permission: Permission, user_or_group: UserOrGroup): """Set the given permission on this permission group. All previous permissions are removed. :raises AssertionError: when no user or group is given. """ from resolwe.permissions.utils import get_identity # Circular import entity, entity_name = get_identity(user_or_group) self.permissions.update_or_create( **{"permission_group": self, entity_name: entity}, defaults={"value": permission.value}, ) def get_permission(self, user_or_group: UserOrGroup) -> Permission: """Get the permission for the given user or group.""" from resolwe.permissions.utils import get_identity # Circular import entity, entity_name = get_identity(user_or_group) # Superuser has all the permissions. if entity_name == "user" and entity.is_superuser: return Permission.highest() permission_models = self.permissions.filter(**{entity_name: entity}) return permission_models[0].permission if permission_models else Permission.NONE class PermissionQuerySet(models.QuerySet): """Queryset with methods that simlify filtering by permissions.""" def _filter_by_permission( self, user: Optional[User], groups: Optional[List[Group]], permission: Permission, public: bool = True, with_superuser: bool = True, ) -> models.QuerySet: """Filter queryset by permissions. This is a generic method that is called in public methods. :attr user: the user which permissions should be considered. :attr groups: the groups which permissions should be considered. :attr permission: the lowest permission entity must have. :attr public: when True consider also public permission. :attr with_superuser: when false treat superuser as reguar user. """ # Skip filtering for superuser when with_superuser is set. if user is not None and user.is_superuser and with_superuser: return self # Handle special case of Storage and Relation. filters_prefix = "" if self.model._meta.label == "flow.Storage": filters_prefix = "data__" filters = dict() if user: filters["user"] = models.Q( **{ f"{filters_prefix}permission_group__permissions__user": user, f"{filters_prefix}permission_group__permissions__value__gte": permission, } ) if public: filters["public"] = models.Q( **{ f"{filters_prefix}permission_group__permissions__user": get_anonymous_user(), f"{filters_prefix}permission_group__permissions__value__gte": permission, } ) if groups: filters["groups"] = models.Q( **{ f"{filters_prefix}permission_group__permissions__group__in": groups.values_list( "pk", flat=True ), f"{filters_prefix}permission_group__permissions__value__gte": permission, } ) # List here is needed otherwise more joins are performed on the query # bellow. Some Django queries (for example ExpressionLateralJoin) do # not like that and will fail without evaluating the ids query first. ids = list( self.filter( reduce(lambda filters, filter: filters | filter, filters.values()) ) .distinct() .values_list("id", flat=True) ) return self.filter(id__in=ids) def filter_for_user( self, user: User, permission: Permission = Permission.VIEW, use_groups: bool = True, public: bool = True, with_superuser: bool = True, ) -> models.QuerySet: """Filter objects for user. :attr user: the user which permissions should be considered. :attr permission: the lowest permission entity must have. :attr use_groups: when True consider also permissions of the user groups. :attr public: when True consider also public permission. :attr with_superuser: when false treat superuser as reguar user. """ from resolwe.permissions.utils import get_user # Circular import user = get_user(user) groups = user.groups.all() if use_groups else [] return self._filter_by_permission( user, groups, permission, public, with_superuser ) class PermissionObject(models.Model): """Base permission object. Every object that has permissions must inherit from this one. """ class Meta: """Make this class abstract so no new table is created for it.""" abstract = True #: permission group for the object permission_group = models.ForeignKey( PermissionGroup, on_delete=models.CASCADE, related_name="%(class)s", null=True ) #: custom manager with permission filtering methods. objects = PermissionQuerySet.as_manager() def __init__(self, *args, **kwargs): """Initialize.""" # The properties used to determine if object is in container. self._container_properties = ("collection", "entity") super().__init__(*args, **kwargs) def is_owner(self, user: User) -> bool: """Return if user is the owner of this instance.""" return self.has_permission(Permission.OWNER, user) def has_permission(self, permission: Permission, user: User): """Check if user has the given permission on the current object.""" return ( self._meta.model.objects.filter(pk=self.pk) .filter_for_user(user, permission) .exists() ) def set_permission(self, permission: Permission, user_or_group: UserOrGroup): """Set permission on this instance. It performs additional check if permissions can be set on this object. :raises RuntimeError: when given object has no permission_group or is contained in a container. """ if self.in_container(): raise RuntimeError( f"The permissions can not be set on object {self} ({self._meta.label}) in container." ) self.permission_group.set_permission(permission, user_or_group) def get_permission(self, user_or_group: UserOrGroup) -> Permission: """Get permission for given user or group on this instance.""" return self.permission_group.get_permission(user_or_group) def get_permissions(self, user_or_group: UserOrGroup) -> PermissionList: """Get a list of all permissions on the object. The Permission.NONE is excluded from list. """ permission = self.get_permission(user_or_group) if permission: return list(permission) else: return [] @property def topmost_container(self) -> Optional[models.Model]: """Get the top-most container of the object. :returns: the top-most container or None if it does not exist. """ for property in self._container_properties: value = getattr(self, property, None) if value is not None: return value return None def in_container(self) -> bool: """Return if object lies in a container.""" return self.topmost_container is not None def save(self, *args, **kwargs): """Set the permission_group property of the object. If object belongs to a container set its permission group to the one used by the container. If object does not belong to a container and has no permission group create a new one and assign it to the object. Mental note: this could lead to orphaned PermissionGroup objects lying around. """ container = self.topmost_container if container is not None: self.permission_group_id = container.permission_group_id elif self.permission_group is None: self.permission_group = PermissionGroup.objects.create() super().save(*args, **kwargs)
34.632609
101
0.647166
95ba10266ddefea002193c73e2be42c4a78cea7a
2,109
rb
Ruby
db/schema.rb
tsycho/taggeddata
b1c765ed2398b0e3d70dc4a3f925966d28078395
[ "MIT" ]
null
null
null
db/schema.rb
tsycho/taggeddata
b1c765ed2398b0e3d70dc4a3f925966d28078395
[ "MIT" ]
7
2016-01-18T17:45:11.000Z
2016-01-24T08:36:51.000Z
db/schema.rb
tsycho/taggeddata
b1c765ed2398b0e3d70dc4a3f925966d28078395
[ "MIT" ]
null
null
null
# encoding: UTF-8 # This file is auto-generated from the current state of the database. Instead # of editing this file, please use the migrations feature of Active Record to # incrementally modify your database, and then regenerate this schema definition. # # Note that this schema.rb definition is the authoritative source for your # database schema. If you need to create the application database on another # system, you should be using db:schema:load, not running all the migrations # from scratch. The latter is a flawed and unsustainable approach (the more migrations # you'll amass, the slower it'll run and the greater likelihood for issues). # # It's strongly recommended that you check this file into your version control system. ActiveRecord::Schema.define(version: 20160123050457) do # These are extensions that must be enabled in order to support this database enable_extension "plpgsql" create_table "api_keys", force: :cascade do |t| t.integer "user_id", null: false t.string "key", null: false end add_index "api_keys", ["key"], name: "index_api_keys_on_key", unique: true, using: :btree create_table "data", force: :cascade do |t| t.integer "user_id", null: false t.decimal "value" t.jsonb "data" t.boolean "is_public", default: false, null: false t.text "tags", default: [], array: true t.date "date", null: false end add_index "data", ["user_id"], name: "index_data_on_user", using: :btree add_index "data", ["tags"], name: "index_data_on_tags", using: :gin create_table "users", force: :cascade do |t| t.string "provider", null: false t.string "uid", null: false t.string "name" t.string "email" t.string "photo" t.datetime "created_at", null: false t.datetime "updated_at", null: false end add_index "users", ["provider", "uid"], name: "index_users_on_provider_and_uid", using: :btree add_foreign_key "api_keys", "users", on_delete: :cascade add_foreign_key "data", "users", on_delete: :cascade end
39.792453
96
0.688004
339e1a8f6003299aca940d423634ec66f05cfc52
1,711
h
C
happy_new_year.h
jinykim0x80/happy_new_year
f4fbbea978bcfe48ea0c7ed2d33d1c3e74cf9a1b
[ "MIT" ]
null
null
null
happy_new_year.h
jinykim0x80/happy_new_year
f4fbbea978bcfe48ea0c7ed2d33d1c3e74cf9a1b
[ "MIT" ]
null
null
null
happy_new_year.h
jinykim0x80/happy_new_year
f4fbbea978bcfe48ea0c7ed2d33d1c3e74cf9a1b
[ "MIT" ]
null
null
null
#include <iostream> #include <ncurses.h> #include <unistd.h> #include <fstream> #include <string> using namespace std; #define CANVAS_SKY_X 150 #define CANVAS_SKY_Y 20 #define CANVAS_URBAN_X 130 #define CANVAS_URBAN_Y 10 char canvas_sky[20][150]; char canvas_urban[10][130]; string getascii(string); void night(); void morning(); //void init_night(); void init_sky(); void init_urban(); void print_sky(); void print_urban(); void moveObject(); #define SUN_HIEIGHT 15 #define SUN_WIDTH 40 char sun[SUN_HIEIGHT][SUN_WIDTH] = { " . ' .", " . . : . .", " '. ______ .'", " ' _.-\"` `\"-._ '", " .' '.", " `'--. / \\ .--'`", " / \\,", " ; ;", "- -- | | -- -", " | |", " ; ;", " .-' \\ / '-." }; #define TEXT_HEIGHT 8 #define TEXT_WIDTH 90 char text[TEXT_HEIGHT][TEXT_WIDTH] = { " _ _ _ _ __ __ ", " | | | | | \\ | | \\ \\ / / ", " | |_| | __ _ _ __ _ __ _ _ | \\| | _____ __ \\ V /___ __ _ _ __ ", " | _ |/ _` | '_ \\| '_ \\| | | | | . ` |/ _ \\ \\ /\\ / / \\ // _ \\/ _` | '__|", " | | | | (_| | |_) | |_) | |_| | | |\\ | __/\\ V V / | | __/ (_| | | ", " \\_| |_/\\__,_| .__/| .__/ \\__, | \\_| \\_/\\___| \\_/\\_/ \\_/\\___|\\__,_|_| ", " | | | | __/ | ", " |_| |_| |___/ " };
31.109091
90
0.328463
dd5a715f5bf253327f5794822d327b6f4c1386a9
176
java
Java
rdfunit-webdemo/src/main/java/org/aksw/rdfunit/webdemo/utils/DataOption.java
k00ni/RDFUnit
15b120ca0c5f5c903091758d831db966e7c65982
[ "Apache-2.0" ]
109
2015-01-02T15:40:47.000Z
2022-03-15T14:40:28.000Z
rdfunit-webdemo/src/main/java/org/aksw/rdfunit/webdemo/utils/DataOption.java
k00ni/RDFUnit
15b120ca0c5f5c903091758d831db966e7c65982
[ "Apache-2.0" ]
84
2015-01-07T07:56:43.000Z
2022-03-15T07:59:32.000Z
rdfunit-webdemo/src/main/java/org/aksw/rdfunit/webdemo/utils/DataOption.java
k00ni/RDFUnit
15b120ca0c5f5c903091758d831db966e7c65982
[ "Apache-2.0" ]
40
2015-01-06T17:34:50.000Z
2022-03-14T13:57:09.000Z
package org.aksw.rdfunit.webdemo.utils; /** * Description * * @author Dimitris Kontokostas * @since 8/30/14 6:51 PM */ public enum DataOption { SPARQL, URI, TEXT }
12.571429
39
0.664773
4b13d7bcf6fe94fa08f5b0919cba0976ed18c695
1,079
gemspec
Ruby
omniauth-paypal-oauth2.gemspec
scttdavs/omniauth-paypal-oauth2
b4e14c88a4e8f9dba8037120f0805104f15bdb7d
[ "MIT" ]
null
null
null
omniauth-paypal-oauth2.gemspec
scttdavs/omniauth-paypal-oauth2
b4e14c88a4e8f9dba8037120f0805104f15bdb7d
[ "MIT" ]
null
null
null
omniauth-paypal-oauth2.gemspec
scttdavs/omniauth-paypal-oauth2
b4e14c88a4e8f9dba8037120f0805104f15bdb7d
[ "MIT" ]
null
null
null
# frozen_string_literal: true require File.expand_path( File.join('..', 'lib', 'omniauth', 'paypal_oauth2', 'version'), __FILE__ ) Gem::Specification.new do |gem| gem.name = 'omniauth-paypal-oauth2' gem.version = OmniAuth::PaypalOauth2::VERSION gem.platform = Gem::Platform::RUBY gem.summary = 'A PayPal OAuth2 strategy for OmniAuth' gem.description = 'A PayPal OAuth2 strategy for OmniAuth' gem.authors = 'Jonas Hübotter' gem.email = 'jonas.huebotter@gmail.com' gem.homepage = 'https://github.com/jonhue/omniauth-paypal-oauth2' gem.license = 'MIT' gem.files = Dir['README.md', 'LICENSE', 'lib/**/*'] gem.require_paths = ['lib'] gem.required_ruby_version = '>= 2.3' gem.add_dependency 'json', '>= 1.7', '<3' gem.add_dependency 'omniauth-oauth2', '~> 1.5' gem.add_development_dependency 'rspec' gem.add_development_dependency 'rubocop' gem.add_development_dependency 'rubocop-rspec' end
34.806452
80
0.609824
0df5c53cc2ed5783fd2cb4906092833c1529f2a8
4,062
cs
C#
Alpaca.Markets/Obsolete/SockClient.cs
camerontbelt/alpaca-trade-api-csharp
e066deaf4b8dc5b9974496a77350b4870a23bdb8
[ "Apache-2.0" ]
null
null
null
Alpaca.Markets/Obsolete/SockClient.cs
camerontbelt/alpaca-trade-api-csharp
e066deaf4b8dc5b9974496a77350b4870a23bdb8
[ "Apache-2.0" ]
null
null
null
Alpaca.Markets/Obsolete/SockClient.cs
camerontbelt/alpaca-trade-api-csharp
e066deaf4b8dc5b9974496a77350b4870a23bdb8
[ "Apache-2.0" ]
null
null
null
using System; using System.Diagnostics.CodeAnalysis; namespace Alpaca.Markets { /// <summary> /// Provides unified type-safe access for Alpaca streaming API. /// </summary> [Obsolete("This class is deprecated and will be removed in the upcoming releases. Use the AlpacaStreamingClient class instead.", true)] [SuppressMessage("ReSharper", "UnusedType.Global")] [SuppressMessage("ReSharper", "EventNeverSubscribedTo.Global")] public sealed class SockClient : IDisposable { private readonly AlpacaStreamingClient _client; /// <summary> /// Creates new instance of <see cref="SockClient"/> object. /// </summary> /// <param name="keyId">Application key identifier.</param> /// <param name="secretKey">Application secret key.</param> /// <param name="alpacaRestApi">Alpaca REST API endpoint URL.</param> /// <param name="webSocketFactory">Factory class for web socket wrapper creation.</param> public SockClient( String keyId, String secretKey, String? alpacaRestApi = null, IWebSocketFactory? webSocketFactory = null) : this(createConfiguration( keyId, secretKey, alpacaRestApi.GetUrlSafe(Environments.Live.AlpacaTradingApi), webSocketFactory)) { } /// <summary> /// Creates new instance of <see cref="SockClient"/> object. /// </summary> /// <param name="keyId">Application key identifier.</param> /// <param name="secretKey">Application secret key.</param> /// <param name="alpacaRestApi">Alpaca REST API endpoint URL.</param> /// <param name="webSocketFactory">Factory class for web socket wrapper creation.</param> public SockClient( String keyId, String secretKey, Uri alpacaRestApi, IWebSocketFactory? webSocketFactory) : this(createConfiguration(keyId, secretKey, alpacaRestApi, webSocketFactory)) { } /// <summary> /// Creates new instance of <see cref="SockClient"/> object. /// </summary> /// <param name="configuration">Configuration parameters object.</param> private SockClient( AlpacaStreamingClientConfiguration configuration) => _client = new AlpacaStreamingClient(configuration); /// <summary> /// Occured when new account update received from stream. /// </summary> [SuppressMessage("Design", "CA1030:Use events where appropriate", Justification = "Compiler issue")] public event Action<IAccountUpdate>? OnAccountUpdate { add => _client.OnAccountUpdate += value; remove => _client.OnAccountUpdate -= value; } /// <summary> /// Occured when new trade update received from stream. /// </summary> [SuppressMessage("Design", "CA1030:Use events where appropriate", Justification = "Compiler issue")] public event Action<ITradeUpdate>? OnTradeUpdate { add => _client.OnTradeUpdate += value; remove => _client.OnTradeUpdate -= value; } /// <inheritdoc/> public void Dispose() => _client.Dispose(); private static AlpacaStreamingClientConfiguration createConfiguration( String keyId, String secretKey, Uri alpacaRestApi, IWebSocketFactory? webSocketFactory) => new AlpacaStreamingClientConfiguration { SecurityId = new SecretKey( keyId ?? throw new ArgumentException("Application key id should not be null.", nameof(keyId)), secretKey ?? throw new ArgumentException("Application secret key should not be null.", nameof(secretKey))), ApiEndpoint = alpacaRestApi ?? Environments.Live.AlpacaTradingApi, WebSocketFactory = webSocketFactory ?? WebSocket4NetFactory.Instance, }; } }
42.3125
139
0.620876
e763d682d026950f8d0a50716b2601d23d4b7e20
9,937
php
PHP
resources/views/layouts/adminto/sidebar_menu.blade.php
alireza5014/adclicki
1160fa4b0a8b3ce2bcefcd93e886227dc4e134da
[ "MIT" ]
null
null
null
resources/views/layouts/adminto/sidebar_menu.blade.php
alireza5014/adclicki
1160fa4b0a8b3ce2bcefcd93e886227dc4e134da
[ "MIT" ]
null
null
null
resources/views/layouts/adminto/sidebar_menu.blade.php
alireza5014/adclicki
1160fa4b0a8b3ce2bcefcd93e886227dc4e134da
[ "MIT" ]
1
2021-01-21T12:07:34.000Z
2021-01-21T12:07:34.000Z
<div class="modal fade bs-example-modal-sm" tabindex="-1" role="dialog" aria-labelledby="mySmallModalLabel" aria-hidden="true" style=" top:30%;display: none;"> <div class="modal-dialog modal-sm"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button> <h4 class="modal-title" id="mySmallModalLabel"> خروج </h4> </div> <div class="modal-body"> <a href="{{url('logout')}}"><i class="fa fa-book"></i> <span> {{trans('admin_panel.logout')}}</span></a> </div> </div><!-- /.modal-content --> </div><!-- /.modal-dialog --> </div><!-- /.modal --> <div class="user-box " style="padding: 1px 1px 1px 1px !important;"> <div class="card-box-1"> <ul class="list-inline"> <li> <a href="{{route('user_profile',['id'=>auth($guard)->user()->id])}}"> <img src="{{url(auth($guard)->user()->image_path)}}" alt="user-img" title="" class="img-circle img-thumbnail img-responsive " width="30px"> </a> </li> <li> <a href="#">{{auth($guard)->user()->fname }} {{auth($guard)->user()->lname}}</a> </li> <li>{{user_type(auth($guard)->user()->type)}}</li> </ul> @if(auth($guard)->user()->country!='Iran' && auth($guard)->user()->country!='') <p class="error text-center">شما از IP کشور ({{auth($guard)->user()->country}}) استفاده کرده اید و طبق قوانین سایت حساب کاربری شما حذف خواهد شد</p> @endif </div> <ul class="list-inline"> @if($guard=='admin') <li> <a href="{{route('admin_profile',['id'=>auth($guard)->user()->id])}}"> <i class="zmdi zmdi-edit"></i> </a> </li> <a href="{{route('getLogout')}}"> <i class="zmdi zmdi-power btn btn-xs btn-danger"></i> </a> @else <li> <a href="{{route('user.password')}}" title="تغییر گذرواژه"> <i class="zmdi zmdi-key btn btn-xs btn-primary"></i> </a> </li> <li> <a href="{{route('user_profile',['id'=>auth($guard)->user()->id])}}" title="ویرایش پروفایل"> <i class="zmdi zmdi-edit btn btn-xs btn-info"></i> </a> </li> <li><a href="{{route('getUserLogout')}}" title=" خروج از حساب کاربری"> <i class="zmdi zmdi-power btn btn-xs btn-danger"></i> </a></li> <li><a href="{{url('')}}" class=" btn-primary btn-xs"><i class="fa fa-internet-explorer " title=" نمایش سایت"></i></a></li> @endif </ul> </div> <div id="sidebar-menu"> <div class="clearfix"></div> @if($guard=='admin') <ul> <li> <a href="{{url('/admin/home')}}" class="waves-effect"><i class="zmdi zmdi-view-dashboard"></i> <span> داشبورد </span> </a> </li> <li> <a href="{{route('admin.withdrawals.list')}}" class="waves-effect"><i class="zmdi zmdi-view-dashboard"></i> <span class="label label-danger pull-right">{!! getUnPayedWithdraw() !!}</span> <span> درخواست واریز ها </span> </a> </li> <li> <a href="{{route('admin.ads.clicki.list')}}" class="waves-effect"> <i class="zmdi zmdi-view-dashboard"></i> <span class="label label-danger pull-right">{!! getUnConfirmClickiAds() !!}</span> <span> لیست تبلیغات کلیکی </span> </a></li> </li> <li> <a href="{{route('admin.ads.google_search.list')}}" class="waves-effect"> <i class="zmdi zmdi-view-dashboard"></i> <span class="label label-danger pull-right">{!! getUnConfirmGoogleSearchAds() !!}</span> <span> لیست تبلیغات جستجو گوگل </span> </a></li> </li> <li> <a href="{{route('admin.payments.list')}}" class="waves-effect"> <i class="zmdi zmdi-view-dashboard"></i> <span class="label label-danger pull-right">{!! getUserPayment() !!}</span> <span> لیست پرداخت ها </span> </a></li> </li> <li class="has_sub"> <a href="javascript:void(0);" class="waves-effect"><i class="zfa fa-location-arrow"></i> <span class="menu-arrow"></span><span> آنالیز سایت </span> </a> <ul class="list-unstyled"> <li><a href="{{route('analyzes')}}" class="waves-effect"> <span> نمودار ها</span> </a></li> <li><a href="{{route('analyzes_keywords')}}" class="waves-effect"> <span> کلمات کلیدی </span> </a> </li> <li><a href="{{route('analyzes_links')}}" class="waves-effect"> <span> لینک ها</span> </a></li> </ul> </li> <li class="has_sub"> <a href="javascript:void(0);" class="waves-effect"><i class="zfa fa-location-arrow"></i> <span class="menu-arrow"></span><span> کاربران </span> </a> <ul class="list-unstyled"> <li><a href="{{route('create_user')}}" class="waves-effect"> <span> کاربر جدید</span> </a></li> <li><a href="{{route('users_message_list')}}" class="waves-effect"> <span> لیست پیامهای کاربران</span> </a></li> <li><a href="{{route('users_list')}}" class="waves-effect"> <span> لیست همه کاربران</span> </a></li> </li> </ul> </li> <li> <a href="{{url('admin/tickets/all')}}" class="waves-effect"> <i class="fa fa-instagram"></i> <span class="label label-danger pull-right">{!! getUnAnsweredTicket() !!}</span> <span> تیکت ها </span> </a> </li> <li class="has_sub"> <a href="javascript:void(0);" class="waves-effect"><i class="zfa fa-location-arrow"></i> <span class="menu-arrow"></span><span> تنظیمات </span> </a> <ul class="list-unstyled"> <li><a href="{{url('admin/setting')}}" class="waves-effect"> <span> تنظیمات عمومی </span> </a> </li> <li><a href="{{route('web_hook.edit')}}" class="waves-effect"> <span> تنظیم وب هوک </span> </a> </li> </ul> </li> <li> <a href="{{route('site_map')}}" class="waves-effect"><i class="zmdi zmdi-view-dashboard"></i> <span> ساخت نقشه سایت </span> </a> </li> </ul> @elseif($guard=='user') <ul> <li> <a href="{{url('user/home')}}" class="waves-effect"><i class="zmdi zmdi-view-dashboard"></i> <span> میز کار </span> </a> </li> @if(getActivityType()==0) @include('layouts.adminto.menu0') @elseif(getActivityType()==1) @include('layouts.adminto.menu1') @else @include('layouts.adminto.menu1') @include('layouts.adminto.menu0') @endif <li> <a href="{{url('user/ticket-list')}}" class="waves-effect"><i class="fa fa-ticket"></i> <span> تیکت پشتیبانی </span> </a> </li> <li class="has_sub"> <a href="javascript:void(0);" class="waves-effect"><i class="fa fa-user"></i> <span class="menu-arrow"></span><span> مدیریت پروفایل </span> </a> <ul class="list-unstyled"> <li> <a href="{{route('user_profile',['id'=>auth($guard)->user()->id])}}" class="waves-effect"> <span> ویرایش اطلاعات کاربری </span> </a> </li> <li> <a href="{{route('user.edit.bank_info')}}" class="waves-effect"> <span> ویرایش اطلاعات بانکی </span> </a> </li> <li> <a href="{{route('user.password')}}" class="waves-effect"> <span> تغییر رمز عبور </span> </a> </li> </ul> </li> <li> <a href="{{url('user/notification')}}" class="waves-effect"><i class="fa fa-telegram"></i> <span> اطلاع رسانی (تلگرام) </span> <span class="label label-danger pull-right">جدید</span> </a> </li> <li> <a href="{{url('user/message')}}" class="waves-effect"><i class="fa fa-newspaper"></i> <span> پیامها </span> <span class="label label-danger pull-right">1</span> </a> </li> <li> <a href="{{url('user/learning')}}" class="waves-effect"><i class="fa fa-book"></i> <span> آموزش </span> </a> </li> </ul> @endif </div>
35.237589
129
0.431116
da63e90aa902cc94c06cece21c0146a10fb0cb3b
487
php
PHP
src/Grid/Factory/IBase.php
abtercms/framework
0d2591765f67e941e199f1ee0ab571ca4cd776c6
[ "MIT" ]
1
2019-11-28T20:15:53.000Z
2019-11-28T20:15:53.000Z
src/Grid/Factory/IBase.php
abtercms/framework
0d2591765f67e941e199f1ee0ab571ca4cd776c6
[ "MIT" ]
null
null
null
src/Grid/Factory/IBase.php
abtercms/framework
0d2591765f67e941e199f1ee0ab571ca4cd776c6
[ "MIT" ]
null
null
null
<?php declare(strict_types=1); namespace AbterPhp\Framework\Grid\Factory; use AbterPhp\Framework\Grid\Component\Filters; use AbterPhp\Framework\Grid\IGrid; interface IBase { /** * @param Filters $filters * * @return IBase */ public function setFilters(Filters $filters): IBase; /** * @param array $params * @param string $baseUrl * * @return IGrid */ public function createGrid(array $params, string $baseUrl): IGrid; }
18.037037
70
0.644764
a9b9afccc57d65004f063ab8cc9c27e59ae7a230
28,122
rs
Rust
src/gfx3d/pipeline.rs
ameykusurkar/rustyPixelGameEngine
719a0aae76da658c879756456c820b8298d7f237
[ "BSD-3-Clause" ]
66
2019-02-20T22:53:09.000Z
2022-02-15T19:14:20.000Z
src/gfx3d/pipeline.rs
ameykusurkar/rustyPixelGameEngine
719a0aae76da658c879756456c820b8298d7f237
[ "BSD-3-Clause" ]
6
2020-03-28T22:13:16.000Z
2020-06-01T06:57:58.000Z
src/gfx3d/pipeline.rs
ameykusurkar/rustyPixelGameEngine
719a0aae76da658c879756456c820b8298d7f237
[ "BSD-3-Clause" ]
8
2020-01-25T15:06:23.000Z
2020-09-02T17:42:04.000Z
use crate::color::Color; use crate::gfx3d::plane::Plane; use crate::gfx3d::vec4d::Vec4d; use crate::{PGE}; use crate::gfx3d::triangle::Triangle; use crate::Sprite; use super::vec3d::Vec3d; use super::mat4x4::Mat4x4; use std::cmp::{max, min}; pub enum RenderOptions { Wire, Flat, Textured, } pub enum CullDirection { Cw, Ccw } pub struct Pipeline { proj: Mat4x4, view: Mat4x4, world: Mat4x4, texture: Sprite, view_x: f32, view_y: f32, view_w: f32, view_h: f32, near: f32, depth_buffer: Vec<f32>, } impl Pipeline { pub fn new(width: usize, height: usize) -> Self { Pipeline { proj: Mat4x4::make_identity(), view: Mat4x4::make_identity(), world: Mat4x4::make_identity(), texture: Sprite::new(0, 0), view_x: 0.0, view_y: 0.0, view_w: 0.0, view_h: 0.0, near: 0.0, depth_buffer: vec![0.0; width * height], } } pub fn set_projection(&mut self, fov_degrees: f32, aspect_ratio: f32, near: f32, far: f32, left: f32, top: f32, width: f32, height: f32) { self.proj = Mat4x4::make_projection(fov_degrees, aspect_ratio, near, far); self.view_x = left; self.view_y = top; self.view_w = width; self.view_h = height; self.near = near; } pub fn set_camera(&mut self, pos: Vec3d, look_at: Vec3d, up: Vec3d) { let t = Mat4x4::make_point_at(pos, look_at, up); self.view = t.inverse(); } pub fn set_transform(&mut self, transform: Mat4x4) { self.world = transform; } pub fn set_texture(&mut self, texture: &Sprite) { self.texture = texture.clone(); } pub fn render(&mut self, pge: &mut PGE, triangles: &Vec<Triangle>, tex: &Sprite) { // flags: RenderOptions, cull_dir: CullDirection) { #[allow(unused_variables)] let mut tri_count = 0; let world_view = self.world * self.view; // Process Triangles for tri in triangles { let mut tri_transformed = Triangle::new(); tri_transformed.col = tri.col; // Just copy through texture coordinates tri_transformed.t = tri.t; // Transform Triangle from object into projected space tri_transformed.p[0] = world_view * tri.p[0]; tri_transformed.p[1] = world_view * tri.p[1]; tri_transformed.p[2] = world_view * tri.p[2]; // Calculate Triangle Normal in WorldView Space let line_1 = tri_transformed.p[1] - tri_transformed.p[0]; let line_2 = tri_transformed.p[2] - tri_transformed.p[0]; let tri_world_normal = line_1.cross(&line_2).norm(); // Cull triangles that face away from viewer // Clockwise only for now if tri_world_normal.dot(&tri_transformed.p[0]) > 0.0 { continue; } // Clip triangle against near plane let near_clipped_tris = tri_transformed.clip_against_plane(&Plane { position: Vec4d{x: 0.0, y:0.0, z:self.near, w:1.0}, normal: Vec4d{x: 0.0, y:0.0, z:1.0, w:1.0} }); for near_tri in near_clipped_tris { let mut tri_projected = near_tri; tri_projected.col = near_tri.col; // Project new triangle tri_projected.p[0] = self.proj * near_tri.p[0]; tri_projected.p[1] = self.proj * near_tri.p[1]; tri_projected.p[2] = self.proj * near_tri.p[2]; // Apply Projection to Verts tri_projected.p[0] /= tri_projected.p[0].w; tri_projected.p[1] /= tri_projected.p[1].w; tri_projected.p[2] /= tri_projected.p[2].w; // Apply Projection to Tex coords tri_projected.t[0].x /= tri_projected.p[0].w; tri_projected.t[1].x /= tri_projected.p[1].w; tri_projected.t[2].x /= tri_projected.p[2].w; tri_projected.t[0].y /= tri_projected.p[0].w; tri_projected.t[1].y /= tri_projected.p[1].w; tri_projected.t[2].y /= tri_projected.p[2].w; tri_projected.t[0].z = 1.0 / tri_projected.p[0].w; tri_projected.t[1].z = 1.0 / tri_projected.p[1].w; tri_projected.t[2].z = 1.0 / tri_projected.p[2].w; // Clip against viewport in screen space // Clip triangles against all four screen edges, this could yield // a bunch of triangles, so create a queue that we traverse to // ensure we only test new triangles generated against planes // Add initial triangle let mut view_clipped_tris = vec!(tri_projected); for p in 0..4 { if let Some(tri_to_clip) = view_clipped_tris.pop() { // Clip it against a plane. We only need to test each // subsequent plane, against subsequent new triangles // as all triangles after a plane clip are guaranteed // to lie on the inside of the plane. I like how this // comment is almost completely and utterly justified let clipped = match p { 0 => { tri_to_clip.clip_against_plane(&Plane { position: Vec4d{x: 0.0, y:-1.0, z:0.0, w:1.0}, normal: Vec4d{x: 0.0, y:1.0, z:0.0, w:1.0} }) }, 1 => { tri_to_clip.clip_against_plane(&Plane { position: Vec4d{x: 0.0, y:1.0, z:0.0, w:1.0}, normal: Vec4d{x: 0.0, y:-1.0, z:0.0, w:1.0} }) }, 2 => { tri_to_clip.clip_against_plane(&Plane { position: Vec4d{x: 1.0, y:0.0, z:0.0, w:1.0}, normal: Vec4d{x: -1.0, y:0.0, z:0.0, w:1.0} }) }, 3 => { tri_to_clip.clip_against_plane(&Plane { position: Vec4d{x: -1.0, y:0.0, z:0.0, w:1.0}, normal: Vec4d{x: 1.0, y:0.0, z:0.0, w:1.0} }) }, _ => { panic!() } }; for t in clipped { view_clipped_tris.push(t); } } } for mut tri_raster in view_clipped_tris { // Scale to viewport tri_raster.col = tri_projected.col; let mut offset_view = Vec4d { x:1.0,y:1.0,z:0.0, w:1.0 }; tri_raster.p[0] += offset_view; tri_raster.p[1] += offset_view; tri_raster.p[2] += offset_view; tri_raster.p[0].x *= 0.5 * self.view_w; tri_raster.p[0].y *= 0.5 * self.view_h; tri_raster.p[1].x *= 0.5 * self.view_w; tri_raster.p[1].y *= 0.5 * self.view_h; tri_raster.p[2].x *= 0.5 * self.view_w; tri_raster.p[2].y *= 0.5 * self.view_h; offset_view = Vec4d { x:self.view_x, y:self.view_y,z:0.0, w:1.0 }; tri_raster.p[0] += offset_view; tri_raster.p[1] += offset_view; tri_raster.p[2] += offset_view; /*pge.fill_triangle(tri_raster.p[0].x as i32, tri_raster.p[0].y as i32, tri_raster.p[1].x as i32, tri_raster.p[1].y as i32, tri_raster.p[2].x as i32, tri_raster.p[2].y as i32, &tri_raster.col);*/ //tri_raster.draw_tex(pge, &tex); //self.textured_triangle(pge, tri_raster.p[0].x as i32, tri_raster.p[0].y as i32, tri_raster.t[0].x, tri_raster.t[0].y, tri_raster.t[0].z, // tri_raster.p[1].x as i32, tri_raster.p[1].y as i32, tri_raster.t[1].x, tri_raster.t[1].y, tri_raster.t[1].z, // tri_raster.p[2].x as i32, tri_raster.p[2].y as i32, tri_raster.t[2].x, tri_raster.t[2].y, tri_raster.t[2].z, // &tex); self.render_triangle_texture(pge, &tri_raster.p[0], &tri_raster.p[1], &tri_raster.p[2], &tri_raster.t[0], &tri_raster.t[1], &tri_raster.t[2], &tex); tri_count += 1; /*pge.draw_triangle(tri_raster.p[0].x as i32, tri_raster.p[0].y as i32, tri_raster.p[1].x as i32, tri_raster.p[1].y as i32, tri_raster.p[2].x as i32, tri_raster.p[2].y as i32, &Pixel::rgb(255, 255, 255));*/ } } } } // c1-c3 is the color for each point pub fn shaded_textured_triangle(&mut self, pge: &mut PGE, mut x1: i32, mut y1: i32, mut u1: f32, mut v1: f32, mut w1: f32, mut c1: Color, mut x2: i32, mut y2: i32, mut u2: f32, mut v2: f32, mut w2: f32, mut c2: Color, mut x3: i32, mut y3: i32, mut u3: f32, mut v3: f32, mut w3: f32, mut c3: Color, tex: &Sprite) { if y2 < y1 { std::mem::swap(&mut y1, &mut y2); std::mem::swap(&mut x1, &mut x2); std::mem::swap(&mut u1, &mut u2); std::mem::swap(&mut v1, &mut v2); std::mem::swap(&mut w1, &mut w2); std::mem::swap(&mut c1, &mut c2); } if y3 < y1 { std::mem::swap(&mut y1, &mut y3); std::mem::swap(&mut x1, &mut x3); std::mem::swap(&mut u1, &mut u3); std::mem::swap(&mut v1, &mut v3); std::mem::swap(&mut w1, &mut w3); std::mem::swap(&mut c1, &mut c3); } if y3 < y2 { std::mem::swap(&mut y2, &mut y3); std::mem::swap(&mut x2, &mut x3); std::mem::swap(&mut u2, &mut u3); std::mem::swap(&mut v2, &mut v3); std::mem::swap(&mut w2, &mut w3); std::mem::swap(&mut c2, &mut c3); } let mut dy1 = y2 - y1; let mut dx1 = x2 - x1; let mut dv1 = v2 - v1; let mut du1 = u2 - u1; let mut dw1 = w2 - w1; let mut _dc1 = c2 - c1; let dy2 = y3 - y1; let dx2 = x3 - x1; let dv2 = v3 - v1; let du2 = u3 - u1; let dw2 = w3 - w1; let dc2 = c3 - c1; let mut tex_u: f32; let mut tex_v: f32; let mut tex_w: f32; let mut _col_r: f32; let mut _col_g: f32; let mut _col_b: f32; let mut _col_a: f32; let mut dax_step = 0.0; let mut du1_step = 0.0; let mut du2_step = 0.0; let mut dw1_step = 0.0; let mut dc1r_step = 0.0; let mut dc1g_step = 0.0; let mut dc1b_step = 0.0; let mut dc1a_step = 0.0; let mut dbx_step = 0.0; let mut dv1_step = 0.0; let mut dv2_step = 0.0; let mut dw2_step = 0.0; let mut dc2r_step = 0.0; let mut dc2g_step = 0.0; let mut dc2b_step = 0.0; let mut dc2a_step = 0.0; if dy1 > 0 { dax_step = dx1 as f32 / dy1.abs() as f32; du1_step = du1 / dy1.abs() as f32; dv1_step = dv1 / dy1.abs() as f32; dw1_step = dw1 / dy1.abs() as f32; dc1r_step = _dc1.r / dy1.abs() as f32; dc1g_step = _dc1.g / dy1.abs() as f32; dc1b_step = _dc1.b / dy1.abs() as f32; dc1a_step = _dc1.a / dy1.abs() as f32; } if dy2 > 0 { dbx_step = dx2 as f32 / dy2.abs() as f32; du2_step = du2 / dy2.abs() as f32; dv2_step = dv2 / dy2.abs() as f32; dw2_step = dw2 / dy2.abs() as f32; dc2r_step = dc2.r / dy2.abs() as f32; dc2g_step = dc2.g / dy2.abs() as f32; dc2b_step = dc2.b / dy2.abs() as f32; dc2a_step = dc2.a / dy2.abs() as f32; } if dy1 > 0 { for i in y1..y2 { let mut ax = x1 + ((i - y1) as f32 * dax_step) as i32; let mut bx = x1 + ((i - y1) as f32 * dbx_step) as i32; let mut tex_su = u1 + (i - y1) as f32 * du1_step; let mut tex_sv = v1 + (i - y1) as f32 * dv1_step; let mut tex_sw = w1 + (i - y1) as f32 * dw1_step; let mut col_sr = c1.r + (i - y1) as f32 * dc1r_step; let mut col_sg = c1.g + (i - y1) as f32 * dc1g_step; let mut col_sb = c1.b + (i - y1) as f32 * dc1b_step; let mut col_sa = c1.a + (i - y1) as f32 * dc1a_step; let mut tex_eu = u1 + (i - y1) as f32 * du2_step; let mut tex_ev = v1 + (i - y1) as f32 * dv2_step; let mut tex_ew = w1 + (i - y1) as f32 * dw2_step; let mut col_er = c1.r + (i - y1) as f32 * dc2r_step; let mut col_eg = c1.g + (i - y1) as f32 * dc2g_step; let mut col_eb = c1.b + (i - y1) as f32 * dc2b_step; let mut col_ea = c1.a + (i - y1) as f32 * dc2a_step; if ax > bx { std::mem::swap(&mut ax, &mut bx); std::mem::swap(&mut tex_su, &mut tex_eu); std::mem::swap(&mut tex_sv, &mut tex_ev); std::mem::swap(&mut tex_sw, &mut tex_ew); std::mem::swap(&mut col_sr, &mut col_er); std::mem::swap(&mut col_sg, &mut col_eg); std::mem::swap(&mut col_sb, &mut col_eb); std::mem::swap(&mut col_sa, &mut col_ea); } let tstep = 1.0 / (bx - ax) as f32; let mut t = 0.0; for j in ax..bx { tex_u = (1.0 - t) * tex_su + t * tex_eu; tex_v = (1.0 - t) * tex_sv + t * tex_ev; tex_w = (1.0 - t) * tex_sw + t * tex_ew; _col_r = (1.0 - t) * col_sr + t * col_er; _col_g = (1.0 - t) * col_sg + t * col_eg; _col_b = (1.0 - t) * col_sb + t * col_eb; _col_a = (1.0 - t) * col_sa + t * col_ea; // TODO - use interpolated color!!!! if tex_w > self.depth_buffer[(i * pge.screen_width + j) as usize] { pge.draw(j, i, &tex.sample(tex_u / tex_w, tex_v / tex_w)); self.depth_buffer[(i * pge.screen_width + j) as usize] = tex_w; } t += tstep; } } } dy1 = y3 - y2; dx1 = x3 - x2; dv1 = v3 - v2; du1 = u3 - u2; dw1 = w3 - w2; _dc1 = c3 - c2; if dy1 > 0 { dax_step = dx1 as f32 / dy1.abs() as f32; } if dy2 > 0 { dbx_step = dx2 as f32 / dy2.abs() as f32; } du1_step = 0.0; dv1_step = 0.0; if dy1 > 0 { du1_step = du1 / dy1.abs() as f32; dv1_step = dv1 / dy1.abs() as f32; dw1_step = dw1 / dy1.abs() as f32; } if dy1 > 0 { for i in y2..y3 { let mut ax = x2 + ((i - y2) as f32 * dax_step) as i32; let mut bx = x1 + ((i - y1) as f32 * dbx_step) as i32; let mut tex_su = u2 + (i - y2) as f32 * du1_step; let mut tex_sv = v2 + (i - y2) as f32 * dv1_step; let mut tex_sw = w2 + (i - y2) as f32 * dw1_step; let mut col_sr = c2.r + (i - y2) as f32 * dc1r_step; let mut col_sg = c2.g + (i - y2) as f32 * dc1g_step; let mut col_sb = c2.b + (i - y2) as f32 * dc1b_step; let mut col_sa = c2.a + (i - y2) as f32 * dc1a_step; let mut tex_eu = u1 + (i - y1) as f32 * du2_step; let mut tex_ev = v1 + (i - y1) as f32 * dv2_step; let mut tex_ew = w1 + (i - y1) as f32 * dw2_step; let mut col_er = c1.r + (i - y1) as f32 * dc2r_step; let mut col_eg = c1.g + (i - y1) as f32 * dc2g_step; let mut col_eb = c1.b + (i - y1) as f32 * dc2b_step; let mut col_ea = c1.a + (i - y1) as f32 * dc2a_step; if ax > bx { std::mem::swap(&mut ax, &mut bx); std::mem::swap(&mut tex_su, &mut tex_eu); std::mem::swap(&mut tex_sv, &mut tex_ev); std::mem::swap(&mut tex_sw, &mut tex_ew); std::mem::swap(&mut col_sr, &mut col_er); std::mem::swap(&mut col_sg, &mut col_eg); std::mem::swap(&mut col_sb, &mut col_eb); std::mem::swap(&mut col_sa, &mut col_ea); } let tstep = 1.0 / (bx - ax) as f32; let mut t = 0.0; for j in ax..bx { tex_u = (1.0 - t) * tex_su + t * tex_eu; tex_v = (1.0 - t) * tex_sv + t * tex_ev; tex_w = (1.0 - t) * tex_sw + t * tex_ew; _col_r = (1.0 - t) * col_sr + t * col_er; _col_g = (1.0 - t) * col_sg + t * col_eg; _col_b = (1.0 - t) * col_sb + t * col_eb; _col_a = (1.0 - t) * col_sa + t * col_ea; // TODO - use interpolated color!!!! if tex_w > self.depth_buffer[(i * pge.screen_width + j) as usize] { pge.draw(j, i, &tex.sample(tex_u / tex_w, tex_v / tex_w)); self.depth_buffer[(i * pge.screen_width + j) as usize] = tex_w; } t += tstep; } } } } pub fn render_triangle_texture(&mut self, pge: &mut PGE, a: &Vec4d, b: &Vec4d, c: &Vec4d, auv: &Vec3d, buv: &Vec3d, cuv: &Vec3d, tex: &Sprite) { // algorithm only fills counter clockwise triangles, so swap as needed // For a triangle A B C, you can find the winding by computing the cross product (B - A) x (C - A). For 2d tri's, with z=0, it will only have a z component. // To give all the same winding, swap vertices C and B if this z component is negative. let cross = (b.y - a.y) * (c.x - b.x) - (b.x - a.x) * (c.y - b.y); let v0 = a; let mut v1 = b; let mut v2 = c; let v0uv = auv; let mut v1uv = buv; let mut v2uv = cuv; if cross > 0.0 { std::mem::swap(&mut v1, &mut v2); std::mem::swap(&mut v1uv, &mut v2uv); } // use fixed-point only for X and Y. Avoid work for Z and W. let fx_pt_x0 = (v0.x + 0.5) as i32; let fx_pt_x1 = (v1.x + 0.5) as i32; let fx_pt_x2 = (v2.x + 0.5) as i32; let fx_pt_y0 = (v0.y + 0.5) as i32; let fx_pt_y1 = (v1.y + 0.5) as i32; let fx_pt_y2 = (v2.y + 0.5) as i32; let z0 = v0.z; let mut z1 = v1.z; let mut z2 = v2.z; // texture space let t0u = v0uv.x; let mut t1u = v1uv.x; let mut t2u = v2uv.x; let t0v = v0uv.y; let mut t1v = v1uv.y; let mut t2v = v2uv.y; let t0z = v0uv.z; let mut t1z = v1uv.z; let mut t2z = v2uv.z; // Fab(x, y) = Ax + By + C = 0 // Fab(x, y) = (ya - yb)x + (xb - xa)y + (xa * yb - xb * ya) = 0 // Compute A = (ya - yb) for the 3 line segments that make up each triangle let a0 = fx_pt_y1 - fx_pt_y2; let a1 = fx_pt_y2 - fx_pt_y0; let a2 = fx_pt_y0 - fx_pt_y1; // Compute B = (xb - xa) for the 3 line segments that make up each triangle let b0 = fx_pt_x2 - fx_pt_x1; let b1 = fx_pt_x0 - fx_pt_x2; let b2 = fx_pt_x1 - fx_pt_x0; // Compute C = (xa * yb - xb * ya) for the 3 line segments that make up each triangle let c0 = fx_pt_x1 * fx_pt_y2 - fx_pt_x2 * fx_pt_y1; let c1 = fx_pt_x2 * fx_pt_y0 - fx_pt_x0 * fx_pt_y2; let c2 = fx_pt_x0 * fx_pt_y1 - fx_pt_x1 * fx_pt_y0; // Determine edges let is_top_left = |v0: &Vec4d, v1: &Vec4d| -> bool { v0.y > v1.y }; // We follow fill rules and add a bias let bias0 = if is_top_left(v1, v2) { 0 } else { -1 }; let bias1 = if is_top_left(v2, v0) { 0 } else { -1 }; let bias2 = if is_top_left(v0, v1) { 0 } else { -1 }; // Compute triangle area let tri_area = (fx_pt_x1 - fx_pt_x0) * (fx_pt_y2 - fx_pt_y0) - (fx_pt_x0 - fx_pt_x2) * (fx_pt_y0 - fx_pt_y1); let one_over_tri_area = 1.0 / tri_area as f32; z1 = (z1 - z0) * one_over_tri_area; z2 = (z2 - z0) * one_over_tri_area; t1u = (t1u - t0u) * one_over_tri_area; t2u = (t2u - t0u) * one_over_tri_area; t1v = (t1v - t0v) * one_over_tri_area; t2v = (t2v - t0v) * one_over_tri_area; t1z = (t1z - t0z) * one_over_tri_area; t2z = (t2z - t0z) * one_over_tri_area; // Use bounding box traversal strategy to determine which pixels to rasterize let start_x = max(min(min(fx_pt_x0, fx_pt_x1), fx_pt_x2), 0);// & 0xFFFFFFFE; let end_x = min(max(max(fx_pt_x0, fx_pt_x1), fx_pt_x2), pge.screen_width); let start_y = max(min(min(fx_pt_y0, fx_pt_y1), fx_pt_y2), 0);// & 0xFFFFFFFE; let end_y = min(max(max(fx_pt_y0, fx_pt_y1), fx_pt_y2), pge.screen_height); let mut row_idx = start_y * pge.screen_width + start_x; let col = start_x; let mut row = start_y; // Incrementally compute Fab(x, y) for all the pixels inside the bounding box formed by (start_x, end_x) and (start_y, end_y) let mut alpha0 = (a0 * col) + (b0 * row) + c0 + bias0; let mut beta0 = (a1 * col) + (b1 * row) + c1 + bias1; let mut gama0 = (a2 * col) + (b2 * row) + c2 + bias2; let zx = a1 as f32 * z1 + a2 as f32 * z2; let tux = a1 as f32 * t1u + a2 as f32 * t2u; let tvx = a1 as f32 * t1v + a2 as f32 * t2v; let tz = a1 as f32 * t1z + a2 as f32 * t2z; for _ in start_y..end_y { // Compute barycentric coordinates let mut index = row_idx; let mut alpha = alpha0; let mut beta = beta0; let mut gama = gama0; let mut depth = z0 + z1 * beta as f32 + z2 * gama as f32; let mut u = t0u + t1u * beta as f32 + t2u * gama as f32; let mut v = t0v + t1v * beta as f32 + t2v * gama as f32; let mut uv_z = t0z + t1z * beta as f32 + t2z * gama as f32; for _ in start_x..end_x { //Test Pixel inside triangle let mask = alpha | beta | gama; let previous_depth_value = self.depth_buffer[index as usize]; let merged_depth = depth.max(previous_depth_value); let finaldepth = if mask < 0 { previous_depth_value } else { merged_depth }; self.depth_buffer[index as usize] = finaldepth; if mask > 0 && previous_depth_value < finaldepth { let one_over_uv_z = 1.0 / uv_z; let sample = tex.sample(u * one_over_uv_z, v * one_over_uv_z); pge.draw_target[pge.current_draw_target].data[index as usize] = sample; } // inc per pixel index += 1; alpha += a0; beta += a1; gama += a2; depth += zx; u += tux; v += tvx; uv_z += tz; } // inc per row row += 1; row_idx += pge.screen_width; alpha0 += b0; beta0 += b1; gama0 += b2; } } pub fn textured_triangle(&mut self, pge: &mut PGE, mut x1: i32, mut y1: i32, mut u1: f32, mut v1: f32, mut w1: f32, mut x2: i32, mut y2: i32, mut u2: f32, mut v2: f32, mut w2: f32, mut x3: i32, mut y3: i32, mut u3: f32, mut v3: f32, mut w3: f32, tex: &Sprite) { if y2 < y1 { std::mem::swap(&mut y1, &mut y2); std::mem::swap(&mut x1, &mut x2); std::mem::swap(&mut u1, &mut u2); std::mem::swap(&mut v1, &mut v2); std::mem::swap(&mut w1, &mut w2); } if y3 < y1 { std::mem::swap(&mut y1, &mut y3); std::mem::swap(&mut x1, &mut x3); std::mem::swap(&mut u1, &mut u3); std::mem::swap(&mut v1, &mut v3); std::mem::swap(&mut w1, &mut w3); } if y3 < y2 { std::mem::swap(&mut y2, &mut y3); std::mem::swap(&mut x2, &mut x3); std::mem::swap(&mut u2, &mut u3); std::mem::swap(&mut v2, &mut v3); std::mem::swap(&mut w2, &mut w3); } let mut dy1 = y2 - y1; let mut dx1 = x2 - x1; let mut dv1 = v2 - v1; let mut du1 = u2 - u1; let mut dw1 = w2 - w1; let dy2 = y3 - y1; let dx2 = x3 - x1; let dv2 = v3 - v1; let du2 = u3 - u1; let dw2 = w3 - w1; let mut tex_u: f32; let mut tex_v: f32; let mut tex_w: f32; let mut dax_step = 0.0; let mut du1_step = 0.0; let mut du2_step = 0.0; let mut dw1_step = 0.0; let mut dbx_step = 0.0; let mut dv1_step = 0.0; let mut dv2_step = 0.0; let mut dw2_step = 0.0; if dy1 > 0 { dax_step = dx1 as f32 / dy1.abs() as f32; du1_step = du1 / dy1.abs() as f32; dv1_step = dv1 / dy1.abs() as f32; dw1_step = dw1 / dy1.abs() as f32; } if dy2 > 0 { du2_step = du2 / dy2.abs() as f32; dv2_step = dv2 / dy2.abs() as f32; dw2_step = dw2 / dy2.abs() as f32; dbx_step = dx2 as f32 / dy2.abs() as f32; } if dy1 > 0 { for i in y1..y2 { let mut ax = x1 + ((i - y1) as f32 * dax_step) as i32; let mut bx = x1 + ((i - y1) as f32 * dbx_step) as i32; let mut tex_su = u1 + (i - y1) as f32 * du1_step; let mut tex_sv = v1 + (i - y1) as f32 * dv1_step; let mut tex_sw = w1 + (i - y1) as f32 * dw1_step; let mut tex_eu = u1 + (i - y1) as f32 * du2_step; let mut tex_ev = v1 + (i - y1) as f32 * dv2_step; let mut tex_ew = w1 + (i - y1) as f32 * dw2_step; if ax > bx { std::mem::swap(&mut ax, &mut bx); std::mem::swap(&mut tex_su, &mut tex_eu); std::mem::swap(&mut tex_sv, &mut tex_ev); std::mem::swap(&mut tex_sw, &mut tex_ew); } let tstep = 1.0 / (bx - ax) as f32; let mut t = 0.0; for j in ax..bx { tex_u = (1.0 - t) * tex_su + t * tex_eu; tex_v = (1.0 - t) * tex_sv + t * tex_ev; tex_w = (1.0 - t) * tex_sw + t * tex_ew; let index = (i * pge.screen_width + j) as usize; if index < self.depth_buffer.len() { if tex_w > self.depth_buffer[index] { pge.draw(j, i, &tex.sample(tex_u / tex_w, tex_v / tex_w)); self.depth_buffer[index] = tex_w; } } t += tstep; } } } dy1 = y3 - y2; dx1 = x3 - x2; dv1 = v3 - v2; du1 = u3 - u2; dw1 = w3 - w2; if dy1 > 0 { dax_step = dx1 as f32 / dy1.abs() as f32; } if dy2 > 0 { dbx_step = dx2 as f32 / dy2.abs() as f32; } du1_step = 0.0; dv1_step = 0.0; if dy1 > 0 { du1_step = du1 / dy1.abs() as f32; dv1_step = dv1 / dy1.abs() as f32; dw1_step = dw1 / dy1.abs() as f32; } if dy1 > 0 { for i in y2..y3 { let mut ax = x2 + ((i - y2) as f32 * dax_step) as i32; let mut bx = x1 + ((i - y1) as f32 * dbx_step) as i32; let mut tex_su = u2 + (i - y2) as f32 * du1_step; let mut tex_sv = v2 + (i - y2) as f32 * dv1_step; let mut tex_sw = w2 + (i - y2) as f32 * dw1_step; let mut tex_eu = u1 + (i - y1) as f32 * du2_step; let mut tex_ev = v1 + (i - y1) as f32 * dv2_step; let mut tex_ew = w1 + (i - y1) as f32 * dw2_step; if ax > bx { std::mem::swap(&mut ax, &mut bx); std::mem::swap(&mut tex_su, &mut tex_eu); std::mem::swap(&mut tex_sv, &mut tex_ev); std::mem::swap(&mut tex_sw, &mut tex_ew); } let tstep = 1.0 / (bx - ax) as f32; let mut t = 0.0; for j in ax..bx { tex_u = (1.0 - t) * tex_su + t * tex_eu; tex_v = (1.0 - t) * tex_sv + t * tex_ev; tex_w = (1.0 - t) * tex_sw + t * tex_ew; let index = (i * pge.screen_width + j) as usize; if index < self.depth_buffer.len() { if tex_w > self.depth_buffer[index] { pge.draw(j, i, &tex.sample(tex_u / tex_w, tex_v / tex_w)); self.depth_buffer[index] = tex_w; } } t += tstep; } } } } pub fn clear_depth(&mut self) { // NOTE: sloooooooow!!!!! /* for y in 0..self.screen_height { for x in 0..self.screen_width { self.draw_target[self.current_draw_target].set_pixel(x as i32, y as i32, &p); } } */ // Much faster, but still might be slow? //self.draw_target[self.current_draw_target].clear(p.clone()); // Proper way, adds about 30 fps for i in self.depth_buffer.iter_mut() { *i = 0.0; } } }
37.149273
170
0.504872
dbb4555074af7a2ef7675856735400e17b6c6e1a
9,630
php
PHP
app/admin/controller/ActiveController.php
qianshuai09/ztx
61084cec7a23e5618211fa0c859c4cb46d0bd769
[ "Apache-2.0" ]
null
null
null
app/admin/controller/ActiveController.php
qianshuai09/ztx
61084cec7a23e5618211fa0c859c4cb46d0bd769
[ "Apache-2.0" ]
null
null
null
app/admin/controller/ActiveController.php
qianshuai09/ztx
61084cec7a23e5618211fa0c859c4cb46d0bd769
[ "Apache-2.0" ]
null
null
null
<?php namespace app\admin\controller; use app\admin\model\ActiveModel; use app\admin\model\StationModel; use cmf\controller\AdminBaseController; class ActiveController extends AdminBaseController { public function index(){ $activeModel = new ActiveModel(); $actvie = $activeModel->where('pcategory',1)->paginate(10); $this->assign("active",$actvie); $this->assign('page',$actvie->render()); return $this->fetch(); } public function edit(){ $id = $this->request->param('id'); $activeModel = new ActiveModel(); $actvie = $activeModel->where('pid',$id)->find(); $this->assign('result',$actvie); return $this->fetch(); } public function editPost(){ $data = $this->request->param(); $slidePostModel = new ActiveModel(); $result = $slidePostModel->save($data, ['pid' => $data['pid']]); if ($result === false) { $this->error($slidePostModel->getError()); } $this->success("保存成功!", url("active/index")); } public function job(){ $activeModel = new ActiveModel(); $actvie = $activeModel->where('pcategory',2)->paginate(10); $this->assign("active",$actvie); $this->assign('page',$actvie->render()); return $this->fetch(); } public function AddJob(){ return $this->fetch(); } public function editJob(){ $id = $this->request->param('id'); $activeModel = new ActiveModel(); $actvie = $activeModel->where('pid',$id)->find(); $this->assign('result',$actvie); return $this->fetch(); } public function editJobPost(){ $data = $this->request->param(); $slidePostModel = new ActiveModel(); $result = $slidePostModel->save($data, ['pid' => $data['pid']]); if ($result === false) { $this->error($slidePostModel->getError()); } $this->success("保存成功!", url("active/job")); } public function active(){ $activeModel = new ActiveModel(); $actvie = $activeModel->where('pcategory',3)->paginate(10); $this->assign("active",$actvie); $this->assign('page',$actvie->render()); return $this->fetch(); } public function add(){ return $this->fetch(); } public function addPost(){ if ($this->request->isPost()) { $data = $this->request->param(); $productModel = new ActiveModel(); $productModel->data([ 'pimg' => $data['pimg'], 'pname'=>$data['pname'], 'ptitle' => $data['ptitle'], 'pprice' => $data['pprice'], 'zanzhu' => $data['zanzhu'], 'starttime' => $data['starttime'], 'endtime' => $data['endtime'], 'pdetail'=>$data['pdetail'], 'pcategory'=>1, 'create_time'=>date('Y-m-d h:i:sa') ]); $result = $productModel->save(); if($result===false){ $this->error($productModel->getError()); }else{ $this->success("添加成功!",url('active/index')); } } } public function addactive(){ return $this->fetch(); } public function addactivePost(){ if ($this->request->isPost()) { $data = $this->request->param(); $productModel = new ActiveModel(); if (!empty($data['photo_urls'])) { $data['purl'] = []; foreach ($data['photo_urls'] as $key => $url) { $photoUrl = cmf_asset_relative_url($url); array_push($data['purl'], ["url" => $photoUrl]); } //将二维数组转换成字符串对象存入数据库 $pimges = json_encode($data['purl']); //从数据库中拿到字符串对象还原的函数是 unserialize() $productModel->data([ 'pimg' => $data['pimg'], 'pname'=>$data['pname'], 'ptitle' => $data['ptitle'], 'atime' => $data['atime'], 'alocation' => $data['alocation'], 'abeizhu' => $data['abeizhu'], 'pextend' => $pimges, 'pcategory'=>3, 'create_time'=>date('Y-m-d h:i:sa') ]); $result = $productModel->save(); if($result===false){ $this->error($productModel->getError()); }else{ $this->success("添加成功!",url('active/active')); } } } } public function editActivePost(){ if ($this->request->isPost()) { $data = $this->request->param(); $productModel = new ActiveModel(); if (!empty($data['photo_urls'])) { $data['purl'] = []; foreach ($data['photo_urls'] as $key => $url) { $photoUrl = cmf_asset_relative_url($url); array_push($data['purl'], ["url" => $photoUrl]); } //将二维数组转换成字符串对象存入数据库 $pimges = json_encode($data['purl']); //从数据库中拿到字符串对象还原的函数是 unserialize() $datas = [ 'pimg' => $data['pimg'], 'pname'=>$data['pname'], 'ptitle' => $data['ptitle'], 'atime' => $data['atime'], 'alocation' => $data['alocation'], 'abeizhu' => $data['abeizhu'], 'pextend' => $pimges, 'pcategory'=>3, ]; $result = $productModel->save($datas, ['pid' => $data['pid']]); if($result===false){ $this->error($productModel->getError()); }else{ $this->success("编辑成功!",url('active/active')); } } } } /* * 产品删除 * */ public function delete(){ $product_model = new ActiveModel(); $data = $this->request->param(); $result = $product_model->where(['pid'=>$data['id']])->delete(); if ($result) { $this->success(lang('DELETE_SUCCESS')); } else { $this->error(lang('DELETE_FAILED')); } } public function activeedit(){ $id = $this->request->param('id', 0, 'intval'); $productModel = new ActiveModel(); $product = $productModel->where('pid',$id)->find(); $pimgs = $product['pextend']; $this->assign('photo',$pimgs); $this->assign('product',$product); return $this->fetch(); } public function Manager(){ $stationModel = new StationModel; $station = $stationModel ->alias("a") ->join('ztx_active b','a.mcate = b.pid') ->paginate(10); $this->assign('page',$station->render()); $this->assign('station',$station); return $this->fetch(); } public function AddStation(){ $activeModel = new ActiveModel(); $active = $activeModel->where('pcategory',2)->field('pid,pname')->select(); $this->assign("active",$active); return $this->fetch(); } public function AddStationPost(){ $data = $this->request->param(); $categoryModel = new StationModel(); $result = $categoryModel->save($data); if ($result === false) { $this->error($categoryModel->getError()); } $this->success("添加成功!", url("active/Manager")); } public function addJobPost(){ $data = $this->request->param(); $categoryModel = new ActiveModel(); $result = $categoryModel->save($data); if ($result === false) { $this->error($categoryModel->getError()); } $this->success("添加成功!", url("active/Job")); } public function deleteStation(){ $product_model = new stationModel(); $data = $this->request->param(); $result = $product_model->where(['mid'=>$data['id']])->delete(); if ($result) { $this->success(lang('DELETE_SUCCESS')); } else { $this->error(lang('DELETE_FAILED')); } } public function editstation(){ $id = $this->request->param('id'); $slidePostModel = new stationModel(); $activeModel = new ActiveModel(); $active = $activeModel->where('pcategory',2)->field('pid,pname')->select(); $result = $slidePostModel->where('mid', $id)->find(); $this->assign('result', $result); $this->assign('category',$active); return $this->fetch(); } public function EditStationPost(){ $data = $this->request->param(); $slidePostModel = new stationModel(); $result = $slidePostModel->save($data, ['mid' => $data['mid']]); if ($result === false) { $this->error($slidePostModel->getError()); } $this->success("保存成功!", url("active/Manager")); } }
32.315436
83
0.457736
ea82e5ef04ce544fe4d1976b4de19e36b8e8b58f
2,709
dart
Dart
src/constants.dart
jdw1996/pub-name-generator
bfc59848663525377d2c7ecdc7976febf7836030
[ "MIT" ]
null
null
null
src/constants.dart
jdw1996/pub-name-generator
bfc59848663525377d2c7ecdc7976febf7836030
[ "MIT" ]
null
null
null
src/constants.dart
jdw1996/pub-name-generator
bfc59848663525377d2c7ecdc7976febf7836030
[ "MIT" ]
null
null
null
// // Joseph Winters // Constants for generating pub names // Winter 2017 // import 'dart:collection'; List<String> ANIMALS_AND_PEOPLE = [ // People "Archer", "Baker", "Baron", "Boxer", "Brewer", "Carpenter", "Cobbler", "Cooper", "Fletcher", "Friar", "Haberdasher", "Jester", "King", "Knave", "Knight", "Lady", "Lord", "Maid", "Mason", "Queen", "Smith", "Squire", "Thief", "Wainwright", // Animals "Ape", "Badger", "Bantam", "Beagle", "Bear", "Boar", "Buck", "Bull", "Bulldog", "Cod", "Crab", "Crow", "Deer", "Doe", "Dog", "Dove", "Drake", "Duck", "Eagle", "Eel", "Elephant", "Ewe", "Falcon", "Faun", "Fish", "Fox", "Frog", "Gelding", "Goat", "Goose", "Gosling", "Hare", "Hart", "Hen", "Hog", "Horse", "Hound", "Lamb", "Leopard", "Lion", "Magpie", "Mare", "Mole", "Mouse", "Ostrich", "Owl", "Oyster", "Pheasant", "Pig", "Poodle", "Rabbit", "Ram", "Rat", "Raven", "Rooster", "Serpent", "Sheep", "Snake", "Sow", "Stag", "Stallion", "Steed", "Swan", "Swine", "Tabby", "Toad", "Trout", "Turtle", "Unicorn", "Viper", "Whale", "Wolf", // Mythical "Centaur", "Dragon", "Fawn", "Gnome", "Ogre", "Wizard", "Wyvern" ]; List<String> THINGS = [ "Ale", "Anchor", "Anvil", "Arrow", "Barrel", "Barrow", "Belt", "Boat", "Boot", "Bowl", "Brick", "Bristle", "Bucket", "Bugle", "Candle", "Cannon", "Cap", "Carriage", "Cart", "Castle", "Chimney", "Cloak", "Cloud", "Club", "Coach", "Compass", "Crate", "Crown", "Dagger", "Diamond", "Feather", "Fiddle", "Hammer", "Harp", "Hearth", "Ingot", "Iron", "Jig", "Keg", "Knife", "Lager", "Loaf", "Nettle", "Oar", "Oat", "Orb", "Pearl", "Pickle", "Pie", "Pint", "Pipe", "Pistol", "Quill", "Rifle", "Rigging", "Rope", "Rose", "Rye", "Sceptre", "Sextant", "Shovel", "Shrub", "Spear", "Spindle", "Stocking", "Stone", "Stout", "Stove", "Sword", "Tartan", "Thistle", "Tower", "Trumpet", "Turret", "Wheel", "Whistle" ]..addAll(ANIMALS_AND_PEOPLE); List<String> ADJECTIVES = [ "Ailing", "Blue", "Clever", "Comely", "Cowardly", "Craven", "Dancing", "Dark", "Drunken", "Fiery", "Fighting", "Filthy", "Golden", "Green", "Grey", "Jolly", "Jousting", "Jumping", "Merchant", "Mounted", "Nimble", "Old", "Orange", "Plump", "Ragged", "Red", "Silver", "Slippered", "Slippery", "Sly", "Sour", "Speckled", "Tin", "Ugly", "Violet", "Wailing", "Wild", "Yellow" ];
11.43038
37
0.487634
c48cfba9d42cfb4716984d276820d78152cc8c38
10,864
cpp
C++
src/megaobd.cpp
ConnorRigby/megaobd
b1434444991e512237a81a54ee39f87fc3dd063d
[ "MIT" ]
null
null
null
src/megaobd.cpp
ConnorRigby/megaobd
b1434444991e512237a81a54ee39f87fc3dd063d
[ "MIT" ]
null
null
null
src/megaobd.cpp
ConnorRigby/megaobd
b1434444991e512237a81a54ee39f87fc3dd063d
[ "MIT" ]
1
2021-04-16T09:56:13.000Z
2021-04-16T09:56:13.000Z
#include "OBD9141sim.h" #include <AltSoftSerial.h> #include <CRC32.h> // OBD constants #define OBD_TX_PIN 9 #define OBD_RX_PIN 8 AltSoftSerial OBD_SERIAL; OBD9141sim OBD; CRC32 CRC; // Megasquirt Constants #define MEGASQUIRT_SERIAL Serial const uint8_t CMD_A_PAYLOAD[7] = {0x0, 0x1, 0x41, 0xD3, 0xD9, 0x9E, 0x8B}; enum STATUS_RECV_STATE { STATUS_RECV_SIZE_MSB, STATUS_RECV_SIZE_LSB, STATUS_RECV_STATUS, STATUS_RECV_DATA, STATUS_RECV_CRC32, STATUS_RECV_COMPLETE, STATUS_RECV_ERROR_CRC32 }; #define BUFFER_MAX_SIZE 0xFFFF /** Structure for holding state of a Megasquirt serial command. */ struct payload { STATUS_RECV_STATE state; uint16_t size; uint16_t read; uint32_t crc32; uint8_t status; uint8_t buffer[]; }; typedef enum status_field { STATUS_UINT8, STATUS_INT8, STATUS_UINT16, STATUS_INT16 } status_field_type_t; /** Structure for holding MegaSquirt A command */ struct status { uint16_t secs; uint16_t pw1; uint16_t pw2; uint16_t rpm; int16_t advance; // TODO(Connor) - Change this to a union uint8_t squirt; // TODO(Connor) - Change this to a union uint8_t engine; uint8_t afrtgt1raw; uint8_t afrtgt2raw; int16_t barometer; int16_t map; int16_t mat; int16_t clt; int16_t tps; uint16_t maf; uint16_t vss1; }; /** Structure for holding fault codes */ struct dtc { uint16_t fuel; uint8_t load; uint8_t clt; uint8_t shortTermTrim; uint8_t longTermTrim; uint16_t rpm; uint8_t vss; }; /** Used to store fault codes */ struct dtc faults[16]; /** Stores the most recent payload from Megasquirt */ struct payload msPayload; /** Stores the most recent result of the `A` command */ struct status msStatus; /** * Writes the A command to the serial port. */ void writeMegasquirtPayload(); /** * Process data in the msPayload struct */ void processMegasquirtPayload(); void realTimeValue(void*, size_t, status_field_type_t); void setup() { // Initialize OBD stuff OBD.begin(OBD_SERIAL, OBD_RX_PIN, OBD_TX_PIN); OBD.keep_init_state(true); OBD.initialize(); // Initialize MegaSquirt transport MEGASQUIRT_SERIAL.begin(115200); *msPayload.buffer = malloc(0xFFFF); writeMegasquirtPayload(); } void loop() { // Process MegaSquirt data while(MEGASQUIRT_SERIAL.available()) { switch(msPayload.state) { case STATUS_RECV_SIZE_MSB: msPayload.buffer[0] = MEGASQUIRT_SERIAL.read(); msPayload.state = STATUS_RECV_SIZE_LSB; break; case STATUS_RECV_SIZE_LSB: msPayload.size = (msPayload.buffer[0] << 8) | MEGASQUIRT_SERIAL.read(); msPayload.state = STATUS_RECV_STATUS; break; case STATUS_RECV_STATUS: msPayload.status = MEGASQUIRT_SERIAL.read(); msPayload.state = STATUS_RECV_DATA; break; case STATUS_RECV_DATA: msPayload.buffer[msPayload.read++] = MEGASQUIRT_SERIAL.read(); // Data read complete if(msPayload.read == msPayload.size) { msPayload.state = STATUS_RECV_CRC32; } break; case STATUS_RECV_CRC32: msPayload.buffer[msPayload.read++] = MEGASQUIRT_SERIAL.read(); // read 4 more bytes if(msPayload.read = (msPayload.size + 4)) { msPayload.crc32 = msPayload.buffer[msPayload.read-3] | (msPayload.buffer[msPayload.read-2] << 8) | (msPayload.buffer[msPayload.read-1] << 16) | (msPayload.buffer[msPayload.read] << 24); uint32_t calculated = CRC.calculate(msPayload.buffer, msPayload.size); // Check crc32 if(msPayload.crc32 == calculated) { msPayload.state = STATUS_RECV_COMPLETE; } else { msPayload.state = STATUS_RECV_ERROR_CRC32; } } break; case STATUS_RECV_COMPLETE: processMegasquirtPayload(); break; default: // Handle error here break; } } // Process OBD requests. // Only 8 answers can be sent at a time. OBD.loop(); /** Miata ECU supports the following type 1 PIDS: 0x00 - PIDs supported (01-20) [01, 03-07, 0C-11, 13-15, 1C, 20] 0x01 - Monitor status since DTCs cleared 0x03 - Fuel system status 0x04 - Calculated engine load value 0x05 - Engine coolant temperature 0x06 - Short term fuel % trim - Bank 1 0x07 - Long term fuel % trim - Bank 1 0x0C - Engine RPM 0x0D - Vehicle speed 0x0E - Timing advance 0x0F - Intake air temperature 0x10 - MAF air flow rate 0x11 - Throttle position 0x13 - Oxygen sensors present 0x14 - Bank 1, Sensor 1: O2S Voltage, Short term fuel trim 0x15 - Bank 1, Sensor 2: O2S Voltage, Short term fuel trim 0x1C - OBD standards this vehicle conforms to 0x20 - PIDs supported (21-40) 0x21 - Distance traveled with MIL on */ // Helper vars uint8_t a; uint8_t b; // Supported PIDS: [01, 03-07, 0C-11, 13-15, 1C, 20] // 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F 10 11 12 13 14 15 16 17 18 19 1A 1B 1C 1D 1E 1F 20 // 1 0 1 1 1 1 1 0 0 0 0 1 1 1 1 1 1 0 1 1 1 0 0 0 0 0 0 1 0 0 0 1 // 10111110000111111011100000010001 OBD.setAnswer(0x01, 0x00, 32, 0b10111110000111111011100000010001); // Note that test availability is indicated by set (1) bit and completeness is indicated by reset (0) bit. // ByteA: MIL + number of active codes // ByteB: Spark mode and tests available/complete // ByteC: CARB tests available // ByteD: CARB tests complete OBD.setAnswer(0x01, 0x01, 32, 0b0000000000000111111111110000); // Fuel System status // Should be built from the `msStatus.squirt` // OBD.setAnswer(0x01, 0x03, ); // Engine status // Should be built from the `msStatus.engine` // OBD.setAnswer(0x01, 0x04, ); // Coolant // This may need to be converted to C? OBD.setAnswer(0x01, 0x05, (uint8_t)(msStatus.clt + 40)); // Short term fuel trim // OBD.setAnswer(0x01, 0x06, (uint8_t)); // Long term fuel trim // OBD.setAnswer(0x01, 0x07, (uint8_t)); // Engine RPM a = msStatus.rpm & 0xFF; b = msStatus.rpm >> 8; uint16_t rpm = (256 * a + b) / 4; OBD.setAnswer(0x01, 0x0C, (uint16_t)rpm); // VSS // OBD.setAnswer(0x01, 0x0D, (uint8_t) ); // Every 8 answers. OBD.loop(); // Advance uint8_t advance = (msStatus.advance / 2) - 64; OBD.setAnswer(0x01, 0x0E, (uint8_t)advance); // IAT (may need to convert to C?) OBD.setAnswer(0x01, 0x0F, (uint8_t)(msStatus.mat - 40)); // MAF a = msStatus.maf & 0xFF; b = msStatus.maf >> 8; uint16_t maf = (256 * a + b) / 100; OBD.setAnswer(0x01, 0x10, (uint16_t)maf); // TPS uint8_t tps = (100/255) * msStatus.tps; OBD.setAnswer(0x01, 0x11, (uint8_t)tps); // Number of O2 sensors // These bytes might be backwards, but the result is the same? OBD.setAnswer(0x01, 0x13, (uint8_t)0b11001100); // O2 Sensors (2 is not used) // TODO 0x14 second byte should be the same as pid 0x06 // TODO the first byte should be voltage of the sensor for both answers OBD.setAnswer(0x01, 0x14, (uint16_t)0x00FF); OBD.setAnswer(0x01, 0x15, (uint16_t)0x00FF); // OBD compliance // 0x01 = CARB OBD.setAnswer(0x01, 0x1C, (uint8_t)0x01); // Every 8 answers. OBD.loop(); // PIDs 21-40 // Miata only supports 21 OBD.setAnswer(0x01, 0x20, 32, 0b10000000000000000000000000000000); OBD.setAnswer(0x01, 0x21, (uint16_t)0); /** Miata ECU supports the following type 2 PIDS: 0x00 - PIDs supported (01-20) 0x02 - Freeze DTC 0x03 - Fuel system status 0x04 - Calculated engine load value 0x05 - Engine coolant temperature 0x06 - Short term fuel % trim - Bank 1 0x07 - Long term fuel % trim - Bank 1 0x0C - Engine RPM 0x0D - Vehicle speed */ // Supported PIDS: [01, 02, 03, 04, 05, 06, 07, 0C, 0D] OBD.setAnswer(0x02, 0x01, 32, 0b1111111100011000000000000000000); // OBD.setAnswer(0x02, 0x02); // OBD.setAnswer(0x02, 0x03) // OBD.setAnswer(0x02, 0x04) // OBD.setAnswer(0x02, 0x05) // OBD.setAnswer(0x02, 0x06) // Every 8 answers. OBD.loop(); // OBD.setAnswer(0x02, 0x07) // OBD.setAnswer(0x02, 0x0C) // OBD.setAnswer(0x02, 0x0D) // End loop with telling MegaSquirt we want another status. writeMegasquirtPayload(); } void processMegasquirtPayload() { switch(msPayload.status) { // Realtime data case 0x01: // This is a huge, ugly assign. // uint16_t msStatus.secs realTimeValue(&msStatus.secs, 0, STATUS_UINT16); // uint16_t msStatus.pw1; realTimeValue(&msStatus.pw1, 2, STATUS_UINT16); // uint16_t msStatus.pw2; realTimeValue(&msStatus.pw2, 4, STATUS_UINT16); // uint16_t msStatus.rpm; realTimeValue(&msStatus.rpm, 6, STATUS_UINT16); // int16_t msStatus.advance; realTimeValue(&msStatus.advance, 8, STATUS_INT16); // uint8_t msStatus.squirt; realTimeValue(&msStatus.squirt, 10, STATUS_UINT8); // uint8_t msStatus.engine; realTimeValue(&msStatus.engine, 11, STATUS_UINT8); // uint8_t msStatus.afrtgt1raw; // uint8_t msStatus.afrtgt2raw; // int16_t msStatus.barometer; realTimeValue(&msStatus.barometer, 16, STATUS_INT16); // int16_t msStatus.map; realTimeValue(&msStatus.map, 18, STATUS_INT16); // int16_t msStatus.mat; realTimeValue(&msStatus.mat, 20, STATUS_INT16); // int16_t msStatus.clt; realTimeValue(&msStatus.clt, 22, STATUS_INT16); // int16_t msStatus.tps; realTimeValue(&msStatus.tps, 24, STATUS_INT16); // uint16_t maf; realTimeValue(&msStatus.maf, 210, STATUS_UINT16); // uint16_t vss1; realTimeValue(&msStatus.vss1, 336, STATUS_INT16); break; default: // Unknown status break; } } void realTimeValue(void *valuePtr, size_t offset, status_field_type_t type) { switch(type) { case STATUS_UINT8: { uint8_t *fieldPtr = (uint8_t*)valuePtr; *fieldPtr = msPayload.buffer[offset]; break; } case STATUS_INT8: { int8_t *fieldPtr = (int8_t*)valuePtr; *fieldPtr = msPayload.buffer[offset]; break; } case STATUS_UINT16: { uint16_t *fieldPtr = (uint16_t*)valuePtr; *fieldPtr = (msPayload.buffer[offset] << 8) | msPayload.buffer[offset+1]; break; } case STATUS_INT16: { uint16_t tmp = (msPayload.buffer[offset] << 8) | msPayload.buffer[offset+1]; int16_t *fieldPtr = (int16_t*)valuePtr; *fieldPtr = (int16_t) tmp; break; } } } void writeMegasquirtPayload() { uint16_t i; for(i = 0; i < 7; i++) { MEGASQUIRT_SERIAL.write(CMD_A_PAYLOAD[i]); } // Reset state machine msPayload.state = STATUS_RECV_SIZE_MSB; msPayload.size = 0; msPayload.crc32 = 0; msPayload.read = 0; // Clear buffer for(i=0; i < BUFFER_MAX_SIZE; i++) { msPayload.buffer[i] = 0; } }
25.928401
195
0.657861
bd03a1fa3a8550e362a10ebace76466887940e6f
2,669
dart
Dart
lib/src/sorting/insertion.dart
dipu-bd/algorithms
6171a492ea53be892bded768c743ac5076488259
[ "BSD-3-Clause" ]
9
2021-12-07T21:03:40.000Z
2022-02-15T05:58:10.000Z
lib/src/sorting/insertion.dart
dipu-bd/algorithmic
6171a492ea53be892bded768c743ac5076488259
[ "BSD-3-Clause" ]
null
null
null
lib/src/sorting/insertion.dart
dipu-bd/algorithmic
6171a492ea53be892bded768c743ac5076488259
[ "BSD-3-Clause" ]
null
null
null
// Copyright (c) 2021, Sudipto Chandra // All rights reserved. Check LICENSE file for details. /// Sorts the [list] of numbers using the /// [insertion sort](https://en.wikipedia.org/wiki/Insertion_sort) algorithm. /// /// ## Parameters /// /// * [list] is any list of items to be sorted. /// * To perform partial sorting, you can specify the [begin] or [end]. /// * [begin] is the start index of the range to be sorted. /// * If [begin] is negative, range starts at the 0 /// * If [begin] is not below the length of the [list], range will be empty. /// * [end] is the final index if the range to be sorted. It is exclusive. /// * If [end] is above the length of the [list], it will be ignored. /// * If [end] is negative, the absolute value of it will be subtracted /// from the length of the [list] to determine where the range ends. /// * If [end] is not greater than the [begin], the range will be empty. /// * [compare] is a custom compare to order the list elements. /// If it is null and [list] items are not [Comparable], [TypeError] is thrown. /// /// ## Details /// /// The insertion sort algorithm sorts the [list] in an increasing order by virtually /// splitting it into two parts. Left part is ordered, the right part is unordered. /// In each iteration, it removes the first item from unordered part, and insert it /// into the ordered part maintaining the increasing order. /// /// ---------------------------------------------------------------- /// Complexity: Time `O(n^2)` | Space `O(1)` <br> /// Best Case: Time `O(n)` | Space `O(1)` void insertionSort<E>( List<E> list, { int? begin, int? end, Comparator<E>? compare, }) { int b, e; int n = list.length; // Find the range given the parameters. b = 0; e = n; if (begin != null && b < begin) { b = begin; } if (end != null && end < e) { e = end; if (e < 0) e += n; } if (compare == null) { insertionSortDefault(list, b, e); } else { insertionSortCustom(list, b, e, compare); } } /// sorts range `[b, e)` void insertionSortDefault<E>(List<E> list, int b, int e) { E tmp; int i, j; i = b + 1; while (i < e) { j = i; while (j > b && (list[j - 1] as Comparable).compareTo(list[j]) > 0) { tmp = list[j]; list[j] = list[j - 1]; list[j - 1] = tmp; j--; } i++; } } /// sorts range `[b, e)` void insertionSortCustom<E>(List<E> list, int b, int e, Comparator<E> compare) { E tmp; int i, j; i = b + 1; while (i < e) { j = i; while (j > b && compare(list[j - 1], list[j]) > 0) { tmp = list[j]; list[j] = list[j - 1]; list[j - 1] = tmp; j--; } i++; } }
29.01087
85
0.57662
e71bdba4656626ec50cda2f9a85c3873cb85b155
16,052
php
PHP
resources/views/admin/teacher_edit.blade.php
jeff-david/SMS
3fa20a4b3a9b8673395207875f63c0c763858b59
[ "MIT" ]
null
null
null
resources/views/admin/teacher_edit.blade.php
jeff-david/SMS
3fa20a4b3a9b8673395207875f63c0c763858b59
[ "MIT" ]
20
2021-03-10T07:32:43.000Z
2022-02-03T02:37:37.000Z
resources/views/admin/teacher_edit.blade.php
jeff-david/SMS
3fa20a4b3a9b8673395207875f63c0c763858b59
[ "MIT" ]
null
null
null
@extends('layout.admin') @section('content') <!-- PAGE CONTENT--> <div class="main-content"> <div class="section__content section__content--p30"> <div class="container-fluid"> <div class="row"> <div class="col-lg-12"> <div class="card" style="padding: 10px;margin-top: 45px;"> @if (Session::has('failed')) <div class="alert alert-danger alert-block"> <button type="button" class="close" data-dismiss="alert">×</button> <strong>{{ Session::get('failed') }}</strong> </div> @endif <div class="card-header"> <h2><small>Teacher Profile</small></h2> </div> <form action="{{route('admin.teacher_update',$teacher->id)}}" method="POST" novalidate="novalidate"> @csrf <div class="card-body"> <div class="card-title"> <h3><small>Teacher's Information</small></h3> </div> <div class="row"> <div class="col col-md-4"> <div class="form-group has-success"> <label for="profession" class="control-label mb-1"><small>Department</small></label> <select name="department" class="form-control"> <option value="" selected="selected">-------------Select Departments------------</option> <option value="1"@if($teacher->departments_id=='1') selected='selected' @endif>Aral-Pan</option> <option value="2"@if($teacher->departments_id=='2') selected='selected' @endif>Filipino</option> <option value="3"@if($teacher->departments_id=='3') selected='selected' @endif>Science</option> <option value="4"@if($teacher->departments_id=='4') selected='selected' @endif>English</option> <option value="5"@if($teacher->departments_id=='5') selected='selected' @endif>TVET</option> <option value="6"@if($teacher->departments_id=='6') selected='selected' @endif>CLE</option> <option value="7"@if($teacher->departments_id=='7') selected='selected' @endif>MUSIC</option> <option value="8"@if($teacher->departments_id=='8') selected='selected' @endif>P.E</option> <option value="9"@if($teacher->departments_id=='9') selected='selected' @endif>ARTS</option> <option value="10"@if($teacher->departments_id=='10') selected='selected' @endif>HEALTH</option> <option value="11"@if($teacher->departments_id=='11') selected='selected' @endif>MATH</option> <option value="12"@if($teacher->departments_id=='12') selected='selected' @endif>HOMEROOM</option> </select> <span class="text-danger">{{ $errors->first('department') }}</span> </div> </div> <div class="col col-md-4"> <div class="form-group has-success"> <label for="lrn" class="control-label mb-1"><small>Cell no:</small></label> <input id="cell_no" name="cell_no" type="text" class="form-control" value="{{old('cell_no',$teacher->cell_no)}}"> <span class="text-danger">{{ $errors->first('cell_no') }}</span> </div> </div> <div class="col col-md-4"> <div class="form-group has-success"> <label for="datetoday" class="control-label mb-1"><small>Register Date</small></label> <input id="register_date" name="register_date" type="date" class="form-control" value="{{old('register_date',$teacher->register_date)}}"> <span class="text-danger">{{ $errors->first('register_date') }}</span> </div> </div> </div> <div class="row"> <div class="col col-md-4"> <div class="form-group has-success"> <label for="lastname" class="control-label mb-1"><small>Last Name</small></label> <input id="slname" name="lastname" type="text" class="form-control" value="{{old('lastname',$teacher->lastname)}}"> <span class="text-danger">{{ $errors->first('lastname') }}</span> </div> </div> <div class=" col-md-4"> <div class="form-group has-success"> <label for="sfname" class="control-label mb-1"><small>First Name</small></label> <input id="sfname" name="firstname" type="text" class="form-control" value="{{old('firstname',$teacher->firstname)}}"> <span class="text-danger">{{ $errors->first('firstname') }}</span> </div> </div> <div class="col-md-4"> <div class="form-group has-success"> <label for="smname" class="control-label mb-1"><small>Middle Name</small></label> <input id="smname" name="middlename" type="text" class="form-control" value="{{old('middlename',$teacher->middlename)}}"> <span class="text-danger">{{ $errors->first('middlename') }}</span> </div> </div> </div> <div class="row"> <div class="col col-md-2"> <div class="form-group has-success"> <label for="gender" class="control-label mb-1"><small>Gender</small></label> <select name="gender" id="gender" class="form-control"> <option value="male"@if($teacher->gender=='male') selected='selected' @endif>Male</option> <option value="female"@if($teacher->gender =='female') selected='selected' @endif>Female</option> </select> <span class="text-danger">{{ $errors->first('gender') }}</span> </div> </div> <div class="col col-md-2"> <div class="form-group has-success"> <label for="age" class="control-label mb-1"><small>Age</small></label> <input id="age" name="age" type="number" class="form-control"value="{{old('age',$teacher->age)}}"> <span class="text-danger">{{ $errors->first('age') }}</span> </div> </div> <div class="col col-md-4"> <div class="form-group has-success"> <label for="birthDate" class="control-label mb-1"><small>Birth Date</small></label> <input id="birthDate" name="birthdate" type="date" class="form-control" value="{{old('birthdate',$teacher->birthdate)}}"> <span class="text-danger">{{ $errors->first('birthdate') }}</span> </div> </div> <div class="col col-md-4"> <div class="form-group has-success"> <label for="religion" class="control-label mb-1"><small>Religion</small></label> <input id="religion" name="religion" type="text" class="form-control" value="{{old('religion',$teacher->religion)}}"> <span class="text-danger">{{ $errors->first('religion') }}</span> </div> </div> </div> <div class="row"> <div class="col-md-6"> <div class="form-group has-success"> <label for="sAddress" class="control-label mb-1"><small>Street Address</small></label> <input id="sAddress" name="street_address" type="text" class="form-control" value="{{old('street_address',$teacher->street_address)}}"> <span class="text-danger">{{ $errors->first('street_address') }}</span> </div> </div> <div class="col col-md-3"> <div class="form-group has-success"> <label for="city" class="control-label mb-1"><small>City</small></label> <input id="city" name="city" type="text" class="form-control" value="{{old('city',$teacher->city)}}"> <span class="text-danger">{{ $errors->first('city') }}</span> </div> </div> <div class="col col-md-3"> <div class="form-group has-success"> <label for="province" class="control-label mb-1"><small>Province</small></label> <input id="province" name="province" type="text" class="form-control" value="{{old('province',$teacher->province)}}"> <span class="text-danger">{{ $errors->first('province') }}</span> </div> </div> </div> <div class="row"> <div class="col-md-8"> <div class="form-group has-success"> <label for="motherName" class="control-label mb-1"><small>School Graduate</small></label> <input id="school_graduated" name="school_graduated" type="text" class="form-control" value="{{old('school_graduated',$teacher->school_graduated)}}"> <span class="text-danger">{{ $errors->first('school_graduated') }}</span> </div> </div> <div class="col-md-4"> <div class="form-group has-success"> <label for="motherOccupation" class="control-label mb-1"><small>Date Graduated:</small></label> <input id="date_graduated" name="date_graduated" type="date" class="form-control" value="{{old('date_graduated',$teacher->date_graduated)}}"> <span class="text-danger">{{ $errors->first('date_graduated') }}</span> </div> </div> </div> <div class="row"> <div class="col-md-6"> <div class="form-group has-success"> <label for="username" class="control-label mb-1"><small>Username</small></label> <input id="username" name="username" type="text" class="form-control" value="{{old('username',$teacher->username)}}" readOnly> <span class="text-danger">{{ $errors->first('username') }}</span> </div> </div> <div class="col-md-6"> <div class="form-group has-success"> <label for="password" class="control-label mb-1"><small>Password</small></label> <input id="password" name="password" type="text" class="form-control" value="{{old('password',$teacher->password)}}" readOnly> <span class="text-danger">{{ $errors->first('password') }}</span> </div> </div> </div> <div class="text-center"> <input type="submit" class="btn btn-info mb-1" value="Save"/> </div> @if (Session::has('success')) <div class="alert alert-danger alert-block"> <button type="button" class="close" data-dismiss="alert">×</button> <strong>{{ Session::get('success') }}</strong> </div> @endif </form> </div> </div> </div> </div> </div> </div> <!-- PAGE CONTENT--> </div> @endsection
77.173077
193
0.363693
4561427f6cbf84141bfb75ac6f80af3466ec7c0f
2,671
py
Python
Study/RNN/mnist_rnn.py
Tim232/Python-Things
05f0f373a4cf298e70d9668c88a6e3a9d1cd8146
[ "MIT" ]
2
2020-12-05T07:42:55.000Z
2021-01-06T23:23:18.000Z
Study/RNN/mnist_rnn.py
Tim232/Python-Things
05f0f373a4cf298e70d9668c88a6e3a9d1cd8146
[ "MIT" ]
null
null
null
Study/RNN/mnist_rnn.py
Tim232/Python-Things
05f0f373a4cf298e70d9668c88a6e3a9d1cd8146
[ "MIT" ]
null
null
null
# 머신러닝 학습의 Hello World 와 같은 MNIST(손글씨 숫자 인식) 문제를 신경망으로 풀어봅니다. import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data mnist = input_data.read_data_sets("./mnist/data/", one_hot=True) ######### # 옵션 설정 ###### learning_rate = 0.001 total_epoch = 10 batch_size = 128 # RNN 은 순서가 있는 자료를 다루므로, # 한 번에 입력받는 갯수와, 총 몇 단계로 이루어져있는 데이터를 받을지를 설정해야합니다. # 이를 위해 가로 픽셀수를 n_input 으로, 세로 픽셀수를 입력 단계인 n_step 으로 설정하였습니다. n_input = 28 n_step = 28 n_hidden = 128 n_class = 10 ######### # 신경망 모델 구성 ###### X = tf.placeholder(tf.float32, [None, n_step, n_input]) Y = tf.placeholder(tf.float32, [None, n_class]) W = tf.Variable(tf.random_normal([n_hidden, n_class])) b = tf.Variable(tf.random_normal([n_class])) # RNN 에 학습에 사용할 셀을 생성합니다 # 다음 함수들을 사용하면 다른 구조의 셀로 간단하게 변경할 수 있습니다 # BasicRNNCell,BasicLSTMCell,GRUCell cell = tf.contrib.rnn.BasicRNNCell(n_hidden) # RNN 신경망을 생성합니다 # 원래는 다음과 같은 과정을 거쳐야 하지만 # states = tf.zeros(batch_size) # for i in range(n_step): # outputs, states = cell(X[[:, i]], states) # ... # 다음처럼 tf.nn.dynamic_rnn 함수를 사용하면 # CNN 의 tf.nn.conv2d 함수처럼 간단하게 RNN 신경망을 만들어줍니다. # 겁나 매직!! outputs, states = tf.nn.dynamic_rnn(cell, X, dtype=tf.float32) # 결과를 Y의 다음 형식과 바꿔야 하기 때문에 # Y : [batch_size, n_class] # outputs 의 형태를 이에 맞춰 변경해야합니다. # outputs : [batch_size, n_step, n_hidden] # -> [n_step, batch_size, n_hidden] # -> [batch_size, n_hidden] outputs = tf.transpose(outputs, [1, 0, 2]) outputs = outputs[-1] model = tf.matmul(outputs, W) + b cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=model, labels=Y)) optimizer = tf.train.AdamOptimizer(learning_rate).minimize(cost) ######### # 신경망 모델 학습 ###### sess = tf.Session() sess.run(tf.global_variables_initializer()) total_batch = int(mnist.train.num_examples/batch_size) for epoch in range(total_epoch): total_cost = 0 for i in range(total_batch): batch_xs, batch_ys = mnist.train.next_batch(batch_size) # X 데이터를 RNN 입력 데이터에 맞게 [batch_size, n_step, n_input] 형태로 변환합니다. batch_xs = batch_xs.reshape((batch_size, n_step, n_input)) _, cost_val = sess.run([optimizer, cost], feed_dict={X: batch_xs, Y: batch_ys}) total_cost += cost_val print('Epoch:', '%04d' % (epoch + 1), 'Avg. cost =', '{:.3f}'.format(total_cost / total_batch)) print('최적화 완료!') ######### # 결과 확인 ###### is_correct = tf.equal(tf.argmax(model, 1), tf.argmax(Y, 1)) accuracy = tf.reduce_mean(tf.cast(is_correct, tf.float32)) test_batch_size = len(mnist.test.images) test_xs = mnist.test.images.reshape(test_batch_size, n_step, n_input) test_ys = mnist.test.labels print('정확도:', sess.run(accuracy, feed_dict={X: test_xs, Y: test_ys}))
29.677778
99
0.687009
c21fb41a33686e08a5bba5b9b70cf3c3744e8e03
1,844
dart
Dart
lib/infrastructure/exercise/models/exercise_model.dart
VitoMinheere/power_progress
a8053af3a4ee53d41aaf048511fb247a98229a38
[ "MIT" ]
1
2021-01-03T11:10:34.000Z
2021-01-03T11:10:34.000Z
lib/infrastructure/exercise/models/exercise_model.dart
VitoMinheere/power_progress
a8053af3a4ee53d41aaf048511fb247a98229a38
[ "MIT" ]
null
null
null
lib/infrastructure/exercise/models/exercise_model.dart
VitoMinheere/power_progress
a8053af3a4ee53d41aaf048511fb247a98229a38
[ "MIT" ]
null
null
null
import 'package:flutter/foundation.dart'; import 'package:hive/hive.dart'; import '../../../domain/exercise/entities/exercise.dart'; import '../../../domain/exercise/entities/value_objects/exercise_name.dart'; import '../../../domain/exercise/entities/value_objects/incrementation.dart'; import '../../../domain/exercise/entities/value_objects/month.dart'; import '../../../domain/exercise/entities/value_objects/note.dart'; import '../../../domain/exercise/entities/value_objects/one_rm.dart'; import '../../../domain/exercise/entities/value_objects/week.dart'; part 'exercise_model.g.dart'; @HiveType(typeId: 0) class ExerciseModel { @HiveField(0) int id; @HiveField(1) double oneRm; @HiveField(2) String name; @HiveField(3) double incrementation; @HiveField(4) String note; @HiveField(5) int month; @HiveField(6) int nextWeekIndex; ExerciseModel({ @required this.id, @required this.oneRm, @required this.name, @required this.incrementation, @required this.month, @required this.nextWeekIndex, @required this.note, }); factory ExerciseModel.fromEntity(Exercise exercise) { return ExerciseModel( id: exercise.id, oneRm: exercise.oneRm.getOrCrash(), name: exercise.name.getOrCrash(), incrementation: exercise.incrementation.getOrCrash(), month: exercise.month.getOrCrash(), nextWeekIndex: exercise.nextWeek.getOrCrash().index, note: exercise.note?.getOrCrash(), ); } static Exercise toEntity(ExerciseModel model) { return Exercise( id: model.id, oneRm: OneRm(model.oneRm), name: ExerciseName(model.name), incrementation: Incrementation(model.incrementation), month: Month(model.month ?? 1), nextWeek: Week.parse(model.nextWeekIndex ?? 0), note: Note(model.note), ); } }
28.369231
77
0.688178
54b6c78c120fe152b1bbc7c1e47c4070e0e5a155
1,581
cpp
C++
src/cameraFast.cpp
Hengoo/BVHRaytracer
d911f06e1af88859a9c94926669f334a64c516eb
[ "MIT" ]
null
null
null
src/cameraFast.cpp
Hengoo/BVHRaytracer
d911f06e1af88859a9c94926669f334a64c516eb
[ "MIT" ]
null
null
null
src/cameraFast.cpp
Hengoo/BVHRaytracer
d911f06e1af88859a9c94926669f334a64c516eb
[ "MIT" ]
null
null
null
#include "cameraFast.h" CameraFast::CameraFast(std::string path, std::string name, std::string problem, std::string problemPrefix, int nonTemplateWorkGroupSize, bool saveDistance, bool wideRender, std::vector<glm::vec3>& positions, std::vector<glm::vec3>& lookCenters, size_t width, size_t height, glm::vec3 upward, float focalLength) :Camera(path, name, problem, nonTemplateWorkGroupSize, positions, lookCenters, width, height, upward, focalLength), problemPrefix(problemPrefix), saveDistance(saveDistance), wideRender(wideRender) { image.resize(height * width * 4); if (wideRender) { int timeSize = (height / nonTemplateWorkGroupSize) * (width / nonTemplateWorkGroupSize); timesRay.resize(timeSize); timesTriangles.resize(timeSize); } else { timesRay.resize(height * width); timesTriangles.resize(height * width); } } CameraFast::CameraFast(std::string path, std::string name, std::string problem, std::string problemPrefix, int nonTemplateWorkGroupSize, bool saveDistance, bool wideRender, std::vector<glm::mat4>& transforms, size_t width, size_t height, float focalLength) :Camera(path, name, problem, nonTemplateWorkGroupSize, transforms, width, height, focalLength), problemPrefix(problemPrefix), saveDistance(saveDistance), wideRender(wideRender) { image.resize(height * width * 4); if (wideRender) { int timeSize = (height / nonTemplateWorkGroupSize) * (width / nonTemplateWorkGroupSize); timesRay.resize(timeSize); timesTriangles.resize(timeSize); } else { timesRay.resize(height * width); timesTriangles.resize(height * width); } }
42.72973
197
0.764706
ef4ea688ae4fd6b1a7d7b812e8f59dd8ce3e0c72
154
php
PHP
app/Repositories/UserRepositoryInterface.php
LeChatSoeur/Blog3wa
f488baeb7ef27bf95a3b886db7ad86b8f4ddf23e
[ "MIT" ]
null
null
null
app/Repositories/UserRepositoryInterface.php
LeChatSoeur/Blog3wa
f488baeb7ef27bf95a3b886db7ad86b8f4ddf23e
[ "MIT" ]
null
null
null
app/Repositories/UserRepositoryInterface.php
LeChatSoeur/Blog3wa
f488baeb7ef27bf95a3b886db7ad86b8f4ddf23e
[ "MIT" ]
null
null
null
<?php namespace App\Repositories; interface UserRepositoryInterface { public function dob($request); public function save($request, $dob); }
11.846154
41
0.720779
405e395f02dd9d34831444efbcb31ef7331b7a9c
1,167
ts
TypeScript
src/pages/tagged-files/tagged-files.ts
SyShock/Meaning
4ba730629148e8f687b378082acd74d3a3890b6f
[ "MIT" ]
2
2018-01-31T21:07:24.000Z
2019-12-22T02:27:03.000Z
src/pages/tagged-files/tagged-files.ts
SyShock/Meaning
4ba730629148e8f687b378082acd74d3a3890b6f
[ "MIT" ]
1
2022-03-25T18:17:26.000Z
2022-03-25T18:17:26.000Z
src/pages/tagged-files/tagged-files.ts
SyShock/Meaning
4ba730629148e8f687b378082acd74d3a3890b6f
[ "MIT" ]
1
2018-08-09T10:03:47.000Z
2018-08-09T10:03:47.000Z
import { Component } from '@angular/core'; import { IonicPage, NavController, NavParams } from 'ionic-angular'; import { THROW_IF_NOT_FOUND } from '@angular/core/src/di/injector'; import { ExternFilesProvider } from '../../providers/extern-files/extern-files'; import { EventsProvider, EventNames } from '../../providers/events/events'; @IonicPage() @Component({ selector: 'page-tagged-files', templateUrl: 'tagged-files.html', }) export class TaggedFilesPage { files: Array<string> filteredFiles: Array<string> fileOpened: boolean = false; constructor( public navCtrl: NavController, public navParams: NavParams, private extFiles: ExternFilesProvider, private events: EventsProvider) { } ionViewDidLoad() { this.files = Array.from(this.navParams.get('filePaths')) } async openFile(fileName) { let ret = { content: null, isTemplate: false } this.fileOpened = true; ret.content = await this.extFiles.openFile(fileName, true, true) this.events.publish(EventNames.fileOpened, ret) this.navCtrl.pop() } ionViewWillLeave() { if (!this.fileOpened) this.events.publish(EventNames.menuToggled) } }
27.785714
80
0.711225
38cb6d4ebac3b6275db100f714b7d826cac31593
214
php
PHP
app/TypiCMS/Modules/Groups/lang/en/global.php
ltdat287/cms-lrv42
8d3841e64a54cbde49694a6c4b9d40650b944ee7
[ "MIT" ]
222
2015-01-02T12:06:04.000Z
2021-05-07T13:45:42.000Z
app/TypiCMS/Modules/Groups/lang/en/global.php
yayann/TypiCMS
898056f741d762cdce860f46f036a4e2b743a183
[ "MIT" ]
30
2015-01-17T11:33:05.000Z
2017-05-20T22:32:22.000Z
app/TypiCMS/Modules/Groups/lang/en/global.php
yayann/TypiCMS
898056f741d762cdce860f46f036a4e2b743a183
[ "MIT" ]
89
2015-01-11T01:00:53.000Z
2021-08-24T10:13:29.000Z
<?php return array( 'name' => 'groups', 'groups' => 'group|groups', 'New' => 'New group', 'Edit' => 'Edit group', 'Back' => 'Back to groups', 'Group permissions' => 'Group permissions', );
21.4
47
0.528037
fa54286fcc62fa3538bbf968e29a5b4093dfce47
8,310
cpp
C++
examples/fast_fourier_transform/test.cpp
drichmond/HOPS
9684c0c9ebe5511fe0c202219a0bcd51fbf61079
[ "BSD-3-Clause" ]
10
2018-10-03T09:19:48.000Z
2021-09-15T14:46:32.000Z
examples/fast_fourier_transform/test.cpp
drichmond/HOPS
9684c0c9ebe5511fe0c202219a0bcd51fbf61079
[ "BSD-3-Clause" ]
1
2019-09-24T17:38:25.000Z
2019-09-24T17:38:25.000Z
examples/fast_fourier_transform/test.cpp
drichmond/HOPS
9684c0c9ebe5511fe0c202219a0bcd51fbf61079
[ "BSD-3-Clause" ]
null
null
null
// ---------------------------------------------------------------------- // Copyright (c) 2018, The Regents of the University of California All // rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following // disclaimer in the documentation and/or other materials provided // with the distribution. // // * Neither the name of The Regents of the University of California // nor the names of its contributors may be used to endorse or // promote products derived from this software without specific // prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL REGENTS OF THE // UNIVERSITY OF CALIFORNIA BE LIABLE FOR ANY DIRECT, INDIRECT, // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, // BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS // OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND // ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR // TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE // USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH // DAMAGE. // ---------------------------------------------------------------------- #include <iostream> #include <complex> #include "utility.hpp" #include "fft.hpp" #ifdef BIT_ACCURATE #include "hls_math.h" #include "ap_fixed.h" #include "ap_int.h" #define DTYPE ap_fixed<32, 16, AP_RND> #else #define DTYPE float #endif #define LOG_LIST_LENGTH 4 #define LIST_LENGTH (1<<LOG_LIST_LENGTH) std::array<std::complex<DTYPE>, LIST_LENGTH> fft_loop_synth(std::array<std::complex<DTYPE>, LIST_LENGTH> const& IN){ #pragma HLS PIPELINE #pragma HLS ARRAY_PARTITION variable=IN._M_instance COMPLETE return loop::fft(IN); } std::array<std::complex<DTYPE>, LIST_LENGTH> bitreverse_loop_synth(std::array<std::complex<DTYPE>, LIST_LENGTH> const& IN){ #pragma HLS PIPELINE #pragma HLS ARRAY_PARTITION variable=IN._M_instance COMPLETE return loop::bitreverse(IN); } std::array<std::complex<DTYPE>, LIST_LENGTH> nptfft_loop_synth(std::array<std::complex<DTYPE>, LIST_LENGTH/2> const& L, std::array<std::complex<DTYPE>, LIST_LENGTH/2> const& R){ return loop::nPtFFT(L, R); } std::array<std::complex<DTYPE>, LIST_LENGTH> fft_hop_synth(std::array<std::complex<DTYPE>, LIST_LENGTH> IN){ #pragma HLS PIPELINE #pragma HLS ARRAY_PARTITION variable=IN._M_instance COMPLETE #pragma HLS_INLINE return fft(IN); } std::array<std::complex<DTYPE>, LIST_LENGTH> bitreverse_hop_synth(std::array<std::complex<DTYPE>, LIST_LENGTH> const& IN){ #pragma HLS PIPELINE #pragma HLS ARRAY_PARTITION variable=IN._M_instance COMPLETE return bitreverse(IN); } std::array<std::complex<DTYPE>, LIST_LENGTH> nptfft_hop_synth(std::array<std::complex<DTYPE>, LIST_LENGTH/2> L, std::array<std::complex<DTYPE>, LIST_LENGTH/2> R){ #pragma HLS PIPELINE #pragma HLS ARRAY_PARTITION variable=L._M_instance COMPLETE #pragma HLS ARRAY_PARTITION variable=R._M_instance COMPLETE return nPtFFT(L, R); } void bit_reverse(DTYPE X_R[LIST_LENGTH], DTYPE X_I[LIST_LENGTH]){ for(unsigned int t = 0; t < LIST_LENGTH; t++){ DTYPE temp; unsigned int b = 0; for(int j = 0; j < LOG_LIST_LENGTH; j++){ b = b << 1; b |= ((t >> j) &1); } if(t > b){ temp = X_R[t]; X_R[t] = X_R[b]; X_R[b] = temp; temp = X_I[t]; X_I[t] = X_I[b]; X_I[b] = temp; } } } void fft(DTYPE X_R[LIST_LENGTH], DTYPE X_I[LIST_LENGTH]) { DTYPE temp_R; /*temporary storage complex variable*/ DTYPE temp_I; /*temporary storage complex variable*/ int i,j,k; /* loop indexes */ int i_lower; /* Index of lower point in butterfly */ int step; int stage; int DFTpts; int BFSkip; /*Butterfly Width*/ int N2 = LIST_LENGTH>>1; /* N2=N>>1 */ /*=====================BEGIN BIT REVERSAL===========================*/ unsigned int t, b; DTYPE temp; bit_reverse(X_R, X_I); /*++++++++++++++++++++++END OF BIT REVERSAL++++++++++++++++++++++++++*/ /*=======================BEGIN: FFT=========================*/ // Do M stages of butterflies step=N2; DTYPE a, e, c, s; int counter; stages: for(stage=1; stage<= LOG_LIST_LENGTH; ++stage){ DFTpts = 1 << stage; // DFT = 2^stage = points in sub DFT BFSkip = DFTpts/2; // Butterfly WIDTHS in sub-DFT k=0; e = -2*M_PI/DFTpts; a = 0.0; counter = 0; // Perform butterflies for j-th stage butterfly: for(j=0; j<BFSkip; ++j){ c = cos((double)a); s = sin((double)a); // Compute butterflies that use same W**k DFTpts: for(i=j; i<LIST_LENGTH; i += DFTpts){ counter ++; i_lower = i + BFSkip; //index of lower point in butterfly //printf("%d %d %d a:%4f \tr:%4f \ti:%4f \trl:%4f \til:%4f\n", stage, i, i_lower, a, X_R[i], X_I[i], X_R[i_lower], X_I[i_lower]); temp_R = X_R[i_lower]*c+ X_I[i_lower]*s; temp_I = X_I[i_lower]*c- X_R[i_lower]*s; X_R[i_lower] = X_R[i] - temp_R; X_I[i_lower] = X_I[i] - temp_I; X_R[i] = X_R[i] + temp_R; X_I[i] = X_I[i] + temp_I; } a = a + e; k+=step; } step=step/2; } } int fft_test(){ std::array<std::complex<DTYPE>, LIST_LENGTH> in, out; DTYPE gold_real[LIST_LENGTH]; DTYPE gold_imag[LIST_LENGTH]; for(int i = 0; i < LIST_LENGTH; i ++){ in[i] = {(DTYPE)(i + 1), (DTYPE)0}; gold_real[i] = i + 1; gold_imag[i] = 0; } fft(gold_real, gold_imag); out = fft_hop_synth(in); for(int i = 0; i < LIST_LENGTH; i ++){ if(std::abs(float(gold_real[i] - out[i].real())) > .25){ std::cout << "Error! Recursive Real FFT Values at index " << i << "did not match" << std::endl; return -1; } if(std::abs(float(gold_imag[i] - out[i].imag())) > .25){ std::cout << "Error! Recursive Imaginary FFT Values at index " << i << "did not match" << std::endl; return -1; } } out = fft_loop_synth(in); for(int i = 0; i < LIST_LENGTH; i ++){ if(std::abs(float(gold_real[i] - out[i].real())) > .25){ std::cout << "Error! Loop Real FFT Values at index " << i << "did not match" << std::endl; return -1; } if(std::abs(float(gold_imag[i] - out[i].imag())) > .25){ std::cout << "Error! Loop Imaginary FFT Values at index " << i << "did not match" << std::endl; return -1; } } std::cout << "Passed FFT tests!" << std::endl; return 0; } int bitreverse_test(){ std::array<std::complex<DTYPE>, LIST_LENGTH> in, out; DTYPE gold_real[LIST_LENGTH]; DTYPE gold_imag[LIST_LENGTH]; for(int i = 0; i < LIST_LENGTH; i ++){ in[i] = {(DTYPE)(i + 1), (DTYPE)0}; gold_real[i] = i + 1; gold_imag[i] = 0; } bit_reverse(gold_real, gold_imag); out = bitreverse_hop_synth(in); for(int i = 0; i < LIST_LENGTH; i ++){ if(std::abs(float(gold_real[i] - out[i].real())) > .25){ std::cout << "Error! Loop Real Bitreverse Values at index " << i << "did not match" << std::endl; return -1; } if(std::abs(float(gold_imag[i] - out[i].imag())) > .25){ std::cout << "Error! Loop Imaginary Bitreverse Values at index " << i << "did not match" << std::endl; return -1; } } out = bitreverse_loop_synth(in); for(int i = 0; i < LIST_LENGTH; i ++){ if(std::abs(float(gold_real[i] - out[i].real())) > .25){ std::cout << "Error! Loop Real Bitreverse Values at index " << i << "did not match" << std::endl; return -1; } if(std::abs(float(gold_imag[i] - out[i].imag())) > .25){ std::cout << "Error! Loop Imaginary Bitreverse Values at index " << i << "did not match" << std::endl; return -1; } } std::cout << "Passed Bitreverse tests!" << std::endl; return 0; } int main(){ int err; if((err = bitreverse_test())){ return err; } if((err = fft_test())){ return err; } std::cout << "FFT Tests Passed!" << std::endl; return 0; }
30.43956
162
0.633213
a16ba5f9d8fd77234e1939443a8d2cdcd01a057f
498
ts
TypeScript
src/index.ts
MichaelJolley/code-community
b7ef729dabd8c34c8a6e7f2124b397c440a65101
[ "MIT" ]
1
2021-02-18T23:50:22.000Z
2021-02-18T23:50:22.000Z
src/index.ts
MichaelJolley/code-community
b7ef729dabd8c34c8a6e7f2124b397c440a65101
[ "MIT" ]
41
2020-01-18T21:38:22.000Z
2021-05-11T00:50:29.000Z
src/index.ts
MichaelJolley/code-community
b7ef729dabd8c34c8a6e7f2124b397c440a65101
[ "MIT" ]
2
2020-01-26T21:01:47.000Z
2020-01-26T21:10:30.000Z
import * as core from '@actions/core' import * as github from '@actions/github' //import * as io from '@actions/io' import * as issues from './issues' import * as pullrequests from './pullrequests' const run = async (): Promise<void> => { switch (github.context.eventName) { case 'issues': issues.processIssue(github.context.payload) break case 'pull-requests': pullrequests.processPullRequest(github.context.payload) break default: break } } run()
22.636364
61
0.666667
f4d2908b8b51282822e041365a6bb3a3aa4fc0de
661
ts
TypeScript
lib/utilities.ts
simdaniel/wem2k-server
c272e13d78f828c58bdceb06a4a0e4e1d97e33da
[ "Apache-2.0" ]
null
null
null
lib/utilities.ts
simdaniel/wem2k-server
c272e13d78f828c58bdceb06a4a0e4e1d97e33da
[ "Apache-2.0" ]
null
null
null
lib/utilities.ts
simdaniel/wem2k-server
c272e13d78f828c58bdceb06a4a0e4e1d97e33da
[ "Apache-2.0" ]
null
null
null
/** * This module contains methods that we use for handling http requests and responses. */ import http from 'http' /** * @param req * @param callback * @returns void */ export function collectBody(req: http.IncomingMessage, callback: any): void { let body = '' req.on('data', (chunk) => { body += chunk }) req.on('end', () => { callback(body) }) } /** * @param res * @param statusCode * @param message The error message * @returns void */ export function writeErrorResponse(res: http.ServerResponse, statusCode: number, message: string): void { res.writeHead(statusCode) res.write(JSON.stringify({ message })) res.end() }
20.030303
105
0.656581
cda28bc6bd878ec90ad936e31537e65e04096e80
7,630
cs
C#
Fundamentals-2.0/HighQualityCode/ExamProblems/07-February-2016/AC-TestingSystem/Work/Controller.cs
sholev/SoftUni
0d5f4b26fa20e5442b91a515f775e80ae6994834
[ "MIT" ]
1
2019-01-22T21:16:45.000Z
2019-01-22T21:16:45.000Z
Fundamentals-2.0/HighQualityCode/ExamProblems/07-February-2016/AC-TestingSystem/Work/Controller.cs
sholev/SoftUni
0d5f4b26fa20e5442b91a515f775e80ae6994834
[ "MIT" ]
null
null
null
Fundamentals-2.0/HighQualityCode/ExamProblems/07-February-2016/AC-TestingSystem/Work/Controller.cs
sholev/SoftUni
0d5f4b26fa20e5442b91a515f775e80ae6994834
[ "MIT" ]
null
null
null
namespace AC_TestingSystem.Work { using System; using System.Collections.Generic; using System.Linq; using System.Text; using AC_TestingSystem.Core; using AC_TestingSystem.Data; using AC_TestingSystem.Interfaces; using AC_TestingSystem.Models; public class Controller { private readonly Engine engine; private readonly Repository repository; public Controller(Engine engine, Repository repository) { this.engine = engine; this.repository = repository; } public string ExecuteCommand() { var command = this.engine.Command; string output; switch (command.Name) { case "RegisterStationaryAirConditioner": this.engine.ValidateParametersCount(command, 4); output = this.RegisterStationaryAirConditioner( command.Parameters[0], command.Parameters[1], command.Parameters[2], int.Parse(command.Parameters[3])); break; case "RegisterCarAirConditioner": this.engine.ValidateParametersCount(command, 3); output = this.RegisterCarAirConditioner( command.Parameters[0], command.Parameters[1], int.Parse(command.Parameters[2])); break; case "RegisterPlaneAirConditioner": this.engine.ValidateParametersCount(command, 4); output = this.RegisterPlaneAirConditioner( command.Parameters[0], command.Parameters[1], int.Parse(command.Parameters[2]), command.Parameters[3]); break; case "TestAirConditioner": this.engine.ValidateParametersCount(command, 2); output = this.TestAirConditioner( command.Parameters[0], command.Parameters[1]); break; case "FindAirConditioner": this.engine.ValidateParametersCount(command, 2); output = this.FindAirConditioner( command.Parameters[0], command.Parameters[1]); break; case "FindReport": this.engine.ValidateParametersCount(command, 2); output = this.FindReport( command.Parameters[0], command.Parameters[1]); break; case "Status": this.engine.ValidateParametersCount(command, 0); output = this.Status(); break; case "FindAllReportsByManufacturer": this.engine.ValidateParametersCount(command, 1); output = this.FindAllReportsByManufacturer(command.Parameters[0]); break; default: throw new IndexOutOfRangeException(Constants.InvalidCommand); } return output; } /// <summary> /// Get a status describing how many of the /// air conditioners in the repository /// have reports. /// </summary> /// <returns></returns> private string Status() { int reports = this.repository.GetReportsCount(); double airConditioners = this.repository.GetAirConditionersCount(); double percent = reports / airConditioners; percent = percent * 100; return string.Format(Constants.Status, percent); } private string FindAllReportsByManufacturer(string manufacturer) { List<IReport> reports = this.repository.GetReportsByManufacturer(manufacturer); if (reports.Count == 0) { return Constants.NoReports; } reports = reports.OrderBy(x => x.Mark).ToList(); StringBuilder reportsPrint = new StringBuilder(); reportsPrint.AppendLine(string.Format("Reports from {0}:", manufacturer)); reportsPrint.Append(string.Join(Environment.NewLine, reports)); return reportsPrint.ToString(); } private string RegisterStationaryAirConditioner(string manufacturer, string model, string energyEfficiencyRating, int powerUsage) { AirConditioner airConditioner = new AirConditioner(manufacturer, model, energyEfficiencyRating, powerUsage); this.repository.AddAirConditioner(airConditioner); return string.Format(Constants.Register, airConditioner.Model, airConditioner.Manufacturer); } private string RegisterCarAirConditioner(string manufacturer, string model, int volumeCoverage) { AirConditioner airConditioner = new AirConditioner(manufacturer, model, volumeCoverage); this.repository.AddAirConditioner(airConditioner); return string.Format(Constants.Register, airConditioner.Model, airConditioner.Manufacturer); } /// <summary> /// Register an air conditioner which will be used in a plane. /// </summary> /// <param name="manufacturer">The manufacturer of the air conditioner.</param> /// <param name="model">The manufacturer of the air conditioner.</param> /// <param name="volumeCoverage">The volume coverege of the air conditioner.</param> /// <param name="electricityUsed">The electricity used by the air conditioner.</param> /// <returns>Returns a string with information about the registered air conditioner.</returns> private string RegisterPlaneAirConditioner(string manufacturer, string model, int volumeCoverage, string electricityUsed) { AirConditioner airConditioner = new AirConditioner(manufacturer, model, volumeCoverage, electricityUsed); this.repository.AddAirConditioner(airConditioner); return string.Format(Constants.Register, airConditioner.Model, airConditioner.Manufacturer); } private string TestAirConditioner(string manufacturer, string model) { AirConditioner airConditioner = this.repository.GetAirConditioner(manufacturer, model); airConditioner.EnergyRating += 5; var mark = airConditioner.Test(); this.repository.AddReport(new Report(airConditioner.Manufacturer, airConditioner.Model, mark)); return string.Format(Constants.Test, model, manufacturer); } /// <summary> /// Find air conditioner by given model and manufacturer. /// </summary> /// <param name="manufacturer">The manufacturer of the air conditioner.</param> /// <param name="model">The manufacturer of the air conditioner.</param> /// <returns></returns> private string FindAirConditioner(string manufacturer, string model) { AirConditioner airConditioner = this.repository.GetAirConditioner(manufacturer, model); return airConditioner.ToString(); } private string FindReport(string manufacturer, string model) { IReport report = this.repository.GetReport(manufacturer, model); return report.ToString(); } } }
41.923077
137
0.588336
2488ed0b869fde9b2691f2b3ba457ce3a7a93258
437
php
PHP
src/Fields/Dropdown/templates/foundation/dropdown.mustache.php
helmut/forms
8e834603eb4e119f034a4e77e4a980e7f9ad0bd1
[ "MIT" ]
null
null
null
src/Fields/Dropdown/templates/foundation/dropdown.mustache.php
helmut/forms
8e834603eb4e119f034a4e77e4a980e7f9ad0bd1
[ "MIT" ]
null
null
null
src/Fields/Dropdown/templates/foundation/dropdown.mustache.php
helmut/forms
8e834603eb4e119f034a4e77e4a980e7f9ad0bd1
[ "MIT" ]
null
null
null
<div class="row"> <div class="medium-12 columns"> <label>{{ label }}{{# required }} <span style="font-weight:normal" title="{{ lang.required }}">*</span>{{/ required}}<br /> <select name="{{ name }}" style="width:auto"> <option value=""></option> {{# options }} <option value="{{ value }}"{{# selected }} selected="selected"{{/ selected}}>{{ label }}</option> {{/ options }} </select> </label> </div> </div>
33.615385
125
0.556064
da814e5a15d38623b7bc5ccd62218add681b066f
844
php
PHP
config/mail.config.php
mangasf/sifo-common-instance
27455416465224a603dbcec19a15bc8183248779
[ "Apache-2.0" ]
null
null
null
config/mail.config.php
mangasf/sifo-common-instance
27455416465224a603dbcec19a15bc8183248779
[ "Apache-2.0" ]
2
2017-08-24T09:29:01.000Z
2019-03-12T22:56:25.000Z
config/mail.config.php
mangasf/sifo-common-instance
27455416465224a603dbcec19a15bc8183248779
[ "Apache-2.0" ]
4
2016-05-08T08:42:27.000Z
2020-04-16T15:10:11.000Z
<?php /** * Email configuration. More options can be added. See Mail class. * * The key values must be PHPMailer attributes. You can remove attributes, defaults will be used * */ $config['From'] = 'noreply@localhost'; $config['FromName'] = 'Sifo Administrator'; $config['CharSet'] = 'utf-8'; $config['ContentType'] = 'text/html'; // Method to send mail: ("mail", "sendmail", or "smtp"). $config['Mailer'] = 'mail'; $config['Sendmail'] = '/usr/sbin/sendmail'; // SMTP settings (apply if mailer is smtp) $config['Host'] = 'localhost'; $config['Port'] = 25; $config['Host'] = 'localhost'; $config['Host'] = 'localhost'; // Options are "", "ssl" or "tls" $config['SMTPSecure'] = ''; $config['SMTPAuth'] = false; $config['Username'] = ''; $config['Password'] = ''; $config['Timeout'] = 10; $config['SMTPDebug'] = false;
28.133333
96
0.622038
b0bcbab34b08207063e8e40db9038eb66145e4aa
4,026
py
Python
test/base.py
jsbronder/delbert
c6c809c4c521914a3d9b172f490b1bbb08d1ca78
[ "BSD-3-Clause" ]
null
null
null
test/base.py
jsbronder/delbert
c6c809c4c521914a3d9b172f490b1bbb08d1ca78
[ "BSD-3-Clause" ]
13
2015-01-05T18:31:11.000Z
2019-11-30T21:47:52.000Z
test/base.py
jsbronder/delbert
c6c809c4c521914a3d9b172f490b1bbb08d1ca78
[ "BSD-3-Clause" ]
2
2016-03-17T22:00:56.000Z
2018-06-19T18:44:13.000Z
import inspect import functools import json import os import re import sys import unittest import responses sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))) import delbert.bot import delbert.channels plugin_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), '../plugins')) TEST_CHANNEL = '#test' TEST_NICK = 'testbot' def load_plugin(name, obj_name, config={}, *args, **kwds): """ Load a plugin. @param name - filename of plugin @param obj_name - name of the plugin within the file to load @param config - dictionary of extra configuration to pass to the plugin @param *args - extra arguments to pass to the plugin @param *kwds - extra keyword arguments to pass to the plugin. @return - an instance of the plugin """ env = {} execfile(os.path.join(plugin_dir, name), env) return env[obj_name](config, *args, **kwds) def load_plugin_and_excs(name, obj_name, config={}, *args, **kwds): """ Load a plugin and any exceptions defined by the plugin. This is useful for unittesting to make sure that certain exceptions are raised. @param name - filename of plugin @param obj_name - name of the plugin within the file to load @param config - dictionary of extra configuration to pass to the plugin @param *args - extra arguments to pass to the plugin @param *kwds - extra keyword arguments to pass to the plugin. @return - Tuple containing the plugin and a dictionary containing all exceptions defined in the plugin file ({exc_name: exc_class}). """ env = {} execfile(os.path.join(plugin_dir, name), env) plugin = env[obj_name](config, *args, **kwds) excs = {symbol:cls for symbol, cls in env.items() if inspect.isclass(cls) and issubclass(cls, Exception)} return (plugin, excs) class TestProto(delbert.bot.BotProtocol): def __init__(self, plugins): priv_channel = delbert.channels.Channel(TEST_NICK, {}) _ = [priv_channel.register_plugin(p) for p in plugins] channel_map = { TEST_CHANNEL: TestChannel(plugins), TEST_NICK: priv_channel, } _ = [p.initialize(TEST_NICK, self) for p in plugins] self._msgs = [] delbert.bot.BotProtocol.__init__(self, TEST_NICK, 'pw', channel_map) @property def msgs(self): return self._msgs def clear(self): self._msgs = [] def _call(self, *args, **kwds): _ = kwds.pop('cb', None) _ = kwds.pop('eb', None) args[0](*args[1:], **kwds) def send_msg(self, channel, msg): self._msgs.append(('msg', channel, msg)) def send_notice(self, channel, msg): self._msgs.append(('notice', channel, msg)) class TestChannel(delbert.channels.Channel): def __init__(self, plugins): config = { 'config-plugin': { 'commands': ['cmd1'], }, } super(TestChannel, self).__init__(TEST_CHANNEL, config) _ = [self.register_plugin(p) for p in plugins] def net_test(func): net_tests = os.environ.get('DELBERT_RUN_NET_TESTS') is not None @unittest.skipIf(not net_tests, 'Network tests are disabled') @functools.wraps(func) def wrapper(*args, **kwds): return func(*args, **kwds) return wrapper def create_json_response(url, resp): """ Create a mocked json response for the given url. @param url - regex string representing the urls to match @param resp - dictionary representing the json response """ responses.add(responses.GET, re.compile(url), content_type='application/json', body=json.dumps(resp)) def create_response(url, resp): """ Create a mocked response for the given url. @param url - regex string representing the urls to match @param resp - text to return as the response content """ responses.add(responses.GET, re.compile(url), body=resp)
29.602941
109
0.647789
cac0292bf1c2e4b2446357c7c166e461f4aba032
1,084
swift
Swift
Sources/VGSCheckoutSDK/Core/Checkout/UseCases/CheckoutServices/VGSCheckoutServiceProtocol.swift
verygoodsecurity/vgs-checkout-ios
cc4590434af5f4b80794a718a2eee919065db080
[ "MIT" ]
8
2021-11-11T12:33:02.000Z
2022-01-12T14:39:08.000Z
Sources/VGSCheckoutSDK/Core/Checkout/UseCases/CheckoutServices/VGSCheckoutServiceProtocol.swift
verygoodsecurity/vgs-checkout-ios
cc4590434af5f4b80794a718a2eee919065db080
[ "MIT" ]
null
null
null
Sources/VGSCheckoutSDK/Core/Checkout/UseCases/CheckoutServices/VGSCheckoutServiceProtocol.swift
verygoodsecurity/vgs-checkout-ios
cc4590434af5f4b80794a718a2eee919065db080
[ "MIT" ]
1
2021-11-03T08:31:21.000Z
2021-11-03T08:31:21.000Z
// // VGSCheckoutServiceProtocol.swift // VGSCheckoutSDK import Foundation #if os(iOS) import UIKit #endif /// Defines interface for state change in checkout service. internal protocol VGSCheckoutServiceDelegateProtocol: AnyObject { /// no:doc func checkoutServiceStateDidChange(with state: VGSAddCardFlowState, in service: VGSCheckoutServiceProtocol) } /// Defines interface for checkout service. /// Checkout service should: /// 1. init with configuration, collect, UI theme; /// 2. create root checkout view controller; /// 3. provide delegate to notify `VGSCheckout` instance with changes in service state. internal protocol VGSCheckoutServiceProtocol { /// no:doc init(checkoutConfigurationType: VGSCheckoutConfigurationType, vgsCollect: VGSCollect, uiTheme: VGSCheckoutThemeProtocol) /// Builds checkout view controller. /// - Returns: `UIViewController` object, view controller. func buildCheckoutViewController() -> UIViewController /// An object that acts as a checkout service delegate. var serviceDelegate: VGSCheckoutServiceDelegateProtocol? {get set} }
31.882353
121
0.789668
33fdee3b79240f5744fdda4ac80085c8bed72e38
944
swift
Swift
Tests/TestArgFileTests/TestToRunTests.swift
Eysner/Emcee
4949428b936594fd7b319201aa306aae0f7ead0f
[ "MIT" ]
233
2018-09-04T14:38:58.000Z
2022-03-30T06:01:00.000Z
Tests/TestArgFileTests/TestToRunTests.swift
EvgenyIv96/Emcee
a665ac0576af8079b97d0cb8c71cfdc33122bc2f
[ "MIT" ]
31
2018-09-08T07:48:57.000Z
2022-03-24T11:55:54.000Z
Tests/TestArgFileTests/TestToRunTests.swift
EvgenyIv96/Emcee
a665ac0576af8079b97d0cb8c71cfdc33122bc2f
[ "MIT" ]
19
2018-09-07T05:39:29.000Z
2022-03-15T16:37:49.000Z
import Foundation import TestArgFile import RunnerModels import XCTest final class TestToRunTests: XCTestCase { let decoder = JSONDecoder() func test__parsing_single_test_name() { let json = "{\"test\": {\"predicateType\": \"singleTestName\", \"testName\": \"ClassName/testName\"}}" let expected = ["test": TestToRun.testName(TestName(className: "ClassName", methodName: "testName"))] XCTAssertEqual( try decoder.decode([String: TestToRun].self, from: Data(json.utf8)), expected ) } func test__parsing_all_tests_provided_by_runtime_dump() { let json = "{\"test\": {\"predicateType\": \"allDiscoveredTests\"}}" let expected = ["test": TestToRun.allDiscoveredTests] XCTAssertEqual( try decoder.decode([String: TestToRun].self, from: Data(json.utf8)), expected ) } }
29.5
110
0.606992
2a1debf3410693370a4ae28bda4996c133841834
8,914
lua
Lua
script/c60150809.lua
purerosefallen/thcDDuel
660f27e4fb97de1c510f759fffcf9d59d8c6ef34
[ "Apache-2.0" ]
null
null
null
script/c60150809.lua
purerosefallen/thcDDuel
660f27e4fb97de1c510f759fffcf9d59d8c6ef34
[ "Apache-2.0" ]
null
null
null
script/c60150809.lua
purerosefallen/thcDDuel
660f27e4fb97de1c510f759fffcf9d59d8c6ef34
[ "Apache-2.0" ]
null
null
null
--真正的虚无-爱莎 function c60150809.initial_effect(c) c:SetUniqueOnField(1,1,60150809) --xyz summon c:EnableReviveLimit() local e111=Effect.CreateEffect(c) e111:SetProperty(EFFECT_FLAG_UNCOPYABLE) e111:SetType(EFFECT_TYPE_FIELD) e111:SetCode(EFFECT_SPSUMMON_PROC) e111:SetRange(LOCATION_EXTRA) e111:SetCondition(c60150809.xyzcon) e111:SetOperation(c60150809.xyzop) e111:SetValue(SUMMON_TYPE_XYZ) c:RegisterEffect(e111) --除外1 local e1=Effect.CreateEffect(c) e1:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_CONTINUOUS) e1:SetCode(EVENT_SPSUMMON_SUCCESS) e1:SetProperty(EFFECT_FLAG_DELAY) e1:SetRange(LOCATION_MZONE) e1:SetCountLimit(4,60150809) e1:SetCondition(c60150809.drcon) e1:SetOperation(c60150809.drop) c:RegisterEffect(e1) --除外2 local e2=Effect.CreateEffect(c) e2:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_CONTINUOUS) e2:SetCode(EVENT_SPSUMMON_SUCCESS) e2:SetProperty(EFFECT_FLAG_DELAY) e2:SetRange(LOCATION_MZONE) e2:SetCountLimit(4,60150809) e2:SetCondition(c60150809.drcon2) e2:SetOperation(c60150809.drop2) c:RegisterEffect(e2) --除外3 local e3=Effect.CreateEffect(c) e3:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_CONTINUOUS) e3:SetCode(EVENT_SPSUMMON_SUCCESS) e3:SetProperty(EFFECT_FLAG_DELAY) e3:SetRange(LOCATION_MZONE) e3:SetCountLimit(4,60150809) e3:SetCondition(c60150809.drcon3) e3:SetOperation(c60150809.drop3) c:RegisterEffect(e3) --除外4 local e4=Effect.CreateEffect(c) e4:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_CONTINUOUS) e4:SetCode(EVENT_SPSUMMON_SUCCESS) e4:SetProperty(EFFECT_FLAG_DELAY) e4:SetRange(LOCATION_MZONE) e4:SetCountLimit(4,60150809) e4:SetCondition(c60150809.drcon4) e4:SetOperation(c60150809.drop4) c:RegisterEffect(e4) --cannot target local e5=Effect.CreateEffect(c) e5:SetType(EFFECT_TYPE_SINGLE) e5:SetProperty(EFFECT_FLAG_SINGLE_RANGE) e5:SetRange(LOCATION_MZONE) e5:SetCode(EFFECT_CANNOT_BE_EFFECT_TARGET) e5:SetCondition(c60150809.condition) e5:SetValue(c60150809.tgvalue) c:RegisterEffect(e5) --control local e6=Effect.CreateEffect(c) e6:SetType(EFFECT_TYPE_SINGLE) e6:SetProperty(EFFECT_FLAG_SINGLE_RANGE) e6:SetRange(LOCATION_MZONE) e6:SetCode(EFFECT_CANNOT_CHANGE_CONTROL) e6:SetCondition(c60150809.condition) c:RegisterEffect(e6) -- local e11=Effect.CreateEffect(c) e11:SetType(EFFECT_TYPE_SINGLE) e11:SetProperty(EFFECT_FLAG_SINGLE_RANGE) e11:SetRange(LOCATION_MZONE) e11:SetCode(EFFECT_IMMUNE_EFFECT) e11:SetCondition(c60150809.condition) e11:SetValue(c60150809.efilter) c:RegisterEffect(e11) --material local e7=Effect.CreateEffect(c) e7:SetDescription(aux.Stringid(12744567,0)) e7:SetType(EFFECT_TYPE_QUICK_O) e7:SetCode(EVENT_FREE_CHAIN) e7:SetProperty(EFFECT_FLAG_CARD_TARGET) e7:SetRange(LOCATION_MZONE) e7:SetCountLimit(1) e7:SetCondition(c60150809.condition2) e7:SetTarget(c60150809.target) e7:SetOperation(c60150809.operation) c:RegisterEffect(e7) --[[--自残 local e8=Effect.CreateEffect(c) e8:SetDescription(aux.Stringid(60150809,1)) e8:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_TRIGGER_F) e8:SetCode(EVENT_PHASE+PHASE_END) e8:SetRange(LOCATION_MZONE) e8:SetCountLimit(1) e8:SetOperation(c60150809.tgop) c:RegisterEffect(e8)]] --destroy replace local e9=Effect.CreateEffect(c) e9:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_CONTINUOUS) e9:SetProperty(EFFECT_FLAG_SINGLE_RANGE) e9:SetCode(EFFECT_DESTROY_REPLACE) e9:SetRange(LOCATION_MZONE) e9:SetTarget(c60150809.reptg) c:RegisterEffect(e9) --destroy replace local e10=Effect.CreateEffect(c) e10:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_CONTINUOUS) e10:SetProperty(EFFECT_FLAG_SINGLE_RANGE) e10:SetCode(EFFECT_DESTROY_REPLACE) e10:SetRange(LOCATION_MZONE) e10:SetTarget(c60150809.reptg2) c:RegisterEffect(e10) end function c60150809.efilter(e,te) return te:IsActiveType(TYPE_TRAP) end function c60150809.mfilter(c) return c:IsFaceup() and c:IsType(TYPE_XYZ) and c:IsRace(RACE_SPELLCASTER) and c:GetRank()==8 end function c60150809.xyzfilter1(c,g) return g:IsExists(c60150809.xyzfilter2,1,c,c:GetRank()) end function c60150809.xyzfilter2(c,rk) return c:GetRank()==8 end function c60150809.xyzcon(e,c,og) if c==nil then return true end local tp=c:GetControler() local mg=Duel.GetMatchingGroup(c60150809.mfilter,tp,LOCATION_MZONE,0,nil) return Duel.GetLocationCount(tp,LOCATION_MZONE)>-1 and mg:IsExists(c60150809.xyzfilter1,1,nil,mg) end function c60150809.xyzop(e,tp,eg,ep,ev,re,r,rp,c,og) local mg=Duel.GetMatchingGroup(c60150809.mfilter,tp,LOCATION_MZONE,0,nil) Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_XMATERIAL) local g1=mg:FilterSelect(tp,c60150809.xyzfilter1,1,1,nil,mg) local tc1=g1:GetFirst() Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_XMATERIAL) local g2=mg:FilterSelect(tp,c60150809.xyzfilter2,1,1,tc1,tc1:GetRank()) local tc2=g2:GetFirst() g1:Merge(g2) local sg1=tc1:GetOverlayGroup() local sg2=tc2:GetOverlayGroup() sg1:Merge(sg2) Duel.SendtoGrave(sg1,REASON_RULE) c:SetMaterial(g1) Duel.Overlay(c,g1) end function c60150809.sfilter(c,sp) return c:GetSummonPlayer()==sp end function c60150809.drcon(e,tp,eg,ep,ev,re,r,rp) return ep~=tp and eg:IsExists(Card.IsPreviousLocation,1,nil,LOCATION_HAND) and e:GetHandler():GetOverlayGroup():IsExists(Card.IsCode,1,nil,60150807) end function c60150809.drop(e,tp,eg,ep,ev,re,r,rp) if eg:IsExists(c60150809.sfilter,1,nil,1-tp) then Duel.Hint(HINT_CARD,0,60150809) local g=Duel.GetFieldCard(1-tp,LOCATION_GRAVE,Duel.GetFieldGroupCount(1-tp,LOCATION_GRAVE,0)-1) Duel.Remove(g,POS_FACEDOWN,REASON_EFFECT) end end function c60150809.drcon2(e,tp,eg,ep,ev,re,r,rp) return ep~=tp and eg:IsExists(Card.IsPreviousLocation,1,nil,LOCATION_GRAVE) and e:GetHandler():GetOverlayGroup():IsExists(Card.IsCode,1,nil,60150807) end function c60150809.drop2(e,tp,eg,ep,ev,re,r,rp) if eg:IsExists(c60150809.sfilter,1,nil,1-tp) then Duel.Hint(HINT_CARD,0,60150809) local g=Duel.GetFieldCard(1-tp,LOCATION_DECK,Duel.GetFieldGroupCount(1-tp,LOCATION_DECK,0)-1) Duel.Remove(g,POS_FACEDOWN,REASON_EFFECT) end end function c60150809.drcon3(e,tp,eg,ep,ev,re,r,rp) return ep~=tp and eg:IsExists(Card.IsPreviousLocation,1,nil,LOCATION_DECK) and e:GetHandler():GetOverlayGroup():IsExists(Card.IsCode,1,nil,60150807) end function c60150809.drop3(e,tp,eg,ep,ev,re,r,rp) if eg:IsExists(c60150809.sfilter,1,nil,1-tp) then Duel.Hint(HINT_CARD,0,60150809) local g=Duel.GetFieldCard(1-tp,LOCATION_EXTRA,Duel.GetFieldGroupCount(1-tp,LOCATION_EXTRA,0)-1) Duel.Remove(g,POS_FACEDOWN,REASON_EFFECT) end end function c60150809.drcon4(e,tp,eg,ep,ev,re,r,rp) return ep~=tp and eg:IsExists(Card.IsPreviousLocation,1,nil,LOCATION_EXTRA) and e:GetHandler():GetOverlayGroup():IsExists(Card.IsCode,1,nil,60150807) end function c60150809.drop4(e,tp,eg,ep,ev,re,r,rp) if eg:IsExists(c60150809.sfilter,1,nil,1-tp) then Duel.Hint(HINT_CARD,0,60150809) local g=Duel.GetFieldGroup(tp,0,LOCATION_HAND):RandomSelect(tp,1) Duel.Remove(g,POS_FACEDOWN,REASON_EFFECT) end end function c60150809.condition(e,tp,eg,ep,ev,re,r,rp) return e:GetHandler():GetOverlayGroup():IsExists(Card.IsCode,1,nil,60150808) end function c60150809.tgvalue(e,re,rp) return rp~=e:GetHandlerPlayer() end function c60150809.condition2(e,tp,eg,ep,ev,re,r,rp) return e:GetHandler():GetOverlayCount()<3 and e:GetHandler():GetOverlayGroup():IsExists(Card.IsCode,1,nil,60150807) end function c60150809.filter(c) return (c:IsFaceup() or c:IsFacedown()) and c:IsAbleToChangeControler() end function c60150809.target(e,tp,eg,ep,ev,re,r,rp,chk,chkc) if chkc then return chkc:IsLocation(LOCATION_REMOVED) and chkc:IsControler(1-tp) and c60150809.filter(chkc) end if chk==0 then return e:GetHandler():IsType(TYPE_XYZ) and Duel.IsExistingTarget(c60150809.filter,tp,0,LOCATION_REMOVED,1,nil) end Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_TARGET) Duel.SelectTarget(tp,c60150809.filter,tp,0,LOCATION_REMOVED,1,1,nil) end function c60150809.operation(e,tp,eg,ep,ev,re,r,rp) local c=e:GetHandler() local tc=Duel.GetFirstTarget() if c:IsRelateToEffect(e) and tc:IsRelateToEffect(e) and not tc:IsImmuneToEffect(e) then Duel.Overlay(c,Group.FromCards(tc)) end end function c60150809.tgop(e,tp,eg,ep,ev,re,r,rp) local g=Duel.GetFieldGroup(tp,0,LOCATION_DECK+LOCATION_HAND+LOCATION_GRAVE+LOCATION_EXTRA+LOCATION_ONFIELD):RandomSelect(tp,1) Duel.Remove(g,POS_FACEDOWN,REASON_EFFECT) end function c60150809.reptg(e,tp,eg,ep,ev,re,r,rp,chk) local c=e:GetHandler() if chk==0 then return c:IsReason(REASON_BATTLE) and c:CheckRemoveOverlayCard(tp,1,REASON_BATTLE) end if Duel.SelectYesNo(tp,aux.Stringid(60150809,2)) then c:RemoveOverlayCard(tp,1,1,REASON_EFFECT) return true else return false end end function c60150809.reptg2(e,tp,eg,ep,ev,re,r,rp,chk) local c=e:GetHandler() if chk==0 then return c:IsReason(REASON_EFFECT) and c:CheckRemoveOverlayCard(tp,1,REASON_EFFECT) end if Duel.SelectYesNo(tp,aux.Stringid(60150809,2)) then c:RemoveOverlayCard(tp,1,1,REASON_EFFECT) return true else return false end end
36.235772
130
0.802782
afd6a5b398af0f7bc093a6d1d1baa5d69897de07
136
rs
Rust
package/launcher.rs
ngryman/rust
46dc2ced8db465d92cd0527ac55c0a875261136e
[ "MIT" ]
157
2019-08-01T16:30:08.000Z
2021-02-11T08:40:58.000Z
package/launcher.rs
ngryman/rust
46dc2ced8db465d92cd0527ac55c0a875261136e
[ "MIT" ]
32
2019-07-31T21:52:49.000Z
2021-02-07T03:55:42.000Z
package/launcher.rs
ngryman/rust
46dc2ced8db465d92cd0527ac55c0a875261136e
[ "MIT" ]
18
2019-08-01T19:14:45.000Z
2021-01-28T15:30:21.000Z
use vercel_lambda::lambda; use std::error::Error; // PLACEHOLDER fn main() -> Result<(), Box<dyn Error>> { Ok(lambda!(handler)) }
15.111111
41
0.639706
3ee0ff3722c2a03fcb851ebc518b0cdb0955ab14
464
swift
Swift
BillionWallet/BWalletManager.swift
Billionapp/billion-wallet-ios
f9c96e78e10b4b191497f433bdb171021db226dc
[ "MIT" ]
18
2017-11-03T23:46:09.000Z
2021-11-11T07:59:17.000Z
BillionWallet/BWalletManager.swift
Billionapp/billion-wallet-ios
f9c96e78e10b4b191497f433bdb171021db226dc
[ "MIT" ]
null
null
null
BillionWallet/BWalletManager.swift
Billionapp/billion-wallet-ios
f9c96e78e10b4b191497f433bdb171021db226dc
[ "MIT" ]
5
2018-02-15T13:45:20.000Z
2022-02-21T06:52:26.000Z
// // BWalletManager.swift // BillionWallet // // Created by Evolution Group Ltd on 06.02.2018. // Copyright © 2018 Evolution Group Ltd. All rights reserved. // import Foundation protocol BWalletManager: class { var noWallet: Bool { get } var seedPhrase: String? { get } var seedCreationTime: TimeInterval { get } var isTestnet: Bool { get } func generateRandomSeed() -> String? func recoverWallet(withPhrase phrase: String) throws }
24.421053
62
0.698276
d61b10beba4aab9cb15056c7dba3b8c511038aa4
6,524
cs
C#
Assets/External Assets/3rdPersonCamera/Scripts/FreeForm.cs
eehjhunggnujhee/thing-thing-thing
eff3c144f847b56be81962b0d2d57eb6c398979f
[ "MIT" ]
null
null
null
Assets/External Assets/3rdPersonCamera/Scripts/FreeForm.cs
eehjhunggnujhee/thing-thing-thing
eff3c144f847b56be81962b0d2d57eb6c398979f
[ "MIT" ]
null
null
null
Assets/External Assets/3rdPersonCamera/Scripts/FreeForm.cs
eehjhunggnujhee/thing-thing-thing
eff3c144f847b56be81962b0d2d57eb6c398979f
[ "MIT" ]
null
null
null
using System; using UnityEngine; namespace ThirdPersonCamera { public enum CameraMode { Always, Hold } [RequireComponent(typeof(CameraController))] public class FreeForm : MonoBehaviour { public bool cameraEnabled = true; public CameraMode cameraMode = CameraMode.Hold; public bool controllerEnabled = false; public bool controllerInvertY = true; public bool mouseInvertY = false; public bool lockMouseCursor = true; public Vector2 mouseSensitivity = new Vector2(1.5f, 1.0f); public Vector2 controllerSensitivity = new Vector2(1.0f, 0.7f); [HideInInspector] public float x; [HideInInspector] public float y; private float yAngle; private float angle; private string rightAxisXName; private string rightAxisYName; private bool mouse0; private bool mouse1; private Vector3 upVector; private Vector3 downVector; private bool smartPivotInit; private CameraController cameraController; public void Start() { cameraController = GetComponent<CameraController>(); mouse0 = false; mouse1 = false; x = 0; y = 0; smartPivotInit = true; upVector = Vector3.up; downVector = Vector3.down; string platform = Application.platform.ToString().ToLower(); if (platform.Contains("windows") || platform.Contains("linux")) { rightAxisXName = "Right_4"; rightAxisYName = "Right_5"; } else { rightAxisXName = "Right_3"; rightAxisYName = "Right_4"; } // test if the controller axis are setup try { Input.GetAxis(rightAxisXName); Input.GetAxis(rightAxisYName); } catch { Debug.LogWarning("Controller Error - Right axis not set in InputManager. Controller is disabled!"); controllerEnabled = false; } } public void Update() { if (cameraEnabled) { mouse0 = Input.GetMouseButton(0); mouse1 = Input.GetMouseButton(1); if ((cameraMode == CameraMode.Hold && mouse0 || mouse1) || cameraMode == CameraMode.Always) { x = Input.GetAxis("Mouse X") * mouseSensitivity.x; y = Input.GetAxis("Mouse Y") * mouseSensitivity.y; if (mouseInvertY) y *= -1.0f; if (lockMouseCursor) { Cursor.visible = false; Cursor.lockState = CursorLockMode.Locked; } } else { x = 0; y = 0; if (Cursor.lockState == CursorLockMode.Locked) { Cursor.visible = true; Cursor.lockState = CursorLockMode.None; } } if (controllerEnabled && x == 0 && y == 0) { x = Input.GetAxis(rightAxisXName) * controllerSensitivity.x; y = Input.GetAxis(rightAxisYName) * controllerSensitivity.y; if (controllerInvertY) y *= -1.0f; } if (Input.GetAxis("Mouse ScrollWheel") < 0) // back { cameraController.desiredDistance += cameraController.zoomOutStepValue; } if (Input.GetAxis("Mouse ScrollWheel") > 0) // forward { cameraController.desiredDistance -= cameraController.zoomOutStepValue; } if (cameraController.desiredDistance < 0) cameraController.desiredDistance = 0; Vector3 offsetVectorTransformed = cameraController.target.transform.rotation * cameraController.offsetVector; transform.RotateAround(cameraController.target.position + offsetVectorTransformed, cameraController.target.up, x); yAngle = -y; // Prevent camera flipping angle = Vector3.Angle(transform.forward, upVector); if (yAngle > 0) { if (angle + yAngle > 180.0f) { yAngle = Vector3.Angle(transform.forward, upVector) - 180; if (yAngle < 0) yAngle = 0; } } else { if (angle + yAngle < 0.0f) { yAngle = Vector3.Angle(transform.forward, downVector) - 180; } } if (!cameraController.smartPivot || cameraController.cameraNormalMode && (!cameraController.bGroundHit || (cameraController.bGroundHit && y < 0) || transform.position.y > (cameraController.target.position.y + cameraController.offsetVector.y))) { // normal mode transform.RotateAround(cameraController.target.position + offsetVectorTransformed, transform.right, yAngle); } else { // smart pivot mode if (smartPivotInit) { smartPivotInit = false; cameraController.InitSmartPivot(); } transform.RotateAround(transform.position, transform.right, yAngle); if (transform.rotation.eulerAngles.x > cameraController.startingY || (transform.rotation.eulerAngles.x >= 0 && transform.rotation.eulerAngles.x < 90)) { smartPivotInit = true; cameraController.DisableSmartPivot(); } } } } } }
33.628866
194
0.470877
a490648584f377325ca39c1ab33f0da700dce6c9
1,352
h
C
costa_thread_pool.h
cstriker1407/costa_thread_pool
3afa0838270a97c093ff8c0bd1bddceeebb37ca7
[ "BSD-2-Clause" ]
null
null
null
costa_thread_pool.h
cstriker1407/costa_thread_pool
3afa0838270a97c093ff8c0bd1bddceeebb37ca7
[ "BSD-2-Clause" ]
null
null
null
costa_thread_pool.h
cstriker1407/costa_thread_pool
3afa0838270a97c093ff8c0bd1bddceeebb37ca7
[ "BSD-2-Clause" ]
null
null
null
/* 一个线程池实现 1. written by cstriker1407@yeah.net http://cstriker1407.info/blog/ 2. Follow BSD */ #ifndef COSTA_THREAD_POOL_H #define COSTA_THREAD_POOL_H #include <stdio.h> #include <string.h> #define costa_memset memset #define costa_null 0 #define costa_debug(fmt, ...) printf("[DBG %4d]"fmt"\r\n", __LINE__, ##__VA_ARGS__) #define costa_error(fmt, ...) printf("[ERR %4d]"fmt"\r\n", __LINE__, ##__VA_ARGS__) #ifdef __cplusplus extern "C" { #endif //线程池最大线程数目 #define COSTA_TPOOL_MAX_THREADS 5 typedef enum { COSTA_JOB_START, COSTA_JOB_FINISH }COST_JOB_EVENT; /* 初始化一个线程池 */ int costa_init( unsigned int (*sys_get_time_ms)(void), //获取当前时间毫秒数 void (*sys_new_thread_cb)( void (*job_process)(void *p_thread_param), void *p_thread_param), //系统开启线程回调 void (*sys_lock)(void), //加锁 void (*sys_unlock)(void), //解锁 void (*sys_sleep)(unsigned int sleep_ms), //系统休眠回调 void (*costa_job_event_cb)(void (*costa_job_cb)(void *p_param), COST_JOB_EVENT event) //内存池状态回调, nolock!!! ); /* 添加一个任务 */ int costa_add_job(void (*costa_job_cb)(void *p_param), void *p_param); /* 打印线程池状态 */ void costa_print_status(void); #ifdef __cplusplus } #endif /* __cplusplus */ #endif // COSTA_THREAD_POOL_H
26.509804
122
0.641272
e21c70613c049f8395215dca4cd13f4005eff353
97
py
Python
HJ 108/code.py
swy20190/NiuKe
d9dbbbbac403f5b4fe37efe82f9708aff614f018
[ "MIT" ]
null
null
null
HJ 108/code.py
swy20190/NiuKe
d9dbbbbac403f5b4fe37efe82f9708aff614f018
[ "MIT" ]
null
null
null
HJ 108/code.py
swy20190/NiuKe
d9dbbbbac403f5b4fe37efe82f9708aff614f018
[ "MIT" ]
null
null
null
import math a, b = list(map(int, input().split())) answer = a*b/math.gcd(a, b) print(int(answer))
24.25
38
0.649485
d68f7135fc0065f81647ee1f3548e0c324a76855
2,642
cs
C#
src/SFA.DAS.NotificationService.Infrastructure.Test/Repositories/AccountRepositoryTest.cs
SkillsFundingAgency/das-employerportal
0527ef3a9afb419d750c449d97bd96b6f888ee8a
[ "MIT" ]
2
2017-11-30T14:36:54.000Z
2021-02-22T13:18:55.000Z
src/SFA.DAS.NotificationService.Infrastructure.Test/Repositories/AccountRepositoryTest.cs
SkillsFundingAgency/das-employerportal
0527ef3a9afb419d750c449d97bd96b6f888ee8a
[ "MIT" ]
null
null
null
src/SFA.DAS.NotificationService.Infrastructure.Test/Repositories/AccountRepositoryTest.cs
SkillsFundingAgency/das-employerportal
0527ef3a9afb419d750c449d97bd96b6f888ee8a
[ "MIT" ]
1
2021-04-11T08:53:28.000Z
2021-04-11T08:53:28.000Z
using System.Configuration; using System.Threading.Tasks; using FluentAssertions; using Moq; using NUnit.Framework; using SFA.DAS.Configuration; using SFA.DAS.NotificationService.Application; using SFA.DAS.NotificationService.Domain.Models; using SFA.DAS.NotificationService.Infrastructure.Repositories; namespace SFA.DAS.NotificationService.Infrastructure.Test.Repositories { /// <summary> /// These tests are here to test the full functionaility of the repository as we currently don't use /// all the methods of the repository. These test will later on be replaced by full scale intergration /// test that will test end to end. These tests are ignored by default. /// </summary> [TestFixture] [Ignore("This test is mainly to test the repository code locally as we currently don't have a full integration test yet")] public class AccountRepositoryTest { private Account _account; private AccountRepository _repository; private NotificationServiceConfiguration _configuration; private Mock<IConfigurationService> _configurationServiceMock; [SetUp] public void Init() { _configuration = new NotificationServiceConfiguration { LevyDatabase = new LevyDatabaseConfiguration { ConnectionString = ConfigurationManager.ConnectionStrings["DAS_AML"].ConnectionString } }; _configurationServiceMock = new Mock<IConfigurationService>(); _configurationServiceMock.Setup(x => x.GetAsync<NotificationServiceConfiguration>()).ReturnsAsync(_configuration); _account = new Account { Id = 500, Name = "Test Account" }; _repository = new AccountRepository(_configurationServiceMock.Object); } [Test] public async Task ShouldBeAbleToCreateAndGetAndDeleteAnAccount() { // Save the account _account.Id = await _repository.Save(_account); // Test both the save and get code to make sure the account can be retrieved from the database var result = await _repository.Get(_account.Id); result.Id.Should().Be(_account.Id); result.Name.Trim().Should().Be(_account.Name); // Delete the account await _repository.Delete(_account); // Make sure the account is no longer in the database (it has been deleted) result = await _repository.Get(_account.Id); result.Should().BeNull(); } } }
37.742857
126
0.656699
2f276041429e9e3cca02b176071494e1fd3d2cfb
791
js
JavaScript
misc/task-pkg.js
xiongjia/abathur
f4041b48ad9116fa2e47ab14eac03b2a42b85620
[ "MIT" ]
1
2020-07-24T21:13:53.000Z
2020-07-24T21:13:53.000Z
misc/task-pkg.js
xiongjia/abathur
f4041b48ad9116fa2e47ab14eac03b2a42b85620
[ "MIT" ]
null
null
null
misc/task-pkg.js
xiongjia/abathur
f4041b48ad9116fa2e47ab14eac03b2a42b85620
[ "MIT" ]
null
null
null
'use strict'; exports = module.exports = (opts) => { const gulp = require('gulp'); const { dirs, conf } = opts; gulp.task('deploy', () => { const rsync = require('gulp-rsync'); const rsyncOpt = { root: dirs.DIST + '/', hostname: conf.DEPLOY_HOST, destination: conf.DEPLOY_DEST, chmod: 'ugo=rwX', compress: true, archive: true, delete: true, clean: true, recursive: true }; return gulp.src(dirs.DIST + '/**') .pipe(rsync(rsyncOpt)); }); gulp.task('sitemap', [ 'clean:pkg:sitemap' ], () => { const sitemap = require('gulp-sitemap'); gulp.src(dirs.DIST + '/**/*.html', { read: false }) .pipe(sitemap({ siteUrl: conf.DEPLOY_SITE })) .pipe(gulp.dest(dirs.DIST)); }); };
23.264706
55
0.542351
8b3309e66c0544f5298f424c94014759a163b08f
6,101
rb
Ruby
src/vsphere_cpi/lib/cloud/vsphere/network.rb
miro-grapeup/bosh-vsphere-cpi-release
83439386f9a83049d659cea724ec0526fb1d567f
[ "Apache-2.0" ]
25
2015-06-03T21:42:04.000Z
2018-05-15T08:07:47.000Z
src/vsphere_cpi/lib/cloud/vsphere/network.rb
miro-grapeup/bosh-vsphere-cpi-release
83439386f9a83049d659cea724ec0526fb1d567f
[ "Apache-2.0" ]
163
2018-10-01T19:58:49.000Z
2022-03-29T09:25:19.000Z
src/vsphere_cpi/lib/cloud/vsphere/network.rb
miro-grapeup/bosh-vsphere-cpi-release
83439386f9a83049d659cea724ec0526fb1d567f
[ "Apache-2.0" ]
30
2015-05-26T07:02:10.000Z
2018-05-01T10:30:15.000Z
require 'cloud/vsphere/logger' require 'netaddr' module VSphereCloud class NetworkDeletionError < StandardError end class Network include Logger TAG_SCOPE_NAME = 'bosh_cpi_subnet_id' def initialize(switch_provider, router_provider, ip_block_provider) @switch_provider = switch_provider @router_provider = router_provider @ip_block_provider = ip_block_provider end # Create T1 router and virtual switch attached to it def create(network_definition) begin range_prefix, gateway = identify_subnet_range_prefix_and_gateway(network_definition) edge_cluster_id = get_edge_cluster_id(network_definition.t0_router_id) fail_if_switch_exists(network_definition.switch_name) unless network_definition.switch_name.nil? t1_router_id = create_t1_router(edge_cluster_id, network_definition.t1_name) enable_route_advertisement(t1_router_id) logger.debug("Attaching T1(#{t1_router_id}) to T0(#{network_definition.t0_router_id})") @router_provider.attach_t1_to_t0(network_definition.t0_router_id, t1_router_id) if @block_subnet tags = [ NSXT::Tag.new(scope: TAG_SCOPE_NAME, tag: @block_subnet.id) ] end logger.info("Creating logical switch in zone #{network_definition.transport_zone_id}") switch = @switch_provider.create_logical_switch(network_definition.transport_zone_id, name: network_definition.switch_name, tags: tags) switch_id = switch.id logger.debug("Attaching switch(#{switch_id}) to T1(#{t1_router_id})") attach_switch_to_t1(switch_id, t1_router_id, gateway, range_prefix) rescue => e logger.error('Failed to create network. Trying to clean up') @router_provider.delete_t1_router(t1_router_id) unless t1_router_id.nil? @switch_provider.delete_logical_switch(switch_id) unless switch_id.nil? @ip_block_provider.release_subnet(@block_subnet.id) unless @block_subnet.nil? raise "Failed to create network. Has router been created: #{!t1_router_id.nil?}. Has switch been created: #{!switch_id.nil?}. Exception: #{e.message}" end if @block_subnet ManagedNetwork.new(switch, @block_subnet.cidr, gateway) else ManagedNetwork.new(switch) end end def destroy(switch_id) logger.info("Destroying network infrastructure with switch id #{switch_id}") raise 'switch id must be provided for deleting a network' if switch_id.nil? # check if switch exists first switch = @switch_provider.get_switch_by_id(switch_id) t1_router_ids = @router_provider.get_attached_router_ids(switch_id) raise NetworkDeletionError, "Expected switch #{switch_id} to have one router attached. Found #{t1_router_ids.length}" if t1_router_ids.length != 1 switch_ports = @switch_provider.get_attached_switch_ports(switch_id).select do |logical_port| @switch_provider.get_logical_port_status(logical_port.id) == "UP" end raise NetworkDeletionError, "Expected switch #{switch_id} to have at most one operational port but found #{switch_ports.length}" if switch_ports.length > 1 release_subnets(switch.tags) logger.debug("Deleting logical switch with id #{switch_id}") @switch_provider.delete_logical_switch(switch_id) t1_router_id = t1_router_ids.first attached_switches = @router_provider.get_attached_switches_ids(t1_router_id) raise NetworkDeletionError, "Can not delete router #{t1_router_id}. It has extra ports that are not created by BOSH." if attached_switches.length != 0 logger.debug("Detach T1 router #{t1_router_id} from T0") @router_provider.detach_t1_from_t0(t1_router_id) logger.debug("Deleteing router with id #{t1_router_id}") @router_provider.delete_t1_router(t1_router_id) end private def identify_subnet_range_prefix_and_gateway(network_definition) if network_definition.has_range? [network_definition.range_prefix, network_definition.gateway] else logger.debug("Trying to allocate subnet in ip block #{network_definition.ip_block_id}") @block_subnet = @ip_block_provider.allocate_cidr_range(network_definition.ip_block_id, block_size(network_definition.netmask_bits)) logger.info("Allocated subnet #{@block_subnet.cidr} in block #{network_definition.ip_block_id}") block_subnet_cidr = NetAddr::CIDR.create(@block_subnet.cidr).to_i [network_definition.netmask_bits, NetAddr::CIDR.create(block_subnet_cidr + 1).ip] end end def get_edge_cluster_id(t0_router_id) logger.debug("Getting edge cluster id of router #{t0_router_id}") @router_provider.get_edge_cluster_id(t0_router_id) end def create_t1_router(edge_cluster_id, t1_name) logger.info("Creating T1 router in cluster #{edge_cluster_id}") @router_provider.create_t1_router(edge_cluster_id, t1_name).id end def enable_route_advertisement(t1_router_id) logger.debug("Enable route advertisement for router #{t1_router_id}") @router_provider.enable_route_advertisement(t1_router_id) end def block_size(netmask_bits) 2 ** (32 - netmask_bits) end def release_subnets(tags) return if tags.nil? tags.each do |tag| if tag.scope == TAG_SCOPE_NAME logger.debug("Releasing subnet with id #{tag.tag}") @ip_block_provider.release_subnet(tag.tag) end end end def attach_switch_to_t1(switch_id, t1_router_id, ip_address, prefix_length) logical_port = @switch_provider.create_logical_port(switch_id) @router_provider.attach_switch_to_t1(logical_port.id, t1_router_id, ip_address, prefix_length) end def fail_if_switch_exists(switch_name) switches = @switch_provider.get_switches_by_name(switch_name) raise "Switch #{switch_name} already exists. Please use different name." if switches.length > 0 end end end
44.210145
161
0.725291
af3ecbc7455964d383a8e70358b013e18918674d
1,518
py
Python
byceps/blueprints/admin/webhook/forms.py
GyBraLAN/byceps
b53087849c10a531b66d08999116fa1bef312a7f
[ "BSD-3-Clause" ]
null
null
null
byceps/blueprints/admin/webhook/forms.py
GyBraLAN/byceps
b53087849c10a531b66d08999116fa1bef312a7f
[ "BSD-3-Clause" ]
null
null
null
byceps/blueprints/admin/webhook/forms.py
GyBraLAN/byceps
b53087849c10a531b66d08999116fa1bef312a7f
[ "BSD-3-Clause" ]
null
null
null
""" byceps.blueprints.admin.webhook.forms ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ :Copyright: 2006-2021 Jochen Kupperschmidt :License: Revised BSD (see `LICENSE` file for details) """ from __future__ import annotations from flask_babel import lazy_gettext from wtforms import BooleanField, SelectMultipleField, StringField from wtforms.validators import InputRequired, Optional from wtforms.widgets import CheckboxInput, ListWidget from ....announce.events import EVENT_TYPES_TO_NAMES from ....util.l10n import LocalizedForm class MultiCheckboxField(SelectMultipleField): widget = ListWidget(prefix_label=False) option_widget = CheckboxInput() def _get_event_type_choices() -> list[tuple[str, str]]: event_names = EVENT_TYPES_TO_NAMES.values() return [(event_name, event_name) for event_name in sorted(event_names)] class _BaseForm(LocalizedForm): description = StringField(lazy_gettext('Description'), [InputRequired()]) format = StringField(lazy_gettext('Format'), [InputRequired()]) url = StringField(lazy_gettext('URL'), [InputRequired()]) event_types = MultiCheckboxField( lazy_gettext('Event types'), choices=_get_event_type_choices(), validators=[InputRequired()], ) class CreateForm(_BaseForm): pass class UpdateForm(_BaseForm): text_prefix = StringField(lazy_gettext('Text prefix'), [Optional()]) extra_fields = StringField(lazy_gettext('Additional fields'), [Optional()]) enabled = BooleanField(lazy_gettext('Enabled'))
30.979592
79
0.737813
80133ae8712f8135d6c92bcdfaaa667b3038bcb1
2,737
psd1
PowerShell
DSC/Modules/xStorage/2.9.0.0/DSCResources/MSFT_xDiskAccessPath/en-us/MSFT_xDiskAccessPath.strings.psd1
Matticusau/WorkShopSQLAutomation
e0e5782be45a6b255ace6119c3bdde2dbf5f5dec
[ "MIT" ]
1
2018-11-23T16:51:30.000Z
2018-11-23T16:51:30.000Z
DSC/Modules/xStorage/2.9.0.0/DSCResources/MSFT_xDiskAccessPath/en-us/MSFT_xDiskAccessPath.strings.psd1
Matticusau/WorkShopSQLAutomation
e0e5782be45a6b255ace6119c3bdde2dbf5f5dec
[ "MIT" ]
null
null
null
DSC/Modules/xStorage/2.9.0.0/DSCResources/MSFT_xDiskAccessPath/en-us/MSFT_xDiskAccessPath.strings.psd1
Matticusau/WorkShopSQLAutomation
e0e5782be45a6b255ace6119c3bdde2dbf5f5dec
[ "MIT" ]
null
null
null
ConvertFrom-StringData @' GettingDiskMessage = Getting Disk '{0}' status for access path '{1}'. SettingDiskMessage = Setting Disk '{0}' status for access path '{1}'. SetDiskOnlineMessage = Setting disk number '{0}' is online. SetDiskReadwriteMessage = Setting disk number '{0}' to read/write. CheckingDiskPartitionStyleMessage = Checking disk number '{0}' partition style. InitializingDiskMessage = Initializing disk number '{0}'. DiskAlreadyInitializedMessage = Disk number '{0}' is already initialized with GPT. CreatingPartitionMessage = Creating partition on disk number '{0}' using {1}. FormattingVolumeMessage = Formatting the volume as '{0}'. SuccessfullyInitializedMessage = Successfully initialized volume and assigned to access path '{0}'. ChangingDriveLetterMessage = The volume already exists, changing access path '{0}' to '{1}'. AssigningDriveLetterMessage = Assigning access path '{0}'. ChangingVolumeLabelMessage = Changing Volume assigned to access path '{0}' label to '{1}'. NewPartitionIsReadOnlyMessage = New partition '{1}' on disk '{0}' is readonly. Waiting for it to become writable. TestingDiskMessage = Testing Disk '{0}' status for access path '{1}'. CheckDiskInitializedMessage = Checking if disk number '{0}' is initialized. DiskNotFoundMessage = Disk number '{0}' was not found. DiskNotOnlineMessage = Disk number '{0}' is not online. DiskReadOnlyMessage = Disk number '{0}' is readonly. DiskNotGPTMessage = Disk number '{0}' is initialised with '{1}' partition style. GPT required. AccessPathNotFoundMessage = A volume assigned to access path '{0}' was not found. SizeMismatchMessage = Volume assigned to access path '{0}' has size {1}, which does not match expected size {2}. AllocationUnitSizeMismatchMessage = Volume assigned to access path '{0}' has allocation unit size {1} KB does not match expected allocation unit size {2} KB. FileSystemFormatMismatch = Volume assigned to access path '{0}' filesystem format '{1}' does not match expected format '{2}'. DriveLabelMismatch = Volume assigned to access path '{0}' label '{1}' does not match expected label '{2}'. PartitionAlreadyAssignedMessage = Partition '{1}' is already assigned to access path '{0}'. MatchingPartitionNotFoundMessage = Disk number '{0}' already contains paritions, but none match required size. MatchingPartitionFoundMessage = Disk number '{0}' already contains paritions, and partition '{1}' matches required size. DiskAlreadyInitializedError = Disk number '{0}' is already initialized with {1}. NewParitionIsReadOnlyError = New partition '{1}' on disk '{0}' did not become writable in the expected time. '@
80.5
161
0.735477
367945348e4cbedd37ef4571bf517d1b1356f4b2
287
rs
Rust
crates/plugins/binarizer/src/compilers/mod.rs
gents83/INOX
8ff4f851ab6493b9d613fce4a08bb0ba58dee568
[ "MIT" ]
5
2022-02-27T12:48:52.000Z
2022-03-26T17:57:59.000Z
crates/plugins/binarizer/src/compilers/mod.rs
gents83/SABI
8ff4f851ab6493b9d613fce4a08bb0ba58dee568
[ "MIT" ]
1
2022-03-14T17:02:23.000Z
2022-03-14T17:02:23.000Z
crates/plugins/binarizer/src/compilers/mod.rs
gents83/SABI
8ff4f851ab6493b9d613fce4a08bb0ba58dee568
[ "MIT" ]
null
null
null
pub use crate::copy_compiler::*; pub use crate::font_compiler::*; pub use crate::gltf_compiler::*; pub use crate::image_compiler::*; pub use crate::shader_compiler::*; pub mod copy_compiler; pub mod font_compiler; pub mod gltf_compiler; pub mod image_compiler; pub mod shader_compiler;
23.916667
34
0.770035
0dba7393495d7e47c16bb6023d8e907755beff16
800
cs
C#
src/Essensoft.AspNetCore.Payment.Alipay/Domain/AlipayFinancialnetAuthCommoditySyncModel.cs
lzw316/payment
8e19d096d1ad38c64b1d930d4886eceb41bd7013
[ "MIT" ]
null
null
null
src/Essensoft.AspNetCore.Payment.Alipay/Domain/AlipayFinancialnetAuthCommoditySyncModel.cs
lzw316/payment
8e19d096d1ad38c64b1d930d4886eceb41bd7013
[ "MIT" ]
null
null
null
src/Essensoft.AspNetCore.Payment.Alipay/Domain/AlipayFinancialnetAuthCommoditySyncModel.cs
lzw316/payment
8e19d096d1ad38c64b1d930d4886eceb41bd7013
[ "MIT" ]
null
null
null
using System.Collections.Generic; using System.Text.Json.Serialization; namespace Essensoft.AspNetCore.Payment.Alipay.Domain { /// <summary> /// AlipayFinancialnetAuthCommoditySyncModel Data Structure. /// </summary> public class AlipayFinancialnetAuthCommoditySyncModel : AlipayObject { /// <summary> /// 同步商品信息 /// </summary> [JsonPropertyName("commodity_infos")] public List<CommodityInfoList> CommodityInfos { get; set; } /// <summary> /// 幂等字段 /// </summary> [JsonPropertyName("out_order_no")] public string OutOrderNo { get; set; } /// <summary> /// 平台标识 /// </summary> [JsonPropertyName("platform_id")] public string PlatformId { get; set; } } }
26.666667
72
0.60375
79b538b6194649c69d38090577d7f65c897d2372
984
php
PHP
routes/admin.php
syedurrhmn/zend43
29cea34a248ccc22e4d791139eb8256c277eec20
[ "MIT" ]
1
2019-12-05T04:57:55.000Z
2019-12-05T04:57:55.000Z
routes/admin.php
therokan/zend43
29cea34a248ccc22e4d791139eb8256c277eec20
[ "MIT" ]
4
2021-03-10T01:21:34.000Z
2022-02-26T21:07:21.000Z
routes/admin.php
syedurrhmn/zend43
29cea34a248ccc22e4d791139eb8256c277eec20
[ "MIT" ]
null
null
null
<?php /* Admin Routes */ Auth::routes(); Route::group(['prefix' => 'admin'], function () { Route::get('login', 'Admin\LoginController@showLoginForm')->name('admin.login'); Route::post('login', 'Admin\LoginController@login')->name('admin.login.post'); Route::get('logout', 'Admin\LoginController@logout')->name('admin.logout'); Route::group(['middleware' => ['auth:admin']], function () { Route::get('/', function () { return view('admin.dashboard.index'); })->name('admin.dashboard'); }); }); /* Route::get('/admin', function(){ return view('admin.dashboard.index'); }); Route::get('/dashboard2', function(){ return view('admin.dashboard.index2'); }); Route::get('/calendar', function(){ return view('admin.dashboard.calendar'); }); Route::get('/page-error', function(){ return view('admin.dashboard.page-error'); }); Route::get('/invoice', function(){ return view('admin.dashboard.invoice'); }); */
22.883721
84
0.60874
15cfaed0176ff52960c936723b9bd4150fd0e8c3
1,266
swift
Swift
Sources/App/Models/Hello.swift
calzam/NearbyServer
2513addb44c03b52491e89ceebbd0ac777201bf3
[ "MIT" ]
null
null
null
Sources/App/Models/Hello.swift
calzam/NearbyServer
2513addb44c03b52491e89ceebbd0ac777201bf3
[ "MIT" ]
null
null
null
Sources/App/Models/Hello.swift
calzam/NearbyServer
2513addb44c03b52491e89ceebbd0ac777201bf3
[ "MIT" ]
null
null
null
// // Hello.swift // App // // Created by Marco Calzana on 23.11.17. // import Vapor import FluentProvider import HTTP final class Hello: Model { let storage = Storage() enum Keys { static let message = "message" } let message: String init(message: String) { self.message = message } func makeRow() throws -> Row { var row = Row() try row.set(Keys.message, message) return row } init(row: Row) throws { message = try row.get(Keys.message) } } extension Hello: Preparation { static func prepare(_ database: Database) throws { try database.create(self) { builder in builder.id() builder.string(Keys.message) } } static func revert(_ database: Database) throws { try database.delete(self) } } extension Hello: JSONConvertible { func makeJSON() throws -> JSON { // return try JSON(makeRow()) var json = JSON() try json.set(Keys.message, message) return json } convenience init(json: JSON) throws { self.init( message: try json.get(Keys.message) ) } } extension Hello: ResponseRepresentable {}
18.895522
54
0.567141
8511e70dc47fcabd7f3014c56cb358c2918cb4fd
1,141
cs
C#
test/cafe.Test/ProgramTest.cs
bizsbuzz/cafe
14e7ae3a33eb92f83dc938a47d1dc6d9474609eb
[ "Apache-2.0" ]
30
2016-12-14T21:11:01.000Z
2021-01-03T02:59:24.000Z
test/cafe.Test/ProgramTest.cs
bizsbuzz/cafe
14e7ae3a33eb92f83dc938a47d1dc6d9474609eb
[ "Apache-2.0" ]
23
2017-01-23T23:18:01.000Z
2017-06-20T01:11:01.000Z
test/cafe.Test/ProgramTest.cs
bizsbuzz/cafe
14e7ae3a33eb92f83dc938a47d1dc6d9474609eb
[ "Apache-2.0" ]
16
2016-12-15T15:06:07.000Z
2020-06-03T13:44:49.000Z
using cafe.CommandLine; using FluentAssertions; using Xunit; namespace cafe.Test { public class ProgramTest { [Fact] public void LogConfigurationFile_ShouldBeClientForNoArguments() { AssertLogConfigurationFileIs("nlog-client.config"); } [Fact] public void LogConfigurationFile_ShouldBeClientForNonServerArguments() { AssertLogConfigurationFileIs("nlog-client.config", "chef", "run"); } [Fact] public void LogConfigurationFile_ShouldBeServerForServerArgument() { AssertLogConfigurationFileIs("nlog-server.config", "server"); } [Fact] public void LogConfigurationFile_ShouldBeServerForServerRunAsServiceArguments() { AssertLogConfigurationFileIs(LoggingInitializer.ServerLoggingConfigurationFile, "server", "--run-as-service"); } private void AssertLogConfigurationFileIs(string expectedConfigFile, params string[] args) { LoggingInitializer.LoggingConfigurationFileFor(args).Should().Be(expectedConfigFile); } } }
30.837838
122
0.666959
a7d88f6890bd2036a8c5049529863073f3d705ff
509
sql
SQL
Security/db_dsmrapi.sql
sensate-iot/dsmr-product-database
c0c791939cc19acc0846609665f082cdb77c9a1b
[ "Apache-2.0" ]
null
null
null
Security/db_dsmrapi.sql
sensate-iot/dsmr-product-database
c0c791939cc19acc0846609665f082cdb77c9a1b
[ "Apache-2.0" ]
null
null
null
Security/db_dsmrapi.sql
sensate-iot/dsmr-product-database
c0c791939cc19acc0846609665f082cdb77c9a1b
[ "Apache-2.0" ]
null
null
null
CREATE ROLE [db_dsmrapi] GO GRANT EXECUTE ON [dbo].[DsmrApi_GetProductToken] TO [db_dsmrapi] GO GRANT EXECUTE ON [dbo].[DsmrApi_GetSensorsByUserId] TO [db_dsmrapi] GO GRANT EXECUTE ON [dbo].[DsmrApi_SelectUserById] TO [db_dsmrapi] GO GRANT EXECUTE ON [dbo].[DsmrApi_SelectDevicesForUser] TO [db_dsmrapi] GO GRANT EXECUTE ON [dbo].[DsmrApi_Login] TO [db_dsmrapi] GO GRANT EXECUTE ON [dbo].[DsmrApi_Logout] TO [db_dsmrapi] GO GRANT EXECUTE ON [dbo].[DsmrApi_ResetOtpToken] TO [db_dsmrapi] GO
28.277778
70
0.75835
2c9c9eb503ff60d2b2cea463b4a5559931a2e01d
287
py
Python
mpirical/exceptions.py
NCAR/mpi-pytest
b4a181c902dd57fe7fa555f80d9dd6ba26a9c0fa
[ "Apache-2.0" ]
11
2019-02-26T03:08:05.000Z
2021-03-07T00:32:14.000Z
mpirical/exceptions.py
NCAR/mpi-pytest
b4a181c902dd57fe7fa555f80d9dd6ba26a9c0fa
[ "Apache-2.0" ]
20
2019-02-14T00:08:12.000Z
2020-01-17T00:26:32.000Z
mpirical/exceptions.py
NCAR/mpi-pytest
b4a181c902dd57fe7fa555f80d9dd6ba26a9c0fa
[ "Apache-2.0" ]
2
2019-12-19T21:09:50.000Z
2019-12-20T18:05:48.000Z
from sys import exc_info from six import reraise class ExceptionInfo(object): """A wrapper class for exceptions and traceback information""" def __init__(self, rank): self.rank = rank self.info = exc_info() def reraise(self): reraise(*self.info)
19.133333
66
0.662021
7d103d6a5b76207a684436488b16f08d01fad712
1,180
rs
Rust
src/macros.rs
mellium/communique-gtk
1f35ea3fde4d75dbc4d0ba640ff7ad46f2c70c0b
[ "BSD-2-Clause" ]
null
null
null
src/macros.rs
mellium/communique-gtk
1f35ea3fde4d75dbc4d0ba640ff7ad46f2c70c0b
[ "BSD-2-Clause" ]
null
null
null
src/macros.rs
mellium/communique-gtk
1f35ea3fde4d75dbc4d0ba640ff7ad46f2c70c0b
[ "BSD-2-Clause" ]
null
null
null
/// Makes it easier to clone GTK objects before moving them into closures. /// Borrowed from the gtk-rs examples. macro_rules! clone { (@param _) => ( _ ); (@param $x:ident) => ( $x ); ($($n:ident),+ => move || $body:expr) => ( { $( let $n = $n.clone(); )+ move || $body } ); ($($n:ident),+ => move |$($p:tt),+| $body:expr) => ( { $( let $n = $n.clone(); )+ move |$(clone!(@param $p),)+| $body } ); } /// Fetches a translation given the language and a key representing the string. macro_rules! translate( ( $key:expr ) => { { use crate::res::strings::{LANG, STRINGS}; match STRINGS.get(LANG.as_str()).unwrap_or(&STRINGS["en-us"]).get($key) { None => &STRINGS["en-us"][$key], Some(s) => *s, } } }; // These two variants should only be used internally and are for defining translation maps. { $($key:expr => $value:expr,)+ } => { { let mut m = ::std::collections::HashMap::new(); $( m.insert($key, $value); )+ m } }; );
28.780488
95
0.455932
ebfa4d9ab604599357aa58b268478f7d5f7c2c4e
1,256
swift
Swift
Yelp/DealSwitchTableViewCell.swift
jerlao/Yelp
c19b9983af705647660ab5bf5e48cb3124204843
[ "Apache-2.0" ]
null
null
null
Yelp/DealSwitchTableViewCell.swift
jerlao/Yelp
c19b9983af705647660ab5bf5e48cb3124204843
[ "Apache-2.0" ]
1
2016-02-15T00:34:21.000Z
2016-02-15T14:01:48.000Z
Yelp/DealSwitchTableViewCell.swift
jerlao/Yelp
c19b9983af705647660ab5bf5e48cb3124204843
[ "Apache-2.0" ]
null
null
null
// // DealSwitchTableViewCell.swift // Yelp // // Created by Jerry on 2/13/16. // Copyright © 2016 Timothy Lee. All rights reserved. // import UIKit @objc protocol DealSwitchTableViewCellDelegate { optional func dealSwitchTableViewCell(dealCell: DealSwitchTableViewCell, didChangeValue value: Bool) } class DealSwitchTableViewCell: UITableViewCell { @IBOutlet weak var dealLabel: UILabel! @IBOutlet weak var dealSwitch: UISwitch! weak var delegate:DealSwitchTableViewCellDelegate? override func awakeFromNib() { super.awakeFromNib() // Initialization code self.dealSwitch.addTarget(self, action: "onSwitchChanged", forControlEvents: UIControlEvents.ValueChanged) self.dealSwitch.tintColor = UIColor(red: 255/255, green: 126/255, blue: 126/255, alpha: 1) self.dealSwitch.thumbTintColor = UIColor(red: 255/255, green: 126/255, blue: 126/255, alpha: 1) } override func setSelected(selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } func onSwitchChanged() { self.delegate?.dealSwitchTableViewCell?(self, didChangeValue: self.dealSwitch.on) } }
30.634146
114
0.705414
4cda262e37f5f77dc90b16fcf05b9cb0974a8969
499
py
Python
fitbark_tests/__init__.py
alexhouse/python-fitbark
8a665c8974829079781fb6e65fbe8b4fe3d1e5da
[ "Apache-2.0" ]
1
2019-03-12T04:48:55.000Z
2019-03-12T04:48:55.000Z
fitbark_tests/__init__.py
alexhouse/python-fitbark
8a665c8974829079781fb6e65fbe8b4fe3d1e5da
[ "Apache-2.0" ]
null
null
null
fitbark_tests/__init__.py
alexhouse/python-fitbark
8a665c8974829079781fb6e65fbe8b4fe3d1e5da
[ "Apache-2.0" ]
1
2020-07-16T07:01:51.000Z
2020-07-16T07:01:51.000Z
import unittest from .test_api import ( APITest, ResourceAccessTest ) from .test_auth import Auth2Test from .test_exceptions import ExceptionTest def all_tests(consumer_key="", consumer_secret="", user_key=None, user_secret=None): suite = unittest.TestSuite() suite.addTest(unittest.makeSuite(ExceptionTest)) suite.addTest(unittest.makeSuite(Auth2Test)) suite.addTest(unittest.makeSuite(APITest)) suite.addTest(unittest.makeSuite(ResourceAccessTest)) return suite
27.722222
84
0.771543
907b61cd17f632d327987f08ba503b56290d96d9
991
swift
Swift
Handy/UILayoutGuide.swift
bumpersfm/handy
1bbe17cee73ace6c71efdae5570faab5b1a14a82
[ "MIT" ]
null
null
null
Handy/UILayoutGuide.swift
bumpersfm/handy
1bbe17cee73ace6c71efdae5570faab5b1a14a82
[ "MIT" ]
null
null
null
Handy/UILayoutGuide.swift
bumpersfm/handy
1bbe17cee73ace6c71efdae5570faab5b1a14a82
[ "MIT" ]
null
null
null
// // Created by Dani Postigo on 11/25/16. // import Foundation import UIKit extension UILayoutGuide { public func anchor(withSubview view: UIView, insets: UIEdgeInsets? = nil) { view.preservesSuperviewLayoutMargins = true self.anchor(toViewFrame: view) } public func anchor(toViewFrame view: UIView, insets: UIEdgeInsets? = nil) { NSLayoutConstraint.activateConstraints([ self.leadingAnchor.constraintEqualToAnchor(view.leadingAnchor), self.trailingAnchor.constraintEqualToAnchor(view.trailingAnchor), self.topAnchor.constraintEqualToAnchor(view.topAnchor), self.bottomAnchor.constraintEqualToAnchor(view.bottomAnchor), ]) } } extension UIView { public func anchor(view: UIView, layoutMargins margins: UIEdgeInsets? = nil) { self.addView(view) self.layoutMargins = margins ?? self.layoutMargins self.layoutMarginsGuide.anchor(withSubview: view) } }
30.96875
82
0.695257
04ac38eee27345e25ebe1af74fc4d5584b8d7eef
657
dart
Dart
dart/tosser.dart
ewilderj/coin-tosser
dbb78efed32eefb23f2ef00659c8187e642cad77
[ "MIT" ]
1
2021-01-27T08:35:06.000Z
2021-01-27T08:35:06.000Z
dart/tosser.dart
ewilderj/coin-tosser
dbb78efed32eefb23f2ef00659c8187e642cad77
[ "MIT" ]
null
null
null
dart/tosser.dart
ewilderj/coin-tosser
dbb78efed32eefb23f2ef00659c8187e642cad77
[ "MIT" ]
null
null
null
#library('tosser'); #import('dart:html'); #source('Util.dart'); #source('Game.dart'); #source('Experiment.dart'); class tosser { void main() { document.query("#input_form").on.submit.add((e) { // stop form submitting, then run the experiment e.preventDefault(); run(); }); } int getParameter(String param) { InputElement ele = document.query("#${param}"); return Math.parseInt(ele.value); } void run() { Experiment e = new Experiment(getParameter("runs"), getParameter("tosses")); e.run(); document.query('#results').innerHTML = e.asciiGraph(); } } void main() { new tosser().main(); }
19.323529
80
0.608828
b0be2dab3a63f0cb3d9d3bdfab2cb2812cc2a281
1,919
py
Python
cms/migrations/0010_auto_20160526_2100.py
porimol/django-blog
3f6b1241a33bfe86049b9bf20c9325323a795513
[ "MIT" ]
null
null
null
cms/migrations/0010_auto_20160526_2100.py
porimol/django-blog
3f6b1241a33bfe86049b9bf20c9325323a795513
[ "MIT" ]
null
null
null
cms/migrations/0010_auto_20160526_2100.py
porimol/django-blog
3f6b1241a33bfe86049b9bf20c9325323a795513
[ "MIT" ]
null
null
null
# -*- coding: utf-8 -*- # Generated by Django 1.9.4 on 2016-05-26 21:00 from __future__ import unicode_literals import ckeditor.fields from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('cms', '0009_auto_20160523_2050'), ] operations = [ migrations.CreateModel( name='CategoryToPost', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ], ), migrations.AlterModelOptions( name='category', options={'verbose_name_plural': 'Categories'}, ), migrations.RemoveField( model_name='post', name='category', ), migrations.AlterField( model_name='category', name='description', field=ckeditor.fields.RichTextField(), ), migrations.AlterField( model_name='post', name='description', field=ckeditor.fields.RichTextField(), ), migrations.AlterField( model_name='tag', name='description', field=ckeditor.fields.RichTextField(), ), migrations.AddField( model_name='categorytopost', name='category', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='cms.Category'), ), migrations.AddField( model_name='categorytopost', name='post', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='cms.Post'), ), migrations.AddField( model_name='post', name='categories', field=models.ManyToManyField(blank=True, null=True, through='cms.CategoryToPost', to='cms.Category'), ), ]
30.951613
114
0.574257
5ad7ac327673db9b5e6d381e5c5fab2087e39b8f
1,890
cs
C#
Source/Xoqal.Utilities/Attributes/ValidExtensionsAttribute.cs
AmirKarimi/Xoqal
7186f41c9bd06a6b5201206e0cb38aae0282b77a
[ "Apache-2.0" ]
7
2015-07-19T05:36:13.000Z
2016-05-21T12:49:48.000Z
Source/Xoqal.Utilities/Attributes/ValidExtensionsAttribute.cs
AmirKarimi/Xoqal
7186f41c9bd06a6b5201206e0cb38aae0282b77a
[ "Apache-2.0" ]
null
null
null
Source/Xoqal.Utilities/Attributes/ValidExtensionsAttribute.cs
AmirKarimi/Xoqal
7186f41c9bd06a6b5201206e0cb38aae0282b77a
[ "Apache-2.0" ]
1
2015-06-17T23:15:36.000Z
2015-06-17T23:15:36.000Z
#region License // ValidExtensionsAttribute.cs // // Copyright (c) 2012 Xoqal.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. #endregion namespace Xoqal.Utilities.Attributes { using System; using System.Linq; /// <summary> /// /// </summary> /// <seealso cref="System.Attribute" /> [AttributeUsage(AttributeTargets.All, Inherited = false, AllowMultiple = true)] public class ValidExtensionsAttribute : Attribute { private readonly string extensionList; /// <summary> /// Initializes a new instance of the <see cref="ValidExtensionsAttribute" /> class. /// </summary> /// <param name="extensions"> The extensions. </param> public ValidExtensionsAttribute(string extensions) { this.extensionList = extensions; } /// <summary> /// Gets the extensions in comma separated format. /// </summary> /// <value> The extensions in comma separated format. </value> public string ExtensionList { get { return this.extensionList; } } /// <summary> /// Gets the extensions. /// </summary> /// <returns> </returns> public string[] GetExtentions() { return this.extensionList.Split(',').Select(e => e.Trim().ToLower()).ToArray(); } } }
30.983607
92
0.628571
23caa0d68ac33c632be85c4742baaa41eaac497e
2,201
js
JavaScript
build/translations/eo.js
minki607/ckeditor5-build-classic
f990b9f6e4a321970c097b552e6857e00500606b
[ "MIT" ]
null
null
null
build/translations/eo.js
minki607/ckeditor5-build-classic
f990b9f6e4a321970c097b552e6857e00500606b
[ "MIT" ]
null
null
null
build/translations/eo.js
minki607/ckeditor5-build-classic
f990b9f6e4a321970c097b552e6857e00500606b
[ "MIT" ]
null
null
null
(function(d){d['eo']=Object.assign(d['eo']||{},{a:"Cannot upload file:",b:"Image toolbar",c:"Table toolbar",d:"Saving changes",e:"Words: %0",f:"Characters: %0",g:"grasa",h:"kursiva",i:"Block quote",j:"Underline",k:"Skribu klarigon pri la bildo",l:"Bildo kun reala dimensio",m:"Flanka biildo",n:"Left aligned image",o:"Centered image",p:"Right aligned image",q:"bilda fenestraĵo",r:"Insert image or file",s:"Enmetu bildon",t:"Upload failed",u:"media widget",v:"Elektu ĉapon",w:"Ĉapo",x:"Insert media",y:"The URL must not be empty.",z:"This media URL is not supported.",aa:"Ligilo",ab:"Numerita Listo",ac:"Bula Listo",ad:"Insert table",ae:"Header column",af:"Insert column left",ag:"Insert column right",ah:"Delete column",ai:"Column",aj:"Header row",ak:"Insert row below",al:"Insert row above",am:"Delete row",an:"Row",ao:"Merge cell up",ap:"Merge cell right",aq:"Merge cell down",ar:"Merge cell left",as:"Split cell vertically",at:"Split cell horizontally",au:"Merge cells",av:"Increase indent",aw:"Decrease indent",ax:"Upload in progress",ay:"Widget toolbar",az:"Yellow marker",ba:"Green marker",bb:"Pink marker",bc:"Blue marker",bd:"Red pen",be:"Green pen",bf:"Remove highlight",bg:"Highlight",bh:"Text highlight toolbar",bi:"Align left",bj:"Align right",bk:"Align center",bl:"Justify",bm:"Text alignment",bn:"Text alignment toolbar",bo:"Ŝanĝu la alternativan tekston de la bildo",bp:"Could not obtain resized image URL.",bq:"Selecting resized image failed",br:"Could not insert image at the current position.",bs:"Inserting image failed",bt:"Redaktilo de Riĉa Teksto",bu:"Editor toolbar",bv:"Show more items",bw:"%0 of %1",bx:"Previous",by:"Next",bz:"Dropdown toolbar",ca:"Konservi",cb:"Nuligi",cc:"Alternativa teksto",cd:"Malfari",ce:"Refari",cf:"Open in a new tab",cg:"Downloadable",ch:"URL de la ligilo",ci:"Malligi",cj:"Edit link",ck:"Open link in new tab",cl:"This link has no URL",cm:"Paragrafo",cn:"Ĉapo 1",co:"Ĉapo 2",cp:"Ĉapo 3",cq:"Heading 4",cr:"Heading 5",cs:"Heading 6",ct:"Paste the media URL in the input.",cu:"Tip: Paste the URL into the content to embed faster.",cv:"Media URL",cw:"Redaktilo de Riĉa Teksto, %0"})})(window.CKEDITOR_TRANSLATIONS||(window.CKEDITOR_TRANSLATIONS={}));
2,201
2,201
0.718764
2571546992cd7232497698a933274757702699f3
39
html
HTML
src/app/alert-loader/alert-loader.component.html
jyasveer/fabric8-analytics-dependency-editor
d28e1ce39431ea2f71e8ce6e8d8215d5854a00ec
[ "Apache-2.0" ]
null
null
null
src/app/alert-loader/alert-loader.component.html
jyasveer/fabric8-analytics-dependency-editor
d28e1ce39431ea2f71e8ce6e8d8215d5854a00ec
[ "Apache-2.0" ]
25
2018-03-19T09:47:28.000Z
2018-08-31T06:02:51.000Z
src/app/alert-loader/alert-loader.component.html
jyasveer/fabric8-analytics-dependency-editor
d28e1ce39431ea2f71e8ce6e8d8215d5854a00ec
[ "Apache-2.0" ]
5
2017-12-22T11:23:47.000Z
2018-01-30T08:37:49.000Z
<div class="spinner spinner-lg"></div>
19.5
38
0.692308
f1dbc8d80bf9e68023b5cad72f003e383a2286d6
213
builder
Ruby
app/views/spree/products/_props.rss.builder
mdavo6/spree_product_feed
bbd7617d26317af33bed5aacae8d883b5291b22e
[ "MIT" ]
8
2020-05-25T11:48:54.000Z
2021-10-19T22:57:18.000Z
app/views/spree/products/_props.rss.builder
mdavo6/spree_product_feed
bbd7617d26317af33bed5aacae8d883b5291b22e
[ "MIT" ]
2
2020-05-22T09:27:06.000Z
2021-08-11T01:26:08.000Z
app/views/spree/products/_props.rss.builder
mdavo6/spree_product_feed
bbd7617d26317af33bed5aacae8d883b5291b22e
[ "MIT" ]
9
2020-05-25T08:52:21.000Z
2021-10-18T18:02:34.000Z
product.product_properties.each do |product_property| if product_property.property.presentation.downcase == "product_feed" xml.tag!(product_property.property.name.downcase, product_property.value) end end
35.5
77
0.816901
afd853e97f60d5889670a0048c5aa1cf1fa587c5
2,763
rs
Rust
exercise/docs/src/lib.rs
XanderXAJ/ultimate_rust2
327dec3d3b788317493cc2aba78cce0bb76c7b40
[ "MIT" ]
null
null
null
exercise/docs/src/lib.rs
XanderXAJ/ultimate_rust2
327dec3d3b788317493cc2aba78cce0bb76c7b40
[ "MIT" ]
null
null
null
exercise/docs/src/lib.rs
XanderXAJ/ultimate_rust2
327dec3d3b788317493cc2aba78cce0bb76c7b40
[ "MIT" ]
null
null
null
// 1. Thank you for volunteering to document our pumpkin library! Let's start by grabbing the first // paragraph from https://en.wikipedia.org/wiki/Pumpkin and pasting it as our module-level // documentation. Hint: Use inner-documentation comments. // // Once you've got the documentation here, run `cargo doc --no-deps --open` and take a look! //! A pumpkin is a cultivar of winter squash that is round with smooth, slightly ribbed skin, and is most often deep yellow to orange in coloration. The thick shell contains the seeds and pulp. The name is most commonly used for cultivars of Cucurbita pepo, but some cultivars of Cucurbita maxima, C. argyrosperma, and C. moschata with similar appearance are also sometimes called "pumpkin". // 2. What about an image!? Add an image of a pumpkin to the end of the module-level documentation. // The markdown format is ![some alt text](https://url-to-the-image.png) // Here's the image to link to: https://upload.wikimedia.org/wikipedia/commons/thumb/5/5c/FrenchMarketPumpkinsB.jpg/700px-FrenchMarketPumpkinsB.jpg //! ![a pile of pumpkins](https://upload.wikimedia.org/wikipedia/commons/thumb/5/5c/FrenchMarketPumpkinsB.jpg/700px-FrenchMarketPumpkinsB.jpg) // 3. Document the Pumpkin struct. // - The description on the index page should be "Big orange thing" // - Make a section header called "Recipes" // - Explain that recipes will be coming soon. // - Document the "roundness" field, explaining that it is a percentage // - Document the "orangeness" field, explaining that it is a number from 8 to 27 /** Big orange thing # Recipes Coming soon. **/ pub struct Pumpkin { /// Roundness, expressed as a percentage pub roundness: f32, /// Orangeness, on a scale of 8 to 27 pub orangeness: i32, } // 4. Document the "smash" method. Explain that if you smash the pumpkin, it will be gone. Then it // can't be used for pie. :'-( impl Pumpkin { /// Smashes the pumpkin, making it ineligible for use in pie pub fn smash(self) {} } // 5. Document that BURNT_ORANGE is for the "orangeness" field in the Pumpkin struct. // - Link to the Pumpkin struct in your description pub const BURNT_ORANGE: i32 = 13; // Challenge: Find the option to pass to `cargo doc` so that documentation for this private item // gets generated as well. Hint: `cargo doc -h` will show you all the relevant options. /// For internal use only. In fact, this documentation is so private that it won't be generated. /// At least not by default. But if you pass the correct option in, it will magically appear! #[allow(dead_code)] // to silence the warning enum PrivateEnum { /// For Halloween. To be lit by candlelight. JackOLantern, /// For dessert during North American winter holidays. PumpkinPie, }
46.830508
391
0.737242
18a0cc2487061ba6c359cfff45dc7ad8d51e590e
17,053
ts
TypeScript
test/factories/grundModel.ts
digitalservice4germany/grundsteuer
3c354bac1995764d23f4b5b08ae8987aaad0049f
[ "MIT" ]
6
2021-12-28T12:42:33.000Z
2022-02-15T09:38:36.000Z
test/factories/grundModel.ts
digitalservice4germany/grundsteuer
3c354bac1995764d23f4b5b08ae8987aaad0049f
[ "MIT" ]
105
2021-12-28T13:33:02.000Z
2022-03-30T22:53:03.000Z
test/factories/grundModel.ts
digitalservice4germany/grundsteuer
3c354bac1995764d23f4b5b08ae8987aaad0049f
[ "MIT" ]
null
null
null
import { Factory } from "fishery"; import _ from "lodash"; import { EigentuemerAnzahlFields, EigentuemerPersonGesetzlicherVertreterFields, Flurstueck, GrundModel, GrundstueckAbweichendeEntwicklungFields, GrundstueckAdresseFields, GrundstueckAnzahlFields, GrundstueckBodenrichtwertEingabeFields, GrundstueckGemeindeFields, GrundstueckSteuernummerFields, GrundstueckTypFields, Person, } from "~/domain/steps"; import { GebaeudeAb1949Fields } from "~/domain/steps/gebaeude/ab1949"; import { GebaeudeKernsaniertFields } from "~/domain/steps/gebaeude/kernsaniert"; import { GebaeudeWeitereWohnraeumeFields } from "~/domain/steps/gebaeude/weitereWohnraeume"; import { GebaeudeGaragenFields } from "~/domain/steps/gebaeude/garagen"; import { EigentuemerVerheiratetFields } from "~/domain/steps/eigentuemer/verheiratet"; import { EigentuemerEmpfangsvollmachtFields } from "~/domain/steps/eigentuemer/empfangsvollmacht"; import { flurstueckFactory } from "./flurstueck"; import { EigentuemerPersonAdresseFields } from "~/domain/steps/eigentuemer/person/adresse"; import { EigentuemerBruchteilsgemeinschaftFields } from "~/domain/steps/eigentuemer/bruchteilsgemeinschaft"; import { GebaeudeBaujahrFields } from "~/domain/steps/gebaeude/baujahr"; import { GebaeudeKernsanierungsjahrFields } from "~/domain/steps/gebaeude/kernsanierungsjahr"; import { GebaeudeAbbruchverpflichtungFields } from "~/domain/steps/gebaeude/abbruchverpflichtung"; import { GebaeudeAbbruchverpflichtungsjahrFields } from "~/domain/steps/gebaeude/abbruchverpflichtungsjahr"; import { GebaeudeWohnflaecheFields } from "~/domain/steps/gebaeude/wohnflaeche"; import { GebaeudeWohnflaechenFields } from "~/domain/steps/gebaeude/wohnflaechen"; import { GebaeudeWeitereWohnraeumeDetailsFields } from "~/domain/steps/gebaeude/weitereWohnraeumeDetails"; import { GebaeudeGaragenAnzahlFields } from "~/domain/steps/gebaeude/garagenAnzahl"; import { EigentuemerBruchteilsgemeinschaftAngabenFields } from "~/domain/steps/eigentuemer/bruchteilsgemeinschaftangaben/angaben"; import { EigentuemerEmpfangsbevollmaechtigterNameFields } from "~/domain/steps/eigentuemer/empfangsbevollmaechtigter/name"; import { EigentuemerEmpfangsbevollmaechtigterAdresseFields } from "~/domain/steps/eigentuemer/empfangsbevollmaechtigter/adresse"; import { ZusammenfassungFields } from "~/domain/steps/zusammenfassung"; import { GrundstueckBodenrichtwertAnzahlFields } from "~/domain/steps/grundstueck/bodenrichtwert/anzahl"; import { GrundstueckFlurstueckMiteigentumsanteilFields } from "~/domain/steps/grundstueck/miteigentumsanteil"; type PersonTransientParams = { transient: { personIndex: number; }; }; const strasse = _.sample([ "Hauptstraße", "Tal", "P4", "Straße 254", "Bischöflich-Geistlicher-Rat-Josef-Zinnbauer-Straße", "Laehr'scher Jagdweg", "Rue d'Achères", ]); const hausnummer = _.sample(["1", "42", "9999"]); const plz = _.sample(["01001", "90329"]); const ort = _.sample([ "Hausen", "Au", "Hellschen-Heringsand-Unterschaar", "Petershagen/Eggersdorf", "St. Leon-Rot", ]); class GrundModelFactory extends Factory<GrundModel> { grundstueckAdresse(fields?: Partial<GrundstueckAdresseFields>) { return this.params({ grundstueck: { adresse: { strasse, hausnummer, zusatzangaben: "something", plz, ort, ...fields, }, }, }); } grundstueckSteuernummer(fields?: Partial<GrundstueckSteuernummerFields>) { return this.params({ grundstueck: { steuernummer: { steuernummer: "1234567890", ...fields, }, }, }); } grundstueckTyp(fields?: Partial<GrundstueckTypFields>) { return this.params({ grundstueck: { typ: { typ: fields ? fields.typ : "einfamilienhaus", ...fields, }, }, }); } grundstueckAbweichendeEntwicklung( fields?: Partial<GrundstueckAbweichendeEntwicklungFields> ) { return this.params({ grundstueck: { abweichendeEntwicklung: { zustand: "bauerwartungsland", ...fields, }, }, }); } grundstueckGemeinde(fields?: Partial<GrundstueckGemeindeFields>) { return this.params({ grundstueck: { gemeinde: { innerhalbEinerGemeinde: "true", ...fields, }, }, }); } grundstueckAnzahl(fields?: Partial<GrundstueckAnzahlFields>) { return this.params({ grundstueck: { anzahl: { anzahl: "2", ...fields, }, }, }); } grundstueckFlurstueck({ list, count, }: { list?: Flurstueck[]; count?: number; }) { const flurstueckList = list || flurstueckFactory .angaben() .flur() .groesse() .buildList(count || 1); return this.params({ grundstueck: { flurstueck: flurstueckList, }, }); } miteigentumsanteil( fields?: Partial<GrundstueckFlurstueckMiteigentumsanteilFields> ) { return this.params({ grundstueck: { miteigentumsanteil: { wirtschaftlicheEinheitZaehler: "1", wirtschaftlicheEinheitNenner: "234", ...fields, }, }, }); } grundstueckBodenrichtwert( eingabeFields?: Partial<GrundstueckBodenrichtwertEingabeFields>, anzahlFields?: Partial<GrundstueckBodenrichtwertAnzahlFields> ) { return this.params({ grundstueck: { bodenrichtwertEingabe: { bodenrichtwert: "200", ...eingabeFields, }, bodenrichtwertAnzahl: { anzahl: "1", ...anzahlFields, }, }, }); } gebaeudeAb1949(fields?: Partial<GebaeudeAb1949Fields>) { return this.params({ gebaeude: { ab1949: { isAb1949: fields ? fields?.isAb1949 : "true", }, }, }); } gebaeudeBaujahr(fields?: Partial<GebaeudeBaujahrFields>) { return this.params({ gebaeude: { baujahr: { baujahr: fields?.baujahr, }, }, }); } kernsaniert( fields?: Partial<GebaeudeKernsaniertFields> & Partial<GebaeudeKernsanierungsjahrFields> ) { return this.params({ gebaeude: { kernsaniert: { isKernsaniert: fields ? fields?.isKernsaniert : "true", }, kernsanierungsjahr: { kernsanierungsjahr: fields ? fields?.kernsanierungsjahr : "", }, }, }); } abbruchverpflichtung( fields?: Partial<GebaeudeAbbruchverpflichtungFields> & Partial<GebaeudeAbbruchverpflichtungsjahrFields> ) { return this.params({ gebaeude: { abbruchverpflichtung: { hasAbbruchverpflichtung: fields?.hasAbbruchverpflichtung ? fields?.hasAbbruchverpflichtung : "true", }, abbruchverpflichtungsjahr: { abbruchverpflichtungsjahr: fields?.abbruchverpflichtungsjahr ? fields.abbruchverpflichtungsjahr : "", }, }, }); } wohnflaechen( fields?: Partial<GebaeudeWohnflaecheFields> & Partial<GebaeudeWohnflaechenFields> ) { return this.params({ gebaeude: { wohnflaeche: { wohnflaeche: fields?.wohnflaeche ? fields?.wohnflaeche : "", }, wohnflaechen: { wohnflaeche1: fields?.wohnflaeche1 ? fields.wohnflaeche1 : "", wohnflaeche2: fields?.wohnflaeche2 ? fields.wohnflaeche2 : "", }, }, }); } withWeitereWohnraeume( fields?: Partial<GebaeudeWeitereWohnraeumeFields> & Partial<GebaeudeWeitereWohnraeumeDetailsFields> ) { return this.params({ gebaeude: { weitereWohnraeume: { hasWeitereWohnraeume: fields ? fields?.hasWeitereWohnraeume : "true", }, weitereWohnraeumeDetails: { anzahl: fields ? fields.anzahl : "", flaeche: fields ? fields.flaeche : "", }, }, }); } withGaragen( fields?: Partial<GebaeudeGaragenFields> & Partial<GebaeudeGaragenAnzahlFields> ) { return this.params({ gebaeude: { garagen: { hasGaragen: fields ? fields?.hasGaragen : "true", }, garagenAnzahl: { anzahlGaragen: fields ? fields.anzahlGaragen : "", }, }, }); } eigentuemerAnzahl(fields?: Partial<EigentuemerAnzahlFields>) { return this.params({ eigentuemer: { anzahl: { anzahl: fields?.anzahl || "1", }, }, }); } eigentuemerVerheiratet(fields?: Partial<EigentuemerVerheiratetFields>) { return this.params({ eigentuemer: { verheiratet: { areVerheiratet: fields?.areVerheiratet, }, }, }); } eigentuemerPerson({ list }: { list?: Person[] }) { return this.params({ eigentuemer: { person: list, }, }); } eigentuemerPersonAdresse( fields?: Partial<EigentuemerPersonAdresseFields>, params?: PersonTransientParams ) { return this.params({ eigentuemer: { // eslint-disable-next-line @typescript-eslint/ban-ts-comment // @ts-ignore person: { [params?.transient.personIndex || 0]: { adresse: fields, }, }, }, }); } eigentuemerPersonGesetzlicherVertreter( fields?: Partial<EigentuemerPersonGesetzlicherVertreterFields>, params?: PersonTransientParams ) { return this.params({ eigentuemer: { // eslint-disable-next-line @typescript-eslint/ban-ts-comment // @ts-ignore person: { [params?.transient.personIndex || 0]: { gesetzlicherVertreter: { hasVertreter: fields?.hasVertreter || "false", }, }, }, }, }); } eigentuemerBruchteilsgemeinschaft( fields?: Partial<EigentuemerBruchteilsgemeinschaftFields> & Partial<EigentuemerBruchteilsgemeinschaftAngabenFields> ) { return this.params({ eigentuemer: { // eslint-disable-next-line @typescript-eslint/ban-ts-comment // @ts-ignore bruchteilsgemeinschaft: { predefinedData: fields?.predefinedData, }, bruchteilsgemeinschaftangaben: { angaben: { name: fields?.name, strasse: fields?.strasse, hausnummer: fields?.hausnummer, postfach: fields?.postfach, plz: fields?.plz, ort: fields?.ort, }, }, }, }); } eigentuemerEmpfangsvollmacht( fields?: Partial<EigentuemerEmpfangsvollmachtFields> & Partial<EigentuemerEmpfangsbevollmaechtigterNameFields> & Partial<EigentuemerEmpfangsbevollmaechtigterAdresseFields> ) { return this.params({ eigentuemer: { // eslint-disable-next-line @typescript-eslint/ban-ts-comment // @ts-ignore empfangsvollmacht: { hasEmpfangsvollmacht: fields?.hasEmpfangsvollmacht || "false", }, empfangsbevollmaechtigter: { name: { anrede: fields?.anrede, titel: fields?.titel, vorname: fields?.vorname, name: fields?.name, }, adresse: { strasse: fields?.strasse, hausnummer: fields?.hausnummer, postfach: fields?.postfach, plz: fields?.plz, ort: fields?.ort, telefonnummer: fields?.telefonnummer, }, }, }, }); } // TODO refactor, use grundstueckAnzahl flurstueckAnzahl(fields?: Partial<GrundstueckAnzahlFields>) { return this.params({ grundstueck: { anzahl: { anzahl: fields?.anzahl || "1", }, }, }); } freitext(fields?: Partial<ZusammenfassungFields>) { return this.params({ zusammenfassung: { freitext: fields?.freitext, }, }); } full() { return this.params( this.grundstueckTyp({ typ: "einfamilienhaus" }) .grundstueckAdresse({ strasse: "GST Strasse", hausnummer: "2GST", zusatzangaben: "GST Zusatzangaben", plz: "12345", ort: "GST Ort", bundesland: "BB", }) .grundstueckSteuernummer({ steuernummer: "1234567890" }) .grundstueckAbweichendeEntwicklung({ zustand: "rohbauland" }) .grundstueckGemeinde({ innerhalbEinerGemeinde: "true" }) .miteigentumsanteil({ wirtschaftlicheEinheitZaehler: "67,1", wirtschaftlicheEinheitNenner: "89", }) .grundstueckBodenrichtwert({ bodenrichtwert: "123" }) .flurstueckAnzahl({ anzahl: "2" }) .grundstueckFlurstueck({ list: [ { angaben: { grundbuchblattnummer: "1", gemarkung: "2", }, flur: { flur: "1", flurstueckZaehler: "23", flurstueckNenner: "45", }, groesse: { groesseHa: "", groesseA: "", groesseQm: "1234", }, }, { angaben: { grundbuchblattnummer: "2", gemarkung: "3", }, flur: { flur: "2", flurstueckZaehler: "34", flurstueckNenner: "56", }, groesse: { groesseHa: "", groesseA: "123", groesseQm: "45", }, }, ], count: 2, }) .gebaeudeAb1949({ isAb1949: "true" }) .gebaeudeBaujahr({ baujahr: "2000" }) .kernsaniert({ isKernsaniert: "true", kernsanierungsjahr: "2001" }) .abbruchverpflichtung({ hasAbbruchverpflichtung: "true", abbruchverpflichtungsjahr: "2030", }) .wohnflaechen({ wohnflaeche: "100" }) .withWeitereWohnraeume({ hasWeitereWohnraeume: "true", anzahl: "2", flaeche: "200", }) .withGaragen({ hasGaragen: "true", anzahlGaragen: "3" }) .eigentuemerAnzahl({ anzahl: "2" }) .eigentuemerVerheiratet({ areVerheiratet: "false" }) .eigentuemerPerson({ list: [ { persoenlicheAngaben: { anrede: "frau", titel: "1 Titel", vorname: "1 Vorname", name: "1 Name", geburtsdatum: "31.01.1111", }, adresse: { strasse: "1 Strasse", hausnummer: "1 H", plz: "12345", ort: "1 Ort", telefonnummer: "111111", }, steuerId: { steuerId: "02293417683", }, gesetzlicherVertreter: { hasVertreter: "false", }, anteil: { zaehler: "1", nenner: "2", }, }, { persoenlicheAngaben: { anrede: "herr", titel: "2 Titel", vorname: "2 Vorname", name: "2 Name", geburtsdatum: "02.02.2000", }, adresse: { postfach: "23", plz: "22345", ort: "2 Ort", telefonnummer: "222222", }, steuerId: { steuerId: "04452397687", }, gesetzlicherVertreter: { hasVertreter: "true", }, vertreter: { name: { anrede: "herr", titel: "VERT Titel", vorname: "VERT Vorname", name: "VERT Name", }, adresse: { strasse: "VERT Strasse", hausnummer: "3VERT", plz: "54321", ort: "VERT Ort", telefonnummer: "333333", }, }, anteil: { zaehler: "3", nenner: "4", }, }, ], }) .eigentuemerBruchteilsgemeinschaft({ predefinedData: "false", name: "BTG Name", postfach: "123456", plz: "54321", ort: "BTG Ort", }) .eigentuemerEmpfangsvollmacht({ hasEmpfangsvollmacht: "true", anrede: "no_anrede", titel: "EMP Titel", vorname: "EMP Vorname", name: "EMP Name", strasse: "EMP Strasse", hausnummer: "2EMP", plz: "24680", ort: "EMP Ort", telefonnummer: "12345", }) .build() ); } } export const grundModelFactory = GrundModelFactory.define(() => ({}));
28.093904
130
0.558142
0ac674f8a2116c438124dbbef5e6cff8820ab07a
2,777
ps1
PowerShell
CrowdinManager/Public/Test/Get-ProjectStructure.Test.ps1
flibustier7seas/crowdin-powershell
89a4c7056d5064d382daa5b5422a65552f71bc3a
[ "MIT" ]
null
null
null
CrowdinManager/Public/Test/Get-ProjectStructure.Test.ps1
flibustier7seas/crowdin-powershell
89a4c7056d5064d382daa5b5422a65552f71bc3a
[ "MIT" ]
null
null
null
CrowdinManager/Public/Test/Get-ProjectStructure.Test.ps1
flibustier7seas/crowdin-powershell
89a4c7056d5064d382daa5b5422a65552f71bc3a
[ "MIT" ]
null
null
null
Import-module $PSScriptRoot\..\Get-ProjectStructure.psm1 -Force Import-module $PSScriptRoot\..\..\Private\Get-CrowdinNodes.psm1 -Force $json = ' { "files": [ { "node_type": "branch", "name": "Test_Branch", "files": [ { "node_type": "directory", "name": "Example1", "files": [] } ] }, { "node_type": "directory", "name": "MyProject", "files": [ { "node_type": "directory", "name": "Folder1", "files": [ { "node_type": "directory", "name": "Folder11", "files": [ { "node_type": "file", "name": "translations.json" } ] }, { "node_type": "file", "name": "translations.json" } ] } ] } ] } ' Describe 'Get-CrowdinNodes' { $info = ConvertFrom-Json -InputObject $json $projectStructure = Get-CrowdinNodes $info.files Context 'Get-BranchNode' { It "Given valid -Branch '<Branch>', it returns '<Expected>'" -TestCases @( @{ Branch = 'Test_Branch'; Expected = $true } ) { param ($Branch, $Expected) $result = Get-BranchNode $projectStructure $Branch $result | Should -Be $Expected } } Context 'Test-ItemExists' { It "Given valid -Path '<Path>' -Type '<Type>', it returns '<Expected>'" -TestCases @( @{ Path = 'MyProject'; Type = 'directory'; Expected = $true }, @{ Path = 'MyProject\Folder1'; Type = 'directory'; Expected = $true }, @{ Path = 'MyProject\Folder1\translations.json'; Type = 'file'; Expected = $true }, @{ Path = 'MyProject\Folder1\Folder11\translations.json'; Type = 'file'; Expected = $true } @{ Path = 'Example1'; Type = 'directory'; Branch = 'Test_Branch'; Expected = $true } ) { param ($Path, $Type, $Branch = '', $Expected) $nodes = $projectStructure if($Branch) { $branchNode = Get-BranchNode $projectStructure $Branch $nodes = $branchNode.files } $result = Test-ItemExists $nodes $Path $Type $result | Should -Be $Expected } } }
30.855556
103
0.411595
b6f1e6900df737a8dcbf67b8e9285d0386e9816e
170
rb
Ruby
db/migrate/20190715104640_add_organisation_id_to_access_limit.rb
uk-gov-mirror/alphagov.publishing-api
9667bf20b2f8707e0b1b0f96f210653a58f006ed
[ "MIT" ]
25
2015-01-30T09:04:47.000Z
2021-05-20T12:09:26.000Z
db/migrate/20190715104640_add_organisation_id_to_access_limit.rb
uk-gov-mirror/alphagov.publishing-api
9667bf20b2f8707e0b1b0f96f210653a58f006ed
[ "MIT" ]
693
2015-02-06T09:32:59.000Z
2022-03-18T16:13:37.000Z
db/migrate/20190715104640_add_organisation_id_to_access_limit.rb
alphagov-mirror/publishing-api
c0c69997d1a1c63bdea3581655dd4c3146281443
[ "MIT" ]
24
2015-02-05T17:00:25.000Z
2021-04-10T18:06:43.000Z
class AddOrganisationIdToAccessLimit < ActiveRecord::Migration[5.2] def change add_column :access_limits, :organisations, :json, null: false, default: [] end end
28.333333
78
0.758824
0d97d7bf4eeafa11a8a1251e97df2202f269add5
218
cs
C#
RogueEssence/Dev/CustomAttributes/SubGroupAttribute.cs
Parakoopa/RogueEssence
0606a6fbf1bcf8baeeba3ee7be52b9ce192efcea
[ "MS-PL", "Zlib", "MIT" ]
null
null
null
RogueEssence/Dev/CustomAttributes/SubGroupAttribute.cs
Parakoopa/RogueEssence
0606a6fbf1bcf8baeeba3ee7be52b9ce192efcea
[ "MS-PL", "Zlib", "MIT" ]
null
null
null
RogueEssence/Dev/CustomAttributes/SubGroupAttribute.cs
Parakoopa/RogueEssence
0606a6fbf1bcf8baeeba3ee7be52b9ce192efcea
[ "MS-PL", "Zlib", "MIT" ]
null
null
null
using System; namespace RogueEssence.Dev { [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property)] public class SubGroupAttribute : Attribute { public SubGroupAttribute() { } } }
19.818182
72
0.706422
e727449b0ddc9f2c8a144482624602ff2abe0051
973
php
PHP
wordpress/ProjetoRest/sobre.php
leonardoanthony/Origamid
346058a6d45abe1ada3f5e800da6c829c298930b
[ "MIT" ]
1
2022-01-17T16:31:10.000Z
2022-01-17T16:31:10.000Z
wordpress/ProjetoRest/sobre.php
leonardoanthony/Origamid
346058a6d45abe1ada3f5e800da6c829c298930b
[ "MIT" ]
null
null
null
wordpress/ProjetoRest/sobre.php
leonardoanthony/Origamid
346058a6d45abe1ada3f5e800da6c829c298930b
[ "MIT" ]
null
null
null
<?php get_header(); ?> <section class="container sobre"> <h2 class="subtitulo">Sobre</h2> <div class="grid-8"> <img src="img/rest-fachada.jpg" alt="Fachada do Rest"> </div> <div class="grid-8"> <h2>História</h2> <p>O incentivo ao avanço tecnológico, assim como a mobilidade dos capitais internacionais auxilia a preparação e a composição dos níveis de motivação departamental.</p> <p>Gostaria de enfatizar que o desenvolvimento contínuo de distintas formas de atuação prepara-nos para enfrentar situações atípicas decorrentes do remanejamento dos quadros funcionais.</p> <h2>Visão</h2> <p>Não obstante, a expansão dos mercados mundiais faz parte de um processo de gerenciamento de alternativas às soluções ortodoxas.</p> <h2>Valores</h2> <p>O empenho em analisar a consolidação das estruturas apresenta tendências no sentido de aprovar a manutenção dos índices pretendidos.</p> </div> </section> <?php get_footer(); ?>
46.333333
193
0.727646
d317a902da441abff92bbafd044ceef874dcb913
308
cs
C#
BgPersonGenerator/City.cs
TsvetanKT/BgPersonGenerator
46ab36d4e7d7823b99d172f0f08708d468e8699b
[ "MIT" ]
null
null
null
BgPersonGenerator/City.cs
TsvetanKT/BgPersonGenerator
46ab36d4e7d7823b99d172f0f08708d468e8699b
[ "MIT" ]
null
null
null
BgPersonGenerator/City.cs
TsvetanKT/BgPersonGenerator
46ab36d4e7d7823b99d172f0f08708d468e8699b
[ "MIT" ]
null
null
null
namespace BgPersonGeneratorSpace { internal class City { internal City(string name, int population) { this.Name = name; this.Population = population; } internal string Name { get; set; } internal int Population { get; set; } } }
19.25
50
0.551948
c8d8478d764578e01ac10c0e0e75447022733343
6,327
go
Go
src/code.cloudfoundry.org/policy-server/cleaner/policy_cleaner_test.go
cloudfoundry-incubator/cf-networking
1197c5d4f357dacd7772b009ee4e49e948357a9e
[ "Apache-2.0" ]
null
null
null
src/code.cloudfoundry.org/policy-server/cleaner/policy_cleaner_test.go
cloudfoundry-incubator/cf-networking
1197c5d4f357dacd7772b009ee4e49e948357a9e
[ "Apache-2.0" ]
null
null
null
src/code.cloudfoundry.org/policy-server/cleaner/policy_cleaner_test.go
cloudfoundry-incubator/cf-networking
1197c5d4f357dacd7772b009ee4e49e948357a9e
[ "Apache-2.0" ]
null
null
null
package cleaner_test import ( "errors" "code.cloudfoundry.org/lager/lagertest" ccfakes "code.cloudfoundry.org/policy-server/cc_client/fakes" "code.cloudfoundry.org/policy-server/cleaner" "code.cloudfoundry.org/policy-server/cleaner/fakes" "code.cloudfoundry.org/policy-server/store" uaafakes "code.cloudfoundry.org/policy-server/uaa_client/fakes" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" "github.com/onsi/gomega/gbytes" ) var _ = Describe("PolicyCleaner", func() { var ( policyCleaner *cleaner.PolicyCleaner fakeStore *fakes.PolicyStore fakeUAAClient *uaafakes.UAAClient fakeCCClient *ccfakes.CCClient logger *lagertest.TestLogger c2cPolicies []store.Policy ) BeforeEach(func() { c2cPolicies = []store.Policy{{ Source: store.Source{ID: "live-guid", Tag: "tag"}, Destination: store.Destination{ ID: "live-guid", Tag: "tag", Protocol: "tcp", Ports: store.Ports{ Start: 8080, End: 8080, }, }, }, { Source: store.Source{ID: "dead-guid", Tag: "tag"}, Destination: store.Destination{ ID: "live-guid", Tag: "tag", Protocol: "udp", Ports: store.Ports{ Start: 1234, End: 1234, }, }, }, { Source: store.Source{ID: "live-guid", Tag: "tag"}, Destination: store.Destination{ ID: "dead-guid", Tag: "tag", Protocol: "udp", Ports: store.Ports{ Start: 1234, End: 1234, }, }, }} fakeStore = &fakes.PolicyStore{} fakeUAAClient = &uaafakes.UAAClient{} fakeCCClient = &ccfakes.CCClient{} logger = lagertest.NewTestLogger("test") policyCleaner = cleaner.NewPolicyCleaner(logger, fakeStore, fakeUAAClient, fakeCCClient, 0) fakeUAAClient.GetTokenReturns("valid-token", nil) fakeStore.AllReturns(c2cPolicies, nil) fakeCCClient.GetLiveAppGUIDsStub = func(token string, appGUIDs []string) (map[string]struct{}, error) { liveGUIDs := make(map[string]struct{}) for _, guid := range appGUIDs { if guid == "live-guid" { liveGUIDs[guid] = struct{}{} } } return liveGUIDs, nil } }) It("Deletes c2c policies that reference apps that do not exist", func() { deletedPolicies, err := policyCleaner.DeleteStalePolicies() Expect(err).NotTo(HaveOccurred()) Expect(fakeStore.AllCallCount()).To(Equal(1)) Expect(fakeUAAClient.GetTokenCallCount()).To(Equal(1)) Expect(fakeCCClient.GetLiveAppGUIDsCallCount()).To(Equal(1)) token, guids := fakeCCClient.GetLiveAppGUIDsArgsForCall(0) Expect(token).To(Equal("valid-token")) Expect(guids).To(ConsistOf("live-guid", "dead-guid")) stalePolicies := c2cPolicies[1:] Expect(fakeStore.DeleteCallCount()).To(Equal(1)) Expect(fakeStore.DeleteArgsForCall(0)).To(Equal(stalePolicies)) Expect(logger).To(gbytes.Say("deleting stale policies:.*c2c_policies.*dead-guid.*dead-guid.*total_c2c_policies\":2")) Expect(deletedPolicies).To(Equal(stalePolicies)) }) Context("when there are more apps with policies than the CC chunk size", func() { BeforeEach(func() { policyCleaner = &cleaner.PolicyCleaner{ Logger: logger, Store: fakeStore, UAAClient: fakeUAAClient, CCClient: fakeCCClient, CCAppRequestChunkSize: 1, } }) It("Calls the CC server multiple times to check which policies to delete", func() { returnedPolicies, err := policyCleaner.DeleteStalePolicies() Expect(err).NotTo(HaveOccurred()) Expect(fakeStore.AllCallCount()).To(Equal(1)) Expect(fakeUAAClient.GetTokenCallCount()).To(Equal(1)) Expect(fakeCCClient.GetLiveAppGUIDsCallCount()).To(Equal(2)) token0, guids0 := fakeCCClient.GetLiveAppGUIDsArgsForCall(0) Expect(token0).To(Equal("valid-token")) token1, guids1 := fakeCCClient.GetLiveAppGUIDsArgsForCall(1) Expect(token1).To(Equal("valid-token")) Expect([][]string{guids0, guids1}).To(ConsistOf( []string{"live-guid"}, []string{"dead-guid"}, )) stalePolicies := c2cPolicies[1:] Expect(fakeStore.DeleteCallCount()).To(Equal(1)) deletedPolicies := fakeStore.DeleteArgsForCall(0) Expect(deletedPolicies).To(Equal(stalePolicies)) Expect(logger).To(gbytes.Say("deleting stale policies:.*c2c_policies.*dead-guid.*dead-guid.*total_c2c_policies\":2")) staleAPIPolicies := c2cPolicies[1:] Expect(returnedPolicies).To(ConsistOf(staleAPIPolicies[0], staleAPIPolicies[1])) }) }) Context("When retrieving policies from the db fails", func() { BeforeEach(func() { fakeStore.AllReturns([]store.Policy{}, errors.New("potato")) }) It("returns a meaningful error", func() { _, err := policyCleaner.DeleteStalePolicies() Expect(err).To(MatchError("database read failed for c2c policies: potato")) }) It("logs the error", func() { policyCleaner.DeleteStalePolicies() Expect(logger).To(gbytes.Say("store-list-policies-failed.*potato")) }) }) Context("When getting the UAA token fails", func() { BeforeEach(func() { fakeUAAClient.GetTokenReturns("", errors.New("potato")) }) It("returns a meaningful error", func() { _, err := policyCleaner.DeleteStalePolicies() Expect(err).To(MatchError("get UAA token failed: potato")) }) It("logs the full error", func() { policyCleaner.DeleteStalePolicies() Expect(logger).To(gbytes.Say("get-uaa-token-failed.*potato")) }) }) Context("When getting the apps from the Cloud-Controller fails", func() { BeforeEach(func() { fakeCCClient.GetLiveAppGUIDsReturns(nil, errors.New("potato")) }) It("returns a meaningful error", func() { _, err := policyCleaner.DeleteStalePolicies() Expect(err).To(MatchError("get app guids from Cloud-Controller failed: potato")) }) It("logs the full error", func() { policyCleaner.DeleteStalePolicies() Expect(logger).To(gbytes.Say("cc-get-app-guids-failed.*potato")) }) }) Context("When deleting the policies fails", func() { BeforeEach(func() { fakeStore.DeleteReturns(errors.New("potato")) }) It("returns a meaningful error", func() { _, err := policyCleaner.DeleteStalePolicies() Expect(err).To(MatchError("database write failed: potato")) }) It("logs the full error", func() { policyCleaner.DeleteStalePolicies() Expect(logger).To(gbytes.Say("store-delete-policies-failed.*potato")) }) }) })
30.713592
120
0.682946
05d37b297a9f2fcdf04514fab982cad7467733d0
1,609
py
Python
src/tune.py
avaneesh93/frame-prediction
c7f45fed3651bd8fc7e2db1a88eefb8a8057f117
[ "MIT" ]
1
2020-07-08T10:20:22.000Z
2020-07-08T10:20:22.000Z
src/tune.py
avaneesh93/frame-prediction
c7f45fed3651bd8fc7e2db1a88eefb8a8057f117
[ "MIT" ]
null
null
null
src/tune.py
avaneesh93/frame-prediction
c7f45fed3651bd8fc7e2db1a88eefb8a8057f117
[ "MIT" ]
null
null
null
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sat Dec 8 22:10:50 2018 @author: roshanprakash """ from dataset_loader import * from encode_decode import * from train_model import * from test_model import * import matplotlib.pyplot as plt import numpy as np import os # first load the data print('Loading data...') data = dataset_loader(delta_t = 40.0, k = 10, offset = 10) print('Loaded data!') # setup some data specific variables dt = data.delta_t X_train = data.X_train['walking'] y_train = data.y_train['walking'] opt_flows_train = data.optical_flows_train['walking'] motion_representations_train = data.motion_representations_train['walking'] X_test = data.X_test['walking'] y_test = data.y_test['walking'] opt_flows_test = data.optical_flows_test['walking'] # now, tune the model learning_rates = [1e-7, 1e-6, 1e-4, 1e-3, 1e-2] losses = [] best_rate = None best_loss = np.inf """ Runs 100 epochs with different learning rates and writes losses to file """ for lr in learning_rates: print('Training for learning rate {}'.format(lr)) epoch_losses = train_model(X_train, y_train, dt, \ opt_flows_train, motion_representations_train, baseline = False, \ lr, epochs = 100, tune = True, print_every = 10) print() losses.append(epoch_losses) if epoch_losses[-1] < best_loss: best_loss = epoch_losses[-1] best_rate = lr np.save(os.path.dirname(os.getcwd()) + '/tune/{}_lr'.format(lr), epoch_losses) print('Best learning rate found for 100 epochs of training {}'.format(best_rate))
29.254545
97
0.691734
dd7b2c2525bf6552b32614583409d5388a6c03a1
3,798
java
Java
app/src/main/java/com/example/faloka_mobile/BaseActivity.java
faloka1/faloka-android
b0c4b3e96dc58ea0c239ae918e8e813fa40bce89
[ "MIT" ]
null
null
null
app/src/main/java/com/example/faloka_mobile/BaseActivity.java
faloka1/faloka-android
b0c4b3e96dc58ea0c239ae918e8e813fa40bce89
[ "MIT" ]
64
2021-09-24T14:42:46.000Z
2022-01-07T01:14:00.000Z
app/src/main/java/com/example/faloka_mobile/BaseActivity.java
faloka1/faloka-android
b0c4b3e96dc58ea0c239ae918e8e813fa40bce89
[ "MIT" ]
1
2021-09-24T14:19:34.000Z
2021-09-24T14:19:34.000Z
package com.example.faloka_mobile; import android.app.Activity; import android.content.Intent; import android.graphics.Typeface; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.Toast; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.appcompat.app.AppCompatActivity; import com.example.faloka_mobile.Account.AuthFlagListener; import com.example.faloka_mobile.Cart.CartActivity; import com.example.faloka_mobile.Cart.CartCountItemListener; import com.example.faloka_mobile.Cart.CartEmptyActivity; import com.example.faloka_mobile.Cart.CartRepository; import com.example.faloka_mobile.Login.LoginRepository; import com.example.faloka_mobile.Login.TokenManager; import ru.nikartm.support.BadgePosition; import ru.nikartm.support.ImageBadgeView; public class BaseActivity extends AppCompatActivity implements CartCountItemListener, AuthFlagListener { private ImageBadgeView badgeView; private int count; private static boolean flagAuth; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { if(!flagAuth){ CartRepository.getCountCarts(getApplicationContext(), this::onItemCount, this::onUnauthorized); } super.onCreate(savedInstanceState); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.top_menu, menu); return super.onCreateOptionsMenu(menu); } @Override protected void onResume() { TokenManager tokenManager = TokenManager.getInstance(getApplicationContext().getSharedPreferences("Token",0)); if(!tokenManager.isLogin()){ super.onResume(); return; } CartRepository.getCountCarts(getApplicationContext(), this::onItemCount, this::onUnauthorized); super.onResume(); } @Override public boolean onOptionsItemSelected(@NonNull MenuItem item) { switch (item.getItemId()){ case android.R.id.home: this.finish(); return true; case R.id.top_menu_cart: break; } return super.onOptionsItemSelected(item); } @Override public boolean onPrepareOptionsMenu(Menu menu) { MenuItem menuItem = menu.findItem(R.id.top_menu_cart); badgeView = menuItem.getActionView().findViewById(R.id.cart_badge); badgeView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if(count <= 0){ if(!LoginRepository.isValidationLogin(BaseActivity.this)){ return; } Intent intent = new Intent(getApplicationContext(), CartEmptyActivity.class); startActivity(intent); } else { Intent intent = new Intent(getApplicationContext(), CartActivity.class); startActivity(intent); } } }); return super.onPrepareOptionsMenu(menu); } @Override public void onItemCount(int count) { this.count = count; if(badgeView != null) { badgeView.setBadgeValue(count) .setBadgeOvalAfterFirst(true) .setBadgeTextSize(8) .setMaxBadgeValue(999) .setBadgePosition(BadgePosition.TOP_RIGHT) .setBadgeTextStyle(Typeface.NORMAL) .setShowCounter(true) .setBadgePadding(4); } } @Override public void onUnauthorized(boolean flag) { this.flagAuth = flag; } }
32.741379
118
0.647446
e30811ea9c97333af39cdca8a2b416363f38d677
7,984
asm
Assembly
src_68k/func/sprites.asm
sheng007/freemlib-neogeo
3044ede6531f80d371a1d9baaf7b30f57e548db3
[ "0BSD" ]
26
2015-01-05T16:27:43.000Z
2021-07-10T17:54:34.000Z
src_68k/func/sprites.asm
sheng007/freemlib-neogeo
3044ede6531f80d371a1d9baaf7b30f57e548db3
[ "0BSD" ]
12
2015-11-26T22:17:09.000Z
2018-06-03T11:47:45.000Z
src_68k/func/sprites.asm
sheng007/freemlib-neogeo
3044ede6531f80d371a1d9baaf7b30f57e548db3
[ "0BSD" ]
5
2015-02-26T03:23:53.000Z
2021-03-17T07:42:37.000Z
; freemlib for Neo-Geo - (General) Sprite Functions ;==============================================================================; ; todo: a lot of things need to exist here. ; Overall a sprite consists of values written to four sections: ; * SCB1 ($0000-$6FFF) Tilemaps, palette, auto-animation, and flip bits ; * SCB2 ($8000-$81FF) Shrinking coefficients ; * SCB3 ($8200-$83FF) Y position, Sticky bit, Sprite height ; * SCB4 ($8400-$85FF) X position ; There's also some values that I'm not sure of yet: ; * ($8600-$867F) Sprite list for even scanlines ; * ($8680-$86FF) Sprite list for odd scanlines ;==============================================================================; ; Calculating X position: ; FEDCBA9876543210 ; 000000000------- ; ||||||||| ; +++++++++- 9-bit X position, relative to left border of screen. (0-511) ; xPos = (x<<7) ; utilmac_CalcSprX ; Calculates a Sprite's X value (for SCB4). ; (Input) ; \1 X value ; (Output) ; d0 Shifted X value utilmac_CalcSprX: macro move.w (\1<<7),d0 endm ;------------------------------------------------------------------------------; ; Calculating Y position: ; FEDCBA9876543210 ; 000000000~~~~~~~ ; ||||||||| ; +++++++++- 9-bit Y position; Position is 496-Y from top border of the screen. ; yPos = ((496-y)<<7) ; It's up to you to combine the rest of the SCB3 values as needed. ; utilmac_CalcSprY ; Calculates a Sprite's Y value (for SCB3). ; (Input) ; \1 Y value ; (Output) ; d0 Calculated Y value utilmac_CalcSprY: macro move.w ((496-\1)<<7),d0 endm ;==============================================================================; ; [Sprites] ;------------------------------------------------------------------------------; ; spr_LoadDirect ; Loads a single sprite into the VRAM. Can be called on its own, or by mspr_Load. ; (Params) ; d0 [word] Sprite index (0-511; sprite 0 is not recommended!) ; a0 [long] Pointer to Sprite Data Block spr_LoadDirect: ; start reading from sprite data block move.w (a0)+,d1 ; $00: sprite height (in tiles) ; Handle SCB1 move.l (a0)+,a1 ; $02-05: pointer to SCB1 tilemap data jsr spr_ParseSCB1 ; SCB2 ($8000-$81FF) move.w #$8000,d2 ; begin at $8000 add.w d0,d2 ; add sprite index move.w d2,LSPC_ADDR ; set new VRAM address move.w (a0)+,LSPC_DATA ; $06: SCB2 data ; SCB3 ($8200-$83FF) move.w #$8200,d2 ; begin at $8200 add.w d0,d2 ; add sprite index move.w d2,LSPC_ADDR ; set new VRAM address move.w (a0)+,LSPC_DATA ; $08: SCB3 data ; SCB4 ($8400-$85FF) move.w #$8400,d2 ; begin at $8400 add.w d0,d2 ; add sprite index move.w d2,LSPC_ADDR ; set new VRAM address move.w (a0)+,LSPC_DATA ; $0A: SCB4 data rts ;------------------------------------------------------------------------------; ; spr_ParseSCB1 ; Internal routine for writing SCB1 tilemap data. ; (Params) ; d0 [word] Sprite index (carried over from spr_LoadDirect or mspr_Load) ; d1 [word] Number of tiles to parse ; a1 [long] Pointer to SCB1 tilemap data spr_ParseSCB1: move.w #1,LSPC_INCR ; VRAM increment +1 moveq #0,d2 ; clear d2 ; convert sprite index into starting SCB1 location ;(either d0*64 or d0<<6) = SCB1 VRAM location move.w d0,d2 ; copy sprite index (d0) to temp lsl.w #6,d2 ; d2 << 6 move.w d2,LSPC_ADDR ; write new vram address ; check number of tiles cmpi.w #1,d1 ; numTiles == 1? bgt .spr_ParseSCB1_Multiple ; otherwise, loop. ; if numTiles == 1, do a single write. .spr_ParseSCB1_Single: move.w (a1)+,LSPC_DATA ; 1) Tile Number LSB move.w (a1)+,LSPC_DATA ; 2) Palette, Tile Number MSB, Auto-Animation flags, V/H flip flags bra .spr_ParseSCB1_End .spr_ParseSCB1_Multiple: move.w d1,d7 ; copy num tiles (d1) to temp subi.w #1,d7 ; subtract 1 for loop counter ; tile loop .spr_ParseSCB1_Loop: move.w (a1)+,LSPC_DATA ; 1) Tile Number LSB move.w (a1)+,LSPC_DATA ; 2) Palette, Tile Number MSB, Auto-Animation flags, V/H flip flags dbra d7,.spr_ParseSCB1_Loop .spr_ParseSCB1_End: rts ;==============================================================================; ; Sprite Macros ;------------------------------------------------------------------------------; ; semantic names for SCB1Data flags AUTOANIM_NONE equ 0 ; no auto animation AUTOANIM_4 equ 4 ; 4-frame auto animation AUTOANIM_8 equ 8 ; 8-frame auto animation ;-----------------------; VFLIP_NO equ 0 ; no vertical flip VFLIP_YES equ 1 ; vertical flip HFLIP_NO equ 0 ; no horizontal flip HFLIP_YES equ 1 ; horizontal flip ;------------------------------------------------------------------------------; ; sprmac_SCB1Data ; Writes a single SCB1 data entry into the binary. ; This macro converts normal values to their SCB1 equivalents. ; You will want to use this macro multiple times for Sprites with Height > 1. ; Note: This macro assumes you know the palette and auto-animation values when ; you're writing data into the ROM. (A better solution is needed for metasprite ; initialization and other such tasks.) ; (Params) ; \1 [long] Tile Number (20 bits; SCB1 even, SCB1 odd (bits 4-7)) ; \2 [byte] Palette Number (8 bits; SCB1 odd (bits 8-15)) ; \3 [byte] Auto-Animation (0,4,8) (2 bits; SCB1 odd (bits 2,3) 4=2bit, 8=3bit) ; \4 [byte] Vertical Flip (1 bit; SCB1 odd (bit 1)) ; \5 [byte] Horizontal Flip (1 bit; SCB1 odd (bit 0)) sprmac_SCB1Data: macro dc.w (\1&$0FFFF) dc.w (\2<<8)|((\1&$F0000)>>12)|(\3)|(\4<<1)|\5 endm ;------------------------------------------------------------------------------; ; sprmac_SpriteData ; Writes Sprite data into the binary. ; This macro converts normal values to their SCB* section equivalents. ; (Aside from SCB1 tilemaps, which are handled with the sprmac_SCB1Data macro.) ; The point of this macro is to be user-friendly, so that they don't need to ; handle all the crap required to create the SCB data. ; Major Note: This does not handle the sticky bit in SCB3. ; (Params) ; \1 [word] Sprite Height, in tiles (bottom 6 bits of SCB3) ; \2 [word] X position (9 bits (SCB4); converted to X<<7) ; \3 [word] Y position (9 bits (SCB3); converted to (496-Y)<<7) ; \4 [long] Pointer to SCB1 tilemap data ; \5 [byte] Horizontal Shrink (0-F) ; \6 [byte] Vertical Shrink (00-FF) sprmac_SpriteData: macro dc.w \1 ; Sprite Height (in tiles) dc.l \4 ; pointer to SCB1 data dc.w ((\5&$0F)<<8)|(\6&$FF) ; SCB2 dc.w ((496-\3)<<7)|(\1&$3F) ; SCB3 (sans sticky bit) dc.w (\2)<<7 ; SCB4 endm ;==============================================================================; ; [Metasprites] ; Metasprite code will need to be revisited (see doc/functions/sprite.txt) ;------------------------------------------------------------------------------; ; mspr_Load ; Loads a Metasprite into the VRAM. ; Uses spr_LoadDirect, forces sticky bit. ; (Params) ; d0 [word] Metasprite starting sprite index ; a0 [long] Pointer to Metasprite Data Block mspr_Load: move.w d0,d5 ; save initial sprite number movea.l a0,a2 ; a0 is used by other routines move.w (a2)+,d6 ; $00: number of sprites in metasprite subi.w #1,d6 ; subtract 1 for loop counter ; metasprite sprite loading loop .mspr_Load_Loop: movea.l (a2)+,a0 ; get sprite data block pointer jsr spr_LoadDirect ; load sprite ; something about automatically setting sticky bit if d0 > d5 cmp.w d5,d0 beq .mspr_LoadLoop_Continue ; set sticky bit for this sprite move.w d0,d4 ; temporary for getting SCB3 addr addi.w #$8200,d4 ; address into SCB3 move.w d4,LSPC_ADDR ; set VRAM addr move.w #$0040,LSPC_DATA ; set sticky bit .mspr_LoadLoop_Continue: addq.w #1,d0 ; update sprite index dbra d6,.mspr_Load_Loop ; loop until finished .mspr_Load_End: rts ;==============================================================================;
33.266667
92
0.575401
a1d8bed629894b96e20046671b9fd4e7dc0b91d6
33,475
psm1
PowerShell
ComputeAdmin/AzureStack.ComputeAdmin.psm1
MilanNXT/AzureStack-Tools
72147c9fb9f88808d0defa378da9ec73899da681
[ "MIT" ]
1
2019-04-09T20:43:13.000Z
2019-04-09T20:43:13.000Z
ComputeAdmin/AzureStack.ComputeAdmin.psm1
MilanNXT/AzureStack-Tools
72147c9fb9f88808d0defa378da9ec73899da681
[ "MIT" ]
null
null
null
ComputeAdmin/AzureStack.ComputeAdmin.psm1
MilanNXT/AzureStack-Tools
72147c9fb9f88808d0defa378da9ec73899da681
[ "MIT" ]
1
2019-07-03T04:03:13.000Z
2019-07-03T04:03:13.000Z
# Copyright (c) Microsoft Corporation. All rights reserved. # See LICENSE.txt in the project root for license information. <# .SYNOPSIS Adds the VMSS Gallery Item to your Azure Stack Marketplace. #> function Add-AzsVMSSGalleryItem { [CmdletBinding()] Param( [Parameter(Mandatory = $false)] [ValidatePattern("^[0-9a-zA-Z]+$")] [ValidateLength(1, 128)] [String] $Location ) $Location = Get-AzsHomeLocation -Location $Location $rgName = "vmss.gallery" New-AzureRmResourceGroup -Name $rgName -Location $Location -Force $saName = "vmssgallery" $null = New-AzureRmStorageAccount -ResourceGroupName $rgName -Location $Location -Name $saName -Type Standard_LRS $cName = "gallery" Set-AzureRmCurrentStorageAccount -StorageAccountName $saName -ResourceGroupName $rgName $container = Get-AzureStorageContainer -Name $cName -ErrorAction SilentlyContinue if (-not ($container)) { New-AzureStorageContainer -Name $cName -Permission Blob } $fileName = "microsoft.vmss.1.3.6.azpkg" $blob = Set-AzureStorageBlobContent -File ($PSScriptRoot + "\" + $fileName) -Blob $fileName -Container $cName -Force $container = Get-AzureStorageContainer -Name $cName -ErrorAction SilentlyContinue $uri = $blob.Context.BlobEndPoint + $container.Name + "/" + $blob.Name Add-AzsGalleryItem -GalleryItemUri $uri } Export-ModuleMember -Function 'Add-AzsVMSSGalleryItem' <# .SYNOPSIS Adds the VMSS Gallery Item from your Azure Stack Marketplace. #> function Remove-AzsVMSSGalleryItem { [CmdletBinding(SupportsShouldProcess = $true)] param() $item = Get-AzsGalleryItem -Name "microsoft.vmss.1.3.6" if ($item) { if ($pscmdlet.ShouldProcess("Delete VMSS Gallery Item")) { $null = $item | Remove-AzsGalleryItem $item } } } Export-ModuleMember -Function 'Remove-AzsVMSSGalleryItem' <# .SYNOPSIS Uploads a VM Image to your Azure Stack and creates a Marketplace item for it. #> function Add-AzsVMImage { [CmdletBinding(DefaultParameterSetName = 'VMImageFromLocal')] Param( [Parameter(Mandatory = $true, ParameterSetName = 'VMImageFromLocal')] [Parameter(Mandatory = $true, ParameterSetName = 'VMImageFromAzure')] [ValidatePattern("[a-zA-Z0-9-]{3,}")] [String] $Publisher, [Parameter(Mandatory = $true, ParameterSetName = 'VMImageFromLocal')] [Parameter(Mandatory = $true, ParameterSetName = 'VMImageFromAzure')] [ValidatePattern("[a-zA-Z0-9-]{3,}")] [String] $Offer, [Parameter(Mandatory = $true, ParameterSetName = 'VMImageFromLocal')] [Parameter(Mandatory = $true, ParameterSetName = 'VMImageFromAzure')] [ValidatePattern("[a-zA-Z0-9-]{3,}")] [String] $Sku, [Parameter(Mandatory = $true, ParameterSetName = 'VMImageFromLocal')] [Parameter(Mandatory = $true, ParameterSetName = 'VMImageFromAzure')] [ValidatePattern("\d+\.\d+\.\d+")] [String] $Version, [Parameter(Mandatory = $true, ParameterSetName = 'VMImageFromLocal')] [ValidateNotNullorEmpty()] [String] $OSDiskLocalPath, [Parameter(Mandatory = $true, ParameterSetName = 'VMImageFromAzure')] [ValidateNotNullorEmpty()] [String] $OSDiskBlobURI, [Parameter(Mandatory = $true, ParameterSetName = 'VMImageFromLocal')] [Parameter(Mandatory = $true, ParameterSetName = 'VMImageFromAzure')] [ValidateSet('Windows' , 'Linux')] [String] $OSType, [Parameter(Mandatory = $false, ParameterSetName = 'VMImageFromLocal')] [Parameter(Mandatory = $false, ParameterSetName = 'VMImageFromAzure')] [String] $Location, [Parameter(ParameterSetName = 'VMImageFromLocal')] [string[]] $DataDisksLocalPaths, [Parameter(ParameterSetName = 'VMImageFromAzure')] [string[]] $DataDiskBlobURIs, [Parameter(ParameterSetName = 'VMImageFromLocal')] [Parameter(ParameterSetName = 'VMImageFromAzure')] [string] $BillingPartNumber, [Parameter(ParameterSetName = 'VMImageFromLocal')] [Parameter(ParameterSetName = 'VMImageFromAzure')] [string] $Title, [Parameter(ParameterSetName = 'VMImageFromLocal')] [Parameter(ParameterSetName = 'VMImageFromAzure')] [string] $Description, [Parameter(ParameterSetName = 'VMImageFromLocal')] [Parameter(ParameterSetName = 'VMImageFromAzure')] [bool] $CreateGalleryItem = $true, [switch] $Force ) $location = Get-AzsHomeLocation -Location $location if ($CreateGalleryItem -eq $false -and $PSBoundParameters.ContainsKey('title')) { Write-Error -Message "The title parameter only applies to creating a gallery item." -ErrorAction Stop } if ($CreateGalleryItem -eq $false -and $PSBoundParameters.ContainsKey('description')) { Write-Error -Message "The description parameter only applies to creating a gallery item." -ErrorAction Stop } $resourceGroupName = "addvmimageresourcegroup" $storageAccountName = "addvmimagestorageaccount" $containerName = "addvmimagecontainer" #pre validate if image is not already deployed $VMImageAlreadyAvailable = $false if ($(Get-AzsVMImage -publisher $publisher -offer $offer -sku $sku -version $version -location $location -ErrorAction SilentlyContinue).Properties.ProvisioningState -eq 'Succeeded') { $VMImageAlreadyAvailable = $true Write-Verbose -Message ('VM Image with publisher "{0}", offer "{1}", sku "{2}", version "{3}" already is present.' -f $publisher, $offer, $sku, $version) -Verbose -ErrorAction Stop } #potentially the RG was not cleaned up when exception happened in previous run. Test for exist if (-not (Get-AzureRmResourceGroup -Name $resourceGroupName -Location $location -ErrorAction SilentlyContinue)) { New-AzureRmResourceGroup -Name $resourceGroupName -Location $location } #same for storage $storageAccount = Get-AzureRmStorageAccount -Name $storageAccountName -ResourceGroupName $resourceGroupName -ErrorAction SilentlyContinue if (-not ($storageAccount)) { $storageAccount = New-AzureRmStorageAccount -Name $storageAccountName -Location $location -ResourceGroupName $resourceGroupName -Type Standard_LRS } Set-AzureRmCurrentStorageAccount -StorageAccountName $storageAccountName -ResourceGroupName $resourceGroupName #same for container $container = Get-AzureStorageContainer -Name $containerName -ErrorAction SilentlyContinue if (-not ($container)) { $container = New-AzureStorageContainer -Name $containerName -Permission Blob } if (($pscmdlet.ParameterSetName -eq "VMImageFromLocal") -and (-not $VMImageAlreadyAvailable)) { $storageAccount.PrimaryEndpoints.Blob $script:osDiskName = Split-Path $osDiskLocalPath -Leaf $script:osDiskBlobURIFromLocal = '{0}{1}/{2}' -f $storageAccount.PrimaryEndpoints.Blob.AbsoluteUri, $containerName, $osDiskName Add-AzureRmVhd -Destination $osDiskBlobURIFromLocal -ResourceGroupName $resourceGroupName -LocalFilePath $osDiskLocalPath -OverWrite $script:dataDiskBlobURIsFromLocal = New-Object System.Collections.ArrayList if ($PSBoundParameters.ContainsKey('dataDisksLocalPaths')) { foreach ($dataDiskLocalPath in $dataDisksLocalPaths) { $dataDiskName = Split-Path $dataDiskLocalPath -Leaf $dataDiskBlobURI = "https://$storageAccountName.blob.$Domain/$containerName/$dataDiskName" $dataDiskBlobURIsFromLocal.Add($dataDiskBlobURI) Add-AzureRmVhd -Destination $dataDiskBlobURI -ResourceGroupName $resourceGroupName -LocalFilePath $dataDiskLocalPath -OverWrite } } } #building platform image JSON #building osDisk json if ($pscmdlet.ParameterSetName -eq "VMImageFromLocal") { $osDiskJSON = '"OsDisk":{"OsType":"' + $osType + '","Uri":"' + $osDiskBlobURIFromLocal + '"}' } else { $osDiskJSON = '"OsDisk":{"OsType":"' + $osType + '","Uri":"' + $osDiskBlobURI + '"}' } #building details JSON $detailsJSON = '' if ($PSBoundParameters.ContainsKey('billingPartNumber')) { $detailsJSON = '"Details":{"BillingPartNumber":"' + $billingPartNumber + '"}' } #building dataDisk JSON $dataDisksJSON = '' if ($pscmdlet.ParameterSetName -eq "VMImageFromLocal") { if ($dataDiskBlobURIsFromLocal.Count -ne 0) { $dataDisksJSON = '"DataDisks":[' $i = 0 foreach ($dataDiskBlobURI in $dataDiskBlobURIsFromLocal) { if ($i -ne 0) { $dataDisksJSON = $dataDisksJSON + ', ' } $newDataDisk = '{"Lun":' + $i + ', "Uri":"' + $dataDiskBlobURI + '"}' $dataDisksJSON = $dataDisksJSON + $newDataDisk; ++$i } $dataDisksJSON = $dataDisksJSON + ']' } } else { if ($dataDiskBlobURIs.Count -ne 0) { $dataDisksJSON = '"DataDisks":[' $i = 0 foreach ($dataDiskBlobURI in $dataDiskBlobURIs) { if ($i -ne 0) { $dataDisksJSON = $dataDisksJSON + ', ' } $newDataDisk = '{"Lun":' + $i + ', "Uri":"' + $dataDiskBlobURI + '"}' $dataDisksJSON = $dataDisksJSON + $newDataDisk; ++$i } $dataDisksJSON = $dataDisksJSON + ']' } } #building ARMResource $propertyBody = $osDiskJSON if (![string]::IsNullOrEmpty($dataDisksJson)) { $propertyBody = $propertyBody + ', ' + $dataDisksJson } if (![string]::IsNullOrEmpty($detailsJson)) { $propertyBody = $propertyBody + ', ' + $detailsJson } if (-not $VMImageAlreadyAvailable) { $imageDescription = "publisher: {0}, offer: {1}, sku: {2}, version: {3}" -f $publisher, $offer, $sku, $version $propertyBody = "{" + $propertyBody + "}" $params = @{ ResourceType = "Microsoft.Compute.Admin/locations/artifactTypes/publishers/offers/skus/versions" ResourceName = "{0}/platformImage/{1}/{2}/{3}/{4}" -f $location, $publisher, $offer, $sku, $version ApiVersion = "2015-12-01-preview" Properties = ConvertFrom-Json $propertyBody } Write-Verbose "Creating VM Image..." New-AzureRmResource @params -ErrorAction Stop -Force } $platformImage = Get-AzsVMImage -publisher $publisher -offer $offer -sku $sku -version $version -location $location while ($platformImage.Properties.ProvisioningState -ne 'Succeeded') { if ($platformImage.Properties.ProvisioningState -eq 'Failed') { Write-Error -Message "VM image download failed." -ErrorAction Stop } if ($platformImage.Properties.ProvisioningState -eq 'Canceled') { Write-Error -Message "VM image download was canceled." -ErrorAction Stop } Write-Verbose "Downloading..."; Start-Sleep -Seconds 10 $platformImage = Get-AzsVMImage -publisher $publisher -offer $offer -sku $sku -version $version -location $location } #reaquire storage account context Set-AzureRmCurrentStorageAccount -StorageAccountName $storageAccountName -ResourceGroupName $resourceGroupName $container = Get-AzureStorageContainer -Name $containerName -ErrorAction SilentlyContinue if ($CreateGalleryItem -eq $true -And $platformImage.Properties.ProvisioningState -eq 'Succeeded') { $GalleryItem = CreateGalleryItem -publisher $publisher -offer $offer -sku $sku -version $version -osType $osType -title $title -description $description $null = $container| Set-AzureStorageBlobContent -File $GalleryItem.FullName -Blob $galleryItem.Name $galleryItemURI = '{0}{1}/{2}' -f $storageAccount.PrimaryEndpoints.Blob.AbsoluteUri, $containerName, $galleryItem.Name Add-AzsGalleryItem -GalleryItemUri $galleryItemURI #cleanup Remove-Item $GalleryItem } Remove-AzureStorageContainer -Name $containerName -Force Remove-AzureRmStorageAccount -ResourceGroupName $resourceGroupName -AccountName $storageAccountName Remove-AzureRmResourceGroup -Name $resourceGroupName -Force } Export-ModuleMember -Function 'Add-AzsVMImage' <# .SYNOPSIS Removes an existing VM Image from your Azure Stack. Does not delete any maketplace items created by Add-AzSVMImage. #> function Remove-AzsVMImage { [CmdletBinding(SupportsShouldProcess = $true)] Param( [Parameter(Mandatory = $true)] [ValidatePattern("[a-zA-Z0-9-]{3,}")] [String] $Publisher, [Parameter(Mandatory = $true)] [ValidatePattern("[a-zA-Z0-9-]{3,}")] [String] $Offer, [Parameter(Mandatory = $true)] [ValidatePattern("[a-zA-Z0-9-]{3,}")] [String] $Sku, [Parameter(Mandatory = $true)] [ValidatePattern("\d+\.\d+\.\d+")] [String] $Version, [Parameter(Mandatory = $false)] [String] $Location, [switch] $KeepMarketplaceItem, [switch] $Force ) $location = Get-AzsHomeLocation -Location $location $VMImageExists = $false if (Get-AzsVMImage -publisher $publisher -offer $offer -sku $sku -version $version -location $location -ErrorAction SilentlyContinue) { Write-Verbose "VM Image is present in Azure Stack - continuing to remove" -Verbose $VMImageExists = $true } else { Write-Verbose -Message ('VM Image with publisher "{0}", offer "{1}", sku "{2}" is not present and will not be removed. Marketplace item may still be removed.' -f $publisher, $offer, $sku) -ErrorAction Stop } if ($VMImageExists) { $imageDescription = "publisher: {0}, offer: {1}, sku: {2}, version: {3}" -f $publisher, $offer, $sku, $version if ($Force.IsPresent -or $PSCmdlet.ShouldContinue("Are you sure to delete VM image with $imageDescription ?", "")) { try { $params = @{ ResourceType = "Microsoft.Compute.Admin/locations/artifactTypes/publishers/offers/skus/versions" ResourceName = "{0}/platformImage/{1}/{2}/{3}/{4}" -f $location, $publisher, $offer, $sku, $version ApiVersion = "2015-12-01-preview" } Write-Verbose -Message "Deleting VM Image" -Verbose Remove-AzureRmResource @params -Force } catch { Write-Error -Message ('Deletion of VM Image with {0} failed with Error:{1}.' -f $imageDescription, $Error) -ErrorAction Stop } } } if (-not $KeepMarketplaceItem) { Write-Verbose "Removing the marketplace item for the VM Image." -Verbose $name = "$offer$sku" #Remove periods so that the offer and sku can be retrieved from the Marketplace Item name $name = $name -replace "\.", "-" if ($pscmdlet.ShouldProcess("$("Remove Gallery Item: '{0}', offer: '{1}', sku: '{2}'" -f $publisher,$offer,$sku)")) { Get-AzsGalleryItem | Where-Object {$_.Name -contains "$publisher.$name.$version"} | Remove-AzsGalleryItem } } } Export-ModuleMember -Function 'Remove-AzsVMImage' <# .SYNOPSIS Gets a VM Image from your Azure Stack as an Administrator to view the provisioning state of the image. #> function Get-AzsVMImage { Param( [Parameter(Mandatory = $true)] [ValidatePattern("[a-zA-Z0-9-]{3,}")] [String] $Publisher, [Parameter(Mandatory = $true)] [ValidatePattern("[a-zA-Z0-9-]{3,}")] [String] $Offer, [Parameter(Mandatory = $true)] [ValidatePattern("[a-zA-Z0-9-]{3,}")] [String] $Sku, [Parameter(Mandatory = $true)] [ValidatePattern("\d+\.\d+\.\d+")] [String] $Version, [Parameter(Mandatory = $false)] [String] $Location ) $location = Get-AzsHomeLocation -Location $location $params = @{ ResourceType = "Microsoft.Compute.Admin/locations/artifactTypes/publishers/offers/skus/versions" ResourceName = "{0}/platformImage/{1}/{2}/{3}/{4}" -f $location, $publisher, $offer, $sku, $version ApiVersion = "2015-12-01-preview" } try { $platformImage = Get-AzureRmResource @params return $platformImage } catch { return $null } } Export-ModuleMember -Function 'Get-AzsVMImage' <# .SYNOPSIS Creates and Uploads a new Server 2016 Core and / or Full Image and creates a Marketplace item for it. #> function New-AzsServer2016VMImage { [cmdletbinding(DefaultParameterSetName = 'NoCU')] param ( [Parameter()] [validateset('Full', 'Core', 'Both')] [String] $Version = 'Full', [Parameter(ParameterSetName = 'LatestCU')] [switch] $IncludeLatestCU, [Parameter(ParameterSetName = 'ManualCUUri')] [string] $CUUri, [Parameter(ParameterSetName = 'ManualCUPath')] [string] $CUPath, [Parameter()] [string] $VHDSizeInMB = 40960, [Parameter(Mandatory)] [ValidateScript( {Test-Path -Path $_})] [string] $ISOPath, [Parameter(Mandatory = $false)] [String] $Location, [Parameter()] [bool] $CreateGalleryItem = $true, [Parameter()] [bool] $Net35 = $true ) begin { function CreateWindowsVHD { [cmdletbinding()] param ( [string] $VHDPath, [uint32] $VHDSizeInMB, [string] $IsoPath, [string] $Edition, [string] $CabPath, [switch] $Net35 ) $tmpfile = New-TemporaryFile "create vdisk FILE=`"$VHDPath`" TYPE=EXPANDABLE MAXIMUM=$VHDSizeInMB" | Out-File -FilePath $tmpfile.FullName -Encoding ascii Write-Verbose -Message "Creating VHD at: $VHDPath of size: $VHDSizeInMB MB" diskpart.exe /s $tmpfile.FullName | Out-Null $tmpfile | Remove-Item -Force try { if (!(Test-Path -Path $VHDPath)) { Write-Error -Message "VHD was not created" -ErrorAction Stop } Write-Verbose -Message "Preparing VHD" $VHDMount = Mount-DiskImage -ImagePath $VHDPath -PassThru -ErrorAction Stop $disk = $VHDMount | Get-DiskImage -ErrorAction Stop | Get-Disk -ErrorAction SilentlyContinue $disk | Initialize-Disk -PartitionStyle MBR -ErrorAction Stop $partition = New-Partition -UseMaximumSize -Disknumber $disk.DiskNumber -IsActive:$True -AssignDriveLetter -ErrorAction Stop $volume = Format-Volume -Partition $partition -FileSystem NTFS -confirm:$false -ErrorAction Stop $VHDDriveLetter = $volume.DriveLetter Write-Verbose -Message "VHD is mounted at drive letter: $VHDDriveLetter" Write-Verbose -Message "Mounting ISO" $IsoMount = Mount-DiskImage -ImagePath $ISOPath -PassThru $IsoDriveLetter = ($IsoMount | Get-Volume).DriveLetter Write-Verbose -Message "ISO is mounted at drive letter: $IsoDriveLetter" Write-Verbose -Message "Applying Image $Edition to VHD" $ExpandArgs = @{ ApplyPath = "$VHDDriveLetter`:\" ImagePath = "$IsoDriveLetter`:\Sources\install.wim" Name = $Edition ErrorAction = 'Stop' } $null = Expand-WindowsImage @ExpandArgs if ($CabPath) { Write-Verbose -Message "Applying update: $(Split-Path -Path $CabPath -Leaf)" $null = Add-WindowsPackage -PackagePath $CabPath -Path "$VHDDriveLetter`:\" -ErrorAction Stop } if ($Net35) { Write-Verbose -Message "Adding .NET 3.5" $null = Add-WindowsPackage -PackagePath "$IsoDriveLetter`:\sources\sxs\microsoft-windows-netfx3-ondemand-package.cab" -Path "$VHDDriveLetter`:\" } Write-Verbose -Message "Making VHD bootable" $null = & "$VHDDriveLetter`:\Windows\System32\bcdboot.exe" "$VHDDriveLetter`:\windows" "/s" "$VHDDriveLetter`:" "/f" "BIOS" } catch { Write-Error -ErrorRecord $_ -ErrorAction Stop } finally { if ($VHDMount) { $VHDMount | Dismount-DiskImage } if ($IsoMount) { $IsoMount | Dismount-DiskImage } } } function ExpandMSU { param ( $Path ) $expandcab = expand -f:*KB*.cab (Resolve-Path $Path) (Split-Path (Resolve-Path $Path)) $expandcab[3].Split()[1] } } process { $location = Get-AzsHomeLocation -Location $location Write-Verbose -Message "Checking ISO path for a valid ISO." -Verbose if (!$IsoPath.ToLower().contains('.iso')) { Write-Error -Message "ISO path is not a valid ISO file." -ErrorAction Stop } if (!([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) { Write-Error -Message "New-AzsServer2016VMImage must run with Administrator privileges" -ErrorAction Stop } $ModulePath = Split-Path -Path $MyInvocation.MyCommand.Module.Path $CoreEdition = 'Windows Server 2016 SERVERDATACENTERCORE' $FullEdition = 'Windows Server 2016 SERVERDATACENTER' if ($pscmdlet.ParameterSetName -ne 'NoCU') { if ($pscmdlet.ParameterSetName -eq 'ManualCUPath') { $CUFile = Split-Path -Path $CUPath -Leaf $FileExt = $CUFile.Split('.')[-1] if ($FileExt -eq 'msu') { $CabPath = ExpandMSU -Path $CUPath } elseif ($FileExt -eq 'cab') { $CabPath = $CUPath } else { Write-Error -Message "CU File: $CUFile has the wrong file extension. Should be 'cab' or 'msu' but is $FileExt" -ErrorAction Stop } } else { if ($IncludeLatestCU) { #for latest CU, check https://support.microsoft.com/en-us/help/4000825/windows-10-and-windows-server-2016-update-history $Uri = 'http://download.windowsupdate.com/c/msdownload/update/software/secu/2017/10/windows10.0-kb4041691-x64_6b578432462f6bec9b4c903b3119d437ef32eb29.msu' $OutFile = "$ModulePath\update.msu" } else { #test if manual Uri is giving 200 $TestCUUri = Invoke-WebRequest -Uri $CUUri -UseBasicParsing -Method Head if ($TestCUUri.StatusCode -ne 200) { Write-Error -Message "The CU Uri specified is not valid. StatusCode: $($TestCUUri.StatusCode)" -ErrorAction Stop } else { $Uri = $CUUri $OutFile = "$ModulePath\" + $CUUri.Split('/')[-1] } } $CurrentProgressPref = $ProgressPreference $ProgressPreference = 'SilentlyContinue' Write-Verbose -Message "Starting download of CU. This will take some time." -Verbose Invoke-WebRequest -Uri $Uri -OutFile $OutFile -UseBasicParsing $ProgressPreference = $CurrentProgressPref Unblock-File -Path $OutFile $CabPath = ExpandMSU -Path $OutFile } } $ConvertParams = @{ VHDSizeInMB = $VhdSizeInMB IsoPath = $ISOPath } if ($null -ne $CabPath) { [void] $ConvertParams.Add('CabPath', $CabPath) } if ($Net35) { [void] $ConvertParams.Add('Net35', $true) } $PublishArguments = @{ publisher = 'MicrosoftWindowsServer' offer = 'WindowsServer' version = '1.0.0' osType = 'Windows' location = $location } if ($Version -eq 'Core' -or $Version -eq 'Both') { $sku = "2016-Datacenter-Server-Core" #Pre-validate that the VM Image is not already available $VMImageAlreadyAvailable = $false if ($(Get-AzsVMImage -publisher $PublishArguments.publisher -offer $PublishArguments.offer -sku $sku -version $PublishArguments.version -location $PublishArguments.location -ErrorAction SilentlyContinue).Properties.ProvisioningState -eq 'Succeeded') { $VMImageAlreadyAvailable = $true Write-Verbose -Message ('VM Image with publisher "{0}", offer "{1}", sku "{2}", version "{3}" already is present.' -f $publisher, $offer, $sku, $version) -Verbose -ErrorAction Stop } $ImagePath = "$ModulePath\Server2016DatacenterCoreEval.vhd" try { if ((!(Test-Path -Path $ImagePath)) -and (!$VMImageAlreadyAvailable)) { Write-Verbose -Message "Creating Server Core Image" CreateWindowsVHD @ConvertParams -VHDPath $ImagePath -Edition $CoreEdition -ErrorAction Stop -Verbose } else { Write-Verbose -Message "Server Core VHD already found." } if ($CreateGalleryItem) { $description = "This evaluation image should not be used for production workloads." Add-AzsVMImage -sku $sku -osDiskLocalPath $ImagePath @PublishArguments -title "Windows Server 2016 Datacenter Core Eval" -description $description -CreateGalleryItem $CreateGalleryItem } else { Add-AzsVMImage -sku $sku -osDiskLocalPath $ImagePath @PublishArguments -CreateGalleryItem $CreateGalleryItem } } catch { Write-Error -ErrorRecord $_ -ErrorAction Stop } } if ($Version -eq 'Full' -or $Version -eq 'Both') { $ImagePath = "$ModulePath\Server2016DatacenterFullEval.vhd" try { $sku = "2016-Datacenter" #Pre-validate that the VM Image is not already available $VMImageAlreadyAvailable = $false if ($(Get-AzsVMImage -publisher $PublishArguments.publisher -offer $PublishArguments.offer -sku $sku -version $PublishArguments.version -location $PublishArguments.location -ErrorAction SilentlyContinue).Properties.ProvisioningState -eq 'Succeeded') { $VMImageAlreadyAvailable = $true Write-Verbose -Message ('VM Image with publisher "{0}", offer "{1}", sku "{2}", version "{3}" already is present.' -f $publisher, $offer, $sku, $version) -Verbose -ErrorAction Stop } if ((!(Test-Path -Path $ImagePath)) -and (!$VMImageAlreadyAvailable)) { Write-Verbose -Message "Creating Server Full Image" -Verbose CreateWindowsVHD @ConvertParams -VHDPath $ImagePath -Edition $FullEdition -ErrorAction Stop -Verbose } else { Write-Verbose -Message "Server Full VHD already found." } if ($CreateGalleryItem) { $description = "This evaluation image should not be used for production workloads." Add-AzsVMImage -sku $sku -osDiskLocalPath $ImagePath @PublishArguments -title "Windows Server 2016 Datacenter Eval" -description $description -CreateGalleryItem $CreateGalleryItem } else { Add-AzsVMImage -sku $sku -osDiskLocalPath $ImagePath @PublishArguments -CreateGalleryItem $CreateGalleryItem } } catch { Write-Error -ErrorRecord $_ -ErrorAction Stop } } if (Test-Path -Path $ImagePath) { Remove-Item $ImagePath } } } Export-ModuleMember -Function 'New-AzsServer2016VMImage' Function CreateGalleryItem { Param( [ValidatePattern("[a-zA-Z0-9-]{3,}")] [String] $Publisher, [ValidatePattern("[a-zA-Z0-9-]{3,}")] [String] $Offer, [ValidatePattern("[a-zA-Z0-9-]{3,}")] [String] $Sku, [ValidatePattern("\d+\.\d+\.\d")] [String] $Version, [ValidateSet('Windows' , 'Linux')] [String] $OSType, [string] $Title, [string] $Description ) $workdir = '{0}{1}' -f [System.IO.Path]::GetTempPath(), [System.Guid]::NewGuid().ToString() New-Item $workdir -ItemType Directory | Out-Null $compressedGalleryItemPath = Join-Path $PSScriptRoot 'CustomizedVMGalleryItem.azpkg' Copy-Item -Path $compressedGalleryItemPath -Destination "$workdir\CustomizedVMGalleryItem.zip" $extractedGalleryItemPath = Join-Path $workdir 'galleryItem' New-Item -ItemType directory -Path $extractedGalleryItemPath | Out-Null expand-archive -Path "$workdir\CustomizedVMGalleryItem.zip" -DestinationPath $extractedGalleryItemPath -Force $maxAttempts = 5 for ($retryAttempts = 1; $retryAttempts -le $maxAttempts; $retryAttempts++) { try { Write-Verbose -Message "Downloading Azure Stack Marketplace Item Generator Attempt $retryAttempts" -Verbose Invoke-WebRequest -Uri http://www.aka.ms/azurestackmarketplaceitem -OutFile "$workdir\MarketplaceItem.zip" break } catch { if ($retryAttempts -ge $maxAttempts) { Write-Error "Failed to download Azure Stack Marketplace Item Generator" -ErrorAction Stop } } } Expand-Archive -Path "$workdir\MarketplaceItem.zip" -DestinationPath $workdir -Force #region UIDef $createUIDefinitionPath = Join-Path $extractedGalleryItemPath 'DeploymentTemplates\CreateUIDefinition.json' $JSON = Get-Content $createUIDefinitionPath | Out-String | ConvertFrom-Json $JSON.parameters.osPlatform = $osType $JSON.parameters.imageReference.publisher = $publisher $JSON.parameters.imageReference.offer = $offer $JSON.parameters.imageReference.sku = $sku $JSON | ConvertTo-Json -Compress| set-content $createUIDefinitionPath #endregion #region Manifest $manifestPath = Join-Path $extractedGalleryItemPath 'manifest.json' $JSON = Get-Content $manifestPath | Out-String | ConvertFrom-Json if (!$title) { $title = "{0}-{1}-{2}" -f $publisher, $offer, $sku } $name = "$offer$sku" #Remove periods so that the offer and sku can be part of the MarketplaceItem name $name = $name -replace "\.", "-" $JSON.name = $name $JSON.publisher = $publisher $JSON.version = $version $JSON.displayName = $title $JSON.publisherDisplayName = $publisher $JSON.publisherLegalName = $publisher $JSON | ConvertTo-Json -Compress| set-content $manifestPath #endregion #region Strings if (!$description) { $description = "Create a virtual machine from a VM image. Publisher: {0}, Offer: {1}, Sku:{2}, Version: {3}" -f $publisher, $offer, $sku, $version } $stringsPath = Join-Path $extractedGalleryItemPath 'strings\resources.resjson' $JSON = Get-Content $stringsPath | Out-String | ConvertFrom-Json $JSON.longSummary = $description $JSON.description = $description $JSON.summary = $description $JSON | ConvertTo-Json -Compress | set-content $stringsPath #endregion $extractedGalleryPackagerExePath = Join-Path $workdir "Azure Stack Marketplace Item Generator and Sample\AzureGalleryPackageGenerator" $galleryItemName = $publisher + "." + $name + "." + $version + ".azpkg" $currentPath = $pwd Set-Location -Path $extractedGalleryPackagerExePath .\AzureGalleryPackager.exe package -m $manifestPath -o $workdir Set-Location -Path $currentPath #cleanup Remove-Item $extractedGalleryItemPath -Recurse -Force Remove-Item "$workdir\Azure Stack Marketplace Item Generator and Sample" -Recurse -Force Remove-Item "$workdir\CustomizedVMGalleryItem.zip" Remove-Item "$workdir\MarketplaceItem.zip" $azpkg = '{0}\{1}' -f $workdir, $galleryItemName return Get-Item -LiteralPath $azpkg } Function Get-AzsHomeLocation { param( [Parameter(Mandatory = $false)] [string] $Location ) if ($Location) { return $Location } $locationResource = Get-AzsLocation return $locationResource.Name }
40.428744
267
0.609589
48d8bc9e5ded00663ce91b121657a8fea2a75225
156
swift
Swift
CouchTrackerCoreTests/Extensions/Bundle+Testing.swift
arctouch/CouchTracker
01e21f689b17f9a7ef17e1d2d1f35c3c5e3ca583
[ "Unlicense" ]
48
2017-11-23T18:04:59.000Z
2022-03-10T17:33:56.000Z
CouchTrackerCoreTests/Extensions/Bundle+Testing.swift
arctouch/CouchTracker
01e21f689b17f9a7ef17e1d2d1f35c3c5e3ca583
[ "Unlicense" ]
90
2017-10-20T21:42:14.000Z
2020-05-21T14:41:12.000Z
CouchTrackerCoreTests/Extensions/Bundle+Testing.swift
arctouch/CouchTracker
01e21f689b17f9a7ef17e1d2d1f35c3c5e3ca583
[ "Unlicense" ]
10
2019-01-06T23:04:08.000Z
2022-02-10T12:21:30.000Z
import Foundation extension Bundle { static var testing: Bundle { return Bundle(identifier: "io.github.pietrocaselani.CouchTrackerCoreTests")! } }
19.5
80
0.75641
9f484590ca0f633b5e2ccd5d68fcf934de1f76d4
5,230
asm
Assembly
Transynther/x86/_processed/NONE/_xt_sm_/i9-9900K_12_0xa0_notsx.log_6_206.asm
ljhsiun2/medusa
67d769b8a2fb42c538f10287abaf0e6dbb463f0c
[ "MIT" ]
9
2020-08-13T19:41:58.000Z
2022-03-30T12:22:51.000Z
Transynther/x86/_processed/NONE/_xt_sm_/i9-9900K_12_0xa0_notsx.log_6_206.asm
ljhsiun2/medusa
67d769b8a2fb42c538f10287abaf0e6dbb463f0c
[ "MIT" ]
1
2021-04-29T06:29:35.000Z
2021-05-13T21:02:30.000Z
Transynther/x86/_processed/NONE/_xt_sm_/i9-9900K_12_0xa0_notsx.log_6_206.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 %r15 push %r9 push %rbx push %rcx push %rdi push %rsi lea addresses_UC_ht+0x1b278, %r10 nop and %rbx, %rbx and $0xffffffffffffffc0, %r10 movaps (%r10), %xmm4 vpextrq $0, %xmm4, %r9 nop nop nop nop nop dec %r9 lea addresses_D_ht+0x2748, %r13 nop nop nop add $43774, %r15 mov $0x6162636465666768, %r11 movq %r11, %xmm6 vmovups %ymm6, (%r13) cmp $56919, %rbx lea addresses_A_ht+0x1dcf8, %rsi lea addresses_WC_ht+0x180f8, %rdi nop nop nop nop cmp $31308, %r13 mov $103, %rcx rep movsq inc %r9 lea addresses_WT_ht+0x38f8, %rsi lea addresses_normal_ht+0x12f8, %rdi nop sub %r13, %r13 mov $74, %rcx rep movsw nop sub %rsi, %rsi lea addresses_D_ht+0xaf16, %r9 nop nop nop nop nop sub %rdi, %rdi movl $0x61626364, (%r9) nop nop nop nop xor %r13, %r13 lea addresses_WT_ht+0x7bc7, %rsi lea addresses_WC_ht+0x1b6f8, %rdi nop nop nop nop inc %rbx mov $53, %rcx rep movsl nop nop dec %rbx lea addresses_D_ht+0xf3d0, %r13 nop nop nop xor %r9, %r9 mov $0x6162636465666768, %rbx movq %rbx, %xmm6 movups %xmm6, (%r13) nop nop nop nop and $50992, %rbx lea addresses_WT_ht+0xb0f8, %rsi lea addresses_normal_ht+0x19838, %rdi clflush (%rdi) nop nop nop nop nop and %rbx, %rbx mov $7, %rcx rep movsw nop nop xor $52388, %rsi lea addresses_D_ht+0x54f8, %r11 nop nop nop sub $53539, %rdi mov (%r11), %r10d nop nop nop nop sub %rdi, %rdi lea addresses_D_ht+0x95ef, %rdi nop nop nop nop cmp $64464, %r11 mov $0x6162636465666768, %rsi movq %rsi, %xmm6 vmovups %ymm6, (%rdi) nop xor %rdi, %rdi pop %rsi pop %rdi pop %rcx pop %rbx pop %r9 pop %r15 pop %r13 pop %r11 pop %r10 ret .global s_faulty_load s_faulty_load: push %r11 push %r12 push %r13 push %r14 push %r15 push %r9 push %rdi // Store lea addresses_RW+0x1a6f8, %r12 nop nop nop nop xor %r15, %r15 mov $0x5152535455565758, %rdi movq %rdi, %xmm4 movups %xmm4, (%r12) nop xor $42615, %r14 // Store lea addresses_RW+0x2cf8, %rdi nop nop nop nop nop sub %r15, %r15 mov $0x5152535455565758, %r14 movq %r14, (%rdi) nop nop sub %r14, %r14 // Store lea addresses_PSE+0x18df8, %r12 nop nop nop and %r9, %r9 mov $0x5152535455565758, %r14 movq %r14, (%r12) nop xor %r13, %r13 // Store lea addresses_normal+0x196fe, %r9 clflush (%r9) nop nop inc %r13 movl $0x51525354, (%r9) nop nop nop nop nop and %r13, %r13 // Store lea addresses_A+0x14330, %r12 clflush (%r12) nop xor $19059, %r15 mov $0x5152535455565758, %r14 movq %r14, (%r12) dec %r13 // Store mov $0x398, %r9 nop nop nop nop add $40704, %r13 mov $0x5152535455565758, %rdi movq %rdi, (%r9) and $62661, %r13 // Faulty Load lea addresses_RW+0x1a6f8, %r11 clflush (%r11) nop nop inc %r14 movb (%r11), %r13b lea oracles, %r14 and $0xff, %r13 shlq $12, %r13 mov (%r14,%r13,1), %r13 pop %rdi pop %r9 pop %r15 pop %r14 pop %r13 pop %r12 pop %r11 ret /* <gen_faulty_load> [REF] {'src': {'type': 'addresses_RW', 'AVXalign': True, 'size': 16, 'NT': False, 'same': False, 'congruent': 0}, 'OP': 'LOAD'} {'OP': 'STOR', 'dst': {'type': 'addresses_RW', 'AVXalign': False, 'size': 16, 'NT': False, 'same': True, 'congruent': 0}} {'OP': 'STOR', 'dst': {'type': 'addresses_RW', 'AVXalign': False, 'size': 8, 'NT': False, 'same': False, 'congruent': 9}} {'OP': 'STOR', 'dst': {'type': 'addresses_PSE', 'AVXalign': True, 'size': 8, 'NT': False, 'same': False, 'congruent': 8}} {'OP': 'STOR', 'dst': {'type': 'addresses_normal', 'AVXalign': False, 'size': 4, 'NT': False, 'same': False, 'congruent': 0}} {'OP': 'STOR', 'dst': {'type': 'addresses_A', 'AVXalign': False, 'size': 8, 'NT': False, 'same': False, 'congruent': 2}} {'OP': 'STOR', 'dst': {'type': 'addresses_P', 'AVXalign': False, 'size': 8, 'NT': False, 'same': False, 'congruent': 4}} [Faulty Load] {'src': {'type': 'addresses_RW', 'AVXalign': False, 'size': 1, 'NT': False, 'same': True, 'congruent': 0}, 'OP': 'LOAD'} <gen_prepare_buffer> {'src': {'type': 'addresses_UC_ht', 'AVXalign': True, 'size': 16, 'NT': True, 'same': False, 'congruent': 7}, 'OP': 'LOAD'} {'OP': 'STOR', 'dst': {'type': 'addresses_D_ht', 'AVXalign': False, 'size': 32, 'NT': False, 'same': False, 'congruent': 4}} {'src': {'type': 'addresses_A_ht', 'congruent': 7, 'same': False}, 'OP': 'REPM', 'dst': {'type': 'addresses_WC_ht', 'congruent': 9, 'same': False}} {'src': {'type': 'addresses_WT_ht', 'congruent': 3, 'same': False}, 'OP': 'REPM', 'dst': {'type': 'addresses_normal_ht', 'congruent': 9, 'same': False}} {'OP': 'STOR', 'dst': {'type': 'addresses_D_ht', 'AVXalign': False, 'size': 4, 'NT': False, 'same': False, 'congruent': 1}} {'src': {'type': 'addresses_WT_ht', 'congruent': 0, 'same': False}, 'OP': 'REPM', 'dst': {'type': 'addresses_WC_ht', 'congruent': 11, 'same': False}} {'OP': 'STOR', 'dst': {'type': 'addresses_D_ht', 'AVXalign': False, 'size': 16, 'NT': False, 'same': False, 'congruent': 3}} {'src': {'type': 'addresses_WT_ht', 'congruent': 9, 'same': False}, 'OP': 'REPM', 'dst': {'type': 'addresses_normal_ht', 'congruent': 3, 'same': False}} {'src': {'type': 'addresses_D_ht', 'AVXalign': False, 'size': 4, 'NT': False, 'same': False, 'congruent': 8}, 'OP': 'LOAD'} {'OP': 'STOR', 'dst': {'type': 'addresses_D_ht', 'AVXalign': False, 'size': 32, 'NT': False, 'same': False, 'congruent': 0}} {'58': 6} 58 58 58 58 58 58 */
19.810606
152
0.650478
8c81164f732e30e69d517a3e10b799e3ebf955cd
759
lua
Lua
vendor/RainbowRepacker/tool/engine_android(5)/assets/scripts/view/kScreen_1280_800/games/common2/onlooker/onlooker_spinner_item.lua
huangtao/cloud-test
8087b1337d47daab9eb39335ca6e286df0e4b4dc
[ "Apache-2.0" ]
1
2018-09-12T15:43:32.000Z
2018-09-12T15:43:32.000Z
vendor/RainbowRepacker/tool/engine_android(5)/assets/scripts/view/kScreen_1280_800/games/common2/onlooker/onlooker_spinner_item.lua
huangtao/cloud-test
8087b1337d47daab9eb39335ca6e286df0e4b4dc
[ "Apache-2.0" ]
null
null
null
vendor/RainbowRepacker/tool/engine_android(5)/assets/scripts/view/kScreen_1280_800/games/common2/onlooker/onlooker_spinner_item.lua
huangtao/cloud-test
8087b1337d47daab9eb39335ca6e286df0e4b4dc
[ "Apache-2.0" ]
3
2018-09-12T15:43:33.000Z
2019-07-10T09:50:15.000Z
local onlooker_spinner_pin_map = require("qnFiles/qnPlist/games/onlooker_spinner_pin"); local onlooker_spinner_item= { name="onlooker_spinner_item",type=0,typeName="View",time=0,x=0,y=0,width=130,height=37,visible=1,fillParentWidth=0,fillParentHeight=0,nodeAlign=kAlignTopLeft, { name="name",type=4,typeName="Text",time=0,x=0,y=0,width=80,height=27,visible=1,fillParentWidth=0,fillParentHeight=0,nodeAlign=kAlignLeft,fontSize=20,textAlign=kAlignLeft,colorRed=238,colorGreen=206,colorBlue=144,string=[[四个字哈]],colorA=1 }, { name="icon_friend",type=1,typeName="Image",time=0,x=80,y=0,width=25,height=25,visible=1,fillParentWidth=0,fillParentHeight=0,nodeAlign=kAlignLeft,file=onlooker_spinner_pin_map['icon_friend.png'] } } return onlooker_spinner_item;
63.25
238
0.802372
9b25a9bd76b48d861847f44e91c5b1db7ce68e50
1,437
lua
Lua
hoem tele.lua
xVoid-xyz/Roblox-Scripts
7eb176fa654f2ea5fbc6bcccced1b15df7ed82c2
[ "BSD-3-Clause" ]
70
2021-02-09T17:21:32.000Z
2022-03-28T12:41:42.000Z
hoem tele.lua
xVoid-xyz/Roblox-Scripts
7eb176fa654f2ea5fbc6bcccced1b15df7ed82c2
[ "BSD-3-Clause" ]
4
2021-08-19T22:05:58.000Z
2022-03-19T18:58:01.000Z
hoem tele.lua
xVoid-xyz/Roblox-Scripts
7eb176fa654f2ea5fbc6bcccced1b15df7ed82c2
[ "BSD-3-Clause" ]
325
2021-02-26T22:23:41.000Z
2022-03-31T19:36:12.000Z
vip = "acb227" plyr = game.Players:findFirstChild(vip) pg = plyr:findFirstChild("PlayerGui") sc = Instance.new("ScreenGui") sc.Name = "unHide" sc.Parent = pg use = no tx = Instance.new("TextButton") tx.BackgroundTransparency = 0.3 tx.Name = "Text - Reset" tx.Parent = sc tx.Position = UDim2.new(0, 200, 0, 125) tx.Size = UDim2.new(0, 99, 0, 20) tx.Text = "Home Tele" tx.MouseButton1Click:connect(function() human = plyr.Character:findFirstChild("Humanoid") if human ~= nil and use == no then use = yes plyr.Character.Humanoid.WalkSpeed = 0 plyr.Character.Humanoid.Sit = true plyr.Character.Torso.Anchored = true plyr.Character.Torso.CFrame = plyr.Character.Torso.CFrame - Vector3.new(0, 2, 0) wait(1) part = Instance.new("Part") part.Parent = workspace part.Size = Vector3.new(1, 1, 1) part.BrickColor = BrickColor.new("Bright violate") part.Transparency = 0.2 part.Anchored = true part.CFrame = plyr.Character.Torso.CFrame mesh = Instance.new("SpecialMesh") mesh.MeshType = "Sphere" mesh.Scale = Vector3.new(1, 1, 1) mesh.Parent = part for i = 1, 50 do mesh.Scale = mesh.Scale + Vector3.new(0.5, 0.5, 0.5) end part.Parent = nil plyr.Character.Torso.CFrame = CFrame.new(0, 3, 0) plyr.Character.Humanoid.WalkSpeed = 16 plyr.Character.Humanoid.Jump = true plyr.Character.Torso.Anchored = false use = no end end) plyr.Chatted:connect(function(msg) if msg == "removed" then sc:Remove() end end)
26.127273
80
0.705637
143278a660a9ca12f23e6c37b8b84644e9011bc1
817
ts
TypeScript
src/createElement.ts
ggassmann/react2
6245b2b375007eb70b08ee4e87ca2296195d63ff
[ "MIT" ]
null
null
null
src/createElement.ts
ggassmann/react2
6245b2b375007eb70b08ee4e87ca2296195d63ff
[ "MIT" ]
null
null
null
src/createElement.ts
ggassmann/react2
6245b2b375007eb70b08ee4e87ca2296195d63ff
[ "MIT" ]
null
null
null
import isUndefined from '@f/is-undefined' import isString from '@f/is-string' import isNumber from '@f/is-number' import isNull from '@f/is-null' import { IVNode } from './lib/IVNode'; export function createElement(type, attributes, ...children) { if (!type) throw new TypeError('element() needs a type.') attributes = attributes || {} let key = isString(attributes.key) || isNumber(attributes.key) ? attributes.key : null delete attributes.key if (typeof type === 'object') { type = Object.assign(type, { attributes, children }); return type; } if (typeof type === 'function') { //return createThunkElement(type, key, attributes, children, type) } return { type: 'native', tagName: type, attributes, children, key } };
24.757576
71
0.630355
39f38ccd94d1ab4b910f6b9757013bd91df9ebfa
5,747
rs
Rust
arch/x86_64/boot2snow/src/boot2snow.rs
fossabot/SnowFlake
50145c23984f9a9724566a597d6a1b979ded49a1
[ "BSD-3-Clause" ]
null
null
null
arch/x86_64/boot2snow/src/boot2snow.rs
fossabot/SnowFlake
50145c23984f9a9724566a597d6a1b979ded49a1
[ "BSD-3-Clause" ]
null
null
null
arch/x86_64/boot2snow/src/boot2snow.rs
fossabot/SnowFlake
50145c23984f9a9724566a597d6a1b979ded49a1
[ "BSD-3-Clause" ]
null
null
null
use core::mem::size_of; use color::*; use {EntryPoint, elf, kernel_proto}; use conf::Configuration; use uefi::status::*; use uefi::boot_services::protocols; use uefi::boot_services::{BootServices, AllocateType, MemoryDescriptor, MemoryType}; use {PATH_CONFIG, PATH_FALLBACK_KERNEL}; use {get_conout, get_boot_services, get_image_handle, get_runtime_services, get_graphics_output}; pub extern fn init() -> Result<(), ()> { let boot_services = get_boot_services(); let image_handle = get_image_handle(); let runtime_services = get_runtime_services(); let gop = get_graphics_output(); { // Obtain the "LoadedImage" representing the bootloader, from which we get the boot volume let image_proto: &protocols::LoadedImage = boot_services.handle_protocol(&image_handle).expect("image_handle - LoadedImage"); if image_proto.file_path.type_code() != (4,4) { panic!("Loader wans't loaded from a filesystem - type_code = {:?}", image_proto.file_path.type_code()); } let system_volume_fs: &protocols::SimpleFileSystem = boot_services.handle_protocol(&image_proto.device_handle).expect("image_proto - FileProtocol"); // - Get the root of this volume and load the bootloader configuration file from it let system_volume_root = system_volume_fs.open_volume().expect("system_volume_fs - File"); let config = match Configuration::from_file(boot_services, &system_volume_root, PATH_CONFIG.into()) { Ok(c) => c, Err(e) => panic!("Failed to load config file: {:?}", e), }; // - Load the kernel. let entrypoint = load_kernel_file(boot_services, &system_volume_root, &config.kernel).expect("Unable to load kernel"); // Save memory map let (map_size, map_key, ent_size, ent_ver, map) = { let mut map_size = 0; let mut map_key = 0; let mut ent_size = 0; let mut ent_ver = 0; match unsafe { (boot_services.get_memory_map)(&mut map_size, ::core::ptr::null_mut(), &mut map_key, &mut ent_size, &mut ent_ver) } { SUCCESS => {}, BUFFER_TOO_SMALL => {}, e => panic!("Sorry, get_memory_map() Failed :( - {:?}", e), } assert_eq!( ent_size, size_of::<MemoryDescriptor>() ); let mut map; loop { map = boot_services.allocate_pool_vec( MemoryType::LoaderData, map_size / ent_size ).unwrap(); match unsafe { (boot_services.get_memory_map)(&mut map_size, map.as_mut_ptr(), &mut map_key, &mut ent_size, &mut ent_ver) } { SUCCESS => break, BUFFER_TOO_SMALL => continue, e => panic!("get_memory_map 2 - {:?}", e), } } unsafe { map.set_len( map_size / ent_size ); } (map_size, map_key, ent_size, ent_ver, map) }; unsafe { (boot_services.exit_boot_services)(image_handle, map_key).expect("Sorry, exit_boot_services() failed"); (runtime_services.set_virtual_address_map)(map_size, ent_size, ent_ver, map.as_ptr()).expect("Sorry, set_virtual_address_map() failed :("); } let boot_info = kernel_proto::Info { runtime_services: runtime_services as *const _ as *const (), // TODO: Get from the configuration cmdline_ptr: 1 as *const u8, cmdline_len: 0, map_addr: map.as_ptr() as usize as u64, map_entnum: map.len() as u32, map_entsz: size_of::<MemoryDescriptor>() as u32, vid_addr: gop.mode.frame_buffer_base as *mut Color, width: unsafe { (*gop.mode.info).horizontal_resolution }, height: unsafe { (*gop.mode.info).vertical_resolution } }; // - Execute kernel (passing a magic value and general boot information) entrypoint(0x71FF0EF1, &boot_info); } Ok(()) } fn load_kernel_file(boot_services: &::uefi::boot_services::BootServices, sys_vol: &protocols::File, filename: &::uefi::CStr16) -> Result<EntryPoint, ::uefi::Status> { let mut kernel_file = match sys_vol.open_read(filename) { Ok(k) => k, Err(e) => panic!("Failed to open kernel '{}' - {:?}", filename, e), }; // Load kernel from this file (ELF). let elf_hdr = { let mut hdr = elf::ElfHeader::default(); // SAFE: Converts to POD for read kernel_file.read( unsafe { ::core::slice::from_raw_parts_mut( &mut hdr as *mut _ as *mut u8, size_of::<elf::ElfHeader>() ) } ).expect("ElfHeader read"); hdr }; elf_hdr.check_header(); for i in 0 .. elf_hdr.e_phnum { let mut ent = elf::PhEnt::default(); kernel_file.set_position(elf_hdr.e_phoff as u64 + (i as usize * size_of::<elf::PhEnt>()) as u64 ).expect("PhEnt seek"); // SAFE: Converts to POD for read kernel_file.read( unsafe { ::core::slice::from_raw_parts_mut( &mut ent as *mut _ as *mut u8, size_of::<elf::PhEnt>() ) } ).expect("PhEnt read"); if ent.p_type == 1 { println!("- {:#x}+{:#x} loads +{:#x}+{:#x}", ent.p_paddr, ent.p_memsz, ent.p_offset, ent.p_filesz ); let mut addr = ent.p_paddr as u64; // SAFE: Correct call to FFI unsafe { (boot_services.allocate_pages)( AllocateType::Address, MemoryType::LoaderData, ent.p_memsz as usize / 0x4096, &mut addr ).expect("Allocating pages for program segment") }; // SAFE: This memory has just been allocated by the above let data_slice = unsafe { ::core::slice::from_raw_parts_mut(ent.p_paddr as usize as *mut u8, ent.p_memsz as usize) }; kernel_file.set_position(ent.p_offset as u64).expect("seek segment"); kernel_file.read( &mut data_slice[.. ent.p_filesz as usize] ).expect("read segment"); for b in &mut data_slice[ent.p_filesz as usize .. ent.p_memsz as usize] { *b = 0; } } } // SAFE: Assuming that the executable is sane, and that it follows the correct calling convention Ok(unsafe { ::core::mem::transmute(elf_hdr.e_entry as usize) }) }
35.91875
164
0.665565
f479124b45155ea14cd7db5b5c87b379e75685bd
796
tsx
TypeScript
app/components/page.tsx
elthrasher/planetstack
061b726c398629a601ff5b5bf41d5d9e05c74171
[ "MIT" ]
1
2021-08-23T06:48:51.000Z
2021-08-23T06:48:51.000Z
app/components/page.tsx
elthrasher/planetstack
061b726c398629a601ff5b5bf41d5d9e05c74171
[ "MIT" ]
1
2021-08-11T20:20:51.000Z
2021-09-30T01:59:08.000Z
app/components/page.tsx
elthrasher/planetstack
061b726c398629a601ff5b5bf41d5d9e05c74171
[ "MIT" ]
null
null
null
import React, { useContext } from 'react'; import { backgrounds } from '../../types/data/backgrounds'; import { WSContext } from '../providers/WSProvider'; import { Chooser } from './chooser'; import { DraggableIcon } from './draggable-icon'; import { Header } from './header'; export const Page = (): JSX.Element => { const { gs } = useContext(WSContext); return ( <div style={{ backgroundImage: `url('${backgrounds[gs.bg].path}')`, backgroundRepeat: 'no-repeat', backgroundSize: 'cover', display: 'block', height: '100vh', width: '100vw', }} > <Header /> <Chooser /> {Object.entries(gs.icons).map(([key, icon]) => ( <DraggableIcon icon={icon} id={key} key={key} /> ))} </div> ); };
26.533333
61
0.561558
c9970779f0c0115b247033583aa87306da15cd5f
956
ts
TypeScript
projects/ng-carousel/src/lib/private/models/procedure/procedure-pipe/test/mock-state-merge-procedure/mock-state-merge-procedure.ts
IT-premium-team/ng-carousel-cdk
2d1afa2ad26f26f2adcb10ab6371680466dcd0d9
[ "MIT" ]
9
2019-10-18T08:43:23.000Z
2022-02-18T21:25:11.000Z
projects/ng-carousel/src/lib/private/models/procedure/procedure-pipe/test/mock-state-merge-procedure/mock-state-merge-procedure.ts
IT-premium-team/ng-carousel-cdk
2d1afa2ad26f26f2adcb10ab6371680466dcd0d9
[ "MIT" ]
108
2019-08-04T11:57:49.000Z
2022-02-10T13:24:10.000Z
projects/ng-carousel/src/lib/private/models/procedure/procedure-pipe/test/mock-state-merge-procedure/mock-state-merge-procedure.ts
IT-premium-team/ng-carousel-cdk
2d1afa2ad26f26f2adcb10ab6371680466dcd0d9
[ "MIT" ]
1
2021-07-16T20:47:58.000Z
2021-07-16T20:47:58.000Z
import { CarouselState } from '../../../../carousel-state'; import { ContinueWith } from '../../../handler/contiue-with.model'; import { ProcedureCarouselState } from '../../../procedure-carousel-state.interface'; import { ProcedureStateFacade } from '../../../procedure-state-facade.interface'; import { Procedure } from '../../../procedure.type'; /** * Merges provided state as if this procedure * did some actual work with state */ export function mockStateMergeProcedure( partialState: Partial<CarouselState>, partialProcedureState: Partial<ProcedureCarouselState>, ): Procedure { return ({state, procedureState}: Readonly<ProcedureStateFacade>) => { const mergedState: CarouselState = { ...state, ...partialState, }; const mergedProcedureState: Partial<ProcedureCarouselState> = { ...procedureState, ...partialProcedureState, }; return new ContinueWith(mergedState, mergedProcedureState); }; }
34.142857
85
0.695607
1b94e144aa00dabe4d52c45454452984516856ba
740
kt
Kotlin
app/src/main/kotlin/com/bl_lia/kirakiratter/domain/interactor/config/SetSimpleModeUseCase.kt
m-kmr/kktAPK
0140ff4af6320199484826c587b12b01fc2007a8
[ "MIT" ]
23
2017-04-24T10:35:28.000Z
2018-09-13T06:57:18.000Z
app/src/main/kotlin/com/bl_lia/kirakiratter/domain/interactor/config/SetSimpleModeUseCase.kt
m-kmr/kktAPK
0140ff4af6320199484826c587b12b01fc2007a8
[ "MIT" ]
83
2017-04-28T17:14:59.000Z
2020-04-28T12:37:49.000Z
app/src/main/kotlin/com/bl_lia/kirakiratter/domain/interactor/config/SetSimpleModeUseCase.kt
m-kmr/kktAPK
0140ff4af6320199484826c587b12b01fc2007a8
[ "MIT" ]
5
2017-04-28T10:30:32.000Z
2019-11-29T08:13:12.000Z
package com.bl_lia.kirakiratter.domain.interactor.config import com.bl_lia.kirakiratter.domain.executor.PostExecutionThread import com.bl_lia.kirakiratter.domain.executor.ThreadExecutor import com.bl_lia.kirakiratter.domain.interactor.SingleUseCase import com.bl_lia.kirakiratter.domain.repository.ConfigRepository import io.reactivex.Single class SetSimpleModeUseCase( private val configRepository: ConfigRepository, private val threadExecutor: ThreadExecutor, private val postExecutionThread: PostExecutionThread ) : SingleUseCase<Boolean>(threadExecutor, postExecutionThread) { override fun build(params: Array<out Any>): Single<Boolean> = configRepository.setSimpleMode(params[0] as Boolean) }
43.529412
66
0.810811
1a64adabe4506504fef1a21223ad7fb1e038bb92
931
py
Python
Car_rental/repositories/PriceRepo.py
evalisv/verklegt1-2018
bbf9d6ca66a1f01058c41c9160f982f3621abea7
[ "MIT" ]
null
null
null
Car_rental/repositories/PriceRepo.py
evalisv/verklegt1-2018
bbf9d6ca66a1f01058c41c9160f982f3621abea7
[ "MIT" ]
null
null
null
Car_rental/repositories/PriceRepo.py
evalisv/verklegt1-2018
bbf9d6ca66a1f01058c41c9160f982f3621abea7
[ "MIT" ]
null
null
null
import csv from models.Price import Price class PriceRepo: def __init__(self): self.__price = [] def get_price_list(self): self.__price = [] with open ("data/prices.csv", "r") as csv_file: csv_reader = csv.DictReader(csv_file) #Til þess að geta filterað út frá lyklum þarf að nota DictReader if self.__price == []: for line in csv_reader: self.__price.append(line) return self.__price def change_price(self, new_value): self.__new_value = new_value with open ("data/prices.csv", "w", encoding = "utf-8") as changed_csv: fieldnames = ["Category", "Price", "Insurance"] csv_writer = csv.DictWriter(changed_csv, fieldnames = fieldnames, lineterminator = "\n") csv_writer.writeheader() for line in new_value: csv_writer.writerow(line)
33.25
116
0.593985
bda1b25e61bf8f6505cf014b6a010171a8d3056d
299
rb
Ruby
db/migrate/20170724121529_create_purchases.rb
singals/bharat-on-rails
86d5456b9854dddcc1ee428452506f41cf2432fa
[ "Apache-2.0" ]
null
null
null
db/migrate/20170724121529_create_purchases.rb
singals/bharat-on-rails
86d5456b9854dddcc1ee428452506f41cf2432fa
[ "Apache-2.0" ]
null
null
null
db/migrate/20170724121529_create_purchases.rb
singals/bharat-on-rails
86d5456b9854dddcc1ee428452506f41cf2432fa
[ "Apache-2.0" ]
null
null
null
# frozen_string_literal: true class CreatePurchases < ActiveRecord::Migration[5.1] def change create_table :purchases do |t| t.string :seller_name t.string :city t.string :phone t.integer :invoice_number t.float :total_cost t.timestamps end end end
18.6875
52
0.668896
3876533ccba6a3f601b1bfff711742ceec655960
2,834
php
PHP
app/Http/Controllers/HomeController.php
rsm23/plexus
c291facc7dee0636e68616a17fb20f081f24dbf4
[ "MIT" ]
null
null
null
app/Http/Controllers/HomeController.php
rsm23/plexus
c291facc7dee0636e68616a17fb20f081f24dbf4
[ "MIT" ]
null
null
null
app/Http/Controllers/HomeController.php
rsm23/plexus
c291facc7dee0636e68616a17fb20f081f24dbf4
[ "MIT" ]
null
null
null
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use File; use Auth; use Session; use View; use App\Score; use App\Event; use App\User; use Response; use Redirect; use HTML; class HomeController extends Controller { /** * Create a new controller instance. * * @return void */ public function __construct() { $this->middleware( 'verify', [ 'except' => [ 'logout', 'leaderboard', 'showLeaderboard', 'forum' ] ] ); } /** * Show the form for login of the society. * * @return \Illuminate\Http\Response */ public function society() { return File::get(public_path()."/backoffice/pages/login.html"); // return View('auth.Society.login'); } /** * Show the form for login of the User. * * @return \Illuminate\Http\Response */ public function user() { return File::get(public_path()."/gameplay/login.html"); } /** * Show the form for login of the User. * * @return \Illuminate\Http\Response */ public function userRegister() { return File::get(public_path()."/gameplay/register.html"); } /** * LeaderBoard. * * @param int $id * @return \Illuminate\Http\Response */ public function showLeaderboard($id) { $event = Event::where('eventCode', $id)->first(); if (!count($event)) { return Redirect::to('/'); } return File::get(public_path()."/gameplay/leaderboard.html"); } /** * LeaderBoard. * * @param int $id * @return \Illuminate\Http\Response */ public function leaderboard($id) { $event = Event::where('eventCode', $id)->first(); /*if (!count($event)) { return Redirect::to('/'); }*/ $eventId = $event->id; $score = Score::where('eventId', $eventId) ->orderBy('score', 'desc')->orderBy('logged_on', 'asc')->limit(30)->get(); foreach ($score as $key => $value) { $user = User::find($value->userId); $value->user = $user; $value->eventName = $event->eventName; } return Response::json( [ "status" => true, "data" => $score ] ); } public function logout(Request $request) { Session::flush(); Auth::guard('society')->logout(); Auth::guard('user')->logout(); return Redirect::to('/login'); } public function forum($eventCode) { $event = Event::where('eventCode', $eventCode)->first(); // return $event->forum; return Redirect::to($event->forum); } }
22.140625
86
0.511997
a337028ac6aa1b98363aa0564308c26c7f3b3e1a
639
ts
TypeScript
packages/icons/test/icons.spec.ts
mehrdad-shokri/ux
80258a9aec3b99584a0fc223baff59ae7913c53c
[ "MIT" ]
411
2016-11-04T16:35:11.000Z
2022-03-03T14:24:55.000Z
packages/icons/test/icons.spec.ts
mehrdad-shokri/ux
80258a9aec3b99584a0fc223baff59ae7913c53c
[ "MIT" ]
291
2016-11-04T19:27:22.000Z
2022-02-27T05:21:56.000Z
packages/icons/test/icons.spec.ts
mehrdad-shokri/ux
80258a9aec3b99584a0fc223baff59ae7913c53c
[ "MIT" ]
89
2016-11-04T16:52:25.000Z
2021-11-21T09:59:53.000Z
import './setup'; import { UxIcon } from '../src/index'; import { Container } from 'aurelia-framework'; describe('@aurelia-ux/icons', () => { describe('icons.spec.ts', () => { it('binds/unbinds correctly', () => { const container = new Container(); const host = document.createElement('div'); container.registerInstance(Element, host); const uxIcon = container.get(UxIcon); spyOn(uxIcon, 'themeChanged'); spyOn(uxIcon, 'sizeChanged'); uxIcon.bind(); expect(uxIcon.themeChanged).toHaveBeenCalledTimes(1); expect(uxIcon.sizeChanged).toHaveBeenCalledTimes(1); }); }); });
27.782609
59
0.632238