code
stringlengths
3
1.05M
repo_name
stringlengths
4
116
path
stringlengths
4
991
language
stringclasses
9 values
license
stringclasses
15 values
size
int32
3
1.05M
module PgToCsv VERSION = "0.0.1" end
Solomon/pg_to_csv
lib/pg_to_csv/version.rb
Ruby
mit
39
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using Web.UI.Interfaces; namespace Web.UI.Controllers { public class CategoryController : BaseController { ICategoryRepository _categoryRepository; public CategoryController(ICategoryRepository categoryRepository) { this._categoryRepository = categoryRepository; } // GET: Product public ActionResult Index() { return View(); } public ActionResult GetProductCategory() { return Json(_categoryRepository.GetProductCategory(), JsonRequestBehavior.AllowGet); } } }
lizhen325/DakHanMaRi
Web.UI/Controllers/CategoryController.cs
C#
mit
710
define(['underscore', 'klik/core/Class'], function (_, Class) { 'use strict'; return Class('GameObject', { methods: { preload: function() { }, create: function() { }, update: function() { } } }); });
kctang/klik
src/core/GameObject.js
JavaScript
mit
302
<?php $week = array('日','月','火','水','木','金','土'); ?> @extends('layouts.app') @section('title', 'みんなの目標') @section('content') <div class="container"> <div class="row text-center"> <h2>「{{ \Request::input('searchword') }}」の検索結果</h2> <h5>公開設定の目標のみ表示されます</h5> </div> @forelse ($aims as $aim) <div class="panel panel-body spacer10"> <div class="col-xs-4 col-sm-2"> <img class="pix" src="/img/level/{{ $aim->level }}.png" alt="レベル{{ $aim->level }}"> </div> <div class="col-xs-8 col-sm-10"> <a href="/{{ $aim->name }}" class="name"><small>{{ $aim->name }}</small></a> <time datetime="{{date('Y-m-d H:i:s', strtotime($aim->created_at))}}">{!! $ft->convert_to_fuzzy_time($aim->created_at) !!}</time> <p><b>{{$aim->aim}}</b></p> <div class="pull-left"> <span onClick="Reply({{$aim->id}})" class="glyphicon glyphicon glyphicon-comment"></span>&nbsp;{{ count($comments[$aim->id]) }} <span onClick="AimLike({{$aim->id}})" class="glyphicon glyphicon-thumbs-up"></span>&nbsp;<span id="like_count{{$aim->id}}">{{$aim->like_count}}</span> </div> </div> <div id="reply{{$aim->id}}" style="display: none;clear:both;"> @foreach ($comments[$aim->id] as $comment) <div class="row spacer30 panel panel-body"> <div class="col-xs-offset-1 col-xs-3 col-sm-2"> <img class="pix" src="/img/level/{{ $comment->level }}.png" alt="レベル{{ $comment->level }}"> </div> <div class="col-xs-8 col-sm-9"> <a href="/{{ $comment->name }}" class="name"><small>{{ $comment->name }}</small></a> <p><b>{{$comment->comment}}</b></p> </div> </div> @endforeach @if (Auth::user()) <form class="form-horizontal col-xs-offset-1 col-xs-11" role="form" method="POST" action="{{ secure_url('/comment') }}"> {{ csrf_field() }} <div class="form-group{{ $errors->has('aim') ? ' has-error' : '' }} spacer10"> <div class="col-xs-9"> <input type="text" class="form-control" name="comment" placeholder="応援コメント"> @if ($errors->has('comment')) <span class="help-block"> <b>{{ $errors->first('comment') }}</b> </span> @endif </div> <div class="col-xs-3 text-center"> <input type="hidden" name="aim_id" value="{{$aim->id}}"> <button type="submit" class="btn btn-primary" value="入力">入力</button> </div> </div> </form> @endif </div> </div> @empty <div class="panel panel-body"> <p class="text-center">一致する目標はありません。</p> </div> @endforelse <div class="row spacer20"> <div class="text-center"> {{ $aims->appends(Request::only('searchword'))->links() }} </div> </div> </div> @endsection @section('js') <script> function AimLike(id){ $.ajax({ type:'GET', url:'/aimlike', data:'id='+id, success: function(data){ if(data !== 'error'){ $('#'+'like_count'+id).html(data); $('#'+'like_count'+id).css('color','#a63400'); } }, }); } function Reply(id){ $("#reply"+id).slideToggle(300); } </script> @endsection
masasikatano/openaim
resources/views/search.blade.php
PHP
mit
3,656
/** * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for * license information. * * Code generated by Microsoft (R) AutoRest Code Generator. * Changes may cause incorrect behavior and will be lost if the code is * regenerated. */ package fixtures.azurespecials.models; import com.microsoft.rest.AutoRestException; import retrofit.Response; /** * Exception thrown for an invalid response with Error information. */ public class ErrorException extends AutoRestException { /** * Information about the associated HTTP response. */ private Response response; /** * The actual response body. */ private Error body; /** * Initializes a new instance of the ErrorException class. */ public ErrorException() { } /** * Initializes a new instance of the ErrorException class. * * @param message The exception message. */ public ErrorException(final String message) { super(message); } /** * Initializes a new instance of the ErrorException class. * * @param message the exception message * @param cause exception that caused this exception to occur */ public ErrorException(final String message, final Throwable cause) { super(message, cause); } /** * Initializes a new instance of the ErrorException class. * * @param cause exception that caused this exception to occur */ public ErrorException(final Throwable cause) { super(cause); } /** * Gets information about the associated HTTP response. * * @return the HTTP response */ public Response getResponse() { return response; } /** * Gets the HTTP response body. * * @return the response body */ public Error getBody() { return body; } /** * Sets the HTTP response. * * @param response the HTTP response */ public void setResponse(Response response) { this.response = response; } /** * Sets the HTTP response body. * * @param body the response body */ public void setBody(Error body) { this.body = body; } }
vulcansteel/autorest
AutoRest/Generators/Java/Azure.Java.Tests/src/main/java/fixtures/azurespecials/models/ErrorException.java
Java
mit
2,283
package com.logistics.pvis.color; public class Color { public int r, g, b, a; public Color(int r, int g, int b, int a) { this.r = r; this.g = g; this.b = b; this.a = a; } public Color(int r, int g, int b) { this.r = r; this.g = g; this.b = b; this.a = 255; } public Color(int grayScale) { this.r = grayScale; this.g = grayScale; this.b = grayScale; this.a = 255; } public static final Color WHITE = new Color(255); public static final Color BLACK = new Color(0); /* (non-Javadoc) * @see java.lang.Object#hashCode() */ @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + a; result = prime * result + b; result = prime * result + g; result = prime * result + r; return result; } /* (non-Javadoc) * @see java.lang.Object#equals(java.lang.Object) */ @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Color other = (Color) obj; if (a != other.a) return false; if (b != other.b) return false; if (g != other.g) return false; if (r != other.r) return false; return true; } }
sunyifan112358/pvis
src/main/com/logistics/pvis/color/Color.java
Java
mit
1,233
class RegistrationsController < ApplicationController helper_method :registration, :registration_params def new @registration = Registration.new(year: current_year) end def create @registration = Registration.new(registration_params) render :new end private attr_reader :registration def registration_params params.fetch(:registration, {}).permit(:year, :name, :email, :phone, :receive_updates, { t_shirt_orders_attributes: %i[ name size ] }) end def current_year Date.current.year end end
johncarney/veterans-walk
app/controllers/registrations_controller.rb
Ruby
mit
538
Given "I am not signed in" do visit destroy_user_session_path end Given "I am signed in" do Given 'I am not signed in' And 'I have a user with email "user@getshrink.com" and password "shrink"' When 'I go to the homepage' And 'I fill in "Email" with "user@getshrink.com"' And 'I fill in "Password" with "shrink"' And 'I press "Sign in"' Then 'I should see "Signed in successfully."' And 'I should be on the homepage' end
jcxplorer/shrink
features/step_definitions/authentication_steps.rb
Ruby
mit
439
package com.timekeeping.app.activities; import java.util.ArrayList; import java.util.List; import android.app.Activity; import android.app.AlertDialog.Builder; import android.content.ActivityNotFoundException; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.databinding.DataBindingUtil; import android.net.Uri; import android.os.Bundle; import android.support.design.widget.Snackbar; import android.support.v4.app.ActivityCompat; import android.support.v4.app.DialogFragment; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentTransaction; import android.support.v4.view.GravityCompat; import android.support.v4.view.MenuItemCompat; import android.support.v4.view.ViewCompat; import android.support.v7.app.ActionBar; import android.support.v7.app.ActionBarDrawerToggle; import android.support.v7.view.ActionMode; import android.support.v7.view.ActionMode.Callback; import android.support.v7.widget.GridLayoutManager; import android.support.v7.widget.RecyclerView; import android.text.Spannable; import android.text.SpannableString; import android.text.TextUtils; import android.text.format.DateFormat; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import com.chopping.activities.BaseActivity; import com.chopping.application.BasicPrefs; import com.chopping.bus.CloseDrawerEvent; import com.codetroopers.betterpickers.radialtimepicker.RadialTimePickerDialogFragment; import com.codetroopers.betterpickers.radialtimepicker.RadialTimePickerDialogFragment.OnDialogDismissListener; import com.codetroopers.betterpickers.radialtimepicker.RadialTimePickerDialogFragment.OnTimeSetListener; import com.google.android.gms.ads.AdListener; import com.google.android.gms.ads.AdRequest; import com.google.android.gms.ads.InterstitialAd; import com.google.android.gms.common.ConnectionResult; import com.google.android.gms.common.GooglePlayServicesUtil; import com.timekeeping.R; import com.timekeeping.app.App; import com.timekeeping.app.adapters.TimeKeepingListAdapter; import com.timekeeping.app.fragments.AboutDialogFragment; import com.timekeeping.app.fragments.AboutDialogFragment.EulaConfirmationDialog; import com.timekeeping.app.fragments.CommentDialogFragment; import com.timekeeping.app.fragments.VolumeDialogFragment; import com.timekeeping.bus.DeleteTimeEvent; import com.timekeeping.bus.EULAConfirmedEvent; import com.timekeeping.bus.EULARejectEvent; import com.timekeeping.bus.EditTaskEvent; import com.timekeeping.bus.EditTimeEvent; import com.timekeeping.bus.SaveCommentEvent; import com.timekeeping.bus.SavedWeekDaysEvent; import com.timekeeping.bus.SelectItemEvent; import com.timekeeping.bus.StartActionModeEvent; import com.timekeeping.bus.SwitchOnOffTimeEvent; import com.timekeeping.data.Time; import com.timekeeping.databinding.ActivityMainBinding; import com.timekeeping.utils.Prefs; import com.timekeeping.utils.TypefaceSpan; import com.timekeeping.utils.Utils; import com.timekeeping.widget.FontTextView.Fonts; import io.realm.Realm; import io.realm.RealmAsyncTask; import io.realm.RealmChangeListener; import io.realm.RealmQuery; import io.realm.RealmResults; /** * The {@link MainActivity}. * * @author Xinyue Zhao */ public class MainActivity extends BaseActivity implements OnClickListener, OnTimeSetListener, OnDialogDismissListener { /** * Main layout for this component. */ private static final int LAYOUT = R.layout.activity_main; /** * Menu for the Action-Mode. */ private static final int ACTION_MODE_MENU = R.menu.action_mode; /** * Main menu. */ private static final int MENU_MAIN = R.menu.menu_main; /** * Use navigation-drawer for this fork. */ private ActionBarDrawerToggle mDrawerToggle; /** * The {@link android.support.v7.view.ActionMode}. */ private ActionMode mActionMode; /** * Edit a item or not. */ private boolean mEdit; /** * {@link Time} to edit. */ private Time mEditedTime; /** * The interstitial ad. */ private InterstitialAd mInterstitialAd; /** * Data-binding. */ private ActivityMainBinding mBinding; private Realm mRealm; private RealmAsyncTask mTransaction; //------------------------------------------------ //Subscribes, event-handlers //------------------------------------------------ /** * Handler for {@link EULARejectEvent}. * * @param e * Event {@link EULARejectEvent}. */ public void onEvent( EULARejectEvent e ) { ActivityCompat.finishAfterTransition( this ); } /** * Handler for {@link EULAConfirmedEvent} * * @param e * Event {@link EULAConfirmedEvent}. */ public void onEvent( EULAConfirmedEvent e ) { } /** * Handler for {@link DeleteTimeEvent}. * * @param e * Event {@link DeleteTimeEvent}. */ public void onEvent( DeleteTimeEvent e ) { Time time = e.getTime(); final int position = e.getPosition(); if( time != null ) { mRealm.beginTransaction(); mRealm.addChangeListener( new RealmChangeListener() { @Override public void onChange() { mBinding.getAdapter() .notifyItemRemoved( position ); mRealm.removeChangeListener( this ); } } ); time.removeFromRealm(); mRealm.commitTransaction(); } } /** * Handler for {@link EditTimeEvent}. * * @param e * Event {@link EditTimeEvent}. */ public void onEvent( EditTimeEvent e ) { editTime( e.getPosition(), e.getTime() ); } /** * Handler for {@link SwitchOnOffTimeEvent}. * * @param e * Event {@link SwitchOnOffTimeEvent}. */ public void onEvent( SwitchOnOffTimeEvent e ) { setTimeOnOff( e.getPosition(), e.getTime() ); } /** * Handler for {@link }. * * @param e * Event {@link}. */ public void onEvent( CloseDrawerEvent e ) { mBinding.drawerLayout.closeDrawers(); } /** * Handler for {@link SelectItemEvent}. * * @param e * Event {@link SelectItemEvent}. */ public void onEvent( SelectItemEvent e ) { toggleSelection( e.getPosition() ); } /** * Handler for {@link StartActionModeEvent}. * * @param e * Event {@link StartActionModeEvent}. */ public void onEvent( StartActionModeEvent e ) { //See more about action-mode. //http://databasefaq.com/index.php/answer/19065/android-android-fragments-recyclerview-android-actionmode-problems-with-implementing-contextual-action-mode-in-recyclerview-fragment mActionMode = startSupportActionMode( new Callback() { @Override public boolean onCreateActionMode( ActionMode mode, Menu menu ) { mode.getMenuInflater() .inflate( ACTION_MODE_MENU, menu ); mBinding.toolbar.setVisibility( View.GONE ); mBinding.errorContent.setStatusBarBackgroundColor( R.color.primary_dark_color ); mBinding.getAdapter() .setActionMode( true ); mBinding.getAdapter() .notifyDataSetChanged(); mBinding.addNewTimeBtn.hide(); return true; } @Override public boolean onPrepareActionMode( ActionMode mode, Menu menu ) { return false; } @Override public boolean onActionItemClicked( ActionMode mode, MenuItem item ) { final List<Integer> selectedItems = mBinding.getAdapter() .getSelectedItems(); final List<Time> selectedTimes = new ArrayList<>(); for( Integer pos : selectedItems ) { selectedTimes.add( mBinding.getAdapter() .getData() .get( pos ) ); } mRealm.beginTransaction(); for( Time delTime : selectedTimes ) { delTime.removeFromRealm(); } mRealm.addChangeListener( new RealmChangeListener() { @Override public void onChange() { for( Integer pos : selectedItems ) { mBinding.getAdapter() .notifyItemRemoved( pos.intValue() ); if( mActionMode != null ) { mActionMode.finish(); } } mRealm.removeChangeListener( this ); } } ); mRealm.commitTransaction(); return true; } @Override public void onDestroyActionMode( ActionMode mode ) { mActionMode = null; mBinding.toolbar.setVisibility( View.VISIBLE ); mBinding.getAdapter() .clearSelection(); mBinding.getAdapter() .setActionMode( false ); mBinding.getAdapter() .notifyDataSetChanged(); mBinding.addNewTimeBtn.show(); } } ); } /** * Handler for {@link com.timekeeping.bus.EditTaskEvent}. * * @param e * Event {@link com.timekeeping.bus.EditTaskEvent}. */ public void onEvent( EditTaskEvent e ) { showDialogFragment( CommentDialogFragment.newInstance( App.Instance, e.getPosition(), e.getTime() ), null ); } /** * Handler for {@link SaveCommentEvent}. * * @param e * Event {@link SaveCommentEvent}. */ public void onEvent( SaveCommentEvent e ) { mEdit = true; mRealm.beginTransaction(); mEditedTime = e.getTime(); mEditedTime.setTask( e.getComment() ); updateOthers( e.getPosition() ); } /** * Handler for {@link com.timekeeping.bus.SavedWeekDaysEvent}. * * @param e * Event {@link com.timekeeping.bus.SavedWeekDaysEvent}. */ public void onEvent( SavedWeekDaysEvent e ) { mEdit = true; mRealm.beginTransaction(); mEditedTime = e.getTime(); mEditedTime.setWeekDays( e.getWeekDays() ); updateOthers( e.getPosition() ); } //------------------------------------------------ @Override public boolean onCreateOptionsMenu( Menu menu ) { getMenuInflater().inflate( MENU_MAIN, menu ); MenuItem menuShare = menu.findItem( R.id.action_share_app ); //Getting the actionprovider associated with the menu item whose id is share. android.support.v7.widget.ShareActionProvider provider = (android.support.v7.widget.ShareActionProvider) MenuItemCompat.getActionProvider( menuShare ); //Setting a share intent. String subject = getString( R.string.lbl_share_app_title, getString( R.string.application_name ) ); String text = getString( R.string.lbl_share_app_content, getString( R.string.tray_info ) ); provider.setShareIntent( Utils.getDefaultShareIntent( provider, subject, text ) ); MenuItem volMi = menu.findItem( R.id.action_volume ); int volume = Prefs.getInstance( getApplication() ) .getVolume(); String[] labels = getResources().getStringArray( R.array.volumes ); String label; int icon; switch( volume ) { case 0: label = labels[ 0 ]; icon = R.drawable.ic_volume_vibration; break; case 2: label = labels[ 2 ]; icon = R.drawable.ic_volume_sharp; break; default: label = labels[ 1 ]; icon = R.drawable.ic_volume_medium; break; } volMi.setIcon( icon ); volMi.setTitle( label ); return true; } @Override public boolean onOptionsItemSelected( MenuItem item ) { if( mDrawerToggle != null && mDrawerToggle.onOptionsItemSelected( item ) ) { return true; } int id = item.getItemId(); switch( id ) { case R.id.action_about: showDialogFragment( AboutDialogFragment.newInstance( this ), null ); break; case R.id.action_volume: showDialogFragment( VolumeDialogFragment.newInstance( this ), null ); break; } return super.onOptionsItemSelected( item ); } @Override public void onClick( View v ) { switch( v.getId() ) { case R.id.add_new_time_btn: addNewTime(); break; } } /** * Added a new entry of {@link com.timekeeping.data.Time} to database. */ private void addNewTime() { mBinding.addNewTimeBtn.hide(); RadialTimePickerDialogFragment timePickerDialog = RadialTimePickerDialogFragment.newInstance( this, 0, 0, DateFormat.is24HourFormat( this ) ); timePickerDialog.setOnDismissListener( this ); timePickerDialog.show( getSupportFragmentManager(), null ); } /** * Edit a entry of {@link com.timekeeping.data.Time} to database. */ private void editTime( int position ) { mBinding.addNewTimeBtn.show(); RadialTimePickerDialogFragment timePickerDialog = RadialTimePickerDialogFragment.newInstance( this, mEditedTime.getHour(), mEditedTime.getMinute(), DateFormat.is24HourFormat( this ) ); timePickerDialog.setOnDismissListener( this ); timePickerDialog.show( getSupportFragmentManager(), position + "" ); } /** * Start to edit a {@link com.timekeeping.data.Time} * * @param position * The position of {@link Time} to edit. * @param timeToEdit * The object to edit. */ private void editTime( int position, Time timeToEdit ) { mEdit = true; mEditedTime = timeToEdit; if( mEditedTime != null ) { editTime( position ); } } /** * Set on/off status of the time. It is toggled. * * @param position * The position of {@link Time} to update. * @param timeToSet * The object to set. */ private void setTimeOnOff( int position, Time timeToSet ) { mEdit = true; mEditedTime = timeToSet; mRealm.beginTransaction(); mEditedTime.setOnOff( !mEditedTime.isOnOff() ); updateOthers( position ); } private void refreshGrid() { final RealmResults<Time> result = mRealm.where( Time.class ) .findAllSortedAsync( "editTime", RealmResults.SORT_ORDER_DESCENDING ); result.addChangeListener( new RealmChangeListener() { @Override public void onChange() { mBinding.getAdapter() .setData( result ); mBinding.getAdapter() .notifyDataSetChanged(); mRealm.removeChangeListener( this ); } } ); } /** * Insert a {@link com.timekeeping.data.Time} to database. * * @param hourOfDay * Hour * @param minute * Minute. */ private void insertNewTime( int hourOfDay, int minute ) { final Time newTime = new Time( System.currentTimeMillis(), hourOfDay, minute, System.currentTimeMillis(), true ); final RealmResults<Time> results = mRealm.where( Time.class ) .equalTo( "hour", newTime.getHour() ) .equalTo( "minute", newTime.getMinute() ) .findAllAsync(); results.addChangeListener( new RealmChangeListener() { @Override public void onChange() { if( results.size() == 0 ) { mRealm.addChangeListener( new RealmChangeListener() { @Override public void onChange() { mBinding.getAdapter() .notifyItemInserted( 0 ); showStatusMessage( newTime ); mBinding.scheduleGv.getLayoutManager() .scrollToPosition( 0 ); mRealm.removeChangeListener( this ); } } ); mRealm.beginTransaction(); mRealm.copyToRealm( newTime ); mRealm.commitTransaction(); } else { showStatusMessage( getString( R.string.msg_duplicated_setting ) ); } results.removeChangeListener( this ); } } ); } /** * Edited and update a {@link com.timekeeping.data.Time} to database. */ private void updateTime( final int position, final int hourOfDay, final int minute ) { final RealmQuery<Time> query = mRealm.where( Time.class ) .equalTo( "hour", hourOfDay ) .equalTo( "minute", minute ); final RealmResults<Time> results = query.findAllAsync(); results.addChangeListener( new RealmChangeListener() { @Override public void onChange() { if( query.count() == 0 ) { mRealm.beginTransaction(); mRealm.addChangeListener( new RealmChangeListener() { @Override public void onChange() { mBinding.getAdapter() .notifyItemChanged( position ); mRealm.removeChangeListener( this ); } } ); mEditedTime.setHour( hourOfDay ); mEditedTime.setMinute( minute ); mRealm.copyToRealmOrUpdate( mEditedTime ); mRealm.commitTransaction(); mEdit = false; results.removeChangeListener( this ); } else { showStatusMessage( getString( R.string.msg_duplicated_setting ) ); } } } ); } /** * Edited and update a {@link com.timekeeping.data.Time}'s comment/task to database. * * @param position * The position of {@link Time} to update. */ private void updateOthers( final int position ) { mRealm.addChangeListener( new RealmChangeListener() { @Override public void onChange() { mBinding.getAdapter() .notifyItemChanged( position ); mRealm.removeChangeListener( this ); } } ); mRealm.copyToRealmOrUpdate( mEditedTime ); mRealm.commitTransaction(); mEdit = false; } /** * Show a message after changing item on database. * * @param time * The item that has been changed. */ private void showStatusMessage( Time time ) { String fmt = getString( time.isOnOff() ? R.string.on_status : R.string.off_status ); String message = String.format( fmt, Utils.formatTime( time ) ); Snackbar.make( findViewById( R.id.error_content ), message, Snackbar.LENGTH_LONG ) .show(); } /** * Show a message. * * @param msg * Some text to show */ private void showStatusMessage( String msg ) { Snackbar.make( findViewById( R.id.error_content ), msg, Snackbar.LENGTH_LONG ) .show(); } @Override public void onTimeSet( RadialTimePickerDialogFragment dialog, int hourOfDay, int minute ) { if( mEdit && dialog.getTag() != null ) { int pos = Integer.parseInt( dialog.getTag() .toString() ); updateTime( pos, hourOfDay, minute ); } else { insertNewTime( hourOfDay, minute ); } } @Override protected void onAppConfigLoaded() { super.onAppConfigLoaded(); addDrawerHeader(); refreshGrid(); } @Override protected void onAppConfigIgnored() { super.onAppConfigIgnored(); addDrawerHeader(); refreshGrid(); } private void addDrawerHeader() { if( mBinding.navView.getHeaderCount() == 0 ) { mBinding.navView.addHeaderView( getLayoutInflater().inflate( R.layout.nav_header, mBinding.navView, false ) ); } } @Override protected BasicPrefs getPrefs() { return Prefs.getInstance( getApplication() ); } @Override protected void onPostCreate( Bundle savedInstanceState ) { super.onPostCreate( savedInstanceState ); setErrorHandlerAvailable( false ); } /** * Initialize the navigation drawer. */ private void initDrawer() { ActionBar actionBar = getSupportActionBar(); if( actionBar != null ) { actionBar.setHomeButtonEnabled( true ); actionBar.setDisplayHomeAsUpEnabled( true ); mBinding.drawerLayout.setDrawerListener( mDrawerToggle = new ActionBarDrawerToggle( this, mBinding.drawerLayout, R.string.application_name, R.string.application_name ) ); } } /** * To confirm whether the validation of the Play-service of Google Inc. */ private void checkPlayService() { final int isFound = GooglePlayServicesUtil.isGooglePlayServicesAvailable( this ); if( isFound == ConnectionResult.SUCCESS ) {//Ignore update. //The "End User License Agreement" must be confirmed before you use this application. if( !Prefs.getInstance( getApplication() ) .isEULAOnceConfirmed() ) { showDialogFragment( new EulaConfirmationDialog(), null ); } } else { new Builder( this ).setTitle( R.string.application_name ) .setMessage( R.string.lbl_play_service ) .setCancelable( false ) .setPositiveButton( R.string.btn_ok, new DialogInterface.OnClickListener() { public void onClick( DialogInterface dialog, int whichButton ) { dialog.dismiss(); Intent intent = new Intent( Intent.ACTION_VIEW ); intent.setData( Uri.parse( getString( R.string.play_service_url ) ) ); try { startActivity( intent ); } catch( ActivityNotFoundException e0 ) { intent.setData( Uri.parse( getString( R.string.play_service_web ) ) ); try { startActivity( intent ); } catch( Exception e1 ) { //Ignore now. } } finally { finish(); } } } ) .create() .show(); } } /** * Show {@link android.support.v4.app.DialogFragment}. * * @param _dlgFrg * An instance of {@link android.support.v4.app.DialogFragment}. * @param _tagName * Tag name for dialog, default is "dlg". To grantee that only one instance of {@link android.support.v4.app.DialogFragment} can been seen. */ protected void showDialogFragment( DialogFragment _dlgFrg, String _tagName ) { try { if( _dlgFrg != null ) { DialogFragment dialogFragment = _dlgFrg; FragmentTransaction ft = getSupportFragmentManager().beginTransaction(); // Ensure that there's only one dialog to the user. Fragment prev = getSupportFragmentManager().findFragmentByTag( "dlg" ); if( prev != null ) { ft.remove( prev ); } try { if( TextUtils.isEmpty( _tagName ) ) { dialogFragment.show( ft, "dlg" ); } else { dialogFragment.show( ft, _tagName ); } } catch( Exception _e ) { } } } catch( Exception _e ) { } } @Override public void onDialogDismiss( DialogInterface dialoginterface ) { mBinding.addNewTimeBtn.show(); } /** * Invoke displayInterstitial() when you are ready to display an interstitial. */ public void displayInterstitial() { if( mInterstitialAd.isLoaded() ) { mInterstitialAd.show(); } } /** * Select items on view when opened action-mode. * * @param position * The select position. */ private void toggleSelection( int position ) { mBinding.getAdapter() .toggleSelection( position ); int count = mBinding.getAdapter() .getSelectedItemCount(); if( count == 0 ) { mActionMode.finish(); } else { mActionMode.setTitle( String.valueOf( count ) ); mActionMode.invalidate(); } } private void initGrid() { mBinding.scheduleGv.setLayoutManager( new GridLayoutManager( this, getResources().getInteger( R.integer.card_count ) ) ); mBinding.scheduleGv.addOnScrollListener( new RecyclerView.OnScrollListener() { @Override public void onScrolled( RecyclerView recyclerView, int dx, int dy ) { float y = ViewCompat.getY( recyclerView ); if( y < dy ) { if( mBinding.addNewTimeBtn.isShown() ) { mBinding.addNewTimeBtn.hide(); } } else { if( !mBinding.addNewTimeBtn.isShown() ) { if( mBinding.getAdapter() != null && mBinding.getAdapter() .isActionMode() ) { return; } mBinding.addNewTimeBtn.show(); } } } } ); mBinding.setAdapter( new TimeKeepingListAdapter() ); } private void initBar() { SpannableString s = new SpannableString( getString( R.string.application_name ) ); s.setSpan( new TypefaceSpan( this, Fonts.FONT_LIGHT ), 0, s.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE ); setSupportActionBar( mBinding.toolbar ); mBinding.toolbar.setTitle( s ); } /** * Show single instance of {@link MainActivity} * * @param cxt * {@link Context}. */ public static void showInstance( Activity cxt ) { Intent intent = new Intent( cxt, MainActivity.class ); intent.setFlags( Intent.FLAG_ACTIVITY_SINGLE_TOP|Intent.FLAG_ACTIVITY_CLEAR_TOP ); ActivityCompat.startActivity( cxt, intent, null ); } @Override public void onBackPressed() { if( mBinding.drawerLayout.isDrawerOpen( GravityCompat.START ) || mBinding.drawerLayout.isDrawerOpen( GravityCompat.END ) ) { mBinding.drawerLayout.closeDrawers(); } else { super.onBackPressed(); } } private void initAds() { Prefs prefs = Prefs.getInstance( getApplication() ); int curTime = prefs.getShownDetailsTimes(); int adsTimes = 10; if( curTime % adsTimes == 0 ) { // Create an ad. mInterstitialAd = new InterstitialAd( this ); mInterstitialAd.setAdUnitId( getString( R.string.ad_unit_id ) ); // Create ad request. AdRequest adRequest = new AdRequest.Builder().build(); // Begin loading your interstitial. mInterstitialAd.setAdListener( new AdListener() { @Override public void onAdLoaded() { super.onAdLoaded(); displayInterstitial(); } } ); mInterstitialAd.loadAd( adRequest ); } curTime++; prefs.setShownDetailsTimes( curTime ); } private void initComponents() { mBinding = DataBindingUtil.setContentView( this, LAYOUT ); setUpErrorHandling( (ViewGroup) findViewById( R.id.error_content ) ); //FAB mBinding.addNewTimeBtn.setOnClickListener( this ); } @Override protected void onCreate( Bundle savedInstanceState ) { mRealm = Realm.getInstance( App.Instance ); super.onCreate( savedInstanceState ); initComponents(); initBar(); initDrawer(); initGrid(); initAds(); } @Override protected void onDestroy() { if( mTransaction != null && !mTransaction.isCancelled() ) { mTransaction.cancel(); } if( mRealm != null ) { mRealm.removeAllChangeListeners(); mRealm.close(); } super.onDestroy(); } @Override public void onResume() { super.onResume(); if( mDrawerToggle != null ) { mDrawerToggle.syncState(); } checkPlayService(); } }
XinyueZ/timekeeping
app/src/main/java/com/timekeeping/app/activities/MainActivity.java
Java
mit
25,657
//= require_tree . $(document).ready(function() { var labelXML = ""; $.get("/javascripts/StudentNametag.label", function(data) { labelXML = data; }); var printers = dymo.label.framework.getPrinters(); var printerName = ""; for (var i = 0; i < printers.length; ++i) { var printer = printers[i]; if (printer.printerType == "LabelWriterPrinter") { printerName = printer.name; break; } } $('#print').click(function() { if (labelXML === "") { return false; } var label = dymo.label.framework.openLabelXml(labelXML); label.setObjectText("FirstName", "Chris"); label.setObjectText("LastName", "White"); label.setObjectText("MajorGradDate", "Computer Science"); if (printerName === "") { alert('No Printers Available. If you have a printer attached, please try restarting your computer.'); return false; } label.print(printerName) console.log('hi!'); return false; }); });
whitecl/dymo-js-sample
source/javascripts/all.js
JavaScript
mit
1,003
// // Description: // Control Spot from campfire. https://github.com/1stdibs/Spot // // Dependencies: // underscore // // Configuration: // HUBOT_SPOT_URL // // Commands: // hubot music status? - Lets you know what's up // hubot play! - Plays current playlist or song. // hubot pause - Pause the music. // hubot play next - Plays the next song. // hubot play back - Plays the previous song. // hubot playing? - Returns the currently-played song. // hubot spot volume? - Returns the current spotify volume level. // hubot spot volume [0-100] - Sets the spotify volume. // hubot [name here] says turn it down - Sets the volume to 15 and blames [name here]. // hubot say <message> - Tells hubot to read a message aloud. // hubot play <song> - Play a particular song. This plays the first most popular result. // hubot find x artist <artist-query> - Searches for x (or 6) most popular artist matching query // hubot find x music <track-query> - Searches for x (or 6) most popular tracks matching query // hubot find x music by <artist-query> - Searches for x (or 6) most popular tracks by artist-query // hubot find x albums <album-query> - Searches for x (or 6) most popular albums matching query // hubot find x albums by <artist-query> - Searches for x (or 6) most popular albums by artist-query // hubot show me album <album-query> - Pulls up the album for the given search, or if (x:y) format, the album associated with given result // hubot show me this album - Pulls up the album for the currently playing track // hubot show me music by this artist - Pulls up tracks by the current artist // hubot play n - Play the nth track from the last search results // hubot play x:y - Play the y-th track from x-th result set // hubot how much longer? - Hubot tells you how much is left on the current track // hubot queue? - Pulls up the current queue // hubot queue (track name | track result #) - Adds the given track to the queue // hubot dequeue #(queue number) - removes the given queue line item (by current position in the queue) // Authors: // andromedado, jballant // /*jslint node: true */ "use strict"; var CAMPFIRE_CHRONOLOGICAL_DELAY, DEFAULT_LIMIT, Queue, URL, VERSION, comparePart, compareVersions, determineLimit, getCurrentVersion, getStrHandler, https, now, playingRespond, remainingRespond, sayMyError, sayYourError, setVolume, spotNext, spotRequest, templates, trim, volumeLockDuration, volumeLocked, volumeRespond, words, _; var showAlbumArt; var logger = require('./support/logger'); var emoji = require('./support/emoji'); var versioning = require('./support/spotVersion'); var util = require('util'); https = require('https'); _ = require('underscore'); VERSION = versioning.version; URL = "" + process.env.HUBOT_SPOT_URL; CAMPFIRE_CHRONOLOGICAL_DELAY = 700; DEFAULT_LIMIT = 6; Queue = {}; templates = require('./support/spotifyTemplates'); function randEl (arr) { return arr[Math.floor(Math.random() * arr.length)]; } function getVersionString () { return util.format(':sparkles::%s::sparkles:Dibsy-Spot-Integration v%s:sparkles::%s::sparkles:', randEl(emoji.things), versioning.version, randEl(emoji.things)); } //getCurrentVersion = function (callback) { // return https.get('https://raw.github.com/1stdibs/hubot-scripts/master/src/scripts/spot.js', function (res) { // var data; // data = ''; // res.on('data', function (d) { // return data += d; // }); // return res.on('end', function () { // var bits, version; // bits = data.match(/VERSION = '([\d\.]+)'/); // version = bits && bits[1]; // return callback(!version, version); // }); // }).on('error', function (e) { // return callback(e); // }); //}; compareVersions = function (base, comparator) { var bParts, cParts, diff, re; if (base === comparator) { return 'up-to-date'; } re = /^(\d+)(\.(\d+))?(\.(\d+))?/; bParts = base.match(re); cParts = comparator.match(re); diff = false; if (bParts && cParts) { [ { k: 1, n: 'major version' }, { k: 3, n: 'minor version' }, { k: 5, n: 'patch', pn: 'patches' } ].forEach(function (obj) { return diff = diff || comparePart(bParts[obj.k], cParts[obj.k], obj.n, obj.pn); }); } if (!diff) { diff = 'different than the repo version: ' + base; } return diff; }; comparePart = function (b, c, partName, partNamePlural) { var diff, stem, suffix, whats; if (b === c) { return false; } diff = Math.abs(Number(c) - Number(b)); if (Number(c) > Number(b)) { stem = 'ahead'; suffix = '; the repo should probably be updated.'; } else { stem = 'behind'; suffix = '; you should probably update me. https://github.com/1stdibs/hubot-scripts'; } if (diff === 1) { whats = partName; } else { whats = partNamePlural || (partName + 's'); } return stem + ' by ' + diff + ' ' + whats + suffix; }; spotRequest = require('./support/spotRequest'); now = function () { return ~~(Date.now() / 1000); }; trim = function (str) { return String(str).replace(/^\s+/, '').replace(/\s+$/, ''); }; volumeLockDuration = 60000; words = { 'a couple': 2, 'default': 3, 'a few': 4, 'many': 6, 'a lot': 10, 'lots of': 10 }; determineLimit = function (word) { if (String(word).match(/^\d+$/)) { return word; } if (!word || !words.hasOwnProperty(word)) { word = 'default'; } return words[word]; }; spotNext = function (msg) { return spotRequest(msg, '/next', 'put', {}, function (err, res, body) { if (err) { return sayMyError(err, msg); } return msg.send(":small_blue_diamond: " + body + " :fast_forward:"); }); }; volumeRespond = function (message) { return spotRequest(message, '/volume', 'get', {}, function (err, res, body) { if (err) { return sayMyError(err, message); } return message.send("Spot volume is " + body + ". :mega:"); }); }; remainingRespond = function (message) { return spotRequest(message, '/how-much-longer', 'get', {}, function (err, res, body) { if (err) { return sayMyError(err, message); } return message.send(":small_blue_diamond: " + body); }); }; playingRespond = function (message) { return spotRequest(message, '/playing', 'get', {}, function (err, res, body) { var next; if (err) { return sayMyError(err, message); } showAlbumArt(message); message.send(":notes: " + body); next = Queue.next(); if (next) { return message.send(":small_blue_diamond: Up next is \"" + next.name + "\""); } }); }; getStrHandler = function (message) { return function (err, str) { if (err) { return sayMyError(err, message); } else { return message.send(str); } }; }; sayMyError = function (err, message) { return message.send(":flushed: " + err); }; sayYourError = function (message) { return message.send(":no_good: Syntax Error [" + Math.floor(Math.random() * Math.pow(10, 4)) + "]"); }; volumeLocked = false; var volumeKeywords = { '💯' : 100, ':100:' : 100, 'max' : 100 }; setVolume = function (level, message) { var params; level = level + ""; if (volumeLocked) { message.send(':no_good: Spot volume is currently locked'); return; } if (level.match(/^\++$/)) { spotRequest(message, '/bumpup', 'put', {}, function (err, res, body) { if (err) { return sayMyError(err, message); } return message.send("Spot volume bumped to " + body + ". :mega:"); }); return; } if (level.match(/^-+$/)) { spotRequest(message, '/bumpdown', 'put', {}, function (err, res, body) { if (err) { return sayMyError(err, message); } return message.send("Spot volume bumped down to " + body + ". :mega:"); }); return; } if (volumeKeywords[level]) { level = volumeKeywords[level] + ''; } if (!level.match(/^\d+$/)) { message.send("Invalid volume: " + level); return; } params = { volume: level }; return spotRequest(message, '/volume', 'put', params, function (err, res, body) { if (err) { return sayMyError(err, message); } return message.send("Spot volume set to " + body + ". :mega:"); }); }; var convertEmoji = function (str) { if (str[0] === ':' && str[str.length - 1] === ':') { str = str.replace(/_/g, ' ').replace(/:/g, ''); } return str }; function setupDefaultQueue(queue, reload, callback) { var fs = require('fs'); if (!queue.isEmpty() || reload) { if (!reload) { logger.minorInfo('found no redis stuff for %s', queue.getName()); } else { logger.minorInfo('reloading playlist for %s', queue.getName()); } logger.minorInfo('reading file %s', process.env.HUBOT_SPOTIFY_PLAYLIST_FILE); fs.readFile(process.env.HUBOT_SPOTIFY_PLAYLIST_FILE, 'utf-8', function (err, data) { if (err) { throw err; } var json = JSON.parse(data), len = json.length, i = -1, list; //list = json; list = _.shuffle(json); queue.clear(); // Empty the existing playlist, new songs wont be added otherwise queue.addTracks(list); // Add the shuffled list to the empty playlist queue.playNext(); // Start playling queue.start(); if (callback) { callback(queue); } }); } } module.exports = function (robot) { var Assoc, Support, playlistQueue = require('./support/spotifyQueue')(robot, URL, 'playlistQueue', true), queueMaster = require('./support/spotifyQueueMaster')(); var say = require('./support/say'); say.attachToRobot(robot); Queue = require('./support/spotifyQueue')(robot, URL); Support = require('./support/spotifySupport')(robot, URL, Queue); Assoc = require('./support/spotifyAssoc')(robot); //if (process.env.HUBOT_SPOTIFY_PLAYLIST_FILE) { // // Set up default queue // setupDefaultQueue(playlistQueue); // // // Set the default queue on the queue master // queueMaster.setDefault(playlistQueue); // // // Add the user queue // queueMaster.addQueue(Queue); // // // Conduct the queues (the default queue will // // play if user queue is empty) // queueMaster.conduct(); //} Queue.start(); showAlbumArt = function showAlbumArt(message) { //No Longer Works =( //message.send("" + URL + "/now/playing/" + Math.ceil(Math.random() * 10000000000) + '/album.png'); return Support.getCurrentTrackURL(function (err, url) { if (err) { sayMyError(err, message); } else { message.send(url); } }); }; function blame (message) { return Support.translateToTrack('this', message.message.user.id, function (err, track) { var user; if (err) { sayMyError(err, message); return; } user = Assoc.get(track.href); if (user) { return message.send(':small_blue_diamond: ' + user + ' requested ' + templates.trackLine(track)); } return message.send(':small_blue_diamond: Spotify Playlist'); }); } robot.respond(/show (me )?this album/i, function (message) { return Support.getCurrentAlbum(function (err, album, resultIndex) { var str; if (!err) { str = templates.albumSummary(album, resultIndex); } return getStrHandler(message)(err, str); }); }); robot.respond(/((find|show) )?(me )?((\d+) )?album(s)? (.+)/i, function (message) { if (message.match[6]) { return Support.findAlbums(message.match[7], message.message.user.id, message.match[5] || DEFAULT_LIMIT, getStrHandler(message)); } if (!message.match[7] || trim(message.match[7]) !== 'art') { return Support.translateToAlbum(trim(message.match[7]), message.message.user.id, function (err, album, resultIndex) { var str; if (!err) { str = templates.albumSummary(album, resultIndex); } return getStrHandler(message)(err, str); }); } }); robot.respond(/find ((\d+) )?artists (.+)/i, function (message) { return Support.findArtists(message.match[3], message.message.user.id, message.match[2] || DEFAULT_LIMIT, getStrHandler(message)); }); robot.respond(/(show|find) (me )?((\d+) )?(music|tracks|songs) (.+)/i, function (message) { return Support.findTracks(convertEmoji(message.match[6]), message.message.user.id, message.match[4] || DEFAULT_LIMIT, getStrHandler(message)); }); robot.respond(/purge results!/i, function (message) { Support.purgeLists(); return message.send(':ok_hand:'); }); robot.respond(/purge music cache!/i, function (message) { Support.purgeMusicDataCache(); return message.send(':ok_hand:'); }); robot.respond(/(blame|credit)\s*$/i, blame); robot.respond(/who asked for (.+)\??/i, blame); robot.respond(/(play|queue) (.+)/i, function (message) { return Support.translateToTrack(trim(message.match[2]), message.message.user.id, function (err, track) { if (err) { sayMyError(err, message); return; } Assoc.set(track.href, message.message.user.name); if (message.match[1].toLowerCase() === 'play' && !Queue.locked()) { Queue.stop(); message.send(':small_blue_diamond: Switching to ' + templates.trackLine(track, true)); Support.playTrack(track, function (err) { Queue.start(); if (err) { return sayMyError(err, message); } }); return; } return Queue.addTrack(track, function (err, index) { if (err) { sayMyError(err, message); return; } return message.send(":small_blue_diamond: #" + index + " in the queue is " + templates.trackLine(track)); }); }); }); robot.respond(/music status\??/i, function (message) { spotRequest(message, '/seconds-left', 'get', {}, function (err, res, body) { if (err) { return sayMyError(err, message); } var seconds; seconds = parseInt(String(body).replace(/[^\d\.]+/g, ''), 10) || 1; return setTimeout(function () { return spotRequest(message, '/seconds-left', 'get', {}, function (err, res, body) { if (err) { return sayMyError(err, message); } var seconds2; seconds2 = parseInt(String(body).replace(/[^\d\.]+/g, ''), 10) || 1; if (seconds === seconds2) { return message.send(":small_blue_diamond: The music appears to be paused"); } return remainingRespond(message); }); }, 2000); }); blame(message); playingRespond(message); volumeRespond(message); return Queue.describe(message); }); robot.respond(/(show (me )?the )?queue\??\s*$/i, function (message) { return Queue.describe(message); }); robot.respond(/dequeue #?(\d+)/i, function (message) { return Queue.dequeue(+message.match[1], function (err, name) { if (err) { message.send(":flushed: " + err); return; } return message.send(":small_blue_diamond: \"" + name + "\" removed from the queue"); }); }); robot.respond(/play!/i, function (message) { message.finish(); return spotRequest(message, '/play', 'put', {}, function (err, res, body) { if (err) { return sayMyError(err, message); } return message.send(":notes: " + body); }); }); robot.respond(/pause/i, function (message) { var params; params = { volume: 0 }; return spotRequest(message, '/pause', 'put', params, function (err, res, body) { if (err) { return sayMyError(err, message); } return message.send("" + body + " :cry:"); }); }); robot.respond(/next/i, function (message) { if (Queue.locked()) { message.send(":raised_hand: Not yet, this was queued"); return; } var q = (Queue.isEmpty()) ? playlistQueue : Queue; if (q.next()) { return q.playNext(function (err, track) { if (err) { spotNext(message); return; } return q.send(":small_blue_diamond: Ok, on to " + track.name); }); } else { return spotNext(message); } }); robot.respond(/back/i, function (message) { return spotRequest(message, '/back', 'put', {}, function (err, res, body) { if (err) { return sayMyError(err, message); } return message.send("" + body + " :rewind:"); }); }); robot.respond(/playing\?/i, function (message) { playingRespond(message); return blame(message); }); robot.respond(/album art\??/i, function (message) { return spotRequest(message, '/playing', 'get', {}, function (err, res, body) { if (err) { sayMyError(err, message); } return showAlbumArt(message); }); }); robot.respond(/lock spot volume at (\d+)/i, function (message) { var volume; if (volumeLocked) { message.send(':no_good: Spot volume is currently locked'); return; } volume = parseInt(message.match[1]) || 0; setVolume(volume, message); if (volume < 45) { message.send(':no_good: I won\'t lock the spot volume that low'); return; } if (volume > 85) { message.send(':no_good: I won\'t lock the spot volume that high'); return; } volumeLocked = true; return setTimeout(function () { return volumeLocked = false; }, volumeLockDuration); }); robot.respond(/(set )?spot volume(( to)? (.+)|\??)$/i, function (message) { var adi; if (message.match[1] || message.match[4]) { adi = trim(message.match[4]) || '0'; return setVolume(adi, message); } volumeRespond(message); }); robot.respond(/(how much )?(time )?(remaining|left)\??$/i, remainingRespond); robot.respond(/(.*) says.*turn.*down.*/i, function (message) { var name, params; name = message.match[1]; message.send("" + name + " says, 'Turn down the music and get off my lawn!' :bowtie:"); params = { volume: 15 }; return spotRequest(message, '/volume', 'put', params, function (err, res, body) { if (err) { return sayMyError(err, message); } return message.send("Spot volume set to " + body + ". :mega:"); }); }); robot.respond(/reload default playlist/i, function (message) { setupDefaultQueue(playlistQueue, true, function () { message.send("Reloaded default playlist"); }); }); //TODO: Make a responder to add to defaultQueue robot.messageRoom('#general', getVersionString()); return robot.respond(/spot version\??/i, function (message) { return message.send(getVersionString()); // return getCurrentVersion(function (e, repoVersion) { // var msg; // msg = getVersionString(); // if (!e) { // msg += '; I am ' + compareVersions(repoVersion, VERSION); // } // return message.send(msg); // }); }); };
dyg2104/hubot-scripts
src/scripts/spot.js
JavaScript
mit
21,207
require 'spec_helper' require 'securerandom' describe Chore::DuplicateDetector do class FakeDalli def initialize @store = {} end def add(id, val, ttl=0) if @store[id] && @store[id][:inserted] + @store[id][:ttl] > Time.now.to_i return false else @store[id] = {:val => val, :ttl => ttl, :inserted => Time.now.to_i} return true end end end let(:memcache) { FakeDalli.new } let(:dupe_on_cache_failure) { false } let(:dedupe_params) { { :memcached_client => memcache, :dupe_on_cache_failure => dupe_on_cache_failure } } let(:dedupe) { Chore::DuplicateDetector.new(dedupe_params)} let(:timeout) { 2 } let(:queue_url) {"queue://bogus/url"} let(:queue) { double('queue', :visibility_timeout=>timeout, :url=>queue_url) } let(:id) { SecureRandom.uuid } let(:message) { double('message', :id=>id, :queue=>queue) } let(:message_data) {{:id=>message.id, :visibility_timeout=>queue.visibility_timeout, :queue=>queue.url}} describe "#found_duplicate" do it 'should not return true if the message has not already been seen' do expect(dedupe.found_duplicate?(message_data)).to_not be true end it 'should return true if the message has already been seen' do memcache.add(message_data[:id], 1, message_data[:visibility_timeout]) expect(dedupe.found_duplicate?(message_data)).to be true end it 'should return false if given an invalid message' do expect(dedupe.found_duplicate?({})).to be false end it "should return false when identity store errors" do expect(memcache).to receive(:add).and_raise("no") expect(dedupe.found_duplicate?(message_data)).to be false end it "should set the timeout to be the queue's " do expect(memcache).to receive(:add).with(id,"1",timeout).and_call_original expect(dedupe.found_duplicate?(message_data)).to be false end it "should call #visibility_timeout once and only once" do expect(queue).to receive(:visibility_timeout).once 3.times { dedupe.found_duplicate?(message_data) } end context 'when a memecached connection error occurs' do context 'and when Chore.config.dedupe_strategy is set to :strict' do let(:dupe_on_cache_failure) { true } it "returns true" do expect(memcache).to receive(:add).and_raise expect(dedupe.found_duplicate?(message_data)).to be true end end end end end
Tapjoy/chore
spec/chore/duplicate_detector_spec.rb
Ruby
mit
2,473
import {Component, OnInit, OnDestroy, Input, Host} from '@angular/core'; import {NgClass, NgStyle} from '@angular/common'; import {ProgressDirective} from './progress.directive'; // todo: number pipe // todo: use query from progress? @Component({ selector: 'bar', directives: [NgClass, NgStyle], template: ` <div class="progress-meter" style="min-width: 0;" role="progressbar" [ngStyle]="{width: (percent < 100 ? percent : 100) + '%', transition: transition}" aria-valuemin="0" [attr.aria-valuenow]="value" [attr.aria-valuetext]="percent.toFixed(0) + '%'" [attr.aria-valuemax]="max"> <p class="progress-meter-text"> <ng-content></ng-content> </p> </div> ` }) export class BarComponent implements OnInit, OnDestroy { @Input() public type:string; @Input() public get value():number { return this._value; } public set value(v:number) { if (!v && v !== 0) { return; } this._value = v; this.recalculatePercentage(); } public percent:number = 0; public transition:string; public progress:ProgressDirective; private _value:number; public constructor(@Host() progress:ProgressDirective) { this.progress = progress; } public ngOnInit():void { this.progress.addBar(this); } public ngOnDestroy():void { this.progress.removeBar(this); } public recalculatePercentage():void { this.percent = +(100 * this.value / this.progress.max).toFixed(2); let totalPercentage = this.progress.bars.reduce(function (total:number, bar:BarComponent):number { return total + bar.percent; }, 0); if (totalPercentage > 100) { this.percent -= totalPercentage - 100; } } }
Neil-Ni/ng2-foundation
components/progressbar/bar.component.ts
TypeScript
mit
1,733
import request from 'request'; import wsse from 'wsse'; import xml2js from 'xml2js'; function pad(n) { return ('0' + n).slice(-2); } const toString = Object.prototype.toString; // 型判定 function isString(v) { return toString.call(v) == '[object String]'; } function isDate(v) { return toString.call(v) == '[object Date]'; } function isArray(v) { return toString.call(v) == '[object Array]'; } function isBoolean(v) { return toString.call(v) == '[object Boolean]'; } // DateをISO8601形式文字列に変換する // String.toISOString()はタイムゾーンがZとなってしまうので。。 function toISOString(d = new Date()) { const timezoneOffset = d.getTimezoneOffset(); const hour = Math.abs(timezoneOffset / 60) | 0; const minutes = Math.abs(timezoneOffset % 60); let tzstr = 'Z'; if (timezoneOffset < 0) { tzstr = `+${pad(hour)}:${pad(minutes)}`; } else if (timezoneOffset > 0) { tzstr = `-${pad(hour)}:${pad(minutes)}`; } return `${d.getUTCFullYear()}-${pad(d.getUTCMonth() + 1)}-${pad(d.getUTCDate())}T${pad(d.getUTCHours())}:${pad(d.getUTCMinutes())}:${pad(d.getUTCSeconds())}${tzstr}`; } // ISO8601形式かどうかをチェックする正規表現 var ISO8601Format = /^\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d:[0-5]\d([+-][0-2]\d:[0-5]\d|Z)$/; // Hatena::Blog AtomPub API wrapper // // - GET CollectionURI (/<username>/<blog_id>/atom/entry) // => Blog#index // - POST CollectionURI (/<username>/<blog_id>/atom/entry) // => Blog#create // - GET MemberURI (/<username>/<blog_id>/atom/entry/<entry_id>) // => Blog#show // - PUT MemberURI (/<username>/<blog_id>/atom/entry/<entry_id>) // => Blog#update // - DELETE MemberURI (/<username>/<blog_id>/atom/entry/<entry_id>) // => Blog#destroy // - GET ServiceDocumentURI (/<username>/<blog_id>/atom) // => None // - GET CategoryDocumentURI (/<username>/<blog_id>/atom/category) // => None class Blog { static initClass() { this.prototype._rawRequest = request; this.prototype._xmlBuilder = new xml2js.Builder(); this.prototype._xmlParser = new xml2js.Parser({ explicitArray: false, explicitCharkey: true }); } // コンストラクタ constructor({ type = 'wsse',// 認証タイプ : 'wsse'もしくは'oauth'のいずれかを指定する。 // type 'wsse','oauth'両方に必要な設定(必須) userName,// はてなブログのユーザーIDを指定する。 blogId,// はてなブログIDを指定する。 apiKey,// はてなブログのAPIキーを指定する。 // type 'oauth'のみ必須となる設定(必須) consumerKey,// コンシューマー・キー consumerSecret,// コンシューマー・シークレット accessToken,// アクセス・トークン accessTokenSecret// アクセストークン・シークレット }) { this._type = type; // 各パラメータのチェック if (this._type != 'oauth' && this._type != 'wsse') { throw new Error('constructor:typeには"wsse"もしくは"oauth"以外の値は指定できません。'); } if (!userName) { throw new Error('constructor:userNameが空白・null・未指定です。正しいはてなブログユーザー名を指定してください。'); } if (!blogId) { throw new Error('constructor:blogIdが空白・null・未指定です。正しいはてなブログIDを指定してください。'); } if (!apiKey) { throw new Error('constructor:apiKeyが空白・null・未指定です。正しいはてなブログAPIキーを指定してください。'); } if (this.type_ == 'oauth') { if (!consumerKey) { throw new Error('constructor:consumerKeyが空白・null・未指定です。正しいコンシューマー・キーを指定してください。'); } if (!consumerSecret) { throw new Error('constructor:consumerSecretが空白・null・未指定です。正しいコンシューマー・シークレットを指定してください。'); } if (!accessToken) { throw new Error('constructor:accessTokenが空白・null・未指定です。正しいアクセス・トークンを指定してください。'); } if (!accessTokenSecret) { throw new Error('constructor:accessTokenSecretが空白・null・未指定です。正しいアクセス・トークン・シークレットを指定してください。'); } } else { if (consumerKey) { console.warn('"wsse"では使用しないconsumerKeyパラメータが指定されています。'); } if (consumerSecret) { console.warn('"wsse"では使用しないconsumerSecretパラメータが指定されています。'); } if (accessToken) { console.warn('"wsse"では使用しないaccessTokenパラメータが指定されています。'); } if (accessTokenSecret) { console.warn('"wsse"では使用しないaccessTokenSecretパラメータが指定されています。'); } } this._userName = userName; this._blogId = blogId;; this._apiKey = apiKey; this._consumerKey = consumerKey; this._consumerSecret = consumerSecret; this._accessToken = accessToken; this._accessTokenSecret = accessTokenSecret; this._baseUrl = 'https://blog.hatena.ne.jp'; } // POST CollectionURI (/<username>/<blog_id>/atom/entry) // 戻り値: // Promise postEntry({ title = '',// タイトル文字列 content = '',// 記事本文 updated = new Date(), // 日付 categories,// カテゴリ draft = false // 下書きかどうか }) { const method = 'post'; const path = `/${this._userName}/${this._blogId}/atom/entry`; title = !title ? '' : title; content = !content ? '' : content; const body = { entry: { $: { xmlns: 'http://www.w3.org/2005/Atom', 'xmlns:app': 'http://www.w3.org/2007/app' }, title: { _: title }, content: { $: { type: 'text/plain' }, _: content } } }; // 日付文字列のチェック if (isDate(updated)) { // DateはISO8601文字列に変換 updated = toISOString(updated); } else if (!updated.match(ISO8601Format)) { return this._reject('postEntry:updatedの日付フォーマットに誤りがあります。指定できるのはDateオブジェクトかISO8601文字列のみです。'); } // categoriesのチェック if (categories) { if (!isArray(categories)) { if (isString(categories)) { categories = [categories]; } else { return this._reject('postEntry:categoriesに文字列もしくは文字配列以外の値が指定されています。指定できるのは文字列か、文字配列のみです。'); } } else { for (let i = 0, e = categories.length; i < e; ++i) { if (!isString(categories[i])) { return this._reject('postEntry:categoriesの配列中に文字列でないものが含まれています。配列に含めることができるのは文字列のみです。'); } } } } // draftのチェック if (!isBoolean(draft)) { return this._reject('postEntry:draftにブール値以外の値が含まれています。') } if (updated) { body.entry.updated = { _: updated }; } if (categories) { body.entry.category = categories.map(c => ({ $: { term: c } })); } if (draft ? draft : false) { body.entry['app:control'] = { 'app:draft': { _: 'yes' } }; } let statusCode = 201; // requestの発行。結果はプロミスで返却される return this._request({ method, path, body, statusCode }); } // PUT MemberURI (/<username>/<blog_id>/atom/entry/<entry_id>) // returns: // Promise updateEntry({ id,// エントリID(必須) title,// タイトル(必須) content,// 記事本体(必須) updated,// 更新日付(必須) categories,// カテゴリ(オプション) draft = false //下書きがどうか(既定:false(公開)) }) { if (!id) return this._rejectRequired('updateEntry', 'id'); if (!content) return this._rejectRequired('updateEntry', 'content'); if (!title) return this._rejectRequired('updateEntry', 'title'); if (!updated) return this._rejectRequired('updateEntry', 'updated'); // updatedのチェック if (isDate(updated)) { // DateはISO8601文字列に変換 updated = toISOString(updated); } else if (!updated.match(ISO8601Format)) { return this._reject('updateEntry:updatedの日付フォーマットに誤りがあります。指定できるのはDateオブジェクトかISO8601文字列のみです。'); } // categoriesのチェック if (categories) { if (!isArray(categories)) { if (isString(categories)) { categories = [categories]; } else { return this._reject('postEntry:categoriesに文字列もしくは文字配列以外の値が指定されています。指定できるのは文字列か、文字配列のみです。'); } } else { for (let i = 0, e = categories.length; i < e; ++i) { if (!isString(categories[i])) { return this._reject('postEntry:categoriesの配列中に文字列でないものが含まれています。配列に含めることができるのは文字列のみです。'); } } } } // draftのチェック if (!isBoolean(draft)) { return this._reject('postEntry:draftにブール値以外の値が含まれています。') } title = !title ? '' : title; content = !content ? '' : content; const method = 'put'; const path = `/${this._userName}/${this._blogId}/atom/entry/${id}`; const body = { entry: { $: { xmlns: 'http://www.w3.org/2005/Atom', 'xmlns:app': 'http://www.w3.org/2007/app' }, content: { $: { type: 'text/plain' }, _: content } } }; title && (body.entry.title = { _: title }); body.entry.updated = { _: updated }; if (categories != null) { body.entry.category = categories.map(c => ({ $: { term: c } })); } if (draft != null ? draft : false) { body.entry['app:control'] = { 'app:draft': { _: 'yes' } }; } let statusCode = 200; return this._request({ method, path, body, statusCode }); } // DELETE MemberURI (/<username>/<blog_id>/atom/entry/<entry_id>) // params: // options: (required) // - id: entry id. (required) // returns: // Promise deleteEntry(id) { if (id == null) { return this._rejectRequired('deleteEntry', 'id'); } let method = 'delete'; let path = `/${this._userName}/${this._blogId}/atom/entry/${id}`; let statusCode = 200; return this._request({ method, path, statusCode }); } // GET MemberURI (/<username>/<blog_id>/atom/entry/<entry_id>) // returns: // Promise getEntry(id) { if (id == null) { return this._rejectRequired('getEntry', 'id'); } let method = 'get'; let path = `/${this._userName}/${this._blogId}/atom/entry/${id}`; let statusCode = 200; return this._request({ method, path, statusCode }); } // GET CollectionURI (/<username>/<blog_id>/atom/entry) // returns: // Promise getEntries(page) { const method = 'get'; const pathWithoutQuery = `/${this._userName}/${this._blogId}/atom/entry`; const query = page ? `?page=${page}` : ''; const path = pathWithoutQuery + query; const statusCode = 200; return this._request({ method, path, statusCode }) .then(res => { const results = { res: res }; // 前のページのPage IDを取り出す const next = res.feed.link.filter((d) => d.$.rel == 'next'); if (next && next[0]) { const regexp = /\?page\=([0-9]*)$/; const maches = regexp.exec(next[0].$.href); const nextPageID = maches[1].trim(); if(nextPageID) results.nextPageID = nextPageID; } // 単一エントリ・エントリなしの対応 if(res.feed.entry){ if(!isArray(res.feed.entry)){ // 単一エントリの場合は配列に格納しなおす res.feed.entry = [res.feed.entry]; } } else { // entryがない場合はから配列を返す res.feed.entry = []; } return results; }); } // entryのJSONデータからEntry IDを取り出す。 getEntryID(entry /* entryのJSONデータ */){ // 入力値のチェック if(!entry.id){ throw new Error('与えられたパラメータが不正です。'); } const maches = entry.id._.match(/^tag:[^:]+:[^-]+-[^-]+-\d+-(\d+)$/); if(!maches[1]) throw new Error('与えられたパラメータが不正です。'); return maches[1]; } _reject(message) { let e; try { e = new Error(message); return Promise.reject(e); } catch (error) { return Promise.reject(error); } } _rejectRequired(methodName, paramStr) { return this._reject(`${methodName}:{}.${paramStr}が指定されていません。{}.${paramStr}は必須項目です。`); } _request({ method, path, body, statusCode }) { const params = {}; params.method = method; params.url = this._baseUrl + path; if (this._type === 'oauth') { params.oauth = { consumer_key: this._consumerKey, consumer_secret: this._consumerSecret, token: this._accessToken, token_secret: this._accessTokenSecret }; } else { // @_type is 'wsse' const token = wsse().getUsernameToken(this._userName, this._apiKey, { nonceBase64: true }); params.headers = { 'Authorization': 'WSSE profile="UsernameToken"', 'X-WSSE': `UsernameToken ${token}` }; } const promise = (body != null) ? this._toXml(body) : Promise.resolve(null); return promise .then(body => { if (body != null) { params.body = body; } return this._requestPromise(params); }).then(res => { //console.log(res.headers,res.statusCode,res.statusMessage); if (res.statusCode !== statusCode) { throw new Error(`HTTP status code is ${res.statusCode}`); } //console.log(res.body); return this._toJson(res.body); }); } _requestPromise(params) { return new Promise(( (resolve, reject) => { return this._rawRequest(params, function (err, res) { if (err != null) { return reject(err); } else { return resolve(res); } }); })); } _toJson(xml) { return new Promise((resolve, reject) =>{ return this._xmlParser.parseString(xml, (err, result)=> { if (err != null) { return reject(err); } else { return resolve(result); } }); }); } _toXml(json) { try { let xml = this._xmlBuilder.buildObject(json); return Promise.resolve(xml); } catch (e) { return Promise.reject(e); } } } Blog.initClass(); export default Blog;
sfpgmr/node-hatena-blog-api2
src/blog.js
JavaScript
mit
15,445
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.FilterList = undefined; var _slicedToArray = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }(); var _react = require('react'); var _react2 = _interopRequireDefault(_react); var _FilterItem = require('./FilterItem'); var _FilterList = require('../FilterList'); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var FilterList = exports.FilterList = function (_BaseFilterList) { _inherits(FilterList, _BaseFilterList); function FilterList() { var _ref; var _temp, _this, _ret; _classCallCheck(this, FilterList); for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } return _ret = (_temp = (_this = _possibleConstructorReturn(this, (_ref = FilterList.__proto__ || Object.getPrototypeOf(FilterList)).call.apply(_ref, [this].concat(args))), _this), _this.doRenderFilterItem = function (_ref2) { var _ref3 = _slicedToArray(_ref2, 2), filterId = _ref3[0], filter = _ref3[1]; var _this$props = _this.props, fields = _this$props.fields, removeLabel = _this$props.removeLabel; return _react2.default.createElement(_FilterItem.FilterItem, { key: filterId, filter: filter, fields: fields, removeLabel: removeLabel, onRemoveClick: function onRemoveClick() { return _this.removeFilter(filterId); }, onFieldChange: function onFieldChange(name) { return _this.onFieldChange(filterId, name); }, onValueChange: function onValueChange(value) { return _this.onValueChange(filterId, value); }, onOperatorChange: function onOperatorChange(operator) { return _this.onOperatorChange(filterId, operator); } }); }, _temp), _possibleConstructorReturn(_this, _ret); } return FilterList; }(_FilterList.FilterList); //# sourceMappingURL=FilterList.js.map
reactmob/dos-filter
lib/Fabric/FilterList.js
JavaScript
mit
3,795
package edu.galileo.android.photofeed.main.ui; public interface MainView { void onUploadInit(); void onUploadComplete(); void onUploadError(String error); }
micromasterandroid/androidadvanced
Lesson 4/PhotoFeed/app/src/main/java/edu/galileo/android/photofeed/main/ui/MainView.java
Java
mit
171
import { Hash } from 'archmage-persistence' export interface Block { hash: Hash format: number number: number content: Hash previous?: Hash timestamp: Date }
silentorb/archmage
packages/archmage-chaining/src/chaining/types.ts
TypeScript
mit
171
require "edition" require_relative 'simple_smart_answer_edition/node' require_relative 'simple_smart_answer_edition/node/option' class SimpleSmartAnswerEdition < Edition include Mongoid::Document field :body, type: String embeds_many :nodes, :class_name => "SimpleSmartAnswerEdition::Node" accepts_nested_attributes_for :nodes, allow_destroy: true GOVSPEAK_FIELDS = [:body] @fields_to_clone = [:body] def whole_body body end def build_clone(edition_class=nil) new_edition = super(edition_class) new_edition.body = self.body if new_edition.is_a?(SimpleSmartAnswerEdition) self.nodes.each {|n| new_edition.nodes << n.clone } end new_edition end # Workaround mongoid conflicting mods error # See https://github.com/mongoid/mongoid/issues/1219 # Override update_attributes so that nested nodes are updated individually. # This get around the problem of mongoid issuing a query with conflicting modifications # to the same document. alias_method :original_update_attributes, :update_attributes def update_attributes(attributes) if nodes_attrs = attributes.delete(:nodes_attributes) nodes_attrs.each do |index, node_attrs| if node_id = node_attrs['id'] node = nodes.find(node_id) if destroy_in_attrs?(node_attrs) node.destroy else node.update_attributes(node_attrs) end else nodes << Node.new(node_attrs) unless destroy_in_attrs?(node_attrs) end end end original_update_attributes(attributes) end def initial_node self.nodes.first end def destroy_in_attrs?(attrs) attrs['_destroy'] == '1' end end
dinuksha/Test
app/models/simple_smart_answer_edition.rb
Ruby
mit
1,716
var React = require('react'); var Link = require('react-router-dom').Link; class Home extends React.Component { render() { return ( <div className='home-container'> <h1>Github Battle: Battle your friends...and stuff.</h1> <Link className='button' to='/battle'> Battle </Link> </div> ) } } module.exports = Home;
brianmmcgrath/react-github-battle
app/components/Home.js
JavaScript
mit
430
export { AuthenticationService } from './authentication.service'; export { CustomHttp } from './customHttp';
Zinadore/capstoneed-common
src/shared/Services/index.ts
TypeScript
mit
109
/** * @file * @author zdying */ 'use strict'; var assert = require('assert'); var path = require('path'); var parseHosts = require('../src/proxy/tools/parseHosts'); describe('proxy hosts',function(){ it('正确解析hosts文件', function(){ var hostsObj = parseHosts(path.resolve(__dirname, 'proxy/hosts.example')); var target = { 'hiipack.com': '127.0.0.1:8800', 'hii.com': '127.0.0.1:8800', 'example.com': '127.0.0.1', 'example.com.cn': '127.0.0.1' }; assert(JSON.stringify(hostsObj) === JSON.stringify(target)) }); });
zdying/hiipack
test/proxy.hosts.test.js
JavaScript
mit
618
var EventEmitter = require('events').EventEmitter; var _ = require('underscore'); var Message = require('./Message'); var ProduceRequest = require('./ProduceRequest'); var Connection = require('./Connection'); var ConnectionCache = require('./ConnectionCache'); var Producer = function(topic, options){ if (!topic || (!_.isString(topic))){ throw "the first parameter, topic, is mandatory."; } this.MAX_MESSAGE_SIZE = 1024 * 1024; // 1 megabyte options = options || {}; this.topic = topic; this.partition = options.partition || 0; this.host = options.host || 'localhost'; this.port = options.port || 9092; this.useConnectionCache = options.connectionCache; this.connection = null; }; Producer.prototype = Object.create(EventEmitter.prototype); Producer.prototype.connect = function(){ var that = this; if (this.useConnectionCache) { this.connection = Producer._connectionCache.getConnection(this.port, this.host); } else { this.connection = new Connection(this.port, this.host); } this.connection.once('connect', function(){ that.emit('connect'); }); this.connection.on('error', function(err) { if (!!err.message && (err.message === 'connect ECONNREFUSED' || err.message.indexOf('connect ECONNREFUSED') === 0) ) { that.emit('error', err); } }); this.connection.connect(); }; Producer.prototype.send = function(messages, options, cb) { var that = this; if (arguments.length === 2){ // "options" is not a required parameter, so handle the // case when it's not set. cb = options; options = {}; } if (!cb || (typeof cb != 'function')){ throw "A callback with an error parameter must be supplied"; } options.partition = options.partition || this.partition; options.topic = options.topic || this.topic; messages = toListOfMessages(toArray(messages)); var request = new ProduceRequest(options.topic, options.partition, messages); this.connection.write(request.toBytes(), cb); }; Producer._connectionCache = new ConnectionCache(); Producer.clearConnectionCache = function() { Producer._connectionCache.clear(); }; module.exports = Producer; var toListOfMessages = function(args) { return _.map(args, function(arg) { if (arg instanceof Message) { return arg; } return new Message(arg); }); }; var toArray = function(arg) { if (_.isArray(arg)) return arg; return [arg]; };
uber/Prozess
Producer.js
JavaScript
mit
2,432
/* * The MIT License (MIT) * * Copyright (c) 2016 Erik Zivkovic * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package se.bes.mhfs.plugin; import se.bes.mhfs.manager.HFSMonitor; import java.io.File; import java.io.FileFilter; import java.util.Hashtable; public class PluginManager { private final Hashtable<String, Plugin> plugins = new Hashtable<>(); private HFSMonitor monitor; public PluginManager(HFSMonitor monitor) { this.monitor = monitor; } public synchronized void registerPlugin(Plugin plugin) { plugins.put(plugin.getName(), plugin); } public synchronized Plugin getPluginByIdentifier(String identifier) { return plugins.get(identifier); } public synchronized String[] getPluginStrings() { String[] strings = new String[plugins.size()]; plugins.keySet().toArray(strings); return strings; } public void setupPlugins() { File pluginDir = new File("./plugins/"); File[] files = pluginDir.listFiles(new FileFilter() { public boolean accept(File pathname) { return pathname.isFile() && pathname.getName().endsWith(".hfsplugin"); } }); if(files == null) return; PluginClassLoader pcl = new PluginClassLoader(); for(File f:files){ try { Class c = pcl.loadClass(f.getName()); c.getConstructors()[0].newInstance((new Object[]{monitor})); System.out.println("Added Plugin: " + f.getName()); } catch (Exception e) { e.printStackTrace(); } } } }
bes/MHFS
src/main/java/se/bes/mhfs/plugin/PluginManager.java
Java
mit
2,713
import numpy as np import scipy.misc import matplotlib.pyplot as plt x = np.linspace(0, 5, 100) y1 = np.power(2, x) y2 = scipy.misc.factorial(x) plt.plot(x, y1) plt.plot(x, y2) plt.grid(True) plt.savefig('../../img/question_4_plots/g.png')
ammiranda/CS325
week1/plots/question_4/g.py
Python
mit
243
using System.Diagnostics.CodeAnalysis; using System.Windows; using System.Windows.Controls; using System.Windows.Input; using System.Windows.Interactivity; namespace GSD.Behaviors { [SuppressMessage( "ReSharper", "MemberCanBePrivate.Global" )] [ExcludeFromCodeCoverage] internal class EnterCommand : Behavior<TextBox> { protected override void OnAttached() { base.OnAttached(); AssociatedObject.KeyDown += ( s, e ) => { if( e.Key != Key.Return || Command == null || !Command.CanExecute( CommandParameter ) ) { return; } Command.Execute( CommandParameter ); if( ClearAfterExecute ) { AssociatedObject.Text = string.Empty; } }; } public bool ClearAfterExecute { get { return (bool)GetValue( ClearAfterExecuteProperty ); } set { SetValue( ClearAfterExecuteProperty, value ); } } public ICommand Command { get { return (ICommand)GetValue( CommandProperty ); } set { SetValue( CommandProperty, value ); } } public object CommandParameter { get { return GetValue( CommandParameterProperty ); } set { SetValue( CommandParameterProperty, value ); } } public static readonly DependencyProperty ClearAfterExecuteProperty = DependencyProperty.Register( "ClearAfterExecute", typeof( bool ), typeof( EnterCommand ), new PropertyMetadata( true ) ); public static readonly DependencyProperty CommandParameterProperty = DependencyProperty.Register( "CommandParameter", typeof( object ), typeof( EnterCommand ), new PropertyMetadata( null ) ); public static readonly DependencyProperty CommandProperty = DependencyProperty.Register( "Command", typeof( ICommand ), typeof( EnterCommand ), new PropertyMetadata( null ) ); } }
TheSylence/GSD
GSD/Behaviors/EnterCommand.cs
C#
mit
1,719
/** * Swaggy Jenkins * Jenkins API clients generated from Swagger / Open API specification * * The version of the OpenAPI document: 1.1.2-pre.0 * Contact: blah@cliffano.com * * NOTE: This class is auto generated by OpenAPI-Generator 5.4.0. * https://openapi-generator.tech * Do not edit the class manually. */ #include "ClockDifference.h" #include <string> #include <vector> #include <sstream> #include <stdexcept> #include <boost/property_tree/ptree.hpp> #include <boost/property_tree/json_parser.hpp> using boost::property_tree::ptree; using boost::property_tree::read_json; using boost::property_tree::write_json; namespace org { namespace openapitools { namespace server { namespace model { ClockDifference::ClockDifference(boost::property_tree::ptree const& pt) { fromPropertyTree(pt); } std::string ClockDifference::toJsonString(bool prettyJson /* = false */) { return toJsonString_internal(prettyJson); } void ClockDifference::fromJsonString(std::string const& jsonString) { fromJsonString_internal(jsonString); } boost::property_tree::ptree ClockDifference::toPropertyTree() { return toPropertyTree_internal(); } void ClockDifference::fromPropertyTree(boost::property_tree::ptree const& pt) { fromPropertyTree_internal(pt); } std::string ClockDifference::toJsonString_internal(bool prettyJson) { std::stringstream ss; write_json(ss, this->toPropertyTree(), prettyJson); return ss.str(); } void ClockDifference::fromJsonString_internal(std::string const& jsonString) { std::stringstream ss(jsonString); ptree pt; read_json(ss,pt); this->fromPropertyTree(pt); } ptree ClockDifference::toPropertyTree_internal() { ptree pt; ptree tmp_node; pt.put("_class", m__class); pt.put("diff", m_Diff); return pt; } void ClockDifference::fromPropertyTree_internal(ptree const &pt) { ptree tmp_node; m__class = pt.get("_class", ""); m_Diff = pt.get("diff", 0); } std::string ClockDifference::get_Class() const { return m__class; } void ClockDifference::set_Class(std::string value) { m__class = value; } int32_t ClockDifference::getDiff() const { return m_Diff; } void ClockDifference::setDiff(int32_t value) { m_Diff = value; } std::vector<ClockDifference> createClockDifferenceVectorFromJsonString(const std::string& json) { std::stringstream sstream(json); boost::property_tree::ptree pt; boost::property_tree::json_parser::read_json(sstream,pt); auto vec = std::vector<ClockDifference>(); for (const auto& child: pt) { vec.emplace_back(ClockDifference(child.second)); } return vec; } } } } }
cliffano/swaggy-jenkins
clients/cpp-restbed-server/generated/model/ClockDifference.cpp
C++
mit
2,607
using System; using System.Collections.Generic; using System.Reactive.Linq; using System.Reactive.Threading.Tasks; using MS.Core; namespace System.Runtime.Remoting.Channels { public static class __IServerChannelSink { public static IObservable < Tuple <System.Runtime.Remoting.Channels.ServerProcessing, System.Runtime.Remoting.Messaging.IMessage, System.Runtime.Remoting.Channels.ITransportHeaders, System.IO.Stream>> ProcessMessage( this IObservable<System.Runtime.Remoting.Channels.IServerChannelSink> IServerChannelSinkValue, IObservable<System.Runtime.Remoting.Channels.IServerChannelSinkStack> sinkStack, IObservable<System.Runtime.Remoting.Messaging.IMessage> requestMsg, IObservable<System.Runtime.Remoting.Channels.ITransportHeaders> requestHeaders, IObservable<System.IO.Stream> requestStream) { return Observable.Zip(IServerChannelSinkValue, sinkStack, requestMsg, requestHeaders, requestStream, (IServerChannelSinkValueLambda, sinkStackLambda, requestMsgLambda, requestHeadersLambda, requestStreamLambda) => { System.Runtime.Remoting.Messaging.IMessage responseMsgOutput = default(System.Runtime.Remoting.Messaging.IMessage); System.Runtime.Remoting.Channels.ITransportHeaders responseHeadersOutput = default(System.Runtime.Remoting.Channels.ITransportHeaders); System.IO.Stream responseStreamOutput = default(System.IO.Stream); var result = IServerChannelSinkValueLambda.ProcessMessage(sinkStackLambda, requestMsgLambda, requestHeadersLambda, requestStreamLambda, out responseMsgOutput, out responseHeadersOutput, out responseStreamOutput); return Tuple.Create(result, responseMsgOutput, responseHeadersOutput, responseStreamOutput); }); } public static IObservable<System.Reactive.Unit> AsyncProcessResponse( this IObservable<System.Runtime.Remoting.Channels.IServerChannelSink> IServerChannelSinkValue, IObservable<System.Runtime.Remoting.Channels.IServerResponseChannelSinkStack> sinkStack, IObservable<System.Object> state, IObservable<System.Runtime.Remoting.Messaging.IMessage> msg, IObservable<System.Runtime.Remoting.Channels.ITransportHeaders> headers, IObservable<System.IO.Stream> stream) { return ObservableExt.ZipExecute(IServerChannelSinkValue, sinkStack, state, msg, headers, stream, (IServerChannelSinkValueLambda, sinkStackLambda, stateLambda, msgLambda, headersLambda, streamLambda) => IServerChannelSinkValueLambda.AsyncProcessResponse(sinkStackLambda, stateLambda, msgLambda, headersLambda, streamLambda)); } public static IObservable<System.IO.Stream> GetResponseStream( this IObservable<System.Runtime.Remoting.Channels.IServerChannelSink> IServerChannelSinkValue, IObservable<System.Runtime.Remoting.Channels.IServerResponseChannelSinkStack> sinkStack, IObservable<System.Object> state, IObservable<System.Runtime.Remoting.Messaging.IMessage> msg, IObservable<System.Runtime.Remoting.Channels.ITransportHeaders> headers) { return Observable.Zip(IServerChannelSinkValue, sinkStack, state, msg, headers, (IServerChannelSinkValueLambda, sinkStackLambda, stateLambda, msgLambda, headersLambda) => IServerChannelSinkValueLambda.GetResponseStream(sinkStackLambda, stateLambda, msgLambda, headersLambda)); } public static IObservable<System.Runtime.Remoting.Channels.IServerChannelSink> get_NextChannelSink( this IObservable<System.Runtime.Remoting.Channels.IServerChannelSink> IServerChannelSinkValue) { return Observable.Select(IServerChannelSinkValue, (IServerChannelSinkValueLambda) => IServerChannelSinkValueLambda.NextChannelSink); } } }
RixianOpenTech/RxWrappers
Source/Wrappers/mscorlib/System.Runtime.Remoting.Channels.IServerChannelSink.cs
C#
mit
4,315
require "ios-deploy/version" module IosDeploy # Your code goes here... end
mokagio/ios-deploy-gem
lib/ios-deploy.rb
Ruby
mit
78
require_dependency "conductor/application_controller" module Conductor class DatabasesController < ApplicationController def show @database = Database.instance end def update @database = Database.instance @database.content = params[:database][:content] @database.save flash[:success] = "The database was successfully updated!" redirect_to database_path end end end
NewRosies/conductor
app/controllers/conductor/databases_controller.rb
Ruby
mit
422
webpackJsonp([0x78854e72ca23],{567:function(t,e){t.exports={pathContext:{}}}}); //# sourceMappingURL=path---blog-gatsby-github-a0e39f21c11f6a62c5ab.js.map
russellschmidt/russellschmidt.github.io
path---blog-gatsby-github-a0e39f21c11f6a62c5ab.js
JavaScript
mit
154
module Mruby # (Not documented) # # ## Fields: # :struct_name :: # (String) # :dfree :: # (FFI::Pointer(*)) class MrbDataType < FFI::Struct layout :struct_name, :string, :dfree, :pointer end end
DAddYE/mrb
lib/mrb/mrb_data_type.rb
Ruby
mit
233
package me.yoerger.geoff.edu.progClass.assignments.eight; import java.util.Scanner; import me.yoerger.geoff.edu.progClass.assignments.Analysis; import me.yoerger.geoff.edu.progClass.assignments.Printer; import me.yoerger.geoff.edu.progClass.bookClasses.FileChooser; import me.yoerger.geoff.edu.progClass.bookClasses.Picture; import me.yoerger.geoff.edu.progClass.bookClasses.Pixel; import me.yoerger.geoff.edu.progClass.mod8.Grayscale; public class eightFive implements Analysis{ public static void main(String[] args) { System.out.println("Select your grayscale picture or hit cancel to select a picture to be grayscaled."); String picLoc = FileChooser.pickAFile(); if(picLoc == null) { String noGrayPicLoc = FileChooser.pickAFile(); if(noGrayPicLoc == null || !noGrayPicLoc.matches(".*\\.jpe?g")) System.exit(1); picLoc = Grayscale.grayscale(noGrayPicLoc); } if(!picLoc.matches(".*\\.jpe?g")) System.exit(1); Picture pic = new Picture(picLoc); Scanner in = new Scanner(System.in); System.out.println("How much red scale do you want applied? (0 or more)"); double redScale = in.nextDouble(); System.out.println("Blue?"); double blueScale = in.nextDouble(); System.out.println("Green?"); double greenScale = in.nextDouble(); in.close(); for(Pixel pixel : pic.getPixels()) { pixel.setRed((int) (pixel.getRed() * redScale)); pixel.setGreen((int) (pixel.getGreen() * greenScale)); pixel.setBlue((int) (pixel.getBlue() * blueScale)); } pic.show(); } @Override public void printQuestions(Printer printer) { printer.print("Describe the me.yoerger.geoff.edu.progClass.main point of this assignment. (Required)"); printer.printAnswer("Apply color scales to a grayscale picture."); printer.print("Discuss how this assignment relates to a real-life situation. (Required)"); printer.printAnswer("This could be used in art programs to colorize a previously grayscale picture, like an older one."); printer.print("Reflect on your growth as a programmer. (Required)"); printer.printAnswer("I learned how to test to see if a string that represents a certain file has a certain extension"); printer.print("Describe the biggest problem encountered and how it was fixed."); printer.printAnswer("Making the Grayscale class, I had to do a lot of repetitiveness and iteration."); printer.print("Describe at least one thing that will be done differently in the future."); printer.printAnswer("Have the program detect if the selected picture is already grayscaled or not."); printer.print("Suggest how this assignment could be extended."); printer.printAnswer("Have it apply alpha values too."); printer.print("How could you apply a meaningful color palette to a weather satellite image showing temperatures or pressures?"); printer.printAnswer("By using this!"); printer.print("What question(s) of your own did you answer while writing this program?"); printer.printAnswer("How do determine if a file selecter was closed or not."); printer.print("What unanswered question(s) do you have after writing this program?"); printer.printAnswer("Is there a way to have the GPU do this task?"); } }
DirkyJerky/ProgrammingClass
src/me/yoerger/geoff/edu/progClass/assignments/eight/eightFive.java
Java
mit
3,209
<?php ob_start(); session_start(); require_once( '../../../wp-load.php' ); wp(); header('HTTP/1.1 200 OK'); if (!function_exists('wp_handle_upload')){ require_once( ABSPATH . 'wp-admin/includes/file.php' ); } $body = @file_get_contents('php://input'); $event_json = json_decode($body); if( $event_json->data->object->status == "paid" ){ //if paid $new_status = get_term_by( 'slug', 'completed', 'shop_order_status' ); wp_set_object_terms( $event_json->data->object->reference_id, array( $new_status->slug), 'shop_order_status', false ); } file_put_contents("conekta_last_event.json", $event_json->data->object->id);
CORBmx/Kiwi
update_conekta.php
PHP
mit
629
/****************************************************************************** * The MIT License (MIT) * * Copyright (c) 2015-2018 Baldur Karlsson * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. ******************************************************************************/ #include "../vk_core.h" #include "../vk_debug.h" #include "../vk_rendertext.h" #include "../vk_shader_cache.h" #include "api/replay/version.h" // intercept and overwrite the application info if present. We must use the same appinfo on // capture and replay, and the safer default is not to replay as if we were the original app but // with a slightly different workload. So instead we trample what the app reported and put in our // own info. static VkApplicationInfo renderdocAppInfo = { VK_STRUCTURE_TYPE_APPLICATION_INFO, NULL, "RenderDoc Capturing App", VK_MAKE_VERSION(RENDERDOC_VERSION_MAJOR, RENDERDOC_VERSION_MINOR, 0), "RenderDoc", VK_MAKE_VERSION(RENDERDOC_VERSION_MAJOR, RENDERDOC_VERSION_MINOR, 0), VK_API_VERSION_1_0, }; // vk_dispatchtables.cpp void InitDeviceTable(VkDevice dev, PFN_vkGetDeviceProcAddr gpa); void InitInstanceTable(VkInstance inst, PFN_vkGetInstanceProcAddr gpa); // Init/shutdown order: // // On capture, WrappedVulkan is new'd and delete'd before vkCreateInstance() and after // vkDestroyInstance() // On replay, WrappedVulkan is new'd and delete'd before Initialise() and after Shutdown() // // The class constructor and destructor handle only *non-API* work. All API objects must be created // and // torn down in the latter functions (vkCreateInstance/vkDestroyInstance during capture, and // Initialise/Shutdown during replay). // // Note that during capture we have vkDestroyDevice before vkDestroyDevice that does most of the // work. // // Also we assume correctness from the application, that all objects are destroyed before the device // and // instance are destroyed. We only clean up after our own objects. static void StripUnwantedLayers(vector<string> &Layers) { for(auto it = Layers.begin(); it != Layers.end();) { // don't try and create our own layer on replay! if(*it == RENDERDOC_VULKAN_LAYER_NAME) { it = Layers.erase(it); continue; } // don't enable tracing or dumping layers just in case they // came along with the application if(*it == "VK_LAYER_LUNARG_api_dump" || *it == "VK_LAYER_LUNARG_vktrace") { it = Layers.erase(it); continue; } // also remove the framerate monitor layer as it's buggy and doesn't do anything // in our case if(*it == "VK_LAYER_LUNARG_monitor") { it = Layers.erase(it); continue; } // filter out validation layers if(*it == "VK_LAYER_LUNARG_standard_validation" || *it == "VK_LAYER_LUNARG_core_validation" || *it == "VK_LAYER_LUNARG_device_limits" || *it == "VK_LAYER_LUNARG_image" || *it == "VK_LAYER_LUNARG_object_tracker" || *it == "VK_LAYER_LUNARG_parameter_validation" || *it == "VK_LAYER_LUNARG_swapchain" || *it == "VK_LAYER_GOOGLE_threading" || *it == "VK_LAYER_GOOGLE_unique_objects") { it = Layers.erase(it); continue; } ++it; } } ReplayStatus WrappedVulkan::Initialise(VkInitParams &params, uint64_t sectionVersion) { m_InitParams = params; m_SectionVersion = sectionVersion; // PORTABILITY verify that layers/extensions are available StripUnwantedLayers(params.Layers); #if ENABLED(FORCE_VALIDATION_LAYERS) && DISABLED(RDOC_ANDROID) params.Layers.push_back("VK_LAYER_LUNARG_standard_validation"); #endif // strip out any WSI/direct display extensions. We'll add the ones we want for creating windows // on the current platforms below, and we don't replay any of the WSI functionality // directly so these extensions aren't needed for(auto it = params.Extensions.begin(); it != params.Extensions.end();) { if(*it == "VK_KHR_xlib_surface" || *it == "VK_KHR_xcb_surface" || *it == "VK_KHR_wayland_surface" || *it == "VK_KHR_mir_surface" || *it == "VK_KHR_android_surface" || *it == "VK_KHR_win32_surface" || *it == "VK_KHR_display" || *it == "VK_EXT_direct_mode_display" || *it == "VK_EXT_acquire_xlib_display" || *it == "VK_EXT_display_surface_counter") { it = params.Extensions.erase(it); } else { ++it; } } RDCEraseEl(m_ExtensionsEnabled); std::set<string> supportedExtensions; for(size_t i = 0; i <= params.Layers.size(); i++) { const char *pLayerName = (i == 0 ? NULL : params.Layers[i - 1].c_str()); uint32_t count = 0; GetInstanceDispatchTable(NULL)->EnumerateInstanceExtensionProperties(pLayerName, &count, NULL); VkExtensionProperties *props = new VkExtensionProperties[count]; GetInstanceDispatchTable(NULL)->EnumerateInstanceExtensionProperties(pLayerName, &count, props); for(uint32_t e = 0; e < count; e++) supportedExtensions.insert(props[e].extensionName); SAFE_DELETE_ARRAY(props); } std::set<string> supportedLayers; { uint32_t count = 0; GetInstanceDispatchTable(NULL)->EnumerateInstanceLayerProperties(&count, NULL); VkLayerProperties *props = new VkLayerProperties[count]; GetInstanceDispatchTable(NULL)->EnumerateInstanceLayerProperties(&count, props); for(uint32_t e = 0; e < count; e++) supportedLayers.insert(props[e].layerName); SAFE_DELETE_ARRAY(props); } AddRequiredExtensions(true, params.Extensions, supportedExtensions); if(supportedExtensions.find(VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME) == supportedExtensions.end()) { RDCWARN("Unsupported required instance extension for AMD performance counters '%s'", VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME); } else { if(std::find(params.Extensions.begin(), params.Extensions.end(), VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME) == params.Extensions.end()) params.Extensions.push_back(VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME); } // verify that extensions & layers are supported for(size_t i = 0; i < params.Layers.size(); i++) { if(supportedLayers.find(params.Layers[i]) == supportedLayers.end()) { RDCERR("Capture requires layer '%s' which is not supported", params.Layers[i].c_str()); return ReplayStatus::APIHardwareUnsupported; } } for(size_t i = 0; i < params.Extensions.size(); i++) { if(supportedExtensions.find(params.Extensions[i]) == supportedExtensions.end()) { RDCERR("Capture requires extension '%s' which is not supported", params.Extensions[i].c_str()); return ReplayStatus::APIHardwareUnsupported; } } // we always want this extension if it's available, and not already enabled if(supportedExtensions.find(VK_EXT_DEBUG_REPORT_EXTENSION_NAME) != supportedExtensions.end() && std::find(params.Extensions.begin(), params.Extensions.end(), VK_EXT_DEBUG_REPORT_EXTENSION_NAME) == params.Extensions.end()) { RDCLOG("Enabling VK_EXT_debug_report"); params.Extensions.push_back(VK_EXT_DEBUG_REPORT_EXTENSION_NAME); } const char **layerscstr = new const char *[params.Layers.size()]; for(size_t i = 0; i < params.Layers.size(); i++) layerscstr[i] = params.Layers[i].c_str(); const char **extscstr = new const char *[params.Extensions.size()]; for(size_t i = 0; i < params.Extensions.size(); i++) extscstr[i] = params.Extensions[i].c_str(); VkInstanceCreateInfo instinfo = { VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO, NULL, 0, &renderdocAppInfo, (uint32_t)params.Layers.size(), layerscstr, (uint32_t)params.Extensions.size(), extscstr, }; m_Instance = VK_NULL_HANDLE; VkResult ret = GetInstanceDispatchTable(NULL)->CreateInstance(&instinfo, NULL, &m_Instance); InstanceDeviceInfo extInfo; #undef CheckExt #define CheckExt(name) \ if(!strcmp(instinfo.ppEnabledExtensionNames[i], #name)) \ { \ extInfo.ext_##name = true; \ } for(uint32_t i = 0; i < instinfo.enabledExtensionCount; i++) { CheckInstanceExts(); } SAFE_DELETE_ARRAY(layerscstr); SAFE_DELETE_ARRAY(extscstr); if(ret != VK_SUCCESS) return ReplayStatus::APIHardwareUnsupported; RDCASSERTEQUAL(ret, VK_SUCCESS); GetResourceManager()->WrapResource(m_Instance, m_Instance); GetResourceManager()->AddLiveResource(params.InstanceID, m_Instance); // we'll add the chunk later when we re-process it. AddResource(params.InstanceID, ResourceType::Device, "Instance"); GetReplay()->GetResourceDesc(params.InstanceID).initialisationChunks.clear(); InitInstanceExtensionTables(m_Instance, &extInfo); m_DbgMsgCallback = VK_NULL_HANDLE; m_PhysicalDevice = VK_NULL_HANDLE; m_Device = VK_NULL_HANDLE; m_QueueFamilyIdx = ~0U; m_Queue = VK_NULL_HANDLE; m_InternalCmds.Reset(); if(ObjDisp(m_Instance)->CreateDebugReportCallbackEXT) { VkDebugReportCallbackCreateInfoEXT debugInfo = {}; debugInfo.sType = VK_STRUCTURE_TYPE_DEBUG_REPORT_CREATE_INFO_EXT; debugInfo.pNext = NULL; debugInfo.pfnCallback = &DebugCallbackStatic; debugInfo.pUserData = this; debugInfo.flags = VK_DEBUG_REPORT_WARNING_BIT_EXT | VK_DEBUG_REPORT_PERFORMANCE_WARNING_BIT_EXT | VK_DEBUG_REPORT_ERROR_BIT_EXT; ObjDisp(m_Instance) ->CreateDebugReportCallbackEXT(Unwrap(m_Instance), &debugInfo, NULL, &m_DbgMsgCallback); } uint32_t count = 0; VkResult vkr = ObjDisp(m_Instance)->EnumeratePhysicalDevices(Unwrap(m_Instance), &count, NULL); RDCASSERTEQUAL(vkr, VK_SUCCESS); m_ReplayPhysicalDevices.resize(count); m_ReplayPhysicalDevicesUsed.resize(count); m_OriginalPhysicalDevices.resize(count); m_MemIdxMaps.resize(count); vkr = ObjDisp(m_Instance) ->EnumeratePhysicalDevices(Unwrap(m_Instance), &count, &m_ReplayPhysicalDevices[0]); RDCASSERTEQUAL(vkr, VK_SUCCESS); for(uint32_t i = 0; i < count; i++) GetResourceManager()->WrapResource(m_Instance, m_ReplayPhysicalDevices[i]); return ReplayStatus::Succeeded; } VkResult WrappedVulkan::vkCreateInstance(const VkInstanceCreateInfo *pCreateInfo, const VkAllocationCallbacks *pAllocator, VkInstance *pInstance) { RDCASSERT(pCreateInfo); // don't support any extensions for this createinfo RDCASSERT(pCreateInfo->pApplicationInfo == NULL || pCreateInfo->pApplicationInfo->pNext == NULL); VkLayerInstanceCreateInfo *layerCreateInfo = (VkLayerInstanceCreateInfo *)pCreateInfo->pNext; // step through the chain of pNext until we get to the link info while(layerCreateInfo && (layerCreateInfo->sType != VK_STRUCTURE_TYPE_LOADER_INSTANCE_CREATE_INFO || layerCreateInfo->function != VK_LAYER_LINK_INFO)) { layerCreateInfo = (VkLayerInstanceCreateInfo *)layerCreateInfo->pNext; } RDCASSERT(layerCreateInfo); if(layerCreateInfo == NULL) { RDCERR("Couldn't find loader instance create info, which is required. Incompatible loader?"); return VK_ERROR_INITIALIZATION_FAILED; } PFN_vkGetInstanceProcAddr gpa = layerCreateInfo->u.pLayerInfo->pfnNextGetInstanceProcAddr; // move chain on for next layer layerCreateInfo->u.pLayerInfo = layerCreateInfo->u.pLayerInfo->pNext; PFN_vkCreateInstance createFunc = (PFN_vkCreateInstance)gpa(VK_NULL_HANDLE, "vkCreateInstance"); VkInstanceCreateInfo modifiedCreateInfo; modifiedCreateInfo = *pCreateInfo; for(uint32_t i = 0; i < modifiedCreateInfo.enabledExtensionCount; i++) { if(!IsSupportedExtension(modifiedCreateInfo.ppEnabledExtensionNames[i])) { RDCERR("RenderDoc does not support instance extension '%s'.", modifiedCreateInfo.ppEnabledExtensionNames[i]); RDCERR("File an issue on github to request support: https://github.com/baldurk/renderdoc"); // see if any debug report callbacks were passed in the pNext chain VkDebugReportCallbackCreateInfoEXT *report = (VkDebugReportCallbackCreateInfoEXT *)pCreateInfo->pNext; while(report) { if(report && report->sType == VK_STRUCTURE_TYPE_DEBUG_REPORT_CALLBACK_CREATE_INFO_EXT) report->pfnCallback(VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_INSTANCE_EXT, 0, 1, 1, "RDOC", "RenderDoc does not support a requested instance extension.", report->pUserData); report = (VkDebugReportCallbackCreateInfoEXT *)report->pNext; } return VK_ERROR_EXTENSION_NOT_PRESENT; } } const char **addedExts = new const char *[modifiedCreateInfo.enabledExtensionCount + 1]; bool hasDebugReport = false; for(uint32_t i = 0; i < modifiedCreateInfo.enabledExtensionCount; i++) { addedExts[i] = modifiedCreateInfo.ppEnabledExtensionNames[i]; if(!strcmp(addedExts[i], VK_EXT_DEBUG_REPORT_EXTENSION_NAME)) hasDebugReport = true; } // enumerate what instance extensions are available void *module = Process::LoadModule(VulkanLibraryName); PFN_vkEnumerateInstanceExtensionProperties enumInstExts = (PFN_vkEnumerateInstanceExtensionProperties)Process::GetFunctionAddress( module, "vkEnumerateInstanceExtensionProperties"); uint32_t numSupportedExts = 0; enumInstExts(NULL, &numSupportedExts, NULL); std::vector<VkExtensionProperties> supportedExts(numSupportedExts); enumInstExts(NULL, &numSupportedExts, &supportedExts[0]); // always enable debug report, if it's available if(!hasDebugReport) { for(const VkExtensionProperties &ext : supportedExts) { if(!strcmp(ext.extensionName, VK_EXT_DEBUG_REPORT_EXTENSION_NAME)) { addedExts[modifiedCreateInfo.enabledExtensionCount++] = VK_EXT_DEBUG_REPORT_EXTENSION_NAME; break; } } } modifiedCreateInfo.ppEnabledExtensionNames = addedExts; if(modifiedCreateInfo.pApplicationInfo) modifiedCreateInfo.pApplicationInfo = &renderdocAppInfo; VkResult ret = createFunc(&modifiedCreateInfo, pAllocator, pInstance); m_Instance = *pInstance; InitInstanceTable(m_Instance, gpa); GetResourceManager()->WrapResource(m_Instance, m_Instance); *pInstance = m_Instance; // should only be called during capture RDCASSERT(IsCaptureMode(m_State)); m_InitParams.Set(pCreateInfo, GetResID(m_Instance)); VkResourceRecord *record = GetResourceManager()->AddResourceRecord(m_Instance); record->instDevInfo = new InstanceDeviceInfo(); #undef CheckExt #define CheckExt(name) \ if(!strcmp(modifiedCreateInfo.ppEnabledExtensionNames[i], #name)) \ { \ record->instDevInfo->ext_##name = true; \ } for(uint32_t i = 0; i < modifiedCreateInfo.enabledExtensionCount; i++) { CheckInstanceExts(); } delete[] addedExts; InitInstanceExtensionTables(m_Instance, record->instDevInfo); RenderDoc::Inst().AddDeviceFrameCapturer(LayerDisp(m_Instance), this); m_DbgMsgCallback = VK_NULL_HANDLE; m_PhysicalDevice = VK_NULL_HANDLE; m_Device = VK_NULL_HANDLE; m_QueueFamilyIdx = ~0U; m_Queue = VK_NULL_HANDLE; m_InternalCmds.Reset(); if(ObjDisp(m_Instance)->CreateDebugReportCallbackEXT) { VkDebugReportCallbackCreateInfoEXT debugInfo = {}; debugInfo.sType = VK_STRUCTURE_TYPE_DEBUG_REPORT_CREATE_INFO_EXT; debugInfo.pNext = NULL; debugInfo.pfnCallback = &DebugCallbackStatic; debugInfo.pUserData = this; debugInfo.flags = VK_DEBUG_REPORT_WARNING_BIT_EXT | VK_DEBUG_REPORT_PERFORMANCE_WARNING_BIT_EXT | VK_DEBUG_REPORT_ERROR_BIT_EXT; ObjDisp(m_Instance) ->CreateDebugReportCallbackEXT(Unwrap(m_Instance), &debugInfo, NULL, &m_DbgMsgCallback); } if(ret == VK_SUCCESS) { RDCLOG("Initialised capture layer in Vulkan instance."); } return ret; } void WrappedVulkan::Shutdown() { // flush out any pending commands/semaphores SubmitCmds(); SubmitSemaphores(); FlushQ(); // destroy any events we created for waiting on for(size_t i = 0; i < m_PersistentEvents.size(); i++) ObjDisp(GetDev())->DestroyEvent(Unwrap(GetDev()), m_PersistentEvents[i], NULL); m_PersistentEvents.clear(); // since we didn't create proper registered resources for our command buffers, // they won't be taken down properly with the pool. So we release them (just our // data) here. for(size_t i = 0; i < m_InternalCmds.freecmds.size(); i++) GetResourceManager()->ReleaseWrappedResource(m_InternalCmds.freecmds[i]); // destroy the pool if(m_Device != VK_NULL_HANDLE && m_InternalCmds.cmdpool != VK_NULL_HANDLE) { ObjDisp(m_Device)->DestroyCommandPool(Unwrap(m_Device), Unwrap(m_InternalCmds.cmdpool), NULL); GetResourceManager()->ReleaseWrappedResource(m_InternalCmds.cmdpool); } for(size_t i = 0; i < m_InternalCmds.freesems.size(); i++) { ObjDisp(m_Device)->DestroySemaphore(Unwrap(m_Device), Unwrap(m_InternalCmds.freesems[i]), NULL); GetResourceManager()->ReleaseWrappedResource(m_InternalCmds.freesems[i]); } FreeAllMemory(MemoryScope::InitialContents); // we do more in Shutdown than the equivalent vkDestroyInstance since on replay there's // no explicit vkDestroyDevice, we destroy the device here then the instance // destroy the physical devices manually because due to remapping the may have leftover // refcounts for(size_t i = 0; i < m_ReplayPhysicalDevices.size(); i++) GetResourceManager()->ReleaseWrappedResource(m_ReplayPhysicalDevices[i]); m_Replay.DestroyResources(); // destroy debug manager and any objects it created SAFE_DELETE(m_DebugManager); SAFE_DELETE(m_ShaderCache); if(m_Instance && ObjDisp(m_Instance)->DestroyDebugReportCallbackEXT && m_DbgMsgCallback != VK_NULL_HANDLE) ObjDisp(m_Instance)->DestroyDebugReportCallbackEXT(Unwrap(m_Instance), m_DbgMsgCallback, NULL); // need to store the unwrapped device and instance to destroy the // API object after resource manager shutdown VkInstance inst = Unwrap(m_Instance); VkDevice dev = Unwrap(m_Device); const VkLayerDispatchTable *vt = m_Device != VK_NULL_HANDLE ? ObjDisp(m_Device) : NULL; const VkLayerInstanceDispatchTable *vit = m_Instance != VK_NULL_HANDLE ? ObjDisp(m_Instance) : NULL; // this destroys the wrapped objects for the devices and instances m_ResourceManager->Shutdown(); delete GetWrapped(m_Device); delete GetWrapped(m_Instance); m_PhysicalDevice = VK_NULL_HANDLE; m_Device = VK_NULL_HANDLE; m_Instance = VK_NULL_HANDLE; m_ReplayPhysicalDevices.clear(); m_PhysicalDevices.clear(); for(size_t i = 0; i < m_QueueFamilies.size(); i++) delete[] m_QueueFamilies[i]; m_QueueFamilies.clear(); // finally destroy device then instance if(vt) vt->DestroyDevice(dev, NULL); if(vit) vit->DestroyInstance(inst, NULL); } void WrappedVulkan::vkDestroyInstance(VkInstance instance, const VkAllocationCallbacks *pAllocator) { RDCASSERT(m_Instance == instance); if(ObjDisp(m_Instance)->DestroyDebugReportCallbackEXT && m_DbgMsgCallback != VK_NULL_HANDLE) ObjDisp(m_Instance)->DestroyDebugReportCallbackEXT(Unwrap(m_Instance), m_DbgMsgCallback, NULL); // the device should already have been destroyed, assuming that the // application is well behaved. If not, we just leak. ObjDisp(m_Instance)->DestroyInstance(Unwrap(m_Instance), NULL); GetResourceManager()->ReleaseWrappedResource(m_Instance); RenderDoc::Inst().RemoveDeviceFrameCapturer(LayerDisp(m_Instance)); m_Instance = VK_NULL_HANDLE; } template <typename SerialiserType> bool WrappedVulkan::Serialise_vkEnumeratePhysicalDevices(SerialiserType &ser, VkInstance instance, uint32_t *pPhysicalDeviceCount, VkPhysicalDevice *pPhysicalDevices) { SERIALISE_ELEMENT(instance); SERIALISE_ELEMENT_LOCAL(PhysicalDeviceIndex, *pPhysicalDeviceCount); SERIALISE_ELEMENT_LOCAL(PhysicalDevice, GetResID(*pPhysicalDevices)).TypedAs("VkPhysicalDevice"); uint32_t memIdxMap[VK_MAX_MEMORY_TYPES] = {0}; // not used at the moment but useful for reference and might be used // in the future VkPhysicalDeviceProperties physProps; VkPhysicalDeviceMemoryProperties memProps; VkPhysicalDeviceFeatures physFeatures; uint32_t queueCount = 0; VkQueueFamilyProperties queueProps[16]; if(ser.IsWriting()) { memcpy(memIdxMap, GetRecord(*pPhysicalDevices)->memIdxMap, sizeof(memIdxMap)); ObjDisp(instance)->GetPhysicalDeviceProperties(Unwrap(*pPhysicalDevices), &physProps); ObjDisp(instance)->GetPhysicalDeviceMemoryProperties(Unwrap(*pPhysicalDevices), &memProps); ObjDisp(instance)->GetPhysicalDeviceFeatures(Unwrap(*pPhysicalDevices), &physFeatures); ObjDisp(instance)->GetPhysicalDeviceQueueFamilyProperties(Unwrap(*pPhysicalDevices), &queueCount, NULL); if(queueCount > 16) { RDCWARN("More than 16 queues"); queueCount = 16; } ObjDisp(instance)->GetPhysicalDeviceQueueFamilyProperties(Unwrap(*pPhysicalDevices), &queueCount, queueProps); } SERIALISE_ELEMENT(memIdxMap); SERIALISE_ELEMENT(physProps); SERIALISE_ELEMENT(memProps); SERIALISE_ELEMENT(physFeatures); SERIALISE_ELEMENT(queueCount); SERIALISE_ELEMENT(queueProps); VkPhysicalDevice pd = VK_NULL_HANDLE; SERIALISE_CHECK_READ_ERRORS(); if(IsReplayingAndReading()) { { VkDriverInfo capturedVersion(physProps); RDCLOG("Capture describes physical device %u:", PhysicalDeviceIndex); RDCLOG(" - %s (ver %u.%u patch 0x%x) - %04x:%04x", physProps.deviceName, capturedVersion.Major(), capturedVersion.Minor(), capturedVersion.Patch(), physProps.vendorID, physProps.deviceID); if(PhysicalDeviceIndex >= m_OriginalPhysicalDevices.size()) m_OriginalPhysicalDevices.resize(PhysicalDeviceIndex + 1); m_OriginalPhysicalDevices[PhysicalDeviceIndex].props = physProps; m_OriginalPhysicalDevices[PhysicalDeviceIndex].memProps = memProps; m_OriginalPhysicalDevices[PhysicalDeviceIndex].features = physFeatures; } // match up physical devices to those available on replay as best as possible. In general // hopefully the most common case is when there's a precise match, and maybe the order changed. // // If more GPUs were present on replay than during capture, we map many-to-one which might have // bad side-effects as e.g. we have to pick one memidxmap, but this is as good as we can do. uint32_t bestIdx = 0; VkPhysicalDeviceProperties bestPhysProps; VkPhysicalDeviceMemoryProperties bestMemProps; pd = m_ReplayPhysicalDevices[bestIdx]; ObjDisp(pd)->GetPhysicalDeviceProperties(Unwrap(pd), &bestPhysProps); ObjDisp(pd)->GetPhysicalDeviceMemoryProperties(Unwrap(pd), &bestMemProps); for(uint32_t i = 1; i < (uint32_t)m_ReplayPhysicalDevices.size(); i++) { VkPhysicalDeviceProperties compPhysProps; VkPhysicalDeviceMemoryProperties compMemProps; pd = m_ReplayPhysicalDevices[i]; // find the best possible match for this physical device ObjDisp(pd)->GetPhysicalDeviceProperties(Unwrap(pd), &compPhysProps); ObjDisp(pd)->GetPhysicalDeviceMemoryProperties(Unwrap(pd), &compMemProps); // an exact vendorID match is a better match than not if(compPhysProps.vendorID == physProps.vendorID && bestPhysProps.vendorID != physProps.vendorID) { bestIdx = i; bestPhysProps = compPhysProps; bestMemProps = compMemProps; continue; } else if(compPhysProps.vendorID != physProps.vendorID) { continue; } // ditto deviceID if(compPhysProps.deviceID == physProps.deviceID && bestPhysProps.deviceID != physProps.deviceID) { bestIdx = i; bestPhysProps = compPhysProps; bestMemProps = compMemProps; continue; } else if(compPhysProps.deviceID != physProps.deviceID) { continue; } // if we have multiple identical devices, which isn't uncommon, favour the one // that hasn't been assigned if(m_ReplayPhysicalDevicesUsed[bestIdx] && !m_ReplayPhysicalDevicesUsed[i]) { bestIdx = i; bestPhysProps = compPhysProps; bestMemProps = compMemProps; continue; } // this device isn't any better, ignore it } { VkDriverInfo runningVersion(bestPhysProps); RDCLOG("Mapping during replay to physical device %u:", bestIdx); RDCLOG(" - %s (ver %u.%u patch 0x%x) - %04x:%04x", bestPhysProps.deviceName, runningVersion.Major(), runningVersion.Minor(), runningVersion.Patch(), bestPhysProps.vendorID, bestPhysProps.deviceID); } pd = m_ReplayPhysicalDevices[bestIdx]; if(!m_ReplayPhysicalDevicesUsed[bestIdx]) GetResourceManager()->AddLiveResource(PhysicalDevice, pd); else GetResourceManager()->ReplaceResource(PhysicalDevice, GetResourceManager()->GetOriginalID(GetResID(pd))); AddResource(PhysicalDevice, ResourceType::Device, "Physical Device"); DerivedResource(m_Instance, PhysicalDevice); if(PhysicalDeviceIndex >= m_PhysicalDevices.size()) m_PhysicalDevices.resize(PhysicalDeviceIndex + 1); m_PhysicalDevices[PhysicalDeviceIndex] = pd; if(m_ReplayPhysicalDevicesUsed[bestIdx]) { // error if we're remapping multiple physical devices to the same best match RDCERR( "Mapping multiple capture-time physical devices to a single replay-time physical device." "This means the HW has changed between capture and replay and may cause bugs."); } else if(m_MemIdxMaps[bestIdx] == NULL) { // the first physical device 'wins' for the memory index map uint32_t *storedMap = new uint32_t[32]; memcpy(storedMap, memIdxMap, sizeof(memIdxMap)); for(uint32_t i = 0; i < 32; i++) storedMap[i] = i; m_MemIdxMaps[bestIdx] = storedMap; } m_ReplayPhysicalDevicesUsed[bestIdx] = true; } return true; } VkResult WrappedVulkan::vkEnumeratePhysicalDevices(VkInstance instance, uint32_t *pPhysicalDeviceCount, VkPhysicalDevice *pPhysicalDevices) { uint32_t count; VkResult vkr = ObjDisp(instance)->EnumeratePhysicalDevices(Unwrap(instance), &count, NULL); if(vkr != VK_SUCCESS) return vkr; VkPhysicalDevice *devices = new VkPhysicalDevice[count]; SERIALISE_TIME_CALL( vkr = ObjDisp(instance)->EnumeratePhysicalDevices(Unwrap(instance), &count, devices)); RDCASSERTEQUAL(vkr, VK_SUCCESS); m_PhysicalDevices.resize(count); m_SupportedQueueFamilies.resize(count); for(uint32_t i = 0; i < count; i++) { // it's perfectly valid for enumerate type functions to return the same handle // each time. If that happens, we will already have a wrapper created so just // return the wrapped object to the user and do nothing else if(m_PhysicalDevices[i] != VK_NULL_HANDLE) { GetWrapped(m_PhysicalDevices[i])->RewrapObject(devices[i]); devices[i] = m_PhysicalDevices[i]; } else { GetResourceManager()->WrapResource(instance, devices[i]); if(IsCaptureMode(m_State)) { // add the record first since it's used in the serialise function below to fetch // the memory indices VkResourceRecord *record = GetResourceManager()->AddResourceRecord(devices[i]); RDCASSERT(record); record->memProps = new VkPhysicalDeviceMemoryProperties(); ObjDisp(devices[i])->GetPhysicalDeviceMemoryProperties(Unwrap(devices[i]), record->memProps); m_PhysicalDevices[i] = devices[i]; // we remap memory indices to discourage coherent maps as much as possible RemapMemoryIndices(record->memProps, &record->memIdxMap); { CACHE_THREAD_SERIALISER(); SCOPED_SERIALISE_CHUNK(VulkanChunk::vkEnumeratePhysicalDevices); Serialise_vkEnumeratePhysicalDevices(ser, instance, &i, &devices[i]); record->AddChunk(scope.Get()); } VkResourceRecord *instrecord = GetRecord(instance); instrecord->AddParent(record); // treat physical devices as pool members of the instance (ie. freed when the instance dies) { instrecord->LockChunks(); instrecord->pooledChildren.push_back(record); instrecord->UnlockChunks(); } } } // find the queue with the most bits set and only report that one { uint32_t queuecount = 0; ObjDisp(m_PhysicalDevices[i]) ->GetPhysicalDeviceQueueFamilyProperties(Unwrap(m_PhysicalDevices[i]), &queuecount, NULL); VkQueueFamilyProperties *props = new VkQueueFamilyProperties[queuecount]; ObjDisp(m_PhysicalDevices[i]) ->GetPhysicalDeviceQueueFamilyProperties(Unwrap(m_PhysicalDevices[i]), &queuecount, props); uint32_t best = 0; // don't need to explicitly check for transfer, because graphics bit // implies it. We do have to check for compute bit, because there might // be a graphics only queue - it just means we have to keep looking // to find the grpahics & compute queue family which is guaranteed. for(uint32_t q = 1; q < queuecount; q++) { // compare current against the known best VkQueueFamilyProperties &currentProps = props[q]; VkQueueFamilyProperties &bestProps = props[best]; const bool currentGraphics = (currentProps.queueFlags & VK_QUEUE_GRAPHICS_BIT) != 0; const bool currentCompute = (currentProps.queueFlags & VK_QUEUE_COMPUTE_BIT) != 0; const bool currentSparse = (currentProps.queueFlags & VK_QUEUE_SPARSE_BINDING_BIT) != 0; const bool bestGraphics = (bestProps.queueFlags & VK_QUEUE_GRAPHICS_BIT) != 0; const bool bestCompute = (bestProps.queueFlags & VK_QUEUE_COMPUTE_BIT) != 0; const bool bestSparse = (bestProps.queueFlags & VK_QUEUE_SPARSE_BINDING_BIT) != 0; // if one has graphics bit set, but the other doesn't if(currentGraphics != bestGraphics) { // if current has graphics but best doesn't, we have a new best if(currentGraphics) best = q; continue; } if(currentCompute != bestCompute) { // if current has compute but best doesn't, we have a new best if(currentCompute) best = q; continue; } // if we've gotten here, both best and current have graphics and compute. Check // to see if the current is somehow better than best (in the case of a tie, we // keep the lower index of queue). if(currentSparse != bestSparse) { if(currentSparse) best = q; continue; } if(currentProps.timestampValidBits != bestProps.timestampValidBits) { if(currentProps.timestampValidBits > bestProps.timestampValidBits) best = q; continue; } if(currentProps.minImageTransferGranularity.width < bestProps.minImageTransferGranularity.width || currentProps.minImageTransferGranularity.height < bestProps.minImageTransferGranularity.height || currentProps.minImageTransferGranularity.depth < bestProps.minImageTransferGranularity.depth) { best = q; continue; } } // only report a single available queue in this family props[best].queueCount = 1; m_SupportedQueueFamilies[i] = std::make_pair(best, props[best]); SAFE_DELETE_ARRAY(props); } } if(pPhysicalDeviceCount) *pPhysicalDeviceCount = count; if(pPhysicalDevices) memcpy(pPhysicalDevices, devices, count * sizeof(VkPhysicalDevice)); SAFE_DELETE_ARRAY(devices); return VK_SUCCESS; } template <typename SerialiserType> bool WrappedVulkan::Serialise_vkCreateDevice(SerialiserType &ser, VkPhysicalDevice physicalDevice, const VkDeviceCreateInfo *pCreateInfo, const VkAllocationCallbacks *pAllocator, VkDevice *pDevice) { SERIALISE_ELEMENT(physicalDevice); SERIALISE_ELEMENT_LOCAL(CreateInfo, *pCreateInfo); SERIALISE_ELEMENT_OPT(pAllocator); SERIALISE_ELEMENT_LOCAL(Device, GetResID(*pDevice)).TypedAs("VkDevice"); SERIALISE_ELEMENT(m_SupportedQueueFamily).Hidden(); SERIALISE_CHECK_READ_ERRORS(); if(IsReplayingAndReading()) { // we must make any modifications locally, so the free of pointers // in the serialised VkDeviceCreateInfo don't double-free VkDeviceCreateInfo createInfo = CreateInfo; std::vector<string> Extensions; for(uint32_t i = 0; i < createInfo.enabledExtensionCount; i++) { // don't include the debug marker extension if(!strcmp(createInfo.ppEnabledExtensionNames[i], VK_EXT_DEBUG_MARKER_EXTENSION_NAME)) continue; // don't include direct-display WSI extensions if(!strcmp(createInfo.ppEnabledExtensionNames[i], VK_KHR_DISPLAY_SWAPCHAIN_EXTENSION_NAME) || !strcmp(createInfo.ppEnabledExtensionNames[i], VK_EXT_DISPLAY_CONTROL_EXTENSION_NAME)) continue; Extensions.push_back(createInfo.ppEnabledExtensionNames[i]); } if(std::find(Extensions.begin(), Extensions.end(), VK_AMD_NEGATIVE_VIEWPORT_HEIGHT_EXTENSION_NAME) != Extensions.end()) m_ExtensionsEnabled[VkCheckExt_AMD_neg_viewport] = true; std::vector<string> Layers; for(uint32_t i = 0; i < createInfo.enabledLayerCount; i++) Layers.push_back(createInfo.ppEnabledLayerNames[i]); StripUnwantedLayers(Layers); std::set<string> supportedExtensions; for(size_t i = 0; i <= Layers.size(); i++) { const char *pLayerName = (i == 0 ? NULL : Layers[i - 1].c_str()); uint32_t count = 0; ObjDisp(physicalDevice) ->EnumerateDeviceExtensionProperties(Unwrap(physicalDevice), pLayerName, &count, NULL); VkExtensionProperties *props = new VkExtensionProperties[count]; ObjDisp(physicalDevice) ->EnumerateDeviceExtensionProperties(Unwrap(physicalDevice), pLayerName, &count, props); for(uint32_t e = 0; e < count; e++) supportedExtensions.insert(props[e].extensionName); SAFE_DELETE_ARRAY(props); } AddRequiredExtensions(false, Extensions, supportedExtensions); // enable VK_EXT_debug_marker if it's available, to replay markers to the driver/any other // layers that might be listening if(supportedExtensions.find(VK_EXT_DEBUG_MARKER_EXTENSION_NAME) != supportedExtensions.end()) { Extensions.push_back(VK_EXT_DEBUG_MARKER_EXTENSION_NAME); RDCLOG("Enabling VK_EXT_debug_marker"); } // enable VK_EXT_debug_marker if it's available, to fetch shader disassembly if(supportedExtensions.find(VK_AMD_SHADER_INFO_EXTENSION_NAME) != supportedExtensions.end()) { Extensions.push_back(VK_AMD_SHADER_INFO_EXTENSION_NAME); RDCLOG("Enabling VK_AMD_shader_info"); } createInfo.enabledLayerCount = (uint32_t)Layers.size(); const char **layerArray = NULL; if(!Layers.empty()) { layerArray = new const char *[createInfo.enabledLayerCount]; for(uint32_t i = 0; i < createInfo.enabledLayerCount; i++) layerArray[i] = Layers[i].c_str(); createInfo.ppEnabledLayerNames = layerArray; } createInfo.enabledExtensionCount = (uint32_t)Extensions.size(); const char **extArray = NULL; if(!Extensions.empty()) { extArray = new const char *[createInfo.enabledExtensionCount]; for(uint32_t i = 0; i < createInfo.enabledExtensionCount; i++) { if(supportedExtensions.find(Extensions[i]) == supportedExtensions.end()) { m_FailedReplayStatus = ReplayStatus::APIHardwareUnsupported; RDCERR("Capture requires extension '%s' which is not supported", Extensions[i].c_str()); return false; } extArray[i] = Extensions[i].c_str(); } createInfo.ppEnabledExtensionNames = extArray; } VkDevice device; uint32_t qCount = 0; ObjDisp(physicalDevice)->GetPhysicalDeviceQueueFamilyProperties(Unwrap(physicalDevice), &qCount, NULL); VkQueueFamilyProperties *props = new VkQueueFamilyProperties[qCount]; ObjDisp(physicalDevice) ->GetPhysicalDeviceQueueFamilyProperties(Unwrap(physicalDevice), &qCount, props); bool found = false; uint32_t qFamilyIdx = 0; VkQueueFlags search = (VK_QUEUE_GRAPHICS_BIT); // for queue priorities, if we need it float one = 1.0f; // if we need to change the requested queues, it will point to this VkDeviceQueueCreateInfo *modQueues = NULL; for(uint32_t i = 0; i < createInfo.queueCreateInfoCount; i++) { uint32_t idx = createInfo.pQueueCreateInfos[i].queueFamilyIndex; RDCASSERT(idx < qCount); // this requested queue is one we can use too if((props[idx].queueFlags & search) == search && createInfo.pQueueCreateInfos[i].queueCount > 0) { qFamilyIdx = idx; found = true; break; } } // if we didn't find it, search for which queue family we should add a request for if(!found) { RDCDEBUG("App didn't request a queue family we can use - adding our own"); for(uint32_t i = 0; i < qCount; i++) { if((props[i].queueFlags & search) == search) { qFamilyIdx = i; found = true; break; } } if(!found) { SAFE_DELETE_ARRAY(props); RDCERR( "Can't add a queue with required properties for RenderDoc! Unsupported configuration"); } else { // we found the queue family, add it modQueues = new VkDeviceQueueCreateInfo[createInfo.queueCreateInfoCount + 1]; for(uint32_t i = 0; i < createInfo.queueCreateInfoCount; i++) modQueues[i] = createInfo.pQueueCreateInfos[i]; modQueues[createInfo.queueCreateInfoCount].queueFamilyIndex = qFamilyIdx; modQueues[createInfo.queueCreateInfoCount].queueCount = 1; modQueues[createInfo.queueCreateInfoCount].pQueuePriorities = &one; createInfo.pQueueCreateInfos = modQueues; createInfo.queueCreateInfoCount++; } } SAFE_DELETE_ARRAY(props); VkPhysicalDeviceFeatures enabledFeatures = {0}; if(createInfo.pEnabledFeatures != NULL) enabledFeatures = *createInfo.pEnabledFeatures; createInfo.pEnabledFeatures = &enabledFeatures; VkPhysicalDeviceFeatures availFeatures = {0}; ObjDisp(physicalDevice)->GetPhysicalDeviceFeatures(Unwrap(physicalDevice), &availFeatures); if(availFeatures.depthClamp) enabledFeatures.depthClamp = true; else RDCWARN( "depthClamp = false, overlays like highlight drawcall won't show depth-clipped pixels."); if(availFeatures.fillModeNonSolid) enabledFeatures.fillModeNonSolid = true; // we have a fallback for this case, so no warning if(availFeatures.geometryShader) enabledFeatures.geometryShader = true; else RDCWARN( "geometryShader = false, lit mesh rendering will not be available if rendering on this " "device."); if(availFeatures.robustBufferAccess) enabledFeatures.robustBufferAccess = true; else RDCWARN( "robustBufferAccess = false, out of bounds access due to bugs in application or " "RenderDoc may cause crashes"); if(availFeatures.shaderStorageImageWriteWithoutFormat) enabledFeatures.shaderStorageImageWriteWithoutFormat = true; else RDCWARN( "shaderStorageImageWriteWithoutFormat = false, save/load from 2DMS textures will not be " "possible"); if(availFeatures.shaderStorageImageMultisample) enabledFeatures.shaderStorageImageMultisample = true; else RDCWARN( "shaderStorageImageMultisample = false, save/load from 2DMS textures will not be " "possible"); if(availFeatures.sampleRateShading) enabledFeatures.sampleRateShading = true; else RDCWARN( "sampleRateShading = false, save/load from depth 2DMS textures will not be " "possible"); uint32_t numExts = 0; VkResult vkr = ObjDisp(physicalDevice) ->EnumerateDeviceExtensionProperties(Unwrap(physicalDevice), NULL, &numExts, NULL); RDCASSERTEQUAL(vkr, VK_SUCCESS); VkExtensionProperties *exts = new VkExtensionProperties[numExts]; vkr = ObjDisp(physicalDevice) ->EnumerateDeviceExtensionProperties(Unwrap(physicalDevice), NULL, &numExts, exts); RDCASSERTEQUAL(vkr, VK_SUCCESS); for(uint32_t i = 0; i < numExts; i++) RDCLOG("Ext %u: %s (%u)", i, exts[i].extensionName, exts[i].specVersion); SAFE_DELETE_ARRAY(exts); // PORTABILITY check that extensions and layers supported in capture (from createInfo) are // supported in replay vkr = GetDeviceDispatchTable(NULL)->CreateDevice(Unwrap(physicalDevice), &createInfo, NULL, &device); RDCASSERTEQUAL(vkr, VK_SUCCESS); GetResourceManager()->WrapResource(device, device); GetResourceManager()->AddLiveResource(Device, device); AddResource(Device, ResourceType::Device, "Device"); DerivedResource(physicalDevice, Device); InstanceDeviceInfo extInfo; #undef CheckExt #define CheckExt(name) \ if(!strcmp(createInfo.ppEnabledExtensionNames[i], #name)) \ { \ extInfo.ext_##name = true; \ } for(uint32_t i = 0; i < createInfo.enabledExtensionCount; i++) { CheckDeviceExts(); } InitDeviceExtensionTables(device, &extInfo); RDCASSERT(m_Device == VK_NULL_HANDLE); // MULTIDEVICE m_PhysicalDevice = physicalDevice; m_Device = device; m_QueueFamilyIdx = qFamilyIdx; if(m_InternalCmds.cmdpool == VK_NULL_HANDLE) { VkCommandPoolCreateInfo poolInfo = {VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO, NULL, VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT, qFamilyIdx}; vkr = ObjDisp(device)->CreateCommandPool(Unwrap(device), &poolInfo, NULL, &m_InternalCmds.cmdpool); RDCASSERTEQUAL(vkr, VK_SUCCESS); GetResourceManager()->WrapResource(Unwrap(device), m_InternalCmds.cmdpool); } ObjDisp(physicalDevice) ->GetPhysicalDeviceProperties(Unwrap(physicalDevice), &m_PhysicalDeviceData.props); ObjDisp(physicalDevice) ->GetPhysicalDeviceMemoryProperties(Unwrap(physicalDevice), &m_PhysicalDeviceData.memProps); ObjDisp(physicalDevice) ->GetPhysicalDeviceFeatures(Unwrap(physicalDevice), &m_PhysicalDeviceData.features); for(int i = VK_FORMAT_BEGIN_RANGE + 1; i < VK_FORMAT_END_RANGE; i++) ObjDisp(physicalDevice) ->GetPhysicalDeviceFormatProperties(Unwrap(physicalDevice), VkFormat(i), &m_PhysicalDeviceData.fmtprops[i]); m_PhysicalDeviceData.readbackMemIndex = m_PhysicalDeviceData.GetMemoryIndex(~0U, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT, 0); m_PhysicalDeviceData.uploadMemIndex = m_PhysicalDeviceData.GetMemoryIndex(~0U, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT, 0); m_PhysicalDeviceData.GPULocalMemIndex = m_PhysicalDeviceData.GetMemoryIndex( ~0U, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT); for(size_t i = 0; i < m_PhysicalDevices.size(); i++) { if(physicalDevice == m_PhysicalDevices[i]) { m_PhysicalDeviceData.memIdxMap = m_MemIdxMaps[i]; break; } } APIProps.vendor = GetDriverVersion().Vendor(); m_ShaderCache = new VulkanShaderCache(this); m_DebugManager = new VulkanDebugManager(this); m_Replay.CreateResources(); SAFE_DELETE_ARRAY(modQueues); SAFE_DELETE_ARRAY(layerArray); SAFE_DELETE_ARRAY(extArray); } return true; } VkResult WrappedVulkan::vkCreateDevice(VkPhysicalDevice physicalDevice, const VkDeviceCreateInfo *pCreateInfo, const VkAllocationCallbacks *pAllocator, VkDevice *pDevice) { VkDeviceCreateInfo createInfo = *pCreateInfo; uint32_t qCount = 0; VkResult vkr = VK_SUCCESS; ObjDisp(physicalDevice)->GetPhysicalDeviceQueueFamilyProperties(Unwrap(physicalDevice), &qCount, NULL); VkQueueFamilyProperties *props = new VkQueueFamilyProperties[qCount]; ObjDisp(physicalDevice)->GetPhysicalDeviceQueueFamilyProperties(Unwrap(physicalDevice), &qCount, props); // find a queue that supports all capabilities, and if one doesn't exist, add it. bool found = false; uint32_t qFamilyIdx = 0; VkQueueFlags search = (VK_QUEUE_GRAPHICS_BIT); // for queue priorities, if we need it float one = 1.0f; // if we need to change the requested queues, it will point to this VkDeviceQueueCreateInfo *modQueues = NULL; for(uint32_t i = 0; i < createInfo.queueCreateInfoCount; i++) { uint32_t idx = createInfo.pQueueCreateInfos[i].queueFamilyIndex; RDCASSERT(idx < qCount); // this requested queue is one we can use too if((props[idx].queueFlags & search) == search && createInfo.pQueueCreateInfos[i].queueCount > 0) { qFamilyIdx = idx; found = true; break; } } // if we didn't find it, search for which queue family we should add a request for if(!found) { RDCDEBUG("App didn't request a queue family we can use - adding our own"); for(uint32_t i = 0; i < qCount; i++) { if((props[i].queueFlags & search) == search) { qFamilyIdx = i; found = true; break; } } if(!found) { SAFE_DELETE_ARRAY(props); RDCERR("Can't add a queue with required properties for RenderDoc! Unsupported configuration"); return VK_ERROR_INITIALIZATION_FAILED; } // we found the queue family, add it modQueues = new VkDeviceQueueCreateInfo[createInfo.queueCreateInfoCount + 1]; for(uint32_t i = 0; i < createInfo.queueCreateInfoCount; i++) modQueues[i] = createInfo.pQueueCreateInfos[i]; modQueues[createInfo.queueCreateInfoCount].queueFamilyIndex = qFamilyIdx; modQueues[createInfo.queueCreateInfoCount].queueCount = 1; modQueues[createInfo.queueCreateInfoCount].pQueuePriorities = &one; createInfo.pQueueCreateInfos = modQueues; createInfo.queueCreateInfoCount++; } SAFE_DELETE_ARRAY(props); m_QueueFamilies.resize(createInfo.queueCreateInfoCount); for(size_t i = 0; i < createInfo.queueCreateInfoCount; i++) { uint32_t family = createInfo.pQueueCreateInfos[i].queueFamilyIndex; uint32_t count = createInfo.pQueueCreateInfos[i].queueCount; m_QueueFamilies.resize(RDCMAX(m_QueueFamilies.size(), size_t(family + 1))); m_QueueFamilies[family] = new VkQueue[count]; for(uint32_t q = 0; q < count; q++) m_QueueFamilies[family][q] = VK_NULL_HANDLE; } // find the matching physical device for(size_t i = 0; i < m_PhysicalDevices.size(); i++) if(m_PhysicalDevices[i] == physicalDevice) m_SupportedQueueFamily = m_SupportedQueueFamilies[i].first; VkLayerDeviceCreateInfo *layerCreateInfo = (VkLayerDeviceCreateInfo *)pCreateInfo->pNext; // step through the chain of pNext until we get to the link info while(layerCreateInfo && (layerCreateInfo->sType != VK_STRUCTURE_TYPE_LOADER_DEVICE_CREATE_INFO || layerCreateInfo->function != VK_LAYER_LINK_INFO)) { layerCreateInfo = (VkLayerDeviceCreateInfo *)layerCreateInfo->pNext; } RDCASSERT(layerCreateInfo); if(layerCreateInfo == NULL) { RDCERR("Couldn't find loader device create info, which is required. Incompatible loader?"); return VK_ERROR_INITIALIZATION_FAILED; } PFN_vkGetDeviceProcAddr gdpa = layerCreateInfo->u.pLayerInfo->pfnNextGetDeviceProcAddr; PFN_vkGetInstanceProcAddr gipa = layerCreateInfo->u.pLayerInfo->pfnNextGetInstanceProcAddr; // move chain on for next layer layerCreateInfo->u.pLayerInfo = layerCreateInfo->u.pLayerInfo->pNext; PFN_vkCreateDevice createFunc = (PFN_vkCreateDevice)gipa(VK_NULL_HANDLE, "vkCreateDevice"); // now search again through for the loader data callback (if it exists) layerCreateInfo = (VkLayerDeviceCreateInfo *)pCreateInfo->pNext; // step through the chain of pNext while(layerCreateInfo && (layerCreateInfo->sType != VK_STRUCTURE_TYPE_LOADER_DEVICE_CREATE_INFO || layerCreateInfo->function != VK_LOADER_DATA_CALLBACK)) { layerCreateInfo = (VkLayerDeviceCreateInfo *)layerCreateInfo->pNext; } // if we found one (we might not - on old loaders), then store the func ptr for // use instead of SetDispatchTableOverMagicNumber if(layerCreateInfo) { RDCASSERT(m_SetDeviceLoaderData == layerCreateInfo->u.pfnSetDeviceLoaderData || m_SetDeviceLoaderData == NULL, (void *)m_SetDeviceLoaderData, (void *)layerCreateInfo->u.pfnSetDeviceLoaderData); m_SetDeviceLoaderData = layerCreateInfo->u.pfnSetDeviceLoaderData; } // patch enabled features VkPhysicalDeviceFeatures availFeatures; ObjDisp(physicalDevice)->GetPhysicalDeviceFeatures(Unwrap(physicalDevice), &availFeatures); // default to all off. This is equivalent to createInfo.pEnabledFeatures == NULL VkPhysicalDeviceFeatures enabledFeatures = {0}; // if the user enabled features, of course we want to enable them. if(createInfo.pEnabledFeatures) enabledFeatures = *createInfo.pEnabledFeatures; if(availFeatures.shaderStorageImageWriteWithoutFormat) enabledFeatures.shaderStorageImageWriteWithoutFormat = true; else RDCWARN( "shaderStorageImageWriteWithoutFormat = false, save/load from 2DMS textures will not be " "possible"); if(availFeatures.shaderStorageImageMultisample) enabledFeatures.shaderStorageImageMultisample = true; else RDCWARN( "shaderStorageImageMultisample = false, save/load from 2DMS textures will not be " "possible"); if(availFeatures.sampleRateShading) enabledFeatures.sampleRateShading = true; else RDCWARN( "sampleRateShading = false, save/load from depth 2DMS textures will not be " "possible"); if(availFeatures.occlusionQueryPrecise) enabledFeatures.occlusionQueryPrecise = true; else RDCWARN("occlusionQueryPrecise = false, samples written counter will not work"); if(availFeatures.pipelineStatisticsQuery) enabledFeatures.pipelineStatisticsQuery = true; else RDCWARN("pipelineStatisticsQuery = false, pipeline counters will not work"); createInfo.pEnabledFeatures = &enabledFeatures; VkResult ret; SERIALISE_TIME_CALL(ret = createFunc(Unwrap(physicalDevice), &createInfo, pAllocator, pDevice)); // don't serialise out any of the pNext stuff for layer initialisation // (note that we asserted above that there was nothing else in the chain) createInfo.pNext = NULL; if(ret == VK_SUCCESS) { InitDeviceTable(*pDevice, gdpa); ResourceId id = GetResourceManager()->WrapResource(*pDevice, *pDevice); if(IsCaptureMode(m_State)) { Chunk *chunk = NULL; { CACHE_THREAD_SERIALISER(); SCOPED_SERIALISE_CHUNK(VulkanChunk::vkCreateDevice); Serialise_vkCreateDevice(ser, physicalDevice, &createInfo, NULL, pDevice); chunk = scope.Get(); } VkResourceRecord *record = GetResourceManager()->AddResourceRecord(*pDevice); RDCASSERT(record); record->AddChunk(chunk); record->memIdxMap = GetRecord(physicalDevice)->memIdxMap; record->instDevInfo = new InstanceDeviceInfo(); #undef CheckExt #define CheckExt(name) \ record->instDevInfo->ext_##name = GetRecord(m_Instance)->instDevInfo->ext_##name; // inherit extension enablement from instance, that way GetDeviceProcAddress can check // for enabled extensions for instance functions CheckInstanceExts(); #undef CheckExt #define CheckExt(name) \ if(!strcmp(createInfo.ppEnabledExtensionNames[i], #name)) \ { \ record->instDevInfo->ext_##name = true; \ } for(uint32_t i = 0; i < createInfo.enabledExtensionCount; i++) { CheckDeviceExts(); } InitDeviceExtensionTables(*pDevice, record->instDevInfo); } else { GetResourceManager()->AddLiveResource(id, *pDevice); } VkDevice device = *pDevice; RDCASSERT(m_Device == VK_NULL_HANDLE); // MULTIDEVICE m_PhysicalDevice = physicalDevice; m_Device = device; m_QueueFamilyIdx = qFamilyIdx; if(m_InternalCmds.cmdpool == VK_NULL_HANDLE) { VkCommandPoolCreateInfo poolInfo = {VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO, NULL, VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT, qFamilyIdx}; vkr = ObjDisp(device)->CreateCommandPool(Unwrap(device), &poolInfo, NULL, &m_InternalCmds.cmdpool); RDCASSERTEQUAL(vkr, VK_SUCCESS); GetResourceManager()->WrapResource(Unwrap(device), m_InternalCmds.cmdpool); } ObjDisp(physicalDevice) ->GetPhysicalDeviceProperties(Unwrap(physicalDevice), &m_PhysicalDeviceData.props); ObjDisp(physicalDevice) ->GetPhysicalDeviceMemoryProperties(Unwrap(physicalDevice), &m_PhysicalDeviceData.memProps); ObjDisp(physicalDevice) ->GetPhysicalDeviceFeatures(Unwrap(physicalDevice), &m_PhysicalDeviceData.features); for(int i = VK_FORMAT_BEGIN_RANGE + 1; i < VK_FORMAT_END_RANGE; i++) ObjDisp(physicalDevice) ->GetPhysicalDeviceFormatProperties(Unwrap(physicalDevice), VkFormat(i), &m_PhysicalDeviceData.fmtprops[i]); m_PhysicalDeviceData.readbackMemIndex = m_PhysicalDeviceData.GetMemoryIndex(~0U, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT, 0); m_PhysicalDeviceData.uploadMemIndex = m_PhysicalDeviceData.GetMemoryIndex(~0U, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT, 0); m_PhysicalDeviceData.GPULocalMemIndex = m_PhysicalDeviceData.GetMemoryIndex( ~0U, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT); m_PhysicalDeviceData.fakeMemProps = GetRecord(physicalDevice)->memProps; m_ShaderCache = new VulkanShaderCache(this); m_TextRenderer = new VulkanTextRenderer(this); m_DebugManager = new VulkanDebugManager(this); } SAFE_DELETE_ARRAY(modQueues); return ret; } void WrappedVulkan::vkDestroyDevice(VkDevice device, const VkAllocationCallbacks *pAllocator) { // flush out any pending commands/semaphores SubmitCmds(); SubmitSemaphores(); FlushQ(); // MULTIDEVICE this function will need to check if the device is the one we // used for debugmanager/cmd pool etc, and only remove child queues and // resources (instead of doing full resource manager shutdown). // Or will we have a debug manager per-device? RDCASSERT(m_Device == device); // delete all debug manager objects SAFE_DELETE(m_DebugManager); SAFE_DELETE(m_ShaderCache); SAFE_DELETE(m_TextRenderer); // since we didn't create proper registered resources for our command buffers, // they won't be taken down properly with the pool. So we release them (just our // data) here. for(size_t i = 0; i < m_InternalCmds.freecmds.size(); i++) GetResourceManager()->ReleaseWrappedResource(m_InternalCmds.freecmds[i]); // destroy our command pool if(m_InternalCmds.cmdpool != VK_NULL_HANDLE) { ObjDisp(m_Device)->DestroyCommandPool(Unwrap(m_Device), Unwrap(m_InternalCmds.cmdpool), NULL); GetResourceManager()->ReleaseWrappedResource(m_InternalCmds.cmdpool); } for(size_t i = 0; i < m_InternalCmds.freesems.size(); i++) { ObjDisp(m_Device)->DestroySemaphore(Unwrap(m_Device), Unwrap(m_InternalCmds.freesems[i]), NULL); GetResourceManager()->ReleaseWrappedResource(m_InternalCmds.freesems[i]); } m_InternalCmds.Reset(); m_QueueFamilyIdx = ~0U; m_Queue = VK_NULL_HANDLE; // destroy the API device immediately. There should be no more // resources left in the resource manager device/physical device/instance. // Anything we created should be gone and anything the application created // should be deleted by now. // If there were any leaks, we will leak them ourselves in vkDestroyInstance // rather than try to delete API objects after the device has gone ObjDisp(m_Device)->DestroyDevice(Unwrap(m_Device), pAllocator); GetResourceManager()->ReleaseWrappedResource(m_Device); m_Device = VK_NULL_HANDLE; m_PhysicalDevice = VK_NULL_HANDLE; } template <typename SerialiserType> bool WrappedVulkan::Serialise_vkDeviceWaitIdle(SerialiserType &ser, VkDevice device) { SERIALISE_ELEMENT(device); SERIALISE_CHECK_READ_ERRORS(); if(IsReplayingAndReading()) { ObjDisp(device)->DeviceWaitIdle(Unwrap(device)); } return true; } VkResult WrappedVulkan::vkDeviceWaitIdle(VkDevice device) { VkResult ret; SERIALISE_TIME_CALL(ret = ObjDisp(device)->DeviceWaitIdle(Unwrap(device))); if(IsActiveCapturing(m_State)) { CACHE_THREAD_SERIALISER(); SCOPED_SERIALISE_CHUNK(VulkanChunk::vkDeviceWaitIdle); Serialise_vkDeviceWaitIdle(ser, device); m_FrameCaptureRecord->AddChunk(scope.Get()); } return ret; } INSTANTIATE_FUNCTION_SERIALISED(VkResult, vkEnumeratePhysicalDevices, VkInstance instance, uint32_t *pPhysicalDeviceCount, VkPhysicalDevice *pPhysicalDevices); INSTANTIATE_FUNCTION_SERIALISED(VkResult, vkCreateDevice, VkPhysicalDevice physicalDevice, const VkDeviceCreateInfo *pCreateInfo, const VkAllocationCallbacks *pAllocator, VkDevice *pDevice); INSTANTIATE_FUNCTION_SERIALISED(VkResult, vkDeviceWaitIdle, VkDevice device);
etnlGD/renderdoc
renderdoc/driver/vulkan/wrappers/vk_device_funcs.cpp
C++
mit
60,078
// Template Source: Enum.java.tt // ------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. // ------------------------------------------------------------------------------ package com.microsoft.graph.models; /** * The Enum Subject Rights Request Status. */ public enum SubjectRightsRequestStatus { /** * active */ ACTIVE, /** * closed */ CLOSED, /** * unknown Future Value */ UNKNOWN_FUTURE_VALUE, /** * For SubjectRightsRequestStatus values that were not expected from the service */ UNEXPECTED_VALUE }
microsoftgraph/msgraph-sdk-java
src/main/java/com/microsoft/graph/models/SubjectRightsRequestStatus.java
Java
mit
750
package org.scribe.services; import static org.junit.Assert.*; import org.junit.*; import org.scribe.exceptions.OAuthException; public class HMACSha1SignatureServiceTest { private HMACSha1SignatureService service; @Before public void setup() { service = new HMACSha1SignatureService(); } @Test public void shouldReturnSignatureMethodString() { String expected = "HMAC-SHA1"; assertEquals(expected, service.getSignatureMethod()); } @Test public void shouldReturnSignature() { String apiSecret = "api secret"; String tokenSecret = "token secret"; String baseString = "base string"; String signature = "cyxvUDZY/5cQBcBiKulaNgnhN/w="; assertEquals(signature, service.getSignature(baseString, apiSecret, tokenSecret)); } @Test(expected = OAuthException.class) public void shouldThrowExceptionIfBaseStringIsNull() { service.getSignature(null, "apiSecret", "tokenSecret"); } @Test(expected = OAuthException.class) public void shouldThrowExceptionIfBaseStringIsEmpty() { service.getSignature(" ", "apiSecret", "tokenSecret"); } @Test(expected = OAuthException.class) public void shouldThrowExceptionIfApiSecretIsNull() { service.getSignature("base string", null, "tokenSecret"); } @Test(expected = OAuthException.class) public void shouldThrowExceptionIfApiSecretIsEmpty() { service.getSignature("base string", " ", "tokenSecret"); } }
jamietsao/scribe-java
src/test/java/org/scribe/services/HMACSha1SignatureServiceTest.java
Java
mit
1,447
define(['jquery', 'backbone', 'BaseView'], function ($, Backbone, BaseView) { describe('BaseView', function () { describe('(managing views)', function() { var view, childView1, childView2, childView3, childView4; beforeEach(function(){ view = new (BaseView.extend({}))(); childView1 = new (Backbone.View.extend({ name: 'child1'}))(); childView2 = new (Backbone.View.extend({ name: 'child2'}))(); childView3 = new (Backbone.View.extend({ name: 'child3'}))(); childView4 = new (Backbone.View.extend({ name: 'child4'}))(); }); it('can have a view added anonymously', function() { expect(view.add(childView1)).toBe(1); function Abc() {} var a = new Abc(); expect(function(){view.add(a);}).toThrow(); }); it('can add view at given position', function() { // TODO: moar tests expect(view.add(childView1, 2)).toBe(3); }); it('can get view from given position', function() { view.add(childView1, 2); expect(typeof view.get(2)).toBe('object'); expect(view.get(5)).toBeUndefined(); }); it('can have multiple views added anonymously with no possition given', function () { view.add([childView1, childView2]); expect(view.size()).toBe(2); view.add([childView3, childView4]); expect(view.size()).toBe(4); expect(view.get(3).name).toBe('child4'); expect(view.get(1).name).toBe('child2'); }); it('can have multiple anonymous views added at given possition', function () { view.add([childView2, childView1]); view.add([childView4, childView3], 1); expect(view.size()).toBe(4); expect(view.get(2).name).toBe('child3'); expect(view.get(3).name).toBe('child1'); }); it('can add view by name', function() { view.add({ "name": childView1 }); expect(view.get("name").name).toBe('child1'); }); it('can have multiple named views added at given possition', function () { view.add([childView4, childView3, childView3]); view.add({"c2": childView2, "c1": childView1}, 2); expect(view.size()).toBe(5); expect(view.get(3).name).toBe('child1'); expect(view.get(1).name).toBe('child3'); expect(view.get(4).name).toBe('child3'); expect(view.get("c2").name).toBe('child2'); }); it('can return a valid position of a view in a collection', function () { view.add([childView4, childView3]); view.add({"c2": childView2, "c1": childView1}, 1); expect(view.getPosition(childView4)).toEqual(0); expect(view.getPosition(childView2)).toEqual(1); expect(view.getPosition(childView1)).toEqual(2); expect(view.getPosition('c1')).toEqual(2); expect(view.getPosition('c2')).toEqual(1); }); it('can return a valid count of views in a collection', function () { view.add([childView1, childView2]); view.add({"c3": childView3}); expect(view.size()).toEqual(3); }); it('can change view position using it\'s name or position', function () { view.add({ 'c1': childView1, 'c2': childView2, 'c3': childView3 }); // move by name view.move('c1', 2); expect(view.getPosition('c1')).toEqual(2); expect(view.getPosition('c2')).toEqual(0); expect(view.getPosition('c3')).toEqual(1); // move by position view.move(1, 2); expect(view.getPosition('c1')).toEqual(1); expect(view.getPosition('c2')).toEqual(0); expect(view.getPosition('c3')).toEqual(2); }); it('can remove view by name from collection', function () { view.add({"c1": childView1}); view.pullOut('c1'); expect(view.size()).toEqual(0); }); it('can remove view by index from collection', function () { view.add({"c1": childView1}); view.pullOut(0); expect(view.size()).toEqual(0); }); it('call dispose method on remove', function () { spyOn(view, 'dispose'); view.remove(); expect(view.dispose).toHaveBeenCalled(); }); it('call custom onDispose method if defined', function () { view.onDispose = function () {}; spyOn(view, 'onDispose'); view.remove(); expect(view.onDispose).toHaveBeenCalled(); }); it('call remove on every child view before remove itself', function () { spyOn(childView1, 'remove'); spyOn(childView2, 'remove'); view.add([childView1, childView2]); view.remove(); expect(childView1.remove).toHaveBeenCalled(); expect(childView2.remove).toHaveBeenCalled(); }); }); describe('(rendering views)', function() { var view, childView1, childView2; beforeEach(function(){ view = new (BaseView.extend({}))(); childView1 = new (BaseView.extend({}))(); childView2 = new (BaseView.extend({}))(); }); it('trigger render on each child view', function () { spyOn(childView1, 'render').and.callThrough(); spyOn(childView2, 'render').and.callThrough(); view.add([childView1, childView2]); view.render(); expect(childView1.render).toHaveBeenCalled(); expect(childView2.render).toHaveBeenCalled(); }); it('if no views are added, use template function for generating HTML', function () { var template = '<a href="http://example.com/">example</a>'; view.template = function () { return template; }; spyOn(view, 'template').and.callThrough(); expect(view.size()).toEqual(0); view.render(); expect(view.template).toHaveBeenCalled(); }); }); }); });
lrodziewicz/backbone-asterisk
test/BaseView.spec.js
JavaScript
mit
6,941
<?php namespace Toyotadjakarta\SalesModule\Model; use Anomaly\Streams\Platform\Database\Seeder\Seeder; class ModelSeeder extends Seeder { /** * Run the seeder. */ public function run() { // } }
vileopratama/portal-toyotadjakarta
addons/toyotadjakarta/toyotadjakarta/sales-module/src/Model/ModelSeeder.php
PHP
mit
231
<?php /** * List View Single Event * This file contains one event in the list view * * Override this template in your own theme by creating a file at [your-theme]/tribe-events/list/single-event.php * * @version 4.5.6 * */ if ( ! defined( 'ABSPATH' ) ) { die( '-1' ); } // Setup an array of venue details for use later in the template $venue_details = tribe_get_venue_details(); // Venue $has_venue_address = ( ! empty( $venue_details['address'] ) ) ? ' location' : ''; // Organizer $organizer = tribe_get_organizer(); //Date and Time $info = tribe_events_event_schedule_details(); ?> <!--eventbox--> <div class="row event-container"> <!--Bereich links-------------------------------------------------------------------------------------------------> <div class="small-5 medium-3 large-2 columns event-content date"> <!-- Event Date --> <?php do_action( 'tribe_events_before_the_meta' ) ?> <div class="fa-lg text-center event-list-date"> <?php echo strtok($info, ','); ?> </div><!-- .tribe-events-event-meta --> </div> <!--Bereich mitte-------------------------------------------------------------------------> <div class="small-9 medium-11 large-9 columns event-content middle"> <!-- Event Title --> <?php do_action( 'tribe_events_before_the_event_title' ) ?> <h3 class="tribe-events-list-event-title event-list-text "> <?php the_title() ?> </h3> <!--Künstler=Veranstalter- falls angegeben anzeigen--> <?php if ( tribe_get_organizer()!="" ) : ?> <h5>KÜNSTLER <?php echo tribe_get_organizer(); ?></h5> <?php endif; ?> <!--Falls Zeit angegeben--> <?php if (strstr($info, ',')==true) : ?> <h5> <?php echo substr($info, strpos($info, ",")+1); ?></h5> <?php endif;?> <?php do_action( 'tribe_events_after_the_event_title' ) ?> <a href="<?php echo esc_url( tribe_get_event_link() ); ?>" class="tribe-events-read-more event-list-text" rel="bookmark"> DETAILS </a> </div> <!--Bereich rechts-------------------------------------------------------------------------> <div class="hide-for-small-only hide-for-medium-only large-3 columns event-content list-event-image "> <!-- Event Image --> <img class="pic float-right" src="<?php echo tribe_event_featured_image( null, 'medium',false,false );?>"> </img> </div> </div><!--ende Eventbox --> <?php do_action( 'tribe_events_after_the_content' );
philipptrenz/wkkv_theme
tribe-events/list/single-event.php
PHP
mit
2,377
package visitor.rgpike.com; import android.app.Activity; import android.app.ProgressDialog; import android.content.Context; import android.os.AsyncTask; import android.util.Log; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.BufferedReader; import java.util.List; import java.util.regex.Pattern; import java.util.regex.Matcher; import org.apache.http.client.HttpClient; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.methods.HttpPost; import org.apache.http.HttpResponse; import org.apache.http.HttpEntity; import org.apache.http.NameValuePair; import org.apache.http.impl.client.DefaultHttpClient; public abstract class HttpPostThreadBase extends AsyncTask<String, String, String> { private Context context; private String message; private String url; private boolean simulate; private String line; private ProgressDialog dialog; public HttpPostThreadBase( Activity activity, Context context, String message, String url, boolean simulate) { this.context = context; this.message = message; this.url = url; this.simulate = simulate; this.dialog = new ProgressDialog(this.context); } @Override protected void onPreExecute() { this.dialog.setMessage(message); this.dialog.show(); } @Override protected String doInBackground(String... passcode) { if (simulate == false) { line = postData(); } else { line = "<HTML><HEAD><TITLE>Authentication Success</TITLE><meta http-equiv=\"Refresh\" content=\"1;URL=http://10.11.12.13:8080/wlan/greeting.html?timeout=-666\"></HEAD><BODY></BODY></HTML>"; } line = extractTitle(line); return line; } @Override protected void onPostExecute(String s) { Log.d("Toast", "Complete"); this.dialog.hide(); Popup(line); } private String extractTitle(String s) { String title = ""; Log.d("VISITOR", "Matching against: " + s); try { Pattern pattern = Pattern.compile("<TITLE>(.*)</TITLE>"); Matcher matcher = pattern.matcher(s); if (matcher.find() == true) { title = matcher.group(1); Log.d("VISITOR", "Matched: " + title); } } catch (java.util.regex.PatternSyntaxException pse) { Log.e("VISITOR", "Illegal pattern"); } return title; } protected abstract List<NameValuePair> populatePostData(); private String postData() { HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost(url); try { List<NameValuePair> nameValuePairs = populatePostData(); httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); Log.d("VISITOR", "Posting..."); HttpResponse response = httpclient.execute(httppost); HttpEntity entity = response.getEntity(); InputStream is = entity.getContent(); BufferedReader reader = new BufferedReader(new InputStreamReader(is)); String line = reader.readLine(); return line; } catch (ClientProtocolException e) { } catch (IOException e) { } return null; } private void Popup(String s) { /* LayoutInflater inflater = activity.getLayoutInflater(); View layout = inflater.inflate(R.layout.toast_layout, (ViewGroup) activity.findViewById(R.id.toast_layout_root)); TextView text = (TextView) layout.findViewById(R.id.text); text.setText(s); Toast toast = new Toast(context.getApplicationContext()); toast.setGravity(Gravity.TOP, 0, 0); toast.setDuration(Toast.LENGTH_LONG); toast.setView(layout); toast.show(); */ } }
arcanericky/hotspot-pass
src/visitor/rgpike/com/HttpPostThreadBase.java
Java
mit
3,746
class ApplicationController < ActionController::Base helper_method :current_user before_action :set_raven_context def ensure_authenticated! return if current_user redirect_to "/login" end def ensure_admin! return if current_user.admin? head :not_found end def ensure_not_authenticated! return unless current_user redirect_to "/" end def current_user if session[:buck_id] @current_user ||= User.find_by(buck_id: session[:buck_id]) else @current_user = nil end end def send_back(flash = {}, fallback = nil) redirect_back( fallback_location: fallback.nil? ? "/" : fallback, flash: flash ) end def set_raven_context Raven.user_context(user: current_user.attributes.except(:password_digest)) unless current_user.nil? Raven.extra_context(params: params.to_unsafe_h, url: request.url) end end
osumb/challenges
app/controllers/application_controller.rb
Ruby
mit
897
import { bindable } from 'aurelia-framework'; import { Example19 } from './example19'; import { SlickDataView, SlickGrid, ViewModelBindableData } from '../../aurelia-slickgrid'; export class DetailViewCustomElement { @bindable() model!: { duration: Date; percentComplete: number; reporter: string; start: Date; finish: Date; effortDriven: boolean; assignee: string; title: string; }; // you also have access to the following objects (it must match the exact property names shown below) addon: any; // row detail addon instance grid!: SlickGrid; dataView!: SlickDataView; // you can also optionally use the Parent Component reference // NOTE that you MUST provide it through the "parent" property in your "rowDetail" grid options parent?: Example19; bind(_bindingContext: any, overrideContext: any) { if (overrideContext && overrideContext.parentOverrideContext && overrideContext.parentOverrideContext.bindingContext && overrideContext.parentOverrideContext.bindingContext.model) { this.bindReferences(overrideContext.parentOverrideContext.bindingContext); } } bindReferences(data: ViewModelBindableData) { if (data) { this.model = data.model; this.addon = data.addon; this.grid = data.grid; this.dataView = data.dataView; this.parent = data.parent; } } alertAssignee(name: string) { if (typeof name === 'string') { alert(`Assignee on this task is: ${name.toUpperCase()}`); } else { alert('No one is assigned to this task.'); } } deleteRow(model: any) { if (confirm(`Are you sure that you want to delete ${model.title}?`)) { // you first need to collapse all rows (via the 3rd party addon instance) this.addon.collapseAll(); // then you can delete the item from the dataView this.dataView.deleteItem(model.rowId); this.parent!.showFlashMessage(`Deleted row with ${model.title}`, 'danger'); } } callParentMethod(model: any) { this.parent!.showFlashMessage(`We just called Parent Method from the Row Detail Child Component on ${model.title}`); } }
ghiscoding/aurelia-slickgrid
src/examples/slickgrid/example19-detail-view.ts
TypeScript
mit
2,145
package city.animations.interfaces; import city.bases.interfaces.AnimationInterface; public interface MarketAnimatedCashier extends AnimationInterface{ // Data // Constructor // Abstract // Movement // Getters // Setters // Utilities }
zhangtdavid/SimCity
src/city/animations/interfaces/MarketAnimatedCashier.java
Java
mit
276
<?php namespace Site\Bundle\BackendBundle\Form; use Symfony\Component\Form\AbstractType; use Symfony\Component\Form\FormBuilderInterface; use Symfony\Component\OptionsResolver\OptionsResolverInterface; use Doctrine\ORM\EntityRepository; class FrontDillerCentreInfoForm extends AbstractType { public function __construct ($phones, $blocks) { $ph = unserialize($phones); if(is_array($ph)) $this->phones = implode(', ', $ph); else $this->phones = ''; $bl = unserialize($blocks); if(is_array($bl)) $this->blocks = $bl; else $this->blocks = array(); } public function buildForm(FormBuilderInterface $builder, array $options) { $builder->add('name',null,array('label' => 'Название', 'attr' => array('class' => 'form-control') )); $builder->add('legalAddress',null,array('label' => 'Адрес', 'attr' => array('class' => 'form-control') )); $builder->add('phone',null,array('label' => 'Телефоны (через запятую)', 'data' => $this->phones, 'attr' => array('class' => 'form-control') )); $builder->add('worktime',null,array('label' => 'Время работы', 'attr' => array('class' => 'form-control') )); $builder->add('block_title_1',null,array('label' => 'Заголовок', 'mapped' => false, 'data' => (isset($this->blocks['block_title_1'])) ? $this->blocks['block_title_1'] : '', 'attr' => array('class' => 'form-control') )); $builder->add('block_title_2',null,array('label' => 'Заголовок', 'mapped' => false, 'data' => (isset($this->blocks['block_title_2'])) ? $this->blocks['block_title_2'] : '', 'attr' => array('class' => 'form-control') )); $builder->add('block_title_3',null,array('label' => 'Заголовок', 'mapped' => false, 'data' => (isset($this->blocks['block_title_3'])) ? $this->blocks['block_title_3'] : '', 'attr' => array('class' => 'form-control') )); $builder->add('block_body_1','textarea',array('label' => 'Текст', 'mapped' => false, 'data' => (isset($this->blocks['block_body_1'])) ? $this->blocks['block_body_1'] : '', 'attr' => array('class' => 'form-control') )); $builder->add('block_body_2','textarea',array('label' => 'Текст', 'mapped' => false, 'data' => (isset($this->blocks['block_body_2'])) ? $this->blocks['block_body_2'] : '', 'attr' => array('class' => 'form-control') )); $builder->add('block_body_3','textarea',array('label' => 'Текст', 'mapped' => false, 'data' => (isset($this->blocks['block_body_3'])) ? $this->blocks['block_body_3'] : '', 'attr' => array('class' => 'form-control') )); $builder->add('pricelist','file',array('label' => 'Документ', 'mapped' => false, 'required' => false)); } public function setDefaultOptions(OptionsResolverInterface $resolver) { $resolver->setDefaults(array( 'data_class' => 'Site\Bundle\BackendBundle\Entity\DillerCentre' )); } public function getName() { return 'diller'; } }
markmoskalenko/mirlada
src/Site/Bundle/BackendBundle/Form/FrontDillerCentreInfoForm.php
PHP
mit
3,126
package fr.insee.rmes.utils.ddi; import java.io.StringWriter; import javax.xml.transform.OutputKeys; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.w3c.dom.Node; public class UtilXML { private final static Logger logger = LogManager.getLogger(UtilXML.class); public static String nodeToString(Node node) { StringWriter sw = new StringWriter(); try { Transformer t = TransformerFactory.newInstance().newTransformer(); t.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); t.setOutputProperty(OutputKeys.INDENT, "yes"); t.transform(new DOMSource(node), new StreamResult(sw)); } catch (TransformerException te) { logger.error("nodeToString Transformer Exception"); } return sw.toString(); } }
InseeFr/DDI-Access-Services
src/main/java/fr/insee/rmes/utils/ddi/UtilXML.java
Java
mit
1,006
using System; using System.Collections.Generic; using System.Linq; namespace Deepcode.CommandLine.Parser { /// <summary> /// Represents a parsed command line - the command line switches and values /// are parsed into a structured collection that is exposed from this class. /// </summary> public class CommandLineArguments { private readonly Dictionary<string, List<string>> _tokens; /// <summary> /// Gets the list of switches that have been parsed /// </summary> public string[] Switches { get { return _tokens.Keys.Where( k => !string.IsNullOrEmpty(k)).ToArray(); } } /// <summary> /// Gets the list of verbs /// </summary> public string[] Verbs { get { if (HasSwitch("")) return Switch(""); return new string[0]; } } /// <summary> /// Initialise an instance of CommandLine /// </summary> public CommandLineArguments() { _tokens = new Dictionary<string, List<string>>(); } /// <summary> /// Returns true/false if the parser has found a switch with the given name /// </summary> /// <param name="switchName"></param> /// <returns></returns> public bool HasSwitch(string switchName) { return _tokens.ContainsKey(switchName); } /// <summary> /// Gets the values associated with the switch with the given name /// </summary> /// <param name="key"></param> /// <returns></returns> public string[] Switch(string key) { return _tokens[key].ToArray(); } /// <summary> /// Gets a single string value for a given switch. If multiple values have /// been presented against the switch, these are joined together. /// </summary> /// <param name="key"></param> /// <returns></returns> public string SwitchMerged(string key) { return string.Join(" ", _tokens[key]); } /// <summary> /// Adds the switch and value pair to the structured collection. /// </summary> /// <param name="key"></param> /// <param name="value"></param> public CommandLineArguments AddValue(string key, string value) { if (! HasSwitch(key)) _tokens.Add(key, new List<string>()); if (! String.IsNullOrEmpty(value)) _tokens[key].Add(value); return this; } /// <summary> /// Adds a verb to the structured collection (a value without /// a switch). Same as calling AddValue("", value); /// </summary> /// <param name="value"></param> /// <returns></returns> public CommandLineArguments AddVerb(string value) { return AddValue("", value); } } }
Deepcodecouk/Deepcode.CommandLine
src/Deepcode.CommandLine/Parser/CommandLineArguments.cs
C#
mit
2,503
#include <craft/character.hpp> #include <craft/shaderVoxel.hpp> #include <craft/chunkController.hpp> #define GLM_FORCE_RADIANS #include <glm/gtc/constants.hpp> #include <glm/gtc/matrix_inverse.hpp> #include <glm/gtc/matrix_transform.hpp> #include <cmath> #include <iostream> void character::velocity () { if (xdown == 1) { xvel += 0.3f; } else if (xdown == -1) { xvel -= 0.3f; } if (ydown == 1) { yvel += 0.3f; } else if (ydown == -1) { yvel -= 0.3f; } if (zdown == 1) { zvel += 0.3f; } else if (zdown == -1) { zvel -= 0.3f; } if (xrdown == 1) { if (xrot < 1.0f) { xrvel += 0.01f; if (xrot + xrvel < xlimitmax) { xrot = xrot + xrvel; } else { xrot = xlimitmax; xlimitmax = xrot + 0.25f; xlimitmin = xrot - 0.25f; xrdown = 0; } } } if (xrdown == -1) { if (xrot > 0.0f) { xrvel -= 0.01f; if (xrot + xrvel > xlimitmin) { xrot = xrot + xrvel; } else { xrot = xlimitmin; xlimitmax = xrot + 0.25f; xlimitmin = xrot - 0.25f; xrdown = 0; } } } if (zrdown == 1) { zrvel += 0.01f; if (zrot + zrvel < zlimitmax) { zrot = zrot + zrvel; } else { zrot = zlimitmax; zlimitmax = zrot + 0.5f; zlimitmin = zrot - 0.5f; zrdown = 0; } } if (zrdown == -1) { zrvel -= 0.01f; if (zrot + zrvel > zlimitmin) { zrot = zrot + zrvel; } else { zrot = zlimitmin; zlimitmax = zrot + 0.5f; zlimitmin = zrot - 0.5f; zrdown = 0; } } } void character::collision () { } void character::transform () { view = glm::translate(glm::mat4(1.0f), glm::vec3(xpos, ypos, zpos)); view = glm::rotate(view, glm::pi<float>() * -zrot, glm::vec3(0, 0, 1)); view = view * glm::translate(glm::mat4(1.0f), glm::vec3(xvel, yvel, zvel)); view = glm::rotate(view, glm::pi<float>() * xrot, glm::vec3(1, 0, 0)); xpos = view[3][0]; ypos = view[3][1]; zpos = view[3][2]; view = view * glm::translate(glm::mat4(1.0f), glm::vec3(0.0f, 0.0f, nclip + 0.5f)); p = glm::vec3(view[3][0], view[3][1], view[3][2]); view = glm::affineInverse(view); } void character::frustumBuild () { d = glm::vec3(0.0f, 0.0f, -1.0f); cs = cos(glm::pi<float>() * xrot); sn = sin(glm::pi<float>() * xrot); yn = d[1] * cs - d[2] * sn; zn = d[1] * sn + d[2] * cs; d[1] = yn; d[2] = zn; cs = cos(glm::pi<float>() * -zrot); sn = sin(glm::pi<float>() * -zrot); xn = d[0] * cs - d[1] * sn; yn = d[0] * sn + d[1] * cs; d[0] = xn; d[1] = yn; right = glm::normalize( glm::cross(d, glm::vec3(0.0f,0.00001f,1.0f)) ); up = glm::normalize(glm::cross(d, right)); nearDist = nclip - 8.0f; Hnear = 8.0f * scale / ratio; Wnear = 8.0f * scale; farDist = fclip + 8.0f; Hfar = 8.0f * scale / ratio; Wfar = 8.0f * scale; view_frustum.fc = p + d * farDist; view_frustum.ftl = view_frustum.fc + (up * Hfar) - (right * Wfar); view_frustum.ftr = view_frustum.fc + (up * Hfar) + (right * Wfar); view_frustum.fbl = view_frustum.fc - (up * Hfar) - (right * Wfar); view_frustum.fbr = view_frustum.fc - (up * Hfar) + (right * Wfar); view_frustum.nc = p + d * nearDist; view_frustum.ntl = view_frustum.nc + (up * Hnear) - (right * Wnear); view_frustum.ntr = view_frustum.nc + (up * Hnear) + (right * Wnear); view_frustum.nbl = view_frustum.nc - (up * Hnear) - (right * Wnear); view_frustum.nbr = view_frustum.nc - (up * Hnear) + (right * Wnear); planes[0].init(view_frustum.ftr, view_frustum.fbl, view_frustum.ftl); planes[1].init(view_frustum.ntr, view_frustum.nbl, view_frustum.nbr); planes[2].init(view_frustum.fbl, view_frustum.ntl, view_frustum.ftl); planes[3].init(view_frustum.fbr, view_frustum.ntr, view_frustum.nbr); planes[4].init(view_frustum.nbl, view_frustum.fbr, view_frustum.nbr); planes[5].init(view_frustum.ntl, view_frustum.ftr, view_frustum.ftl); planes[6].init(glm::vec3(0, 1, 0), glm::vec3(1, 0, 0), glm::vec3(0, 0, 10)); } void character::setFlagAuto () { if ( xvel == 0 && yvel == 0 && zvel == 0 && xrvel == 0 && zrvel == 0 ) { flag = 0; } else { flag = 1; } } character::character () { } character::character (float xpos_input, float ypos_input, float zpos_input, float ratio_input) { xpos = xpos_input; ypos = ypos_input; zpos = zpos_input; xseg = int( xpos / 16 ); yseg = int( ypos / 16 ); fov = 1.0f; ratio = ratio_input; nclip = 25.0f; fclip = 80.0f; scale = 5; size = 1; xdown = 0; ydown = 0; zdown = 0; xvel = 0; yvel = 0; zvel = 0; xrot = 0.5f; zrot = 0.0f; zlimitmax = zrot + 0.5f; zlimitmin = zrot - 0.5f; xlimitmax = xrot + 0.25f; xlimitmin = xrot - 0.25f; xrdown = 0; zrdown = 0; xrvel = 0; zrvel = 0; init(); flag = 0; } void character::init () { transform(); proj = glm::ortho ( -8.0f * scale, 8.0f * scale, -8.0f * scale / ratio, 8.0f * scale / ratio, nclip, fclip ); frustumBuild(); } void character::update (chunkController* chunkController01) { if (flag == 1) { velocity(); collision(); transform(); frustumBuild(); if (xvel != 0) { xvel *= 0.75; if ( (xvel < 0.01f && xvel > 0.0f) || (xvel > -0.01f && xvel < 0.0f) ) xvel = 0; } if (yvel != 0) { yvel *= 0.75; if ( (yvel < 0.01f && yvel > 0.0f) || (yvel > -0.01f && yvel < 0.0f) ) yvel = 0; } if (zvel != 0) { zvel *= 0.75; if ( (zvel < 0.01f && zvel > 0.0f) || (zvel > -0.01f && zvel < 0.0f) ) zvel = 0; } if (zrvel != 0) { zrvel *= 0.9; if ( (zrvel < 0.001f && zrvel > 0.0f) || (zrvel > -0.001f && zrvel < 0.0f) ) zrvel = 0; } if (xrvel != 0) { xrvel *= 0.5; if ( (xrvel < 0.001f && xrvel > 0.0f) || (xrvel > -0.001f && xrvel < 0.0f) ) xrvel = 0; } flag = 2; } } void character::updateUni(shaderVoxel* shader) { if (flag == 2) { glUniformMatrix4fv(shader->getUniView(), 1, GL_FALSE, glm::value_ptr( view )); glUniformMatrix4fv(shader->getUniProj(), 1, GL_FALSE, glm::value_ptr( proj )); setFlagAuto(); } } int character::frustumCheck (float x, float y, float z, float r) { glm::vec3 p(x, y, z); int inside = 1; for (int i = 0; i < 6; i++) { if (planes[i].intersection(p, r) != 1) inside = 0; } return inside; } void character::setXdown (int input) { xdown = input; flag = 1; } void character::setYdown (int input) { ydown = input; flag = 1; } void character::setZdown (int input) { zdown = input; flag = 1; } void character::setXseg (int input) { xseg = input; } void character::setYseg (int input) { yseg = input; } void character::setZrdown (int input) { zrdown = input; flag = 1; } void character::setXrdown (int input) { xrdown = input; flag = 1; } void character::setFov (float input) { fov = input; } void character::setNclip (float input) { nclip = input; } void character::setFclip (float input) { fclip = input; } void character::setFlag (int input) { flag = input; } glm::mat4 character::getView () { return view; } glm::mat4 character::getProj () { return proj; } float character::getXpos () { return xpos; } float character::getYpos () { return ypos; } float character::getZpos () { return zpos; } int character::getXseg () { return xseg; } int character::getYseg () { return yseg; } float character::getFov () { return fov; } float character::getNclip () { return nclip; } float character::getFclip () { return fclip; } int character::getFlag () { return flag; }
joshbainbridge/craft-game
src/character.cpp
C++
mit
7,418
//start drag of element function drag(ev) { ev.dataTransfer.setData("text", ev.target.id); } //allow drop of element function allowDrop(ev) { ev.preventDefault(); } //drag of element function drop(ev) { ev.preventDefault(); var data = ev.dataTransfer.getData("text"); ev.target.appendChild(document.getElementById(data)); } //variable for generating unique task id var randomId = 0; //add a new task function addCard() { var title = document.getElementById('addtask').value; //verifying task description if(title.length>0){ var itm = document.getElementById("item2"); var cln = itm.cloneNode(true); //cloning the card cln.id = "unique" + ++randomId; //generating unique id cln.childNodes[3].innerText = title; //attaching task to to do board document.getElementById('todo').appendChild(cln); } else{ alert("Please Add Task"); } } //Deletion Of task function removeCard(removeCardId){ var cardElement = removeCardId.parentNode.parentNode; cardElement.remove(); }
arpit2126/AGILE-DASHBOARD
main.js
JavaScript
mit
1,098
#include "RemoveDuplicateLetters.hpp" #include <vector> using namespace std; string RemoveDuplicateLetters::removeDuplicateLetters(string s) { vector<int> freq(256, 0); vector<bool> visited(256, false); string ret; for (auto c : s) freq[c]++; for (auto c : s) { freq[c]--; if (visited[c]) continue; while (!ret.empty() && ret.back() > c && freq[ret.back()]) { visited[ret.back()] = false; ret.pop_back(); } ret += c; visited[c] = true; } return ret; }
yanzhe-chen/leetcode
src/RemoveDuplicateLetters.cpp
C++
mit
561
if (typeof (window) === 'undefined') var loki = require('../../src/lokijs.js'); describe('testing unique index serialization', function () { var db; beforeEach(function () { db = new loki(); users = db.addCollection('users'); users.insert([{ username: 'joe' }, { username: 'jack' }, { username: 'john' }, { username: 'jim' }]); users.ensureUniqueIndex('username'); }); it('should have a unique index', function () { var ser = db.serialize(), reloaded = new loki(); var loaded = reloaded.loadJSON(ser); var coll = reloaded.getCollection('users'); expect(coll.data.length).toEqual(4); expect(coll.constraints.unique.username).toBeDefined(); var joe = coll.by('username', 'joe'); expect(joe).toBeDefined(); expect(joe.username).toEqual('joe'); expect(reloaded.options.serializationMethod).toBe("normal"); expect(reloaded.options.destructureDelimiter).toBe("$<\n"); }); }); describe('testing destructured serialization/deserialization', function () { it('verify default (D) destructuring works as expected', function() { var ddb = new loki("test.db", { serializationMethod: "destructured" }); var coll = ddb.addCollection("testcoll"); coll.insert({ name : "test1", val: 100 }); coll.insert({ name : "test2", val: 101 }); coll.insert({ name : "test3", val: 102 }); var coll2 = ddb.addCollection("another"); coll2.insert({ a: 1, b: 2 }); var destructuredJson = ddb.serialize(); var cddb = new loki("test.db", { serializationMethod: "destructured" }); cddb.loadJSON(destructuredJson); expect(cddb.options.serializationMethod).toEqual("destructured"); expect(cddb.collections.length).toEqual(2); expect(cddb.collections[0].data.length).toEqual(3); expect(cddb.collections[0].data[0].val).toEqual(ddb.collections[0].data[0].val); expect(cddb.collections[1].data.length).toEqual(1); expect(cddb.collections[1].data[0].a).toEqual(ddb.collections[1].data[0].a); }); // Destructuring Formats : // D : one big Delimited string { partitioned: false, delimited : true } // DA : Delimited Array of strings [0] db [1] collection [n] collection { partitioned: true, delimited: true } // NDA : Non-Delimited Array : one iterable array with empty string collection partitions { partitioned: false, delimited: false } // NDAA : Non-Delimited Array with subArrays. db at [0] and collection subarrays at [n] { partitioned: true, delimited : false } it('verify custom destructuring works as expected', function() { var methods = ['D', 'DA', 'NDA', 'NDAA']; var idx, options, result; var cddb, ddb = new loki("test.db"); var coll = ddb.addCollection("testcoll"); coll.insert({ name : "test1", val: 100 }); coll.insert({ name : "test2", val: 101 }); coll.insert({ name : "test3", val: 102 }); var coll2 = ddb.addCollection("another"); coll2.insert({ a: 1, b: 2 }); for(idx=0; idx < methods.length; idx++) { switch (idx) { case 'D' : options = { partitioned: false, delimited : true }; break; case 'DA' : options = { partitioned: true, delimited: true }; break; case 'NDA' : options = { partitioned: false, delimited: false }; break; case 'NDAA' : options = { partitioned: true, delimited : false }; break; default : options = {}; break; } // do custom destructuring result = ddb.serializeDestructured(options); // reinflate from custom destructuring var cddb = new loki("test.db"); var reinflatedDatabase = cddb.deserializeDestructured(result, options); cddb.loadJSONObject(reinflatedDatabase); // assert expectations on reinflated database expect(cddb.collections.length).toEqual(2); expect(cddb.collections[0].data.length).toEqual(3); expect(cddb.collections[0].data[0].val).toEqual(ddb.collections[0].data[0].val); expect(cddb.collections[0].data[0].$loki).toEqual(ddb.collections[0].data[0].$loki); expect(cddb.collections[0].data[2].$loki).toEqual(ddb.collections[0].data[2].$loki); expect(cddb.collections[1].data.length).toEqual(1); expect(cddb.collections[1].data[0].a).toEqual(ddb.collections[1].data[0].a); } }); it('verify individual partitioning works correctly', function() { var idx, options, result; var cddb, ddb = new loki("test.db"); var coll = ddb.addCollection("testcoll"); coll.insert({ name : "test1", val: 100 }); coll.insert({ name : "test2", val: 101 }); coll.insert({ name : "test3", val: 102 }); var coll2 = ddb.addCollection("another"); coll2.insert({ a: 1, b: 2 }); // Verify db alone works correctly using NDAA format result = ddb.serializeDestructured({ partitioned: true, delimited : false, partition: -1 // indicates to get serialized db container only }); var cddb = new loki('test'); cddb.loadJSON(result); expect(cddb.collections.length).toEqual(2); expect(cddb.collections[0].data.length).toEqual(0); expect(cddb.collections[1].data.length).toEqual(0); expect(cddb.collections[0].name).toEqual(ddb.collections[0].name); expect(cddb.collections[1].name).toEqual(ddb.collections[1].name); // Verify collection alone works correctly using NDAA format result = ddb.serializeDestructured({ partitioned: true, delimited : false, partition: 0 // collection [0] only }); // we dont need to test all components of reassembling whole database // so we will just call helper function to deserialize just collection data var data = ddb.deserializeCollection(result, { partitioned: true, delimited : false }); expect(data.length).toEqual(ddb.collections[0].data.length); expect(data[0].val).toEqual(ddb.collections[0].data[0].val); expect(data[1].val).toEqual(ddb.collections[0].data[1].val); expect(data[2].val).toEqual(ddb.collections[0].data[2].val); expect(data[0].$loki).toEqual(ddb.collections[0].data[0].$loki); expect(data[1].$loki).toEqual(ddb.collections[0].data[1].$loki); expect(data[2].$loki).toEqual(ddb.collections[0].data[2].$loki); // Verify collection alone works correctly using DA format (the other partitioned format) result = ddb.serializeDestructured({ partitioned: true, delimited : true, partition: 0 // collection [0] only }); // now reinflate from that interim DA format data = ddb.deserializeCollection(result, { partitioned: true, delimited: true }); expect(data.length).toEqual(ddb.collections[0].data.length); expect(data[0].val).toEqual(ddb.collections[0].data[0].val); expect(data[1].val).toEqual(ddb.collections[0].data[1].val); expect(data[2].val).toEqual(ddb.collections[0].data[2].val); expect(data[0].$loki).toEqual(ddb.collections[0].data[0].$loki); expect(data[1].$loki).toEqual(ddb.collections[0].data[1].$loki); expect(data[2].$loki).toEqual(ddb.collections[0].data[2].$loki); }); }); describe('testing adapter functionality', function () { it('verify basic memory adapter functionality works', function(done) { var idx, options, result; var memAdapter = new loki.LokiMemoryAdapter(); var ddb = new loki("test.db", { adapter: memAdapter }); var coll = ddb.addCollection("testcoll"); coll.insert({ name : "test1", val: 100 }); coll.insert({ name : "test2", val: 101 }); coll.insert({ name : "test3", val: 102 }); var coll2 = ddb.addCollection("another"); coll2.insert({ a: 1, b: 2 }); ddb.saveDatabase(function(err) { expect(memAdapter.hashStore.hasOwnProperty("test.db")).toEqual(true); expect(memAdapter.hashStore["test.db"].savecount).toEqual(1); // although we are mostly using callbacks, memory adapter is essentially synchronous with callbacks var cdb = new loki("test.db", { adapter: memAdapter }); cdb.loadDatabase({}, function() { expect(cdb.collections.length).toEqual(2); expect(cdb.getCollection("testcoll").findOne({name:"test2"}).val).toEqual(101); expect(cdb.collections[0].data.length).toEqual(3); expect(cdb.collections[1].data.length).toEqual(1); done(); }); }); }); it('verify loki deleteDatabase works', function (done) { var memAdapter = new loki.LokiMemoryAdapter({ asyncResponses: true }); var ddb = new loki("test.db", { adapter: memAdapter }); var coll = ddb.addCollection("testcoll"); coll.insert({ name : "test1", val: 100 }); coll.insert({ name : "test2", val: 101 }); coll.insert({ name : "test3", val: 102 }); ddb.saveDatabase(function(err) { expect(memAdapter.hashStore.hasOwnProperty("test.db")).toEqual(true); expect(memAdapter.hashStore["test.db"].savecount).toEqual(1); ddb.deleteDatabase(function(err) { expect(memAdapter.hashStore.hasOwnProperty("test.db")).toEqual(false); done(); }); }); }); it('verify partioning adapter works', function(done) { var mem = new loki.LokiMemoryAdapter(); var adapter = new loki.LokiPartitioningAdapter(mem); var db = new loki('sandbox.db', {adapter: adapter}); // Add a collection to the database var items = db.addCollection('items'); items.insert({ name : 'mjolnir', owner: 'thor', maker: 'dwarves' }); items.insert({ name : 'gungnir', owner: 'odin', maker: 'elves' }); items.insert({ name : 'tyrfing', owner: 'Svafrlami', maker: 'dwarves' }); items.insert({ name : 'draupnir', owner: 'odin', maker: 'elves' }); var another = db.addCollection('another'); var ai = another.insert({ a:1, b:2 }); // make sure maxId was restored correctly over partitioned save/load cycle var itemMaxId = items.maxId; // for purposes of our memory adapter it is pretty much synchronous db.saveDatabase(function(err) { // should have partitioned the data expect(Object.keys(mem.hashStore).length).toEqual(3); expect(mem.hashStore.hasOwnProperty("sandbox.db")).toEqual(true); expect(mem.hashStore.hasOwnProperty("sandbox.db.0")).toEqual(true); expect(mem.hashStore.hasOwnProperty("sandbox.db.1")).toEqual(true); // all partitions should have been saved once each expect(mem.hashStore["sandbox.db"].savecount).toEqual(1); expect(mem.hashStore["sandbox.db.0"].savecount).toEqual(1); expect(mem.hashStore["sandbox.db.1"].savecount).toEqual(1); // so let's go ahead and update one of our collections to make it dirty ai.b = 3; another.update(ai); // and save again to ensure lastsave is different on for db container and that one collection db.saveDatabase(function(err) { // db container always gets saved since we currently have no 'dirty' flag on it to check expect(mem.hashStore["sandbox.db"].savecount).toEqual(2); // we didn't change this expect(mem.hashStore["sandbox.db.0"].savecount).toEqual(1); // we updated this collection so it should have been saved again expect(mem.hashStore["sandbox.db.1"].savecount).toEqual(2); // ok now lets load from it var db2 = new loki('sandbox.db', { adapter: adapter}); db2.loadDatabase({}, function(err) { expect(db2.getCollection("items").maxId).toEqual(itemMaxId); expect(db2.collections.length).toEqual(2); expect(db2.collections[0].data.length).toEqual(4); expect(db2.collections[1].data.length).toEqual(1); expect(db2.getCollection("items").findOne({ name : 'gungnir'}).owner).toEqual("odin"); expect(db2.getCollection("another").findOne({ a: 1}).b).toEqual(3); done(); }); }); }); }); it('verify partioning adapter with paging mode enabled works', function(done) { var mem = new loki.LokiMemoryAdapter(); // we will use an exceptionally low page size (128bytes) to test with small dataset var adapter = new loki.LokiPartitioningAdapter(mem, { paging: true, pageSize: 128}); var db = new loki('sandbox.db', {adapter: adapter}); // Add a collection to the database var items = db.addCollection('items'); items.insert({ name : 'mjolnir', owner: 'thor', maker: 'dwarves' }); items.insert({ name : 'gungnir', owner: 'odin', maker: 'elves' }); var tyr = items.insert({ name : 'tyrfing', owner: 'Svafrlami', maker: 'dwarves' }); items.insert({ name : 'draupnir', owner: 'odin', maker: 'elves' }); var another = db.addCollection('another'); var ai = another.insert({ a:1, b:2 }); // for purposes of our memory adapter it is pretty much synchronous db.saveDatabase(function(err) { // should have partitioned the data expect(Object.keys(mem.hashStore).length).toEqual(4); expect(mem.hashStore.hasOwnProperty("sandbox.db")).toEqual(true); expect(mem.hashStore.hasOwnProperty("sandbox.db.0.0")).toEqual(true); expect(mem.hashStore.hasOwnProperty("sandbox.db.0.1")).toEqual(true); expect(mem.hashStore.hasOwnProperty("sandbox.db.1.0")).toEqual(true); // all partitions should have been saved once each expect(mem.hashStore["sandbox.db"].savecount).toEqual(1); expect(mem.hashStore["sandbox.db.0.0"].savecount).toEqual(1); expect(mem.hashStore["sandbox.db.0.1"].savecount).toEqual(1); expect(mem.hashStore["sandbox.db.1.0"].savecount).toEqual(1); // so let's go ahead and update one of our collections to make it dirty ai.b = 3; another.update(ai); // and save again to ensure lastsave is different on for db container and that one collection db.saveDatabase(function(err) { // db container always gets saved since we currently have no 'dirty' flag on it to check expect(mem.hashStore["sandbox.db"].savecount).toEqual(2); // we didn't change this expect(mem.hashStore["sandbox.db.0.0"].savecount).toEqual(1); expect(mem.hashStore["sandbox.db.0.0"].savecount).toEqual(1); // we updated this collection so it should have been saved again expect(mem.hashStore["sandbox.db.1.0"].savecount).toEqual(2); // now update a multi page items collection and verify both pages were saved tyr.maker = "elves"; items.update(tyr); db.saveDatabase(); expect(mem.hashStore["sandbox.db"].savecount).toEqual(3); expect(mem.hashStore["sandbox.db.0.0"].savecount).toEqual(2); expect(mem.hashStore["sandbox.db.0.0"].savecount).toEqual(2); expect(mem.hashStore["sandbox.db.1.0"].savecount).toEqual(2); // ok now lets load from it var db2 = new loki('sandbox.db', { adapter: adapter}); db2.loadDatabase(); expect(db2.collections.length).toEqual(2); expect(db2.collections[0].data.length).toEqual(4); expect(db2.collections[1].data.length).toEqual(1); expect(db2.getCollection("items").findOne({ name : 'tyrfing'}).maker).toEqual("elves"); expect(db2.getCollection("another").findOne({ a: 1}).b).toEqual(3); // verify empty collection saves with paging db.addCollection("extracoll"); db.saveDatabase(function(err) { expect(mem.hashStore["sandbox.db"].savecount).toEqual(4); expect(mem.hashStore["sandbox.db.0.0"].savecount).toEqual(2); expect(mem.hashStore["sandbox.db.0.0"].savecount).toEqual(2); expect(mem.hashStore["sandbox.db.1.0"].savecount).toEqual(2); expect(mem.hashStore["sandbox.db.2.0"].savecount).toEqual(1); // now verify loading empty collection works with paging codepath db2 = new loki('sandbox.db', { adapter: adapter}); db2.loadDatabase(); expect(db2.collections.length).toEqual(3); expect(db2.collections[0].data.length).toEqual(4); expect(db2.collections[1].data.length).toEqual(1); expect(db2.collections[2].data.length).toEqual(0); }); }); }); setTimeout(done, 700); }); it('verify reference adapters get db reference which is copy and serializable-safe', function(done) { // Current loki functionality with regards to reference mode adapters: // Since we don't use serializeReplacer on reference mode adapters, we make // lightweight clone, cloning only db container and collection containers (object refs are same). function MyFakeReferenceAdapter() { this.mode = "reference" } MyFakeReferenceAdapter.prototype.loadDatabase = function(dbname, callback) { expect(typeof(dbname)).toEqual("string"); expect(typeof(callback)).toEqual("function"); var result = new loki("new db"); var n1 = result.addCollection("n1"); var n2 = result.addCollection("n2"); n1.insert({m: 9, n: 8}); n2.insert({m:7, n:6}); callback(result); }; MyFakeReferenceAdapter.prototype.exportDatabase = function(dbname, dbref, callback) { expect(typeof(dbname)).toEqual("string"); expect(dbref.constructor.name).toEqual("Loki"); expect(typeof(callback)).toEqual("function"); expect(dbref.persistenceAdapter).toEqual(null); expect(dbref.collections.length).toEqual(2); expect(dbref.getCollection("c1").findOne({a:1}).b).toEqual(2); // these changes should not affect original database dbref.filename = "somethingelse"; dbref.collections[0].name = "see1"; // (accidentally?) updating a document should... dbref.collections[0].findOne({a:1}).b=3; }; var adapter = new MyFakeReferenceAdapter(); var db = new loki("rma test", {adapter: adapter}); var c1 = db.addCollection("c1"); var c2 = db.addCollection("c2"); c1.insert({a:1, b:2}); c2.insert({a:3, b:4}); db.saveDatabase(function() { expect(db.persistenceAdapter).toNotEqual(null); expect(db.filename).toEqual("rma test"); expect(db.collections[0].name).toEqual("c1"); expect(db.getCollection("c1").findOne({a:1}).b).toEqual(3); }); var db2 = new loki("other name", { adapter: adapter}); db2.loadDatabase({}, function() { expect(db2.collections.length).toEqual(2); expect(db2.collections[0].name).toEqual("n1"); expect(db2.collections[1].name).toEqual("n2"); expect(db2.getCollection("n1").findOne({m:9}).n).toEqual(8); done(); }); }); }); describe('async adapter tests', function() { it('verify throttled async drain works', function(done) { var mem = new loki.LokiMemoryAdapter({ asyncResponses: true, asyncTimeout: 50 }); var db = new loki('sandbox.db', {adapter: mem, throttledSaves: true}); // Add a collection to the database var items = db.addCollection('items'); var mjol = items.insert({ name : 'mjolnir', owner: 'thor', maker: 'dwarves' }); var gun = items.insert({ name : 'gungnir', owner: 'odin', maker: 'elves' }); var tyr = items.insert({ name : 'tyrfing', owner: 'Svafrlami', maker: 'dwarves' }); var drau = items.insert({ name : 'draupnir', owner: 'odin', maker: 'elves' }); var another = db.addCollection('another'); var ai = another.insert({ a:1, b:2 }); // this should immediately kick off the first save db.saveDatabase(); // the following saves (all async) should coalesce into one save ai.b = 3; another.update(ai); db.saveDatabase(); tyr.owner = "arngrim"; items.update(tyr); db.saveDatabase(); drau.maker = 'dwarves'; items.update(drau); db.saveDatabase(); db.throttledSaveDrain(function () { // Wait until saves are complete and then loading the database and make // sure all saves are complete and includes their changes var db2 = new loki('sandbox.db', { adapter: mem }); db2.loadDatabase({}, function() { // total of 2 saves should have occurred expect(mem.hashStore["sandbox.db"].savecount).toEqual(2); // verify the saved database contains all expected changes expect(db2.getCollection("another").findOne({a:1}).b).toEqual(3); expect(db2.getCollection("items").findOne({name:'tyrfing'}).owner).toEqual('arngrim'); expect(db2.getCollection("items").findOne({name:'draupnir'}).maker).toEqual('dwarves'); done(); }); }); }); it('verify throttledSaveDrain with duration timeout works', function(done) { var mem = new loki.LokiMemoryAdapter({ asyncResponses: true, asyncTimeout: 100 }); var db = new loki('sandbox.db', { adapter: mem }); // Add a collection to the database var items = db.addCollection('items'); var mjol = items.insert({ name : 'mjolnir', owner: 'thor', maker: 'dwarves' }); var gun = items.insert({ name : 'gungnir', owner: 'odin', maker: 'elves' }); var tyr = items.insert({ name : 'tyrfing', owner: 'Svafrlami', maker: 'dwarves' }); var drau = items.insert({ name : 'draupnir', owner: 'odin', maker: 'elves' }); var another = db.addCollection('another'); var ai = another.insert({ a:1, b:2 }); // this should immediately kick off the first save (~100ms) db.saveDatabase(); // now queue up a sequence to be run one after the other, at ~50ms each (~300ms total) when first completes ai.b = 3; another.update(ai); db.saveDatabase(function() { tyr.owner = "arngrim"; items.update(tyr); db.saveDatabase(function() { drau.maker = 'dwarves'; items.update(drau); db.saveDatabase(); }); }); expect(db.throttledSaves).toEqual(true); expect(db.throttledSavePending).toEqual(true); // we want this to fail so above they should be bootstrapping several // saves which take about 400ms to complete. // The full drain can take one save/callback cycle longer than duration (~100ms). db.throttledSaveDrain(function (success) { expect(success).toEqual(false); done(); }, { recursiveWaitLimit: true, recursiveWaitLimitDuration: 200 }); }); it('verify throttled async throttles', function(done) { var mem = new loki.LokiMemoryAdapter({ asyncResponses: true, asyncTimeout: 50 }); var db = new loki('sandbox.db', { adapter: mem }); // Add a collection to the database var items = db.addCollection('items'); var mjol = items.insert({ name : 'mjolnir', owner: 'thor', maker: 'dwarves' }); var gun = items.insert({ name : 'gungnir', owner: 'odin', maker: 'elves' }); var tyr = items.insert({ name : 'tyrfing', owner: 'Svafrlami', maker: 'dwarves' }); var drau = items.insert({ name : 'draupnir', owner: 'odin', maker: 'elves' }); var another = db.addCollection('another'); var ai = another.insert({ a:1, b:2 }); // this should immediately kick off the first save db.saveDatabase(); // the following saves (all async) should coalesce into one save ai.b = 3; another.update(ai); db.saveDatabase(); tyr.owner = "arngrim"; items.update(tyr); db.saveDatabase(); drau.maker = 'dwarves'; items.update(drau); db.saveDatabase(); // give all async saves time to complete and then verify outcome db.throttledSaveDrain(function () { // total of 2 saves should have occurred expect(mem.hashStore["sandbox.db"].savecount).toEqual(2); // verify the saved database contains all expected changes var db2 = new loki('sandbox.db', { adapter: mem }); db2.loadDatabase({}, function() { expect(db2.getCollection("another").findOne({a:1}).b).toEqual(3); expect(db2.getCollection("items").findOne({name:'tyrfing'}).owner).toEqual('arngrim'); expect(db2.getCollection("items").findOne({name:'draupnir'}).maker).toEqual('dwarves'); done(); }); }); }); it('verify throttled async works as expected', function(done) { var mem = new loki.LokiMemoryAdapter({ asyncResponses: true, asyncTimeout: 50 }); var adapter = new loki.LokiPartitioningAdapter(mem); var throttled = true; var db = new loki('sandbox.db', {adapter: adapter, throttledSaves: throttled}); // Add a collection to the database var items = db.addCollection('items'); items.insert({ name : 'mjolnir', owner: 'thor', maker: 'dwarves' }); items.insert({ name : 'gungnir', owner: 'odin', maker: 'elves' }); var tyr = items.insert({ name : 'tyrfing', owner: 'Svafrlami', maker: 'dwarves' }); items.insert({ name : 'draupnir', owner: 'odin', maker: 'elves' }); var another = db.addCollection('another'); var ai = another.insert({ a:1, b:2 }); db.saveDatabase(function(err) { // should have partitioned the data expect(Object.keys(mem.hashStore).length).toEqual(3); expect(mem.hashStore.hasOwnProperty("sandbox.db")).toEqual(true); expect(mem.hashStore.hasOwnProperty("sandbox.db.0")).toEqual(true); expect(mem.hashStore.hasOwnProperty("sandbox.db.1")).toEqual(true); // all partitions should have been saved once each expect(mem.hashStore["sandbox.db"].savecount).toEqual(1); expect(mem.hashStore["sandbox.db.0"].savecount).toEqual(1); expect(mem.hashStore["sandbox.db.1"].savecount).toEqual(1); // so let's go ahead and update one of our collections to make it dirty ai.b = 3; another.update(ai); // and save again to ensure lastsave is different on for db container and that one collection db.saveDatabase(function(err) { // db container always gets saved since we currently have no 'dirty' flag on it to check expect(mem.hashStore["sandbox.db"].savecount).toEqual(2); // we didn't change this expect(mem.hashStore["sandbox.db.0"].savecount).toEqual(1); // we updated this collection so it should have been saved again expect(mem.hashStore["sandbox.db.1"].savecount).toEqual(2); // now update a multi page items collection and verify both pages were saved tyr.maker = "elves"; items.update(tyr); db.saveDatabase(function(err) { expect(mem.hashStore["sandbox.db"].savecount).toEqual(3); expect(mem.hashStore["sandbox.db.0"].savecount).toEqual(2); expect(mem.hashStore["sandbox.db.1"].savecount).toEqual(2); // ok now lets load from it var db2 = new loki('sandbox.db', { adapter: adapter, throttledSaves: throttled}); db2.loadDatabase({}, function(err) { done(); expect(db2.collections.length).toEqual(2); expect(db2.collections[0].data.length).toEqual(4); expect(db2.collections[1].data.length).toEqual(1); expect(db2.getCollection("items").findOne({ name : 'tyrfing'}).maker).toEqual("elves"); expect(db2.getCollection("another").findOne({ a: 1}).b).toEqual(3); // verify empty collection saves with paging db.addCollection("extracoll"); db.saveDatabase(function(err) { expect(mem.hashStore["sandbox.db"].savecount).toEqual(4); expect(mem.hashStore["sandbox.db.0"].savecount).toEqual(2); expect(mem.hashStore["sandbox.db.1"].savecount).toEqual(2); expect(mem.hashStore["sandbox.db.2"].savecount).toEqual(1); // now verify loading empty collection works with paging codepath db2 = new loki('sandbox.db', { adapter: adapter, throttledSaves: throttled}); db2.loadDatabase({}, function() { expect(db2.collections.length).toEqual(3); expect(db2.collections[0].data.length).toEqual(4); expect(db2.collections[1].data.length).toEqual(1); expect(db2.collections[2].data.length).toEqual(0); // since async calls are being used, use jasmine done() to indicate test finished done(); }); }); }); }); }); }); }); it('verify loadDatabase in the middle of throttled saves will wait for queue to drain first', function(done) { var mem = new loki.LokiMemoryAdapter({ asyncResponses: true, asyncTimeout: 75 }); var db = new loki('sandbox.db', { adapter: mem }); // Add a collection to the database var items = db.addCollection('items'); var mjol = items.insert({ name : 'mjolnir', owner: 'thor', maker: 'dwarves' }); var gun = items.insert({ name : 'gungnir', owner: 'odin', maker: 'elves' }); var tyr = items.insert({ name : 'tyrfing', owner: 'Svafrlami', maker: 'dwarves' }); var drau = items.insert({ name : 'draupnir', owner: 'odin', maker: 'elves' }); var another = db.addCollection('another'); var ai = another.insert({ a:1, b:2 }); // this should immediately kick off the first save (~100ms) db.saveDatabase(); // now queue up a sequence to be run one after the other, at ~50ms each (~300ms total) when first completes ai.b = 3; another.update(ai); db.saveDatabase(function() { tyr.owner = "arngrim"; items.update(tyr); db.saveDatabase(function() { drau.maker = 'dwarves'; items.update(drau); db.saveDatabase(); }); }); expect(db.throttledSaves).toEqual(true); expect(db.throttledSavePending).toEqual(true); // at this point, several rounds of saves should be triggered... // a load at this scope (possibly simulating script run from different code path) // should wait until any pending saves are complete, then freeze saves (queue them ) while loading, // then re-enable saves db.loadDatabase({}, function (success) { expect(db.getCollection('another').findOne({a:1}).b).toEqual(3); expect(db.getCollection('items').findOne({name:'tyrfing'}).owner).toEqual('arngrim'); expect(db.getCollection('items').findOne({name:'draupnir'}).maker).toEqual('dwarves'); done(); }); }); }); describe('testing changesAPI', function() { it('verify pending changes persist across save/load cycle', function(done) { var mem = new loki.LokiMemoryAdapter(); var db = new loki('sandbox.db', { adapter: mem }); // Add a collection to the database var items = db.addCollection('items', { disableChangesApi: false }); // Add some documents to the collection items.insert({ name : 'mjolnir', owner: 'thor', maker: 'dwarves' }); items.insert({ name : 'gungnir', owner: 'odin', maker: 'elves' }); items.insert({ name : 'tyrfing', owner: 'Svafrlami', maker: 'dwarves' }); items.insert({ name : 'draupnir', owner: 'odin', maker: 'elves' }); // Find and update an existing document var tyrfing = items.findOne({'name': 'tyrfing'}); tyrfing.owner = 'arngrim'; items.update(tyrfing); // memory adapter is synchronous so i will not bother with callbacks db.saveDatabase(function(err) { var db2 = new loki('sandbox.db', { adapter: mem }); db2.loadDatabase({}); var result = JSON.parse(db2.serializeChanges()); expect(result.length).toEqual(5); expect(result[0].name).toEqual("items"); expect(result[0].operation).toEqual("I"); expect(result[0].obj.name).toEqual("mjolnir"); expect(result[4].name).toEqual("items"); expect(result[4].operation).toEqual("U"); expect(result[4].obj.name).toEqual("tyrfing"); done(); }); }); });
VladimirTechMan/LokiJS
spec/generic/persistence.spec.js
JavaScript
mit
31,627
package net.glowstone.msg; public final class RelativeEntityPositionRotationMessage extends Message { private final int id, deltaX, deltaY, deltaZ, rotation, pitch; public RelativeEntityPositionRotationMessage(int id, int deltaX, int deltaY, int deltaZ, int rotation, int pitch) { this.id = id; this.deltaX = deltaX; this.deltaY = deltaY; this.deltaZ = deltaZ; this.rotation = rotation; this.pitch = pitch; } public int getId() { return id; } public int getDeltaX() { return deltaX; } public int getDeltaY() { return deltaY; } public int getDeltaZ() { return deltaZ; } public int getRotation() { return rotation; } public int getPitch() { return pitch; } @Override public String toString() { return "RelativeEntityPositionRotationMessage{id=" + id + ",deltaX=" + deltaX + ",deltaY=" + deltaY + ",deltaZ=" + deltaZ + "rotation=" + rotation + ",pitch=" + pitch + "}"; } }
karlthepagan/Glowstone
src/main/java/net/glowstone/msg/RelativeEntityPositionRotationMessage.java
Java
mit
1,088
import java.util.Arrays; import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); for (int i = 0; i < n; i++) { int k = sc.nextInt(); int[] input = new int[k]; for (int j = 0; j < k; j++) { input[j] = sc.nextInt(); } System.out.println(count_inversion(input)); } } public static long count_cross(int[] left, int[] right) {; long inversion_count = 0; int i = 0, j = 0; while (i < left.length && j < right.length) { if (left[i] <= right[j]) { i++; } else { inversion_count += left.length - i; j++; } } return inversion_count; } public static void merge(int[] input, int[] L, int[] R) { int l = 0, r = 0, i = 0; while (l < L.length && r < R.length) { if (L[l] <= R[r]) { input[i] = L[l]; i++; l++; } else { input[i] = R[r]; r++; i++; } } while (l < L.length) { input[i] = L[l]; l++; i++; } while (r < R.length) { input[i] = R[r]; r++; i++; } } public static long count_inversion(int[] input) { if (input.length == 1) { return 0; } int mid = input.length >> 2; int[] L = Arrays.copyOfRange(input, 0, mid + 1); int[] R = Arrays.copyOfRange(input, mid + 1, input.length); long left = count_inversion(L); long right = count_inversion(R); long cross_count = count_cross(L, R); long count = left + right + cross_count; merge(input, L, R); return count; } }
yijingbai/LeetCode
SPOJ/CODESPTB_InsersionSort/InsersionSort.java
Java
mit
1,972
module FootballApi class MatchInfo attr_accessor :stadium_name, :attendance, :time, :referee, :id def initialize(hash = {}) @id = hash[:id] @stadium_name = hash[:stadium][:name] if hash[:stadium] @attendance = hash[:attendance][:name] if hash[:attendance] @time = hash[:time][:name] if hash[:time] @referee = hash[:referee][:name] if hash[:referee] end end end
AfonsoTsukamoto/football_api
lib/football_api/match_info.rb
Ruby
mit
445
/* * This file is part of Prism, licensed under the MIT License (MIT). * * Copyright (c) 2015 Helion3 http://helion3.com/ * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.helion3.prism.api.records; public interface Actionable { /** * Reverses the result of this event on a subject * unless the state of the subject has changed since * this event, in way that would conflict. * * For example, if the subject was a block, and * the action removed the block, this will restore * the block at the same location. * * @return ActionableResult Results of applier action */ public ActionableResult rollback() throws Exception; /** * Re-applies the result of this event to a subject, * unless the subject does not exist in a state that * would allow this change. * * @return ActionableResult Results of applier action */ public ActionableResult restore() throws Exception; }
Stonebound/Prism
src/main/java/com/helion3/prism/api/records/Actionable.java
Java
mit
2,008
using System.Collections.Generic; using System.Linq; using FancyTraveller.Domain.Logic; using FancyTraveller.Domain.Model; using FancyTraveller.Domain.POCO; namespace FancyTraveller.Domain.Services { public class RouteService : IRouteService { private readonly IVertexRepository vertexRepository; private readonly IRouteFinder routeFinder; public RouteService(IVertexRepository vertexRepository, IRouteFinder routeFinder) { this.vertexRepository = vertexRepository; this.routeFinder = routeFinder; } #region Implementation of IRouteService public IList<City> AvailableCities { get { return vertexRepository.GetAll().Select(vertex => vertex.SourceCity).Distinct(new CityEqualityComparer()).ToList(); } } public Result FindShortestRoute(int source, int destination, IDictionary<int, IList<Vertex>> vertices) { var result = routeFinder.FindShortestRoute(source, destination, vertices); return new Result() { Distance = result.Item1, VisitedCities = AvailableCities.Where(city => result.Item2.Contains(city.Id)).ToList() }; } public IDictionary<int, IList<Vertex>> LoadDistancesBetweenCities(int[] citiesToSkip) { var dataFromCitiesFile = vertexRepository.GetAll(); IDictionary<int, IList<Vertex>> listOfNeighboursDistance = new Dictionary<int, IList<Vertex>>(); foreach (var d in dataFromCitiesFile) { if(ShouldBeSkipped(d, citiesToSkip)) continue; if (listOfNeighboursDistance.ContainsKey(d.SourceCity.Id)) listOfNeighboursDistance[d.SourceCity.Id].Add(d); else listOfNeighboursDistance.Add(d.SourceCity.Id, new List<Vertex>() { d }); } return listOfNeighboursDistance; } private bool ShouldBeSkipped(Vertex vertex, int[] citiesToSkip) { return citiesToSkip.Contains(vertex.DestinationCity.Id) || citiesToSkip.Contains(vertex.SourceCity.Id); } #endregion } }
tkestowicz/FancyTraveller
FancyTravellerApp/FancyTraveller.Domain/Services/RouteService.cs
C#
mit
2,238
const TYPE_NUMBER = 'number'; export function isNumber(value: unknown): value is number { return typeof value === TYPE_NUMBER || value instanceof Number; }
rumble-charts/rumble-charts
src/helpers/isNumber.ts
TypeScript
mit
161
// module of common directives, filters, etc namespace common { 'use strict'; angular .module('common', []); }
yellownoggin/dkindred
src/client/app/common/common.module.ts
TypeScript
mit
128
/** * Description : This is a test suite that tests an LRS endpoint based on the testing requirements document * found at https://github.com/adlnet/xAPI_LRS_Test/blob/master/TestingRequirements.md * * https://github.com/adlnet/xAPI_LRS_Test/blob/master/TestingRequirements.md * */ (function (module) { "use strict"; // defines overwriting data var INVALID_DATE = '01/011/2015'; var INVALID_NUMERIC = 12345; var INVALID_OBJECT = {key: 'should fail'}; var INVALID_STRING = 'should fail'; var INVALID_UUID_TOO_MANY_DIGITS = 'AA97B177-9383-4934-8543-0F91A7A028368'; var INVALID_UUID_INVALID_LETTER = 'MA97B177-9383-4934-8543-0F91A7A02836'; var INVALID_VERSION_0_9_9 = '0.9.9'; var INVALID_VERSION_1_1_0 = '1.1.0'; var VALID_EXTENSION = {extensions: {'http://example.com/null': null}}; var VALID_VERSION_1_0 = '1.0'; var VALID_VERSION_1_0_9 = '1.0.9'; // configures tests module.exports.config = function () { return [ { name: 'Statements Verify Templates', config: [ { name: 'should pass statement template', templates: [ {statement: '{{statements.default}}'}, {timestamp: '2013-05-18T05:32:34.804Z'} ], expect: [200] } ] }, { name: 'A Statement contains an "actor" property (Multiplicity, 4.1.b)', config: [ { name: 'statement "actor" missing', templates: [ {statement: '{{statements.no_actor}}'} ], expect: [400] } ] }, { name: 'A Statement contains a "verb" property (Multiplicity, 4.1.b)', config: [ { name: 'statement "verb" missing', templates: [ {statement: '{{statements.no_verb}}'} ], expect: [400] } ] }, { name: 'A Statement contains an "object" property (Multiplicity, 4.1.b)', config: [ { name: 'statement "object" missing', templates: [ {statement: '{{statements.no_object}}'} ], expect: [400] } ] }, { name: 'A Statement\'s "id" property is a String (Type, 4.1.1.description.a)', config: [ { name: 'statement "id" invalid numeric', templates: [ {statement: '{{statements.default}}'}, {id: INVALID_NUMERIC} ], expect: [400] }, { name: 'statement "id" invalid object', templates: [ {statement: '{{statements.default}}'}, {id: INVALID_OBJECT} ], expect: [400] } ] }, { name: 'A Statement\'s "id" property is a UUID following RFC 4122 (Syntax, RFC 4122)', config: [ { name: 'statement "id" invalid UUID with too many digits', templates: [ {statement: '{{statements.default}}'}, {id: INVALID_UUID_TOO_MANY_DIGITS} ], expect: [400] }, { name: 'statement "id" invalid UUID with non A-F', templates: [ {statement: '{{statements.default}}'}, {id: INVALID_UUID_INVALID_LETTER} ], expect: [400] } ] }, { name: 'A TimeStamp is defined as a Date/Time formatted according to ISO 8601 (Format, ISO8601)', config: [ { name: 'statement "template" invalid string', templates: [ {statement: '{{statements.default}}'}, {timestamp: INVALID_STRING} ], expect: [400] }, { name: 'statement "template" invalid date', templates: [ {statement: '{{statements.default}}'}, {timestamp: INVALID_DATE} ], expect: [400] } ] }, { name: 'A "timestamp" property is a TimeStamp (Type, 4.1.2.1.table1.row7.a, 4.1.2.1.table1.row7.b)', config: [ { name: 'statement "template" invalid string', templates: [ {statement: '{{statements.default}}'}, {timestamp: INVALID_STRING} ], expect: [400] }, { name: 'statement "template" invalid date', templates: [ {statement: '{{statements.default}}'}, {timestamp: INVALID_DATE} ], expect: [400] } ] }, { name: 'A "stored" property is a TimeStamp (Type, 4.1.2.1.table1.row8.a, 4.1.2.1.table1.row8.b)', config: [ { name: 'statement "stored" invalid string', templates: [ {statement: '{{statements.default}}'}, {stored: INVALID_STRING} ], expect: [400] }, { name: 'statement "stored" invalid date', templates: [ {statement: '{{statements.default}}'}, {stored: INVALID_DATE} ], expect: [400] } ] }, { name: 'A "version" property enters the LRS with the value of "1.0.0" or is not used (Vocabulary, 4.1.10.e, 4.1.10.f)', config: [ { name: 'statement "version" invalid string', templates: [ {statement: '{{statements.default}}'}, {version: INVALID_STRING} ], expect: [400] }, { name: 'statement "version" invalid', templates: [ {statement: '{{statements.default}}'}, {version: INVALID_VERSION_0_9_9} ], expect: [400] } ] }, { name: 'An LRS rejects with error code 400 Bad Request any Statement having a property whose value is set to "null", except in an "extensions" property (4.1.12.d.a)', config: [ { name: 'statement actor should fail on "null"', templates: [ {statement: '{{statements.actor}}'}, {actor: '{{agents.mbox}}'}, {name: null} ], expect: [400] }, { name: 'statement verb should fail on "null"', templates: [ {statement: '{{statements.verb}}'}, {verb: '{{verbs.default}}'}, {display: {'en-US': null}} ], expect: [400] }, { name: 'statement context should fail on "null"', templates: [ {statement: '{{statements.context}}'}, {context: '{{contexts.default}}'}, {registration: null} ], expect: [400] }, { name: 'statement object should fail on "null"', templates: [ {statement: '{{statements.object_activity}}'}, {object: '{{activities.default}}'}, {definition: {moreInfo: null}} ], expect: [400] }, { name: 'statement activity extensions can be empty', templates: [ {statement: '{{statements.object_activity}}'}, {object: '{{activities.no_extensions}}'}, {definition: VALID_EXTENSION} ], expect: [200] }, { name: 'statement result extensions can be empty', templates: [ {statement: '{{statements.result}}'}, {result: '{{results.no_extensions}}'}, VALID_EXTENSION ], expect: [200] }, { name: 'statement context extensions can be empty', templates: [ {statement: '{{statements.context}}'}, {context: '{{contexts.no_extensions}}'}, VALID_EXTENSION ], expect: [200] }, { name: 'statement substatement activity extensions can be empty', templates: [ {statement: '{{statements.object_substatement}}'}, {object: '{{substatements.activity}}'}, {object: '{{activities.no_extensions}}'}, {definition: VALID_EXTENSION} ], expect: [200] }, { name: 'statement substatement result extensions can be empty', templates: [ {statement: '{{statements.object_substatement}}'}, {object: '{{substatements.result}}'}, {result: '{{results.no_extensions}}'}, VALID_EXTENSION ], expect: [200] }, { name: 'statement substatement context extensions can be empty', templates: [ {statement: '{{statements.object_substatement}}'}, {object: '{{substatements.context}}'}, {context: '{{contexts.no_extensions}}'}, VALID_EXTENSION ], expect: [200] } ] }, { name: 'An LRS rejects with error code 400 Bad Request, a Request which uses "version" and has the value set to anything but "1.0" or "1.0.x", where x is the semantic versioning number (Format, 4.1.10.b, 6.2.c, 6.2.f)', config: [ { name: 'statement "version" valid 1.0', templates: [ {statement: '{{statements.default}}'}, {version: VALID_VERSION_1_0} ], expect: [200] }, { name: 'statement "version" valid 1.0.9', templates: [ {statement: '{{statements.default}}'}, {version: VALID_VERSION_1_0_9} ], expect: [200] }, { name: 'statement "version" invalid 0.9.9', templates: [ {statement: '{{statements.default}}'}, {version: INVALID_VERSION_0_9_9} ], expect: [400] }, { name: 'statement "version" invalid 1.1.0', templates: [ {statement: '{{statements.default}}'}, {version: INVALID_VERSION_1_1_0} ], expect: [400] } ] }, { name: 'An LRS rejects with error code 400 Bad Request, a Request which the "X-Experience-API-Version" header\'s value is anything but "1.0" or "1.0.x", where x is the semantic versioning number to any API except the About API (Format, 6.2.d, 6.2.e, 6.2.f, 7.7.f)', config: [ { name: 'statement "version" valid 1.0', templates: [ {statement: '{{statements.default}}'}, {version: VALID_VERSION_1_0} ], expect: [200] }, { name: 'statement "version" valid 1.0.9', templates: [ {statement: '{{statements.default}}'}, {version: VALID_VERSION_1_0_9} ], expect: [200] }, { name: 'statement "version" invalid 0.9.9', templates: [ {statement: '{{statements.default}}'}, {version: INVALID_VERSION_0_9_9} ], expect: [400] }, { name: 'statement "version" invalid 1.1.0', templates: [ {statement: '{{statements.default}}'}, {version: INVALID_VERSION_1_1_0} ], expect: [400] } ] }, { name: 'An LRS rejects with error code 400 Bad Request any Statement violating a Statement Requirement. (4.1.12, Varies)', config: [ { name: 'statement "actor" missing reply 400', templates: [ {statement: '{{statements.no_actor}}'} ], expect: [400] }, { name: 'statement "verb" missing reply 400', templates: [ {statement: '{{statements.no_verb}}'} ], expect: [400] }, { name: 'statement "object" missing reply 400', templates: [ {statement: '{{statements.no_object}}'} ], expect: [400] } ] } ]; }; }(module));
cr8onski/lrs-conformance-test-suite
test/v1_0_2/configs/statements.js
JavaScript
mit
16,935
package creditnote import ( "testing" assert "github.com/stretchr/testify/require" stripe "github.com/stripe/stripe-go/v72" _ "github.com/stripe/stripe-go/v72/testing" ) func TestCreditNoteGet(t *testing.T) { cn, err := Get("cn_123", nil) assert.Nil(t, err) assert.NotNil(t, cn) } func TestCreditNoteList(t *testing.T) { params := &stripe.CreditNoteListParams{ Invoice: stripe.String("in_123"), } i := List(params) // Verify that we can get at least one credit note assert.True(t, i.Next()) assert.Nil(t, i.Err()) assert.NotNil(t, i.CreditNote()) assert.NotNil(t, i.CreditNoteList()) } func TestCreditNoteListLines(t *testing.T) { i := ListLines(&stripe.CreditNoteLineItemListParams{ ID: stripe.String("cn_123"), }) // Verify that we can get at least one invoice assert.True(t, i.Next()) assert.Nil(t, i.Err()) assert.NotNil(t, i.CreditNoteLineItem()) assert.NotNil(t, i.CreditNoteLineItemList()) } func TestCreditNoteListPreviewLines(t *testing.T) { params := &stripe.CreditNoteLineItemListPreviewParams{ Invoice: stripe.String("in_123"), Lines: []*stripe.CreditNoteLineParams{ { Type: stripe.String(string(stripe.CreditNoteLineItemTypeInvoiceLineItem)), Amount: stripe.Int64(100), InvoiceLineItem: stripe.String("ili_123"), TaxRates: stripe.StringSlice([]string{ "txr_123", }), }, }, } i := ListPreviewLines(params) // Verify that we can get at least one invoice assert.True(t, i.Next()) assert.Nil(t, i.Err()) assert.NotNil(t, i.CreditNoteLineItem()) } func TestCreditNoteNew(t *testing.T) { params := &stripe.CreditNoteParams{ Amount: stripe.Int64(100), Invoice: stripe.String("in_123"), Reason: stripe.String(string(stripe.CreditNoteReasonDuplicate)), Lines: []*stripe.CreditNoteLineParams{ { Type: stripe.String(string(stripe.CreditNoteLineItemTypeInvoiceLineItem)), Amount: stripe.Int64(100), InvoiceLineItem: stripe.String("ili_123"), TaxRates: stripe.StringSlice([]string{ "txr_123", }), }, }, } cn, err := New(params) assert.Nil(t, err) assert.NotNil(t, cn) } func TestCreditNoteUpdate(t *testing.T) { params := &stripe.CreditNoteParams{ Params: stripe.Params{ Metadata: map[string]string{ "foo": "bar", }, }, } cn, err := Update("cn_123", params) assert.Nil(t, err) assert.NotNil(t, cn) } func TestCreditNotePreview(t *testing.T) { params := &stripe.CreditNotePreviewParams{ Amount: stripe.Int64(100), Invoice: stripe.String("in_123"), Lines: []*stripe.CreditNoteLineParams{ { Type: stripe.String(string(stripe.CreditNoteLineItemTypeInvoiceLineItem)), Amount: stripe.Int64(100), InvoiceLineItem: stripe.String("ili_123"), TaxRates: stripe.StringSlice([]string{ "txr_123", }), }, }, } cn, err := Preview(params) assert.Nil(t, err) assert.NotNil(t, cn) } func TestCreditNoteVoidCreditNote(t *testing.T) { params := &stripe.CreditNoteVoidParams{} cn, err := VoidCreditNote("cn_123", params) assert.Nil(t, err) assert.NotNil(t, cn) }
stripe/stripe-go
creditnote/client_test.go
GO
mit
3,100
<?php namespace BackOffice\RO\ReservationBundle\DependencyInjection; use Symfony\Component\Config\Definition\Builder\TreeBuilder; use Symfony\Component\Config\Definition\ConfigurationInterface; /** * This is the class that validates and merges configuration from your app/config files * * To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/extension.html#cookbook-bundles-extension-config-class} */ class Configuration implements ConfigurationInterface { /** * {@inheritdoc} */ public function getConfigTreeBuilder() { $treeBuilder = new TreeBuilder(); $rootNode = $treeBuilder->root('reservation'); // Here you should define the parameters that are allowed to // configure your bundle. See the documentation linked above for // more information on that topic. return $treeBuilder; } }
ramisg85/oueslatirami
src/BackOffice/RO/ReservationBundle/DependencyInjection/Configuration.php
PHP
mit
891
CatarsePaypalExpress::Engine.routes.draw do resources :paypal_express, only: [], path: 'payment/paypal_express' do collection do post :ipn end member do get :review match :pay match :success match :cancel end end end
MHBA/catarse_paypal_express
config/routes.rb
Ruby
mit
271
package com.symbolplay.tria.game; public final class CollisionEffects { public static final int JUMP_BOOST = 0; public static final int REPOSITION_PLATFORMS = 1; public static final int VISIBLE_ON_JUMP = 2; public static final int IMPALE_ATTACHED_SPIKES = 3; public static final int REVEAL_ON_JUMP = 4; public static final int IMPALE_SPIKES = 5; public static final int TOGGLE_SPIKES = 6; private static final int NUM_EFFECTS = 7; private final boolean effects[]; private final Object effectData[]; private final JumpBoostCollisionEffectData jumpBoostCollisionEffectData; private final RevealOnJumpCollisionEffectData revealOnJumpCollisionEffectData; public CollisionEffects() { effects = new boolean[NUM_EFFECTS]; effectData = new Object[NUM_EFFECTS]; jumpBoostCollisionEffectData = new JumpBoostCollisionEffectData(); revealOnJumpCollisionEffectData = new RevealOnJumpCollisionEffectData(); } public void clear() { for (int i = 0; i < NUM_EFFECTS; i++) { effects[i] = false; } } public void set(int effect) { set(effect, 0.0f); } public void set(int effect, Object data) { effects[effect] = true; effectData[effect] = data; } public void setJumpBoostEffect(float speed, float soundVolume) { effects[JUMP_BOOST] = true; jumpBoostCollisionEffectData.jumpBoostSpeed = speed; jumpBoostCollisionEffectData.soundVolume = soundVolume; effectData[JUMP_BOOST] = jumpBoostCollisionEffectData; } public void setRevealOnJumpEffect(int[] revealOnJumpIds) { effects[REVEAL_ON_JUMP] = true; revealOnJumpCollisionEffectData.revealOnJumpIds = revealOnJumpIds; effectData[REVEAL_ON_JUMP] = revealOnJumpCollisionEffectData; } public boolean isEffectActive(int effect) { return effects[effect]; } public Object getEffectData(int effect) { return effectData[effect]; } }
mrzli/tria
core/src/com/symbolplay/tria/game/CollisionEffects.java
Java
mit
2,103
<?php /* SVN FILE: $Id: cake_test_case.php 7945 2008-12-19 02:16:01Z gwoo $ */ /** * Short description for file. * * Long description for file * * PHP versions 4 and 5 * * CakePHP(tm) Tests <https://trac.cakephp.org/wiki/Developement/TestSuite> * Copyright 2005-2008, Cake Software Foundation, Inc. (http://www.cakefoundation.org) * * Licensed under The Open Group Test Suite License * Redistributions of files must retain the above copyright notice. * * @filesource * @copyright Copyright 2005-2008, Cake Software Foundation, Inc. (http://www.cakefoundation.org) * @link https://trac.cakephp.org/wiki/Developement/TestSuite CakePHP(tm) Tests * @package cake * @subpackage cake.cake.tests.libs * @since CakePHP(tm) v 1.2.0.4667 * @version $Revision: 7945 $ * @modifiedby $LastChangedBy: gwoo $ * @lastmodified $Date: 2008-12-18 21:16:01 -0500 (Thu, 18 Dec 2008) $ * @license http://www.opensource.org/licenses/opengroup.php The Open Group Test Suite License */ if (!class_exists('dispatcher')) { require CAKE . 'dispatcher.php'; } require_once CAKE_TESTS_LIB . 'cake_test_model.php'; require_once CAKE_TESTS_LIB . 'cake_test_fixture.php'; App::import('Vendor', 'simpletest' . DS . 'unit_tester'); /** * Short description for class. * * @package cake * @subpackage cake.cake.tests.lib */ class CakeTestDispatcher extends Dispatcher { var $controller; var $testCase; function testCase(&$testCase) { $this->testCase =& $testCase; } function _invoke (&$controller, $params, $missingAction = false) { $this->controller =& $controller; if (isset($this->testCase) && method_exists($this->testCase, 'startController')) { $this->testCase->startController($this->controller, $params); } $result = parent::_invoke($this->controller, $params, $missingAction); if (isset($this->testCase) && method_exists($this->testCase, 'endController')) { $this->testCase->endController($this->controller, $params); } return $result; } } /** * Short description for class. * * @package cake * @subpackage cake.cake.tests.lib */ class CakeTestCase extends UnitTestCase { /** * Methods used internally. * * @var array * @access private */ var $methods = array('start', 'end', 'startcase', 'endcase', 'starttest', 'endtest'); var $__truncated = true; var $__savedGetData = array(); /** * By default, all fixtures attached to this class will be truncated and reloaded after each test. * Set this to false to handle manually * * @var array * @access public */ var $autoFixtures = true; /** * Set this to false to avoid tables to be dropped if they already exist * * @var boolean * @access public */ var $dropTables = true; /** * Maps fixture class names to fixture identifiers as included in CakeTestCase::$fixtures * * @var array * @access protected */ var $_fixtureClassMap = array(); /** * Called when a test case (group of methods) is about to start (to be overriden when needed.) * * @param string $method Test method about to get executed. * * @access protected */ function startCase() { } /** * Called when a test case (group of methods) has been executed (to be overriden when needed.) * * @param string $method Test method about that was executed. * * @access protected */ function endCase() { } /** * Called when a test case method is about to start (to be overriden when needed.) * * @param string $method Test method about to get executed. * * @access protected */ function startTest($method) { } /** * Called when a test case method has been executed (to be overriden when needed.) * * @param string $method Test method about that was executed. * * @access protected */ function endTest($method) { } /** * Overrides SimpleTestCase::assert to enable calling of skipIf() from within tests */ function assert(&$expectation, $compare, $message = '%s') { if ($this->_should_skip) { return; } return parent::assert($expectation, $compare, $message); } /** * Overrides SimpleTestCase::skipIf to provide a boolean return value */ function skipIf($shouldSkip, $message = '%s') { parent::skipIf($shouldSkip, $message); return $shouldSkip; } /** * Callback issued when a controller's action is about to be invoked through testAction(). * * @param Controller $controller Controller that's about to be invoked. * @param array $params Additional parameters as sent by testAction(). */ function startController(&$controller, $params = array()) { if (isset($params['fixturize']) && ((is_array($params['fixturize']) && !empty($params['fixturize'])) || $params['fixturize'] === true)) { if (!isset($this->db)) { $this->_initDb(); } if ($controller->uses === false) { $list = array($controller->modelClass); } else { $list = is_array($controller->uses) ? $controller->uses : array($controller->uses); } $models = array(); ClassRegistry::config(array('ds' => $params['connection'])); foreach ($list as $name) { if ((is_array($params['fixturize']) && in_array($name, $params['fixturize'])) || $params['fixturize'] === true) { if (class_exists($name) || App::import('Model', $name)) { $object =& ClassRegistry::init($name); //switch back to specified datasource. $object->setDataSource($params['connection']); $db =& ConnectionManager::getDataSource($object->useDbConfig); $db->cacheSources = false; $models[$object->alias] = array( 'table' => $object->table, 'model' => $object->alias, 'key' => strtolower($name), ); } } } ClassRegistry::config(array('ds' => 'test_suite')); if (!empty($models) && isset($this->db)) { $this->_actionFixtures = array(); foreach ($models as $model) { $fixture =& new CakeTestFixture($this->db); $fixture->name = $model['model'] . 'Test'; $fixture->table = $model['table']; $fixture->import = array('model' => $model['model'], 'records' => true); $fixture->init(); $fixture->create($this->db); $fixture->insert($this->db); $this->_actionFixtures[] =& $fixture; } foreach ($models as $model) { $object =& ClassRegistry::getObject($model['key']); if ($object !== false) { $object->setDataSource('test_suite'); $object->cacheSources = false; } } } } } /** * Callback issued when a controller's action has been invoked through testAction(). * * @param Controller $controller Controller that has been invoked. * * @param array $params Additional parameters as sent by testAction(). */ function endController(&$controller, $params = array()) { if (isset($this->db) && isset($this->_actionFixtures) && !empty($this->_actionFixtures)) { foreach ($this->_actionFixtures as $fixture) { $fixture->drop($this->db); } } } /** * Executes a Cake URL, and can get (depending on the $params['return'] value): * * 1. 'result': Whatever the action returns (and also specifies $this->params['requested'] for controller) * 2. 'view': The rendered view, without the layout * 3. 'contents': The rendered view, within the layout. * 4. 'vars': the view vars * * @param string $url Cake URL to execute (e.g: /articles/view/455) * @param array $params Parameters, or simply a string of what to return * @return mixed Whatever is returned depending of requested result * @access public */ function testAction($url, $params = array()) { $default = array( 'return' => 'result', 'fixturize' => false, 'data' => array(), 'method' => 'post', 'connection' => 'default' ); if (is_string($params)) { $params = array('return' => $params); } $params = array_merge($default, $params); $toSave = array( 'case' => null, 'group' => null, 'app' => null, 'output' => null, 'show' => null, 'plugin' => null ); $this->__savedGetData = (empty($this->__savedGetData)) ? array_intersect_key($_GET, $toSave) : $this->__savedGetData; $data = (!empty($params['data'])) ? $params['data'] : array(); if (strtolower($params['method']) == 'get') { $_GET = array_merge($this->__savedGetData, $data); $_POST = array(); } else { $_POST = array('data' => $data); $_GET = $this->__savedGetData; } $return = $params['return']; $params = array_diff_key($params, array('data' => null, 'method' => null, 'return' => null)); $dispatcher =& new CakeTestDispatcher(); $dispatcher->testCase($this); if ($return != 'result') { if ($return != 'contents') { $params['layout'] = false; } ob_start(); @$dispatcher->dispatch($url, $params); $result = ob_get_clean(); if ($return == 'vars') { $view =& ClassRegistry::getObject('view'); $viewVars = $view->getVars(); $result = array(); foreach ($viewVars as $var) { $result[$var] = $view->getVar($var); } if (!empty($view->pageTitle)) { $result = array_merge($result, array('title' => $view->pageTitle)); } } } else { $params['return'] = 1; $params['bare'] = 1; $params['requested'] = 1; $result = @$dispatcher->dispatch($url, $params); } if (isset($this->_actionFixtures)) { unset($this->_actionFixtures); } ClassRegistry::flush(); return $result; } /** * Announces the start of a test. * * @param string $method Test method just started. * * @access public */ function before($method) { parent::before($method); if (isset($this->fixtures) && (!is_array($this->fixtures) || empty($this->fixtures))) { unset($this->fixtures); } // Set up DB connection if (isset($this->fixtures) && strtolower($method) == 'start') { $this->_initDb(); $this->_loadFixtures(); } // Create records if (isset($this->_fixtures) && isset($this->db) && !in_array(strtolower($method), array('start', 'end')) && $this->__truncated && $this->autoFixtures == true) { foreach ($this->_fixtures as $fixture) { $inserts = $fixture->insert($this->db); } } if (!in_array(strtolower($method), $this->methods)) { $this->startTest($method); } } /** * Runs as first test to create tables. * * @access public */ function start() { if (isset($this->_fixtures) && isset($this->db)) { Configure::write('Cache.disable', true); $cacheSources = $this->db->cacheSources; $this->db->cacheSources = false; $sources = $this->db->listSources(); $this->db->cacheSources = $cacheSources; if (!$this->dropTables) { return; } foreach ($this->_fixtures as $fixture) { if (in_array($fixture->table, $sources)) { $fixture->drop($this->db); $fixture->create($this->db); } elseif (!in_array($fixture->table, $sources)) { $fixture->create($this->db); } } } } /** * Runs as last test to drop tables. * * @access public */ function end() { if (isset($this->_fixtures) && isset($this->db)) { if ($this->dropTables) { foreach (array_reverse($this->_fixtures) as $fixture) { $fixture->drop($this->db); } } $this->db->sources(true); Configure::write('Cache.disable', false); } if (class_exists('ClassRegistry')) { ClassRegistry::flush(); } } /** * Announces the end of a test. * * @param string $method Test method just finished. * * @access public */ function after($method) { if (isset($this->_fixtures) && isset($this->db) && !in_array(strtolower($method), array('start', 'end'))) { foreach ($this->_fixtures as $fixture) { $fixture->truncate($this->db); } $this->__truncated = true; } else { $this->__truncated = false; } if (!in_array(strtolower($method), $this->methods)) { $this->endTest($method); } $this->_should_skip = false; parent::after($method); } /** * Gets a list of test names. Normally that will be all internal methods that start with the * name "test". This method should be overridden if you want a different rule. * * @return array List of test names. * * @access public */ function getTests() { $methods = array_diff(parent::getTests(), array('testAction', 'testaction')); $methods = array_merge(array_merge(array('start', 'startCase'), $methods), array('endCase', 'end')); return $methods; } /** * Chooses which fixtures to load for a given test * * @param string $fixture Each parameter is a model name that corresponds to a fixture, i.e. 'Post', 'Author', etc. * @access public * @see CakeTestCase::$autoFixtures */ function loadFixtures() { $args = func_get_args(); foreach ($args as $class) { if (isset($this->_fixtureClassMap[$class])) { $fixture = $this->_fixtures[$this->_fixtureClassMap[$class]]; $fixture->truncate($this->db); $fixture->insert($this->db); } else { trigger_error("Non-existent fixture class {$class} referenced in test", E_USER_WARNING); } } } /** * Takes an array $expected and generates a regex from it to match the provided $string. Samples for $expected: * * Checks for an input tag with a name attribute (contains any value) and an id attribute that contains 'my-input': * array('input' => array('name', 'id' => 'my-input')) * * Checks for two p elements with some text in them: * array( * array('p' => true), * 'textA', * '/p', * array('p' => true), * 'textB', * '/p' * ) * * You can also specify a pattern expression as part of the attribute values, or the tag being defined, * if you prepend the value with preg: and enclose it with slashes, like so: * array( * array('input' => array('name', 'id' => 'preg:/FieldName\d+/')), * 'preg:/My\s+field/' * ) * * Important: This function is very forgiving about whitespace and also accepts any permutation of attribute order. * It will also allow whitespaces between specified tags. * * @param string $string An HTML/XHTML/XML string * @param array $expected An array, see above * @param string $message SimpleTest failure output string * @access public */ function assertTags($string, $expected, $fullDebug = false) { $regex = array(); $normalized = array(); foreach ((array) $expected as $key => $val) { if (!is_numeric($key)) { $normalized[] = array($key => $val); } else { $normalized[] = $val; } } $i = 0; foreach ($normalized as $tags) { $i++; if (is_string($tags) && $tags{0} == '<') { $tags = array(substr($tags, 1) => array()); } elseif (is_string($tags)) { if (preg_match('/^\*?\//', $tags, $match)) { $prefix = array(null, null); if ($match[0] == '*/') { $prefix = array('Anything, ', '.*?'); } $regex[] = array( sprintf('%sClose %s tag', $prefix[0], substr($tags, strlen($match[0]))), sprintf('%s<[\s]*\/[\s]*%s[\s]*>[\n\r]*', $prefix[1], substr($tags, strlen($match[0]))), $i, ); continue; } if (!empty($tags) && preg_match('/^preg\:\/(.+)\/$/i', $tags, $matches)) { $tags = $matches[1]; $type = 'Regex matches'; } else { $tags = preg_quote($tags, '/'); $type = 'Text equals'; } $regex[] = array( sprintf('%s "%s"', $type, $tags), $tags, $i, ); continue; } foreach ($tags as $tag => $attributes) { $regex[] = array( sprintf('Open %s tag', $tag), sprintf('[\s]*<%s', preg_quote($tag, '/')), $i, ); if ($attributes === true) { $attributes = array(); } $attrs = array(); $explanations = array(); foreach ($attributes as $attr => $val) { if (is_numeric($attr) && preg_match('/^preg\:\/(.+)\/$/i', $val, $matches)) { $attrs[] = $matches[1]; $explanations[] = sprintf('Regex "%s" matches', $matches[1]); continue; } else { $quotes = '"'; if (is_numeric($attr)) { $attr = $val; $val = '.+?'; $explanations[] = sprintf('Attribute "%s" present', $attr); } else if (!empty($val) && preg_match('/^preg\:\/(.+)\/$/i', $val, $matches)) { $quotes = '"?'; $val = $matches[1]; $explanations[] = sprintf('Attribute "%s" matches "%s"', $attr, $val); } else { $explanations[] = sprintf('Attribute "%s" == "%s"', $attr, $val); $val = preg_quote($val, '/'); } $attrs[] = '[\s]+'.preg_quote($attr, '/').'='.$quotes.$val.$quotes; } } if ($attrs) { $permutations = $this->__array_permute($attrs); $permutationTokens = array(); foreach ($permutations as $permutation) { $permutationTokens[] = join('', $permutation); } $regex[] = array( sprintf('%s', join(', ', $explanations)), $permutationTokens, $i, ); } $regex[] = array( sprintf('End %s tag', $tag), '[\s]*\/?[\s]*>[\n\r]*', $i, ); } } foreach ($regex as $i => $assertation) { list($description, $expressions, $itemNum) = $assertation; $matches = false; foreach ((array)$expressions as $expression) { if (preg_match(sprintf('/^%s/s', $expression), $string, $match)) { $matches = true; $string = substr($string, strlen($match[0])); break; } } if (!$matches) { $this->assert(new TrueExpectation(), false, sprintf('Item #%d / regex #%d failed: %s', $itemNum, $i, $description)); if ($fullDebug) { debug($string, true); debug($regex, true); } return false; } } return $this->assert(new TrueExpectation(), true, '%s'); } /** * Generates all permutation of an array $items and returns them in a new array. * * @param array $items An array of items * @return array * @access public */ function __array_permute($items, $perms = array()) { static $permuted; if (empty($perms)) { $permuted = array(); } if (empty($items)) { $permuted[] = $perms; } else { $numItems = count($items) - 1; for ($i = $numItems; $i >= 0; --$i) { $newItems = $items; $newPerms = $perms; list($tmp) = array_splice($newItems, $i, 1); array_unshift($newPerms, $tmp); $this->__array_permute($newItems, $newPerms); } return $permuted; } } /** * Initialize DB connection. * * @access protected */ function _initDb() { $testDbAvailable = in_array('test', array_keys(ConnectionManager::enumConnectionObjects())); $_prefix = null; if ($testDbAvailable) { // Try for test DB restore_error_handler(); @$db =& ConnectionManager::getDataSource('test'); set_error_handler('simpleTestErrorHandler'); $testDbAvailable = $db->isConnected(); } // Try for default DB if (!$testDbAvailable) { $db =& ConnectionManager::getDataSource('default'); $_prefix = $db->config['prefix']; $db->config['prefix'] = 'test_suite_'; } ConnectionManager::create('test_suite', $db->config); $db->config['prefix'] = $_prefix; // Get db connection $this->db =& ConnectionManager::getDataSource('test_suite'); $this->db->cacheSources = false; ClassRegistry::config(array('ds' => 'test_suite')); } /** * Load fixtures specified in var $fixtures. * * @access private */ function _loadFixtures() { if (!isset($this->fixtures) || empty($this->fixtures)) { return; } if (!is_array($this->fixtures)) { $this->fixtures = array_map('trim', explode(',', $this->fixtures)); } $this->_fixtures = array(); foreach ($this->fixtures as $index => $fixture) { $fixtureFile = null; if (strpos($fixture, 'core.') === 0) { $fixture = substr($fixture, strlen('core.')); foreach (Configure::corePaths('cake') as $key => $path) { $fixturePaths[] = $path . DS . 'tests' . DS . 'fixtures'; } } elseif (strpos($fixture, 'app.') === 0) { $fixture = substr($fixture, strlen('app.')); $fixturePaths = array( TESTS . 'fixtures', VENDORS . 'tests' . DS . 'fixtures' ); } elseif (strpos($fixture, 'plugin.') === 0) { $parts = explode('.', $fixture, 3); $pluginName = $parts[1]; $fixture = $parts[2]; $fixturePaths = array( APP . 'plugins' . DS . $pluginName . DS . 'tests' . DS . 'fixtures', TESTS . 'fixtures', VENDORS . 'tests' . DS . 'fixtures' ); $pluginPaths = Configure::read('pluginPaths'); foreach ($pluginPaths as $path) { if (file_exists($path . $pluginName . DS . 'tests' . DS. 'fixtures')) { $fixturePaths[0] = $path . $pluginName . DS . 'tests' . DS. 'fixtures'; break; } } } else { $fixturePaths = array( TESTS . 'fixtures', VENDORS . 'tests' . DS . 'fixtures', TEST_CAKE_CORE_INCLUDE_PATH . DS . 'cake' . DS . 'tests' . DS . 'fixtures' ); } foreach ($fixturePaths as $path) { if (is_readable($path . DS . $fixture . '_fixture.php')) { $fixtureFile = $path . DS . $fixture . '_fixture.php'; break; } } if (isset($fixtureFile)) { require_once($fixtureFile); $fixtureClass = Inflector::camelize($fixture) . 'Fixture'; $this->_fixtures[$this->fixtures[$index]] =& new $fixtureClass($this->db); $this->_fixtureClassMap[Inflector::camelize($fixture)] = $this->fixtures[$index]; } } if (empty($this->_fixtures)) { unset($this->_fixtures); } } } ?>
tectronics/fambom
cake/tests/lib/cake_test_case.php
PHP
mit
21,057
#include "ofApp.h" #include "SharedUtils.h" void updatePuppet(Skeleton* skeleton, ofxPuppet& puppet) { for(int i = 0; i < skeleton->size(); i++) { puppet.setControlPoint(skeleton->getControlIndex(i), skeleton->getPositionAbsolute(i)); } } //-------------------------------------------------------------- void ofApp::setup(){ scenes.push_back(new NoneScene(&puppet, &handSkeleton, &immutableHandSkeleton)); scenes.push_back(new WaveScene(&puppet, &handSkeleton, &immutableHandSkeleton)); scenes.push_back(new WiggleScene(&puppet, &handSkeleton, &immutableHandSkeleton)); scenes.push_back(new WobbleScene(&puppet, &handSkeleton, &immutableHandSkeleton)); scenes.push_back(new EqualizeScene(&puppet, &handSkeleton, &immutableHandSkeleton)); scenes.push_back(new NorthScene(&puppet, &handSkeleton, &immutableHandSkeleton)); scenes.push_back(new MeanderScene(&puppet, &handSkeleton, &immutableHandSkeleton)); scenes.push_back(new SinusoidalLengthScene(&puppet, &handSkeleton, &immutableHandSkeleton)); scenes.push_back(new MiddleDifferentLengthScene(&puppet, &handSkeleton, &immutableHandSkeleton)); scenes.push_back(new StartrekScene(&puppet, &handSkeleton, &immutableHandSkeleton)); scenes.push_back(new PropogatingWiggleScene(&puppet, &handWithFingertipsSkeleton, &immutableHandWithFingertipsSkeleton)); scenes.push_back(new PulsatingPalmScene(&puppet, &palmSkeleton, &immutablePalmSkeleton)); scenes.push_back(new RetractingFingersScene(&puppet, &handWithFingertipsSkeleton, &immutableHandWithFingertipsSkeleton)); scenes.push_back(new StraightenFingersScene(&puppet, &handWithFingertipsSkeleton, &immutableHandWithFingertipsSkeleton)); scenes.push_back(new SplayFingersScene(&puppet, &handWithFingertipsSkeleton, &immutableHandWithFingertipsSkeleton)); scenes.push_back(new PropogatingWiggleScene(&puppet, &handWithFingertipsSkeleton, &immutableHandWithFingertipsSkeleton)); scenes.push_back(new SinusoidalWiggleScene(&puppet, &handWithFingertipsSkeleton, &immutableHandWithFingertipsSkeleton)); scenes.push_back(new GrowingMiddleFingerScene(&puppet, &handWithFingertipsSkeleton, &immutableHandWithFingertipsSkeleton)); scenes.push_back(new PinkyPuppeteerScene(&puppet, &handWithFingertipsSkeleton, &immutableHandWithFingertipsSkeleton)); scenes.push_back(new FingerLengthPuppeteerScene(&puppet, &handWithFingertipsSkeleton, &immutableHandWithFingertipsSkeleton)); scenes.push_back(new LissajousScene(&puppet, &threePointSkeleton, &immutableThreePointSkeleton)); sharedSetup(); string basePath = ofToDataPath("", true); ofSetDataPathRoot("../../../../../SharedData2013/"); // for Golan's machine. Don't delete, please! setupGui(); hand.loadImage("hand/genericHandCenteredNew.jpg"); mesh.load("hand/handmarksNew.ply"); for (int i = 0; i < mesh.getNumVertices(); i++) { mesh.addTexCoord(mesh.getVertex(i)); } //---------------------------- // Set up the puppet. puppet.setup(mesh); //---------------------------- // Set up all of the skeletons. previousSkeleton = NULL; currentSkeleton = NULL; handSkeleton.setup(mesh); immutableHandSkeleton.setup(mesh); handWithFingertipsSkeleton.setup(mesh); immutableHandWithFingertipsSkeleton.setup(mesh); palmSkeleton.setup(mesh); immutablePalmSkeleton.setup(mesh); wristSpineSkeleton.setup(mesh); immutableWristSpineSkeleton.setup(mesh); threePointSkeleton.setup(mesh); immutableThreePointSkeleton.setup(mesh); // Initialize gui features mouseControl = false; showImage = true; showWireframe = true; showSkeleton = true; frameBasedAnimation = false; showGuis = true; sceneRadio = 0; } void ofApp::setupGui() { // set up the guis for each scene for (int i=0; i < scenes.size(); i++) { sceneNames.push_back(scenes[i]->getName()); sceneWithSkeletonNames.push_back(scenes[i]->getNameWithSkeleton()); scenes[i]->setupGui(); scenes[i]->setupMouseGui(); } } //-------------------------------------------------------------- void ofApp::update(){ handSkeleton.setup(mesh); immutableHandSkeleton.setup(mesh); // get the current scene int scene = sceneRadio;//getSelection(0); scenes[scene]->update(); setSkeleton(scenes[scene]->getSkeleton()); // update the puppet using the current scene's skeleton updatePuppet(currentSkeleton, puppet); puppet.update(); } //-------------------------------------------------------------- void ofApp::draw(){ ofBackground(0); ofSetColor(255); if (showImage) { hand.bind(); puppet.drawFaces(); hand.unbind(); } if(showWireframe) { puppet.drawWireframe(); puppet.drawControlPoints(); } if(showSkeleton) { currentSkeleton->draw(); } int scene = sceneRadio; scenes[scene]->draw(); } void ofApp::setSkeleton(Skeleton* skeleton) { if(skeleton != currentSkeleton) { previousSkeleton = currentSkeleton; currentSkeleton = skeleton; if(previousSkeleton != NULL) { vector<int>& previousControlIndices = previousSkeleton->getControlIndices(); for(int i = 0; i < previousControlIndices.size(); i++) { puppet.removeControlPoint(previousControlIndices[i]); } } vector<int>& currentControlIndices = currentSkeleton->getControlIndices(); for(int i = 0; i < currentControlIndices.size(); i++) { puppet.setControlPoint(currentControlIndices[i]); } } } //-------------------------------------------------------------- void ofApp::keyPressed(int key){ switch(key){ case OF_KEY_RIGHT : sceneRadio = (sceneRadio+1) % scenes.size(); cout << "scene " << sceneRadio << endl; break; case OF_KEY_LEFT : sceneRadio -=1; if(sceneRadio<0)sceneRadio = scenes.size()-1; cout << "scene " << sceneRadio << endl; break; } } //-------------------------------------------------------------- void ofApp::keyReleased(int key){ } //-------------------------------------------------------------- void ofApp::mouseMoved(int x, int y ){ } //-------------------------------------------------------------- void ofApp::mouseDragged(int x, int y, int button){ } //-------------------------------------------------------------- void ofApp::mousePressed(int x, int y, int button){ } //-------------------------------------------------------------- void ofApp::mouseReleased(int x, int y, int button){ } //-------------------------------------------------------------- void ofApp::windowResized(int w, int h){ } //-------------------------------------------------------------- void ofApp::gotMessage(ofMessage msg){ } //-------------------------------------------------------------- void ofApp::dragEvent(ofDragInfo dragInfo){ }
CreativeInquiry/digital_art_2014
MeshTester/src/ofApp.cpp
C++
mit
6,809
<?php namespace Home\Controller; use Think\Controller; class AddressController extends Controller { protected function _initialize () { if (!session('user')) { if (IS_AJAX) { $this->ajaxReturn(['status'=>2, 'info'=>'请登陆之后在执行此操作!']); } else { $this->error('您还没有登陆,没有权限进行此操作!正在跳转到首页...', '/Index/index', 2); } } } public function del () { $address_id = I('post.address_id'); if (D('Address')->where(['address_id' => $address_id])->delete()) { $this->ajaxReturn(['status'=>1, 'info'=>'删除成功!']); } else { $this->ajaxReturn(['status'=>2, 'info'=>'删除失败!']); } } public function add () { $address = D('Address'); $_POST['user_id'] = session('user.user_id'); if($address->create(null, 1)){ $address_id = $address->add(); if ($address_id) { $this->ajaxReturn(['status'=>1, 'info'=>'添加成功!']); } else { $this->ajaxReturn(['status'=>2, 'info'=>'添加失败!']); } } else { $this->ajaxReturn(['status'=>2, 'info'=>$address->getError()]); } } public function edit () { $address = D('Address'); if($address->create(null, 2)){ $address_id = $address->where(['address_id' => I('post.address_id')])->save(); if ($address_id) { $this->ajaxReturn(['status'=>1, 'info'=>'保存成功!']); } else { $this->ajaxReturn(['status'=>2, 'info'=>'保存失败!']); } } else { $this->ajaxReturn(['status'=>2, 'info'=>$address->getError()]); } } public function getForm () { $content = $this->fetch('form'); $this->ajaxReturn(['status'=>1, 'content'=>$content]); } public function setAddress () { $address = D('Address'); $address->where(['user_id' => session('user.user_id'), 'is_default' => 1])->setField('is_default', 0); if ($address->where(['address_id' => I('post.address_id')])->setField('is_default', 1) >= 0) { $this->ajaxReturn(['status'=>1, 'info'=>'设置成功!']); } else { $this->ajaxReturn(['status'=>2, 'info'=>'设置失败!']); } } public function getAddress () { return D('Address')->where(['user_id' => session('user.user_id')])->order('is_default desc')->select(); } }
hookidea/yiwukongjian
Application/Home/Controller/AddressController.class.php
PHP
mit
2,650
public class ENG { }
zacswolf/CompSciProjects
Java (AP CompSci)/Eclipse/RankedGPA/src/ENG.java
Java
mit
23
require "rails_helper" RSpec.describe FormsController do describe "#index" do context "when an application has been started" do it "renders the index page" do current_app = create(:common_application) session[:current_application_id] = current_app.id get :index expect(response).to render_template(:index) end end end describe ".skip?" do it "defaults to false" do expect(FormsController.skip?(double("foo"))).to eq(false) end end describe "#application_title" do context "when no application present yet" do it "returns a string for all programs" do expect(controller.application_title).to eq("Food Assistance + Healthcare Coverage") end end context "when only applying for food assistance" do it "returns Food Assistance" do current_app = create(:common_application, navigator: build(:application_navigator, applying_for_food: true)) session[:current_application_id] = current_app.id expect(controller.application_title).to eq("Food Assistance") end end context "when only applying for healthcare coverage" do it "returns Healthcare Coverage" do current_app = create(:common_application, navigator: build(:application_navigator, applying_for_healthcare: true)) session[:current_application_id] = current_app.id expect(controller.application_title).to eq("Healthcare Coverage") end end context "when only applying for all programs" do it "returns Food Assistance + Healthcare Coverage" do current_app = create(:common_application, navigator: build(:application_navigator, applying_for_healthcare: true, applying_for_food: true)) session[:current_application_id] = current_app.id expect(controller.application_title).to eq("Food Assistance + Healthcare Coverage") end end end end
codeforamerica/michigan-benefits
spec/controllers/forms_controller_spec.rb
Ruby
mit
2,108
import { MutableRefObject, useEffect, useMemo, useState } from 'react'; import { useApi } from '@proton/components'; import { addMilliseconds } from '@proton/shared/lib/date-fns-utc'; import { Calendar as tsCalendar } from '@proton/shared/lib/interfaces/calendar'; import { noop } from '@proton/shared/lib/helpers/function'; import { DAY, MINUTE } from '@proton/shared/lib/constants'; import getCalendarsAlarmsCached from './getCalendarsAlarmsCached'; import { CalendarsAlarmsCache } from './CacheInterface'; const PADDING = 2 * MINUTE; export const getCalendarsAlarmsCache = ({ start = new Date(2000, 1, 1), end = new Date(2000, 1, 1), } = {}): CalendarsAlarmsCache => ({ calendarsCache: {}, start, end, }); const useCalendarsAlarms = ( calendars: tsCalendar[], cacheRef: MutableRefObject<CalendarsAlarmsCache>, lookAhead = 2 * DAY ) => { const api = useApi(); const [forceRefresh, setForceRefresh] = useState<any>(); const calendarIDs = useMemo(() => calendars.map(({ ID }) => ID), [calendars]); useEffect(() => { let timeoutHandle = 0; let unmounted = false; const update = async () => { const now = new Date(); // Cache is invalid if (+cacheRef.current.end - PADDING <= +now) { cacheRef.current = getCalendarsAlarmsCache({ start: now, end: addMilliseconds(now, lookAhead), }); cacheRef.current.rerender = () => setForceRefresh({}); } const promise = getCalendarsAlarmsCached(api, cacheRef.current.calendarsCache, calendarIDs, [ cacheRef.current.start, cacheRef.current.end, ]); cacheRef.current.promise = promise; if (timeoutHandle) { clearTimeout(timeoutHandle); } await promise; // If it's not the latest, ignore if (unmounted || promise !== cacheRef.current.promise) { return; } const delay = Math.max(0, +cacheRef.current.end - PADDING - Date.now()); timeoutHandle = window.setTimeout(() => { update().catch(noop); }, delay); setForceRefresh({}); }; update().catch(noop); cacheRef.current.rerender = () => setForceRefresh({}); return () => { cacheRef.current.rerender = undefined; unmounted = true; clearTimeout(timeoutHandle); }; }, [calendarIDs]); return useMemo(() => { const { calendarsCache } = cacheRef.current; return calendarIDs .map((calendarID) => { return calendarsCache[calendarID]?.result ?? []; }) .flat() .sort((a, b) => { return a.Occurrence - b.Occurrence; }); }, [forceRefresh, calendarIDs]); }; export default useCalendarsAlarms;
ProtonMail/WebClient
applications/calendar/src/app/containers/alarms/useCalendarsAlarms.ts
TypeScript
mit
3,017
class ArrowSprite extends Phaser.Sprite { constructor(game, x, y) { super(game, x, y, 'arrow'); this.game.stage.addChild(this); this.scale.set(0.2); this.alpha = 0.2; this.anchor.setTo(0.5, 1.3); this.animations.add('rotate', [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13], 30, true); this.animations.play('rotate', 30, true); this.currentlyControlling = 'player'; } updatePosition(playerObject, wormObject) { this.x = this.currentlyControlling === 'player' ? playerObject.x : wormObject.x; this.x -= this.game.camera.x; // Shift with camera position this.y = this.currentlyControlling === 'player' ? playerObject.y : wormObject.y; let playerHoldsOn = this.currentlyControlling === 'player' && playerObject.body.velocity.x === 0; let wormHoldsOn = this.currentlyControlling === 'worm' && wormObject.body.velocity.x === 0 && wormObject.body.velocity.y === 0; if (playerHoldsOn || wormHoldsOn) { this.scale.set(0.8); this.anchor.setTo(0.5, 1); } else { this.anchor.setTo(0.5, 1.3); this.scale.set(0.2); } } // Note: 'this' here is context from Main! static switchPlayer () { if (this.tabButton.arrow.currentlyControlling === 'player') { this.tabButton.arrow.currentlyControlling = 'worm'; this.game.camera.follow(this.wormObject); } else { this.tabButton.arrow.currentlyControlling = 'player'; this.game.camera.follow(this.playerObject); } } } export default ArrowSprite;
babruix/alien_worm_game
src/objects/Arrow.js
JavaScript
mit
1,556
import { Injectable } from '@angular/core'; @Injectable() export class DummyService { // eslint-disable-next-line no-useless-constructor constructor() {} getItems() { return new Promise(resolve => { setTimeout(() => { resolve(['Joe', 'Jane']); }, 2000); }); } }
storybooks/react-storybook
examples/angular-cli/src/stories/moduleMetadata/dummy.service.ts
TypeScript
mit
300
require "danger/commands/local_helpers/pry_setup" RSpec.describe Danger::PrySetup do before { cleanup } after { cleanup } describe "#setup_pry" do it "copies the Dangerfile and appends bindings.pry" do Dir.mktmpdir do |dir| dangerfile_path = "#{dir}/Dangerfile" File.write(dangerfile_path, "") dangerfile_copy = described_class .new(testing_ui) .setup_pry(dangerfile_path) expect(File).to exist(dangerfile_copy) expect(File.read(dangerfile_copy)).to include("binding.pry; File.delete(\"_Dangerfile.tmp\")") end end it "doesn't copy a nonexistant Dangerfile" do described_class.new(testing_ui).setup_pry("") expect(File).not_to exist("_Dangerfile.tmp") end it "warns when the pry gem is not installed" do ui = testing_ui expect(Kernel).to receive(:require).with("pry").and_raise(LoadError) expect do described_class.new(ui).setup_pry("Dangerfile") end.to raise_error(SystemExit) expect(ui.err_string).to include("Pry was not found") end def cleanup File.delete "_Dangerfile.tmp" if File.exist? "_Dangerfile.tmp" end end end
KrauseFx/danger
spec/lib/danger/commands/local_helpers/pry_setup_spec.rb
Ruby
mit
1,200
class HomeController < ApplicationController skip_authorization_check def index @project_promotions = ProjectPromotion.includes(:project => :brand).order("projects.title") @tags_by_category = Tag.includes(:tag_category, :projects).order(:name).group_by(&:tag_category) end end
nbudin/larp_library
app/controllers/home_controller.rb
Ruby
mit
292
module Overcast class Color def self.darken(hex, amount=0.5) hex = remove_pound(hex) rgb = convert_to_rgb(hex).map{|element| element * amount } convert_to_hex(rgb) end def self.lighten(hex, amount=0.5) hex = remove_pound(hex) rgb = convert_to_rgb(hex).map{ |element| [(element + 255 * amount).round, 255].min } convert_to_hex(rgb) end private def self.remove_pound(hex) hex.gsub('#', '') end def self.convert_to_rgb(hex) hex.scan(/../).map {|color| color.hex} end def self.convert_to_hex(rgb) "#%02x%02x%02x" % rgb end end end
jespr/overcast
lib/overcast/color.rb
Ruby
mit
633
#include "Receiver.h" #include "ofGraphics.h" #include "Utils.h" namespace ofxSpout { //---------- Receiver::Receiver() : defaultFormat(GL_RGBA) { this->spoutReceiver = nullptr; } //---------- Receiver::~Receiver() { this->release(); } //---------- bool Receiver::init(std::string channelName) { this->release(); try { this->spoutReceiver = new SpoutReceiver(); //name provided, so let's use it if (!channelName.empty()) { this->spoutReceiver->SetReceiverName(channelName.c_str()); } return true; } catch (const char * e) { ofLogError(__FUNCTION__) << "Channel : " << channelName << " : " << e; return false; } } //---------- void Receiver::release() { if (this->isInitialized()) { this->spoutReceiver->ReleaseReceiver(); delete this->spoutReceiver; this->spoutReceiver = nullptr; } } //---------- bool Receiver::isInitialized() const { if (this->spoutReceiver) { return true; } else { return false; } } //---------- bool Receiver::receive(ofTexture & texture) { try { //check if we're initialised if (!this->isInitialized()) { throw("Not initialized"); } //check if the texture is allocated correctly, if not, allocate it if (this->spoutReceiver->IsUpdated()) { texture.allocate(this->spoutReceiver->GetSenderWidth(), this->spoutReceiver->GetSenderHeight(), GL_RGBA); } //pull data into the texture (keep any existing fbo attachments) GLint drawFboId = 0; glGetIntegerv(GL_DRAW_FRAMEBUFFER_BINDING, &drawFboId); if (!this->spoutReceiver->ReceiveTextureData(texture.getTextureData().textureID, texture.getTextureData().textureTarget, drawFboId)) { throw("Can't receive texture"); } return true; } catch (const char * e) { ofLogError(__FUNCTION__) << e; return false; } } //---------- bool Receiver::selectSenderPanel() { try { if (!this->isInitialized()) { throw("Not initialized"); } this->spoutReceiver->SelectSender(); return true; } catch (const char * e) { ofLogError(__FUNCTION__) << e; return false; } } //----------- std::string Receiver::getChannelName() const { if (this->isInitialized()) { return this->spoutReceiver->GetSenderName(); } return ""; } //---------- float Receiver::getWidth() const { if (this->isInitialized()) { return this->spoutReceiver->GetSenderWidth(); } return 0; } //---------- float Receiver::getHeight() const { if (this->isInitialized()) { return this->spoutReceiver->GetSenderHeight(); } return 0; } }
elliotwoods/ofxSpout
src/ofxSpout/Receiver.cpp
C++
mit
2,691
class RenameUserIdInContacts < ActiveRecord::Migration def self.up rename_column "contacts", "user_id", "az_user_id" end def self.down rename_column "contacts", "az_user_id", "user_id" end end
stg34/azalo
db/migrate/20100709182724_rename_user_id_in_contacts.rb
Ruby
mit
210
<header class="banner" role="banner"> <nav role="navigation" class="navbar navbar-inverse"> <div class="container"> <!-- Brand and toggle get grouped for better mobile display --> <div class="navbar-header"> <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="brand navbar-brand" href="<?= esc_url(home_url('/')); ?>"><?php bloginfo('name'); ?></a> </div> <!-- Collect the nav links, forms, and other content for toggling --> <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1"> <?php if (has_nav_menu('primary_navigation')) : wp_nav_menu(['theme_location' => 'primary_navigation', 'menu_class' => 'nav navbar-nav']); endif; ?> </div><!-- /.navbar-collapse --> </div><!-- /.container-fluid --> </nav> </header> <div class="feature-box" style="background-image: url('/app/uploads/2015/08/Spartan_Race_-_Muddy_Hit-web.jpg'); background-size: cover;"> <img class="logo center-block" src="/app/uploads/2015/08/average-ocr_web.png" alt="average-ocr_web" width="150" height="150" /> </div>
obelis/AverageOCR
web/app/themes/averageocr/templates/header.php
PHP
mit
1,410
import random color_names=[ 'aliceblue', 'antiquewhite', 'aqua', 'aquamarine', 'azure', 'beige', 'bisque', 'blanchedalmond', 'blue', 'blueviolet', 'brown', 'burlywood', 'cadetblue', 'chartreuse', 'chocolate', 'coral', 'cornflowerblue', 'cornsilk', 'crimson', 'cyan', 'darkblue', 'darkcyan', 'darkgoldenrod', 'darkgray', 'darkgreen', 'darkkhaki', 'darkmagenta', 'darkolivegreen', 'darkorange', 'darkorchid', 'darkred', 'darksalmon', 'darkseagreen', 'darkslateblue', 'darkturquoise', 'darkviolet', 'deeppink', 'deepskyblue', 'dimgray', 'dodgerblue', 'firebrick', 'floralwhite', 'forestgreen', 'fuchsia', 'gainsboro', 'ghostwhite', 'gold', 'goldenrod', 'gray', 'green', 'greenyellow', 'honeydew', 'hotpink', 'indianred', 'indigo', 'ivory', 'khaki', 'lavender', 'lavenderblush', 'lawngreen', 'lemonchiffon', 'lightblue', 'lightcoral', 'lightcyan', 'lightgoldenrodyellow', 'lightgreen', 'lightgray', 'lightpink', 'lightsalmon', 'lightseagreen', 'lightskyblue', 'lightslategray', 'lightsteelblue', 'lightyellow', 'lime', 'limegreen', 'linen', 'magenta', 'maroon', 'mediumaquamarine', 'mediumblue', 'mediumorchid', 'mediumpurple', 'mediumseagreen', 'mediumslateblue', 'mediumspringgreen', 'mediumturquoise', 'mediumvioletred', 'mintcream', 'mistyrose', 'moccasin', 'navajowhite', 'navy', 'oldlace', 'olive', 'olivedrab', 'orange', 'orangered', 'orchid', 'palegoldenrod', 'palegreen', 'paleturquoise', 'palevioletred', 'papayawhip', 'peachpuff', 'peru', 'pink', 'plum', 'powderblue', 'purple', 'red', 'rosybrown', 'royalblue', 'saddlebrown', 'salmon', 'sandybrown', 'seagreen', 'seashell', 'sienna', 'silver', 'skyblue', 'slateblue', 'slategray', 'snow', 'springgreen', 'steelblue', 'tan', 'teal', 'thistle', 'tomato', 'turquoise', 'violet', 'wheat', 'white', 'whitesmoke', 'yellow', 'yellowgreen', ] def getRandomColors(num): if num > len(color_names): return color_names ns = set() while num > len(ns): ns.add(random.choice(color_names)) return list(ns)
largetalk/tenbagger
draw/colors.py
Python
mit
2,176
using System.Collections.Generic; using System.Text; namespace SourceGenerators { internal static class Templates { public static string AppRoutes(IEnumerable<string> allRoutes) { // hard code the namespace for now var sb = new StringBuilder(@" using System.Collections.Generic; using System.Collections.ObjectModel; namespace BlazorApp1 { public static class AppRoutes { public static ReadOnlyCollection<string> Routes { get; } = new ReadOnlyCollection<string>( new List<string> { "); foreach (var route in allRoutes) { sb.AppendLine($"\"{route}\","); } sb.Append(@" } ); } }"); return sb.ToString(); } public static string PageDetail() { return @" namespace BlazorApp1 { public record PageDetail(string Route, string Title, string Icon); } "; } public static string MenuItemAttribute() { return @" namespace BlazorApp1 { public class MenuItemAttribute : System.Attribute { public string Icon { get; } public string Description { get; } public int Order { get; } public MenuItemAttribute( string icon, string description, int order = 0 ) { Icon = icon; Description = description; Order = order; } } } "; } public static string MenuPages(IEnumerable<RouteableComponent> pages) { // hard code the namespace for now var sb = new StringBuilder(@" using System.Collections.Generic; using System.Collections.ObjectModel; namespace BlazorApp1 { public static class PageDetails { public static ReadOnlyCollection<PageDetail> MenuPages { get; } = new ReadOnlyCollection<PageDetail>( new List<PageDetail> { "); foreach (var page in pages) { sb.AppendLine($"new PageDetail(\"{page.Route}\", \"{page.Title}\", \"{page.Icon}\"),"); } sb.Append(@" } ); } }"); return sb.ToString(); } } }
andrewlock/blog-examples
BlazorPreRender/BlazorApp1/SourceGenerators/Templates.cs
C#
mit
2,345
#region Copyright //-------------------------------------------------------------------------------------------------------- // <copyright file="RecentChanges.ascx.cs" company="DNN Corp®"> // DNN Corp® - http://www.dnnsoftware.com Copyright (c) 2002-2013 by DNN Corp® // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and // associated documentation files (the "Software"), to deal in the Software without restriction, // including without limitation the rights to use, copy, modify, merge, publish, distribute, // sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT // NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // </copyright> ////-------------------------------------------------------------------------------------------------------- #endregion Copyright using DotNetNuke.Services.Localization; using DotNetNuke.Wiki.Utilities; namespace DotNetNuke.Wiki.Views { /// <summary> /// Recent changes class based on WikiModuleBase /// </summary> public partial class RecentChanges : WikiModuleBase { #region Constructor /// <summary> /// Initializes a new instance of the <see cref="RecentChanges"/> class. /// </summary> public RecentChanges() { this.Load += this.Page_Load; } #endregion Constructor #region Events /// <summary> /// Handles the Click event of the Last 7 Days control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event /// data.</param> protected void CmdLast7Days_Click(object sender, System.EventArgs e) { this.HitTable.Text = this.CreateRecentChangeTable(7); } /// <summary> /// Handles the Click event of the Last 24 hours control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event /// data.</param> protected void CmdLast24Hrs_Click(object sender, System.EventArgs e) { this.HitTable.Text = this.CreateRecentChangeTable(1); } /// <summary> /// Handles the Click event of the Last Month control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event /// data.</param> protected void CmdLastMonth_Click(object sender, System.EventArgs e) { this.HitTable.Text = this.CreateRecentChangeTable(31); } /// <summary> /// Handles the Load event of the Page control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.EventArgs" /> instance containing the event /// data.</param> public new void Page_Load(object sender, System.EventArgs e) { this.LoadLocalization(); if (!this.IsPostBack) { this.HitTable.Text = this.CreateRecentChangeTable(1); } } #endregion Events #region Methods /// <summary> /// Loads the localization. /// </summary> private void LoadLocalization() { this.TitleLbl.Text = Localization.GetString("RCTitle", this.RouterResourceFile); this.cmdLast24Hrs.Text = Localization.GetString("RCLast24h", this.RouterResourceFile); this.cmdLast7Days.Text = Localization.GetString("RCLast7d", this.RouterResourceFile); this.cmdLastMonth.Text = Localization.GetString("RCLastMonth", this.RouterResourceFile); } #endregion Methods } }
DNNCommunity/DNN.Wiki
Views/RecentChanges.ascx.cs
C#
mit
4,659
package ku_TR import ( "testing" "time" "github.com/go-playground/locales" "github.com/go-playground/locales/currency" ) func TestLocale(t *testing.T) { trans := New() expected := "ku_TR" if trans.Locale() != expected { t.Errorf("Expected '%s' Got '%s'", expected, trans.Locale()) } } func TestPluralsRange(t *testing.T) { trans := New() tests := []struct { expected locales.PluralRule }{ // { // expected: locales.PluralRuleOther, // }, } rules := trans.PluralsRange() // expected := 1 // if len(rules) != expected { // t.Errorf("Expected '%d' Got '%d'", expected, len(rules)) // } for _, tt := range tests { r := locales.PluralRuleUnknown for i := 0; i < len(rules); i++ { if rules[i] == tt.expected { r = rules[i] break } } if r == locales.PluralRuleUnknown { t.Errorf("Expected '%s' Got '%s'", tt.expected, r) } } } func TestPluralsOrdinal(t *testing.T) { trans := New() tests := []struct { expected locales.PluralRule }{ // { // expected: locales.PluralRuleOne, // }, // { // expected: locales.PluralRuleTwo, // }, // { // expected: locales.PluralRuleFew, // }, // { // expected: locales.PluralRuleOther, // }, } rules := trans.PluralsOrdinal() // expected := 4 // if len(rules) != expected { // t.Errorf("Expected '%d' Got '%d'", expected, len(rules)) // } for _, tt := range tests { r := locales.PluralRuleUnknown for i := 0; i < len(rules); i++ { if rules[i] == tt.expected { r = rules[i] break } } if r == locales.PluralRuleUnknown { t.Errorf("Expected '%s' Got '%s'", tt.expected, r) } } } func TestPluralsCardinal(t *testing.T) { trans := New() tests := []struct { expected locales.PluralRule }{ // { // expected: locales.PluralRuleOne, // }, // { // expected: locales.PluralRuleOther, // }, } rules := trans.PluralsCardinal() // expected := 2 // if len(rules) != expected { // t.Errorf("Expected '%d' Got '%d'", expected, len(rules)) // } for _, tt := range tests { r := locales.PluralRuleUnknown for i := 0; i < len(rules); i++ { if rules[i] == tt.expected { r = rules[i] break } } if r == locales.PluralRuleUnknown { t.Errorf("Expected '%s' Got '%s'", tt.expected, r) } } } func TestRangePlurals(t *testing.T) { trans := New() tests := []struct { num1 float64 v1 uint64 num2 float64 v2 uint64 expected locales.PluralRule }{ // { // num1: 1, // v1: 1, // num2: 2, // v2: 2, // expected: locales.PluralRuleOther, // }, } for _, tt := range tests { rule := trans.RangePluralRule(tt.num1, tt.v1, tt.num2, tt.v2) if rule != tt.expected { t.Errorf("Expected '%s' Got '%s'", tt.expected, rule) } } } func TestOrdinalPlurals(t *testing.T) { trans := New() tests := []struct { num float64 v uint64 expected locales.PluralRule }{ // { // num: 1, // v: 0, // expected: locales.PluralRuleOne, // }, // { // num: 2, // v: 0, // expected: locales.PluralRuleTwo, // }, // { // num: 3, // v: 0, // expected: locales.PluralRuleFew, // }, // { // num: 4, // v: 0, // expected: locales.PluralRuleOther, // }, } for _, tt := range tests { rule := trans.OrdinalPluralRule(tt.num, tt.v) if rule != tt.expected { t.Errorf("Expected '%s' Got '%s'", tt.expected, rule) } } } func TestCardinalPlurals(t *testing.T) { trans := New() tests := []struct { num float64 v uint64 expected locales.PluralRule }{ // { // num: 1, // v: 0, // expected: locales.PluralRuleOne, // }, // { // num: 4, // v: 0, // expected: locales.PluralRuleOther, // }, } for _, tt := range tests { rule := trans.CardinalPluralRule(tt.num, tt.v) if rule != tt.expected { t.Errorf("Expected '%s' Got '%s'", tt.expected, rule) } } } func TestDaysAbbreviated(t *testing.T) { trans := New() days := trans.WeekdaysAbbreviated() for i, day := range days { s := trans.WeekdayAbbreviated(time.Weekday(i)) if s != day { t.Errorf("Expected '%s' Got '%s'", day, s) } } tests := []struct { idx int expected string }{ // { // idx: 0, // expected: "Sun", // }, // { // idx: 1, // expected: "Mon", // }, // { // idx: 2, // expected: "Tue", // }, // { // idx: 3, // expected: "Wed", // }, // { // idx: 4, // expected: "Thu", // }, // { // idx: 5, // expected: "Fri", // }, // { // idx: 6, // expected: "Sat", // }, } for _, tt := range tests { s := trans.WeekdayAbbreviated(time.Weekday(tt.idx)) if s != tt.expected { t.Errorf("Expected '%s' Got '%s'", tt.expected, s) } } } func TestDaysNarrow(t *testing.T) { trans := New() days := trans.WeekdaysNarrow() for i, day := range days { s := trans.WeekdayNarrow(time.Weekday(i)) if s != day { t.Errorf("Expected '%s' Got '%s'", string(day), s) } } tests := []struct { idx int expected string }{ // { // idx: 0, // expected: "S", // }, // { // idx: 1, // expected: "M", // }, // { // idx: 2, // expected: "T", // }, // { // idx: 3, // expected: "W", // }, // { // idx: 4, // expected: "T", // }, // { // idx: 5, // expected: "F", // }, // { // idx: 6, // expected: "S", // }, } for _, tt := range tests { s := trans.WeekdayNarrow(time.Weekday(tt.idx)) if s != tt.expected { t.Errorf("Expected '%s' Got '%s'", tt.expected, s) } } } func TestDaysShort(t *testing.T) { trans := New() days := trans.WeekdaysShort() for i, day := range days { s := trans.WeekdayShort(time.Weekday(i)) if s != day { t.Errorf("Expected '%s' Got '%s'", day, s) } } tests := []struct { idx int expected string }{ // { // idx: 0, // expected: "Su", // }, // { // idx: 1, // expected: "Mo", // }, // { // idx: 2, // expected: "Tu", // }, // { // idx: 3, // expected: "We", // }, // { // idx: 4, // expected: "Th", // }, // { // idx: 5, // expected: "Fr", // }, // { // idx: 6, // expected: "Sa", // }, } for _, tt := range tests { s := trans.WeekdayShort(time.Weekday(tt.idx)) if s != tt.expected { t.Errorf("Expected '%s' Got '%s'", tt.expected, s) } } } func TestDaysWide(t *testing.T) { trans := New() days := trans.WeekdaysWide() for i, day := range days { s := trans.WeekdayWide(time.Weekday(i)) if s != day { t.Errorf("Expected '%s' Got '%s'", day, s) } } tests := []struct { idx int expected string }{ // { // idx: 0, // expected: "Sunday", // }, // { // idx: 1, // expected: "Monday", // }, // { // idx: 2, // expected: "Tuesday", // }, // { // idx: 3, // expected: "Wednesday", // }, // { // idx: 4, // expected: "Thursday", // }, // { // idx: 5, // expected: "Friday", // }, // { // idx: 6, // expected: "Saturday", // }, } for _, tt := range tests { s := trans.WeekdayWide(time.Weekday(tt.idx)) if s != tt.expected { t.Errorf("Expected '%s' Got '%s'", tt.expected, s) } } } func TestMonthsAbbreviated(t *testing.T) { trans := New() months := trans.MonthsAbbreviated() for i, month := range months { s := trans.MonthAbbreviated(time.Month(i + 1)) if s != month { t.Errorf("Expected '%s' Got '%s'", month, s) } } tests := []struct { idx int expected string }{ // { // idx: 1, // expected: "Jan", // }, // { // idx: 2, // expected: "Feb", // }, // { // idx: 3, // expected: "Mar", // }, // { // idx: 4, // expected: "Apr", // }, // { // idx: 5, // expected: "May", // }, // { // idx: 6, // expected: "Jun", // }, // { // idx: 7, // expected: "Jul", // }, // { // idx: 8, // expected: "Aug", // }, // { // idx: 9, // expected: "Sep", // }, // { // idx: 10, // expected: "Oct", // }, // { // idx: 11, // expected: "Nov", // }, // { // idx: 12, // expected: "Dec", // }, } for _, tt := range tests { s := trans.MonthAbbreviated(time.Month(tt.idx)) if s != tt.expected { t.Errorf("Expected '%s' Got '%s'", tt.expected, s) } } } func TestMonthsNarrow(t *testing.T) { trans := New() months := trans.MonthsNarrow() for i, month := range months { s := trans.MonthNarrow(time.Month(i + 1)) if s != month { t.Errorf("Expected '%s' Got '%s'", month, s) } } tests := []struct { idx int expected string }{ // { // idx: 1, // expected: "J", // }, // { // idx: 2, // expected: "F", // }, // { // idx: 3, // expected: "M", // }, // { // idx: 4, // expected: "A", // }, // { // idx: 5, // expected: "M", // }, // { // idx: 6, // expected: "J", // }, // { // idx: 7, // expected: "J", // }, // { // idx: 8, // expected: "A", // }, // { // idx: 9, // expected: "S", // }, // { // idx: 10, // expected: "O", // }, // { // idx: 11, // expected: "N", // }, // { // idx: 12, // expected: "D", // }, } for _, tt := range tests { s := trans.MonthNarrow(time.Month(tt.idx)) if s != tt.expected { t.Errorf("Expected '%s' Got '%s'", tt.expected, s) } } } func TestMonthsWide(t *testing.T) { trans := New() months := trans.MonthsWide() for i, month := range months { s := trans.MonthWide(time.Month(i + 1)) if s != month { t.Errorf("Expected '%s' Got '%s'", month, s) } } tests := []struct { idx int expected string }{ // { // idx: 1, // expected: "January", // }, // { // idx: 2, // expected: "February", // }, // { // idx: 3, // expected: "March", // }, // { // idx: 4, // expected: "April", // }, // { // idx: 5, // expected: "May", // }, // { // idx: 6, // expected: "June", // }, // { // idx: 7, // expected: "July", // }, // { // idx: 8, // expected: "August", // }, // { // idx: 9, // expected: "September", // }, // { // idx: 10, // expected: "October", // }, // { // idx: 11, // expected: "November", // }, // { // idx: 12, // expected: "December", // }, } for _, tt := range tests { s := string(trans.MonthWide(time.Month(tt.idx))) if s != tt.expected { t.Errorf("Expected '%s' Got '%s'", tt.expected, s) } } } func TestFmtTimeFull(t *testing.T) { // loc, err := time.LoadLocation("America/Toronto") // if err != nil { // t.Errorf("Expected '<nil>' Got '%s'", err) // } // fixed := time.FixedZone("OTHER", -4) tests := []struct { t time.Time expected string }{ // { // t: time.Date(2016, 02, 03, 9, 5, 1, 0, loc), // expected: "9:05:01 am Eastern Standard Time", // }, // { // t: time.Date(2016, 02, 03, 20, 5, 1, 0, fixed), // expected: "8:05:01 pm OTHER", // }, } trans := New() for _, tt := range tests { s := trans.FmtTimeFull(tt.t) if s != tt.expected { t.Errorf("Expected '%s' Got '%s'", tt.expected, s) } } } func TestFmtTimeLong(t *testing.T) { // loc, err := time.LoadLocation("America/Toronto") // if err != nil { // t.Errorf("Expected '<nil>' Got '%s'", err) // } tests := []struct { t time.Time expected string }{ // { // t: time.Date(2016, 02, 03, 9, 5, 1, 0, loc), // expected: "9:05:01 am EST", // }, // { // t: time.Date(2016, 02, 03, 20, 5, 1, 0, loc), // expected: "8:05:01 pm EST", // }, } trans := New() for _, tt := range tests { s := trans.FmtTimeLong(tt.t) if s != tt.expected { t.Errorf("Expected '%s' Got '%s'", tt.expected, s) } } } func TestFmtTimeMedium(t *testing.T) { tests := []struct { t time.Time expected string }{ // { // t: time.Date(2016, 02, 03, 9, 5, 1, 0, time.UTC), // expected: "9:05:01 am", // }, // { // t: time.Date(2016, 02, 03, 20, 5, 1, 0, time.UTC), // expected: "8:05:01 pm", // }, } trans := New() for _, tt := range tests { s := trans.FmtTimeMedium(tt.t) if s != tt.expected { t.Errorf("Expected '%s' Got '%s'", tt.expected, s) } } } func TestFmtTimeShort(t *testing.T) { tests := []struct { t time.Time expected string }{ // { // t: time.Date(2016, 02, 03, 9, 5, 1, 0, time.UTC), // expected: "9:05 am", // }, // { // t: time.Date(2016, 02, 03, 20, 5, 1, 0, time.UTC), // expected: "8:05 pm", // }, } trans := New() for _, tt := range tests { s := trans.FmtTimeShort(tt.t) if s != tt.expected { t.Errorf("Expected '%s' Got '%s'", tt.expected, s) } } } func TestFmtDateFull(t *testing.T) { tests := []struct { t time.Time expected string }{ // { // t: time.Date(2016, 02, 03, 9, 0, 1, 0, time.UTC), // expected: "Wednesday, February 3, 2016", // }, } trans := New() for _, tt := range tests { s := trans.FmtDateFull(tt.t) if s != tt.expected { t.Errorf("Expected '%s' Got '%s'", tt.expected, s) } } } func TestFmtDateLong(t *testing.T) { tests := []struct { t time.Time expected string }{ // { // t: time.Date(2016, 02, 03, 9, 0, 1, 0, time.UTC), // expected: "February 3, 2016", // }, } trans := New() for _, tt := range tests { s := trans.FmtDateLong(tt.t) if s != tt.expected { t.Errorf("Expected '%s' Got '%s'", tt.expected, s) } } } func TestFmtDateMedium(t *testing.T) { tests := []struct { t time.Time expected string }{ // { // t: time.Date(2016, 02, 03, 9, 0, 1, 0, time.UTC), // expected: "Feb 3, 2016", // }, } trans := New() for _, tt := range tests { s := trans.FmtDateMedium(tt.t) if s != tt.expected { t.Errorf("Expected '%s' Got '%s'", tt.expected, s) } } } func TestFmtDateShort(t *testing.T) { tests := []struct { t time.Time expected string }{ // { // t: time.Date(2016, 02, 03, 9, 0, 1, 0, time.UTC), // expected: "2/3/16", // }, // { // t: time.Date(-500, 02, 03, 9, 0, 1, 0, time.UTC), // expected: "2/3/500", // }, } trans := New() for _, tt := range tests { s := trans.FmtDateShort(tt.t) if s != tt.expected { t.Errorf("Expected '%s' Got '%s'", tt.expected, s) } } } func TestFmtNumber(t *testing.T) { tests := []struct { num float64 v uint64 expected string }{ // { // num: 1123456.5643, // v: 2, // expected: "1,123,456.56", // }, // { // num: 1123456.5643, // v: 1, // expected: "1,123,456.6", // }, // { // num: 221123456.5643, // v: 3, // expected: "221,123,456.564", // }, // { // num: -221123456.5643, // v: 3, // expected: "-221,123,456.564", // }, // { // num: -221123456.5643, // v: 3, // expected: "-221,123,456.564", // }, // { // num: 0, // v: 2, // expected: "0.00", // }, // { // num: -0, // v: 2, // expected: "0.00", // }, // { // num: -0, // v: 2, // expected: "0.00", // }, } trans := New() for _, tt := range tests { s := trans.FmtNumber(tt.num, tt.v) if s != tt.expected { t.Errorf("Expected '%s' Got '%s'", tt.expected, s) } } } func TestFmtCurrency(t *testing.T) { tests := []struct { num float64 v uint64 currency currency.Type expected string }{ // { // num: 1123456.5643, // v: 2, // currency: currency.USD, // expected: "$1,123,456.56", // }, // { // num: 1123456.5643, // v: 1, // currency: currency.USD, // expected: "$1,123,456.60", // }, // { // num: 221123456.5643, // v: 3, // currency: currency.USD, // expected: "$221,123,456.564", // }, // { // num: -221123456.5643, // v: 3, // currency: currency.USD, // expected: "-$221,123,456.564", // }, // { // num: -221123456.5643, // v: 3, // currency: currency.CAD, // expected: "-CAD 221,123,456.564", // }, // { // num: 0, // v: 2, // currency: currency.USD, // expected: "$0.00", // }, // { // num: -0, // v: 2, // currency: currency.USD, // expected: "$0.00", // }, // { // num: -0, // v: 2, // currency: currency.CAD, // expected: "CAD 0.00", // }, // { // num: 1.23, // v: 0, // currency: currency.USD, // expected: "$1.00", // }, } trans := New() for _, tt := range tests { s := trans.FmtCurrency(tt.num, tt.v, tt.currency) if s != tt.expected { t.Errorf("Expected '%s' Got '%s'", tt.expected, s) } } } func TestFmtAccounting(t *testing.T) { tests := []struct { num float64 v uint64 currency currency.Type expected string }{ // { // num: 1123456.5643, // v: 2, // currency: currency.USD, // expected: "$1,123,456.56", // }, // { // num: 1123456.5643, // v: 1, // currency: currency.USD, // expected: "$1,123,456.60", // }, // { // num: 221123456.5643, // v: 3, // currency: currency.USD, // expected: "$221,123,456.564", // }, // { // num: -221123456.5643, // v: 3, // currency: currency.USD, // expected: "($221,123,456.564)", // }, // { // num: -221123456.5643, // v: 3, // currency: currency.CAD, // expected: "(CAD 221,123,456.564)", // }, // { // num: -0, // v: 2, // currency: currency.USD, // expected: "$0.00", // }, // { // num: -0, // v: 2, // currency: currency.CAD, // expected: "CAD 0.00", // }, // { // num: 1.23, // v: 0, // currency: currency.USD, // expected: "$1.00", // }, } trans := New() for _, tt := range tests { s := trans.FmtAccounting(tt.num, tt.v, tt.currency) if s != tt.expected { t.Errorf("Expected '%s' Got '%s'", tt.expected, s) } } } func TestFmtPercent(t *testing.T) { tests := []struct { num float64 v uint64 expected string }{ // { // num: 15, // v: 0, // expected: "15%", // }, // { // num: 15, // v: 2, // expected: "15.00%", // }, // { // num: 434.45, // v: 0, // expected: "434%", // }, // { // num: 34.4, // v: 2, // expected: "34.40%", // }, // { // num: -34, // v: 0, // expected: "-34%", // }, } trans := New() for _, tt := range tests { s := trans.FmtPercent(tt.num, tt.v) if s != tt.expected { t.Errorf("Expected '%s' Got '%s'", tt.expected, s) } } }
go-playground/locales
ku_TR/ku_TR_test.go
GO
mit
19,303
var _for = require ('../index'); var should = require ('should'); describe ('passing data', function () { it ('should call the loop with the passed data', function (done) { var results = ''; var loop = _for ( 0, function (i) { return i < 2; }, function (i) { return i + 1; }, function (i, _break, _continue, data) { results = results + i + data; _continue (); }); loop ('a', function () { loop ('b', function () { loop ('c', function (data) { should.not.exist (data); results.should.eql('0a1a0b1b0c1c'); done (); }); }); }); }); it ('should work when making a loop with two arguments', function (done) { var results = ''; var loop = _for (2, function (i, _break, _continue, data) { results = results + i + data; _continue (); }); loop ('a', function () { loop ('b', function () { loop ('c', function (data) { should.not.exist (data); results.should.eql('0a1a0b1b0c1c'); done (); }); }); }); }); });
JosephJNK/async-for
tests/data.tests.js
JavaScript
mit
1,126
#region License // Copyright (c) 2013 Chandramouleswaran Ravichandran // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. #endregion using System; using System.Windows; using System.Windows.Data; using VEF.Interfaces.Controls; namespace VEF.Interfaces.Converters { public class MenuVisibilityConverter : IValueConverter { #region IValueConverter Members public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { AbstractMenuItem menu = value as AbstractMenuItem; if (menu == null) return Visibility.Hidden; if (menu.Command != null && menu.Command.CanExecute(null) == false && menu.HideDisabled == true) return Visibility.Collapsed; if (menu.Children.Count > 0 || menu.Command != null || menu.IsCheckable == true) return Visibility.Visible; return Visibility.Collapsed; } public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { throw new NotImplementedException(); } #endregion } }
devxkh/FrankE
Editor/VEF/VEF.Core.Shared/Interfaces/Converters/MenuVisibilityConverter.cs
C#
mit
2,235
using System; namespace Paramore.Darker.Builder { internal sealed class RegistryActionWrapper : IQueryHandlerDecoratorRegistry { private readonly Action<Type> _action; public RegistryActionWrapper(Action<Type> action) { _action = action; } public void Register(Type decoratorType) { _action(decoratorType); } } }
BrighterCommand/Darker
src/Paramore.Darker/Builder/RegistryActionWrapper.cs
C#
mit
407
# encoding: utf-8 class LogoPhotoUploader < CarrierWave::Uploader::Base # Include RMagick or MiniMagick support: # include CarrierWave::RMagick include CarrierWave::MiniMagick # Choose what kind of storage to use for this uploader: storage :file # storage :fog # Override the directory where uploaded files will be stored. # This is a sensible default for uploaders that are meant to be mounted: def store_dir "uploads/logo/" end # Provide a default URL as a default if there hasn't been a file uploaded: # def default_url # # For Rails 3.1+ asset pipeline compatibility: # # ActionController::Base.helpers.asset_path("fallback/" + [version_name, "default.png"].compact.join('_')) # # "/images/fallback/" + [version_name, "default.png"].compact.join('_') # end # Process files as they are uploaded: # process :scale => [200, 300] # # def scale(width, height) # # do something # end # Create different versions of your uploaded files: process :resize_to_fit => [50, 50] # Add a white list of extensions which are allowed to be uploaded. # For images you might use something like this: def extension_white_list %w(jpg jpeg gif png) end # Override the filename of the uploaded files: # Avoid using model.id or version_name here, see uploader/store.rb for details. # def filename # "something.jpg" if original_filename # end def filename "logo." + original_filename.split(".").last if original_filename end end
zhaoguobin/company_website
app/uploaders/logo_photo_uploader.rb
Ruby
mit
1,512
/** * @fileoverview A rule to suggest using of const declaration for variables that are never reassigned after declared. * @author Toru Nagashima */ "use strict"; const astUtils = require("../util/ast-utils"); //------------------------------------------------------------------------------ // Helpers //------------------------------------------------------------------------------ const PATTERN_TYPE = /^(?:.+?Pattern|RestElement|SpreadProperty|ExperimentalRestProperty|Property)$/; const DECLARATION_HOST_TYPE = /^(?:Program|BlockStatement|SwitchCase)$/; const DESTRUCTURING_HOST_TYPE = /^(?:VariableDeclarator|AssignmentExpression)$/; /** * Checks whether a given node is located at `ForStatement.init` or not. * * @param {ASTNode} node - A node to check. * @returns {boolean} `true` if the node is located at `ForStatement.init`. */ function isInitOfForStatement(node) { return node.parent.type === "ForStatement" && node.parent.init === node; } /** * Checks whether a given Identifier node becomes a VariableDeclaration or not. * * @param {ASTNode} identifier - An Identifier node to check. * @returns {boolean} `true` if the node can become a VariableDeclaration. */ function canBecomeVariableDeclaration(identifier) { let node = identifier.parent; while (PATTERN_TYPE.test(node.type)) { node = node.parent; } return ( node.type === "VariableDeclarator" || ( node.type === "AssignmentExpression" && node.parent.type === "ExpressionStatement" && DECLARATION_HOST_TYPE.test(node.parent.parent.type) ) ); } /** * Checks if an property or element is from outer scope or function parameters * in destructing pattern. * * @param {string} name - A variable name to be checked. * @param {eslint-scope.Scope} initScope - A scope to start find. * @returns {boolean} Indicates if the variable is from outer scope or function parameters. */ function isOuterVariableInDestructing(name, initScope) { if (initScope.through.find(ref => ref.resolved && ref.resolved.name === name)) { return true; } const variable = astUtils.getVariableByName(initScope, name); if (variable !== null) { return variable.defs.some(def => def.type === "Parameter"); } return false; } /** * Gets the VariableDeclarator/AssignmentExpression node that a given reference * belongs to. * This is used to detect a mix of reassigned and never reassigned in a * destructuring. * * @param {eslint-scope.Reference} reference - A reference to get. * @returns {ASTNode|null} A VariableDeclarator/AssignmentExpression node or * null. */ function getDestructuringHost(reference) { if (!reference.isWrite()) { return null; } let node = reference.identifier.parent; while (PATTERN_TYPE.test(node.type)) { node = node.parent; } if (!DESTRUCTURING_HOST_TYPE.test(node.type)) { return null; } return node; } /** * Determines if a destructuring assignment node contains * any MemberExpression nodes. This is used to determine if a * variable that is only written once using destructuring can be * safely converted into a const declaration. * @param {ASTNode} node The ObjectPattern or ArrayPattern node to check. * @returns {boolean} True if the destructuring pattern contains * a MemberExpression, false if not. */ function hasMemberExpressionAssignment(node) { switch (node.type) { case "ObjectPattern": return node.properties.some(prop => { if (prop) { /* * Spread elements have an argument property while * others have a value property. Because different * parsers use different node types for spread elements, * we just check if there is an argument property. */ return hasMemberExpressionAssignment(prop.argument || prop.value); } return false; }); case "ArrayPattern": return node.elements.some(element => { if (element) { return hasMemberExpressionAssignment(element); } return false; }); case "AssignmentPattern": return hasMemberExpressionAssignment(node.left); case "MemberExpression": return true; // no default } return false; } /** * Gets an identifier node of a given variable. * * If the initialization exists or one or more reading references exist before * the first assignment, the identifier node is the node of the declaration. * Otherwise, the identifier node is the node of the first assignment. * * If the variable should not change to const, this function returns null. * - If the variable is reassigned. * - If the variable is never initialized nor assigned. * - If the variable is initialized in a different scope from the declaration. * - If the unique assignment of the variable cannot change to a declaration. * e.g. `if (a) b = 1` / `return (b = 1)` * - If the variable is declared in the global scope and `eslintUsed` is `true`. * `/*exported foo` directive comment makes such variables. This rule does not * warn such variables because this rule cannot distinguish whether the * exported variables are reassigned or not. * * @param {eslint-scope.Variable} variable - A variable to get. * @param {boolean} ignoreReadBeforeAssign - * The value of `ignoreReadBeforeAssign` option. * @returns {ASTNode|null} * An Identifier node if the variable should change to const. * Otherwise, null. */ function getIdentifierIfShouldBeConst(variable, ignoreReadBeforeAssign) { if (variable.eslintUsed && variable.scope.type === "global") { return null; } // Finds the unique WriteReference. let writer = null; let isReadBeforeInit = false; const references = variable.references; for (let i = 0; i < references.length; ++i) { const reference = references[i]; if (reference.isWrite()) { const isReassigned = ( writer !== null && writer.identifier !== reference.identifier ); if (isReassigned) { return null; } const destructuringHost = getDestructuringHost(reference); if (destructuringHost !== null && destructuringHost.left !== void 0) { const leftNode = destructuringHost.left; let hasOuterVariables = false, hasNonIdentifiers = false; if (leftNode.type === "ObjectPattern") { const properties = leftNode.properties; hasOuterVariables = properties .filter(prop => prop.value) .map(prop => prop.value.name) .some(name => isOuterVariableInDestructing(name, variable.scope)); hasNonIdentifiers = hasMemberExpressionAssignment(leftNode); } else if (leftNode.type === "ArrayPattern") { const elements = leftNode.elements; hasOuterVariables = elements .map(element => element && element.name) .some(name => isOuterVariableInDestructing(name, variable.scope)); hasNonIdentifiers = hasMemberExpressionAssignment(leftNode); } if (hasOuterVariables || hasNonIdentifiers) { return null; } } writer = reference; } else if (reference.isRead() && writer === null) { if (ignoreReadBeforeAssign) { return null; } isReadBeforeInit = true; } } /* * If the assignment is from a different scope, ignore it. * If the assignment cannot change to a declaration, ignore it. */ const shouldBeConst = ( writer !== null && writer.from === variable.scope && canBecomeVariableDeclaration(writer.identifier) ); if (!shouldBeConst) { return null; } if (isReadBeforeInit) { return variable.defs[0].name; } return writer.identifier; } /** * Groups by the VariableDeclarator/AssignmentExpression node that each * reference of given variables belongs to. * This is used to detect a mix of reassigned and never reassigned in a * destructuring. * * @param {eslint-scope.Variable[]} variables - Variables to group by destructuring. * @param {boolean} ignoreReadBeforeAssign - * The value of `ignoreReadBeforeAssign` option. * @returns {Map<ASTNode, ASTNode[]>} Grouped identifier nodes. */ function groupByDestructuring(variables, ignoreReadBeforeAssign) { const identifierMap = new Map(); for (let i = 0; i < variables.length; ++i) { const variable = variables[i]; const references = variable.references; const identifier = getIdentifierIfShouldBeConst(variable, ignoreReadBeforeAssign); let prevId = null; for (let j = 0; j < references.length; ++j) { const reference = references[j]; const id = reference.identifier; /* * Avoid counting a reference twice or more for default values of * destructuring. */ if (id === prevId) { continue; } prevId = id; // Add the identifier node into the destructuring group. const group = getDestructuringHost(reference); if (group) { if (identifierMap.has(group)) { identifierMap.get(group).push(identifier); } else { identifierMap.set(group, [identifier]); } } } } return identifierMap; } /** * Finds the nearest parent of node with a given type. * * @param {ASTNode} node – The node to search from. * @param {string} type – The type field of the parent node. * @param {Function} shouldStop – a predicate that returns true if the traversal should stop, and false otherwise. * @returns {ASTNode} The closest ancestor with the specified type; null if no such ancestor exists. */ function findUp(node, type, shouldStop) { if (!node || shouldStop(node)) { return null; } if (node.type === type) { return node; } return findUp(node.parent, type, shouldStop); } //------------------------------------------------------------------------------ // Rule Definition //------------------------------------------------------------------------------ module.exports = { meta: { type: "suggestion", docs: { description: "require `const` declarations for variables that are never reassigned after declared", category: "ECMAScript 6", recommended: false, url: "https://eslint.org/docs/rules/prefer-const" }, fixable: "code", schema: [ { type: "object", properties: { destructuring: { enum: ["any", "all"] }, ignoreReadBeforeAssign: { type: "boolean" } }, additionalProperties: false } ] }, create(context) { const options = context.options[0] || {}; const sourceCode = context.getSourceCode(); const shouldMatchAnyDestructuredVariable = options.destructuring !== "all"; const ignoreReadBeforeAssign = options.ignoreReadBeforeAssign === true; const variables = []; let reportCount = 0; let name = ""; /** * Reports given identifier nodes if all of the nodes should be declared * as const. * * The argument 'nodes' is an array of Identifier nodes. * This node is the result of 'getIdentifierIfShouldBeConst()', so it's * nullable. In simple declaration or assignment cases, the length of * the array is 1. In destructuring cases, the length of the array can * be 2 or more. * * @param {(eslint-scope.Reference|null)[]} nodes - * References which are grouped by destructuring to report. * @returns {void} */ function checkGroup(nodes) { const nodesToReport = nodes.filter(Boolean); if (nodes.length && (shouldMatchAnyDestructuredVariable || nodesToReport.length === nodes.length)) { const varDeclParent = findUp(nodes[0], "VariableDeclaration", parentNode => parentNode.type.endsWith("Statement")); const isVarDecParentNull = varDeclParent === null; if (!isVarDecParentNull && varDeclParent.declarations.length > 0) { const firstDeclaration = varDeclParent.declarations[0]; if (firstDeclaration.init) { const firstDecParent = firstDeclaration.init.parent; /* * First we check the declaration type and then depending on * if the type is a "VariableDeclarator" or its an "ObjectPattern" * we compare the name from the first identifier, if the names are different * we assign the new name and reset the count of reportCount and nodeCount in * order to check each block for the number of reported errors and base our fix * based on comparing nodes.length and nodesToReport.length. */ if (firstDecParent.type === "VariableDeclarator") { if (firstDecParent.id.name !== name) { name = firstDecParent.id.name; reportCount = 0; } if (firstDecParent.id.type === "ObjectPattern") { if (firstDecParent.init.name !== name) { name = firstDecParent.init.name; reportCount = 0; } } } } } let shouldFix = varDeclParent && // Don't do a fix unless the variable is initialized (or it's in a for-in or for-of loop) (varDeclParent.parent.type === "ForInStatement" || varDeclParent.parent.type === "ForOfStatement" || varDeclParent.declarations[0].init) && /* * If options.destructuring is "all", then this warning will not occur unless * every assignment in the destructuring should be const. In that case, it's safe * to apply the fix. */ nodesToReport.length === nodes.length; if (!isVarDecParentNull && varDeclParent.declarations && varDeclParent.declarations.length !== 1) { if (varDeclParent && varDeclParent.declarations && varDeclParent.declarations.length >= 1) { /* * Add nodesToReport.length to a count, then comparing the count to the length * of the declarations in the current block. */ reportCount += nodesToReport.length; shouldFix = shouldFix && (reportCount === varDeclParent.declarations.length); } } nodesToReport.forEach(node => { context.report({ node, message: "'{{name}}' is never reassigned. Use 'const' instead.", data: node, fix: shouldFix ? fixer => fixer.replaceText(sourceCode.getFirstToken(varDeclParent), "const") : null }); }); } } return { "Program:exit"() { groupByDestructuring(variables, ignoreReadBeforeAssign).forEach(checkGroup); }, VariableDeclaration(node) { if (node.kind === "let" && !isInitOfForStatement(node)) { variables.push(...context.getDeclaredVariables(node)); } } }; } };
Aladdin-ADD/eslint
lib/rules/prefer-const.js
JavaScript
mit
16,721
""" Compare the regions predicted to be prophages to the regions that are marked as prophages in our testing set Probably the hardest part of this is the identifiers! """ import os import sys import argparse import gzip from Bio import SeqIO, BiopythonWarning from PhiSpyModules import message, is_gzip_file __author__ = 'Rob Edwards' __copyright__ = 'Copyright 2020, Rob Edwards' __credits__ = ['Rob Edwards'] __license__ = 'MIT' __maintainer__ = 'Rob Edwards' __email__ = 'raedwards@gmail.com' def genbank_seqio(gbkf): if is_gzip_file(gbkf): handle = gzip.open(gbkf, 'rt') else: handle = open(gbkf, 'r') return SeqIO.parse(handle, "genbank") def actual_phage_cds(gbkf, verbose=False): """ Read the genbank file and return a list of features that are actually phage regions :param gbkf: the test genbank file with CDS marked with is_phage :param verbose: more output :return: a set of phage features """ if verbose: message(f"Reading {gbkf}", "GREEN", "stderr") phage = {} nonphage = {} for seq in genbank_seqio(gbkf): for feat in seq.features: if feat.type == 'CDS': if 'product' not in feat.qualifiers: feat.qualifiers['product'] = [f"Hypothetical protein (not annotated in {gbkf})"] if 'is_phage' in feat.qualifiers: phage[str(feat.translate(seq, cds=False).seq).upper()] = feat.qualifiers['product'][0] else: nonphage[str(feat.translate(seq, cds=False).seq).upper()] = feat.qualifiers['product'][0] return phage, nonphage def predicted_genbank(predf, verbose=False): """ Read the predictions from the genbank file and return a set of features :param predf: the predictions file :param verbose: more output :return: a set of predicted phage genes """ if verbose: message(f"Reading {predf}", "GREEN", "stderr") predicted = {} for seq in genbank_seqio(predf): for feat in seq.features: if feat.type == 'CDS': if 'product' in feat.qualifiers: predicted[str(feat.translate(seq, cds=False).seq).upper()] = feat.qualifiers['product'][0] else: predicted[str(feat.translate(seq, cds=False).seq).upper()] = f"Hypothetical protein (not annotated in {predf})" if verbose: message(f"Found {len(predicted)} predicted prophage features", "BLUE", "stderr") return predicted def predicted_regions(regf, gbkf, verbose): """ Pull the phage genes from the regions :param regf: the regions file with contigs/start/stop :param gbkf: the genbank file used to make those predictions :param verbose: more output :return: a set of predicted phage genes """ regions = {} if verbose: message(f"Reading {regf}", "GREEN", "stderr") with open(regf, 'r') as f: for l in f: p = l.strip().split("\t") assert(len(p) == 3), f"Expected a tple of [contig, start, stop] in {regf}" p[1] = int(p[1]) p[2] = int(p[2]) if p[0] not in regions: regions[p[0]] = [] if p[2] < p[1]: regions[p[0]].append([p[2], p[1]]) else: regions[p[0]].append([p[1], p[2]]) if verbose: message(f"Reading {gbkf} again to get the phage regions", "GREEN", "stderr") predicted = {} for seq in genbank_seqio(gbkf): if seq.id in regions: for loc in regions[seq.id]: if verbose: message(f"Getting from {loc[0]} to {loc[1]}", "PINK", "stderr") for feat in seq[loc[0]:loc[1]].features: if feat.type == 'CDS': if 'product' in feat.qualifiers: predicted[str(feat.translate(seq[loc[0]:loc[1]], cds=False).seq).upper()] = feat.qualifiers['product'][0] else: predicted[str(feat.translate(seq[loc[0]:loc[1]], cds=False).seq).upper()] = f"Hypothetical protein (not annotated in {gbkf})" if verbose: message(f"Found {len(predicted)} predicted prophage features", "BLUE", "stderr") return predicted def compare_real_predicted(phage: dict, nonphage: dict, predicted: dict, print_fp: bool, print_fn: bool, verbose: bool): """ Compare the features that are real and predicted :param print_fn: print out the false negative matches :param print_fp: print out the false positive matches :param phage: actual phage features :param nonphage: actual non phage features :param predicted: predicted phage features :param verbose: more output :return: """ if verbose: message(f"Comparing real and predicted", "GREEN", "stderr") # TP = phage intersection predicted # TN = nonphage intersection [not in predicted] # FP = nonphage intersection predicted # FN = phage intersection [not in predicted] # convert the keys to sets phage_set = set(phage.keys()) nonphage_set = set(nonphage.keys()) predicted_set = set(predicted.keys()) # calculate not in predicted not_predicted = set() for s in phage_set.union(nonphage): if s not in predicted: not_predicted.add(s) print(f"Found:\nTest set:\n\tPhage: {len(phage)} Not phage: {len(nonphage)}") print(f"Predictions:\n\tPhage: {len(predicted)} Not phage: {len(not_predicted)}") tp = len(phage_set.intersection(predicted_set)) tn = len(nonphage_set.intersection(not_predicted)) fp = len(nonphage_set.intersection(predicted_set)) fn = len(phage_set.intersection(not_predicted)) print(f"TP: {tp} FP: {fp} TN: {tn} FN: {fn}") try: accuracy = (tp+tn)/(tp + tn + fp + fn) except ZeroDivisionError: accuracy = "NaN" try: precision = tp/(tp+fp) except ZeroDivisionError: precision = "NaN" try: recall = tp/(tp+fn) except ZeroDivisionError: recall = "NaN" try: specificity = tn/(tn+fp) except ZeroDivisionError: specificity = "NaN" f1_score = "NaN" if accuracy != "NaN" and precision != "NaN" and recall != "NaN" and specificity != "NaN": try: f1_score = 2*(recall * precision) / (recall + precision) except ZeroDivisionError: f1_score = "NaN" if accuracy != "NaN": print(f"Accuracy: {accuracy:.3f}\t(this is the ratio of the correctly labeled phage genes to the whole pool of genes") else: print("Accuracy: NaN") if precision != "NaN": print(f"Precision: {precision:.3f}\t(This is the ratio of correctly labeled phage genes to all predictions)") else: print("Precision: NaN") if recall != "NaN": print(f"Recall: {recall:.3f}\t(This is the fraction of actual phage genes we got right)") else: print("Recall: NaN") if specificity != "NaN": print(f"Specificity: {specificity:.3f}\t(This is the fraction of non phage genes we got right)") else: print("Specificity: NaN") if f1_score != "NaN": print(f"f1 score: {f1_score:.3f}\t(this is the harmonic mean of precision and recall, and is the best measure when, as in this case, there is a big difference between the number of phage and non-phage genes)") else: print("f1 score: NaN") if print_fp: for i in nonphage_set.intersection(predicted_set): print(f"FP\t{i}\t{nonphage[i]}") if print_fn: for i in phage_set.intersection(not_predicted): print(f"FN\t{i}\t{[phage[i]]}") if __name__ == '__main__': parser = argparse.ArgumentParser(description="Compare predictions to reality") parser.add_argument('-t', '--testfile', help='test file that has phage proteins marked with the is_phage qualifier', required=True) parser.add_argument('-p', '--predictfile', help='predictions genbank file that has each prophage as a sequence entry') parser.add_argument('-r', '--regionsfile', help='predictions regions file that has tuple of [contig, start, end]') parser.add_argument('--fp', help='print out the false positives', action='store_true') parser.add_argument('--fn', help='print out the false negatives', action='store_true') parser.add_argument('-v', help='verbose output', action='store_true') args = parser.parse_args() pred = None if args.predictfile: pred = predicted_genbank(args.predictfile, args.v) elif args.regionsfile: pred = predicted_regions(args.regionsfile, args.testfile, args.v) else: message("FATAL: Please provide either a predictions genbank or tsv file", "RED", "stderr") phage, nonphage = actual_phage_cds(args.testfile, args.v) compare_real_predicted(phage, nonphage, pred, args.fp, args.fn, args.v)
linsalrob/PhiSpy
scripts/compare_predictions_to_phages.py
Python
mit
8,988
from pymarkdownlint.tests.base import BaseTestCase from pymarkdownlint.config import LintConfig, LintConfigError from pymarkdownlint import rules class LintConfigTests(BaseTestCase): def test_get_rule_by_name_or_id(self): config = LintConfig() # get by id expected = rules.MaxLineLengthRule() rule = config.get_rule_by_name_or_id('R1') self.assertEqual(rule, expected) # get by name expected = rules.TrailingWhiteSpace() rule = config.get_rule_by_name_or_id('trailing-whitespace') self.assertEqual(rule, expected) # get non-existing rule = config.get_rule_by_name_or_id('foo') self.assertIsNone(rule) def test_default_rules(self): config = LintConfig() expected_rule_classes = [rules.MaxLineLengthRule, rules.TrailingWhiteSpace, rules.HardTab] expected_rules = [rule_cls() for rule_cls in expected_rule_classes] self.assertEqual(config.default_rule_classes, expected_rule_classes) self.assertEqual(config.rules, expected_rules) def test_load_config_from_file(self): # regular config file load, no problems LintConfig.load_from_file(self.get_sample_path("markdownlint")) # bad config file load foo_path = self.get_sample_path("foo") with self.assertRaisesRegexp(LintConfigError, "Invalid file path: {0}".format(foo_path)): LintConfig.load_from_file(foo_path) # error during file parsing bad_markdowlint_path = self.get_sample_path("badmarkdownlint") expected_error_msg = "Error during config file parsing: File contains no section headers." with self.assertRaisesRegexp(LintConfigError, expected_error_msg): LintConfig.load_from_file(bad_markdowlint_path)
jorisroovers/pymarkdownlint
pymarkdownlint/tests/test_config.py
Python
mit
1,809
Template.SightingsEdit.helpers({ onDelete: function () { return function (result) { //when record is deleted, go back to record listing Router.go('SightingsList'); }; }, }); Template.SightingsEdit.events({ }); Template.SightingsEdit.rendered = function () { }; AutoForm.hooks({ updateSightingsForm: { onSuccess: function (operation, result, template) { Router.go('SightingsView', { _id: template.data.doc._id }); }, } });
bdunnette/meleagris
client/views/sightings/sightingsEdit.js
JavaScript
mit
482
/** * Copyright (c) 2013 Egor Pushkin. All rights reserved. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.scientificsoft.iremote.platform.net; import java.io.InputStream; import java.io.OutputStream; import java.io.IOException; import java.net.InetSocketAddress; import java.net.SocketTimeoutException; import com.scientificsoft.iremote.server.tools.TimeoutException; public class Socket { private java.net.Socket _socket = null; public Socket(String host, String port, long timeout) throws IOException, TimeoutException { try { _socket = new java.net.Socket(); _socket.connect(new InetSocketAddress(host, new Integer(port)), (int)timeout); } catch ( SocketTimeoutException e ) { throw new TimeoutException(); } catch ( Exception e ) { throw new IOException("Failed to establish connection."); } } public InputStream getInputStream() throws IOException { return _socket.getInputStream(); } public OutputStream getOutputStream() throws IOException { return _socket.getOutputStream(); } public void close() throws IOException { try { _socket.shutdownInput(); } catch ( Exception e ) { } try { _socket.shutdownOutput(); } catch ( Exception e ) { } _socket.close(); } }
egorpushkin/iremote
dev/iRemote.Android/src/com/scientificsoft/iremote/platform/net/Socket.java
Java
mit
2,463
package org.zenframework.easyservices.update; import java.util.Collection; @SuppressWarnings("rawtypes") public class CollectionUpdateAdapter implements UpdateAdapter<Collection> { @Override public Class<Collection> getValueClass() { return Collection.class; } @SuppressWarnings("unchecked") @Override public void update(Collection oldValue, Collection newValue, ValueUpdater updater) { if (oldValue == newValue || newValue == null) return; if (oldValue == null) throw new UpdateException("Old value is null"); oldValue.clear(); oldValue.addAll(newValue); } }
zenframework/easy-services
easy-services-core/src/main/java/org/zenframework/easyservices/update/CollectionUpdateAdapter.java
Java
mit
657
""" homeassistant.components.binary_sensor ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Component to interface with binary sensors (sensors which only know two states) that can be monitored. For more details about this component, please refer to the documentation at https://home-assistant.io/components/binary_sensor/ """ import logging from homeassistant.helpers.entity_component import EntityComponent from homeassistant.helpers.entity import Entity from homeassistant.const import (STATE_ON, STATE_OFF) DOMAIN = 'binary_sensor' DEPENDENCIES = [] SCAN_INTERVAL = 30 ENTITY_ID_FORMAT = DOMAIN + '.{}' def setup(hass, config): """ Track states and offer events for binary sensors. """ component = EntityComponent( logging.getLogger(__name__), DOMAIN, hass, SCAN_INTERVAL) component.setup(config) return True # pylint: disable=no-self-use class BinarySensorDevice(Entity): """ Represents a binary sensor. """ @property def is_on(self): """ True if the binary sensor is on. """ return None @property def state(self): """ Returns the state of the binary sensor. """ return STATE_ON if self.is_on else STATE_OFF @property def friendly_state(self): """ Returns the friendly state of the binary sensor. """ return None
badele/home-assistant
homeassistant/components/binary_sensor/__init__.py
Python
mit
1,321
<?php $eZTranslationCacheCodeDate = 1058863428; $CacheInfo = array ( 'charset' => 'utf-8', ); $TranslationInfo = array ( 'context' => 'design/admin/content/edit', ); $TranslationRoot = array ( 'd5c6e07de8b9dccaac1d0452dee0b581' => array ( 'context' => 'design/admin/content/edit', 'source' => 'Edit <%object_name> [%class_name]', 'comment' => NULL, 'translation' => 'Modifica <%object_name> [%class_name]', 'key' => 'd5c6e07de8b9dccaac1d0452dee0b581', ), 'e811c8a9685fbfaf39c964a635600fd5' => array ( 'context' => 'design/admin/content/edit', 'source' => 'Translating content from %from_lang to %to_lang', 'comment' => NULL, 'translation' => 'Esecuzione traduzione del contenuto da %from_lang a %to_lang', 'key' => 'e811c8a9685fbfaf39c964a635600fd5', ), '11fb129ce59c549f147420ee3451ac24' => array ( 'context' => 'design/admin/content/edit', 'source' => 'Send for publishing', 'comment' => NULL, 'translation' => 'Pubblica', 'key' => '11fb129ce59c549f147420ee3451ac24', ), '8c5749194e3baf11dddd5c34b1811596' => array ( 'context' => 'design/admin/content/edit', 'source' => 'Store draft', 'comment' => NULL, 'translation' => 'Registra bozza', 'key' => '8c5749194e3baf11dddd5c34b1811596', ), 'd506eed04b8a1daa90d9dbe145445605' => array ( 'context' => 'design/admin/content/edit', 'source' => 'Store the contents of the draft that is being edited and continue editing. Use this button to periodically save your work while editing.', 'comment' => NULL, 'translation' => 'Registra i contenuti della bozza in fase di modifica e continua a modificare. Usa questo pulsante per salvare periodicamente il tuo lavoro mentre modifichi.', 'key' => 'd506eed04b8a1daa90d9dbe145445605', ), 'd7ebb04b02e47d0bd52637484b18f14e' => array ( 'context' => 'design/admin/content/edit', 'source' => 'Discard draft', 'comment' => NULL, 'translation' => 'Annulla bozza', 'key' => 'd7ebb04b02e47d0bd52637484b18f14e', ), '8ff4bdf4365cea79d60c64729aa5a3d7' => array ( 'context' => 'design/admin/content/edit', 'source' => 'Published', 'comment' => NULL, 'translation' => 'Pubblicato', 'key' => '8ff4bdf4365cea79d60c64729aa5a3d7', ), 'd57eeb192509b0a21c9fb559e0875ee4' => array ( 'context' => 'design/admin/content/edit', 'source' => 'Modified', 'comment' => NULL, 'translation' => 'Modificato il', 'key' => 'd57eeb192509b0a21c9fb559e0875ee4', ), 'b5f9dcbfc8129dbad5a5a46430976cab' => array ( 'context' => 'design/admin/content/edit', 'source' => 'Section', 'comment' => NULL, 'translation' => 'Sezione', 'key' => 'b5f9dcbfc8129dbad5a5a46430976cab', ), 'a8122643230a05433801fbfdc325b0ac' => array ( 'context' => 'design/admin/content/edit', 'source' => 'Depth', 'comment' => NULL, 'translation' => 'Profondità', 'key' => 'a8122643230a05433801fbfdc325b0ac', ), 'de3a2815973e43df00aee9ea89c2e9ee' => array ( 'context' => 'design/admin/content/edit', 'source' => 'Name', 'comment' => NULL, 'translation' => 'Nome', 'key' => 'de3a2815973e43df00aee9ea89c2e9ee', ), '0c449515a963c751510ea4a1c5ad5a16' => array ( 'context' => 'design/admin/content/edit', 'source' => 'Priority', 'comment' => NULL, 'translation' => 'Priorità', 'key' => '0c449515a963c751510ea4a1c5ad5a16', ), '67bc86a3e97a3a3d92ea3beb65dd6e87' => array ( 'context' => 'design/admin/content/edit', 'source' => 'Locations [%locations]', 'comment' => NULL, 'translation' => 'Collocazioni [%locations]', 'key' => '67bc86a3e97a3a3d92ea3beb65dd6e87', ), 'ab439be2c1960ef2864aba2706f3da54' => array ( 'context' => 'design/admin/content/edit', 'source' => 'Invert selection.', 'comment' => NULL, 'translation' => 'Inverti selezione.', 'key' => 'ab439be2c1960ef2864aba2706f3da54', ), '49e8f0ddafe626663288d81e2fb49ca0' => array ( 'context' => 'design/admin/content/edit', 'source' => 'Location', 'comment' => NULL, 'translation' => 'Collocazione', 'key' => '49e8f0ddafe626663288d81e2fb49ca0', ), 'eef9b86d0bc32e55d39032df03d414f7' => array ( 'context' => 'design/admin/content/edit', 'source' => 'Sub items', 'comment' => NULL, 'translation' => 'Sotto-elementi', 'key' => 'eef9b86d0bc32e55d39032df03d414f7', ), 'cc6dc33d8904d3c3b934998b16c5f64b' => array ( 'context' => 'design/admin/content/edit', 'source' => 'Sorting of sub items', 'comment' => NULL, 'translation' => 'Ordinamento sotto-elementi', 'key' => 'cc6dc33d8904d3c3b934998b16c5f64b', ), '2f0a11483a590a1f6268a02200198343' => array ( 'context' => 'design/admin/content/edit', 'source' => 'Current visibility', 'comment' => NULL, 'translation' => 'Visibilità corrente', 'key' => '2f0a11483a590a1f6268a02200198343', ), '14d015346e3dcd669f6b7289e556c379' => array ( 'context' => 'design/admin/content/edit', 'source' => 'Visibility after publishing', 'comment' => NULL, 'translation' => 'Visibilità dopo la pubblicazione', 'key' => '14d015346e3dcd669f6b7289e556c379', ), 'f2d0aed249fd63a9ad7750f5e3b05826' => array ( 'context' => 'design/admin/content/edit', 'source' => 'Main', 'comment' => NULL, 'translation' => 'Principale', 'key' => 'f2d0aed249fd63a9ad7750f5e3b05826', ), 'f0f5443a120379e97eaf90b672707d60' => array ( 'context' => 'design/admin/content/edit', 'source' => 'Select location for removal.', 'comment' => NULL, 'translation' => 'Seleziona la collocazione da eliminare.', 'key' => 'f0f5443a120379e97eaf90b672707d60', ), '0de946921daa4f766d6cb8b899f50c1f' => array ( 'context' => 'design/admin/content/edit', 'source' => 'Desc.', 'comment' => NULL, 'translation' => 'Disc.', 'key' => '0de946921daa4f766d6cb8b899f50c1f', ), '876544ffd52dfaa722d262e22b1ccb50' => array ( 'context' => 'design/admin/content/edit', 'source' => 'Asc.', 'comment' => NULL, 'translation' => 'Asc.', 'key' => '876544ffd52dfaa722d262e22b1ccb50', ), '783d1958da4861ba7dc9f1d396513661' => array ( 'context' => 'design/admin/content/edit', 'source' => 'Hidden by parent', 'comment' => NULL, 'translation' => 'Nascosto dal genitore', 'key' => '783d1958da4861ba7dc9f1d396513661', ), 'a7e239075d454945331613656140d9e4' => array ( 'context' => 'design/admin/content/edit', 'source' => 'Visible', 'comment' => NULL, 'translation' => 'Visibile', 'key' => 'a7e239075d454945331613656140d9e4', ), '275526eb7c8f1a68977c1239e1905d67' => array ( 'context' => 'design/admin/content/edit', 'source' => 'Unchanged', 'comment' => NULL, 'translation' => 'Non modificato', 'key' => '275526eb7c8f1a68977c1239e1905d67', ), '856d33ca67120cf3e125b3e674792f2d' => array ( 'context' => 'design/admin/content/edit', 'source' => 'Hidden', 'comment' => NULL, 'translation' => 'Nascosto', 'key' => '856d33ca67120cf3e125b3e674792f2d', ), '9b78cdb793ba06dd24c1cb659fd8f18e' => array ( 'context' => 'design/admin/content/edit', 'source' => 'Use these radio buttons to specify the main location (main node) for the object being edited.', 'comment' => NULL, 'translation' => 'Usa questi pulsanti radio per specificare la collocazione principale (nodo principale) dell\'oggetto in fase di modifica.', 'key' => '9b78cdb793ba06dd24c1cb659fd8f18e', ), '026f2a715a276e9d8d737446b9da0018' => array ( 'context' => 'design/admin/content/edit', 'source' => 'Move to another location.', 'comment' => NULL, 'translation' => 'Sposta in un\'altra collocazione.', 'key' => '026f2a715a276e9d8d737446b9da0018', ), '30e0f7f35119baaa4d4454fbe2913660' => array ( 'context' => 'design/admin/content/edit', 'source' => 'Remove selected', 'comment' => NULL, 'translation' => 'Elimina selezionati', 'key' => '30e0f7f35119baaa4d4454fbe2913660', ), '3bd76c0ad50229499785fd214b38a423' => array ( 'context' => 'design/admin/content/edit', 'source' => 'Remove selected locations.', 'comment' => NULL, 'translation' => 'Elimina le collocazioni selezionate.', 'key' => '3bd76c0ad50229499785fd214b38a423', ), '91f558d19141ff4355d842ee41371638' => array ( 'context' => 'design/admin/content/edit', 'source' => 'Add locations', 'comment' => NULL, 'translation' => 'Aggiungi collocazioni', 'key' => '91f558d19141ff4355d842ee41371638', ), 'd1348b630823ba147fee6a3080b93e6a' => array ( 'context' => 'design/admin/content/edit', 'source' => 'Add one or more locations for the object being edited.', 'comment' => NULL, 'translation' => 'Aggiungi una o più collocazioni per l\'oggetto in fase di modifica.', 'key' => 'd1348b630823ba147fee6a3080b93e6a', ), '24684de48a0e5f5cd59453cfaecf3fe2' => array ( 'context' => 'design/admin/content/edit', 'source' => 'Object information', 'comment' => NULL, 'translation' => 'Informazioni sull\'oggetto', 'key' => '24684de48a0e5f5cd59453cfaecf3fe2', ), '7ef3f2da93bc270f92af697bf09d2478' => array ( 'context' => 'design/admin/content/edit', 'source' => 'ID', 'comment' => NULL, 'translation' => 'ID', 'key' => '7ef3f2da93bc270f92af697bf09d2478', ), 'db6996ee096133dd3bf27a66d6c6a245' => array ( 'context' => 'design/admin/content/edit', 'source' => 'Created', 'comment' => NULL, 'translation' => 'Creato il', 'key' => 'db6996ee096133dd3bf27a66d6c6a245', ), '3504c716aee9e860aea283ab634315f5' => array ( 'context' => 'design/admin/content/edit', 'source' => 'Not yet published', 'comment' => NULL, 'translation' => 'Non ancora pubblicato', 'key' => '3504c716aee9e860aea283ab634315f5', ), '8a20002c7443ef8d46e8fd516830827a' => array ( 'context' => 'design/admin/content/edit', 'source' => 'Published version', 'comment' => NULL, 'translation' => 'Versione pubblicata', 'key' => '8a20002c7443ef8d46e8fd516830827a', ), '3b445a4b6127869d991f6b9f21540def' => array ( 'context' => 'design/admin/content/edit', 'source' => 'Manage versions', 'comment' => NULL, 'translation' => 'Gestisci versioni', 'key' => '3b445a4b6127869d991f6b9f21540def', ), '459828e3bbf9aca1b85a34598762c68f' => array ( 'context' => 'design/admin/content/edit', 'source' => 'View and manage (copy, delete, etc.) the versions of this object.', 'comment' => NULL, 'translation' => 'Guarda ed amministra (copia, cancella, ecc.) le versioni di quest\'oggetto.', 'key' => '459828e3bbf9aca1b85a34598762c68f', ), '337ce19fed6e1043de7d521d5f20a58c' => array ( 'context' => 'design/admin/content/edit', 'source' => 'Current draft', 'comment' => NULL, 'translation' => 'Bozza corrente', 'key' => '337ce19fed6e1043de7d521d5f20a58c', ), '3bc586e5f657cf80e47166d0049f6c75' => array ( 'context' => 'design/admin/content/edit', 'source' => 'Version', 'comment' => NULL, 'translation' => 'Versione', 'key' => '3bc586e5f657cf80e47166d0049f6c75', ), '34ea08d6e0326ca7a804a034afd76eba' => array ( 'context' => 'design/admin/content/edit', 'source' => 'View', 'comment' => NULL, 'translation' => 'Visualizza', 'key' => '34ea08d6e0326ca7a804a034afd76eba', ), 'e1668f1e0ee902c1ec6ce6b87fca974e' => array ( 'context' => 'design/admin/content/edit', 'source' => 'Preview the draft that is being edited.', 'comment' => NULL, 'translation' => 'Visualizza la bozza in fase di modifica.', 'key' => 'e1668f1e0ee902c1ec6ce6b87fca974e', ), '9cfee90b36ba6a94a051395e41071d64' => array ( 'context' => 'design/admin/content/edit', 'source' => 'Store and exit', 'comment' => NULL, 'translation' => 'Registra ed esci', 'key' => '9cfee90b36ba6a94a051395e41071d64', ), '1b7dc1e4c2c6fb9afa6ba1d0d2cfe22e' => array ( 'context' => 'design/admin/content/edit', 'source' => 'Store the draft that is being edited and exit from edit mode.', 'comment' => NULL, 'translation' => 'Registra la bozza in fase di modifica ed esci dalla modalità di modifica.', 'key' => '1b7dc1e4c2c6fb9afa6ba1d0d2cfe22e', ), 'deff3631a2a6a7aefe62c90e6f531393' => array ( 'context' => 'design/admin/content/edit', 'source' => 'Translate', 'comment' => NULL, 'translation' => 'Traduci', 'key' => 'deff3631a2a6a7aefe62c90e6f531393', ), '15261022404c70f9d80d19670046617c' => array ( 'context' => 'design/admin/content/edit', 'source' => 'Related objects [%related_objects]', 'comment' => NULL, 'translation' => 'Oggetti correlati [%related_objects]', 'key' => '15261022404c70f9d80d19670046617c', ), 'bdc9407d88adf5b51f71300747bc65b4' => array ( 'context' => 'design/admin/content/edit', 'source' => 'Related images [%related_images]', 'comment' => NULL, 'translation' => 'Immagini correlate [%related_images]', 'key' => 'bdc9407d88adf5b51f71300747bc65b4', ), '49e4893c354086bd227f26833da6fae3' => array ( 'context' => 'design/admin/content/edit', 'source' => 'Related files [%related_files]', 'comment' => NULL, 'translation' => 'File correlati [%related_files]', 'key' => '49e4893c354086bd227f26833da6fae3', ), 'fb0e2e8db005e5abbfc19f74d4d2ff59' => array ( 'context' => 'design/admin/content/edit', 'source' => 'File type', 'comment' => NULL, 'translation' => 'Tipo file', 'key' => 'fb0e2e8db005e5abbfc19f74d4d2ff59', ), 'cbe610719066288bb0f8f16e66eb60bf' => array ( 'context' => 'design/admin/content/edit', 'source' => 'Size', 'comment' => NULL, 'translation' => 'Dimensione', 'key' => 'cbe610719066288bb0f8f16e66eb60bf', ), '7629938cdf31fb430956705c4f25915c' => array ( 'context' => 'design/admin/content/edit', 'source' => 'XML code', 'comment' => NULL, 'translation' => 'Codice XML', 'key' => '7629938cdf31fb430956705c4f25915c', ), '2e759ee05aa1ad12add670edbc15d2c2' => array ( 'context' => 'design/admin/content/edit', 'source' => 'Related content [%related_objects]', 'comment' => NULL, 'translation' => 'Oggetti correlati [%related_objects]', 'key' => '2e759ee05aa1ad12add670edbc15d2c2', ), '42720949af15fd05c21a1220ce7dcaed' => array ( 'context' => 'design/admin/content/edit', 'source' => 'Type', 'comment' => NULL, 'translation' => 'Tipo', 'key' => '42720949af15fd05c21a1220ce7dcaed', ), 'a71c6cd033f06f84a746efa15bec425f' => array ( 'context' => 'design/admin/content/edit', 'source' => 'There are no objects related to the one that is currently being edited.', 'comment' => NULL, 'translation' => 'Non vi sono oggetti correlati a quello attualmente in fase di modifica.', 'key' => 'a71c6cd033f06f84a746efa15bec425f', ), '7c9c383b8a6efc73a57865ea173956f4' => array ( 'context' => 'design/admin/content/edit', 'source' => 'Remove the selected items from the list(s) above. It is only the relations that will be removed. The items will not be deleted.', 'comment' => NULL, 'translation' => 'Elimina gli elementi selezionati dalla lista(e) in alto. Verranno eliminate solo le relazioni. Gli elementi non saranno eliminati.', 'key' => '7c9c383b8a6efc73a57865ea173956f4', ), 'e4bc8d93d24d7f58fcd273d10a85a787' => array ( 'context' => 'design/admin/content/edit', 'source' => 'Add existing', 'comment' => NULL, 'translation' => 'Aggiungi esistente', 'key' => 'e4bc8d93d24d7f58fcd273d10a85a787', ), '42bfc9071828350c26ed3c83b752a191' => array ( 'context' => 'design/admin/content/edit', 'source' => 'Add an existing item as a related object.', 'comment' => NULL, 'translation' => 'Aggiungi un elemento esistente come oggetto correlato.', 'key' => '42bfc9071828350c26ed3c83b752a191', ), 'ba94e70cabd1cb7edd98f029ed9e6219' => array ( 'context' => 'design/admin/content/edit', 'source' => 'Upload new', 'comment' => NULL, 'translation' => 'Upload nuovo', 'key' => 'ba94e70cabd1cb7edd98f029ed9e6219', ), '5c9aa913f95d407fbb752e4cb03c31d5' => array ( 'context' => 'design/admin/content/edit', 'source' => 'Upload a file and add it as a related object.', 'comment' => NULL, 'translation' => 'Carica un file e aggiungilo come oggetto correlato.', 'key' => '5c9aa913f95d407fbb752e4cb03c31d5', ), 'c32705fc7ed02108c0cc8637bfb014a3' => array ( 'context' => 'design/admin/content/edit', 'source' => 'The draft could not be stored.', 'comment' => NULL, 'translation' => 'La bozza non può essere registrata.', 'key' => 'c32705fc7ed02108c0cc8637bfb014a3', ), '0107a013d1906cdccde3185dac816952' => array ( 'context' => 'design/admin/content/edit', 'source' => 'Required data is either missing or is invalid', 'comment' => NULL, 'translation' => 'I dati richiesti sono mancanti o non corretti', 'key' => '0107a013d1906cdccde3185dac816952', ), '4636bf4dbd364e83747d95d2e5291f09' => array ( 'context' => 'design/admin/content/edit', 'source' => 'The following locations are invalid', 'comment' => NULL, 'translation' => 'Le seguenti collocazioni non sono valide', 'key' => '4636bf4dbd364e83747d95d2e5291f09', ), 'a4e029b88453feb1b89b03e5f94d7417' => array ( 'context' => 'design/admin/content/edit', 'source' => 'The draft was only partially stored.', 'comment' => NULL, 'translation' => 'Bozza registrata solo parzialmente.', 'key' => 'a4e029b88453feb1b89b03e5f94d7417', ), '5547c5c42894c60e4f4e423b62a29ea1' => array ( 'context' => 'design/admin/content/edit', 'source' => 'The draft was successfully stored.', 'comment' => NULL, 'translation' => 'Registrazione bozza riuscita.', 'key' => '5547c5c42894c60e4f4e423b62a29ea1', ), '978390e9e54157ef85305dbab13222b8' => array ( 'context' => 'design/admin/content/edit', 'source' => 'Are you sure you want to discard the draft?', 'comment' => NULL, 'translation' => 'Sei sicuro di voler annullare la bozza?', 'key' => '978390e9e54157ef85305dbab13222b8', ), 'b2151a3ff3097b7918ffb0bf77ddd3d9' => array ( 'context' => 'design/admin/content/edit', 'source' => 'Discard the draft that is being edited. This will also remove the translations that belong to the draft (if any).', 'comment' => NULL, 'translation' => 'Annulla la bozza in fase di modifica. Rimuoverai anche le traduzioni appartenenti alla bozza (se ve ne sono).', 'key' => 'b2151a3ff3097b7918ffb0bf77ddd3d9', ), '64b2382b215c4fa9830f9a21fb2c4ca8' => array ( 'context' => 'design/admin/content/edit', 'source' => 'Translate from', 'comment' => NULL, 'translation' => 'Traduci da', 'key' => '64b2382b215c4fa9830f9a21fb2c4ca8', ), '7410909128e3c35ccf9d14cceb80820e' => array ( 'context' => 'design/admin/content/edit', 'source' => 'No translation', 'comment' => NULL, 'translation' => 'Nessuna traduzione', 'key' => '7410909128e3c35ccf9d14cceb80820e', ), 'a535d0e0c96877445a89aef4ee173dc4' => array ( 'context' => 'design/admin/content/edit', 'source' => 'Edit the current object showing the selected language as a reference.', 'comment' => NULL, 'translation' => 'Modifica i seguenti oggetti mostrando la lingua selezionata come riferimento.', 'key' => 'a535d0e0c96877445a89aef4ee173dc4', ), 'd692cfde1a62954707c8672718099413' => array ( 'context' => 'design/admin/content/edit', 'source' => 'Publish data', 'comment' => NULL, 'translation' => 'Pubblica i dati', 'key' => 'd692cfde1a62954707c8672718099413', ), 'eb0ae2aa2dc3d1e21c38bb5c4216db5d' => array ( 'context' => 'design/admin/content/edit', 'source' => 'Back to edit', 'comment' => NULL, 'translation' => 'Torna alla modifica', 'key' => 'eb0ae2aa2dc3d1e21c38bb5c4216db5d', ), 'ec3eb846d3b45c2b95ac208645003f88' => array ( 'context' => 'design/admin/content/edit', 'source' => 'Relation type', 'comment' => NULL, 'translation' => 'Tipo di relazione', 'key' => 'ec3eb846d3b45c2b95ac208645003f88', ), '54a0d205353a46d3d3a0e72dcb9de665' => array ( 'context' => 'design/admin/content/edit', 'source' => 'Common', 'comment' => NULL, 'translation' => 'Comune', 'key' => '54a0d205353a46d3d3a0e72dcb9de665', ), '58e308c58d795fe23ce95b39e31631b0' => array ( 'context' => 'design/admin/content/edit', 'source' => 'Embedded', 'comment' => NULL, 'translation' => 'Incluso', 'key' => '58e308c58d795fe23ce95b39e31631b0', ), '3e931f75750447a56ff75badd13e66d5' => array ( 'context' => 'design/admin/content/edit', 'source' => 'Linked', 'comment' => NULL, 'translation' => 'Collegato', 'key' => '3e931f75750447a56ff75badd13e66d5', ), '6f1be5a3016b77c751f014cba5abf62b' => array ( 'context' => 'design/admin/content/edit', 'source' => 'Attribute', 'comment' => NULL, 'translation' => 'Attributo', 'key' => '6f1be5a3016b77c751f014cba5abf62b', ), '630cf7951abe12d79a7d8e68e4e59b8c' => array ( 'context' => 'design/admin/content/edit', 'source' => 'Copy this code and paste it into an XML field to embed the object.', 'comment' => NULL, 'translation' => 'Copia questo codice ed incollalo in un campo XML per includere l\'oggetto.', 'key' => '630cf7951abe12d79a7d8e68e4e59b8c', ), '88fc57c68a451c3ae68461cd1be0ac09' => array ( 'context' => 'design/admin/content/edit', 'source' => 'Copy this code and paste it into an XML field to link the object.', 'comment' => NULL, 'translation' => 'Copia questo codice ed incollalo in un campo XML per collegare l\'oggetto.', 'key' => '88fc57c68a451c3ae68461cd1be0ac09', ), '2e6bc1eade5bc87d907d552c1f2850c2' => array ( 'context' => 'design/admin/content/edit', 'source' => 'Top node', 'comment' => NULL, 'translation' => 'Nodo superiore', 'key' => '2e6bc1eade5bc87d907d552c1f2850c2', ), 'e21865e61399551e932cfa56e2f037c3' => array ( 'context' => 'design/admin/content/edit', 'source' => 'Publish the contents of the draft that is being edited. The draft will become the published version of the object.', 'comment' => NULL, 'translation' => 'Pubblica i contenuti della bozza in fase di modifica. La bozza diverrà la versione pubblicata dell\'oggetto.', 'key' => 'e21865e61399551e932cfa56e2f037c3', ), 'a0ff5452f01b802f02e9589528383468' => array ( 'context' => 'design/admin/content/edit', 'source' => 'Class identifier', 'comment' => NULL, 'translation' => 'Identificatore della classe', 'key' => 'a0ff5452f01b802f02e9589528383468', ), 'a03bc27f29960a05a2082afa54bd767f' => array ( 'context' => 'design/admin/content/edit', 'source' => 'Class name', 'comment' => NULL, 'translation' => 'Nome della classe', 'key' => 'a03bc27f29960a05a2082afa54bd767f', ), '548d9e60b02ca3fea8f9eca6e5ea270b' => array ( 'context' => 'design/admin/content/edit', 'source' => 'This location will remain unchanged when the object is published.', 'comment' => NULL, 'translation' => 'Questa collocazione non verrà modificata quando l\'oggetto verrà pubblicato.', 'key' => '548d9e60b02ca3fea8f9eca6e5ea270b', ), 'b84aa5ba3b4a29912b256550b85372d2' => array ( 'context' => 'design/admin/content/edit', 'source' => 'This location will be created when the object is published.', 'comment' => NULL, 'translation' => 'Questa collocazione verrà creata quando l\'oggetto verrà pubblicato.', 'key' => 'b84aa5ba3b4a29912b256550b85372d2', ), '8dfc007c6f91ff521eb15a6ae1cfda44' => array ( 'context' => 'design/admin/content/edit', 'source' => 'This location will be moved when the object is published.', 'comment' => NULL, 'translation' => 'Questa collocazione verrà spostata quando l\'oggetto verrà pubblicato.', 'key' => '8dfc007c6f91ff521eb15a6ae1cfda44', ), '99deb2fe1a6237dcc341c6a0f3dc7980' => array ( 'context' => 'design/admin/content/edit', 'source' => 'This location will be removed when the object is published.', 'comment' => NULL, 'translation' => 'Questa collocazione verrà eliminata quando l\'oggetto verrà pubblicato.', 'key' => '99deb2fe1a6237dcc341c6a0f3dc7980', ), '1559f1473d1db10faf6251edb2bda77e' => array ( 'context' => 'design/admin/content/edit', 'source' => 'You do not have permission to remove this location.', 'comment' => NULL, 'translation' => 'Non hai i permessi per eliminare questa collocazione.', 'key' => '1559f1473d1db10faf6251edb2bda77e', ), 'fdd63332e502d8369d3cf5e937afc089' => array ( 'context' => 'design/admin/content/edit', 'source' => 'Use this menu to set the sorting method for the sub items in this location.', 'comment' => NULL, 'translation' => 'Usa questo menù per impostare il metodo di ordinamento dei sotto-elementi di questa collocazione.', 'key' => 'fdd63332e502d8369d3cf5e937afc089', ), '6deedda369647ff46f481b752d545896' => array ( 'context' => 'design/admin/content/edit', 'source' => 'Use this menu to set the sorting direction for the sub items in this location.', 'comment' => NULL, 'translation' => 'Usa questo menù per impostare la direzione di ordinamento dei sotto-elementi di questa collocazione.', 'key' => '6deedda369647ff46f481b752d545896', ), '657e97cded3ee381946c164372ca6986' => array ( 'context' => 'design/admin/content/edit', 'source' => 'You cannot add or remove locations because the object being edited belongs to a top node.', 'comment' => NULL, 'translation' => 'Non puoi aggiungere o eliminare collocazioni perché l\'oggetto in fase di modifica appartiene ad un nodo principale.', 'key' => '657e97cded3ee381946c164372ca6986', ), 'cc637428ff7420fa16299a1534569ba3' => array ( 'context' => 'design/admin/content/edit', 'source' => 'You do not have permission to view this object', 'comment' => NULL, 'translation' => 'Non sei abilitato a vedere quest\'oggetto', 'key' => 'cc637428ff7420fa16299a1534569ba3', ), 'e18abee452b4714bda51c8f4e41135ea' => array ( 'context' => 'design/admin/content/edit', 'source' => 'You cannot manage the versions of this object because there is only one version available (the one that is being edited).', 'comment' => NULL, 'translation' => 'Non puoi gestire le versioni di quest\'oggetto perché c\'è solo una versione disponibile (quella che viene modificata).', 'key' => 'e18abee452b4714bda51c8f4e41135ea', ), 'eb8bc6ee1e297b27503af0207afddca1' => array ( 'context' => 'design/admin/content/edit', 'source' => 'States', 'comment' => NULL, 'translation' => 'Stati', 'key' => 'eb8bc6ee1e297b27503af0207afddca1', ), '6cd07f3dd6f612f4a629660e3f17f225' => array ( 'context' => 'design/admin/content/edit', 'source' => 'The following data is invalid according to the custom validation rules', 'comment' => NULL, 'translation' => 'I seguenti dati non sono validi sulla base delle regole di validazione impostate', 'key' => '6cd07f3dd6f612f4a629660e3f17f225', ), 'c134eae4296615056100774aba5c737c' => array ( 'context' => 'design/admin/content/edit', 'source' => 'Toggle fullscreen editing!', 'comment' => NULL, 'translation' => 'Tasto per la modifica a schermo intero!', 'key' => 'c134eae4296615056100774aba5c737c', ), '2b21fdd22aac1dc9d52badd4daa84cc8' => array ( 'context' => 'design/admin/content/edit', 'source' => 'Store draft and exit', 'comment' => NULL, 'translation' => 'Registra bozza ed esci', 'key' => '2b21fdd22aac1dc9d52badd4daa84cc8', ), 'c19fe6950ef73d4a5aac038c6c2f3e1b' => array ( 'context' => 'design/admin/content/edit', 'source' => 'Store the draft that is being edited and exit from edit mode. Use when you need to exit your work and return later to continue.', 'comment' => NULL, 'translation' => 'Registra la bozza in fase di modifica ed esci dalla modifica. Usa questo pulsante per uscire dal tuo lavoro e tornare successivamente per continuare.', 'key' => 'c19fe6950ef73d4a5aac038c6c2f3e1b', ), '820c3bacd630fd295899e660ba22918c' => array ( 'context' => 'design/admin/content/edit', 'source' => 'Edit <%object_name> (%class_name)', 'comment' => NULL, 'translation' => 'Modifica <%object_name> (%class_name)', 'key' => '820c3bacd630fd295899e660ba22918c', ), '8950a2381757b6dd0db5091483661bb0' => array ( 'context' => 'design/admin/content/edit', 'source' => 'Locations (%locations)', 'comment' => NULL, 'translation' => 'Collocazioni (%locations)', 'key' => '8950a2381757b6dd0db5091483661bb0', ), '3965117f5e3158b59fe549e6cdba2c9a' => array ( 'context' => 'design/admin/content/edit', 'source' => 'Preview', 'comment' => NULL, 'translation' => 'Anteprima', 'key' => '3965117f5e3158b59fe549e6cdba2c9a', ), '6042d6c6f7e4f2e7e22e7c65162514ae' => array ( 'context' => 'design/admin/content/edit', 'source' => 'Existing translations', 'comment' => NULL, 'translation' => 'Traduzioni esistenti', 'key' => '6042d6c6f7e4f2e7e22e7c65162514ae', ), '6763edccdd45769450ffd1434299bf10' => array ( 'context' => 'design/admin/content/edit', 'source' => 'Base translation on', 'comment' => NULL, 'translation' => 'Traduzione di base su', 'key' => '6763edccdd45769450ffd1434299bf10', ), '21d0fdacb0a7736484e419ed81e22956' => array ( 'context' => 'design/admin/content/edit', 'source' => 'None', 'comment' => NULL, 'translation' => 'Nessuna', 'key' => '21d0fdacb0a7736484e419ed81e22956', ), '06304ec517378373e9de1c95fb429df1' => array ( 'context' => 'design/admin/content/edit', 'source' => 'Related objects (%related_objects)', 'comment' => NULL, 'translation' => 'Oggetti correlati (%related_objects)', 'key' => '06304ec517378373e9de1c95fb429df1', ), 'b104c545ae07332644ae2d20a9f1384b' => array ( 'context' => 'design/admin/content/edit', 'source' => 'Related images (%related_images)', 'comment' => NULL, 'translation' => 'Immagini correlate (%related_images)', 'key' => 'b104c545ae07332644ae2d20a9f1384b', ), '3d94b5daec0e506ade7e107b6b73d978' => array ( 'context' => 'design/admin/content/edit', 'source' => 'Related files (%related_files)', 'comment' => NULL, 'translation' => 'File correlati (%related_files)', 'key' => '3d94b5daec0e506ade7e107b6b73d978', ), '8adb2a84570bcb0cc99ec5ae9d73bf95' => array ( 'context' => 'design/admin/content/edit', 'source' => 'Related content (%related_objects)', 'comment' => NULL, 'translation' => 'Oggetti correlati (%related_objects)', 'key' => '8adb2a84570bcb0cc99ec5ae9d73bf95', ), '58607b576d3d0e5e08333fccc24d840c' => array ( 'context' => 'design/admin/content/edit', 'source' => 'View the draft that is being edited.', 'comment' => NULL, 'translation' => 'Visualizza la bozza in fase di modifica.', 'key' => '58607b576d3d0e5e08333fccc24d840c', ), '21cf1f883c2e361d5810fa6bc0eac58e' => array ( 'context' => 'design/admin/content/edit', 'source' => 'Path String', 'comment' => NULL, 'translation' => 'Stringa percorso', 'key' => '21cf1f883c2e361d5810fa6bc0eac58e', ), '03fb656941a080471b673d39a3d6d0fb' => array ( 'context' => 'design/admin/content/edit', 'source' => 'Go to the top', 'comment' => NULL, 'translation' => 'Vai all\'inizio', 'key' => '03fb656941a080471b673d39a3d6d0fb', ), ); ?>
SnceGroup/snce-website
web/var/cache/translation/f1fa2db4683ed697d014961bf03dd47c/ita-IT/e1865bb9511c2e58519696970e878347.php
PHP
mit
32,257
// Copyright (c) 2012-2013 The PPCoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <boost/assign/list_of.hpp> #include "kernel.h" #include "txdb.h" using namespace std; extern int nStakeMaxAge; extern int nStakeTargetSpacing; typedef std::map<int, unsigned int> MapModifierCheckpoints; // Hard checkpoints of stake modifiers to ensure they are deterministic static std::map<int, unsigned int> mapStakeModifierCheckpoints = boost::assign::map_list_of ( 0, 0xfd11f4e7 ) ( 1, 0x2dcbe358 ) ; // Hard checkpoints of stake modifiers to ensure they are deterministic (testNet) static std::map<int, unsigned int> mapStakeModifierCheckpointsTestNet = boost::assign::map_list_of ( 0, 0x0e00670bu ) ; // Get time weight int64 GetWeight(int64 nIntervalBeginning, int64 nIntervalEnd) { // Kernel hash weight starts from 0 at the 30-day min age // this change increases active coins participating the hash and helps // to secure the network when proof-of-stake difficulty is low // // Maximum TimeWeight is 90 days. return min(nIntervalEnd - nIntervalBeginning - nStakeMinAge, (int64)nStakeMaxAge); } // Get the last stake modifier and its generation time from a given block static bool GetLastStakeModifier(const CBlockIndex* pindex, uint64& nStakeModifier, int64& nModifierTime) { if (!pindex) return error("GetLastStakeModifier: null pindex"); while (pindex && pindex->pprev && !pindex->GeneratedStakeModifier()) pindex = pindex->pprev; if (!pindex->GeneratedStakeModifier()) return error("GetLastStakeModifier: no generation at genesis block"); nStakeModifier = pindex->nStakeModifier; nModifierTime = pindex->GetBlockTime(); return true; } // Get selection interval section (in seconds) static int64 GetStakeModifierSelectionIntervalSection(int nSection) { assert (nSection >= 0 && nSection < 64); return (nModifierInterval * 63 / (63 + ((63 - nSection) * (MODIFIER_INTERVAL_RATIO - 1)))); } // Get stake modifier selection interval (in seconds) static int64 GetStakeModifierSelectionInterval() { int64 nSelectionInterval = 0; for (int nSection=0; nSection<64; nSection++) nSelectionInterval += GetStakeModifierSelectionIntervalSection(nSection); return nSelectionInterval; } // select a block from the candidate blocks in vSortedByTimestamp, excluding // already selected blocks in vSelectedBlocks, and with timestamp up to // nSelectionIntervalStop. static bool SelectBlockFromCandidates(vector<pair<int64, uint256> >& vSortedByTimestamp, map<uint256, const CBlockIndex*>& mapSelectedBlocks, int64 nSelectionIntervalStop, uint64 nStakeModifierPrev, const CBlockIndex** pindexSelected) { bool fSelected = false; uint256 hashBest = 0; *pindexSelected = (const CBlockIndex*) 0; BOOST_FOREACH(const PAIRTYPE(int64, uint256)& item, vSortedByTimestamp) { if (!mapBlockIndex.count(item.second)) return error("SelectBlockFromCandidates: failed to find block index for candidate block %s", item.second.ToString().c_str()); const CBlockIndex* pindex = mapBlockIndex[item.second]; if (fSelected && pindex->GetBlockTime() > nSelectionIntervalStop) break; if (mapSelectedBlocks.count(pindex->GetBlockHash()) > 0) continue; // compute the selection hash by hashing its proof-hash and the // previous proof-of-stake modifier uint256 hashProof = pindex->IsProofOfStake()? pindex->hashProofOfStake : pindex->GetBlockHash(); CDataStream ss(SER_GETHASH, 0); ss << hashProof << nStakeModifierPrev; uint256 hashSelection = Hash(ss.begin(), ss.end()); // the selection hash is divided by 2**32 so that proof-of-stake block // is always favored over proof-of-work block. this is to preserve // the energy efficiency property if (pindex->IsProofOfStake()) hashSelection >>= 32; if (fSelected && hashSelection < hashBest) { hashBest = hashSelection; *pindexSelected = (const CBlockIndex*) pindex; } else if (!fSelected) { fSelected = true; hashBest = hashSelection; *pindexSelected = (const CBlockIndex*) pindex; } } if (fDebug && GetBoolArg("-printstakemodifier")) printf("SelectBlockFromCandidates: selection hash=%s\n", hashBest.ToString().c_str()); return fSelected; } // Stake Modifier (hash modifier of proof-of-stake): // The purpose of stake modifier is to prevent a txout (coin) owner from // computing future proof-of-stake generated by this txout at the time // of transaction confirmation. To meet kernel protocol, the txout // must hash with a future stake modifier to generate the proof. // Stake modifier consists of bits each of which is contributed from a // selected block of a given block group in the past. // The selection of a block is based on a hash of the block's proof-hash and // the previous stake modifier. // Stake modifier is recomputed at a fixed time interval instead of every // block. This is to make it difficult for an attacker to gain control of // additional bits in the stake modifier, even after generating a chain of // blocks. bool ComputeNextStakeModifier(const CBlockIndex* pindexPrev, uint64& nStakeModifier, bool& fGeneratedStakeModifier) { nStakeModifier = 0; fGeneratedStakeModifier = false; if (!pindexPrev) { fGeneratedStakeModifier = true; return true; // genesis block's modifier is 0 } // First find current stake modifier and its generation block time // if it's not old enough, return the same stake modifier int64 nModifierTime = 0; if (!GetLastStakeModifier(pindexPrev, nStakeModifier, nModifierTime)) return error("ComputeNextStakeModifier: unable to get last modifier"); if (fDebug) { printf("ComputeNextStakeModifier: prev modifier=0x%016"PRI64x" time=%s\n", nStakeModifier, DateTimeStrFormat(nModifierTime).c_str()); } if (nModifierTime / nModifierInterval >= pindexPrev->GetBlockTime() / nModifierInterval) return true; // Sort candidate blocks by timestamp vector<pair<int64, uint256> > vSortedByTimestamp; vSortedByTimestamp.reserve(64 * nModifierInterval / nStakeTargetSpacing); int64 nSelectionInterval = GetStakeModifierSelectionInterval(); int64 nSelectionIntervalStart = (pindexPrev->GetBlockTime() / nModifierInterval) * nModifierInterval - nSelectionInterval; const CBlockIndex* pindex = pindexPrev; while (pindex && pindex->GetBlockTime() >= nSelectionIntervalStart) { vSortedByTimestamp.push_back(make_pair(pindex->GetBlockTime(), pindex->GetBlockHash())); pindex = pindex->pprev; } int nHeightFirstCandidate = pindex ? (pindex->nHeight + 1) : 0; reverse(vSortedByTimestamp.begin(), vSortedByTimestamp.end()); sort(vSortedByTimestamp.begin(), vSortedByTimestamp.end()); // Select 64 blocks from candidate blocks to generate stake modifier uint64 nStakeModifierNew = 0; int64 nSelectionIntervalStop = nSelectionIntervalStart; map<uint256, const CBlockIndex*> mapSelectedBlocks; for (int nRound=0; nRound<min(64, (int)vSortedByTimestamp.size()); nRound++) { // add an interval section to the current selection round nSelectionIntervalStop += GetStakeModifierSelectionIntervalSection(nRound); // select a block from the candidates of current round if (!SelectBlockFromCandidates(vSortedByTimestamp, mapSelectedBlocks, nSelectionIntervalStop, nStakeModifier, &pindex)) return error("ComputeNextStakeModifier: unable to select block at round %d", nRound); // write the entropy bit of the selected block nStakeModifierNew |= (((uint64)pindex->GetStakeEntropyBit()) << nRound); // add the selected block from candidates to selected list mapSelectedBlocks.insert(make_pair(pindex->GetBlockHash(), pindex)); if (fDebug && GetBoolArg("-printstakemodifier")) printf("ComputeNextStakeModifier: selected round %d stop=%s height=%d bit=%d\n", nRound, DateTimeStrFormat(nSelectionIntervalStop).c_str(), pindex->nHeight, pindex->GetStakeEntropyBit()); } // Print selection map for visualization of the selected blocks if (fDebug && GetBoolArg("-printstakemodifier")) { string strSelectionMap = ""; // '-' indicates proof-of-work blocks not selected strSelectionMap.insert(0, pindexPrev->nHeight - nHeightFirstCandidate + 1, '-'); pindex = pindexPrev; while (pindex && pindex->nHeight >= nHeightFirstCandidate) { // '=' indicates proof-of-stake blocks not selected if (pindex->IsProofOfStake()) strSelectionMap.replace(pindex->nHeight - nHeightFirstCandidate, 1, "="); pindex = pindex->pprev; } BOOST_FOREACH(const PAIRTYPE(uint256, const CBlockIndex*)& item, mapSelectedBlocks) { // 'S' indicates selected proof-of-stake blocks // 'W' indicates selected proof-of-work blocks strSelectionMap.replace(item.second->nHeight - nHeightFirstCandidate, 1, item.second->IsProofOfStake()? "S" : "W"); } printf("ComputeNextStakeModifier: selection height [%d, %d] map %s\n", nHeightFirstCandidate, pindexPrev->nHeight, strSelectionMap.c_str()); } if (fDebug) { printf("ComputeNextStakeModifier: new modifier=0x%016"PRI64x" time=%s\n", nStakeModifierNew, DateTimeStrFormat(pindexPrev->GetBlockTime()).c_str()); } nStakeModifier = nStakeModifierNew; fGeneratedStakeModifier = true; return true; } // The stake modifier used to hash for a stake kernel is chosen as the stake // modifier about a selection interval later than the coin generating the kernel static bool GetKernelStakeModifier(uint256 hashBlockFrom, uint64& nStakeModifier, int& nStakeModifierHeight, int64& nStakeModifierTime, bool fPrintProofOfStake) { nStakeModifier = 0; if (!mapBlockIndex.count(hashBlockFrom)) return error("GetKernelStakeModifier() : block not indexed"); const CBlockIndex* pindexFrom = mapBlockIndex[hashBlockFrom]; nStakeModifierHeight = pindexFrom->nHeight; nStakeModifierTime = pindexFrom->GetBlockTime(); int64 nStakeModifierSelectionInterval = GetStakeModifierSelectionInterval(); const CBlockIndex* pindex = pindexFrom; // loop to find the stake modifier later by a selection interval while (nStakeModifierTime < pindexFrom->GetBlockTime() + nStakeModifierSelectionInterval) { if (!pindex->pnext) { // reached best block; may happen if node is behind on block chain if (fPrintProofOfStake || (pindex->GetBlockTime() + nStakeMinAge - nStakeModifierSelectionInterval > GetAdjustedTime())) return error("GetKernelStakeModifier() : reached best block %s at height %d from block %s", pindex->GetBlockHash().ToString().c_str(), pindex->nHeight, hashBlockFrom.ToString().c_str()); else return false; } pindex = pindex->pnext; if (pindex->GeneratedStakeModifier()) { nStakeModifierHeight = pindex->nHeight; nStakeModifierTime = pindex->GetBlockTime(); } } nStakeModifier = pindex->nStakeModifier; return true; } // ppcoin kernel protocol // coinstake must meet hash target according to the protocol: // kernel (input 0) must meet the formula // hash(nStakeModifier + txPrev.block.nTime + txPrev.offset + txPrev.nTime + txPrev.vout.n + nTime) < bnTarget * nCoinDayWeight // this ensures that the chance of getting a coinstake is proportional to the // amount of coin age one owns. // The reason this hash is chosen is the following: // nStakeModifier: scrambles computation to make it very difficult to precompute // future proof-of-stake at the time of the coin's confirmation // txPrev.block.nTime: prevent nodes from guessing a good timestamp to // generate transaction for future advantage // txPrev.offset: offset of txPrev inside block, to reduce the chance of // nodes generating coinstake at the same time // txPrev.nTime: reduce the chance of nodes generating coinstake at the same // time // txPrev.vout.n: output number of txPrev, to reduce the chance of nodes // generating coinstake at the same time // block/tx hash should not be used here as they can be generated in vast // quantities so as to generate blocks faster, degrading the system back into // a proof-of-work situation. // bool CheckStakeKernelHash(unsigned int nBits, const CBlock& blockFrom, unsigned int nTxPrevOffset, const CTransaction& txPrev, const COutPoint& prevout, unsigned int nTimeTx, uint256& hashProofOfStake, uint256& targetProofOfStake, bool fPrintProofOfStake) { if (nTimeTx < txPrev.nTime) // Transaction timestamp violation return error("CheckStakeKernelHash() : nTime violation"); unsigned int nTimeBlockFrom = blockFrom.GetBlockTime(); if (nTimeBlockFrom + nStakeMinAge > nTimeTx) // Min age requirement return error("CheckStakeKernelHash() : min age violation"); CBigNum bnTargetPerCoinDay; bnTargetPerCoinDay.SetCompact(nBits); int64 nValueIn = txPrev.vout[prevout.n].nValue; uint256 hashBlockFrom = blockFrom.GetHash(); CBigNum bnCoinDayWeight = CBigNum(nValueIn) * GetWeight((int64)txPrev.nTime, (int64)nTimeTx) / COIN / (24 * 60 * 60); targetProofOfStake = (bnCoinDayWeight * bnTargetPerCoinDay).getuint256(); // Calculate hash CDataStream ss(SER_GETHASH, 0); uint64 nStakeModifier = 0; int nStakeModifierHeight = 0; int64 nStakeModifierTime = 0; if (!GetKernelStakeModifier(hashBlockFrom, nStakeModifier, nStakeModifierHeight, nStakeModifierTime, fPrintProofOfStake)) return false; ss << nStakeModifier; ss << nTimeBlockFrom << nTxPrevOffset << txPrev.nTime << prevout.n << nTimeTx; hashProofOfStake = Hash(ss.begin(), ss.end()); if (fPrintProofOfStake) { printf("CheckStakeKernelHash() : using modifier 0x%016"PRI64x" at height=%d timestamp=%s for block from height=%d timestamp=%s\n", nStakeModifier, nStakeModifierHeight, DateTimeStrFormat(nStakeModifierTime).c_str(), mapBlockIndex[hashBlockFrom]->nHeight, DateTimeStrFormat(blockFrom.GetBlockTime()).c_str()); printf("CheckStakeKernelHash() : check modifier=0x%016"PRI64x" nTimeBlockFrom=%u nTxPrevOffset=%u nTimeTxPrev=%u nPrevout=%u nTimeTx=%u hashProof=%s\n", nStakeModifier, nTimeBlockFrom, nTxPrevOffset, txPrev.nTime, prevout.n, nTimeTx, hashProofOfStake.ToString().c_str()); } // Now check if proof-of-stake hash meets target protocol if (CBigNum(hashProofOfStake) > bnCoinDayWeight * bnTargetPerCoinDay) return false; if (fDebug && !fPrintProofOfStake) { printf("CheckStakeKernelHash() : using modifier 0x%016"PRI64x" at height=%d timestamp=%s for block from height=%d timestamp=%s\n", nStakeModifier, nStakeModifierHeight, DateTimeStrFormat(nStakeModifierTime).c_str(), mapBlockIndex[hashBlockFrom]->nHeight, DateTimeStrFormat(blockFrom.GetBlockTime()).c_str()); printf("CheckStakeKernelHash() : pass modifier=0x%016"PRI64x" nTimeBlockFrom=%u nTxPrevOffset=%u nTimeTxPrev=%u nPrevout=%u nTimeTx=%u hashProof=%s\n", nStakeModifier, nTimeBlockFrom, nTxPrevOffset, txPrev.nTime, prevout.n, nTimeTx, hashProofOfStake.ToString().c_str()); } return true; } // Check kernel hash target and coinstake signature bool CheckProofOfStake(const CTransaction& tx, unsigned int nBits, uint256& hashProofOfStake, uint256& targetProofOfStake) { if (!tx.IsCoinStake()) return error("CheckProofOfStake() : called on non-coinstake %s", tx.GetHash().ToString().c_str()); // Kernel (input 0) must match the stake hash target per coin age (nBits) const CTxIn& txin = tx.vin[0]; // First try finding the previous transaction in database CTxDB txdb("r"); CTransaction txPrev; CTxIndex txindex; if (!txPrev.ReadFromDisk(txdb, txin.prevout, txindex)) return tx.DoS(1, error("CheckProofOfStake() : INFO: read txPrev failed")); // previous transaction not in main chain, may occur during initial download // Verify signature if (!VerifySignature(txPrev, tx, 0, true, 0)) return tx.DoS(100, error("CheckProofOfStake() : VerifySignature failed on coinstake %s", tx.GetHash().ToString().c_str())); // Read block header CBlock block; if (!block.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos, false)) return fDebug? error("CheckProofOfStake() : read block failed") : false; // unable to read block of previous transaction if (!CheckStakeKernelHash(nBits, block, txindex.pos.nTxPos - txindex.pos.nBlockPos, txPrev, txin.prevout, tx.nTime, hashProofOfStake, targetProofOfStake, fDebug)) return tx.DoS(1, error("CheckProofOfStake() : INFO: check kernel failed on coinstake %s, hashProof=%s", tx.GetHash().ToString().c_str(), hashProofOfStake.ToString().c_str())); // may occur during initial download or if behind on block chain sync return true; } // Check whether the coinstake timestamp meets protocol bool CheckCoinStakeTimestamp(int64 nTimeBlock, int64 nTimeTx) { // v0.3 protocol return (nTimeBlock == nTimeTx); } // Get stake modifier checksum unsigned int GetStakeModifierChecksum(const CBlockIndex* pindex) { assert (pindex->pprev || pindex->GetBlockHash() == (!fTestNet ? hashGenesisBlock : hashGenesisBlockTestNet)); // Hash previous checksum with flags, hashProofOfStake and nStakeModifier CDataStream ss(SER_GETHASH, 0); if (pindex->pprev) ss << pindex->pprev->nStakeModifierChecksum; ss << pindex->nFlags << pindex->hashProofOfStake << pindex->nStakeModifier; uint256 hashChecksum = Hash(ss.begin(), ss.end()); hashChecksum >>= (256 - 32); return hashChecksum.Get64(); } // Check stake modifier hard checkpoints bool CheckStakeModifierCheckpoints(int nHeight, unsigned int nStakeModifierChecksum) { MapModifierCheckpoints& checkpoints = (fTestNet ? mapStakeModifierCheckpointsTestNet : mapStakeModifierCheckpoints); if (checkpoints.count(nHeight)) return nStakeModifierChecksum == checkpoints[nHeight]; return true; }
Rimbit/Wallets
src/kernel.cpp
C++
mit
18,814
require 'cnpj' module Presenter class CNPJ < Each def output ::CNPJ.new(value).formatted end end end
thiagoa/super_form
lib/presenter/cnpj.rb
Ruby
mit
120
package main import ( "net/http" "github.com/freehaha/token-auth" "github.com/freehaha/token-auth/memory" "github.com/gorilla/mux" ) // Route type is used to define a route of the API type Route struct { Name string Method string Pattern string HandlerFunc http.HandlerFunc } // Routes type is an array of Route type Routes []Route // NewRouter is the constructeur of the Router // It will create every routes from the routes variable just above func NewRouter() *mux.Router { tokenAuth := tauth.NewTokenAuth(nil, nil, memStore, nil) router := mux.NewRouter().StrictSlash(true) for _, route := range publicRoutes { router. Methods(route.Method). Path(route.Pattern). Name(route.Name). Handler(route.HandlerFunc) } for _, route := range routes { router. Methods(route.Method). Path(route.Pattern). Name(route.Name). Handler(tokenAuth.HandleFunc(route.HandlerFunc)) } return router } var memStore = memstore.New("salty") var publicRoutes = Routes{ Route{"LogUser", "GET", "/user/{id}/login/{token}", LogUserController}, } var routes = Routes{ //Debt Route{"GetDebt", "GET", "/debt/{id}", GetDebtController}, Route{"DeleteDebt", "DELETE", "/debt/{id}", DeleteDebtController}, Route{"AddImageDebt", "POST", "/debt/{id}/image", AddImageDebtController}, Route{"ReimburseDebt", "PUT", "/debt/{id}", ReimburseDebtController}, //User + Debt Route{"GetMyDebts", "GET", "/user/{userID}/mydebt", GetMyDebtsController}, Route{"GetTheirDebts", "GET", "/user/{userID}/debt", GetTheirDebtsController}, Route{"CreateDebt", "POST", "/user/{userID}/debt", CreateDebtController}, //User Route{"GetUser", "GET", "/user/{id}", GetUserController}, Route{"CreateUser", "POST", "/user", CreateUserController}, Route{"DeleteUser", "DELETE", "/user/{id}", DeleteUserController}, Route{"AddPayee", "POST", "/user/{id}/payee/{payeeID}", AddPayeeController}, Route{"RemovePayee", "DELETE", "/user/{id}/payee/{payeeID}", RemovePayeeController}, //Notification Route{"GetNotification", "GET", "/user/{id}/notification", GetNotificationController}, }
fthomasmorel/reimburse-me-golang
routes.go
GO
mit
2,108
#include "smd3d.h" #define SMSFACE_MAX 1000 //Àӽà ÆäÀ̽º ¸ñ·Ï ÀúÀå Àå¼Ò smSTAGE_FACE *smFaceList[ SMSFACE_MAX ]; int smFaceListCnt; //°É¾î ´Ù´Ò¼ö ÀÖ´Â ÃÖ´ë °íÀúÂ÷ int Stage_StepHeight = 10*fONE; int smStage_WaterChk; //¹° ýũ¿ë Ç÷¢ smSTAGE_FACE *CheckFace=0; //Æò¸é°ú 1Á¡ÀÇ À§Ä¡ÀÇ °ªÀ» ±¸ÇÔ ( Æò¸é ¹æÁ¤½Ä ) int smGetPlaneProduct( POINT3D *p1 , POINT3D *p2 , POINT3D *p3 , POINT3D *p ) { int ux , uy , uz; int vx , vy , vz; int nx , ny , nz; int result; //º¤ÅÍ °è»ê ux = (p2->x - p1->x)>>6 ; uy = (p2->y - p1->y)>>6 ; uz = (p2->z - p1->z)>>6 ; vx = (p3->x - p1->x)>>6 ; vy = (p3->y - p1->y)>>6 ; vz = (p3->z - p1->z)>>6 ; //³ë¸» °è»ê nx = (uy*vz - uz*vy)>>2 ; ny = (uz*vx - ux*vz)>>2 ; nz = (ux*vy - uy*vx)>>2 ; //Æò¸é ¹æÁ¤½Ä¿¡ ´ëÀÔ result = ( nx*((p->x-p1->x)>>6) + ny*((p->y-p1->y)>>6) + nz*((p->z-p1->z)>>6) ); return result; }; //Æò¸é°ú 1Á¡ÀÇ À§Ä¡ÀÇ °ªÀ» ±¸ÇÔ ( Æò¸é ¹æÁ¤½Ä ) int smGetThroughPlane( POINT3D *p1 , POINT3D *p2 , POINT3D *p3 , POINT3D *sp , POINT3D *ep , POINT3D *cp ) { int ux , uy , uz; int vx , vy , vz; int nx , ny , nz; int denominator , t; int lx,ly,lz; //º¤ÅÍ °è»ê ux = (p2->x - p1->x) ; uy = (p2->y - p1->y) ; uz = (p2->z - p1->z) ; vx = (p3->x - p1->x) ; vy = (p3->y - p1->y) ; vz = (p3->z - p1->z) ; //³ë¸» °è»ê nx = (uy*vz - uz*vy)>>3; ny = (uz*vx - ux*vz)>>3; nz = (ux*vy - uy*vx)>>3; lx = ep->x - sp->x; ly = ep->y - sp->y; lz = ep->z - sp->z; denominator = ( nx * lx + ny * ly + nz * lz )>>3; if ( denominator!=0 ) { t = (( ( -nx * sp->x + nx * p1->x ) + ( -ny * sp->y + ny * p1->y ) + ( -nz * sp->z + nz * p1->z ) )<<3)/ denominator; // if ( t>=0 && t<=fONE ) { if ( t>=0 && t<=8 ) { cp->x = sp->x + ((lx * t)>>3); cp->y = sp->y + ((ly * t)>>3); cp->z = sp->z + ((lz * t)>>3); return TRUE; } } return FALSE; }; /* BOOL CollisionLineVSPolygon( LPD3DVECTOR lpCollisionPoint, LPD3DVECTOR lpLineBegin, LPD3DVECTOR lpLineEnd, LPD3DVECTOR lpPolygonVtx1, LPD3DVECTOR lpPolygonVtx2, LPD3DVECTOR lpPolygonVtx3 ) { // 1) get Polygon normal vector(CrossProduct) D3DVECTOR PolygonNormal, u, v; u.x = lpPolygonVtx2->x - lpPolygonVtx1->x; u.y = lpPolygonVtx2->y - lpPolygonVtx1->y; u.z = lpPolygonVtx2->z - lpPolygonVtx1->z; v.x = lpPolygonVtx3->x - lpPolygonVtx1->x; v.y = lpPolygonVtx3->y - lpPolygonVtx1->y; v.z = lpPolygonVtx3->z - lpPolygonVtx1->z; PolygonNormal.x = u.y*v.z - u.z*v.y; PolygonNormal.y = u.z*v.x - u.x*v.z; PolygonNormal.z = u.x*v.y - u.y*v.x; // 2) get t of Line equation( 0 <= t <= 1 ) D3DVALUE denominator = ((PolygonNormal.x * ( lpLineEnd->x - lpLineBegin->x) ) + (PolygonNormal.y * ( lpLineEnd->y - lpLineBegin->y) ) + (PolygonNormal.z * ( lpLineEnd->z - lpLineBegin->z) ) ); D3DVALUE t; if( denominator != 0 ) { t = (( -PolygonNormal.x * lpLineBegin->x + PolygonNormal.x * lpPolygonVtx1->x) + ( -PolygonNormal.y * lpLineBegin->y + PolygonNormal.y * lpPolygonVtx1->y) + ( -PolygonNormal.z * lpLineBegin->z + PolygonNormal.z * lpPolygonVtx1->z) ) / denominator; if( ( t >= 0.0f ) && ( t <= 1.0f ) ) { lpCollisionPoint->x = lpLineBegin.x + (lpLineEnd->x - lpLineBegin->x) * t; lpCollisionPoint->y = lpLineBegin.y + (lpLineEnd->y - lpLineBegin->y) * t; lpCollisionPoint->z = lpLineBegin.z + (lpLineEnd->z - lpLineBegin->z) * t; return TRUE; } else return FALSE; } else return FALSE; } */ int smGetTriangleImact( POINT3D *p1 , POINT3D *p2 , POINT3D *p3 , POINT3D *sp , POINT3D *ep ) { int vx,vy,vz; POINT3D cp1, cp2, cp3; int c1,c2; c1 = smGetPlaneProduct( p1 , p2 , p3 , sp ); c2 = smGetPlaneProduct( p1 , p2 , p3 , ep ); if ( (c1<=0 && c2<=0) || ( c1>0 && c2>0 ) ) return FALSE; vx = (ep->x - sp->x)<<4; vy = (ep->y - sp->y)<<4; vz = (ep->z - sp->z)<<4; cp1.x = p1->x + vx; cp1.y = p1->y + vy; cp1.z = p1->z + vz; cp2.x = p2->x + vx; cp2.y = p2->y + vy; cp2.z = p2->z + vz; cp3.x = p3->x + vx; cp3.y = p3->y + vy; cp3.z = p3->z + vz; c1 = smGetPlaneProduct( p1 , p2 , &cp1 , sp ); if ( c1>=0 ) return FALSE; c1 = smGetPlaneProduct( p2 , p3 , &cp2 , sp ); if ( c1>=0 ) return FALSE; c1 = smGetPlaneProduct( p3 , p1 , &cp3 , sp ); if ( c1>=0 ) return FALSE; return TRUE; }; int smGetTriangleOnArea( smSTAGE_VERTEX *sp1 , smSTAGE_VERTEX *sp2 , smSTAGE_VERTEX *sp3 , POINT3D *sp ) { // int vx,vy,vz; POINT3D cp1, cp2, cp3; int c1;//,c2; POINT3D p1,p2,p3; p1.x = sp1->x; p1.y = sp1->y; p1.z = sp1->z; p2.x = sp2->x; p2.y = sp2->y; p2.z = sp2->z; p3.x = sp3->x; p3.y = sp3->y; p3.z = sp3->z; cp1.x = p1.x; cp1.y = p1.y - 32*fONE; cp1.z = p1.z; cp2.x = p2.x; cp2.y = p2.y - 32*fONE; cp2.z = p2.z; cp3.x = p3.x; cp3.y = p3.y - 32*fONE; cp3.z = p3.z; c1 = smGetPlaneProduct( &p1 , &p2 , &cp1 , sp ); if ( c1>=0 ) return FALSE; c1 = smGetPlaneProduct( &p2 , &p3 , &cp2 , sp ); if ( c1>=0 ) return FALSE; c1 = smGetPlaneProduct( &p3 , &p1 , &cp3 , sp ); if ( c1>=0 ) return FALSE; return TRUE; }; //Æò¸é°ú 1Á¡ÀÇ À§Ä¡ÀÇ °ªÀ» ±¸ÇÔ ( Æò¸é ¹æÁ¤½Ä ) int smSTAGE3D::GetPlaneProduct( smSTAGE_FACE *face , POINT3D *p ) { int result; smSTAGE_VERTEX *vp; vp = &Vertex[ face->Vertex[0] ]; //Æò¸é ¹æÁ¤½Ä¿¡ ´ëÀÔ result = ( (face->VectNormal[0]>>4) * ((p->x - vp->x)>>4) + (face->VectNormal[1]>>4) * ((p->y - vp->y)>>4) + (face->VectNormal[2]>>4) * ((p->z - vp->z)>>4) ); return result; }; //Æò¸é°ú 1Á¡ÀÇ À§Ä¡ÀÇ °ªÀ» ±¸ÇÔ ( Æò¸é ¹æÁ¤½Ä ) int smSTAGE3D::GetThroughPlane( smSTAGE_FACE *face , POINT3D *sp , POINT3D *ep ) { // int result; POINT3D p1,p2,p3,cp,ssp,eep; smSTAGE_VERTEX *vp; vp = &Vertex[ face->Vertex[0] ]; p1.x = vp->x>>5; p1.y = vp->y>>5; p1.z = vp->z>>5; vp = &Vertex[ face->Vertex[1] ]; p2.x = vp->x>>5; p2.y = vp->y>>5; p2.z = vp->z>>5; vp = &Vertex[ face->Vertex[2] ]; p3.x = vp->x>>5; p3.y = vp->y>>5; p3.z = vp->z>>5; ssp.x = sp->x>>5; ssp.y = sp->y>>5; ssp.z = sp->z>>5; eep.x = ep->x>>5; eep.y = ep->y>>5; eep.z = ep->z>>5; return smGetThroughPlane( &p1,&p2,&p3,&ssp,&eep,&cp ); }; //smGetThroughPlane smSTAGE_FACE *DebugFace = 0; WORD DebugFaceMat = 0; //°¢ ¶óÀÎÀÌ ÆäÀ̽º¸¦ °üÅëÇÏ´ÂÁö °Ë»çÇÑ´Ù ( ¸ðµç ¼±ºÐÀÌ °üÅëÇÏÁö ¾ÊÀ» °æ¿ì TRUE ±×¿ÜÀÇ °æ¿ì FALSE ) int smSTAGE3D::GetTriangleImact( smSTAGE_FACE *face, smLINE3D *pLines , int LineCnt ) { int vx,vy,vz; POINT3D p1,p2,p3; POINT3D cp; POINT3D *sp,*ep; int c1,c2; smSTAGE_VERTEX *vp; int cnt; int flag , TrueCnt; //ÆäÀ̽ºÀÇ ÁÂÇ¥3°³¸¦ Æ÷ÀÎÅÍ·Î ¸¸µë vp = &Vertex[ face->Vertex[0] ]; p1.x = vp->x; p1.y = vp->y; p1.z = vp->z; vp = &Vertex[ face->Vertex[1] ]; p2.x = vp->x; p2.y = vp->y; p2.z = vp->z; vp = &Vertex[ face->Vertex[2] ]; p3.x = vp->x; p3.y = vp->y; p3.z = vp->z; TrueCnt = 0; for(int cnt=0;cnt<LineCnt;cnt++ ) { sp = &pLines[cnt].sp; ep = &pLines[cnt].ep; flag = TRUE; if ( ((sp->y<p1.y && sp->y<p2.y && sp->y<p3.y) || (sp->y>p1.y && sp->y>p2.y && sp->y>p3.y) ) && ((ep->y<p1.y && ep->y<p2.y && ep->y<p3.y) || (ep->y>p1.y && ep->y>p2.y && ep->y>p3.y) ) ) flag = FALSE; if ( flag ) { //Æò¸éÀ» °üÅëÇÏ´ÂÁö È®ÀÎ c1 = GetPlaneProduct( face , sp ); c2 = GetPlaneProduct( face , ep ); if ( (c1<=0 && c2<=0) || ( c1>0 && c2>0 ) ) flag = FALSE; // if ( GetThroughPlane( face , sp , ep )==FALSE ) // flag = FALSE; //###################################################################################### //ÀÛ ¼º ÀÚ : ¿À ¿µ ¼® //if( flag == TRUE ) //{ // vx = (ep->x - sp->x)<<8; // vy = (ep->y - sp->y)<<8; // vz = (ep->z - sp->z)<<8; //} //»ï°¢Çü°ú ¿¬Àå¼± ÁÂÇ¥ Æò¸é Á¦ÀÛ if ( c1<=0 ) { vx = (ep->x - sp->x)<<8; vy = (ep->y - sp->y)<<8; vz = (ep->z - sp->z)<<8; } else { vx = (sp->x - ep->x)<<8; vy = (ep->y - ep->y)<<8; vz = (ep->z - ep->z)<<8; } //###################################################################################### // Åë°úÇÏ´Â ¼±ÀÌ »ï°¢Çü ¿µ¿ª ¾È¿¡ ÀÖ´ÂÁö Á¶»ç // 3°³ÀÇ °¡»óÀÇ Æò¸éÀ» ¸¸µé¾î Æò¸éÀ§Ä¡¸¦ È®ÀÎÇÏ´Â ¹æ¹ý if ( flag==TRUE ) { cp.x = p1.x + vx; cp.y = p1.y + vy; cp.z = p1.z + vz; c1 = smGetPlaneProduct( &p1 , &p2 , &cp , sp ); //###################################################################################### //ÀÛ ¼º ÀÚ : ¿À ¿µ ¼® //if( c2 >= 0 && c1 >= 0 ) // flag = FALSE; //else if( c2 < 0 && c1 < 0 ) // flag = FALSE; if ( c1>0 ) flag=FALSE; //###################################################################################### } if (flag==TRUE) { cp.x = p2.x + vx; cp.y = p2.y + vy; cp.z = p2.z + vz; c1 = smGetPlaneProduct( &p2 , &p3 , &cp , sp ); //###################################################################################### //ÀÛ ¼º ÀÚ : ¿À ¿µ ¼® //if( c2 >= 0 && c1 >= 0 ) // flag = FALSE; //else if( c2 < 0 && c1 < 0 ) // flag = FALSE; if ( c1>0 ) flag=FALSE; //###################################################################################### } if (flag==TRUE) { cp.x = p3.x + vx; cp.y = p3.y + vy; cp.z = p3.z + vz; c1 = smGetPlaneProduct( &p3 , &p1 , &cp , sp ); //###################################################################################### //ÀÛ ¼º ÀÚ : ¿À ¿µ ¼® //if( c2 >= 0 && c1 >= 0 ) // flag = FALSE; //else if( c2 < 0 && c1 < 0 ) // flag = FALSE; if ( c1>0 ) flag=FALSE; //###################################################################################### } if ( flag==TRUE ) { return TRUE; } } } return FALSE; } //TÀ̵¿ÇÒ À§Ä¡¸¦ TÀÚ ¶óÀÎÀ¸·Î ã´Â´Ù static int smMakeTLine( POINT3D *Posi , POINT3D *Angle , int dist , int ObjWidth , int ObjHeight, smLINE3D *Lines , POINT3D *ep ) { int width; int dist2 = dist+fONE*12; int PosiMinY = fONE*12; int PosiMaxY = ObjHeight-(ObjHeight>>2); width = ObjWidth>>2; GetMoveLocation( 0, 0, dist, Angle->x, Angle->y, Angle->z ); ep->x = Posi->x+GeoResult_X; ep->y = Posi->y+GeoResult_Y; ep->z = Posi->z+GeoResult_Z; GetMoveLocation( 0, PosiMinY, 0, Angle->x, Angle->y, Angle->z ); Lines[0].sp.x=Posi->x+GeoResult_X; Lines[0].sp.y=Posi->y+GeoResult_Y; Lines[0].sp.z=Posi->z+GeoResult_Z; GetMoveLocation( 0, PosiMinY, dist2, Angle->x, Angle->y, Angle->z ); Lines[0].ep.x=Posi->x+GeoResult_X; Lines[0].ep.y=Posi->y+GeoResult_Y; Lines[0].ep.z=Posi->z+GeoResult_Z; GetMoveLocation( 0, PosiMaxY, 0, Angle->x, Angle->y, Angle->z ); Lines[1].sp.x=Posi->x+GeoResult_X; Lines[1].sp.y=Posi->y+GeoResult_Y; Lines[1].sp.z=Posi->z+GeoResult_Z; GetMoveLocation( 0, PosiMaxY, dist2, Angle->x, Angle->y, Angle->z ); Lines[1].ep.x=Posi->x+GeoResult_X; Lines[1].ep.y=Posi->y+GeoResult_Y; Lines[1].ep.z=Posi->z+GeoResult_Z; GetMoveLocation( -width, PosiMinY, dist2, Angle->x, Angle->y, Angle->z ); Lines[2].sp.x=Posi->x+GeoResult_X; Lines[2].sp.y=Posi->y+GeoResult_Y; Lines[2].sp.z=Posi->z+GeoResult_Z; GetMoveLocation( width, PosiMinY, dist2, Angle->x, Angle->y, Angle->z ); Lines[2].ep.x=Posi->x+GeoResult_X; Lines[2].ep.y=Posi->y+GeoResult_Y; Lines[2].ep.z=Posi->z+GeoResult_Z; GetMoveLocation( -width, PosiMaxY, dist2, Angle->x, Angle->y, Angle->z ); Lines[3].sp.x=Posi->x+GeoResult_X; Lines[3].sp.y=Posi->y+GeoResult_Y; Lines[3].sp.z=Posi->z+GeoResult_Z; GetMoveLocation( width, PosiMaxY, dist2, Angle->x, Angle->y, Angle->z ); Lines[3].ep.x=Posi->x+GeoResult_X; Lines[3].ep.y=Posi->y+GeoResult_Y; Lines[3].ep.z=Posi->z+GeoResult_Z; return 4; } //XÀ̵¿ÇÒ À§Ä¡¸¦ X ¶óÀÎÀ¸·Î ã´Â´Ù static int smMakeXLine( POINT3D *Posi , POINT3D *Angle , int dist , int ObjWidth , int ObjHeight, smLINE3D *Lines , POINT3D *ep ) { int width; int dist2 = dist+fONE*12; int PosiMinY = fONE*15; int PosiMaxY = ObjHeight-(ObjHeight>>2); int left,right,top,bottom; width = ObjWidth>>2; GetMoveLocation( 0, 0, dist, Angle->x, Angle->y, Angle->z ); ep->x = Posi->x+GeoResult_X; ep->y = Posi->y+GeoResult_Y; ep->z = Posi->z+GeoResult_Z; left = -width; right = width; top = -width; bottom = width; GetMoveLocation( 0, PosiMinY, 0, Angle->x, Angle->y, Angle->z ); Lines[0].sp.x=Posi->x+GeoResult_X; Lines[0].sp.y=Posi->y+GeoResult_Y; Lines[0].sp.z=Posi->z+GeoResult_Z; GetMoveLocation( 0, PosiMinY, dist2, Angle->x, Angle->y, Angle->z ); Lines[0].ep.x=Posi->x+GeoResult_X; Lines[0].ep.y=Posi->y+GeoResult_Y; Lines[0].ep.z=Posi->z+GeoResult_Z; GetMoveLocation( 0, PosiMaxY, 0, Angle->x, Angle->y, Angle->z ); Lines[1].sp.x=Posi->x+GeoResult_X; Lines[1].sp.y=Posi->y+GeoResult_Y; Lines[1].sp.z=Posi->z+GeoResult_Z; GetMoveLocation( 0, PosiMaxY, dist2, Angle->x, Angle->y, Angle->z ); Lines[1].ep.x=Posi->x+GeoResult_X; Lines[1].ep.y=Posi->y+GeoResult_Y; Lines[1].ep.z=Posi->z+GeoResult_Z; GetMoveLocation( -width, PosiMinY, -width, Angle->x, Angle->y, Angle->z ); Lines[2].sp.x=ep->x+GeoResult_X; Lines[2].sp.y=ep->y+GeoResult_Y; Lines[2].sp.z=ep->z+GeoResult_Z; GetMoveLocation( width, PosiMinY, width, Angle->x, Angle->y, Angle->z ); Lines[2].ep.x=ep->x+GeoResult_X; Lines[2].ep.y=ep->y+GeoResult_Y; Lines[2].ep.z=ep->z+GeoResult_Z; GetMoveLocation( -width, PosiMaxY, width, Angle->x, Angle->y, Angle->z ); Lines[3].sp.x=ep->x+GeoResult_X; Lines[3].sp.y=ep->y+GeoResult_Y; Lines[3].sp.z=ep->z+GeoResult_Z; GetMoveLocation( width, PosiMaxY, -width, Angle->x, Angle->y, Angle->z ); Lines[3].ep.x=ep->x+GeoResult_X; Lines[3].ep.y=ep->y+GeoResult_Y; Lines[3].ep.z=ep->z+GeoResult_Z; return 6; } class smCHAR; //´Ù¸¥ ij¸¯ÅÍ¿ÍÀÇ À§Ä¡ °ãÄ¡´ÂÁö È®ÀÎ extern smCHAR *CheckOtherPlayPosi( int x, int y, int z ); //À̵¿ÇÒ ¹æÇâ°ú À§Ä¡¸¦ °Ë»çÇÏ¿© ÁÂÇ¥¸¦ µ¹·ÁÁØ´Ù int smSTAGE3D::CheckNextMove( POINT3D *Posi, POINT3D *Angle , POINT3D *MovePosi, int dist , int ObjWidth , int ObjHeight , int CheckOverLap ) { int he,height; // int num, fnum; int cnt; smSTAGE_FACE *face; // int CalcSum; POINT3D ep; POINT3D zAngle[3]; smLINE3D Lines[8]; //int left,right,top,bottom; if ( !Head ) return NULL; CheckFace = 0; smStage_WaterChk = CLIP_OUT; height = CLIP_OUT; zAngle[0].x = Angle->x; zAngle[0].y = Angle->y; zAngle[0].z = Angle->z; zAngle[1].x = Angle->x; zAngle[1].y = (Angle->y- 768) & ANGCLIP; zAngle[1].z = Angle->z; zAngle[2].x = Angle->x; zAngle[2].y = (Angle->y+ 768) & ANGCLIP; zAngle[2].z = Angle->z; int hy; int heFace; int acnt; int cnt2; int Sucess = 0; int Oly = Posi->y; int WaterHeight; int whe; hy = (ObjHeight+fONE*16384); acnt = MakeAreaFaceList( Posi->x-fONE*64*1 , Posi->z-fONE*64*1 , fONE*64*2 , fONE*64*2 , Posi->y+hy , Posi->y-hy ); if ( !acnt ) return NULL; int ccnt; int LineCnt; WaterHeight = CLIP_OUT; for( ccnt=0;ccnt<3;ccnt++ ) { LineCnt = smMakeTLine( Posi , &zAngle[ccnt] , dist , ObjWidth , ObjHeight, Lines , &ep ); // LineCnt = smMakeXLine( Posi , &zAngle[ccnt] , dist , ObjWidth , ObjHeight, Lines , &ep ); for(int cnt=0;cnt<acnt;cnt++ ) { face = smFaceList[cnt]; if ( smMaterial[ face->Vertex[3] ].MeshState & SMMAT_STAT_CHECK_FACE ) { he = GetPolyHeight( face , ep.x, ep.z ); if ( he!=CLIP_OUT ) { hy = he-ep.y; if ( hy< Stage_StepHeight ) {//10*fONE ) { if ( height<he ) { height = he; heFace = cnt; } } CheckFace = face; } } else { //if (smMaterial[ face->Vertex[3] ].Transparency!=0.1) { // //±âÁ¸¿¡ ¿øº». if (smMaterial[ face->Vertex[3] ].Transparency>0.1) { //###################################################################################### //ÀÛ ¼º ÀÚ : ¿À ¿µ ¼® if( smMaterial[face->Vertex[3]].Transparency > 0.1 || smMaterial[face->Vertex[3]].MeshState & sMATS_SCRIPT_ORG_WATER ) //###################################################################################### { //¹° ³ôÀÌ °è»ê he = GetPolyHeight( face , ep.x, ep.z ); if ( WaterHeight<he ) WaterHeight = he; } } } if ( height!=CLIP_OUT ) { smStage_WaterChk = WaterHeight; whe = (height+(ObjHeight>>1))+10*fONE; if ( WaterHeight!=CLIP_OUT && WaterHeight>whe && WaterHeight<whe+5*fONE ) { //¹°¼Ó¿¡ Àá±è //return FALSE; cnt2 = 0; } else { for( cnt2=0;cnt2<acnt;cnt2++ ) { if ( smMaterial[ smFaceList[cnt2]->Vertex[3] ].MeshState & SMMAT_STAT_CHECK_FACE ) { if ( GetTriangleImact( smFaceList[cnt2], Lines ,LineCnt )==TRUE ) { cnt2=-1; break; } } } } if ( cnt2>0 ) { if ( CheckOverLap ) { if ( ccnt>0 && CheckOtherPlayPosi( ep.x , height, ep.z )==NULL ) { MovePosi->x = ep.x; MovePosi->z = ep.z; MovePosi->y = height; Sucess = TRUE; return ccnt+1; } } else { MovePosi->x = ep.x; MovePosi->z = ep.z; MovePosi->y = height; Sucess = TRUE; return ccnt+1; } } } if ( ccnt==0 ) dist>>=1; } CheckFace = 0; return NULL; } //ÇöÀç À§Ä¡¿¡¼­ÀÇ ¹Ù´Ú ³ôÀ̸¦ ±¸ÇÑ´Ù int smSTAGE3D::GetFloorHeight( int x, int y, int z , int ObjHeight ) { int he,height; int cnt; smSTAGE_FACE *face; int hy; int acnt; hy = (ObjHeight+fONE*16384); acnt = MakeAreaFaceList( x-fONE*64*1 , z-fONE*64*1 , fONE*64*2 , fONE*64*2 , y+hy , y-hy ); if ( !acnt ) return CLIP_OUT; height = CLIP_OUT; for(int cnt=0;cnt<acnt;cnt++ ) { face = smFaceList[cnt]; if ( smMaterial[ face->Vertex[3] ].MeshState & SMMAT_STAT_CHECK_FACE ) { he = GetPolyHeight( face , x, z ); if ( he!=CLIP_OUT ) { hy = he-y; if ( hy<10*fONE ) { if ( height<he ) { height = he; } } } } } return height; } //ÇöÀç À§Ä¡¿¡¼­ÀÇ ¹Ù´Ú ³ôÀ̸¦ ±¸ÇÑ´Ù int smSTAGE3D::GetFloorHeight2( int x, int y, int z , int ObjHeight ) { int he,height; int cnt; smSTAGE_FACE *face; int hy; int acnt; hy = (ObjHeight+fONE*16384); acnt = MakeAreaFaceList( x-fONE*64*1 , z-fONE*64*1 , fONE*64*2 , fONE*64*2 , y+hy , y-hy ); if ( !acnt ) return CLIP_OUT; height = CLIP_OUT; for(int cnt=0;cnt<acnt;cnt++ ) { face = smFaceList[cnt]; if ( smMaterial[ face->Vertex[3] ].MeshState & SMMAT_STAT_CHECK_FACE ) { he = GetPolyHeight( face , x, z ); if ( he!=CLIP_OUT ) { hy = he-y; if ( hy>10*fONE ) { if ( height>he ) { height = he; } } } } } return height; } //ÇöÀç ³ôÀÌ¿¡ °ãÄ¡´Â Æú¸®°ïÀÌ ÀÖ´Â Áö È®ÀÎÈÄ ÀÖÀ¸¸é Àüü ³ôÀ̸¦ ±¸ÇÑ´Ù int smSTAGE3D::GetEmptyHeight( int x, int y, int z , int ObjHeight ) { int he,height; int cnt; smSTAGE_FACE *face; int hy; int acnt; int fchk; fchk = 0; hy = (ObjHeight+fONE*16384); acnt = MakeAreaFaceList( x-fONE*64*1 , z-fONE*64*1 , fONE*64*2 , fONE*64*2 , y+hy , y-hy ); if ( !acnt ) return CLIP_OUT; height = CLIP_OUT; for(int cnt=0;cnt<acnt;cnt++ ) { face = smFaceList[cnt]; if ( smMaterial[ face->Vertex[3] ].MeshState & SMMAT_STAT_CHECK_FACE ) { he = GetPolyHeight( face , x, z ); if ( he!=CLIP_OUT ) { if ( height<he ) { height = he; } if ( he<y+ObjHeight && he>y ) fchk++; } } } if ( fchk==0 ) return NULL; return height; } //¹Ù´Ú Æú¸®°ï ¸é¿¡ y==height ¿Í ÀÏÄ¡ÇÏ´ÂÁö È®ÀÎ int smSTAGE3D::CheckFloorFaceHeight( int x, int y, int z , int hSize ) { int cnt; smSTAGE_FACE *face; int height = 1000000; int acnt; int he; int hy = fONE*16384; acnt = MakeAreaFaceList( x-fONE*64*1 , z-fONE*64*1 , fONE*64*2 , fONE*64*2 , y+hy , y-hy ); if ( !acnt ) return CLIP_OUT; for(int cnt=0;cnt<acnt;cnt++ ) { face = smFaceList[cnt]; if ( smMaterial[ face->Vertex[3] ].MeshState & SMMAT_STAT_CHECK_FACE ) { he = abs(GetPolyHeight( face , x, z )-y); if ( he<height ) height = he; if ( he<=hSize ) return 0; } } if ( height==1000000 ) height = CLIP_OUT; return height; } //ÁöÁ¤µÈ ¹æÇâÀÇ °Å¸®¸¦ ÀÕ´Â ¼±ºÐ¿¡ Æú¸®°ÇÀÌ Ãæµ¹ÇÏ´ÂÁö È®ÀÎ int smSTAGE3D::CheckVecImpact( POINT3D *Posi, POINT3D *Angle , int dist ) { smLINE3D sLine[1]; if ( !Head ) return 0; int hy; int acnt; int cnt2; hy = (fONE*64); acnt = MakeAreaFaceList( Posi->x-fONE*64*1 , Posi->z-fONE*64*1 , fONE*64*2 , fONE*64*2 , Posi->y+hy , Posi->y-hy ); if ( !acnt ) return TRUE; memcpy( &sLine[0].sp , Posi , sizeof( POINT3D ) ); GetMoveLocation( 0, 0, dist, Angle->x, Angle->y, Angle->z ); sLine[0].ep.x = Posi->x+GeoResult_X; sLine[0].ep.y = Posi->y+GeoResult_Y; sLine[0].ep.z = Posi->z+GeoResult_Z; for( cnt2=0;cnt2<acnt;cnt2++ ) { if ( smMaterial[ smFaceList[cnt2]->Vertex[3] ].MeshState & SMMAT_STAT_CHECK_FACE ) { if ( GetTriangleImact( smFaceList[cnt2], sLine ,1 )==TRUE ) { Posi->x = sLine[0].ep.x; Posi->y = sLine[0].ep.y; Posi->z = sLine[0].ep.z; return FALSE; } } } Posi->x = sLine[0].ep.x; Posi->y = sLine[0].ep.y; Posi->z = sLine[0].ep.z; return TRUE; } //ÁöÁ¤µÈ ¹æÇâÀÇ °Å¸®¸¦ ÀÕ´Â ¼±ºÐ¿¡ Æú¸®°ÇÀÌ Ãæµ¹ÇÏ´ÂÁö È®ÀÎ int smSTAGE3D::CheckVecImpact2( int sx,int sy,int sz, int ex,int ey,int ez ) { smLINE3D sLine[1]; if ( !Head ) return 0; int hy; int acnt; int cnt2; hy = (fONE*128); acnt = MakeAreaFaceList( sx-fONE*64*1 , sz-fONE*64*1 , fONE*64*2 , fONE*64*2 , sy+hy , sy-hy ); if ( !acnt ) return TRUE; sLine[0].sp.x = sx; sLine[0].sp.y = sy; sLine[0].sp.z = sz; sLine[0].ep.x = ex; sLine[0].ep.y = ey; sLine[0].ep.z = ez; for( cnt2=0;cnt2<acnt;cnt2++ ) { if ( smMaterial[ smFaceList[cnt2]->Vertex[3] ].MeshState & SMMAT_STAT_CHECK_FACE ) { if ( GetTriangleImact( smFaceList[cnt2], sLine ,1 )==TRUE ) { return FALSE; } } } return TRUE; } smSTAGE3D::smSTAGE3D() { // ¶óÀÌÆ® º¤ÅÍ VectLight.x = fONE; VectLight.y = -fONE; VectLight.z = fONE/2; Bright = DEFAULT_BRIGHT; Contrast = DEFAULT_CONTRAST; Head = FALSE; smLight = 0; nLight = 0; MemMode = 0; } smSTAGE3D::~smSTAGE3D() { Close(); } smSTAGE3D::smSTAGE3D( int nv , int nf ) { // ¶óÀÌÆ® º¤ÅÍ VectLight.x = fONE; VectLight.y = -fONE; VectLight.z = fONE/2; Bright = DEFAULT_BRIGHT; Contrast = DEFAULT_CONTRAST; Head = FALSE; smLight = 0; nLight = 0; MemMode = 0; Init( nv, nf ); } //###################################################################################### //ÀÛ ¼º ÀÚ : ¿À ¿µ ¼® void smSTAGE3D::Init(void) { nLight = 0; nTexLink = 0; nFace = 0; nVertex = 0; ::ZeroMemory( StageArea, sizeof(StageArea) ); AreaList = NULL; Vertex = NULL; Face = NULL; TexLink = NULL; smLight = NULL; smMaterialGroup = NULL; StageObject = NULL; smMaterial = NULL; lpwAreaBuff = NULL; } //###################################################################################### int smSTAGE3D::Init( int nv , int nf ) { Vertex = new smSTAGE_VERTEX[ nv ]; Face = new smSTAGE_FACE[ nf ]; TexLink = new smTEXLINK[ nf * 4 ]; StageObject = new smSTAGE_OBJECT; nVertex = 0; nFace = 0; nTexLink = 0; nVertColor = 0; SumCount = 0; CalcSumCount = 0; smMaterialGroup = 0; lpwAreaBuff = 0; StageMapRect.top = 0; StageMapRect.bottom = 0; StageMapRect.left = 0; StageMapRect.right = 0; clearStageArea(); return TRUE; } int smSTAGE3D::Close() { Head = 0; /* int cnt,cnt2; int num; for( cnt2=MAP_SIZE-1;cnt2>=0;cnt2--) { for( cnt=MAP_SIZE-1;cnt>=0;cnt-- ) { num = (int)StageArea[ cnt ][ cnt2 ]; if ( num>0 ) { delete StageArea[cnt][cnt2]; } } } */ /* MemMode smLIGHT3D *smLight; //Á¶¸í ¼³Á¤ int nLight; //Á¶¸í ¼ö */ if ( nLight ) delete smLight; if ( lpwAreaBuff ) delete lpwAreaBuff; if ( nTexLink ) delete TexLink; if ( nFace ) delete Face; if ( nVertex ) delete Vertex; if ( StageObject ) delete StageObject; if ( smMaterialGroup ) delete smMaterialGroup; return TRUE; } //¹öÅØ½º ÁÂÇ¥ Ãß°¡ int smSTAGE3D::AddVertex ( int x, int y, int z ) { Vertex[nVertex].sum = 0; Vertex[nVertex].x = x; Vertex[nVertex].y = y; Vertex[nVertex].z = z; Vertex[nVertex].sDef_Color[ SMC_R ] = 255; Vertex[nVertex].sDef_Color[ SMC_G ] = 255; Vertex[nVertex].sDef_Color[ SMC_B ] = 255; Vertex[nVertex].sDef_Color[ SMC_A ] = 255; if ( nVertex==0 ) { //¸ÇóÀ½ °ªÀ¸·Î ÃʱâÈ­ StageMapRect.top = z; StageMapRect.bottom = z; StageMapRect.left = x; StageMapRect.right = x; } else { //Á¸Àç ÇÏ´Â ±¸¿ªÅ©±â ¼³Á¤ if ( StageMapRect.top>z ) StageMapRect.top = z; if ( StageMapRect.bottom<z ) StageMapRect.bottom = z; if ( StageMapRect.left>x ) StageMapRect.left = x; if ( StageMapRect.right<x ) StageMapRect.right = x; } nVertex++; return (nVertex-1); } //ÆäÀ̽º Ãß°¡ int smSTAGE3D::AddFace ( int a, int b, int c , int matrial ) { Face[nFace].sum = 0; Face[nFace].Vertex[0] = a; Face[nFace].Vertex[1] = b; Face[nFace].Vertex[2] = c; Face[nFace].Vertex[3] = matrial; Face[nFace].lpTexLink = 0; // ÅØ½ºÃÄ ¿¬°á ÁÂÇ¥ nFace++; /* //µð¹ö±ë¿ë int x,z,sx,sz; x = abs( Vertex[a].x - Vertex[b].x ); if ( x>64*30*fONE ) { x = x; } x = abs( Vertex[b].x - Vertex[c].x ); if ( x>64*30*fONE ) { x = x; } x = abs( Vertex[c].x - Vertex[a].x ); if ( x>64*30*fONE ) { x = x; } x = abs( Vertex[a].z - Vertex[b].z ); if ( x>64*30*fONE ) { x = x; } x = abs( Vertex[b].z - Vertex[c].z ); if ( x>64*30*fONE ) { x = x; } x = abs( Vertex[c].z - Vertex[a].z ); if ( x>64*30*fONE ) { x = x; } */ return nFace-1; } //ÆäÀ̽º¿¡ ¸ÞÆ®¸®¾ó ÀÔ·Â int smSTAGE3D::SetFaceMaterial( int FaceNum , int MatNum ) { Face[ FaceNum ].Vertex[3] = MatNum; return TRUE; } //¹öÅØ½º¿¡ »ö ¼³Á¤ int smSTAGE3D::SetVertexColor ( DWORD NumVertex , BYTE r , BYTE g, BYTE b , BYTE a ) { Vertex[ NumVertex ].sDef_Color[ SMC_R ] = r; Vertex[ NumVertex ].sDef_Color[ SMC_G ] = g; Vertex[ NumVertex ].sDef_Color[ SMC_B ] = b; Vertex[ NumVertex ].sDef_Color[ SMC_A ] = a; return TRUE; } //ÅØ½ºÃÄ ÁÂÇ¥¿¬°áÀ» Ãß°¡ÇÑ´Ù int smSTAGE3D::AddTexLink( int FaceNum , DWORD *hTex , smFTPOINT *t1 , smFTPOINT *t2 , smFTPOINT *t3 ) { int cnt; smTEXLINK *tl; //ÁÂÇ¥¼³Á¤ TexLink[ nTexLink ].u[0] = t1->u; TexLink[ nTexLink ].v[0] = t1->v; TexLink[ nTexLink ].u[1] = t2->u; TexLink[ nTexLink ].v[1] = t2->v; TexLink[ nTexLink ].u[2] = t3->u; TexLink[ nTexLink ].v[2] = t3->v; TexLink[ nTexLink ].hTexture = hTex; TexLink[ nTexLink ].NextTex = 0; //ÁöÁ¤µÈ ÆäÀ̽º¿Í ¿¬°á½ÃŲ´Ù if ( !Face[FaceNum].lpTexLink ) { //ÃÖÃÊÀÇ ÅØ½ºÃÄÁÂÇ¥ÀÏ °æ¿ì Face[FaceNum].lpTexLink = &TexLink[ nTexLink ]; } else { //ÀÌ¹Ì ¿¬°áµÇÀÖ´Â ÁÂÇ¥°¡ Àִ°æ¿ì tl = Face[FaceNum].lpTexLink; for(int cnt=0;cnt<8;cnt++ ) { if ( !tl->NextTex ) { //¸¶Áö¸·À¸·Î ¿¬°áµÈ ÁÂÇ¥¸¦ ã¾Æ ¿¬°á tl->NextTex = &TexLink[ nTexLink ]; break; } else { //´ÙÀ½ ÁÂÇ¥·Î ³Ñ±è tl = tl->NextTex; } } } nTexLink++; return nTexLink-1; } //³ë¸» °ªÀ» ±¸ÇÏ¿© ¹öÅØ½º¿¡ ½¦À̵ù ¸í¾ÏÀ» Ãß°¡ÇÑ´Ù //###################################################################################### //ÀÛ ¼º ÀÚ : ¿À ¿µ ¼® int smSTAGE3D::SetVertexShade( int isSetLight ) //###################################################################################### { int cnt; int cnt2; POINT3D p[3]; POINT3D pn; POINT3D *normal; POINT3D pLight; int *NormalCnt; int gShade; int r,g,b; memcpy( &pLight , &VectLight , sizeof( POINT3D ) ); normal = new POINT3D[nVertex]; NormalCnt = new int [nVertex]; // Normal°ª ÃʱâÈ­ for(int cnt=0; cnt<nVertex ;cnt++) { normal[cnt].x = 0; normal[cnt].y = 0; normal[cnt].z = 0; NormalCnt[cnt] = 0; } // NormalÁÂÇ¥ ±¸ÇÔ for(int cnt=0; cnt<nFace; cnt++ ) { for(cnt2=0;cnt2<3;cnt2++) { p[cnt2].x = Vertex[ Face[cnt].Vertex[cnt2] ].x>>FLOATNS; p[cnt2].y = Vertex[ Face[cnt].Vertex[cnt2] ].y>>FLOATNS; p[cnt2].z = Vertex[ Face[cnt].Vertex[cnt2] ].z>>FLOATNS; } SetNormal( &p[0], &p[1], &p[2] , &pn ); //Face ³ë¸»º¤ÅÍ ¼³Á¤ Face[cnt].VectNormal[0] = (short)pn.x; Face[cnt].VectNormal[1] = (short)pn.y; Face[cnt].VectNormal[2] = (short)pn.z; for(cnt2=0;cnt2<3;cnt2++) { normal[ Face[cnt].Vertex[cnt2] ].x += pn.x; normal[ Face[cnt].Vertex[cnt2] ].y += pn.y; normal[ Face[cnt].Vertex[cnt2] ].z += pn.z; NormalCnt[ Face[cnt].Vertex[cnt2] ] ++; } } // gShade ³ë¸» ±¸ÇÑµÚ RGBA·Î ¹öÅØ½º¿¡ ÀúÀå for(int cnt=0; cnt<nVertex; cnt++ ) { if ( NormalCnt[ cnt ]>0 ) { normal[ cnt ].x /= NormalCnt[cnt]; normal[ cnt ].y /= NormalCnt[cnt]; normal[ cnt ].z /= NormalCnt[cnt]; } pn.x = normal[ cnt ].x; pn.y = normal[ cnt ].y; pn.z = normal[ cnt ].z; //###################################################################################### //ÀÛ ¼º ÀÚ : ¿À ¿µ ¼® if( isSetLight ) { gShade = ((pn.x * pLight.x) + (pn.y * pLight.y) + (pn.z * pLight.z)) >> FLOATNS; gShade /= Contrast; //CONTRAST gShade += Bright; //BRIGHT r = Vertex[ cnt ].sDef_Color[ SMC_R ]; g = Vertex[ cnt ].sDef_Color[ SMC_G ]; b = Vertex[ cnt ].sDef_Color[ SMC_B ]; r = ( r*gShade )>>8; // %1ºñÀ² x 0 ~ 2 ±îÁö g = ( g*gShade )>>8; b = ( b*gShade )>>8; Vertex[ cnt ].sDef_Color[SMC_R] = r; Vertex[ cnt ].sDef_Color[SMC_G] = g; Vertex[ cnt ].sDef_Color[SMC_B] = b; Vertex[ cnt ].sDef_Color[SMC_A] = 255; //Alpha } //###################################################################################### } float transp; for(int cnt=0;cnt<nFace;cnt++) { transp = smMaterial[ Face[cnt].Vertex[3] ].Transparency; if ( transp>0 ) { for( cnt2=0;cnt2<3;cnt2++ ) { Vertex[ Face[cnt].Vertex[cnt2] ].sDef_Color[ SMC_A ] = 255-((BYTE)(transp * 255)); } } } delete NormalCnt; delete normal; return TRUE; } //¸ðµç ¹öÅØ½º¿¡ Á¶¸í°ªÀ» Ãß°¡ ÇÑ´Ù int smSTAGE3D::AddVertexLightRound( POINT3D *LightPos , int r, int g, int b, int Range ) { int cnt; double ddist; int dist; int dr,dg,db; int lx,ly,lz; int dRange; int x,y,z; int eLight; dRange = ((Range/256)*72) >>FLOATNS; dRange *= dRange; lx = LightPos->x; ly = LightPos->y; lz = LightPos->z; /* r/=8; g/=8; b/=8; */ for(int cnt=0; cnt<nVertex; cnt++ ) { x = (lx - Vertex[ cnt ].x)>>FLOATNS; y = (ly - Vertex[ cnt ].y)>>FLOATNS; z = (lz - Vertex[ cnt ].z)>>FLOATNS; /* if ( abs(x)>Range || abs(y)>Range || abs(z)>Range ) ddist = dRange; else ddist = x*x+y*y+z*z; */ ddist = x*x+y*y+z*z; if ( ddist<dRange ) { //Á¶¸í ¹üÀ§ ¾È¿¡ ÀÖÀ½ dist = (int)sqrt( ddist ); eLight = (Range>>FLOATNS)-dist; //eLight = dRange-ddist; eLight = fONE - ((eLight<<FLOATNS)/dRange); dr = (r * eLight)>>FLOATNS; dg = (g * eLight)>>FLOATNS; db = (b * eLight)>>FLOATNS; Vertex[cnt].sDef_Color[SMC_R] += dr; Vertex[cnt].sDef_Color[SMC_G] += dg; Vertex[cnt].sDef_Color[SMC_B] += db; if ( Vertex[cnt].sDef_Color[SMC_R]>360 ) Vertex[cnt].sDef_Color[SMC_R] = 360; if ( Vertex[cnt].sDef_Color[SMC_G]>360 ) Vertex[cnt].sDef_Color[SMC_G] = 360; if ( Vertex[cnt].sDef_Color[SMC_B]>360 ) Vertex[cnt].sDef_Color[SMC_B] = 360; /* Vertex[cnt].sDef_Color[0] += db; Vertex[cnt].sDef_Color[1] += dg; Vertex[cnt].sDef_Color[2] += dr; */ /* if ( Vertex[cnt].sDef_Color[0]>420 ) Vertex[cnt].sDef_Color[0]=420; if ( Vertex[cnt].sDef_Color[1]>420 ) Vertex[cnt].sDef_Color[1]=420; if ( Vertex[cnt].sDef_Color[2]>420 ) Vertex[cnt].sDef_Color[2]=420; */ } } return TRUE; } //µ¿Àû Á¶¸í ÃʱâÈ­ ( ¼³Á¤ °¹¼ö ) int smSTAGE3D::InitDynLight( int nl ) { nLight = 0; smLight = new smLIGHT3D[ nl ]; return TRUE; } //¸ðµç ¹öÅØ½º¿¡ Á¶¸í°ªÀ» Ãß°¡ ÇÑ´Ù int smSTAGE3D::AddDynLight( int type , POINT3D *LightPos , int r, int g, int b, int Range ) { smLight[nLight].type = type; smLight[nLight].x = LightPos->x; smLight[nLight].y = LightPos->y; smLight[nLight].z = LightPos->z; smLight[nLight].r = r; smLight[nLight].g = g; smLight[nLight].b = b; smLight[nLight].Range = Range; nLight++; return TRUE; } //###################################################################################### //ÀÛ ¼º ÀÚ : ¿À ¿µ ¼® int smSTAGE3D::CheckFaceIceFoot( POINT3D *Pos, POINT3D *Angle, int CheckHeight ) { int num = CheckHeight + (fONE*16384); int acnt = MakeAreaFaceList( Pos->x - (fONE*64*1), Pos->z - (fONE*64*1), fONE*64*2, fONE*64*2, Pos->y+num, Pos->y-num ); if( ! acnt ) return 0; smSTAGE_FACE *face; int faceNum = 0, faceheight = CLIP_OUT; for( int cnt=0; cnt < acnt; cnt++ ) { face = smFaceList[ cnt ]; num = smMaterial[ face->Vertex[3] ].MeshState; if( (num & SMMAT_STAT_CHECK_FACE) && (num & sMATS_SCRIPT_CHECK_ICE) ) { num = GetPolyHeight( face, Pos->x, Pos->z ); if( num != CLIP_OUT ) { if( (num - Pos->y) < 10 * fONE ) { if( faceheight < num ) { faceheight = num; faceNum = cnt; } } } } } if( faceNum == 0 ) return 0; face = smFaceList[ faceNum ]; Angle->x = GetRadian2D( 0, -1024, face->VectNormal[2], face->VectNormal[1] ); Angle->z = GetRadian2D( 0, -1024, face->VectNormal[0], face->VectNormal[1] ); Pos->y = faceheight + (1*fONE); return 1; } //###################################################################################### /* MemMode smLIGHT3D *smLight; //Á¶¸í ¼³Á¤ int nLight; //Á¶¸í ¼ö struct smLIGHT3D { int type; int x,y,z; int Range; BYTE r,g,b; }; */ /* // ¹öÅØ½º struct smSTAGE_VERTEX { DWORD sum; // ÃÖ±Ù ¿¬»ê ¹øÈ£ smRENDVERTEX *lpRendVertex; // ·»´õ¸µÀ» À§ÇÑ ¹öÅØ½º Æ÷ÀÎÅÍ // ¼Ò½º ¹öÅØ½º int x,y,z; // ¿ùµå ÁÂÇ¥ //BYTE bDef_Color[4]; // ±âº» »ö»ó (RGBA)(Color ) //BYTE bDef_Specular[4]; // ±âº» »ö»ó (RGBA)(Specular ) short sDef_Color[4]; // ±âº» »ö»ó ( RGBA ) }; // ÇöÀç Å©±â 28 ¹ÙÀÌÆ® */ //Àӽà ÆäÀ̽º ¸ñ·ÏÀ» ÀÛ¼ºÇÑ´Ù int smSTAGE3D::MakeAreaFaceList( int x,int z, int width, int height , int top , int bottom ) { int cnt; smSTAGE_FACE *face; int CalcSum; int wx,wz; int lx,lz; int num,fnum; int cntX , cntZ; int sx,sz; int y1,y2,y3; smFaceListCnt = 0; CalcSumCount++; CalcSum = CalcSumCount; sx = (x>>(FLOATNS+6))&0xFF; sz = (z>>(FLOATNS+6))&0xFF; wx = sx+(width>>(FLOATNS+6)); wz = sz+(height>>(FLOATNS+6)); //###################################################################################### //ÀÛ ¼º ÀÚ : ¿À ¿µ ¼® //for( cntX=sx; cntX <= wx; cntX++ ) //{ // for( cntZ=sz; cntZ <= wz; cntZ++ ) for( cntX=sx; cntX < wx; cntX++ ) { for( cntZ=sz; cntZ < wz; cntZ++ ) { //###################################################################################### lx=cntX&0xFF; lz=cntZ&0xFF; if ( StageArea[lx][lz] ) { //¿µ¿ª num = StageArea[lx][lz][0]; //¿µ¿ª¿¡ Æ÷ÇÔµÈ ÆäÀ̽º ¼ö for( cnt=1;cnt<num+1;cnt++ ) { fnum = StageArea[lx][lz][cnt]; face = &Face[ fnum ]; if ( face->CalcSum!=CalcSum ) { face->CalcSum = CalcSum; y1 = Vertex[face->Vertex[0]].y; y2 = Vertex[face->Vertex[1]].y; y3 = Vertex[face->Vertex[2]].y; if ( (y1<top && y1>bottom) || (y2<top && y2>bottom) || (y3<top && y3>bottom) ) smFaceList[ smFaceListCnt ++] = face; } } } } } CalcSumCount++; return smFaceListCnt; } //ÆäÀ̽º¿¡ ÇØ´çÇÏ´Â ³ôÀ̸¦ ±¸ÇÑ´Ù int smSTAGE3D::GetPolyHeight( smSTAGE_FACE *face , int x, int z ) { smSTAGE_VERTEX *p[3]; smSTAGE_VERTEX *ptop, *pmid , *pbot; int cnt; int lx , tx , bx; int ly , ty , by; int lz , tz , bz; int x1 , x2; int y1 , y2; int ye,xe; int yl; p[0] = &Vertex[ face->Vertex[0] ]; p[1] = &Vertex[ face->Vertex[1] ]; p[2] = &Vertex[ face->Vertex[2] ]; ptop = p[0]; pbot = p[1]; pmid = p[2]; //ÃÖ»óÀ§ Æ÷ÀÎÆ® for(cnt=0;cnt<3;cnt++) { if ( p[cnt]->z<ptop->z ) ptop = p[cnt]; } if ( ptop==pbot ) pbot = pmid; //ÃÖÇÏÀ§ Æ÷ÀÎÆ® for(cnt=0;cnt<3;cnt++) { if ( p[cnt]->z>pbot->z && ptop!=p[cnt] ) pbot = p[cnt]; } //Áß°£ Æ÷ÀÎÆ® for(cnt=0;cnt<3;cnt++) { if ( ptop!=p[cnt] && pbot!=p[cnt] ) { pmid = p[cnt]; break; } } if ( z<ptop->z || z>pbot->z ) return CLIP_OUT; lz = pbot->z - ptop->z; tz = pmid->z - ptop->z; bz = pbot->z - pmid->z; if ( lz!=0 ) lx = ((pbot->x - ptop->x)<<FLOATNS) / lz ; else lx = 0; if ( tz!=0 ) tx = ((pmid->x - ptop->x)<<FLOATNS) / tz ; else tx = 0; if ( bz!=0 ) bx = ((pbot->x - pmid->x)<<FLOATNS) / bz ; else bx = 0; x1 = (( lx * ( z - ptop->z ) )>>FLOATNS) + ptop->x; if( z<pmid->z ) { x2 = (( tx * ( z - ptop->z ) )>>FLOATNS) + ptop->x; } else { x2 = (( bx * ( z - pmid->z ) )>>FLOATNS) + pmid->x; } if ( lz!=0 ) ly = ((pbot->y - ptop->y)<<FLOATNS) / lz ; else ly = 0; if ( tz!=0 ) ty = ((pmid->y - ptop->y)<<FLOATNS) / tz ; else ty = 0; if ( bz!=0 ) by = ((pbot->y - pmid->y)<<FLOATNS) / bz ; else by = 0; y1 = (( ly * ( z - ptop->z ) ) >>FLOATNS) + ptop->y; if( z<pmid->z ) { y2 = (( ty * ( z - ptop->z ) )>>FLOATNS) + ptop->y; } else { y2 = (( by * ( z - pmid->z ) )>>FLOATNS) + pmid->y; } if ( x1>x2 ) { cnt=x1; x1=x2; x2=cnt; cnt=y1; y1=y2; y2=cnt; } if ( x<x1 || x>x2 ) return CLIP_OUT; xe = x2-x1; ye = y2-y1; if ( xe!=0 ) yl = (ye<<FLOATNS) / xe; else yl = y1; return (( yl * (x - x1 ))>>FLOATNS)+y1; } //¿µ¿ª¿¡ ÇØ´çÇÏ´Â ÆäÀ̽º¸¦ °Ë»çÇÏ¿© ³ôÀ̸¦ ±¸ÇÑ´Ù int smSTAGE3D::GetAreaHeight( int ax, int az , int x, int z ) { int he,height; int num, fnum; int cnt; smSTAGE_FACE *face; int CalcSum; int lx,lz; lx = ax&0xFF; lz = az&0xFF; CalcSum = CalcSumCount; height = -200*fONE; if ( StageArea[lx][lz] ) { //¿µ¿ª num = StageArea[lx][lz][0]; //¿µ¿ª¿¡ Æ÷ÇÔµÈ ÆäÀ̽º ¼ö for( cnt=1;cnt<num+1;cnt++ ) { fnum = StageArea[lx][lz][cnt]; face = &Face[ fnum ]; if ( face->CalcSum!=CalcSum && smMaterial[ face->Vertex[3] ].MeshState & SMMAT_STAT_CHECK_FACE ) { face->CalcSum = CalcSum; he = GetPolyHeight( face , x, z ); if ( he!=CLIP_OUT && he>height ) height = he; } } } return height; } //¿µ¿ª¿¡ ÇØ´çÇÏ´Â ÆäÀ̽º¸¦ °Ë»çÇÏ¿© ³ôÀ̸¦ ±¸ÇÑ´Ù ( ¹ÝÅõ¸í °ªµµ À¯È¿ ó¸® ) int smSTAGE3D::GetAreaHeight2( int ax, int az , int x, int z ) { int he,height; int num, fnum; int cnt; smSTAGE_FACE *face; int CalcSum; int lx,lz; lx = ax&0xFF; lz = az&0xFF; CalcSum = CalcSumCount; height = -200*fONE; if ( StageArea[lx][lz] ) { //¿µ¿ª num = StageArea[lx][lz][0]; //¿µ¿ª¿¡ Æ÷ÇÔµÈ ÆäÀ̽º ¼ö for( cnt=1;cnt<num+1;cnt++ ) { fnum = StageArea[lx][lz][cnt]; face = &Face[ fnum ]; //if ( face->CalcSum!=CalcSum && // ( smMaterial[ face->Vertex[3] ].MeshState & SMMAT_STAT_CHECK_FACE || smMaterial[ face->Vertex[3] ].Transparency!=0 ) ) { if ( face->CalcSum!=CalcSum ) { face->CalcSum = CalcSum; he = GetPolyHeight( face , x, z ); if ( he!=CLIP_OUT && he>height ) height = he; } } } return height; } //ÆäÀ̽º¿¡ ÇØ´çÇÏ´Â ³ôÀ̸¦ ±¸ÇÑ´Ù int smSTAGE3D::GetHeight( int x, int z ) { int lx,lz; int height = 0; if ( !Head ) return 0; lx = x >> (6+FLOATNS); lz = z >> (6+FLOATNS); height = GetAreaHeight( lx,lz , x, z ); CalcSumCount ++; return height; } //ÆäÀ̽º¿¡ ÇØ´çÇÏ´Â ³ôÀ̸¦ ±¸ÇÑ´Ù int smSTAGE3D::GetHeight2( int x, int z ) { int lx,lz; int height = 0; if ( !Head ) return 0; lx = x >> (6+FLOATNS); lz = z >> (6+FLOATNS); height = GetAreaHeight2( lx,lz , x, z ); CalcSumCount ++; return height; } //À̵¿ÇÒ À§Ä¡ÀÇ Àå¾Ö¹°À» °Ë»çÇÑ´Ù int smSTAGE3D::CheckSolid( int sx, int sy, int sz , int dx, int dy, int dz ) { int num, fnum; int cnt; smSTAGE_FACE *face; int CalcSum; int lx,lz; POINT3D p1,p2,p3,sp,dp; sp.x=sx; sp.y=sy; sp.z=sz; dp.x=dx; dp.y=dy; dp.z=dz; CalcSum = CalcSumCount; lx = dx >> (6+FLOATNS); lz = dz >> (6+FLOATNS); lx &= 0xFF; lz &= 0xFF; if ( StageArea[lx][lz] ) { //¿µ¿ª num = StageArea[lx][lz][0]; //¿µ¿ª¿¡ Æ÷ÇÔµÈ ÆäÀ̽º ¼ö for( cnt=1;cnt<num+1;cnt++ ) { fnum = StageArea[lx][lz][cnt]; face = &Face[ fnum ]; if ( face->CalcSum!=CalcSum && smMaterial[ face->Vertex[3] ].MeshState & SMMAT_STAT_CHECK_FACE ) { face->CalcSum = CalcSum; p1.x = Vertex[ face->Vertex[0] ].x; p1.y = Vertex[ face->Vertex[0] ].y; p1.z = Vertex[ face->Vertex[0] ].z; p2.x = Vertex[ face->Vertex[1] ].x; p2.y = Vertex[ face->Vertex[1] ].y; p2.z = Vertex[ face->Vertex[1] ].z; p3.x = Vertex[ face->Vertex[2] ].x; p3.y = Vertex[ face->Vertex[2] ].y; p3.z = Vertex[ face->Vertex[2] ].z; if ( smGetTriangleImact( &p1,&p2,&p3,&sp,&dp )==TRUE ) { CalcSumCount ++; return TRUE; } } } } lx = sx >> (6+FLOATNS); lz = sz >> (6+FLOATNS); lx &= 0xFF; lz &= 0xFF; if ( StageArea[lx][lz] ) { //¿µ¿ª num = StageArea[lx][lz][0]; //¿µ¿ª¿¡ Æ÷ÇÔµÈ ÆäÀ̽º ¼ö for( cnt=1;cnt<num+1;cnt++ ) { fnum = StageArea[lx][lz][cnt]; face = &Face[ fnum ]; if ( face->CalcSum!=CalcSum && smMaterial[ face->Vertex[3] ].MeshState & SMMAT_STAT_CHECK_FACE ) { face->CalcSum = CalcSum; p1.x = Vertex[ face->Vertex[0] ].x; p1.y = Vertex[ face->Vertex[0] ].y; p1.z = Vertex[ face->Vertex[0] ].z; p2.x = Vertex[ face->Vertex[1] ].x; p2.y = Vertex[ face->Vertex[1] ].y; p2.z = Vertex[ face->Vertex[1] ].z; p3.x = Vertex[ face->Vertex[2] ].x; p3.y = Vertex[ face->Vertex[2] ].y; p3.z = Vertex[ face->Vertex[2] ].z; if ( smGetTriangleImact( &p1,&p2,&p3,&sp,&dp )==TRUE ) { CalcSumCount ++; return TRUE; } } } } CalcSumCount ++; return FALSE; } // StageArea¸¦ 0 À¸·Î ÃʱâÈ­ void smSTAGE3D::clearStageArea() { int x,y; for(y=0;y<MAP_SIZE;y++) { for(x=0;x<MAP_SIZE;x++) { StageArea[x][y] = 0; } } } // »ï°¢ÆäÀ̽º°¡ À§Ä¡ÇÑ ±¸¿ª(64x64) À» ±¸ÇÏ¿© AreaList ¿¡ ¼³Á¤ int smSTAGE3D::getPolyAreas( POINT3D *ip1 , POINT3D *ip2, POINT3D *ip3 ) { POINT3D p1, p2 , p3; POINT3D *p[3]; int cnt; int left , right , top , bottom; int cntX,cntY; memcpy( &p1, ip1 , sizeof( POINT3D ) ); memcpy( &p2, ip2 , sizeof( POINT3D ) ); memcpy( &p3, ip3 , sizeof( POINT3D ) ); p[0] = &p1; p[1] = &p2; p[2] = &p3; left = p[0]->x; right = p[0]->x; top = p[0]->z; bottom = p[0]->z; for( cnt=1; cnt<3; cnt++ ) { if ( p[cnt]->x < left ) left = p[cnt]->x; if ( p[cnt]->x > right ) right = p[cnt]->x; if ( p[cnt]->z < top ) top = p[cnt]->z; if ( p[cnt]->z > bottom ) bottom = p[cnt]->z; } left >>=6; right >>=6; top >>=6; bottom>>=6; right++; bottom++; AreaListCnt = 0; for( cntX=left; cntX<right; cntX++ ) { for( cntY=top; cntY<bottom; cntY++ ) { AreaList[ AreaListCnt ].x = cntX & 0xFF ; // AreaList[ AreaListCnt ].y = cntY & 0xFF ; // AreaListCnt ++; } } return TRUE; } //°¢ Æú¸®°ïÀÌ À§Ä¡ÇÑ ¿µ¿ª Á¤º¸¸¦ ¸¸µé¾î ÀúÀåÇÑ´Ù int smSTAGE3D::SetupPolyAreas() { POINT3D p[3]; int cnt,cnt2; int num; // ±¸¿ª ¹è¿­ ¿µ¿ªÀÇ ¸ðµç °ªÀ» 0 À¸·Î ÃʱâÈ­ clearStageArea(); AreaList = new POINT [ 4096 ]; // ¸ðµç Face¸¦ °Ë»çÇÏ¿© Â÷ÁöÇÏ´Â °ø°£ ±¸¿ªÀ» È®ÀÎÇÏ¿© ±¸¿ª ¹è¿­ ¿µ¿ª¿¡ ÇÒ´çµÉ °ø°£À» ±¸ÇÑ´Ù for(int cnt=0;cnt<nFace;cnt++ ) { for(cnt2=0;cnt2<3;cnt2++) { p[cnt2].x = Vertex[ Face[cnt].Vertex[cnt2] ].x>>FLOATNS; p[cnt2].y = Vertex[ Face[cnt].Vertex[cnt2] ].y>>FLOATNS; p[cnt2].z = Vertex[ Face[cnt].Vertex[cnt2] ].z>>FLOATNS; } getPolyAreas( &p[0] , &p[1], &p[2] ); //ÀÏ´Ü StageArea¿¡ ÀúÀåµÉ ÆäÀ̽º ¼ö¸¦ ÀúÀå if ( AreaListCnt>0 ) { for( cnt2=0;cnt2<AreaListCnt;cnt2++ ) { StageArea[ AreaList[cnt2].x ][ AreaList[cnt2].y]++; } } } delete AreaList; // lpwAreaBuff = 0; int wbCnt; wbCnt = 0; // ±¸¿ª ¿µ¿ª¿¡ ÇÊ¿äÇÑ °ø°£ È®º¸ for( cnt2=0;cnt2<MAP_SIZE;cnt2++) { for(int cnt=0;cnt<MAP_SIZE;cnt++ ) { num = (int)StageArea[ cnt ][ cnt2 ]; //°è»êµÈ ÆäÀ̽º ¼öÆÇÅ­ ¹öÆÛ¸¦ ÀâÀ½ if ( num>0 ) { wbCnt += num+1; } } } wAreaSize = wbCnt; lpwAreaBuff = new WORD[ wbCnt ]; wbCnt = 0; // ±¸¿ª ¿µ¿ª¿¡ ÇÊ¿äÇÑ °ø°£ È®º¸ for( cnt2=0;cnt2<MAP_SIZE;cnt2++) { for(int cnt=0;cnt<MAP_SIZE;cnt++ ) { num = (int)StageArea[ cnt ][ cnt2 ]; //°è»êµÈ ÆäÀ̽º ¼öÆÇÅ­ ¹öÆÛ¸¦ ÀâÀ½ if ( num>0 ) { StageArea[cnt][cnt2] = &lpwAreaBuff[wbCnt]; StageArea[cnt][cnt2][0] = 0; wbCnt += num+1; } } } /* // ±¸¿ª ¿µ¿ª¿¡ ÇÊ¿äÇÑ °ø°£ È®º¸ for( cnt2=0;cnt2<MAP_SIZE;cnt2++) { for(int cnt=0;cnt<MAP_SIZE;cnt++ ) { num = (int)StageArea[ cnt ][ cnt2 ]; //°è»êµÈ ÆäÀ̽º ¼öÆÇÅ­ ¹öÆÛ¸¦ ÀâÀ½ if ( num>0 ) { num/=sizeof( WORD ); StageArea[cnt][cnt2] = new WORD[ num+1 ]; if ( StageArea[cnt][cnt2] ) StageArea[cnt][cnt2][0] = 0; // ¹è¿­ÀÇ[0]Àº Æ÷ÇÔÇÏ´Â Æú¸®°ï °¹¼ö else StageArea[cnt][cnt2] = 0; // ¹è¿­ÀÇ[0]Àº Æ÷ÇÔÇÏ´Â Æú¸®°ï °¹¼ö } } } */ AreaList = new POINT [ 4096 ]; // ´Ù½Ã Face¸¦ °Ë»çÇϰí È®º¸µÈ ¿µ¿ª¿¡ °ªÀ» ¼³Á¤ for(int cnt=0;cnt<nFace;cnt++ ) { for(cnt2=0;cnt2<3;cnt2++) { p[cnt2].x = Vertex[ Face[cnt].Vertex[cnt2] ].x>>FLOATNS; p[cnt2].y = Vertex[ Face[cnt].Vertex[cnt2] ].y>>FLOATNS; p[cnt2].z = Vertex[ Face[cnt].Vertex[cnt2] ].z>>FLOATNS; } getPolyAreas( &p[0] , &p[1], &p[2] ); if ( AreaListCnt>0 ) { for( cnt2=0;cnt2<AreaListCnt;cnt2++ ) { StageArea[ AreaList[cnt2].x ][ AreaList[cnt2].y ][0]++; num = StageArea[ AreaList[cnt2].x ][ AreaList[cnt2].y ][0]; StageArea[ AreaList[cnt2].x ][ AreaList[cnt2].y ][ num ] = cnt; } } } delete AreaList; return TRUE; } // ·»´õ¸µÀ» À§ÇÑ ¿¬»ê°ú Á¤·Ä int smSTAGE3D::RenderGeom() { int cnt; int x1,x2; int t; int h,w; int num; int fnum; smSTAGE_FACE *face; int clipW,clipH; smRENDFACE *rendface; int k=0; if ( smMaterialGroup ) smRender.SetMaterialGroup( smMaterialGroup ); //·»´õ¸µ¿ë Àӽà ¹öÆÛ ÃʱâÈ­ ( ¹öÅØ½º Æ÷ÀÎÅÍ ¾Ë·ÁÁÜ ) smRender.InitStageMesh ( Vertex , SumCount ); for( h=MapPosiTop; h<MapPosiBot ; h++ ) { x1 = MapPosiLeft[ h&0xFF ]; x2 = MapPosiRight[ h&0xFF ]; if ( x1>x2 ) { t=x1; x1=x2 ; x2=t; } // x1<->x2 ¹Ù²Þ clipH = h&0xFF; for( w=x1; w<x2 ; w++ ) { clipW = w&0xFF; if ( StageArea[clipW][clipH] ) { //·»´õ¸µ µÉ ¿µ¿ª num = StageArea[clipW][clipH][0]; //¿µ¿ª¿¡ Æ÷ÇÔµÈ ÆäÀ̽º ¼ö for( cnt=1;cnt<num+1;cnt++ ) { fnum = StageArea[clipW][clipH][cnt]; face = &Face[ fnum ]; // if ( face->sum != SumCount && CheckFace!=face ) { if ( face->sum != SumCount ) { //&& (smMaterial[Face[ fnum ].Vertex[3]].UseState&Display sMATS_SCRIPT_NOTVIEW) ) { rendface = smRender.AddStageFace( face ); // ·»´õ¸µ ÆäÀ̽º·Î Ãß°¡ } k++; } } } } smRender.ClipRendFace(); // Àüü ·»´õ¸µ ÆäÀ̽º¸¦ Ŭ¸®ÇÎ smRender.GeomVertex2D(); // ¹öÅØ½º¸¦ 2DÁÂÇ¥·Î º¯È¯ return TRUE; } #define STAGE_RECT_LIMIT (30*64*fONE) #define STAGE_RECT_LIMIT2 (240*64*fONE) int smSTAGE3D::DrawStage(int x , int y, int z, int angX, int angY, int angZ , smEMATRIX *eRotMatrix ) { if ( !Head ) return 0; SumCount++; //±×¸±¼ö ÀÖ´Â Áö¿ªÀ» ¹þ¾î³­ °æ¿ì Ãâ·Â ÇÏÁö ¾ÊÀ½ if ( z<(StageMapRect.top-STAGE_RECT_LIMIT) ) return FALSE; if ( z>(StageMapRect.bottom+STAGE_RECT_LIMIT) ) return FALSE; if ( x<(StageMapRect.left-STAGE_RECT_LIMIT) ) return FALSE; if ( x>(StageMapRect.right+STAGE_RECT_LIMIT) ) return FALSE; CameraX = x>>FLOATNS; CameraY = y>>FLOATNS; CameraZ = z>>FLOATNS; CameraY -= 1500; if (CameraY<400) CameraY=400; CameraAngX = GetRadian( angX ); CameraAngY = GetRadian( angY ); CameraAngZ = GetRadian( angZ ); //###################################################################################### //ÀÛ ¼º ÀÚ : ¿À ¿µ ¼® if( CameraAngX > ANGLE_90 ) CameraAngX = ANGLE_360-CameraAngX; //###################################################################################### SetViewLength(); SetViewRadian(); if ( MakeMapTable() ) { if ( eRotMatrix ) smRender.SetCameraPosi( x, y, z, eRotMatrix ); else smRender.SetCameraPosi( x, y, z, angX, angY, angZ ); CameraAngX = GetRadian( angX ); CameraAngY = GetRadian( angY ); CameraAngZ = GetRadian( angZ ); /* int cnt,dx,dy,dz,dist; for(cnt=0;cnt<nLight;cnt++) { dx = (x-smLight[cnt].x)>>FLOATNS; dy = (y-smLight[cnt].y)>>FLOATNS; dz = (z-smLight[cnt].z)>>FLOATNS; dist = dx*dx+dy*dy+dz*dz; if ( dist<0x300000 ) { smRender.AddDynamicLight( smLight[cnt].x,smLight[cnt].y,smLight[cnt].z, smLight[cnt].r,smLight[cnt].g,smLight[cnt].b, 0 , smLight[cnt].Range ); } } */ RenderGeom(); // smRender D3D·»´õ¸µ smRender.RenderD3D(); StageObject->Draw( x, y, z, angX, angY, angZ ); } return FALSE; } int smSTAGE3D::DrawStage2(int x , int y, int z, int angX, int angY, int angZ , smEMATRIX *eRotMatrix ) { if ( !Head ) return 0; SumCount++; //±×¸±¼ö ÀÖ´Â Áö¿ªÀ» ¹þ¾î³­ °æ¿ì Ãâ·Â ÇÏÁö ¾ÊÀ½ if ( z<(StageMapRect.top-STAGE_RECT_LIMIT) ) return FALSE; if ( z>(StageMapRect.bottom+STAGE_RECT_LIMIT) ) return FALSE; if ( x<(StageMapRect.left-STAGE_RECT_LIMIT) ) return FALSE; if ( x>(StageMapRect.right+STAGE_RECT_LIMIT) ) return FALSE; if ( z<(StageMapRect.bottom-STAGE_RECT_LIMIT2) ) return FALSE; if ( z>(StageMapRect.top+STAGE_RECT_LIMIT2) ) return FALSE; if ( x<(StageMapRect.right-STAGE_RECT_LIMIT2) ) return FALSE; if ( x>(StageMapRect.left+STAGE_RECT_LIMIT2) ) return FALSE; CameraX = x>>FLOATNS; CameraY = y>>FLOATNS; CameraZ = z>>FLOATNS; CameraY -= 1500; if (CameraY<400) CameraY=400; CameraAngX = GetRadian( angX ); CameraAngY = GetRadian( angY ); CameraAngZ = GetRadian( angZ ); //###################################################################################### //ÀÛ ¼º ÀÚ : ¿À ¿µ ¼® if( CameraAngX > ANGLE_90 ) CameraAngX = ANGLE_360-CameraAngX; //###################################################################################### SetViewLength(); SetViewRadian(); if ( MakeMapTable() ) { if ( eRotMatrix ) smRender.SetCameraPosi( x, y, z, eRotMatrix ); else smRender.SetCameraPosi( x, y, z, angX, angY, angZ ); CameraAngX = GetRadian( angX ); CameraAngY = GetRadian( angY ); CameraAngZ = GetRadian( angZ ); RenderGeom(); // smRender D3D·»´õ¸µ smRender.RenderD3D(); return TRUE; } return FALSE; } //###################################################################################### //ÀÛ ¼º ÀÚ : ¿À ¿µ ¼® int smSTAGE3D::DrawOpeningStage(int x, int y, int z, int angX, int angY, int angZ, int FrameStep ) { if ( !Head ) return 0; SumCount++; //±×¸±¼ö ÀÖ´Â Áö¿ªÀ» ¹þ¾î³­ °æ¿ì Ãâ·Â ÇÏÁö ¾ÊÀ½ if ( z<(StageMapRect.top-STAGE_RECT_LIMIT) ) return FALSE; if ( z>(StageMapRect.bottom+STAGE_RECT_LIMIT) ) return FALSE; if ( x<(StageMapRect.left-STAGE_RECT_LIMIT) ) return FALSE; if ( x>(StageMapRect.right+STAGE_RECT_LIMIT) ) return FALSE; CameraX = x>>FLOATNS; CameraY = y>>FLOATNS; CameraZ = z>>FLOATNS; CameraY -= 1500; if (CameraY<400) CameraY=400; CameraAngX = GetRadian( angX ); CameraAngY = GetRadian( angY ); CameraAngZ = GetRadian( angZ ); if( CameraAngX > ANGLE_90 ) CameraAngX = ANGLE_360-CameraAngX; SetViewLength(); SetViewRadian(); if ( MakeMapTable() ) { smRender.SetCameraPosi( x, y, z, angX, angY, angZ ); CameraAngX = GetRadian( angX ); CameraAngY = GetRadian( angY ); CameraAngZ = GetRadian( angZ ); RenderGeom(); // smRender D3D·»´õ¸µ smRender.RenderD3D(); StageObject->DrawOpening( x, y, z, angX, angY, angZ, FrameStep ); } return FALSE; } //###################################################################################### static char *szSMDFileHeader = "SMD Stage data Ver 0.72"; //µ¥ÀÌŸ¸¦ ÆÄÀÏ·Î ÀúÀå int smSTAGE3D::SaveFile( char *szFile ) { HANDLE hFile; DWORD dwAcess; int cnt,cnt2,slen; int pFile; // int size; smDFILE_HEADER FileHeader; lstrcpy( FileHeader.szHeader , szSMDFileHeader ); Head = FALSE; //Çì´õ Á¦ÀÛ if ( smMaterialGroup ) FileHeader.MatCounter = smMaterialGroup->MaterialCount; else FileHeader.MatCounter = 0; //ÆÄÀÏ Æ÷ÀÎÅÍ pFile = sizeof( smDFILE_HEADER );// + sizeof( smPAT3D ); FileHeader.MatFilePoint = pFile; //¸ÞÆ®¸®¾ó µ¥ÀÌŸ ÀúÀå Å©±â if ( smMaterialGroup ) pFile+= smMaterialGroup->GetSaveSize(); FileHeader.First_ObjInfoPoint = pFile; //ÆÄÀÏ·Î ÀúÀå hFile = CreateFile( szFile , GENERIC_WRITE , FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, OPEN_ALWAYS , FILE_ATTRIBUTE_NORMAL , NULL ); if ( hFile == INVALID_HANDLE_VALUE ) return FALSE; //Çì´õ ÀúÀå WriteFile( hFile , &FileHeader , sizeof( smDFILE_HEADER ) , &dwAcess , NULL ); //ÇöÀç Ŭ·¡½ºÀÇ µ¥ÀÌŸ ÀúÀå WriteFile( hFile , &Head , sizeof( smSTAGE3D ) , &dwAcess , NULL ); //¸ÞÆ®¸®¾ó µ¥ÀÌŸ ÀúÀå if ( smMaterialGroup ) smMaterialGroup->SaveFile( hFile ); // °¢ ¸Þ½Ã µ¥ÀÌŸ¸¦ ÀúÀå WriteFile( hFile , Vertex , sizeof( smSTAGE_VERTEX )* nVertex , &dwAcess , NULL ); WriteFile( hFile , Face , sizeof( smSTAGE_FACE )* nFace , &dwAcess , NULL ); WriteFile( hFile , TexLink , sizeof( smTEXLINK ) * nTexLink , &dwAcess , NULL ); if ( nLight>0 ) WriteFile( hFile , smLight , sizeof( smLIGHT3D ) * nLight , &dwAcess , NULL ); // ±¸¿ª ¿µ¿ªÀÇ µ¥ÀÌŸ¸¦ ÀúÀå for( cnt2=0;cnt2<MAP_SIZE;cnt2++) { for(int cnt=0;cnt<MAP_SIZE;cnt++ ) { if (StageArea[ cnt ][ cnt2 ]) { slen = (StageArea[cnt][cnt2][0]+1) ; WriteFile( hFile , &slen , sizeof(int) , &dwAcess , NULL ); WriteFile( hFile , StageArea[cnt][cnt2] , slen * sizeof( WORD ), &dwAcess , NULL ); } } } //ÇÚµé ´Ý±¸ Á¾·á CloseHandle( hFile ); return TRUE; } //ÆÄÀÏ¿¡¼­ µ¥ÀÌŸ¸¦ ·Îµå int smSTAGE3D::LoadFile( char *szFile ) { HANDLE hFile; DWORD dwAcess; int cnt,cnt2; int size; int slen; int wbCnt; smTEXLINK *lpOldTexLink; int SubTexLink; smDFILE_HEADER FileHeader; hFile = CreateFile( szFile , GENERIC_READ , FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, OPEN_EXISTING , FILE_ATTRIBUTE_NORMAL , NULL ); //Çì´õÀÇ ³»¿ëÀ» Àоî¿È size=ReadFile( hFile , &FileHeader , sizeof( smDFILE_HEADER ) , &dwAcess , NULL ); //Çì´õ°¡ Ʋ¸² ( ¹öÀüÀÌ Æ²¸®°Å³ª.. ) if ( lstrcmp( FileHeader.szHeader , szSMDFileHeader )!=0 ) { //ÇÚµé ´Ý±¸ Á¾·á CloseHandle( hFile ); return FALSE; } //Ŭ·¡½ºÀÇ ³»¿ëÀ» ÀÐÀ½ ReadFile( hFile , &Head , sizeof( smSTAGE3D ) , &dwAcess , NULL ); lpOldTexLink = TexLink; //¸ÞÆ®¸®¾ó Àоî¿È if ( FileHeader.MatCounter ) { smMaterialGroup = new smMATERIAL_GROUP; smMaterialGroup->LoadFile( hFile ); smMaterial = smMaterialGroup->smMaterial; } //»õ·Î¿î ¸Þ¸ð¸® ºí·° ÇÒ´ç Vertex = new smSTAGE_VERTEX[ nVertex ]; ReadFile( hFile , Vertex , sizeof( smSTAGE_VERTEX ) * nVertex , &dwAcess , NULL ); Face = new smSTAGE_FACE[ nFace ]; ReadFile( hFile , Face , sizeof( smSTAGE_FACE ) * nFace , &dwAcess , NULL ); TexLink = new smTEXLINK[ nTexLink ]; ReadFile( hFile , TexLink , sizeof( smTEXLINK ) * nTexLink , &dwAcess , NULL ); if ( nLight>0 ) { smLight = new smLIGHT3D[nLight]; ReadFile( hFile , smLight , sizeof( smLIGHT3D ) * nLight , &dwAcess , NULL ); } //ÅØ½ºÃÄ ÁÂÇ¥°¡ ¾îµå·¹½º Æ÷ÀÎÅÍ·Î µÇ ÀÖÀ¸¹Ç·Î »õ·Î º¸Á¤ÇÔ SubTexLink = TexLink-lpOldTexLink; for(int cnt=0;cnt<nTexLink;cnt++) { if ( TexLink[cnt].NextTex ) { SubTexLink = TexLink[cnt].NextTex-lpOldTexLink; TexLink[cnt].NextTex = TexLink + SubTexLink; } } for(int cnt=0;cnt<nFace;cnt++) { if ( Face[cnt].lpTexLink ) { SubTexLink = Face[cnt].lpTexLink-lpOldTexLink; Face[cnt].lpTexLink = TexLink + SubTexLink; } } StageObject = new smSTAGE_OBJECT; lpwAreaBuff = new WORD[ wAreaSize ]; wbCnt = 0; // ±¸¿ª ¿µ¿ªÀÇ µ¥ÀÌŸ¸¦ ÀÐÀ½ for( cnt2=0;cnt2<MAP_SIZE;cnt2++) { for(int cnt=0;cnt<MAP_SIZE;cnt++ ) { if (StageArea[ cnt ][ cnt2 ]) { ReadFile( hFile , &slen , sizeof(int) , &dwAcess , NULL ); StageArea[cnt][cnt2] = &lpwAreaBuff[ wbCnt ]; ReadFile( hFile , StageArea[cnt][cnt2] , slen*sizeof(WORD) , &dwAcess , NULL ); wbCnt += slen; } } } //ÇÚµé ´Ý±¸ Á¾·á CloseHandle( hFile ); CalcSumCount++; return TRUE; }
rafaellincoln/Source-Priston-Tale
J_Server/smLib3d/smStage3d.cpp
C++
mit
55,585
package io.reactivesw.order.order.infrastructure.enums; /** * Created by Davis on 16/11/17. */ public enum OrderState { /** * Open order state. */ Open, /** * Confirmed order state. */ Confirmed, /** * Complete order state. */ Complete, /** * Cancelled order state. */ Cancelled; }
reactivesw/customer_server
src/main/java/io/reactivesw/order/order/infrastructure/enums/OrderState.java
Java
mit
327
<?php namespace Ibw\MagSoftBundle\Entity; use Doctrine\ORM\EntityRepository; /** * ProiecteRepository * * This class was generated by the Doctrine ORM. Add your own custom * repository methods below. */ class ProiecteRepository extends EntityRepository { public function getLastProiectGeneratId() { $qb = $this->createQueryBuilder('j') ->select('max(j.nrProiectGenerat)'); return $qb->getQuery()->getSingleScalarResult(); } public function getLastDosarDefinitivId() { $qb = $this->createQueryBuilder('j') ->select('max(j.nrDosarDefinitiv)'); return $qb->getQuery()->getSingleScalarResult(); } public function getLastProiectId() { $qb = $this->createQueryBuilder('j') ->select('max(j.id)'); return $qb->getQuery()->getResult(); } public function getRaportLucrari($partener = 0, $dateFrom = null, $dateTo = null) { $qb = $this->getEntityManager()->createQueryBuilder(); $qb->select('p, c, pt') ->from('IbwMagSoftBundle:Proiecte', 'p') ->innerJoin('p.clienti', 'c') ->innerJoin('c.parteneri', 'pt'); if ($partener != 0) { $qb->andwhere('pt.id= :partener') ->setParameter('partener', $partener); } if ($dateFrom != new \DateTime() && $dateTo != new \DateTime()) { $qb->andwhere('p.dataCerereAcordAcces BETWEEN :fromDate and :toDate') ->setParameter('fromDate', $dateFrom) ->setParameter('toDate', $dateTo); } return $qb->getQuery()->getResult(); } public function getRaportProiecte($partener = 0, $dateFrom = null, $dateTo = null) { $qb = $this->getEntityManager()->createQueryBuilder(); $qb->select('p, c, pt, pr') ->from('IbwMagSoftBundle:Proiecte', 'p') ->innerJoin('p.clienti', 'c') ->innerJoin('c.parteneri', 'pt') ->innerJoin('p.pret', 'pr'); if ($partener != 0) { $qb->andwhere('pt.id= :partener') ->setParameter('partener', $partener); } if ($dateFrom != new \DateTime() && $dateTo != new \DateTime()) { $qb->andwhere('p.dataCerereAcordAcces BETWEEN :fromDate and :toDate') ->setParameter('fromDate', $dateFrom) ->setParameter('toDate', $dateTo); } return $qb->getQuery()->getResult(); } public function getSumPret() { $qb = $this->getEntityManager()->createQueryBuilder(); $qb->select('sum(p.pret)') ->from('IbwMagSoftBundle:Proiecte', 'p'); return $qb->getQuery()->getSingleScalarResult(); } public function getProiectPriceByPartener() { $qb = $this->getEntityManager()->createQueryBuilder(); $qb->select('p.valoarePret') ->from('IbwMagSoftBundle:Pret', 'p') ->where('p.parteneri = :partener') ->setParameter('partener', 'numePartener1'); return $qb->getQuery()->getArrayResult(); } }
annonnim/magsoft
src/Ibw/MagSoftBundle/Entity/ProiecteRepository.php
PHP
mit
3,167
package org.adaptlab.chpir.android.survey.utils; import org.adaptlab.chpir.android.survey.models.DeviceUser; public class AuthUtils { private static DeviceUser sCurrentUser = null; public static boolean isSignedIn() { return sCurrentUser != null; } public static void signOut() { sCurrentUser = null; } public static void signIn(DeviceUser deviceUser) { sCurrentUser = deviceUser; } public static DeviceUser getCurrentUser() { return sCurrentUser; } }
DukeMobileTech/AndroidSurvey
app/src/main/java/org/adaptlab/chpir/android/survey/utils/AuthUtils.java
Java
mit
543
using System; namespace SDNUMobile.SDK.Entity.Bathroom { /// <summary> /// 浴室使用用量实体 /// </summary> public class BathroomUsageAmount { #region 字段 private DateTime _logTime; private Int32[] _amount; #endregion #region 属性 /// <summary> /// 获取或设置记录时间 /// </summary> public DateTime LogTime { get { return this._logTime; } set { this._logTime = value; } } /// <summary> /// 获取或设置使用数量 /// </summary> public Int32[] Amount { get { return this._amount; } set { this._amount = value; } } #endregion } }
isdnu/DotNetSDK
SDNUMobile.SDK/Entity/Bathroom/BathroomUsageAmount.cs
C#
mit
809