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 |
|---|---|---|---|---|---|
using System;
using System.Collections.Generic;
using System.Text;
using System.Diagnostics;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Input;
using Anarian.Interfaces;
using Anarian.Events;
namespace Anarian.DataStructures.Input
{
public class Controller : IUpdatable
{
PlayerIndex m_playerIndex;
GamePadType m_gamePadType;
GamePadCapabilities m_gamePadCapabilities;
GamePadState m_gamePadState;
GamePadState m_prevGamePadState;
bool m_isConnected;
public PlayerIndex PlayerIndex { get { return m_playerIndex; } }
public GamePadType GamePadType { get { return m_gamePadType; } }
public GamePadCapabilities GamePadCapabilities { get { return m_gamePadCapabilities; } }
public GamePadState GamePadState { get { return m_gamePadState; } }
public GamePadState PrevGamePadState { get { return m_prevGamePadState; } }
public bool IsConnected { get { return m_isConnected; } }
public Controller(PlayerIndex playerIndex)
{
m_playerIndex = playerIndex;
Reset();
}
public void Reset()
{
m_gamePadCapabilities = GamePad.GetCapabilities(m_playerIndex);
m_gamePadType = m_gamePadCapabilities.GamePadType;
m_gamePadState = GamePad.GetState(m_playerIndex);
m_prevGamePadState = m_gamePadState;
m_isConnected = m_gamePadState.IsConnected;
}
#region Interface Implimentations
void IUpdatable.Update(GameTime gameTime) { Update(gameTime); }
#endregion
public void Update(GameTime gameTime)
{
//if (!m_isConnected) return;
// Get the States
m_prevGamePadState = m_gamePadState;
m_gamePadState = GamePad.GetState(m_playerIndex);
// Update if it is connected or not
m_isConnected = m_gamePadState.IsConnected;
#region Preform Events
if (GamePadDown != null) {
if (IsButtonDown(Buttons.A)) { GamePadClicked(this, new GamePadPressedEventArgs(gameTime, Buttons.A, PlayerIndex)); }
if (IsButtonDown(Buttons.B)) { GamePadClicked(this, new GamePadPressedEventArgs(gameTime, Buttons.B, PlayerIndex)); }
if (IsButtonDown(Buttons.X)) { GamePadClicked(this, new GamePadPressedEventArgs(gameTime, Buttons.X, PlayerIndex)); }
if (IsButtonDown(Buttons.Y)) { GamePadClicked(this, new GamePadPressedEventArgs(gameTime, Buttons.Y, PlayerIndex)); }
if (IsButtonDown(Buttons.LeftShoulder)) { GamePadClicked(this, new GamePadPressedEventArgs(gameTime, Buttons.LeftShoulder, PlayerIndex)); }
if (IsButtonDown(Buttons.RightShoulder)) { GamePadClicked(this, new GamePadPressedEventArgs(gameTime, Buttons.RightShoulder, PlayerIndex)); }
if (IsButtonDown(Buttons.LeftStick)) { GamePadClicked(this, new GamePadPressedEventArgs(gameTime, Buttons.LeftStick, PlayerIndex)); }
if (IsButtonDown(Buttons.RightStick)) { GamePadClicked(this, new GamePadPressedEventArgs(gameTime, Buttons.RightStick, PlayerIndex)); }
if (IsButtonDown(Buttons.DPadUp)) { GamePadClicked(this, new GamePadPressedEventArgs(gameTime, Buttons.DPadUp, PlayerIndex)); }
if (IsButtonDown(Buttons.DPadDown)) { GamePadClicked(this, new GamePadPressedEventArgs(gameTime, Buttons.DPadDown, PlayerIndex)); }
if (IsButtonDown(Buttons.DPadLeft)) { GamePadClicked(this, new GamePadPressedEventArgs(gameTime, Buttons.DPadLeft, PlayerIndex)); }
if (IsButtonDown(Buttons.DPadRight)) { GamePadClicked(this, new GamePadPressedEventArgs(gameTime, Buttons.DPadRight, PlayerIndex)); }
}
if (GamePadClicked != null) {
if (ButtonPressed(Buttons.A)) { GamePadClicked(this, new GamePadPressedEventArgs(gameTime, Buttons.A, PlayerIndex)); }
if (ButtonPressed(Buttons.B)) { GamePadClicked(this, new GamePadPressedEventArgs(gameTime, Buttons.B, PlayerIndex)); }
if (ButtonPressed(Buttons.X)) { GamePadClicked(this, new GamePadPressedEventArgs(gameTime, Buttons.X, PlayerIndex)); }
if (ButtonPressed(Buttons.Y)) { GamePadClicked(this, new GamePadPressedEventArgs(gameTime, Buttons.Y, PlayerIndex)); }
if (ButtonPressed(Buttons.LeftShoulder)) { GamePadClicked(this, new GamePadPressedEventArgs(gameTime, Buttons.LeftShoulder, PlayerIndex)); }
if (ButtonPressed(Buttons.RightShoulder)) { GamePadClicked(this, new GamePadPressedEventArgs(gameTime, Buttons.RightShoulder, PlayerIndex)); }
if (ButtonPressed(Buttons.LeftStick)) { GamePadClicked(this, new GamePadPressedEventArgs(gameTime, Buttons.LeftStick, PlayerIndex)); }
if (ButtonPressed(Buttons.RightStick)) { GamePadClicked(this, new GamePadPressedEventArgs(gameTime, Buttons.RightStick, PlayerIndex)); }
if (ButtonPressed(Buttons.DPadUp)) { GamePadClicked(this, new GamePadPressedEventArgs(gameTime, Buttons.DPadUp, PlayerIndex)); }
if (ButtonPressed(Buttons.DPadDown)) { GamePadClicked(this, new GamePadPressedEventArgs(gameTime, Buttons.DPadDown, PlayerIndex)); }
if (ButtonPressed(Buttons.DPadLeft)) { GamePadClicked(this, new GamePadPressedEventArgs(gameTime, Buttons.DPadLeft, PlayerIndex)); }
if (ButtonPressed(Buttons.DPadRight)) { GamePadClicked(this, new GamePadPressedEventArgs(gameTime, Buttons.DPadRight, PlayerIndex)); }
}
if (GamePadMoved != null) {
if (HasLeftThumbstickMoved()) {
GamePadMoved(this,
new GamePadMovedEventsArgs(
gameTime,
Buttons.LeftStick,
PlayerIndex,
m_gamePadState.ThumbSticks.Left,
m_prevGamePadState.ThumbSticks.Left - m_gamePadState.ThumbSticks.Left)
);
}
if (HasRightThumbstickMoved()) {
GamePadMoved(this,
new GamePadMovedEventsArgs(
gameTime,
Buttons.RightStick,
PlayerIndex,
m_gamePadState.ThumbSticks.Right,
m_prevGamePadState.ThumbSticks.Right - m_gamePadState.ThumbSticks.Right)
);
}
if (HasLeftTriggerMoved()) {
GamePadMoved(this,
new GamePadMovedEventsArgs(
gameTime,
Buttons.LeftTrigger,
PlayerIndex,
new Vector2(0.0f, m_gamePadState.Triggers.Left),
new Vector2(0.0f, m_prevGamePadState.Triggers.Left) - new Vector2(0.0f, m_gamePadState.Triggers.Left))
);
}
if (HasRightTriggerMoved()) {
GamePadMoved(this,
new GamePadMovedEventsArgs(
gameTime,
Buttons.RightTrigger,
PlayerIndex,
new Vector2(0.0f, m_gamePadState.Triggers.Right),
new Vector2(0.0f, m_prevGamePadState.Triggers.Right) - new Vector2(0.0f, m_gamePadState.Triggers.Right))
);
}
}
#endregion
}
#region Helper Methods
public bool ButtonPressed(Buttons button)
{
if (m_prevGamePadState.IsButtonDown(button) == true &&
m_gamePadState.IsButtonUp(button) == true)
return true;
return false;
}
public bool IsButtonDown(Buttons button)
{
return m_gamePadState.IsButtonDown(button);
}
public bool IsButtonUp(Buttons button)
{
return m_gamePadState.IsButtonUp(button);
}
public void SetVibration(float leftMotor, float rightMotor)
{
GamePad.SetVibration(m_playerIndex, leftMotor, rightMotor);
}
#region Thumbsticks
public bool HasLeftThumbstickMoved()
{
if (m_gamePadState.ThumbSticks.Left == Vector2.Zero) return false;
return true;
}
public bool HasRightThumbstickMoved()
{
if (m_gamePadState.ThumbSticks.Right == Vector2.Zero) return false;
return true;
}
#endregion
#region Triggers
public bool HasLeftTriggerMoved()
{
if (m_gamePadState.Triggers.Left == 0.0f) return false;
return true;
}
public bool HasRightTriggerMoved()
{
if (m_gamePadState.Triggers.Right == 0.0f) return false;
return true;
}
#endregion
public bool HasInputChanged(bool ignoreThumbsticks)
{
if ((m_gamePadState.IsConnected) && (m_gamePadState.PacketNumber != m_prevGamePadState.PacketNumber))
{
//ignore thumbstick movement
if ((ignoreThumbsticks == true) && ((m_gamePadState.ThumbSticks.Left.Length() != m_prevGamePadState.ThumbSticks.Left.Length()) && (m_gamePadState.ThumbSticks.Right.Length() != m_prevGamePadState.ThumbSticks.Right.Length())))
return false;
return true;
}
return false;
}
#endregion
#region Events
public static event GamePadDownEventHandler GamePadDown;
public static event GamePadPressedEventHandler GamePadClicked;
public static event GamePadMovedEventHandler GamePadMoved;
#endregion
}
}
| KillerrinStudios/Anarian-Game-Engine-MonoGame | Anarian Game Engine.Shared/DataStructures/Input/Controller.cs | C# | mit | 10,322 |
package api2go
import (
"context"
"time"
)
// APIContextAllocatorFunc to allow custom context implementations
type APIContextAllocatorFunc func(*API) APIContexter
// APIContexter embedding context.Context and requesting two helper functions
type APIContexter interface {
context.Context
Set(key string, value interface{})
Get(key string) (interface{}, bool)
Reset()
}
// APIContext api2go context for handlers, nil implementations related to Deadline and Done.
type APIContext struct {
keys map[string]interface{}
}
// Set a string key value in the context
func (c *APIContext) Set(key string, value interface{}) {
if c.keys == nil {
c.keys = make(map[string]interface{})
}
c.keys[key] = value
}
// Get a key value from the context
func (c *APIContext) Get(key string) (value interface{}, exists bool) {
if c.keys != nil {
value, exists = c.keys[key]
}
return
}
// Reset resets all values on Context, making it safe to reuse
func (c *APIContext) Reset() {
c.keys = nil
}
// Deadline implements net/context
func (c *APIContext) Deadline() (deadline time.Time, ok bool) {
return
}
// Done implements net/context
func (c *APIContext) Done() <-chan struct{} {
return nil
}
// Err implements net/context
func (c *APIContext) Err() error {
return nil
}
// Value implements net/context
func (c *APIContext) Value(key interface{}) interface{} {
if keyAsString, ok := key.(string); ok {
val, _ := c.Get(keyAsString)
return val
}
return nil
}
// Compile time check
var _ APIContexter = &APIContext{}
// ContextQueryParams fetches the QueryParams if Set
func ContextQueryParams(c *APIContext) map[string][]string {
qp, ok := c.Get("QueryParams")
if ok == false {
qp = make(map[string][]string)
c.Set("QueryParams", qp)
}
return qp.(map[string][]string)
}
| manyminds/api2go | context.go | GO | mit | 1,793 |
// This file auto generated by plugin for ida pro. Generated code only for x64. Please, dont change manually
#pragma once
#include <common/common.h>
START_ATF_NAMESPACE
typedef int (WINAPIV *PSYM_ENUMERATESYMBOLS_CALLBACK)(_SYMBOL_INFO *, unsigned int, void *);
END_ATF_NAMESPACE
| goodwinxp/Yorozuya | library/ATF/PSYM_ENUMERATESYMBOLS_CALLBACK.hpp | C++ | mit | 287 |
/*
* Copyright (C) 2013 Joseph Mansfield
*
* 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 uk.co.sftrabbit.stackanswers.fragment;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import uk.co.sftrabbit.stackanswers.R;
public class AuthInfoFragment extends Fragment {
public AuthInfoFragment() {
// Do nothing
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.authentication_info, container, false);
}
}
| sftrabbit/StackAnswers | src/uk/co/sftrabbit/stackanswers/fragment/AuthInfoFragment.java | Java | mit | 1,678 |
<?php
namespace moonland\phpexcel;
use yii\helpers\ArrayHelper;
use yii\base\InvalidConfigException;
use yii\base\InvalidParamException;
use yii\i18n\Formatter;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
/**
* Excel Widget for generate Excel File or for load Excel File.
*
* Usage
* -----
*
* Exporting data into an excel file.
*
* ~~~
*
* // export data only one worksheet.
*
* \moonland\phpexcel\Excel::widget([
* 'models' => $allModels,
* 'mode' => 'export', //default value as 'export'
* 'columns' => ['column1','column2','column3'],
* //without header working, because the header will be get label from attribute label.
* 'headers' => ['column1' => 'Header Column 1','column2' => 'Header Column 2', 'column3' => 'Header Column 3'],
* ]);
*
* \moonland\phpexcel\Excel::export([
* 'models' => $allModels,
* 'columns' => ['column1','column2','column3'],
* //without header working, because the header will be get label from attribute label.
* 'headers' => ['column1' => 'Header Column 1','column2' => 'Header Column 2', 'column3' => 'Header Column 3'],
* ]);
*
* // export data with multiple worksheet.
*
* \moonland\phpexcel\Excel::widget([
* 'isMultipleSheet' => true,
* 'models' => [
* 'sheet1' => $allModels1,
* 'sheet2' => $allModels2,
* 'sheet3' => $allModels3
* ],
* 'mode' => 'export', //default value as 'export'
* 'columns' => [
* 'sheet1' => ['column1','column2','column3'],
* 'sheet2' => ['column1','column2','column3'],
* 'sheet3' => ['column1','column2','column3']
* ],
* //without header working, because the header will be get label from attribute label.
* 'headers' => [
* 'sheet1' => ['column1' => 'Header Column 1','column2' => 'Header Column 2', 'column3' => 'Header Column 3'],
* 'sheet2' => ['column1' => 'Header Column 1','column2' => 'Header Column 2', 'column3' => 'Header Column 3'],
* 'sheet3' => ['column1' => 'Header Column 1','column2' => 'Header Column 2', 'column3' => 'Header Column 3']
* ],
* ]);
*
* \moonland\phpexcel\Excel::export([
* 'isMultipleSheet' => true,
* 'models' => [
* 'sheet1' => $allModels1,
* 'sheet2' => $allModels2,
* 'sheet3' => $allModels3
* ],
* 'columns' => [
* 'sheet1' => ['column1','column2','column3'],
* 'sheet2' => ['column1','column2','column3'],
* 'sheet3' => ['column1','column2','column3']
* ],
* //without header working, because the header will be get label from attribute label.
* 'headers' => [
* 'sheet1' => ['column1' => 'Header Column 1','column2' => 'Header Column 2', 'column3' => 'Header Column 3'],
* 'sheet2' => ['column1' => 'Header Column 1','column2' => 'Header Column 2', 'column3' => 'Header Column 3'],
* 'sheet3' => ['column1' => 'Header Column 1','column2' => 'Header Column 2', 'column3' => 'Header Column 3']
* ],
* ]);
*
* ~~~
*
* New Feature for exporting data, you can use this if you familiar yii gridview.
* That is same with gridview data column.
* Columns in array mode valid params are 'attribute', 'header', 'format', 'value', and footer (TODO).
* Columns in string mode valid layout are 'attribute:format:header:footer(TODO)'.
*
* ~~~
*
* \moonland\phpexcel\Excel::export([
* 'models' => Post::find()->all(),
* 'columns' => [
* 'author.name:text:Author Name',
* [
* 'attribute' => 'content',
* 'header' => 'Content Post',
* 'format' => 'text',
* 'value' => function($model) {
* return ExampleClass::removeText('example', $model->content);
* },
* ],
* 'like_it:text:Reader like this content',
* 'created_at:datetime',
* [
* 'attribute' => 'updated_at',
* 'format' => 'date',
* ],
* ],
* 'headers' => [
* 'created_at' => 'Date Created Content',
* ],
* ]);
*
* ~~~
*
*
* Import file excel and return into an array.
*
* ~~~
*
* $data = \moonland\phpexcel\Excel::import($fileName, $config); // $config is an optional
*
* $data = \moonland\phpexcel\Excel::widget([
* 'mode' => 'import',
* 'fileName' => $fileName,
* 'setFirstRecordAsKeys' => true, // if you want to set the keys of record column with first record, if it not set, the header with use the alphabet column on excel.
* 'setIndexSheetByName' => true, // set this if your excel data with multiple worksheet, the index of array will be set with the sheet name. If this not set, the index will use numeric.
* 'getOnlySheet' => 'sheet1', // you can set this property if you want to get the specified sheet from the excel data with multiple worksheet.
* ]);
*
* $data = \moonland\phpexcel\Excel::import($fileName, [
* 'setFirstRecordAsKeys' => true, // if you want to set the keys of record column with first record, if it not set, the header with use the alphabet column on excel.
* 'setIndexSheetByName' => true, // set this if your excel data with multiple worksheet, the index of array will be set with the sheet name. If this not set, the index will use numeric.
* 'getOnlySheet' => 'sheet1', // you can set this property if you want to get the specified sheet from the excel data with multiple worksheet.
* ]);
*
* // import data with multiple file.
*
* $data = \moonland\phpexcel\Excel::widget([
* 'mode' => 'import',
* 'fileName' => [
* 'file1' => $fileName1,
* 'file2' => $fileName2,
* 'file3' => $fileName3,
* ],
* 'setFirstRecordAsKeys' => true, // if you want to set the keys of record column with first record, if it not set, the header with use the alphabet column on excel.
* 'setIndexSheetByName' => true, // set this if your excel data with multiple worksheet, the index of array will be set with the sheet name. If this not set, the index will use numeric.
* 'getOnlySheet' => 'sheet1', // you can set this property if you want to get the specified sheet from the excel data with multiple worksheet.
* ]);
*
* $data = \moonland\phpexcel\Excel::import([
* 'file1' => $fileName1,
* 'file2' => $fileName2,
* 'file3' => $fileName3,
* ], [
* 'setFirstRecordAsKeys' => true, // if you want to set the keys of record column with first record, if it not set, the header with use the alphabet column on excel.
* 'setIndexSheetByName' => true, // set this if your excel data with multiple worksheet, the index of array will be set with the sheet name. If this not set, the index will use numeric.
* 'getOnlySheet' => 'sheet1', // you can set this property if you want to get the specified sheet from the excel data with multiple worksheet.
* ]);
*
* ~~~
*
* Result example from the code on the top :
*
* ~~~
*
* // only one sheet or specified sheet.
*
* Array([0] => Array([name] => Anam, [email] => moh.khoirul.anaam@gmail.com, [framework interest] => Yii2),
* [1] => Array([name] => Example, [email] => example@moonlandsoft.com, [framework interest] => Yii2));
*
* // data with multiple worksheet
*
* Array([Sheet1] => Array([0] => Array([name] => Anam, [email] => moh.khoirul.anaam@gmail.com, [framework interest] => Yii2),
* [1] => Array([name] => Example, [email] => example@moonlandsoft.com, [framework interest] => Yii2)),
* [Sheet2] => Array([0] => Array([name] => Anam, [email] => moh.khoirul.anaam@gmail.com, [framework interest] => Yii2),
* [1] => Array([name] => Example, [email] => example@moonlandsoft.com, [framework interest] => Yii2)));
*
* // data with multiple file and specified sheet or only one worksheet
*
* Array([file1] => Array([0] => Array([name] => Anam, [email] => moh.khoirul.anaam@gmail.com, [framework interest] => Yii2),
* [1] => Array([name] => Example, [email] => example@moonlandsoft.com, [framework interest] => Yii2)),
* [file2] => Array([0] => Array([name] => Anam, [email] => moh.khoirul.anaam@gmail.com, [framework interest] => Yii2),
* [1] => Array([name] => Example, [email] => example@moonlandsoft.com, [framework interest] => Yii2)));
*
* // data with multiple file and multiple worksheet
*
* Array([file1] => Array([Sheet1] => Array([0] => Array([name] => Anam, [email] => moh.khoirul.anaam@gmail.com, [framework interest] => Yii2),
* [1] => Array([name] => Example, [email] => example@moonlandsoft.com, [framework interest] => Yii2)),
* [Sheet2] => Array([0] => Array([name] => Anam, [email] => moh.khoirul.anaam@gmail.com, [framework interest] => Yii2),
* [1] => Array([name] => Example, [email] => example@moonlandsoft.com, [framework interest] => Yii2))),
* [file2] => Array([Sheet1] => Array([0] => Array([name] => Anam, [email] => moh.khoirul.anaam@gmail.com, [framework interest] => Yii2),
* [1] => Array([name] => Example, [email] => example@moonlandsoft.com, [framework interest] => Yii2)),
* [Sheet2] => Array([0] => Array([name] => Anam, [email] => moh.khoirul.anaam@gmail.com, [framework interest] => Yii2),
* [1] => Array([name] => Example, [email] => example@moonlandsoft.com, [framework interest] => Yii2))));
*
* ~~~
*
* @property string $mode is an export mode or import mode. valid value are 'export' and 'import'
* @property boolean $isMultipleSheet for set the export excel with multiple sheet.
* @property array $properties for set property on the excel object.
* @property array $models Model object or DataProvider object with much data.
* @property array $columns to get the attributes from the model, this valid value only the exist attribute on the model.
* If this is not set, then all attribute of the model will be set as columns.
* @property array $headers to set the header column on first line. Set this if want to custom header.
* If not set, the header will get attributes label of model attributes.
* @property string|array $fileName is a name for file name to export or import. Multiple file name only use for import mode, not work if you use the export mode.
* @property string $savePath is a directory to save the file or you can blank this to set the file as attachment.
* @property string $format for excel to export. Valid value are 'Xls','Xlsx','Xml','Ods','Slk','Gnumeric','Csv', and 'Html'.
* @property boolean $setFirstTitle to set the title column on the first line. The columns will have a header on the first line.
* @property boolean $asAttachment to set the file excel to download mode.
* @property boolean $setFirstRecordAsKeys to set the first record on excel file to a keys of array per line.
* If you want to set the keys of record column with first record, if it not set, the header with use the alphabet column on excel.
* @property boolean $setIndexSheetByName to set the sheet index by sheet name or array result if the sheet not only one
* @property string $getOnlySheet is a sheet name to getting the data. This is only get the sheet with same name.
* @property array|Formatter $formatter the formatter used to format model attribute values into displayable texts.
* This can be either an instance of [[Formatter]] or an configuration array for creating the [[Formatter]]
* instance. If this property is not set, the "formatter" application component will be used.
*
* @author Moh Khoirul Anam <moh.khoirul.anaam@gmail.com>
* @copyright 2014
* @since 1
*/
class Excel extends \yii\base\Widget
{
// Border style
const BORDER_NONE = 'none';
const BORDER_DASHDOT = 'dashDot';
const BORDER_DASHDOTDOT = 'dashDotDot';
const BORDER_DASHED = 'dashed';
const BORDER_DOTTED = 'dotted';
const BORDER_DOUBLE = 'double';
const BORDER_HAIR = 'hair';
const BORDER_MEDIUM = 'medium';
const BORDER_MEDIUMDASHDOT = 'mediumDashDot';
const BORDER_MEDIUMDASHDOTDOT = 'mediumDashDotDot';
const BORDER_MEDIUMDASHED = 'mediumDashed';
const BORDER_SLANTDASHDOT = 'slantDashDot';
const BORDER_THICK = 'thick';
const BORDER_THIN = 'thin';
// Colors
const COLOR_BLACK = 'FF000000';
const COLOR_WHITE = 'FFFFFFFF';
const COLOR_RED = 'FFFF0000';
const COLOR_DARKRED = 'FF800000';
const COLOR_BLUE = 'FF0000FF';
const COLOR_DARKBLUE = 'FF000080';
const COLOR_GREEN = 'FF00FF00';
const COLOR_DARKGREEN = 'FF008000';
const COLOR_YELLOW = 'FFFFFF00';
const COLOR_DARKYELLOW = 'FF808000';
// Horizontal alignment styles
const HORIZONTAL_GENERAL = 'general';
const HORIZONTAL_LEFT = 'left';
const HORIZONTAL_RIGHT = 'right';
const HORIZONTAL_CENTER = 'center';
const HORIZONTAL_CENTER_CONTINUOUS = 'centerContinuous';
const HORIZONTAL_JUSTIFY = 'justify';
const HORIZONTAL_FILL = 'fill';
const HORIZONTAL_DISTRIBUTED = 'distributed'; // Excel2007 only
// Vertical alignment styles
const VERTICAL_BOTTOM = 'bottom';
const VERTICAL_TOP = 'top';
const VERTICAL_CENTER = 'center';
const VERTICAL_JUSTIFY = 'justify';
const VERTICAL_DISTRIBUTED = 'distributed'; // Excel2007 only
// Read order
const READORDER_CONTEXT = 0;
const READORDER_LTR = 1;
const READORDER_RTL = 2;
// Fill types
const FILL_NONE = 'none';
const FILL_SOLID = 'solid';
const FILL_GRADIENT_LINEAR = 'linear';
const FILL_GRADIENT_PATH = 'path';
const FILL_PATTERN_DARKDOWN = 'darkDown';
const FILL_PATTERN_DARKGRAY = 'darkGray';
const FILL_PATTERN_DARKGRID = 'darkGrid';
const FILL_PATTERN_DARKHORIZONTAL = 'darkHorizontal';
const FILL_PATTERN_DARKTRELLIS = 'darkTrellis';
const FILL_PATTERN_DARKUP = 'darkUp';
const FILL_PATTERN_DARKVERTICAL = 'darkVertical';
const FILL_PATTERN_GRAY0625 = 'gray0625';
const FILL_PATTERN_GRAY125 = 'gray125';
const FILL_PATTERN_LIGHTDOWN = 'lightDown';
const FILL_PATTERN_LIGHTGRAY = 'lightGray';
const FILL_PATTERN_LIGHTGRID = 'lightGrid';
const FILL_PATTERN_LIGHTHORIZONTAL = 'lightHorizontal';
const FILL_PATTERN_LIGHTTRELLIS = 'lightTrellis';
const FILL_PATTERN_LIGHTUP = 'lightUp';
const FILL_PATTERN_LIGHTVERTICAL = 'lightVertical';
const FILL_PATTERN_MEDIUMGRAY = 'mediumGray';
// Pre-defined formats
const FORMAT_GENERAL = 'General';
const FORMAT_TEXT = '@';
const FORMAT_NUMBER = '0';
const FORMAT_NUMBER_00 = '0.00';
const FORMAT_NUMBER_COMMA_SEPARATED1 = '#,##0.00';
const FORMAT_NUMBER_COMMA_SEPARATED2 = '#,##0.00_-';
const FORMAT_PERCENTAGE = '0%';
const FORMAT_PERCENTAGE_00 = '0.00%';
const FORMAT_DATE_YYYYMMDD2 = 'yyyy-mm-dd';
const FORMAT_DATE_YYYYMMDD = 'yy-mm-dd';
const FORMAT_DATE_DDMMYYYY = 'dd/mm/yy';
const FORMAT_DATE_DMYSLASH = 'd/m/yy';
const FORMAT_DATE_DMYMINUS = 'd-m-yy';
const FORMAT_DATE_DMMINUS = 'd-m';
const FORMAT_DATE_MYMINUS = 'm-yy';
const FORMAT_DATE_XLSX14 = 'mm-dd-yy';
const FORMAT_DATE_XLSX15 = 'd-mmm-yy';
const FORMAT_DATE_XLSX16 = 'd-mmm';
const FORMAT_DATE_XLSX17 = 'mmm-yy';
const FORMAT_DATE_XLSX22 = 'm/d/yy h:mm';
const FORMAT_DATE_DATETIME = 'd/m/yy h:mm';
const FORMAT_DATE_TIME1 = 'h:mm AM/PM';
const FORMAT_DATE_TIME2 = 'h:mm:ss AM/PM';
const FORMAT_DATE_TIME3 = 'h:mm';
const FORMAT_DATE_TIME4 = 'h:mm:ss';
const FORMAT_DATE_TIME5 = 'mm:ss';
const FORMAT_DATE_TIME6 = 'h:mm:ss';
const FORMAT_DATE_TIME7 = 'i:s.S';
const FORMAT_DATE_TIME8 = 'h:mm:ss;@';
const FORMAT_DATE_YYYYMMDDSLASH = 'yy/mm/dd;@';
const FORMAT_CURRENCY_USD_SIMPLE = '"$"#,##0.00_-';
const FORMAT_CURRENCY_USD = '$#,##0_-';
const FORMAT_CURRENCY_EUR_SIMPLE = '#,##0.00_-"€"';
const FORMAT_CURRENCY_EUR = '#,##0_-"€"';
/**
* @var string mode is an export mode or import mode. valid value are 'export' and 'import'.
*/
public $mode = 'export';
/**
* @var boolean for set the export excel with multiple sheet.
*/
public $isMultipleSheet = false;
/**
* @var array properties for set property on the excel object.
*/
public $properties;
/**
* @var Model object or DataProvider object with much data.
*/
public $models;
/**
* @var array columns to get the attributes from the model, this valid value only the exist attribute on the model.
* If this is not set, then all attribute of the model will be set as columns.
*/
public $columns = [];
/**
* @var array header to set the header column on first line. Set this if want to custom header.
* If not set, the header will get attributes label of model attributes.
*/
public $headers = [];
/**
* @var string|array name for file name to export or save.
*/
public $fileName;
/**
* @var string save path is a directory to save the file or you can blank this to set the file as attachment.
*/
public $savePath;
/**
* @var string format for excel to export. Valid value are 'Xls','Xlsx','Xml','Ods','Slk','Gnumeric','Csv', and 'Html'.
*/
public $format;
/**
* @var boolean to set the title column on the first line.
*/
public $setFirstTitle = true;
/**
* @var boolean to set the file excel to download mode.
*/
public $asAttachment = false;
/**
* @var boolean to set the first record on excel file to a keys of array per line.
* If you want to set the keys of record column with first record, if it not set, the header with use the alphabet column on excel.
*/
public $setFirstRecordAsKeys = true;
/**
* @var boolean to set the sheet index by sheet name or array result if the sheet not only one.
*/
public $setIndexSheetByName = false;
/**
* @var string sheetname to getting. This is only get the sheet with same name.
*/
public $getOnlySheet;
/**
* @var boolean to set the import data will return as array.
*/
public $asArray;
/**
* @var array to unread record by index number.
*/
public $leaveRecordByIndex = [];
/**
* @var array to read record by index, other will leave.
*/
public $getOnlyRecordByIndex = [];
/**
* @var array|Formatter the formatter used to format model attribute values into displayable texts.
* This can be either an instance of [[Formatter]] or an configuration array for creating the [[Formatter]]
* instance. If this property is not set, the "formatter" application component will be used.
*/
public $formatter;
/**
* @var boolean define the column autosize
*/
public $autoSize = false;
/**
* @var boolean if true, this writer pre-calculates all formulas in the spreadsheet. This can be slow on large spreadsheets, and maybe even unwanted.
*/
public $preCalculationFormula = false;
/**
* @var boolean Because of a bug in the Office2003 compatibility pack, there can be some small issues when opening Xlsx spreadsheets (mostly related to formula calculation)
*/
public $compatibilityOffice2003 = false;
/**
* @var custom CSV delimiter for import. Works only with CSV files
*/
public $CSVDelimiter = ";";
/**
* @var custom CSV encoding for import. Works only with CSV files
*/
public $CSVEncoding = "UTF-8";
/**
* (non-PHPdoc)
* @see \yii\base\Object::init()
*/
public function init()
{
parent::init();
if ($this->formatter == null) {
$this->formatter = \Yii::$app->getFormatter();
} elseif (is_array($this->formatter)) {
$this->formatter = \Yii::createObject($this->formatter);
}
if (!$this->formatter instanceof Formatter) {
throw new InvalidConfigException('The "formatter" property must be either a Format object or a configuration array.');
}
}
/**
* Setting data from models
*/
public function executeColumns(&$activeSheet = null, $models, $columns = [], $headers = [])
{
if ($activeSheet == null) {
$activeSheet = $this->activeSheet;
}
$hasHeader = false;
$row = 1;
$char = 26;
foreach ($models as $model) {
if (empty($columns)) {
$columns = $model->attributes();
}
if ($this->setFirstTitle && !$hasHeader) {
$isPlus = false;
$colplus = 0;
$colnum = 1;
foreach ($columns as $key=>$column) {
$col = '';
if ($colnum > $char) {
$colplus += 1;
$colnum = 1;
$isPlus = true;
}
if ($isPlus) {
$col .= chr(64+$colplus);
}
$col .= chr(64+$colnum);
$header = '';
if (is_array($column)) {
if (isset($column['header'])) {
$header = $column['header'];
} elseif (isset($column['attribute']) && isset($headers[$column['attribute']])) {
$header = $headers[$column['attribute']];
} elseif (isset($column['attribute'])) {
$header = $model->getAttributeLabel($column['attribute']);
} elseif (isset($column['cellFormat']) && is_array($column['cellFormat'])) {
$activeSheet->getStyle($col.$row)->applyFromArray($column['cellFormat']);
}
} else {
if(isset($headers[$column])) {
$header = $headers[$column];
} else {
$header = $model->getAttributeLabel($column);
}
}
if (isset($column['width'])) {
$activeSheet->getColumnDimension(strtoupper($col))->setWidth($column['width']);
}
$activeSheet->setCellValue($col.$row,$header);
$colnum++;
}
$hasHeader=true;
$row++;
}
$isPlus = false;
$colplus = 0;
$colnum = 1;
foreach ($columns as $key=>$column) {
$col = '';
if ($colnum > $char) {
$colplus++;
$colnum = 1;
$isPlus = true;
}
if ($isPlus) {
$col .= chr(64+$colplus);
}
$col .= chr(64+$colnum);
if (is_array($column)) {
$column_value = $this->executeGetColumnData($model, $column);
if (isset($column['cellFormat']) && is_array($column['cellFormat'])) {
$activeSheet->getStyle($col.$row)->applyFromArray($column['cellFormat']);
}
} else {
$column_value = $this->executeGetColumnData($model, ['attribute' => $column]);
}
$activeSheet->setCellValue($col.$row,$column_value);
$colnum++;
}
$row++;
if($this->autoSize){
foreach (range(0, $colnum) as $col) {
$activeSheet->getColumnDimensionByColumn($col)->setAutoSize(true);
}
}
}
}
/**
* Setting label or keys on every record if setFirstRecordAsKeys is true.
* @param array $sheetData
* @return multitype:multitype:array
*/
public function executeArrayLabel($sheetData)
{
$keys = ArrayHelper::remove($sheetData, '1');
$new_data = [];
foreach ($sheetData as $values)
{
$new_data[] = array_combine($keys, $values);
}
return $new_data;
}
/**
* Leave record with same index number.
* @param array $sheetData
* @param array $index
* @return array
*/
public function executeLeaveRecords($sheetData = [], $index = [])
{
foreach ($sheetData as $key => $data)
{
if (in_array($key, $index))
{
unset($sheetData[$key]);
}
}
return $sheetData;
}
/**
* Read record with same index number.
* @param array $sheetData
* @param array $index
* @return array
*/
public function executeGetOnlyRecords($sheetData = [], $index = [])
{
foreach ($sheetData as $key => $data)
{
if (!in_array($key, $index))
{
unset($sheetData[$key]);
}
}
return $sheetData;
}
/**
* Getting column value.
* @param Model $model
* @param array $params
* @return Ambigous <NULL, string, mixed>
*/
public function executeGetColumnData($model, $params = [])
{
$value = null;
if (isset($params['value']) && $params['value'] !== null) {
if (is_string($params['value'])) {
$value = ArrayHelper::getValue($model, $params['value']);
} else {
$value = call_user_func($params['value'], $model, $this);
}
} elseif (isset($params['attribute']) && $params['attribute'] !== null) {
$value = ArrayHelper::getValue($model, $params['attribute']);
}
if (isset($params['format']) && $params['format'] != null)
$value = $this->formatter()->format($value, $params['format']);
return $value;
}
/**
* Populating columns for checking the column is string or array. if is string this will be checking have a formatter or header.
* @param array $columns
* @throws InvalidParamException
* @return multitype:multitype:array
*/
public function populateColumns($columns = [])
{
$_columns = [];
foreach ($columns as $key => $value)
{
if (is_string($value))
{
$value_log = explode(':', $value);
$_columns[$key] = ['attribute' => $value_log[0]];
if (isset($value_log[1]) && $value_log[1] !== null) {
$_columns[$key]['format'] = $value_log[1];
}
if (isset($value_log[2]) && $value_log[2] !== null) {
$_columns[$key]['header'] = $value_log[2];
}
} elseif (is_array($value)) {
if (!isset($value['attribute']) && !isset($value['value'])) {
throw new \InvalidArgumentException('Attribute or Value must be defined.');
}
$_columns[$key] = $value;
}
}
return $_columns;
}
/**
* Formatter for i18n.
* @return Formatter
*/
public function formatter()
{
if (!isset($this->formatter))
$this->formatter = \Yii::$app->getFormatter();
return $this->formatter;
}
/**
* Setting header to download generated file xls
*/
public function setHeaders()
{
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment;filename="' . $this->getFileName() .'"');
header('Cache-Control: max-age=0');
}
/**
* Getting the file name of exporting xls file
* @return string
*/
public function getFileName()
{
$fileName = 'exports.xlsx';
if (isset($this->fileName)) {
$fileName = $this->fileName;
if (strpos($fileName, '.xlsx') === false)
$fileName .= '.xlsx';
}
return $fileName;
}
/**
* Setting properties for excel file
* @param PHPExcel $objectExcel
* @param array $properties
*/
public function properties(&$objectExcel, $properties = [])
{
foreach ($properties as $key => $value)
{
$keyname = "set" . ucfirst($key);
$objectExcel->getProperties()->{$keyname}($value);
}
}
/**
* saving the xls file to download or to path
*/
public function writeFile($sheet)
{
if (!isset($this->format))
$this->format = 'Xlsx';
$objectwriter = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($sheet, $this->format);
$path = 'php://output';
if (isset($this->savePath) && $this->savePath != null) {
$path = $this->savePath . '/' . $this->getFileName();
}
$objectwriter->setOffice2003Compatibility($this->compatibilityOffice2003);
$objectwriter->setPreCalculateFormulas($this->preCalculationFormula);
$objectwriter->save($path);
if ($path == 'php://output')
exit();
return true;
}
/**
* reading the xls file
*/
public function readFile($fileName)
{
if (!isset($this->format))
$this->format = \PhpOffice\PhpSpreadsheet\IOFactory::identify($fileName);
$objectreader = \PhpOffice\PhpSpreadsheet\IOFactory::createReader($this->format);
if ($this->format == "Csv") {
$objectreader->setDelimiter($this->CSVDelimiter);
$objectreader->setInputEncoding($this->CSVEncoding);
}
$objectPhpExcel = $objectreader->load($fileName);
$sheetCount = $objectPhpExcel->getSheetCount();
$sheetDatas = [];
if ($sheetCount > 1) {
foreach ($objectPhpExcel->getSheetNames() as $sheetIndex => $sheetName) {
if (isset($this->getOnlySheet) && $this->getOnlySheet != null) {
if(!$objectPhpExcel->getSheetByName($this->getOnlySheet)) {
return $sheetDatas;
}
$objectPhpExcel->setActiveSheetIndexByName($this->getOnlySheet);
$indexed = $this->getOnlySheet;
$sheetDatas[$indexed] = $objectPhpExcel->getActiveSheet()->toArray(null, true, true, true);
if ($this->setFirstRecordAsKeys) {
$sheetDatas[$indexed] = $this->executeArrayLabel($sheetDatas[$indexed]);
}
if (!empty($this->getOnlyRecordByIndex)) {
$sheetDatas[$indexed] = $this->executeGetOnlyRecords($sheetDatas[$indexed], $this->getOnlyRecordByIndex);
}
if (!empty($this->leaveRecordByIndex)) {
$sheetDatas[$indexed] = $this->executeLeaveRecords($sheetDatas[$indexed], $this->leaveRecordByIndex);
}
return $sheetDatas[$indexed];
} else {
$objectPhpExcel->setActiveSheetIndexByName($sheetName);
$indexed = $this->setIndexSheetByName==true ? $sheetName : $sheetIndex;
$sheetDatas[$indexed] = $objectPhpExcel->getActiveSheet()->toArray(null, true, true, true);
if ($this->setFirstRecordAsKeys) {
$sheetDatas[$indexed] = $this->executeArrayLabel($sheetDatas[$indexed]);
}
if (!empty($this->getOnlyRecordByIndex) && isset($this->getOnlyRecordByIndex[$indexed]) && is_array($this->getOnlyRecordByIndex[$indexed])) {
$sheetDatas = $this->executeGetOnlyRecords($sheetDatas, $this->getOnlyRecordByIndex[$indexed]);
}
if (!empty($this->leaveRecordByIndex) && isset($this->leaveRecordByIndex[$indexed]) && is_array($this->leaveRecordByIndex[$indexed])) {
$sheetDatas[$indexed] = $this->executeLeaveRecords($sheetDatas[$indexed], $this->leaveRecordByIndex[$indexed]);
}
}
}
} else {
$sheetDatas = $objectPhpExcel->getActiveSheet()->toArray(null, true, true, true);
if ($this->setFirstRecordAsKeys) {
$sheetDatas = $this->executeArrayLabel($sheetDatas);
}
if (!empty($this->getOnlyRecordByIndex)) {
$sheetDatas = $this->executeGetOnlyRecords($sheetDatas, $this->getOnlyRecordByIndex);
}
if (!empty($this->leaveRecordByIndex)) {
$sheetDatas = $this->executeLeaveRecords($sheetDatas, $this->leaveRecordByIndex);
}
}
return $sheetDatas;
}
/**
* (non-PHPdoc)
* @see \yii\base\Widget::run()
*/
public function run()
{
if ($this->mode == 'export')
{
$sheet = new Spreadsheet();
if (!isset($this->models))
throw new InvalidConfigException('Config models must be set');
if (isset($this->properties))
{
$this->properties($sheet, $this->properties);
}
if ($this->isMultipleSheet) {
$index = 0;
$worksheet = [];
foreach ($this->models as $title => $models) {
$sheet->createSheet($index);
$sheet->getSheet($index)->setTitle($title);
$worksheet[$index] = $sheet->getSheet($index);
$columns = isset($this->columns[$title]) ? $this->columns[$title] : [];
$headers = isset($this->headers[$title]) ? $this->headers[$title] : [];
$this->executeColumns($worksheet[$index], $models, $this->populateColumns($columns), $headers);
$index++;
}
} else {
$worksheet = $sheet->getActiveSheet();
$this->executeColumns($worksheet, $this->models, isset($this->columns) ? $this->populateColumns($this->columns) : [], isset($this->headers) ? $this->headers : []);
}
if ($this->asAttachment) {
$this->setHeaders();
}
$this->writeFile($sheet);
$sheet->disconnectWorksheets();
unset($sheet);
}
elseif ($this->mode == 'import')
{
if (is_array($this->fileName)) {
$datas = [];
foreach ($this->fileName as $key => $filename) {
$datas[$key] = $this->readFile($filename);
}
return $datas;
} else {
return $this->readFile($this->fileName);
}
}
}
/**
* Exporting data into an excel file.
*
* ~~~
*
* \moonland\phpexcel\Excel::export([
* 'models' => $allModels,
* 'columns' => ['column1','column2','column3'],
* //without header working, because the header will be get label from attribute label.
* 'header' => ['column1' => 'Header Column 1','column2' => 'Header Column 2', 'column3' => 'Header Column 3'],
* ]);
*
* ~~~
*
* New Feature for exporting data, you can use this if you familiar yii gridview.
* That is same with gridview data column.
* Columns in array mode valid params are 'attribute', 'header', 'format', 'value', and footer (TODO).
* Columns in string mode valid layout are 'attribute:format:header:footer(TODO)'.
*
* ~~~
*
* \moonland\phpexcel\Excel::export([
* 'models' => Post::find()->all(),
* 'columns' => [
* 'author.name:text:Author Name',
* [
* 'attribute' => 'content',
* 'header' => 'Content Post',
* 'format' => 'text',
* 'value' => function($model) {
* return ExampleClass::removeText('example', $model->content);
* },
* ],
* 'like_it:text:Reader like this content',
* 'created_at:datetime',
* [
* 'attribute' => 'updated_at',
* 'format' => 'date',
* ],
* ],
* 'headers' => [
* 'created_at' => 'Date Created Content',
* ],
* ]);
*
* ~~~
*
* @param array $config
* @return string
*/
public static function export($config=[])
{
$config = ArrayHelper::merge(['mode' => 'export'], $config);
return self::widget($config);
}
/**
* Import file excel and return into an array.
*
* ~~~
*
* $data = \moonland\phpexcel\Excel::import($fileName, ['setFirstRecordAsKeys' => true]);
*
* ~~~
*
* @param string!array $fileName to load.
* @param array $config is a more configuration.
* @return string
*/
public static function import($fileName, $config=[])
{
$config = ArrayHelper::merge(['mode' => 'import', 'fileName' => $fileName, 'asArray' => true], $config);
return self::widget($config);
}
/**
* @param array $config
* @return string
*/
public static function widget($config = [])
{
if ((isset($config['mode']) and $config['mode'] == 'import') && !isset($config['asArray'])) {
$config['asArray'] = true;
}
if (isset($config['asArray']) && $config['asArray']==true)
{
$config['class'] = get_called_class();
$widget = \Yii::createObject($config);
return $widget->run();
} else {
return parent::widget($config);
}
}
}
| moonlandsoft/yii2-phpexcel | Excel.php | PHP | mit | 33,886 |
module Text
class Sorter
def self.sort(text_components)
components = text_components.clone
components = components.shuffle
nil_priorities, components = components.partition {|c| c.priority.nil? }
components = components.sort_by(&:priority_index)
components = components.reverse
components = components + nil_priorities
end
end
end
| roschaefer/story.board | app/lib/text/sorter.rb | Ruby | mit | 379 |
<?php
require_once('../../global_functions.php');
require_once('../../connections/parameters.php');
try {
if (!isset($_SESSION)) {
session_start();
}
$s2_response = array();
$db = new dbWrapper_v3($hostname_gds_site, $username_gds_site, $password_gds_site, $database_gds_site, true);
if (empty($db)) throw new Exception('No DB!');
$memcached = new Cache(NULL, NULL, $localDev);
checkLogin_v2();
if (empty($_SESSION['user_id64'])) throw new Exception('Not logged in!');
//Check if logged in user is an admin
$adminCheck = adminCheck($_SESSION['user_id64'], 'admin');
$steamIDmanipulator = new SteamID($_SESSION['user_id64']);
$steamID32 = $steamIDmanipulator->getsteamID32();
$steamID64 = $steamIDmanipulator->getsteamID64();
if (
empty($_POST['mod_workshop_link']) ||
empty($_POST['mod_contact_address'])
) {
throw new Exception('Missing or invalid required parameter(s)!');
}
if (!filter_var($_POST['mod_contact_address'], FILTER_VALIDATE_EMAIL)) {
throw new Exception('Invalid email address!');
} else {
$db->q(
'INSERT INTO `gds_users_options`
(
`user_id32`,
`user_id64`,
`user_email`,
`sub_dev_news`,
`date_updated`,
`date_recorded`
)
VALUES (
?,
?,
?,
1,
NULL,
NULL
)
ON DUPLICATE KEY UPDATE
`user_email` = VALUES(`user_email`),
`sub_dev_news` = VALUES(`sub_dev_news`);',
'sss',
array(
$steamID32,
$steamID64,
$_POST['mod_contact_address']
)
);
}
$steamAPI = new steam_webapi($api_key1);
if (!stristr($_POST['mod_workshop_link'], 'steamcommunity.com/sharedfiles/filedetails/?id=')) {
throw new Exception('Bad workshop link');
}
$modWork = htmlentities(rtrim(rtrim(cut_str($_POST['mod_workshop_link'], 'steamcommunity.com/sharedfiles/filedetails/?id='), '/'), '&searchtext='));
$mod_details = $steamAPI->GetPublishedFileDetails($modWork);
if ($mod_details['response']['result'] != 1) {
throw new Exception('Bad steam response. API probably down.');
}
$modName = !empty($mod_details['response']['publishedfiledetails'][0]['title'])
? htmlentities($mod_details['response']['publishedfiledetails'][0]['title'])
: 'UNKNOWN MOD NAME';
$modDesc = !empty($mod_details['response']['publishedfiledetails'][0]['description'])
? htmlentities($mod_details['response']['publishedfiledetails'][0]['description'])
: 'UNKNOWN MOD DESCRIPTION';
$modOwner = !empty($mod_details['response']['publishedfiledetails'][0]['creator'])
? htmlentities($mod_details['response']['publishedfiledetails'][0]['creator'])
: '-1';
$modApp = !empty($mod_details['response']['publishedfiledetails'][0]['consumer_app_id'])
? htmlentities($mod_details['response']['publishedfiledetails'][0]['consumer_app_id'])
: '-1';
if ($_SESSION['user_id64'] != $modOwner && !$adminCheck) {
throw new Exception('Insufficient privilege to add this mod. Login as the mod developer or contact admins via <strong><a class="boldGreenText" href="https://github.com/GetDotaStats/stat-collection/issues" target="_blank">issue tracker</a></strong>!');
}
if ($modApp != 570) {
throw new Exception('Mod is not for Dota2.');
}
if (!empty($_POST['mod_steam_group']) && stristr($_POST['mod_steam_group'], 'steamcommunity.com/groups/')) {
$modGroup = htmlentities(rtrim(cut_str($_POST['mod_steam_group'], 'groups/'), '/'));
} else {
$modGroup = NULL;
}
$insertSQL = $db->q(
'INSERT INTO `mod_list` (`steam_id64`, `mod_identifier`, `mod_name`, `mod_description`, `mod_workshop_link`, `mod_steam_group`)
VALUES (?, ?, ?, ?, ?, ?);',
'ssssss', //STUPID x64 windows PHP is actually x86
array(
$modOwner,
md5($modName . time()),
$modName,
$modDesc,
$modWork,
$modGroup,
)
);
if ($insertSQL) {
$modID = $db->last_index();
$json_response['result'] = 'Success! Found mod and added to DB for approval as #' . $modID;
$db->q(
'INSERT INTO `mod_list_owners` (`mod_id`, `steam_id64`)
VALUES (?, ?);',
'is', //STUPID x64 windows PHP is actually x86
array(
$modID,
$modOwner,
)
);
updateUserDetails($modOwner, $api_key2);
$irc_message = new irc_message($webhook_gds_site_normal);
$message = array(
array(
$irc_message->colour_generator('red'),
'[ADMIN]',
$irc_message->colour_generator(NULL),
),
array(
$irc_message->colour_generator('green'),
'[MOD]',
$irc_message->colour_generator(NULL),
),
array(
$irc_message->colour_generator('bold'),
$irc_message->colour_generator('blue'),
'Pending approval:',
$irc_message->colour_generator(NULL),
$irc_message->colour_generator('bold'),
),
array(
$irc_message->colour_generator('orange'),
'{' . $modID . '}',
$irc_message->colour_generator(NULL),
),
array($modName),
array(' || http://getdotastats.com/#admin__mod_approve'),
);
$message = $irc_message->combine_message($message);
$irc_message->post_message($message, array('localDev' => $localDev));
} else {
$json_response['error'] = 'Mod not added to database. Failed to add mod for approval.';
}
} catch (Exception $e) {
$json_response['error'] = 'Caught Exception: ' . $e->getMessage();
} finally {
if (isset($memcached)) $memcached->close();
if (!isset($json_response)) $json_response = array('error' => 'Unknown exception');
}
try {
header('Content-Type: application/json');
echo utf8_encode(json_encode($json_response));
} catch (Exception $e) {
unset($json_response);
$json_response['error'] = 'Caught Exception: ' . $e->getMessage();
echo utf8_encode(json_encode($json_response));
} | GetDotaStats/site | site_files/s2/my/mod_request_ajax.php | PHP | mit | 6,730 |
module Prawn
module Charts
class Bar < Base
attr_accessor :ratio
def initialize pdf, opts = {}
super pdf, opts
@ratio = opts[:ratio] || 0.75
end
def plot_values
return if series.nil?
series.each_with_index do |bar,index|
point_x = first_x_point index
bar[:values].each do |h|
fill_color bar[:color]
fill do
height = value_height(h[:value])
rectangle [point_x,height], bar_width, height
end
point_x += additional_points
end
end
end
def first_x_point index
(bar_width * index) + (bar_space * (index + 1))
end
def additional_points
(bar_space + bar_width) * series.count
end
def x_points
points = nil
series.each_with_index do |bar,index|
tmp = []
tmp << first_x_point(index) + (bar_width / 2)
bar[:values].each do |h|
tmp << tmp.last + additional_points
end
points ||= [0] * tmp.length
tmp.each_with_index do |point, i|
points[i] += point
end
end
points.map do |point|
(point / series.count).to_i
end
end
def bar_width
@bar_width ||= (bounds.width * ratio) / series_length.to_f
end
def bar_space
@bar_space ||= (bounds.width * (1.0 - ratio)) / (series_length + 1).to_f
end
def series_length
series.map { |v| v[:values].length }.max * series.count
end
def value_height val
bounds.height * ((val - min_value) / series_height.to_f)
end
end
end
end
| cajun/prawn-charts | lib/prawn/charts/bar.rb | Ruby | mit | 1,724 |
package com.swfarm.biz.product.dao.impl;
import com.swfarm.biz.product.bo.SkuSaleMapping;
import com.swfarm.biz.product.dao.SkuSaleMappingDao;
import com.swfarm.pub.framework.dao.GenericDaoHibernateImpl;
public class SkuSaleMappingDaoImpl extends GenericDaoHibernateImpl<SkuSaleMapping, Long> implements SkuSaleMappingDao {
public SkuSaleMappingDaoImpl(Class<SkuSaleMapping> type) {
super(type);
}
} | zhangqiang110/my4j | pms/src/main/java/com/swfarm/biz/product/dao/impl/SkuSaleMappingDaoImpl.java | Java | mit | 419 |
<?php
namespace AppBundle\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
class ProfileFormType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('name');
}
public function getParent()
{
return 'FOS\UserBundle\Form\Type\ProfileFormType';
}
public function getBlockPrefix()
{
return 'app_user_profile';
}
// For Symfony 2.x
public function getName()
{
return $this->getBlockPrefix();
}
} | efalder413/PKMNBreeder | src/AppBundle/Form/ProfileFormType.php | PHP | mit | 586 |
using Nethereum.Generators.Model;
using Nethereum.Generators.Net;
namespace Nethereum.Generator.Console.Models
{
public class ContractDefinition
{
public string ContractName { get; set; }
public ContractABI Abi { get; set; }
public string Bytecode { get; set; }
public ContractDefinition(string abi)
{
Abi = new GeneratorModelABIDeserialiser().DeserialiseABI(abi);
}
}
}
| Nethereum/Nethereum | generators/Nethereum.Generator.Console/Models/ContractDefinition.cs | C# | mit | 450 |
'use strict';
module.exports = require('./toPairsIn');
//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIi4uLy4uLy4uL2NsaWVudC9saWIvbG9kYXNoL2VudHJpZXNJbi5qcyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiOztBQUFBLE9BQU8sT0FBUCxHQUFpQixRQUFRLGFBQVIsQ0FBakIiLCJmaWxlIjoiZW50cmllc0luLmpzIiwic291cmNlc0NvbnRlbnQiOlsibW9kdWxlLmV4cG9ydHMgPSByZXF1aXJlKCcuL3RvUGFpcnNJbicpO1xuIl19 | justin-lai/hackd.in | compiled/client/lib/lodash/entriesIn.js | JavaScript | mit | 394 |
""" -*- coding: utf-8 -*- """
from python2awscli import bin_aws
from python2awscli.error import AWSNotFound, ParseError, AWSDuplicate
from python2awscli import must
class BaseSecurityGroup(object):
def __init__(self, name, region, vpc, description, inbound=None, outbound=None):
"""
:param name: String, name of SG
:param region: String, AWS region
:param vpc: String, IP of the VPC this SG belongs to
:param description: String
:param inbound: List of dicts, IP Permissions that should exist
:param outbound: List of dicts, IP Permissions that should exist
"""
self.id = None
self.name = name
self.region = region
self.vpc = vpc
self.description = description
self.IpPermissions = []
self.IpPermissionsEgress = []
self.owner = None
self.changed = False
try:
self._get()
except AWSNotFound:
self._create()
self._merge_rules(must.be_list(inbound), self.IpPermissions)
self._merge_rules(must.be_list(outbound), self.IpPermissionsEgress, egress=True)
if self.changed:
self._get()
def _break_out(self, existing):
"""
Undo AWS's rule flattening so we can do simple 'if rule in existing' logic later.
:param existing: List of SG rules as dicts.
:return: List of SG rules as dicts.
"""
spool = list()
for rule in existing:
for ip in rule['IpRanges']:
copy_of_rule = rule.copy()
copy_of_rule['IpRanges'] = [ip]
copy_of_rule['UserIdGroupPairs'] = []
spool.append(copy_of_rule)
for group in rule['UserIdGroupPairs']:
copy_of_rule = rule.copy()
copy_of_rule['IpRanges'] = []
copy_of_rule['UserIdGroupPairs'] = [group]
spool.append(copy_of_rule)
return spool
def _merge_rules(self, requested, active, egress=False):
"""
:param requested: List of dicts, IP Permissions that should exist
:param active: List of dicts, IP Permissions that already exist
:param egress: Bool, addressing outbound rules or not?
:return: Bool
"""
if not isinstance(requested, list):
raise ParseError(
'SecurityGroup {0}, need a list of dicts, instead got "{1}"'.format(self.name, requested))
for rule in requested:
if rule not in active:
self._add_rule(rule, egress)
for active_rule in active:
if active_rule not in requested:
self._rm_rule(active_rule, egress)
return True
def _add_rule(self, ip_permissions, egress):
"""
:param ip_permissions: Dict of IP Permissions
:param egress: Bool
:return: Bool
"""
direction = 'authorize-security-group-ingress'
if egress:
direction = 'authorize-security-group-egress'
command = ['ec2', direction,
'--region', self.region,
'--group-id', self.id,
'--ip-permissions', str(ip_permissions).replace("'", '"')
]
bin_aws(command)
print('Authorized: {0}'.format(ip_permissions)) # TODO: Log(...)
self.changed = True
return True
def _rm_rule(self, ip_permissions, egress):
"""
:param ip_permissions: Dict of IP Permissions
:param egress: Bool
:return: Bool
"""
direction = 'revoke-security-group-ingress'
if egress:
direction = 'revoke-security-group-egress'
command = ['ec2', direction,
'--region', self.region,
'--group-id', self.id,
'--ip-permissions', str(ip_permissions).replace("'", '"')
]
bin_aws(command)
print('Revoked: {0}'.format(ip_permissions)) # TODO: Log(...)
self.changed = True
return True
def _create(self):
"""
Create a Security Group
:return:
"""
# AWS grants all new SGs this default outbound rule "This is pro-human & anti-machine behavior."
default_egress = {
'Ipv6Ranges': [],
'PrefixListIds': [],
'IpRanges': [{'CidrIp': '0.0.0.0/0'}],
'UserIdGroupPairs': [], 'IpProtocol': '-1'
}
command = [
'ec2', 'create-security-group',
'--region', self.region,
'--group-name', self.name,
'--description', self.description,
'--vpc-id', self.vpc
]
try:
self.id = bin_aws(command, key='GroupId')
except AWSDuplicate:
return False # OK if it already exists.
print('Created {0}'.format(command)) # TODO: Log(...)
self.IpPermissions = []
self.IpPermissionsEgress = [default_egress]
self.changed = True
return True
def _get(self):
"""
Get information about Security Group from AWS and update self
:return: Bool
"""
command = ['ec2', 'describe-security-groups', '--region', self.region, '--group-names', self.name]
result = bin_aws(command, key='SecurityGroups', max=1) # will raise NotFound if empty
me = result[0]
self.id = me['GroupId']
self.owner = me['OwnerId']
self.IpPermissions = self._break_out(me['IpPermissions'])
self.IpPermissionsEgress = self._break_out(me['IpPermissionsEgress'])
print('Got {0}'.format(command)) # TODO: Log(...)
return True
def _delete(self):
"""
Delete myself by my own id.
As of 20170114 no other methods call me. You must do `foo._delete()`
:return:
"""
command = ['ec2', 'delete-security-group', '--region', self.region,
# '--dry-run',
'--group-id', self.id
]
bin_aws(command, decode_output=False)
print('Deleted {0}'.format(command)) # TODO: Log(...)
return True
| jhazelwo/python-awscli | python2awscli/model/securitygroup.py | Python | mit | 6,235 |
package com.fqc.jdk8;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
public class test06 {
public static void main(String[] args) {
int[] arr = {1, 2, 3, 4, 5};
ArrayList<Integer> list = Arrays.stream(arr).collect(ArrayList::new, ArrayList::add, ArrayList::addAll);
Set<Integer> set = list.stream().collect(Collectors.toSet());
System.out.println(set.contains(33));
ArrayList<User> users = new ArrayList<>();
for (int i = 0; i < 10; i++) {
users.add(new User("name:" + i));
}
Map<String, User> map = users.stream().collect(Collectors.toMap(u -> u.username, u -> u));
map.forEach((s, user) -> System.out.println(user.username));
}
}
class User {
String username;
public User(String username) {
this.username = username;
}
}
| fqc/Java_Basic | src/main/java/com/fqc/jdk8/test06.java | Java | mit | 927 |
// Deprecated: use github.com/multiformats/go-multiaddr-fmt instead.
package mafmt
import (
nmafmt "github.com/multiformats/go-multiaddr-fmt"
)
// Deprecated: use github.com/multiformats/go-multiaddr-fmt instead.
var IP = nmafmt.IP
// Deprecated: use github.com/multiformats/go-multiaddr-fmt instead.
var TCP = nmafmt.TCP
// Deprecated: use github.com/multiformats/go-multiaddr-fmt instead.
var UDP = nmafmt.UDP
// Deprecated: use github.com/multiformats/go-multiaddr-fmt instead.
var UTP = nmafmt.UTP
// Deprecated: use github.com/multiformats/go-multiaddr-fmt instead.
var QUIC = nmafmt.QUIC
// Deprecated: use github.com/multiformats/go-multiaddr-fmt instead.
var Unreliable = nmafmt.Unreliable
// Deprecated: use github.com/multiformats/go-multiaddr-fmt instead.
var Reliable = nmafmt.Reliable
// Deprecated: use github.com/multiformats/go-multiaddr-fmt instead.
var IPFS = nmafmt.IPFS
// Deprecated: use github.com/multiformats/go-multiaddr-fmt instead.
var And = nmafmt.And
// Deprecated: use github.com/multiformats/go-multiaddr-fmt instead.
var Or = nmafmt.Or
// Deprecated: use github.com/multiformats/go-multiaddr-fmt instead.
type Pattern = nmafmt.Pattern
// Deprecated: use github.com/multiformats/go-multiaddr-fmt instead.
type Base = nmafmt.Base
| whyrusleeping/mafmt | patterns.go | GO | mit | 1,274 |
var chalk = require('chalk');
var safeStringify = require('fast-safe-stringify')
function handleErrorObject(key, value) {
if (value instanceof Error) {
return Object.getOwnPropertyNames(value).reduce(function(error, key) {
error[key] = value[key]
return error
}, {})
}
return value
}
function stringify(o) { return safeStringify(o, handleErrorObject, ' '); }
function debug() {
if (!process.env.WINSTON_CLOUDWATCH_DEBUG) return;
var args = [].slice.call(arguments);
var lastParam = args.pop();
var color = chalk.red;
if (lastParam !== true) {
args.push(lastParam);
color = chalk.green;
}
args[0] = color(args[0]);
args.unshift(chalk.blue('DEBUG:'));
console.log.apply(console, args);
}
module.exports = {
stringify: stringify,
debug: debug
};
| lazywithclass/winston-cloudwatch | lib/utils.js | JavaScript | mit | 806 |
<?php if (isset($consumers) && is_array($consumers)){ ?>
<?php $this->load->helper('security'); ?>
<tbody>
<?php foreach($consumers as $consumer){ ?>
<tr>
<td>
<a data-toggle="modal" data-target="#dynamicModal" href="<?php echo site_url("consumers/edit/$consumer->id");?>"><span class="glyphicon glyphicon-pencil"></span></a>
</td>
<td>
<?php echo $consumer->id; ?>
</td>
<td>
<?php echo xss_clean($consumer->name); ?>
</td>
</tr>
<?php } ?>
</tbody>
<tfoot>
<tr class="pagination-tr">
<td colspan="3" class="pagination-tr">
<div class="text-center">
<?php echo $this->pagination->create_links(); ?>
</div>
</td>
</tr>
</tfoot>
<?php }?>
| weslleih/almoxarifado | application/views/tbodys/consumers.php | PHP | mit | 848 |
package rholang.parsing.delimc.Absyn; // Java Package generated by the BNF Converter.
public class TType2 extends TType {
public final Type type_1, type_2;
public TType2(Type p1, Type p2) { type_1 = p1; type_2 = p2; }
public <R,A> R accept(rholang.parsing.delimc.Absyn.TType.Visitor<R,A> v, A arg) { return v.visit(this, arg); }
public boolean equals(Object o) {
if (this == o) return true;
if (o instanceof rholang.parsing.delimc.Absyn.TType2) {
rholang.parsing.delimc.Absyn.TType2 x = (rholang.parsing.delimc.Absyn.TType2)o;
return this.type_1.equals(x.type_1) && this.type_2.equals(x.type_2);
}
return false;
}
public int hashCode() {
return 37*(this.type_1.hashCode())+this.type_2.hashCode();
}
}
| rchain/Rholang | src/main/java/rholang/parsing/delimc/Absyn/TType2.java | Java | mit | 753 |
require 'rubygems'
require 'test/unit'
require 'shoulda'
$LOAD_PATH.unshift(File.join(File.dirname(__FILE__), '..', 'lib'))
$LOAD_PATH.unshift(File.dirname(__FILE__))
require 'sinatra'
require 'sinatra/path'
class Test::Unit::TestCase
end
| JunKikuchi/sinatra-path | test/helper.rb | Ruby | mit | 241 |
"use strict"
const createTileGridConverter = require(`./createTileGridConverter`)
const colorDepth = require(`./colorDepth`)
module.exports = ({palette, images}) => {
const converter = createTileGridConverter({
tileWidth: 7,
tileHeight: 9,
columns: 19,
tileCount: 95,
raw32bitData: colorDepth.convert8to32({palette, raw8bitData: images}),
})
return {
convertToPng: converter.convertToPng
}
} | chuckrector/mappo | src/converter/createVerge1SmallFntConverter.js | JavaScript | mit | 426 |
# -*- coding: utf-8 -*-
"""urls.py: messages extends"""
from django.conf.urls import url
from messages_extends.views import message_mark_all_read, message_mark_read
urlpatterns = [
url(r'^mark_read/(?P<message_id>\d+)/$', message_mark_read, name='message_mark_read'),
url(r'^mark_read/all/$', message_mark_all_read, name='message_mark_all_read'),
]
| AliLozano/django-messages-extends | messages_extends/urls.py | Python | mit | 358 |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
$(document).ready(function(){
var oldAction = $('#comment-form').attr("action");
hljs.initHighlightingOnLoad();
$('#coolness div').hover(function(){
$('#coolness .second').fadeOut(500);
}, function(){
$('#coolness .second').fadeIn(1000).stop(false, true);
});
$(".reply a").click(function() {
var add = this.className;
var action = oldAction + '/' + add;
$("#comment-form").attr("action", action);
console.log($('#comment-form').attr("action"));
});
});
| mzj/yabb | src/MZJ/YabBundle/Resources/public/js/bootstrap.js | JavaScript | mit | 683 |
#include "Sound.h"
#include <Windows.h>
#include "DigitalGraffiti.h"
Sound::Sound(void)
{
// Find music and sound files
std::string exeDir = DigitalGraffiti::getExeDirectory();
DigitalGraffiti::getFileList(exeDir + "\\sound\\instructions\\*", instructionsMusicList);
DigitalGraffiti::getFileList(exeDir + "\\sound\\cleanup\\*", cleanupMusicList);
DigitalGraffiti::getFileList(exeDir + "\\sound\\splat\\*", splatSoundList);
instructionsCounter = 0;
cleanupCounter = 0;
splatCounter = 0;
numInstructions= instructionsMusicList.size();
numCleanup = cleanupMusicList.size();
numSplat = splatSoundList.size();
if(DigitalGraffiti::DEBUG)
{
printf("Sound directory is: %s\n", exeDir.c_str());
printf("\tnumInstructions = %u\n", numInstructions);
printf("\tnumCleanup = %u\n", numCleanup);
printf("\tnumSplat = %u\n", numSplat);
}
}
void Sound::playInstructionsMusic(void)
{
if(numInstructions > 0)
{
if(DigitalGraffiti::DEBUG)
{
printf("Play %s\n", instructionsMusicList[instructionsCounter].c_str());
}
PlaySound(TEXT(instructionsMusicList[instructionsCounter].c_str()), NULL, SND_FILENAME | SND_ASYNC| SND_NOWAIT);
instructionsCounter = (instructionsCounter + 1) % numInstructions;
}
}
void Sound::playCleanupMusic(void)
{
if(numCleanup > 0)
{
if(DigitalGraffiti::DEBUG)
{
printf("Play %s\n", cleanupMusicList[cleanupCounter].c_str());
}
PlaySound(TEXT(cleanupMusicList[cleanupCounter].c_str()), NULL, SND_FILENAME | SND_ASYNC| SND_NOWAIT);
cleanupCounter = (cleanupCounter + 1) % numCleanup;
}
}
void Sound::playSplatSound(void)
{
if(numSplat > 0)
{
if(DigitalGraffiti::DEBUG)
{
printf("Play %s\n", splatSoundList[splatCounter].c_str());
}
PlaySound(TEXT(splatSoundList[splatCounter].c_str()), NULL, SND_FILENAME | SND_ASYNC| SND_NOWAIT);
splatCounter = (splatCounter + 1) % numSplat;
}
} | nbbrooks/digital-graffiti | DigitalGraffiti/Sound.cpp | C++ | mit | 1,924 |
using System.Collections.ObjectModel;
using AppStudio.Common;
using AppStudio.Common.Navigation;
using Windows.UI.Xaml;
namespace WindowsAppStudio.Navigation
{
public abstract class NavigationNode : ObservableBase
{
private bool _isSelected;
public string Title { get; set; }
public string Label { get; set; }
public abstract bool IsContainer { get; }
public bool IsSelected
{
get
{
return _isSelected;
}
set
{
SetProperty(ref _isSelected, value);
}
}
public abstract void Selected();
}
public class ItemNavigationNode : NavigationNode, INavigable
{
public override bool IsContainer
{
get
{
return false;
}
}
public NavigationInfo NavigationInfo { get; set; }
public override void Selected()
{
NavigationService.NavigateTo(this);
}
}
public class GroupNavigationNode : NavigationNode
{
private Visibility _visibility;
public GroupNavigationNode()
{
Nodes = new ObservableCollection<NavigationNode>();
}
public override bool IsContainer
{
get
{
return true;
}
}
public ObservableCollection<NavigationNode> Nodes { get; set; }
public Visibility Visibility
{
get { return _visibility; }
set { SetProperty(ref _visibility, value); }
}
public override void Selected()
{
if (Visibility == Visibility.Collapsed)
{
Visibility = Visibility.Visible;
}
else
{
Visibility = Visibility.Collapsed;
}
}
}
}
| wasteam/WindowsAppStudioApp | WindowsAppStudio.W10/Navigation/NavigationNode.cs | C# | mit | 2,027 |
// This file auto generated by plugin for ida pro. Generated code only for x64. Please, dont change manually
#pragma once
#include <common/common.h>
#include <CRecallRequest.hpp>
START_ATF_NAMESPACE
namespace Info
{
using CRecallRequestctor_CRecallRequest2_ptr = void (WINAPIV*)(struct CRecallRequest*, uint16_t);
using CRecallRequestctor_CRecallRequest2_clbk = void (WINAPIV*)(struct CRecallRequest*, uint16_t, CRecallRequestctor_CRecallRequest2_ptr);
using CRecallRequestClear4_ptr = void (WINAPIV*)(struct CRecallRequest*);
using CRecallRequestClear4_clbk = void (WINAPIV*)(struct CRecallRequest*, CRecallRequestClear4_ptr);
using CRecallRequestClose6_ptr = void (WINAPIV*)(struct CRecallRequest*, bool);
using CRecallRequestClose6_clbk = void (WINAPIV*)(struct CRecallRequest*, bool, CRecallRequestClose6_ptr);
using CRecallRequestGetID8_ptr = uint16_t (WINAPIV*)(struct CRecallRequest*);
using CRecallRequestGetID8_clbk = uint16_t (WINAPIV*)(struct CRecallRequest*, CRecallRequestGetID8_ptr);
using CRecallRequestGetOwner10_ptr = struct CPlayer* (WINAPIV*)(struct CRecallRequest*);
using CRecallRequestGetOwner10_clbk = struct CPlayer* (WINAPIV*)(struct CRecallRequest*, CRecallRequestGetOwner10_ptr);
using CRecallRequestIsBattleModeUse12_ptr = bool (WINAPIV*)(struct CRecallRequest*);
using CRecallRequestIsBattleModeUse12_clbk = bool (WINAPIV*)(struct CRecallRequest*, CRecallRequestIsBattleModeUse12_ptr);
using CRecallRequestIsClose14_ptr = bool (WINAPIV*)(struct CRecallRequest*);
using CRecallRequestIsClose14_clbk = bool (WINAPIV*)(struct CRecallRequest*, CRecallRequestIsClose14_ptr);
using CRecallRequestIsRecallAfterStoneState16_ptr = bool (WINAPIV*)(struct CRecallRequest*);
using CRecallRequestIsRecallAfterStoneState16_clbk = bool (WINAPIV*)(struct CRecallRequest*, CRecallRequestIsRecallAfterStoneState16_ptr);
using CRecallRequestIsRecallParty18_ptr = bool (WINAPIV*)(struct CRecallRequest*);
using CRecallRequestIsRecallParty18_clbk = bool (WINAPIV*)(struct CRecallRequest*, CRecallRequestIsRecallParty18_ptr);
using CRecallRequestIsTimeOut20_ptr = bool (WINAPIV*)(struct CRecallRequest*);
using CRecallRequestIsTimeOut20_clbk = bool (WINAPIV*)(struct CRecallRequest*, CRecallRequestIsTimeOut20_ptr);
using CRecallRequestIsWait22_ptr = bool (WINAPIV*)(struct CRecallRequest*);
using CRecallRequestIsWait22_clbk = bool (WINAPIV*)(struct CRecallRequest*, CRecallRequestIsWait22_ptr);
using CRecallRequestRecall24_ptr = char (WINAPIV*)(struct CRecallRequest*, struct CPlayer*, bool);
using CRecallRequestRecall24_clbk = char (WINAPIV*)(struct CRecallRequest*, struct CPlayer*, bool, CRecallRequestRecall24_ptr);
using CRecallRequestRegist26_ptr = char (WINAPIV*)(struct CRecallRequest*, struct CPlayer*, struct CCharacter*, bool, bool, bool);
using CRecallRequestRegist26_clbk = char (WINAPIV*)(struct CRecallRequest*, struct CPlayer*, struct CCharacter*, bool, bool, bool, CRecallRequestRegist26_ptr);
using CRecallRequestdtor_CRecallRequest30_ptr = void (WINAPIV*)(struct CRecallRequest*);
using CRecallRequestdtor_CRecallRequest30_clbk = void (WINAPIV*)(struct CRecallRequest*, CRecallRequestdtor_CRecallRequest30_ptr);
}; // end namespace Info
END_ATF_NAMESPACE
| goodwinxp/Yorozuya | library/ATF/CRecallRequestInfo.hpp | C++ | mit | 3,442 |
class DiscountTechnicalTypesController < ApplicationController
before_action :set_discount_technical_type, only: [:show, :edit, :update, :destroy]
# GET /discount_technical_types
# GET /discount_technical_types.json
def index
@discount_technical_types = DiscountTechnicalType.all
end
# GET /discount_technical_types/1
# GET /discount_technical_types/1.json
def show
end
# GET /discount_technical_types/new
def new
@discount_technical_type = DiscountTechnicalType.new
end
# GET /discount_technical_types/1/edit
def edit
end
# POST /discount_technical_types
# POST /discount_technical_types.json
def create
@discount_technical_type = DiscountTechnicalType.new(discount_technical_type_params)
respond_to do |format|
if @discount_technical_type.save
format.html { redirect_to @discount_technical_type, notice: 'Discount technical type was successfully created.' }
format.json { render :show, status: :created, location: @discount_technical_type }
else
format.html { render :new }
format.json { render json: @discount_technical_type.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /discount_technical_types/1
# PATCH/PUT /discount_technical_types/1.json
def update
respond_to do |format|
if @discount_technical_type.update(discount_technical_type_params)
format.html { redirect_to @discount_technical_type, notice: 'Discount technical type was successfully updated.' }
format.json { render :show, status: :ok, location: @discount_technical_type }
else
format.html { render :edit }
format.json { render json: @discount_technical_type.errors, status: :unprocessable_entity }
end
end
end
# DELETE /discount_technical_types/1
# DELETE /discount_technical_types/1.json
def destroy
@discount_technical_type.destroy
respond_to do |format|
format.html { redirect_to discount_technical_types_url, notice: 'Discount technical type was successfully destroyed.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_discount_technical_type
@discount_technical_type = DiscountTechnicalType.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def discount_technical_type_params
params.require(:discount_technical_type).permit(:value)
end
end
| maxjuniorbr/mobSeg | app/controllers/discount_technical_types_controller.rb | Ruby | mit | 2,523 |
using System.Net.Sockets;
namespace VidereLib.EventArgs
{
/// <summary>
/// EventArgs for the OnClientConnected event.
/// </summary>
public class OnClientConnectedEventArgs : System.EventArgs
{
/// <summary>
/// The connected client.
/// </summary>
public TcpClient Client { private set; get; }
/// <summary>
/// Constructor.
/// </summary>
/// <param name="client">The connected client.</param>
public OnClientConnectedEventArgs( TcpClient client )
{
this.Client = client;
}
}
}
| Wolf-Code/Videre | Videre/VidereLib/EventArgs/OnClientConnectedEventArgs.cs | C# | mit | 610 |
require 'rubygems'
require 'net/dns'
module Reedland
module Command
class Host
def self.run(address)
regular = Net::DNS::Resolver.start address.join(" ")
mx = Net::DNS::Resolver.new.search(address.join(" "), Net::DNS::MX)
return "#{regular}\n#{mx}"
end
end
end
end | reedphish/discord-reedland | commands/host.rb | Ruby | mit | 291 |
(function(Object) {
Object.Model.Background = Object.Model.PresentationObject.extend({
"initialize" : function() {
Object.Model.PresentationObject.prototype.initialize.call(this);
}
},{
"type" : "Background",
"attributes" : _.defaults({
"skybox" : {
"type" : "res-texture",
"name" : "skybox",
"_default" : ""
},
"name" : {
"type" : "string",
"_default" : "new Background",
"name" : "name"
}
}, Object.Model.PresentationObject.attributes)
});
}(sp.module("object"))); | larsrohwedder/scenepoint | client_src/modules/object/model/Background.js | JavaScript | mit | 532 |
<?php
namespace HsBundle;
use HsBundle\DependencyInjection\Compiler\ReportsCompilerPass;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\HttpKernel\Bundle\Bundle;
class HsBundle extends Bundle
{
public function build(ContainerBuilder $container)
{
parent::build($container);
$container->addCompilerPass(new ReportsCompilerPass());
}
}
| deregenboog/ecd | src/HsBundle/HsBundle.php | PHP | mit | 401 |
import './Modal.scss'
import pugTpl from './Modal.pug'
import mixin from '../../mixin'
import alert from '@vue2do/component/module/Modal/alert'
import confirm from '@vue2do/component/module/Modal/confirm'
export default {
name: 'PageCompModal',
template: pugTpl(),
mixins: [mixin],
data() {
return {
testName: 'test'
}
},
methods: {
simple() {
this.$refs.simple.show()
},
alert() {
alert({
message: '这是一个警告弹窗',
theme: this.typeTheme,
ui: this.typeUI
})
},
confirm() {
confirm({
message: '这是一个确认弹窗',
title: '测试确认弹出',
theme: 'danger',
ui: 'bootstrap'
})
},
showFullPop() {
this.$refs.fullPop.show()
},
hideFullPop() {
this.$refs.fullPop.hide()
},
showPureModal() {
this.$refs.pureModal.show()
},
hidePureModal() {
this.$refs.pureModal.hide()
}
}
}
| zen0822/vue2do | app/doc/client/component/page/Component/message/Modal/Modal.js | JavaScript | mit | 995 |
package com.igonics.transformers.simple;
import java.io.PrintStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.DefaultParser;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
import org.relique.jdbc.csv.CsvDriver;
import com.igonics.transformers.simple.helpers.CSVDirWalker;
import com.igonics.transformers.simple.helpers.CSVLogger;
/**
* @author gggordon <https://github.com/gggordon>
* @version 1.0.0
* @description Transforms sub-directories of similar CSV files into one database file
* @created 1.11.2015
*
* */
public class JavaCSVTransform {
/**
* @param baseDir Base Directory to Check for CSV Files
* @param dbFile Database File Name or Path
* @param subDirectoryDepth Recursive Depth to check for CSV Files. -1 will recurse indefinitely
* @param keepTemporaryFile Keep Temporary Buffer File or Delete
* */
public void createCSVDatabase(String baseDir, String dbFile,int subDirectoryDepth,boolean keepTemporaryFile){
final String BASE_DIR =baseDir==null? System.getProperty("user.dir") + "\\dataFiles" : baseDir;
final String DB_FILE = dbFile==null?"DB-" + System.currentTimeMillis() + ".csv":dbFile;
long startTime = System.currentTimeMillis();
CSVLogger.info("Base Dir : " + BASE_DIR);
try {
CSVDirWalker dirWalker = new CSVDirWalker(BASE_DIR, subDirectoryDepth);
//Process Directories
dirWalker.start();
CSVLogger.debug("Column Names : " + dirWalker.getHeader());
CSVLogger.info("Temporary Buffer File Complete. Starting Database Queries");
// Writing to database
// Load the driver.
Class.forName("org.relique.jdbc.csv.CsvDriver");
// Create a connection. The first command line parameter is the directory containing the .csv files.
Connection conn = DriverManager.getConnection("jdbc:relique:csv:"
+ System.getProperty("user.dir"));
// Create a Statement object to execute the query with.
Statement stmt = conn.createStatement();
ResultSet results = stmt.executeQuery("SELECT * FROM "
+ dirWalker.getTempBufferPath().replaceAll(".csv", ""));
CSVLogger.info("Retrieved Records From Temporary File");
// Dump out the results to a CSV file with the same format
// using CsvJdbc helper function
CSVLogger.info("Writing Records to database file");
long databaseSaveStartTime = System.currentTimeMillis();
//Create redirect stream to database file
PrintStream printStream = new PrintStream(DB_FILE);
//print column headings
printStream.print(dirWalker.getHeader()+System.lineSeparator());
CsvDriver.writeToCsv(results, printStream, false);
CSVLogger.info("Time taken to save records to database (ms): "+(System.currentTimeMillis() - databaseSaveStartTime));
//delete temporary file
if(!keepTemporaryFile){
CSVLogger.info("Removing Temporary File");
dirWalker.removeTemporaryFile();
}
//Output Program Execution Completed
CSVLogger.info("Total execution time (ms) : "
+ (System.currentTimeMillis() - startTime)
+ " | Approx Size (bytes) : "
+ dirWalker.getTotalBytesRead());
} catch (Exception ioe) {
CSVLogger.error(ioe.getMessage(), ioe);
}
}
// TODO: Modularize Concepts
public static void main(String args[]) {
//Parse Command Line Options
Options opts = new Options();
HelpFormatter formatter = new HelpFormatter();
opts.addOption("d", "dir", false, "Base Directory of CSV files. Default : Current Directory");
opts.addOption("db", "database", false, "Database File Name. Default DB-{timestamp}.csv");
opts.addOption("depth", "depth", false, "Recursive Depth. Set -1 to recurse indefintely. Default : -1");
opts.addOption("keepTemp",false,"Keeps Temporary file. Default : false");
opts.addOption("h", "help", false, "Display Help");
try {
CommandLine cmd = new DefaultParser().parse(opts,args);
if(cmd.hasOption("h") || cmd.hasOption("help")){
formatter.printHelp( "javacsvtransform", opts );
return;
}
//Create CSV Database With Command Line Options or Defaults
new JavaCSVTransform().createCSVDatabase(cmd.getOptionValue("d"), cmd.getOptionValue("db"),Integer.parseInt(cmd.getOptionValue("depth", "-1")), cmd.hasOption("keepTemp"));
} catch (ParseException e) {
formatter.printHelp( "javacsvtransform", opts );
}
}
}
| gggordon/JavaCSVTransform | src/com/igonics/transformers/simple/JavaCSVTransform.java | Java | mit | 4,527 |
/*
* JDIVisitor
* Copyright (C) 2014 Adrian Herrera
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
package org.jdivisitor.debugger.launcher;
import java.net.InetSocketAddress;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang3.Validate;
import com.sun.jdi.Bootstrap;
import com.sun.jdi.VirtualMachine;
import com.sun.jdi.connect.AttachingConnector;
import com.sun.jdi.connect.Connector;
/**
* Attach (via a socket) to a listening virtual machine in debug mode.
*
* @author Adrian Herrera
*
*/
public class RemoteVMConnector extends VMConnector {
/**
* Socket connection details.
*/
private final InetSocketAddress socketAddress;
/**
* Constructor.
*
* @param hostname Name of the host to connect to
* @param port Port number the virtual machine is listening on
*/
public RemoteVMConnector(String hostname, int port) {
this(new InetSocketAddress(hostname, port));
}
/**
* Constructor.
*
* @param sockAddr Socket address structure to connect to.
*/
public RemoteVMConnector(InetSocketAddress sockAddr) {
socketAddress = Validate.notNull(sockAddr);
}
@Override
public VirtualMachine connect() throws Exception {
List<AttachingConnector> connectors = Bootstrap.virtualMachineManager()
.attachingConnectors();
AttachingConnector connector = findConnector(
"com.sun.jdi.SocketAttach", connectors);
Map<String, Connector.Argument> arguments = connectorArguments(connector);
VirtualMachine vm = connector.attach(arguments);
// TODO - redirect stdout and stderr?
return vm;
}
/**
* Set the socket-attaching connector's arguments.
*
* @param connector A socket-attaching connector
* @return The socket-attaching connector's arguments
*/
private Map<String, Connector.Argument> connectorArguments(
AttachingConnector connector) {
Map<String, Connector.Argument> arguments = connector
.defaultArguments();
arguments.get("hostname").setValue(socketAddress.getHostName());
arguments.get("port").setValue(
Integer.toString(socketAddress.getPort()));
return arguments;
}
}
| adrianherrera/jdivisitor | src/main/java/org/jdivisitor/debugger/launcher/RemoteVMConnector.java | Java | mit | 2,991 |
# The MIT License (MIT)
#
# Copyright (c) 2016 Frederic Guillot
#
# 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.
from cliff import app
from cliff import commandmanager
from pbr import version as app_version
import sys
from kanboard_cli.commands import application
from kanboard_cli.commands import project
from kanboard_cli.commands import task
from kanboard_cli import client
class KanboardShell(app.App):
def __init__(self):
super(KanboardShell, self).__init__(
description='Kanboard Command Line Client',
version=app_version.VersionInfo('kanboard_cli').version_string(),
command_manager=commandmanager.CommandManager('kanboard.cli'),
deferred_help=True)
self.client = None
self.is_super_user = True
def build_option_parser(self, description, version, argparse_kwargs=None):
parser = super(KanboardShell, self).build_option_parser(
description, version, argparse_kwargs=argparse_kwargs)
parser.add_argument(
'--url',
metavar='<api url>',
help='Kanboard API URL',
)
parser.add_argument(
'--username',
metavar='<api username>',
help='API username',
)
parser.add_argument(
'--password',
metavar='<api password>',
help='API password/token',
)
parser.add_argument(
'--auth-header',
metavar='<authentication header>',
help='API authentication header',
)
return parser
def initialize_app(self, argv):
client_manager = client.ClientManager(self.options)
self.client = client_manager.get_client()
self.is_super_user = client_manager.is_super_user()
self.command_manager.add_command('app version', application.ShowVersion)
self.command_manager.add_command('app timezone', application.ShowTimezone)
self.command_manager.add_command('project show', project.ShowProject)
self.command_manager.add_command('project list', project.ListProjects)
self.command_manager.add_command('task create', task.CreateTask)
self.command_manager.add_command('task list', task.ListTasks)
def main(argv=sys.argv[1:]):
return KanboardShell().run(argv)
if __name__ == '__main__':
sys.exit(main(sys.argv[1:]))
| kanboard/kanboard-cli | kanboard_cli/shell.py | Python | mit | 3,401 |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace cShART
{
public class ARTFlystick : ARTObject
{
private bool visible;
private int numberOfButtons;
private int numberOfControllers;
private int buttonStates;
private float[] controllerStates;
public static ARTFlystick Empty()
{
return new ARTFlystick(-1, false, 0, 0, 0, new float[0], ARTPoint.Empty(), ARTMatrix.Empty());
}
public ARTFlystick(int id, bool visible, int numberOfButtons, int buttonStates, int numberOfControllers, float[] controllerStates, ARTPoint position, ARTMatrix matrix) : base(id, position, matrix)
{
this.visible = visible;
this.numberOfButtons = numberOfButtons;
this.numberOfControllers = numberOfControllers;
this.buttonStates = buttonStates;
this.controllerStates = controllerStates;
}
public bool isVisible()
{
return this.visible;
}
public int getNumberOfButtons()
{
return this.numberOfButtons;
}
public int getNumberOfControllers()
{
return this.numberOfControllers;
}
public int getButtonStates()
{
return this.buttonStates;
}
/// <summary>
/// This Method translates the button states integer into actual english for better handling.
/// (aka tells you which button is currently pushed.) Useful for debugging.
/// </summary>
/// <returns>Returns a string containing names of pushed buttons</returns>
public String getPushedButtonsByName()
{
//Byte binBStates = Convert.ToByte(buttonStates);
// BitArray BA = new BitArray(binBStates);
//int[] StatesArray = new int[]{buttonStates};
//Array.Reverse(StatesArray);
BitArray binBStates = new BitArray(new int[]{buttonStates});
String output = "";
//byte[] binBStates = BitConverter.GetBytes(buttonStates);
if (binBStates[3])
{
output = output + "LeftButton";
}
if (binBStates[2])
{
if (!output.Equals(""))
{
output = output + "/";
}
output = output + "MiddleButton";
}
if (binBStates[1])
{
if (!output.Equals(""))
{
output = output + "/";
}
output = output + "RightButton";
}
if (binBStates[0])
{
if (!output.Equals(""))
{
output = output + "/";
}
output = output + "Trigger";
}
if (output == "")
{
output = "NothingPressed";
}
return output + " Byte: " + binBStates.ToString();
}
/// <summary>
/// This method is for further button handling of the flystick. You will receive a bit array which represents the currently pushed buttons.
/// Array value and corresponding buttons are:
/// [0] = Trigger
/// [1] = Right button
/// [2] = Middle button
/// [3] = Left button
/// </summary>
/// <returns>Returns a bit array represting currently pushed buttons</returns>
public BitArray GetStateArrayOfButtons()
{
return new BitArray(new int[]{buttonStates});
}
public float[] GetStickXYPos()
{
return this.controllerStates;
}
override protected String nameToString()
{
return "ARTFlystick";
}
protected String controllerStatesToString()
{
String res = "";
for (int i = 0; i < this.controllerStates.Length; i++)
{
res = res + this.controllerStates[i];
if (i + 1 < this.controllerStates.Length)
{
res = res + ", ";
}
}
return res;
}
override protected String extensionsToString()
{
return "isVisible: " + isVisible() + Environment.NewLine + "numberOfButtons: " + getNumberOfButtons() + ", buttonStates: " + getButtonStates() + Environment.NewLine + "numberOfControllers: " + getNumberOfControllers() + ", controllerStates: " + controllerStatesToString() + Environment.NewLine;
}
}
}
| schMarXman/cShART | ARTFlystick.cs | C# | mit | 4,744 |
using System;
using System.Text.RegularExpressions;
namespace _07_Hideout
{
class Hideout
{
static void Main()
{
string input = Console.ReadLine();
while (true)
{
string[] parameters = Console.ReadLine().Split();
string key = Regex.Escape(parameters[0]);
string pattern = @"(" + key + "{" + parameters[1] + ",})";
Regex r = new Regex(pattern);
Match match = r.Match(input);
if (match.Success)
{
Console.WriteLine("Hideout found at index {0} and it is with size {1}!", match.Index, match.Groups[0].Length);
break;
}
}
}
}
}
| nellypeneva/SoftUniProjects | 01_ProgrFundamentalsMay/32_Strings-and-Regular-Expressions-More-Exercises/07_Hideout/Hideout.cs | C# | mit | 795 |
using System.ComponentModel.DataAnnotations;
namespace JezekT.AspNetCore.IdentityServer4.WebApp.Models.AccountSettingsViewModels
{
public class ConfirmEmailViewModel
{
[Display(Name = "Email", ResourceType = typeof(Resources.Models.AccountSettingsViewModels.ConfirmEmailViewModel))]
public string Email { get; set; }
}
}
| jezekt/AspNetCore | JezekT.AspNetCore.IdentityServer4.WebApp/Models/AccountSettingsViewModels/ConfirmEmailViewModel.cs | C# | mit | 354 |
"use strict";
var i = 180; //3分固定
function count(){
if(i <= 0){
document.getElementById("output").innerHTML = "完成!";
}else{
document.getElementById("output").innerHTML = i + "s";
}
i -= 1;
}
window.onload = function(){
setInterval("count()", 1000);
}; | Shin-nosukeSaito/elctron_app | ramen.js | JavaScript | mit | 280 |
#include <fstream>
#include <iostream>
#include <vector>
int main(int argc, char **argv) {
std::vector<std::string> args(argv, argv + argc);
std::ofstream tty;
tty.open("/dev/tty");
if (args.size() <= 1 || (args.size() & 2) == 1) {
std::cerr << "usage: maplabel [devlocal remote]... remotedir\n";
return 1;
}
std::string curdir = args[args.size() - 1];
for (size_t i = 1; i + 1 < args.size(); i += 2) {
if (curdir.find(args[i + 1]) == 0) {
if ((curdir.size() > args[i + 1].size() &&
curdir[args[i + 1].size()] == '/') ||
curdir.size() == args[i + 1].size()) {
tty << "\033];" << args[i] + curdir.substr(args[i + 1].size())
<< "\007\n";
return 0;
}
}
}
tty << "\033];" << curdir << "\007\n";
return 0;
}
| uluyol/tools | maplabel/main.cc | C++ | mit | 804 |
package com.catsprogrammer.catsfourthv;
/**
* Created by C on 2016-09-14.
*/
public class MatrixCalculator {
public static float[] getRotationMatrixFromOrientation(float[] o) {
float[] xM = new float[9];
float[] yM = new float[9];
float[] zM = new float[9];
float sinX = (float) Math.sin(o[1]);
float cosX = (float) Math.cos(o[1]);
float sinY = (float) Math.sin(o[2]);
float cosY = (float) Math.cos(o[2]);
float sinZ = (float) Math.sin(o[0]);
float cosZ = (float) Math.cos(o[0]);
// rotation about x-axis (pitch)
xM[0] = 1.0f;
xM[1] = 0.0f;
xM[2] = 0.0f;
xM[3] = 0.0f;
xM[4] = cosX;
xM[5] = sinX;
xM[6] = 0.0f;
xM[7] = -sinX;
xM[8] = cosX;
// rotation about y-axis (roll)
yM[0] = cosY;
yM[1] = 0.0f;
yM[2] = sinY;
yM[3] = 0.0f;
yM[4] = 1.0f;
yM[5] = 0.0f;
yM[6] = -sinY;
yM[7] = 0.0f;
yM[8] = cosY;
// rotation about z-axis (azimuth)
zM[0] = cosZ;
zM[1] = sinZ;
zM[2] = 0.0f;
zM[3] = -sinZ;
zM[4] = cosZ;
zM[5] = 0.0f;
zM[6] = 0.0f;
zM[7] = 0.0f;
zM[8] = 1.0f;
// rotation order is y, x, z (roll, pitch, azimuth)
float[] resultMatrix = matrixMultiplication(xM, yM);
resultMatrix = matrixMultiplication(zM, resultMatrix); //????????????????왜?????????????
return resultMatrix;
}
public static float[] matrixMultiplication(float[] A, float[] B) {
float[] result = new float[9];
result[0] = A[0] * B[0] + A[1] * B[3] + A[2] * B[6];
result[1] = A[0] * B[1] + A[1] * B[4] + A[2] * B[7];
result[2] = A[0] * B[2] + A[1] * B[5] + A[2] * B[8];
result[3] = A[3] * B[0] + A[4] * B[3] + A[5] * B[6];
result[4] = A[3] * B[1] + A[4] * B[4] + A[5] * B[7];
result[5] = A[3] * B[2] + A[4] * B[5] + A[5] * B[8];
result[6] = A[6] * B[0] + A[7] * B[3] + A[8] * B[6];
result[7] = A[6] * B[1] + A[7] * B[4] + A[8] * B[7];
result[8] = A[6] * B[2] + A[7] * B[5] + A[8] * B[8];
return result;
}
}
| CatsProject/CycleAssistantTools | mobile/src/main/java/com/catsprogrammer/catsfourthv/MatrixCalculator.java | Java | mit | 2,238 |
import { browser, by, element } from 'protractor';
export class Angular2Page {
navigateTo() {
return browser.get('/');
}
getParagraphText() {
return element(by.css('app-root h1')).getText();
}
}
| deepak1725/django-angular4 | users/static/ngApp/angular2/e2e/app.po.ts | TypeScript | mit | 213 |
<!-- START LEFT SIDEBAR NAV-->
<?php
$role = "";
switch($this->session->userdata('ROLE_ID')){
case 1:
$role = "Administrator";
break;
case 2:
$role = "Adopting Parent";
break;
case 3:
$role = "Biological Parent/Guardian";
break;
}
?>
<aside id="left-sidebar-nav">
<ul id="slide-out" class="side-nav fixed leftside-navigation">
<li class="user-details cyan darken-2">
<div class="row">
<div class="col col s4 m4 l4">
<img src="<?=base_url();?>assets/images/profile.png" alt="" class="circle responsive-img valign profile-image">
</div>
<div class="col col s8 m8 l8">
<a class="btn-flat dropdown-button waves-effect waves-light white-text profile-btn" href="#" data-activates="profile-dropdown"><?=$this->session->userdata('NAME');?></a>
<p class="user-roal"><?=$role;?></p>
</div>
</div>
</li>
<li class="bold"><a href="<?=base_url();?>front/adopting_parent" class="waves-effect waves-cyan"><i class="mdi-action-dashboard"></i> Dashboard</a>
</li>
<li class="bold"><a href="<?=base_url();?>front/personal_details" class="waves-effect waves-cyan"><i class="mdi-content-content-paste"></i> Personal Details</a>
</li>
<li class="bold"><a href="<?=base_url();?>front/search_child" class="waves-effect waves-cyan"><i class="mdi-action-search"></i> Search Child</a>
</li>
<li class="no-padding">
<ul class="collapsible collapsible-accordion">
<li class="bold"><a class="collapsible-header waves-effect waves-cyan"><i class="mdi-communication-chat"></i> Meetings</a>
<div class="collapsible-body">
<ul>
<li><a href="<?=base_url();?>front/search_child">Setup a Meeting</a>
</li>
<li><a href="<?=base_url();?>front/past_meetings">Past Meetings</a>
</li>
</ul>
</div>
</li>
<li class="bold"><a class="collapsible-header waves-effect waves-cyan"><i class="mdi-editor-vertical-align-bottom"></i> Adoption</a>
<div class="collapsible-body">
<ul>
<li><a href="<?=base_url();?>front/adoption">Create Request</a>
</li>
<li><a href="<?=base_url();?>front/past_adoptions">Past Requests</a>
</li>
</ul>
</div>
</li>
</ul>
</li>
</ul>
</aside>
<!-- END LEFT SIDEBAR NAV--> | ushangt/FosterCare | application/views/front/adopting_parent/menu.php | PHP | mit | 2,980 |
package es.sandbox.ui.messages.argument;
import es.sandbox.ui.messages.resolver.MessageResolver;
import es.sandbox.ui.messages.resolver.Resolvable;
import java.util.ArrayList;
import java.util.List;
class LinkArgument implements Link, Resolvable {
private static final String LINK_FORMAT = "<a href=\"%s\" title=\"%s\" class=\"%s\">%s</a>";
private static final String LINK_FORMAT_WITHOUT_CSS_CLASS = "<a href=\"%s\" title=\"%s\">%s</a>";
private String url;
private Text text;
private String cssClass;
public LinkArgument(String url) {
url(url);
}
private void assertThatUrlIsValid(String url) {
if (url == null) {
throw new NullPointerException("Link url can't be null");
}
if (url.trim().isEmpty()) {
throw new IllegalArgumentException("Link url can't be empty");
}
}
@Override
public LinkArgument url(String url) {
assertThatUrlIsValid(url);
this.url = url;
return this;
}
@Override
public LinkArgument title(Text text) {
this.text = text;
return this;
}
@Override
public LinkArgument title(String code, Object... arguments) {
this.text = new TextArgument(code, arguments);
return this;
}
@Override
public LinkArgument cssClass(String cssClass) {
this.cssClass = trimToNull(cssClass);
return this;
}
private static final String trimToNull(final String theString) {
if (theString == null) {
return null;
}
final String trimmed = theString.trim();
return trimmed.isEmpty() ? null : trimmed;
}
@Override
public String resolve(MessageResolver messageResolver) {
MessageResolver.assertThatIsNotNull(messageResolver);
return String.format(linkFormat(), arguments(messageResolver));
}
private String linkFormat() {
return this.cssClass == null ? LINK_FORMAT_WITHOUT_CSS_CLASS : LINK_FORMAT;
}
private Object[] arguments(MessageResolver messageResolver) {
final List<Object> arguments = new ArrayList<Object>();
final String title = resolveTitle(messageResolver);
arguments.add(this.url);
arguments.add(title == null ? this.url : title);
if (this.cssClass != null) {
arguments.add(this.cssClass);
}
arguments.add(title == null ? this.url : title);
return arguments.toArray(new Object[0]);
}
private String resolveTitle(MessageResolver messageResolver) {
return trimToNull(this.text == null ? null : ((Resolvable) this.text).resolve(messageResolver));
}
@Override
public String toString() {
return String.format("link{%s, %s, %s}", this.url, this.text, this.cssClass);
}
}
| jeslopalo/flash-messages | flash-messages-core/src/main/java/es/sandbox/ui/messages/argument/LinkArgument.java | Java | mit | 2,828 |
/*
Copyright 2011 Google Inc.
Modifications Copyright (c) 2014 Simon Zimmermann
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package blob
import (
"io"
)
// Fetcher is the minimal interface for retrieving a blob from storage.
// The full storage interface is blobserver.Storage.
type Fetcher interface {
// Fetch returns a blob. If the blob is not found then
// os.ErrNotExist should be returned for the error (not a wrapped
// error with a ErrNotExist inside)
//
// The caller should close blob.
Fetch(Ref) (blob io.ReadCloser, size uint32, err error)
}
| simonz05/blobserver | blob/fetcher.go | GO | mit | 1,050 |
module HTMLValidationHelpers
def bad_html
'<html><title>the title<title></head><body><p>blah blah</body></html>'
end
def good_html
html_5_doctype + '<html><title>the title</title></head><body><p>a paragraph</p></body></html>'
end
def dtd
'<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">'
end
def html_5_doctype
'<!DOCTYPE html>'
end
def warning_html
html_5_doctype + '<html><title proprietary="1">h</title></head><body><p>a para</p></body></html>'
end
end
| ericbeland/html_validation | spec/helpers/html_validation_helpers.rb | Ruby | mit | 576 |
using System.Xml.Serialization;
namespace ImgLab
{
[XmlRoot("source")]
public sealed class Source
{
[XmlElement("database")]
public string Database
{
get;
set;
}
}
} | takuya-takeuchi/DlibDotNet | tools/ImgLab/Source.cs | C# | mit | 263 |
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef pair<int,int> ii;
typedef vector<int> vi;
typedef vector<ii> vii;
int main () {
int n;
while(scanf("%d", &n) && n) {
bitset<32> bs,a,b;
bs = n;
int cont = 0;
for(int i = 0; i < 32; i++) {
if(bs.test(i)) {
if(cont%2) b.set(i);
else a.set(i);
cont++;
}
}
//int x = a;
printf("%u %u\n", a.to_ulong(), b.to_ulong());
}
return 0;
}
| matheuscarius/competitive-programming | uva/11933-2.cpp | C++ | mit | 491 |
describe Certificate do
it { is_expected.to have_property :id }
it { is_expected.to have_property :identifier }
it { is_expected.to have_property :image_key }
it { is_expected.to have_property :certificate_key }
it { is_expected.to have_property :created_at }
it { is_expected.to belong_to :delivery }
it { is_expected.to belong_to :student }
describe 'Creating a Certificate' do
before do
course = Course.create(title: 'Learn To Code 101', description: 'Introduction to programming')
delivery = course.deliveries.create(start_date: '2015-01-01')
student = delivery.students.create(full_name: 'Thomas Ochman', email: 'thomas@random.com')
@certificate = student.certificates.create(created_at: DateTime.now, delivery: delivery)
end
after { FileUtils.rm_rf Dir['pdf/test/**/*.pdf'] }
it 'adds an identifier after create' do
expect(@certificate.identifier.size).to eq 64
end
it 'has a Student name' do
expect(@certificate.student.full_name).to eq 'Thomas Ochman'
end
it 'has a Course name' do
expect(@certificate.delivery.course.title).to eq 'Learn To Code 101'
end
it 'has a Course delivery date' do
expect(@certificate.delivery.start_date.to_s).to eq '2015-01-01'
end
describe 'S3' do
before { CertificateGenerator.generate(@certificate) }
it 'can be fetched by #image_url' do
binding.pry
expect(@certificate.image_url).to eq 'https://certz.s3.amazonaws.com/pdf/test/thomas_ochman_2015-01-01.jpg'
end
it 'can be fetched by #certificate_url' do
expect(@certificate.certificate_url).to eq 'https://certz.s3.amazonaws.com/pdf/test/thomas_ochman_2015-01-01.pdf'
end
it 'returns #bitly_lookup' do
expect(@certificate.bitly_lookup).to eq "http://localhost:9292/verify/#{@certificate.identifier}"
end
it 'returns #stats' do
expect(@certificate.stats).to eq 0
end
end
end
end
| CraftAcademy/workshop | spec/certificate_spec.rb | Ruby | mit | 1,999 |
<?php
namespace OpenRailData\NetworkRail\Services\Stomp\Topics\Rtppm\Entities\Performance;
/**
* Class Performance
*
* @package OpenRailData\NetworkRail\Services\Stomp\Topics\Rtppm\Entities\Performance
*/
class Performance
{
/**
* @var int
*/
private $totalCount;
/**
* @var int
*/
private $onTimeCount;
/**
* @var int
*/
private $lateCount;
/**
* @var int
*/
private $cancelledOrVeryLateCount;
/**
* @var Ppm
*/
private $ppm;
/**
* @var RollingPpm
*/
private $rollingPpm;
public function __construct($data)
{
if (property_exists($data, "Total"))
$this->setTotalCount($data->Total);
if (property_exists($data, "OnTime"))
$this->setOnTimeCount($data->OnTime);
if (property_exists($data, "Late"))
$this->setLateCount($data->Late);
if (property_exists($data, "CancelVeryLate"))
$this->setCancelledOrVeryLateCount($data->CancelVeryLate);
if (property_exists($data, "PPM"))
$this->setPpm(new Ppm($data->PPM));
if (property_exists($data, "RollingPPM"))
$this->setRollingPpm(new RollingPpm($data->RollingPPM));
}
/**
* @return int
*/
public function getTotalCount()
{
return $this->totalCount;
}
/**
* @param int $totalCount
*
* @return $this;
*/
public function setTotalCount($totalCount)
{
$this->totalCount = (int)$totalCount;
return $this;
}
/**
* @return int
*/
public function getOnTimeCount()
{
return $this->onTimeCount;
}
/**
* @param int $onTimeCount
*
* @return $this;
*/
public function setOnTimeCount($onTimeCount)
{
$this->onTimeCount = (int)$onTimeCount;
return $this;
}
/**
* @return int
*/
public function getLateCount()
{
return $this->lateCount;
}
/**
* @param int $lateCount
*
* @return $this;
*/
public function setLateCount($lateCount)
{
$this->lateCount = (int)$lateCount;
return $this;
}
/**
* @return int
*/
public function getCancelledOrVeryLateCount()
{
return $this->cancelledOrVeryLateCount;
}
/**
* @param int $cancelledOrVeryLateCount
*
* @return $this;
*/
public function setCancelledOrVeryLateCount($cancelledOrVeryLateCount)
{
$this->cancelledOrVeryLateCount = (int)$cancelledOrVeryLateCount;
return $this;
}
/**
* @return Ppm
*/
public function getPpm()
{
return $this->ppm;
}
/**
* @param Ppm $ppm
*
* @return $this
*/
public function setPpm(Ppm $ppm)
{
$this->ppm = $ppm;
return $this;
}
/**
* @return RollingPpm
*/
public function getRollingPpm()
{
return $this->rollingPpm;
}
/**
* @param RollingPpm $rollingPpm
*
* @return $this
*/
public function setRollingPpm(RollingPpm $rollingPpm)
{
$this->rollingPpm = $rollingPpm;
return $this;
}
} | neilmcgibbon/php-open-rail-data | src/NetworkRail/Services/Stomp/Topics/Rtppm/Entities/Performance/Performance.php | PHP | mit | 3,258 |
import numpy as np
import matplotlib.pylab as plt
from numba import cuda, uint8, int32, uint32, jit
from timeit import default_timer as timer
@cuda.jit('void(uint8[:], int32, int32[:], int32[:])')
def lbp_kernel(input, neighborhood, powers, h):
i = cuda.grid(1)
r = 0
if i < input.shape[0] - 2 * neighborhood:
i += neighborhood
for j in range(i - neighborhood, i):
if input[j] >= input[i]:
r += powers[j - i + neighborhood]
for j in range(i + 1, i + neighborhood + 1):
if input[j] >= input[i]:
r += powers[j - i + neighborhood - 1]
cuda.atomic.add(h, r, 1)
def extract_1dlbp_gpu(input, neighborhood, d_powers):
maxThread = 512
blockDim = maxThread
d_input = cuda.to_device(input)
hist = np.zeros(2 ** (2 * neighborhood), dtype='int32')
gridDim = (len(input) - 2 * neighborhood + blockDim) / blockDim
d_hist = cuda.to_device(hist)
lbp_kernel[gridDim, blockDim](d_input, neighborhood, d_powers, d_hist)
d_hist.to_host()
return hist
def extract_1dlbp_gpu_debug(input, neighborhood, powers, res):
maxThread = 512
blockDim = maxThread
gridDim = (len(input) - 2 * neighborhood + blockDim) / blockDim
for block in range(0, gridDim):
for thread in range(0, blockDim):
r = 0
i = blockDim * block + thread
if i < input.shape[0] - 2 * neighborhood:
i += neighborhood
for j in range(i - neighborhood, i):
if input[j] >= input[i]:
r += powers[j - i + neighborhood]
for j in range(i + 1, i + neighborhood + 1):
if input[j] >= input[i]:
r += powers[j - i + neighborhood - 1]
res[r] += 1
return res
@jit("int32[:](uint8[:], int64, int32[:], int32[:])", nopython=True)
def extract_1dlbp_cpu_jit(input, neighborhood, powers, res):
maxThread = 512
blockDim = maxThread
gridDim = (len(input) - 2 * neighborhood + blockDim) / blockDim
for block in range(0, gridDim):
for thread in range(0, blockDim):
r = 0
i = blockDim * block + thread
if i < input.shape[0] - 2 * neighborhood:
i += neighborhood
for j in range(i - neighborhood, i):
if input[j] >= input[i]:
r += powers[j - i + neighborhood]
for j in range(i + 1, i + neighborhood + 1):
if input[j] >= input[i]:
r += powers[j - i + neighborhood - 1]
res[r] += 1
return res
def extract_1dlbp_cpu(input, neighborhood, p):
"""
Extract the 1d lbp pattern on CPU
"""
res = np.zeros(1 << (2 * neighborhood))
for i in range(neighborhood, len(input) - neighborhood):
left = input[i - neighborhood : i]
right = input[i + 1 : i + neighborhood + 1]
both = np.r_[left, right]
res[np.sum(p [both >= input[i]])] += 1
return res
X = np.arange(3, 7)
X = 10 ** X
neighborhood = 4
cpu_times = np.zeros(X.shape[0])
cpu_times_simple = cpu_times.copy()
cpu_times_jit = cpu_times.copy()
gpu_times = np.zeros(X.shape[0])
p = 1 << np.array(range(0, 2 * neighborhood), dtype='int32')
d_powers = cuda.to_device(p)
for i, x in enumerate(X):
input = np.random.randint(0, 256, size = x).astype(np.uint8)
print "Length: {0}".format(x)
print "--------------"
start = timer()
h_cpu = extract_1dlbp_cpu(input, neighborhood, p)
cpu_times[i] = timer() - start
print "Finished on CPU: time: {0:3.5f}s".format(cpu_times[i])
res = np.zeros(1 << (2 * neighborhood), dtype='int32')
start = timer()
h_cpu_simple = extract_1dlbp_gpu_debug(input, neighborhood, p, res)
cpu_times_simple[i] = timer() - start
print "Finished on CPU (simple): time: {0:3.5f}s".format(cpu_times_simple[i])
res = np.zeros(1 << (2 * neighborhood), dtype='int32')
start = timer()
h_cpu_jit = extract_1dlbp_cpu_jit(input, neighborhood, p, res)
cpu_times_jit[i] = timer() - start
print "Finished on CPU (numba: jit): time: {0:3.5f}s".format(cpu_times_jit[i])
start = timer()
h_gpu = extract_1dlbp_gpu(input, neighborhood, d_powers)
gpu_times[i] = timer() - start
print "Finished on GPU: time: {0:3.5f}s".format(gpu_times[i])
print "All h_cpu == h_gpu: ", (h_cpu_jit == h_gpu).all() and (h_cpu_simple == h_cpu_jit).all() and (h_cpu == h_cpu_jit).all()
print ''
f = plt.figure(figsize=(10, 5))
plt.plot(X, cpu_times, label = "CPU")
plt.plot(X, cpu_times_simple, label = "CPU non-vectorized")
plt.plot(X, cpu_times_jit, label = "CPU jit")
plt.plot(X, gpu_times, label = "GPU")
plt.yscale('log')
plt.xscale('log')
plt.xlabel('input length')
plt.ylabel('time, sec')
plt.legend()
plt.show()
| fierval/KaggleMalware | Learning/1dlbp_tests.py | Python | mit | 4,911 |
package me.F_o_F_1092.WeatherVote.PluginManager.Spigot;
import java.util.ArrayList;
import java.util.List;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import me.F_o_F_1092.WeatherVote.Options;
import me.F_o_F_1092.WeatherVote.PluginManager.Command;
import me.F_o_F_1092.WeatherVote.PluginManager.CommandListener;
import me.F_o_F_1092.WeatherVote.PluginManager.HelpMessage;
public class HelpPageListener extends me.F_o_F_1092.WeatherVote.PluginManager.HelpPageListener {
public static void sendMessage(Player p, int page) {
List<HelpMessage> personalHelpMessages = getAllPersonalHelpMessages(p);
List<HelpMessage> personalHelpPageMessages = getHelpPageMessages(p, personalHelpMessages, page);
p.sendMessage("");
JSONMessageListener.send(p, getNavBar(personalHelpMessages, personalHelpPageMessages, page));
p.sendMessage("");
for (HelpMessage hm : personalHelpPageMessages) {
JSONMessageListener.send(p, hm.getJsonString());
}
p.sendMessage("");
if (getMaxPlayerPages(personalHelpMessages) != 1) {
p.sendMessage(Options.msg.get("helpTextGui.4").replace("[PAGE]", (page + 1) + ""));
}
JSONMessageListener.send(p, getNavBar(personalHelpMessages, personalHelpPageMessages, page));
p.sendMessage("");
}
public static void sendNormalMessage(CommandSender cs) {
cs.sendMessage(Options.msg.get("color.1") + "§m----------------§r " + pluginNametag + Options.msg.get("color.1") + "§m----------------");
cs.sendMessage("");
for (Command command : CommandListener.getAllCommands()) {
cs.sendMessage(command.getHelpMessage().getNormalString());
}
cs.sendMessage("");
cs.sendMessage(Options.msg.get("color.1") + "§m----------------§r " + pluginNametag + Options.msg.get("color.1") + "§m----------------");
}
private static List<HelpMessage> getHelpPageMessages(Player p, List<HelpMessage> personalHelpMessages, int page) {
List<HelpMessage> personalHelpPageMessages = new ArrayList<HelpMessage>();
for (int i = 0; i < maxHelpMessages; i++) {
if (personalHelpMessages.size() >= (page * maxHelpMessages + i + 1)) {
personalHelpPageMessages.add(personalHelpMessages.get(page * maxHelpMessages + i));
}
}
return personalHelpPageMessages;
}
public static int getMaxPlayerPages(Player p) {
return (int) java.lang.Math.ceil(((double)getAllPersonalHelpMessages(p).size() / (double)maxHelpMessages));
}
private static List<HelpMessage> getAllPersonalHelpMessages(Player p) {
List<HelpMessage> personalHelpMessages = new ArrayList<HelpMessage>();
for (Command command : CommandListener.getAllCommands()) {
if (command.getPermission()== null || p.hasPermission(command.getPermission())) {
personalHelpMessages.add(command.getHelpMessage());
}
}
return personalHelpMessages;
}
} | fof1092/WeatherVote | src/me/F_o_F_1092/WeatherVote/PluginManager/Spigot/HelpPageListener.java | Java | mit | 2,808 |
namespace _05_SlicingFile
{
using System;
using System.Collections.Generic;
using System.IO;
class StartUp
{
static void Main()
{
var sourceFile = @"D:\SoftUni\05-Csharp Advanced\08-EXERCISE STREAMS\Resources\sliceMe.mp4";
var destinationDirectory = @"D:\SoftUni\05-Csharp Advanced\08-EXERCISE STREAMS\HomeWorkResults\";
int parts = 5;
Slice(sourceFile, destinationDirectory, parts);
var files = new List<string>
{
"05-SlicingFile-Part-01.mp4",
"05-SlicingFile-Part-02.mp4",
"05-SlicingFile-Part-03.mp4",
"05-SlicingFile-Part-04.mp4",
"05-SlicingFile-Part-05.mp4",
};
Assemble(files, destinationDirectory);
}
static void Slice(string sourceFile, string destinationDirectory, int parts)
{
using (var reader = new FileStream(sourceFile, FileMode.Open))
{
long partSize = (long)Math.Ceiling((double)reader.Length / parts);
for (int i = 1; i <= parts; i++)
{
long currentPartSize = 0;
var fileName = $"{destinationDirectory}05-SlicingFile-Part-0{i}.mp4";
using (var writer = new FileStream(fileName, FileMode.Create))
{
var buffer = new byte[4096];
while (reader.Read(buffer, 0, buffer.Length) == 4096)
{
writer.Write(buffer, 0, buffer.Length);
currentPartSize += 4096;
if (currentPartSize >= partSize)
{
break;
}
}
}
}
}
}
static void Assemble(List<string> files, string destinationDirectory)
{
var assembledFilePath = $"{destinationDirectory}05-SlicingFile-Assembled.mp4";
using (var writer = new FileStream(assembledFilePath, FileMode.Create))
{
var buffer = new byte[4096];
for (int i = 0; i < files.Count; i++)
{
var filePath = $"{destinationDirectory}{files[i]}";
using (var reader = new FileStream(filePath, FileMode.Open))
{
while (reader.Read(buffer,0,buffer.Length) != 0)
{
writer.Write(buffer, 0, buffer.Length);
}
}
}
}
}
}
} | MrPIvanov/SoftUni | 04-Csharp Advanced/08-EXERCISE STREAMS/08-StreamsExercises/05-SlicingFile/StartUp.cs | C# | mit | 2,788 |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("BeastApplication")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("BeastApplication")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: ComVisible(false)] | mpenchev86/WindowsApplicationsTeamwork | WindowsPhoneApplication/BeastApplication/Properties/AssemblyInfo.cs | C# | mit | 1,052 |
define(['omega/entity', 'omega/core'], function (e, o) {
'use strict';
var triggerKey = function (action, e) {
o.trigger(action, {
keyCode: e.keyCode,
shiftKey: e.shiftKey,
ctrlKey: e.ctrlKey,
altKey: e.altKey
});
};
window.onkeydown = function (e) {
triggerKey('KeyDown', e);
};
window.onkeyup = function (e) {
triggerKey('KeyUp', e);
};
// ---
return e.extend({
keyboard: {keys: {}},
init: function () {
o.bind('KeyDown', function (e) {
this.keyboard.keys[e.keyCode] = true;
this.trigger('KeyDown', e);
}, this);
o.bind('KeyUp', function (e) {
this.keyboard.keys[e.keyCode] = false;
this.trigger('KeyUp', e);
}, this);
},
isKeyDown: function (keyCode) {
return (this.keyboard.keys[keyCode]);
}
});
});
| alecsammon/OmegaJS | omega/behaviour/keyboard.js | JavaScript | mit | 897 |
package zeonClient.mods;
import java.util.Iterator;
import org.lwjgl.input.Keyboard;
import net.minecraft.client.entity.EntityOtherPlayerMP;
import net.minecraft.client.entity.EntityPlayerSP;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.network.play.client.CPacketPlayerDigging;
import net.minecraft.network.play.client.CPacketPlayerDigging.Action;
import net.minecraft.network.play.client.CPacketUseEntity;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.EnumHand;
import net.minecraft.util.math.BlockPos;
import zeonClient.main.Category;
public class KillAura extends Mod {
private int ticks = 0;
public KillAura() {
super("KillAura", "KillAura", Keyboard.KEY_R, Category.COMBAT);
}
public void onUpdate() {
if(this.isToggled()) {
ticks++;
if(ticks >= 20 - speed()) {
ticks = 0;
mc.player.rotationYaw +=0.2F;
for(Iterator<Entity> entities = mc.world.loadedEntityList.iterator(); entities.hasNext();) {
Object object = entities.next();
if(object instanceof EntityLivingBase) {
EntityLivingBase e = (EntityLivingBase) object;
if(e instanceof EntityPlayerSP) continue;
if(mc.player.getDistanceToEntity(e) <= 7F) {
if(e.isInvisible()) {
break;
}
if(e.isEntityAlive()) {
if(mc.player.getHeldItemMainhand() != null) {
mc.player.attackTargetEntityWithCurrentItem(e);
}
if(mc.player.isActiveItemStackBlocking()) {
mc.player.connection.sendPacket(new CPacketPlayerDigging(Action.RELEASE_USE_ITEM, new BlockPos(0, 0, 0), EnumFacing.UP));
}
mc.player.connection.sendPacket(new CPacketUseEntity(e));
mc.player.swingArm(EnumHand.MAIN_HAND);
break;
}
}
}
}
}
}
}
private int speed() {
return 18;
}
}
| A-D-I-T-Y-A/Zeon-Client | src/minecraft/zeonClient/mods/KillAura.java | Java | mit | 2,021 |
package com.github.lunatrius.schematica.client.gui;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.GuiSlot;
import net.minecraft.client.renderer.Tessellator;
import net.minecraft.client.resources.I18n;
import net.minecraft.item.ItemStack;
class GuiSchematicMaterialsSlot extends GuiSlot {
private final Minecraft minecraft = Minecraft.getMinecraft();
private final GuiSchematicMaterials guiSchematicMaterials;
protected int selectedIndex = -1;
private final String strUnknownBlock = I18n.format("schematica.gui.unknownblock");
public GuiSchematicMaterialsSlot(GuiSchematicMaterials par1) {
super(Minecraft.getMinecraft(), par1.width, par1.height, 16, par1.height - 34, 24);
this.guiSchematicMaterials = par1;
this.selectedIndex = -1;
}
@Override
protected int getSize() {
return this.guiSchematicMaterials.blockList.size();
}
@Override
protected void elementClicked(int index, boolean par2, int par3, int par4) {
this.selectedIndex = index;
}
@Override
protected boolean isSelected(int index) {
return index == this.selectedIndex;
}
@Override
protected void drawBackground() {
}
@Override
protected void drawContainerBackground(Tessellator tessellator) {
}
@Override
protected void drawSlot(int index, int x, int y, int par4, Tessellator tessellator, int par6, int par7) {
ItemStack itemStack = this.guiSchematicMaterials.blockList.get(index);
String itemName;
String amount = Integer.toString(itemStack.stackSize);
if (itemStack.getItem() != null) {
itemName = itemStack.getItem().getItemStackDisplayName(itemStack);
} else {
itemName = this.strUnknownBlock;
}
GuiHelper.drawItemStack(this.minecraft.renderEngine, this.minecraft.fontRenderer, x, y, itemStack);
this.guiSchematicMaterials.drawString(this.minecraft.fontRenderer, itemName, x + 24, y + 6, 0xFFFFFF);
this.guiSchematicMaterials.drawString(this.minecraft.fontRenderer, amount, x + 215 - this.minecraft.fontRenderer.getStringWidth(amount), y + 6, 0xFFFFFF);
}
}
| CannibalVox/Schematica | src/main/java/com/github/lunatrius/schematica/client/gui/GuiSchematicMaterialsSlot.java | Java | mit | 2,204 |
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
/**
* A CodeIgniter library that wraps \Firebase\JWT\JWT methods.
*/
class Jwt {
function __construct()
{
// TODO: Is this the best way to do this? (Issue #4 at psignoret/aad-sso-codeigniter.)
require_once(APPPATH . 'libraries/JWT/JWT.php');
require_once(APPPATH . 'libraries/JWT/BeforeValidException.php');
require_once(APPPATH . 'libraries/JWT/ExpiredException.php');
require_once(APPPATH . 'libraries/JWT/SignatureInvalidException.php');
}
/**
* Wrapper function for JWT::decode.
*/
public function decode($jwt, $key, $allowed_algs = array())
{
return \Firebase\JWT\JWT::decode($jwt, $key, $allowed_algs);
}
}
| psignoret/aad-sso-codeigniter | application/libraries/Jwt.php | PHP | mit | 774 |
$(window).on('load', function() {//main
const dom = {//define inputs
tswitch: $("#wave-switch input"),
aSlider: $("input#angle"),//angle slider
nSlider: $("input#refractive-index-ratio"),
};
let layout = {//define layout of pot
showlegend: false,
scene: {
aspectmode: "cube",
xaxis: {range: [-2, 2]},
yaxis: {range: [-2, 2]},
zaxis: {range: [-2, 2]},
camera: {
eye: {x: 0, y: 0, z: -2}//adjust camera starting view
}
},
};
//define constants
let size = 100;
let t = 0;
let isPlay = false;
let E_0 = 0.5;
let w_r = 2e9;
let c = 3e8; // Speed of light
let n1 = 1;
let k_1 = (n1*w_r)/c;
let k_2,theta_i,theta_t;
let x_data = numeric.linspace(2, 0, size);//x and y data is always the same and just change z
let x_data_t = math.add(-2,x_data);
let y_data = numeric.linspace(-2, 2, size);
//constants based of of inputs
let condition = $("input[name = wave-switch]:checked").val();
let angle_of_incidence = parseFloat($("input#angle").val());
let n2 = parseFloat($("input#refractive-index-ratio").val());
function snell(theta_i){//snells law
console.log(Math.sin(theta_i));
console.log((n1 / n2))
return Math.asin((n1 / n2) * Math.sin(theta_i));
};
function getData_wave_incident(){//produces data for the incident wave on the boundry
let z,z_square = [];
let k_x = Math.cos(theta_i)*k_1;
let k_y = Math.sin(theta_i)*k_1;
for (let v=0;v < y_data.length ;v++) {
let z_row = [];
for (let i = 0; i < x_data.length ; i++) {
z = E_0* Math.sin(k_x* x_data[i]+k_y*y_data[v]+w_r*t);
z_row.push(z);
}
z_square.push(z_row);
}
return z_square
}
function getData_wave_reflected(){//produces data for the reflected wave on the boundry
let z,z_square = [];
let k_x = Math.cos(-theta_i)*k_1;
let k_y = Math.sin(-theta_i)*k_1;
let E_0_r = reflect();
for (let v=0;v < y_data.length ;v++) {
let z_row = [];
for (let i = 0; i < x_data.length ; i++) {
z = E_0_r* Math.sin(k_x* x_data[i]+k_y*y_data[v]-w_r*t);
z_row.push(z);
}
z_square.push(z_row);
}
return z_square
}
function getData_wave_transmitted(){//produces data for the incident wave on the boundry
let z,z_square = [];
let E_0_t = transmit();
let k_y = Math.sin(theta_i)*k_1;
let k_x = Math.cos(theta_t)*k_2;
for (let v=0;v < y_data.length ;v++) {
let z_row = [];
for (let i = 0; i < x_data_t.length ; i++) {
z = E_0_t*Math.sin(k_x*x_data_t[i]+k_y*y_data[v]+w_r*t);
z_row.push(z);
}
z_square.push(z_row);//Not entirelly sure the physics is correct need to review
}
return z_square
}
function transmit(){//gives the new amplitude of the transmitted wave
let E_t0;
if (isNaN(theta_t) === true){//if snells law return not a number this means total internal refection is occurring hence no transmitted wave(no attenuation accounted for)
return 0
}
else {
E_t0 = E_0 * (2. * n1 * Math.cos(theta_i)) / (n1 * Math.cos(theta_i) + n2 * Math.cos(theta_t))
return E_t0
}
};
function reflect() {//gives the amplitude of the refected wave
if (n1 === n2) {//if both materials have same refractive index then there is no reflection
return 0
}
else {
let E_r0;
if (isNaN(theta_t) === true){
E_r0 = E_0;
}
else {
E_r0 = E_0 * (n1 * Math.cos(theta_i) - n2 * Math.cos(theta_t)) / (n1 * Math.cos(theta_i) + n2 * Math.cos(theta_t))
}
return E_r0
}
};
function plot_data() {//produces the traces of the plot
$("#angle-display").html($("input#angle").val().toString()+"°");//update display
$("#refractive-index-ratio-display").html($("input#refractive-index-ratio").val().toString());
condition = $("input[name = wave-switch]:checked").val();//update value of constants
angle_of_incidence = parseFloat($("input#angle").val());
n2 = parseFloat($("input#refractive-index-ratio").val());
k_2 = (n2*w_r)/c;
theta_i = Math.PI * (angle_of_incidence / 180);
theta_t = snell(theta_i);
if (isNaN(Math.asin(n2))=== true){//update value of citical angle
$("#critical_angle-display").html("No Total Internal Reflection possible");
}else{
$("#critical_angle-display").html(((180*Math.asin(n2))/Math.PI).toFixed(2).toString()+"°");
}
let data = [];
if (condition === "incident") {//creates trace dependent of the conditions of the system
let incident_wave = {
opacity: 1,
x: x_data,
y: y_data,
z: getData_wave_incident(),
type: 'surface',
name: "Incident"
};
data.push(incident_wave);
}
else if(condition === "reflected") {
let reflected_wave = {
opacity: 1,
x: x_data,
y: y_data,
z: getData_wave_reflected(),
type: 'surface',
name: "Reflected"
};
data.push(reflected_wave);
}
else{
let incident_plus_reflected_wave = {
opacity: 1,
x: x_data,
y: y_data,
z: math.add(getData_wave_incident(),getData_wave_reflected()),
type: 'surface',
name:"Reflected and Incident combined"
};
data.push(incident_plus_reflected_wave);
}
let transmitted_wave = {
opacity: 1,
x: x_data_t,
y: y_data,
z: getData_wave_transmitted(),
type: 'surface',
name:"Transmitted"
};
let opacity_1;//opacity gives qualitative representation of refractive index
let opacity_2;
if((1 < n2) && (n2 <= 15)){//decide opacity dependant on refractive index
opacity_1 = 0;
opacity_2 = n2/10
}
else if((0.1 <= n2) && (n2< 1)){
opacity_1 = 0.1/n2;
opacity_2 = 0;
}
else{
opacity_1 = 0;
opacity_2 = 0;
}
let material_1 =//dielectric one
{
opacity: opacity_1,
color: '#379F9F',
type: "mesh3d",
name: "material 1",
z: [-2, -2, 2, 2, -2, -2, 2, 2],
y: [-2, 2, 2, -2, -2, 2, 2, -2],
x: [2, 2, 2, 2, 0, 0, 0, 0],
i: [7, 0, 0, 0, 4, 4, 6, 6, 4, 0, 3, 2],
j: [3, 4, 1, 2, 5, 6, 5, 2, 0, 1, 6, 3],
k: [0, 7, 2, 3, 6, 7, 1, 1, 5, 5, 7, 6],
};
let material_2 =//dielectric two
{
opacity: opacity_2,
color: '#379F9F',
type: "mesh3d",
name: "material 2",
z: [-2, -2, 2, 2, -2, -2, 2, 2],
y: [-2, 2, 2, -2, -2, 2, 2, -2],
x: [0, 0, 0, 0, -2, -2, -2, -2],
i: [7, 0, 0, 0, 4, 4, 6, 6, 4, 0, 3, 2],
j: [3, 4, 1, 2, 5, 6, 5, 2, 0, 1, 6, 3],
k: [0, 7, 2, 3, 6, 7, 1, 1, 5, 5, 7, 6],
};
data.push(transmitted_wave,material_1,material_2);
if (data.length < 5) {//animate function requires data sets of the same length hence those unused in situation must be filled with empty traces
let extensionSize = data.length;
for (let i = 0; i < (5 - extensionSize); ++i){
data.push(
{
type: "scatter3d",
mode: "lines",
x: [0],
y: [0],
z: [0]
}
);
}
}
return data
}
function update_graph(){//update animation
Plotly.animate("graph",
{data: plot_data()},//updated data
{
fromcurrent: true,
transition: {duration: 0,},
frame: {duration: 0, redraw: false,},
mode: "afterall"
}
);
};
function play_loop(){//handles the play button
if(isPlay === true) {
t++;//keeps time ticking
Plotly.animate("graph",
{data: plot_data()},
{
fromcurrent: true,
transition: {duration: 0,},
frame: {duration: 0, redraw: false,},
mode: "afterall"
});
requestAnimationFrame(play_loop);//prepares next frame
}
return 0;
};
function initial() {
Plotly.purge("graph");
Plotly.newPlot('graph', plot_data(),layout);//create plot
dom.tswitch.on("change", update_graph);//change of input produces reaction
dom.aSlider.on("input", update_graph);
dom.nSlider.on("input", update_graph);
$('#playButton').on('click', function() {
document.getElementById("playButton").value = (isPlay) ? "Play" : "Stop";//change button label
isPlay = !isPlay;
w_t = 0;//reset time to 0
requestAnimationFrame(play_loop);
});
};
initial();
}); | cydcowley/Imperial-Visualizations | visuals_EM/Waves and Dielectrics/scripts/2D_Dielectric_Dielectric.js | JavaScript | mit | 10,284 |
// Package machinelearningservices implements the Azure ARM Machinelearningservices service API version 2019-06-01.
//
// These APIs allow end users to operate on Azure Machine Learning Workspace resources.
package machinelearningservices
// 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.
import (
"github.com/Azure/go-autorest/autorest"
)
const (
// DefaultBaseURI is the default URI used for the service Machinelearningservices
DefaultBaseURI = "https://management.azure.com"
)
// BaseClient is the base client for Machinelearningservices.
type BaseClient struct {
autorest.Client
BaseURI string
SubscriptionID string
}
// New creates an instance of the BaseClient client.
func New(subscriptionID string) BaseClient {
return NewWithBaseURI(DefaultBaseURI, subscriptionID)
}
// NewWithBaseURI creates an instance of the BaseClient client using a custom endpoint. Use this when interacting with
// an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure stack).
func NewWithBaseURI(baseURI string, subscriptionID string) BaseClient {
return BaseClient{
Client: autorest.NewClientWithUserAgent(UserAgent()),
BaseURI: baseURI,
SubscriptionID: subscriptionID,
}
}
| Azure/azure-sdk-for-go | services/machinelearningservices/mgmt/2019-06-01/machinelearningservices/client.go | GO | mit | 1,478 |
<?php
namespace App\Http\Controllers;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
class AdminLoginController extends Controller
{
/*
|--------------------------------------------------------------------------
| Login Controller
|--------------------------------------------------------------------------
|
| This controller handles authenticating users for the application and
| redirecting them to your home screen. The controller uses a trait
| to conveniently provide its functionality to your applications.
|
*/
use AuthenticatesUsers;
/**
* Where to redirect users after login / registration.
*
* @var string
*/
protected $redirectTo = '/admin/home';
protected $username;
/**
* Create a new controller instance.
*
* @return void
*/
public function __construct()
{
$this->middleware('guest:web', ['except' => 'logout']);
}
/**
* 重写登录视图页面
* @author 晚黎
* @date 2016-09-05T23:06:16+0800
* @return [type] [description]
*/
public function showLoginForm()
{
return view('auth.admin-login');
}
/**
* 自定义认证驱动
* @author 晚黎
* @date 2016-09-05T23:53:07+0800
* @return [type] [description]
*/
public function username(){
return 'name';
}
protected function guard()
{
return auth()->guard('web');
}
}
| mobyan/thc-platform | src/app/Http/Controllers/AdminLoginController.php | PHP | mit | 1,582 |
package pixlepix.auracascade.data;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
/**
* Created by localmacaccount on 5/31/15.
*/
public class Quest {
//TODO QUEST
public static int nextId;
public final ItemStack target;
public final ItemStack result;
public final int id;
public String string;
public Quest(String string, ItemStack target, ItemStack result) {
this.target = target;
this.result = result;
this.string = string;
this.id = nextId;
nextId++;
}
public boolean hasCompleted(EntityPlayer player) {
// QuestData questData = (QuestData) player.getExtendedProperties(QuestData.EXT_PROP_NAME);
// return questData.completedQuests.contains(this);
return false;
}
public void complete(EntityPlayer player) {
//QuestData questData = (QuestData) player.getExtendedProperties(QuestData.EXT_PROP_NAME);
// questData.completedQuests.add(this);
// AuraCascade.analytics.eventDesign("questComplete", id);
}
}
| pixlepix/Aura-Cascade | src/main/java/pixlepix/auracascade/data/Quest.java | Java | mit | 1,082 |
<?php
/*
* This file is part of the Itkg\Core package.
*
* (c) Interakting - Business & Decision
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Itkg\Core\Cache\Adapter;
use Itkg\Core\Cache\AdapterInterface;
use Itkg\Core\CacheableInterface;
/**
* Class Persistent
*
* Store cache in specific adapter & keep in memory (with array storage)
*
* @package Itkg\Core\Cache\Adapter
*/
class Persistent extends Registry
{
/**
* @var \Itkg\Core\Cache\AdapterInterface
*/
protected $adapter;
/**
* @param AdapterInterface $adapter
*/
public function __construct(AdapterInterface $adapter)
{
$this->adapter = $adapter;
}
/**
* Get value from cache
*
* @param \Itkg\Core\CacheableInterface $item
*
* @return string
*/
public function get(CacheableInterface $item)
{
if (false !== $result = parent::get($item)) {
return $result;
}
return $this->adapter->get($item);
}
/**
* Set a value into the cache
*
* @param \Itkg\Core\CacheableInterface $item
*
* @return void
*/
public function set(CacheableInterface $item)
{
parent::set($item);
$this->adapter->set($item);
}
/**
* Remove a value from cache
*
* @param \Itkg\Core\CacheableInterface $item
* @return void
*/
public function remove(CacheableInterface $item)
{
parent::remove($item);
$this->adapter->remove($item);
}
/**
* Remove cache
*
* @return void
*/
public function removeAll()
{
parent::removeAll();
$this->adapter->removeAll();
}
/**
* @return AdapterInterface
*/
public function getAdapter()
{
return $this->adapter;
}
/**
* @param AdapterInterface $adapter
*
* @return $this
*/
public function setAdapter(AdapterInterface $adapter)
{
$this->adapter = $adapter;
return $this;
}
}
| itkg/core | src/Itkg/Core/Cache/Adapter/Persistent.php | PHP | mit | 2,140 |
// Copyright (c) 2011-2013 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "splashscreen.h"
#include "clientversion.h"
#include "util.h"
#include <QPainter>
#undef loop /* ugh, remove this when the #define loop is gone from util.h */
#include <QApplication>
SplashScreen::SplashScreen(const QPixmap &pixmap, Qt::WindowFlags f) :
QSplashScreen(pixmap, f)
{
// set reference point, paddings
//int paddingLeftCol2 = 230;
//int paddingTopCol2 = 376;
//int line1 = 0;
//int line2 = 13;
//int line3 = 26;
//int line4 = 26;
float fontFactor = 1.0;
// define text to place
QString titleText = QString(QApplication::applicationName()).replace(QString("-testnet"), QString(""), Qt::CaseSensitive); // cut of testnet, place it as single object further down
QString versionText = QString("Version %1 ").arg(QString::fromStdString(FormatFullVersion()));
QString copyrightText1 = QChar(0xA9)+QString(" 2009-%1 ").arg(COPYRIGHT_YEAR) + QString(tr("The Bitcoin developers"));
QString copyrightText2 = QChar(0xA9)+QString(" 2011-%1 ").arg(COPYRIGHT_YEAR) + QString(tr("The Litecoin developers"));
QString copyrightText3 = QChar(0xA9)+QString(" 2013-%1 ").arg(COPYRIGHT_YEAR) + QString(tr("The Quarkcoin developers"));
QString font = "Arial";
// load the bitmap for writing some text over it
QPixmap newPixmap;
if(GetBoolArg("-testnet")) {
newPixmap = QPixmap(":/images/splash_testnet");
}
else {
newPixmap = QPixmap(":/images/splash");
}
QPainter pixPaint(&newPixmap);
pixPaint.setPen(QColor(70,70,70));
pixPaint.setFont(QFont(font, 9*fontFactor));
// pixPaint.drawText(paddingLeftCol2,paddingTopCol2+line3,versionText);
// draw copyright stuff
pixPaint.setFont(QFont(font, 9*fontFactor));
// pixPaint.drawText(paddingLeftCol2,paddingTopCol2+line1,copyrightText1);
// pixPaint.drawText(paddingLeftCol2,paddingTopCol2+line2,copyrightText2);
// pixPaint.drawText(paddingLeftCol2,paddingTopCol2+line2+line2,copyrightText3);
pixPaint.end();
this->setPixmap(newPixmap);
}
| paulmadore/woodcoin | src/qt/splashscreen.cpp | C++ | mit | 2,296 |
<?php
namespace Oro\Bundle\NoteBundle\Controller;
use FOS\RestBundle\Util\Codes;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Bundle\FrameworkBundle\Routing\Router;
use Symfony\Component\HttpFoundation\Response;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Oro\Bundle\SecurityBundle\Annotation\AclAncestor;
use Oro\Bundle\EntityBundle\Tools\EntityRoutingHelper;
use Oro\Bundle\NoteBundle\Entity\Note;
use Oro\Bundle\NoteBundle\Entity\Manager\NoteManager;
/**
* @Route("/notes")
*/
class NoteController extends Controller
{
/**
* @Route(
* "/view/widget/{entityClass}/{entityId}",
* name="oro_note_widget_notes"
* )
*
* @AclAncestor("oro_note_view")
* @Template("OroNoteBundle:Note:notes.html.twig")
*/
public function widgetAction($entityClass, $entityId)
{
$entity = $this->getEntityRoutingHelper()->getEntity($entityClass, $entityId);
return [
'entity' => $entity
];
}
/**
* @Route(
* "/view/{entityClass}/{entityId}",
* name="oro_note_notes"
* )
*
* @AclAncestor("oro_note_view")
*/
public function getAction($entityClass, $entityId)
{
$entityClass = $this->getEntityRoutingHelper()->resolveEntityClass($entityClass);
$sorting = strtoupper($this->getRequest()->get('sorting', 'DESC'));
$manager = $this->getNoteManager();
$result = $manager->getEntityViewModels(
$manager->getList($entityClass, $entityId, $sorting)
);
return new Response(json_encode($result), Codes::HTTP_OK);
}
/**
* @Route("/widget/info/{id}", name="oro_note_widget_info", requirements={"id"="\d+"})
* @Template
* @AclAncestor("oro_note_view")
*/
public function infoAction(Note $entity)
{
return array('entity' => $entity);
}
/**
* @Route("/create/{entityClass}/{entityId}", name="oro_note_create")
*
* @Template("OroNoteBundle:Note:update.html.twig")
* @AclAncestor("oro_note_create")
*/
public function createAction($entityClass, $entityId)
{
$entityRoutingHelper = $this->getEntityRoutingHelper();
$entity = $entityRoutingHelper->getEntity($entityClass, $entityId);
$entityClass = get_class($entity);
$noteEntity = new Note();
$noteEntity->setTarget($entity);
$formAction = $entityRoutingHelper->generateUrlByRequest(
'oro_note_create',
$this->getRequest(),
$entityRoutingHelper->getRouteParameters($entityClass, $entityId)
);
return $this->update($noteEntity, $formAction);
}
/**
* @Route("/update/{id}", name="oro_note_update", requirements={"id"="\d+"})
*
* @Template
* @AclAncestor("oro_note_update")
*/
public function updateAction(Note $entity)
{
$formAction = $this->get('router')->generate('oro_note_update', ['id' => $entity->getId()]);
return $this->update($entity, $formAction);
}
protected function update(Note $entity, $formAction)
{
$responseData = [
'entity' => $entity,
'saved' => false
];
if ($this->get('oro_note.form.handler.note')->process($entity)) {
$responseData['saved'] = true;
$responseData['model'] = $this->getNoteManager()->getEntityViewModel($entity);
}
$responseData['form'] = $this->get('oro_note.form.note')->createView();
$responseData['formAction'] = $formAction;
return $responseData;
}
/**
* @return NoteManager
*/
protected function getNoteManager()
{
return $this->get('oro_note.manager');
}
/**
* @return EntityRoutingHelper
*/
protected function getEntityRoutingHelper()
{
return $this->get('oro_entity.routing_helper');
}
}
| morontt/platform | src/Oro/Bundle/NoteBundle/Controller/NoteController.php | PHP | mit | 4,038 |
'use strict';
memoryApp.controller('AuthCtrl', function ($scope, $location, AuthService) {
$scope.register = function () {
var username = $scope.registerUsername;
var password = $scope.registerPassword;
if (username && password) {
AuthService.register(username, password).then(
function () {
$location.path('/dashboard');
},
function (error) {
$scope.registerError = error;
}
);
} else {
$scope.registerError = 'Username and password required';
}
};
$scope.login = function () {
var username = $scope.loginUsername;
var password = $scope.loginPassword;
if (username && password) {
AuthService.login(username, password).then(
function () {
$location.path('/dashboard');
},
function (error) {
$scope.loginError = error;
}
);
} else {
$scope.error = 'Username and password required';
}
};
}); | emilkjer/django-memorycms | backend/static/js/controllers/auth.js | JavaScript | mit | 980 |
/**
* MIT License
*
* Copyright (c) 2017 zgqq
*
* 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 mah.ui.util;
import mah.ui.key.KeystateManager;
import mah.ui.layout.Layout;
import mah.ui.pane.input.InputPane;
import mah.ui.pane.input.InputPaneProvider;
import mah.ui.window.WindowManager;
import org.jetbrains.annotations.Nullable;
/**
* Created by zgq on 2017-01-12 11:17
*/
public final class UiUtils {
private UiUtils(){}
public static void hideWindow() {
KeystateManager.getInstance().reset();
WindowManager.getInstance().getCurrentWindow().hide();
}
@Nullable
public static InputPane getInputPane() {
Layout currentLayout = WindowManager.getInstance().getCurrentWindow().getCurrentLayout();
if (currentLayout instanceof InputPaneProvider) {
InputPaneProvider layout = (InputPaneProvider) currentLayout;
return layout.getInputPane();
}
return null;
}
}
| zgqq/mah | mah-core/src/main/java/mah/ui/util/UiUtils.java | Java | mit | 1,999 |
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
/*
|--------------------------------------------------------------------------
| Base Site URL
|--------------------------------------------------------------------------
|
| URL to your CodeIgniter root. Typically this will be your base URL,
| WITH a trailing slash:
|
| http://example.com/
|
| WARNING: You MUST set this value!
|
| If it is not set, then CodeIgniter will try guess the protocol and path
| your installation, but due to security concerns the hostname will be set
| to $_SERVER['SERVER_ADDR'] if available, or localhost otherwise.
| The auto-detection mechanism exists only for convenience during
| development and MUST NOT be used in production!
|
| If you need to allow multiple domains, remember that this file is still
| a PHP script and you can easily do that on your own.
|
*/
$config['base_url'] = 'http://localhost/sirumkit1';
/*
|--------------------------------------------------------------------------
| Index File
|--------------------------------------------------------------------------
|
| Typically this will be your index.php file, unless you've renamed it to
| something else. If you are using mod_rewrite to remove the page set this
| variable so that it is blank.
|
*/
$config['index_page'] = 'index.php';
/*
|--------------------------------------------------------------------------
| URI PROTOCOL
|--------------------------------------------------------------------------
|
| This item determines which server global should be used to retrieve the
| URI string. The default setting of 'REQUEST_URI' works for most servers.
| If your links do not seem to work, try one of the other delicious flavors:
|
| 'REQUEST_URI' Uses $_SERVER['REQUEST_URI']
| 'QUERY_STRING' Uses $_SERVER['QUERY_STRING']
| 'PATH_INFO' Uses $_SERVER['PATH_INFO']
|
| WARNING: If you set this to 'PATH_INFO', URIs will always be URL-decoded!
*/
$config['uri_protocol'] = 'REQUEST_URI';
/*
|--------------------------------------------------------------------------
| URL suffix
|--------------------------------------------------------------------------
|
| This option allows you to add a suffix to all URLs generated by CodeIgniter.
| For more information please see the user guide:
|
| https://codeigniter.com/user_guide/general/urls.html
*/
$config['url_suffix'] = '';
/*
|--------------------------------------------------------------------------
| Default Language
|--------------------------------------------------------------------------
|
| This determines which set of language files should be used. Make sure
| there is an available translation if you intend to use something other
| than english.
|
*/
$config['language'] = 'english';
/*
|--------------------------------------------------------------------------
| Default Character Set
|--------------------------------------------------------------------------
|
| This determines which character set is used by default in various methods
| that require a character set to be provided.
|
| See http://php.net/htmlspecialchars for a list of supported charsets.
|
*/
$config['charset'] = 'UTF-8';
/*
|--------------------------------------------------------------------------
| Enable/Disable System Hooks
|--------------------------------------------------------------------------
|
| If you would like to use the 'hooks' feature you must enable it by
| setting this variable to TRUE (boolean). See the user guide for details.
|
*/
$config['enable_hooks'] = FALSE;
/*
|--------------------------------------------------------------------------
| Class Extension Prefix
|--------------------------------------------------------------------------
|
| This item allows you to set the filename/classname prefix when extending
| native libraries. For more information please see the user guide:
|
| https://codeigniter.com/user_guide/general/core_classes.html
| https://codeigniter.com/user_guide/general/creating_libraries.html
|
*/
$config['subclass_prefix'] = 'MY_';
/*
|--------------------------------------------------------------------------
| Composer auto-loading
|--------------------------------------------------------------------------
|
| Enabling this setting will tell CodeIgniter to look for a Composer
| package auto-loader script in application/vendor/autoload.php.
|
| $config['composer_autoload'] = TRUE;
|
| Or if you have your vendor/ directory located somewhere else, you
| can opt to set a specific path as well:
|
| $config['composer_autoload'] = '/path/to/vendor/autoload.php';
|
| For more information about Composer, please visit http://getcomposer.org/
|
| Note: This will NOT disable or override the CodeIgniter-specific
| autoloading (application/config/autoload.php)
*/
$config['composer_autoload'] = FALSE;
/*
|--------------------------------------------------------------------------
| Allowed URL Characters
|--------------------------------------------------------------------------
|
| This lets you specify which characters are permitted within your URLs.
| When someone tries to submit a URL with disallowed characters they will
| get a warning message.
|
| As a security measure you are STRONGLY encouraged to restrict URLs to
| as few characters as possible. By default only these are allowed: a-z 0-9~%.:_-
|
| Leave blank to allow all characters -- but only if you are insane.
|
| The configured value is actually a regular expression character group
| and it will be executed as: ! preg_match('/^[<permitted_uri_chars>]+$/i
|
| DO NOT CHANGE THIS UNLESS YOU FULLY UNDERSTAND THE REPERCUSSIONS!!
|
*/
$config['permitted_uri_chars'] = 'a-z 0-9~%.:_\-';
/*
|--------------------------------------------------------------------------
| Enable Query Strings
|--------------------------------------------------------------------------
|
| By default CodeIgniter uses search-engine friendly segment based URLs:
| example.com/who/what/where/
|
| By default CodeIgniter enables access to the $_GET array. If for some
| reason you would like to disable it, set 'allow_get_array' to FALSE.
|
| You can optionally enable standard query string based URLs:
| example.com?who=me&what=something&where=here
|
| Options are: TRUE or FALSE (boolean)
|
| The other items let you set the query string 'words' that will
| invoke your controllers and its functions:
| example.com/index.php?c=controller&m=function
|
| Please note that some of the helpers won't work as expected when
| this feature is enabled, since CodeIgniter is designed primarily to
| use segment based URLs.
|
*/
$config['allow_get_array'] = TRUE;
$config['enable_query_strings'] = FALSE;
$config['controller_trigger'] = 'c';
$config['function_trigger'] = 'm';
$config['directory_trigger'] = 'd';
/*
|--------------------------------------------------------------------------
| Error Logging Threshold
|--------------------------------------------------------------------------
|
| You can enable error logging by setting a threshold over zero. The
| threshold determines what gets logged. Threshold options are:
|
| 0 = Disables logging, Error logging TURNED OFF
| 1 = Error Messages (including PHP errors)
| 2 = Debug Messages
| 3 = Informational Messages
| 4 = All Messages
|
| You can also pass an array with threshold levels to show individual error types
|
| array(2) = Debug Messages, without Error Messages
|
| For a live site you'll usually only enable Errors (1) to be logged otherwise
| your log files will fill up very fast.
|
*/
$config['log_threshold'] = 0;
/*
|--------------------------------------------------------------------------
| Error Logging Directory Path
|--------------------------------------------------------------------------
|
| Leave this BLANK unless you would like to set something other than the default
| application/logs/ directory. Use a full server path with trailing slash.
|
*/
$config['log_path'] = '';
/*
|--------------------------------------------------------------------------
| Log File Extension
|--------------------------------------------------------------------------
|
| The default filename extension for log files. The default 'php' allows for
| protecting the log files via basic scripting, when they are to be stored
| under a publicly accessible directory.
|
| Note: Leaving it blank will default to 'php'.
|
*/
$config['log_file_extension'] = '';
/*
|--------------------------------------------------------------------------
| Log File Permissions
|--------------------------------------------------------------------------
|
| The file system permissions to be applied on newly created log files.
|
| IMPORTANT: This MUST be an integer (no quotes) and you MUST use octal
| integer notation (i.e. 0700, 0644, etc.)
*/
$config['log_file_permissions'] = 0644;
/*
|--------------------------------------------------------------------------
| Date Format for Logs
|--------------------------------------------------------------------------
|
| Each item that is logged has an associated date. You can use PHP date
| codes to set your own date formatting
|
*/
$config['log_date_format'] = 'Y-m-d H:i:s';
/*
|--------------------------------------------------------------------------
| Error Views Directory Path
|--------------------------------------------------------------------------
|
| Leave this BLANK unless you would like to set something other than the default
| application/views/errors/ directory. Use a full server path with trailing slash.
|
*/
$config['error_views_path'] = '';
/*
|--------------------------------------------------------------------------
| Cache Directory Path
|--------------------------------------------------------------------------
|
| Leave this BLANK unless you would like to set something other than the default
| application/cache/ directory. Use a full server path with trailing slash.
|
*/
$config['cache_path'] = '';
/*
|--------------------------------------------------------------------------
| Cache Include Query String
|--------------------------------------------------------------------------
|
| Whether to take the URL query string into consideration when generating
| output cache files. Valid options are:
|
| FALSE = Disabled
| TRUE = Enabled, take all query parameters into account.
| Please be aware that this may result in numerous cache
| files generated for the same page over and over again.
| array('q') = Enabled, but only take into account the specified list
| of query parameters.
|
*/
$config['cache_query_string'] = FALSE;
/*
|--------------------------------------------------------------------------
| Encryption Key
|--------------------------------------------------------------------------
|
| If you use the Encryption class, you must set an encryption key.
| See the user guide for more info.
|
| https://codeigniter.com/user_guide/libraries/encryption.html
|
*/
$config['encryption_key'] = '';
/*
|--------------------------------------------------------------------------
| Session Variables
|--------------------------------------------------------------------------
|
| 'sess_driver'
|
| The storage driver to use: files, database, redis, memcached
|
| 'sess_cookie_name'
|
| The session cookie name, must contain only [0-9a-z_-] characters
|
| 'sess_expiration'
|
| The number of SECONDS you want the session to last.
| Setting to 0 (zero) means expire when the browser is closed.
|
| 'sess_save_path'
|
| The location to save sessions to, driver dependent.
|
| For the 'files' driver, it's a path to a writable directory.
| WARNING: Only absolute paths are supported!
|
| For the 'database' driver, it's a table name.
| Please read up the manual for the format with other session drivers.
|
| IMPORTANT: You are REQUIRED to set a valid save path!
|
| 'sess_match_ip'
|
| Whether to match the user's IP address when reading the session data.
|
| WARNING: If you're using the database driver, don't forget to update
| your session table's PRIMARY KEY when changing this setting.
|
| 'sess_time_to_update'
|
| How many seconds between CI regenerating the session ID.
|
| 'sess_regenerate_destroy'
|
| Whether to destroy session data associated with the old session ID
| when auto-regenerating the session ID. When set to FALSE, the data
| will be later deleted by the garbage collector.
|
| Other session cookie settings are shared with the rest of the application,
| except for 'cookie_prefix' and 'cookie_httponly', which are ignored here.
|
*/
$config['sess_driver'] = 'files';
$config['sess_cookie_name'] = 'ci_session';
$config['sess_expiration'] = 7200;
$config['sess_save_path'] = NULL;
$config['sess_match_ip'] = FALSE;
$config['sess_time_to_update'] = 300;
$config['sess_regenerate_destroy'] = FALSE;
/*
|--------------------------------------------------------------------------
| Cookie Related Variables
|--------------------------------------------------------------------------
|
| 'cookie_prefix' = Set a cookie name prefix if you need to avoid collisions
| 'cookie_domain' = Set to .your-domain.com for site-wide cookies
| 'cookie_path' = Typically will be a forward slash
| 'cookie_secure' = Cookie will only be set if a secure HTTPS connection exists.
| 'cookie_httponly' = Cookie will only be accessible via HTTP(S) (no javascript)
|
| Note: These settings (with the exception of 'cookie_prefix' and
| 'cookie_httponly') will also affect sessions.
|
*/
$config['cookie_prefix'] = '';
$config['cookie_domain'] = '';
$config['cookie_path'] = '/';
$config['cookie_secure'] = FALSE;
$config['cookie_httponly'] = FALSE;
/*
|--------------------------------------------------------------------------
| Standardize newlines
|--------------------------------------------------------------------------
|
| Determines whether to standardize newline characters in input data,
| meaning to replace \r\n, \r, \n occurrences with the PHP_EOL value.
|
| This is particularly useful for portability between UNIX-based OSes,
| (usually \n) and Windows (\r\n).
|
*/
$config['standardize_newlines'] = FALSE;
/*
|--------------------------------------------------------------------------
| Global XSS Filtering
|--------------------------------------------------------------------------
|
| Determines whether the XSS filter is always active when GET, POST or
| COOKIE data is encountered
|
| WARNING: This feature is DEPRECATED and currently available only
| for backwards compatibility purposes!
|
*/
$config['global_xss_filtering'] = FALSE;
/*
|--------------------------------------------------------------------------
| Cross Site Request Forgery
|--------------------------------------------------------------------------
| Enables a CSRF cookie token to be set. When set to TRUE, token will be
| checked on a submitted form. If you are accepting user data, it is strongly
| recommended CSRF protection be enabled.
|
| 'csrf_token_name' = The token name
| 'csrf_cookie_name' = The cookie name
| 'csrf_expire' = The number in seconds the token should expire.
| 'csrf_regenerate' = Regenerate token on every submission
| 'csrf_exclude_uris' = Array of URIs which ignore CSRF checks
*/
$config['csrf_protection'] = FALSE;
$config['csrf_token_name'] = 'csrf_test_name';
$config['csrf_cookie_name'] = 'csrf_cookie_name';
$config['csrf_expire'] = 7200;
$config['csrf_regenerate'] = TRUE;
$config['csrf_exclude_uris'] = array();
/*
|--------------------------------------------------------------------------
| Output Compression
|--------------------------------------------------------------------------
|
| Enables Gzip output compression for faster page loads. When enabled,
| the output class will test whether your server supports Gzip.
| Even if it does, however, not all browsers support compression
| so enable only if you are reasonably sure your visitors can handle it.
|
| Only used if zlib.output_compression is turned off in your php.ini.
| Please do not use it together with httpd-level output compression.
|
| VERY IMPORTANT: If you are getting a blank page when compression is enabled it
| means you are prematurely outputting something to your browser. It could
| even be a line of whitespace at the end of one of your scripts. For
| compression to work, nothing can be sent before the output buffer is called
| by the output class. Do not 'echo' any values with compression enabled.
|
*/
$config['compress_output'] = FALSE;
/*
|--------------------------------------------------------------------------
| Master Time Reference
|--------------------------------------------------------------------------
|
| Options are 'local' or any PHP supported timezone. This preference tells
| the system whether to use your server's local time as the master 'now'
| reference, or convert it to the configured one timezone. See the 'date
| helper' page of the user guide for information regarding date handling.
|
*/
$config['time_reference'] = 'local';
/*
|--------------------------------------------------------------------------
| Rewrite PHP Short Tags
|--------------------------------------------------------------------------
|
| If your PHP installation does not have short tag support enabled CI
| can rewrite the tags on-the-fly, enabling you to utilize that syntax
| in your view files. Options are TRUE or FALSE (boolean)
|
| Note: You need to have eval() enabled for this to work.
|
*/
$config['rewrite_short_tags'] = FALSE;
/*
|--------------------------------------------------------------------------
| Reverse Proxy IPs
|--------------------------------------------------------------------------
|
| If your server is behind a reverse proxy, you must whitelist the proxy
| IP addresses from which CodeIgniter should trust headers such as
| HTTP_X_FORWARDED_FOR and HTTP_CLIENT_IP in order to properly identify
| the visitor's IP address.
|
| You can use both an array or a comma-separated list of proxy addresses,
| as well as specifying whole subnets. Here are a few examples:
|
| Comma-separated: '10.0.1.200,192.168.5.0/24'
| Array: array('10.0.1.200', '192.168.5.0/24')
*/
$config['proxy_ips'] = '';
| hafiznuzal/sirumkit1 | application/config/config.php | PHP | mit | 18,153 |
<?xml version="1.0" ?><!DOCTYPE TS><TS language="nb" version="2.0">
<defaultcodec>UTF-8</defaultcodec>
<context>
<name>AboutDialog</name>
<message>
<location filename="../forms/aboutdialog.ui" line="+14"/>
<source>About RupayaCoin</source>
<translation>Om RupayaCoin</translation>
</message>
<message>
<location line="+39"/>
<source><b>RupayaCoin</b> version</source>
<translation><b>RupayaCoin</b> versjon</translation>
</message>
<message>
<location line="+57"/>
<source>
This is experimental software.
Distributed under the MIT/X11 software license, see the accompanying file COPYING or http://www.opensource.org/licenses/mit-license.php.
This product includes software developed by the OpenSSL Project for use in the OpenSSL Toolkit (http://www.openssl.org/) and cryptographic software written by Eric Young (eay@cryptsoft.com) and UPnP software written by Thomas Bernard.</source>
<translation>
Dette er eksperimentell programvare.
Distribuert under MIT/X11 programvarelisensen, se medfølgende fil COPYING eller http://www.opensource.org/licenses/mit-license.php.
Dette produktet inneholder programvare utviklet av OpenSSL prosjektet for bruk i OpenSSL Toolkit (http://www.openssl.org/) og kryptografisk programvare skrevet av Eric Young (eay@cryptsoft.com) og UPnP programvare skrevet av Thomas Bernard.</translation>
</message>
<message>
<location filename="../aboutdialog.cpp" line="+14"/>
<source>Copyright</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>The RupayaCoin developers</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>AddressBookPage</name>
<message>
<location filename="../forms/addressbookpage.ui" line="+14"/>
<source>Address Book</source>
<translation>Adressebok</translation>
</message>
<message>
<location line="+19"/>
<source>Double-click to edit address or label</source>
<translation>Dobbeltklikk for å redigere adresse eller merkelapp</translation>
</message>
<message>
<location line="+27"/>
<source>Create a new address</source>
<translation>Lag en ny adresse</translation>
</message>
<message>
<location line="+14"/>
<source>Copy the currently selected address to the system clipboard</source>
<translation>Kopier den valgte adressen til systemets utklippstavle</translation>
</message>
<message>
<location line="-11"/>
<source>&New Address</source>
<translation>&Ny Adresse</translation>
</message>
<message>
<location filename="../addressbookpage.cpp" line="+63"/>
<source>These are your RupayaCoin addresses for receiving payments. You may want to give a different one to each sender so you can keep track of who is paying you.</source>
<translation>Dette er dine RupayaCoin-adresser for mottak av betalinger. Du kan gi forskjellige adresser til alle som skal betale deg for å holde bedre oversikt.</translation>
</message>
<message>
<location filename="../forms/addressbookpage.ui" line="+14"/>
<source>&Copy Address</source>
<translation>&Kopier Adresse</translation>
</message>
<message>
<location line="+11"/>
<source>Show &QR Code</source>
<translation>Vis &QR Kode</translation>
</message>
<message>
<location line="+11"/>
<source>Sign a message to prove you own a RupayaCoin address</source>
<translation>Signer en melding for å bevise at du eier en RupayaCoin-adresse</translation>
</message>
<message>
<location line="+3"/>
<source>Sign &Message</source>
<translation>Signér &Melding</translation>
</message>
<message>
<location line="+25"/>
<source>Delete the currently selected address from the list</source>
<translation>Slett den valgte adressen fra listen.</translation>
</message>
<message>
<location line="+27"/>
<source>Export the data in the current tab to a file</source>
<translation>Eksporter data fra nåværende fane til fil</translation>
</message>
<message>
<location line="+3"/>
<source>&Export</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-44"/>
<source>Verify a message to ensure it was signed with a specified RupayaCoin address</source>
<translation>Verifiser en melding for å være sikker på at den ble signert av en angitt RupayaCoin-adresse</translation>
</message>
<message>
<location line="+3"/>
<source>&Verify Message</source>
<translation>&Verifiser Melding</translation>
</message>
<message>
<location line="+14"/>
<source>&Delete</source>
<translation>&Slett</translation>
</message>
<message>
<location filename="../addressbookpage.cpp" line="-5"/>
<source>These are your RupayaCoin addresses for sending payments. Always check the amount and the receiving address before sending coins.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>Copy &Label</source>
<translation>Kopier &Merkelapp</translation>
</message>
<message>
<location line="+1"/>
<source>&Edit</source>
<translation>&Rediger</translation>
</message>
<message>
<location line="+1"/>
<source>Send &Coins</source>
<translation>Send &Coins</translation>
</message>
<message>
<location line="+260"/>
<source>Export Address Book Data</source>
<translation>Eksporter adressebok</translation>
</message>
<message>
<location line="+1"/>
<source>Comma separated file (*.csv)</source>
<translation>Kommaseparert fil (*.csv)</translation>
</message>
<message>
<location line="+13"/>
<source>Error exporting</source>
<translation>Feil ved eksportering</translation>
</message>
<message>
<location line="+0"/>
<source>Could not write to file %1.</source>
<translation>Kunne ikke skrive til filen %1.</translation>
</message>
</context>
<context>
<name>AddressTableModel</name>
<message>
<location filename="../addresstablemodel.cpp" line="+144"/>
<source>Label</source>
<translation>Merkelapp</translation>
</message>
<message>
<location line="+0"/>
<source>Address</source>
<translation>Adresse</translation>
</message>
<message>
<location line="+36"/>
<source>(no label)</source>
<translation>(ingen merkelapp)</translation>
</message>
</context>
<context>
<name>AskPassphraseDialog</name>
<message>
<location filename="../forms/askpassphrasedialog.ui" line="+26"/>
<source>Passphrase Dialog</source>
<translation>Dialog for Adgangsfrase</translation>
</message>
<message>
<location line="+21"/>
<source>Enter passphrase</source>
<translation>Angi adgangsfrase</translation>
</message>
<message>
<location line="+14"/>
<source>New passphrase</source>
<translation>Ny adgangsfrase</translation>
</message>
<message>
<location line="+14"/>
<source>Repeat new passphrase</source>
<translation>Gjenta ny adgangsfrase</translation>
</message>
<message>
<location filename="../askpassphrasedialog.cpp" line="+33"/>
<source>Enter the new passphrase to the wallet.<br/>Please use a passphrase of <b>10 or more random characters</b>, or <b>eight or more words</b>.</source>
<translation>Skriv inn den nye adgangsfrasen for lommeboken.<br/>Vennligst bruk en adgangsfrase med <b>10 eller flere tilfeldige tegn</b>, eller <b>åtte eller flere ord</b>.</translation>
</message>
<message>
<location line="+1"/>
<source>Encrypt wallet</source>
<translation>Krypter lommebok</translation>
</message>
<message>
<location line="+3"/>
<source>This operation needs your wallet passphrase to unlock the wallet.</source>
<translation>Denne operasjonen krever adgangsfrasen til lommeboken for å låse den opp.</translation>
</message>
<message>
<location line="+5"/>
<source>Unlock wallet</source>
<translation>Lås opp lommebok</translation>
</message>
<message>
<location line="+3"/>
<source>This operation needs your wallet passphrase to decrypt the wallet.</source>
<translation>Denne operasjonen krever adgangsfrasen til lommeboken for å dekryptere den.</translation>
</message>
<message>
<location line="+5"/>
<source>Decrypt wallet</source>
<translation>Dekrypter lommebok</translation>
</message>
<message>
<location line="+3"/>
<source>Change passphrase</source>
<translation>Endre adgangsfrase</translation>
</message>
<message>
<location line="+1"/>
<source>Enter the old and new passphrase to the wallet.</source>
<translation>Skriv inn gammel og ny adgangsfrase for lommeboken.</translation>
</message>
<message>
<location line="+46"/>
<source>Confirm wallet encryption</source>
<translation>Bekreft kryptering av lommebok</translation>
</message>
<message>
<location line="+1"/>
<source>Warning: If you encrypt your wallet and lose your passphrase, you will <b>LOSE ALL OF YOUR RupayaCoinS</b>!</source>
<translation>Advarsel: Hvis du krypterer lommeboken og mister adgangsfrasen, så vil du <b>MISTE ALLE DINE RupayaCoinS</b>!</translation>
</message>
<message>
<location line="+0"/>
<source>Are you sure you wish to encrypt your wallet?</source>
<translation>Er du sikker på at du vil kryptere lommeboken?</translation>
</message>
<message>
<location line="+15"/>
<source>IMPORTANT: Any previous backups you have made of your wallet file should be replaced with the newly generated, encrypted wallet file. For security reasons, previous backups of the unencrypted wallet file will become useless as soon as you start using the new, encrypted wallet.</source>
<translation>VIKTIG: Tidligere sikkerhetskopier av din lommebok-fil, bør erstattes med den nylig genererte, krypterte filen, da de blir ugyldiggjort av sikkerhetshensyn så snart du begynner å bruke den nye krypterte lommeboken.</translation>
</message>
<message>
<location line="+100"/>
<location line="+24"/>
<source>Warning: The Caps Lock key is on!</source>
<translation>Advarsel: Caps Lock er på !</translation>
</message>
<message>
<location line="-130"/>
<location line="+58"/>
<source>Wallet encrypted</source>
<translation>Lommebok kryptert</translation>
</message>
<message>
<location line="-56"/>
<source>RupayaCoin will close now to finish the encryption process. Remember that encrypting your wallet cannot fully protect your RupayaCoins from being stolen by malware infecting your computer.</source>
<translation>RupayaCoin vil nå lukkes for å fullføre krypteringsprosessen. Husk at kryptering av lommeboken ikke fullt ut kan beskytte dine RupayaCoins fra å bli stjålet om skadevare infiserer datamaskinen.</translation>
</message>
<message>
<location line="+13"/>
<location line="+7"/>
<location line="+42"/>
<location line="+6"/>
<source>Wallet encryption failed</source>
<translation>Kryptering av lommebok feilet</translation>
</message>
<message>
<location line="-54"/>
<source>Wallet encryption failed due to an internal error. Your wallet was not encrypted.</source>
<translation>Kryptering av lommebok feilet på grunn av en intern feil. Din lommebok ble ikke kryptert.</translation>
</message>
<message>
<location line="+7"/>
<location line="+48"/>
<source>The supplied passphrases do not match.</source>
<translation>De angitte adgangsfrasene er ulike.</translation>
</message>
<message>
<location line="-37"/>
<source>Wallet unlock failed</source>
<translation>Opplåsing av lommebok feilet</translation>
</message>
<message>
<location line="+1"/>
<location line="+11"/>
<location line="+19"/>
<source>The passphrase entered for the wallet decryption was incorrect.</source>
<translation>Adgangsfrasen angitt for dekryptering av lommeboken var feil.</translation>
</message>
<message>
<location line="-20"/>
<source>Wallet decryption failed</source>
<translation>Dekryptering av lommebok feilet</translation>
</message>
<message>
<location line="+14"/>
<source>Wallet passphrase was successfully changed.</source>
<translation>Adgangsfrase for lommebok endret.</translation>
</message>
</context>
<context>
<name>BitcoinGUI</name>
<message>
<location filename="../bitcoingui.cpp" line="+233"/>
<source>Sign &message...</source>
<translation>Signer &melding...</translation>
</message>
<message>
<location line="+280"/>
<source>Synchronizing with network...</source>
<translation>Synkroniserer med nettverk...</translation>
</message>
<message>
<location line="-349"/>
<source>&Overview</source>
<translation>&Oversikt</translation>
</message>
<message>
<location line="+1"/>
<source>Show general overview of wallet</source>
<translation>Vis generell oversikt over lommeboken</translation>
</message>
<message>
<location line="+20"/>
<source>&Transactions</source>
<translation>&Transaksjoner</translation>
</message>
<message>
<location line="+1"/>
<source>Browse transaction history</source>
<translation>Vis transaksjonshistorikk</translation>
</message>
<message>
<location line="+7"/>
<source>Edit the list of stored addresses and labels for sending</source>
<translation>Rediger listen over adresser og deres merkelapper</translation>
</message>
<message>
<location line="-14"/>
<source>Show the list of addresses for receiving payments</source>
<translation>Vis listen over adresser for mottak av betalinger</translation>
</message>
<message>
<location line="+31"/>
<source>E&xit</source>
<translation>&Avslutt</translation>
</message>
<message>
<location line="+1"/>
<source>Quit application</source>
<translation>Avslutt applikasjonen</translation>
</message>
<message>
<location line="+4"/>
<source>Show information about RupayaCoin</source>
<translation>Vis informasjon om RupayaCoin</translation>
</message>
<message>
<location line="+2"/>
<source>About &Qt</source>
<translation>Om &Qt</translation>
</message>
<message>
<location line="+1"/>
<source>Show information about Qt</source>
<translation>Vis informasjon om Qt</translation>
</message>
<message>
<location line="+2"/>
<source>&Options...</source>
<translation>&Innstillinger...</translation>
</message>
<message>
<location line="+6"/>
<source>&Encrypt Wallet...</source>
<translation>&Krypter Lommebok...</translation>
</message>
<message>
<location line="+3"/>
<source>&Backup Wallet...</source>
<translation>Lag &Sikkerhetskopi av Lommebok...</translation>
</message>
<message>
<location line="+2"/>
<source>&Change Passphrase...</source>
<translation>&Endre Adgangsfrase...</translation>
</message>
<message>
<location line="+285"/>
<source>Importing blocks from disk...</source>
<translation>Importere blokker...</translation>
</message>
<message>
<location line="+3"/>
<source>Reindexing blocks on disk...</source>
<translation>Re-indekserer blokker på disk...</translation>
</message>
<message>
<location line="-347"/>
<source>Send coins to a RupayaCoin address</source>
<translation>Send til en RupayaCoin-adresse</translation>
</message>
<message>
<location line="+49"/>
<source>Modify configuration options for RupayaCoin</source>
<translation>Endre oppsett for RupayaCoin</translation>
</message>
<message>
<location line="+9"/>
<source>Backup wallet to another location</source>
<translation>Sikkerhetskopiér lommebok til annet sted</translation>
</message>
<message>
<location line="+2"/>
<source>Change the passphrase used for wallet encryption</source>
<translation>Endre adgangsfrasen brukt for kryptering av lommebok</translation>
</message>
<message>
<location line="+6"/>
<source>&Debug window</source>
<translation>&Feilsøkingsvindu</translation>
</message>
<message>
<location line="+1"/>
<source>Open debugging and diagnostic console</source>
<translation>Åpne konsoll for feilsøk og diagnostikk</translation>
</message>
<message>
<location line="-4"/>
<source>&Verify message...</source>
<translation>&Verifiser melding...</translation>
</message>
<message>
<location line="-165"/>
<location line="+530"/>
<source>RupayaCoin</source>
<translation>RupayaCoin</translation>
</message>
<message>
<location line="-530"/>
<source>Wallet</source>
<translation>Lommebok</translation>
</message>
<message>
<location line="+101"/>
<source>&Send</source>
<translation>&Send</translation>
</message>
<message>
<location line="+7"/>
<source>&Receive</source>
<translation>&Motta</translation>
</message>
<message>
<location line="+14"/>
<source>&Addresses</source>
<translation>&Adressebok</translation>
</message>
<message>
<location line="+22"/>
<source>&About RupayaCoin</source>
<translation>&Om RupayaCoin</translation>
</message>
<message>
<location line="+9"/>
<source>&Show / Hide</source>
<translation>&Gjem / vis</translation>
</message>
<message>
<location line="+1"/>
<source>Show or hide the main Window</source>
<translation>Vis eller skjul hovedvinduet</translation>
</message>
<message>
<location line="+3"/>
<source>Encrypt the private keys that belong to your wallet</source>
<translation>Krypter de private nøklene som tilhører lommeboken din</translation>
</message>
<message>
<location line="+7"/>
<source>Sign messages with your RupayaCoin addresses to prove you own them</source>
<translation>Signér en melding for å bevise at du eier denne adressen</translation>
</message>
<message>
<location line="+2"/>
<source>Verify messages to ensure they were signed with specified RupayaCoin addresses</source>
<translation>Bekreft meldinger for å være sikker på at de ble signert av en angitt RupayaCoin-adresse</translation>
</message>
<message>
<location line="+28"/>
<source>&File</source>
<translation>&Fil</translation>
</message>
<message>
<location line="+7"/>
<source>&Settings</source>
<translation>&Innstillinger</translation>
</message>
<message>
<location line="+6"/>
<source>&Help</source>
<translation>&Hjelp</translation>
</message>
<message>
<location line="+9"/>
<source>Tabs toolbar</source>
<translation>Verktøylinje for faner</translation>
</message>
<message>
<location line="+17"/>
<location line="+10"/>
<source>[testnet]</source>
<translation>[testnett]</translation>
</message>
<message>
<location line="+47"/>
<source>RupayaCoin client</source>
<translation>RupayaCoinklient</translation>
</message>
<message numerus="yes">
<location line="+141"/>
<source>%n active connection(s) to RupayaCoin network</source>
<translation><numerusform>%n aktiv forbindelse til RupayaCoin-nettverket</numerusform><numerusform>%n aktive forbindelser til RupayaCoin-nettverket</numerusform></translation>
</message>
<message>
<location line="+22"/>
<source>No block source available...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+12"/>
<source>Processed %1 of %2 (estimated) blocks of transaction history.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Processed %1 blocks of transaction history.</source>
<translation>Lastet %1 blokker med transaksjonshistorikk.</translation>
</message>
<message numerus="yes">
<location line="+20"/>
<source>%n hour(s)</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message numerus="yes">
<location line="+4"/>
<source>%n day(s)</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message numerus="yes">
<location line="+4"/>
<source>%n week(s)</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message>
<location line="+4"/>
<source>%1 behind</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+14"/>
<source>Last received block was generated %1 ago.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Transactions after this will not yet be visible.</source>
<translation>Transaksjoner etter dette vil ikke være synlige enda.</translation>
</message>
<message>
<location line="+22"/>
<source>Error</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Warning</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Information</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+70"/>
<source>This transaction is over the size limit. You can still send it for a fee of %1, which goes to the nodes that process your transaction and helps to support the network. Do you want to pay the fee?</source>
<translation>Denne transaksjonen overstiger størrelsesbegrensningen. Du kan likevel sende den med et gebyr på %1, som går til nodene som prosesserer transaksjonen din og støtter nettverket. Vil du betale gebyret?</translation>
</message>
<message>
<location line="-140"/>
<source>Up to date</source>
<translation>Ajour</translation>
</message>
<message>
<location line="+31"/>
<source>Catching up...</source>
<translation>Kommer ajour...</translation>
</message>
<message>
<location line="+113"/>
<source>Confirm transaction fee</source>
<translation>Bekreft transaksjonsgebyr</translation>
</message>
<message>
<location line="+8"/>
<source>Sent transaction</source>
<translation>Sendt transaksjon</translation>
</message>
<message>
<location line="+0"/>
<source>Incoming transaction</source>
<translation>Innkommende transaksjon</translation>
</message>
<message>
<location line="+1"/>
<source>Date: %1
Amount: %2
Type: %3
Address: %4
</source>
<translation>Dato: %1
Beløp: %2
Type: %3
Adresse: %4
</translation>
</message>
<message>
<location line="+33"/>
<location line="+23"/>
<source>URI handling</source>
<translation>URI håndtering</translation>
</message>
<message>
<location line="-23"/>
<location line="+23"/>
<source>URI can not be parsed! This can be caused by an invalid RupayaCoin address or malformed URI parameters.</source>
<translation>URI kunne ikke tolkes! Dette kan forårsakes av en ugyldig RupayaCoin-adresse eller feil i URI-parametere.</translation>
</message>
<message>
<location line="+17"/>
<source>Wallet is <b>encrypted</b> and currently <b>unlocked</b></source>
<translation>Lommeboken er <b>kryptert</b> og for tiden <b>ulåst</b></translation>
</message>
<message>
<location line="+8"/>
<source>Wallet is <b>encrypted</b> and currently <b>locked</b></source>
<translation>Lommeboken er <b>kryptert</b> og for tiden <b>låst</b></translation>
</message>
<message>
<location filename="../bitcoin.cpp" line="+111"/>
<source>A fatal error occurred. RupayaCoin can no longer continue safely and will quit.</source>
<translation>En fatal feil har inntruffet. Det er ikke trygt å fortsette og RupayaCoin må derfor avslutte.</translation>
</message>
</context>
<context>
<name>ClientModel</name>
<message>
<location filename="../clientmodel.cpp" line="+104"/>
<source>Network Alert</source>
<translation>Nettverksvarsel</translation>
</message>
</context>
<context>
<name>EditAddressDialog</name>
<message>
<location filename="../forms/editaddressdialog.ui" line="+14"/>
<source>Edit Address</source>
<translation>Rediger adresse</translation>
</message>
<message>
<location line="+11"/>
<source>&Label</source>
<translation>&Merkelapp</translation>
</message>
<message>
<location line="+10"/>
<source>The label associated with this address book entry</source>
<translation>Merkelappen koblet til denne adressen i adresseboken</translation>
</message>
<message>
<location line="+7"/>
<source>&Address</source>
<translation>&Adresse</translation>
</message>
<message>
<location line="+10"/>
<source>The address associated with this address book entry. This can only be modified for sending addresses.</source>
<translation>Adressen til denne oppføringen i adresseboken. Denne kan kun endres for utsendingsadresser.</translation>
</message>
<message>
<location filename="../editaddressdialog.cpp" line="+21"/>
<source>New receiving address</source>
<translation>Ny mottaksadresse</translation>
</message>
<message>
<location line="+4"/>
<source>New sending address</source>
<translation>Ny utsendingsadresse</translation>
</message>
<message>
<location line="+3"/>
<source>Edit receiving address</source>
<translation>Rediger mottaksadresse</translation>
</message>
<message>
<location line="+4"/>
<source>Edit sending address</source>
<translation>Rediger utsendingsadresse</translation>
</message>
<message>
<location line="+76"/>
<source>The entered address "%1" is already in the address book.</source>
<translation>Den oppgitte adressen "%1" er allerede i adresseboken.</translation>
</message>
<message>
<location line="-5"/>
<source>The entered address "%1" is not a valid RupayaCoin address.</source>
<translation>Den angitte adressed "%1" er ikke en gyldig RupayaCoin-adresse.</translation>
</message>
<message>
<location line="+10"/>
<source>Could not unlock wallet.</source>
<translation>Kunne ikke låse opp lommeboken.</translation>
</message>
<message>
<location line="+5"/>
<source>New key generation failed.</source>
<translation>Generering av ny nøkkel feilet.</translation>
</message>
</context>
<context>
<name>GUIUtil::HelpMessageBox</name>
<message>
<location filename="../guiutil.cpp" line="+424"/>
<location line="+12"/>
<source>RupayaCoin-Qt</source>
<translation>RupayaCoin-Qt</translation>
</message>
<message>
<location line="-12"/>
<source>version</source>
<translation>versjon</translation>
</message>
<message>
<location line="+2"/>
<source>Usage:</source>
<translation>Bruk:</translation>
</message>
<message>
<location line="+1"/>
<source>command-line options</source>
<translation>kommandolinjevalg</translation>
</message>
<message>
<location line="+4"/>
<source>UI options</source>
<translation>valg i brukergrensesnitt</translation>
</message>
<message>
<location line="+1"/>
<source>Set language, for example "de_DE" (default: system locale)</source>
<translation>Sett språk, for eksempel "nb_NO" (standardverdi: fra operativsystem)</translation>
</message>
<message>
<location line="+1"/>
<source>Start minimized</source>
<translation>Start minimert
</translation>
</message>
<message>
<location line="+1"/>
<source>Show splash screen on startup (default: 1)</source>
<translation>Vis splashskjerm ved oppstart (standardverdi: 1)</translation>
</message>
</context>
<context>
<name>OptionsDialog</name>
<message>
<location filename="../forms/optionsdialog.ui" line="+14"/>
<source>Options</source>
<translation>Innstillinger</translation>
</message>
<message>
<location line="+16"/>
<source>&Main</source>
<translation>&Hoved</translation>
</message>
<message>
<location line="+6"/>
<source>Optional transaction fee per kB that helps make sure your transactions are processed quickly. Most transactions are 1 kB.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+15"/>
<source>Pay transaction &fee</source>
<translation>Betal transaksjons&gebyr</translation>
</message>
<message>
<location line="+31"/>
<source>Automatically start RupayaCoin after logging in to the system.</source>
<translation>Start RupayaCoin automatisk etter innlogging.</translation>
</message>
<message>
<location line="+3"/>
<source>&Start RupayaCoin on system login</source>
<translation>&Start RupayaCoin ved systeminnlogging</translation>
</message>
<message>
<location line="+35"/>
<source>Reset all client options to default.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Reset Options</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>&Network</source>
<translation>&Nettverk</translation>
</message>
<message>
<location line="+6"/>
<source>Automatically open the RupayaCoin client port on the router. This only works when your router supports UPnP and it is enabled.</source>
<translation>Åpne automatisk RupayaCoin klientporten på ruteren. Dette virker kun om din ruter støtter UPnP og dette er påslått.</translation>
</message>
<message>
<location line="+3"/>
<source>Map port using &UPnP</source>
<translation>Sett opp port vha. &UPnP</translation>
</message>
<message>
<location line="+7"/>
<source>Connect to the RupayaCoin network through a SOCKS proxy (e.g. when connecting through Tor).</source>
<translation>Koble til RupayaCoin-nettverket gjennom en SOCKS proxy (f.eks. ved tilkobling gjennom Tor).</translation>
</message>
<message>
<location line="+3"/>
<source>&Connect through SOCKS proxy:</source>
<translation>&Koble til gjenom SOCKS proxy:</translation>
</message>
<message>
<location line="+9"/>
<source>Proxy &IP:</source>
<translation>Proxy &IP:</translation>
</message>
<message>
<location line="+19"/>
<source>IP address of the proxy (e.g. 127.0.0.1)</source>
<translation>IP-adresse for mellomtjener (f.eks. 127.0.0.1)</translation>
</message>
<message>
<location line="+7"/>
<source>&Port:</source>
<translation>&Port:</translation>
</message>
<message>
<location line="+19"/>
<source>Port of the proxy (e.g. 9050)</source>
<translation>Proxyens port (f.eks. 9050)</translation>
</message>
<message>
<location line="+7"/>
<source>SOCKS &Version:</source>
<translation>SOCKS &Versjon:</translation>
</message>
<message>
<location line="+13"/>
<source>SOCKS version of the proxy (e.g. 5)</source>
<translation>Proxyens SOCKS versjon (f.eks. 5)</translation>
</message>
<message>
<location line="+36"/>
<source>&Window</source>
<translation>&Vindu</translation>
</message>
<message>
<location line="+6"/>
<source>Show only a tray icon after minimizing the window.</source>
<translation>Vis kun ikon i systemkurv etter minimering av vinduet.</translation>
</message>
<message>
<location line="+3"/>
<source>&Minimize to the tray instead of the taskbar</source>
<translation>&Minimer til systemkurv istedenfor oppgavelinjen</translation>
</message>
<message>
<location line="+7"/>
<source>Minimize instead of exit the application when the window is closed. When this option is enabled, the application will be closed only after selecting Quit in the menu.</source>
<translation>Minimerer vinduet istedenfor å avslutte applikasjonen når vinduet lukkes. Når dette er slått på avsluttes applikasjonen kun ved å velge avslutt i menyen.</translation>
</message>
<message>
<location line="+3"/>
<source>M&inimize on close</source>
<translation>M&inimer ved lukking</translation>
</message>
<message>
<location line="+21"/>
<source>&Display</source>
<translation>&Visning</translation>
</message>
<message>
<location line="+8"/>
<source>User Interface &language:</source>
<translation>&Språk for brukergrensesnitt</translation>
</message>
<message>
<location line="+13"/>
<source>The user interface language can be set here. This setting will take effect after restarting RupayaCoin.</source>
<translation>Språket for brukergrensesnittet kan settes her. Innstillingen trer i kraft ved omstart av RupayaCoin.</translation>
</message>
<message>
<location line="+11"/>
<source>&Unit to show amounts in:</source>
<translation>&Enhet for visning av beløper:</translation>
</message>
<message>
<location line="+13"/>
<source>Choose the default subdivision unit to show in the interface and when sending coins.</source>
<translation>Velg standard delt enhet for visning i grensesnittet og for sending av RupayaCoins.</translation>
</message>
<message>
<location line="+9"/>
<source>Whether to show RupayaCoin addresses in the transaction list or not.</source>
<translation>Om RupayaCoin-adresser skal vises i transaksjonslisten eller ikke.</translation>
</message>
<message>
<location line="+3"/>
<source>&Display addresses in transaction list</source>
<translation>&Vis adresser i transaksjonslisten</translation>
</message>
<message>
<location line="+71"/>
<source>&OK</source>
<translation>&OK</translation>
</message>
<message>
<location line="+7"/>
<source>&Cancel</source>
<translation>&Avbryt</translation>
</message>
<message>
<location line="+10"/>
<source>&Apply</source>
<translation>&Bruk</translation>
</message>
<message>
<location filename="../optionsdialog.cpp" line="+53"/>
<source>default</source>
<translation>standardverdi</translation>
</message>
<message>
<location line="+130"/>
<source>Confirm options reset</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Some settings may require a client restart to take effect.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>Do you want to proceed?</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+42"/>
<location line="+9"/>
<source>Warning</source>
<translation>Advarsel</translation>
</message>
<message>
<location line="-9"/>
<location line="+9"/>
<source>This setting will take effect after restarting RupayaCoin.</source>
<translation>Denne innstillingen trer i kraft etter omstart av RupayaCoin.</translation>
</message>
<message>
<location line="+29"/>
<source>The supplied proxy address is invalid.</source>
<translation>Angitt proxyadresse er ugyldig.</translation>
</message>
</context>
<context>
<name>OverviewPage</name>
<message>
<location filename="../forms/overviewpage.ui" line="+14"/>
<source>Form</source>
<translation>Skjema</translation>
</message>
<message>
<location line="+50"/>
<location line="+166"/>
<source>The displayed information may be out of date. Your wallet automatically synchronizes with the RupayaCoin network after a connection is established, but this process has not completed yet.</source>
<translation>Informasjonen som vises kan være foreldet. Din lommebok synkroniseres automatisk med RupayaCoin-nettverket etter at tilkobling er opprettet, men denne prosessen er ikke ferdig enda.</translation>
</message>
<message>
<location line="-124"/>
<source>Balance:</source>
<translation>Saldo:</translation>
</message>
<message>
<location line="+29"/>
<source>Unconfirmed:</source>
<translation>Ubekreftet</translation>
</message>
<message>
<location line="-78"/>
<source>Wallet</source>
<translation>Lommebok</translation>
</message>
<message>
<location line="+107"/>
<source>Immature:</source>
<translation>Umoden:</translation>
</message>
<message>
<location line="+13"/>
<source>Mined balance that has not yet matured</source>
<translation>Minet saldo har ikke modnet enda</translation>
</message>
<message>
<location line="+46"/>
<source><b>Recent transactions</b></source>
<translation><b>Siste transaksjoner</b></translation>
</message>
<message>
<location line="-101"/>
<source>Your current balance</source>
<translation>Din nåværende saldo</translation>
</message>
<message>
<location line="+29"/>
<source>Total of transactions that have yet to be confirmed, and do not yet count toward the current balance</source>
<translation>Totalt antall ubekreftede transaksjoner som ikke telles med i saldo enda</translation>
</message>
<message>
<location filename="../overviewpage.cpp" line="+116"/>
<location line="+1"/>
<source>out of sync</source>
<translation>ute av synk</translation>
</message>
</context>
<context>
<name>PaymentServer</name>
<message>
<location filename="../paymentserver.cpp" line="+107"/>
<source>Cannot start RupayaCoin: click-to-pay handler</source>
<translation>Kan ikke starte RupayaCoin: klikk-og-betal håndterer</translation>
</message>
</context>
<context>
<name>QRCodeDialog</name>
<message>
<location filename="../forms/qrcodedialog.ui" line="+14"/>
<source>QR Code Dialog</source>
<translation>Dialog for QR Kode</translation>
</message>
<message>
<location line="+59"/>
<source>Request Payment</source>
<translation>Etterspør Betaling</translation>
</message>
<message>
<location line="+56"/>
<source>Amount:</source>
<translation>Beløp:</translation>
</message>
<message>
<location line="-44"/>
<source>Label:</source>
<translation>Merkelapp:</translation>
</message>
<message>
<location line="+19"/>
<source>Message:</source>
<translation>Melding:</translation>
</message>
<message>
<location line="+71"/>
<source>&Save As...</source>
<translation>&Lagre Som...</translation>
</message>
<message>
<location filename="../qrcodedialog.cpp" line="+62"/>
<source>Error encoding URI into QR Code.</source>
<translation>Feil ved koding av URI i QR kode.</translation>
</message>
<message>
<location line="+40"/>
<source>The entered amount is invalid, please check.</source>
<translation>Angitt beløp er ugyldig.</translation>
</message>
<message>
<location line="+23"/>
<source>Resulting URI too long, try to reduce the text for label / message.</source>
<translation>Resulterende URI for lang, prøv å redusere teksten for merkelapp / melding.</translation>
</message>
<message>
<location line="+25"/>
<source>Save QR Code</source>
<translation>Lagre QR Kode</translation>
</message>
<message>
<location line="+0"/>
<source>PNG Images (*.png)</source>
<translation>PNG bilder (*.png)</translation>
</message>
</context>
<context>
<name>RPCConsole</name>
<message>
<location filename="../forms/rpcconsole.ui" line="+46"/>
<source>Client name</source>
<translation>Klientnavn</translation>
</message>
<message>
<location line="+10"/>
<location line="+23"/>
<location line="+26"/>
<location line="+23"/>
<location line="+23"/>
<location line="+36"/>
<location line="+53"/>
<location line="+23"/>
<location line="+23"/>
<location filename="../rpcconsole.cpp" line="+339"/>
<source>N/A</source>
<translation>-</translation>
</message>
<message>
<location line="-217"/>
<source>Client version</source>
<translation>Klientversjon</translation>
</message>
<message>
<location line="-45"/>
<source>&Information</source>
<translation>&Informasjon</translation>
</message>
<message>
<location line="+68"/>
<source>Using OpenSSL version</source>
<translation>Bruker OpenSSL versjon</translation>
</message>
<message>
<location line="+49"/>
<source>Startup time</source>
<translation>Oppstartstidspunkt</translation>
</message>
<message>
<location line="+29"/>
<source>Network</source>
<translation>Nettverk</translation>
</message>
<message>
<location line="+7"/>
<source>Number of connections</source>
<translation>Antall tilkoblinger</translation>
</message>
<message>
<location line="+23"/>
<source>On testnet</source>
<translation>På testnett</translation>
</message>
<message>
<location line="+23"/>
<source>Block chain</source>
<translation>Blokkjeden</translation>
</message>
<message>
<location line="+7"/>
<source>Current number of blocks</source>
<translation>Nåværende antall blokker</translation>
</message>
<message>
<location line="+23"/>
<source>Estimated total blocks</source>
<translation>Estimert totalt antall blokker</translation>
</message>
<message>
<location line="+23"/>
<source>Last block time</source>
<translation>Tidspunkt for siste blokk</translation>
</message>
<message>
<location line="+52"/>
<source>&Open</source>
<translation>&Åpne</translation>
</message>
<message>
<location line="+16"/>
<source>Command-line options</source>
<translation>Kommandolinjevalg</translation>
</message>
<message>
<location line="+7"/>
<source>Show the RupayaCoin-Qt help message to get a list with possible RupayaCoin command-line options.</source>
<translation>Vis RupayaCoin-Qt hjelpemelding for å få en liste med mulige kommandolinjevalg.</translation>
</message>
<message>
<location line="+3"/>
<source>&Show</source>
<translation>&Vis</translation>
</message>
<message>
<location line="+24"/>
<source>&Console</source>
<translation>&Konsoll</translation>
</message>
<message>
<location line="-260"/>
<source>Build date</source>
<translation>Byggedato</translation>
</message>
<message>
<location line="-104"/>
<source>RupayaCoin - Debug window</source>
<translation>RupayaCoin - vindu for feilsøk</translation>
</message>
<message>
<location line="+25"/>
<source>RupayaCoin Core</source>
<translation>RupayaCoin Kjerne</translation>
</message>
<message>
<location line="+279"/>
<source>Debug log file</source>
<translation>Loggfil for feilsøk</translation>
</message>
<message>
<location line="+7"/>
<source>Open the RupayaCoin debug log file from the current data directory. This can take a few seconds for large log files.</source>
<translation>Åpne RupayaCoin loggfil for feilsøk fra datamappen. Dette kan ta noen sekunder for store loggfiler.</translation>
</message>
<message>
<location line="+102"/>
<source>Clear console</source>
<translation>Tøm konsoll</translation>
</message>
<message>
<location filename="../rpcconsole.cpp" line="-30"/>
<source>Welcome to the RupayaCoin RPC console.</source>
<translation>Velkommen til RupayaCoin RPC konsoll.</translation>
</message>
<message>
<location line="+1"/>
<source>Use up and down arrows to navigate history, and <b>Ctrl-L</b> to clear screen.</source>
<translation>Bruk opp og ned pil for å navigere historikken, og <b>Ctrl-L</b> for å tømme skjermen.</translation>
</message>
<message>
<location line="+1"/>
<source>Type <b>help</b> for an overview of available commands.</source>
<translation>Skriv <b>help</b> for en oversikt over kommandoer.</translation>
</message>
</context>
<context>
<name>SendCoinsDialog</name>
<message>
<location filename="../forms/sendcoinsdialog.ui" line="+14"/>
<location filename="../sendcoinsdialog.cpp" line="+124"/>
<location line="+5"/>
<location line="+5"/>
<location line="+5"/>
<location line="+6"/>
<location line="+5"/>
<location line="+5"/>
<source>Send Coins</source>
<translation>Send RupayaCoins</translation>
</message>
<message>
<location line="+50"/>
<source>Send to multiple recipients at once</source>
<translation>Send til flere enn én mottaker</translation>
</message>
<message>
<location line="+3"/>
<source>Add &Recipient</source>
<translation>&Legg til Mottaker</translation>
</message>
<message>
<location line="+20"/>
<source>Remove all transaction fields</source>
<translation>Fjern alle transaksjonsfelter</translation>
</message>
<message>
<location line="+3"/>
<source>Clear &All</source>
<translation>Fjern &Alt</translation>
</message>
<message>
<location line="+22"/>
<source>Balance:</source>
<translation>Saldo:</translation>
</message>
<message>
<location line="+10"/>
<source>123.456 BTC</source>
<translation>123.456 BTC</translation>
</message>
<message>
<location line="+31"/>
<source>Confirm the send action</source>
<translation>Bekreft sending</translation>
</message>
<message>
<location line="+3"/>
<source>S&end</source>
<translation>S&end</translation>
</message>
<message>
<location filename="../sendcoinsdialog.cpp" line="-59"/>
<source><b>%1</b> to %2 (%3)</source>
<translation><b>%1</b> til %2 (%3)</translation>
</message>
<message>
<location line="+5"/>
<source>Confirm send coins</source>
<translation>Bekreft sending av RupayaCoins</translation>
</message>
<message>
<location line="+1"/>
<source>Are you sure you want to send %1?</source>
<translation>Er du sikker på at du vil sende %1?</translation>
</message>
<message>
<location line="+0"/>
<source> and </source>
<translation> og </translation>
</message>
<message>
<location line="+23"/>
<source>The recipient address is not valid, please recheck.</source>
<translation>Adresse for mottaker er ugyldig.</translation>
</message>
<message>
<location line="+5"/>
<source>The amount to pay must be larger than 0.</source>
<translation>Beløpen som skal betales må være over 0.</translation>
</message>
<message>
<location line="+5"/>
<source>The amount exceeds your balance.</source>
<translation>Beløpet overstiger saldo.</translation>
</message>
<message>
<location line="+5"/>
<source>The total exceeds your balance when the %1 transaction fee is included.</source>
<translation>Totalbeløpet overstiger saldo etter at %1 transaksjonsgebyr er lagt til.</translation>
</message>
<message>
<location line="+6"/>
<source>Duplicate address found, can only send to each address once per send operation.</source>
<translation>Duplikate adresser funnet. Kan bare sende én gang til hver adresse per operasjon.</translation>
</message>
<message>
<location line="+5"/>
<source>Error: Transaction creation failed!</source>
<translation>Feil: Opprettelse av transaksjon feilet </translation>
</message>
<message>
<location line="+5"/>
<source>Error: The transaction was rejected. This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source>
<translation>Feil: Transaksjonen ble avvist. Dette kan skje om noe av beløpet allerede var brukt, f.eks. hvis du kopierte wallet.dat og noen RupayaCoins ble brukt i kopien men ikke ble markert som brukt her.</translation>
</message>
</context>
<context>
<name>SendCoinsEntry</name>
<message>
<location filename="../forms/sendcoinsentry.ui" line="+14"/>
<source>Form</source>
<translation>Skjema</translation>
</message>
<message>
<location line="+15"/>
<source>A&mount:</source>
<translation>&Beløp:</translation>
</message>
<message>
<location line="+13"/>
<source>Pay &To:</source>
<translation>Betal &Til:</translation>
</message>
<message>
<location line="+34"/>
<source>The address to send the payment to (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source>
<translation>Adressen betalingen skal sendes til (f.eks. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</translation>
</message>
<message>
<location line="+60"/>
<location filename="../sendcoinsentry.cpp" line="+26"/>
<source>Enter a label for this address to add it to your address book</source>
<translation>Skriv inn en merkelapp for denne adressen for å legge den til i din adressebok</translation>
</message>
<message>
<location line="-78"/>
<source>&Label:</source>
<translation>&Merkelapp:</translation>
</message>
<message>
<location line="+28"/>
<source>Choose address from address book</source>
<translation>Velg adresse fra adresseboken</translation>
</message>
<message>
<location line="+10"/>
<source>Alt+A</source>
<translation>Alt+A</translation>
</message>
<message>
<location line="+7"/>
<source>Paste address from clipboard</source>
<translation>Lim inn adresse fra utklippstavlen</translation>
</message>
<message>
<location line="+10"/>
<source>Alt+P</source>
<translation>Alt+P</translation>
</message>
<message>
<location line="+7"/>
<source>Remove this recipient</source>
<translation>Fjern denne mottakeren</translation>
</message>
<message>
<location filename="../sendcoinsentry.cpp" line="+1"/>
<source>Enter a RupayaCoin address (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source>
<translation>Skriv inn en RupayaCoin adresse (f.eks. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</translation>
</message>
</context>
<context>
<name>SignVerifyMessageDialog</name>
<message>
<location filename="../forms/signverifymessagedialog.ui" line="+14"/>
<source>Signatures - Sign / Verify a Message</source>
<translation>Signaturer - Signer / Verifiser en melding</translation>
</message>
<message>
<location line="+13"/>
<source>&Sign Message</source>
<translation>&Signér Melding</translation>
</message>
<message>
<location line="+6"/>
<source>You can sign messages with your addresses to prove you own them. Be careful not to sign anything vague, as phishing attacks may try to trick you into signing your identity over to them. Only sign fully-detailed statements you agree to.</source>
<translation>Du kan signere meldinger med dine adresser for å bevise at du eier dem. Ikke signér vage meldinger da phishing-angrep kan prøve å lure deg til å signere din identitet over til andre. Signér kun fullt detaljerte utsagn som du er enig i.</translation>
</message>
<message>
<location line="+18"/>
<source>The address to sign the message with (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source>
<translation>Adressen for signering av meldingen (f.eks. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</translation>
</message>
<message>
<location line="+10"/>
<location line="+213"/>
<source>Choose an address from the address book</source>
<translation>Velg en adresse fra adresseboken</translation>
</message>
<message>
<location line="-203"/>
<location line="+213"/>
<source>Alt+A</source>
<translation>Alt+A</translation>
</message>
<message>
<location line="-203"/>
<source>Paste address from clipboard</source>
<translation>Lim inn adresse fra utklippstavlen</translation>
</message>
<message>
<location line="+10"/>
<source>Alt+P</source>
<translation>Alt+P</translation>
</message>
<message>
<location line="+12"/>
<source>Enter the message you want to sign here</source>
<translation>Skriv inn meldingen du vil signere her</translation>
</message>
<message>
<location line="+7"/>
<source>Signature</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+27"/>
<source>Copy the current signature to the system clipboard</source>
<translation>Kopier valgt signatur til utklippstavle</translation>
</message>
<message>
<location line="+21"/>
<source>Sign the message to prove you own this RupayaCoin address</source>
<translation>Signer meldingen for å bevise at du eier denne RupayaCoin-adressen</translation>
</message>
<message>
<location line="+3"/>
<source>Sign &Message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+14"/>
<source>Reset all sign message fields</source>
<translation>Tilbakestill alle felter for meldingssignering</translation>
</message>
<message>
<location line="+3"/>
<location line="+146"/>
<source>Clear &All</source>
<translation>Fjern &Alt</translation>
</message>
<message>
<location line="-87"/>
<source>&Verify Message</source>
<translation>&Verifiser Melding</translation>
</message>
<message>
<location line="+6"/>
<source>Enter the signing address, message (ensure you copy line breaks, spaces, tabs, etc. exactly) and signature below to verify the message. Be careful not to read more into the signature than what is in the signed message itself, to avoid being tricked by a man-in-the-middle attack.</source>
<translation>Angi adresse for signering, melding (vær sikker på at du kopierer linjeskift, mellomrom, tab, etc. helt nøyaktig) og signatur under for å verifisere meldingen. Vær forsiktig med at du ikke gir signaturen mer betydning enn det som faktisk står i meldingen, for å unngå å bli lurt av såkalte "man-in-the-middle" angrep.</translation>
</message>
<message>
<location line="+21"/>
<source>The address the message was signed with (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source>
<translation>Adressen meldingen var signert med (f.eks. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</translation>
</message>
<message>
<location line="+40"/>
<source>Verify the message to ensure it was signed with the specified RupayaCoin address</source>
<translation>Verifiser meldingen for å være sikker på at den ble signert av den angitte RupayaCoin-adressen</translation>
</message>
<message>
<location line="+3"/>
<source>Verify &Message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+14"/>
<source>Reset all verify message fields</source>
<translation>Tilbakestill alle felter for meldingsverifikasjon</translation>
</message>
<message>
<location filename="../signverifymessagedialog.cpp" line="+27"/>
<location line="+3"/>
<source>Enter a RupayaCoin address (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source>
<translation>Skriv inn en RupayaCoin adresse (f.eks. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</translation>
</message>
<message>
<location line="-2"/>
<source>Click "Sign Message" to generate signature</source>
<translation>Klikk "Signer Melding" for å generere signatur</translation>
</message>
<message>
<location line="+3"/>
<source>Enter RupayaCoin signature</source>
<translation>Angi RupayaCoin signatur</translation>
</message>
<message>
<location line="+82"/>
<location line="+81"/>
<source>The entered address is invalid.</source>
<translation>Angitt adresse er ugyldig.</translation>
</message>
<message>
<location line="-81"/>
<location line="+8"/>
<location line="+73"/>
<location line="+8"/>
<source>Please check the address and try again.</source>
<translation>Vennligst sjekk adressen og prøv igjen.</translation>
</message>
<message>
<location line="-81"/>
<location line="+81"/>
<source>The entered address does not refer to a key.</source>
<translation>Angitt adresse refererer ikke til en nøkkel.</translation>
</message>
<message>
<location line="-73"/>
<source>Wallet unlock was cancelled.</source>
<translation>Opplåsing av lommebok ble avbrutt.</translation>
</message>
<message>
<location line="+8"/>
<source>Private key for the entered address is not available.</source>
<translation>Privat nøkkel for den angitte adressen er ikke tilgjengelig.</translation>
</message>
<message>
<location line="+12"/>
<source>Message signing failed.</source>
<translation>Signering av melding feilet.</translation>
</message>
<message>
<location line="+5"/>
<source>Message signed.</source>
<translation>Melding signert.</translation>
</message>
<message>
<location line="+59"/>
<source>The signature could not be decoded.</source>
<translation>Signaturen kunne ikke dekodes.</translation>
</message>
<message>
<location line="+0"/>
<location line="+13"/>
<source>Please check the signature and try again.</source>
<translation>Vennligst sjekk signaturen og prøv igjen.</translation>
</message>
<message>
<location line="+0"/>
<source>The signature did not match the message digest.</source>
<translation>Signaturen passer ikke til meldingen.</translation>
</message>
<message>
<location line="+7"/>
<source>Message verification failed.</source>
<translation>Verifikasjon av melding feilet.</translation>
</message>
<message>
<location line="+5"/>
<source>Message verified.</source>
<translation>Melding verifisert.</translation>
</message>
</context>
<context>
<name>SplashScreen</name>
<message>
<location filename="../splashscreen.cpp" line="+22"/>
<source>The RupayaCoin developers</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>[testnet]</source>
<translation>[testnett]</translation>
</message>
</context>
<context>
<name>TransactionDesc</name>
<message>
<location filename="../transactiondesc.cpp" line="+20"/>
<source>Open until %1</source>
<translation>Åpen til %1</translation>
</message>
<message>
<location line="+6"/>
<source>%1/offline</source>
<translation>%1/frakoblet</translation>
</message>
<message>
<location line="+2"/>
<source>%1/unconfirmed</source>
<translation>%1/ubekreftet</translation>
</message>
<message>
<location line="+2"/>
<source>%1 confirmations</source>
<translation>%1 bekreftelser</translation>
</message>
<message>
<location line="+18"/>
<source>Status</source>
<translation>Status</translation>
</message>
<message numerus="yes">
<location line="+7"/>
<source>, broadcast through %n node(s)</source>
<translation><numerusform>, kringkast gjennom %n node</numerusform><numerusform>, kringkast gjennom %n noder</numerusform></translation>
</message>
<message>
<location line="+4"/>
<source>Date</source>
<translation>Dato</translation>
</message>
<message>
<location line="+7"/>
<source>Source</source>
<translation>Kilde</translation>
</message>
<message>
<location line="+0"/>
<source>Generated</source>
<translation>Generert</translation>
</message>
<message>
<location line="+5"/>
<location line="+17"/>
<source>From</source>
<translation>Fra</translation>
</message>
<message>
<location line="+1"/>
<location line="+22"/>
<location line="+58"/>
<source>To</source>
<translation>Til</translation>
</message>
<message>
<location line="-77"/>
<location line="+2"/>
<source>own address</source>
<translation>egen adresse</translation>
</message>
<message>
<location line="-2"/>
<source>label</source>
<translation>merkelapp</translation>
</message>
<message>
<location line="+37"/>
<location line="+12"/>
<location line="+45"/>
<location line="+17"/>
<location line="+30"/>
<source>Credit</source>
<translation>Kredit</translation>
</message>
<message numerus="yes">
<location line="-102"/>
<source>matures in %n more block(s)</source>
<translation><numerusform>blir moden om %n blokk</numerusform><numerusform>blir moden om %n blokker</numerusform></translation>
</message>
<message>
<location line="+2"/>
<source>not accepted</source>
<translation>ikke akseptert</translation>
</message>
<message>
<location line="+44"/>
<location line="+8"/>
<location line="+15"/>
<location line="+30"/>
<source>Debit</source>
<translation>Debet</translation>
</message>
<message>
<location line="-39"/>
<source>Transaction fee</source>
<translation>Transaksjonsgebyr</translation>
</message>
<message>
<location line="+16"/>
<source>Net amount</source>
<translation>Nettobeløp</translation>
</message>
<message>
<location line="+6"/>
<source>Message</source>
<translation>Melding</translation>
</message>
<message>
<location line="+2"/>
<source>Comment</source>
<translation>Kommentar</translation>
</message>
<message>
<location line="+2"/>
<source>Transaction ID</source>
<translation>Transaksjons-ID</translation>
</message>
<message>
<location line="+3"/>
<source>Generated coins must mature 120 blocks before they can be spent. When you generated this block, it was broadcast to the network to be added to the block chain. If it fails to get into the chain, its state will change to "not accepted" and it won't be spendable. This may occasionally happen if another node generates a block within a few seconds of yours.</source>
<translation>Genererte RupayaCoins må modnes 120 blokker før de kan brukes. Da du genererte denne blokken ble den kringkastet til nettverket for å legges til i blokkjeden. Hvis den ikke kommer inn i kjeden får den tilstanden "ikke akseptert" og vil ikke kunne brukes. Dette skjer noen ganger hvis en annen node genererer en blokk noen sekunder fra din.</translation>
</message>
<message>
<location line="+7"/>
<source>Debug information</source>
<translation>Informasjon for feilsøk</translation>
</message>
<message>
<location line="+8"/>
<source>Transaction</source>
<translation>Transaksjon</translation>
</message>
<message>
<location line="+3"/>
<source>Inputs</source>
<translation>Inndata</translation>
</message>
<message>
<location line="+23"/>
<source>Amount</source>
<translation>Beløp</translation>
</message>
<message>
<location line="+1"/>
<source>true</source>
<translation>sann</translation>
</message>
<message>
<location line="+0"/>
<source>false</source>
<translation>usann</translation>
</message>
<message>
<location line="-209"/>
<source>, has not been successfully broadcast yet</source>
<translation>, har ikke blitt kringkastet uten problemer enda.</translation>
</message>
<message numerus="yes">
<location line="-35"/>
<source>Open for %n more block(s)</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message>
<location line="+70"/>
<source>unknown</source>
<translation>ukjent</translation>
</message>
</context>
<context>
<name>TransactionDescDialog</name>
<message>
<location filename="../forms/transactiondescdialog.ui" line="+14"/>
<source>Transaction details</source>
<translation>Transaksjonsdetaljer</translation>
</message>
<message>
<location line="+6"/>
<source>This pane shows a detailed description of the transaction</source>
<translation>Her vises en detaljert beskrivelse av transaksjonen</translation>
</message>
</context>
<context>
<name>TransactionTableModel</name>
<message>
<location filename="../transactiontablemodel.cpp" line="+225"/>
<source>Date</source>
<translation>Dato</translation>
</message>
<message>
<location line="+0"/>
<source>Type</source>
<translation>Type</translation>
</message>
<message>
<location line="+0"/>
<source>Address</source>
<translation>Adresse</translation>
</message>
<message>
<location line="+0"/>
<source>Amount</source>
<translation>Beløp</translation>
</message>
<message numerus="yes">
<location line="+57"/>
<source>Open for %n more block(s)</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message>
<location line="+3"/>
<source>Open until %1</source>
<translation>Åpen til %1</translation>
</message>
<message>
<location line="+3"/>
<source>Offline (%1 confirmations)</source>
<translation>Frakoblet (%1 bekreftelser)</translation>
</message>
<message>
<location line="+3"/>
<source>Unconfirmed (%1 of %2 confirmations)</source>
<translation>Ubekreftet (%1 av %2 bekreftelser)</translation>
</message>
<message>
<location line="+3"/>
<source>Confirmed (%1 confirmations)</source>
<translation>Bekreftet (%1 bekreftelser)</translation>
</message>
<message numerus="yes">
<location line="+8"/>
<source>Mined balance will be available when it matures in %n more block(s)</source>
<translation><numerusform>Minet saldo blir tilgjengelig når den modner om %n blokk</numerusform><numerusform>Minet saldo blir tilgjengelig når den modner om %n blokker</numerusform></translation>
</message>
<message>
<location line="+5"/>
<source>This block was not received by any other nodes and will probably not be accepted!</source>
<translation>Denne blokken har ikke blitt mottatt av noen andre noder og vil sannsynligvis ikke bli akseptert!</translation>
</message>
<message>
<location line="+3"/>
<source>Generated but not accepted</source>
<translation>Generert men ikke akseptert</translation>
</message>
<message>
<location line="+43"/>
<source>Received with</source>
<translation>Mottatt med</translation>
</message>
<message>
<location line="+2"/>
<source>Received from</source>
<translation>Mottatt fra</translation>
</message>
<message>
<location line="+3"/>
<source>Sent to</source>
<translation>Sendt til</translation>
</message>
<message>
<location line="+2"/>
<source>Payment to yourself</source>
<translation>Betaling til deg selv</translation>
</message>
<message>
<location line="+2"/>
<source>Mined</source>
<translation>Utvunnet</translation>
</message>
<message>
<location line="+38"/>
<source>(n/a)</source>
<translation>-</translation>
</message>
<message>
<location line="+199"/>
<source>Transaction status. Hover over this field to show number of confirmations.</source>
<translation>Transaksjonsstatus. Hold muspekeren over dette feltet for å se antall bekreftelser.</translation>
</message>
<message>
<location line="+2"/>
<source>Date and time that the transaction was received.</source>
<translation>Dato og tid for da transaksjonen ble mottat.</translation>
</message>
<message>
<location line="+2"/>
<source>Type of transaction.</source>
<translation>Type transaksjon.</translation>
</message>
<message>
<location line="+2"/>
<source>Destination address of transaction.</source>
<translation>Mottaksadresse for transaksjonen</translation>
</message>
<message>
<location line="+2"/>
<source>Amount removed from or added to balance.</source>
<translation>Beløp fjernet eller lagt til saldo.</translation>
</message>
</context>
<context>
<name>TransactionView</name>
<message>
<location filename="../transactionview.cpp" line="+52"/>
<location line="+16"/>
<source>All</source>
<translation>Alle</translation>
</message>
<message>
<location line="-15"/>
<source>Today</source>
<translation>I dag</translation>
</message>
<message>
<location line="+1"/>
<source>This week</source>
<translation>Denne uken</translation>
</message>
<message>
<location line="+1"/>
<source>This month</source>
<translation>Denne måneden</translation>
</message>
<message>
<location line="+1"/>
<source>Last month</source>
<translation>Forrige måned</translation>
</message>
<message>
<location line="+1"/>
<source>This year</source>
<translation>Dette året</translation>
</message>
<message>
<location line="+1"/>
<source>Range...</source>
<translation>Intervall...</translation>
</message>
<message>
<location line="+11"/>
<source>Received with</source>
<translation>Mottatt med</translation>
</message>
<message>
<location line="+2"/>
<source>Sent to</source>
<translation>Sendt til</translation>
</message>
<message>
<location line="+2"/>
<source>To yourself</source>
<translation>Til deg selv</translation>
</message>
<message>
<location line="+1"/>
<source>Mined</source>
<translation>Utvunnet</translation>
</message>
<message>
<location line="+1"/>
<source>Other</source>
<translation>Andre</translation>
</message>
<message>
<location line="+7"/>
<source>Enter address or label to search</source>
<translation>Skriv inn adresse eller merkelapp for søk</translation>
</message>
<message>
<location line="+7"/>
<source>Min amount</source>
<translation>Minimumsbeløp</translation>
</message>
<message>
<location line="+34"/>
<source>Copy address</source>
<translation>Kopier adresse</translation>
</message>
<message>
<location line="+1"/>
<source>Copy label</source>
<translation>Kopier merkelapp</translation>
</message>
<message>
<location line="+1"/>
<source>Copy amount</source>
<translation>Kopiér beløp</translation>
</message>
<message>
<location line="+1"/>
<source>Copy transaction ID</source>
<translation>Kopier transaksjons-ID</translation>
</message>
<message>
<location line="+1"/>
<source>Edit label</source>
<translation>Rediger merkelapp</translation>
</message>
<message>
<location line="+1"/>
<source>Show transaction details</source>
<translation>Vis transaksjonsdetaljer</translation>
</message>
<message>
<location line="+139"/>
<source>Export Transaction Data</source>
<translation>Eksporter transaksjonsdata</translation>
</message>
<message>
<location line="+1"/>
<source>Comma separated file (*.csv)</source>
<translation>Kommaseparert fil (*.csv)</translation>
</message>
<message>
<location line="+8"/>
<source>Confirmed</source>
<translation>Bekreftet</translation>
</message>
<message>
<location line="+1"/>
<source>Date</source>
<translation>Dato</translation>
</message>
<message>
<location line="+1"/>
<source>Type</source>
<translation>Type</translation>
</message>
<message>
<location line="+1"/>
<source>Label</source>
<translation>Merkelapp</translation>
</message>
<message>
<location line="+1"/>
<source>Address</source>
<translation>Adresse</translation>
</message>
<message>
<location line="+1"/>
<source>Amount</source>
<translation>Beløp</translation>
</message>
<message>
<location line="+1"/>
<source>ID</source>
<translation>ID</translation>
</message>
<message>
<location line="+4"/>
<source>Error exporting</source>
<translation>Feil ved eksport</translation>
</message>
<message>
<location line="+0"/>
<source>Could not write to file %1.</source>
<translation>Kunne ikke skrive til filen %1.</translation>
</message>
<message>
<location line="+100"/>
<source>Range:</source>
<translation>Intervall:</translation>
</message>
<message>
<location line="+8"/>
<source>to</source>
<translation>til</translation>
</message>
</context>
<context>
<name>WalletModel</name>
<message>
<location filename="../walletmodel.cpp" line="+193"/>
<source>Send Coins</source>
<translation>Send RupayaCoins</translation>
</message>
</context>
<context>
<name>WalletView</name>
<message>
<location filename="../walletview.cpp" line="+42"/>
<source>&Export</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Export the data in the current tab to a file</source>
<translation>Eksporter data fra nåværende fane til fil</translation>
</message>
<message>
<location line="+193"/>
<source>Backup Wallet</source>
<translation>Sikkerhetskopier lommebok</translation>
</message>
<message>
<location line="+0"/>
<source>Wallet Data (*.dat)</source>
<translation>Lommebokdata (*.dat)</translation>
</message>
<message>
<location line="+3"/>
<source>Backup Failed</source>
<translation>Sikkerhetskopiering feilet</translation>
</message>
<message>
<location line="+0"/>
<source>There was an error trying to save the wallet data to the new location.</source>
<translation>En feil oppstod under lagringen av lommeboken til den nye plasseringen.</translation>
</message>
<message>
<location line="+4"/>
<source>Backup Successful</source>
<translation>Sikkerhetskopiering fullført</translation>
</message>
<message>
<location line="+0"/>
<source>The wallet data was successfully saved to the new location.</source>
<translation>Lommebokdata ble lagret til den nye plasseringen. </translation>
</message>
</context>
<context>
<name>bitcoin-core</name>
<message>
<location filename="../bitcoinstrings.cpp" line="+94"/>
<source>RupayaCoin version</source>
<translation>RupayaCoin versjon</translation>
</message>
<message>
<location line="+102"/>
<source>Usage:</source>
<translation>Bruk:</translation>
</message>
<message>
<location line="-29"/>
<source>Send command to -server or RupayaCoind</source>
<translation>Send kommando til -server eller RupayaCoind</translation>
</message>
<message>
<location line="-23"/>
<source>List commands</source>
<translation>List opp kommandoer</translation>
</message>
<message>
<location line="-12"/>
<source>Get help for a command</source>
<translation>Vis hjelpetekst for en kommando</translation>
</message>
<message>
<location line="+24"/>
<source>Options:</source>
<translation>Innstillinger:</translation>
</message>
<message>
<location line="+24"/>
<source>Specify configuration file (default: RupayaCoin.conf)</source>
<translation>Angi konfigurasjonsfil (standardverdi: RupayaCoin.conf)</translation>
</message>
<message>
<location line="+3"/>
<source>Specify pid file (default: RupayaCoind.pid)</source>
<translation>Angi pid-fil (standardverdi: RupayaCoind.pid)</translation>
</message>
<message>
<location line="-1"/>
<source>Specify data directory</source>
<translation>Angi mappe for datafiler</translation>
</message>
<message>
<location line="-9"/>
<source>Set database cache size in megabytes (default: 25)</source>
<translation>Sett størrelse på mellomlager for database i megabytes (standardverdi: 25)</translation>
</message>
<message>
<location line="-28"/>
<source>Listen for connections on <port> (default: 22556 or testnet: 44556)</source>
<translation>Lytt etter tilkoblinger på <port> (standardverdi: 22556 eller testnet: 44556)</translation>
</message>
<message>
<location line="+5"/>
<source>Maintain at most <n> connections to peers (default: 125)</source>
<translation>Hold maks <n> koblinger åpne til andre noder (standardverdi: 125)</translation>
</message>
<message>
<location line="-48"/>
<source>Connect to a node to retrieve peer addresses, and disconnect</source>
<translation>Koble til node for å hente adresser til andre noder, koble så fra igjen</translation>
</message>
<message>
<location line="+82"/>
<source>Specify your own public address</source>
<translation>Angi din egen offentlige adresse</translation>
</message>
<message>
<location line="+3"/>
<source>Threshold for disconnecting misbehaving peers (default: 100)</source>
<translation>Grenseverdi for å koble fra noder med dårlig oppførsel (standardverdi: 100)</translation>
</message>
<message>
<location line="-134"/>
<source>Number of seconds to keep misbehaving peers from reconnecting (default: 86400)</source>
<translation>Antall sekunder noder med dårlig oppførsel hindres fra å koble til på nytt (standardverdi: 86400)</translation>
</message>
<message>
<location line="-29"/>
<source>An error occurred while setting up the RPC port %u for listening on IPv4: %s</source>
<translation>En feil oppstod ved opprettelse av RPC port %u for lytting: %s</translation>
</message>
<message>
<location line="+27"/>
<source>Listen for JSON-RPC connections on <port> (default: 22555 or testnet: 44555)</source>
<translation>Lytt etter JSON-RPC tilkoblinger på <port> (standardverdi: 22555 or testnet: 44555)</translation>
</message>
<message>
<location line="+37"/>
<source>Accept command line and JSON-RPC commands</source>
<translation>Ta imot kommandolinje- og JSON-RPC-kommandoer</translation>
</message>
<message>
<location line="+76"/>
<source>Run in the background as a daemon and accept commands</source>
<translation>Kjør i bakgrunnen som daemon og ta imot kommandoer</translation>
</message>
<message>
<location line="+37"/>
<source>Use the test network</source>
<translation>Bruk testnettverket</translation>
</message>
<message>
<location line="-112"/>
<source>Accept connections from outside (default: 1 if no -proxy or -connect)</source>
<translation>Ta imot tilkoblinger fra utsiden (standardverdi: 1 hvis uten -proxy eller -connect)</translation>
</message>
<message>
<location line="-80"/>
<source>%s, you must set a rpcpassword in the configuration file:
%s
It is recommended you use the following random password:
rpcuser=RupayaCoinrpc
rpcpassword=%s
(you do not need to remember this password)
The username and password MUST NOT be the same.
If the file does not exist, create it with owner-readable-only file permissions.
It is also recommended to set alertnotify so you are notified of problems;
for example: alertnotify=echo %%s | mail -s "RupayaCoin Alert" admin@foo.com
</source>
<translation>%s, du må angi rpcpassord i konfigurasjonsfilen.
%s
Det anbefales at du bruker det følgende tilfeldige passordet:
rpcbruker=RupayaCoinrpc
rpcpassord=%s
(du behøver ikke å huske passordet)
Brukernavnet og passordet MÅ IKKE være like.
Om filen ikke eksisterer, opprett den nå med eier-kun-les filrettigheter.
Det er også anbefalt at å sette varselsmelding slik du får melding om problemer.
For eksempel: varselmelding=echo %%s | mail -s "RupayaCoin varsel" admin@foo.com</translation>
</message>
<message>
<location line="+17"/>
<source>An error occurred while setting up the RPC port %u for listening on IPv6, falling back to IPv4: %s</source>
<translation>En feil oppstod under oppsettet av RPC port %u for IPv6, tilbakestilles til IPv4: %s</translation>
</message>
<message>
<location line="+3"/>
<source>Bind to given address and always listen on it. Use [host]:port notation for IPv6</source>
<translation>Bind til angitt adresse. Bruk [vertsmaskin]:port notasjon for IPv6</translation>
</message>
<message>
<location line="+3"/>
<source>Cannot obtain a lock on data directory %s. RupayaCoin is probably already running.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Error: The transaction was rejected! This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Error: This transaction requires a transaction fee of at least %s because of its amount, complexity, or use of recently received funds!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Execute command when a relevant alert is received (%s in cmd is replaced by message)</source>
<translation>Kjør kommando når relevant varsel blir mottatt (%s i cmd er erstattet med TxID)</translation>
</message>
<message>
<location line="+3"/>
<source>Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)</source>
<translation>Kjør kommando når en lommeboktransaksjon endres (%s i cmd er erstattet med TxID)</translation>
</message>
<message>
<location line="+11"/>
<source>Set maximum size of high-priority/low-fee transactions in bytes (default: 27000)</source>
<translation>Sett maks størrelse for transaksjoner med høy prioritet / lavt gebyr, i bytes (standardverdi: 27000)</translation>
</message>
<message>
<location line="+6"/>
<source>This is a pre-release test build - use at your own risk - do not use for mining or merchant applications</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Warning: -paytxfee is set very high! This is the transaction fee you will pay if you send a transaction.</source>
<translation>Advarsel: -paytxfee er satt veldig høyt! Dette er transaksjonsgebyret du betaler når du sender transaksjoner.</translation>
</message>
<message>
<location line="+3"/>
<source>Warning: Displayed transactions may not be correct! You may need to upgrade, or other nodes may need to upgrade.</source>
<translation>Advarsel: Viste transaksjoner kan være feil! Du, eller andre noder, kan trenge en oppgradering.</translation>
</message>
<message>
<location line="+3"/>
<source>Warning: Please check that your computer's date and time are correct! If your clock is wrong RupayaCoin will not work properly.</source>
<translation>Advarsel: Vennligst undersøk at din datamaskin har riktig dato og klokkeslett! Hvis klokken er stilt feil vil ikke RupayaCoin fungere riktig.</translation>
</message>
<message>
<location line="+3"/>
<source>Warning: error reading wallet.dat! All keys read correctly, but transaction data or address book entries might be missing or incorrect.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Warning: wallet.dat corrupt, data salvaged! Original wallet.dat saved as wallet.{timestamp}.bak in %s; if your balance or transactions are incorrect you should restore from a backup.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+14"/>
<source>Attempt to recover private keys from a corrupt wallet.dat</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Block creation options:</source>
<translation>Valg for opprettelse av blokker:</translation>
</message>
<message>
<location line="+5"/>
<source>Connect only to the specified node(s)</source>
<translation>Koble kun til angitt(e) node(r)</translation>
</message>
<message>
<location line="+3"/>
<source>Corrupted block database detected</source>
<translation>Oppdaget korrupt blokkdatabase</translation>
</message>
<message>
<location line="+1"/>
<source>Discover own IP address (default: 1 when listening and no -externalip)</source>
<translation>Oppdag egen IP-adresse (standardverdi: 1 ved lytting og uten -externalip)</translation>
</message>
<message>
<location line="+1"/>
<source>Do you want to rebuild the block database now?</source>
<translation>Ønsker du å gjenopprette blokkdatabasen nå?</translation>
</message>
<message>
<location line="+2"/>
<source>Error initializing block database</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Error initializing wallet database environment %s!</source>
<translation>Feil under oppstart av lommebokdatabasemiljø %s!</translation>
</message>
<message>
<location line="+1"/>
<source>Error loading block database</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Error opening block database</source>
<translation>Feil under åpning av blokkdatabase</translation>
</message>
<message>
<location line="+2"/>
<source>Error: Disk space is low!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Error: Wallet locked, unable to create transaction!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Error: system error: </source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to listen on any port. Use -listen=0 if you want this.</source>
<translation>Kunne ikke lytte på noen port. Bruk -listen=0 hvis det er dette du vil.</translation>
</message>
<message>
<location line="+1"/>
<source>Failed to read block info</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to read block</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to sync block index</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to write block index</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to write block info</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to write block</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to write file info</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to write to coin database</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to write transaction index</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to write undo data</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Find peers using DNS lookup (default: 1 unless -connect)</source>
<translation>Finn andre noder gjennom DNS-oppslag (standardverdi: 1 med mindre -connect er oppgit)</translation>
</message>
<message>
<location line="+1"/>
<source>Generate coins (default: 0)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>How many blocks to check at startup (default: 288, 0 = all)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>How thorough the block verification is (0-4, default: 3)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+19"/>
<source>Not enough file descriptors available.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>Rebuild block chain index from current blk000??.dat files</source>
<translation>Gjenopprett blokkjedeindex fra blk000??.dat filer</translation>
</message>
<message>
<location line="+16"/>
<source>Set the number of threads to service RPC calls (default: 4)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+26"/>
<source>Verifying blocks...</source>
<translation>Verifiserer blokker...</translation>
</message>
<message>
<location line="+1"/>
<source>Verifying wallet...</source>
<translation>Verifiserer lommebok...</translation>
</message>
<message>
<location line="-69"/>
<source>Imports blocks from external blk000??.dat file</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-76"/>
<source>Set the number of script verification threads (up to 16, 0 = auto, <0 = leave that many cores free, default: 0)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+77"/>
<source>Information</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Invalid -tor address: '%s'</source>
<translation>Ugyldig -tor adresse: '%s'</translation>
</message>
<message>
<location line="+1"/>
<source>Invalid amount for -minrelaytxfee=<amount>: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Invalid amount for -mintxfee=<amount>: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>Maintain a full transaction index (default: 0)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Maximum per-connection receive buffer, <n>*1000 bytes (default: 5000)</source>
<translation>Maks mottaksbuffer per forbindelse, <n>*1000 bytes (standardverdi: 5000)</translation>
</message>
<message>
<location line="+1"/>
<source>Maximum per-connection send buffer, <n>*1000 bytes (default: 1000)</source>
<translation>Maks sendebuffer per forbindelse, <n>*1000 bytes (standardverdi: 1000)</translation>
</message>
<message>
<location line="+2"/>
<source>Only accept block chain matching built-in checkpoints (default: 1)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Only connect to nodes in network <net> (IPv4, IPv6 or Tor)</source>
<translation>Koble kun til noder i nettverket <nett> (IPv4, IPv6 eller Tor)</translation>
</message>
<message>
<location line="+2"/>
<source>Output extra debugging information. Implies all other -debug* options</source>
<translation>Skriv ekstra informasjon for feilsøk. Medfører at alle -debug* valg tas med</translation>
</message>
<message>
<location line="+1"/>
<source>Output extra network debugging information</source>
<translation>Skriv ekstra informasjon for feilsøk av nettverk</translation>
</message>
<message>
<location line="+2"/>
<source>Prepend debug output with timestamp (default: 1)</source>
<translation>Sett tidsstempel på debugmeldinger</translation>
</message>
<message>
<location line="+5"/>
<source>SSL options: (see the RupayaCoin Wiki for SSL setup instructions)</source>
<translation>SSL valg: (se RupayaCoin Wiki for instruksjoner for oppsett av SSL)</translation>
</message>
<message>
<location line="+1"/>
<source>Select the version of socks proxy to use (4-5, default: 5)</source>
<translation>Velg versjon av socks proxy (4-5, standardverdi 5)</translation>
</message>
<message>
<location line="+3"/>
<source>Send trace/debug info to console instead of debug.log file</source>
<translation>Send spor/debug informasjon til konsollet istedenfor debug.log filen</translation>
</message>
<message>
<location line="+1"/>
<source>Send trace/debug info to debugger</source>
<translation>Send spor/debug informasjon til debugger</translation>
</message>
<message>
<location line="+5"/>
<source>Set maximum block size in bytes (default: 250000)</source>
<translation>Sett maks blokkstørrelse i bytes (standardverdi: 250000)</translation>
</message>
<message>
<location line="+1"/>
<source>Set minimum block size in bytes (default: 0)</source>
<translation>Sett minimum blokkstørrelse i bytes (standardverdi: 0)</translation>
</message>
<message>
<location line="+2"/>
<source>Shrink debug.log file on client startup (default: 1 when no -debug)</source>
<translation>Krymp debug.log filen når klienten starter (standardverdi: 1 hvis uten -debug)</translation>
</message>
<message>
<location line="+1"/>
<source>Signing transaction failed</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Specify connection timeout in milliseconds (default: 5000)</source>
<translation>Angi tidsavbrudd for forbindelse i millisekunder (standardverdi: 5000)</translation>
</message>
<message>
<location line="+4"/>
<source>System error: </source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Transaction amount too small</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Transaction amounts must be positive</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Transaction too large</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Use UPnP to map the listening port (default: 0)</source>
<translation>Bruk UPnP for lytteport (standardverdi: 0)</translation>
</message>
<message>
<location line="+1"/>
<source>Use UPnP to map the listening port (default: 1 when listening)</source>
<translation>Bruk UPnP for lytteport (standardverdi: 1 ved lytting)</translation>
</message>
<message>
<location line="+1"/>
<source>Use proxy to reach tor hidden services (default: same as -proxy)</source>
<translation>Bruk en proxy for å nå skjulte tor tjenester (standardverdi: samme som -proxy)</translation>
</message>
<message>
<location line="+2"/>
<source>Username for JSON-RPC connections</source>
<translation>Brukernavn for JSON-RPC forbindelser</translation>
</message>
<message>
<location line="+4"/>
<source>Warning</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Warning: This version is obsolete, upgrade required!</source>
<translation>Advarsel: Denne versjonen er foreldet, oppgradering kreves!</translation>
</message>
<message>
<location line="+1"/>
<source>You need to rebuild the databases using -reindex to change -txindex</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>wallet.dat corrupt, salvage failed</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-50"/>
<source>Password for JSON-RPC connections</source>
<translation>Passord for JSON-RPC forbindelser</translation>
</message>
<message>
<location line="-67"/>
<source>Allow JSON-RPC connections from specified IP address</source>
<translation>Tillat JSON-RPC tilkoblinger fra angitt IP-adresse</translation>
</message>
<message>
<location line="+76"/>
<source>Send commands to node running on <ip> (default: 127.0.0.1)</source>
<translation>Send kommandoer til node på <ip> (standardverdi: 127.0.0.1)</translation>
</message>
<message>
<location line="-120"/>
<source>Execute command when the best block changes (%s in cmd is replaced by block hash)</source>
<translation>Eksekvér kommando når beste blokk endrer seg (%s i kommandoen erstattes med blokkens hash)</translation>
</message>
<message>
<location line="+147"/>
<source>Upgrade wallet to latest format</source>
<translation>Oppgradér lommebok til nyeste format</translation>
</message>
<message>
<location line="-21"/>
<source>Set key pool size to <n> (default: 100)</source>
<translation>Angi størrelse på nøkkel-lager til <n> (standardverdi: 100)</translation>
</message>
<message>
<location line="-12"/>
<source>Rescan the block chain for missing wallet transactions</source>
<translation>Se gjennom blokk-kjeden etter manglende lommeboktransaksjoner</translation>
</message>
<message>
<location line="+35"/>
<source>Use OpenSSL (https) for JSON-RPC connections</source>
<translation>Bruk OpenSSL (https) for JSON-RPC forbindelser</translation>
</message>
<message>
<location line="-26"/>
<source>Server certificate file (default: server.cert)</source>
<translation>Servers sertifikat (standardverdi: server.cert)</translation>
</message>
<message>
<location line="+1"/>
<source>Server private key (default: server.pem)</source>
<translation>Servers private nøkkel (standardverdi: server.pem)</translation>
</message>
<message>
<location line="-151"/>
<source>Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)</source>
<translation>Akseptable krypteringsmetoder (standardverdi: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)</translation>
</message>
<message>
<location line="+165"/>
<source>This help message</source>
<translation>Denne hjelpemeldingen</translation>
</message>
<message>
<location line="+6"/>
<source>Unable to bind to %s on this computer (bind returned error %d, %s)</source>
<translation>Kan ikke binde til %s på denne datamaskinen (bind returnerte feil %d, %s)</translation>
</message>
<message>
<location line="-91"/>
<source>Connect through socks proxy</source>
<translation>Koble til gjennom socks proxy</translation>
</message>
<message>
<location line="-10"/>
<source>Allow DNS lookups for -addnode, -seednode and -connect</source>
<translation>Tillat DNS oppslag for -addnode, -seednode og -connect</translation>
</message>
<message>
<location line="+55"/>
<source>Loading addresses...</source>
<translation>Laster adresser...</translation>
</message>
<message>
<location line="-35"/>
<source>Error loading wallet.dat: Wallet corrupted</source>
<translation>Feil ved lasting av wallet.dat: Lommeboken er skadet</translation>
</message>
<message>
<location line="+1"/>
<source>Error loading wallet.dat: Wallet requires newer version of RupayaCoin</source>
<translation>Feil ved lasting av wallet.dat: Lommeboken krever en nyere versjon av RupayaCoin</translation>
</message>
<message>
<location line="+93"/>
<source>Wallet needed to be rewritten: restart RupayaCoin to complete</source>
<translation>Lommeboken måtte skrives om: start RupayaCoin på nytt for å fullføre</translation>
</message>
<message>
<location line="-95"/>
<source>Error loading wallet.dat</source>
<translation>Feil ved lasting av wallet.dat</translation>
</message>
<message>
<location line="+28"/>
<source>Invalid -proxy address: '%s'</source>
<translation>Ugyldig -proxy adresse: '%s'</translation>
</message>
<message>
<location line="+56"/>
<source>Unknown network specified in -onlynet: '%s'</source>
<translation>Ukjent nettverk angitt i -onlynet '%s'</translation>
</message>
<message>
<location line="-1"/>
<source>Unknown -socks proxy version requested: %i</source>
<translation>Ukjent -socks proxy versjon angitt: %i</translation>
</message>
<message>
<location line="-96"/>
<source>Cannot resolve -bind address: '%s'</source>
<translation>Kunne ikke slå opp -bind adresse: '%s'</translation>
</message>
<message>
<location line="+1"/>
<source>Cannot resolve -externalip address: '%s'</source>
<translation>Kunne ikke slå opp -externalip adresse: '%s'</translation>
</message>
<message>
<location line="+44"/>
<source>Invalid amount for -paytxfee=<amount>: '%s'</source>
<translation>Ugyldig beløp for -paytxfee=<beløp>: '%s'</translation>
</message>
<message>
<location line="+1"/>
<source>Invalid amount</source>
<translation>Ugyldig beløp</translation>
</message>
<message>
<location line="-6"/>
<source>Insufficient funds</source>
<translation>Utilstrekkelige midler</translation>
</message>
<message>
<location line="+10"/>
<source>Loading block index...</source>
<translation>Laster blokkindeks...</translation>
</message>
<message>
<location line="-57"/>
<source>Add a node to connect to and attempt to keep the connection open</source>
<translation>Legg til node for tilkobling og hold forbindelsen åpen</translation>
</message>
<message>
<location line="-25"/>
<source>Unable to bind to %s on this computer. RupayaCoin is probably already running.</source>
<translation>Kan ikke binde til %s på denne datamaskinen. Sannsynligvis kjører RupayaCoin allerede.</translation>
</message>
<message>
<location line="+64"/>
<source>Fee per KB to add to transactions you send</source>
<translation>Gebyr per KB for transaksjoner du sender</translation>
</message>
<message>
<location line="+19"/>
<source>Loading wallet...</source>
<translation>Laster lommebok...</translation>
</message>
<message>
<location line="-52"/>
<source>Cannot downgrade wallet</source>
<translation>Kan ikke nedgradere lommebok</translation>
</message>
<message>
<location line="+3"/>
<source>Cannot write default address</source>
<translation>Kan ikke skrive standardadresse</translation>
</message>
<message>
<location line="+64"/>
<source>Rescanning...</source>
<translation>Leser gjennom...</translation>
</message>
<message>
<location line="-57"/>
<source>Done loading</source>
<translation>Ferdig med lasting</translation>
</message>
<message>
<location line="+82"/>
<source>To use the %s option</source>
<translation>For å bruke %s opsjonen</translation>
</message>
<message>
<location line="-74"/>
<source>Error</source>
<translation>Feil</translation>
</message>
<message>
<location line="-31"/>
<source>You must set rpcpassword=<password> in the configuration file:
%s
If the file does not exist, create it with owner-readable-only file permissions.</source>
<translation>Du må sette rpcpassword=<passord> i konfigurasjonsfilen:
%s
Hvis filen ikke finnes, opprett den med leserettighet kun for eier av filen.</translation>
</message>
</context>
</TS>
| tyarlande/rupayacoin | src/qt/locale/bitcoin_nb.ts | TypeScript | mit | 113,521 |
require File.expand_path('../helper', __FILE__)
class BeforeFilterTest < Test::Unit::TestCase
it "executes filters in the order defined" do
count = 0
mock_app do
get('/') { 'Hello World' }
before do
assert_equal 0, count
count = 1
end
before do
assert_equal 1, count
count = 2
end
end
get '/'
assert ok?
assert_equal 2, count
assert_equal 'Hello World', body
end
it "can modify the request" do
mock_app do
get('/foo') { 'foo' }
get('/bar') { 'bar' }
before { request.path_info = '/bar' }
end
get '/foo'
assert ok?
assert_equal 'bar', body
end
it "can modify instance variables available to routes" do
mock_app do
before { @foo = 'bar' }
get('/foo') { @foo }
end
get '/foo'
assert ok?
assert_equal 'bar', body
end
it "allows redirects" do
mock_app do
before { redirect '/bar' }
get('/foo') do
fail 'before block should have halted processing'
'ORLY?!'
end
end
get '/foo'
assert redirect?
assert_equal 'http://example.org/bar', response['Location']
assert_equal '', body
end
it "does not modify the response with its return value" do
mock_app do
before { 'Hello World!' }
get('/foo') do
assert_equal [], response.body
'cool'
end
end
get '/foo'
assert ok?
assert_equal 'cool', body
end
it "does modify the response with halt" do
mock_app do
before { halt 302, 'Hi' }
get '/foo' do
"should not happen"
end
end
get '/foo'
assert_equal 302, response.status
assert_equal 'Hi', body
end
it "gives you access to params" do
mock_app do
before { @foo = params['foo'] }
get('/foo') { @foo }
end
get '/foo?foo=cool'
assert ok?
assert_equal 'cool', body
end
it "properly unescapes parameters" do
mock_app do
before { @foo = params['foo'] }
get('/foo') { @foo }
end
get '/foo?foo=bar%3Abaz%2Fbend'
assert ok?
assert_equal 'bar:baz/bend', body
end
it "runs filters defined in superclasses" do
base = Class.new(Morrissey::Base)
base.before { @foo = 'hello from superclass' }
mock_app(base) { get('/foo') { @foo } }
get '/foo'
assert_equal 'hello from superclass', body
end
it 'does not run before filter when serving static files' do
ran_filter = false
mock_app do
before { ran_filter = true }
set :static, true
set :public_folder, File.dirname(__FILE__)
end
get "/#{File.basename(__FILE__)}"
assert ok?
assert_equal File.read(__FILE__), body
assert !ran_filter
end
it 'takes an optional route pattern' do
ran_filter = false
mock_app do
before("/b*") { ran_filter = true }
get('/foo') { }
get('/bar') { }
end
get '/foo'
assert !ran_filter
get '/bar'
assert ran_filter
end
it 'generates block arguments from route pattern' do
subpath = nil
mock_app do
before("/foo/:sub") { |s| subpath = s }
get('/foo/*') { }
end
get '/foo/bar'
assert_equal subpath, 'bar'
end
it 'can catch exceptions in before filters and handle them properly' do
doodle = ''
mock_app do
before do
doodle += 'This begins'
raise StandardError, "before"
end
get "/" do
doodle = 'and runs'
end
error 500 do
"Error handled #{env['morrissey.error'].message}"
end
end
doodle = ''
get '/'
assert_equal 'Error handled before', body
assert_equal 'This begins', doodle
end
end
class AfterFilterTest < Test::Unit::TestCase
it "executes before and after filters in correct order" do
invoked = 0
mock_app do
before { invoked = 2 }
get('/') { invoked += 2; 'hello' }
after { invoked *= 2 }
end
get '/'
assert ok?
assert_equal 8, invoked
end
it "executes filters in the order defined" do
count = 0
mock_app do
get('/') { 'Hello World' }
after do
assert_equal 0, count
count = 1
end
after do
assert_equal 1, count
count = 2
end
end
get '/'
assert ok?
assert_equal 2, count
assert_equal 'Hello World', body
end
it "allows redirects" do
mock_app do
get('/foo') { 'ORLY' }
after { redirect '/bar' }
end
get '/foo'
assert redirect?
assert_equal 'http://example.org/bar', response['Location']
assert_equal '', body
end
it "does not modify the response with its return value" do
mock_app do
get('/foo') { 'cool' }
after { 'Hello World!' }
end
get '/foo'
assert ok?
assert_equal 'cool', body
end
it "does modify the response with halt" do
mock_app do
get '/foo' do
"should not be returned"
end
after { halt 302, 'Hi' }
end
get '/foo'
assert_equal 302, response.status
assert_equal 'Hi', body
end
it "runs filters defined in superclasses" do
count = 2
base = Class.new(Morrissey::Base)
base.after { count *= 2 }
mock_app(base) do
get('/foo') do
count += 2
"ok"
end
end
get '/foo'
assert_equal 8, count
end
it 'does not run after filter when serving static files' do
ran_filter = false
mock_app do
after { ran_filter = true }
set :static, true
set :public_folder, File.dirname(__FILE__)
end
get "/#{File.basename(__FILE__)}"
assert ok?
assert_equal File.read(__FILE__), body
assert !ran_filter
end
it 'takes an optional route pattern' do
ran_filter = false
mock_app do
after("/b*") { ran_filter = true }
get('/foo') { }
get('/bar') { }
end
get '/foo'
assert !ran_filter
get '/bar'
assert ran_filter
end
it 'changes to path_info from a pattern matching before filter are respected when routing' do
mock_app do
before('/foo') { request.path_info = '/bar' }
get('/bar') { 'blah' }
end
get '/foo'
assert ok?
assert_equal 'blah', body
end
it 'generates block arguments from route pattern' do
subpath = nil
mock_app do
after("/foo/:sub") { |s| subpath = s }
get('/foo/*') { }
end
get '/foo/bar'
assert_equal subpath, 'bar'
end
it 'is possible to access url params from the route param' do
ran = false
mock_app do
get('/foo/*') { }
before('/foo/:sub') do
assert_equal params[:sub], 'bar'
ran = true
end
end
get '/foo/bar'
assert ran
end
it 'is possible to apply host_name conditions to before filters with no path' do
ran = false
mock_app do
before(:host_name => 'example.com') { ran = true }
get('/') { 'welcome' }
end
get('/', {}, { 'HTTP_HOST' => 'example.org' })
assert !ran
get('/', {}, { 'HTTP_HOST' => 'example.com' })
assert ran
end
it 'is possible to apply host_name conditions to before filters with a path' do
ran = false
mock_app do
before('/foo', :host_name => 'example.com') { ran = true }
get('/') { 'welcome' }
end
get('/', {}, { 'HTTP_HOST' => 'example.com' })
assert !ran
get('/foo', {}, { 'HTTP_HOST' => 'example.org' })
assert !ran
get('/foo', {}, { 'HTTP_HOST' => 'example.com' })
assert ran
end
it 'is possible to apply host_name conditions to after filters with no path' do
ran = false
mock_app do
after(:host_name => 'example.com') { ran = true }
get('/') { 'welcome' }
end
get('/', {}, { 'HTTP_HOST' => 'example.org' })
assert !ran
get('/', {}, { 'HTTP_HOST' => 'example.com' })
assert ran
end
it 'is possible to apply host_name conditions to after filters with a path' do
ran = false
mock_app do
after('/foo', :host_name => 'example.com') { ran = true }
get('/') { 'welcome' }
end
get('/', {}, { 'HTTP_HOST' => 'example.com' })
assert !ran
get('/foo', {}, { 'HTTP_HOST' => 'example.org' })
assert !ran
get('/foo', {}, { 'HTTP_HOST' => 'example.com' })
assert ran
end
it 'is possible to apply user_agent conditions to before filters with no path' do
ran = false
mock_app do
before(:user_agent => /foo/) { ran = true }
get('/') { 'welcome' }
end
get('/', {}, { 'HTTP_USER_AGENT' => 'bar' })
assert !ran
get('/', {}, { 'HTTP_USER_AGENT' => 'foo' })
assert ran
end
it 'is possible to apply user_agent conditions to before filters with a path' do
ran = false
mock_app do
before('/foo', :user_agent => /foo/) { ran = true }
get('/') { 'welcome' }
end
get('/', {}, { 'HTTP_USER_AGENT' => 'foo' })
assert !ran
get('/foo', {}, { 'HTTP_USER_AGENT' => 'bar' })
assert !ran
get('/foo', {}, { 'HTTP_USER_AGENT' => 'foo' })
assert ran
end
it 'can add params' do
mock_app do
before { params['foo'] = 'bar' }
get('/') { params['foo'] }
end
get '/'
assert_body 'bar'
end
it 'can remove params' do
mock_app do
before { params.delete('foo') }
get('/') { params['foo'].to_s }
end
get '/?foo=bar'
assert_body ''
end
it 'is possible to apply user_agent conditions to after filters with no path' do
ran = false
mock_app do
after(:user_agent => /foo/) { ran = true }
get('/') { 'welcome' }
end
get('/', {}, { 'HTTP_USER_AGENT' => 'bar' })
assert !ran
get('/', {}, { 'HTTP_USER_AGENT' => 'foo' })
assert ran
end
it 'is possible to apply user_agent conditions to after filters with a path' do
ran = false
mock_app do
after('/foo', :user_agent => /foo/) { ran = true }
get('/') { 'welcome' }
end
get('/', {}, { 'HTTP_USER_AGENT' => 'foo' })
assert !ran
get('/foo', {}, { 'HTTP_USER_AGENT' => 'bar' })
assert !ran
get('/foo', {}, { 'HTTP_USER_AGENT' => 'foo' })
assert ran
end
it 'only triggeres provides condition if conforms with current Content-Type' do
mock_app do
before(:provides => :txt) { @type = 'txt' }
before(:provides => :html) { @type = 'html' }
get('/') { @type }
end
get('/', {}, { 'HTTP_ACCEPT' => '*/*' })
assert_body 'txt'
end
it 'can catch exceptions in after filters and handle them properly' do
doodle = ''
mock_app do
after do
doodle += ' and after'
raise StandardError, "after"
end
get "/foo" do
doodle = 'Been now'
raise StandardError, "now"
end
get "/" do
doodle = 'Been now'
end
error 500 do
"Error handled #{env['morrissey.error'].message}"
end
end
get '/foo'
assert_equal 'Error handled now', body
assert_equal 'Been now and after', doodle
doodle = ''
get '/'
assert_equal 'Error handled after', body
assert_equal 'Been now and after', doodle
end
end
| Callygraphy/morrissey | test/filter_test.rb | Ruby | mit | 11,117 |
<?php
namespace IdeaSeven\Core\Services\Menu;
use IdeaSeven\Core\Exceptions\InvalidMenuStructureException;
use IdeaSeven\Core\Helpers\Strings;
use IdeaSeven\Core\Services\Lang\Contracts\LanguagesContract;
/**
* Class PermalinkCreator
* @package IdeaSeven\Core\Services\Menu
*/
class PermalinkCreator
{
/**
* @var array
*/
protected $node;
/**
* @var ValidateMenuItem
*/
protected $validator;
/**
* @var Strings
*/
protected $stringHelpers;
protected $lang;
/**
* PermalinkCreator constructor.
* @param ValidateMenuItem $validator
* @param array $node
*/
public function __construct(ValidateMenuItem $validator, array $node, LanguagesContract $lang)
{
$this->validator = $validator;
$this->node = $node;
$this->stringHelpers = new Strings();
$this->lang = $lang;
}
/**
* @return array|mixed|string
*/
public function handle()
{
if ( ! isset($this->node['settings']) || ! is_array($this->node['settings'])){
$this->node['settings'] = [];
}
if ($this->validator->checkIfLinkBuildingIsRequired()){
return $this->build($this->node);
}
if ($this->validator->checkIfItIsCustomLink()) {
return $this->node;
}
return '';
}
/**
* Build all the fields based on the model
* titleField can either be a string or an array with a pattern property
* The pattern of title field can be an array of locales, as this is a translatable field
* @example : titleField => ['en'=>'pattern','es'=>'el patterno']
*
* @param array $node
* @return array
*/
private function build(array $node)
{
// If it is, query it and pass it down to the sprintf
//set title and permalink
//get an instance of the model
$model = new $node['model'];
$item = $model->find($node['item_id'])->toArray();
$node['permalink'] = $this->stringHelpers->vksprintf($node['slug_pattern'], $item);
//care for translations
$title = [];
if (is_string($node['titleField'])) {
//This is a copy paste situation, don't mind it
$title = $item->{$node['titleField']};
} else {
//for all available locales, add a title
//The pattern can be a localized array like so : [en : '', el : '']
//or a single string, in which case, we apply the same format to all locales
foreach ($this->lang->locales() as $locale) {
if (is_array($node['titleField']['pattern'])) {
//we will check for each locale
if (isset($locale['code']) && array_key_exists($locale['code'], $node['titleField']['pattern'])){
$title[$locale['code']] = $this->stringHelpers->vksprintf($node['titleField']['pattern'][$locale['code']], $item);
}
//so what happens if we are missing a locale?
//screw it
} else {
$title[$locale['code']] = $this->stringHelpers->vksprintf($node['titleField']['pattern'], $item);
}
}
}
if ( ! isset($node['settings']) || ! is_array($node['settings'])){
$node['settings'] = [];
}
$node['settings']['titleField'] = $node['titleField'];
$node['title'] = $title;
return $node;
}
} | mbouclas/mcms-laravel-core | src/Services/Menu/PermalinkCreator.php | PHP | mit | 3,536 |
<?php
/* TwigBundle:Exception:exception_full.html.twig */
class __TwigTemplate_add344e1e383c1eb02227246319313ae extends Twig_Template
{
public function __construct(Twig_Environment $env)
{
parent::__construct($env);
$this->parent = $this->env->loadTemplate("TwigBundle::layout.html.twig");
$this->blocks = array(
'head' => array($this, 'block_head'),
'title' => array($this, 'block_title'),
'body' => array($this, 'block_body'),
);
}
protected function doGetParent(array $context)
{
return "TwigBundle::layout.html.twig";
}
protected function doDisplay(array $context, array $blocks = array())
{
$this->parent->display($context, array_merge($this->blocks, $blocks));
}
// line 3
public function block_head($context, array $blocks = array())
{
// line 4
echo " <link href=\"";
echo twig_escape_filter($this->env, $this->env->getExtension('assets')->getAssetUrl("bundles/framework/css/exception.css"), "html", null, true);
echo "\" rel=\"stylesheet\" type=\"text/css\" media=\"all\" />
";
}
// line 7
public function block_title($context, array $blocks = array())
{
// line 8
echo " ";
echo twig_escape_filter($this->env, $this->getAttribute($this->getContext($context, "exception"), "message"), "html", null, true);
echo " (";
echo twig_escape_filter($this->env, $this->getContext($context, "status_code"), "html", null, true);
echo " ";
echo twig_escape_filter($this->env, $this->getContext($context, "status_text"), "html", null, true);
echo ")
";
}
// line 11
public function block_body($context, array $blocks = array())
{
// line 12
echo " ";
$this->env->loadTemplate("TwigBundle:Exception:exception.html.twig")->display($context);
}
public function getTemplateName()
{
return "TwigBundle:Exception:exception_full.html.twig";
}
public function isTraitable()
{
return false;
}
public function getDebugInfo()
{
return array ( 57 => 12, 54 => 11, 43 => 8, 40 => 7, 33 => 4, 30 => 3,);
}
}
| krlts/Homefanfics | app/cache/dev/twig/ad/d3/44e1e383c1eb02227246319313ae.php | PHP | mit | 2,264 |
<?php
namespace CBSi\ProductBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use CBSi\ProductBundle\Model\Product;
use CBSi\ProductBundle\ApiClient;
class DefaultController extends Controller
{
public function indexAction($name)
{
return $this->render('CBSiProductBundle:Default:index.html.twig', array('name' => $name));
}
public function showProductsAction(){
$apiClient = $this->container->get('Product.ApiClient');
$products = $apiClient->getAction('products.json');
$objProducts = array();
foreach ($products as $product) {
array_push($objProducts, new Product($product['id'], $product['name'], $product['description'], $product['price']));
}
return $this->render('CBSiProductBundle:Default:productListing.html.twig', array('products' => $objProducts));
}
public function showSingleAction($id){
$apiClient = $this->container->get('Product.ApiClient');
$products = $apiClient->getAction('products/' . $id .'.json');
if(is_null($products)){
throw $this->createNotFoundException('The product ID ' . $id .' does not exist');
}
$product = new Product($products['id'], $products['name'], $products['description'], $products['price']);
$products = array($product);
return $this->render('CBSiProductBundle:Default:productListing.html.twig', array('products' => $products));
}
}
| smp4488/symfony2 | src/CBSi/ProductBundle/Controller/DefaultController.php | PHP | mit | 1,439 |
export const PlusCircle = `
<svg viewBox="0 0 28 28">
<g fill="none" fill-rule="evenodd">
<path d="M8 14h12" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round"/>
<circle stroke="currentColor" cx="14" cy="14" r="13"/>
<path d="M14 8v12" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round"/>
</g>
</svg>`;
| clair-design/clair | packages/icons/icons/PlusCircle.ts | TypeScript | mit | 355 |
<?php
/*
* Description of bibliographyController
*
* This is a controller loading the bibliography. It does not support any user input
*/
namespace PNM\controllers;
class bibliographyController
{
public function load()
{
$bibliography = new \PNM\models\bibliography();
$view = new \PNM\views\bibliographyView();
$view->echoRender($bibliography);
}
}
| ailintom/persons-names-MK | PHP/controllers/bibliographyController.php | PHP | mit | 394 |
package com.missingeye.pixelpainter.events.network.texture;
import com.missingeye.pixelpainter.common.PixelMetadata;
import net.minecraft.util.ResourceLocation;
/**
* Created on 1/17/2015.
*
* @auhtor Samuel Agius (Belpois)
*/
public class ServerUpdatedTexturePacketEvent extends UpdatedTexturePacketEvent
{
public ServerUpdatedTexturePacketEvent(ResourceLocation resourceLocation, PixelMetadata[] pixelMetadata)
{
super(resourceLocation, pixelMetadata);
}
}
| Belpois/pixelpainter | src/main/java/com/missingeye/pixelpainter/events/network/texture/ServerUpdatedTexturePacketEvent.java | Java | mit | 470 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
namespace QSDStudy
{
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
}
}
| lsolano/qsd_study | QSDStudy/App_Start/RouteConfig.cs | C# | mit | 578 |
#ifndef LUCE_HEADER_TYPETRAIT_TYPEEQUAL_HH
#define LUCE_HEADER_TYPETRAIT_TYPEEQUAL_HH
#include <Luce/Configuration.hh>
#include <Luce/Utility/NonComparable.hh>
#include <Luce/Utility/NonCopyable.hh>
namespace Luce
{
namespace TypeTrait
{
template<typename Lhs_, typename Rhs_>
struct TypeEqual LUCE_MACRO_FINAL
: private Utility::NonComparable, private Utility::NonCopyable
{
LUCE_MACRO_CANNOT_PARENT(TypeEqual)
public:
static const bool Value = false;
};
template<typename Type_>
struct TypeEqual<Type_, Type_> LUCE_MACRO_FINAL
: private Utility::NonComparable, private Utility::NonCopyable
{
LUCE_MACRO_CANNOT_PARENT(TypeEqual)
public:
static const bool Value = true;
};
}
using Luce::TypeTrait::TypeEqual;
}
#endif | kmc7468/Luce | Include/Luce/TypeTrait/TypeEqual.hh | C++ | mit | 799 |
export type TemplateToken = string | TemplatePlaceholder;
export interface TemplatePlaceholder {
before: string;
after: string;
name: string;
}
interface TokenScanner {
text: string;
pos: number;
}
const enum TemplateChars {
/** `[` character */
Start = 91,
/** `]` character */
End = 93,
/* `_` character */
Underscore = 95,
/* `-` character */
Dash = 45,
}
/**
* Splits given string into template tokens.
* Template is a string which contains placeholders which are uppercase names
* between `[` and `]`, for example: `[PLACEHOLDER]`.
* Unlike other templates, a placeholder may contain extra characters before and
* after name: `[%PLACEHOLDER.]`. If data for `PLACEHOLDER` is defined, it will
* be outputted with with these extra character, otherwise will be completely omitted.
*/
export default function template(text: string): TemplateToken[] {
const tokens: TemplateToken[] = [];
const scanner: TokenScanner = { pos: 0, text };
let placeholder: TemplatePlaceholder | undefined;
let offset = scanner.pos;
let pos = scanner.pos;
while (scanner.pos < scanner.text.length) {
pos = scanner.pos;
if (placeholder = consumePlaceholder(scanner)) {
if (offset !== scanner.pos) {
tokens.push(text.slice(offset, pos));
}
tokens.push(placeholder);
offset = scanner.pos;
} else {
scanner.pos++;
}
}
if (offset !== scanner.pos) {
tokens.push(text.slice(offset));
}
return tokens;
}
/**
* Consumes placeholder like `[#ID]` from given scanner
*/
function consumePlaceholder(scanner: TokenScanner): TemplatePlaceholder | undefined {
if (peek(scanner) === TemplateChars.Start) {
const start = ++scanner.pos;
let namePos = start;
let afterPos = start;
let stack = 1;
while (scanner.pos < scanner.text.length) {
const code = peek(scanner);
if (isTokenStart(code)) {
namePos = scanner.pos;
while (isToken(peek(scanner))) {
scanner.pos++;
}
afterPos = scanner.pos;
} else {
if (code === TemplateChars.Start) {
stack++;
} else if (code === TemplateChars.End) {
if (--stack === 0) {
return {
before: scanner.text.slice(start, namePos),
after: scanner.text.slice(afterPos, scanner.pos++),
name: scanner.text.slice(namePos, afterPos)
};
}
}
scanner.pos++;
}
}
}
}
function peek(scanner: TokenScanner, pos = scanner.pos): number {
return scanner.text.charCodeAt(pos);
}
function isTokenStart(code: number): boolean {
return code >= 65 && code <= 90; // A-Z
}
function isToken(code: number): boolean {
return isTokenStart(code)
|| (code > 47 && code < 58) /* 0-9 */
|| code === TemplateChars.Underscore
|| code === TemplateChars.Dash;
}
| emmetio/emmet | src/markup/format/template.ts | TypeScript | mit | 3,227 |
package com.example.aperture.core.contacts;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.provider.ContactsContract;
import java.util.List;
import java.util.ArrayList;
import com.example.aperture.core.Module;
public class EmailFilter extends Filter {
private final static String[] DATA_PROJECTION = new String[] {
ContactsContract.Contacts.LOOKUP_KEY,
ContactsContract.Contacts.DISPLAY_NAME_PRIMARY,
ContactsContract.Data.DATA1
};
private final static String MIMETYPE_SELECTION =
ContactsContract.Data.MIMETYPE + "=?";
private final static String[] EMAIL_MIMETYPE = new String[] {
ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE
};
private final static String[] PREFIXES = new String[] {
"send an email to ",
"send email to ",
"email "
};
private final static class EmailComparer implements java.util.Comparator<Intent> {
private String mFragment;
public EmailComparer(String fragment) {
mFragment = fragment;
}
@Override
public boolean equals(Object o) { return false; }
@Override
public int compare(Intent a, Intent b) {
// Get the emails from the intents.
String x = a.getStringExtra(ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE);
String y = b.getStringExtra(ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE);
// Split the emails into usernames and domains.
String xu = x.substring(0, x.indexOf('@'));
String yu = y.substring(0, y.indexOf('@'));
String xd = x.substring(x.indexOf('@')+1);
String yd = y.substring(y.indexOf('@')+1);
// Get the locations of the query in the usernames and domains.
int ixu = xu.indexOf(mFragment), iyu = yu.indexOf(mFragment);
int ixd = xd.indexOf(mFragment), iyd = yd.indexOf(mFragment);
// TODO refactor this to be less iffy
// Explicitly writing out the comparision logic to avoid violating
// general sorting contract for total ordering.
if(ixu != -1 && iyu != -1) {
if(ixu < iyu) return -1;
else if(iyu < ixu) return 1;
else return xu.compareTo(yu);
}
else if(ixu != -1 && iyu == -1) {
return -1;
}
else if(ixu == -1 && iyu != -1) {
return 1;
}
else {
if(ixd != -1 && iyd != -1) {
if(ixd < iyd) return -1;
else if(iyd < ixd) return 1;
else return xd.compareTo(yd);
}
else if(ixd != -1 && iyd == -1) {
return -1;
}
else if(ixd == -1 && iyd != -1) {
return 1;
}
else
return x.compareTo(y);
}
}
}
private void sort(List<Intent> results, String query) {
Intent[] buffer = new Intent[results.size()];
java.util.Arrays.sort(results.toArray(buffer), 0, buffer.length,
new EmailComparer(query));
results.clear();
for(int i = 0; i < buffer.length; ++i)
results.add(buffer[i]);
}
@Override
public List<Intent> filter(Context context, String query) {
List<Intent> results = new ArrayList<Intent>();
boolean hasPrefix = false;
for(String prefix: PREFIXES) {
if(query.startsWith(prefix)) {
query = query.substring(prefix.length());
hasPrefix = true;
break;
}
}
Cursor data = context.getContentResolver().query(
ContactsContract.Data.CONTENT_URI,
DATA_PROJECTION,
MIMETYPE_SELECTION,
EMAIL_MIMETYPE,
null);
if(hasPrefix)
results.addAll(filterByName(data, query));
results.addAll(filterByAddress(data, query));
data.close();
return results;
}
private List<Intent> filterByName(Cursor data, String query) {
List<Intent> results = new ArrayList<Intent>();
query = query.toLowerCase();
for(data.moveToFirst(); !data.isAfterLast(); data.moveToNext()) {
String name = data.getString(1).toLowerCase();
if(name.contains(query))
results.add(intentFor(data.getString(1), data.getString(2)));
}
return results;
}
private List<Intent> filterByAddress(Cursor data, String query) {
List<Intent> results = new ArrayList<Intent>();
for(data.moveToFirst(); !data.isAfterLast(); data.moveToNext()) {
String email = data.getString(2);
if(email.contains(query))
results.add(intentFor(data.getString(1), email));
}
sort(results, query);
return results;
}
private Intent intentFor(String displayName, String email) {
Intent result = new Intent(Intent.ACTION_SENDTO,
new Uri.Builder().scheme("mailto").opaquePart(email).build());
result.putExtra(ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE, email);
result.putExtra(Module.RESPONSE_TEXT,
String.format("%1$s <%2$s>", displayName, email));
return result;
}
}
| ayshen/caek | src/com/example/aperture/core/contacts/EmailFilter.java | Java | mit | 5,607 |
<?php
return array (
'id' => 'samsung_n300_ver1',
'fallback' => 'uptext_generic',
'capabilities' =>
array (
'model_name' => 'SGH-N300',
'brand_name' => 'Samsung',
'streaming_real_media' => 'none',
),
);
| cuckata23/wurfl-data | data/samsung_n300_ver1.php | PHP | mit | 226 |
// Copyright (c) 2011-2014 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "kcoingui.h"
#include "kcoinunits.h"
#include "clientmodel.h"
#include "guiconstants.h"
#include "guiutil.h"
#include "networkstyle.h"
#include "notificator.h"
#include "openuridialog.h"
#include "optionsdialog.h"
#include "optionsmodel.h"
#include "platformstyle.h"
#include "rpcconsole.h"
#include "utilitydialog.h"
#ifdef ENABLE_WALLET
#include "walletframe.h"
#include "walletmodel.h"
#endif // ENABLE_WALLET
#ifdef Q_OS_MAC
#include "macdockiconhandler.h"
#endif
#include "init.h"
#include "ui_interface.h"
#include "util.h"
#include <iostream>
#include <QAction>
#include <QApplication>
#include <QDateTime>
#include <QDesktopWidget>
#include <QDragEnterEvent>
#include <QListWidget>
#include <QMenuBar>
#include <QMessageBox>
#include <QMimeData>
#include <QProgressBar>
#include <QProgressDialog>
#include <QSettings>
#include <QStackedWidget>
#include <QStatusBar>
#include <QStyle>
#include <QTimer>
#include <QToolBar>
#include <QVBoxLayout>
#if QT_VERSION < 0x050000
#include <QTextDocument>
#include <QUrl>
#else
#include <QUrlQuery>
#endif
const QString KcoinGUI::DEFAULT_WALLET = "~Default";
KcoinGUI::KcoinGUI(const PlatformStyle *platformStyle, const NetworkStyle *networkStyle, QWidget *parent) :
QMainWindow(parent),
clientModel(0),
walletFrame(0),
unitDisplayControl(0),
labelEncryptionIcon(0),
labelConnectionsIcon(0),
labelBlocksIcon(0),
progressBarLabel(0),
progressBar(0),
progressDialog(0),
appMenuBar(0),
overviewAction(0),
historyAction(0),
quitAction(0),
sendCoinsAction(0),
sendCoinsMenuAction(0),
usedSendingAddressesAction(0),
usedReceivingAddressesAction(0),
signMessageAction(0),
verifyMessageAction(0),
aboutAction(0),
receiveCoinsAction(0),
receiveCoinsMenuAction(0),
optionsAction(0),
toggleHideAction(0),
encryptWalletAction(0),
backupWalletAction(0),
changePassphraseAction(0),
aboutQtAction(0),
openRPCConsoleAction(0),
openAction(0),
showHelpMessageAction(0),
trayIcon(0),
trayIconMenu(0),
notificator(0),
rpcConsole(0),
prevBlocks(0),
spinnerFrame(0),
platformStyle(platformStyle)
{
GUIUtil::restoreWindowGeometry("nWindow", QSize(850, 550), this);
QString windowTitle = tr("Kcoin Core") + " - ";
#ifdef ENABLE_WALLET
/* if compiled with wallet support, -disablewallet can still disable the wallet */
enableWallet = !GetBoolArg("-disablewallet", false);
#else
enableWallet = false;
#endif // ENABLE_WALLET
if(enableWallet)
{
windowTitle += tr("Wallet");
} else {
windowTitle += tr("Node");
}
windowTitle += " " + networkStyle->getTitleAddText();
#ifndef Q_OS_MAC
QApplication::setWindowIcon(networkStyle->getTrayAndWindowIcon());
setWindowIcon(networkStyle->getTrayAndWindowIcon());
#else
MacDockIconHandler::instance()->setIcon(networkStyle->getAppIcon());
#endif
setWindowTitle(windowTitle);
#if defined(Q_OS_MAC) && QT_VERSION < 0x050000
// This property is not implemented in Qt 5. Setting it has no effect.
// A replacement API (QtMacUnifiedToolBar) is available in QtMacExtras.
setUnifiedTitleAndToolBarOnMac(true);
#endif
rpcConsole = new RPCConsole(platformStyle, 0);
#ifdef ENABLE_WALLET
if(enableWallet)
{
/** Create wallet frame and make it the central widget */
walletFrame = new WalletFrame(platformStyle, this);
setCentralWidget(walletFrame);
} else
#endif // ENABLE_WALLET
{
/* When compiled without wallet or -disablewallet is provided,
* the central widget is the rpc console.
*/
setCentralWidget(rpcConsole);
}
// Accept D&D of URIs
setAcceptDrops(true);
// Create actions for the toolbar, menu bar and tray/dock icon
// Needs walletFrame to be initialized
createActions();
// Create application menu bar
createMenuBar();
// Create the toolbars
createToolBars();
// Create system tray icon and notification
createTrayIcon(networkStyle);
// Create status bar
statusBar();
// Disable size grip because it looks ugly and nobody needs it
statusBar()->setSizeGripEnabled(false);
// Status bar notification icons
QFrame *frameBlocks = new QFrame();
frameBlocks->setContentsMargins(0,0,0,0);
frameBlocks->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Preferred);
QHBoxLayout *frameBlocksLayout = new QHBoxLayout(frameBlocks);
frameBlocksLayout->setContentsMargins(3,0,3,0);
frameBlocksLayout->setSpacing(3);
unitDisplayControl = new UnitDisplayStatusBarControl(platformStyle);
labelEncryptionIcon = new QLabel();
labelConnectionsIcon = new QLabel();
labelBlocksIcon = new QLabel();
if(enableWallet)
{
frameBlocksLayout->addStretch();
frameBlocksLayout->addWidget(unitDisplayControl);
frameBlocksLayout->addStretch();
frameBlocksLayout->addWidget(labelEncryptionIcon);
}
frameBlocksLayout->addStretch();
frameBlocksLayout->addWidget(labelConnectionsIcon);
frameBlocksLayout->addStretch();
frameBlocksLayout->addWidget(labelBlocksIcon);
frameBlocksLayout->addStretch();
// Progress bar and label for blocks download
progressBarLabel = new QLabel();
progressBarLabel->setVisible(false);
progressBar = new GUIUtil::ProgressBar();
progressBar->setAlignment(Qt::AlignCenter);
progressBar->setVisible(false);
// Override style sheet for progress bar for styles that have a segmented progress bar,
// as they make the text unreadable (workaround for issue #1071)
// See https://qt-project.org/doc/qt-4.8/gallery.html
QString curStyle = QApplication::style()->metaObject()->className();
if(curStyle == "QWindowsStyle" || curStyle == "QWindowsXPStyle")
{
progressBar->setStyleSheet("QProgressBar { background-color: #e8e8e8; border: 1px solid grey; border-radius: 7px; padding: 1px; text-align: center; } QProgressBar::chunk { background: QLinearGradient(x1: 0, y1: 0, x2: 1, y2: 0, stop: 0 #FF8000, stop: 1 orange); border-radius: 7px; margin: 0px; }");
}
statusBar()->addWidget(progressBarLabel);
statusBar()->addWidget(progressBar);
statusBar()->addPermanentWidget(frameBlocks);
connect(openRPCConsoleAction, SIGNAL(triggered()), rpcConsole, SLOT(show()));
// prevents an open debug window from becoming stuck/unusable on client shutdown
connect(quitAction, SIGNAL(triggered()), rpcConsole, SLOT(hide()));
// Install event filter to be able to catch status tip events (QEvent::StatusTip)
this->installEventFilter(this);
// Initially wallet actions should be disabled
setWalletActionsEnabled(false);
// Subscribe to notifications from core
subscribeToCoreSignals();
}
KcoinGUI::~KcoinGUI()
{
// Unsubscribe from notifications from core
unsubscribeFromCoreSignals();
GUIUtil::saveWindowGeometry("nWindow", this);
if(trayIcon) // Hide tray icon, as deleting will let it linger until quit (on Ubuntu)
trayIcon->hide();
#ifdef Q_OS_MAC
delete appMenuBar;
MacDockIconHandler::cleanup();
#endif
delete rpcConsole;
}
void KcoinGUI::createActions()
{
QActionGroup *tabGroup = new QActionGroup(this);
overviewAction = new QAction(platformStyle->SingleColorIcon(":/icons/overview"), tr("&Overview"), this);
overviewAction->setStatusTip(tr("Show general overview of wallet"));
overviewAction->setToolTip(overviewAction->statusTip());
overviewAction->setCheckable(true);
overviewAction->setShortcut(QKeySequence(Qt::ALT + Qt::Key_1));
tabGroup->addAction(overviewAction);
sendCoinsAction = new QAction(platformStyle->SingleColorIcon(":/icons/send"), tr("&Send"), this);
sendCoinsAction->setStatusTip(tr("Send coins to a Kcoin address"));
sendCoinsAction->setToolTip(sendCoinsAction->statusTip());
sendCoinsAction->setCheckable(true);
sendCoinsAction->setShortcut(QKeySequence(Qt::ALT + Qt::Key_2));
tabGroup->addAction(sendCoinsAction);
sendCoinsMenuAction = new QAction(platformStyle->TextColorIcon(":/icons/send"), sendCoinsAction->text(), this);
sendCoinsMenuAction->setStatusTip(sendCoinsAction->statusTip());
sendCoinsMenuAction->setToolTip(sendCoinsMenuAction->statusTip());
receiveCoinsAction = new QAction(platformStyle->SingleColorIcon(":/icons/receiving_addresses"), tr("&Receive"), this);
receiveCoinsAction->setStatusTip(tr("Request payments (generates QR codes and kcoin: URIs)"));
receiveCoinsAction->setToolTip(receiveCoinsAction->statusTip());
receiveCoinsAction->setCheckable(true);
receiveCoinsAction->setShortcut(QKeySequence(Qt::ALT + Qt::Key_3));
tabGroup->addAction(receiveCoinsAction);
receiveCoinsMenuAction = new QAction(platformStyle->TextColorIcon(":/icons/receiving_addresses"), receiveCoinsAction->text(), this);
receiveCoinsMenuAction->setStatusTip(receiveCoinsAction->statusTip());
receiveCoinsMenuAction->setToolTip(receiveCoinsMenuAction->statusTip());
historyAction = new QAction(platformStyle->SingleColorIcon(":/icons/history"), tr("&Transactions"), this);
historyAction->setStatusTip(tr("Browse transaction history"));
historyAction->setToolTip(historyAction->statusTip());
historyAction->setCheckable(true);
historyAction->setShortcut(QKeySequence(Qt::ALT + Qt::Key_4));
tabGroup->addAction(historyAction);
#ifdef ENABLE_WALLET
// These showNormalIfMinimized are needed because Send Coins and Receive Coins
// can be triggered from the tray menu, and need to show the GUI to be useful.
connect(overviewAction, SIGNAL(triggered()), this, SLOT(showNormalIfMinimized()));
connect(overviewAction, SIGNAL(triggered()), this, SLOT(gotoOverviewPage()));
connect(sendCoinsAction, SIGNAL(triggered()), this, SLOT(showNormalIfMinimized()));
connect(sendCoinsAction, SIGNAL(triggered()), this, SLOT(gotoSendCoinsPage()));
connect(sendCoinsMenuAction, SIGNAL(triggered()), this, SLOT(showNormalIfMinimized()));
connect(sendCoinsMenuAction, SIGNAL(triggered()), this, SLOT(gotoSendCoinsPage()));
connect(receiveCoinsAction, SIGNAL(triggered()), this, SLOT(showNormalIfMinimized()));
connect(receiveCoinsAction, SIGNAL(triggered()), this, SLOT(gotoReceiveCoinsPage()));
connect(receiveCoinsMenuAction, SIGNAL(triggered()), this, SLOT(showNormalIfMinimized()));
connect(receiveCoinsMenuAction, SIGNAL(triggered()), this, SLOT(gotoReceiveCoinsPage()));
connect(historyAction, SIGNAL(triggered()), this, SLOT(showNormalIfMinimized()));
connect(historyAction, SIGNAL(triggered()), this, SLOT(gotoHistoryPage()));
#endif // ENABLE_WALLET
quitAction = new QAction(platformStyle->TextColorIcon(":/icons/quit"), tr("E&xit"), this);
quitAction->setStatusTip(tr("Quit application"));
quitAction->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_Q));
quitAction->setMenuRole(QAction::QuitRole);
aboutAction = new QAction(platformStyle->TextColorIcon(":/icons/about"), tr("&About Kcoin Core"), this);
aboutAction->setStatusTip(tr("Show information about Kcoin Core"));
aboutAction->setMenuRole(QAction::AboutRole);
aboutQtAction = new QAction(platformStyle->TextColorIcon(":/icons/about_qt"), tr("About &Qt"), this);
aboutQtAction->setStatusTip(tr("Show information about Qt"));
aboutQtAction->setMenuRole(QAction::AboutQtRole);
optionsAction = new QAction(platformStyle->TextColorIcon(":/icons/options"), tr("&Options..."), this);
optionsAction->setStatusTip(tr("Modify configuration options for Kcoin Core"));
optionsAction->setMenuRole(QAction::PreferencesRole);
toggleHideAction = new QAction(platformStyle->TextColorIcon(":/icons/about"), tr("&Show / Hide"), this);
toggleHideAction->setStatusTip(tr("Show or hide the main Window"));
encryptWalletAction = new QAction(platformStyle->TextColorIcon(":/icons/lock_closed"), tr("&Encrypt Wallet..."), this);
encryptWalletAction->setStatusTip(tr("Encrypt the private keys that belong to your wallet"));
encryptWalletAction->setCheckable(true);
backupWalletAction = new QAction(platformStyle->TextColorIcon(":/icons/filesave"), tr("&Backup Wallet..."), this);
backupWalletAction->setStatusTip(tr("Backup wallet to another location"));
changePassphraseAction = new QAction(platformStyle->TextColorIcon(":/icons/key"), tr("&Change Passphrase..."), this);
changePassphraseAction->setStatusTip(tr("Change the passphrase used for wallet encryption"));
signMessageAction = new QAction(platformStyle->TextColorIcon(":/icons/edit"), tr("Sign &message..."), this);
signMessageAction->setStatusTip(tr("Sign messages with your Kcoin addresses to prove you own them"));
verifyMessageAction = new QAction(platformStyle->TextColorIcon(":/icons/verify"), tr("&Verify message..."), this);
verifyMessageAction->setStatusTip(tr("Verify messages to ensure they were signed with specified Kcoin addresses"));
openRPCConsoleAction = new QAction(platformStyle->TextColorIcon(":/icons/debugwindow"), tr("&Debug window"), this);
openRPCConsoleAction->setStatusTip(tr("Open debugging and diagnostic console"));
usedSendingAddressesAction = new QAction(platformStyle->TextColorIcon(":/icons/address-book"), tr("&Sending addresses..."), this);
usedSendingAddressesAction->setStatusTip(tr("Show the list of used sending addresses and labels"));
usedReceivingAddressesAction = new QAction(platformStyle->TextColorIcon(":/icons/address-book"), tr("&Receiving addresses..."), this);
usedReceivingAddressesAction->setStatusTip(tr("Show the list of used receiving addresses and labels"));
openAction = new QAction(platformStyle->TextColorIcon(":/icons/open"), tr("Open &URI..."), this);
openAction->setStatusTip(tr("Open a kcoin: URI or payment request"));
showHelpMessageAction = new QAction(platformStyle->TextColorIcon(":/icons/info"), tr("&Command-line options"), this);
showHelpMessageAction->setMenuRole(QAction::NoRole);
showHelpMessageAction->setStatusTip(tr("Show the Kcoin Core help message to get a list with possible Kcoin command-line options"));
connect(quitAction, SIGNAL(triggered()), qApp, SLOT(quit()));
connect(aboutAction, SIGNAL(triggered()), this, SLOT(aboutClicked()));
connect(aboutQtAction, SIGNAL(triggered()), qApp, SLOT(aboutQt()));
connect(optionsAction, SIGNAL(triggered()), this, SLOT(optionsClicked()));
connect(toggleHideAction, SIGNAL(triggered()), this, SLOT(toggleHidden()));
connect(showHelpMessageAction, SIGNAL(triggered()), this, SLOT(showHelpMessageClicked()));
#ifdef ENABLE_WALLET
if(walletFrame)
{
connect(encryptWalletAction, SIGNAL(triggered(bool)), walletFrame, SLOT(encryptWallet(bool)));
connect(backupWalletAction, SIGNAL(triggered()), walletFrame, SLOT(backupWallet()));
connect(changePassphraseAction, SIGNAL(triggered()), walletFrame, SLOT(changePassphrase()));
connect(signMessageAction, SIGNAL(triggered()), this, SLOT(gotoSignMessageTab()));
connect(verifyMessageAction, SIGNAL(triggered()), this, SLOT(gotoVerifyMessageTab()));
connect(usedSendingAddressesAction, SIGNAL(triggered()), walletFrame, SLOT(usedSendingAddresses()));
connect(usedReceivingAddressesAction, SIGNAL(triggered()), walletFrame, SLOT(usedReceivingAddresses()));
connect(openAction, SIGNAL(triggered()), this, SLOT(openClicked()));
}
#endif // ENABLE_WALLET
}
void KcoinGUI::createMenuBar()
{
#ifdef Q_OS_MAC
// Create a decoupled menu bar on Mac which stays even if the window is closed
appMenuBar = new QMenuBar();
#else
// Get the main window's menu bar on other platforms
appMenuBar = menuBar();
#endif
// Configure the menus
QMenu *file = appMenuBar->addMenu(tr("&File"));
if(walletFrame)
{
file->addAction(openAction);
file->addAction(backupWalletAction);
file->addAction(signMessageAction);
file->addAction(verifyMessageAction);
file->addSeparator();
file->addAction(usedSendingAddressesAction);
file->addAction(usedReceivingAddressesAction);
file->addSeparator();
}
file->addAction(quitAction);
QMenu *settings = appMenuBar->addMenu(tr("&Settings"));
if(walletFrame)
{
settings->addAction(encryptWalletAction);
settings->addAction(changePassphraseAction);
settings->addSeparator();
}
settings->addAction(optionsAction);
QMenu *help = appMenuBar->addMenu(tr("&Help"));
if(walletFrame)
{
help->addAction(openRPCConsoleAction);
}
help->addAction(showHelpMessageAction);
help->addSeparator();
help->addAction(aboutAction);
help->addAction(aboutQtAction);
}
void KcoinGUI::createToolBars()
{
if(walletFrame)
{
QToolBar *toolbar = addToolBar(tr("Tabs toolbar"));
toolbar->setMovable(false);
toolbar->setToolButtonStyle(Qt::ToolButtonTextBesideIcon);
toolbar->addAction(overviewAction);
toolbar->addAction(sendCoinsAction);
toolbar->addAction(receiveCoinsAction);
toolbar->addAction(historyAction);
overviewAction->setChecked(true);
}
}
void KcoinGUI::setClientModel(ClientModel *clientModel)
{
this->clientModel = clientModel;
if(clientModel)
{
// Create system tray menu (or setup the dock menu) that late to prevent users from calling actions,
// while the client has not yet fully loaded
createTrayIconMenu();
// Keep up to date with client
setNumConnections(clientModel->getNumConnections());
connect(clientModel, SIGNAL(numConnectionsChanged(int)), this, SLOT(setNumConnections(int)));
setNumBlocks(clientModel->getNumBlocks(), clientModel->getLastBlockDate());
connect(clientModel, SIGNAL(numBlocksChanged(int,QDateTime)), this, SLOT(setNumBlocks(int,QDateTime)));
// Receive and report messages from client model
connect(clientModel, SIGNAL(message(QString,QString,unsigned int)), this, SLOT(message(QString,QString,unsigned int)));
// Show progress dialog
connect(clientModel, SIGNAL(showProgress(QString,int)), this, SLOT(showProgress(QString,int)));
rpcConsole->setClientModel(clientModel);
#ifdef ENABLE_WALLET
if(walletFrame)
{
walletFrame->setClientModel(clientModel);
}
#endif // ENABLE_WALLET
unitDisplayControl->setOptionsModel(clientModel->getOptionsModel());
} else {
// Disable possibility to show main window via action
toggleHideAction->setEnabled(false);
if(trayIconMenu)
{
// Disable context menu on tray icon
trayIconMenu->clear();
}
}
}
#ifdef ENABLE_WALLET
bool KcoinGUI::addWallet(const QString& name, WalletModel *walletModel)
{
if(!walletFrame)
return false;
setWalletActionsEnabled(true);
return walletFrame->addWallet(name, walletModel);
}
bool KcoinGUI::setCurrentWallet(const QString& name)
{
if(!walletFrame)
return false;
return walletFrame->setCurrentWallet(name);
}
void KcoinGUI::removeAllWallets()
{
if(!walletFrame)
return;
setWalletActionsEnabled(false);
walletFrame->removeAllWallets();
}
#endif // ENABLE_WALLET
void KcoinGUI::setWalletActionsEnabled(bool enabled)
{
overviewAction->setEnabled(enabled);
sendCoinsAction->setEnabled(enabled);
sendCoinsMenuAction->setEnabled(enabled);
receiveCoinsAction->setEnabled(enabled);
receiveCoinsMenuAction->setEnabled(enabled);
historyAction->setEnabled(enabled);
encryptWalletAction->setEnabled(enabled);
backupWalletAction->setEnabled(enabled);
changePassphraseAction->setEnabled(enabled);
signMessageAction->setEnabled(enabled);
verifyMessageAction->setEnabled(enabled);
usedSendingAddressesAction->setEnabled(enabled);
usedReceivingAddressesAction->setEnabled(enabled);
openAction->setEnabled(enabled);
}
void KcoinGUI::createTrayIcon(const NetworkStyle *networkStyle)
{
#ifndef Q_OS_MAC
trayIcon = new QSystemTrayIcon(this);
QString toolTip = tr("Kcoin Core client") + " " + networkStyle->getTitleAddText();
trayIcon->setToolTip(toolTip);
trayIcon->setIcon(networkStyle->getTrayAndWindowIcon());
trayIcon->show();
#endif
notificator = new Notificator(QApplication::applicationName(), trayIcon, this);
}
void KcoinGUI::createTrayIconMenu()
{
#ifndef Q_OS_MAC
// return if trayIcon is unset (only on non-Mac OSes)
if (!trayIcon)
return;
trayIconMenu = new QMenu(this);
trayIcon->setContextMenu(trayIconMenu);
connect(trayIcon, SIGNAL(activated(QSystemTrayIcon::ActivationReason)),
this, SLOT(trayIconActivated(QSystemTrayIcon::ActivationReason)));
#else
// Note: On Mac, the dock icon is used to provide the tray's functionality.
MacDockIconHandler *dockIconHandler = MacDockIconHandler::instance();
dockIconHandler->setMainWindow((QMainWindow *)this);
trayIconMenu = dockIconHandler->dockMenu();
#endif
// Configuration of the tray icon (or dock icon) icon menu
trayIconMenu->addAction(toggleHideAction);
trayIconMenu->addSeparator();
trayIconMenu->addAction(sendCoinsMenuAction);
trayIconMenu->addAction(receiveCoinsMenuAction);
trayIconMenu->addSeparator();
trayIconMenu->addAction(signMessageAction);
trayIconMenu->addAction(verifyMessageAction);
trayIconMenu->addSeparator();
trayIconMenu->addAction(optionsAction);
trayIconMenu->addAction(openRPCConsoleAction);
#ifndef Q_OS_MAC // This is built-in on Mac
trayIconMenu->addSeparator();
trayIconMenu->addAction(quitAction);
#endif
}
#ifndef Q_OS_MAC
void KcoinGUI::trayIconActivated(QSystemTrayIcon::ActivationReason reason)
{
if(reason == QSystemTrayIcon::Trigger)
{
// Click on system tray icon triggers show/hide of the main window
toggleHidden();
}
}
#endif
void KcoinGUI::optionsClicked()
{
if(!clientModel || !clientModel->getOptionsModel())
return;
OptionsDialog dlg(this, enableWallet);
dlg.setModel(clientModel->getOptionsModel());
dlg.exec();
}
void KcoinGUI::aboutClicked()
{
if(!clientModel)
return;
HelpMessageDialog dlg(this, true);
dlg.exec();
}
void KcoinGUI::showHelpMessageClicked()
{
HelpMessageDialog *help = new HelpMessageDialog(this, false);
help->setAttribute(Qt::WA_DeleteOnClose);
help->show();
}
#ifdef ENABLE_WALLET
void KcoinGUI::openClicked()
{
OpenURIDialog dlg(this);
if(dlg.exec())
{
Q_EMIT receivedURI(dlg.getURI());
}
}
void KcoinGUI::gotoOverviewPage()
{
overviewAction->setChecked(true);
if (walletFrame) walletFrame->gotoOverviewPage();
}
void KcoinGUI::gotoHistoryPage()
{
historyAction->setChecked(true);
if (walletFrame) walletFrame->gotoHistoryPage();
}
void KcoinGUI::gotoReceiveCoinsPage()
{
receiveCoinsAction->setChecked(true);
if (walletFrame) walletFrame->gotoReceiveCoinsPage();
}
void KcoinGUI::gotoSendCoinsPage(QString addr)
{
sendCoinsAction->setChecked(true);
if (walletFrame) walletFrame->gotoSendCoinsPage(addr);
}
void KcoinGUI::gotoSignMessageTab(QString addr)
{
if (walletFrame) walletFrame->gotoSignMessageTab(addr);
}
void KcoinGUI::gotoVerifyMessageTab(QString addr)
{
if (walletFrame) walletFrame->gotoVerifyMessageTab(addr);
}
#endif // ENABLE_WALLET
void KcoinGUI::setNumConnections(int count)
{
QString icon;
switch(count)
{
case 0: icon = ":/icons/connect_0"; break;
case 1: case 2: case 3: icon = ":/icons/connect_1"; break;
case 4: case 5: case 6: icon = ":/icons/connect_2"; break;
case 7: case 8: case 9: icon = ":/icons/connect_3"; break;
default: icon = ":/icons/connect_4"; break;
}
labelConnectionsIcon->setPixmap(platformStyle->SingleColorIcon(icon).pixmap(STATUSBAR_ICONSIZE,STATUSBAR_ICONSIZE));
labelConnectionsIcon->setToolTip(tr("%n active connection(s) to Kcoin network", "", count));
}
void KcoinGUI::setNumBlocks(int count, const QDateTime& blockDate)
{
if(!clientModel)
return;
// Prevent orphan statusbar messages (e.g. hover Quit in main menu, wait until chain-sync starts -> garbelled text)
statusBar()->clearMessage();
// Acquire current block source
enum BlockSource blockSource = clientModel->getBlockSource();
switch (blockSource) {
case BLOCK_SOURCE_NETWORK:
progressBarLabel->setText(tr("Synchronizing with network..."));
break;
case BLOCK_SOURCE_DISK:
progressBarLabel->setText(tr("Importing blocks from disk..."));
break;
case BLOCK_SOURCE_REINDEX:
progressBarLabel->setText(tr("Reindexing blocks on disk..."));
break;
case BLOCK_SOURCE_NONE:
// Case: not Importing, not Reindexing and no network connection
progressBarLabel->setText(tr("No block source available..."));
break;
}
QString tooltip;
QDateTime currentDate = QDateTime::currentDateTime();
qint64 secs = blockDate.secsTo(currentDate);
tooltip = tr("Processed %n block(s) of transaction history.", "", count);
// Set icon state: spinning if catching up, tick otherwise
if(secs < 90*60)
{
tooltip = tr("Up to date") + QString(".<br>") + tooltip;
labelBlocksIcon->setPixmap(platformStyle->SingleColorIcon(":/icons/synced").pixmap(STATUSBAR_ICONSIZE, STATUSBAR_ICONSIZE));
#ifdef ENABLE_WALLET
if(walletFrame)
walletFrame->showOutOfSyncWarning(false);
#endif // ENABLE_WALLET
progressBarLabel->setVisible(false);
progressBar->setVisible(false);
}
else
{
// Represent time from last generated block in human readable text
QString timeBehindText;
const int HOUR_IN_SECONDS = 60*60;
const int DAY_IN_SECONDS = 24*60*60;
const int WEEK_IN_SECONDS = 7*24*60*60;
const int YEAR_IN_SECONDS = 31556952; // Average length of year in Gregorian calendar
if(secs < 2*DAY_IN_SECONDS)
{
timeBehindText = tr("%n hour(s)","",secs/HOUR_IN_SECONDS);
}
else if(secs < 2*WEEK_IN_SECONDS)
{
timeBehindText = tr("%n day(s)","",secs/DAY_IN_SECONDS);
}
else if(secs < YEAR_IN_SECONDS)
{
timeBehindText = tr("%n week(s)","",secs/WEEK_IN_SECONDS);
}
else
{
qint64 years = secs / YEAR_IN_SECONDS;
qint64 remainder = secs % YEAR_IN_SECONDS;
timeBehindText = tr("%1 and %2").arg(tr("%n year(s)", "", years)).arg(tr("%n week(s)","", remainder/WEEK_IN_SECONDS));
}
progressBarLabel->setVisible(true);
progressBar->setFormat(tr("%1 behind").arg(timeBehindText));
progressBar->setMaximum(1000000000);
progressBar->setValue(clientModel->getVerificationProgress() * 1000000000.0 + 0.5);
progressBar->setVisible(true);
tooltip = tr("Catching up...") + QString("<br>") + tooltip;
if(count != prevBlocks)
{
labelBlocksIcon->setPixmap(platformStyle->SingleColorIcon(QString(
":/movies/spinner-%1").arg(spinnerFrame, 3, 10, QChar('0')))
.pixmap(STATUSBAR_ICONSIZE, STATUSBAR_ICONSIZE));
spinnerFrame = (spinnerFrame + 1) % SPINNER_FRAMES;
}
prevBlocks = count;
#ifdef ENABLE_WALLET
if(walletFrame)
walletFrame->showOutOfSyncWarning(true);
#endif // ENABLE_WALLET
tooltip += QString("<br>");
tooltip += tr("Last received block was generated %1 ago.").arg(timeBehindText);
tooltip += QString("<br>");
tooltip += tr("Transactions after this will not yet be visible.");
}
// Don't word-wrap this (fixed-width) tooltip
tooltip = QString("<nobr>") + tooltip + QString("</nobr>");
labelBlocksIcon->setToolTip(tooltip);
progressBarLabel->setToolTip(tooltip);
progressBar->setToolTip(tooltip);
}
void KcoinGUI::message(const QString &title, const QString &message, unsigned int style, bool *ret)
{
QString strTitle = tr("Kcoin"); // default title
// Default to information icon
int nMBoxIcon = QMessageBox::Information;
int nNotifyIcon = Notificator::Information;
QString msgType;
// Prefer supplied title over style based title
if (!title.isEmpty()) {
msgType = title;
}
else {
switch (style) {
case CClientUIInterface::MSG_ERROR:
msgType = tr("Error");
break;
case CClientUIInterface::MSG_WARNING:
msgType = tr("Warning");
break;
case CClientUIInterface::MSG_INFORMATION:
msgType = tr("Information");
break;
default:
break;
}
}
// Append title to "Kcoin - "
if (!msgType.isEmpty())
strTitle += " - " + msgType;
// Check for error/warning icon
if (style & CClientUIInterface::ICON_ERROR) {
nMBoxIcon = QMessageBox::Critical;
nNotifyIcon = Notificator::Critical;
}
else if (style & CClientUIInterface::ICON_WARNING) {
nMBoxIcon = QMessageBox::Warning;
nNotifyIcon = Notificator::Warning;
}
// Display message
if (style & CClientUIInterface::MODAL) {
// Check for buttons, use OK as default, if none was supplied
QMessageBox::StandardButton buttons;
if (!(buttons = (QMessageBox::StandardButton)(style & CClientUIInterface::BTN_MASK)))
buttons = QMessageBox::Ok;
showNormalIfMinimized();
QMessageBox mBox((QMessageBox::Icon)nMBoxIcon, strTitle, message, buttons, this);
int r = mBox.exec();
if (ret != NULL)
*ret = r == QMessageBox::Ok;
}
else
notificator->notify((Notificator::Class)nNotifyIcon, strTitle, message);
}
void KcoinGUI::changeEvent(QEvent *e)
{
QMainWindow::changeEvent(e);
#ifndef Q_OS_MAC // Ignored on Mac
if(e->type() == QEvent::WindowStateChange)
{
if(clientModel && clientModel->getOptionsModel() && clientModel->getOptionsModel()->getMinimizeToTray())
{
QWindowStateChangeEvent *wsevt = static_cast<QWindowStateChangeEvent*>(e);
if(!(wsevt->oldState() & Qt::WindowMinimized) && isMinimized())
{
QTimer::singleShot(0, this, SLOT(hide()));
e->ignore();
}
}
}
#endif
}
void KcoinGUI::closeEvent(QCloseEvent *event)
{
#ifndef Q_OS_MAC // Ignored on Mac
if(clientModel && clientModel->getOptionsModel())
{
if(!clientModel->getOptionsModel()->getMinimizeToTray() &&
!clientModel->getOptionsModel()->getMinimizeOnClose())
{
// close rpcConsole in case it was open to make some space for the shutdown window
rpcConsole->close();
QApplication::quit();
}
}
#endif
QMainWindow::closeEvent(event);
}
#ifdef ENABLE_WALLET
void KcoinGUI::incomingTransaction(const QString& date, int unit, const CAmount& amount, const QString& type, const QString& address, const QString& label)
{
// On new transaction, make an info balloon
QString msg = tr("Date: %1\n").arg(date) +
tr("Amount: %1\n").arg(KcoinUnits::formatWithUnit(unit, amount, true)) +
tr("Type: %1\n").arg(type);
if (!label.isEmpty())
msg += tr("Label: %1\n").arg(label);
else if (!address.isEmpty())
msg += tr("Address: %1\n").arg(address);
message((amount)<0 ? tr("Sent transaction") : tr("Incoming transaction"),
msg, CClientUIInterface::MSG_INFORMATION);
}
#endif // ENABLE_WALLET
void KcoinGUI::dragEnterEvent(QDragEnterEvent *event)
{
// Accept only URIs
if(event->mimeData()->hasUrls())
event->acceptProposedAction();
}
void KcoinGUI::dropEvent(QDropEvent *event)
{
if(event->mimeData()->hasUrls())
{
Q_FOREACH(const QUrl &uri, event->mimeData()->urls())
{
Q_EMIT receivedURI(uri.toString());
}
}
event->acceptProposedAction();
}
bool KcoinGUI::eventFilter(QObject *object, QEvent *event)
{
// Catch status tip events
if (event->type() == QEvent::StatusTip)
{
// Prevent adding text from setStatusTip(), if we currently use the status bar for displaying other stuff
if (progressBarLabel->isVisible() || progressBar->isVisible())
return true;
}
return QMainWindow::eventFilter(object, event);
}
#ifdef ENABLE_WALLET
bool KcoinGUI::handlePaymentRequest(const SendCoinsRecipient& recipient)
{
// URI has to be valid
if (walletFrame && walletFrame->handlePaymentRequest(recipient))
{
showNormalIfMinimized();
gotoSendCoinsPage();
return true;
}
return false;
}
void KcoinGUI::setEncryptionStatus(int status)
{
switch(status)
{
case WalletModel::Unencrypted:
labelEncryptionIcon->hide();
encryptWalletAction->setChecked(false);
changePassphraseAction->setEnabled(false);
encryptWalletAction->setEnabled(true);
break;
case WalletModel::Unlocked:
labelEncryptionIcon->show();
labelEncryptionIcon->setPixmap(platformStyle->SingleColorIcon(":/icons/lock_open").pixmap(STATUSBAR_ICONSIZE,STATUSBAR_ICONSIZE));
labelEncryptionIcon->setToolTip(tr("Wallet is <b>encrypted</b> and currently <b>unlocked</b>"));
encryptWalletAction->setChecked(true);
changePassphraseAction->setEnabled(true);
encryptWalletAction->setEnabled(false); // TODO: decrypt currently not supported
break;
case WalletModel::Locked:
labelEncryptionIcon->show();
labelEncryptionIcon->setPixmap(platformStyle->SingleColorIcon(":/icons/lock_closed").pixmap(STATUSBAR_ICONSIZE,STATUSBAR_ICONSIZE));
labelEncryptionIcon->setToolTip(tr("Wallet is <b>encrypted</b> and currently <b>locked</b>"));
encryptWalletAction->setChecked(true);
changePassphraseAction->setEnabled(true);
encryptWalletAction->setEnabled(false); // TODO: decrypt currently not supported
break;
}
}
#endif // ENABLE_WALLET
void KcoinGUI::showNormalIfMinimized(bool fToggleHidden)
{
if(!clientModel)
return;
// activateWindow() (sometimes) helps with keyboard focus on Windows
if (isHidden())
{
show();
activateWindow();
}
else if (isMinimized())
{
showNormal();
activateWindow();
}
else if (GUIUtil::isObscured(this))
{
raise();
activateWindow();
}
else if(fToggleHidden)
hide();
}
void KcoinGUI::toggleHidden()
{
showNormalIfMinimized(true);
}
void KcoinGUI::detectShutdown()
{
if (ShutdownRequested())
{
if(rpcConsole)
rpcConsole->hide();
qApp->quit();
}
}
void KcoinGUI::showProgress(const QString &title, int nProgress)
{
if (nProgress == 0)
{
progressDialog = new QProgressDialog(title, "", 0, 100);
progressDialog->setWindowModality(Qt::ApplicationModal);
progressDialog->setMinimumDuration(0);
progressDialog->setCancelButton(0);
progressDialog->setAutoClose(false);
progressDialog->setValue(0);
}
else if (nProgress == 100)
{
if (progressDialog)
{
progressDialog->close();
progressDialog->deleteLater();
}
}
else if (progressDialog)
progressDialog->setValue(nProgress);
}
static bool ThreadSafeMessageBox(KcoinGUI *gui, const std::string& message, const std::string& caption, unsigned int style)
{
bool modal = (style & CClientUIInterface::MODAL);
// The SECURE flag has no effect in the Qt GUI.
// bool secure = (style & CClientUIInterface::SECURE);
style &= ~CClientUIInterface::SECURE;
bool ret = false;
// In case of modal message, use blocking connection to wait for user to click a button
QMetaObject::invokeMethod(gui, "message",
modal ? GUIUtil::blockingGUIThreadConnection() : Qt::QueuedConnection,
Q_ARG(QString, QString::fromStdString(caption)),
Q_ARG(QString, QString::fromStdString(message)),
Q_ARG(unsigned int, style),
Q_ARG(bool*, &ret));
return ret;
}
void KcoinGUI::subscribeToCoreSignals()
{
// Connect signals to client
uiInterface.ThreadSafeMessageBox.connect(boost::bind(ThreadSafeMessageBox, this, _1, _2, _3));
}
void KcoinGUI::unsubscribeFromCoreSignals()
{
// Disconnect signals from client
uiInterface.ThreadSafeMessageBox.disconnect(boost::bind(ThreadSafeMessageBox, this, _1, _2, _3));
}
UnitDisplayStatusBarControl::UnitDisplayStatusBarControl(const PlatformStyle *platformStyle) :
optionsModel(0),
menu(0)
{
createContextMenu();
setToolTip(tr("Unit to show amounts in. Click to select another unit."));
QList<KcoinUnits::Unit> units = KcoinUnits::availableUnits();
int max_width = 0;
const QFontMetrics fm(font());
Q_FOREACH (const KcoinUnits::Unit unit, units)
{
max_width = qMax(max_width, fm.width(KcoinUnits::name(unit)));
}
setMinimumSize(max_width, 0);
setAlignment(Qt::AlignRight | Qt::AlignVCenter);
setStyleSheet(QString("QLabel { color : %1 }").arg(platformStyle->SingleColor().name()));
}
/** So that it responds to button clicks */
void UnitDisplayStatusBarControl::mousePressEvent(QMouseEvent *event)
{
onDisplayUnitsClicked(event->pos());
}
/** Creates context menu, its actions, and wires up all the relevant signals for mouse events. */
void UnitDisplayStatusBarControl::createContextMenu()
{
menu = new QMenu();
Q_FOREACH(KcoinUnits::Unit u, KcoinUnits::availableUnits())
{
QAction *menuAction = new QAction(QString(KcoinUnits::name(u)), this);
menuAction->setData(QVariant(u));
menu->addAction(menuAction);
}
connect(menu,SIGNAL(triggered(QAction*)),this,SLOT(onMenuSelection(QAction*)));
}
/** Lets the control know about the Options Model (and its signals) */
void UnitDisplayStatusBarControl::setOptionsModel(OptionsModel *optionsModel)
{
if (optionsModel)
{
this->optionsModel = optionsModel;
// be aware of a display unit change reported by the OptionsModel object.
connect(optionsModel,SIGNAL(displayUnitChanged(int)),this,SLOT(updateDisplayUnit(int)));
// initialize the display units label with the current value in the model.
updateDisplayUnit(optionsModel->getDisplayUnit());
}
}
/** When Display Units are changed on OptionsModel it will refresh the display text of the control on the status bar */
void UnitDisplayStatusBarControl::updateDisplayUnit(int newUnits)
{
setText(KcoinUnits::name(newUnits));
}
/** Shows context menu with Display Unit options by the mouse coordinates */
void UnitDisplayStatusBarControl::onDisplayUnitsClicked(const QPoint& point)
{
QPoint globalPos = mapToGlobal(point);
menu->exec(globalPos);
}
/** Tells underlying optionsModel to update its current display unit. */
void UnitDisplayStatusBarControl::onMenuSelection(QAction* action)
{
if (action)
{
optionsModel->setDisplayUnit(action->data());
}
}
| Kcoin-project/kcoin | src/qt/kcoingui.cpp | C++ | mit | 39,810 |
var xmas = {};
(function() {
xmas.present = {
box: {}
};
}());
(function(global) {
global.xmas.present.box.color = 'Red';
}(this));
| watilde/rejs-example | test/fixture1.js | JavaScript | mit | 146 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace GSAKWrapper.Excel
{
public class PropertyItemHasUserNote : PropertyItem
{
public PropertyItemHasUserNote()
: base("HasUserNote")
{
}
public override object GetValue(GeocacheData gc)
{
return gc.Caches.HasUserNote != 0;
}
}
}
| GlobalcachingEU/GSAKWrapper | GSAKWrapper/Excel/PropertyItemHasUserNote.cs | C# | mit | 439 |
Vswiki::Application.configure do
# Settings specified here will take precedence over those in config/application.rb.
# Code is not reloaded between requests.
config.cache_classes = true
# Eager load code on boot. This eager loads most of Rails and
# your application in memory, allowing both thread web servers
# and those relying on copy on write to perform better.
# Rake tasks automatically ignore this option for performance.
config.eager_load = true
# Full error reports are disabled and caching is turned on.
config.consider_all_requests_local = false
config.action_controller.perform_caching = true
# Enable Rack::Cache to put a simple HTTP cache in front of your application
# Add `rack-cache` to your Gemfile before enabling this.
# For large-scale production use, consider using a caching reverse proxy like nginx, varnish or squid.
# config.action_dispatch.rack_cache = true
# Disable serving static files from the `/public` folder by default since
# Apache or NGINX already handles this.
config.public_file_server.enabled = ENV['RAILS_SERVE_STATIC_FILES'].present?
# Compress JavaScripts and CSS.
config.assets.js_compressor = :uglifier
# config.assets.css_compressor = :sass
# Do not fallback to assets pipeline if a precompiled asset is missed.
config.assets.compile = false
# Generate digests for assets URLs.
config.assets.digest = true
# Version of your assets, change this if you want to expire all your assets.
config.assets.version = '1.0'
# Specifies the header that your server uses for sending files.
# config.action_dispatch.x_sendfile_header = "X-Sendfile" # for apache
# config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for nginx
# Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies.
# config.force_ssl = true
# Set to :debug to see everything in the log.
config.log_level = :info
# Prepend all log lines with the following tags.
# config.log_tags = [ :subdomain, :uuid ]
# Use a different logger for distributed setups.
# config.logger = ActiveSupport::TaggedLogging.new(SyslogLogger.new)
# Use a different cache store in production.
# config.cache_store = :mem_cache_store
# Enable serving of images, stylesheets, and JavaScripts from an asset server.
# config.action_controller.asset_host = "http://assets.example.com"
# Precompile additional assets.
# application.js, application.css, and all non-JS/CSS in app/assets folder are already added.
# config.assets.precompile += %w( search.js )
# Ignore bad email addresses and do not raise email delivery errors.
# Set this to true and configure the email server for immediate delivery to raise delivery errors.
# config.action_mailer.raise_delivery_errors = false
# Enable locale fallbacks for I18n (makes lookups for any locale fall back to
# the I18n.default_locale when a translation can not be found).
config.i18n.fallbacks = true
# Send deprecation notices to registered listeners.
config.active_support.deprecation = :notify
# Disable automatic flushing of the log to improve performance.
# config.autoflush_log = false
# Use default logging formatter so that PID and timestamp are not suppressed.
config.log_formatter = ::Logger::Formatter.new
end
| villez/vswiki | config/environments/production.rb | Ruby | mit | 3,332 |
/**
* A decorator for making sure specific function being invoked serializely.
*
* Usage:
* class A {
* @serialize
* async foo() {}
* }
*
*/
export default function serialize(target, key, descriptor) {
let prev = null;
function serializeFunc(...args) {
const next = () =>
Promise.resolve(descriptor.value.apply(this, args)).then(() => {
prev = null;
});
prev = prev ? prev.then(next) : next();
return prev;
}
return {
...descriptor,
value: serializeFunc,
};
}
| ringcentral/ringcentral-js-widget | packages/ringcentral-integration/lib/serialize.js | JavaScript | mit | 524 |
<?php
namespace Application\Controller;
use Zend\Mvc\Controller\AbstractRestfulController;
use Zend\View\Model\JsonModel;
class UserController extends AbstractRestfulController
{
protected $collectionOptions = array('GET', 'POST');
protected $resourceOptions = array('GET', 'PUT', 'DELETE');
protected function _getOptions()
{
// if we have an ID, return specific item
if ($this->params->fromRoute('id', false)) {
return $this->resourceOptions;
}
// no ID, return collection
return $this->collectionOptions;
}
public function option()
{
$response = $this->getResponse();
// If in Options Array, Allow
$response->getHeaders()
->addHeaderLine('Allow', implode(',', $this->_getOptions()));
return $response;
}
public function setEventManager(EventManagerInterface $events)
{
$this->events = $events;
// Register the listener and callback method with a priority of 10
$events->attach('dispatch', array($this, 'checkOptions'), 10);
}
public function checkOptions($e)
{
if (in_array($e->getRequest()->getMethod(), $this->_getOptions())) {
// Method Allowed, Nothing to Do
return;
}
// Method Not Allowed
$response = $this->getResponse();
$response->setStatusCode(405);
return $response;
}
public function create($data)
{
// Get created service to handle user creation
// in this case userAPIService extends UserService and
// adds in the _links or available actions to the result
$userAPIService = $this->getServiceLocator()->get('userAPIService');
$result = $userAPIService->create($data);
$response = $this->getResponse();
$response->setStatusCode(201);
// Send Data to the View
return new JsonModel($result);
}
}
| amercier/dogu-legacy | UserController.php | PHP | mit | 1,957 |
<?php
/**
* This module shows an introduction tour for new users
*
* @package profiler.modules_core.like
* @since 0.5
*/
class TourModule extends HWebModule
{
public $isCoreModule = true;
public static function onDashboardSidebarInit($event)
{
if (HSetting::Get('enable', 'tour') == 1 && Yii::app()->user->getModel()->getSetting("hideTourPanel", "tour") != 1) {
$event->sender->addWidget('application.modules_core.tour.widgets.TourDashboardWidget', array(), array('sortOrder' => 0));
}
}
}
| ProfilerTeam/Profiler | protected/modules_core/tour/TourModule.php | PHP | mit | 547 |
package ast
import (
"testing"
"bitbucket.org/yyuu/xtc/xt"
)
func TestPrefixOpNode(t *testing.T) {
x := NewPrefixOpNode(loc(0,0), "--", NewVariableNode(loc(0,0), "a"))
s := `{
"ClassName": "ast.PrefixOpNode",
"Location": "[:0,0]",
"Operator": "--",
"Expr": {
"ClassName": "ast.VariableNode",
"Location": "[:0,0]",
"Name": "a",
"Entity": null
},
"Amount": 1,
"Type": null
}`
xt.AssertStringEqualsDiff(t, "PrefixOpNode", xt.JSON(x), s)
}
| yyuu/xtc | ast/prefix_op_test.go | GO | mit | 478 |
package com.dpanayotov.simpleweather.api.base;
public class BaseForecastResponse {
}
| deanpanayotov/simple_weather | SimpleWeather/app/src/main/java/com/dpanayotov/simpleweather/api/base/BaseForecastResponse.java | Java | mit | 87 |
require 'rails_helper'
RSpec.describe "Pages", :type => :request do
describe "GET /pages" do
it "redirects when unauthenticated" do
get pages_path
expect(response.status).to be(302)
end
end
let(:rory) {User.create!(name: 'Rory', uid: "1")}
let(:valid_attributes) { { path: 'path/to/page', body: 'I am **content**' } }
let(:invalid_attributes) { { path: 'bad_page', body: nil} }
let(:valid_session) { { user_id: rory.id} }
describe "GET index" do
it "assigns all pages as @pages" do
sign_in rory
page = Page.create! valid_attributes
get pages_path
expect(response.body).to include("All Wiki Pages")
end
end
describe "GET show" do
it "assigns the requested page as @page" do
sign_in rory
page = Page.create! valid_attributes
get page_path(page)
expect(response.body).to include("I am")
end
end
describe "GET new" do
it "assigns a new page as @page" do
sign_in rory
get new_page_path
expect(response.body).to include("Path to the page")
end
end
describe "GET edit" do
it "assigns the requested page as @page" do
sign_in rory
page = Page.create! valid_attributes
get edit_page_path(page)
expect(response.body).to include("Path to the page")
end
end
describe "POST create" do
describe "with valid params" do
it "creates a new Page" do
sign_in rory
expect {
post pages_path, params: {page: valid_attributes}
}.to change(Page, :count).by(1)
end
it "redirects to the created page" do
sign_in rory
post pages_path, params: {page: valid_attributes}
expect(response).to redirect_to("/#{Page.last.path}")
end
end
describe "with invalid params" do
it "assigns a newly created but unsaved page as @page" do
sign_in rory
post pages_path, params: {page: invalid_attributes}
expect(response.body).to include("Body can't be blank")
end
end
end
describe "PUT update" do
describe "with valid params" do
let(:new_attributes) { {path: 'new/path'} }
it "updates the requested page" do
sign_in rory
page = Page.create! valid_attributes
put page_path(page), params: {page: new_attributes}
page.reload
expect(page.path).to eq('new/path')
end
it "redirects to the page" do
sign_in rory
page = Page.create! valid_attributes
put page_path(page), params: {page: new_attributes}
page.reload
expect(response).to redirect_to("/#{new_attributes[:path]}")
end
end
describe "with invalid params" do
it "assigns the page as @page" do
sign_in rory
page = Page.create! valid_attributes
put page_path(page), params: {page: invalid_attributes}
expect(response.body).to include("Body can't be blank")
end
end
end
describe "DELETE destroy" do
it "destroys the requested page" do
sign_in rory
page = Page.create! valid_attributes
expect {
delete page_path(page)
}.to change(Page, :count).by(-1)
end
it "redirects to the pages list" do
sign_in rory
page = Page.create! valid_attributes
delete page_path(page)
expect(response).to redirect_to(pages_url)
end
end
end
| csexton/corporate-tool | spec/requests/pages_request_spec.rb | Ruby | mit | 3,401 |
var functions = {}
functions.evaluateSnapshotType = function (name) {
var splittedName = name.split('-')
var type = splittedName[splittedName.length - 1].split('.')[0]
return type === 'motion' ? type : type === 'snapshot' ? 'periodic' : 'unknown'
}
functions.getSnapshotDate = function (name) {
var splittedData = name.split('.')[0].split('-')[0].split('/')
return splittedData[splittedData.length - 1]
}
module.exports = functions
| rackdon/securityCam-server | src/utils/commonUtils.js | JavaScript | mit | 446 |
package bsw
import (
"testing"
)
func TestMX(t *testing.T) {
_, results, err := MX("stacktitan.com", "8.8.8.8")
if err != nil {
t.Error("error returned from MX")
t.Log(err)
}
found := false
for _, r := range results {
if r.Hostname == "mx1.emailsrvr.com" {
found = true
}
}
if !found {
t.Error("MX did not find correct mx server")
t.Log(results)
}
}
| intfrr/blacksheepwall | bsw/mx_test.go | GO | mit | 376 |
package edu.avans.hartigehap.web.util;
import java.io.UnsupportedEncodingException;
import javax.servlet.http.HttpServletRequest;
import org.springframework.web.util.UriUtils;
import org.springframework.web.util.WebUtils;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class UrlUtil {
private UrlUtil() {
}
public static String encodeUrlPathSegment(String pathSegment, HttpServletRequest httpServletRequest) {
String enc = httpServletRequest.getCharacterEncoding();
if (enc == null) {
enc = WebUtils.DEFAULT_CHARACTER_ENCODING;
}
try {
pathSegment = UriUtils.encodePathSegment(pathSegment, enc);
} catch (UnsupportedEncodingException uee) {
log.error("UnsupportedEncodingException", uee);
}
return pathSegment;
}
}
| jermeyjungbeker/VP11B2 | src/main/java/edu/avans/hartigehap/web/util/UrlUtil.java | Java | mit | 833 |
package com.veggie.src.java.controllers.transaction;
import java.util.List;
import com.veggie.src.java.controllers.Controller;
import com.veggie.src.java.form.Form;
import com.veggie.src.java.form.AbstractFormBuilder;
import com.veggie.src.java.form.AbstractFormBuilderFactory;
import com.veggie.src.java.notification.Notification;
import com.veggie.src.java.notification.AbstractNotificationFactory;
import com.veggie.src.java.database.AbstractDatabaseManagerFactory;
import com.veggie.src.java.database.TransactionDatabaseManager;
import com.veggie.src.java.database.ItemDatabaseManager;
public class ReturnController implements Controller
{
private AbstractFormBuilder formBuilder;
private int itemid;
public ReturnController(){}
public Form activate()
{
formBuilder = AbstractFormBuilderFactory.getInstance().createFormBuilder();
formBuilder.addField("Item ID");
return formBuilder.getResult();
}
public Notification submitForm(Form form)
{
Notification notification;
List<String> formData = form.getData();
try{
itemid = Integer.parseInt(formData.get(0));
TransactionDatabaseManager transactionDBManager = AbstractDatabaseManagerFactory.getInstance().createTransactionDatabaseManager();
ItemDatabaseManager itemDBManager = AbstractDatabaseManagerFactory.getInstance().createItemDatabaseManager();
if(itemDBManager.getItem(itemid) == null){
return AbstractNotificationFactory.getInstance().createErrorNotification("Error item does not exist!");
}
transactionDBManager.finalizeTransaction(itemid);
notification = AbstractNotificationFactory.getInstance().createSuccessNotification("Item sucessfully returned!");
}catch(Exception e){
notification = AbstractNotificationFactory.getInstance().createErrorNotification("Error form data failure");
}
return notification; //???????
}
public void respondToNotification(Notification notif) {
//TO DO
}
}
| ejw0013/vegemite-smoothie | com/veggie/src/java/controllers/transaction/ReturnController.java | Java | mit | 1,973 |
using Android.App.Job;
namespace Plugin.FirebasePushNotification
{
public class PNFirebaseJobService : JobService
{
public override bool OnStartJob(JobParameters @params)
{
return false;
}
public override bool OnStopJob(JobParameters @params)
{
return false;
}
}
} | CrossGeeks/FirebasePushNotificationPlugin | Plugin.FirebasePushNotification/PNFirebasejobService.android.cs | C# | mit | 353 |
(function() {
'use strict';
angular
.module('rtsApp')
.directive('hasAuthority', hasAuthority);
hasAuthority.$inject = ['Principal'];
function hasAuthority(Principal) {
var directive = {
restrict: 'A',
link: linkFunc
};
return directive;
function linkFunc(scope, element, attrs) {
var authority = attrs.hasAuthority.replace(/\s+/g, '');
var setVisible = function () {
element.removeClass('hidden');
},
setHidden = function () {
element.addClass('hidden');
},
defineVisibility = function (reset) {
if (reset) {
setVisible();
}
Principal.hasAuthority(authority)
.then(function (result) {
if (result) {
setVisible();
} else {
setHidden();
}
});
};
if (authority.length > 0) {
defineVisibility(true);
scope.$watch(function() {
return Principal.isAuthenticated();
}, function() {
defineVisibility(true);
});
}
}
}
})();
| EnricoSchw/readthisstuff.com | src/main/webapp/app/services/auth/has-authority.directive.js | JavaScript | mit | 1,477 |
require 'rails_helper'
RSpec.describe Gallery, type: :model do
it "is valid with valid attributes" do
gallery = create(:gallery)
expect(gallery).to be_valid
end
describe "associations and validations" do
it { should have_many(:collections) }
it { should validate_presence_of(:name) }
it { should validate_uniqueness_of(:name) }
end
describe ".active" do
it "only returns active galleries" do
gallery1 = create(:gallery, archive: false)
gallery2 = create(:gallery, archive: false)
non_active_gallery = create(:gallery, archive: true)
galleries = Gallery.active
expect(galleries).to eq [gallery1, gallery2]
end
end
describe ".archived" do
it "return archived galleries" do
gallery1 = create(:gallery, archive: false)
gallery2 = create(:gallery, archive: true)
gallery3 = create(:gallery, archive: true)
galleries = Gallery.archived
expect(galleries).to eq [gallery2, gallery3]
end
end
end
| ericbooker12/fuzzy_hat_artist_site | spec/models/gallery_spec.rb | Ruby | mit | 1,006 |
Gitscm::Application.routes.draw do
constraints(:host => 'whygitisbetterthanx.com') do
root :to => 'site#redirect_wgibtx', as: :whygitisbetterthanx
end
constraints(:host => 'progit.org') do
root :to => 'site#redirect_book', as: :progit
get '*path' => 'site#redirect_book'
end
# constraints(:subdomain => 'book') do
# root :to => 'site#redirect_book'
# get '*path' => 'site#redirect_combook'
# end
get "site/index"
get "/doc" => "doc#index"
get "/docs" => "doc#ref"
get "/docs/howto/:file", to: redirect {|path_params, req|
"https://github.com/git/git/blob/master/Documentation/howto/#{path_params[:file]}.txt"
}
get "/docs/:file.html" => "doc#man", :as => :doc_file_html, :file => /[\w\-\.]+/
get "/docs/:file" => "doc#man", :as => :doc_file, :file => /[\w\-\.]+/
get "/docs/:file/:version" => "doc#man", :version => /[^\/]+/
get "/doc/ext" => "doc#ext"
%w{man ref git}.each do |path|
get "/#{path}/:file" => redirect("/docs/%{file}")
get "/#{path}/:file/:version" => redirect("/docs/%{file}/%{version}"),
:version => /[^\/]+/
end
resource :book do
get "/ch:chapter-:section.html" => "books#chapter"
get "/:lang/ch:chapter-:section.html" => "books#chapter"
get "/index" => redirect("/book")
get "/commands" => "books#commands"
get "/:lang/v:edition" => "books#show"
get "/:lang/v:edition/:slug" => "books#section"
get "/:lang/v:edition/:chapter/:link" => "books#link", chapter: /(ch|app)\d+/
get "/:lang" => "books#show", as: :lang
get "/:lang/:slug" => "books#section", as: :slug
end
post "/update" => "books#update"
get "/download" => "downloads#index"
get "/download/:platform" => "downloads#download"
get "/download/gui/:platform" => "downloads#gui"
resources :downloads, :only => [:index] do
collection do
get "/guis" => "downloads#guis"
get "/installers" => "downloads#installers"
get "/logos" => "downloads#logos"
get "/latest" => "downloads#latest"
end
end
get "/:year/:month/:day/:slug" => "blog#post", :year => /\d{4}/,
:month => /\d{2}/,
:day => /\d{2}/
get "/blog/:year/:month/:day/:slug" => "blog#post", :year => /\d{4}/,
:month => /\d{2}/,
:day => /\d{2}/
get "/blog" => "blog#index"
get "/publish" => "doc#book_update"
post "/related" => "doc#related_update"
get "/about" => "about#index"
get "/about/:section" => "about#index"
get "/videos" => "doc#videos"
get "/video/:id" => "doc#watch"
get "/community" => "community#index"
get "/search" => "site#search"
get "/search/results" => "site#search_results"
# mapping for jasons mocks
get "/documentation" => "doc#index"
get "/documentation/reference" => "doc#ref"
get "/documentation/reference/:file.html" => "doc#man"
get "/documentation/book" => "doc#book"
get "/documentation/videos" => "doc#videos"
get "/documentation/external-links" => "doc#ext"
get "/course/svn" => "site#svn"
get "/sfc" => "site#sfc"
get "/trademark" => redirect("/about/trademark")
get "/contributors" => redirect("https://github.com/git/git/graphs/contributors")
root :to => 'site#index'
end
| jasonlong/git-scm.com | config/routes.rb | Ruby | mit | 3,528 |
var async = require('async');
function captainHook(schema) {
// Pre-Save Setup
schema.pre('validate', function (next) {
var self = this;
this._wasNew = this.isNew;
if (this.isNew) {
this.runPreMethods(schema.preCreateMethods, self, function(){
next();
});
} else {
this.runPreMethods(schema.preUpdateMethods, self, function(){
next();
});
}
});
// Post-Save Setup
schema.post('save', function () {
var self = this;
if (this._wasNew) {
this.runPostMethods(schema.postCreateMethods, self);
} else {
this.runPostMethods(schema.postUpdateMethods, self);
}
});
/**
* Pre-Hooks
* These hooks run before an instance has been created / updated
*/
schema.methods.runPreMethods = function(methods, self, callback){
async.eachSeries(methods,
function(fn, cb) {
fn(self, cb);
}, function(err){
if (err){ throw err; }
callback();
});
};
// Pre-Create Methods
schema.preCreateMethods = [];
schema.preCreate = function(fn){
schema.preCreateMethods.push(fn);
};
// Pre-Update Methods
schema.preUpdateMethods = [];
schema.preUpdate = function(fn){
schema.preUpdateMethods.push(fn);
};
/**
* Post-Hooks
* These hooks run after an instance has been created / updated
*/
schema.methods.runPostMethods = function(methods, self){
async.eachSeries(methods,
function(fn, cb) {
fn(self, cb);
}, function(err){
if (err){ throw err; }
});
};
// Post-Create Methods
schema.postCreateMethods = [];
schema.postCreate = function(fn){
schema.postCreateMethods.push(fn);
};
// Post-Update Methods
schema.postUpdateMethods = [];
schema.postUpdate = function(fn){
schema.postUpdateMethods.push(fn);
};
}
module.exports = captainHook;
| hackley/captain-hook | lib/index.js | JavaScript | mit | 1,881 |
<?php
function formatBytes($bytes, $precision = 2) {
$units = array('B', 'KB', 'MB', 'GB', 'TB');
$bytes = max($bytes, 0);
$pow = floor(($bytes ? log($bytes) : 0) / log(1024));
$pow = min($pow, count($units) - 1);
$bytes /= pow(1024, $pow);
return round($bytes, $precision) . ' ' . $units[$pow];
}
function secondsToTime($seconds) {
$dtF = new DateTime("@0");
$dtT = new DateTime("@$seconds");
return $dtF->diff($dtT)->format('%a days');
}
function pagination($query,$per_page=10,$page=1,$url='?'){
global $con;
$query = "SELECT COUNT(*) as `num` FROM {$query}";
$row = mysqli_fetch_array(mysqli_query($con,$query));
$total = $row['num'];
$adjacents = "2";
$prevlabel = "‹ Prev";
$nextlabel = "Next ›";
$lastlabel = "Last ››";
$page = ($page == 0 ? 1 : $page);
$start = ($page - 1) * $per_page;
$prev = $page - 1;
$next = $page + 1;
$lastpage = ceil($total/$per_page);
$lpm1 = $lastpage - 1; // //last page minus 1
$pagination = "";
if($lastpage > 1){
$pagination .= "<ul class='pagination'>";
$pagination .= "<li class='page_info'>Page {$page} of {$lastpage}</li>";
if ($page > 1) $pagination.= "<li><a href='{$url}page={$prev}'>{$prevlabel}</a></li>";
if ($lastpage < 7 + ($adjacents * 2)){
for ($counter = 1; $counter <= $lastpage; $counter++){
if ($counter == $page)
$pagination.= "<li><a class='current'>{$counter}</a></li>";
else
$pagination.= "<li><a href='{$url}page={$counter}'>{$counter}</a></li>";
}
} elseif($lastpage > 5 + ($adjacents * 2)){
if($page < 1 + ($adjacents * 2)) {
for ($counter = 1; $counter < 4 + ($adjacents * 2); $counter++){
if ($counter == $page)
$pagination.= "<li><a class='current'>{$counter}</a></li>";
else
$pagination.= "<li><a href='{$url}page={$counter}'>{$counter}</a></li>";
}
$pagination.= "<li class='dot'>...</li>";
$pagination.= "<li><a href='{$url}page={$lpm1}'>{$lpm1}</a></li>";
$pagination.= "<li><a href='{$url}page={$lastpage}'>{$lastpage}</a></li>";
} elseif($lastpage - ($adjacents * 2) > $page && $page > ($adjacents * 2)) {
$pagination.= "<li><a href='{$url}page=1'>1</a></li>";
$pagination.= "<li><a href='{$url}page=2'>2</a></li>";
$pagination.= "<li class='dot'>...</li>";
for ($counter = $page - $adjacents; $counter <= $page + $adjacents; $counter++) {
if ($counter == $page)
$pagination.= "<li><a class='current'>{$counter}</a></li>";
else
$pagination.= "<li><a href='{$url}page={$counter}'>{$counter}</a></li>";
}
$pagination.= "<li class='dot'>..</li>";
$pagination.= "<li><a href='{$url}page={$lpm1}'>{$lpm1}</a></li>";
$pagination.= "<li><a href='{$url}page={$lastpage}'>{$lastpage}</a></li>";
} else {
$pagination.= "<li><a href='{$url}page=1'>1</a></li>";
$pagination.= "<li><a href='{$url}page=2'>2</a></li>";
$pagination.= "<li class='dot'>..</li>";
for ($counter = $lastpage - (2 + ($adjacents * 2)); $counter <= $lastpage; $counter++) {
if ($counter == $page)
$pagination.= "<li><a class='current'>{$counter}</a></li>";
else
$pagination.= "<li><a href='{$url}page={$counter}'>{$counter}</a></li>";
}
}
}
if ($page < $counter - 1) {
$pagination.= "<li><a href='{$url}page={$next}'>{$nextlabel}</a></li>";
$pagination.= "<li><a href='{$url}page=$lastpage'>{$lastlabel}</a></li>";
}
$pagination.= "</ul>";
}
return $pagination;
}
function statustorrent($intstatus) {
if( $intstatus == 1 )
return "Waiting to verify local files";
if( $intstatus == 2 )
return "Verifying local files";
if( $intstatus == 4 )
return "<font color=\"#DBA901\">Downloading</font>";
if( $intstatus == 6 )
return "<font color=\"green\">Seeding</font>";
if( $intstatus == 0 )
return "<font color=\"red\">Stopped</font>";
if( $intstatus == 5 )
return "Queued for seeding";
if( $intstatus == 3 )
return "Queued for download";
}
function colorratio($ratio) {
if( $ratio >= 1 )
$color = '#006600';
elseif( $ratio == 1 )
$color = '#33FF00';
elseif( $ratio >= 0.8 )
$color = '#FF9900';
elseif( $ratio >= 0.5 )
$color = '#FF3300';
elseif( $ratio >= 0 )
$color = '#FF0000 ';
return "<font color=\"$color\">$ratio</font>";
}
function rateupload($rate) {
if( $rate > 0 )
return "<img src=\"mos-css/img/arrow_large_up.png\" title=\"".formatBytes($rate)."/s\">";
}
?> | gpires/BroadApi | class/functions.php | PHP | mit | 5,568 |