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.Drawing;
namespace GVNET
{
/// <summary>
/// Basic node with added functionality to control the shape, color, and style of the node.
/// </summary>
public interface INodeSimple : INode
{
/// <summary>
/// Set the shape of a node.
/// </summary>
[DOTKeyword("shape")]
Shape NodeShape { get; }
/// <summary>
/// Color used to fill the background of a node assuming Style=Filled.
/// If this is not defined, the default is used, except for shape=point or when the output format is MIF, which use black by default.
/// </summary>
[DOTKeyword("color")]
Color Color { get; }
/// <summary>
/// Sets the style of the node.
/// </summary>
[DOTKeyword("style")]
NodeStyle Style { get; }
/// <summary>
/// Sets the style of the border of the node.
/// </summary>
[DOTKeyword("style")]
BorderStyle BorderStyle { get; }
}
}
| DylanMeador/gvnet | Source/GVNET/Interfaces/Node Interfaces/INodeSimple.cs | C# | mit | 879 |
package com.lesgrosspoof.bemydiary.network;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Intent;
import com.lesgrosspoof.bemydiary.AbstractActivity;
import com.lesgrosspoof.bemydiary.R;
import com.lesgrosspoof.bemydiary.entities.ItemSelection;
import com.lesgrosspoof.bemydiary.entities.Media;
import com.lesgrosspoof.bemydiary.entities.MediaToUpload;
import com.lesgrosspoof.bemydiary.models.Boards;
import com.lesgrosspoof.bemydiary.models.Medias;
import com.lesgrosspoof.bemydiary.models.Selections;
public class MediaUploader implements AsyncResultListener
{
private static MediaUploader _instance;
private ArrayList<MediaToUpload> queue;
private boolean isUploading;
private AbstractActivity activity;
public static MediaUploader getInstance() {
if (_instance == null)
_instance = new MediaUploader();
return _instance;
}
public void setCallbackActivity(AbstractActivity activity)
{
this.activity = activity;
}
private MediaUploader()
{
queue = new ArrayList<MediaToUpload>();
}
public void addToQueue(MediaToUpload m)
{
queue.add(m);
if(!isUploading)
{
System.out.println("connection is not busy, let's upload !");
notifyLoading();
uploadNext();
}
else
{
System.out.println("oops, must wait until previous upload finishes...");
}
System.out.println("queue : "+queue.toString());
}
private void uploadNext()
{
if(queue.size() > 0)
{
System.out.println("beginning upload...");
isUploading = true;
MediaToUpload media = queue.get(0);
AsyncRequest request = new AsyncRequest(this, AsyncRequest.UPLOAD_MEDIA, "http://dev.bemydiary.fr/media.json", "POST", AuthManager.getInstance().getCookie());
HashMap<String, String> params = new HashMap<String, String>();
String id_selection_site = null;
List<ItemSelection> selections = Selections.getInstance().get(Boards.getInstance().getCurrentBoardId());
for(ItemSelection item : selections)
{
if(item.getId() == Integer.parseInt(media.getId_lieu()))
{
id_selection_site = item.getId_site();
break;
}
}
params.put("medium[selection_id]", id_selection_site);
params.put("authenticity_token", AuthManager.getInstance().getCsrf_token());
System.out.println("csrf : "+AuthManager.getInstance().getCsrf_token());
params.put("medium[upload]", media.getMedia().getContent());
request.execute(params);
}
else
{
System.out.println("Queue is empty, my job here is done !");
this.deleteNotification();
}
}
private void uploadFinished()
{
System.out.println("upload finished.");
isUploading = false;
queue.remove(0);
uploadNext();
}
public void callback(String result, int type)
{
JSONObject json = null;
try
{
json = new JSONObject(result);
}
catch (JSONException e)
{
e.printStackTrace();
}
if(type == AsyncRequest.UPLOAD_MEDIA)
{
if(json != null)
{
System.out.println("Response : "+json.toString());
Media lastMedia = queue.get(0).getMedia();
try
{
lastMedia.setId_site(json.getString("_id"));
}
catch (JSONException e)
{
e.printStackTrace();
}
Medias.getInstance().update(lastMedia);
}
uploadFinished();
}
}
private final void notifyLoading()
{
Notification notification = new Notification(R.drawable.wheelanim, null, System.currentTimeMillis());
PendingIntent pendingIntent = PendingIntent.getActivity(activity, 0,
new Intent(), 0);
notification.flags |= Notification.FLAG_NO_CLEAR;
notification.setLatestEventInfo(activity, "Publication du carnet",
"Mise à jour des médias...", pendingIntent);
((NotificationManager) activity.getSystemService(activity.NOTIFICATION_SERVICE)).notify(
1338, notification);
}
private final void deleteNotification()
{
((NotificationManager) activity.getSystemService(activity.NOTIFICATION_SERVICE)).cancel(1338);
}
public boolean isUploading() {
return isUploading;
}
}
| Pamplemousse/bemydiary | src/com/lesgrosspoof/bemydiary/network/MediaUploader.java | Java | mit | 4,261 |
//! \file ImageRCT.cs
//! \date Fri Aug 01 11:36:31 2014
//! \brief RCT image format implementation.
//
// Copyright (C) 2014-2017 by morkt
//
// 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.
//
using System;
using System.IO;
using System.Linq;
using System.Text;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Diagnostics;
using System.Windows;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using GameRes.Formats.Strings;
using GameRes.Utility;
namespace GameRes.Formats.Majiro
{
internal class RctMetaData : ImageMetaData
{
public int Version;
public bool IsEncrypted;
public uint DataOffset;
public int DataSize;
public int BaseNameLength;
public int BaseRecursionDepth;
}
internal class RctOptions : ResourceOptions
{
public string Password;
}
[Serializable]
public class RctScheme : ResourceScheme
{
public Dictionary<string, string> KnownKeys;
}
[Export(typeof(ImageFormat))]
public sealed class RctFormat : ImageFormat
{
public override string Tag { get { return "RCT"; } }
public override string Description { get { return "Majiro game engine RGB image format"; } }
public override uint Signature { get { return 0x9a925a98; } }
public override bool CanWrite { get { return true; } }
public RctFormat ()
{
Settings = new[] { OverlayFrames, ApplyMask };
}
LocalResourceSetting OverlayFrames = new LocalResourceSetting ("RCTOverlayFrames");
LocalResourceSetting ApplyMask = new LocalResourceSetting ("RCTApplyMask");
public const int BaseRecursionLimit = 8;
public static Dictionary<string, string> KnownKeys = new Dictionary<string, string>();
public override ResourceScheme Scheme
{
get { return new RctScheme { KnownKeys = KnownKeys }; }
set { KnownKeys = ((RctScheme)value).KnownKeys; }
}
public override ImageMetaData ReadMetaData (IBinaryStream stream)
{
var header = stream.ReadHeader (0x14);
if (header[4] != 'T')
return null;
int encryption = header[5];
if (encryption != 'C' && encryption != 'S')
return null;
bool is_encrypted = 'S' == encryption;
if (header[6] != '0')
return null;
int version = header[7] - '0';
if (version != 0 && version != 1)
return null;
uint width = header.ToUInt32 (8);
uint height = header.ToUInt32 (12);
int data_size = header.ToInt32 (16);
int additional_size = 0;
if (1 == version)
{
additional_size = stream.ReadUInt16();
}
if (width > 0x8000 || height > 0x8000)
return null;
return new RctMetaData
{
Width = width,
Height = height,
OffsetX = 0,
OffsetY = 0,
BPP = 24,
Version = version,
IsEncrypted = is_encrypted,
DataOffset = (uint)stream.Position,
DataSize = data_size,
BaseNameLength = additional_size,
};
}
byte[] Key = null;
public override ImageData Read (IBinaryStream file, ImageMetaData info)
{
var meta = (RctMetaData)info;
var pixels = ReadPixelsData (file, meta);
if (ApplyMask.Get<bool>())
{
var mask_name = Path.GetFileNameWithoutExtension (meta.FileName) + "_.rc8";
mask_name = VFS.ChangeFileName (meta.FileName, mask_name);
if (VFS.FileExists (mask_name))
{
try
{
return ApplyMaskToImage (meta, pixels, mask_name);
}
catch { /* ignore mask read errors */ }
}
}
return ImageData.Create (meta, PixelFormats.Bgr24, null, pixels, (int)meta.Width*3);
}
static readonly ResourceInstance<ImageFormat> s_rc8_format = new ResourceInstance<ImageFormat> ("RC8");
ImageData ApplyMaskToImage (RctMetaData info, byte[] image, string mask_name)
{
using (var mask_file = VFS.OpenBinaryStream (mask_name))
{
var mask_info = s_rc8_format.Value.ReadMetaData (mask_file);
if (null == mask_info
|| info.Width != mask_info.Width || info.Height != mask_info.Height)
throw new InvalidFormatException();
using (var reader = new Rc8Format.Reader (mask_file, mask_info))
{
reader.Unpack();
var palette = reader.Palette;
int dst_stride = (int)info.Width * 4;
var pixels = new byte[dst_stride * (int)info.Height];
var alpha = reader.Data;
int a_src = 0;
int src = 0;
for (int dst = 0; dst < pixels.Length; dst += 4)
{
pixels[dst ] = image[src++];
pixels[dst+1] = image[src++];
pixels[dst+2] = image[src++];
var color = palette[alpha[a_src++]];
pixels[dst+3] = (byte)~((color.B + color.G + color.R) / 3);
}
return ImageData.Create (info, PixelFormats.Bgra32, null, pixels, dst_stride);
}
}
}
byte[] CombineImage (byte[] base_image, byte[] overlay)
{
for (int i = 2; i < base_image.Length; i += 3)
{
if (0 == overlay[i-2] && 0 == overlay[i-1] && 0xff == overlay[i])
{
overlay[i-2] = base_image[i-2];
overlay[i-1] = base_image[i-1];
overlay[i] = base_image[i];
}
}
return overlay;
}
byte[] ReadPixelsData (IBinaryStream file, RctMetaData meta)
{
byte[] base_image = null;
if (meta.FileName != null && meta.BaseNameLength > 0 && OverlayFrames.Get<bool>()
&& meta.BaseRecursionDepth < BaseRecursionLimit)
base_image = ReadBaseImage (file, meta);
file.Position = meta.DataOffset + meta.BaseNameLength;
if (meta.IsEncrypted)
file = OpenEncryptedStream (file, meta.DataSize);
try
{
using (var reader = new Reader (file, meta))
{
reader.Unpack();
if (base_image != null)
return CombineImage (base_image, reader.Data);
return reader.Data;
}
}
catch
{
if (meta.IsEncrypted)
Key = null; // probably incorrect encryption scheme caused exception, reset key
throw;
}
}
byte[] ReadBaseImage (IBinaryStream file, RctMetaData meta)
{
try
{
file.Position = meta.DataOffset;
var name = file.ReadCString (meta.BaseNameLength);
string dir_name = VFS.GetDirectoryName (meta.FileName);
name = VFS.CombinePath (dir_name, name);
if (VFS.FileExists (name))
{
using (var base_file = VFS.OpenBinaryStream (name))
{
var base_info = ReadMetaData (base_file) as RctMetaData;
if (null != base_info
&& meta.Width == base_info.Width && meta.Height == base_info.Height)
{
base_info.BaseRecursionDepth = meta.BaseRecursionDepth + 1;
base_info.FileName = name;
return ReadPixelsData (base_file, base_info);
}
}
}
}
catch { /* ignore baseline image read errors */ }
return null;
}
IBinaryStream OpenEncryptedStream (IBinaryStream file, int data_size)
{
if (null == Key)
{
var password = QueryPassword();
if (string.IsNullOrEmpty (password))
throw new UnknownEncryptionScheme();
Key = InitDecryptionKey (password);
}
byte[] data = file.ReadBytes (data_size);
if (data.Length != data_size)
throw new EndOfStreamException();
for (int i = 0; i < data.Length; ++i)
{
data[i] ^= Key[i & 0x3FF];
}
return new BinMemoryStream (data, file.Name);
}
private byte[] InitDecryptionKey (string password)
{
byte[] bin_pass = Encodings.cp932.GetBytes (password);
uint crc32 = Crc32.Compute (bin_pass, 0, bin_pass.Length);
byte[] key_table = new byte[0x400];
unsafe
{
fixed (byte* key_ptr = key_table)
{
uint* key32 = (uint*)key_ptr;
for (int i = 0; i < 0x100; ++i)
*key32++ = crc32 ^ Crc32.Table[(i + crc32) & 0xFF];
}
}
return key_table;
}
private string QueryPassword ()
{
if (VFS.IsVirtual)
{
var password = FindImageKey();
if (!string.IsNullOrEmpty (password))
return password;
}
var options = Query<RctOptions> (arcStrings.ArcImageEncrypted);
return options.Password;
}
static readonly ResourceInstance<ArchiveFormat> s_Majiro = new ResourceInstance<ArchiveFormat> ("MAJIRO");
private string FindImageKey ()
{
var arc_fs = VFS.Top as ArchiveFileSystem;
if (null == arc_fs)
return null;
try
{
// look for "start.mjo" within "scenario.arc" archive
var src_name = arc_fs.Source.File.Name;
var scenario_arc_name = Path.Combine (Path.GetDirectoryName (src_name), "scenario.arc");
if (!File.Exists (scenario_arc_name))
return null;
byte[] script;
using (var file = new ArcView (scenario_arc_name))
using (var arc = s_Majiro.Value.TryOpen (file))
{
if (null == arc)
return null;
var start_mjo = arc.Dir.First (e => e.Name == "start.mjo");
using (var mjo = arc.OpenEntry (start_mjo))
{
script = new byte[mjo.Length];
mjo.Read (script, 0, script.Length);
}
}
if (Binary.AsciiEqual (script, "MajiroObjX1.000"))
DecryptMjo (script);
else if (!Binary.AsciiEqual (script, "MjPlainBytecode"))
return null;
// locate key within start.mjo script
int n = script.ToInt32 (0x18);
for (int offset = 0x20 + n * 8; offset < script.Length - 4; ++offset)
{
offset = Array.IndexOf<byte> (script, 1, offset);
if (-1 == offset)
break;
if (8 != script[offset+1])
continue;
int str_length = script.ToUInt16 (offset+2);
if (0 == str_length || str_length + 12 > script.Length - offset
|| 0x0835 != script.ToUInt16 (offset+str_length+4)
|| 0x7A7B6ED4 != script.ToUInt32 (offset+str_length+6))
continue;
offset += 4;
int end = Array.IndexOf<byte> (script, 0, offset, str_length);
if (-1 != end)
str_length = end - offset;
var password = Encodings.cp932.GetString (script, offset, str_length);
Trace.WriteLine (string.Format ("Found key in start.mjo [{0}]", password), "[RCT]");
return password;
}
}
catch { /* ignore errors */ }
return null;
}
private void DecryptMjo (byte[] data)
{
int offset = 0x1C + 8 * data.ToInt32 (0x18);
if (offset < 0x1C || offset >= data.Length - 4)
return;
int count = data.ToInt32 (offset);
offset += 4;
if (count <= 0 || count > data.Length - offset)
return;
Debug.Assert (Crc32.Table.Length == 0x100);
unsafe
{
fixed (uint* table = Crc32.Table)
{
byte* key = (byte*)table;
for (int i = 0; i < count; ++i)
data[offset+i] ^= key[i & 0x3FF];
}
}
}
public override ResourceOptions GetDefaultOptions ()
{
return new RctOptions { Password = Properties.Settings.Default.RCTPassword };
}
public override ResourceOptions GetOptions (object widget)
{
var w = widget as GUI.WidgetRCT;
if (null != w)
Properties.Settings.Default.RCTPassword = w.Password.Text;
return GetDefaultOptions();
}
public override object GetAccessWidget ()
{
return new GUI.WidgetRCT();
}
public override void Write (Stream file, ImageData image)
{
using (var writer = new Writer (file))
writer.Pack (image.Bitmap);
}
internal class Writer : IDisposable
{
BinaryWriter m_out;
uint[] m_input;
int m_width;
int m_height;
int[] m_shift_table = new int[32];
const int MaxThunkSize = 0xffff + 0x7f;
const int MaxMatchSize = 0xffff;
struct ChunkPosition
{
public ushort Offset;
public ushort Length;
}
public Writer (Stream output)
{
m_out = new BinaryWriter (output, Encoding.ASCII, true);
}
void PrepareInput (BitmapSource bitmap)
{
m_width = bitmap.PixelWidth;
m_height = bitmap.PixelHeight;
int pixels = m_width*m_height;
m_input = new uint[pixels];
if (bitmap.Format != PixelFormats.Bgr32)
{
var converted_bitmap = new FormatConvertedBitmap();
converted_bitmap.BeginInit();
converted_bitmap.Source = bitmap;
converted_bitmap.DestinationFormat = PixelFormats.Bgr32;
converted_bitmap.EndInit();
bitmap = converted_bitmap;
}
unsafe
{
fixed (uint* buffer = m_input)
{
bitmap.CopyPixels (Int32Rect.Empty, (IntPtr)buffer, pixels*4, m_width*4);
}
}
InitShiftTable (m_width);
}
void InitShiftTable (int width)
{
for (int i = 0; i < 32; ++i)
{
int shift = Reader.ShiftTable[i];
int shift_row = shift & 0x0f;
shift >>= 4;
shift_row *= width;
shift -= shift_row;
m_shift_table[i] = shift;
}
}
List<byte> m_buffer = new List<byte>();
int m_buffer_size;
public void Pack (BitmapSource bitmap)
{
PrepareInput (bitmap);
long data_offset = 0x14;
m_out.BaseStream.Position = data_offset;
uint pixel = m_input[0];
m_out.Write ((byte)pixel);
m_out.Write ((byte)(pixel >> 8));
m_out.Write ((byte)(pixel >> 16));
m_buffer.Clear();
m_buffer_size = 0;
int last = m_input.Length;
int current = 1;
while (current != last)
{
var chunk_pos = FindLongest (current, last);
if (chunk_pos.Length > 0)
{
Flush();
WritePos (chunk_pos);
current += chunk_pos.Length;
}
else
{
WritePixel (m_input[current++]);
}
}
Flush();
var data_size = m_out.BaseStream.Position - data_offset;
m_out.BaseStream.Position = 0;
WriteHeader ((uint)data_size);
}
void WriteHeader (uint data_size)
{
m_out.Write (0x9a925a98u);
m_out.Write (0x30304354u);
m_out.Write (m_width);
m_out.Write (m_height);
m_out.Write (data_size);
}
void WritePixel (uint pixel)
{
if (MaxThunkSize == m_buffer_size)
Flush();
m_buffer.Add ((byte)pixel);
m_buffer.Add ((byte)(pixel >> 8));
m_buffer.Add ((byte)(pixel >> 16));
++m_buffer_size;
}
void Flush ()
{
if (0 != m_buffer.Count)
{
if (m_buffer_size > 0x7f)
{
m_out.Write ((byte)0x7f);
m_out.Write ((ushort)(m_buffer_size-0x80));
}
else
m_out.Write ((byte)(m_buffer_size-1));
foreach (var b in m_buffer)
m_out.Write (b);
m_buffer.Clear();
m_buffer_size = 0;
}
}
ChunkPosition FindLongest (int buf_begin, int buf_end)
{
buf_end = Math.Min (buf_begin + MaxMatchSize, buf_end);
ChunkPosition pos = new ChunkPosition { Offset = 0, Length = 0 };
for (int i = 0; i < 32; ++i)
{
int offset = buf_begin + m_shift_table[i];
if (offset < 0)
continue;
if (m_input[offset] != m_input[buf_begin])
continue;
var last = Mismatch (buf_begin+1, buf_end, offset+1);
int weight = last - offset;
if (weight > pos.Length)
{
pos.Offset = (ushort)i;
pos.Length = (ushort)weight;
}
}
return pos;
}
int Mismatch (int first1, int last1, int first2)
{
while (first1 != last1 && m_input[first1] == m_input[first2])
{
++first1;
++first2;
}
return first2;
}
void WritePos (ChunkPosition pos)
{
int code = (pos.Offset << 2) | 0x80;
if (pos.Length > 3)
code |= 3;
else
code |= pos.Length - 1;
m_out.Write ((byte)code);
if (pos.Length > 3)
m_out.Write ((ushort)(pos.Length - 4));
}
#region IDisposable Members
bool disposed = false;
public void Dispose ()
{
Dispose (true);
GC.SuppressFinalize (this);
}
protected virtual void Dispose (bool disposing)
{
if (!disposed)
{
if (disposing)
{
m_out.Dispose();
}
disposed = true;
}
}
#endregion
}
internal sealed class Reader : IDisposable
{
private IBinaryStream m_input;
private uint m_width;
private byte[] m_data;
public byte[] Data { get { return m_data; } }
public Reader (IBinaryStream file, RctMetaData info)
{
m_width = info.Width;
m_data = new byte[m_width * info.Height * 3];
m_input = file;
}
internal static readonly sbyte[] ShiftTable = new sbyte[] {
-16, -32, -48, -64, -80, -96,
49, 33, 17, 1, -15, -31, -47,
50, 34, 18, 2, -14, -30, -46,
51, 35, 19, 3, -13, -29, -45,
36, 20, 4, -12, -28,
};
public void Unpack ()
{
int pixels_remaining = m_data.Length;
int data_pos = 0;
int eax = 0;
while (pixels_remaining > 0)
{
int count = eax*3 + 3;
if (count > pixels_remaining)
throw new InvalidFormatException();
pixels_remaining -= count;
if (count != m_input.Read (m_data, data_pos, count))
throw new InvalidFormatException();
data_pos += count;
while (pixels_remaining > 0)
{
eax = m_input.ReadByte();
if (0 == (eax & 0x80))
{
if (0x7f == eax)
eax += m_input.ReadUInt16();
break;
}
int shift_index = eax >> 2;
eax &= 3;
if (3 == eax)
eax += m_input.ReadUInt16();
count = eax*3 + 3;
if (pixels_remaining < count)
throw new InvalidFormatException();
pixels_remaining -= count;
int shift = ShiftTable[shift_index & 0x1f];
int shift_row = shift & 0x0f;
shift >>= 4;
shift_row *= (int)m_width;
shift -= shift_row;
shift *= 3;
if (shift >= 0 || data_pos+shift < 0)
throw new InvalidFormatException();
Binary.CopyOverlapped (m_data, data_pos+shift, data_pos, count);
data_pos += count;
}
}
}
#region IDisposable Members
public void Dispose ()
{
GC.SuppressFinalize (this);
}
#endregion
}
}
}
| morkt/GARbro | ArcFormats/Majiro/ImageRCT.cs | C# | mit | 25,065 |
'use strict';
describe('Controllers Tests ', function () {
beforeEach(module('solrpressApp'));
describe('SessionsController', function () {
var $scope, SessionsService;
beforeEach(inject(function ($rootScope, $controller, Sessions) {
$scope = $rootScope.$new();
SessionsService = Sessions;
$controller('SessionsController',{$scope:$scope, Sessions:SessionsService});
}));
it('should invalidate session', function () {
//GIVEN
$scope.series = "123456789";
//SET SPY
spyOn(SessionsService, 'delete');
//WHEN
$scope.invalidate($scope.series);
//THEN
expect(SessionsService.delete).toHaveBeenCalled();
expect(SessionsService.delete).toHaveBeenCalledWith({series: "123456789"}, jasmine.any(Function), jasmine.any(Function));
//SIMULATE SUCCESS CALLBACK CALL FROM SERVICE
SessionsService.delete.calls.mostRecent().args[1]();
expect($scope.error).toBeNull();
expect($scope.success).toBe('OK');
});
});
});
| dynamicguy/solrpress | src/test/javascript/spec/app/account/sessions/sessionsControllerSpec.js | JavaScript | mit | 1,153 |
Template.registerHelper("itemTypes", function() {
return [
{label: i18n.t('choose'), value: ''},
{label: i18n.t('offer'), value: 'offer', icon: 'icon gift'},
{label: i18n.t('need'), value: 'need', icon: 'icon fire'},
{label: i18n.t('wish'), value: 'wish', icon: 'icon wizard'},
{label: i18n.t('idea'), value: 'idea', icon: 'icon cloud'}
]
})
| heaven7/wsl-items | lib/client/helpers.js | JavaScript | mit | 391 |
# (c) Roman Neuhauser
# MIT-Licensed
class HashStruct
def initialize hash = {}
@impl = Hash[hash]
end
def [] key
@impl[key]
end
def []= key, val
@impl[key] = val
end
def merge! other
other.each_pair do |key, val|
self[key] = val
end
end
def merge other
rv = self.clone
rv.merge! other
rv
end
def method_missing sym, *args, &block
key = sym
realsym = :[]
if key[-1] == '='
key = key[0..-2].to_sym
realsym = :[]=
end
unless @impl.has_key? key
raise NoMethodError.new "undefined method `%s' for %s" % [
sym.to_s,
self
]
end
@impl.send realsym, *([key] + args), &block
end
def each
@impl.each_key { |key| yield key, self[key] }
end
def each_pair
@impl.each_key { |key| yield key, self[key] }
end
def each_key
@impl.each_key { |key| yield key }
end
def each_value
@impl.each_key { |key| yield self[key] }
end
private
def initialize_copy src
super src
@impl = Hash[ xx: 1, yy: 2 ]
end
end
| roman-neuhauser/hashstruct | lib/hashstruct.rb | Ruby | mit | 1,071 |
using Stranne.BooliLib.Models;
using Xunit.Abstractions;
namespace Stranne.BooliLib.Tests.Models
{
public class DimensionSerializable : Dimension, IXunitSerializable
{
public DimensionSerializable()
{
}
public DimensionSerializable(int height, int width)
: base(height, width)
{
}
public void Deserialize(IXunitSerializationInfo info)
{
Height = info.GetValue<int>(nameof(Height));
Width = info.GetValue<int>(nameof(Width));
}
public void Serialize(IXunitSerializationInfo info)
{
info.AddValue(nameof(Height), Height);
info.AddValue(nameof(Width), Width);
}
}
}
| stranne/BooliLib | Stranne.BooliLib.Tests/Models/DimensionSerializable.cs | C# | mit | 738 |
// --------------------------------------------------------------------------------------------------------------------
//
// cloudfront-config.js - config for AWS CloudFront
//
// Copyright (c) 2011 AppsAttic Ltd - http://www.appsattic.com/
// Written by Andrew Chilton <chilts@appsattic.com>
//
// License: http://opensource.org/licenses/MIT
//
// --------------------------------------------------------------------------------------------------------------------
var data2xml = require('data2xml')({ attrProp : '@', valProp : '#', });
// --------------------------------------------------------------------------------------------------------------------
function pathDistribution(options, args) {
return '/' + this.version() + '/distribution';
}
function pathDistributionId(options, args) {
return '/' + this.version() + '/distribution/' + args.DistributionId;
}
function pathDistributionIdConfig(options, args) {
return '/' + this.version() + '/distribution/' + args.DistributionId + '/config';
}
function pathDistributionInvalidation(options, args) {
return '/' + this.version() + '/distribution/' + args.DistributionId + '/invalidation';
}
function pathDistributionInvalidationId(options, args) {
return '/' + this.version() + '/distribution/' + args.DistributionId + '/invalidation/' + args.InvalidationId;
}
function pathStreamingDistribution(options, args) {
return '/' + this.version() + '/streaming-distribution';
}
function pathStreamingDistributionId(options, args) {
return '/' + this.version() + '/streaming-distribution/' + args.DistributionId;
}
function pathStreamingDistributionIdConfig(options, args) {
return '/' + this.version() + '/streaming-distribution/' + args.DistributionId + '/config';
}
function pathOai(options, args) {
return '/' + this.version() + '/origin-access-identity/cloudfront';
}
function pathOaiId(options, args) {
return '/' + this.version() + '/origin-access-identity/cloudfront/' + args.OriginAccessId;
}
function pathOaiIdConfig(options, args) {
return '/' + this.version() + '/origin-access-identity/cloudfront/' + args.OriginAccessId + '/config';
}
function bodyDistributionConfig(options, args) {
// create the XML
var data = {
'@' : { 'xmlns' : 'http://cloudfront.amazonaws.com/doc/2010-11-01/' },
};
if ( args.S3OriginDnsName ) {
data.S3Origin = {};
data.S3Origin.DNSName = args.S3OriginDnsName;
if ( args.S3OriginOriginAccessIdentity ) {
data.S3Origin.OriginAccessIdentity = args.S3OriginOriginAccessIdentity;
}
}
if ( args.CustomOriginDnsName || args.CustomOriginOriginProtocolPolicy ) {
data.CustomOrigin = {};
if ( args.CustomOriginDnsName ) {
data.CustomOrigin.DNSName = args.CustomOriginDnsName;
}
if ( args.CustomOriginHttpPort ) {
data.CustomOrigin.HTTPPort = args.CustomOriginHttpPort;
}
if ( args.CustomOriginHttpsPort ) {
data.CustomOrigin.HTTPSPort = args.CustomOriginHttpsPort;
}
if ( args.CustomOriginOriginProtocolPolicy ) {
data.CustomOrigin.OriginProtocolPolicy = args.CustomOriginOriginProtocolPolicy;
}
}
data.CallerReference = args.CallerReference;
if ( args.Cname ) {
data.CNAME = args.Cname;
}
if ( args.Comment ) {
data.Comment = args.Comment;
}
if ( args.DefaultRootObject ) {
data.DefaultRootObject = args.DefaultRootObject;
}
data.Enabled = args.Enabled;
if ( args.PriceClass ) {
data.PriceClass = args.PriceClass;
}
if ( args.LoggingBucket ) {
data.Logging = {};
data.Logging.Bucket = args.LoggingBucket;
if ( args.LoggingPrefix ) {
data.Logging.Prefix = args.LoggingPrefix;
}
}
if ( args.TrustedSignersSelf || args.TrustedSignersAwsAccountNumber ) {
data.TrustedSigners = {};
if ( args.TrustedSignersSelf ) {
data.TrustedSigners.Self = '';
}
if ( args.TrustedSignersAwsAccountNumber ) {
data.TrustedSigners.AwsAccountNumber = args.TrustedSignersAwsAccountNumber;
}
}
if ( args.RequiredProtocolsProtocol ) {
data.RequiredProtocols = {};
data.RequiredProtocols.Protocol = args.RequiredProtocolsProtocol;
}
return data2xml('DistributionConfig', data);
}
function bodyStreamingDistributionConfig(options, args) {
// create the XML
var data = {
'@' : { 'xmlns' : 'http://cloudfront.amazonaws.com/doc/2010-11-01/' },
};
if ( args.S3OriginDnsName ) {
data.S3Origin = {};
data.S3Origin.DNSName = args.S3OriginDnsName;
if ( args.S3OriginOriginAccessIdentity ) {
data.S3Origin.OriginAccessIdentity = args.S3OriginOriginAccessIdentity;
}
}
data.CallerReference = args.CallerReference;
if ( args.Cname ) {
data.CNAME = args.Cname;
}
if ( args.Comment ) {
data.Comment = args.Comment;
}
data.Enabled = args.Enabled;
if ( args.PriceClass ) {
data.PriceClass = args.PriceClass;
}
if ( args.LoggingBucket ) {
data.Logging = {};
data.Logging.Bucket = args.LoggingBucket;
if ( args.LoggingPrefix ) {
data.Logging.Prefix = args.LoggingPrefix;
}
}
if ( args.TrustedSignersSelf || args.TrustedSignersAwsAccountNumber ) {
data.TrustedSigners = {};
if ( args.TrustedSignersSelf ) {
data.TrustedSigners.Self = '';
}
if ( args.TrustedSignersAwsAccountNumber ) {
data.TrustedSigners.AwsAccountNumber = args.TrustedSignersAwsAccountNumber;
}
}
return data2xml('StreamingDistributionConfig', data);
}
function bodyOaiConfig(options, args) {
var self = this;
var data = {
'@' : { xmlns : 'http://cloudfront.amazonaws.com/doc/2010-11-01/', },
CallerReference : args.CallerReference,
};
if ( args.Comments ) {
data.Comments = args.Comments;
}
return data2xml('CloudFrontOriginAccessIdentityConfig', data);
}
// --------------------------------------------------------------------------------------------------------------------
module.exports = {
// Operations on Distributions
CreateDistribution : {
url : 'http://docs.amazonwebservices.com/AmazonCloudFront/latest/APIReference/CreateDistribution.html',
method : 'POST',
path : pathDistribution,
args : {
// S3Origin Elements
DnsName : {
type : 'special',
required : false,
},
OriginAccessIdentity : {
type : 'special',
required : false,
},
// CustomOrigin elements
CustomOriginDnsName : {
type : 'special',
required : false,
},
CustomOriginHttpPort : {
type : 'special',
required : false,
},
CustomOriginHttpsPort : {
type : 'special',
required : false,
},
CustomOriginOriginProtocolPolicy : {
type : 'special',
required : false,
},
// other top level elements
CallerReference : {
type : 'special',
required : true,
},
Cname : {
type : 'special',
required : false,
},
Comment : {
type : 'special',
required : false,
},
Enabled : {
type : 'special',
required : true,
},
DefaultRootObject : {
type : 'special',
required : true,
},
// Logging Elements
LoggingBucket : {
type : 'special',
required : false,
},
LoggingPrefix : {
type : 'special',
required : false,
},
// TrustedSigners Elements
TrustedSignersSelf : {
type : 'special',
required : false,
},
TrustedSignersAwsAccountNumber : {
type : 'special',
required : false,
},
RequiredProtocols : {
type : 'special',
required : false,
},
},
body : bodyDistributionConfig,
statusCode: 201,
},
ListDistributions : {
url : 'http://docs.amazonwebservices.com/AmazonCloudFront/latest/APIReference/ListDistributions.html',
path : pathDistribution,
args : {
Marker : {
required : false,
type : 'param',
},
MaxItems : {
required : false,
type : 'param',
},
},
},
GetDistribution : {
url : 'http://docs.amazonwebservices.com/AmazonCloudFront/latest/APIReference/GetDistribution.html',
path : pathDistributionId,
args : {
DistributionId : {
required : true,
type : 'special',
},
},
},
GetDistributionConfig : {
url : 'http://docs.amazonwebservices.com/AmazonCloudFront/latest/APIReference/GetConfig.html',
path : pathDistributionIdConfig,
args : {
DistributionId : {
required : true,
type : 'special',
},
},
},
PutDistributionConfig : {
url : 'http://docs.amazonwebservices.com/AmazonCloudFront/latest/APIReference/PutConfig.html',
method : 'PUT',
path : pathDistributionIdConfig,
args : {
DistributionId : {
required : true,
type : 'special',
},
IfMatch : {
name : 'If-Match',
required : true,
type : 'header'
},
// S3Origin Elements
DnsName : {
type : 'special',
required : false,
},
OriginAccessIdentity : {
type : 'special',
required : false,
},
// CustomOrigin elements
CustomOriginDnsName : {
type : 'special',
required : false,
},
CustomOriginHttpPort : {
type : 'special',
required : false,
},
CustomOriginHttpsPort : {
type : 'special',
required : false,
},
CustomOriginOriginProtocolPolicy : {
type : 'special',
required : false,
},
// other top level elements
CallerReference : {
type : 'special',
required : true,
},
Cname : {
type : 'special',
required : false,
},
Comment : {
type : 'special',
required : false,
},
Enabled : {
type : 'special',
required : true,
},
PriceClass : {
type : 'special',
required : false,
},
DefaultRootObject : {
type : 'special',
required : true,
},
// Logging Elements
LoggingBucket : {
type : 'special',
required : false,
},
LoggingPrefix : {
type : 'special',
required : false,
},
// TrustedSigners Elements
TrustedSignersSelf : {
type : 'special',
required : false,
},
TrustedSignersAwsAccountNumber : {
type : 'special',
required : false,
},
RequiredProtocols : {
type : 'special',
required : false,
},
},
body : bodyDistributionConfig,
},
DeleteDistribution : {
url : 'http://docs.amazonwebservices.com/AmazonCloudFront/latest/APIReference/DeleteDistribution.html',
method : 'DELETE',
path : pathDistributionId,
args : {
DistributionId : {
required : true,
type : 'special',
},
IfMatch : {
name : 'If-Match',
required : true,
type : 'header'
},
},
statusCode : 204,
},
// Operations on Streaming Distributions
CreateStreamingDistribution : {
url : 'http://docs.amazonwebservices.com/AmazonCloudFront/latest/APIReference/CreateStreamingDistribution.html',
method : 'POST',
path : pathStreamingDistribution,
args : {
// S3Origin Elements
S3OriginDnsName : {
type : 'special',
required : false,
},
S3OriginOriginAccessIdentity : {
type : 'special',
required : false,
},
// other top level elements
CallerReference : {
type : 'special',
required : true,
},
Cname : {
type : 'special',
required : false,
},
Comment : {
type : 'special',
required : false,
},
Enabled : {
type : 'special',
required : true,
},
PriceClass : {
type : 'special',
required : false,
},
// Logging Elements
LoggingBucket : {
type : 'special',
required : false,
},
LoggingPrefix : {
type : 'special',
required : false,
},
// TrustedSigners Elements
TrustedSignersSelf : {
type : 'special',
required : false,
},
TrustedSignersAwsAccountNumber : {
type : 'special',
required : false,
},
},
body : bodyStreamingDistributionConfig,
},
ListStreamingDistributions : {
url : 'http://docs.amazonwebservices.com/AmazonCloudFront/latest/APIReference/ListStreamingDistributions.html',
path : pathStreamingDistribution,
args : {
Marker : {
required : false,
type : 'param',
},
MaxItems : {
required : false,
type : 'param',
},
},
},
GetStreamingDistribution : {
url : 'http://docs.amazonwebservices.com/AmazonCloudFront/latest/APIReference/GetStreamingDistribution.html',
path : pathStreamingDistributionId,
args : {
DistributionId : {
required : true,
type : 'special',
},
},
},
GetStreamingDistributionConfig : {
url : 'http://docs.amazonwebservices.com/AmazonCloudFront/latest/APIReference/GetStreamingDistConfig.html',
path : pathStreamingDistributionIdConfig,
args : {
DistributionId : {
required : true,
type : 'special',
},
},
},
PutStreamingDistributionConfig : {
url : 'http://docs.amazonwebservices.com/AmazonCloudFront/latest/APIReference/PutStreamingDistConfig.html',
method : 'PUT',
path : pathStreamingDistributionIdConfig,
args : {
DistributionId : {
required : true,
type : 'special',
},
IfMatch : {
name : 'If-Match',
required : true,
type : 'header'
},
// S3Origin Elements
DnsName : {
type : 'special',
required : false,
},
OriginAccessIdentity : {
type : 'special',
required : false,
},
// other top level elements
CallerReference : {
type : 'special',
required : true,
},
Cname : {
type : 'special',
required : false,
},
Comment : {
type : 'special',
required : false,
},
Enabled : {
type : 'special',
required : true,
},
// Logging Elements
LoggingBucket : {
type : 'special',
required : false,
},
LoggingPrefix : {
type : 'special',
required : false,
},
// TrustedSigners Elements
TrustedSignersSelf : {
type : 'special',
required : false,
},
TrustedSignersAwsAccountNumber : {
type : 'special',
required : false,
},
},
body : bodyStreamingDistributionConfig,
},
DeleteStreamingDistribution : {
url : 'http://docs.amazonwebservices.com/AmazonCloudFront/latest/APIReference/DeleteStreamingDistribution.html',
method : 'DELETE',
path : pathStreamingDistributionId,
args : {
DistributionId : {
required : true,
type : 'special',
},
IfMatch : {
name : 'If-Match',
required : true,
type : 'header'
},
},
statusCode : 204,
},
// Operations on Origin Access Identities
CreateOai : {
url : 'http://docs.amazonwebservices.com/AmazonCloudFront/latest/APIReference/CreateOAI.html',
method : 'POST',
path : pathOai,
args : {
CallerReference : {
required : true,
type : 'special',
},
Comment : {
required : false,
type : 'special',
},
},
body : bodyOaiConfig,
statusCode: 201,
},
ListOais : {
url : 'http://docs.amazonwebservices.com/AmazonCloudFront/latest/APIReference/ListOAIs.html',
path : pathOai,
args : {
Marker : {
required : false,
type : 'param',
},
MaxItems : {
required : false,
type : 'param',
},
},
},
GetOai : {
url : 'http://docs.amazonwebservices.com/AmazonCloudFront/latest/APIReference/GetOAI.html',
path : pathOaiId,
args : {
OriginAccessId : {
required : true,
type : 'special',
},
},
},
GetOaiConfig : {
url : 'http://docs.amazonwebservices.com/AmazonCloudFront/latest/APIReference/GetOAIConfig.html',
path : pathOaiIdConfig,
args : {
OriginAccessId : {
required : true,
type : 'special',
},
},
},
PutOaiConfig : {
url : 'http://docs.amazonwebservices.com/AmazonCloudFront/latest/APIReference/PutOAIConfig.html',
method : 'PUT',
path : pathOai,
args : {
OriginAccessId : {
required : true,
type : 'special',
},
CallerReference : {
required : true,
type : 'special',
},
Comment : {
required : false,
type : 'special',
},
},
body : bodyOaiConfig,
},
DeleteOai : {
url : 'http://docs.amazonwebservices.com/AmazonCloudFront/latest/APIReference/DeleteOAI.html',
method : 'DELETE',
path : pathOaiId,
args : {
OriginAccessId : {
required : true,
type : 'special',
},
IfMatch : {
name : 'If-Match',
required : true,
type : 'header'
},
},
statusCode : 204,
},
// Operations on Invalidations
CreateInvalidation : {
url : 'http://docs.amazonwebservices.com/AmazonCloudFront/latest/APIReference/CreateInvalidation.html',
method : 'POST',
path : pathDistributionInvalidation,
args : {
DistributionId : {
required : true,
type : 'special',
},
Path : {
required : true,
type : 'special',
},
CallerReference : {
required : false,
type : 'special',
},
},
body : function(options, args) {
var self = this;
var data = {
Path : args.Path,
};
if ( args.CallerReference ) {
data.CallerReference = args.CallerReference;
}
return data2xml('InvalidationBatch', data);
},
},
ListInvalidations : {
url : 'http://docs.amazonwebservices.com/AmazonCloudFront/latest/APIReference/ListInvalidation.html',
path : pathDistributionInvalidation,
args : {
DistributionId : {
required : true,
type : 'special',
},
Marker : {
required : false,
type : 'param',
},
MaxItems : {
required : false,
type : 'param',
},
},
},
GetInvalidation : {
url : 'http://docs.amazonwebservices.com/AmazonCloudFront/latest/APIReference/GetInvalidation.html',
path : pathDistributionInvalidationId,
args : {
DistributionId : {
required : true,
type : 'special',
},
Marker : {
required : false,
type : 'param',
},
MaxItems : {
required : false,
type : 'param',
},
},
},
};
// --------------------------------------------------------------------------------------------------------------------
| chilts/awssum-amazon-cloudfront | config.js | JavaScript | mit | 23,102 |
package de.vsis.groomba.communication;
public class Log {
/**
* @author Hannes
*
* Helps to create different log levels for debugging purposes.
*
*/
public final static int OFF = 0;
public final static int ERROR = 1;
public final static int INFO = 2;
public final static int VERBOSE = 3;
public final static int DEBUG = 4;
private String _classname = "";
private boolean _verbose = false;
private boolean _error = false;
private boolean _info = false;
private boolean _debug = false;
public Log() {
// TODO Auto-generated constructor stub
setVerbose();
}
public Log(int level) {
set(level);
}
public Log(String classname) {
_classname = classname;
}
public void debug(String msg){
if(_debug) {
printLogMsg("debug", msg);
}
}
public void log(String msg){
if (_verbose){
printLogMsg("verbose", msg);
}
}
public void error(String msg){
if (_error){
printLogMsg("error", msg);
}
}
public void info(String msg){
if (_info){
printLogMsg("info", msg);
}
}
/** combine and print to console slave
*
*
* @param kind
* @param msg
*/
private void printLogMsg(String kind, String msg){
String fullmsg = "";
if (!_classname.equals("")){
fullmsg = "["+kind+" from "+_classname+"] --- " + msg;
}
else {
fullmsg = "["+kind+"] --- " + msg;
}
System.out.println(fullmsg);
}
public void enableAll() {
_verbose = true;
}
public void dissableAll() {
_verbose = false;
}
public void setVerbose(){
_verbose = true;
_error = true;
_info = true;
_debug = true;
}
public void set(int level){
//0 off, 1 error, 2 info, 3 verbose, 4 Debug(all)
switch(level){
case 0: _verbose = false;
_error = false;
_info = false;
_debug = false;
break;
case 1: _error = true;
_verbose = false;
_info = false;
_debug = false;
break;
case 2: _error = true;
_info = true;
_debug = false;
_verbose = false;
break;
case 3: _verbose = true;
_error = true;
_info = true;
_debug = false;
break;
case 4: setVerbose();
default: _verbose = true;
_error = true;
_info = true;
_debug = true;
break;
}
}
}
| knutgoetz/evka01 | Groomba/src/de/vsis/groomba/communication/Log.java | Java | mit | 2,295 |
import { Component, OnInit, OnDestroy, ElementRef, ViewChild } from '@angular/core';
import { fromEvent } from 'rxjs';
import { debounceTime, distinctUntilChanged, takeWhile } from 'rxjs/operators';
import { Terminal } from 'xterm';
import * as fit from 'xterm/lib/addons/fit/fit';
import * as search from 'xterm/lib/addons/search/search';
import * as webLinks from 'xterm/lib/addons/webLinks/webLinks';
import * as fullscreen from 'xterm/lib/addons/fullscreen/fullscreen';
Terminal.applyAddon(fit);
Terminal.applyAddon(search);
Terminal.applyAddon(webLinks);
Terminal.applyAddon(fullscreen);
@Component({
selector: 'dng-terminal',
templateUrl: './terminal.component.html',
styleUrls: ['./terminal.component.scss']
})
export class TerminalComponent implements OnInit, OnDestroy {
public terminal: Terminal;
title = new Date(Date.now()).toDateString();
protected focused = false;
private destroy = false;
@ViewChild('terminal', { static: true }) term: ElementRef;
@ViewChild('menu', { static: true }) private menu: ElementRef;
constructor() { }
getTerminalMenuClass() {
return (this.focused) ? 'terminalMenuFocus' : 'terminalMenuBlur';
}
ngOnInit() {
this.terminal = new Terminal({
windowsMode: true,
cursorBlink: true,
cols: 100,
rows: 25
});
this.terminal.open(this.term.nativeElement);
this.terminal['webLinksInit']();
this.terminal['fit']();
this.terminal.focus();
this.focused = true;
fromEvent(window, 'resize').pipe(
debounceTime(50),
distinctUntilChanged(),
takeWhile(() => this.destroy === false)
).subscribe(() => this.terminal['fit']());
fromEvent(this.menu.nativeElement, 'click').pipe(
debounceTime(50),
distinctUntilChanged(),
takeWhile(() => this.destroy === false)
).subscribe(() => this.terminal.focus());
this.terminal.on('blur', () => {
this.focused = false;
});
this.terminal.on('focus', () => {
this.focused = true;
});
this.terminal.on('key', (key, e) => {
const printable = (!e.altKey && !e.ctrlKey && !e.metaKey);
/* tslint:disable:deprecation */
if (e.keyCode === 13) {
this.terminal.writeln('');
} else if (e.keyCode === 8) {
this.terminal.write('\b \b');
} else if (e.keyCode === 9) {
this.terminal.write('\t');
} else if (printable) {
this.terminal.write(e.key);
}
/* tslint:enable:deprecation */
});
}
ngOnDestroy() {
this.destroy = true;
this.terminal.dispose();
}
}
| jojanper/angular-app | src/app/pages/apps/pages/terminal/terminal.component.ts | TypeScript | mit | 2,842 |
package com.cngu.androidfun.main;
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import com.cngu.androidfun.R;
import com.cngu.androidfun.data.ActionTopic;
import com.cngu.androidfun.data.MenuTopic;
import com.cngu.androidfun.data.Topic;
import com.cngu.androidfun.view.TopicView;
import java.util.ArrayList;
/**
* A TopicManager serves two purposes:
* <ol>
* <li>contain an in-memory (i.e. not-persisted) database of {@link Topic}s.
* <li>manage a history of selected {@link Topic}s.
* </ol>
*
* <p>Due to the static nature of the Topic menu navigation UI, persistence of these Topics is not
* required and can easily be created on demand.
*/
public class TopicManager implements ITopicManager {
private static final String TAG = TopicManager.class.getSimpleName();
private static final String KEY_HISTORY_STACK = "cngu.key.HISTORY_STACK";
public ArrayList<Topic> mTopics;
public ArrayList<Topic> mHistory;
private boolean mActionTopicReached;
public TopicManager(Context context) {
LayoutInflater inflater = LayoutInflater.from(context);
TopicView rootTopicView = (TopicView) inflater.inflate(R.layout.ui_topic_hierarchy, null);
mTopics = new ArrayList<>();
mHistory = new ArrayList<>();
mActionTopicReached = false;
Topic rootMenu = generateTopicHierarchy(rootTopicView);
mHistory.add(rootMenu);
}
@Override
public boolean isActionTopicReached() {
return mActionTopicReached;
}
@Override
public int getHistorySize() {
return mHistory.size();
}
@Override
public Topic getTopicInHistory(int pageNumber) {
if (pageNumber < 0 || pageNumber >= mHistory.size()) {
return null;
}
return mHistory.get(pageNumber);
}
@Override
public void pushTopicToHistory(Topic topic) {
if (mActionTopicReached) {
throw new IllegalStateException("Cannot navigate to Topics beyond an ActionTopic.");
}
if (topic instanceof ActionTopic) {
mActionTopicReached = true;
}
mHistory.add(topic);
}
@Override
public Topic popTopicFromHistory() {
if (mActionTopicReached) {
mActionTopicReached = false;
}
return mHistory.remove(mHistory.size()-1);
}
@Override
public void loadHistory(Bundle savedInstanceState) {
mHistory = savedInstanceState.getParcelableArrayList(KEY_HISTORY_STACK);
Topic top = mHistory.get(mHistory.size()-1);
mActionTopicReached = (top instanceof ActionTopic);
}
@Override
public void saveHistory(Bundle savedInstanceState) {
savedInstanceState.putParcelableArrayList(KEY_HISTORY_STACK, mHistory);
}
@Override
public boolean isTopicInHistory(Topic topic) {
for (Topic t : mHistory) {
if (topic.equals(t)) {
return true;
}
}
return false;
}
private Topic generateTopicHierarchy(TopicView root) {
if (root == null) {
return null;
}
String title = root.getTitle();
String description = root.getDescription();
if (root.getChildCount() > 0)
{
MenuTopic mt = new MenuTopic(title, description, null);
for (int i = 0; i < root.getChildCount(); i++) {
TopicView child = (TopicView) root.getChildAt(i);
mt.addSubtopic(generateTopicHierarchy(child));
}
return mt;
}
else {
ActionTopic at = new ActionTopic(title, description, root.getDemoFragmentId());
return at;
}
}
}
| cngu/android-fun | app/src/main/java/com/cngu/androidfun/main/TopicManager.java | Java | mit | 3,766 |
/*
* This file is part of NucleusFramework for Bukkit, licensed under the MIT License (MIT).
*
* Copyright (c) JCThePants (www.jcwhatever.com)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.jcwhatever.nucleus.internal.managed.scripting.api;
import com.jcwhatever.nucleus.Nucleus;
import com.jcwhatever.nucleus.mixins.IDisposable;
import com.jcwhatever.nucleus.utils.PreCon;
import com.jcwhatever.nucleus.utils.coords.NamedLocation;
import org.bukkit.Location;
import java.util.Collection;
import javax.annotation.Nullable;
/**
* Sub script API for named locations that can be retrieved by scripts.
*/
public class SAPI_Locations implements IDisposable {
private boolean _isDisposed;
@Override
public boolean isDisposed() {
return _isDisposed;
}
@Override
public void dispose() {
_isDisposed = true;
}
/**
* Get a quest script location by name.
*
* @param name The name of the location.
*/
@Nullable
public Location get(String name) {
PreCon.notNullOrEmpty(name);
NamedLocation result = Nucleus.getScriptManager().getLocations().get(name);
if (result == null)
return null;
return result.toLocation();
}
/**
* Get all script location objects.
*/
public Collection<NamedLocation> getScriptLocations() {
return Nucleus.getScriptManager().getLocations().getAll();
}
/**
* Get all script location objects.
*
* @param output The output collection to put results into.
*
* @return The output collection.
*/
public <T extends Collection<NamedLocation>> T getScriptLocations(T output) {
PreCon.notNull(output);
return Nucleus.getScriptManager().getLocations().getAll(output);
}
}
| JCThePants/NucleusFramework | src/com/jcwhatever/nucleus/internal/managed/scripting/api/SAPI_Locations.java | Java | mit | 2,857 |
var GlobezGame = GlobezGame || {};
GlobezGame.Boot = function() {};
GlobezGame.Boot.prototype = {
preload: function() {
console.log("%cStarting Fish Vs Mines", "color:white; background:red");
this.load.image("loading", "assets/sprites/loading.png");
this.load.image("logo", "assets/sprites/logo.png");
},
create: function() {
this.scale.scaleMode = Phaser.ScaleManager.SHOW_ALL;
this.scale.pageAlignHorizontally = true;
this.scale.pageAlignVertically = true;
// this.scale.setScreenSize(true);
this.physics.startSystem(Phaser.Physics.ARCADE);
this.state.start("Preload");
}
}
var GlobezGame = GlobezGame || {};
GlobezGame.Preload = function() {};
GlobezGame.Preload.prototype = {
preload: function() {
console.log("%cPreloading assets", "color:white; background:red")
var loadingBar = this.add.sprite(160, 340, "loading");
loadingBar.anchor.setTo(0.5, 0.5);
this.load.setPreloadSprite(loadingBar);
var logo = this.add.sprite(160, 240, "logo");
logo.anchor.setTo(0.5, 0.5);
this.load.image("background", "assets/sprites/background.png");
this.load.image("playbutton", "assets/sprites/playbutton.png");
this.load.image("gametitle_sealife", "assets/sprites/gametitle_sealife.png");
this.load.image("gametitle_vs", "assets/sprites/gametitle_vs.png");
this.load.image("gametitle_mines", "assets/sprites/gametitle_mines.png");
this.load.image("blackfade", "assets/sprites/blackfade.png");
this.load.image("bubble", "assets/sprites/bubble.png");
},
create: function() {
this.state.start("GameTitle");
}
}
var GlobezGame = GlobezGame || {};
GlobezGame.GameTitle = function() {
startGame = false;
};
GlobezGame.GameTitle.prototype = {
create: function() {
console.log("%cStarting game title", "color:white; background:red");
this.add.image(0, 0, "background");
//
var bubblesEmitter = this.add.emitter(160, 500, 50);
bubblesEmitter.makeParticles("bubble");
bubblesEmitter.maxParticleScale = 0.6;
bubblesEmitter.minParticleScale = 0.2;
bubblesEmitter.setYSpeed(-30, -40);
bubblesEmitter.setXSpeed(-3, 3);
bubblesEmitter.gravity = 0;
bubblesEmitter.width = 320;
bubblesEmitter.minRotation = 0;
bubblesEmitter.maxRotation = 40;
bubblesEmitter.flow(15000, 2000)
//
var gameTitleSeaLife = this.add.image(160, 70, "gametitle_sealife");
gameTitleSeaLife.anchor.setTo(0.5, 0.5);
gameTitleSeaLife.angle = (2 + Math.random() * 5) * (Math.random() > 0.5 ? 1 : -1);
var seaLifeTween = this.add.tween(gameTitleSeaLife);
seaLifeTween.to({
angle: -gameTitleSeaLife.angle
}, 5000 + Math.random() * 5000, Phaser.Easing.Linear.None, true, 0, 1000, true);
//
var gameTitleVs = this.add.image(190, 120, "gametitle_vs");
gameTitleVs.anchor.setTo(0.5, 0.5);
gameTitleVs.angle = (2 + Math.random() * 5) * (Math.random() > 0.5 ? 1 : -1);
var vsTween = this.add.tween(gameTitleVs);
vsTween.to({
angle: -gameTitleVs.angle
}, 5000 + Math.random() * 5000, Phaser.Easing.Linear.None, true, 0, 1000, true);
//
var gameTitleMines = this.add.image(160, 160, "gametitle_mines");
gameTitleMines.anchor.setTo(0.5, 0.5);
gameTitleMines.angle = (2 + Math.random() * 5) * (Math.random() > 0.5 ? 1 : -1);
var minesTween = this.add.tween(gameTitleMines);
minesTween.to({
angle: -gameTitleMines.angle
}, 5000 + Math.random() * 5000, Phaser.Easing.Linear.None, true, 0, 1000, true);
//
var playButton = this.add.button(160, 320, "playbutton", this.playTheGame, this)
playButton.anchor.setTo(0.5, 0.5);
playButton.angle = (2 + Math.random() * 5) * (Math.random() > 0.5 ? 1 : -1);
var playTween = this.add.tween(playButton);
playTween.to({
angle: -playButton.angle
}, 5000 + Math.random() * 5000, Phaser.Easing.Linear.None, true, 0, 1000, true);
//
var blackFade = this.add.sprite(0, 0, "blackfade");
var fadeTween = this.add.tween(blackFade);
fadeTween.to({
alpha: 0
}, 2000, Phaser.Easing.Cubic.Out, true);
},
playTheGame: function() {
if (!startGame) {
startGame = true
alert("Start the game!!");
}
}
}
var GlobezGame = GlobezGame || {};
GlobezGame.gameOptions = {
gameWidth: 320,
gameHeight: 480
}
GlobezGame.game = new Phaser.Game(GlobezGame.gameOptions.gameWidth, GlobezGame.gameOptions.gameHeight, Phaser.CANVAS, "");
GlobezGame.game.state.add("Boot", GlobezGame.Boot);
GlobezGame.game.state.add("Preload", GlobezGame.Preload);
GlobezGame.game.state.add("GameTitle", GlobezGame.GameTitle);
GlobezGame.game.state.start("Boot");
| jojoee/phaser-examples | games/sea-life-vs-mines/js/game.js | JavaScript | mit | 4,643 |
#ifndef QRW_SKIRMISHPREPARATIONPLAYEROPTIONS_HPP
#define QRW_SKIRMISHPREPARATIONPLAYEROPTIONS_HPP
#include <string>
#include "gui/ng/window.hpp"
namespace namelessgui
{
class LineInput;
}
namespace qrw
{
class SkirmishPreparationPlayerOptions : public namelessgui::Window
{
public:
SkirmishPreparationPlayerOptions();
SkirmishPreparationPlayerOptions(const SkirmishPreparationPlayerOptions&) = delete;
SkirmishPreparationPlayerOptions& operator=(const SkirmishPreparationPlayerOptions&) = delete;
const std::string& getPlayerName();
void setPlayerName(const std::string& name);
private:
namelessgui::LineInput* playerNameInput_;
};
} // namespace qrw
#endif //QRW_SKIRMISHPREPARATIONPLAYEROPTIONS_HPP
| namelessvoid/qrwar | include/game/skirmish/gui/skirmishpreparationplayeroptions.hpp | C++ | mit | 717 |
'use strict';
describe('nothing', () => {
it('should do nothing', () => {
//
});
});
| sthuck/quick-2fa | src/index.spec.js | JavaScript | mit | 94 |
package com.jinwen.thread.ch01;
/**
* 知识点:线程挂起的问题
* @author JIN
*
*/
public class Demo010 {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
final SynchronizedObject1 object = new SynchronizedObject1();
Thread thread1 = new Thread() {
@Override
public void run() {
object.printString();
}
};
thread1.setName("a");
thread1.start();
Thread.sleep(1000);
Thread thread2 = new Thread() {
@Override
public void run() {
System.out
.println("thread2启动了,但进入不了printString()方法!只打印1个begin");
System.out
.println("因为printString()方法被a线程锁定并且永远的suspend暂停了!");
object.printString();
}
};
thread2.start();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
class SynchronizedObject1 {
synchronized public void printString() {
System.out.println("begin");
if (Thread.currentThread().getName().equals("a")) {
System.out.println("a线程永远 suspend了!");
Thread.currentThread().suspend();
}
System.out.println("end");
}
} | jinchen92/JavaBasePractice | src/com/jinwen/thread/ch01/Demo010.java | Java | mit | 1,232 |
#include "TelaPrincipal.h"
TelaPrincipal::TelaPrincipal()
{
}
| VitorDiToro/EC206-EngenhariaDeSoftware2 | SIF_CONSOLE/View/TelaPrincipal.cpp | C++ | mit | 65 |
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package blastbenchmark;
/**
*
* @author thanos
*/
public class Lock {
private boolean isLocked = false;
public synchronized void lock()
throws InterruptedException {
while (isLocked) {
//System.out.println("locked.. sleeping");
wait();
}
isLocked = true;
}
public synchronized void unlock() {
isLocked = false;
notify();
}
}
| BioDAG/odysseys | BlastBenchmark/src/blastbenchmark/Lock.java | Java | mit | 617 |
import { setData } from '@progress/kendo-angular-intl';
setData({
name: "pt-CH",
identity: {
language: "pt",
territory: "CH"
},
territory: "CH",
numbers: {
symbols: {
decimal: ",",
group: " ",
list: ";",
percentSign: "%",
plusSign: "+",
minusSign: "-",
exponential: "E",
superscriptingExponent: "×",
perMille: "‰",
infinity: "∞",
nan: "NaN",
timeSeparator: ":"
},
decimal: {
patterns: [
"n"
],
groupSize: [
3
]
},
scientific: {
patterns: [
"nEn"
],
groupSize: []
},
percent: {
patterns: [
"n%"
],
groupSize: [
3
]
},
currency: {
patterns: [
"n $"
],
groupSize: [
3
],
"unitPattern-count-one": "n $",
"unitPattern-count-other": "n $"
},
accounting: {
patterns: [
"n $",
"(n $)"
],
groupSize: [
3
]
},
currencies: {
ADP: {
displayName: "Peseta de Andorra",
"displayName-count-one": "Peseta de Andorra",
"displayName-count-other": "Pesetas de Andorra",
symbol: "ADP"
},
AED: {
displayName: "Dirham dos Emirados Árabes Unidos",
"displayName-count-one": "Dirham dos Emirados Árabes Unidos",
"displayName-count-other": "Dirhams dos Emirados Árabes Unidos",
symbol: "AED"
},
AFA: {
displayName: "Afeghani (1927–2002)",
"displayName-count-one": "Afegane do Afeganistão (AFA)",
"displayName-count-other": "Afeganes do Afeganistão (AFA)",
symbol: "AFA"
},
AFN: {
displayName: "Afegani do Afeganistão",
"displayName-count-one": "Afegani do Afeganistão",
"displayName-count-other": "Afeganis do Afeganistão",
symbol: "AFN"
},
ALK: {
displayName: "Lek Albanês (1946–1965)",
"displayName-count-one": "Lek Albanês (1946–1965)",
"displayName-count-other": "Leks Albaneses (1946–1965)"
},
ALL: {
displayName: "Lek albanês",
"displayName-count-one": "Lek albanês",
"displayName-count-other": "Leks albaneses",
symbol: "ALL"
},
AMD: {
displayName: "Dram arménio",
"displayName-count-one": "Dram arménio",
"displayName-count-other": "Drams arménios",
symbol: "AMD"
},
ANG: {
displayName: "Florim das Antilhas Holandesas",
"displayName-count-one": "Florim das Antilhas Holandesas",
"displayName-count-other": "Florins das Antilhas Holandesas",
symbol: "ANG"
},
AOA: {
displayName: "Kwanza angolano",
"displayName-count-one": "Kwanza angolano",
"displayName-count-other": "Kwanzas angolanos",
symbol: "AOA",
"symbol-alt-narrow": "Kz"
},
AOK: {
displayName: "Cuanza angolano (1977–1990)",
"displayName-count-one": "Kwanza angolano (AOK)",
"displayName-count-other": "Kwanzas angolanos (AOK)",
symbol: "AOK"
},
AON: {
displayName: "Novo cuanza angolano (1990–2000)",
"displayName-count-one": "Novo kwanza angolano (AON)",
"displayName-count-other": "Novos kwanzas angolanos (AON)",
symbol: "AON"
},
AOR: {
displayName: "Cuanza angolano reajustado (1995–1999)",
"displayName-count-one": "Kwanza angolano reajustado (AOR)",
"displayName-count-other": "Kwanzas angolanos reajustados (AOR)",
symbol: "AOR"
},
ARA: {
displayName: "Austral argentino",
"displayName-count-one": "Austral argentino",
"displayName-count-other": "Austrais argentinos",
symbol: "ARA"
},
ARL: {
displayName: "Peso lei argentino (1970–1983)",
"displayName-count-one": "Peso lei argentino (1970–1983)",
"displayName-count-other": "Pesos lei argentinos (1970–1983)",
symbol: "ARL"
},
ARM: {
displayName: "Peso argentino (1881–1970)",
"displayName-count-one": "Peso argentino (1881–1970)",
"displayName-count-other": "Pesos argentinos (1881–1970)",
symbol: "ARM"
},
ARP: {
displayName: "Peso argentino (1983–1985)",
"displayName-count-one": "Peso argentino (1983–1985)",
"displayName-count-other": "Pesos argentinos (1983–1985)",
symbol: "ARP"
},
ARS: {
displayName: "Peso argentino",
"displayName-count-one": "Peso argentino",
"displayName-count-other": "Pesos argentinos",
symbol: "ARS",
"symbol-alt-narrow": "$"
},
ATS: {
displayName: "Xelim austríaco",
"displayName-count-one": "Schilling australiano",
"displayName-count-other": "Schillings australianos",
symbol: "ATS"
},
AUD: {
displayName: "Dólar australiano",
"displayName-count-one": "Dólar australiano",
"displayName-count-other": "Dólares australianos",
symbol: "AU$",
"symbol-alt-narrow": "$"
},
AWG: {
displayName: "Florim de Aruba",
"displayName-count-one": "Florim de Aruba",
"displayName-count-other": "Florins de Aruba",
symbol: "AWG"
},
AZM: {
displayName: "Manat azerbaijano (1993–2006)",
"displayName-count-one": "Manat do Azeibaijão (1993–2006)",
"displayName-count-other": "Manats do Azeibaijão (1993–2006)",
symbol: "AZM"
},
AZN: {
displayName: "Manat do Azerbaijão",
"displayName-count-one": "Manat do Azerbaijão",
"displayName-count-other": "Manats do Azerbaijão",
symbol: "AZN"
},
BAD: {
displayName: "Dinar da Bósnia-Herzegóvina",
"displayName-count-one": "Dinar da Bósnia Herzegovina",
"displayName-count-other": "Dinares da Bósnia Herzegovina",
symbol: "BAD"
},
BAM: {
displayName: "Marco bósnio-herzegóvino conversível",
"displayName-count-one": "Marco bósnio-herzegóvino conversível",
"displayName-count-other": "Marcos bósnio-herzegóvinos conversíveis",
symbol: "BAM",
"symbol-alt-narrow": "KM"
},
BAN: {
displayName: "Novo dinar da Bósnia-Herzegovina (1994–1997)",
"displayName-count-one": "Novo dinar da Bósnia-Herzegovina",
"displayName-count-other": "Novos dinares da Bósnia-Herzegovina",
symbol: "BAN"
},
BBD: {
displayName: "Dólar barbadense",
"displayName-count-one": "Dólar barbadense",
"displayName-count-other": "Dólares barbadenses",
symbol: "BBD",
"symbol-alt-narrow": "$"
},
BDT: {
displayName: "Taka de Bangladesh",
"displayName-count-one": "Taka de Bangladesh",
"displayName-count-other": "Takas de Bangladesh",
symbol: "BDT",
"symbol-alt-narrow": "৳"
},
BEC: {
displayName: "Franco belga (convertível)",
"displayName-count-one": "Franco belga (conversível)",
"displayName-count-other": "Francos belgas (conversíveis)",
symbol: "BEC"
},
BEF: {
displayName: "Franco belga",
"displayName-count-one": "Franco belga",
"displayName-count-other": "Francos belgas",
symbol: "BEF"
},
BEL: {
displayName: "Franco belga (financeiro)",
"displayName-count-one": "Franco belga (financeiro)",
"displayName-count-other": "Francos belgas (financeiros)",
symbol: "BEL"
},
BGL: {
displayName: "Lev forte búlgaro",
"displayName-count-one": "Lev forte búlgaro",
"displayName-count-other": "Levs fortes búlgaros",
symbol: "BGL"
},
BGM: {
displayName: "Lev socialista búlgaro",
"displayName-count-one": "Lev socialista búlgaro",
"displayName-count-other": "Levs socialistas búlgaros",
symbol: "BGM"
},
BGN: {
displayName: "Lev búlgaro",
"displayName-count-one": "Lev búlgaro",
"displayName-count-other": "Levs búlgaros",
symbol: "BGN"
},
BGO: {
displayName: "Lev búlgaro (1879–1952)",
"displayName-count-one": "Lev búlgaro (1879–1952)",
"displayName-count-other": "Levs búlgaros (1879–1952)",
symbol: "BGO"
},
BHD: {
displayName: "Dinar baremita",
"displayName-count-one": "Dinar baremita",
"displayName-count-other": "Dinares baremitas",
symbol: "BHD"
},
BIF: {
displayName: "Franco burundiano",
"displayName-count-one": "Franco burundiano",
"displayName-count-other": "Francos burundianos",
symbol: "BIF"
},
BMD: {
displayName: "Dólar bermudense",
"displayName-count-one": "Dólar bermudense",
"displayName-count-other": "Dólares bermudenses",
symbol: "BMD",
"symbol-alt-narrow": "$"
},
BND: {
displayName: "Dólar bruneíno",
"displayName-count-one": "Dólar bruneíno",
"displayName-count-other": "Dólares bruneínos",
symbol: "BND",
"symbol-alt-narrow": "$"
},
BOB: {
displayName: "Boliviano",
"displayName-count-one": "Boliviano",
"displayName-count-other": "Bolivianos",
symbol: "BOB",
"symbol-alt-narrow": "Bs"
},
BOL: {
displayName: "Boliviano (1863–1963)",
"displayName-count-one": "Boliviano (1863–1963)",
"displayName-count-other": "Bolivianos (1863–1963)",
symbol: "BOL"
},
BOP: {
displayName: "Peso boliviano",
"displayName-count-one": "Peso boliviano",
"displayName-count-other": "Pesos bolivianos",
symbol: "BOP"
},
BOV: {
displayName: "Mvdol boliviano",
"displayName-count-one": "Mvdol boliviano",
"displayName-count-other": "Mvdols bolivianos",
symbol: "BOV"
},
BRB: {
displayName: "Cruzeiro novo brasileiro (1967–1986)",
"displayName-count-one": "Cruzeiro novo brasileiro (BRB)",
"displayName-count-other": "Cruzeiros novos brasileiros (BRB)",
symbol: "BRB"
},
BRC: {
displayName: "Cruzado brasileiro (1986–1989)",
"displayName-count-one": "Cruzado brasileiro",
"displayName-count-other": "Cruzados brasileiros",
symbol: "BRC"
},
BRE: {
displayName: "Cruzeiro brasileiro (1990–1993)",
"displayName-count-one": "Cruzeiro brasileiro (BRE)",
"displayName-count-other": "Cruzeiros brasileiros (BRE)",
symbol: "BRE"
},
BRL: {
displayName: "Real brasileiro",
"displayName-count-one": "Real brasileiro",
"displayName-count-other": "Reais brasileiros",
symbol: "R$",
"symbol-alt-narrow": "R$"
},
BRN: {
displayName: "Cruzado novo brasileiro (1989–1990)",
"displayName-count-one": "Cruzado novo brasileiro",
"displayName-count-other": "Cruzados novos brasileiros",
symbol: "BRN"
},
BRR: {
displayName: "Cruzeiro brasileiro (1993–1994)",
"displayName-count-one": "Cruzeiro brasileiro",
"displayName-count-other": "Cruzeiros brasileiros",
symbol: "BRR"
},
BRZ: {
displayName: "Cruzeiro brasileiro (1942–1967)",
"displayName-count-one": "Cruzeiro brasileiro antigo",
"displayName-count-other": "Cruzeiros brasileiros antigos",
symbol: "BRZ"
},
BSD: {
displayName: "Dólar das Bahamas",
"displayName-count-one": "Dólar das Bahamas",
"displayName-count-other": "Dólares das Bahamas",
symbol: "BSD",
"symbol-alt-narrow": "$"
},
BTN: {
displayName: "Ngultrum do Butão",
"displayName-count-one": "Ngultrum do Butão",
"displayName-count-other": "Ngultruns do Butão",
symbol: "BTN"
},
BUK: {
displayName: "Kyat birmanês",
"displayName-count-one": "Kyat burmês",
"displayName-count-other": "Kyats burmeses",
symbol: "BUK"
},
BWP: {
displayName: "Pula de Botswana",
"displayName-count-one": "Pula de Botswana",
"displayName-count-other": "Pulas de Botswana",
symbol: "BWP",
"symbol-alt-narrow": "P"
},
BYB: {
displayName: "Rublo novo bielorusso (1994–1999)",
"displayName-count-one": "Novo rublo bielorusso (BYB)",
"displayName-count-other": "Novos rublos bielorussos (BYB)",
symbol: "BYB"
},
BYN: {
displayName: "Rublo bielorrusso",
"displayName-count-one": "Rublo bielorrusso",
"displayName-count-other": "Rublos bielorrussos",
symbol: "BYN",
"symbol-alt-narrow": "р."
},
BYR: {
displayName: "Rublo bielorrusso (2000–2016)",
"displayName-count-one": "Rublo bielorrusso (2000–2016)",
"displayName-count-other": "Rublos bielorrussos (2000–2016)",
symbol: "BYR"
},
BZD: {
displayName: "Dólar belizense",
"displayName-count-one": "Dólar belizense",
"displayName-count-other": "Dólares belizenses",
symbol: "BZD",
"symbol-alt-narrow": "$"
},
CAD: {
displayName: "Dólar canadiano",
"displayName-count-one": "Dólar canadiano",
"displayName-count-other": "Dólares canadianos",
symbol: "CA$",
"symbol-alt-narrow": "$"
},
CDF: {
displayName: "Franco congolês",
"displayName-count-one": "Franco congolês",
"displayName-count-other": "Francos congoleses",
symbol: "CDF"
},
CHE: {
displayName: "Euro WIR",
"displayName-count-one": "Euro WIR",
"displayName-count-other": "Euros WIR",
symbol: "CHE"
},
CHF: {
displayName: "Franco suíço",
"displayName-count-one": "Franco suíço",
"displayName-count-other": "Francos suíços",
symbol: "CHF"
},
CHW: {
displayName: "Franco WIR",
"displayName-count-one": "Franco WIR",
"displayName-count-other": "Francos WIR",
symbol: "CHW"
},
CLE: {
displayName: "Escudo chileno",
"displayName-count-one": "Escudo chileno",
"displayName-count-other": "Escudos chilenos",
symbol: "CLE"
},
CLF: {
displayName: "Unidades de Fomento chilenas",
"displayName-count-one": "Unidade de fomento chilena",
"displayName-count-other": "Unidades de fomento chilenas",
symbol: "CLF"
},
CLP: {
displayName: "Peso chileno",
"displayName-count-one": "Peso chileno",
"displayName-count-other": "Pesos chilenos",
symbol: "CLP",
"symbol-alt-narrow": "$"
},
CNX: {
displayName: "Dólar do Banco Popular da China",
"displayName-count-one": "Dólar do Banco Popular da China",
"displayName-count-other": "Dólares do Banco Popular da China"
},
CNY: {
displayName: "Yuan chinês",
"displayName-count-one": "Yuan chinês",
"displayName-count-other": "Yuans chineses",
symbol: "CN¥",
"symbol-alt-narrow": "¥"
},
COP: {
displayName: "Peso colombiano",
"displayName-count-one": "Peso colombiano",
"displayName-count-other": "Pesos colombianos",
symbol: "COP",
"symbol-alt-narrow": "$"
},
COU: {
displayName: "Unidade de Valor Real",
"displayName-count-one": "Unidade de valor real",
"displayName-count-other": "Unidades de valor real",
symbol: "COU"
},
CRC: {
displayName: "Colon costa-riquenho",
"displayName-count-one": "Colon costa-riquenho",
"displayName-count-other": "Colons costa-riquenhos",
symbol: "CRC",
"symbol-alt-narrow": "₡"
},
CSD: {
displayName: "Dinar sérvio (2002–2006)",
"displayName-count-one": "Dinar antigo da Sérvia",
"displayName-count-other": "Dinares antigos da Sérvia",
symbol: "CSD"
},
CSK: {
displayName: "Coroa Forte checoslovaca",
"displayName-count-one": "Coroa forte tchecoslovaca",
"displayName-count-other": "Coroas fortes tchecoslovacas",
symbol: "CSK"
},
CUC: {
displayName: "Peso cubano conversível",
"displayName-count-one": "Peso cubano conversível",
"displayName-count-other": "Pesos cubanos conversíveis",
symbol: "CUC",
"symbol-alt-narrow": "$"
},
CUP: {
displayName: "Peso cubano",
"displayName-count-one": "Peso cubano",
"displayName-count-other": "Pesos cubanos",
symbol: "CUP",
"symbol-alt-narrow": "$"
},
CVE: {
displayName: "Escudo cabo-verdiano",
"displayName-count-one": "Escudo cabo-verdiano",
"displayName-count-other": "Escudos cabo-verdianos",
symbol: "CVE"
},
CYP: {
displayName: "Libra de Chipre",
"displayName-count-one": "Libra cipriota",
"displayName-count-other": "Libras cipriotas",
symbol: "CYP"
},
CZK: {
displayName: "Coroa checa",
"displayName-count-one": "Coroa checa",
"displayName-count-other": "Coroas checas",
symbol: "CZK",
"symbol-alt-narrow": "Kč"
},
DDM: {
displayName: "Ostmark da Alemanha Oriental",
"displayName-count-one": "Marco da Alemanha Oriental",
"displayName-count-other": "Marcos da Alemanha Oriental",
symbol: "DDM"
},
DEM: {
displayName: "Marco alemão",
"displayName-count-one": "Marco alemão",
"displayName-count-other": "Marcos alemães",
symbol: "DEM"
},
DJF: {
displayName: "Franco jibutiano",
"displayName-count-one": "Franco jibutiano",
"displayName-count-other": "Francos jibutianos",
symbol: "DJF"
},
DKK: {
displayName: "Coroa dinamarquesa",
"displayName-count-one": "Coroa dinamarquesa",
"displayName-count-other": "Coroas dinamarquesas",
symbol: "DKK",
"symbol-alt-narrow": "kr"
},
DOP: {
displayName: "Peso dominicano",
"displayName-count-one": "Peso dominicano",
"displayName-count-other": "Pesos dominicanos",
symbol: "DOP",
"symbol-alt-narrow": "$"
},
DZD: {
displayName: "Dinar argelino",
"displayName-count-one": "Dinar argelino",
"displayName-count-other": "Dinares argelinos",
symbol: "DZD"
},
ECS: {
displayName: "Sucre equatoriano",
"displayName-count-one": "Sucre equatoriano",
"displayName-count-other": "Sucres equatorianos",
symbol: "ECS"
},
ECV: {
displayName: "Unidad de Valor Constante (UVC) do Equador",
"displayName-count-one": "Unidade de valor constante equatoriana (UVC)",
"displayName-count-other": "Unidades de valor constante equatorianas (UVC)",
symbol: "ECV"
},
EEK: {
displayName: "Coroa estoniana",
"displayName-count-one": "Coroa estoniana",
"displayName-count-other": "Coroas estonianas",
symbol: "EEK"
},
EGP: {
displayName: "Libra egípcia",
"displayName-count-one": "Libra egípcia",
"displayName-count-other": "Libras egípcias",
symbol: "EGP",
"symbol-alt-narrow": "E£"
},
ERN: {
displayName: "Nakfa da Eritreia",
"displayName-count-one": "Nakfa da Eritreia",
"displayName-count-other": "Nakfas da Eritreia",
symbol: "ERN"
},
ESA: {
displayName: "Peseta espanhola (conta A)",
"displayName-count-one": "Peseta espanhola (conta A)",
"displayName-count-other": "Pesetas espanholas (conta A)",
symbol: "ESA"
},
ESB: {
displayName: "Peseta espanhola (conta conversível)",
"displayName-count-one": "Peseta espanhola (conta conversível)",
"displayName-count-other": "Pesetas espanholas (conta conversível)",
symbol: "ESB"
},
ESP: {
displayName: "Peseta espanhola",
"displayName-count-one": "Peseta espanhola",
"displayName-count-other": "Pesetas espanholas",
symbol: "ESP",
"symbol-alt-narrow": "₧"
},
ETB: {
displayName: "Birr etíope",
"displayName-count-one": "Birr etíope",
"displayName-count-other": "Birrs etíopes",
symbol: "ETB"
},
EUR: {
displayName: "Euro",
"displayName-count-one": "Euro",
"displayName-count-other": "Euros",
symbol: "€",
"symbol-alt-narrow": "€"
},
FIM: {
displayName: "Marca finlandesa",
"displayName-count-one": "Marco finlandês",
"displayName-count-other": "Marcos finlandeses",
symbol: "FIM"
},
FJD: {
displayName: "Dólar de Fiji",
"displayName-count-one": "Dólar de Fiji",
"displayName-count-other": "Dólares de Fiji",
symbol: "FJD",
"symbol-alt-narrow": "$"
},
FKP: {
displayName: "Libra das Ilhas Falkland",
"displayName-count-one": "Libra das Ilhas Falkland",
"displayName-count-other": "Libras das Ilhas Falkland",
symbol: "FKP",
"symbol-alt-narrow": "£"
},
FRF: {
displayName: "Franco francês",
"displayName-count-one": "Franco francês",
"displayName-count-other": "Francos franceses",
symbol: "FRF"
},
GBP: {
displayName: "Libra esterlina britânica",
"displayName-count-one": "Libra esterlina britânica",
"displayName-count-other": "Libras esterlinas britânicas",
symbol: "£",
"symbol-alt-narrow": "£"
},
GEK: {
displayName: "Cupom Lari georgiano",
"displayName-count-one": "Kupon larit da Geórgia",
"displayName-count-other": "Kupon larits da Geórgia",
symbol: "GEK"
},
GEL: {
displayName: "Lari georgiano",
"displayName-count-one": "Lari georgiano",
"displayName-count-other": "Laris georgianos",
symbol: "GEL",
"symbol-alt-narrow": "₾",
"symbol-alt-variant": "₾"
},
GHC: {
displayName: "Cedi de Gana (1979–2007)",
"displayName-count-one": "Cedi de Gana (1979–2007)",
"displayName-count-other": "Cedis de Gana (1979–2007)",
symbol: "GHC"
},
GHS: {
displayName: "Cedi de Gana",
"displayName-count-one": "Cedi de Gana",
"displayName-count-other": "Cedis de Gana",
symbol: "GHS"
},
GIP: {
displayName: "Libra de Gibraltar",
"displayName-count-one": "Libra de Gibraltar",
"displayName-count-other": "Libras de Gibraltar",
symbol: "GIP",
"symbol-alt-narrow": "£"
},
GMD: {
displayName: "Dalasi da Gâmbia",
"displayName-count-one": "Dalasi da Gâmbia",
"displayName-count-other": "Dalasis da Gâmbia",
symbol: "GMD"
},
GNF: {
displayName: "Franco guineense",
"displayName-count-one": "Franco guineense",
"displayName-count-other": "Francos guineenses",
symbol: "GNF",
"symbol-alt-narrow": "FG"
},
GNS: {
displayName: "Syli da Guiné",
"displayName-count-one": "Syli guineano",
"displayName-count-other": "Sylis guineanos",
symbol: "GNS"
},
GQE: {
displayName: "Ekwele da Guiné Equatorial",
"displayName-count-one": "Ekwele da Guiné Equatorial",
"displayName-count-other": "Ekweles da Guiné Equatorial",
symbol: "GQE"
},
GRD: {
displayName: "Dracma grego",
"displayName-count-one": "Dracma grego",
"displayName-count-other": "Dracmas gregos",
symbol: "GRD"
},
GTQ: {
displayName: "Quetzal da Guatemala",
"displayName-count-one": "Quetzal da Guatemala",
"displayName-count-other": "Quetzales da Guatemala",
symbol: "GTQ",
"symbol-alt-narrow": "Q"
},
GWE: {
displayName: "Escudo da Guiné Portuguesa",
"displayName-count-one": "Escudo da Guiné Portuguesa",
"displayName-count-other": "Escudos da Guinéa Portuguesa",
symbol: "GWE"
},
GWP: {
displayName: "Peso da Guiné-Bissau",
"displayName-count-one": "Peso de Guiné-Bissau",
"displayName-count-other": "Pesos de Guiné-Bissau",
symbol: "GWP"
},
GYD: {
displayName: "Dólar da Guiana",
"displayName-count-one": "Dólar da Guiana",
"displayName-count-other": "Dólares da Guiana",
symbol: "GYD",
"symbol-alt-narrow": "$"
},
HKD: {
displayName: "Dólar de Hong Kong",
"displayName-count-one": "Dólar de Hong Kong",
"displayName-count-other": "Dólares de Hong Kong",
symbol: "HK$",
"symbol-alt-narrow": "$"
},
HNL: {
displayName: "Lempira das Honduras",
"displayName-count-one": "Lempira das Honduras",
"displayName-count-other": "Lempiras das Honduras",
symbol: "HNL",
"symbol-alt-narrow": "L"
},
HRD: {
displayName: "Dinar croata",
"displayName-count-one": "Dinar croata",
"displayName-count-other": "Dinares croatas",
symbol: "HRD"
},
HRK: {
displayName: "Kuna croata",
"displayName-count-one": "Kuna croata",
"displayName-count-other": "Kunas croatas",
symbol: "HRK",
"symbol-alt-narrow": "kn"
},
HTG: {
displayName: "Gourde haitiano",
"displayName-count-one": "Gourde haitiano",
"displayName-count-other": "Gourdes haitianos",
symbol: "HTG"
},
HUF: {
displayName: "Forint húngaro",
"displayName-count-one": "Forint húngaro",
"displayName-count-other": "Forints húngaros",
symbol: "HUF",
"symbol-alt-narrow": "Ft"
},
IDR: {
displayName: "Rupia indonésia",
"displayName-count-one": "Rupia indonésia",
"displayName-count-other": "Rupias indonésias",
symbol: "IDR",
"symbol-alt-narrow": "Rp"
},
IEP: {
displayName: "Libra irlandesa",
"displayName-count-one": "Libra irlandesa",
"displayName-count-other": "Libras irlandesas",
symbol: "IEP"
},
ILP: {
displayName: "Libra israelita",
"displayName-count-one": "Libra israelita",
"displayName-count-other": "Libras israelitas",
symbol: "ILP"
},
ILR: {
displayName: "Sheqel antigo israelita",
"displayName-count-one": "Sheqel antigo israelita",
"displayName-count-other": "Sheqels antigos israelitas"
},
ILS: {
displayName: "Sheqel novo israelita",
"displayName-count-one": "Sheqel novo israelita",
"displayName-count-other": "Sheqels novos israelitas",
symbol: "₪",
"symbol-alt-narrow": "₪"
},
INR: {
displayName: "Rupia indiana",
"displayName-count-one": "Rupia indiana",
"displayName-count-other": "Rupias indianas",
symbol: "₹",
"symbol-alt-narrow": "₹"
},
IQD: {
displayName: "Dinar iraquiano",
"displayName-count-one": "Dinar iraquiano",
"displayName-count-other": "Dinares iraquianos",
symbol: "IQD"
},
IRR: {
displayName: "Rial iraniano",
"displayName-count-one": "Rial iraniano",
"displayName-count-other": "Riais iranianos",
symbol: "IRR"
},
ISJ: {
displayName: "Coroa antiga islandesa",
"displayName-count-one": "Coroa antiga islandesa",
"displayName-count-other": "Coroas antigas islandesas"
},
ISK: {
displayName: "Coroa islandesa",
"displayName-count-one": "Coroa islandesa",
"displayName-count-other": "Coroas islandesas",
symbol: "ISK",
"symbol-alt-narrow": "kr"
},
ITL: {
displayName: "Lira italiana",
"displayName-count-one": "Lira italiana",
"displayName-count-other": "Liras italianas",
symbol: "ITL"
},
JMD: {
displayName: "Dólar jamaicano",
"displayName-count-one": "Dólar jamaicano",
"displayName-count-other": "Dólares jamaicanos",
symbol: "JMD",
"symbol-alt-narrow": "$"
},
JOD: {
displayName: "Dinar jordaniano",
"displayName-count-one": "Dinar jordaniano",
"displayName-count-other": "Dinares jordanianos",
symbol: "JOD"
},
JPY: {
displayName: "Iene japonês",
"displayName-count-one": "Iene japonês",
"displayName-count-other": "Ienes japoneses",
symbol: "JP¥",
"symbol-alt-narrow": "¥"
},
KES: {
displayName: "Xelim queniano",
"displayName-count-one": "Xelim queniano",
"displayName-count-other": "Xelins quenianos",
symbol: "KES"
},
KGS: {
displayName: "Som do Quirguistão",
"displayName-count-one": "Som do Quirguistão",
"displayName-count-other": "Sons do Quirguistão",
symbol: "KGS"
},
KHR: {
displayName: "Riel cambojano",
"displayName-count-one": "Riel cambojano",
"displayName-count-other": "Rieles cambojanos",
symbol: "KHR",
"symbol-alt-narrow": "៛"
},
KMF: {
displayName: "Franco comoriano",
"displayName-count-one": "Franco comoriano",
"displayName-count-other": "Francos comorianos",
symbol: "KMF",
"symbol-alt-narrow": "CF"
},
KPW: {
displayName: "Won norte-coreano",
"displayName-count-one": "Won norte-coreano",
"displayName-count-other": "Wons norte-coreanos",
symbol: "KPW",
"symbol-alt-narrow": "₩"
},
KRH: {
displayName: "Hwan da Coreia do Sul (1953–1962)",
"displayName-count-one": "Hwan da Coreia do Sul",
"displayName-count-other": "Hwans da Coreia do Sul",
symbol: "KRH"
},
KRO: {
displayName: "Won da Coreia do Sul (1945–1953)",
"displayName-count-one": "Won antigo da Coreia do Sul",
"displayName-count-other": "Wons antigos da Coreia do Sul",
symbol: "KRO"
},
KRW: {
displayName: "Won sul-coreano",
"displayName-count-one": "Won sul-coreano",
"displayName-count-other": "Wons sul-coreanos",
symbol: "₩",
"symbol-alt-narrow": "₩"
},
KWD: {
displayName: "Dinar kuwaitiano",
"displayName-count-one": "Dinar kuwaitiano",
"displayName-count-other": "Dinares kuwaitianos",
symbol: "KWD"
},
KYD: {
displayName: "Dólar das Ilhas Caimão",
"displayName-count-one": "Dólar das Ilhas Caimão",
"displayName-count-other": "Dólares das Ilhas Caimão",
symbol: "KYD",
"symbol-alt-narrow": "$"
},
KZT: {
displayName: "Tenge do Cazaquistão",
"displayName-count-one": "Tenge do Cazaquistão",
"displayName-count-other": "Tenges do Cazaquistão",
symbol: "KZT",
"symbol-alt-narrow": "₸"
},
LAK: {
displayName: "Kip de Laos",
"displayName-count-one": "Kip de Laos",
"displayName-count-other": "Kips de Laos",
symbol: "LAK",
"symbol-alt-narrow": "₭"
},
LBP: {
displayName: "Libra libanesa",
"displayName-count-one": "Libra libanesa",
"displayName-count-other": "Libras libanesas",
symbol: "LBP",
"symbol-alt-narrow": "L£"
},
LKR: {
displayName: "Rupia do Sri Lanka",
"displayName-count-one": "Rupia do Sri Lanka",
"displayName-count-other": "Rupias do Sri Lanka",
symbol: "LKR",
"symbol-alt-narrow": "Rs"
},
LRD: {
displayName: "Dólar liberiano",
"displayName-count-one": "Dólar liberiano",
"displayName-count-other": "Dólares liberianos",
symbol: "LRD",
"symbol-alt-narrow": "$"
},
LSL: {
displayName: "Loti do Lesoto",
"displayName-count-one": "Loti do Lesoto",
"displayName-count-other": "Lotis do Lesoto",
symbol: "LSL"
},
LTL: {
displayName: "Litas da Lituânia",
"displayName-count-one": "Litas da Lituânia",
"displayName-count-other": "Litas da Lituânia",
symbol: "LTL",
"symbol-alt-narrow": "Lt"
},
LTT: {
displayName: "Talonas lituano",
"displayName-count-one": "Talonas lituanas",
"displayName-count-other": "Talonases lituanas",
symbol: "LTT"
},
LUC: {
displayName: "Franco conversível de Luxemburgo",
"displayName-count-one": "Franco conversível de Luxemburgo",
"displayName-count-other": "Francos conversíveis de Luxemburgo",
symbol: "LUC"
},
LUF: {
displayName: "Franco luxemburguês",
"displayName-count-one": "Franco de Luxemburgo",
"displayName-count-other": "Francos de Luxemburgo",
symbol: "LUF"
},
LUL: {
displayName: "Franco financeiro de Luxemburgo",
"displayName-count-one": "Franco financeiro de Luxemburgo",
"displayName-count-other": "Francos financeiros de Luxemburgo",
symbol: "LUL"
},
LVL: {
displayName: "Lats da Letónia",
"displayName-count-one": "Lats da Letónia",
"displayName-count-other": "Lats da Letónia",
symbol: "LVL",
"symbol-alt-narrow": "Ls"
},
LVR: {
displayName: "Rublo letão",
"displayName-count-one": "Rublo da Letônia",
"displayName-count-other": "Rublos da Letônia",
symbol: "LVR"
},
LYD: {
displayName: "Dinar líbio",
"displayName-count-one": "Dinar líbio",
"displayName-count-other": "Dinares líbios",
symbol: "LYD"
},
MAD: {
displayName: "Dirham marroquino",
"displayName-count-one": "Dirham marroquino",
"displayName-count-other": "Dirhams marroquinos",
symbol: "MAD"
},
MAF: {
displayName: "Franco marroquino",
"displayName-count-one": "Franco marroquino",
"displayName-count-other": "Francos marroquinos",
symbol: "MAF"
},
MCF: {
displayName: "Franco monegasco",
"displayName-count-one": "Franco monegasco",
"displayName-count-other": "Francos monegascos",
symbol: "MCF"
},
MDC: {
displayName: "Cupon moldávio",
"displayName-count-one": "Cupon moldávio",
"displayName-count-other": "Cupon moldávio",
symbol: "MDC"
},
MDL: {
displayName: "Leu moldavo",
"displayName-count-one": "Leu moldavo",
"displayName-count-other": "Lei moldavos",
symbol: "MDL"
},
MGA: {
displayName: "Ariari de Madagáscar",
"displayName-count-one": "Ariari de Madagáscar",
"displayName-count-other": "Ariaris de Madagáscar",
symbol: "MGA",
"symbol-alt-narrow": "Ar"
},
MGF: {
displayName: "Franco de Madagascar",
"displayName-count-one": "Franco de Madagascar",
"displayName-count-other": "Francos de Madagascar",
symbol: "MGF"
},
MKD: {
displayName: "Dinar macedónio",
"displayName-count-one": "Dinar macedónio",
"displayName-count-other": "Dinares macedónios",
symbol: "MKD"
},
MKN: {
displayName: "Dinar macedônio (1992–1993)",
"displayName-count-one": "Dinar macedônio (1992–1993)",
"displayName-count-other": "Dinares macedônios (1992–1993)",
symbol: "MKN"
},
MLF: {
displayName: "Franco de Mali",
"displayName-count-one": "Franco de Mali",
"displayName-count-other": "Francos de Mali",
symbol: "MLF"
},
MMK: {
displayName: "Kyat de Mianmar",
"displayName-count-one": "Kyat de Mianmar",
"displayName-count-other": "Kyats de Mianmar",
symbol: "MMK",
"symbol-alt-narrow": "K"
},
MNT: {
displayName: "Tugrik da Mongólia",
"displayName-count-one": "Tugrik da Mongólia",
"displayName-count-other": "Tugriks da Mongólia",
symbol: "MNT",
"symbol-alt-narrow": "₮"
},
MOP: {
displayName: "Pataca de Macau",
"displayName-count-one": "Pataca de Macau",
"displayName-count-other": "Patacas de Macau",
symbol: "MOP"
},
MRO: {
displayName: "Ouguiya da Mauritânia",
"displayName-count-one": "Ouguiya da Mauritânia",
"displayName-count-other": "Ouguiyas da Mauritânia",
symbol: "MRO"
},
MTL: {
displayName: "Lira maltesa",
"displayName-count-one": "Lira Maltesa",
"displayName-count-other": "Liras maltesas",
symbol: "MTL"
},
MTP: {
displayName: "Libra maltesa",
"displayName-count-one": "Libra maltesa",
"displayName-count-other": "Libras maltesas",
symbol: "MTP"
},
MUR: {
displayName: "Rupia mauriciana",
"displayName-count-one": "Rupia mauriciana",
"displayName-count-other": "Rupias mauricianas",
symbol: "MUR",
"symbol-alt-narrow": "Rs"
},
MVR: {
displayName: "Rupia das Ilhas Maldivas",
"displayName-count-one": "Rupia das Ilhas Maldivas",
"displayName-count-other": "Rupias das Ilhas Maldivas",
symbol: "MVR"
},
MWK: {
displayName: "Kwacha do Malawi",
"displayName-count-one": "Kwacha do Malawi",
"displayName-count-other": "Kwachas do Malawi",
symbol: "MWK"
},
MXN: {
displayName: "Peso mexicano",
"displayName-count-one": "Peso mexicano",
"displayName-count-other": "Pesos mexicanos",
symbol: "MX$",
"symbol-alt-narrow": "$"
},
MXP: {
displayName: "Peso Plata mexicano (1861–1992)",
"displayName-count-one": "Peso de prata mexicano (1861–1992)",
"displayName-count-other": "Pesos de prata mexicanos (1861–1992)",
symbol: "MXP"
},
MXV: {
displayName: "Unidad de Inversion (UDI) mexicana",
"displayName-count-one": "Unidade de investimento mexicana (UDI)",
"displayName-count-other": "Unidades de investimento mexicanas (UDI)",
symbol: "MXV"
},
MYR: {
displayName: "Ringgit malaio",
"displayName-count-one": "Ringgit malaio",
"displayName-count-other": "Ringgits malaios",
symbol: "MYR",
"symbol-alt-narrow": "RM"
},
MZE: {
displayName: "Escudo de Moçambique",
"displayName-count-one": "Escudo de Moçambique",
"displayName-count-other": "Escudos de Moçambique",
symbol: "MZE"
},
MZM: {
displayName: "Metical de Moçambique (1980–2006)",
"displayName-count-one": "Metical antigo de Moçambique",
"displayName-count-other": "Meticales antigos de Moçambique",
symbol: "MZM"
},
MZN: {
displayName: "Metical de Moçambique",
"displayName-count-one": "Metical de Moçambique",
"displayName-count-other": "Meticales de Moçambique",
symbol: "MZN"
},
NAD: {
displayName: "Dólar da Namíbia",
"displayName-count-one": "Dólar da Namíbia",
"displayName-count-other": "Dólares da Namíbia",
symbol: "NAD",
"symbol-alt-narrow": "$"
},
NGN: {
displayName: "Naira nigeriana",
"displayName-count-one": "Naira nigeriana",
"displayName-count-other": "Nairas nigerianas",
symbol: "NGN",
"symbol-alt-narrow": "₦"
},
NIC: {
displayName: "Córdoba nicaraguano (1988–1991)",
"displayName-count-one": "Córdoba nicaraguano (1988–1991)",
"displayName-count-other": "Córdobas nicaraguano (1988–1991)",
symbol: "NIC"
},
NIO: {
displayName: "Córdoba nicaraguano",
"displayName-count-one": "Córdoba nicaraguano",
"displayName-count-other": "Córdoba nicaraguano",
symbol: "NIO",
"symbol-alt-narrow": "C$"
},
NLG: {
displayName: "Florim holandês",
"displayName-count-one": "Florim holandês",
"displayName-count-other": "Florins holandeses",
symbol: "NLG"
},
NOK: {
displayName: "Coroa norueguesa",
"displayName-count-one": "Coroa norueguesa",
"displayName-count-other": "Coroas norueguesas",
symbol: "NOK",
"symbol-alt-narrow": "kr"
},
NPR: {
displayName: "Rupia nepalesa",
"displayName-count-one": "Rupia nepalesa",
"displayName-count-other": "Rupias nepalesas",
symbol: "NPR",
"symbol-alt-narrow": "Rs"
},
NZD: {
displayName: "Dólar neozelandês",
"displayName-count-one": "Dólar neozelandês",
"displayName-count-other": "Dólares neozelandeses",
symbol: "NZ$",
"symbol-alt-narrow": "$"
},
OMR: {
displayName: "Rial de Omã",
"displayName-count-one": "Rial de Omã",
"displayName-count-other": "Riais de Omã",
symbol: "OMR"
},
PAB: {
displayName: "Balboa do Panamá",
"displayName-count-one": "Balboa do Panamá",
"displayName-count-other": "Balboas do Panamá",
symbol: "PAB"
},
PEI: {
displayName: "Inti peruano",
"displayName-count-one": "Inti peruano",
"displayName-count-other": "Intis peruanos",
symbol: "PEI"
},
PEN: {
displayName: "Sol peruano",
"displayName-count-one": "Sol peruano",
"displayName-count-other": "Soles peruanos",
symbol: "PEN"
},
PES: {
displayName: "Sol peruano (1863–1965)",
"displayName-count-one": "Sol peruano (1863–1965)",
"displayName-count-other": "Soles peruanos (1863–1965)",
symbol: "PES"
},
PGK: {
displayName: "Kina da Papua-Nova Guiné",
"displayName-count-one": "Kina da Papua-Nova Guiné",
"displayName-count-other": "Kinas da Papua-Nova Guiné",
symbol: "PGK"
},
PHP: {
displayName: "Peso filipino",
"displayName-count-one": "Peso filipino",
"displayName-count-other": "Pesos filipinos",
symbol: "PHP",
"symbol-alt-narrow": "₱"
},
PKR: {
displayName: "Rupia paquistanesa",
"displayName-count-one": "Rupia paquistanesa",
"displayName-count-other": "Rupias paquistanesas",
symbol: "PKR",
"symbol-alt-narrow": "Rs"
},
PLN: {
displayName: "Zloti polaco",
"displayName-count-one": "Zloti polaco",
"displayName-count-other": "Zlotis polacos",
symbol: "PLN",
"symbol-alt-narrow": "zł"
},
PLZ: {
displayName: "Zloti polonês (1950–1995)",
"displayName-count-one": "Zloti polonês (1950–1995)",
"displayName-count-other": "Zlotis poloneses (1950–1995)",
symbol: "PLZ"
},
PTE: {
displayName: "Escudo português",
"displayName-count-one": "Escudo português",
"displayName-count-other": "Escudos portugueses",
symbol: "",
decimal: "$",
group: ","
},
PYG: {
displayName: "Guarani paraguaio",
"displayName-count-one": "Guarani paraguaio",
"displayName-count-other": "Guaranis paraguaios",
symbol: "PYG",
"symbol-alt-narrow": "₲"
},
QAR: {
displayName: "Rial do Catar",
"displayName-count-one": "Rial do Catar",
"displayName-count-other": "Riais do Catar",
symbol: "QAR"
},
RHD: {
displayName: "Dólar rodesiano",
"displayName-count-one": "Dólar da Rodésia",
"displayName-count-other": "Dólares da Rodésia",
symbol: "RHD"
},
ROL: {
displayName: "Leu romeno (1952–2006)",
"displayName-count-one": "Leu antigo da Romênia",
"displayName-count-other": "Leus antigos da Romênia",
symbol: "ROL"
},
RON: {
displayName: "Leu romeno",
"displayName-count-one": "Leu romeno",
"displayName-count-other": "Lei romenos",
symbol: "RON",
"symbol-alt-narrow": "L"
},
RSD: {
displayName: "Dinar sérvio",
"displayName-count-one": "Dinar sérvio",
"displayName-count-other": "Dinares sérvios",
symbol: "RSD"
},
RUB: {
displayName: "Rublo russo",
"displayName-count-one": "Rublo russo",
"displayName-count-other": "Rublos russos",
symbol: "RUB",
"symbol-alt-narrow": "₽"
},
RUR: {
displayName: "Rublo russo (1991–1998)",
"displayName-count-one": "Rublo russo (1991–1998)",
"displayName-count-other": "Rublos russos (1991–1998)",
symbol: "RUR",
"symbol-alt-narrow": "р."
},
RWF: {
displayName: "Franco ruandês",
"displayName-count-one": "Franco ruandês",
"displayName-count-other": "Francos ruandeses",
symbol: "RWF",
"symbol-alt-narrow": "RF"
},
SAR: {
displayName: "Rial saudita",
"displayName-count-one": "Rial saudita",
"displayName-count-other": "Riais sauditas",
symbol: "SAR"
},
SBD: {
displayName: "Dólar das Ilhas Salomão",
"displayName-count-one": "Dólar das Ilhas Salomão",
"displayName-count-other": "Dólares das Ilhas Salomão",
symbol: "SBD",
"symbol-alt-narrow": "$"
},
SCR: {
displayName: "Rupia seichelense",
"displayName-count-one": "Rupia seichelense",
"displayName-count-other": "Rupias seichelenses",
symbol: "SCR"
},
SDD: {
displayName: "Dinar sudanês (1992–2007)",
"displayName-count-one": "Dinar antigo do Sudão",
"displayName-count-other": "Dinares antigos do Sudão",
symbol: "SDD"
},
SDG: {
displayName: "Libra sudanesa",
"displayName-count-one": "Libra sudanesa",
"displayName-count-other": "Libras sudanesas",
symbol: "SDG"
},
SDP: {
displayName: "Libra sudanesa (1957–1998)",
"displayName-count-one": "Libra antiga sudanesa",
"displayName-count-other": "Libras antigas sudanesas",
symbol: "SDP"
},
SEK: {
displayName: "Coroa sueca",
"displayName-count-one": "Coroa sueca",
"displayName-count-other": "Coroas suecas",
symbol: "SEK",
"symbol-alt-narrow": "kr"
},
SGD: {
displayName: "Dólar de Singapura",
"displayName-count-one": "Dólar de Singapura",
"displayName-count-other": "Dólares de Singapura",
symbol: "SGD",
"symbol-alt-narrow": "$"
},
SHP: {
displayName: "Libra de Santa Helena",
"displayName-count-one": "Libra de Santa Helena",
"displayName-count-other": "Libras de Santa Helena",
symbol: "SHP",
"symbol-alt-narrow": "£"
},
SIT: {
displayName: "Tolar Bons esloveno",
"displayName-count-one": "Tolar da Eslovênia",
"displayName-count-other": "Tolares da Eslovênia",
symbol: "SIT"
},
SKK: {
displayName: "Coroa eslovaca",
"displayName-count-one": "Coroa eslovaca",
"displayName-count-other": "Coroas eslovacas",
symbol: "SKK"
},
SLL: {
displayName: "Leone de Serra Leoa",
"displayName-count-one": "Leone de Serra Leoa",
"displayName-count-other": "Leones de Serra Leoa",
symbol: "SLL"
},
SOS: {
displayName: "Xelim somali",
"displayName-count-one": "Xelim somali",
"displayName-count-other": "Xelins somalis",
symbol: "SOS"
},
SRD: {
displayName: "Dólar do Suriname",
"displayName-count-one": "Dólar do Suriname",
"displayName-count-other": "Dólares do Suriname",
symbol: "SRD",
"symbol-alt-narrow": "$"
},
SRG: {
displayName: "Florim do Suriname",
"displayName-count-one": "Florim do Suriname",
"displayName-count-other": "Florins do Suriname",
symbol: "SRG"
},
SSP: {
displayName: "Libra sul-sudanesa",
"displayName-count-one": "Libra sul-sudanesa",
"displayName-count-other": "Libras sul-sudanesas",
symbol: "SSP",
"symbol-alt-narrow": "£"
},
STD: {
displayName: "Dobra de São Tomé e Príncipe",
"displayName-count-one": "Dobra de São Tomé e Príncipe",
"displayName-count-other": "Dobras de São Tomé e Príncipe",
symbol: "STD",
"symbol-alt-narrow": "Db"
},
SUR: {
displayName: "Rublo soviético",
"displayName-count-one": "Rublo soviético",
"displayName-count-other": "Rublos soviéticos",
symbol: "SUR"
},
SVC: {
displayName: "Colom salvadorenho",
"displayName-count-one": "Colon de El Salvador",
"displayName-count-other": "Colons de El Salvador",
symbol: "SVC"
},
SYP: {
displayName: "Libra síria",
"displayName-count-one": "Libra síria",
"displayName-count-other": "Libras sírias",
symbol: "SYP",
"symbol-alt-narrow": "£"
},
SZL: {
displayName: "Lilangeni da Suazilândia",
"displayName-count-one": "Lilangeni da Suazilândia",
"displayName-count-other": "Lilangenis da Suazilândia",
symbol: "SZL"
},
THB: {
displayName: "Baht da Tailândia",
"displayName-count-one": "Baht da Tailândia",
"displayName-count-other": "Bahts da Tailândia",
symbol: "฿",
"symbol-alt-narrow": "฿"
},
TJR: {
displayName: "Rublo do Tadjiquistão",
"displayName-count-one": "Rublo do Tajaquistão",
"displayName-count-other": "Rublos do Tajaquistão",
symbol: "TJR"
},
TJS: {
displayName: "Somoni do Tajaquistão",
"displayName-count-one": "Somoni do Tajaquistão",
"displayName-count-other": "Somonis do Tajaquistão",
symbol: "TJS"
},
TMM: {
displayName: "Manat do Turcomenistão (1993–2009)",
"displayName-count-one": "Manat do Turcomenistão (1993–2009)",
"displayName-count-other": "Manats do Turcomenistão (1993–2009)",
symbol: "TMM"
},
TMT: {
displayName: "Manat do Turquemenistão",
"displayName-count-one": "Manat do Turquemenistão",
"displayName-count-other": "Manats do Turquemenistão",
symbol: "TMT"
},
TND: {
displayName: "Dinar tunisino",
"displayName-count-one": "Dinar tunisino",
"displayName-count-other": "Dinares tunisinos",
symbol: "TND"
},
TOP: {
displayName: "Paʻanga de Tonga",
"displayName-count-one": "Paʻanga de Tonga",
"displayName-count-other": "Paʻangas de Tonga",
symbol: "TOP",
"symbol-alt-narrow": "T$"
},
TPE: {
displayName: "Escudo timorense",
"displayName-count-one": "Escudo do Timor",
"displayName-count-other": "Escudos do Timor",
symbol: "TPE"
},
TRL: {
displayName: "Lira turca (1922–2005)",
"displayName-count-one": "Lira turca antiga",
"displayName-count-other": "Liras turcas antigas",
symbol: "TRL"
},
TRY: {
displayName: "Lira turca",
"displayName-count-one": "Lira turca",
"displayName-count-other": "Liras turcas",
symbol: "TRY",
"symbol-alt-narrow": "₺",
"symbol-alt-variant": "TL"
},
TTD: {
displayName: "Dólar de Trindade e Tobago",
"displayName-count-one": "Dólar de Trindade e Tobago",
"displayName-count-other": "Dólares de Trindade e Tobago",
symbol: "TTD",
"symbol-alt-narrow": "$"
},
TWD: {
displayName: "Novo dólar taiwanês",
"displayName-count-one": "Novo dólar taiwanês",
"displayName-count-other": "Novos dólares taiwaneses",
symbol: "NT$",
"symbol-alt-narrow": "NT$"
},
TZS: {
displayName: "Xelim tanzaniano",
"displayName-count-one": "Xelim tanzaniano",
"displayName-count-other": "Xelins tanzanianos",
symbol: "TZS"
},
UAH: {
displayName: "Hryvnia da Ucrânia",
"displayName-count-one": "Hryvnia da Ucrânia",
"displayName-count-other": "Hryvnias da Ucrânia",
symbol: "UAH",
"symbol-alt-narrow": "₴"
},
UAK: {
displayName: "Karbovanetz ucraniano",
"displayName-count-one": "Karbovanetz da Ucrânia",
"displayName-count-other": "Karbovanetzs da Ucrânia",
symbol: "UAK"
},
UGS: {
displayName: "Xelim ugandense (1966–1987)",
"displayName-count-one": "Shilling de Uganda (1966–1987)",
"displayName-count-other": "Shillings de Uganda (1966–1987)",
symbol: "UGS"
},
UGX: {
displayName: "Xelim ugandense",
"displayName-count-one": "Xelim ugandense",
"displayName-count-other": "Xelins ugandenses",
symbol: "UGX"
},
USD: {
displayName: "Dólar dos Estados Unidos",
"displayName-count-one": "Dólar dos Estados Unidos",
"displayName-count-other": "Dólares dos Estados Unidos",
symbol: "US$",
"symbol-alt-narrow": "$"
},
USN: {
displayName: "Dólar norte-americano (Dia seguinte)",
"displayName-count-one": "Dólar americano (dia seguinte)",
"displayName-count-other": "Dólares americanos (dia seguinte)",
symbol: "USN"
},
USS: {
displayName: "Dólar norte-americano (Mesmo dia)",
"displayName-count-one": "Dólar americano (mesmo dia)",
"displayName-count-other": "Dólares americanos (mesmo dia)",
symbol: "USS"
},
UYI: {
displayName: "Peso uruguaio en unidades indexadas",
"displayName-count-one": "Peso uruguaio em unidades indexadas",
"displayName-count-other": "Pesos uruguaios em unidades indexadas",
symbol: "UYI"
},
UYP: {
displayName: "Peso uruguaio (1975–1993)",
"displayName-count-one": "Peso uruguaio (1975–1993)",
"displayName-count-other": "Pesos uruguaios (1975–1993)",
symbol: "UYP"
},
UYU: {
displayName: "Peso uruguaio",
"displayName-count-one": "Peso uruguaio",
"displayName-count-other": "Pesos uruguaios",
symbol: "UYU",
"symbol-alt-narrow": "$"
},
UZS: {
displayName: "Som do Uzbequistão",
"displayName-count-one": "Som do Uzbequistão",
"displayName-count-other": "Sons do Uzbequistão",
symbol: "UZS"
},
VEB: {
displayName: "Bolívar venezuelano (1871–2008)",
"displayName-count-one": "Bolívar venezuelano (1871–2008)",
"displayName-count-other": "Bolívares venezuelanos (1871–2008)",
symbol: "VEB"
},
VEF: {
displayName: "Bolívar venezuelano",
"displayName-count-one": "Bolívar venezuelano",
"displayName-count-other": "Bolívares venezuelanos",
symbol: "VEF",
"symbol-alt-narrow": "Bs"
},
VND: {
displayName: "Dong vietnamita",
"displayName-count-one": "Dong vietnamita",
"displayName-count-other": "Dongs vietnamitas",
symbol: "₫",
"symbol-alt-narrow": "₫"
},
VNN: {
displayName: "Dong vietnamita (1978–1985)",
"displayName-count-one": "Dong vietnamita (1978–1985)",
"displayName-count-other": "Dong vietnamita (1978–1985)",
symbol: "VNN"
},
VUV: {
displayName: "Vatu de Vanuatu",
"displayName-count-one": "Vatu de Vanuatu",
"displayName-count-other": "Vatus de Vanuatu",
symbol: "VUV"
},
WST: {
displayName: "Tala samoano",
"displayName-count-one": "Tala samoano",
"displayName-count-other": "Talas samoanos",
symbol: "WST"
},
XAF: {
displayName: "Franco CFA (BEAC)",
"displayName-count-one": "Franco CFA (BEAC)",
"displayName-count-other": "Francos CFA (BEAC)",
symbol: "FCFA"
},
XAG: {
displayName: "Prata",
"displayName-count-one": "Prata",
"displayName-count-other": "Pratas",
symbol: "XAG"
},
XAU: {
displayName: "Ouro",
"displayName-count-one": "Ouro",
"displayName-count-other": "Ouros",
symbol: "XAU"
},
XBA: {
displayName: "Unidade Composta Europeia",
"displayName-count-one": "Unidade de composição europeia",
"displayName-count-other": "Unidades de composição europeias",
symbol: "XBA"
},
XBB: {
displayName: "Unidade Monetária Europeia",
"displayName-count-one": "Unidade monetária europeia",
"displayName-count-other": "Unidades monetárias europeias",
symbol: "XBB"
},
XBC: {
displayName: "Unidade de Conta Europeia (XBC)",
"displayName-count-one": "Unidade europeia de conta (XBC)",
"displayName-count-other": "Unidades europeias de conta (XBC)",
symbol: "XBC"
},
XBD: {
displayName: "Unidade de Conta Europeia (XBD)",
"displayName-count-one": "Unidade europeia de conta (XBD)",
"displayName-count-other": "Unidades europeias de conta (XBD)",
symbol: "XBD"
},
XCD: {
displayName: "Dólar das Caraíbas Orientais",
"displayName-count-one": "Dólar das Caraíbas Orientais",
"displayName-count-other": "Dólares das Caraíbas Orientais",
symbol: "EC$",
"symbol-alt-narrow": "$"
},
XDR: {
displayName: "Direitos Especiais de Giro",
"displayName-count-one": "Direitos de desenho especiais",
"displayName-count-other": "Direitos de desenho especiais",
symbol: "XDR"
},
XEU: {
displayName: "Unidade de Moeda Europeia",
"displayName-count-one": "Unidade de moeda europeia",
"displayName-count-other": "Unidades de moedas europeias",
symbol: "XEU"
},
XFO: {
displayName: "Franco-ouro francês",
"displayName-count-one": "Franco de ouro francês",
"displayName-count-other": "Francos de ouro franceses",
symbol: "XFO"
},
XFU: {
displayName: "Franco UIC francês",
"displayName-count-one": "Franco UIC francês",
"displayName-count-other": "Francos UIC franceses",
symbol: "XFU"
},
XOF: {
displayName: "Franco CFA (BCEAO)",
"displayName-count-one": "Franco CFA (BCEAO)",
"displayName-count-other": "Francos CFA (BCEAO)",
symbol: "CFA"
},
XPD: {
displayName: "Paládio",
"displayName-count-one": "Paládio",
"displayName-count-other": "Paládios",
symbol: "XPD"
},
XPF: {
displayName: "Franco CFP",
"displayName-count-one": "Franco CFP",
"displayName-count-other": "Francos CFP",
symbol: "CFPF"
},
XPT: {
displayName: "Platina",
"displayName-count-one": "Platina",
"displayName-count-other": "Platinas",
symbol: "XPT"
},
XRE: {
displayName: "Fundos RINET",
"displayName-count-one": "Fundos RINET",
"displayName-count-other": "Fundos RINET",
symbol: "XRE"
},
XSU: {
displayName: "XSU",
symbol: "XSU"
},
XTS: {
displayName: "Código de Moeda de Teste",
"displayName-count-one": "Código de moeda de teste",
"displayName-count-other": "Códigos de moeda de teste",
symbol: "XTS"
},
XUA: {
displayName: "XUA",
symbol: "XUA"
},
XXX: {
displayName: "Moeda desconhecida",
"displayName-count-one": "(moeda desconhecida)",
"displayName-count-other": "(moedas desconhecidas)",
symbol: "XXX"
},
YDD: {
displayName: "Dinar iemenita",
"displayName-count-one": "Dinar do Iêmen",
"displayName-count-other": "Dinares do Iêmen",
symbol: "YDD"
},
YER: {
displayName: "Rial iemenita",
"displayName-count-one": "Rial iemenita",
"displayName-count-other": "Riais iemenitas",
symbol: "YER"
},
YUD: {
displayName: "Dinar forte iugoslavo (1966–1990)",
"displayName-count-one": "Dinar forte iugoslavo",
"displayName-count-other": "Dinares fortes iugoslavos",
symbol: "YUD"
},
YUM: {
displayName: "Dinar noviy iugoslavo (1994–2002)",
"displayName-count-one": "Dinar noviy da Iugoslávia",
"displayName-count-other": "Dinares noviy da Iugoslávia",
symbol: "YUM"
},
YUN: {
displayName: "Dinar conversível iugoslavo (1990–1992)",
"displayName-count-one": "Dinar conversível da Iugoslávia",
"displayName-count-other": "Dinares conversíveis da Iugoslávia",
symbol: "YUN"
},
YUR: {
displayName: "Dinar reformado iugoslavo (1992–1993)",
"displayName-count-one": "Dinar iugoslavo reformado",
"displayName-count-other": "Dinares iugoslavos reformados",
symbol: "YUR"
},
ZAL: {
displayName: "Rand sul-africano (financeiro)",
"displayName-count-one": "Rand da África do Sul (financeiro)",
"displayName-count-other": "Rands da África do Sul (financeiro)",
symbol: "ZAL"
},
ZAR: {
displayName: "Rand sul-africano",
"displayName-count-one": "Rand sul-africano",
"displayName-count-other": "Rands sul-africanos",
symbol: "ZAR",
"symbol-alt-narrow": "R"
},
ZMK: {
displayName: "Kwacha zambiano (1968–2012)",
"displayName-count-one": "Kwacha zambiano (1968–2012)",
"displayName-count-other": "Kwachas zambianos (1968–2012)",
symbol: "ZMK"
},
ZMW: {
displayName: "Kwacha zambiano",
"displayName-count-one": "Kwacha zambiano",
"displayName-count-other": "Kwachas zambianos",
symbol: "ZMW",
"symbol-alt-narrow": "ZK"
},
ZRN: {
displayName: "Zaire Novo zairense (1993–1998)",
"displayName-count-one": "Novo zaire do Zaire",
"displayName-count-other": "Novos zaires do Zaire",
symbol: "ZRN"
},
ZRZ: {
displayName: "Zaire zairense (1971–1993)",
"displayName-count-one": "Zaire do Zaire",
"displayName-count-other": "Zaires do Zaire",
symbol: "ZRZ"
},
ZWD: {
displayName: "Dólar do Zimbábue (1980–2008)",
"displayName-count-one": "Dólar do Zimbábue",
"displayName-count-other": "Dólares do Zimbábue",
symbol: "ZWD"
},
ZWL: {
displayName: "Dólar do Zimbábue (2009)",
"displayName-count-one": "Dólar do Zimbábue (2009)",
"displayName-count-other": "Dólares do Zimbábue (2009)",
symbol: "ZWL"
},
ZWR: {
displayName: "Dólar do Zimbábue (2008)",
"displayName-count-one": "Dólar do Zimbábue (2008)",
"displayName-count-other": "Dólares do Zimbábue (2008)",
symbol: "ZWR"
}
},
localeCurrency: "CHF"
},
calendar: {
patterns: {
d: "dd/MM/y",
D: "EEEE, d 'de' MMMM 'de' y",
m: "d/MM",
M: "d 'de' MMMM",
y: "MM/y",
Y: "MMMM 'de' y",
F: "EEEE, d 'de' MMMM 'de' y HH:mm:ss",
g: "dd/MM/y HH:mm",
G: "dd/MM/y HH:mm:ss",
t: "HH:mm",
T: "HH:mm:ss",
s: "yyyy'-'MM'-'dd'T'HH':'mm':'ss",
u: "yyyy'-'MM'-'dd HH':'mm':'ss'Z'"
},
dateTimeFormats: {
full: "{1} 'às' {0}",
long: "{1} 'às' {0}",
medium: "{1}, {0}",
short: "{1}, {0}",
availableFormats: {
d: "d",
E: "ccc",
Ed: "E, d",
Ehm: "E, h:mm a",
EHm: "E, HH:mm",
Ehms: "E, h:mm:ss a",
EHms: "E, HH:mm:ss",
Gy: "y G",
GyMMM: "MMM 'de' y G",
GyMMMd: "d 'de' MMM 'de' y G",
GyMMMEd: "E, d 'de' MMM 'de' y G",
h: "h a",
H: "HH",
hm: "h:mm a",
Hm: "HH:mm",
hms: "h:mm:ss a",
Hms: "HH:mm:ss",
hmsv: "h:mm:ss a v",
Hmsv: "HH:mm:ss v",
hmv: "h:mm a v",
Hmv: "HH:mm v",
M: "L",
Md: "dd/MM",
MEd: "E, dd/MM",
MMdd: "dd/MM",
MMM: "LLL",
MMMd: "d/MM",
MMMEd: "E, d/MM",
MMMMd: "d 'de' MMMM",
MMMMEd: "ccc, d 'de' MMMM",
"MMMMW-count-one": "W.'ª' 'semana' 'de' MMM",
"MMMMW-count-other": "W.'ª' 'semana' 'de' MMM",
ms: "mm:ss",
y: "y",
yM: "MM/y",
yMd: "dd/MM/y",
yMEd: "E, dd/MM/y",
yMM: "MM/y",
yMMM: "MM/y",
yMMMd: "d/MM/y",
yMMMEd: "E, d/MM/y",
yMMMEEEEd: "EEEE, d/MM/y",
yMMMM: "MMMM 'de' y",
yMMMMd: "d 'de' MMMM 'de' y",
yMMMMEd: "ccc, d 'de' MMMM 'de' y",
yQQQ: "QQQQ 'de' y",
yQQQQ: "QQQQ 'de' y",
"yw-count-one": "w.'ª' 'semana' 'de' y",
"yw-count-other": "w.'ª' 'semana' 'de' y"
}
},
timeFormats: {
full: "HH:mm:ss zzzz",
long: "HH:mm:ss z",
medium: "HH:mm:ss",
short: "HH:mm"
},
dateFormats: {
full: "EEEE, d 'de' MMMM 'de' y",
long: "d 'de' MMMM 'de' y",
medium: "dd/MM/y",
short: "dd/MM/yy"
},
days: {
format: {
abbreviated: [
"domingo",
"segunda",
"terça",
"quarta",
"quinta",
"sexta",
"sábado"
],
narrow: [
"D",
"S",
"T",
"Q",
"Q",
"S",
"S"
],
short: [
"dom",
"seg",
"ter",
"qua",
"qui",
"sex",
"sáb"
],
wide: [
"domingo",
"segunda-feira",
"terça-feira",
"quarta-feira",
"quinta-feira",
"sexta-feira",
"sábado"
]
},
"stand-alone": {
abbreviated: [
"domingo",
"segunda",
"terça",
"quarta",
"quinta",
"sexta",
"sábado"
],
narrow: [
"D",
"S",
"T",
"Q",
"Q",
"S",
"S"
],
short: [
"dom",
"seg",
"ter",
"qua",
"qui",
"sex",
"sáb"
],
wide: [
"domingo",
"segunda-feira",
"terça-feira",
"quarta-feira",
"quinta-feira",
"sexta-feira",
"sábado"
]
}
},
months: {
format: {
abbreviated: [
"jan",
"fev",
"mar",
"abr",
"mai",
"jun",
"jul",
"ago",
"set",
"out",
"nov",
"dez"
],
narrow: [
"J",
"F",
"M",
"A",
"M",
"J",
"J",
"A",
"S",
"O",
"N",
"D"
],
wide: [
"janeiro",
"fevereiro",
"março",
"abril",
"maio",
"junho",
"julho",
"agosto",
"setembro",
"outubro",
"novembro",
"dezembro"
]
},
"stand-alone": {
abbreviated: [
"jan",
"fev",
"mar",
"abr",
"mai",
"jun",
"jul",
"ago",
"set",
"out",
"nov",
"dez"
],
narrow: [
"J",
"F",
"M",
"A",
"M",
"J",
"J",
"A",
"S",
"O",
"N",
"D"
],
wide: [
"janeiro",
"fevereiro",
"março",
"abril",
"maio",
"junho",
"julho",
"agosto",
"setembro",
"outubro",
"novembro",
"dezembro"
]
}
},
quarters: {
format: {
abbreviated: [
"T1",
"T2",
"T3",
"T4"
],
narrow: [
"1",
"2",
"3",
"4"
],
wide: [
"1.º trimestre",
"2.º trimestre",
"3.º trimestre",
"4.º trimestre"
]
},
"stand-alone": {
abbreviated: [
"T1",
"T2",
"T3",
"T4"
],
narrow: [
"1",
"2",
"3",
"4"
],
wide: [
"1.º trimestre",
"2.º trimestre",
"3.º trimestre",
"4.º trimestre"
]
}
},
dayPeriods: {
format: {
abbreviated: {
midnight: "meia-noite",
am: "a.m.",
noon: "meio-dia",
pm: "p.m.",
morning1: "da manhã",
afternoon1: "da tarde",
evening1: "da noite",
night1: "da madrugada"
},
narrow: {
midnight: "meia-noite",
am: "a.m.",
noon: "meio-dia",
pm: "p.m.",
morning1: "manhã",
afternoon1: "tarde",
evening1: "noite",
night1: "madrugada"
},
wide: {
midnight: "meia-noite",
am: "da manhã",
noon: "meio-dia",
pm: "da tarde",
morning1: "da manhã",
afternoon1: "da tarde",
evening1: "da noite",
night1: "da madrugada"
}
},
"stand-alone": {
abbreviated: {
midnight: "meia-noite",
am: "a.m.",
noon: "meio-dia",
pm: "p.m.",
morning1: "manhã",
afternoon1: "tarde",
evening1: "noite",
night1: "madrugada"
},
narrow: {
midnight: "meia-noite",
am: "a.m.",
noon: "meio-dia",
pm: "p.m.",
morning1: "manhã",
afternoon1: "tarde",
evening1: "noite",
night1: "madrugada"
},
wide: {
midnight: "meia-noite",
am: "manhã",
noon: "meio-dia",
pm: "tarde",
morning1: "manhã",
afternoon1: "tarde",
evening1: "noite",
night1: "madrugada"
}
}
},
eras: {
format: {
wide: {
0: "antes de Cristo",
1: "depois de Cristo",
"0-alt-variant": "antes da Era Comum",
"1-alt-variant": "Era Comum"
},
abbreviated: {
0: "a.C.",
1: "d.C.",
"0-alt-variant": "a.E.C.",
"1-alt-variant": "E.C."
},
narrow: {
0: "a.C.",
1: "d.C.",
"0-alt-variant": "a.E.C.",
"1-alt-variant": "E.C."
}
}
},
gmtFormat: "GMT{0}",
gmtZeroFormat: "GMT",
dateFields: {
era: {
wide: "era",
short: "era",
narrow: "era"
},
year: {
wide: "ano",
short: "ano",
narrow: "ano"
},
quarter: {
wide: "trimestre",
short: "trim.",
narrow: "trim."
},
month: {
wide: "mês",
short: "mês",
narrow: "mês"
},
week: {
wide: "semana",
short: "sem.",
narrow: "sem."
},
weekOfMonth: {
wide: "Week Of Month",
short: "Week Of Month",
narrow: "Week Of Month"
},
day: {
wide: "dia",
short: "dia",
narrow: "dia"
},
dayOfYear: {
wide: "Day Of Year",
short: "Day Of Year",
narrow: "Day Of Year"
},
weekday: {
wide: "dia da semana",
short: "dia da semana",
narrow: "dia da semana"
},
weekdayOfMonth: {
wide: "Weekday Of Month",
short: "Weekday Of Month",
narrow: "Weekday Of Month"
},
dayperiod: {
short: "AM/PM",
wide: "AM/PM",
narrow: "AM/PM"
},
hour: {
wide: "hora",
short: "h",
narrow: "h"
},
minute: {
wide: "minuto",
short: "min",
narrow: "min"
},
second: {
wide: "segundo",
short: "s",
narrow: "s"
},
zone: {
wide: "fuso horário",
short: "fuso horário",
narrow: "fuso horário"
}
}
},
firstDay: 1,
likelySubtags: {
pt: "pt-Latn-BR"
}
});
| antpost/antpost-client | node_modules/@progress/kendo-angular-intl/locales/pt-CH/all.js | JavaScript | mit | 93,114 |
using System;
using System.Collections.Generic;
using System.Linq.Expressions;
using System.Web.Mvc;
using VsixMvcAppResult.Models;
using VsixMvcAppResult.Models.Common;
using VsixMvcAppResult.Models.Membership;
using VsixMvcAppResult.UI.Web.Controllers;
using VsixMvcAppResult.UI.Web.Models;
namespace VsixMvcAppResult.UI.Web.Areas.UserAdministration.Models
{
public class DetailsViewModel : baseViewModel
{
public DetailsViewModel()
{
}
public MembershipUserWrapper UserOriginal { get; set; }
public MembershipUserWrapper UserUpdated { get; set; }
public IEnumerable<string> UserRoles { get; set; }
public IEnumerable<string> Roles { get; set; }
public DataResultBoolean ResultLastAction { get; set; }
}
public class DetailsViewModelBinder : DefaultModelBinder
{
public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
DetailsViewModel o = (DetailsViewModel)base.BindModel(controllerContext, bindingContext);
if (ControllerHelper.RequestType(controllerContext) == HttpVerbs.Post)
{
Expression<Func<DetailsViewModel, MembershipUserWrapper>> expression = m => ((DetailsViewModel)bindingContext.Model).UserOriginal;
string expressionText = ExpressionHelper.GetExpressionText(expression);
string jsonUserDetails = bindingContext.ValueProvider.GetValue(expressionText).AttemptedValue;
o.UserOriginal = baseModel.DeserializeFromJson<MembershipUserWrapper>(jsonUserDetails);
}
return o;
}
}
} | jordivila/Net_MVC_NLayer_Result | VsixMvcAppResult/VsixMvcAppResult.UI.Web/Areas/UserAdministration/Models/DetailsViewModel.cs | C# | mit | 1,727 |
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as nls from 'vs/nls';
import * as Objects from 'vs/base/common/objects';
import { IStringDictionary } from 'vs/base/common/collections';
import { Platform } from 'vs/base/common/platform';
import * as Types from 'vs/base/common/types';
import * as UUID from 'vs/base/common/uuid';
import { ValidationStatus, IProblemReporter as IProblemReporterBase } from 'vs/base/common/parsers';
import {
NamedProblemMatcher, ProblemMatcher, ProblemMatcherParser, Config as ProblemMatcherConfig,
isNamedProblemMatcher, ProblemMatcherRegistry
} from 'vs/workbench/parts/tasks/common/problemMatcher';
import { IWorkspaceFolder } from 'vs/platform/workspace/common/workspace';
import * as Tasks from '../common/tasks';
import { TaskDefinitionRegistry } from '../common/taskDefinitionRegistry';
import { TaskDefinition } from 'vs/workbench/parts/tasks/node/tasks';
import { ConfiguredInput } from 'vs/workbench/services/configurationResolver/common/configurationResolver';
export const enum ShellQuoting {
/**
* Default is character escaping.
*/
escape = 1,
/**
* Default is strong quoting
*/
strong = 2,
/**
* Default is weak quoting.
*/
weak = 3
}
export interface ShellQuotingOptions {
/**
* The character used to do character escaping.
*/
escape?: string | {
escapeChar: string;
charsToEscape: string;
};
/**
* The character used for string quoting.
*/
strong?: string;
/**
* The character used for weak quoting.
*/
weak?: string;
}
export interface ShellConfiguration {
executable?: string;
args?: string[];
quoting?: ShellQuotingOptions;
}
export interface CommandOptionsConfig {
/**
* The current working directory of the executed program or shell.
* If omitted VSCode's current workspace root is used.
*/
cwd?: string;
/**
* The additional environment of the executed program or shell. If omitted
* the parent process' environment is used.
*/
env?: IStringDictionary<string>;
/**
* The shell configuration;
*/
shell?: ShellConfiguration;
}
export interface PresentationOptionsConfig {
/**
* Controls whether the terminal executing a task is brought to front or not.
* Defaults to `RevealKind.Always`.
*/
reveal?: string;
/**
* Controls whether the executed command is printed to the output window or terminal as well.
*/
echo?: boolean;
/**
* Controls whether the terminal is focus when this task is executed
*/
focus?: boolean;
/**
* Controls whether the task runs in a new terminal
*/
panel?: string;
/**
* Controls whether to show the "Terminal will be reused by tasks, press any key to close it" message.
*/
showReuseMessage?: boolean;
/**
* Controls whether the terminal should be cleared before running the task.
*/
clear?: boolean;
/**
* Controls whether the task is executed in a specific terminal group using split panes.
*/
group?: string;
}
export interface RunOptionsConfig {
reevaluateOnRerun?: boolean;
runOn?: string;
}
export interface TaskIdentifier {
type?: string;
[name: string]: any;
}
export namespace TaskIdentifier {
export function is(value: any): value is TaskIdentifier {
let candidate: TaskIdentifier = value;
return candidate !== undefined && Types.isString(value.type);
}
}
export interface LegacyTaskProperties {
/**
* @deprecated Use `isBackground` instead.
* Whether the executed command is kept alive and is watching the file system.
*/
isWatching?: boolean;
/**
* @deprecated Use `group` instead.
* Whether this task maps to the default build command.
*/
isBuildCommand?: boolean;
/**
* @deprecated Use `group` instead.
* Whether this task maps to the default test command.
*/
isTestCommand?: boolean;
}
export interface LegacyCommandProperties {
/**
* Whether this is a shell or process
*/
type?: string;
/**
* @deprecated Use presentation options
* Controls whether the output view of the running tasks is brought to front or not.
* See BaseTaskRunnerConfiguration#showOutput for details.
*/
showOutput?: string;
/**
* @deprecated Use presentation options
* Controls whether the executed command is printed to the output windows as well.
*/
echoCommand?: boolean;
/**
* @deprecated Use presentation instead
*/
terminal?: PresentationOptionsConfig;
/**
* @deprecated Use inline commands.
* See BaseTaskRunnerConfiguration#suppressTaskName for details.
*/
suppressTaskName?: boolean;
/**
* Some commands require that the task argument is highlighted with a special
* prefix (e.g. /t: for msbuild). This property can be used to control such
* a prefix.
*/
taskSelector?: string;
/**
* @deprecated use the task type instead.
* Specifies whether the command is a shell command and therefore must
* be executed in a shell interpreter (e.g. cmd.exe, bash, ...).
*
* Defaults to false if omitted.
*/
isShellCommand?: boolean | ShellConfiguration;
}
export type CommandString = string | string[] | { value: string | string[], quoting: 'escape' | 'strong' | 'weak' };
export namespace CommandString {
export function value(value: CommandString): string {
if (Types.isString(value)) {
return value;
} else if (Types.isStringArray(value)) {
return value.join(' ');
} else {
if (Types.isString(value.value)) {
return value.value;
} else {
return value.value.join(' ');
}
}
}
}
export interface BaseCommandProperties {
/**
* The command to be executed. Can be an external program or a shell
* command.
*/
command?: CommandString;
/**
* The command options used when the command is executed. Can be omitted.
*/
options?: CommandOptionsConfig;
/**
* The arguments passed to the command or additional arguments passed to the
* command when using a global command.
*/
args?: CommandString[];
}
export interface CommandProperties extends BaseCommandProperties {
/**
* Windows specific command properties
*/
windows?: BaseCommandProperties;
/**
* OSX specific command properties
*/
osx?: BaseCommandProperties;
/**
* linux specific command properties
*/
linux?: BaseCommandProperties;
}
export interface GroupKind {
kind?: string;
isDefault?: boolean;
}
export interface ConfigurationProperties {
/**
* The task's name
*/
taskName?: string;
/**
* The UI label used for the task.
*/
label?: string;
/**
* An optional indentifier which can be used to reference a task
* in a dependsOn or other attributes.
*/
identifier?: string;
/**
* Whether the executed command is kept alive and runs in the background.
*/
isBackground?: boolean;
/**
* Whether the task should prompt on close for confirmation if running.
*/
promptOnClose?: boolean;
/**
* Defines the group the task belongs too.
*/
group?: string | GroupKind;
/**
* The other tasks the task depend on
*/
dependsOn?: string | TaskIdentifier | Array<string | TaskIdentifier>;
/**
* Controls the behavior of the used terminal
*/
presentation?: PresentationOptionsConfig;
/**
* Controls shell options.
*/
options?: CommandOptionsConfig;
/**
* The problem matcher(s) to use to capture problems in the tasks
* output.
*/
problemMatcher?: ProblemMatcherConfig.ProblemMatcherType;
/**
* Task run options. Control run related properties.
*/
runOptions?: RunOptionsConfig;
}
export interface CustomTask extends CommandProperties, ConfigurationProperties {
/**
* Custom tasks have the type CUSTOMIZED_TASK_TYPE
*/
type?: string;
}
export interface ConfiguringTask extends ConfigurationProperties {
/**
* The contributed type of the task
*/
type?: string;
}
/**
* The base task runner configuration
*/
export interface BaseTaskRunnerConfiguration {
/**
* The command to be executed. Can be an external program or a shell
* command.
*/
command?: CommandString;
/**
* @deprecated Use type instead
*
* Specifies whether the command is a shell command and therefore must
* be executed in a shell interpreter (e.g. cmd.exe, bash, ...).
*
* Defaults to false if omitted.
*/
isShellCommand?: boolean;
/**
* The task type
*/
type?: string;
/**
* The command options used when the command is executed. Can be omitted.
*/
options?: CommandOptionsConfig;
/**
* The arguments passed to the command. Can be omitted.
*/
args?: CommandString[];
/**
* Controls whether the output view of the running tasks is brought to front or not.
* Valid values are:
* "always": bring the output window always to front when a task is executed.
* "silent": only bring it to front if no problem matcher is defined for the task executed.
* "never": never bring the output window to front.
*
* If omitted "always" is used.
*/
showOutput?: string;
/**
* Controls whether the executed command is printed to the output windows as well.
*/
echoCommand?: boolean;
/**
* The group
*/
group?: string | GroupKind;
/**
* Controls the behavior of the used terminal
*/
presentation?: PresentationOptionsConfig;
/**
* If set to false the task name is added as an additional argument to the
* command when executed. If set to true the task name is suppressed. If
* omitted false is used.
*/
suppressTaskName?: boolean;
/**
* Some commands require that the task argument is highlighted with a special
* prefix (e.g. /t: for msbuild). This property can be used to control such
* a prefix.
*/
taskSelector?: string;
/**
* The problem matcher(s) to used if a global command is exucuted (e.g. no tasks
* are defined). A tasks.json file can either contain a global problemMatcher
* property or a tasks property but not both.
*/
problemMatcher?: ProblemMatcherConfig.ProblemMatcherType;
/**
* @deprecated Use `isBackground` instead.
*
* Specifies whether a global command is a watching the filesystem. A task.json
* file can either contain a global isWatching property or a tasks property
* but not both.
*/
isWatching?: boolean;
/**
* Specifies whether a global command is a background task.
*/
isBackground?: boolean;
/**
* Whether the task should prompt on close for confirmation if running.
*/
promptOnClose?: boolean;
/**
* The configuration of the available tasks. A tasks.json file can either
* contain a global problemMatcher property or a tasks property but not both.
*/
tasks?: Array<CustomTask | ConfiguringTask>;
/**
* Problem matcher declarations.
*/
declares?: ProblemMatcherConfig.NamedProblemMatcher[];
/**
* Optional user input variables.
*/
inputs?: ConfiguredInput[];
}
/**
* A configuration of an external build system. BuildConfiguration.buildSystem
* must be set to 'program'
*/
export interface ExternalTaskRunnerConfiguration extends BaseTaskRunnerConfiguration {
_runner?: string;
/**
* Determines the runner to use
*/
runner?: string;
/**
* The config's version number
*/
version: string;
/**
* Windows specific task configuration
*/
windows?: BaseTaskRunnerConfiguration;
/**
* Mac specific task configuration
*/
osx?: BaseTaskRunnerConfiguration;
/**
* Linux speciif task configuration
*/
linux?: BaseTaskRunnerConfiguration;
}
enum ProblemMatcherKind {
Unknown,
String,
ProblemMatcher,
Array
}
const EMPTY_ARRAY: any[] = [];
Object.freeze(EMPTY_ARRAY);
function assignProperty<T, K extends keyof T>(target: T, source: Partial<T>, key: K) {
const sourceAtKey = source[key];
if (sourceAtKey !== undefined) {
target[key] = sourceAtKey!;
}
}
function fillProperty<T, K extends keyof T>(target: T, source: Partial<T>, key: K) {
const sourceAtKey = source[key];
if (target[key] === undefined && sourceAtKey !== undefined) {
target[key] = sourceAtKey!;
}
}
interface ParserType<T> {
isEmpty(value: T | undefined): boolean;
assignProperties(target: T | undefined, source: T | undefined): T | undefined;
fillProperties(target: T | undefined, source: T | undefined): T | undefined;
fillDefaults(value: T | undefined, context: ParseContext): T | undefined;
freeze(value: T): Readonly<T> | undefined;
}
interface MetaData<T, U> {
property: keyof T;
type?: ParserType<U>;
}
function _isEmpty<T>(this: void, value: T, properties: MetaData<T, any>[] | undefined): boolean {
if (value === undefined || value === null || properties === undefined) {
return true;
}
for (let meta of properties) {
let property = value[meta.property];
if (property !== undefined && property !== null) {
if (meta.type !== undefined && !meta.type.isEmpty(property)) {
return false;
} else if (!Array.isArray(property) || property.length > 0) {
return false;
}
}
}
return true;
}
function _assignProperties<T>(this: void, target: T, source: T, properties: MetaData<T, any>[]): T {
if (_isEmpty(source, properties)) {
return target;
}
if (_isEmpty(target, properties)) {
return source;
}
for (let meta of properties) {
let property = meta.property;
let value: any;
if (meta.type !== undefined) {
value = meta.type.assignProperties(target[property], source[property]);
} else {
value = source[property];
}
if (value !== undefined && value !== null) {
target[property] = value;
}
}
return target;
}
function _fillProperties<T>(this: void, target: T, source: T, properties: MetaData<T, any>[] | undefined): T {
if (_isEmpty(source, properties)) {
return target;
}
if (_isEmpty(target, properties)) {
return source;
}
for (let meta of properties!) {
let property = meta.property;
let value: any;
if (meta.type) {
value = meta.type.fillProperties(target[property], source[property]);
} else if (target[property] === undefined) {
value = source[property];
}
if (value !== undefined && value !== null) {
target[property] = value;
}
}
return target;
}
function _fillDefaults<T>(this: void, target: T, defaults: T, properties: MetaData<T, any>[], context: ParseContext): T | undefined {
if (target && Object.isFrozen(target)) {
return target;
}
if (target === undefined || target === null) {
if (defaults !== undefined && defaults !== null) {
return Objects.deepClone(defaults);
} else {
return undefined;
}
}
for (let meta of properties) {
let property = meta.property;
if (target[property] !== undefined) {
continue;
}
let value: any;
if (meta.type) {
value = meta.type.fillDefaults(target[property], context);
} else {
value = defaults[property];
}
if (value !== undefined && value !== null) {
target[property] = value;
}
}
return target;
}
function _freeze<T>(this: void, target: T, properties: MetaData<T, any>[]): Readonly<T> | undefined {
if (target === undefined || target === null) {
return undefined;
}
if (Object.isFrozen(target)) {
return target;
}
for (let meta of properties) {
if (meta.type) {
let value = target[meta.property];
if (value) {
meta.type.freeze(value);
}
}
}
Object.freeze(target);
return target;
}
export namespace RunOnOptions {
export function fromString(value: string | undefined): Tasks.RunOnOptions {
if (!value) {
return Tasks.RunOnOptions.default;
}
switch (value.toLowerCase()) {
case 'folderopen':
return Tasks.RunOnOptions.folderOpen;
case 'default':
default:
return Tasks.RunOnOptions.default;
}
}
}
export namespace RunOptions {
export function fromConfiguration(value: RunOptionsConfig | undefined): Tasks.RunOptions {
return {
reevaluateOnRerun: value ? value.reevaluateOnRerun : true,
runOn: value ? RunOnOptions.fromString(value.runOn) : Tasks.RunOnOptions.default
};
}
}
class ParseContext {
workspaceFolder: IWorkspaceFolder;
problemReporter: IProblemReporter;
namedProblemMatchers: IStringDictionary<NamedProblemMatcher>;
uuidMap: UUIDMap;
engine: Tasks.ExecutionEngine;
schemaVersion: Tasks.JsonSchemaVersion;
platform: Platform;
taskLoadIssues: string[];
}
namespace ShellConfiguration {
const properties: MetaData<Tasks.ShellConfiguration, void>[] = [{ property: 'executable' }, { property: 'args' }, { property: 'quoting' }];
export function is(value: any): value is ShellConfiguration {
let candidate: ShellConfiguration = value;
return candidate && (Types.isString(candidate.executable) || Types.isStringArray(candidate.args));
}
export function from(this: void, config: ShellConfiguration | undefined, context: ParseContext): Tasks.ShellConfiguration | undefined {
if (!is(config)) {
return undefined;
}
let result: ShellConfiguration = {};
if (config.executable !== undefined) {
result.executable = config.executable;
}
if (config.args !== undefined) {
result.args = config.args.slice();
}
if (config.quoting !== undefined) {
result.quoting = Objects.deepClone(config.quoting);
}
return result;
}
export function isEmpty(this: void, value: Tasks.ShellConfiguration): boolean {
return _isEmpty(value, properties);
}
export function assignProperties(this: void, target: Tasks.ShellConfiguration | undefined, source: Tasks.ShellConfiguration | undefined): Tasks.ShellConfiguration | undefined {
return _assignProperties(target, source, properties);
}
export function fillProperties(this: void, target: Tasks.ShellConfiguration, source: Tasks.ShellConfiguration): Tasks.ShellConfiguration {
return _fillProperties(target, source, properties);
}
export function fillDefaults(this: void, value: Tasks.ShellConfiguration, context: ParseContext): Tasks.ShellConfiguration {
return value;
}
export function freeze(this: void, value: Tasks.ShellConfiguration): Readonly<Tasks.ShellConfiguration> | undefined {
if (!value) {
return undefined;
}
return Object.freeze(value);
}
}
namespace CommandOptions {
const properties: MetaData<Tasks.CommandOptions, Tasks.ShellConfiguration>[] = [{ property: 'cwd' }, { property: 'env' }, { property: 'shell', type: ShellConfiguration }];
const defaults: CommandOptionsConfig = { cwd: '${workspaceFolder}' };
export function from(this: void, options: CommandOptionsConfig, context: ParseContext): Tasks.CommandOptions | undefined {
let result: Tasks.CommandOptions = {};
if (options.cwd !== undefined) {
if (Types.isString(options.cwd)) {
result.cwd = options.cwd;
} else {
context.taskLoadIssues.push(nls.localize('ConfigurationParser.invalidCWD', 'Warning: options.cwd must be of type string. Ignoring value {0}\n', options.cwd));
}
}
if (options.env !== undefined) {
result.env = Objects.deepClone(options.env);
}
result.shell = ShellConfiguration.from(options.shell, context);
return isEmpty(result) ? undefined : result;
}
export function isEmpty(value: Tasks.CommandOptions | undefined): boolean {
return _isEmpty(value, properties);
}
export function assignProperties(target: Tasks.CommandOptions | undefined, source: Tasks.CommandOptions | undefined): Tasks.CommandOptions | undefined {
if ((source === undefined) || isEmpty(source)) {
return target;
}
if ((target === undefined) || isEmpty(target)) {
return source;
}
assignProperty(target, source, 'cwd');
if (target.env === undefined) {
target.env = source.env;
} else if (source.env !== undefined) {
let env: { [key: string]: string; } = Object.create(null);
if (target.env !== undefined) {
Object.keys(target.env).forEach(key => env[key] = target.env![key]);
}
if (source.env !== undefined) {
Object.keys(source.env).forEach(key => env[key] = source.env![key]);
}
target.env = env;
}
target.shell = ShellConfiguration.assignProperties(target.shell, source.shell);
return target;
}
export function fillProperties(target: Tasks.CommandOptions | undefined, source: Tasks.CommandOptions | undefined): Tasks.CommandOptions | undefined {
return _fillProperties(target, source, properties);
}
export function fillDefaults(value: Tasks.CommandOptions | undefined, context: ParseContext): Tasks.CommandOptions | undefined {
return _fillDefaults(value, defaults, properties, context);
}
export function freeze(value: Tasks.CommandOptions): Readonly<Tasks.CommandOptions> | undefined {
return _freeze(value, properties);
}
}
namespace CommandConfiguration {
export namespace PresentationOptions {
const properties: MetaData<Tasks.PresentationOptions, void>[] = [{ property: 'echo' }, { property: 'reveal' }, { property: 'focus' }, { property: 'panel' }, { property: 'showReuseMessage' }, { property: 'clear' }, { property: 'group' }];
interface PresentationOptionsShape extends LegacyCommandProperties {
presentation?: PresentationOptionsConfig;
}
export function from(this: void, config: PresentationOptionsShape, context: ParseContext): Tasks.PresentationOptions | undefined {
let echo: boolean;
let reveal: Tasks.RevealKind;
let focus: boolean;
let panel: Tasks.PanelKind;
let showReuseMessage: boolean;
let clear: boolean;
let group: string | undefined;
let hasProps = false;
if (Types.isBoolean(config.echoCommand)) {
echo = config.echoCommand;
hasProps = true;
}
if (Types.isString(config.showOutput)) {
reveal = Tasks.RevealKind.fromString(config.showOutput);
hasProps = true;
}
let presentation = config.presentation || config.terminal;
if (presentation) {
if (Types.isBoolean(presentation.echo)) {
echo = presentation.echo;
}
if (Types.isString(presentation.reveal)) {
reveal = Tasks.RevealKind.fromString(presentation.reveal);
}
if (Types.isBoolean(presentation.focus)) {
focus = presentation.focus;
}
if (Types.isString(presentation.panel)) {
panel = Tasks.PanelKind.fromString(presentation.panel);
}
if (Types.isBoolean(presentation.showReuseMessage)) {
showReuseMessage = presentation.showReuseMessage;
}
if (Types.isBoolean(presentation.clear)) {
clear = presentation.clear;
}
if (Types.isString(presentation.group)) {
group = presentation.group;
}
hasProps = true;
}
if (!hasProps) {
return undefined;
}
return { echo: echo!, reveal: reveal!, focus: focus!, panel: panel!, showReuseMessage: showReuseMessage!, clear: clear!, group };
}
export function assignProperties(target: Tasks.PresentationOptions, source: Tasks.PresentationOptions | undefined): Tasks.PresentationOptions | undefined {
return _assignProperties(target, source, properties);
}
export function fillProperties(target: Tasks.PresentationOptions, source: Tasks.PresentationOptions | undefined): Tasks.PresentationOptions | undefined {
return _fillProperties(target, source, properties);
}
export function fillDefaults(value: Tasks.PresentationOptions, context: ParseContext): Tasks.PresentationOptions | undefined {
let defaultEcho = context.engine === Tasks.ExecutionEngine.Terminal ? true : false;
return _fillDefaults(value, { echo: defaultEcho, reveal: Tasks.RevealKind.Always, focus: false, panel: Tasks.PanelKind.Shared, showReuseMessage: true, clear: false }, properties, context);
}
export function freeze(value: Tasks.PresentationOptions): Readonly<Tasks.PresentationOptions> | undefined {
return _freeze(value, properties);
}
export function isEmpty(this: void, value: Tasks.PresentationOptions): boolean {
return _isEmpty(value, properties);
}
}
namespace ShellString {
export function from(this: void, value: CommandString | undefined): Tasks.CommandString | undefined {
if (value === undefined || value === null) {
return undefined;
}
if (Types.isString(value)) {
return value;
} else if (Types.isStringArray(value)) {
return value.join(' ');
} else {
let quoting = Tasks.ShellQuoting.from(value.quoting);
let result = Types.isString(value.value) ? value.value : Types.isStringArray(value.value) ? value.value.join(' ') : undefined;
if (result) {
return {
value: result,
quoting: quoting
};
} else {
return undefined;
}
}
}
}
interface BaseCommandConfiguationShape extends BaseCommandProperties, LegacyCommandProperties {
}
interface CommandConfiguationShape extends BaseCommandConfiguationShape {
windows?: BaseCommandConfiguationShape;
osx?: BaseCommandConfiguationShape;
linux?: BaseCommandConfiguationShape;
}
const properties: MetaData<Tasks.CommandConfiguration, any>[] = [
{ property: 'runtime' }, { property: 'name' }, { property: 'options', type: CommandOptions },
{ property: 'args' }, { property: 'taskSelector' }, { property: 'suppressTaskName' },
{ property: 'presentation', type: PresentationOptions }
];
export function from(this: void, config: CommandConfiguationShape, context: ParseContext): Tasks.CommandConfiguration | undefined {
let result: Tasks.CommandConfiguration = fromBase(config, context)!;
let osConfig: Tasks.CommandConfiguration | undefined = undefined;
if (config.windows && context.platform === Platform.Windows) {
osConfig = fromBase(config.windows, context);
} else if (config.osx && context.platform === Platform.Mac) {
osConfig = fromBase(config.osx, context);
} else if (config.linux && context.platform === Platform.Linux) {
osConfig = fromBase(config.linux, context);
}
if (osConfig) {
result = assignProperties(result, osConfig, context.schemaVersion === Tasks.JsonSchemaVersion.V2_0_0);
}
return isEmpty(result) ? undefined : result;
}
function fromBase(this: void, config: BaseCommandConfiguationShape, context: ParseContext): Tasks.CommandConfiguration | undefined {
let name: Tasks.CommandString = ShellString.from(config.command)!;
let runtime: Tasks.RuntimeType;
if (Types.isString(config.type)) {
if (config.type === 'shell' || config.type === 'process') {
runtime = Tasks.RuntimeType.fromString(config.type);
}
}
let isShellConfiguration = ShellConfiguration.is(config.isShellCommand);
if (Types.isBoolean(config.isShellCommand) || isShellConfiguration) {
runtime = Tasks.RuntimeType.Shell;
} else if (config.isShellCommand !== undefined) {
runtime = !!config.isShellCommand ? Tasks.RuntimeType.Shell : Tasks.RuntimeType.Process;
}
let result: Tasks.CommandConfiguration = {
name: name!,
runtime: runtime!,
presentation: PresentationOptions.from(config, context)!
};
if (config.args !== undefined) {
result.args = [];
for (let arg of config.args) {
let converted = ShellString.from(arg);
if (converted !== undefined) {
result.args.push(converted);
} else {
context.taskLoadIssues.push(
nls.localize(
'ConfigurationParser.inValidArg',
'Error: command argument must either be a string or a quoted string. Provided value is:\n{0}',
arg ? JSON.stringify(arg, undefined, 4) : 'undefined'
));
}
}
}
if (config.options !== undefined) {
result.options = CommandOptions.from(config.options, context);
if (result.options && result.options.shell === undefined && isShellConfiguration) {
result.options.shell = ShellConfiguration.from(config.isShellCommand as ShellConfiguration, context);
if (context.engine !== Tasks.ExecutionEngine.Terminal) {
context.taskLoadIssues.push(nls.localize('ConfigurationParser.noShell', 'Warning: shell configuration is only supported when executing tasks in the terminal.'));
}
}
}
if (Types.isString(config.taskSelector)) {
result.taskSelector = config.taskSelector;
}
if (Types.isBoolean(config.suppressTaskName)) {
result.suppressTaskName = config.suppressTaskName;
}
return isEmpty(result) ? undefined : result;
}
export function hasCommand(value: Tasks.CommandConfiguration): boolean {
return value && !!value.name;
}
export function isEmpty(value: Tasks.CommandConfiguration | undefined): boolean {
return _isEmpty(value, properties);
}
export function assignProperties(target: Tasks.CommandConfiguration, source: Tasks.CommandConfiguration, overwriteArgs: boolean): Tasks.CommandConfiguration {
if (isEmpty(source)) {
return target;
}
if (isEmpty(target)) {
return source;
}
assignProperty(target, source, 'name');
assignProperty(target, source, 'runtime');
assignProperty(target, source, 'taskSelector');
assignProperty(target, source, 'suppressTaskName');
if (source.args !== undefined) {
if (target.args === undefined || overwriteArgs) {
target.args = source.args;
} else {
target.args = target.args.concat(source.args);
}
}
target.presentation = PresentationOptions.assignProperties(target.presentation!, source.presentation)!;
target.options = CommandOptions.assignProperties(target.options, source.options);
return target;
}
export function fillProperties(target: Tasks.CommandConfiguration, source: Tasks.CommandConfiguration): Tasks.CommandConfiguration {
return _fillProperties(target, source, properties);
}
export function fillGlobals(target: Tasks.CommandConfiguration, source: Tasks.CommandConfiguration | undefined, taskName: string | undefined): Tasks.CommandConfiguration {
if ((source === undefined) || isEmpty(source)) {
return target;
}
target = target || {
name: undefined,
runtime: undefined,
presentation: undefined
};
if (target.name === undefined) {
fillProperty(target, source, 'name');
fillProperty(target, source, 'taskSelector');
fillProperty(target, source, 'suppressTaskName');
let args: Tasks.CommandString[] = source.args ? source.args.slice() : [];
if (!target.suppressTaskName && taskName) {
if (target.taskSelector !== undefined) {
args.push(target.taskSelector + taskName);
} else {
args.push(taskName);
}
}
if (target.args) {
args = args.concat(target.args);
}
target.args = args;
}
fillProperty(target, source, 'runtime');
target.presentation = PresentationOptions.fillProperties(target.presentation!, source.presentation)!;
target.options = CommandOptions.fillProperties(target.options, source.options);
return target;
}
export function fillDefaults(value: Tasks.CommandConfiguration | undefined, context: ParseContext): void {
if (!value || Object.isFrozen(value)) {
return;
}
if (value.name !== undefined && value.runtime === undefined) {
value.runtime = Tasks.RuntimeType.Process;
}
value.presentation = PresentationOptions.fillDefaults(value.presentation!, context)!;
if (!isEmpty(value)) {
value.options = CommandOptions.fillDefaults(value.options, context);
}
if (value.args === undefined) {
value.args = EMPTY_ARRAY;
}
if (value.suppressTaskName === undefined) {
value.suppressTaskName = false;
}
}
export function freeze(value: Tasks.CommandConfiguration): Readonly<Tasks.CommandConfiguration> | undefined {
return _freeze(value, properties);
}
}
namespace ProblemMatcherConverter {
export function namedFrom(this: void, declares: ProblemMatcherConfig.NamedProblemMatcher[] | undefined, context: ParseContext): IStringDictionary<NamedProblemMatcher> {
let result: IStringDictionary<NamedProblemMatcher> = Object.create(null);
if (!Types.isArray(declares)) {
return result;
}
(<ProblemMatcherConfig.NamedProblemMatcher[]>declares).forEach((value) => {
let namedProblemMatcher = (new ProblemMatcherParser(context.problemReporter)).parse(value);
if (isNamedProblemMatcher(namedProblemMatcher)) {
result[namedProblemMatcher.name] = namedProblemMatcher;
} else {
context.problemReporter.error(nls.localize('ConfigurationParser.noName', 'Error: Problem Matcher in declare scope must have a name:\n{0}\n', JSON.stringify(value, undefined, 4)));
}
});
return result;
}
export function from(this: void, config: ProblemMatcherConfig.ProblemMatcherType | undefined, context: ParseContext): ProblemMatcher[] {
let result: ProblemMatcher[] = [];
if (config === undefined) {
return result;
}
let kind = getProblemMatcherKind(config);
if (kind === ProblemMatcherKind.Unknown) {
context.problemReporter.warn(nls.localize(
'ConfigurationParser.unknownMatcherKind',
'Warning: the defined problem matcher is unknown. Supported types are string | ProblemMatcher | Array<string | ProblemMatcher>.\n{0}\n',
JSON.stringify(config, null, 4)));
return result;
} else if (kind === ProblemMatcherKind.String || kind === ProblemMatcherKind.ProblemMatcher) {
let matcher = resolveProblemMatcher(config as ProblemMatcherConfig.ProblemMatcher, context);
if (matcher) {
result.push(matcher);
}
} else if (kind === ProblemMatcherKind.Array) {
let problemMatchers = <(string | ProblemMatcherConfig.ProblemMatcher)[]>config;
problemMatchers.forEach(problemMatcher => {
let matcher = resolveProblemMatcher(problemMatcher, context);
if (matcher) {
result.push(matcher);
}
});
}
return result;
}
function getProblemMatcherKind(this: void, value: ProblemMatcherConfig.ProblemMatcherType): ProblemMatcherKind {
if (Types.isString(value)) {
return ProblemMatcherKind.String;
} else if (Types.isArray(value)) {
return ProblemMatcherKind.Array;
} else if (!Types.isUndefined(value)) {
return ProblemMatcherKind.ProblemMatcher;
} else {
return ProblemMatcherKind.Unknown;
}
}
function resolveProblemMatcher(this: void, value: string | ProblemMatcherConfig.ProblemMatcher, context: ParseContext): ProblemMatcher | undefined {
if (Types.isString(value)) {
let variableName = <string>value;
if (variableName.length > 1 && variableName[0] === '$') {
variableName = variableName.substring(1);
let global = ProblemMatcherRegistry.get(variableName);
if (global) {
return Objects.deepClone(global);
}
let localProblemMatcher = context.namedProblemMatchers[variableName];
if (localProblemMatcher) {
localProblemMatcher = Objects.deepClone(localProblemMatcher);
// remove the name
delete localProblemMatcher.name;
return localProblemMatcher;
}
}
context.taskLoadIssues.push(nls.localize('ConfigurationParser.invalidVaraibleReference', 'Error: Invalid problemMatcher reference: {0}\n', value));
return undefined;
} else {
let json = <ProblemMatcherConfig.ProblemMatcher>value;
return new ProblemMatcherParser(context.problemReporter).parse(json);
}
}
}
const source: Partial<Tasks.TaskSource> = {
kind: Tasks.TaskSourceKind.Workspace,
label: 'Workspace',
config: undefined
};
namespace GroupKind {
export function from(this: void, external: string | GroupKind | undefined): [string, Tasks.GroupType] | undefined {
if (external === undefined) {
return undefined;
}
if (Types.isString(external)) {
if (Tasks.TaskGroup.is(external)) {
return [external, Tasks.GroupType.user];
} else {
return undefined;
}
}
if (!Types.isString(external.kind) || !Tasks.TaskGroup.is(external.kind)) {
return undefined;
}
let group: string = external.kind;
let isDefault: boolean = !!external.isDefault;
return [group, isDefault ? Tasks.GroupType.default : Tasks.GroupType.user];
}
}
namespace TaskDependency {
export function from(this: void, external: string | TaskIdentifier, context: ParseContext): Tasks.TaskDependency | undefined {
if (Types.isString(external)) {
return { workspaceFolder: context.workspaceFolder, task: external };
} else if (TaskIdentifier.is(external)) {
return { workspaceFolder: context.workspaceFolder, task: TaskDefinition.createTaskIdentifier(external as Tasks.TaskIdentifier, context.problemReporter) };
} else {
return undefined;
}
}
}
namespace ConfigurationProperties {
const properties: MetaData<Tasks.ConfigurationProperties, any>[] = [
{ property: 'name' }, { property: 'identifier' }, { property: 'group' }, { property: 'isBackground' },
{ property: 'promptOnClose' }, { property: 'dependsOn' },
{ property: 'presentation', type: CommandConfiguration.PresentationOptions }, { property: 'problemMatchers' }
];
export function from(this: void, external: ConfigurationProperties, context: ParseContext, includeCommandOptions: boolean): Tasks.ConfigurationProperties | undefined {
if (!external) {
return undefined;
}
let result: Tasks.ConfigurationProperties = {};
if (Types.isString(external.taskName)) {
result.name = external.taskName;
}
if (Types.isString(external.label) && context.schemaVersion === Tasks.JsonSchemaVersion.V2_0_0) {
result.name = external.label;
}
if (Types.isString(external.identifier)) {
result.identifier = external.identifier;
}
if (external.isBackground !== undefined) {
result.isBackground = !!external.isBackground;
}
if (external.promptOnClose !== undefined) {
result.promptOnClose = !!external.promptOnClose;
}
if (external.group !== undefined) {
if (Types.isString(external.group) && Tasks.TaskGroup.is(external.group)) {
result.group = external.group;
result.groupType = Tasks.GroupType.user;
} else {
let values = GroupKind.from(external.group);
if (values) {
result.group = values[0];
result.groupType = values[1];
}
}
}
if (external.dependsOn !== undefined) {
if (Types.isArray(external.dependsOn)) {
result.dependsOn = external.dependsOn.reduce((dependencies: Tasks.TaskDependency[], item): Tasks.TaskDependency[] => {
const dependency = TaskDependency.from(item, context);
if (dependency) {
dependencies.push(dependency);
}
return dependencies;
}, []);
} else {
const dependsOnValue = TaskDependency.from(external.dependsOn, context);
result.dependsOn = dependsOnValue ? [dependsOnValue] : undefined;
}
}
if (includeCommandOptions && (external.presentation !== undefined || (external as LegacyCommandProperties).terminal !== undefined)) {
result.presentation = CommandConfiguration.PresentationOptions.from(external, context);
}
if (includeCommandOptions && (external.options !== undefined)) {
result.options = CommandOptions.from(external.options, context);
}
if (external.problemMatcher) {
result.problemMatchers = ProblemMatcherConverter.from(external.problemMatcher, context);
}
return isEmpty(result) ? undefined : result;
}
export function isEmpty(this: void, value: Tasks.ConfigurationProperties): boolean {
return _isEmpty(value, properties);
}
}
namespace ConfiguringTask {
const grunt = 'grunt.';
const jake = 'jake.';
const gulp = 'gulp.';
const npm = 'vscode.npm.';
const typescript = 'vscode.typescript.';
interface CustomizeShape {
customize: string;
}
export function from(this: void, external: ConfiguringTask, context: ParseContext, index: number): Tasks.ConfiguringTask | undefined {
if (!external) {
return undefined;
}
let type = external.type;
let customize = (external as CustomizeShape).customize;
if (!type && !customize) {
context.problemReporter.error(nls.localize('ConfigurationParser.noTaskType', 'Error: tasks configuration must have a type property. The configuration will be ignored.\n{0}\n', JSON.stringify(external, null, 4)));
return undefined;
}
let typeDeclaration = type ? TaskDefinitionRegistry.get(type) : undefined;
if (!typeDeclaration) {
let message = nls.localize('ConfigurationParser.noTypeDefinition', 'Error: there is no registered task type \'{0}\'. Did you miss to install an extension that provides a corresponding task provider?', type);
context.problemReporter.error(message);
return undefined;
}
let identifier: Tasks.TaskIdentifier | undefined;
if (Types.isString(customize)) {
if (customize.indexOf(grunt) === 0) {
identifier = { type: 'grunt', task: customize.substring(grunt.length) };
} else if (customize.indexOf(jake) === 0) {
identifier = { type: 'jake', task: customize.substring(jake.length) };
} else if (customize.indexOf(gulp) === 0) {
identifier = { type: 'gulp', task: customize.substring(gulp.length) };
} else if (customize.indexOf(npm) === 0) {
identifier = { type: 'npm', script: customize.substring(npm.length + 4) };
} else if (customize.indexOf(typescript) === 0) {
identifier = { type: 'typescript', tsconfig: customize.substring(typescript.length + 6) };
}
} else {
if (Types.isString(external.type)) {
identifier = external as Tasks.TaskIdentifier;
}
}
if (identifier === undefined) {
context.problemReporter.error(nls.localize(
'ConfigurationParser.missingType',
'Error: the task configuration \'{0}\' is missing the required property \'type\'. The task configuration will be ignored.', JSON.stringify(external, undefined, 0)
));
return undefined;
}
let taskIdentifier: Tasks.KeyedTaskIdentifier | undefined = TaskDefinition.createTaskIdentifier(identifier, context.problemReporter);
if (taskIdentifier === undefined) {
context.problemReporter.error(nls.localize(
'ConfigurationParser.incorrectType',
'Error: the task configuration \'{0}\' is using an unknown type. The task configuration will be ignored.', JSON.stringify(external, undefined, 0)
));
return undefined;
}
let configElement: Tasks.TaskSourceConfigElement = {
workspaceFolder: context.workspaceFolder,
file: '.vscode\\tasks.json',
index,
element: external
};
let result: Tasks.ConfiguringTask = new Tasks.ConfiguringTask(
`${typeDeclaration.extensionId}.${taskIdentifier._key}`,
Objects.assign({} as Tasks.WorkspaceTaskSource, source, { config: configElement }),
undefined,
type,
taskIdentifier,
RunOptions.fromConfiguration(external.runOptions),
{}
);
let configuration = ConfigurationProperties.from(external, context, true);
if (configuration) {
result.configurationProperties = Objects.assign(result.configurationProperties, configuration);
if (result.configurationProperties.name) {
result._label = result.configurationProperties.name;
} else {
let label = result.configures.type;
if (typeDeclaration.required && typeDeclaration.required.length > 0) {
for (let required of typeDeclaration.required) {
let value = result.configures[required];
if (value) {
label = label + ' ' + value;
break;
}
}
}
result._label = label;
}
if (!result.configurationProperties.identifier) {
result.configurationProperties.identifier = taskIdentifier._key;
}
}
return result;
}
}
namespace CustomTask {
export function from(this: void, external: CustomTask, context: ParseContext, index: number): Tasks.CustomTask | undefined {
if (!external) {
return undefined;
}
let type = external.type;
if (type === undefined || type === null) {
type = Tasks.CUSTOMIZED_TASK_TYPE;
}
if (type !== Tasks.CUSTOMIZED_TASK_TYPE && type !== 'shell' && type !== 'process') {
context.problemReporter.error(nls.localize('ConfigurationParser.notCustom', 'Error: tasks is not declared as a custom task. The configuration will be ignored.\n{0}\n', JSON.stringify(external, null, 4)));
return undefined;
}
let taskName = external.taskName;
if (Types.isString(external.label) && context.schemaVersion === Tasks.JsonSchemaVersion.V2_0_0) {
taskName = external.label;
}
if (!taskName) {
context.problemReporter.error(nls.localize('ConfigurationParser.noTaskName', 'Error: a task must provide a label property. The task will be ignored.\n{0}\n', JSON.stringify(external, null, 4)));
return undefined;
}
let result: Tasks.CustomTask = new Tasks.CustomTask(
context.uuidMap.getUUID(taskName),
Objects.assign({} as Tasks.WorkspaceTaskSource, source, { config: { index, element: external, file: '.vscode\\tasks.json', workspaceFolder: context.workspaceFolder } }),
taskName,
Tasks.CUSTOMIZED_TASK_TYPE,
undefined,
false,
RunOptions.fromConfiguration(external.runOptions),
{
name: taskName,
identifier: taskName,
}
);
let configuration = ConfigurationProperties.from(external, context, false);
if (configuration) {
result.configurationProperties = Objects.assign(result.configurationProperties, configuration);
}
let supportLegacy: boolean = true; //context.schemaVersion === Tasks.JsonSchemaVersion.V2_0_0;
if (supportLegacy) {
let legacy: LegacyTaskProperties = external as LegacyTaskProperties;
if (result.configurationProperties.isBackground === undefined && legacy.isWatching !== undefined) {
result.configurationProperties.isBackground = !!legacy.isWatching;
}
if (result.configurationProperties.group === undefined) {
if (legacy.isBuildCommand === true) {
result.configurationProperties.group = Tasks.TaskGroup.Build;
} else if (legacy.isTestCommand === true) {
result.configurationProperties.group = Tasks.TaskGroup.Test;
}
}
}
let command: Tasks.CommandConfiguration = CommandConfiguration.from(external, context)!;
if (command) {
result.command = command;
}
if (external.command !== undefined) {
// if the task has its own command then we suppress the
// task name by default.
command.suppressTaskName = true;
}
return result;
}
export function fillGlobals(task: Tasks.CustomTask, globals: Globals): void {
// We only merge a command from a global definition if there is no dependsOn
// or there is a dependsOn and a defined command.
if (CommandConfiguration.hasCommand(task.command) || task.configurationProperties.dependsOn === undefined) {
task.command = CommandConfiguration.fillGlobals(task.command, globals.command, task.configurationProperties.name);
}
if (task.configurationProperties.problemMatchers === undefined && globals.problemMatcher !== undefined) {
task.configurationProperties.problemMatchers = Objects.deepClone(globals.problemMatcher);
task.hasDefinedMatchers = true;
}
// promptOnClose is inferred from isBackground if available
if (task.configurationProperties.promptOnClose === undefined && task.configurationProperties.isBackground === undefined && globals.promptOnClose !== undefined) {
task.configurationProperties.promptOnClose = globals.promptOnClose;
}
}
export function fillDefaults(task: Tasks.CustomTask, context: ParseContext): void {
CommandConfiguration.fillDefaults(task.command, context);
if (task.configurationProperties.promptOnClose === undefined) {
task.configurationProperties.promptOnClose = task.configurationProperties.isBackground !== undefined ? !task.configurationProperties.isBackground : true;
}
if (task.configurationProperties.isBackground === undefined) {
task.configurationProperties.isBackground = false;
}
if (task.configurationProperties.problemMatchers === undefined) {
task.configurationProperties.problemMatchers = EMPTY_ARRAY;
}
if (task.configurationProperties.group !== undefined && task.configurationProperties.groupType === undefined) {
task.configurationProperties.groupType = Tasks.GroupType.user;
}
}
export function createCustomTask(contributedTask: Tasks.ContributedTask, configuredProps: Tasks.ConfiguringTask | Tasks.CustomTask): Tasks.CustomTask {
let result: Tasks.CustomTask = new Tasks.CustomTask(
configuredProps._id,
Objects.assign({}, configuredProps._source, { customizes: contributedTask.defines }),
configuredProps.configurationProperties.name || contributedTask._label,
Tasks.CUSTOMIZED_TASK_TYPE,
contributedTask.command,
false,
contributedTask.runOptions,
{
name: configuredProps.configurationProperties.name || contributedTask.configurationProperties.name,
identifier: configuredProps.configurationProperties.identifier || contributedTask.configurationProperties.identifier,
}
);
result.addTaskLoadMessages(configuredProps.taskLoadMessages);
let resultConfigProps: Tasks.ConfigurationProperties = result.configurationProperties;
assignProperty(resultConfigProps, configuredProps.configurationProperties, 'group');
assignProperty(resultConfigProps, configuredProps.configurationProperties, 'groupType');
assignProperty(resultConfigProps, configuredProps.configurationProperties, 'isBackground');
assignProperty(resultConfigProps, configuredProps.configurationProperties, 'dependsOn');
assignProperty(resultConfigProps, configuredProps.configurationProperties, 'problemMatchers');
assignProperty(resultConfigProps, configuredProps.configurationProperties, 'promptOnClose');
result.command.presentation = CommandConfiguration.PresentationOptions.assignProperties(
result.command.presentation!, configuredProps.configurationProperties.presentation)!;
result.command.options = CommandOptions.assignProperties(result.command.options, configuredProps.configurationProperties.options);
let contributedConfigProps: Tasks.ConfigurationProperties = contributedTask.configurationProperties;
fillProperty(resultConfigProps, contributedConfigProps, 'group');
fillProperty(resultConfigProps, contributedConfigProps, 'groupType');
fillProperty(resultConfigProps, contributedConfigProps, 'isBackground');
fillProperty(resultConfigProps, contributedConfigProps, 'dependsOn');
fillProperty(resultConfigProps, contributedConfigProps, 'problemMatchers');
fillProperty(resultConfigProps, contributedConfigProps, 'promptOnClose');
result.command.presentation = CommandConfiguration.PresentationOptions.fillProperties(
result.command.presentation!, contributedConfigProps.presentation)!;
result.command.options = CommandOptions.fillProperties(result.command.options, contributedConfigProps.options);
if (contributedTask.hasDefinedMatchers === true) {
result.hasDefinedMatchers = true;
}
return result;
}
}
interface TaskParseResult {
custom: Tasks.CustomTask[];
configured: Tasks.ConfiguringTask[];
}
namespace TaskParser {
function isCustomTask(value: CustomTask | ConfiguringTask): value is CustomTask {
let type = value.type;
let customize = (value as any).customize;
return customize === undefined && (type === undefined || type === null || type === Tasks.CUSTOMIZED_TASK_TYPE || type === 'shell' || type === 'process');
}
export function from(this: void, externals: Array<CustomTask | ConfiguringTask> | undefined, globals: Globals, context: ParseContext): TaskParseResult {
let result: TaskParseResult = { custom: [], configured: [] };
if (!externals) {
return result;
}
let defaultBuildTask: { task: Tasks.Task | undefined; rank: number; } = { task: undefined, rank: -1 };
let defaultTestTask: { task: Tasks.Task | undefined; rank: number; } = { task: undefined, rank: -1 };
let schema2_0_0: boolean = context.schemaVersion === Tasks.JsonSchemaVersion.V2_0_0;
const baseLoadIssues = Objects.deepClone(context.taskLoadIssues);
for (let index = 0; index < externals.length; index++) {
let external = externals[index];
if (isCustomTask(external)) {
let customTask = CustomTask.from(external, context, index);
if (customTask) {
CustomTask.fillGlobals(customTask, globals);
CustomTask.fillDefaults(customTask, context);
if (schema2_0_0) {
if ((customTask.command === undefined || customTask.command.name === undefined) && (customTask.configurationProperties.dependsOn === undefined || customTask.configurationProperties.dependsOn.length === 0)) {
context.problemReporter.error(nls.localize(
'taskConfiguration.noCommandOrDependsOn', 'Error: the task \'{0}\' neither specifies a command nor a dependsOn property. The task will be ignored. Its definition is:\n{1}',
customTask.configurationProperties.name, JSON.stringify(external, undefined, 4)
));
continue;
}
} else {
if (customTask.command === undefined || customTask.command.name === undefined) {
context.problemReporter.warn(nls.localize(
'taskConfiguration.noCommand', 'Error: the task \'{0}\' doesn\'t define a command. The task will be ignored. Its definition is:\n{1}',
customTask.configurationProperties.name, JSON.stringify(external, undefined, 4)
));
continue;
}
}
if (customTask.configurationProperties.group === Tasks.TaskGroup.Build && defaultBuildTask.rank < 2) {
defaultBuildTask.task = customTask;
defaultBuildTask.rank = 2;
} else if (customTask.configurationProperties.group === Tasks.TaskGroup.Test && defaultTestTask.rank < 2) {
defaultTestTask.task = customTask;
defaultTestTask.rank = 2;
} else if (customTask.configurationProperties.name === 'build' && defaultBuildTask.rank < 1) {
defaultBuildTask.task = customTask;
defaultBuildTask.rank = 1;
} else if (customTask.configurationProperties.name === 'test' && defaultTestTask.rank < 1) {
defaultTestTask.task = customTask;
defaultTestTask.rank = 1;
}
customTask.addTaskLoadMessages(context.taskLoadIssues);
result.custom.push(customTask);
}
} else {
let configuredTask = ConfiguringTask.from(external, context, index);
if (configuredTask) {
configuredTask.addTaskLoadMessages(context.taskLoadIssues);
result.configured.push(configuredTask);
}
}
context.taskLoadIssues = Objects.deepClone(baseLoadIssues);
}
if ((defaultBuildTask.rank > -1) && (defaultBuildTask.rank < 2) && defaultBuildTask.task) {
defaultBuildTask.task.configurationProperties.group = Tasks.TaskGroup.Build;
defaultBuildTask.task.configurationProperties.groupType = Tasks.GroupType.user;
} else if ((defaultTestTask.rank > -1) && (defaultTestTask.rank < 2) && defaultTestTask.task) {
defaultTestTask.task.configurationProperties.group = Tasks.TaskGroup.Test;
defaultTestTask.task.configurationProperties.groupType = Tasks.GroupType.user;
}
return result;
}
export function assignTasks(target: Tasks.CustomTask[], source: Tasks.CustomTask[]): Tasks.CustomTask[] {
if (source === undefined || source.length === 0) {
return target;
}
if (target === undefined || target.length === 0) {
return source;
}
if (source) {
// Tasks are keyed by ID but we need to merge by name
let map: IStringDictionary<Tasks.CustomTask> = Object.create(null);
target.forEach((task) => {
map[task.configurationProperties.name!] = task;
});
source.forEach((task) => {
map[task.configurationProperties.name!] = task;
});
let newTarget: Tasks.CustomTask[] = [];
target.forEach(task => {
newTarget.push(map[task.configurationProperties.name!]);
delete map[task.configurationProperties.name!];
});
Object.keys(map).forEach(key => newTarget.push(map[key]));
target = newTarget;
}
return target;
}
}
interface Globals {
command?: Tasks.CommandConfiguration;
problemMatcher?: ProblemMatcher[];
promptOnClose?: boolean;
suppressTaskName?: boolean;
}
namespace Globals {
export function from(config: ExternalTaskRunnerConfiguration, context: ParseContext): Globals {
let result = fromBase(config, context);
let osGlobals: Globals | undefined = undefined;
if (config.windows && context.platform === Platform.Windows) {
osGlobals = fromBase(config.windows, context);
} else if (config.osx && context.platform === Platform.Mac) {
osGlobals = fromBase(config.osx, context);
} else if (config.linux && context.platform === Platform.Linux) {
osGlobals = fromBase(config.linux, context);
}
if (osGlobals) {
result = Globals.assignProperties(result, osGlobals);
}
let command = CommandConfiguration.from(config, context);
if (command) {
result.command = command;
}
Globals.fillDefaults(result, context);
Globals.freeze(result);
return result;
}
export function fromBase(this: void, config: BaseTaskRunnerConfiguration, context: ParseContext): Globals {
let result: Globals = {};
if (config.suppressTaskName !== undefined) {
result.suppressTaskName = !!config.suppressTaskName;
}
if (config.promptOnClose !== undefined) {
result.promptOnClose = !!config.promptOnClose;
}
if (config.problemMatcher) {
result.problemMatcher = ProblemMatcherConverter.from(config.problemMatcher, context);
}
return result;
}
export function isEmpty(value: Globals): boolean {
return !value || value.command === undefined && value.promptOnClose === undefined && value.suppressTaskName === undefined;
}
export function assignProperties(target: Globals, source: Globals): Globals {
if (isEmpty(source)) {
return target;
}
if (isEmpty(target)) {
return source;
}
assignProperty(target, source, 'promptOnClose');
assignProperty(target, source, 'suppressTaskName');
return target;
}
export function fillDefaults(value: Globals, context: ParseContext): void {
if (!value) {
return;
}
CommandConfiguration.fillDefaults(value.command, context);
if (value.suppressTaskName === undefined) {
value.suppressTaskName = false;
}
if (value.promptOnClose === undefined) {
value.promptOnClose = true;
}
}
export function freeze(value: Globals): void {
Object.freeze(value);
if (value.command) {
CommandConfiguration.freeze(value.command);
}
}
}
export namespace ExecutionEngine {
export function from(config: ExternalTaskRunnerConfiguration): Tasks.ExecutionEngine {
let runner = config.runner || config._runner;
let result: Tasks.ExecutionEngine | undefined;
if (runner) {
switch (runner) {
case 'terminal':
result = Tasks.ExecutionEngine.Terminal;
break;
case 'process':
result = Tasks.ExecutionEngine.Process;
break;
}
}
let schemaVersion = JsonSchemaVersion.from(config);
if (schemaVersion === Tasks.JsonSchemaVersion.V0_1_0) {
return result || Tasks.ExecutionEngine.Process;
} else if (schemaVersion === Tasks.JsonSchemaVersion.V2_0_0) {
return Tasks.ExecutionEngine.Terminal;
} else {
throw new Error('Shouldn\'t happen.');
}
}
}
export namespace JsonSchemaVersion {
const _default: Tasks.JsonSchemaVersion = Tasks.JsonSchemaVersion.V2_0_0;
export function from(config: ExternalTaskRunnerConfiguration): Tasks.JsonSchemaVersion {
let version = config.version;
if (!version) {
return _default;
}
switch (version) {
case '0.1.0':
return Tasks.JsonSchemaVersion.V0_1_0;
case '2.0.0':
return Tasks.JsonSchemaVersion.V2_0_0;
default:
return _default;
}
}
}
export interface ParseResult {
validationStatus: ValidationStatus;
custom: Tasks.CustomTask[];
configured: Tasks.ConfiguringTask[];
engine: Tasks.ExecutionEngine;
}
export interface IProblemReporter extends IProblemReporterBase {
}
class UUIDMap {
private last: IStringDictionary<string | string[]> | undefined;
private current: IStringDictionary<string | string[]>;
constructor(other?: UUIDMap) {
this.current = Object.create(null);
if (other) {
for (let key of Object.keys(other.current)) {
let value = other.current[key];
if (Array.isArray(value)) {
this.current[key] = value.slice();
} else {
this.current[key] = value;
}
}
}
}
public start(): void {
this.last = this.current;
this.current = Object.create(null);
}
public getUUID(identifier: string): string {
let lastValue = this.last ? this.last[identifier] : undefined;
let result: string | undefined = undefined;
if (lastValue !== undefined) {
if (Array.isArray(lastValue)) {
result = lastValue.shift();
if (lastValue.length === 0) {
delete this.last![identifier];
}
} else {
result = lastValue;
delete this.last![identifier];
}
}
if (result === undefined) {
result = UUID.generateUuid();
}
let currentValue = this.current[identifier];
if (currentValue === undefined) {
this.current[identifier] = result;
} else {
if (Array.isArray(currentValue)) {
currentValue.push(result);
} else {
let arrayValue: string[] = [currentValue];
arrayValue.push(result);
this.current[identifier] = arrayValue;
}
}
return result;
}
public finish(): void {
this.last = undefined;
}
}
class ConfigurationParser {
private workspaceFolder: IWorkspaceFolder;
private problemReporter: IProblemReporter;
private uuidMap: UUIDMap;
private platform: Platform;
constructor(workspaceFolder: IWorkspaceFolder, platform: Platform, problemReporter: IProblemReporter, uuidMap: UUIDMap) {
this.workspaceFolder = workspaceFolder;
this.platform = platform;
this.problemReporter = problemReporter;
this.uuidMap = uuidMap;
}
public run(fileConfig: ExternalTaskRunnerConfiguration): ParseResult {
let engine = ExecutionEngine.from(fileConfig);
let schemaVersion = JsonSchemaVersion.from(fileConfig);
let context: ParseContext = {
workspaceFolder: this.workspaceFolder,
problemReporter: this.problemReporter,
uuidMap: this.uuidMap,
namedProblemMatchers: {},
engine,
schemaVersion,
platform: this.platform,
taskLoadIssues: []
};
let taskParseResult = this.createTaskRunnerConfiguration(fileConfig, context);
return {
validationStatus: this.problemReporter.status,
custom: taskParseResult.custom,
configured: taskParseResult.configured,
engine
};
}
private createTaskRunnerConfiguration(fileConfig: ExternalTaskRunnerConfiguration, context: ParseContext): TaskParseResult {
let globals = Globals.from(fileConfig, context);
if (this.problemReporter.status.isFatal()) {
return { custom: [], configured: [] };
}
context.namedProblemMatchers = ProblemMatcherConverter.namedFrom(fileConfig.declares, context);
let globalTasks: Tasks.CustomTask[] | undefined = undefined;
let externalGlobalTasks: Array<ConfiguringTask | CustomTask> | undefined = undefined;
if (fileConfig.windows && context.platform === Platform.Windows) {
globalTasks = TaskParser.from(fileConfig.windows.tasks, globals, context).custom;
externalGlobalTasks = fileConfig.windows.tasks;
} else if (fileConfig.osx && context.platform === Platform.Mac) {
globalTasks = TaskParser.from(fileConfig.osx.tasks, globals, context).custom;
externalGlobalTasks = fileConfig.osx.tasks;
} else if (fileConfig.linux && context.platform === Platform.Linux) {
globalTasks = TaskParser.from(fileConfig.linux.tasks, globals, context).custom;
externalGlobalTasks = fileConfig.linux.tasks;
}
if (context.schemaVersion === Tasks.JsonSchemaVersion.V2_0_0 && globalTasks && globalTasks.length > 0 && externalGlobalTasks && externalGlobalTasks.length > 0) {
let taskContent: string[] = [];
for (let task of externalGlobalTasks) {
taskContent.push(JSON.stringify(task, null, 4));
}
context.problemReporter.error(
nls.localize(
'TaskParse.noOsSpecificGlobalTasks',
'Task version 2.0.0 doesn\'t support global OS specific tasks. Convert them to a task with a OS specific command. Affected tasks are:\n{0}', taskContent.join('\n'))
);
}
let result: TaskParseResult = { custom: [], configured: [] };
if (fileConfig.tasks) {
result = TaskParser.from(fileConfig.tasks, globals, context);
}
if (globalTasks) {
result.custom = TaskParser.assignTasks(result.custom, globalTasks);
}
if ((!result.custom || result.custom.length === 0) && (globals.command && globals.command.name)) {
let matchers: ProblemMatcher[] = ProblemMatcherConverter.from(fileConfig.problemMatcher, context);
let isBackground = fileConfig.isBackground ? !!fileConfig.isBackground : fileConfig.isWatching ? !!fileConfig.isWatching : undefined;
let name = Tasks.CommandString.value(globals.command.name);
let task: Tasks.CustomTask = new Tasks.CustomTask(
context.uuidMap.getUUID(name),
Objects.assign({} as Tasks.WorkspaceTaskSource, source, { config: { index: -1, element: fileConfig, workspaceFolder: context.workspaceFolder } }),
name,
Tasks.CUSTOMIZED_TASK_TYPE,
{
name: undefined,
runtime: undefined,
presentation: undefined,
suppressTaskName: true
},
false,
{ reevaluateOnRerun: true },
{
name: name,
identifier: name,
group: Tasks.TaskGroup.Build,
isBackground: isBackground,
problemMatchers: matchers,
}
);
let value = GroupKind.from(fileConfig.group);
if (value) {
task.configurationProperties.group = value[0];
task.configurationProperties.groupType = value[1];
} else if (fileConfig.group === 'none') {
task.configurationProperties.group = undefined;
}
CustomTask.fillGlobals(task, globals);
CustomTask.fillDefaults(task, context);
result.custom = [task];
}
result.custom = result.custom || [];
result.configured = result.configured || [];
return result;
}
}
let uuidMaps: Map<string, UUIDMap> = new Map();
export function parse(workspaceFolder: IWorkspaceFolder, platform: Platform, configuration: ExternalTaskRunnerConfiguration, logger: IProblemReporter): ParseResult {
let uuidMap = uuidMaps.get(workspaceFolder.uri.toString());
if (!uuidMap) {
uuidMap = new UUIDMap();
uuidMaps.set(workspaceFolder.uri.toString(), uuidMap);
}
try {
uuidMap.start();
return (new ConfigurationParser(workspaceFolder, platform, logger, uuidMap)).run(configuration);
} finally {
uuidMap.finish();
}
}
export function createCustomTask(contributedTask: Tasks.ContributedTask, configuredProps: Tasks.ConfiguringTask | Tasks.CustomTask): Tasks.CustomTask {
return CustomTask.createCustomTask(contributedTask, configuredProps);
}
/*
class VersionConverter {
constructor(private problemReporter: IProblemReporter) {
}
public convert(fromConfig: ExternalTaskRunnerConfiguration): ExternalTaskRunnerConfiguration {
let result: ExternalTaskRunnerConfiguration;
result.version = '2.0.0';
if (Array.isArray(fromConfig.tasks)) {
} else {
result.tasks = [];
}
return result;
}
private convertGlobalTask(fromConfig: ExternalTaskRunnerConfiguration): TaskDescription {
let command: string = this.getGlobalCommand(fromConfig);
if (!command) {
this.problemReporter.error(nls.localize('Converter.noGlobalName', 'No global command specified. Can\'t convert to 2.0.0 version.'));
return undefined;
}
let result: TaskDescription = {
taskName: command
};
if (fromConfig.isShellCommand) {
result.type = 'shell';
} else {
result.type = 'process';
result.args = fromConfig.args;
}
if (fromConfig.)
return result;
}
private getGlobalCommand(fromConfig: ExternalTaskRunnerConfiguration): string {
if (fromConfig.command) {
return fromConfig.command;
} else if (fromConfig.windows && fromConfig.windows.command) {
return fromConfig.windows.command;
} else if (fromConfig.osx && fromConfig.osx.command) {
return fromConfig.osx.command;
} else if (fromConfig.linux && fromConfig.linux.command) {
return fromConfig.linux.command;
} else {
return undefined;
}
}
private createCommandLine(command: string, args: string[], isWindows: boolean): string {
let result: string[];
let commandHasSpace = false;
let argHasSpace = false;
if (TaskDescription.hasUnescapedSpaces(command)) {
result.push(`"${command}"`);
commandHasSpace = true;
} else {
result.push(command);
}
if (args) {
for (let arg of args) {
if (TaskDescription.hasUnescapedSpaces(arg)) {
result.push(`"${arg}"`);
argHasSpace= true;
} else {
result.push(arg);
}
}
}
return result.join(' ');
}
}
*/
| landonepps/vscode | src/vs/workbench/parts/tasks/node/taskConfiguration.ts | TypeScript | mit | 67,393 |
//Symbolic Property
#ifndef _PROBMODELS_BASE_SYMBOLIC_PROPERTY_HPP_
#define _PROBMODELS_BASE_SYMBOLIC_PROPERTY_HPP_
#include <array>
#include "boost/pending/property.hpp"
namespace probmodels {
namespace base {
//Property must be copyable, assignable and copy constructable
template <std::size_t Len, typename Property = boost::no_property>
class SymbolicProperty {
static const std::size_t _array_len = Len+1;
public:
SymbolicProperty() {}
SymbolicProperty(const SymbolicProperty& prop) :
_label(prop._label), _prop(prop._prop) {}
inline const char* label() const { return _label; }
SymbolicProperty& operator= (const SymbolicProperty& property) {
std::copy(property._label, property._label+Len+1, _label);
}
private:
std::array<char,_array_len> _label;
Property _prop;
};
}
}
#endif
| antoniohps/probmodels | include/base/symbolic_property.hpp | C++ | mit | 844 |
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Pegawai extends CI_Controller {
/*
@author : Okki Setyawan © 2016
*/
//ini method yang pertama kali di jalankan oleh codeginiter,semua pemanggilan ada disini termasuk hak akses
public function __construct(){
parent ::__construct();
//panggil model pegawai jika memang controller butuh transaksi data
$this->load->model('model_pegawai');
//jika tidak ada session yang terdaftar maka sistem balik ke halaman login
//if($this->session->userdata('username') == ''){
// redirect(base_url('login'));
//}
}
public function transaksi_id($param='') {
$data = $this->model_pegawai->get_last_personnel_id();
$lastid = $data->row();
$idnya = $lastid->id;
if($idnya=='') { // bila data kosong
$ID = $param."10000001";
//00000001
}else {
$MaksID = $idnya;
$MaksID++;
if($MaksID < 10) $ID = $param."1000000".$MaksID;
else if($MaksID < 100) $ID = $param."100000".$MaksID;
else if($MaksID < 1000) $ID = $param."10000".$MaksID;
else if($MaksID < 10000) $ID = $param."1000".$MaksID;
else if($MaksID < 100000) $ID = $param."100".$MaksID;
else if($MaksID < 1000000) $ID = $param."10".$MaksID;
else if($MaksID < 10000000) $ID = $param."1".$MaksID;
else $ID = $MaksID;
}
return $ID;
}
public function get_all_pegawai_json(){
$data_employee = $this->model_pegawai->get_all_pegawai_json();
$total = count($this->model_pegawai->get_all_pegawai_json());
$data = json_encode($this->model_pegawai->get_all_pegawai_json());
//echo json_encode($this->model_pegawai->get_all_pegawai_json());
//echo "{\"total\":". $total .",\"records\":" . $data . "}";
echo "{\"records\":" . $data . "}";
}
public function get_chart_pegawai_json(){
//$data_employee = $this->model_pegawai->get_all_pegawai_json();
//$total = count($this->model_pegawai->get_all_pegawai_json());
echo json_encode($this->model_pegawai->get_chart_pegawai_json());
//echo json_encode($this->model_pegawai->get_all_pegawai_json());
//echo "{\"total\":". $total .",\"records\":" . $data . "}";
//echo "{\"records\":" . $data . "}";
}
//ini method buat menampilkan ke layar pertama kali ketika controller diakses
public function index() {
//ini variabel buat nimpuk ke view ,ini kalau di smarty namanya assign
$error = '';
$location = $this->uri->segment(1);
$data_employee = $this->model_pegawai->get_all_pegawai();
$data = array('judul'=>'Human Resource Information System (HRIS) ASDP',
'error'=>$error,
'location'=>$location,
'data_employee'=>$data_employee,
'footer'=>'© 2016. Langit Infotama');
//ini mirip sama display smarty tapi si CI ngelempar view sama data sekaligus
//kalau smarty antara display sama assign terpisah
//$this->session->set_flashdata('pesan','');
$this->load->view('pegawai/pegawai_view',$data);
}
public function add_pegawai(){
//ini variabel buat nimpuk ke view ,ini kalau di smarty namanya assign
$error = '';
//$last_personnel_id = $this->model_pegawai->get_last_personnel_id();
$location = $this->uri->segment(2);
$data = array('judul'=>'Human Resource Information System (HRIS) ASDP',
'error'=>$error,
'location'=>$location,
'last_id'=>$this->transaksi_id(),
'footer'=>'© 2016. Langit Infotama');
//ini mirip sama display smarty tapi si CI ngelempar view sama data sekaligus
//kalau smarty antara display sama assign terpisah
$this->load->view('pegawai/pegawai_add',$data);
}
public function pro_add_pegawai(){
//ini adalah tipe parsingan data si CI
$nik = $this->input->post('nik');
$start_date = $this->input->post('tanggal_masuk');
$extgstart_date = substr($start_date,0,2);
$exblstart_date = substr($start_date,3,2);
$exthstart_date = substr($start_date,6,4);
$tanggalmulai = $exthstart_date.$exblstart_date.$extgstart_date;
//$tanggal_masuk = str_replace("-","",date('Ymd',strtotime($this->input->post('tanggal_masuk'))));
//$stor_tanggal_masuk = date('Y-m-d',strtotime($tanggal_masuk));
//$datestart = htmlspecialchars($tanggal_masuk);
$tgldn = substr($datestart,0,2);
$personnel_id = $this->input->post('personnel_id');
$blndn = substr($datestart,3,2);
$thndn = substr($datestart,6,4);
$tglstart = $thndn.$blndn.$tgldn;
$nama = $this->input->post('nama');
//karena model terpisah jadi kita panggil method si model saja ,karena core model sudah dipanggil sama si construct diatas
//jangan lupa parameter parsingan dimasukin
$sqlinsert = $this->model_pegawai->pro_add_pegawai($personnel_id,$nik,$tanggalmulai,$nama);
$link = base_url('pegawai');
//jika berhasil maka pindah ke halaman view pegawai
//$this->session->set_flashdata('pesan','Data Berhasil Dimasukkan');
//redirect(base_url('pegawai'));
echo "<script language=javascript>
alert('Simpan Berhasil');
window.location='$link';
</script>";
}
public function pegawai_update(){
$id = $this->uri->segment(3);
$location = $this->uri->segment(1);
//$this->model_pegawai->pegawai_update($id);
$data_employee = $this->model_pegawai->pegawai_update($id);
$error = '';
$data = array('judul'=>'Human Resource Information System (HRIS) ASDP',
'error'=>$error,
'personnel_id'=>$id,
'location'=>$location,
'data_employee'=>$data_employee,
'footer'=>'© 2016. Langit Infotama');
$this->load->view('pegawai/pegawai_edit',$data);
}
public function pro_update_pegawai(){
$nik = $this->input->post('nik');
$tanggal_masuk = str_replace("-","",date('Ymd',strtotime($this->input->post('tanggal_masuk'))));
$nama = $this->input->post('nama');
//echo $nik.'-'.$stor_tanggal_masuk.'-'.$nama;
$sqlupdate = $this->model_pegawai->pro_update_pegawai($nik,$tanggal_masuk,$nama);
$link = base_url('pegawai');
//jika berhasil maka pindah ke halaman view pegawai
//echo $this->session->set_flashdata('pesan','Data Berhasil Dirubah');
//echo 2;
//redirect(base_url('pegawai'));
//
echo "<script language=javascript>
alert('Perbaikan Berhasil');
window.location='$link';
</script>";
}
public function pegawai_detail(){
$id = $this->uri->segment(3);
$location = $this->uri->segment(2);
$sql = $this->db->query("SELECT *,substr(birth_date,1,4) as thnlahir FROM human_pa_md_emp_personal where personnel_id = '$id' order by start_date desc limit 1")->row_array();
$namapegawai = $sql['name_full'];
$litfoto = $sql['lit_foto'];
$thnlahir = $sql['thnlahir'];
$thn_skrg = date('Y');
$usia = $thn_skrg - $thnlahir;
$data = array('judul'=>'Human Resource Information System (HRIS) ASDP',
'namapegawai'=>$namapegawai,
'litfoto'=>$litfoto,
'usia'=>$usia,
'personnel_id'=>$id,
'location'=>$location,
'footer'=>'© 2016. Langit Infotama');
$this->load->view('pegawai/pegawai_detail',$data);
}
public function pegawai_delete(){
$id = $this->uri->segment(3);
$this->model_pegawai->pegawai_delete($id);
$link = base_url('pegawai');
echo "<script language=javascript>
alert('Hapus Berhasil');
window.location='$link';
</script>";
/*
echo json_encode($this->model_pegawai->pegawai_delete($id));
//$this->session->set_flashdata('pesan','Data Berhasil Dihapus');
// redirect(base_url('pegawai'));
*/
}
public function pegawai_importphoto(){
$sql = $this->db->query("SELECT * FROM human_pa_md_emp_photo order by start_date desc limit 1")->row_array();
$file = 'images/'.$sql['personnel_id'].".jpg";
$handle = fopen($file, 'a+');
fwrite($handle, $sql['binary_data']);
//$result = $this->db->query("SELECT * FROM human_pa_md_emp_photo limit 1")->row_array();
//echo json_encode($result);
/*
$query = "SELECT * FROM human_pa_md_emp_photo limit 1";
$result = $db->Execute($query);
while ($row = $rs->FetchRow()){
$file = 'images/'.$row['personnel_id'].".jpg";
$handle = fopen($file, 'a+');
fwrite($handle, $row['binary_data']);
}
echo json_encode($result);
*/
}
}
| okki23/asdp | application/modules/pegawai/controllers/Pegawai.php | PHP | mit | 8,952 |
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("4.UnicodeCharacter")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("4.UnicodeCharacter")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("fb3fca37-8bf7-4728-8f0f-bd790bf76998")]
// 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")]
| aliv59git/C-1N_HomeAndExam | CSharp1_Home2/4.UnicodeCharacter/Properties/AssemblyInfo.cs | C# | mit | 1,412 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.ChangeTracking.Internal;
using Wodsoft.ComBoost.Data.Entity;
using Wodsoft.ComBoost.Mvc;
using Wodsoft.ComBoost.Data;
using Wodsoft.ComBoost.Forum.Entity;
using System.ComponentModel;
namespace Wodsoft.ComBoost.Forum.Controllers
{
public class HomeController : DomainController
{
public async Task<IActionResult> Index()
{
var context = CreateDomainContext();
context.ValueProvider.SetValue("size", 1000);
var domain = DomainProvider.GetService<EntityDomainService<Entity.Forum>>();
var result = await domain.ExecuteAsync<IEntityViewModel<Entity.Forum>>(context, "List");
return View(result);
}
}
}
| Kation/ComBoost | src/samples/Wodsoft.ComBoost.Forum/Controllers/HomeController.cs | C# | mit | 1,001 |
package seedu.ezdo.logic.parser;
import seedu.ezdo.logic.commands.Command;
/**
* An interface for the command parsers in ezDo.
*/
public interface CommandParser {
/** Parses the given string */
Command parse(String args);
}
| CS2103JAN2017-W14-B4/main | src/main/java/seedu/ezdo/logic/parser/CommandParser.java | Java | mit | 236 |
<?php
namespace Embark\CMS\Database;
use Exception;
use Profiler;
use PDO;
class Connection
{
const UPDATE_ON_DUPLICATE = 1;
protected $log;
protected $conf;
protected $queryCaching;
protected $lastException;
protected $lastQuery;
protected $string;
public function __construct($conf)
{
$this->conf = $conf;
$this->queryCaching = true;
$this->string = sprintf(
'mysql:host=%s;port=%s;dbname=%s',
$conf->host,
$conf->port,
$conf->database
);
}
public function beginTransaction()
{
return $this->connection->beginTransaction();
}
public function commit()
{
return $this->connection->commit();
}
public function rollBack()
{
return $this->connection->rollBack();
}
public function connect()
{
// Already connected:
if (isset($this->connection)) {
return true;
}
// Establish new connection:
$this->connection = new PDO($this->string, $this->conf->user, $this->conf->password, [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_OBJ,
PDO::ATTR_PERSISTENT => false,
PDO::MYSQL_ATTR_USE_BUFFERED_QUERY => true,
PDO::ATTR_EMULATE_PREPARES => false
]);
$this->execute('SET NAMES utf8');
$this->execute('SET time_zone = "+00:00"');
$this->execute('SET storage_engine = "InnoDB"');
return true;
}
public function connected()
{
return $this->connection instanceof PDO;
}
public function execute($statement)
{
return $this->connection->exec($statement);
}
public function prepare($statement, array $driver_options = [])
{
return $this->connection->prepare($statement, $driver_options);
}
public function createDataTableName($schema, $field, $guid)
{
$table = $schema . '_' . $field;
if (strlen($table) > 64) {
$table = trim(substr($table, 0, 63 - strlen($guid)), '-_');
$table .= '_' . $guid;
}
return $table;
}
public function prepareQuery($query, array $values = null)
{
if (is_array($values) && empty($values) === false) {
// Sanitise values:
$values = array_map([$this, 'escape'], $values);
// Inject values:
$query = vsprintf(trim($query), $values);
}
if (isset($this->queryCaching)) {
$query = preg_replace('/^SELECT\s+/i', 'SELECT SQL_'.(!$this->queryCaching ? 'NO_' : NULL).'CACHE ', $query);
}
return $query;
}
public function close()
{
$this->connection = null;
}
public function escape($string)
{
return substr($this->connection->quote($string), 1, -1);
}
public function insert($table, array $fields, $flag = null)
{
$values = [];
$sets = [];
foreach ($fields as $key => $value) {
if (strlen($value) == 0) {
$sets[] = "`{$key}` = NULL";
}
else {
$values[] = $value;
$sets[] = "`{$key}` = '%" . count($values) . '$s\'';
}
}
$query = "INSERT INTO `{$table}` SET " . implode(', ', $sets);
if ($flag == static::UPDATE_ON_DUPLICATE) {
$query .= ' ON DUPLICATE KEY UPDATE ' . implode(', ', $sets);
}
$this->query($query, $values);
return $this->connection->lastInsertId();
}
public function update($table, array $fields, array $values = null, $where = null)
{
$set_values = [];
$sets = [];
foreach ($fields as $key => $value) {
if (strlen($value) == 0) {
$sets[] = "`{$key}` = NULL";
}
else {
$set_values[] = $value;
$sets[] = "`{$key}` = '%s'";
}
}
if (!is_null($where)) {
$where = " WHERE {$where}";
}
$values = (is_array($values) && !empty($values)
? array_merge($set_values, $values)
: $set_values
);
$this->query("UPDATE `{$table}` SET " . implode(', ', $sets) . $where, $values);
}
public function delete($table, array $values = null, $where = null)
{
return $this->query("DELETE FROM `$table` WHERE {$where}", $values);
}
public function truncate($table)
{
return $this->query("TRUNCATE TABLE `{$table}`");
}
public function query($query, array $values = null, $return_type = null, $buffer = null)
{
if (is_null($return_type)) {
$return_type = __NAMESPACE__ . '\\ResultIterator';
}
if (!is_null($buffer)) {
throw new Exception('buffer argument is deprecated.');
}
$query = $this->prepareQuery($query, $values);
$this->lastException = null;
$this->lastQuery = $query;
try {
Profiler::begin('Executing database query');
Profiler::store('query', $query, 'system/database-query action/executed data/sql text/sql');
$result = $this->connection->query($query);
Profiler::end();
} catch (PDOException $e) {
Profiler::store('exception', $e->getMessage(), 'system/exeption');
Profiler::end();
$this->lastException = $e;
$this->log['error'][] = [
'query' => $query,
'message' => $e->getMessage(),
'code' => $e->getCode()
];
throw new Exception(
__(
'MySQL Error (%1$s): %2$s in query "%3$s"',
[$e->getCode(), $e->getMessage(), $query]
),
end($this->log['error'])
);
}
return new $return_type($result);
}
public function cleanFields(array $array)
{
foreach ($array as $key => $val) {
$array[$key] = (strlen($val) == 0 ? 'NULL' : "'".$this->escape(trim($val))."'");
}
return $array;
}
public function lastInsertId()
{
return $this->connection->lastInsertId();
}
public function lastError()
{
return [
$this->lastException->getCode(),
$this->lastException->getMessage(),
$this->lastQuery
];
}
public function lastQuery()
{
return $this->lastQuery;
}
}
| psychoticmeow/journey-cms | packages/system/lib/Database/Connection.php | PHP | mit | 6,723 |
#pragma once
#include <cmath>
// windows MinGW fix
#ifdef __MINGW32__
#ifndef M_PI
const double M_PI = 3.14159265358979323846264338327950288;
#endif
#endif
const double M_2PI = M_PI * 2.0;
inline float _fmod( float x, float y ) { return fmod( fmod( x, y ) + y, y ); } | pinecrew/golos | src/math.hpp | C++ | mit | 271 |
define(function(require) {
var Checker = require("checkers/controller/Checker"),
GameBoard = require("checkers/controller/GameBoard"),
GameSpace = require("checkers/controller/GameSpace");
var instance = null;
function GameBoardUtil() {
}
var getInstance = function() {
if (instance === null) {
instance = new GameBoardUtil();
}
return instance;
}
GameBoardUtil.prototype.getValidMoves = function(checker, gameBoard, posDir) {
var validMoves = new Array();
$.merge(validMoves, this.getEmptySpaceMoves(checker, gameBoard, posDir));
$.merge(validMoves, this.getJumpMoves(checker, gameBoard, posDir));
return validMoves;
}
GameBoardUtil.prototype.getEmptySpaceMoves = function(checker, gameBoard, posDir) {
var emptySpaceMoves = new Array();
var row = checker.getRow() + posDir;
// Checks left move
if (this.isValidMove(row, checker.getColumn() - 1)) {
var gameSpace = gameBoard.getGameSpace(row, checker.getColumn() - 1)
if (gameSpace.isEmpty()) {
emptySpaceMoves.push(gameSpace);
}
}
// Checks right move
if (this.isValidMove(row, checker.getColumn() + 1)) {
var gameSpace = gameBoard.getGameSpace(row, checker.getColumn() + 1);
if (gameSpace.isEmpty()) {
emptySpaceMoves.push(gameSpace);
}
}
if (checker.isKing()) {
var kRow = checker.getRow() - posDir;
// Checks left move
if (this.isValidMove(kRow, checker.getColumn() - 1)) {
var gameSpace = gameBoard.getGameSpace(kRow, checker.getColumn() - 1)
if (gameSpace.isEmpty()) {
emptySpaceMoves.push(gameSpace);
}
}
// Checks right move
if (this.isValidMove(kRow, checker.getColumn() + 1)) {
var gameSpace = gameBoard.getGameSpace(kRow, checker.getColumn() + 1);
if (gameSpace.isEmpty()) {
emptySpaceMoves.push(gameSpace);
}
}
}
return emptySpaceMoves;
}
GameBoardUtil.prototype.isValidMove = function(row, column) {
if (row < 0 || row >= GameBoard.NUMSQUARES || column < 0 || column >= GameBoard.NUMSQUARES) {
return false;
}
return true;
}
GameBoardUtil.prototype.getJumpMoves = function(checker, gameBoard, posDir) {
var jumpMoves = new Array();
var row = checker.getRow() + posDir * 2;
// Checks left jump move
if (this.isValidMove(row, checker.getColumn() - 2)) {
var gameSpace = gameBoard.getGameSpace(row, checker.getColumn() - 2);
if (gameSpace.isEmpty()) {
var jumpedGameSpace = gameBoard.getGameSpace(row - posDir, checker.getColumn() - 1);
if (!jumpedGameSpace.isEmpty() && jumpedGameSpace.getChecker().getPlayerId() != checker.getPlayerId()) {
jumpMoves.push(gameSpace);
}
}
}
// Checks right jump move
if (this.isValidMove(row, checker.getColumn() + 2)) {
var gameSpace = gameBoard.getGameSpace(row, checker.getColumn() + 2);
if (gameSpace.isEmpty()) {
var jumpedGameSpace = gameBoard.getGameSpace(row - posDir, checker.getColumn() + 1);
if (!jumpedGameSpace.isEmpty() && jumpedGameSpace.getChecker().getPlayerId() != checker.getPlayerId()) {
jumpMoves.push(gameSpace);
}
}
}
if (checker.isKing()) {
// Checks left jump move
var kRow = checker.getRow() - posDir * 2;
if (this.isValidMove(kRow, checker.getColumn() - 2)) {
var gameSpace = gameBoard.getGameSpace(kRow, checker.getColumn() - 2);
if (gameSpace.isEmpty()) {
var jumpedGameSpace = gameBoard.getGameSpace(kRow + posDir, checker.getColumn() - 1);
if (!jumpedGameSpace.isEmpty() && jumpedGameSpace.getChecker().getPlayerId() != checker.getPlayerId()) {
jumpMoves.push(gameSpace);
}
}
}
// Checks right jump move
if (this.isValidMove(kRow, checker.getColumn() + 2)) {
var gameSpace = gameBoard.getGameSpace(kRow, checker.getColumn() + 2);
if (gameSpace.isEmpty()) {
var jumpedGameSpace = gameBoard.getGameSpace(kRow + posDir, checker.getColumn() + 1);
if (!jumpedGameSpace.isEmpty() && jumpedGameSpace.getChecker().getPlayerId() != checker.getPlayerId()) {
jumpMoves.push(gameSpace);
}
}
}
}
return jumpMoves;
}
return ({getInstance:getInstance});
}); | RobStrader/Robs-Arcade | js/checkers/util/GameBoardUtil.js | JavaScript | mit | 5,153 |
namespace Novell.Directory.Ldap.Sasl
{
public class SaslDigestMd5Request : SaslRequest
{
public string Host { get; }
public SaslDigestMd5Request()
: base(SaslConstants.Mechanism.DigestMd5)
{
}
public SaslDigestMd5Request(string username, string password, string realmName, string host)
: this()
{
AuthorizationId = username;
Credentials = password.ToUtf8Bytes();
RealmName = realmName;
Host = host;
}
}
}
| dsbenghe/Novell.Directory.Ldap.NETStandard | src/Novell.Directory.Ldap.NETStandard/Sasl/SaslDigestMd5Request.cs | C# | mit | 550 |
import { LOCAL_STORAGE_REMOVE_ITEM, LOCAL_STORAGE_SET_ITEM } from './actionTypes'
import createMiddleware from './middleware'
describe('middleware', () => {
let removeItem
let setItem
let middleware
let next
let store
beforeEach(() => {
removeItem = jest.fn()
setItem = jest.fn()
middleware = createMiddleware({
removeItem,
setItem,
})
next = jest.fn()
store = {
dispatch: jest.fn(),
getState: jest.fn(),
}
})
it('calls next on dummy actionType', () => {
const action = {
type: 'dummyType',
payload: {
key: 'key',
},
}
middleware(store)(next)(action)
expect(next.mock.calls.length).toBe(1)
})
it(`calls removeItem on ${LOCAL_STORAGE_REMOVE_ITEM}`, () => {
const action = {
type: LOCAL_STORAGE_REMOVE_ITEM,
payload: {
key: 'key',
},
}
middleware(store)(next)(action)
expect(removeItem.mock.calls.length).toBe(1)
})
it(`calls removeItem on ${LOCAL_STORAGE_SET_ITEM}`, () => {
const action = {
type: LOCAL_STORAGE_SET_ITEM,
payload: {
key: 'key',
value: 'value',
},
}
middleware(store)(next)(action)
expect(setItem.mock.calls.length).toBe(1)
})
})
| fredrikolovsson/redux-module-local-storage | src/middleware.test.js | JavaScript | mit | 1,262 |
<?php
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/**
* Description of THOR_ACCESSGROUPTYPES_DataBoundSimplePersistable
*
* @author KottkeDP
*/
class THOR_ACCESSGROUPTYPES_DataBoundSimplePersistable extends THOR_DataBoundSimplePersistable{
public function __construct($keyValue = null) {
$sourceKeys = unserialize(ACCESSGROUPTYPES_DBFIELDS);
$database = DB_NAME;
$table = ACCESSGROUPTYPES;
$keyName = GLOBAL_PRIMARY_KEY_NAME;
$isDirty = true;
parent::__construct($sourceKeys, $database, $table, $keyName, $keyValue, $isDirty);
}
}
?>
| USStateDept/thecurrent | bll/persistables/simplePersistables/THOR_ACCESSGROUPTYPES_DataBoundSimplePersistable.class.php | PHP | mit | 709 |
using Xunit;
using XUnit.Extensions.TestOrdering;
[assembly: TestCaseOrderer(DependencyTestCaseOrderer.Name, DependencyTestCaseOrderer.Assembly)]
[assembly: CollectionBehavior(CollectionBehavior.CollectionPerAssembly, DisableTestParallelization = true)]
[assembly: TestCollectionOrderer(DependencyTestCollectionOrderer.Name, DependencyTestCollectionOrderer.Assembly)] | Sebazzz/NetUnitTestComparison | src/BankAccountApp.XUnitTests.Integration/Properties/AssemblyInfo.cs | C# | mit | 371 |
require 'test_helper'
class WatchedExceptionTest < ActiveSupport::TestCase
should_have_named_scope :recent, :limit => 5
should_have_named_scope "recent(20)", :limit => 20
should_have_default_scope :order => "#{WatchedException.quoted_table_name}.created_at DESC"
context "A watched exception instance" do
setup { @watched_exception = Factory(:watched_exception) }
should_validate_uniqueness_of :key
should_validate_presence_of :key
should "generate the controller_action attribute on save" do
@watched_exception.controller_name = "test"
@watched_exception.action_name = "test"
assert_not_equal @watched_exception.controller_action, "test/test"
@watched_exception.save
assert_equal @watched_exception.controller_action, "test/test"
end
should "generate a key when created" do
@watched_exception = Factory.build(:watched_exception, :key => nil)
ActiveSupport::SecureRandom.expects(:hex).with(12).returns("new key")
@watched_exception.save
assert_equal "new key", @watched_exception.key
end
should "know how to generate its name attribute" do
@watched_exception.exception_class = "My Exception"
@watched_exception.stubs(:controller_action).returns("Controller Action")
assert_equal "My Exception in Controller Action", @watched_exception.name
end
end
should "list all exception classes" do
WatchedException.expects(:all).with(:select => "DISTINCT exception_class", :order => "exception_class").returns([])
WatchedException.exception_classes
end
should "list all controller actions" do
WatchedException.expects(:all).with(:select => "DISTINCT controller_action", :order => "controller_action").returns([])
WatchedException.controller_actions
end
end | joshuaclayton/watchtower | test/models/watched_exception_test.rb | Ruby | mit | 1,816 |
<?php
namespace Mawi\Bundle\FrostlogBundle\Controller;
use Symfony\Component\Security\Core\SecurityContext;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Symfony\Component\Yaml\Parser;
use Symfony\Component\Yaml\Exception\ParseException;
class FrontController extends Controller
{
/**
* @Route("/", name="front")
* @Template("MawiFrostlogBundle::layout.html.twig")
*/
public function frontAction()
{
return array();
}
/**
* @Route("/check", name="ajax_login_check")
*/
public function indexAction()
{
if (false === $this->get('security.context')->isGranted(
'IS_AUTHENTICATED_FULLY'
)) {
return new Response('NOT AUTHENTICATED');
}
$token = $this->get('security.context')->getToken();
if ($token) {
$user = $token->getUser();
if ($user) {
return new Response('OK');
} else {
return new Response('NO USER');
}
}
return new Response('NO TOKEN');
}
public function loginPageAction()
{
$request = $this->getRequest();
$session = $request->getSession();
// get the login error if there is one
if ($request->attributes->has(SecurityContext::AUTHENTICATION_ERROR)) {
$error = $request->attributes->get(SecurityContext::AUTHENTICATION_ERROR);
} else {
$error = $session->get(SecurityContext::AUTHENTICATION_ERROR);
$session->remove(SecurityContext::AUTHENTICATION_ERROR);
}
return $this->render('MawiFrostlogBundle:Front:login.html.twig', array(
// last username entered by the user
'last_username' => $session->get(SecurityContext::LAST_USERNAME),
'error' => $error,
));
}
/**
* @Route("/login", name="login")
*/
public function loginAction()
{
return $this->render('MawiFrostlogBundle::layout.html.twig', array(
// last username entered by the user
'content' => 'MawiFrostlogBundle:Front:loginPage',
));
}
/**
* @Route("/login/done", name="login_done")
*/
public function loginDoneAction()
{
return new Response('DONE');
}
/**
* @Route("/login/fail", name="login_fail")
*/
public function loginFailAction()
{
return new Response('FAIL');
}
/**
* @Route("/login_check", name="login_check")
*/
public function loginCheckAction()
{
}
/**
* @Route("/logout", name="logout")
*/
public function logoutAction()
{
}
}
| mawi12345/frostlog | src/Mawi/Bundle/FrostlogBundle/Controller/FrontController.php | PHP | mit | 2,772 |
<?php
namespace AppBundle\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
class SymptomType extends AbstractType
{
/**
* @param FormBuilderInterface $builder
* @param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('name')
->add('description')
->add('condition')
;
}
/**
* @param OptionsResolverInterface $resolver
*/
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'AppBundle\Entity\Symptom'
));
}
/**
* @return string
*/
public function getName()
{
return 'appbundle_symptom';
}
}
| garasuresh/practice2.6 | src/AppBundle/Form/SymptomType.php | PHP | mit | 905 |
# Methods added to this helper will be available to all templates in the application.
# origin: RM
module ApplicationHelper
def icon(icon, label)
content_tag(:span, label, :class => "#{icon}_icon")
end
def page_head(options = {})
html = ''.html_safe
html << content_tag(:h1, options[:title]) if options[:title]
html << render_navigation(options[:navigation]) if options[:navigation]
if html.present?
content_for(:page_head) do
content_tag(:div, :id => 'page_head') do
content_tag(:div, :id => 'page_head_inner') do
html
end
end
end
end
end
def page_navigation(navigation)
content_for(:page_navigation, render_navigation(navigation, :id => 'page_navigation'))
end
def uid
@@next_uid ||= 0
@@next_uid += 1
"element_uid_#{@@next_uid}"
end
# This method is supposed to work with Tex output. Don't use HTML entities.
def money_amount(amount)
if amount.present?
"#{amount.with_comma(2)} €" # this includes a nbsp!
else
"–" # ‐
end
end
def maybe_blank(value, options = {})
if value.present?
if options[:url] && Patterns::URL.match(value)
link_to(value, value)
elsif options[:simple_format]
simple_format(value)
else
value
end
else
'–'.html_safe
end
end
def body_id(id)
content_for :body_id, id
end
def help(message)
content_tag :span, "(#{h message})".html_safe, :class => 'help'
end
def clear
content_tag :div, '', :class => 'clear'
end
def todo(message)
content_tag :span, h(message), :class => 'todo'
end
def pagination(collection)
will_paginate collection, :previous_label => "« zurück", :next_label => "weiter »"
end
def buttons(options = {}, &block)
content = capture(&block)
if content.present?
content += content_tag(:div, options[:links], :class => 'links') if options[:links]
html = content_tag :div, content.html_safe, :class => "buttons #{options[:class]}"
block_called_from_erb?(block) ? concat(html) : html
end
end
def save_cancel_buttons(options = {})
cancel_path = options.delete(:cancel_path) || root_path
save_label = options.delete(:save_label) || "Save"
cancel_label = options.delete(:cancel_label) || "Cancel"
buttons(options.reverse_merge(:class => 'bar')) do
html = ''
html << submit_tag(save_label, :class => "submit", :disable_with => "Please wait...")
html << button_to_function(cancel_label, "location.href = '#{cancel_path}'")
html
end
end
def boring_create_button(options = {}, &block)
button = link_to(icon(:create, options[:label] || "Add"), new_object_path)
buttons(&prepend_html_to_block(button, block))
end
def boring_delete_button(options = {}, &block)
link_to(icon(:delete, "Delete"), object_url, :method => :delete)
end
def boring_edit_button(options = {}, &block)
link_to(icon(:edit, "Edit"), edit_object_url)
end
def prepend_html_to_block(html, block)
lambda do
concatenated = ''.html_safe
concatenated << html
concatenated << capture(&block) if block
concatenated
end
end
def boring_save_cancel_buttons(options = {})
target = translate_model_name(object)
deleted = object.respond_to?(:deleted?) && object.deleted?
links = options.delete(:links)
cancel_path = options.delete(:cancel_path) || collection_path
action = deleted ? "restore" : "delete"
delete_link = if options[:delete_link] && !object.new_record?
link_class = deleted ? "restore" : "delete"
label = icon(link_class, action.titleize)
confirm = options[:"confirm_#{link_class}"] || "#{action.titleize} this #{target}?"
confirm = confirm.call if confirm.respond_to?(:call)
link_to(label, object_url(object), :method => :delete, :confirm => confirm)
else
nil
end
save_cancel_buttons options.merge(
:links => "#{links} #{delete_link}".html_safe,
:cancel_path => cancel_path
)
end
def list
content_tag(:div, render('list'), :id => 'list')
end
def columns(&content)
concat(
content_tag(:div, capture(&content) + clear, :class => 'columns')
)
end
def column(options = {}, &content)
size_class = [options[:size], 'column'].compact.join('_')
klass = [size_class, options[:class]].join(' ')
content = capture(&content)
content = segment(:title => options[:segment], :content => content) if options[:segment]
html = content_tag(:div, :class => klass) do
content_tag(:div, content, :class => 'column_inner')
end
concat html
end
def segment(options = {}, &block)
title = options[:title]
html = ''
html << "<div class='segment #{options[:class]}' id='#{options[:id]}' data-show-for='#{options[:"data-show-for"]}'>"
html << "<h3 class=\"segment_title\"><span>#{title}</span></h3>" if title.present?
html << '<div class="segment_body">'
html << (options[:content] || capture(&block))
html << '</div>'
html << "</div>"
html = html.html_safe
block && block_called_from_erb?(block) ? concat(html) : html
end
def graceful_link_to_remote(name, options = {}, html_options = nil)
html_options ||= {}
link_to_remote(name, options, html_options.merge(:href => options[:url], :method => options[:method]))
end
end
| makandra/serum-rails | spec/test_apps/rails-2-3/app/helpers/application_helper.rb | Ruby | mit | 5,460 |
package market
import (
"github.com/Efruit/marqit/exchange"
"github.com/Efruit/marqit/managers"
"github.com/nu7hatch/gouuid"
"time"
)
type Exchange interface {
manager.Bank
manager.Broker
manager.Ticker
exchange.Dealership
exchange.Auctioner
Init() // Perform initial setup
RunID() (uuid.UUID, uint64, exchange.Mode) // Tell the Run identifier, open number, and exchange model.
AddStock(exchange.Stock) // Define a stock
IPO(exchange.Stock, float32, []exchange.LicenseID) // IPO a stock, volume specified by the exchange.Stock.Number, price by [2], initial holder(s) by [3]. If [3] is empty, the entirety will be given to a random trader.
List() []exchange.Stock // Retrieve the active stock list
Start(time.Duration, time.Duration, uint) // Run the simulation with a day length of [1] and a day count of [2]
Open() // Open the market
Pause() // Stop processing queue items
Resume() // Continue the queue
Close(Normal bool) exchange.Summary // Sound the closing bell. Normal specifies the nature of the closing.
Status() bool // Are we trading?
}
| Efruit/marqit | market/market.go | GO | mit | 1,270 |
import { isFunction } from './isFunction';
/**
* Used to match `RegExp`
* [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns).
*/
import { isObject } from './isObject';
import { isMasked } from './_isMasked';
import { toSource } from './_toSource';
const reRegExpChar = /[\\^$.*+?()[\]{}|]/g;
/** Used to detect host constructors (Safari). */
const reIsHostCtor = /^\[object .+?Constructor\]$/;
/** Used for built-in method references. */
const funcProto = Function.prototype,
objectProto = Object.prototype;
/** Used to resolve the decompiled source of functions. */
const funcToString = funcProto.toString;
/** Used to check objects for own properties. */
const hasOwnProperty = objectProto.hasOwnProperty;
/** Used to detect if a method is native. */
const reIsNative = RegExp(
'^' +
funcToString
.call(hasOwnProperty)
.replace(reRegExpChar, '\\$&')
.replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') +
'$'
);
/**
* The base implementation of `_.isNative` without bad shim checks.
* Returns `true` if `value` is a native function,
* else `false`.
* @param value The value to check.
*/
export function baseIsNative(value) {
if (!isObject(value) || isMasked(value)) {
return false;
}
const pattern = isFunction(value) ? reIsNative : reIsHostCtor;
return pattern.test(toSource(value));
}
| UIUXEngineering/ix-material | libs/fn/src/lib/_common/_baseIsNative.ts | TypeScript | mit | 1,398 |
jQuery.each(param_obj, function (index, value) {
if (!isNaN(value)) {
param_obj[index] = parseInt(value);
}
});
function Portfolio_Gallery_Full_Height(id) {
var _this = this;
_this.container = jQuery('#' + id + '.view-full-height');
_this.hasLoading = _this.container.data("show-loading") == "on";
_this.optionsBlock = _this.container.parent().find('div[id^="huge_it_portfolio_options_"]');
_this.filtersBlock = _this.container.parent().find('div[id^="huge_it_portfolio_filters_"]');
_this.content = _this.container.parent();
_this.element = _this.container.find('.portelement');
_this.defaultBlockHeight = param_obj.ht_view1_block_height;
_this.defaultBlockWidth = param_obj.ht_view1_block_width;
_this.optionSets = _this.optionsBlock.find('.option-set');
_this.optionLinks = _this.optionSets.find('a');
_this.sortBy = _this.optionsBlock.find('#sort-by');
_this.filterButton = _this.filtersBlock.find('ul li');
if (_this.container.data('show-center') == 'on' && ( ( !_this.content.hasClass('sortingActive') && !_this.content.hasClass('filteringActive') )
|| ( _this.optionsBlock.data('sorting-position') == 'top' && _this.filtersBlock.data('filtering-position') == 'top' ) ||
( _this.optionsBlock.data('sorting-position') == 'top' && _this.filtersBlock.data('filtering-position') == '' ) || ( _this.optionsBlock.data('sorting-position') == '' && _this.filtersBlock.data('filtering-position') == 'top' ) )) {
_this.isCentered = _this.container.data("show-center") == "on";
}
_this.documentReady = function () {
_this.container.hugeitmicro({
itemSelector: _this.element,
masonry: {
columnWidth: _this.defaultBlockWidth + 20 + param_obj.ht_view1_element_border_width * 2
},
masonryHorizontal: {
rowHeight: 300 + 20
},
cellsByRow: {
columnWidth: 300 + 20,
rowHeight: 240
},
cellsByColumn: {
columnWidth: 300 + 20,
rowHeight: 240
},
getSortData: {
symbol: function ($elem) {
return $elem.attr('data-symbol');
},
category: function ($elem) {
return $elem.attr('data-category');
},
number: function ($elem) {
return parseInt($elem.find('.number').text(), 10);
},
weight: function ($elem) {
return parseFloat($elem.find('.weight').text().replace(/[\(\)]/g, ''));
},
id: function ($elem) {
return $elem.find('.id').text();
}
}
});
setInterval(function(){
_this.container.hugeitmicro('reLayout');
});
};
_this.manageLoading = function () {
if (_this.hasLoading) {
_this.container.css({'opacity': 1});
_this.optionsBlock.css({'opacity': 1});
_this.filtersBlock.css({'opacity': 1});
_this.content.find('div[id^="huge-it-container-loading-overlay_"]').css('display', 'none');
}
};
_this.showCenter = function () {
if (_this.isCentered) {
var count = _this.element.length;
var elementwidth = _this.defaultBlockWidth + 10 + param_obj.ht_view1_element_border_width * 2;
var enterycontent = _this.content.width();
var whole = ~~(enterycontent / (elementwidth));
if (whole > count) whole = count;
if (whole == 0) {
return false;
}
else {
var sectionwidth = whole * elementwidth + (whole - 1) * 20;
}
_this.container.width(sectionwidth).css({
"margin": "0px auto",
"overflow": "hidden"
});
console.log(elementwidth + " " + enterycontent + " " + whole + " " + sectionwidth);
}
};
_this.addEventListeners = function () {
_this.optionLinks.on('click', _this.optionsClick);
_this.optionsBlock.find('#shuffle a').on('click',_this.randomClick);
_this.filterButton.on('click', _this.filtersClick);
jQuery(window).resize(_this.resizeEvent);
};
_this.resizeEvent = function(){
_this.container.hugeitmicro('reLayout');
_this.showCenter();
};
_this.optionsClick = function () {
var $this = jQuery(this);
if ($this.hasClass('selected')) {
return false;
}
var $optionSet = $this.parents('.option-set');
$optionSet.find('.selected').removeClass('selected');
$this.addClass('selected');
var options = {},
key = $optionSet.attr('data-option-key'),
value = $this.attr('data-option-value');
value = value === 'false' ? false : value;
options[key] = value;
if (key === 'layoutMode' && typeof changeLayoutMode === 'function') {
changeLayoutMode($this, options)
} else {
_this.container.hugeitmicro(options);
}
return false;
};
_this.randomClick = function () {
_this.container.hugeitmicro('shuffle');
_this.sortBy.find('.selected').removeClass('selected');
_this.sortBy.find('[data-option-value="random"]').addClass('selected');
return false;
};
_this.filtersClick = function () {
_this.filterButton.each(function () {
jQuery(this).removeClass('active');
});
jQuery(this).addClass('active');
// get filter value from option value
var filterValue = jQuery(this).attr('rel');
// use filterFn if matches value
_this.container.hugeitmicro({filter: filterValue});
};
_this.init = function () {
_this.showCenter();
jQuery(window).load(_this.manageLoading);
_this.documentReady();
_this.addEventListeners();
};
this.init();
}
var portfolios = [];
jQuery(document).ready(function () {
jQuery(".huge_it_portfolio_container.view-full-height").each(function (i) {
var id = jQuery(this).attr('id');
portfolios[i] = new Portfolio_Gallery_Full_Height(id);
});
}); | rahul121290/php | wp-content/plugins/portfolio-gallery/assets/js/view-full-height.js | JavaScript | mit | 6,558 |
/******************************************************************************
* The MIT License (MIT)
*
* Copyright (c) 2016-2019 Baldur Karlsson
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
******************************************************************************/
#include "core/core.h"
#include "hooks/hooks.h"
#include "os/os_specific.h"
void dlopen_hook_init();
// DllMain equivalent
void library_loaded()
{
if(LibraryHooks::Detect("renderdoc__replay__marker"))
{
RDCDEBUG("Not creating hooks - in replay app");
RenderDoc::Inst().SetReplayApp(true);
RenderDoc::Inst().Initialise();
return;
}
else
{
RenderDoc::Inst().Initialise();
const char *capturefile = Process::GetEnvVariable("RENDERDOC_CAPFILE");
const char *opts = Process::GetEnvVariable("RENDERDOC_CAPOPTS");
if(opts)
{
CaptureOptions optstruct;
optstruct.DecodeFromString(opts);
RDCLOG("Using delay for debugger %u", optstruct.delayForDebugger);
RenderDoc::Inst().SetCaptureOptions(optstruct);
}
if(capturefile)
{
RenderDoc::Inst().SetCaptureFileTemplate(capturefile);
}
std::string curfile;
FileIO::GetExecutableFilename(curfile);
RDCLOG("Loading into %s", curfile.c_str());
LibraryHooks::RegisterHooks();
// we have a short sleep here to allow target control to connect, since unlike windows we can't
// suspend the process during startup.
Threading::Sleep(15);
}
}
// wrap in a struct to enforce ordering. This file is
// linked last, so all other global struct constructors
// should run first
struct init
{
init() { library_loaded(); }
} do_init;
// we want to be sure the constructor and library_loaded are included even when this is in a static
// library, so we have this global function that does nothing but takes the address.
extern "C" __attribute__((visibility("default"))) void *force_include_libentry()
{
return &do_init;
}
| TurtleRockStudios/renderdoc_public | renderdoc/os/posix/posix_libentry.cpp | C++ | mit | 2,988 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Copyright (C), 2013, The Schilduil Team. All rights reserved.
"""
import sys
import pony.orm
import suapp.orm
from suapp.logdecorator import loguse, logging
__all__ = ["Wooster", "Drone", "Jeeves"]
class FlowException(Exception):
pass
class ApplicationClosed(FlowException):
pass
class Wooster:
"""
A Wooster represents a UI window/page.
GENERALLY THESE THINGS ARE REUSED SO YOU NEED TO BE VERY CAREFUL ABOUT SIDE EFFECTS.
In case you have something that cannot be reused do something like:
1/ Create a new class instance of a subclass of Wooster
2/ Call inflow on that
"""
def lock(self):
pass
def unlock(self):
pass
def inflow(self, jeeves, drone):
# The only thing it does is store the Jeeves object.
self.jeeves = jeeves
# MODE: Modal=1, Replace=2, Both=3
# jeeves.drone(self, name, mode, dataobject)
def close(self):
pass
def toJSON(self):
return "Wooster %s" % (hex(self.__hash__()))
class Drone(object):
"""
A drone is the connection between two vertices.
"""
def __init__(self, name, tovertex):
self.name = name
self.tovertex = tovertex
@loguse
def get_new_instance_clone(self, dataobject, mode):
"""
Clone the drone and add the dataobject and mode.
"""
drone = Drone(self.name, self.tovertex)
drone.dataobject = dataobject
drone.mode = mode
return drone
def toJSON(self):
return "Drone %s > %s" % (self.name, self.tovertex)
class Jeeves(object):
"""
Jeeves is the controller that determins the flow.
It uses Drones to go from Wooster to Wooster.
"""
MODE_OPEN = 3
MODE_REPLACE = 2
MODE_MODAL = 1
@loguse
def __init__(self, app=None):
"""
Initializes the Jeeves with an empty flow and app name.
"""
self.flow = {"": {}}
self.app = app
self.views = {}
self.queries = {}
# TODO: I have no idea why I added ormscope: get rid of it?
self.ormscope = {}
def toJSON(self):
"""
Makes this object be made into json.
"""
return "Jeeves %s" % (hex(self.__hash__()))
@loguse
def whichDrone(self, fromname, outmessage, **kwargs):
"""
Finding the drone matching the outmessage.
"""
logging.getLogger(__name__).debug(
": Jeeves[%r].whichDrone : Flow: %s", self, self.flow
)
drone = None
try:
drone = self.flow[fromname][outmessage]
except:
try:
drone = self.flow[""][outmessage]
except:
# TODO: do something else then bluntly exiting.
logging.getLogger(__name__).error(
": Jeeves[%r].whichDrone : Not found '%s' - exiting.",
self,
outmessage,
)
if outmessage == "EXIT":
raise ApplicationClosed()
else:
raise FlowException("Unknown outmessage: %s" % (outmessage))
return drone
@loguse("@") # Not logging the return value.
def _do_query_str(self, query_template, scope, parameters):
"""
Execute a query that is a string.
DEPRECATED
"""
query = query_template % parameters
exec("result = %s" % (query), scope)
return scope["result"]
@loguse("@") # Not logging the return value.
def pre_query(self, name, scope=None, params=None):
"""
Returns the the query and parameters.
The query and the default parameters are looked up in self.queries.
The parameters are next updated with the passed params.
The self.queries is filled by moduleloader from the loaded modlib's
view_definitions() function.
"""
if scope is None:
scope = {}
query_template, defaults = self.queries[name]
# Start with the default defined.
parameters = defaults.copy()
parameters.update(params)
# Making sure the paging parameters are integers.
try:
parameters["pagenum"] = int(parameters["pagenum"])
except:
parameters["pagenum"] = 1
try:
parameters["pagesize"] = int(parameters["pagesize"])
except:
parameters["pagesize"] = 10
logging.getLogger(__name__).debug(
"Paging #%s (%s)", parameters["pagenum"], parameters["pagesize"]
)
return (query_template, parameters)
@loguse("@") # Not loggin the return value.
def do_query(self, name, scope=None, params=None):
"""
Executes a query by name and return the result.
The result is always a UiOrmObject by using UiOrmObject.uize on the
results of the query.
"""
query_template, parameters = self.pre_query(name, scope, params)
if callable(query_template):
# A callable, so just call it.
result = query_template(params=parameters)
else:
# DEPRECATED: python code as a string.
result = self._do_query_str(query_template, scope, parameters)
return (suapp.orm.UiOrmObject.uize(r) for r in result)
@loguse
def do_fetch_set(self, module, table, primarykey, link):
"""
Fetches the result from a foreign key that is a set.
This will return the list of objects representing the rows in the
database pointed to by the foreign key (which name should be passed in
link). The return type is either a list of suapp.orm.UiOrmObject's.
Usually you can follow the foreign key directly, but not in an
asynchronous target (UI) like the web where you need to fetch it anew.
For foreign keys that are not sets you can use do_fetch.
The module, table and primarykey are those from the object having the
foreign key and behave the same as with do_fetch. The extra parameter
link is the foreign key that is pointing to the set.
"""
origin = self.do_fetch(module, table, primarykey)
result = getattr(origin, link)
return (suapp.orm.UiOrmObject.uize(r) for r in result)
@loguse
def do_fetch(self, module, table, primarykey):
"""
Fetches a specific object from the database.
This will return the object representing a row in the
specified table from the database. The return type is
either a pony.orm.core.Entity or suapp.orm.UiOrmObject
subclass, depending on the class name specified in table.
Parameters:
- module: In what module the table is defined.
This should start with modlib.
- table: Class name of the object representing the table.
The class should be a subclass of either
- pony.orm.core.Entity
- suapp.orm.UiOrmObject
- primarykey: A string representing the primary key value
or a list of values (useful in case of a
multi variable primary key).
"""
if isinstance(primarykey, str):
primarykey = [primarykey]
module = sys.modules[module]
table_class = getattr(module, table)
params = {}
if issubclass(table_class, pony.orm.core.Entity):
pk_columns = table_class._pk_columns_
elif issubclass(table_class, suapp.orm.UiOrmObject):
pk_columns = table_class._ui_class._pk_columns_
else:
return None
if len(pk_columns) == 1:
if len(primarykey) == 1:
params[pk_columns[0]] = primarykey[0]
else:
i = 0
for column in pk_columns:
params[column] = primarykey[i]
i += 1
# Checking if the primary key is a foreign key.
for column in pk_columns:
logging.getLogger(__name__).debug(
"Primary key column: %s = %s", column, params[column]
)
logging.getLogger(__name__).debug("Fetching %s (%s)", table_class, params)
if issubclass(table_class, suapp.orm.UiOrmObject):
return table_class(**params)
else:
return table_class.get(**params)
@loguse("@") # Not logging the return value.
def drone(self, fromvertex, name, mode, dataobject, **kwargs):
"""
Find the drone and execute it.
"""
# Find the drone
fromname = ""
result = None
if isinstance(fromvertex, Wooster):
fromname = fromvertex.name
else:
fromname = str(fromvertex)
drone_type = self.whichDrone(fromname, name, **kwargs)
# Clone a new instance of the drone and setting dataobject & mode.
drone = drone_type.get_new_instance_clone(dataobject, mode)
# If there is a callback, call it.
if "callback_drone" in kwargs:
try:
kwargs["callback_drone"](drone)
except:
pass
# Depending on the mode
# Some targets depend on what is returned from inflow.
if mode == self.MODE_MODAL:
if isinstance(fromvertex, Wooster):
fromvertex.lock()
drone.fromvertex = fromvertex
result = drone.tovertex.inflow(self, drone)
if isinstance(fromvertex, Wooster):
fromvertex.unlock()
elif mode == self.MODE_REPLACE:
drone.fromvertex = None
fromvertex.close()
result = drone.tovertex.inflow(self, drone)
elif mode == self.MODE_OPEN:
drone.fromvertex = fromvertex
result = drone.tovertex.inflow(self, drone)
return result
@loguse
def start(self, dataobject=None):
"""
Start the Jeeves flow.
"""
self.drone("", "START", self.MODE_MODAL, dataobject)
if __name__ == "__main__":
logging.basicConfig(
format="%(asctime)s %(levelname)s %(name)s %(message)s", level=logging.DEBUG
)
logging.getLogger("__main__").setLevel(logging.DEBUG)
modulename = "__main__"
print(
"__main__: %s (%s)"
% (
modulename,
logging.getLevelName(logging.getLogger(modulename).getEffectiveLevel()),
)
)
class Application(Wooster):
name = "APP"
def inflow(self, jeeves, drone):
self.jeeves = jeeves
print(
"""This is the Jeeves and Wooster library!
Jeeves is Wooster's indispensible valet: a gentleman's personal
gentleman. In fact this Jeeves can manage more then one Wooster
(so he might not be that personal) and guide information from one
Wooster to another in an organised way making all the Woosters
march to the drones.
"""
)
def lock(self):
pass
def unlock(self):
pass
def close(self):
pass
flow = Jeeves()
flow.flow = {"": {"START": Drone("START", Application())}}
flow.start()
| schilduil/suapp | suapp/jandw.py | Python | mit | 11,304 |
using MyRoutine.Service;
using MyRoutine.Service.Interfaces;
using MyRoutine.Web.Areas.Admin.ViewModels.Users;
using MyRoutine.Web.Controllers;
using MyRoutine.Web.Helpers;
using MyRoutine.Web.ViewModels;
using System.Linq;
using System.Web.Mvc;
using WebMatrix.WebData;
namespace MyRoutine.Web.Areas.Admin.Controllers
{
[Authorize(Roles = "Admin")]
public class UsersController : BaseController
{
readonly IUserService _userService;
readonly ValidationHelper _validationHelper;
public UsersController(IUserService userService, IPickyMessageService pickyMessageService)
{
_userService = userService;
_validationHelper = new ValidationHelper(pickyMessageService, UserSessionData.Name);
}
public ActionResult Index()
{
return View();
}
public JsonResult GetAll(GridFiltersViewModel gridFiltersViewModel)
{
var userGridViewModel = new UserGridViewModel { GridFilters = gridFiltersViewModel };
var users = _userService.GetAllWithFilters(WebSecurity.CurrentUserId, userGridViewModel.GridFilters.Search, userGridViewModel.GridFilters.SearchAdditional,
userGridViewModel.GridFilters.SortColumn, userGridViewModel.GridFilters.SortDirectionIsAscending,
userGridViewModel.GridFilters.Page, userGridViewModel.GridFilters.PageSize);
userGridViewModel.Users = (from user in users
where user.Id != WebSecurity.CurrentUserId
select new UserViewModel
{
Id = user.Id,
Email = user.Email,
Name = user.Name,
DateRegistered = user.DateRegistered,
LastLoginAt = user.LastLoginAt,
IsBanned = user.IsBanned,
BanDate = user.BanDate,
BanReason = user.BanReason,
MembershipIsConfirmed = user.Membership.IsConfirmed
}).ToList();
userGridViewModel.GridFilters.ItemCount = _userService.CountAllWithFilters(WebSecurity.CurrentUserId, userGridViewModel.GridFilters.Search, userGridViewModel.GridFilters.SearchAdditional);
return Json(_validationHelper.ModelStateToJsonResult(ModelState, userGridViewModel), JsonRequestBehavior.AllowGet);
}
[HttpPost]
public JsonResult Ban(BanUserViewModel viewModel)
{
if (ModelState.IsValid)
{
var user = _userService.GetById(viewModel.Id);
if (user != null)
{
_userService.Ban(user, viewModel.BanReason.Trim());
}
else
{
ModelState.AddModelError("", @"An error occured while banning the user.");
}
}
return Json(_validationHelper.ModelStateToJsonResult(ModelState, null, PickyMessageType.BanUserSuccess));
}
[HttpPost]
public JsonResult Unban(int id)
{
var user = _userService.GetById(id);
if (user != null)
{
_userService.Unban(user);
}
else
{
ModelState.AddModelError("", @"An error occured while unbanning the user.");
}
return Json(_validationHelper.ModelStateToJsonResult(ModelState, null, PickyMessageType.UnbanUserSuccess));
}
[HttpPost]
public JsonResult Delete(int id)
{
var user = _userService.GetById(id);
if (user != null)
{
_userService.Delete(user);
}
else
{
ModelState.AddModelError("", @"An error occured while deleting the user.");
}
return Json(_validationHelper.ModelStateToJsonResult(ModelState, null, PickyMessageType.DeleteUserSuccess));
}
}
} | davidtimovski/my-routine | MyRoutine.Web/Areas/Admin/Controllers/UsersController.cs | C# | mit | 4,329 |
package com.doctorAppointmentBookingSystem.repository;
import com.doctorAppointmentBookingSystem.entity.Role;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
/**
* Created by Edi on 16-Apr-17.
*/
@Repository
public interface RoleRepository extends JpaRepository<Role, Long> {
Role findOneByAuthority(String authority);
}
| eslavov11/Doctor-Appointment-Booking-System | src/main/java/com/doctorAppointmentBookingSystem/repository/RoleRepository.java | Java | mit | 393 |
import numpy
from chainer import cuda
from chainer import function
from chainer.utils import array
from chainer.utils import type_check
class BilinearFunction(function.Function):
def check_type_forward(self, in_types):
n_in = type_check.eval(in_types.size())
if n_in != 3 and n_in != 6:
raise type_check.InvalidType(
'%s or %s' % (in_types.size() == 3, in_types.size() == 6),
'%s == %s' % (in_types.size(), n_in))
e1_type, e2_type, W_type = in_types[:3]
type_check_prod = type_check.make_variable(numpy.prod, 'prod')
type_check.expect(
e1_type.dtype == numpy.float32,
e1_type.ndim >= 2,
e2_type.dtype == numpy.float32,
e2_type.ndim >= 2,
e1_type.shape[0] == e2_type.shape[0],
W_type.dtype == numpy.float32,
W_type.ndim == 3,
type_check_prod(e1_type.shape[1:]) == W_type.shape[0],
type_check_prod(e2_type.shape[1:]) == W_type.shape[1],
)
if n_in == 6:
out_size = W_type.shape[2]
V1_type, V2_type, b_type = in_types[3:]
type_check.expect(
V1_type.dtype == numpy.float32,
V1_type.ndim == 2,
V1_type.shape[0] == W_type.shape[0],
V1_type.shape[1] == out_size,
V2_type.dtype == numpy.float32,
V2_type.ndim == 2,
V2_type.shape[0] == W_type.shape[1],
V2_type.shape[1] == out_size,
b_type.dtype == numpy.float32,
b_type.ndim == 1,
b_type.shape[0] == out_size,
)
def forward(self, inputs):
e1 = array.as_mat(inputs[0])
e2 = array.as_mat(inputs[1])
W = inputs[2]
if not type_check.same_types(*inputs):
raise ValueError('numpy and cupy must not be used together\n'
'type(W): {0}, type(e1): {1}, type(e2): {2}'
.format(type(W), type(e1), type(e2)))
xp = cuda.get_array_module(*inputs)
if xp is numpy:
y = numpy.einsum('ij,ik,jkl->il', e1, e2, W)
else:
i_len, j_len = e1.shape
k_len = e2.shape[1]
# 'ij,ik->ijk'
e1e2 = e1[:, :, None] * e2[:, None, :]
# ijk->i[jk]
e1e2 = e1e2.reshape(i_len, j_len * k_len)
# jkl->[jk]l
W_mat = W.reshape(-1, W.shape[2])
# 'i[jk],[jk]l->il'
y = e1e2.dot(W_mat)
if len(inputs) == 6:
V1, V2, b = inputs[3:]
y += e1.dot(V1)
y += e2.dot(V2)
y += b
return y,
def backward(self, inputs, grad_outputs):
e1 = array.as_mat(inputs[0])
e2 = array.as_mat(inputs[1])
W = inputs[2]
gy = grad_outputs[0]
xp = cuda.get_array_module(*inputs)
if xp is numpy:
gW = numpy.einsum('ij,ik,il->jkl', e1, e2, gy)
ge1 = numpy.einsum('ik,jkl,il->ij', e2, W, gy)
ge2 = numpy.einsum('ij,jkl,il->ik', e1, W, gy)
else:
kern = cuda.reduce('T in0, T in1, T in2', 'T out',
'in0 * in1 * in2', 'a + b', 'out = a', 0,
'bilinear_product')
e1_b = e1[:, :, None, None] # ij
e2_b = e2[:, None, :, None] # ik
gy_b = gy[:, None, None, :] # il
W_b = W[None, :, :, :] # jkl
gW = kern(e1_b, e2_b, gy_b, axis=0) # 'ij,ik,il->jkl'
ge1 = kern(e2_b, W_b, gy_b, axis=(2, 3)) # 'ik,jkl,il->ij'
ge2 = kern(e1_b, W_b, gy_b, axis=(1, 3)) # 'ij,jkl,il->ik'
ret = ge1.reshape(inputs[0].shape), ge2.reshape(inputs[1].shape), gW
if len(inputs) == 6:
V1, V2, b = inputs[3:]
gV1 = e1.T.dot(gy)
gV2 = e2.T.dot(gy)
gb = gy.sum(0)
ge1 += gy.dot(V1.T)
ge2 += gy.dot(V2.T)
ret += gV1, gV2, gb
return ret
def bilinear(e1, e2, W, V1=None, V2=None, b=None):
"""Applies a bilinear function based on given parameters.
This is a building block of Neural Tensor Network (see the reference paper
below). It takes two input variables and one or four parameters, and
outputs one variable.
To be precise, denote six input arrays mathematically by
:math:`e^1\\in \\mathbb{R}^{I\\cdot J}`,
:math:`e^2\\in \\mathbb{R}^{I\\cdot K}`,
:math:`W\\in \\mathbb{R}^{J \\cdot K \\cdot L}`,
:math:`V^1\\in \\mathbb{R}^{J \\cdot L}`,
:math:`V^2\\in \\mathbb{R}^{K \\cdot L}`, and
:math:`b\\in \\mathbb{R}^{L}`,
where :math:`I` is mini-batch size.
In this document, we call :math:`V^1`, :math:`V^2`, and :math:`b` linear
parameters.
The output of forward propagation is calculated as
.. math::
y_{il} = \\sum_{jk} e^1_{ij} e^2_{ik} W_{jkl} + \\
\\sum_{j} e^1_{ij} V^1_{jl} + \\sum_{k} e^2_{ik} V^2_{kl} + b_{l}.
Note that V1, V2, b are optional. If these are not given, then this
function omits the last three terms in the above equation.
.. note::
This function accepts an input variable ``e1`` or ``e2`` of a non-matrix
array. In this case, the leading dimension is treated as the batch
dimension, and the other dimensions are reduced to one dimension.
.. note::
In the original paper, :math:`J` and :math:`K`
must be equal and the author denotes :math:`[V^1 V^2]`
(concatenation of matrices) by :math:`V`.
Args:
e1 (~chainer.Variable): Left input variable.
e2 (~chainer.Variable): Right input variable.
W (~chainer.Variable): Quadratic weight variable.
V1 (~chainer.Variable): Left coefficient variable.
V2 (~chainer.Variable): Right coefficient variable.
b (~chainer.Variable): Bias variable.
Returns:
~chainer.Variable: Output variable.
See:
`Reasoning With Neural Tensor Networks for Knowledge Base Completion
<http://papers.nips.cc/paper/5028-reasoning-with-neural-tensor-
networks-for-knowledge-base-completion>`_ [Socher+, NIPS2013].
"""
flags = [V1 is None, V2 is None, b is None]
if any(flags):
if not all(flags):
raise ValueError('All coefficients and bias for bilinear() must '
'be None, if at least one of them is None.')
return BilinearFunction()(e1, e2, W)
else:
return BilinearFunction()(e1, e2, W, V1, V2, b)
| kashif/chainer | chainer/functions/connection/bilinear.py | Python | mit | 6,625 |
import s from './Callouts.css';
import React, { PropTypes } from 'react';
import numbro from 'numbro';
function diversityAtParityOrGreater(conf) {
return conf.diversityPercentage >= 50;
}
function confFromCurrentYear(conf) {
return conf.year == (new Date()).getFullYear();
}
function diversityAccumulator(accumulator, conf) {
return accumulator + conf.diversityPercentage;
}
function diversitySorter(confA, confB) {
if (confA.diversityPercentage < confB.diversityPercentage) {
return 1;
}
if (confA.diversityPercentage > confB.diversityPercentage) {
return -1;
}
return 0;
}
class Callouts extends React.Component {
constructor(props) {
super(props);
this.currentYearConfs = props.confs.filter(confFromCurrentYear);
this.state = {
confs: props.confs,
bestPerformer: props.confs.sort(diversitySorter)[0],
numberOfConfs: props.confs.length,
numberOfConfsAtParityOrGreater: props.confs.filter(diversityAtParityOrGreater).length,
averageDiversity: props.confs.reduce(diversityAccumulator, 0) / props.confs.length,
averageDiversityCurrentYear: this.currentYearConfs.reduce(diversityAccumulator, 0) / this.currentYearConfs.length
};
}
render() {
return (
<div className={s.container}>
<div className="row">
<div className="col-sm-2">
<div className={s.title}>Conferences<br/>tracked</div>
<div className={s.pop}>{this.state.numberOfConfs}</div>
</div>
<div className="col-sm-2">
<div className={s.title}>Best<br/>performer</div>
<div className={s.body}><strong>{this.state.bestPerformer.name} ({this.state.bestPerformer.year})</strong><br/>{numbro(this.state.bestPerformer.diversityPercentage).format('0')}%</div>
</div>
<div className="col-sm-2">
<div className={s.title}>Biggest recent improver</div>
<div className={s.body}><strong>1st Conf</strong><br/>+36%<br/>2016 -> 2017</div>
</div>
<div className="col-sm-2" id={s.nbrConfAtParity}>
<div className={s.title}>#confs >= 50%<br/>diversity</div>
<div className={s.pop}>{this.state.numberOfConfsAtParityOrGreater}</div>
</div>
<div className="col-sm-2">
<div className={s.title}>Average<br/>f:m%</div>
<div className={s.pop}>{numbro(this.state.averageDiversity).format('0')}%</div>
</div>
<div className="col-sm-2">
<div className={s.title}>Average<br/>f:m% (2017)</div>
<div className={s.pop}>{numbro(this.state.averageDiversityCurrentYear).format('0')}%</div>
</div>
</div>
</div>
);
}
}
export default Callouts;
| andeemarks/conf-gen-div-react | components/Callouts/Callouts.js | JavaScript | mit | 2,762 |
/*! simpler-sidebar v1.4.9 (https://github.com/dcdeiv/simpler-sidebar)
** Copyright (c) 2015 - 2016 Davide Di Criscito
** Dual licensed under MIT and GPL-2.0
*/
( function( $ ) {
$.fn.simplerSidebar = function( options ) {
var cfg = $.extend( true, $.fn.simplerSidebar.settings, options );
return this.each( function() {
var align, sbw, ssbInit, ssbStyle, maskInit, maskStyle,
attr = cfg.attr,
$sidebar = $( this ),
$opener = $( cfg.opener ),
$links = cfg.sidebar.closingLinks,
duration = cfg.animation.duration,
sbMaxW = cfg.sidebar.width,
gap = cfg.sidebar.gap,
winMaxW = sbMaxW + gap,
w = $( window ).width(),
animationStart = {},
animationReset = {},
hiddenFlow = function() {
$( "body, html" ).css( "overflow", "hidden" );
},
autoFlow = function() {
$( "body, html" ).css( "overflow", "auto" );
},
activate = {
duration: duration,
easing: cfg.animation.easing,
complete: hiddenFlow
},
deactivate = {
duration: duration,
easing: cfg.animation.easing,
complete: autoFlow
},
animateOpen = function() {
$sidebar
.animate( animationStart, activate )
.attr( "data-" + attr, "active" );
$mask.fadeIn( duration );
},
animateClose = function() {
$sidebar
.animate( animationReset, deactivate )
.attr( "data-" + attr, "disabled" );
$mask.fadeOut( duration );
},
closeSidebar = function() {
var isWhat = $sidebar.attr( "data-" + attr ),
csbw = $sidebar.width();
animationReset[ align ] = -csbw;
if ( isWhat === "active" ) {
animateClose();
}
},
$mask = $( "<div>" ).attr( "data-" + attr, "mask" );
//Checking sidebar align
if ( [ undefined, "right" ].indexOf( cfg.sidebar.align ) !== -1 ) {
align = "right";
} else if ( cfg.sidebar.align === "left" ) {
align = "left";
} else {
console.log( "ERR sidebar.align: you typed \"" + cfg.sidebar.align + "\". You should choose between \"right\" or \"left\"." );
}
//Sidebar style
if ( w < winMaxW ) {
sbw = w - gap;
} else {
sbw = sbMaxW;
}
ssbInit = {
position: "fixed",
top: cfg.top,
bottom: 0,
width: sbw
};
ssbInit[ align ] = -sbw;
animationStart[ align ] = 0;
ssbStyle = $.extend( true, ssbInit, cfg.sidebar.css );
$sidebar.css( ssbStyle )
.attr( "data-" + attr, "disabled" );
//Mask style
maskInit = {
position: "fixed",
top: cfg.top,
right: 0,
bottom: 0,
left: 0,
zIndex: cfg.sidebar.css.zIndex - 1,
display: "none"
};
maskStyle = $.extend( true, maskInit, cfg.mask.css );
//Appending Mask if mask.display is true
if ( [ true, "true", false, "false" ].indexOf( cfg.mask.display) !== -1 ) {
if ( [ true, "true" ].indexOf( cfg.mask.display ) !== -1 ) {
$mask.appendTo( "body" ).css( maskStyle );
}
} else {
console.log( "ERR mask.display: you typed \"" + cfg.mask.display + "\". You should choose between true or false." );
}
//Opening and closing the Sidebar when $opener is clicked
$opener.click( function() {
var isWhat = $sidebar.attr( "data-" + attr ),
csbw = $sidebar.width();
animationReset[ align ] = -csbw;
if ( isWhat === "disabled" ) {
animateOpen();
} else if ( isWhat === "active" ) {
animateClose();
}
});
//Closing Sidebar when the mask is clicked
$mask.click( closeSidebar );
//Closing Sidebar when a link inside of it is clicked
$sidebar.on( "click", $links, closeSidebar );
//Adjusting width;
$( window ).resize( function() {
var rsbw, update,
isWhat = $sidebar.attr( "data-" + attr ),
nw = $( window ).width();
if ( nw < winMaxW ) {
rsbw = nw - gap;
} else {
rsbw = sbMaxW;
}
update = {
width: rsbw
};
if ( isWhat === "disabled" ) {
update[ align ] = -rsbw;
$sidebar.css( update );
} else if ( isWhat === "active" ) {
$sidebar.css( update );
}
});
});
};
$.fn.simplerSidebar.settings = {
attr: "simplersidebar",
top: 0,
animation: {
duration: 500,
easing: "swing"
},
sidebar: {
width: 300,
gap: 64,
closingLinks: "a",
css: {
zIndex: 3000
}
},
mask: {
display: true,
css: {
backgroundColor: "black",
opacity: 0.5,
filter: "Alpha(opacity=50)"
}
}
};
} )( jQuery );
| matrharr/first_aid | bower_components/simpler-sidebar/dist/jquery.simpler-sidebar.js | JavaScript | mit | 4,289 |
package com.github.niwaniwa.we.core.player;
import com.github.niwaniwa.we.core.api.callback.Callback;
import com.github.niwaniwa.we.core.twitter.TwitterManager;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Location;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Player;
import org.bukkit.inventory.Inventory;
import org.bukkit.permissions.Permission;
import twitter4j.Status;
import twitter4j.StatusUpdate;
import java.lang.reflect.InvocationTargetException;
import java.net.InetSocketAddress;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;
public abstract class EggPlayer implements Twitter, WhitePlayer {
private UUID uuid;
private Player player;
public EggPlayer(Player player) {
this.uuid = player.getUniqueId();
this.player = player;
}
public EggPlayer(UUID uuid){
this.uuid = uuid;
this.player = getPlayer();
}
@Override
public void remove() {
player.remove();
}
@Override
public String getName() {
return player.getName();
}
@Override
public String getFullName() {
return getPrefix() + getName();
}
@Override
public Player getPlayer() {
return Bukkit.getPlayer(uuid);
}
public void update(){
this.player = getPlayer();
}
@Override
public UUID getUniqueId() {
return player.getUniqueId();
}
@Override
public boolean isOp() {
return player.isOp();
}
@Override
public boolean isOnline() {
return player.isOnline();
}
@Override
public void sendMessage(String message) {
this.sendMessage(message, true);
}
@Override
public void sendMessage(String[] message) {
Arrays.asList(message).forEach(msg -> sendMessage(msg, true));
}
@Override
public void sendMessage(String message, boolean replaceColorCode) {
player.sendMessage(ChatColor.translateAlternateColorCodes('&', message));
}
@Override
public TwitterManager getTwitterManager() {
throw new UnsupportedOperationException(getClass().getSimpleName());
}
@Override
public boolean hasPermission(String permission) {
return player.hasPermission(permission);
}
@Override
public boolean hasPermission(Permission permission) {
return player.hasPermission(permission);
}
@Override
public InetSocketAddress getAddress() {
return player.getAddress();
}
@Override
public Object getHandle() {
Object object = null;
try {
object = player.getClass().getMethod("getHandle").invoke(player);
} catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
e.printStackTrace();
}
return object;
}
@Override
public Location getLocation() {
return player.getLocation();
}
@Override
public Inventory getInventory() {
return player.getInventory();
}
@Override
public void teleport(Location loc) {
player.teleport(loc);
}
@Override
public void teleport(Entity entity) {
player.teleport(entity);
}
@Override
public void updateStatus(StatusUpdate update) {
throw new UnsupportedOperationException(getClass().getSimpleName());
}
@Override
public void updateStatus(StatusUpdate update, Callback callback) {
throw new UnsupportedOperationException(getClass().getSimpleName());
}
@Override
public void updateStatus(String tweet) {
throw new UnsupportedOperationException(getClass().getSimpleName());
}
@Override
public List<Status> getTimeLine() {
throw new UnsupportedOperationException(getClass().getSimpleName());
}
}
| niwaniwa/WhiteEggCore | src/main/java/com/github/niwaniwa/we/core/player/EggPlayer.java | Java | mit | 3,854 |
package mcjty.rftools.blocks.dimlets;
import mcjty.lib.container.GenericGuiContainer;
import mcjty.lib.gui.Window;
import mcjty.lib.gui.layout.PositionalLayout;
import mcjty.lib.gui.widgets.EnergyBar;
import mcjty.lib.gui.widgets.ImageLabel;
import mcjty.lib.gui.widgets.Panel;
import mcjty.lib.gui.widgets.Widget;
import mcjty.rftools.RFTools;
import mcjty.rftools.network.RFToolsMessages;
import net.minecraft.util.ResourceLocation;
import net.minecraftforge.common.util.ForgeDirection;
import java.awt.*;
public class GuiDimletScrambler extends GenericGuiContainer<DimletScramblerTileEntity> {
public static final int SCRAMBLER_WIDTH = 180;
public static final int SCRAMBLER_HEIGHT = 152;
private EnergyBar energyBar;
private ImageLabel progressIcon;
private static final ResourceLocation iconLocation = new ResourceLocation(RFTools.MODID, "textures/gui/dimletscrambler.png");
private static final ResourceLocation iconGuiElements = new ResourceLocation(RFTools.MODID, "textures/gui/guielements.png");
public GuiDimletScrambler(DimletScramblerTileEntity pearlInjectorTileEntity, DimletScramblerContainer container) {
super(RFTools.instance, RFToolsMessages.INSTANCE, pearlInjectorTileEntity, container, RFTools.GUI_MANUAL_DIMENSION, "scrambler");
pearlInjectorTileEntity.setCurrentRF(pearlInjectorTileEntity.getEnergyStored(ForgeDirection.DOWN));
xSize = SCRAMBLER_WIDTH;
ySize = SCRAMBLER_HEIGHT;
}
@Override
public void initGui() {
super.initGui();
int maxEnergyStored = tileEntity.getMaxEnergyStored(ForgeDirection.DOWN);
energyBar = new EnergyBar(mc, this).setVertical().setMaxValue(maxEnergyStored).setLayoutHint(new PositionalLayout.PositionalHint(10, 7, 8, 54)).setShowText(false);
energyBar.setValue(tileEntity.getCurrentRF());
progressIcon = new ImageLabel(mc, this).setImage(iconGuiElements, 4 * 16, 16);
progressIcon.setLayoutHint(new PositionalLayout.PositionalHint(64, 24, 16, 16));
Widget toplevel = new Panel(mc, this).setBackground(iconLocation).setLayout(new PositionalLayout()).addChild(energyBar).addChild(progressIcon);
toplevel.setBounds(new Rectangle(guiLeft, guiTop, xSize, ySize));
window = new Window(this, toplevel);
tileEntity.requestRfFromServer(RFToolsMessages.INSTANCE);
tileEntity.requestScramblingFromServer();
}
@Override
protected void drawGuiContainerBackgroundLayer(float v, int i, int i2) {
int scrambling = tileEntity.getScrambling();
if (scrambling == 0) {
progressIcon.setImage(iconGuiElements, 4 * 16, 16);
} else {
progressIcon.setImage(iconGuiElements, (scrambling % 4) * 16, 16);
}
drawWindow();
energyBar.setValue(tileEntity.getCurrentRF());
tileEntity.requestRfFromServer(RFToolsMessages.INSTANCE);
tileEntity.requestScramblingFromServer();
}
}
| Elecs-Mods/RFTools | src/main/java/mcjty/rftools/blocks/dimlets/GuiDimletScrambler.java | Java | mit | 2,975 |
// Fill in topbar details.
$('header .right').append(Handlebars.templates.userTopbar(user));
// Fill in sidebar details.
user.created_at = moment(user.created_at).format('MMM DD, YYYY');
var userStars = {user: user, stars: stars};
$('aside').prepend(Handlebars.templates.userSidebar(userStars));
// Populate the organizations list on the sidebar.
var orgList = $('aside #organizations');
orgs.forEach(function (org) {
orgList.append(Handlebars.templates.org(org));
});
// Populate the repos list in the main page.
var repoList = $('section.main .repo-list');
repos = _.sortBy( repos, 'updated_at' ).reverse();
repos.forEach(function (repo) {
repo.updated_at = moment(repo.updated_at).fromNow();
repoList.append(Handlebars.templates.repo(repo));
});
| bholben/GitHub | app/scripts/main.js | JavaScript | mit | 760 |
<?php
if (!defined('BASEPATH'))
exit('No direct script access allowed');
class ModelPersona extends YPS_Model {
CONST OBJETO = 'modelPersona';
CONST PK = 'idPersona';
CONST TABLA = 'personas';
private $idPersona;
private $sufijo_nombre;
private $prefijo_nombre;
private $nombres;
private $apellidos;
private $tpo_documento;
private $documento;
private $sexo;
private $direccion;
private $ciudad;
private $fecha_nacimiento;
private $fotoURL;
private $observacion;
private $estado;
private $eliminado;
public function __construct() {
parent::__construct(SELF::PK, SELF::TABLA);
}
public function magic($var = null, $valor = null){
if (is_null($var)){return false;}
if(is_null($valor)){
return $this->$var;
}else{
$this->$var = $valor;
}
}
public function cargar($row) {
parent::cargar($row);
//Aqui debajo deben cargarse todas las relaciones simples.
// $this->getPersona();
}
// public function getPersona() {
// $rel = parent::getObject(null, 'usuarios_personas', ['idUsuario' => $this->id]);
// //$this->CI->load->model("Catalogos/personas", 'mPersonas');
//
// $persona = new Personas;
// $persona->buscarPorId($rel[0]->IdPersona);
// echo "<pre>";
// print_r($persona);
// echo "</pre>";
// die;
// //return $this->persona;
// }
}
| QInfoDev/YPS | application/models/modelPersona.php | PHP | mit | 1,574 |
import { faker } from 'ember-cli-mirage';
import lodash from 'npm:lodash';
export const CONTAINER_MEMORY = 8023089152;
export function getPorts(isContainer=false) {
let ports = [];
for (let j = 1; j <= faker.random.number({ max: 3 }); j++) {
let obj = {
name: faker.hacker.noun(),
protocol: 'TCP',
};
obj[isContainer ? 'hostPort': 'port'] = faker.random.number();
obj[isContainer ? 'containerPort': 'targetPort'] = faker.random.number();
ports.push(obj);
}
return ports;
}
export function getLabels() {
let labels = {};
for (let j = 1; j <= faker.random.number({ max: 3 }); j++) {
labels[faker.hacker.verb()] = faker.hacker.noun();
}
return labels;
}
export function getSpec(isContainer=false) {
let containers = [];
for (let j = 1; j <= faker.random.number({ min: 1, max: 5 }); j++) {
const name = faker.hacker.verb();
containers.push({
name,
image: `${name}:v${j / 2}`,
ports: getPorts(isContainer),
terminationMessagePath: '/dev/termination-log',
imagePullPolicy: faker.random.arrayElement(['Always', 'Never', 'IfNotPresent'])
});
}
return {
containers,
restartPolicy: faker.random.arrayElement(['Always', 'OnFailure', 'Never']),
terminationGracePeriodSeconds: faker.random.number(),
dnsPolicy: faker.random.arrayElement(['ClusterFirst', 'Default']),
nodeName: faker.internet.ip(),
hostNetwork: faker.random.boolean()
};
}
export function getId(kind, index) {
return `${kind.toLowerCase()}-${index}`;
}
export function getMetadata(kind='Node', index=0, namespace=null) {
let name = getId(kind, index),
creationTimestamp = faker.date.recent(),
labels = getLabels();
if (!namespace && kind !== 'Node') {
namespace = faker.random.arrayElement(['default', 'kube-system', 'app-namespace']);
}
return { name, namespace, creationTimestamp, labels };
}
export function getCAdvisorContainerSpec() {
return {
creation_time: faker.date.recent(),
has_cpu: true,
has_memory: true,
has_filesystem: true,
memory: {
limit: CONTAINER_MEMORY
}
};
}
export function getStat(total, timestamp, cpus=4) {
let per_cpu_usage = [],
maxPerCpu = Math.round(total / cpus);
for (let i = 1; i < cpus; i++) {
per_cpu_usage.push(faker.random.number({ max: maxPerCpu }));
}
let cpu = { usage: { total, per_cpu_usage } },
memory = { usage: faker.random.number({ max: CONTAINER_MEMORY }) },
filesystems = [],
devices = [
'/dev/sda1',
'docker-8:1-7083173-pool',
'/dev/mapper/docker-8:1-7083173-8f138ecc6e8dc81a08b9fee2f256415e96de06a8eb4ab247bde008932fc53c3a'
];
lodash.each(devices, (device) => {
let min = 1024,
max = 1024 * 20,
capacity = faker.random.number({ min, max }),
usage = faker.random.number({ min, max: capacity });
filesystems.push({ device, capacity, usage });
});
return { timestamp, cpu, memory, filesystem: filesystems };
}
| holandes22/kube-admin | app/mirage/factories/fakers.js | JavaScript | mit | 3,027 |
module RubyHashcat
class API < Sinatra::Application
get '/location.json' do
content_type :json
if settings.debug
pp params
end
{:location => settings.ocl_location}.to_json
end
get '/rules.json' do
content_type :json
if settings.debug
pp params
end
list = Dir.entries("#{settings.ocl_location}/rules/")
list.delete('.')
list.delete('..')
{:rules => list}.to_json
end
end
end | dlister/ruby_hashcat | lib/ruby_hashcat/routes/settings.rb | Ruby | mit | 480 |
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("07.AndreyAndBilliard")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("07.AndreyAndBilliard")]
[assembly: AssemblyCopyright("Copyright © 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("426b878b-e631-43ac-9c30-7af12c8f463e")]
// 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")]
| SvetozarMateev/Programming-Fundamentals | ObjectsAndClassesExercises/07.AndreyAndBilliard/Properties/AssemblyInfo.cs | C# | mit | 1,416 |
module.exports = function () {
return {
templateUrl : './shared/partials/footer/directives/footer.html',
controller: require('./footerCtrl'),
restrict: 'E',
scope: {}
};
};
| Arodang/Moroja | app/shared/partials/footer/directives/footerDirective.js | JavaScript | mit | 214 |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta content="IE=edge" http-equiv="X-UA-Compatible">
<meta content="width=device-width, initial-scale=1" name="viewport">
<title>Lavue</title>
<!-- fonts -->
<link href="https://fonts.googleapis.com/css?family=Raleway:100,600"
rel="stylesheet" type="text/css">
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.5.0/css/font-awesome.min.css"
rel="stylesheet">
<link href="{{asset('css/bulma.css')}}" rel="stylesheet"/>
<body>
@yield('content')
<script src="{{asset('js/utils.js')}}"></script>
</body>
</html>
| Rubemlrm/lavue | resources/views/layouts/no-auth.blade.php | PHP | mit | 652 |
<?php
/**
* Client object
*
* @package RpkUtils\Sysinfo
* @author Repkit <repkit@gmail.com>
* @copyright 2015 Repkit
* @license MIT <http://opensource.org/licenses/MIT>
* @since 2015-11-12
*/
namespace RpkUtils\Sysinfo;
class Client
{
/**
* Client ip
* @return string
*/
public static function ip()
{
if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
// check ip from share internet
$ip = $_SERVER['HTTP_CLIENT_IP'];
} elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
// to check ip is pass from proxy
$ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
} elseif (!empty($_SERVER['REMOTE_ADDR'])) {
$ip = $_SERVER['REMOTE_ADDR'];
} else {
$ip = '0.0.0.0';
}
return $ip;
}
} | Repkit/php-utils | src/RpkUtils/Sysinfo/Client.php | PHP | mit | 907 |
<?php
require __DIR__.DIRECTORY_SEPARATOR.'includes.php';
if (strtolower($_SERVER['REQUEST_METHOD']) == 'post') {
$Upload = new \Rundiz\Upload\Upload('filename');
$Upload->move_uploaded_to = __DIR__.DIRECTORY_SEPARATOR.'uploaded-files';
foreach ($_POST as $key => $value) {
$$key = $value;
}
unset($key, $value);
// Set options via properties.
$Upload->allowed_file_extensions = array('gif', 'jpg', 'jpeg', 'png');
if (isset($_POST['upload_max_file_size']) && $_POST['upload_max_file_size'] != null) {
$Upload->max_file_size = intval($_POST['upload_max_file_size']);
}
if (isset($max_image_dimensions) && !empty($max_image_dimensions)) {
$exp_max_image_dimensions = explode(',', $max_image_dimensions);
if (is_array($exp_max_image_dimensions) && count($exp_max_image_dimensions) >= 2 && is_numeric($exp_max_image_dimensions[0]) && is_numeric($exp_max_image_dimensions[1])) {
$Upload->max_image_dimensions = array(intval($exp_max_image_dimensions[0]), intval($exp_max_image_dimensions[1]));
}
unset($exp_max_image_dimensions);
}
if (isset($_POST['new_file_name'])) {
$Upload->new_file_name = htmlspecialchars_decode(trim($_POST['new_file_name']));
}
if (isset($_POST['overwrite'])) {
$Upload->overwrite = ($_POST['overwrite'] === 'true' ? true : false);
}
if (isset($_POST['web_safe_file_name'])) {
$Upload->web_safe_file_name = ($_POST['web_safe_file_name'] === 'true' ? true : false);
}
if (isset($_POST['security_scan'])) {
$Upload->security_scan = ($_POST['security_scan'] === 'true' ? true : false);
}
if (isset($_POST['stop_on_failed_upload_multiple'])) {
$Upload->stop_on_failed_upload_multiple = ($_POST['stop_on_failed_upload_multiple'] === 'true' ? true : false);
}
// Begins upload process.
$upload_result = $Upload->upload();
$uploaded_data = $Upload->getUploadedData();
}// endif; method post.
if (!isset($overwrite)) {
$overwrite = 'false';
}
if (!isset($web_safe_file_name)) {
$web_safe_file_name = 'true';
}
if (!isset($security_scan)) {
$security_scan = 'false';
}
if (!isset($stop_on_failed_upload_multiple)) {
$stop_on_failed_upload_multiple = 'true';
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Test full customization file upload.</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
</head>
<body>
<div class="container">
<div class="row">
<div class="col-xs-12">
<h1>Test full customization file upload.</h1>
<?php if (isset($upload_result) && $upload_result === true) { ?>
<div class="alert alert-success">Upload successfully.</div>
<?php }// endif upload result ?>
<?php if (isset($uploaded_data) && !empty($uploaded_data)) { ?>
<div class="alert alert-info">
<h3>Uploaded files data:</h3>
<pre><?php echo htmlspecialchars(stripslashes(var_export($uploaded_data, true))); ?></pre>
</div>
<?php }// endif; ?>
<?php if (!empty($Upload->error_messages) && is_array($Upload->error_messages)) { ?>
<div class="alert alert-danger">
<?php
foreach ($Upload->error_messages as $error_message) {
echo '<p>'.$error_message.'</p>'."\n";
}// endforeach;
unset($error_message);
?>
</div>
<?php }// endif show errors ?>
</div>
</div>
<div class="row">
<div class="col-sm-6">
<h2>Upload single file</h2>
<form method="post" enctype="multipart/form-data">
<div class="form-group">
<label>Select file</label>
<input type="file" name="filename">
<p class="help-block">Allowed extensions: GIF, JPG, PNG</p>
</div>
<div class="form-group has-feedback">
<label>Max file size</label>
<div class="input-group">
<input type="text" name="upload_max_file_size" value="<?php if (isset($upload_max_file_size)) {echo htmlspecialchars($upload_max_file_size);} ?>" class="form-control">
<span class="input-group-addon">Bytes</span>
</div>
</div>
<div class="form-group">
<label>Max image dimensions</label>
<input type="text" name="max_image_dimensions" value="<?php if (isset($max_image_dimensions)) {echo htmlspecialchars($max_image_dimensions);} ?>" placeholder="width,height" class="form-control">
<p class="help-block">Max image dimensions must be 2 numbers separate by comma. Example: 500,300 is width 500 and height 300 pixels.</p>
</div>
<div class="form-group">
<label>New file name (without file .extension)</label>
<input type="text" name="new_file_name" value="<?php if (isset($new_file_name)) {echo htmlspecialchars($new_file_name);} ?>" class="form-control">
<p class="help-block">For file name limitation test, I suggest you to name this to <strong><?php echo htmlspecialchars('TEST -= !@#$%^&*()_+ []\\ {}| ;\' :" ,./ <>? `~'); ?></strong></p>
</div>
<div class="form-group">
<label>Overwrite existing file</label>
<select name="overwrite" class="form-control">
<option value="true"<?php if (isset($overwrite) && $overwrite === 'true') { ?> selected<?php } ?>>Yes</option>
<option value="false"<?php if (isset($overwrite) && $overwrite === 'false') { ?> selected<?php } ?>>No</option>
</select>
<p class="help-block">If you set new file name and upload multiple file, please set this to no.</p>
</div>
<div class="form-group">
<label>Web safe file name</label>
<select name="web_safe_file_name" class="form-control">
<option value="true"<?php if (isset($web_safe_file_name) && $web_safe_file_name === 'true') { ?> selected<?php } ?>>Yes</option>
<option value="false"<?php if (isset($web_safe_file_name) && $web_safe_file_name === 'false') { ?> selected<?php } ?>>No</option>
</select>
<p class="help-block">English and number chacters, no space (replaced with dash), no special characters, allowed dash and underscore.</p>
</div>
<div class="form-group">
<label>Security scan</label>
<select name="security_scan" class="form-control">
<option value="true"<?php if (isset($security_scan) && $security_scan === 'true') { ?> selected<?php } ?>>Yes</option>
<option value="false"<?php if (isset($security_scan) && $security_scan === 'false') { ?> selected<?php } ?>>No</option>
</select>
<p class="help-block">Scan for PHP and perl code in the file.</p>
</div>
<div>
<button type="submit" class="btn btn-primary">Upload</button>
</div>
</form>
</div>
<div class="col-sm-6">
<h2>Upload multiple file</h2>
<form method="post" enctype="multipart/form-data">
<div class="form-group">
<label>Select file</label>
<input type="file" name="filename[]" multiple>
<p class="help-block">Allowed extensions: GIF, JPG, PNG</p>
</div>
<div class="form-group has-feedback">
<label>Max file size</label>
<div class="input-group">
<input type="text" name="upload_max_file_size" value="<?php if (isset($upload_max_file_size)) {echo htmlspecialchars($upload_max_file_size);} ?>" class="form-control">
<span class="input-group-addon">Bytes</span>
</div>
</div>
<div class="form-group">
<label>Max image dimensions</label>
<input type="text" name="max_image_dimensions" value="<?php if (isset($max_image_dimensions)) {echo htmlspecialchars($max_image_dimensions);} ?>" placeholder="width,height" class="form-control">
<p class="help-block">Max image dimensions must be 2 numbers separate by comma. Example: 500,300 is width 500 and height 300 pixels.</p>
</div>
<div class="form-group">
<label>New file name (without file .extension)</label>
<input type="text" name="new_file_name" value="<?php if (isset($new_file_name)) {echo htmlspecialchars($new_file_name);} ?>" class="form-control">
<p class="help-block">For file name limitation test, I suggest you to name this to <strong><?php echo htmlspecialchars('TEST -= !@#$%^&*()_+ []\\ {}| ;\' :" ,./ <>? `~'); ?></strong></p>
</div>
<div class="form-group">
<label>Overwrite existing file</label>
<select name="overwrite" class="form-control">
<option value="true"<?php if (isset($overwrite) && $overwrite === 'true') { ?> selected<?php } ?>>Yes</option>
<option value="false"<?php if (isset($overwrite) && $overwrite === 'false') { ?> selected<?php } ?>>No</option>
</select>
<p class="help-block">If you set new file name and upload multiple file, please set this to no.</p>
</div>
<div class="form-group">
<label>Web safe file name</label>
<select name="web_safe_file_name" class="form-control">
<option value="true"<?php if (isset($web_safe_file_name) && $web_safe_file_name === 'true') { ?> selected<?php } ?>>Yes</option>
<option value="false"<?php if (isset($web_safe_file_name) && $web_safe_file_name === 'false') { ?> selected<?php } ?>>No</option>
</select>
<p class="help-block">English and number chacters, no space (replaced with dash), no special characters, allowed dash and underscore.</p>
</div>
<div class="form-group">
<label>Security scan</label>
<select name="security_scan" class="form-control">
<option value="true"<?php if (isset($security_scan) && $security_scan === 'true') { ?> selected<?php } ?>>Yes</option>
<option value="false"<?php if (isset($security_scan) && $security_scan === 'false') { ?> selected<?php } ?>>No</option>
</select>
<p class="help-block">Scan for PHP and perl code in the file.</p>
</div>
<div class="form-group">
<label>Stop on failed upload occur</label>
<select name="stop_on_failed_upload_multiple" class="form-control">
<option value="true"<?php if (isset($stop_on_failed_upload_multiple) && $stop_on_failed_upload_multiple === 'true') { ?> selected<?php } ?>>Yes</option>
<option value="false"<?php if (isset($stop_on_failed_upload_multiple) && $stop_on_failed_upload_multiple === 'false') { ?> selected<?php } ?>>No</option>
</select>
<p class="help-block">If you upload multiple file and there is at least one error, do you want it to stop or not?.</p>
</div>
<div>
<button type="submit" class="btn btn-primary">Upload</button>
</div>
</form>
</div>
</div>
<div class="row">
<div class="col-xs-12">
<hr>
<a href="clear-uploaded-files.php" class="btn btn-danger" onclick="return confirm('Are you sure to delete all uploaded files?');">Clear all uploaded files.</a>
</div>
</div>
<div class="row">
<div class="col-xs-12">
<h2>Debug:</h2>
<p>
<strong>upload_max_filesize</strong> limit is <?php echo ini_get('upload_max_filesize'); ?><br>
<strong>post_max_size</strong> limit is <?php echo ini_get('post_max_size'); ?>
</p>
<?php if (strtolower($_SERVER['REQUEST_METHOD']) == 'post' && isset($Upload)) { ?>
<div class="alert alert-info">
<h3>Upload debug:</h3>
<pre><?php
echo htmlspecialchars(stripslashes(var_export($Upload, true)));
echo "\n\n";
echo htmlspecialchars(print_r($_FILES, true));
?></pre>
</div>
<?php }// endif; method post and isset $Upload. ?>
</div>
</div>
</div>
</body>
</html>
<?php
unset($new_file_name, $Upload); | OkveeNet/Vfileup | tests/via-http/test-full-customize-file-upload.php | PHP | mit | 14,779 |
// $Id: LSOCK_CODgram.cpp 79134 2007-07-31 18:23:50Z johnnyw $
#include "ace/LSOCK_CODgram.h"
#if !defined (ACE_LACKS_UNIX_DOMAIN_SOCKETS)
#include "ace/Log_Msg.h"
ACE_RCSID(ace, LSOCK_CODgram, "$Id: LSOCK_CODgram.cpp 79134 2007-07-31 18:23:50Z johnnyw $")
#if !defined (__ACE_INLINE__)
#include "ace/LSOCK_CODgram.inl"
#endif /* __ACE_INLINE__ */
ACE_BEGIN_VERSIONED_NAMESPACE_DECL
ACE_ALLOC_HOOK_DEFINE(ACE_LSOCK_CODgram)
void
ACE_LSOCK_CODgram::dump (void) const
{
#if defined (ACE_HAS_DUMP)
ACE_TRACE ("ACE_LSOCK_CODgram::dump");
ACE_DEBUG ((LM_DEBUG, ACE_BEGIN_DUMP, this));
ACE_SOCK_CODgram::dump ();
ACE_LSOCK::dump ();
ACE_DEBUG ((LM_DEBUG, ACE_END_DUMP));
#endif /* ACE_HAS_DUMP */
}
/* Here's the general-purpose open routine. */
int
ACE_LSOCK_CODgram::open (const ACE_Addr &remote,
const ACE_Addr &local,
int protocol_family,
int protocol)
{
ACE_TRACE ("ACE_LSOCK_CODgram::open");
if (ACE_SOCK_CODgram::open (remote, local, protocol_family,
protocol) == -1)
return -1;
ACE_LSOCK::set_handle (this->get_handle ());
return 0;
}
/* Create a local ACE_SOCK datagram. */
ACE_LSOCK_CODgram::ACE_LSOCK_CODgram (const ACE_Addr &remote,
const ACE_Addr &local,
int protocol_family,
int protocol)
{
ACE_TRACE ("ACE_LSOCK_CODgram::ACE_LSOCK_CODgram");
if (this->open (remote, local, protocol_family,
protocol) == -1)
ACE_ERROR ((LM_ERROR, ACE_TEXT ("%p\n"), ACE_TEXT ("ACE_LSOCK_CODgram")));
}
ACE_END_VERSIONED_NAMESPACE_DECL
#endif /* ACE_LACKS_UNIX_DOMAIN_SOCKETS */
| yuanxu/liveshow_r2 | P2pNet/ace/LSOCK_CODgram.cpp | C++ | mit | 1,814 |
from accounts.models import Practice
def create_practice(request, strategy, backend, uid, response={}, details={}, user=None, social=None, *args, **kwargs):
"""
if user has a practice skip else create new practice
"""
practice, created = Practice.objects.update_or_create(user=user)
return None
| TimothyBest/Appointment_Booking_drchrono | appointment_booking_drchrono/accounts/pipeline.py | Python | mit | 321 |
/*
* Copyright 2002 Sun Microsystems, Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistribution in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* Neither the name of Sun Microsystems, Inc. or the names of
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any
* kind. ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND
* WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY
* EXCLUDED. SUN AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES
* SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING OR
* DISTRIBUTING THE SOFTWARE OR ITS DERIVATIVES. IN NO EVENT WILL SUN
* OR ITS LICENSORS BE LIABLE FOR ANY LOST REVENUE, PROFIT OR DATA, OR
* FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL, INCIDENTAL OR
* PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY OF
* LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE SOFTWARE,
* EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that Software is not designed, licensed or intended
* for use in the design, construction, operation or maintenance of
* any nuclear facility.
*/
package com.sun.j2ee.blueprints.waf.view.taglibs.smart;
import javax.servlet.jsp.JspTagException;
import javax.servlet.jsp.tagext.BodyTagSupport;
import javax.servlet.jsp.tagext.BodyContent;
import java.io.IOException;
import java.util.*;
/**
* A parameter for a link (i.e. a key-value pair in string such
* as "?foo=yes&bar=5").
*/
public class QueryParameterTag extends BodyTagSupport {
String name = "";
public void setName(String n) { name = n; }
public int doAfterBody() throws JspTagException {
LinkTag linkTag
= (LinkTag) findAncestorWithClass(this, LinkTag.class);
BodyContent bc = getBodyContent();
String value = bc.getString();
if (name != null && !name.trim().equals("")
&& value != null && !value.trim().equals("")) {
linkTag.putParameter(name, bc.getString());
}
bc.clearBody();
return SKIP_BODY;
}
}
| pitpitman/GraduateWork | petstore1.3_01/src/waf/src/view/taglibs/com/sun/j2ee/blueprints/taglibs/smart/QueryParameterTag.java | Java | mit | 2,690 |
<?php
/*
|--------------------------------------------------------------------------
| Model Factories
|--------------------------------------------------------------------------
|
| Here you may define all of your model factories. Model factories give
| you a convenient way to create models for testing and seeding your
| database. Just tell the factory how a default model should look.
|
*/
$factory->define(App\User::class, function () {
$hasher = app()->make('hash');
return [
'name' => 'Admin',
'email' => 'admin@admin.com.br',
'password' => $hasher->make("senhaAdmin"),
'is_admin' => 1
];
});
/*
$factory->define(App\Post::class, function (Faker\Generator $faker) {
return [
'title' => $faker->sentence(4),
'content' => $faker->paragraph(4),
'user_id' => mt_rand(1, 10)
];
});
$factory->define(App\Comment::class, function (Faker\Generator $faker) {
return [
'content' => $faker->paragraph(1),
'post_id' => mt_rand(1, 50),
'user_id' => mt_rand(1, 10)
];
});
$factory->define(App\User::class, function (Faker\Generator $faker) {
$hasher = app()->make('hash');
return [
'name' => $faker->name,
'email' => $faker->email,
'password' => $hasher->make("secret"),
'is_admin' => mt_rand(0, 1)
];
});
*/ | diego-drese/swesat | database/factories/ModelFactory.php | PHP | mit | 1,360 |
import React from 'react';
import PropTypes from 'prop-types';
import ColumnChart from './columnChart';
import Tooltip from './../tooltip/tooltip';
import {dateFormats} from './../../utils/displayFormats';
import './columnWidget.css';
const ColumnWidget = ({
chartTitle,
chartDescription,
chartUpdatedDate,
series,
xAxis,
yAxis,
viewport,
displayHighContrast,
}) => {
return (
<article role="article" className="D_widget">
<header>
{chartDescription && <div className="D_CW_infoContainer"><Tooltip text={chartDescription} viewport={viewport} /></div>}
<h1 className="highcharts-title">{chartTitle}</h1>
<span className="highcharts-subtitle">Last updated at <time dateTime={dateFormats.dateTime(chartUpdatedDate)}>{dateFormats.dayMonthYear(chartUpdatedDate)}</time></span>
</header>
<section>
<ColumnChart series={series}
xAxis={xAxis}
yAxis={yAxis}
chartDescription={chartDescription}
displayHighContrast={displayHighContrast} />
</section>
</article>
)
};
if (__DEV__) {
ColumnWidget.propTypes = {
chartTitle: PropTypes.string,
chartDescription: PropTypes.string,
chartUpdatedDate: PropTypes.string,
series: PropTypes.arrayOf(PropTypes.shape({
name: PropTypes.string.isRequired,
units: PropTypes.string,
color: PropTypes.string,
data: PropTypes.array.isRequired,
})).isRequired,
xAxis: PropTypes.arrayOf(PropTypes.shape({
categories: PropTypes.array,
})),
yAxis: PropTypes.arrayOf(PropTypes.shape({
title: PropTypes.object,
})),
viewport: PropTypes.oneOf(['sm', 'md', 'lg', 'xl']),
displayHighContrast: PropTypes.bool,
};
}
export default ColumnWidget;
| govau/datavizkit | src/components/columnWidget/columnWidget.js | JavaScript | mit | 1,815 |
from flask import Flask
from flask import render_template, request
app = Flask(__name__)
@app.route("/")
def main():
room = request.args.get('room', '')
if room:
return render_template('watch.html')
return render_template('index.html')
if __name__ == "__main__":
app.run(host='0.0.0.0', debug=True)
| victorpoluceno/webrtc-sample-client | app/__init__.py | Python | mit | 314 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace RemoveOddPosition
{
class RemoveOddPosition
{
static void Main(string[] args)
{
var words = Console.ReadLine().Split(' ').ToList();
var output = new List<string>();
for (int i = 0; i < words.Count; i++)
{
if (i%2 != 0)
{
output.Add(words[i]);
}
}
Console.WriteLine(string.Join("", output));
}
}
}
| Tcetso/Fundamentals | 15-17_Lists/RemoveOddPosition/RemoveOddPosition.cs | C# | mit | 605 |
# Be sure to restart your server when you modify this file.
# Add new inflection rules using the following format. Inflections
# are locale specific, and you may define rules for as many different
# locales as you wish. All of these examples are active by default:
ActiveSupport::Inflector.inflections(:en) do |inflect|
inflect.irregular 'ability', 'abilities'
end
# These inflection rules are supported but not enabled by default:
# ActiveSupport::Inflector.inflections(:en) do |inflect|
# inflect.acronym 'RESTful'
# end
| netguru/people | config/initializers/inflections.rb | Ruby | mit | 529 |
package jaist.css.covis.cls;
import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPopupMenu;
import jaist.css.covis.util.FramePopup;
public class ArrayPrimitiveMenu extends JPopupMenu implements FramePopup {
private static final long serialVersionUID = 8027248166373847225L;
Covis_primitive v;
Covis_Array a;
JFrame f;
public ArrayPrimitiveMenu(Covis_primitive _v, Covis_Array _a) {
this.v = _v;
this.a = _a;
JMenuItem menuItem;
setLightWeightPopupEnabled(false);
menuItem = new JMenuItem("cancel");
add(menuItem);
addSeparator();
menuItem = new JMenuItem("edit value");
add(menuItem);
menuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String input;
input = JOptionPane.showInputDialog(f, "Input Value", v.getValue());
if (input == null) return;
if (!v.setValue(input)){
JOptionPane.showMessageDialog(f,"Value is not accepted.","Error",JOptionPane.WARNING_MESSAGE);
return;
}
v.buffer.putHistoryEditValueArray(v,a); //ÏXµ½ç\[XR[hÉÇÁ
Informer.playSound("Pop.wav");
}
});
}
public void showWithFrame(Component c, int x, int y, JFrame _f) {
f = _f;
show(c, x, y);
}
}
| miuramo/AnchorGarden | src/jaist/css/covis/cls/ArrayPrimitiveMenu.java | Java | mit | 1,372 |
//
// window.onload = function() {
// var data = {username:'52200', password:'123', remember:52200};
// fetch('/api/users/getUser?id=1').then(function(res) {
// console.log("请求的数据是", res);
// if (res.ok) {
// alert('Submitted!');
// } else {
// alert('Error!');
// }
// }).then(function(body) {
// console.log("请求body的数据是", body);
// // body
// });
// }; | Hitheworld/HelloKoa2 | public/javascript/data.js | JavaScript | mit | 466 |
Meteor.methods({
addAllUserToRoom(rid, activeUsersOnly = false) {
check (rid, String);
check (activeUsersOnly, Boolean);
if (RocketChat.authz.hasRole(this.userId, 'admin') === true) {
const userCount = RocketChat.models.Users.find().count();
if (userCount > RocketChat.settings.get('API_User_Limit')) {
throw new Meteor.Error('error-user-limit-exceeded', 'User Limit Exceeded', {
method: 'addAllToRoom',
});
}
const room = RocketChat.models.Rooms.findOneById(rid);
if (room == null) {
throw new Meteor.Error('error-invalid-room', 'Invalid room', {
method: 'addAllToRoom',
});
}
const userFilter = {};
if (activeUsersOnly === true) {
userFilter.active = true;
}
const users = RocketChat.models.Users.find(userFilter).fetch();
const now = new Date();
users.forEach(function(user) {
const subscription = RocketChat.models.Subscriptions.findOneByRoomIdAndUserId(rid, user._id);
if (subscription != null) {
return;
}
RocketChat.callbacks.run('beforeJoinRoom', user, room);
RocketChat.models.Subscriptions.createWithRoomAndUser(room, user, {
ts: now,
open: true,
alert: true,
unread: 1,
userMentions: 1,
groupMentions: 0,
});
RocketChat.models.Messages.createUserJoinWithRoomIdAndUser(rid, user, {
ts: now,
});
Meteor.defer(function() {});
return RocketChat.callbacks.run('afterJoinRoom', user, room);
});
return true;
} else {
throw (new Meteor.Error(403, 'Access to Method Forbidden', {
method: 'addAllToRoom',
}));
}
},
});
| flaviogrossi/Rocket.Chat | server/methods/addAllUserToRoom.js | JavaScript | mit | 1,600 |
/// <reference path="../_references.d.ts" />
interface sage {
id: number;
name: string;
username: string;
email: string;
dateOfBirth: Date;
sayings?: saying[];
}
interface repositorySage {
getAll: () => ng.IPromise<sage[]>;
getById: (id: number, forceRemote?: boolean) => ng.IPromise<sage>;
remove: (id: number) => ng.IPromise<void>;
save: (sage: sage) => ng.IPromise<void>;
}
(function () {
"use strict";
var serviceId = "repository.sage";
angular.module("app").factory(serviceId, ["$http", "common", "config", repositorySage]);
function repositorySage($http: ng.IHttpService, common: common, config: config) {
var $q = common.$q;
var log = common.logger.getLogFn(serviceId);
var rootUrl = config.remoteServiceRoot + "sage";
var cache: { [id: number]: sage } = {};
var service: repositorySage = {
getAll: getAll,
getById: getById,
remove: remove,
save: save
};
return service;
function getAll() {
return $http.get<sage[]>(rootUrl).then(response => {
var sages = response.data;
log(sages.length + " Sages loaded");
return sages;
});
}
function getById(id: number, forceRemote?: boolean) {
var sage: sage;
if (!forceRemote) {
sage = cache[id];
if (sage) {
log("Sage " + sage.name + " [id: " + sage.id + "] loaded from cache");
return $q.when(sage);
}
}
return $http.get<sage>(rootUrl + "/" + id).then(response => {
sage = response.data;
cache[sage.id] = sage;
log("Sage " + sage.name + " [id: " + sage.id + "] loaded");
return sage;
});
}
function remove(id: number) {
return $http.delete<void>(rootUrl + "/" + id).then(response => {
log("Sage [id: " + id + "] removed");
return response.data;
}, errorReason => $q.reject(errorReason.data));
}
function save(sage: sage) {
return $http.post<void>(rootUrl, sage).then(response => {
log("Sage " + sage.name + " [id: " + sage.id + "] saved");
return response.data;
}, errorReason => $q.reject(errorReason.data));
}
}
})(); | johnnyreilly/proverb-without-implicit-referencing | Proverb.Web/app/services/repository.sage.ts | TypeScript | mit | 2,507 |
<?php
$about = array(
'name' => 'Norsk bokmål',
'author' => array(
'name' => 'Frode Danielsen',
'email' => 'frode@danielsen.net',
'website' => 'http://frode.danielsen.net/'
),
'release-date' => '2011-02-09'
);
/**
* Subsection Manager
*/
$dictionary = array(
'%s Show thumbnail images' =>
'%s Vis miniatyrbilder',
'%s has to be well-formed. Please check opening and closing tags.' =>
'%s må være velformet. Vennligst kontroller åpne- og lukke-taggene.',
'1 result' =>
'1 resultat',
'Allow creation of new items' =>
'Tillat oppretting av nye innlegg',
'Allow deselection of items' =>
'Tillat fjerning av markering for innlegg',
'Allow dropping of items' =>
'Tillat slipp av innlegg',
'Allow selection of items from a list of existing items' =>
'Tillat valg av innlegg fra en liste med eksisterende innlegg',
'Allow selection of multiple items' =>
'Tillat valg av flere innlegg',
'Allow sorting of items' =>
'Tillat sortering av innlegg',
'Are you sure you want to delete {$item}? It will be removed from all entries. This step cannot be undone.' =>
'Er du sikker på at du ønsker å slette {$item}? Den vil bli fjernet fra alle innlegg. Dette kan ikke reverseres.',
'Before you proceed' =>
'Før du fortsetter',
'Behaviour' =>
'Oppførsel',
'Browse' =>
'Bla gjennom',
'Caption' =>
'Tittel',
'Comma separated, alt+click for negation' =>
'Kommaseparert, alt+klikk for negering',
'Data Source XML' =>
'XML i datakilde',
'Display' =>
'Visning',
'Don’t forget to include the Subsection Manager field in your Data Source' =>
'Ikke glem å inkludere Subsection Manager-feltet i din datakilde',
'Drop text' =>
'Tekst ved slipp',
'Filter items by tags or categories' =>
'Filtrer innlegg etter merkelapper eller kategorier',
'Go back to the extension overview.' =>
'Gå tilbake til oversikten over tillegg.',
'I have a working backup of my site including files and database and like to upgrade all my Mediathek fields to Subsection Manager fields.' =>
'Jeg har en fungerende sikkerhetskopi av min nettside inklusive alle filer og databasen og ønsker å oppgradere alle mine Mediathek-felt til Subsection Manager-felt.',
'If you don’t have a backup, create one now!' =>
'Om du ikke har en sikkerhetskopi, opprett en nå!',
'Included elements' =>
'Inkluderte felt',
'Introduction' =>
'Introduksjon',
'New item' =>
'Nytt innlegg',
'No items found.' =>
'Ingen innlegg ble funnet.',
'None Selected' =>
'Ingen valgte',
'Please delete the old Mediathek folder from your <code>extensions</code> folder.' =>
'Vennligst slett den gamle Mediathek-mappen fra din <code>extensions</code>-mappe.',
'Please fill out the form below.' =>
'Vennligst fyll ut skjemaet nedenfor.',
'Please make sure that you have an up-to-date backup of your site, containing all files and folders, and a copy of your database.' =>
'Vennligst sørg for at du har en fersk sikkerhetskopi av din nettside, inklusive all filer og mapper samt en kopi av din database.',
'Replace all Mediathek fields with the Subsection Manager, copying all attached information to the new fields.' =>
'Erstatte alle dine Mediathek-felt med Subsection Manager og kopiere all informasjon til de nye feltene.',
'Subsection' =>
'Underseksjon',
'Subsection Manager' =>
'Subsection Manager',
'Subsection Manager Upgrade' =>
'Oppgradering til Subsection Manager',
'Subsection Manager is a replacement of the Mediathek field, introducing a new interface and an improved feature set. Subsection Manager requires Symphony 2.1 and should not be used side-by-side with Mediathek. This page will help you upgrading your fields from Mediathek to Subsection Manager.' =>
'Subsection Manager er en erstatning for Mediathek-feltet, med et helt nytt grensesnitt og forbedrede funksjoner. Subsection Manager krever Symphony 2.1 og bør ikke brukes sammen med Mediathek. Denne siden hjelper deg med å oppgradere dine felt fra Mediathek til Subsection Manager.',
'The Mediathek folder will stay intact in your extension folder. You will have to delete it manually.' =>
'Mediathek-mappen vil ikke bli berørt i din <code>extensions</code>-mappe. Du må slette denne manuelt selv.',
'The Subsection Manager Upgrade will automatically perform the following actions:' =>
'Oppgradering til Subsection Manager vil automatisk gjennomføre følgende:',
'There are currently no items available. Perhaps you want create one first?' =>
'Det er for øyeblikket ingen innlegg tilgjengelig. Kanskje du ønsker opprette et først?',
'There are no selected items' =>
'Ingen valgte innlegg',
'This process cannot be undone!' =>
'Denne prosessen kan ikke reverseres!',
'This will add a <code>Create New</code> button to the interface' =>
'Dette vil legge til en <code>Opprett ny</code>-knapp i grensesnittet',
'This will add a <code>Remove</code> button to the interface' =>
'Dette vil legge til en <code>Fjern</code>-knapp i grensesnittet',
'This will add a search field to the interface' =>
'Dette vil legge til et søkefelt i grensesnittet',
'This will enable item dragging and reordering' =>
'Dette muliggjør endring av rekkefølge ved å dra innlegg opp eller ned',
'This will enable item dropping on textareas' =>
'Dette muliggjør å slippe innlegg oppå tekstfelt',
'This will switch between single and multiple item lists' =>
'Dette vil veksle mellom muligheten for å velge én eller flere innlegg i opplistinger',
'Uninstall Mediathek' =>
'Avinstaller Mediathek',
'Uninstall Subsection Manager' =>
'Avinstaller Subsection Manager',
'Uninstall the Mediathek extension removing all references in the database.' =>
'Avinstallere Mediathek-tillegget og fjerne alle referanser til det i databasen.',
'Upgrade' =>
'Oppgrader',
'Upgrade all Mediathek fields' =>
'Oppgrader alle Mediathek-felt',
'Upgrade successful' =>
'Oppgraderingen var vellykket',
'Upgrading your Mediathek' =>
'Oppgraderer dine Mediathek-felt',
'Upgrading your Mediathek fields to Subsection Manager will alter your database.' =>
'Oppgradering av dine Mediathek-felt til Subsection Manager vil føre til endringer i din database.',
'Use comma separated entry ids for filtering.' =>
'Bruk en kommaseparert liste med ID-er for innlegg ved filtrering.',
'You are using Mediathek and Subsection Manager simultaneously.' =>
'Du bruker Mediathek og Subsection Manager samtidig.',
'Your Mediathek fields have successfully been upgrade to Subsection Manager.' =>
'Dine Mediathek-felt har blitt vellykket oppgradert til Subsection Manager.',
'item' =>
'innlegg',
'items' =>
'innlegg',
'no results' =>
'ingen resultater',
'{$count} results' =>
'{$count} resultater',
// Missing
'Please make sure that the Stage submodule is initialised and available at %s.' =>
false,
'It\'s available at %s.' =>
false,
'Stage not found' =>
false,
);
| fdanielsen/subsectionmanager | lang/lang.no.php | PHP | mit | 7,134 |
const HttpStatus = require('http-status-codes');
const build = status => {
return (ctx, message) => {
ctx.status = status
ctx.body = message || {message: HttpStatus.getStatusText(status)}
return ctx
}
}
module.exports = {
accepted: build(HttpStatus.ACCEPTED), // 202
badGateway: build(HttpStatus.BAD_GATEWAY), // 502
badRequest: build(HttpStatus.BAD_REQUEST), // 400
conflict: build(HttpStatus.CONFLICT), // 409
continue: build(HttpStatus.CONTINUE), // 100
created: build(HttpStatus.CREATED), // 201
expectationFailed: build(HttpStatus.EXPECTATION_FAILED), // 417
failedDependency: build(HttpStatus.FAILED_DEPENDENCY), // 424
forbidden: build(HttpStatus.FORBIDDEN), // 403
gatewayTimeout: build(HttpStatus.GATEWAY_TIMEOUT), // 504
gone: build(HttpStatus.GONE), // 410
httpVersionNotSupported: build(HttpStatus.HTTP_VERSION_NOT_SUPPORTED), // 505
imATeapot: build(HttpStatus.IM_A_TEAPOT), // 418
insufficientSpaceOnResource: build(HttpStatus.INSUFFICIENT_SPACE_ON_RESOURCE), // 419
insufficientStorage: build(HttpStatus.INSUFFICIENT_STORAGE), // 507
internalServerError: build(HttpStatus.INTERNAL_SERVER_ERROR), // 500
lengthRequired: build(HttpStatus.LENGTH_REQUIRED), // 411
locked: build(HttpStatus.LOCKED), // 423
methodFailure: build(HttpStatus.METHOD_FAILURE), // 420
methodNotAllowed: build(HttpStatus.METHOD_NOT_ALLOWED), // 405
movedPermanently: build(HttpStatus.MOVED_PERMANENTLY), // 301
movedTemporarily: build(HttpStatus.MOVED_TEMPORARILY), // 302
multiStatus: build(HttpStatus.MULTI_STATUS), // 207
multipleChoices: build(HttpStatus.MULTIPLE_CHOICES), // 300
networkAuthenticationRequired: build(HttpStatus.NETWORK_AUTHENTICATION_REQUIRED), // 511
noContent: build(HttpStatus.NO_CONTENT), // 204
nonAuthoritativeInformation: build(HttpStatus.NON_AUTHORITATIVE_INFORMATION), // 203
notAcceptable: build(HttpStatus.NOT_ACCEPTABLE), // 406
notFound: build(HttpStatus.NOT_FOUND), // 404
notImplemented: build(HttpStatus.NOT_IMPLEMENTED), // 501
notModified: build(HttpStatus.NOT_MODIFIED), // 304
ok: build(HttpStatus.OK), // 200
partialContent: build(HttpStatus.PARTIAL_CONTENT), // 206
paymentRequired: build(HttpStatus.PAYMENT_REQUIRED), // 402
permanentRedirect: build(HttpStatus.PERMANENT_REDIRECT), // 308
preconditionFailed: build(HttpStatus.PRECONDITION_FAILED), // 412
preconditionRequired: build(HttpStatus.PRECONDITION_REQUIRED), // 428
processing: build(HttpStatus.PROCESSING), // 102
proxyAuthenticationRequired: build(HttpStatus.PROXY_AUTHENTICATION_REQUIRED), // 407
requestHeaderFieldsTooLarge: build(HttpStatus.REQUEST_HEADER_FIELDS_TOO_LARGE), // 431
requestTimeout: build(HttpStatus.REQUEST_TIMEOUT), // 408
requestTooLong: build(HttpStatus.REQUEST_TOO_LONG), // 413
requestUriTooLong: build(HttpStatus.REQUEST_URI_TOO_LONG), // 414
requestedRangeNotSatisfiable: build(HttpStatus.REQUESTED_RANGE_NOT_SATISFIABLE), // 416
resetContent: build(HttpStatus.RESET_CONTENT), // 205
seeOther: build(HttpStatus.SEE_OTHER), // 303
serviceUnavailable: build(HttpStatus.SERVICE_UNAVAILABLE), // 503
switchingProtocols: build(HttpStatus.SWITCHING_PROTOCOLS), // 101
temporaryRedirect: build(HttpStatus.TEMPORARY_REDIRECT), // 307
tooManyRequests: build(HttpStatus.TOO_MANY_REQUESTS), // 429
unauthorized: build(HttpStatus.UNAUTHORIZED), // 401
unprocessableEntity: build(HttpStatus.UNPROCESSABLE_ENTITY), // 422
unsupportedMediaType: build(HttpStatus.UNSUPPORTED_MEDIA_TYPE), // 415
useProxy: build(HttpStatus.USE_PROXY) // 305
} | lohanbodevan/http-responses | index.js | JavaScript | mit | 3,695 |
module.exports = function verify(check) {
if (typeof check !== 'object') {
throw new Error('check is not an object');
}
var errors = [];
Object.keys(check).forEach(_verify, check);
if (errors.length > 0) {
throw new Error('Health checks failed: '+ errors.join(', '));
}
return true;
function _verify(key, i) {
if (this[key] === false || this[key] instanceof Error) {
errors.push(key);
}
else if (this[key] && typeof this[key] === 'object' && !Array.isArray(this[key])) {
Object.keys(this[key]).forEach(_verify, this[key]);
}
}
};
| super-useful/su-healthcheck | lib/verify.js | JavaScript | mit | 644 |
<?php
namespace artworx\omegacp\Database\Types\Postgresql;
use Doctrine\DBAL\Platforms\AbstractPlatform;
use artworx\omegacp\Database\Types\Type;
class RealType extends Type
{
const NAME = 'real';
const DBTYPE = 'float4';
public function getSQLDeclaration(array $field, AbstractPlatform $platform)
{
return 'real';
}
}
| carloquilala/omegacp | src/Database/Types/Postgresql/RealType.php | PHP | mit | 351 |
using System.Data;
namespace NBA_Stats.ConnectionProviders.Contracts
{
public interface IConnectionProvider
{
IDbConnection CreateConnection(string connectionString);
}
}
| Team-LemonDrop/NBA-Statistics | NBA-Stats/ConnectionProviders/Contracts/IConnectionProvider.cs | C# | mit | 195 |
using System;
public class WithManaged :
IDisposable
{
public void Dispose()
{
}
public void DisposeManaged()
{
DisposeManagedCalled = true;
Property = "a";
Method();
}
public bool DisposeManagedCalled;
public string Property { get; set; }
public void Method()
{
}
} | Fody/Janitor | AssemblyToProcess/WithManaged.cs | C# | mit | 346 |
/* globals describe, beforeEach, it, expect, inject, vehicles, VehicleMock */
describe("Vehicles Factory:", function() {
'use strict';
var $httpBackend,
vehicles,
request,
Showcase;
// Load the main module
beforeEach(module('sc'));
beforeEach(inject(function($injector, _vehicles_, _Showcase_) {
$httpBackend = $injector.get('$httpBackend');
vehicles = _vehicles_;
Showcase = _Showcase_;
request = $httpBackend.whenGET(Showcase.API + 'vehicles').respond(200, angular.copy(VehicleMock.ALL));
$httpBackend.whenGET(Showcase.API + 'vehicles/1').respond(200, VehicleMock.DETAIL);
$httpBackend.whenGET(Showcase.API + 'vehicles/compare/1').respond(200, angular.copy(VehicleMock.COMPARE));
}));
it("should return 4 vehicles", function() {
vehicles.getAll().then(function(response) {
expect(response.length).toEqual(4);
});
$httpBackend.flush();
});
it("should return Toyota as the first Brand", function() {
vehicles.getAll().then(function(response) {
expect(response[0].brand).toEqual('Toyota');
});
$httpBackend.flush();
});
it("should return a 404 error", function() {
request.respond(404, {error: true});
$httpBackend.expectGET(Showcase.API + 'vehicles');
vehicles.getAll().catch(function(error) {
expect(error.error).toBe(true);
});
$httpBackend.flush();
});
it("should return vehicle detail", function() {
vehicles.get(1).then(function(response) {
expect(response.model).toEqual('Avalon');
});
$httpBackend.flush();
});
it("should compare 3 vehicles", function() {
vehicles.compare(1,2,3).then(function(response) {
expect(response.length).toEqual(2);
});
$httpBackend.flush();
});
}); | jandrade/showcase | test/unit/vehicles/factories/vehicles.factory.spec.js | JavaScript | mit | 1,683 |
import { createGlobalStyle } from 'styled-components';
export const GlobalStyle = createGlobalStyle`
body {
margin: 0;
font-family: 'Montserrat', sans-serif;
}
* {
box-sizing: border-box;
}
`;
| hakonhk/vaerhona | ui/global-style.js | JavaScript | mit | 215 |
<?php
use Grav\Common\Grav;
use RocketTheme\Toolbox\ResourceLocator\UniformResourceLocator;
\define('GRAV_CLI', true);
\define('GRAV_REQUEST_TIME', microtime(true));
\define('GRAV_USER_INSTANCE', 'FLEX');
$autoload = require __DIR__ . '/../../vendor/autoload.php';
if (version_compare($ver = PHP_VERSION, $req = GRAV_PHP_MIN, '<')) {
exit(sprintf("You are running PHP %s, but Grav needs at least PHP %s to run.\n", $ver, $req));
}
if (!ini_get('date.timezone')) {
date_default_timezone_set('UTC');
}
if (!file_exists(GRAV_ROOT . '/index.php')) {
exit('FATAL: Must be run from ROOT directory of Grav!');
}
$grav = Grav::instance(array('loader' => $autoload));
$grav->setup('tests');
$grav['config']->init();
// Find all plugins in Grav installation and autoload their classes.
/** @var UniformResourceLocator $locator */
$locator = Grav::instance()['locator'];
$iterator = $locator->getIterator('plugins://');
foreach($iterator as $directory) {
if (!$directory->isDir()) {
continue;
}
$autoloader = $directory->getPathname() . '/vendor/autoload.php';
if (file_exists($autoloader)) {
require $autoloader;
}
}
| Vivalldi/grav | tests/phpstan/plugins-bootstrap.php | PHP | mit | 1,164 |
<div class="container">
<div class="row spacer"></div>
<div class="row">
<div class="col-lg-8 col-lg-offset-2 bg-primary">
<h4>Edit Company Info</h4>
</div>
<div class="col-lg-8 col-lg-offset-2 main-content">
<div class="col-lg-10 col-lg-offset-1">
<form class="form-horizontal" action="<?php echo base_url('update-company-info') ?>" method="post" enctype="multipart/form-data">
<fieldset class="fieldset">
<legend class="">Company Information</legend>
<div class="form-group">
<label for="countryName" class="col-sm-4 control-label">Country Name</label>
<div class="col-sm-8">
<select id="countryName" name="country" class="form-control bfh-countries" data-country="<?php echo $company->country; ?>"></select>
<span class="text-danger">
<?php echo form_error('country') ?>
</span>
</div>
</div>
<div class="form-group">
<label for="name" class="col-sm-4 control-label">Name</label>
<div class="col-sm-8">
<input type="text" name="name" class="form-control" id="name" placeholder="Company Name" value="<?php echo $company->name; ?>">
<input type="hidden" name="update_id" value="<?php echo $this->encryption->encrypt($company->id) ?>">
<span class="text-danger">
<?php echo form_error('name') ?>
</span>
</div>
</div>
<div class="form-group">
<label for="address" class="col-sm-4 control-label">Address</label>
<div class="col-sm-8">
<textarea id="address" name="address" class="form-control" rows="3"><?php echo $company->address; ?></textarea>
</div>
</div>
<div class="form-group">
<label for="phone" class="col-sm-4 control-label">Phone</label>
<div class="col-sm-8">
<input type="text" name="phone" class="form-control" id="phone" placeholder="Phone Number" value="<?php echo $company->phone; ?>">
<span class="text-danger">
<?php echo form_error('phone') ?>
</span>
</div>
</div>
<div class="form-group">
<label for="fax" class="col-sm-4 control-label">Fax</label>
<div class="col-sm-8">
<input type="text" name="fax" class="form-control" id="fax" placeholder="Fax" value="<?php echo $company->fax; ?>">
</div>
</div>
<div class="form-group">
<label for="email" class="col-sm-4 control-label">Email</label>
<div class="col-sm-8">
<input type="text" name="email" class="form-control" id="email" placeholder="Email Address" value="<?php echo $company->email; ?>">
<span class="text-danger">
<?php echo form_error('email') ?>
</span>
</div>
</div>
<div class="form-group">
<label for="webUrl" class="col-sm-4 control-label">Web URL</label>
<div class="col-sm-8">
<input type="text" name="web_url" class="form-control" id="webUrl" placeholder="Website Address" value="<?php echo $company->web_url; ?>">
</div>
</div>
<div class="form-group">
<label for="dateEstablishment" class="col-sm-4 control-label">Date of Establishment</label>
<div class="col-sm-8">
<div class="bfh-datepicker" data-format="y-m-d" data-name="date_established">
<div class="input-prepend bfh-datepicker-toggle" data-toggle="bfh-datepicker">
<span class="add-on"><i class="icon-calendar"></i></span>
<input type="text" class="form-control" id="dateEstablishment" readonly value="<?= $company->date_established; ?>">
</div>
<div class="bfh-datepicker-calendar">
<table class="calendar table table-bordered">
<thead>
<tr class="months-header">
<th class="month" colspan="4">
<a class="previous" href="#"><i class="icon-chevron-left"></i></a>
<span></span>
<a class="next" href="#"><i class="icon-chevron-right"></i></a>
</th>
<th class="year" colspan="3">
<a class="previous" href="#"><i class="icon-chevron-left"></i></a>
<span></span>
<a class="next" href="#"><i class="icon-chevron-right"></i></a>
</th>
</tr>
<tr class="days-header">
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
</div>
</div>
<div class="form-group">
<label for="exampleInputFile" class="col-sm-4 control-label">File input</label>
<div class="col-sm-2">
<img height="50px" src="<?= base_url($company->logo); ?>">
</div>
<div class="col-sm-6">
<input name="logo" type="file" id="exampleInputFile">
<span class="text-danger">
<?php
if($this->session->has_userdata('upload_error')){
print $this->session->flashdata('upload_error');
}
?>
</span>
</div>
</div>
</fieldset>
<div class="form-group">
<div class="col-sm-offset-10 col-sm-2">
<button type="submit" class="btn btn-default btn-primary btn-space">Update</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
| mashqur-ul/simple-ci-crud | application/views/template/company_edit_form.php | PHP | mit | 8,158 |
class Integer
def divisors
res = []
i = 1
while i*i < self
if self % i == 0
res << i
end
i += 1
end
(res.size - 1).downto(1) do |k|
res << self / res[k]
end
res << i if i*i == self
res
end
end
def weird(n)
possible_sums = Hash.new
possible_sums[0] = true
divisors = n.divisors
div_sum = divisors.inject(0) {|s, i| s+i }
return false if div_sum <= n
diff = div_sum - n
return false if divisors.include? diff
divisors.each do |i|
possible_sums.keys.sort.each do |s|
new_sum = s + i
case new_sum <=> diff
when -1
possible_sums[new_sum] = true
when 0
return false
when 1
break
end
end
end
return true
end
n = ARGV.shift or exit
n = n.to_i
m = ARGV.shift
m = m.to_i if m
range = m ? (n..m) : (1..n)
for i in range
puts i if weird(i)
end
| J-Y/RubyQuiz | ruby_quiz/quiz57_sols/solutions/Paolo Capriotti/weird_numbers.rb | Ruby | mit | 898 |
module ClimbsHelper
end
| marinatedpork/chicago_climber | app/helpers/climbs_helper.rb | Ruby | mit | 24 |
// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2012 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 "alert.h"
#include "checkpoints.h"
#include "db.h"
#include "txdb.h"
#include "net.h"
#include "init.h"
#include "ui_interface.h"
#include "checkqueue.h"
#include "kernel.h"
#include <boost/algorithm/string/replace.hpp>
#include <boost/filesystem.hpp>
#include <boost/filesystem/fstream.hpp>
#include "main.h"
using namespace std;
using namespace boost;
CCriticalSection cs_setpwalletRegistered;
set<CWallet*> setpwalletRegistered;
CCriticalSection cs_main;
CTxMemPool mempool;
unsigned int nTransactionsUpdated = 0;
map<uint256, CBlockIndex*> mapBlockIndex;
set<pair<COutPoint, unsigned int> > setStakeSeen;
CBigNum bnProofOfWorkLimit(~uint256(0) >> 20); // "standard" scrypt target limit for proof of work, results with 0,000244140625 proof-of-work difficulty
CBigNum bnProofOfStakeLegacyLimit(~uint256(0) >> 24); // proof of stake target limit from block #15000 and until 20 June 2013, results with 0,00390625 proof of stake difficulty
CBigNum bnProofOfStakeLimit(~uint256(0) >> 27); // proof of stake target limit since 20 June 2013, equal to 0.03125 proof of stake difficulty
CBigNum bnProofOfStakeHardLimit(~uint256(0) >> 30); // disabled temporarily, will be used in the future to fix minimal proof of stake difficulty at 0.25
uint256 nPoWBase = uint256("0x00000000ffff0000000000000000000000000000000000000000000000000000"); // difficulty-1 target
CBigNum bnProofOfWorkLimitTestNet(~uint256(0) >> 16);
unsigned int nStakeMinAge = 60 * 5; // 30 days as zero time weight
unsigned int nStakeMaxAge = 60 * 60 * 24 * 90; // 90 days as full weight
unsigned int nStakeTargetSpacing = 10 * 60; // 10-minute stakes spacing
unsigned int nModifierInterval = 6 * 60 * 60; // time to elapse before new modifier is computed
int nCoinbaseMaturity = 500;
CBlockIndex* pindexGenesisBlock = NULL;
int nBestHeight = -1;
uint256 nBestChainTrust = 0;
uint256 nBestInvalidTrust = 0;
uint256 hashBestChain = 0;
CBlockIndex* pindexBest = NULL;
int64_t nTimeBestReceived = 0;
int nScriptCheckThreads = 0;
CMedianFilter<int> cPeerBlockCounts(5, 0); // Amount of blocks that other nodes claim to have
map<uint256, CBlock*> mapOrphanBlocks;
multimap<uint256, CBlock*> mapOrphanBlocksByPrev;
set<pair<COutPoint, unsigned int> > setStakeSeenOrphan;
map<uint256, uint256> mapProofOfStake;
map<uint256, CTransaction> mapOrphanTransactions;
map<uint256, set<uint256> > mapOrphanTransactionsByPrev;
// Constant stuff for coinbase transactions we create:
CScript COINBASE_FLAGS;
const string strMessageMagic = "NovaCoin Signed Message:\n";
// Settings
int64_t nTransactionFee = MIN_TX_FEE;
int64_t nMinimumInputValue = MIN_TX_FEE;
// Ping and address broadcast intervals
int64_t nPingInterval = 30 * 60;
int64_t nBroadcastInterval = 24 * 60 * 60;
extern enum Checkpoints::CPMode CheckpointsMode;
//////////////////////////////////////////////////////////////////////////////
//
// dispatching functions
//
// These functions dispatch to one or all registered wallets
void RegisterWallet(CWallet* pwalletIn)
{
{
LOCK(cs_setpwalletRegistered);
setpwalletRegistered.insert(pwalletIn);
}
}
void UnregisterWallet(CWallet* pwalletIn)
{
{
LOCK(cs_setpwalletRegistered);
setpwalletRegistered.erase(pwalletIn);
}
}
// check whether the passed transaction is from us
bool static IsFromMe(CTransaction& tx)
{
BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
if (pwallet->IsFromMe(tx))
return true;
return false;
}
// get the wallet transaction with the given hash (if it exists)
bool static GetTransaction(const uint256& hashTx, CWalletTx& wtx)
{
BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
if (pwallet->GetTransaction(hashTx,wtx))
return true;
return false;
}
// erases transaction with the given hash from all wallets
void static EraseFromWallets(uint256 hash)
{
BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
pwallet->EraseFromWallet(hash);
}
// make sure all wallets know about the given transaction, in the given block
void SyncWithWallets(const CTransaction& tx, const CBlock* pblock, bool fUpdate, bool fConnect)
{
if (!fConnect)
{
// ppcoin: wallets need to refund inputs when disconnecting coinstake
if (tx.IsCoinStake())
{
BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
if (pwallet->IsFromMe(tx))
pwallet->DisableTransaction(tx);
}
return;
}
BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
pwallet->AddToWalletIfInvolvingMe(tx, pblock, fUpdate);
// Preloaded coins cache invalidation
fCoinsDataActual = false;
}
// notify wallets about a new best chain
void static SetBestChain(const CBlockLocator& loc)
{
BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
pwallet->SetBestChain(loc);
}
// notify wallets about an updated transaction
void static UpdatedTransaction(const uint256& hashTx)
{
BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
pwallet->UpdatedTransaction(hashTx);
}
// dump all wallets
void static PrintWallets(const CBlock& block)
{
BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
pwallet->PrintWallet(block);
}
// notify wallets about an incoming inventory (for request counts)
void static Inventory(const uint256& hash)
{
BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
pwallet->Inventory(hash);
}
// ask wallets to resend their transactions
void ResendWalletTransactions()
{
BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
pwallet->ResendWalletTransactions();
}
//////////////////////////////////////////////////////////////////////////////
//
// mapOrphanTransactions
//
bool AddOrphanTx(const CTransaction& tx)
{
uint256 hash = tx.GetHash();
if (mapOrphanTransactions.count(hash))
return false;
// Ignore big transactions, to avoid a
// send-big-orphans memory exhaustion attack. If a peer has a legitimate
// large transaction with a missing parent then we assume
// it will rebroadcast it later, after the parent transaction(s)
// have been mined or received.
// 10,000 orphans, each of which is at most 5,000 bytes big is
// at most 500 megabytes of orphans:
size_t nSize = tx.GetSerializeSize(SER_NETWORK, CTransaction::CURRENT_VERSION);
if (nSize > 5000)
{
printf("ignoring large orphan tx (size: %" PRIszu ", hash: %s)\n", nSize, hash.ToString().substr(0,10).c_str());
return false;
}
mapOrphanTransactions[hash] = tx;
BOOST_FOREACH(const CTxIn& txin, tx.vin)
mapOrphanTransactionsByPrev[txin.prevout.hash].insert(hash);
printf("stored orphan tx %s (mapsz %" PRIszu ")\n", hash.ToString().substr(0,10).c_str(),
mapOrphanTransactions.size());
return true;
}
void static EraseOrphanTx(uint256 hash)
{
if (!mapOrphanTransactions.count(hash))
return;
const CTransaction& tx = mapOrphanTransactions[hash];
BOOST_FOREACH(const CTxIn& txin, tx.vin)
{
mapOrphanTransactionsByPrev[txin.prevout.hash].erase(hash);
if (mapOrphanTransactionsByPrev[txin.prevout.hash].empty())
mapOrphanTransactionsByPrev.erase(txin.prevout.hash);
}
mapOrphanTransactions.erase(hash);
}
unsigned int LimitOrphanTxSize(unsigned int nMaxOrphans)
{
unsigned int nEvicted = 0;
while (mapOrphanTransactions.size() > nMaxOrphans)
{
// Evict a random orphan:
uint256 randomhash = GetRandHash();
map<uint256, CTransaction>::iterator it = mapOrphanTransactions.lower_bound(randomhash);
if (it == mapOrphanTransactions.end())
it = mapOrphanTransactions.begin();
EraseOrphanTx(it->first);
++nEvicted;
}
return nEvicted;
}
//////////////////////////////////////////////////////////////////////////////
//
// CTransaction and CTxIndex
//
bool CTransaction::ReadFromDisk(CTxDB& txdb, COutPoint prevout, CTxIndex& txindexRet)
{
SetNull();
if (!txdb.ReadTxIndex(prevout.hash, txindexRet))
return false;
if (!ReadFromDisk(txindexRet.pos))
return false;
if (prevout.n >= vout.size())
{
SetNull();
return false;
}
return true;
}
bool CTransaction::ReadFromDisk(CTxDB& txdb, COutPoint prevout)
{
CTxIndex txindex;
return ReadFromDisk(txdb, prevout, txindex);
}
bool CTransaction::ReadFromDisk(COutPoint prevout)
{
CTxDB txdb("r");
CTxIndex txindex;
return ReadFromDisk(txdb, prevout, txindex);
}
bool CTransaction::IsStandard(string& strReason) const
{
if (nVersion > CTransaction::CURRENT_VERSION)
{
strReason = "version";
return false;
}
unsigned int nDataOut = 0;
txnouttype whichType;
BOOST_FOREACH(const CTxIn& txin, vin)
{
// Biggest 'standard' txin is a 15-of-15 P2SH multisig with compressed
// keys. (remember the 520 byte limit on redeemScript size) That works
// out to a (15*(33+1))+3=513 byte redeemScript, 513+1+15*(73+1)=1624
// bytes of scriptSig, which we round off to 1650 bytes for some minor
// future-proofing. That's also enough to spend a 20-of-20
// CHECKMULTISIG scriptPubKey, though such a scriptPubKey is not
// considered standard)
if (txin.scriptSig.size() > 1650)
{
strReason = "scriptsig-size";
return false;
}
if (!txin.scriptSig.IsPushOnly())
{
strReason = "scriptsig-not-pushonly";
return false;
}
if (!txin.scriptSig.HasCanonicalPushes()) {
strReason = "txin-scriptsig-not-canonicalpushes";
return false;
}
}
BOOST_FOREACH(const CTxOut& txout, vout) {
if (!::IsStandard(txout.scriptPubKey, whichType)) {
strReason = "scriptpubkey";
return false;
}
if (whichType == TX_NULL_DATA)
nDataOut++;
else {
if (txout.nValue == 0) {
strReason = "txout-value=0";
return false;
}
if (!txout.scriptPubKey.HasCanonicalPushes()) {
strReason = "txout-scriptsig-not-canonicalpushes";
return false;
}
}
}
// only one OP_RETURN txout is permitted
if (nDataOut > 1) {
strReason = "multi-op-return";
return false;
}
return true;
}
//
// Check transaction inputs, and make sure any
// pay-to-script-hash transactions are evaluating IsStandard scripts
//
// Why bother? To avoid denial-of-service attacks; an attacker
// can submit a standard HASH... OP_EQUAL transaction,
// which will get accepted into blocks. The redemption
// script can be anything; an attacker could use a very
// expensive-to-check-upon-redemption script like:
// DUP CHECKSIG DROP ... repeated 100 times... OP_1
//
bool CTransaction::AreInputsStandard(const MapPrevTx& mapInputs) const
{
if (IsCoinBase())
return true; // Coinbases don't use vin normally
for (unsigned int i = 0; i < vin.size(); i++)
{
const CTxOut& prev = GetOutputFor(vin[i], mapInputs);
vector<vector<unsigned char> > vSolutions;
txnouttype whichType;
// get the scriptPubKey corresponding to this input:
const CScript& prevScript = prev.scriptPubKey;
if (!Solver(prevScript, whichType, vSolutions))
return false;
int nArgsExpected = ScriptSigArgsExpected(whichType, vSolutions);
if (nArgsExpected < 0)
return false;
// Transactions with extra stuff in their scriptSigs are
// non-standard. Note that this EvalScript() call will
// be quick, because if there are any operations
// beside "push data" in the scriptSig the
// IsStandard() call returns false
vector<vector<unsigned char> > stack;
if (!EvalScript(stack, vin[i].scriptSig, *this, i, false, 0))
return false;
if (whichType == TX_SCRIPTHASH)
{
if (stack.empty())
return false;
CScript subscript(stack.back().begin(), stack.back().end());
vector<vector<unsigned char> > vSolutions2;
txnouttype whichType2;
if (!Solver(subscript, whichType2, vSolutions2))
return false;
if (whichType2 == TX_SCRIPTHASH)
return false;
int tmpExpected;
tmpExpected = ScriptSigArgsExpected(whichType2, vSolutions2);
if (tmpExpected < 0)
return false;
nArgsExpected += tmpExpected;
}
if (stack.size() != (unsigned int)nArgsExpected)
return false;
}
return true;
}
unsigned int
CTransaction::GetLegacySigOpCount() const
{
unsigned int nSigOps = 0;
BOOST_FOREACH(const CTxIn& txin, vin)
{
nSigOps += txin.scriptSig.GetSigOpCount(false);
}
BOOST_FOREACH(const CTxOut& txout, vout)
{
nSigOps += txout.scriptPubKey.GetSigOpCount(false);
}
return nSigOps;
}
int CMerkleTx::SetMerkleBranch(const CBlock* pblock)
{
if (fClient)
{
if (hashBlock == 0)
return 0;
}
else
{
CBlock blockTmp;
if (pblock == NULL)
{
// Load the block this tx is in
CTxIndex txindex;
if (!CTxDB("r").ReadTxIndex(GetHash(), txindex))
return 0;
if (!blockTmp.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos))
return 0;
pblock = &blockTmp;
}
// Update the tx's hashBlock
hashBlock = pblock->GetHash();
// Locate the transaction
for (nIndex = 0; nIndex < (int)pblock->vtx.size(); nIndex++)
if (pblock->vtx[nIndex] == *(CTransaction*)this)
break;
if (nIndex == (int)pblock->vtx.size())
{
vMerkleBranch.clear();
nIndex = -1;
printf("ERROR: SetMerkleBranch() : couldn't find tx in block\n");
return 0;
}
// Fill in merkle branch
vMerkleBranch = pblock->GetMerkleBranch(nIndex);
}
// Is the tx in a block that's in the main chain
map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
if (mi == mapBlockIndex.end())
return 0;
CBlockIndex* pindex = (*mi).second;
if (!pindex || !pindex->IsInMainChain())
return 0;
return pindexBest->nHeight - pindex->nHeight + 1;
}
bool CTransaction::CheckTransaction() const
{
// Basic checks that don't depend on any context
if (vin.empty())
return DoS(10, error("CTransaction::CheckTransaction() : vin empty"));
if (vout.empty())
return DoS(10, error("CTransaction::CheckTransaction() : vout empty"));
// Size limits
if (::GetSerializeSize(*this, SER_NETWORK, PROTOCOL_VERSION) > MAX_BLOCK_SIZE)
return DoS(100, error("CTransaction::CheckTransaction() : size limits failed"));
// Check for negative or overflow output values
int64_t nValueOut = 0;
for (unsigned int i = 0; i < vout.size(); i++)
{
const CTxOut& txout = vout[i];
if (txout.IsEmpty() && !IsCoinBase() && !IsCoinStake())
return DoS(100, error("CTransaction::CheckTransaction() : txout empty for user transaction"));
if (txout.nValue < 0)
return DoS(100, error("CTransaction::CheckTransaction() : txout.nValue is negative"));
if (txout.nValue > MAX_MONEY)
return DoS(100, error("CTransaction::CheckTransaction() : txout.nValue too high"));
nValueOut += txout.nValue;
if (!MoneyRange(nValueOut))
return DoS(100, error("CTransaction::CheckTransaction() : txout total out of range"));
}
// Check for duplicate inputs
set<COutPoint> vInOutPoints;
BOOST_FOREACH(const CTxIn& txin, vin)
{
if (vInOutPoints.count(txin.prevout))
return false;
vInOutPoints.insert(txin.prevout);
}
if (IsCoinBase())
{
if (vin[0].scriptSig.size() < 2 || vin[0].scriptSig.size() > 100)
return DoS(100, error("CTransaction::CheckTransaction() : coinbase script size is invalid"));
}
else
{
BOOST_FOREACH(const CTxIn& txin, vin)
if (txin.prevout.IsNull())
return DoS(10, error("CTransaction::CheckTransaction() : prevout is null"));
}
return true;
}
int64_t CTransaction::GetMinFee(unsigned int nBlockSize, bool fAllowFree, enum GetMinFee_mode mode, unsigned int nBytes) const
{
int64_t nMinTxFee = MIN_TX_FEE, nMinRelayTxFee = MIN_RELAY_TX_FEE;
if(IsCoinStake())
{
// Enforce 0.01 as minimum fee for old approach or coinstake
nMinTxFee = CENT;
nMinRelayTxFee = CENT;
}
// Base fee is either nMinTxFee or nMinRelayTxFee
int64_t nBaseFee = (mode == GMF_RELAY) ? nMinRelayTxFee : nMinTxFee;
unsigned int nNewBlockSize = nBlockSize + nBytes;
int64_t nMinFee = (1 + (int64_t)nBytes / 1000) * nBaseFee;
if (fAllowFree)
{
if (nBlockSize == 1)
{
// Transactions under 1K are free
if (nBytes < 1000)
nMinFee = 0;
}
else
{
// Free transaction area
if (nNewBlockSize < 27000)
nMinFee = 0;
}
}
// To limit dust spam, require additional MIN_TX_FEE/MIN_RELAY_TX_FEE for
// each non empty output which is less than 0.01
//
// It's safe to ignore empty outputs here, because these inputs are allowed
// only for coinbase and coinstake transactions.
BOOST_FOREACH(const CTxOut& txout, vout)
if (txout.nValue < CENT && !txout.IsEmpty())
nMinFee += nBaseFee;
// Raise the price as the block approaches full
if (nBlockSize != 1 && nNewBlockSize >= MAX_BLOCK_SIZE_GEN/2)
{
if (nNewBlockSize >= MAX_BLOCK_SIZE_GEN)
return MAX_MONEY;
nMinFee *= MAX_BLOCK_SIZE_GEN / (MAX_BLOCK_SIZE_GEN - nNewBlockSize);
}
if (!MoneyRange(nMinFee))
nMinFee = MAX_MONEY;
return nMinFee;
}
bool CTxMemPool::accept(CTxDB& txdb, CTransaction &tx, bool fCheckInputs,
bool* pfMissingInputs)
{
if (pfMissingInputs)
*pfMissingInputs = false;
if (!tx.CheckTransaction())
return error("CTxMemPool::accept() : CheckTransaction failed");
// Coinbase is only valid in a block, not as a loose transaction
if (tx.IsCoinBase())
return tx.DoS(100, error("CTxMemPool::accept() : coinbase as individual tx"));
// ppcoin: coinstake is also only valid in a block, not as a loose transaction
if (tx.IsCoinStake())
return tx.DoS(100, error("CTxMemPool::accept() : coinstake as individual tx"));
// To help v0.1.5 clients who would see it as a negative number
if ((int64_t)tx.nLockTime > std::numeric_limits<int>::max())
return error("CTxMemPool::accept() : not accepting nLockTime beyond 2038 yet");
// Rather not work on nonstandard transactions (unless -testnet)
string strNonStd;
if (!fTestNet && !tx.IsStandard(strNonStd))
return error("CTxMemPool::accept() : nonstandard transaction (%s)", strNonStd.c_str());
// Do we already have it?
uint256 hash = tx.GetHash();
{
LOCK(cs);
if (mapTx.count(hash))
return false;
}
if (fCheckInputs)
if (txdb.ContainsTx(hash))
return false;
// Check for conflicts with in-memory transactions
CTransaction* ptxOld = NULL;
for (unsigned int i = 0; i < tx.vin.size(); i++)
{
COutPoint outpoint = tx.vin[i].prevout;
if (mapNextTx.count(outpoint))
{
// Disable replacement feature for now
return false;
// Allow replacing with a newer version of the same transaction
if (i != 0)
return false;
ptxOld = mapNextTx[outpoint].ptx;
if (ptxOld->IsFinal())
return false;
if (!tx.IsNewerThan(*ptxOld))
return false;
for (unsigned int i = 0; i < tx.vin.size(); i++)
{
COutPoint outpoint = tx.vin[i].prevout;
if (!mapNextTx.count(outpoint) || mapNextTx[outpoint].ptx != ptxOld)
return false;
}
break;
}
}
if (fCheckInputs)
{
MapPrevTx mapInputs;
map<uint256, CTxIndex> mapUnused;
bool fInvalid = false;
if (!tx.FetchInputs(txdb, mapUnused, false, false, mapInputs, fInvalid))
{
if (fInvalid)
return error("CTxMemPool::accept() : FetchInputs found invalid tx %s", hash.ToString().substr(0,10).c_str());
if (pfMissingInputs)
*pfMissingInputs = true;
return false;
}
// Check for non-standard pay-to-script-hash in inputs
if (!tx.AreInputsStandard(mapInputs) && !fTestNet)
return error("CTxMemPool::accept() : nonstandard transaction input");
// Note: if you modify this code to accept non-standard transactions, then
// you should add code here to check that the transaction does a
// reasonable number of ECDSA signature verifications.
int64_t nFees = tx.GetValueIn(mapInputs)-tx.GetValueOut();
unsigned int nSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION);
// Don't accept it if it can't get into a block
int64_t txMinFee = tx.GetMinFee(1000, true, GMF_RELAY, nSize);
if (nFees < txMinFee)
return error("CTxMemPool::accept() : not enough fees %s, %" PRId64 " < %" PRId64,
hash.ToString().c_str(),
nFees, txMinFee);
// Continuously rate-limit free transactions
// This mitigates 'penny-flooding' -- sending thousands of free transactions just to
// be annoying or make others' transactions take longer to confirm.
if (nFees < MIN_RELAY_TX_FEE)
{
static CCriticalSection cs;
static double dFreeCount;
static int64_t nLastTime;
int64_t nNow = GetTime();
{
LOCK(cs);
// Use an exponentially decaying ~10-minute window:
dFreeCount *= pow(1.0 - 1.0/600.0, (double)(nNow - nLastTime));
nLastTime = nNow;
// -limitfreerelay unit is thousand-bytes-per-minute
// At default rate it would take over a month to fill 1GB
if (dFreeCount > GetArg("-limitfreerelay", 15)*10*1000 && !IsFromMe(tx))
return error("CTxMemPool::accept() : free transaction rejected by rate limiter");
if (fDebug)
printf("Rate limit dFreeCount: %g => %g\n", dFreeCount, dFreeCount+nSize);
dFreeCount += nSize;
}
}
// Check against previous transactions
// This is done last to help prevent CPU exhaustion denial-of-service attacks.
if (!tx.ConnectInputs(txdb, mapInputs, mapUnused, CDiskTxPos(1,1,1), pindexBest, false, false, true, SIG_SWITCH_TIME < tx.nTime ? STRICT_FLAGS : SOFT_FLAGS))
{
return error("CTxMemPool::accept() : ConnectInputs failed %s", hash.ToString().substr(0,10).c_str());
}
}
// Store transaction in memory
{
LOCK(cs);
if (ptxOld)
{
printf("CTxMemPool::accept() : replacing tx %s with new version\n", ptxOld->GetHash().ToString().c_str());
remove(*ptxOld);
}
addUnchecked(hash, tx);
}
///// are we sure this is ok when loading transactions or restoring block txes
// If updated, erase old tx from wallet
if (ptxOld)
EraseFromWallets(ptxOld->GetHash());
printf("CTxMemPool::accept() : accepted %s (poolsz %" PRIszu ")\n",
hash.ToString().substr(0,10).c_str(),
mapTx.size());
return true;
}
bool CTransaction::AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs, bool* pfMissingInputs)
{
return mempool.accept(txdb, *this, fCheckInputs, pfMissingInputs);
}
bool CTxMemPool::addUnchecked(const uint256& hash, CTransaction &tx)
{
// Add to memory pool without checking anything. Don't call this directly,
// call CTxMemPool::accept to properly check the transaction first.
{
mapTx[hash] = tx;
for (unsigned int i = 0; i < tx.vin.size(); i++)
mapNextTx[tx.vin[i].prevout] = CInPoint(&mapTx[hash], i);
nTransactionsUpdated++;
}
return true;
}
bool CTxMemPool::remove(CTransaction &tx)
{
// Remove transaction from memory pool
{
LOCK(cs);
uint256 hash = tx.GetHash();
if (mapTx.count(hash))
{
BOOST_FOREACH(const CTxIn& txin, tx.vin)
mapNextTx.erase(txin.prevout);
mapTx.erase(hash);
nTransactionsUpdated++;
}
}
return true;
}
void CTxMemPool::clear()
{
LOCK(cs);
mapTx.clear();
mapNextTx.clear();
++nTransactionsUpdated;
}
void CTxMemPool::queryHashes(std::vector<uint256>& vtxid)
{
vtxid.clear();
LOCK(cs);
vtxid.reserve(mapTx.size());
for (map<uint256, CTransaction>::iterator mi = mapTx.begin(); mi != mapTx.end(); ++mi)
vtxid.push_back((*mi).first);
}
int CMerkleTx::GetDepthInMainChain(CBlockIndex* &pindexRet) const
{
if (hashBlock == 0 || nIndex == -1)
return 0;
// Find the block it claims to be in
map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
if (mi == mapBlockIndex.end())
return 0;
CBlockIndex* pindex = (*mi).second;
if (!pindex || !pindex->IsInMainChain())
return 0;
// Make sure the merkle branch connects to this block
if (!fMerkleVerified)
{
if (CBlock::CheckMerkleBranch(GetHash(), vMerkleBranch, nIndex) != pindex->hashMerkleRoot)
return 0;
fMerkleVerified = true;
}
pindexRet = pindex;
return pindexBest->nHeight - pindex->nHeight + 1;
}
int CMerkleTx::GetBlocksToMaturity() const
{
if (!(IsCoinBase() || IsCoinStake()))
return 0;
return max(0, (nCoinbaseMaturity+20) - GetDepthInMainChain());
}
bool CMerkleTx::AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs)
{
if (fClient)
{
if (!IsInMainChain() && !ClientConnectInputs())
return false;
return CTransaction::AcceptToMemoryPool(txdb, false);
}
else
{
return CTransaction::AcceptToMemoryPool(txdb, fCheckInputs);
}
}
bool CMerkleTx::AcceptToMemoryPool()
{
CTxDB txdb("r");
return AcceptToMemoryPool(txdb);
}
bool CWalletTx::AcceptWalletTransaction(CTxDB& txdb, bool fCheckInputs)
{
{
LOCK(mempool.cs);
// Add previous supporting transactions first
BOOST_FOREACH(CMerkleTx& tx, vtxPrev)
{
if (!(tx.IsCoinBase() || tx.IsCoinStake()))
{
uint256 hash = tx.GetHash();
if (!mempool.exists(hash) && !txdb.ContainsTx(hash))
tx.AcceptToMemoryPool(txdb, fCheckInputs);
}
}
return AcceptToMemoryPool(txdb, fCheckInputs);
}
return false;
}
bool CWalletTx::AcceptWalletTransaction()
{
CTxDB txdb("r");
return AcceptWalletTransaction(txdb);
}
int CTxIndex::GetDepthInMainChain() const
{
// Read block header
CBlock block;
if (!block.ReadFromDisk(pos.nFile, pos.nBlockPos, false))
return 0;
// Find the block in the index
map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(block.GetHash());
if (mi == mapBlockIndex.end())
return 0;
CBlockIndex* pindex = (*mi).second;
if (!pindex || !pindex->IsInMainChain())
return 0;
return 1 + nBestHeight - pindex->nHeight;
}
// Return transaction in tx, and if it was found inside a block, its hash is placed in hashBlock
bool GetTransaction(const uint256 &hash, CTransaction &tx, uint256 &hashBlock)
{
{
LOCK(cs_main);
{
LOCK(mempool.cs);
if (mempool.exists(hash))
{
tx = mempool.lookup(hash);
return true;
}
}
CTxDB txdb("r");
CTxIndex txindex;
if (tx.ReadFromDisk(txdb, COutPoint(hash, 0), txindex))
{
CBlock block;
if (block.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos, false))
hashBlock = block.GetHash();
return true;
}
}
return false;
}
//////////////////////////////////////////////////////////////////////////////
//
// CBlock and CBlockIndex
//
static CBlockIndex* pblockindexFBBHLast;
CBlockIndex* FindBlockByHeight(int nHeight)
{
CBlockIndex *pblockindex;
if (nHeight < nBestHeight / 2)
pblockindex = pindexGenesisBlock;
else
pblockindex = pindexBest;
if (pblockindexFBBHLast && abs(nHeight - pblockindex->nHeight) > abs(nHeight - pblockindexFBBHLast->nHeight))
pblockindex = pblockindexFBBHLast;
while (pblockindex->nHeight > nHeight)
pblockindex = pblockindex->pprev;
while (pblockindex->nHeight < nHeight)
pblockindex = pblockindex->pnext;
pblockindexFBBHLast = pblockindex;
return pblockindex;
}
bool CBlock::ReadFromDisk(const CBlockIndex* pindex, bool fReadTransactions)
{
if (!fReadTransactions)
{
*this = pindex->GetBlockHeader();
return true;
}
if (!ReadFromDisk(pindex->nFile, pindex->nBlockPos, fReadTransactions))
return false;
if (GetHash() != pindex->GetBlockHash())
return error("CBlock::ReadFromDisk() : GetHash() doesn't match index");
return true;
}
uint256 static GetOrphanRoot(const CBlock* pblock)
{
// Work back to the first block in the orphan chain
while (mapOrphanBlocks.count(pblock->hashPrevBlock))
pblock = mapOrphanBlocks[pblock->hashPrevBlock];
return pblock->GetHash();
}
// ppcoin: find block wanted by given orphan block
uint256 WantedByOrphan(const CBlock* pblockOrphan)
{
// Work back to the first block in the orphan chain
while (mapOrphanBlocks.count(pblockOrphan->hashPrevBlock))
pblockOrphan = mapOrphanBlocks[pblockOrphan->hashPrevBlock];
return pblockOrphan->hashPrevBlock;
}
// select stake target limit according to hard-coded conditions
CBigNum inline GetProofOfStakeLimit(int nHeight, unsigned int nTime)
{
if(fTestNet) // separate proof of stake target limit for testnet
return bnProofOfStakeLimit;
if(nTime > TARGETS_SWITCH_TIME) // 27 bits since 20 July 2013
return bnProofOfStakeLimit;
if(nHeight + 1 > 15000) // 24 bits since block 15000
return bnProofOfStakeLegacyLimit;
if(nHeight + 1 > 14060) // 31 bits since block 14060 until 15000
return bnProofOfStakeHardLimit;
return bnProofOfWorkLimit; // return bnProofOfWorkLimit of none matched
}
// miner's coin base reward based on nBits
int64_t GetProofOfWorkReward(unsigned int nBits, int64_t nFees)
{
CBigNum bnSubsidyLimit = MAX_MINT_PROOF_OF_WORK;
CBigNum bnTarget;
bnTarget.SetCompact(nBits);
CBigNum bnTargetLimit = bnProofOfWorkLimit;
bnTargetLimit.SetCompact(bnTargetLimit.GetCompact());
// NovaCoin: subsidy is cut in half every 64x multiply of PoW difficulty
// A reasonably continuous curve is used to avoid shock to market
// (nSubsidyLimit / nSubsidy) ** 6 == bnProofOfWorkLimit / bnTarget
//
// Human readable form:
//
// nSubsidy = 100 / (diff ^ 1/6)
CBigNum bnLowerBound = CENT;
CBigNum bnUpperBound = bnSubsidyLimit;
while (bnLowerBound + CENT <= bnUpperBound)
{
CBigNum bnMidValue = (bnLowerBound + bnUpperBound) / 2;
if (fDebug && GetBoolArg("-printcreation"))
printf("GetProofOfWorkReward() : lower=%" PRId64 " upper=%" PRId64 " mid=%" PRId64 "\n", bnLowerBound.getuint64(), bnUpperBound.getuint64(), bnMidValue.getuint64());
if (bnMidValue * bnMidValue * bnMidValue * bnMidValue * bnMidValue * bnMidValue * bnTargetLimit > bnSubsidyLimit * bnSubsidyLimit * bnSubsidyLimit * bnSubsidyLimit * bnSubsidyLimit * bnSubsidyLimit * bnTarget)
bnUpperBound = bnMidValue;
else
bnLowerBound = bnMidValue;
}
int64_t nSubsidy = bnUpperBound.getuint64();
nSubsidy = (nSubsidy / CENT) * CENT;
if (fDebug && GetBoolArg("-printcreation"))
printf("GetProofOfWorkReward() : create=%s nBits=0x%08x nSubsidy=%" PRId64 "\n", FormatMoney(nSubsidy).c_str(), nBits, nSubsidy);
return min(nSubsidy, MAX_MINT_PROOF_OF_WORK) + nFees;
}
// miner's coin stake reward based on nBits and coin age spent (coin-days)
int64_t GetProofOfStakeReward(int64_t nCoinAge, unsigned int nBits, int64_t nTime, bool bCoinYearOnly)
{
int64_t nRewardCoinYear, nSubsidy, nSubsidyLimit = 10 * COIN;
if(fTestNet || nTime > STAKE_SWITCH_TIME)
{
// Stage 2 of emission process is PoS-based. It will be active on mainNet since 20 Jun 2013.
CBigNum bnRewardCoinYearLimit = MAX_MINT_PROOF_OF_STAKE; // Base stake mint rate, 100% year interest
CBigNum bnTarget;
bnTarget.SetCompact(nBits);
CBigNum bnTargetLimit = GetProofOfStakeLimit(0, nTime);
bnTargetLimit.SetCompact(bnTargetLimit.GetCompact());
// NovaCoin: A reasonably continuous curve is used to avoid shock to market
CBigNum bnLowerBound = 1 * CENT, // Lower interest bound is 1% per year
bnUpperBound = bnRewardCoinYearLimit, // Upper interest bound is 100% per year
bnMidPart, bnRewardPart;
while (bnLowerBound + CENT <= bnUpperBound)
{
CBigNum bnMidValue = (bnLowerBound + bnUpperBound) / 2;
if (fDebug && GetBoolArg("-printcreation"))
printf("GetProofOfStakeReward() : lower=%" PRId64 " upper=%" PRId64 " mid=%" PRId64 "\n", bnLowerBound.getuint64(), bnUpperBound.getuint64(), bnMidValue.getuint64());
if(!fTestNet && nTime < STAKECURVE_SWITCH_TIME)
{
//
// Until 20 Oct 2013: reward for coin-year is cut in half every 64x multiply of PoS difficulty
//
// (nRewardCoinYearLimit / nRewardCoinYear) ** 6 == bnProofOfStakeLimit / bnTarget
//
// Human readable form: nRewardCoinYear = 1 / (posdiff ^ 1/6)
//
bnMidPart = bnMidValue * bnMidValue * bnMidValue * bnMidValue * bnMidValue * bnMidValue;
bnRewardPart = bnRewardCoinYearLimit * bnRewardCoinYearLimit * bnRewardCoinYearLimit * bnRewardCoinYearLimit * bnRewardCoinYearLimit * bnRewardCoinYearLimit;
}
else
{
//
// Since 20 Oct 2013: reward for coin-year is cut in half every 8x multiply of PoS difficulty
//
// (nRewardCoinYearLimit / nRewardCoinYear) ** 3 == bnProofOfStakeLimit / bnTarget
//
// Human readable form: nRewardCoinYear = 1 / (posdiff ^ 1/3)
//
bnMidPart = bnMidValue * bnMidValue * bnMidValue;
bnRewardPart = bnRewardCoinYearLimit * bnRewardCoinYearLimit * bnRewardCoinYearLimit;
}
if (bnMidPart * bnTargetLimit > bnRewardPart * bnTarget)
bnUpperBound = bnMidValue;
else
bnLowerBound = bnMidValue;
}
nRewardCoinYear = bnUpperBound.getuint64();
nRewardCoinYear = min((nRewardCoinYear / CENT) * CENT, MAX_MINT_PROOF_OF_STAKE);
}
else
{
// Old creation amount per coin-year, 5% fixed stake mint rate
nRewardCoinYear = 5 * CENT;
}
if(bCoinYearOnly)
return nRewardCoinYear;
nSubsidy = nCoinAge * nRewardCoinYear * 33 / (365 * 33 + 8);
// Set reasonable reward limit for large inputs since 20 Oct 2013
//
// This will stimulate large holders to use smaller inputs, that's good for the network protection
if(fTestNet || STAKECURVE_SWITCH_TIME < nTime)
{
if (fDebug && GetBoolArg("-printcreation") && nSubsidyLimit < nSubsidy)
printf("GetProofOfStakeReward(): %s is greater than %s, coinstake reward will be truncated\n", FormatMoney(nSubsidy).c_str(), FormatMoney(nSubsidyLimit).c_str());
nSubsidy = min(nSubsidy, nSubsidyLimit);
}
if (fDebug && GetBoolArg("-printcreation"))
printf("GetProofOfStakeReward(): create=%s nCoinAge=%" PRId64 " nBits=%d\n", FormatMoney(nSubsidy).c_str(), nCoinAge, nBits);
return nSubsidy;
}
static const int64_t nTargetTimespan = 7 * 24 * 60 * 60; // one week
// get proof of work blocks max spacing according to hard-coded conditions
int64_t inline GetTargetSpacingWorkMax(int nHeight, unsigned int nTime)
{
if(nTime > TARGETS_SWITCH_TIME)
return 3 * nStakeTargetSpacing; // 30 minutes on mainNet since 20 Jul 2013 00:00:00
if(fTestNet)
return 3 * nStakeTargetSpacing; // 15 minutes on testNet
return 12 * nStakeTargetSpacing; // 2 hours otherwise
}
//
// maximum nBits value could possible be required nTime after
//
unsigned int ComputeMaxBits(CBigNum bnTargetLimit, unsigned int nBase, int64_t nTime)
{
CBigNum bnResult;
bnResult.SetCompact(nBase);
bnResult *= 2;
while (nTime > 0 && bnResult < bnTargetLimit)
{
// Maximum 200% adjustment per day...
bnResult *= 2;
nTime -= 24 * 60 * 60;
}
if (bnResult > bnTargetLimit)
bnResult = bnTargetLimit;
return bnResult.GetCompact();
}
//
// minimum amount of work that could possibly be required nTime after
// minimum proof-of-work required was nBase
//
unsigned int ComputeMinWork(unsigned int nBase, int64_t nTime)
{
return ComputeMaxBits(bnProofOfWorkLimit, nBase, nTime);
}
//
// minimum amount of stake that could possibly be required nTime after
// minimum proof-of-stake required was nBase
//
unsigned int ComputeMinStake(unsigned int nBase, int64_t nTime, unsigned int nBlockTime)
{
return ComputeMaxBits(GetProofOfStakeLimit(0, nBlockTime), nBase, nTime);
}
// ppcoin: find last block index up to pindex
const CBlockIndex* GetLastBlockIndex(const CBlockIndex* pindex, bool fProofOfStake)
{
while (pindex && pindex->pprev && (pindex->IsProofOfStake() != fProofOfStake))
pindex = pindex->pprev;
return pindex;
}
unsigned int GetNextTargetRequired(const CBlockIndex* pindexLast, bool fProofOfStake)
{
CBigNum bnTargetLimit = !fProofOfStake ? bnProofOfWorkLimit : GetProofOfStakeLimit(pindexLast->nHeight, pindexLast->nTime);
if (pindexLast == NULL)
return bnTargetLimit.GetCompact(); // genesis block
const CBlockIndex* pindexPrev = GetLastBlockIndex(pindexLast, fProofOfStake);
if (pindexPrev->pprev == NULL)
return bnTargetLimit.GetCompact(); // first block
const CBlockIndex* pindexPrevPrev = GetLastBlockIndex(pindexPrev->pprev, fProofOfStake);
if (pindexPrevPrev->pprev == NULL)
return bnTargetLimit.GetCompact(); // second block
int64_t nActualSpacing = pindexPrev->GetBlockTime() - pindexPrevPrev->GetBlockTime();
// ppcoin: target change every block
// ppcoin: retarget with exponential moving toward target spacing
CBigNum bnNew;
bnNew.SetCompact(pindexPrev->nBits);
int64_t nTargetSpacing = fProofOfStake? nStakeTargetSpacing : min(GetTargetSpacingWorkMax(pindexLast->nHeight, pindexLast->nTime), (int64_t) nStakeTargetSpacing * (1 + pindexLast->nHeight - pindexPrev->nHeight));
int64_t nInterval = nTargetTimespan / nTargetSpacing;
bnNew *= ((nInterval - 1) * nTargetSpacing + nActualSpacing + nActualSpacing);
bnNew /= ((nInterval + 1) * nTargetSpacing);
if (bnNew > bnTargetLimit)
bnNew = bnTargetLimit;
return bnNew.GetCompact();
}
bool CheckProofOfWork(uint256 hash, unsigned int nBits)
{
CBigNum bnTarget;
bnTarget.SetCompact(nBits);
// Check range
if (bnTarget <= 0 || bnTarget > bnProofOfWorkLimit)
return error("CheckProofOfWork() : nBits below minimum work");
// Check proof of work matches claimed amount
if (hash > bnTarget.getuint256())
return error("CheckProofOfWork() : hash doesn't match nBits");
return true;
}
// Return maximum amount of blocks that other nodes claim to have
int GetNumBlocksOfPeers()
{
return std::max(cPeerBlockCounts.median(), Checkpoints::GetTotalBlocksEstimate());
}
bool IsInitialBlockDownload()
{
if (pindexBest == NULL || nBestHeight < Checkpoints::GetTotalBlocksEstimate())
return true;
static int64_t nLastUpdate;
static CBlockIndex* pindexLastBest;
int64_t nCurrentTime = GetTime();
if (pindexBest != pindexLastBest)
{
pindexLastBest = pindexBest;
nLastUpdate = nCurrentTime;
}
return (nCurrentTime - nLastUpdate < 10 &&
pindexBest->GetBlockTime() < nCurrentTime - 24 * 60 * 60);
}
void static InvalidChainFound(CBlockIndex* pindexNew)
{
if (pindexNew->nChainTrust > nBestInvalidTrust)
{
nBestInvalidTrust = pindexNew->nChainTrust;
CTxDB().WriteBestInvalidTrust(CBigNum(nBestInvalidTrust));
uiInterface.NotifyBlocksChanged();
}
uint256 nBestInvalidBlockTrust = pindexNew->nChainTrust - pindexNew->pprev->nChainTrust;
uint256 nBestBlockTrust = pindexBest->nHeight != 0 ? (pindexBest->nChainTrust - pindexBest->pprev->nChainTrust) : pindexBest->nChainTrust;
printf("InvalidChainFound: invalid block=%s height=%d trust=%s blocktrust=%" PRId64 " date=%s\n",
pindexNew->GetBlockHash().ToString().substr(0,20).c_str(), pindexNew->nHeight,
CBigNum(pindexNew->nChainTrust).ToString().c_str(), nBestInvalidBlockTrust.Get64(),
DateTimeStrFormat("%x %H:%M:%S", pindexNew->GetBlockTime()).c_str());
printf("InvalidChainFound: current best=%s height=%d trust=%s blocktrust=%" PRId64 " date=%s\n",
hashBestChain.ToString().substr(0,20).c_str(), nBestHeight,
CBigNum(pindexBest->nChainTrust).ToString().c_str(),
nBestBlockTrust.Get64(),
DateTimeStrFormat("%x %H:%M:%S", pindexBest->GetBlockTime()).c_str());
}
void CBlock::UpdateTime(const CBlockIndex* pindexPrev)
{
nTime = max(GetBlockTime(), GetAdjustedTime());
}
bool CTransaction::DisconnectInputs(CTxDB& txdb)
{
// Relinquish previous transactions' spent pointers
if (!IsCoinBase())
{
BOOST_FOREACH(const CTxIn& txin, vin)
{
COutPoint prevout = txin.prevout;
// Get prev txindex from disk
CTxIndex txindex;
if (!txdb.ReadTxIndex(prevout.hash, txindex))
return error("DisconnectInputs() : ReadTxIndex failed");
if (prevout.n >= txindex.vSpent.size())
return error("DisconnectInputs() : prevout.n out of range");
// Mark outpoint as not spent
txindex.vSpent[prevout.n].SetNull();
// Write back
if (!txdb.UpdateTxIndex(prevout.hash, txindex))
return error("DisconnectInputs() : UpdateTxIndex failed");
}
}
// Remove transaction from index
// This can fail if a duplicate of this transaction was in a chain that got
// reorganized away. This is only possible if this transaction was completely
// spent, so erasing it would be a no-op anyway.
txdb.EraseTxIndex(*this);
return true;
}
bool CTransaction::FetchInputs(CTxDB& txdb, const map<uint256, CTxIndex>& mapTestPool,
bool fBlock, bool fMiner, MapPrevTx& inputsRet, bool& fInvalid)
{
// FetchInputs can return false either because we just haven't seen some inputs
// (in which case the transaction should be stored as an orphan)
// or because the transaction is malformed (in which case the transaction should
// be dropped). If tx is definitely invalid, fInvalid will be set to true.
fInvalid = false;
if (IsCoinBase())
return true; // Coinbase transactions have no inputs to fetch.
for (unsigned int i = 0; i < vin.size(); i++)
{
COutPoint prevout = vin[i].prevout;
if (inputsRet.count(prevout.hash))
continue; // Got it already
// Read txindex
CTxIndex& txindex = inputsRet[prevout.hash].first;
bool fFound = true;
if ((fBlock || fMiner) && mapTestPool.count(prevout.hash))
{
// Get txindex from current proposed changes
txindex = mapTestPool.find(prevout.hash)->second;
}
else
{
// Read txindex from txdb
fFound = txdb.ReadTxIndex(prevout.hash, txindex);
}
if (!fFound && (fBlock || fMiner))
return fMiner ? false : error("FetchInputs() : %s prev tx %s index entry not found", GetHash().ToString().substr(0,10).c_str(), prevout.hash.ToString().substr(0,10).c_str());
// Read txPrev
CTransaction& txPrev = inputsRet[prevout.hash].second;
if (!fFound || txindex.pos == CDiskTxPos(1,1,1))
{
// Get prev tx from single transactions in memory
{
LOCK(mempool.cs);
if (!mempool.exists(prevout.hash))
return error("FetchInputs() : %s mempool Tx prev not found %s", GetHash().ToString().substr(0,10).c_str(), prevout.hash.ToString().substr(0,10).c_str());
txPrev = mempool.lookup(prevout.hash);
}
if (!fFound)
txindex.vSpent.resize(txPrev.vout.size());
}
else
{
// Get prev tx from disk
if (!txPrev.ReadFromDisk(txindex.pos))
return error("FetchInputs() : %s ReadFromDisk prev tx %s failed", GetHash().ToString().substr(0,10).c_str(), prevout.hash.ToString().substr(0,10).c_str());
}
}
// Make sure all prevout.n indexes are valid:
for (unsigned int i = 0; i < vin.size(); i++)
{
const COutPoint prevout = vin[i].prevout;
assert(inputsRet.count(prevout.hash) != 0);
const CTxIndex& txindex = inputsRet[prevout.hash].first;
const CTransaction& txPrev = inputsRet[prevout.hash].second;
if (prevout.n >= txPrev.vout.size() || prevout.n >= txindex.vSpent.size())
{
// Revisit this if/when transaction replacement is implemented and allows
// adding inputs:
fInvalid = true;
return DoS(100, error("FetchInputs() : %s prevout.n out of range %d %" PRIszu " %" PRIszu " prev tx %s\n%s", GetHash().ToString().substr(0,10).c_str(), prevout.n, txPrev.vout.size(), txindex.vSpent.size(), prevout.hash.ToString().substr(0,10).c_str(), txPrev.ToString().c_str()));
}
}
return true;
}
const CTxOut& CTransaction::GetOutputFor(const CTxIn& input, const MapPrevTx& inputs) const
{
MapPrevTx::const_iterator mi = inputs.find(input.prevout.hash);
if (mi == inputs.end())
throw std::runtime_error("CTransaction::GetOutputFor() : prevout.hash not found");
const CTransaction& txPrev = (mi->second).second;
if (input.prevout.n >= txPrev.vout.size())
throw std::runtime_error("CTransaction::GetOutputFor() : prevout.n out of range");
return txPrev.vout[input.prevout.n];
}
int64_t CTransaction::GetValueIn(const MapPrevTx& inputs) const
{
if (IsCoinBase())
return 0;
int64_t nResult = 0;
for (unsigned int i = 0; i < vin.size(); i++)
{
nResult += GetOutputFor(vin[i], inputs).nValue;
}
return nResult;
}
unsigned int CTransaction::GetP2SHSigOpCount(const MapPrevTx& inputs) const
{
if (IsCoinBase())
return 0;
unsigned int nSigOps = 0;
for (unsigned int i = 0; i < vin.size(); i++)
{
const CTxOut& prevout = GetOutputFor(vin[i], inputs);
if (prevout.scriptPubKey.IsPayToScriptHash())
nSigOps += prevout.scriptPubKey.GetSigOpCount(vin[i].scriptSig);
}
return nSigOps;
}
bool CScriptCheck::operator()() const {
const CScript &scriptSig = ptxTo->vin[nIn].scriptSig;
if (!VerifyScript(scriptSig, scriptPubKey, *ptxTo, nIn, nFlags, nHashType))
return error("CScriptCheck() : %s VerifySignature failed", ptxTo->GetHash().ToString().substr(0,10).c_str());
return true;
}
bool VerifySignature(const CTransaction& txFrom, const CTransaction& txTo, unsigned int nIn, unsigned int flags, int nHashType)
{
return CScriptCheck(txFrom, txTo, nIn, flags, nHashType)();
}
bool CTransaction::ConnectInputs(CTxDB& txdb, MapPrevTx inputs, map<uint256, CTxIndex>& mapTestPool, const CDiskTxPos& posThisTx,
const CBlockIndex* pindexBlock, bool fBlock, bool fMiner, bool fScriptChecks, unsigned int flags, std::vector<CScriptCheck> *pvChecks)
{
// Take over previous transactions' spent pointers
// fBlock is true when this is called from AcceptBlock when a new best-block is added to the blockchain
// fMiner is true when called from the internal bitcoin miner
// ... both are false when called from CTransaction::AcceptToMemoryPool
if (!IsCoinBase())
{
int64_t nValueIn = 0;
int64_t nFees = 0;
for (unsigned int i = 0; i < vin.size(); i++)
{
COutPoint prevout = vin[i].prevout;
assert(inputs.count(prevout.hash) > 0);
CTxIndex& txindex = inputs[prevout.hash].first;
CTransaction& txPrev = inputs[prevout.hash].second;
if (prevout.n >= txPrev.vout.size() || prevout.n >= txindex.vSpent.size())
return DoS(100, error("ConnectInputs() : %s prevout.n out of range %d %" PRIszu " %" PRIszu " prev tx %s\n%s", GetHash().ToString().substr(0,10).c_str(), prevout.n, txPrev.vout.size(), txindex.vSpent.size(), prevout.hash.ToString().substr(0,10).c_str(), txPrev.ToString().c_str()));
// If prev is coinbase or coinstake, check that it's matured
if (txPrev.IsCoinBase() || txPrev.IsCoinStake())
for (const CBlockIndex* pindex = pindexBlock; pindex && pindexBlock->nHeight - pindex->nHeight < nCoinbaseMaturity; pindex = pindex->pprev)
if (pindex->nBlockPos == txindex.pos.nBlockPos && pindex->nFile == txindex.pos.nFile)
return error("ConnectInputs() : tried to spend %s at depth %d", txPrev.IsCoinBase() ? "coinbase" : "coinstake", pindexBlock->nHeight - pindex->nHeight);
// ppcoin: check transaction timestamp
if (txPrev.nTime > nTime)
return DoS(100, error("ConnectInputs() : transaction timestamp earlier than input transaction"));
// Check for negative or overflow input values
nValueIn += txPrev.vout[prevout.n].nValue;
if (!MoneyRange(txPrev.vout[prevout.n].nValue) || !MoneyRange(nValueIn))
return DoS(100, error("ConnectInputs() : txin values out of range"));
}
if (pvChecks)
pvChecks->reserve(vin.size());
// The first loop above does all the inexpensive checks.
// Only if ALL inputs pass do we perform expensive ECDSA signature checks.
// Helps prevent CPU exhaustion attacks.
for (unsigned int i = 0; i < vin.size(); i++)
{
COutPoint prevout = vin[i].prevout;
assert(inputs.count(prevout.hash) > 0);
CTxIndex& txindex = inputs[prevout.hash].first;
CTransaction& txPrev = inputs[prevout.hash].second;
// Check for conflicts (double-spend)
// This doesn't trigger the DoS code on purpose; if it did, it would make it easier
// for an attacker to attempt to split the network.
if (!txindex.vSpent[prevout.n].IsNull())
return fMiner ? false : error("ConnectInputs() : %s prev tx already used at %s", GetHash().ToString().substr(0,10).c_str(), txindex.vSpent[prevout.n].ToString().c_str());
// Skip ECDSA signature verification when connecting blocks (fBlock=true)
// before the last blockchain checkpoint. This is safe because block merkle hashes are
// still computed and checked, and any change will be caught at the next checkpoint.
if (fScriptChecks)
{
// Verify signature
CScriptCheck check(txPrev, *this, i, flags, 0);
if (pvChecks)
{
pvChecks->push_back(CScriptCheck());
check.swap(pvChecks->back());
}
else if (!check())
{
if (flags & STRICT_FLAGS)
{
// Don't trigger DoS code in case of STRICT_FLAGS caused failure.
CScriptCheck check(txPrev, *this, i, flags & ~STRICT_FLAGS, 0);
if (check())
return error("ConnectInputs() : %s strict VerifySignature failed", GetHash().ToString().substr(0,10).c_str());
}
return DoS(100,error("ConnectInputs() : %s VerifySignature failed", GetHash().ToString().substr(0,10).c_str()));
}
}
// Mark outpoints as spent
txindex.vSpent[prevout.n] = posThisTx;
// Write back
if (fBlock || fMiner)
{
mapTestPool[prevout.hash] = txindex;
}
}
if (IsCoinStake())
{
// ppcoin: coin stake tx earns reward instead of paying fee
uint64_t nCoinAge;
if (!GetCoinAge(txdb, nCoinAge))
return error("ConnectInputs() : %s unable to get coin age for coinstake", GetHash().ToString().substr(0,10).c_str());
unsigned int nTxSize = (nTime > VALIDATION_SWITCH_TIME || fTestNet) ? GetSerializeSize(SER_NETWORK, PROTOCOL_VERSION) : 0;
int64_t nReward = GetValueOut() - nValueIn;
int64_t nCalculatedReward = GetProofOfStakeReward(nCoinAge, pindexBlock->nBits, nTime) - GetMinFee(1, false, GMF_BLOCK, nTxSize) + CENT;
if (nReward > nCalculatedReward)
return DoS(100, error("ConnectInputs() : coinstake pays too much(actual=%" PRId64 " vs calculated=%" PRId64 ")", nReward, nCalculatedReward));
}
else
{
if (nValueIn < GetValueOut())
return DoS(100, error("ConnectInputs() : %s value in < value out", GetHash().ToString().substr(0,10).c_str()));
// Tally transaction fees
int64_t nTxFee = nValueIn - GetValueOut();
if (nTxFee < 0)
return DoS(100, error("ConnectInputs() : %s nTxFee < 0", GetHash().ToString().substr(0,10).c_str()));
nFees += nTxFee;
if (!MoneyRange(nFees))
return DoS(100, error("ConnectInputs() : nFees out of range"));
}
}
return true;
}
bool CTransaction::ClientConnectInputs()
{
if (IsCoinBase())
return false;
// Take over previous transactions' spent pointers
{
LOCK(mempool.cs);
int64_t nValueIn = 0;
for (unsigned int i = 0; i < vin.size(); i++)
{
// Get prev tx from single transactions in memory
COutPoint prevout = vin[i].prevout;
if (!mempool.exists(prevout.hash))
return false;
CTransaction& txPrev = mempool.lookup(prevout.hash);
if (prevout.n >= txPrev.vout.size())
return false;
// Verify signature
if (!VerifySignature(txPrev, *this, i, SCRIPT_VERIFY_NOCACHE | SCRIPT_VERIFY_P2SH, 0))
return error("ClientConnectInputs() : VerifySignature failed");
///// this is redundant with the mempool.mapNextTx stuff,
///// not sure which I want to get rid of
///// this has to go away now that posNext is gone
// // Check for conflicts
// if (!txPrev.vout[prevout.n].posNext.IsNull())
// return error("ConnectInputs() : prev tx already used");
//
// // Flag outpoints as used
// txPrev.vout[prevout.n].posNext = posThisTx;
nValueIn += txPrev.vout[prevout.n].nValue;
if (!MoneyRange(txPrev.vout[prevout.n].nValue) || !MoneyRange(nValueIn))
return error("ClientConnectInputs() : txin values out of range");
}
if (GetValueOut() > nValueIn)
return false;
}
return true;
}
bool CBlock::DisconnectBlock(CTxDB& txdb, CBlockIndex* pindex)
{
// Disconnect in reverse order
for (int i = vtx.size()-1; i >= 0; i--)
if (!vtx[i].DisconnectInputs(txdb))
return false;
// Update block index on disk without changing it in memory.
// The memory index structure will be changed after the db commits.
if (pindex->pprev)
{
CDiskBlockIndex blockindexPrev(pindex->pprev);
blockindexPrev.hashNext = 0;
if (!txdb.WriteBlockIndex(blockindexPrev))
return error("DisconnectBlock() : WriteBlockIndex failed");
}
// ppcoin: clean up wallet after disconnecting coinstake
BOOST_FOREACH(CTransaction& tx, vtx)
SyncWithWallets(tx, this, false, false);
return true;
}
static CCheckQueue<CScriptCheck> scriptcheckqueue(128);
void ThreadScriptCheck(void*) {
vnThreadsRunning[THREAD_SCRIPTCHECK]++;
RenameThread("novacoin-scriptch");
scriptcheckqueue.Thread();
vnThreadsRunning[THREAD_SCRIPTCHECK]--;
}
void ThreadScriptCheckQuit() {
scriptcheckqueue.Quit();
}
bool CBlock::ConnectBlock(CTxDB& txdb, CBlockIndex* pindex, bool fJustCheck)
{
// Check it again in case a previous version let a bad block in, but skip BlockSig checking
if (!CheckBlock(!fJustCheck, !fJustCheck, false))
return false;
// Do not allow blocks that contain transactions which 'overwrite' older transactions,
// unless those are already completely spent.
// If such overwrites are allowed, coinbases and transactions depending upon those
// can be duplicated to remove the ability to spend the first instance -- even after
// being sent to another address.
// See BIP30 and http://r6.ca/blog/20120206T005236Z.html for more information.
// This logic is not necessary for memory pool transactions, as AcceptToMemoryPool
// already refuses previously-known transaction ids entirely.
// This rule was originally applied all blocks whose timestamp was after March 15, 2012, 0:00 UTC.
// Now that the whole chain is irreversibly beyond that time it is applied to all blocks except the
// two in the chain that violate it. This prevents exploiting the issue against nodes in their
// initial block download.
bool fEnforceBIP30 = true; // Always active in NovaCoin
bool fScriptChecks = pindex->nHeight >= Checkpoints::GetTotalBlocksEstimate();
//// issue here: it doesn't know the version
unsigned int nTxPos;
if (fJustCheck)
// FetchInputs treats CDiskTxPos(1,1,1) as a special "refer to memorypool" indicator
// Since we're just checking the block and not actually connecting it, it might not (and probably shouldn't) be on the disk to get the transaction from
nTxPos = 1;
else
nTxPos = pindex->nBlockPos + ::GetSerializeSize(CBlock(), SER_DISK, CLIENT_VERSION) - (2 * GetSizeOfCompactSize(0)) + GetSizeOfCompactSize(vtx.size());
map<uint256, CTxIndex> mapQueuedChanges;
CCheckQueueControl<CScriptCheck> control(fScriptChecks && nScriptCheckThreads ? &scriptcheckqueue : NULL);
int64_t nFees = 0;
int64_t nValueIn = 0;
int64_t nValueOut = 0;
unsigned int nSigOps = 0;
BOOST_FOREACH(CTransaction& tx, vtx)
{
uint256 hashTx = tx.GetHash();
if (fEnforceBIP30) {
CTxIndex txindexOld;
if (txdb.ReadTxIndex(hashTx, txindexOld)) {
BOOST_FOREACH(CDiskTxPos &pos, txindexOld.vSpent)
if (pos.IsNull())
return false;
}
}
nSigOps += tx.GetLegacySigOpCount();
if (nSigOps > MAX_BLOCK_SIGOPS)
return DoS(100, error("ConnectBlock() : too many sigops"));
CDiskTxPos posThisTx(pindex->nFile, pindex->nBlockPos, nTxPos);
if (!fJustCheck)
nTxPos += ::GetSerializeSize(tx, SER_DISK, CLIENT_VERSION);
MapPrevTx mapInputs;
if (tx.IsCoinBase())
nValueOut += tx.GetValueOut();
else
{
bool fInvalid;
if (!tx.FetchInputs(txdb, mapQueuedChanges, true, false, mapInputs, fInvalid))
return false;
// Add in sigops done by pay-to-script-hash inputs;
// this is to prevent a "rogue miner" from creating
// an incredibly-expensive-to-validate block.
nSigOps += tx.GetP2SHSigOpCount(mapInputs);
if (nSigOps > MAX_BLOCK_SIGOPS)
return DoS(100, error("ConnectBlock() : too many sigops"));
int64_t nTxValueIn = tx.GetValueIn(mapInputs);
int64_t nTxValueOut = tx.GetValueOut();
nValueIn += nTxValueIn;
nValueOut += nTxValueOut;
if (!tx.IsCoinStake())
nFees += nTxValueIn - nTxValueOut;
std::vector<CScriptCheck> vChecks;
if (!tx.ConnectInputs(txdb, mapInputs, mapQueuedChanges, posThisTx, pindex, true, false, fScriptChecks, SCRIPT_VERIFY_NOCACHE | SCRIPT_VERIFY_P2SH, nScriptCheckThreads ? &vChecks : NULL))
return false;
control.Add(vChecks);
}
mapQueuedChanges[hashTx] = CTxIndex(posThisTx, tx.vout.size());
}
if (!control.Wait())
return DoS(100, false);
if (IsProofOfWork())
{
int64_t nBlockReward = GetProofOfWorkReward(nBits, nFees);
// Check coinbase reward
if (vtx[0].GetValueOut() > nBlockReward)
return error("CheckBlock() : coinbase reward exceeded (actual=%" PRId64 " vs calculated=%" PRId64 ")",
vtx[0].GetValueOut(),
nBlockReward);
}
// track money supply and mint amount info
pindex->nMint = nValueOut - nValueIn + nFees;
pindex->nMoneySupply = (pindex->pprev? pindex->pprev->nMoneySupply : 0) + nValueOut - nValueIn;
if (!txdb.WriteBlockIndex(CDiskBlockIndex(pindex)))
return error("Connect() : WriteBlockIndex for pindex failed");
// fees are not collected by proof-of-stake miners
// fees are destroyed to compensate the entire network
if (fDebug && IsProofOfStake() && GetBoolArg("-printcreation"))
printf("ConnectBlock() : destroy=%s nFees=%" PRId64 "\n", FormatMoney(nFees).c_str(), nFees);
if (fJustCheck)
return true;
// Write queued txindex changes
for (map<uint256, CTxIndex>::iterator mi = mapQueuedChanges.begin(); mi != mapQueuedChanges.end(); ++mi)
{
if (!txdb.UpdateTxIndex((*mi).first, (*mi).second))
return error("ConnectBlock() : UpdateTxIndex failed");
}
// Update block index on disk without changing it in memory.
// The memory index structure will be changed after the db commits.
if (pindex->pprev)
{
CDiskBlockIndex blockindexPrev(pindex->pprev);
blockindexPrev.hashNext = pindex->GetBlockHash();
if (!txdb.WriteBlockIndex(blockindexPrev))
return error("ConnectBlock() : WriteBlockIndex failed");
}
// Watch for transactions paying to me
BOOST_FOREACH(CTransaction& tx, vtx)
SyncWithWallets(tx, this, true);
return true;
}
bool static Reorganize(CTxDB& txdb, CBlockIndex* pindexNew)
{
printf("REORGANIZE\n");
// Find the fork
CBlockIndex* pfork = pindexBest;
CBlockIndex* plonger = pindexNew;
while (pfork != plonger)
{
while (plonger->nHeight > pfork->nHeight)
if (!(plonger = plonger->pprev))
return error("Reorganize() : plonger->pprev is null");
if (pfork == plonger)
break;
if (!(pfork = pfork->pprev))
return error("Reorganize() : pfork->pprev is null");
}
// List of what to disconnect
vector<CBlockIndex*> vDisconnect;
for (CBlockIndex* pindex = pindexBest; pindex != pfork; pindex = pindex->pprev)
vDisconnect.push_back(pindex);
// List of what to connect
vector<CBlockIndex*> vConnect;
for (CBlockIndex* pindex = pindexNew; pindex != pfork; pindex = pindex->pprev)
vConnect.push_back(pindex);
reverse(vConnect.begin(), vConnect.end());
printf("REORGANIZE: Disconnect %" PRIszu " blocks; %s..%s\n", vDisconnect.size(), pfork->GetBlockHash().ToString().substr(0,20).c_str(), pindexBest->GetBlockHash().ToString().substr(0,20).c_str());
printf("REORGANIZE: Connect %" PRIszu " blocks; %s..%s\n", vConnect.size(), pfork->GetBlockHash().ToString().substr(0,20).c_str(), pindexNew->GetBlockHash().ToString().substr(0,20).c_str());
// Disconnect shorter branch
vector<CTransaction> vResurrect;
BOOST_FOREACH(CBlockIndex* pindex, vDisconnect)
{
CBlock block;
if (!block.ReadFromDisk(pindex))
return error("Reorganize() : ReadFromDisk for disconnect failed");
if (!block.DisconnectBlock(txdb, pindex))
return error("Reorganize() : DisconnectBlock %s failed", pindex->GetBlockHash().ToString().substr(0,20).c_str());
// Queue memory transactions to resurrect
BOOST_FOREACH(const CTransaction& tx, block.vtx)
if (!(tx.IsCoinBase() || tx.IsCoinStake()))
vResurrect.push_back(tx);
}
// Connect longer branch
vector<CTransaction> vDelete;
for (unsigned int i = 0; i < vConnect.size(); i++)
{
CBlockIndex* pindex = vConnect[i];
CBlock block;
if (!block.ReadFromDisk(pindex))
return error("Reorganize() : ReadFromDisk for connect failed");
if (!block.ConnectBlock(txdb, pindex))
{
// Invalid block
return error("Reorganize() : ConnectBlock %s failed", pindex->GetBlockHash().ToString().substr(0,20).c_str());
}
// Queue memory transactions to delete
BOOST_FOREACH(const CTransaction& tx, block.vtx)
vDelete.push_back(tx);
}
if (!txdb.WriteHashBestChain(pindexNew->GetBlockHash()))
return error("Reorganize() : WriteHashBestChain failed");
// Make sure it's successfully written to disk before changing memory structure
if (!txdb.TxnCommit())
return error("Reorganize() : TxnCommit failed");
// Disconnect shorter branch
BOOST_FOREACH(CBlockIndex* pindex, vDisconnect)
if (pindex->pprev)
pindex->pprev->pnext = NULL;
// Connect longer branch
BOOST_FOREACH(CBlockIndex* pindex, vConnect)
if (pindex->pprev)
pindex->pprev->pnext = pindex;
// Resurrect memory transactions that were in the disconnected branch
BOOST_FOREACH(CTransaction& tx, vResurrect)
tx.AcceptToMemoryPool(txdb, false);
// Delete redundant memory transactions that are in the connected branch
BOOST_FOREACH(CTransaction& tx, vDelete)
mempool.remove(tx);
printf("REORGANIZE: done\n");
return true;
}
// Called from inside SetBestChain: attaches a block to the new best chain being built
bool CBlock::SetBestChainInner(CTxDB& txdb, CBlockIndex *pindexNew)
{
uint256 hash = GetHash();
// Adding to current best branch
if (!ConnectBlock(txdb, pindexNew) || !txdb.WriteHashBestChain(hash))
{
txdb.TxnAbort();
InvalidChainFound(pindexNew);
return false;
}
if (!txdb.TxnCommit())
return error("SetBestChain() : TxnCommit failed");
// Add to current best branch
pindexNew->pprev->pnext = pindexNew;
// Delete redundant memory transactions
BOOST_FOREACH(CTransaction& tx, vtx)
mempool.remove(tx);
return true;
}
bool CBlock::SetBestChain(CTxDB& txdb, CBlockIndex* pindexNew)
{
uint256 hash = GetHash();
if (!txdb.TxnBegin())
return error("SetBestChain() : TxnBegin failed");
if (pindexGenesisBlock == NULL && hash == (!fTestNet ? hashGenesisBlock : hashGenesisBlockTestNet))
{
txdb.WriteHashBestChain(hash);
if (!txdb.TxnCommit())
return error("SetBestChain() : TxnCommit failed");
pindexGenesisBlock = pindexNew;
}
else if (hashPrevBlock == hashBestChain)
{
if (!SetBestChainInner(txdb, pindexNew))
return error("SetBestChain() : SetBestChainInner failed");
}
else
{
// the first block in the new chain that will cause it to become the new best chain
CBlockIndex *pindexIntermediate = pindexNew;
// list of blocks that need to be connected afterwards
std::vector<CBlockIndex*> vpindexSecondary;
// Reorganize is costly in terms of db load, as it works in a single db transaction.
// Try to limit how much needs to be done inside
while (pindexIntermediate->pprev && pindexIntermediate->pprev->nChainTrust > pindexBest->nChainTrust)
{
vpindexSecondary.push_back(pindexIntermediate);
pindexIntermediate = pindexIntermediate->pprev;
}
if (!vpindexSecondary.empty())
printf("Postponing %" PRIszu " reconnects\n", vpindexSecondary.size());
// Switch to new best branch
if (!Reorganize(txdb, pindexIntermediate))
{
txdb.TxnAbort();
InvalidChainFound(pindexNew);
return error("SetBestChain() : Reorganize failed");
}
// Connect further blocks
BOOST_REVERSE_FOREACH(CBlockIndex *pindex, vpindexSecondary)
{
CBlock block;
if (!block.ReadFromDisk(pindex))
{
printf("SetBestChain() : ReadFromDisk failed\n");
break;
}
if (!txdb.TxnBegin()) {
printf("SetBestChain() : TxnBegin 2 failed\n");
break;
}
// errors now are not fatal, we still did a reorganisation to a new chain in a valid way
if (!block.SetBestChainInner(txdb, pindex))
break;
}
}
// Update best block in wallet (so we can detect restored wallets)
bool fIsInitialDownload = IsInitialBlockDownload();
if (!fIsInitialDownload)
{
const CBlockLocator locator(pindexNew);
::SetBestChain(locator);
}
// New best block
hashBestChain = hash;
pindexBest = pindexNew;
pblockindexFBBHLast = NULL;
nBestHeight = pindexBest->nHeight;
nBestChainTrust = pindexNew->nChainTrust;
nTimeBestReceived = GetTime();
nTransactionsUpdated++;
uint256 nBestBlockTrust = pindexBest->nHeight != 0 ? (pindexBest->nChainTrust - pindexBest->pprev->nChainTrust) : pindexBest->nChainTrust;
printf("SetBestChain: new best=%s height=%d trust=%s blocktrust=%" PRId64 " date=%s\n",
hashBestChain.ToString().substr(0,20).c_str(), nBestHeight,
CBigNum(nBestChainTrust).ToString().c_str(),
nBestBlockTrust.Get64(),
DateTimeStrFormat("%x %H:%M:%S", pindexBest->GetBlockTime()).c_str());
// Check the version of the last 100 blocks to see if we need to upgrade:
if (!fIsInitialDownload)
{
int nUpgraded = 0;
const CBlockIndex* pindex = pindexBest;
for (int i = 0; i < 100 && pindex != NULL; i++)
{
if (pindex->nVersion > CBlock::CURRENT_VERSION)
++nUpgraded;
pindex = pindex->pprev;
}
if (nUpgraded > 0)
printf("SetBestChain: %d of last 100 blocks above version %d\n", nUpgraded, CBlock::CURRENT_VERSION);
if (nUpgraded > 100/2)
// strMiscWarning is read by GetWarnings(), called by Qt and the JSON-RPC code to warn the user:
strMiscWarning = _("Warning: This version is obsolete, upgrade required!");
}
std::string strCmd = GetArg("-blocknotify", "");
if (!fIsInitialDownload && !strCmd.empty())
{
boost::replace_all(strCmd, "%s", hashBestChain.GetHex());
boost::thread t(runCommand, strCmd); // thread runs free
}
return true;
}
// ppcoin: total coin age spent in transaction, in the unit of coin-days.
// Only those coins meeting minimum age requirement counts. As those
// transactions not in main chain are not currently indexed so we
// might not find out about their coin age. Older transactions are
// guaranteed to be in main chain by sync-checkpoint. This rule is
// introduced to help nodes establish a consistent view of the coin
// age (trust score) of competing branches.
bool CTransaction::GetCoinAge(CTxDB& txdb, uint64_t& nCoinAge) const
{
CBigNum bnCentSecond = 0; // coin age in the unit of cent-seconds
nCoinAge = 0;
if (IsCoinBase())
return true;
BOOST_FOREACH(const CTxIn& txin, vin)
{
// First try finding the previous transaction in database
CTransaction txPrev;
CTxIndex txindex;
if (!txPrev.ReadFromDisk(txdb, txin.prevout, txindex))
continue; // previous transaction not in main chain
if (nTime < txPrev.nTime)
return false; // Transaction timestamp violation
// Read block header
CBlock block;
if (!block.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos, false))
return false; // unable to read block of previous transaction
if (block.GetBlockTime() + nStakeMinAge > nTime)
continue; // only count coins meeting min age requirement
int64_t nValueIn = txPrev.vout[txin.prevout.n].nValue;
bnCentSecond += CBigNum(nValueIn) * (nTime-txPrev.nTime) / CENT;
if (fDebug && GetBoolArg("-printcoinage"))
printf("coin age nValueIn=%" PRId64 " nTimeDiff=%d bnCentSecond=%s\n", nValueIn, nTime - txPrev.nTime, bnCentSecond.ToString().c_str());
}
CBigNum bnCoinDay = bnCentSecond * CENT / COIN / (24 * 60 * 60);
if (fDebug && GetBoolArg("-printcoinage"))
printf("coin age bnCoinDay=%s\n", bnCoinDay.ToString().c_str());
nCoinAge = bnCoinDay.getuint64();
return true;
}
// ppcoin: total coin age spent in block, in the unit of coin-days.
bool CBlock::GetCoinAge(uint64_t& nCoinAge) const
{
nCoinAge = 0;
CTxDB txdb("r");
BOOST_FOREACH(const CTransaction& tx, vtx)
{
uint64_t nTxCoinAge;
if (tx.GetCoinAge(txdb, nTxCoinAge))
nCoinAge += nTxCoinAge;
else
return false;
}
if (nCoinAge == 0) // block coin age minimum 1 coin-day
nCoinAge = 1;
if (fDebug && GetBoolArg("-printcoinage"))
printf("block coin age total nCoinDays=%" PRId64 "\n", nCoinAge);
return true;
}
bool CBlock::AddToBlockIndex(unsigned int nFile, unsigned int nBlockPos)
{
// Check for duplicate
uint256 hash = GetHash();
if (mapBlockIndex.count(hash))
return error("AddToBlockIndex() : %s already exists", hash.ToString().substr(0,20).c_str());
// Construct new block index object
CBlockIndex* pindexNew = new CBlockIndex(nFile, nBlockPos, *this);
if (!pindexNew)
return error("AddToBlockIndex() : new CBlockIndex failed");
pindexNew->phashBlock = &hash;
map<uint256, CBlockIndex*>::iterator miPrev = mapBlockIndex.find(hashPrevBlock);
if (miPrev != mapBlockIndex.end())
{
pindexNew->pprev = (*miPrev).second;
pindexNew->nHeight = pindexNew->pprev->nHeight + 1;
}
// ppcoin: compute chain trust score
pindexNew->nChainTrust = (pindexNew->pprev ? pindexNew->pprev->nChainTrust : 0) + pindexNew->GetBlockTrust();
// ppcoin: compute stake entropy bit for stake modifier
if (!pindexNew->SetStakeEntropyBit(GetStakeEntropyBit(pindexNew->nHeight)))
return error("AddToBlockIndex() : SetStakeEntropyBit() failed");
// ppcoin: record proof-of-stake hash value
if (pindexNew->IsProofOfStake())
{
if (!mapProofOfStake.count(hash))
return error("AddToBlockIndex() : hashProofOfStake not found in map");
pindexNew->hashProofOfStake = mapProofOfStake[hash];
}
// ppcoin: compute stake modifier
uint64_t nStakeModifier = 0;
bool fGeneratedStakeModifier = false;
if (!ComputeNextStakeModifier(pindexNew, nStakeModifier, fGeneratedStakeModifier))
return error("AddToBlockIndex() : ComputeNextStakeModifier() failed");
pindexNew->SetStakeModifier(nStakeModifier, fGeneratedStakeModifier);
pindexNew->nStakeModifierChecksum = GetStakeModifierChecksum(pindexNew);
if (!CheckStakeModifierCheckpoints(pindexNew->nHeight, pindexNew->nStakeModifierChecksum))
return error("AddToBlockIndex() : Rejected by stake modifier checkpoint height=%d, modifier=0x%016" PRIx64, pindexNew->nHeight, nStakeModifier);
// Add to mapBlockIndex
map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first;
if (pindexNew->IsProofOfStake())
setStakeSeen.insert(make_pair(pindexNew->prevoutStake, pindexNew->nStakeTime));
pindexNew->phashBlock = &((*mi).first);
// Write to disk block index
CTxDB txdb;
if (!txdb.TxnBegin())
return false;
txdb.WriteBlockIndex(CDiskBlockIndex(pindexNew));
if (!txdb.TxnCommit())
return false;
// New best
if (pindexNew->nChainTrust > nBestChainTrust)
if (!SetBestChain(txdb, pindexNew))
return false;
if (pindexNew == pindexBest)
{
// Notify UI to display prev block's coinbase if it was ours
static uint256 hashPrevBestCoinBase;
UpdatedTransaction(hashPrevBestCoinBase);
hashPrevBestCoinBase = vtx[0].GetHash();
}
static int8_t counter = 0;
if( (++counter & 0x0F) == 0 || !IsInitialBlockDownload()) // repaint every 16 blocks if not in initial block download
uiInterface.NotifyBlocksChanged();
return true;
}
bool CBlock::CheckBlock(bool fCheckPOW, bool fCheckMerkleRoot, bool fCheckSig) const
{
// These are checks that are independent of context
// that can be verified before saving an orphan block.
set<uint256> uniqueTx; // tx hashes
unsigned int nSigOps = 0; // total sigops
// Size limits
if (vtx.empty() || vtx.size() > MAX_BLOCK_SIZE || ::GetSerializeSize(*this, SER_NETWORK, PROTOCOL_VERSION) > MAX_BLOCK_SIZE)
return DoS(100, error("CheckBlock() : size limits failed"));
bool fProofOfStake = IsProofOfStake();
// First transaction must be coinbase, the rest must not be
if (!vtx[0].IsCoinBase())
return DoS(100, error("CheckBlock() : first tx is not coinbase"));
if (!vtx[0].CheckTransaction())
return DoS(vtx[0].nDoS, error("CheckBlock() : CheckTransaction failed on coinbase"));
uniqueTx.insert(vtx[0].GetHash());
nSigOps += vtx[0].GetLegacySigOpCount();
if (fProofOfStake)
{
// Proof-of-STake related checkings. Note that we know here that 1st transactions is coinstake. We don't need
// check the type of 1st transaction because it's performed earlier by IsProofOfStake()
// nNonce must be zero for proof-of-stake blocks
if (nNonce != 0)
return DoS(100, error("CheckBlock() : non-zero nonce in proof-of-stake block"));
// Coinbase output should be empty if proof-of-stake block
if (vtx[0].vout.size() != 1 || !vtx[0].vout[0].IsEmpty())
return DoS(100, error("CheckBlock() : coinbase output not empty for proof-of-stake block"));
// Check coinstake timestamp
if (GetBlockTime() != (int64_t)vtx[1].nTime)
return DoS(50, error("CheckBlock() : coinstake timestamp violation nTimeBlock=%" PRId64 " nTimeTx=%u", GetBlockTime(), vtx[1].nTime));
// NovaCoin: check proof-of-stake block signature
if (fCheckSig && !CheckBlockSignature())
return DoS(100, error("CheckBlock() : bad proof-of-stake block signature"));
if (!vtx[1].CheckTransaction())
return DoS(vtx[1].nDoS, error("CheckBlock() : CheckTransaction failed on coinstake"));
uniqueTx.insert(vtx[1].GetHash());
nSigOps += vtx[1].GetLegacySigOpCount();
}
else
{
// Check proof of work matches claimed amount
if (fCheckPOW && !CheckProofOfWork(GetHash(), nBits))
return DoS(50, error("CheckBlock() : proof of work failed"));
// Check timestamp
if (GetBlockTime() > FutureDrift(GetAdjustedTime()))
return error("CheckBlock() : block timestamp too far in the future");
// Check coinbase timestamp
if (GetBlockTime() < PastDrift((int64_t)vtx[0].nTime))
return DoS(50, error("CheckBlock() : coinbase timestamp is too late"));
}
// Iterate all transactions starting from second for proof-of-stake block
// or first for proof-of-work block
for (unsigned int i = fProofOfStake ? 2 : 1; i < vtx.size(); i++)
{
const CTransaction& tx = vtx[i];
// Reject coinbase transactions at non-zero index
if (tx.IsCoinBase())
return DoS(100, error("CheckBlock() : coinbase at wrong index"));
// Reject coinstake transactions at index != 1
if (tx.IsCoinStake())
return DoS(100, error("CheckBlock() : coinstake at wrong index"));
// Check transaction timestamp
if (GetBlockTime() < (int64_t)tx.nTime)
return DoS(50, error("CheckBlock() : block timestamp earlier than transaction timestamp"));
// Check transaction consistency
if (!tx.CheckTransaction())
return DoS(tx.nDoS, error("CheckBlock() : CheckTransaction failed"));
// Add transaction hash into list of unique transaction IDs
uniqueTx.insert(tx.GetHash());
// Calculate sigops count
nSigOps += tx.GetLegacySigOpCount();
}
// Check for duplicate txids. This is caught by ConnectInputs(),
// but catching it earlier avoids a potential DoS attack:
if (uniqueTx.size() != vtx.size())
return DoS(100, error("CheckBlock() : duplicate transaction"));
// Reject block if validation would consume too much resources.
if (nSigOps > MAX_BLOCK_SIGOPS)
return DoS(100, error("CheckBlock() : out-of-bounds SigOpCount"));
// Check merkle root
if (fCheckMerkleRoot && hashMerkleRoot != BuildMerkleTree())
return DoS(100, error("CheckBlock() : hashMerkleRoot mismatch"));
return true;
}
bool CBlock::AcceptBlock()
{
// Check for duplicate
uint256 hash = GetHash();
if (mapBlockIndex.count(hash))
return error("AcceptBlock() : block already in mapBlockIndex");
// Get prev block index
map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashPrevBlock);
if (mi == mapBlockIndex.end())
return DoS(10, error("AcceptBlock() : prev block not found"));
CBlockIndex* pindexPrev = (*mi).second;
int nHeight = pindexPrev->nHeight+1;
// Check proof-of-work or proof-of-stake
if (nBits != GetNextTargetRequired(pindexPrev, IsProofOfStake()))
return DoS(100, error("AcceptBlock() : incorrect %s", IsProofOfWork() ? "proof-of-work" : "proof-of-stake"));
// Check timestamp against prev
if (GetBlockTime() <= pindexPrev->GetMedianTimePast() || FutureDrift(GetBlockTime()) < pindexPrev->GetBlockTime())
return error("AcceptBlock() : block's timestamp is too early");
// Check that all transactions are finalized
BOOST_FOREACH(const CTransaction& tx, vtx)
if (!tx.IsFinal(nHeight, GetBlockTime()))
return DoS(10, error("AcceptBlock() : contains a non-final transaction"));
// Check that the block chain matches the known block chain up to a checkpoint
if (!Checkpoints::CheckHardened(nHeight, hash))
return DoS(100, error("AcceptBlock() : rejected by hardened checkpoint lock-in at %d", nHeight));
bool cpSatisfies = Checkpoints::CheckSync(hash, pindexPrev);
// Check that the block satisfies synchronized checkpoint
if (CheckpointsMode == Checkpoints::STRICT && !cpSatisfies)
return error("AcceptBlock() : rejected by synchronized checkpoint");
if (CheckpointsMode == Checkpoints::ADVISORY && !cpSatisfies)
strMiscWarning = _("WARNING: syncronized checkpoint violation detected, but skipped!");
// Enforce rule that the coinbase starts with serialized block height
CScript expect = CScript() << nHeight;
if (vtx[0].vin[0].scriptSig.size() < expect.size() ||
!std::equal(expect.begin(), expect.end(), vtx[0].vin[0].scriptSig.begin()))
return DoS(100, error("AcceptBlock() : block height mismatch in coinbase"));
// Write block to history file
if (!CheckDiskSpace(::GetSerializeSize(*this, SER_DISK, CLIENT_VERSION)))
return error("AcceptBlock() : out of disk space");
unsigned int nFile = -1;
unsigned int nBlockPos = 0;
if (!WriteToDisk(nFile, nBlockPos))
return error("AcceptBlock() : WriteToDisk failed");
if (!AddToBlockIndex(nFile, nBlockPos))
return error("AcceptBlock() : AddToBlockIndex failed");
// Relay inventory, but don't relay old inventory during initial block download
int nBlockEstimate = Checkpoints::GetTotalBlocksEstimate();
if (hashBestChain == hash)
{
LOCK(cs_vNodes);
BOOST_FOREACH(CNode* pnode, vNodes)
if (nBestHeight > (pnode->nStartingHeight != -1 ? pnode->nStartingHeight - 2000 : nBlockEstimate))
pnode->PushInventory(CInv(MSG_BLOCK, hash));
}
// ppcoin: check pending sync-checkpoint
Checkpoints::AcceptPendingSyncCheckpoint();
return true;
}
uint256 CBlockIndex::GetBlockTrust() const
{
CBigNum bnTarget;
bnTarget.SetCompact(nBits);
if (bnTarget <= 0)
return 0;
/* Old protocol */
if (!fTestNet && GetBlockTime() < CHAINCHECKS_SWITCH_TIME)
return (IsProofOfStake()? ((CBigNum(1)<<256) / (bnTarget+1)).getuint256() : 1);
/* New protocol */
// Calculate work amount for block
uint256 nPoWTrust = (CBigNum(nPoWBase) / (bnTarget+1)).getuint256();
// Set nPowTrust to 1 if we are checking PoS block or PoW difficulty is too low
nPoWTrust = (IsProofOfStake() || nPoWTrust < 1) ? 1 : nPoWTrust;
// Return nPoWTrust for the first 12 blocks
if (pprev == NULL || pprev->nHeight < 12)
return nPoWTrust;
const CBlockIndex* currentIndex = pprev;
if(IsProofOfStake())
{
CBigNum bnNewTrust = (CBigNum(1)<<256) / (bnTarget+1);
// Return 1/3 of score if parent block is not the PoW block
if (!pprev->IsProofOfWork())
return (bnNewTrust / 3).getuint256();
int nPoWCount = 0;
// Check last 12 blocks type
while (pprev->nHeight - currentIndex->nHeight < 12)
{
if (currentIndex->IsProofOfWork())
nPoWCount++;
currentIndex = currentIndex->pprev;
}
// Return 1/3 of score if less than 3 PoW blocks found
if (nPoWCount < 3)
return (bnNewTrust / 3).getuint256();
return bnNewTrust.getuint256();
}
else
{
CBigNum bnLastBlockTrust = CBigNum(pprev->nChainTrust - pprev->pprev->nChainTrust);
// Return nPoWTrust + 2/3 of previous block score if two parent blocks are not PoS blocks
if (!(pprev->IsProofOfStake() && pprev->pprev->IsProofOfStake()))
return nPoWTrust + (2 * bnLastBlockTrust / 3).getuint256();
int nPoSCount = 0;
// Check last 12 blocks type
while (pprev->nHeight - currentIndex->nHeight < 12)
{
if (currentIndex->IsProofOfStake())
nPoSCount++;
currentIndex = currentIndex->pprev;
}
// Return nPoWTrust + 2/3 of previous block score if less than 7 PoS blocks found
if (nPoSCount < 7)
return nPoWTrust + (2 * bnLastBlockTrust / 3).getuint256();
bnTarget.SetCompact(pprev->nBits);
if (bnTarget <= 0)
return 0;
CBigNum bnNewTrust = (CBigNum(1)<<256) / (bnTarget+1);
// Return nPoWTrust + full trust score for previous block nBits
return nPoWTrust + bnNewTrust.getuint256();
}
}
bool CBlockIndex::IsSuperMajority(int minVersion, const CBlockIndex* pstart, unsigned int nRequired, unsigned int nToCheck)
{
unsigned int nFound = 0;
for (unsigned int i = 0; i < nToCheck && nFound < nRequired && pstart != NULL; i++)
{
if (pstart->nVersion >= minVersion)
++nFound;
pstart = pstart->pprev;
}
return (nFound >= nRequired);
}
bool ProcessBlock(CNode* pfrom, CBlock* pblock)
{
// Check for duplicate
uint256 hash = pblock->GetHash();
if (mapBlockIndex.count(hash))
return error("ProcessBlock() : already have block %d %s", mapBlockIndex[hash]->nHeight, hash.ToString().substr(0,20).c_str());
if (mapOrphanBlocks.count(hash))
return error("ProcessBlock() : already have block (orphan) %s", hash.ToString().substr(0,20).c_str());
// ppcoin: check proof-of-stake
// Limited duplicity on stake: prevents block flood attack
// Duplicate stake allowed only when there is orphan child block
if (pblock->IsProofOfStake() && setStakeSeen.count(pblock->GetProofOfStake()) && !mapOrphanBlocksByPrev.count(hash) && !Checkpoints::WantedByPendingSyncCheckpoint(hash))
return error("ProcessBlock() : duplicate proof-of-stake (%s, %d) for block %s", pblock->GetProofOfStake().first.ToString().c_str(), pblock->GetProofOfStake().second, hash.ToString().c_str());
// Preliminary checks
if (!pblock->CheckBlock(true, true, (pblock->nTime > Checkpoints::GetLastCheckpointTime())))
return error("ProcessBlock() : CheckBlock FAILED");
// ppcoin: verify hash target and signature of coinstake tx
if (pblock->IsProofOfStake())
{
uint256 hashProofOfStake = 0, targetProofOfStake = 0;
if (!CheckProofOfStake(pblock->vtx[1], pblock->nBits, hashProofOfStake, targetProofOfStake))
{
printf("WARNING: ProcessBlock(): check proof-of-stake failed for block %s\n", hash.ToString().c_str());
return false; // do not error here as we expect this during initial block download
}
if (!mapProofOfStake.count(hash)) // add to mapProofOfStake
mapProofOfStake.insert(make_pair(hash, hashProofOfStake));
}
CBlockIndex* pcheckpoint = Checkpoints::GetLastSyncCheckpoint();
if (pcheckpoint && pblock->hashPrevBlock != hashBestChain && !Checkpoints::WantedByPendingSyncCheckpoint(hash))
{
// Extra checks to prevent "fill up memory by spamming with bogus blocks"
int64_t deltaTime = pblock->GetBlockTime() - pcheckpoint->nTime;
CBigNum bnNewBlock;
bnNewBlock.SetCompact(pblock->nBits);
CBigNum bnRequired;
if (pblock->IsProofOfStake())
bnRequired.SetCompact(ComputeMinStake(GetLastBlockIndex(pcheckpoint, true)->nBits, deltaTime, pblock->nTime));
else
bnRequired.SetCompact(ComputeMinWork(GetLastBlockIndex(pcheckpoint, false)->nBits, deltaTime));
if (bnNewBlock > bnRequired)
{
if (pfrom)
pfrom->Misbehaving(100);
return error("ProcessBlock() : block with too little %s", pblock->IsProofOfStake()? "proof-of-stake" : "proof-of-work");
}
}
// ppcoin: ask for pending sync-checkpoint if any
if (!IsInitialBlockDownload())
Checkpoints::AskForPendingSyncCheckpoint(pfrom);
// If don't already have its previous block, shunt it off to holding area until we get it
if (!mapBlockIndex.count(pblock->hashPrevBlock))
{
printf("ProcessBlock: ORPHAN BLOCK, prev=%s\n", pblock->hashPrevBlock.ToString().substr(0,20).c_str());
CBlock* pblock2 = new CBlock(*pblock);
// ppcoin: check proof-of-stake
if (pblock2->IsProofOfStake())
{
// Limited duplicity on stake: prevents block flood attack
// Duplicate stake allowed only when there is orphan child block
if (setStakeSeenOrphan.count(pblock2->GetProofOfStake()) && !mapOrphanBlocksByPrev.count(hash) && !Checkpoints::WantedByPendingSyncCheckpoint(hash))
return error("ProcessBlock() : duplicate proof-of-stake (%s, %d) for orphan block %s", pblock2->GetProofOfStake().first.ToString().c_str(), pblock2->GetProofOfStake().second, hash.ToString().c_str());
else
setStakeSeenOrphan.insert(pblock2->GetProofOfStake());
}
mapOrphanBlocks.insert(make_pair(hash, pblock2));
mapOrphanBlocksByPrev.insert(make_pair(pblock2->hashPrevBlock, pblock2));
// Ask this guy to fill in what we're missing
if (pfrom)
{
pfrom->PushGetBlocks(pindexBest, GetOrphanRoot(pblock2));
// ppcoin: getblocks may not obtain the ancestor block rejected
// earlier by duplicate-stake check so we ask for it again directly
if (!IsInitialBlockDownload())
pfrom->AskFor(CInv(MSG_BLOCK, WantedByOrphan(pblock2)));
}
return true;
}
// Store to disk
if (!pblock->AcceptBlock())
return error("ProcessBlock() : AcceptBlock FAILED");
// Recursively process any orphan blocks that depended on this one
vector<uint256> vWorkQueue;
vWorkQueue.push_back(hash);
for (unsigned int i = 0; i < vWorkQueue.size(); i++)
{
uint256 hashPrev = vWorkQueue[i];
for (multimap<uint256, CBlock*>::iterator mi = mapOrphanBlocksByPrev.lower_bound(hashPrev);
mi != mapOrphanBlocksByPrev.upper_bound(hashPrev);
++mi)
{
CBlock* pblockOrphan = (*mi).second;
if (pblockOrphan->AcceptBlock())
vWorkQueue.push_back(pblockOrphan->GetHash());
mapOrphanBlocks.erase(pblockOrphan->GetHash());
setStakeSeenOrphan.erase(pblockOrphan->GetProofOfStake());
delete pblockOrphan;
}
mapOrphanBlocksByPrev.erase(hashPrev);
}
printf("ProcessBlock: ACCEPTED\n");
// ppcoin: if responsible for sync-checkpoint send it
if (pfrom && !CSyncCheckpoint::strMasterPrivKey.empty())
Checkpoints::SendSyncCheckpoint(Checkpoints::AutoSelectSyncCheckpoint());
return true;
}
// novacoin: attempt to generate suitable proof-of-stake
bool CBlock::SignBlock(CWallet& wallet)
{
// if we are trying to sign
// something except proof-of-stake block template
if (!vtx[0].vout[0].IsEmpty())
return false;
// if we are trying to sign
// a complete proof-of-stake block
if (IsProofOfStake())
return true;
static uint32_t nLastCoinStakeSearchTime = GetAdjustedTime(); // startup timestamp
CKey key;
CTransaction txCoinStake;
uint32_t nSearchTime = txCoinStake.nTime; // search to current time
if (nSearchTime > nLastCoinStakeSearchTime)
{
if (wallet.CreateCoinStake(wallet, nBits, nSearchTime-nLastCoinStakeSearchTime, txCoinStake, key))
{
if (txCoinStake.nTime >= max(pindexBest->GetMedianTimePast()+1, PastDrift(pindexBest->GetBlockTime())))
{
// make sure coinstake would meet timestamp protocol
// as it would be the same as the block timestamp
vtx[0].nTime = nTime = txCoinStake.nTime;
nTime = max(pindexBest->GetMedianTimePast()+1, GetMaxTransactionTime());
nTime = max(GetBlockTime(), PastDrift(pindexBest->GetBlockTime()));
// we have to make sure that we have no future timestamps in
// our transactions set
for (vector<CTransaction>::iterator it = vtx.begin(); it != vtx.end();)
if (it->nTime > nTime) { it = vtx.erase(it); } else { ++it; }
vtx.insert(vtx.begin() + 1, txCoinStake);
hashMerkleRoot = BuildMerkleTree();
// append a signature to our block
return key.Sign(GetHash(), vchBlockSig);
}
}
nLastCoinStakeSearchInterval = nSearchTime - nLastCoinStakeSearchTime;
nLastCoinStakeSearchTime = nSearchTime;
}
return false;
}
// ppcoin: check block signature
bool CBlock::CheckBlockSignature() const
{
if (IsProofOfWork())
return true;
vector<valtype> vSolutions;
txnouttype whichType;
const CTxOut& txout = vtx[1].vout[1];
if (!Solver(txout.scriptPubKey, whichType, vSolutions))
return false;
if (whichType == TX_PUBKEY)
{
valtype& vchPubKey = vSolutions[0];
CKey key;
if (!key.SetPubKey(vchPubKey))
return false;
if (vchBlockSig.empty())
return false;
return key.Verify(GetHash(), vchBlockSig);
}
return false;
}
bool CheckDiskSpace(uint64_t nAdditionalBytes)
{
uint64_t nFreeBytesAvailable = filesystem::space(GetDataDir()).available;
// Check for nMinDiskSpace bytes (currently 50MB)
if (nFreeBytesAvailable < nMinDiskSpace + nAdditionalBytes)
{
fShutdown = true;
string strMessage = _("Warning: Disk space is low!");
strMiscWarning = strMessage;
printf("*** %s\n", strMessage.c_str());
uiInterface.ThreadSafeMessageBox(strMessage, "NovaCoin", CClientUIInterface::OK | CClientUIInterface::ICON_EXCLAMATION | CClientUIInterface::MODAL);
StartShutdown();
return false;
}
return true;
}
static filesystem::path BlockFilePath(unsigned int nFile)
{
string strBlockFn = strprintf("blk%04u.dat", nFile);
return GetDataDir() / strBlockFn;
}
FILE* OpenBlockFile(unsigned int nFile, unsigned int nBlockPos, const char* pszMode)
{
if ((nFile < 1) || (nFile == (unsigned int) -1))
return NULL;
FILE* file = fopen(BlockFilePath(nFile).string().c_str(), pszMode);
if (!file)
return NULL;
if (nBlockPos != 0 && !strchr(pszMode, 'a') && !strchr(pszMode, 'w'))
{
if (fseek(file, nBlockPos, SEEK_SET) != 0)
{
fclose(file);
return NULL;
}
}
return file;
}
static unsigned int nCurrentBlockFile = 1;
FILE* AppendBlockFile(unsigned int& nFileRet)
{
nFileRet = 0;
while (true)
{
FILE* file = OpenBlockFile(nCurrentBlockFile, 0, "ab");
if (!file)
return NULL;
if (fseek(file, 0, SEEK_END) != 0)
return NULL;
// FAT32 file size max 4GB, fseek and ftell max 2GB, so we must stay under 2GB
if (ftell(file) < (long)(0x7F000000 - MAX_SIZE))
{
nFileRet = nCurrentBlockFile;
return file;
}
fclose(file);
nCurrentBlockFile++;
}
}
void UnloadBlockIndex()
{
mapBlockIndex.clear();
setStakeSeen.clear();
pindexGenesisBlock = NULL;
nBestHeight = 0;
nBestChainTrust = 0;
nBestInvalidTrust = 0;
hashBestChain = 0;
pindexBest = NULL;
}
bool LoadBlockIndex(bool fAllowNew)
{
if (fTestNet)
{
pchMessageStart[0] = 0xcd;
pchMessageStart[1] = 0xf2;
pchMessageStart[2] = 0xc0;
pchMessageStart[3] = 0xef;
bnProofOfWorkLimit = bnProofOfWorkLimitTestNet; // 16 bits PoW target limit for testnet
nStakeMinAge = 2 * 60 * 60; // test net min age is 2 hours
nModifierInterval = 20 * 60; // test modifier interval is 20 minutes
nCoinbaseMaturity = 10; // test maturity is 10 blocks
nStakeTargetSpacing = 5 * 60; // test block spacing is 5 minutes
}
//
// Load block index
//
CTxDB txdb("cr+");
if (!txdb.LoadBlockIndex())
return false;
//
// Init with genesis block
//
if (mapBlockIndex.empty())
{
if (!fAllowNew)
return false;
// Genesis block
// MainNet:
//CBlock(hash=00000a060336cbb72fe969666d337b87198b1add2abaa59cca226820b32933a4, ver=1, hashPrevBlock=0000000000000000000000000000000000000000000000000000000000000000, hashMerkleRoot=4cb33b3b6a861dcbc685d3e614a9cafb945738d6833f182855679f2fad02057b, nTime=1360105017, nBits=1e0fffff, nNonce=1575379, vtx=1, vchBlockSig=)
// Coinbase(hash=4cb33b3b6a, nTime=1360105017, ver=1, vin.size=1, vout.size=1, nLockTime=0)
// CTxIn(COutPoint(0000000000, 4294967295), coinbase 04ffff001d020f274468747470733a2f2f626974636f696e74616c6b2e6f72672f696e6465782e7068703f746f7069633d3133343137392e6d736731353032313936236d736731353032313936)
// CTxOut(empty)
// vMerkleTree: 4cb33b3b6a
// TestNet:
//CBlock(hash=0000c763e402f2436da9ed36c7286f62c3f6e5dbafce9ff289bd43d7459327eb, ver=1, hashPrevBlock=0000000000000000000000000000000000000000000000000000000000000000, hashMerkleRoot=4cb33b3b6a861dcbc685d3e614a9cafb945738d6833f182855679f2fad02057b, nTime=1360105017, nBits=1f00ffff, nNonce=46534, vtx=1, vchBlockSig=)
// Coinbase(hash=4cb33b3b6a, nTime=1360105017, ver=1, vin.size=1, vout.size=1, nLockTime=0)
// CTxIn(COutPoint(0000000000, 4294967295), coinbase 04ffff001d020f274468747470733a2f2f626974636f696e74616c6b2e6f72672f696e6465782e7068703f746f7069633d3133343137392e6d736731353032313936236d736731353032313936)
// CTxOut(empty)
// vMerkleTree: 4cb33b3b6a
const char* pszTimestamp = "Valentines Day 2105";
CTransaction txNew;
txNew.nTime = 1423729099;
txNew.vin.resize(1);
txNew.vout.resize(1);
txNew.vin[0].scriptSig = CScript() << 486604799 << CBigNum(9999) << vector<unsigned char>((const unsigned char*)pszTimestamp, (const unsigned char*)pszTimestamp + strlen(pszTimestamp));
txNew.vout[0].SetEmpty();
CBlock block;
block.vtx.push_back(txNew);
block.hashPrevBlock = 0;
block.hashMerkleRoot = block.BuildMerkleTree();
block.nVersion = 1;
block.nTime = 1423729099;
block.nBits = bnProofOfWorkLimit.GetCompact();
block.nNonce = !fTestNet ? 0 : 0;
block.print();
printf("block.GetHash() == %s\n", block.GetHash().ToString().c_str());
printf("block.hashMerkleRoot == %s\n", block.hashMerkleRoot.ToString().c_str());
printf("block.nTime = %u \n", block.nTime);
printf("block.nNonce = %u \n", block.nNonce);
printf("block.nBits = %u \n", block.nBits);
//// debug print
assert(block.hashMerkleRoot == uint256("0xb0976022b63c629db3c21a19b2573b578efef372b77155eff7bbd5d90f093e3f"));
assert(block.GetHash() == (!fTestNet ? hashGenesisBlock : hashGenesisBlockTestNet));
//assert(block.CheckBlock());
// Start new block file
unsigned int nFile;
unsigned int nBlockPos;
if (!block.WriteToDisk(nFile, nBlockPos))
return error("LoadBlockIndex() : writing genesis block to disk failed");
if (!block.AddToBlockIndex(nFile, nBlockPos))
return error("LoadBlockIndex() : genesis block not accepted");
// initialize synchronized checkpoint
if (!Checkpoints::WriteSyncCheckpoint((!fTestNet ? hashGenesisBlock : hashGenesisBlockTestNet)))
return error("LoadBlockIndex() : failed to init sync checkpoint");
// upgrade time set to zero if txdb initialized
{
if (!txdb.WriteModifierUpgradeTime(0))
return error("LoadBlockIndex() : failed to init upgrade info");
printf(" Upgrade Info: ModifierUpgradeTime txdb initialization\n");
}
}
{
CTxDB txdb("r+");
string strPubKey = "";
if (!txdb.ReadCheckpointPubKey(strPubKey) || strPubKey != CSyncCheckpoint::strMasterPubKey)
{
// write checkpoint master key to db
txdb.TxnBegin();
if (!txdb.WriteCheckpointPubKey(CSyncCheckpoint::strMasterPubKey))
return error("LoadBlockIndex() : failed to write new checkpoint master key to db");
if (!txdb.TxnCommit())
return error("LoadBlockIndex() : failed to commit new checkpoint master key to db");
if ((!fTestNet) && !Checkpoints::ResetSyncCheckpoint())
return error("LoadBlockIndex() : failed to reset sync-checkpoint");
}
// upgrade time set to zero if blocktreedb initialized
if (txdb.ReadModifierUpgradeTime(nModifierUpgradeTime))
{
if (nModifierUpgradeTime)
printf(" Upgrade Info: blocktreedb upgrade detected at timestamp %d\n", nModifierUpgradeTime);
else
printf(" Upgrade Info: no blocktreedb upgrade detected.\n");
}
else
{
nModifierUpgradeTime = GetTime();
printf(" Upgrade Info: upgrading blocktreedb at timestamp %u\n", nModifierUpgradeTime);
if (!txdb.WriteModifierUpgradeTime(nModifierUpgradeTime))
return error("LoadBlockIndex() : failed to write upgrade info");
}
#ifndef USE_LEVELDB
txdb.Close();
#endif
}
return true;
}
void PrintBlockTree()
{
// pre-compute tree structure
map<CBlockIndex*, vector<CBlockIndex*> > mapNext;
for (map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.begin(); mi != mapBlockIndex.end(); ++mi)
{
CBlockIndex* pindex = (*mi).second;
mapNext[pindex->pprev].push_back(pindex);
// test
//while (rand() % 3 == 0)
// mapNext[pindex->pprev].push_back(pindex);
}
vector<pair<int, CBlockIndex*> > vStack;
vStack.push_back(make_pair(0, pindexGenesisBlock));
int nPrevCol = 0;
while (!vStack.empty())
{
int nCol = vStack.back().first;
CBlockIndex* pindex = vStack.back().second;
vStack.pop_back();
// print split or gap
if (nCol > nPrevCol)
{
for (int i = 0; i < nCol-1; i++)
printf("| ");
printf("|\\\n");
}
else if (nCol < nPrevCol)
{
for (int i = 0; i < nCol; i++)
printf("| ");
printf("|\n");
}
nPrevCol = nCol;
// print columns
for (int i = 0; i < nCol; i++)
printf("| ");
// print item
CBlock block;
block.ReadFromDisk(pindex);
printf("%d (%u,%u) %s %08x %s mint %7s tx %" PRIszu "",
pindex->nHeight,
pindex->nFile,
pindex->nBlockPos,
block.GetHash().ToString().c_str(),
block.nBits,
DateTimeStrFormat("%x %H:%M:%S", block.GetBlockTime()).c_str(),
FormatMoney(pindex->nMint).c_str(),
block.vtx.size());
PrintWallets(block);
// put the main time-chain first
vector<CBlockIndex*>& vNext = mapNext[pindex];
for (unsigned int i = 0; i < vNext.size(); i++)
{
if (vNext[i]->pnext)
{
swap(vNext[0], vNext[i]);
break;
}
}
// iterate children
for (unsigned int i = 0; i < vNext.size(); i++)
vStack.push_back(make_pair(nCol+i, vNext[i]));
}
}
bool LoadExternalBlockFile(FILE* fileIn)
{
int64_t nStart = GetTimeMillis();
int nLoaded = 0;
{
LOCK(cs_main);
try {
CAutoFile blkdat(fileIn, SER_DISK, CLIENT_VERSION);
unsigned int nPos = 0;
while (nPos != (unsigned int)-1 && blkdat.good() && !fRequestShutdown)
{
unsigned char pchData[65536];
do {
fseek(blkdat, nPos, SEEK_SET);
int nRead = fread(pchData, 1, sizeof(pchData), blkdat);
if (nRead <= 8)
{
nPos = (unsigned int)-1;
break;
}
void* nFind = memchr(pchData, pchMessageStart[0], nRead+1-sizeof(pchMessageStart));
if (nFind)
{
if (memcmp(nFind, pchMessageStart, sizeof(pchMessageStart))==0)
{
nPos += ((unsigned char*)nFind - pchData) + sizeof(pchMessageStart);
break;
}
nPos += ((unsigned char*)nFind - pchData) + 1;
}
else
nPos += sizeof(pchData) - sizeof(pchMessageStart) + 1;
} while(!fRequestShutdown);
if (nPos == (unsigned int)-1)
break;
fseek(blkdat, nPos, SEEK_SET);
unsigned int nSize;
blkdat >> nSize;
if (nSize > 0 && nSize <= MAX_BLOCK_SIZE)
{
CBlock block;
blkdat >> block;
if (ProcessBlock(NULL,&block))
{
nLoaded++;
nPos += 4 + nSize;
}
}
}
}
catch (std::exception &e) {
printf("%s() : Deserialize or I/O error caught during load\n",
BOOST_CURRENT_FUNCTION);
}
}
printf("Loaded %i blocks from external file in %" PRId64 "ms\n", nLoaded, GetTimeMillis() - nStart);
return nLoaded > 0;
}
//////////////////////////////////////////////////////////////////////////////
//
// CAlert
//
extern map<uint256, CAlert> mapAlerts;
extern CCriticalSection cs_mapAlerts;
string GetWarnings(string strFor)
{
int nPriority = 0;
string strStatusBar;
string strRPC;
if (GetBoolArg("-testsafemode"))
strRPC = "test";
// Misc warnings like out of disk space and clock is wrong
if (strMiscWarning != "")
{
nPriority = 1000;
strStatusBar = strMiscWarning;
}
// if detected unmet upgrade requirement enter safe mode
// Note: Modifier upgrade requires blockchain redownload if past protocol switch
if (IsFixedModifierInterval(nModifierUpgradeTime + 60*60*24)) // 1 day margin
{
nPriority = 5000;
strStatusBar = strRPC = "WARNING: Blockchain redownload required approaching or past v.0.4.4.6u4 upgrade deadline.";
}
// if detected invalid checkpoint enter safe mode
if (Checkpoints::hashInvalidCheckpoint != 0)
{
nPriority = 3000;
strStatusBar = strRPC = _("WARNING: Invalid checkpoint found! Displayed transactions may not be correct! You may need to upgrade, or notify developers.");
}
// Alerts
{
LOCK(cs_mapAlerts);
BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
{
const CAlert& alert = item.second;
if (alert.AppliesToMe() && alert.nPriority > nPriority)
{
nPriority = alert.nPriority;
strStatusBar = alert.strStatusBar;
if (nPriority > 1000)
strRPC = strStatusBar;
}
}
}
if (strFor == "statusbar")
return strStatusBar;
else if (strFor == "rpc")
return strRPC;
assert(!"GetWarnings() : invalid parameter");
return "error";
}
//////////////////////////////////////////////////////////////////////////////
//
// Messages
//
bool static AlreadyHave(CTxDB& txdb, const CInv& inv)
{
switch (inv.type)
{
case MSG_TX:
{
bool txInMap = false;
{
LOCK(mempool.cs);
txInMap = (mempool.exists(inv.hash));
}
return txInMap ||
mapOrphanTransactions.count(inv.hash) ||
txdb.ContainsTx(inv.hash);
}
case MSG_BLOCK:
return mapBlockIndex.count(inv.hash) ||
mapOrphanBlocks.count(inv.hash);
}
// Don't know what it is, just say we already got one
return true;
}
// The message start string is designed to be unlikely to occur in normal data.
// The characters are rarely used upper ASCII, not valid as UTF-8, and produce
// a large 4-byte int at any alignment.
unsigned char pchMessageStart[4] = { 0xe4, 0xe8, 0xe9, 0xe5 };
bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv)
{
static map<CService, CPubKey> mapReuseKey;
RandAddSeedPerfmon();
if (fDebug)
printf("received: %s (%" PRIszu " bytes)\n", strCommand.c_str(), vRecv.size());
if (mapArgs.count("-dropmessagestest") && GetRand(atoi(mapArgs["-dropmessagestest"])) == 0)
{
printf("dropmessagestest DROPPING RECV MESSAGE\n");
return true;
}
if (strCommand == "version")
{
// Each connection can only send one version message
if (pfrom->nVersion != 0)
{
pfrom->Misbehaving(1);
return false;
}
int64_t nTime;
CAddress addrMe;
CAddress addrFrom;
uint64_t nNonce = 1;
vRecv >> pfrom->nVersion >> pfrom->nServices >> nTime >> addrMe;
if (pfrom->nVersion < MIN_PROTO_VERSION)
{
// Since February 20, 2012, the protocol is initiated at version 209,
// and earlier versions are no longer supported
printf("partner %s using obsolete version %i; disconnecting\n", pfrom->addr.ToString().c_str(), pfrom->nVersion);
pfrom->fDisconnect = true;
return false;
}
if (pfrom->nVersion == 10300)
pfrom->nVersion = 300;
if (!vRecv.empty())
vRecv >> addrFrom >> nNonce;
if (!vRecv.empty())
vRecv >> pfrom->strSubVer;
if (!vRecv.empty())
vRecv >> pfrom->nStartingHeight;
if (pfrom->fInbound && addrMe.IsRoutable())
{
pfrom->addrLocal = addrMe;
SeenLocal(addrMe);
}
// Disconnect if we connected to ourself
if (nNonce == nLocalHostNonce && nNonce > 1)
{
printf("connected to self at %s, disconnecting\n", pfrom->addr.ToString().c_str());
pfrom->fDisconnect = true;
return true;
}
if (pfrom->nVersion < 60010)
{
printf("partner %s using a buggy client %d, disconnecting\n", pfrom->addr.ToString().c_str(), pfrom->nVersion);
pfrom->fDisconnect = true;
return true;
}
// record my external IP reported by peer
if (addrFrom.IsRoutable() && addrMe.IsRoutable())
addrSeenByPeer = addrMe;
// Be shy and don't send version until we hear
if (pfrom->fInbound)
pfrom->PushVersion();
pfrom->fClient = !(pfrom->nServices & NODE_NETWORK);
AddTimeData(pfrom->addr, nTime);
// Change version
pfrom->PushMessage("verack");
pfrom->vSend.SetVersion(min(pfrom->nVersion, PROTOCOL_VERSION));
if (!pfrom->fInbound)
{
// Advertise our address
if (!fNoListen && !IsInitialBlockDownload())
{
CAddress addr = GetLocalAddress(&pfrom->addr);
if (addr.IsRoutable())
pfrom->PushAddress(addr);
}
// Get recent addresses
if (pfrom->fOneShot || pfrom->nVersion >= CADDR_TIME_VERSION || addrman.size() < 1000)
{
pfrom->PushMessage("getaddr");
pfrom->fGetAddr = true;
}
addrman.Good(pfrom->addr);
} else {
if (((CNetAddr)pfrom->addr) == (CNetAddr)addrFrom)
{
addrman.Add(addrFrom, addrFrom);
addrman.Good(addrFrom);
}
}
// Ask the first connected node for block updates
static int nAskedForBlocks = 0;
if (!pfrom->fClient && !pfrom->fOneShot &&
(pfrom->nStartingHeight > (nBestHeight - 144)) &&
(pfrom->nVersion < NOBLKS_VERSION_START ||
pfrom->nVersion >= NOBLKS_VERSION_END) &&
(nAskedForBlocks < 1 || vNodes.size() <= 1))
{
nAskedForBlocks++;
pfrom->PushGetBlocks(pindexBest, uint256(0));
}
// Relay alerts
{
LOCK(cs_mapAlerts);
BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
item.second.RelayTo(pfrom);
}
// Relay sync-checkpoint
{
LOCK(Checkpoints::cs_hashSyncCheckpoint);
if (!Checkpoints::checkpointMessage.IsNull())
Checkpoints::checkpointMessage.RelayTo(pfrom);
}
pfrom->fSuccessfullyConnected = true;
printf("receive version message: version %d, blocks=%d, us=%s, them=%s, peer=%s\n", pfrom->nVersion, pfrom->nStartingHeight, addrMe.ToString().c_str(), addrFrom.ToString().c_str(), pfrom->addr.ToString().c_str());
cPeerBlockCounts.input(pfrom->nStartingHeight);
// ppcoin: ask for pending sync-checkpoint if any
if (!IsInitialBlockDownload())
Checkpoints::AskForPendingSyncCheckpoint(pfrom);
}
else if (pfrom->nVersion == 0)
{
// Must have a version message before anything else
pfrom->Misbehaving(1);
return false;
}
else if (strCommand == "verack")
{
pfrom->vRecv.SetVersion(min(pfrom->nVersion, PROTOCOL_VERSION));
}
else if (strCommand == "addr")
{
vector<CAddress> vAddr;
vRecv >> vAddr;
// Don't want addr from older versions unless seeding
if (pfrom->nVersion < CADDR_TIME_VERSION && addrman.size() > 1000)
return true;
if (vAddr.size() > 1000)
{
pfrom->Misbehaving(20);
return error("message addr size() = %" PRIszu "", vAddr.size());
}
// Store the new addresses
vector<CAddress> vAddrOk;
int64_t nNow = GetAdjustedTime();
int64_t nSince = nNow - 10 * 60;
BOOST_FOREACH(CAddress& addr, vAddr)
{
if (fShutdown)
return true;
if (addr.nTime <= 100000000 || addr.nTime > nNow + 10 * 60)
addr.nTime = nNow - 5 * 24 * 60 * 60;
pfrom->AddAddressKnown(addr);
bool fReachable = IsReachable(addr);
if (addr.nTime > nSince && !pfrom->fGetAddr && vAddr.size() <= 10 && addr.IsRoutable())
{
// Relay to a limited number of other nodes
{
LOCK(cs_vNodes);
// Use deterministic randomness to send to the same nodes for 24 hours
// at a time so the setAddrKnowns of the chosen nodes prevent repeats
static uint256 hashSalt;
if (hashSalt == 0)
hashSalt = GetRandHash();
uint64_t hashAddr = addr.GetHash();
uint256 hashRand = hashSalt ^ (hashAddr<<32) ^ ((GetTime()+hashAddr)/(24*60*60));
hashRand = Hash(BEGIN(hashRand), END(hashRand));
multimap<uint256, CNode*> mapMix;
BOOST_FOREACH(CNode* pnode, vNodes)
{
if (pnode->nVersion < CADDR_TIME_VERSION)
continue;
unsigned int nPointer;
memcpy(&nPointer, &pnode, sizeof(nPointer));
uint256 hashKey = hashRand ^ nPointer;
hashKey = Hash(BEGIN(hashKey), END(hashKey));
mapMix.insert(make_pair(hashKey, pnode));
}
int nRelayNodes = fReachable ? 2 : 1; // limited relaying of addresses outside our network(s)
for (multimap<uint256, CNode*>::iterator mi = mapMix.begin(); mi != mapMix.end() && nRelayNodes-- > 0; ++mi)
((*mi).second)->PushAddress(addr);
}
}
// Do not store addresses outside our network
if (fReachable)
vAddrOk.push_back(addr);
}
addrman.Add(vAddrOk, pfrom->addr, 2 * 60 * 60);
if (vAddr.size() < 1000)
pfrom->fGetAddr = false;
if (pfrom->fOneShot)
pfrom->fDisconnect = true;
}
else if (strCommand == "inv")
{
vector<CInv> vInv;
vRecv >> vInv;
if (vInv.size() > MAX_INV_SZ)
{
pfrom->Misbehaving(20);
return error("message inv size() = %" PRIszu "", vInv.size());
}
// find last block in inv vector
unsigned int nLastBlock = (unsigned int)(-1);
for (unsigned int nInv = 0; nInv < vInv.size(); nInv++) {
if (vInv[vInv.size() - 1 - nInv].type == MSG_BLOCK) {
nLastBlock = vInv.size() - 1 - nInv;
break;
}
}
CTxDB txdb("r");
for (unsigned int nInv = 0; nInv < vInv.size(); nInv++)
{
const CInv &inv = vInv[nInv];
if (fShutdown)
return true;
pfrom->AddInventoryKnown(inv);
bool fAlreadyHave = AlreadyHave(txdb, inv);
if (fDebug)
printf(" got inventory: %s %s\n", inv.ToString().c_str(), fAlreadyHave ? "have" : "new");
if (!fAlreadyHave)
pfrom->AskFor(inv);
else if (inv.type == MSG_BLOCK && mapOrphanBlocks.count(inv.hash)) {
pfrom->PushGetBlocks(pindexBest, GetOrphanRoot(mapOrphanBlocks[inv.hash]));
} else if (nInv == nLastBlock) {
// In case we are on a very long side-chain, it is possible that we already have
// the last block in an inv bundle sent in response to getblocks. Try to detect
// this situation and push another getblocks to continue.
pfrom->PushGetBlocks(mapBlockIndex[inv.hash], uint256(0));
if (fDebug)
printf("force request: %s\n", inv.ToString().c_str());
}
// Track requests for our stuff
Inventory(inv.hash);
}
}
else if (strCommand == "getdata")
{
vector<CInv> vInv;
vRecv >> vInv;
if (vInv.size() > MAX_INV_SZ)
{
pfrom->Misbehaving(20);
return error("message getdata size() = %" PRIszu "", vInv.size());
}
if (fDebugNet || (vInv.size() != 1))
printf("received getdata (%" PRIszu " invsz)\n", vInv.size());
BOOST_FOREACH(const CInv& inv, vInv)
{
if (fShutdown)
return true;
if (fDebugNet || (vInv.size() == 1))
printf("received getdata for: %s\n", inv.ToString().c_str());
if (inv.type == MSG_BLOCK)
{
// Send block from disk
map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(inv.hash);
if (mi != mapBlockIndex.end())
{
CBlock block;
block.ReadFromDisk((*mi).second);
pfrom->PushMessage("block", block);
// Trigger them to send a getblocks request for the next batch of inventory
if (inv.hash == pfrom->hashContinue)
{
// ppcoin: send latest proof-of-work block to allow the
// download node to accept as orphan (proof-of-stake
// block might be rejected by stake connection check)
vector<CInv> vInv;
vInv.push_back(CInv(MSG_BLOCK, GetLastBlockIndex(pindexBest, false)->GetBlockHash()));
pfrom->PushMessage("inv", vInv);
pfrom->hashContinue = 0;
}
}
}
else if (inv.IsKnownType())
{
// Send stream from relay memory
bool pushed = false;
{
LOCK(cs_mapRelay);
map<CInv, CDataStream>::iterator mi = mapRelay.find(inv);
if (mi != mapRelay.end()) {
pfrom->PushMessage(inv.GetCommand(), (*mi).second);
pushed = true;
}
}
if (!pushed && inv.type == MSG_TX) {
LOCK(mempool.cs);
if (mempool.exists(inv.hash)) {
CTransaction tx = mempool.lookup(inv.hash);
CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
ss.reserve(1000);
ss << tx;
pfrom->PushMessage("tx", ss);
}
}
}
// Track requests for our stuff
Inventory(inv.hash);
}
}
else if (strCommand == "getblocks")
{
CBlockLocator locator;
uint256 hashStop;
vRecv >> locator >> hashStop;
// Find the last block the caller has in the main chain
CBlockIndex* pindex = locator.GetBlockIndex();
// Send the rest of the chain
if (pindex)
pindex = pindex->pnext;
int nLimit = 500;
printf("getblocks %d to %s limit %d\n", (pindex ? pindex->nHeight : -1), hashStop.ToString().substr(0,20).c_str(), nLimit);
for (; pindex; pindex = pindex->pnext)
{
if (pindex->GetBlockHash() == hashStop)
{
printf(" getblocks stopping at %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString().substr(0,20).c_str());
// ppcoin: tell downloading node about the latest block if it's
// without risk being rejected due to stake connection check
if (hashStop != hashBestChain && pindex->GetBlockTime() + nStakeMinAge > pindexBest->GetBlockTime())
pfrom->PushInventory(CInv(MSG_BLOCK, hashBestChain));
break;
}
pfrom->PushInventory(CInv(MSG_BLOCK, pindex->GetBlockHash()));
if (--nLimit <= 0)
{
// When this block is requested, we'll send an inv that'll make them
// getblocks the next batch of inventory.
printf(" getblocks stopping at limit %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString().substr(0,20).c_str());
pfrom->hashContinue = pindex->GetBlockHash();
break;
}
}
}
else if (strCommand == "checkpoint")
{
CSyncCheckpoint checkpoint;
vRecv >> checkpoint;
if (checkpoint.ProcessSyncCheckpoint(pfrom))
{
// Relay
pfrom->hashCheckpointKnown = checkpoint.hashCheckpoint;
LOCK(cs_vNodes);
BOOST_FOREACH(CNode* pnode, vNodes)
checkpoint.RelayTo(pnode);
}
}
else if (strCommand == "getheaders")
{
CBlockLocator locator;
uint256 hashStop;
vRecv >> locator >> hashStop;
CBlockIndex* pindex = NULL;
if (locator.IsNull())
{
// If locator is null, return the hashStop block
map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashStop);
if (mi == mapBlockIndex.end())
return true;
pindex = (*mi).second;
}
else
{
// Find the last block the caller has in the main chain
pindex = locator.GetBlockIndex();
if (pindex)
pindex = pindex->pnext;
}
vector<CBlock> vHeaders;
int nLimit = 2000;
printf("getheaders %d to %s\n", (pindex ? pindex->nHeight : -1), hashStop.ToString().substr(0,20).c_str());
for (; pindex; pindex = pindex->pnext)
{
vHeaders.push_back(pindex->GetBlockHeader());
if (--nLimit <= 0 || pindex->GetBlockHash() == hashStop)
break;
}
pfrom->PushMessage("headers", vHeaders);
}
else if (strCommand == "tx")
{
vector<uint256> vWorkQueue;
vector<uint256> vEraseQueue;
CDataStream vMsg(vRecv);
CTxDB txdb("r");
CTransaction tx;
vRecv >> tx;
CInv inv(MSG_TX, tx.GetHash());
pfrom->AddInventoryKnown(inv);
bool fMissingInputs = false;
if (tx.AcceptToMemoryPool(txdb, true, &fMissingInputs))
{
SyncWithWallets(tx, NULL, true);
RelayTransaction(tx, inv.hash);
mapAlreadyAskedFor.erase(inv);
vWorkQueue.push_back(inv.hash);
vEraseQueue.push_back(inv.hash);
// Recursively process any orphan transactions that depended on this one
for (unsigned int i = 0; i < vWorkQueue.size(); i++)
{
uint256 hashPrev = vWorkQueue[i];
for (set<uint256>::iterator mi = mapOrphanTransactionsByPrev[hashPrev].begin();
mi != mapOrphanTransactionsByPrev[hashPrev].end();
++mi)
{
const uint256& orphanTxHash = *mi;
CTransaction& orphanTx = mapOrphanTransactions[orphanTxHash];
bool fMissingInputs2 = false;
if (orphanTx.AcceptToMemoryPool(txdb, true, &fMissingInputs2))
{
printf(" accepted orphan tx %s\n", orphanTxHash.ToString().substr(0,10).c_str());
SyncWithWallets(tx, NULL, true);
RelayTransaction(orphanTx, orphanTxHash);
mapAlreadyAskedFor.erase(CInv(MSG_TX, orphanTxHash));
vWorkQueue.push_back(orphanTxHash);
vEraseQueue.push_back(orphanTxHash);
}
else if (!fMissingInputs2)
{
// invalid orphan
vEraseQueue.push_back(orphanTxHash);
printf(" removed invalid orphan tx %s\n", orphanTxHash.ToString().substr(0,10).c_str());
}
}
}
BOOST_FOREACH(uint256 hash, vEraseQueue)
EraseOrphanTx(hash);
}
else if (fMissingInputs)
{
AddOrphanTx(tx);
// DoS prevention: do not allow mapOrphanTransactions to grow unbounded
unsigned int nEvicted = LimitOrphanTxSize(MAX_ORPHAN_TRANSACTIONS);
if (nEvicted > 0)
printf("mapOrphan overflow, removed %u tx\n", nEvicted);
}
if (tx.nDoS) pfrom->Misbehaving(tx.nDoS);
}
else if (strCommand == "block")
{
CBlock block;
vRecv >> block;
uint256 hashBlock = block.GetHash();
printf("received block %s\n", hashBlock.ToString().substr(0,20).c_str());
// block.print();
CInv inv(MSG_BLOCK, hashBlock);
pfrom->AddInventoryKnown(inv);
if (ProcessBlock(pfrom, &block))
mapAlreadyAskedFor.erase(inv);
if (block.nDoS) pfrom->Misbehaving(block.nDoS);
}
else if (strCommand == "getaddr")
{
// Don't return addresses older than nCutOff timestamp
int64_t nCutOff = GetTime() - (nNodeLifespan * 24 * 60 * 60);
pfrom->vAddrToSend.clear();
vector<CAddress> vAddr = addrman.GetAddr();
BOOST_FOREACH(const CAddress &addr, vAddr)
if(addr.nTime > nCutOff)
pfrom->PushAddress(addr);
}
else if (strCommand == "mempool")
{
std::vector<uint256> vtxid;
mempool.queryHashes(vtxid);
vector<CInv> vInv;
for (unsigned int i = 0; i < vtxid.size(); i++) {
CInv inv(MSG_TX, vtxid[i]);
vInv.push_back(inv);
if (i == (MAX_INV_SZ - 1))
break;
}
if (vInv.size() > 0)
pfrom->PushMessage("inv", vInv);
}
else if (strCommand == "checkorder")
{
uint256 hashReply;
vRecv >> hashReply;
if (!GetBoolArg("-allowreceivebyip"))
{
pfrom->PushMessage("reply", hashReply, (int)2, string(""));
return true;
}
CWalletTx order;
vRecv >> order;
/// we have a chance to check the order here
// Keep giving the same key to the same ip until they use it
if (!mapReuseKey.count(pfrom->addr))
pwalletMain->GetKeyFromPool(mapReuseKey[pfrom->addr], true);
// Send back approval of order and pubkey to use
CScript scriptPubKey;
scriptPubKey << mapReuseKey[pfrom->addr] << OP_CHECKSIG;
pfrom->PushMessage("reply", hashReply, (int)0, scriptPubKey);
}
else if (strCommand == "reply")
{
uint256 hashReply;
vRecv >> hashReply;
CRequestTracker tracker;
{
LOCK(pfrom->cs_mapRequests);
map<uint256, CRequestTracker>::iterator mi = pfrom->mapRequests.find(hashReply);
if (mi != pfrom->mapRequests.end())
{
tracker = (*mi).second;
pfrom->mapRequests.erase(mi);
}
}
if (!tracker.IsNull())
tracker.fn(tracker.param1, vRecv);
}
else if (strCommand == "ping")
{
if (pfrom->nVersion > BIP0031_VERSION)
{
uint64_t nonce = 0;
vRecv >> nonce;
// Echo the message back with the nonce. This allows for two useful features:
//
// 1) A remote node can quickly check if the connection is operational
// 2) Remote nodes can measure the latency of the network thread. If this node
// is overloaded it won't respond to pings quickly and the remote node can
// avoid sending us more work, like chain download requests.
//
// The nonce stops the remote getting confused between different pings: without
// it, if the remote node sends a ping once per second and this node takes 5
// seconds to respond to each, the 5th ping the remote sends would appear to
// return very quickly.
pfrom->PushMessage("pong", nonce);
}
}
else if (strCommand == "alert")
{
CAlert alert;
vRecv >> alert;
uint256 alertHash = alert.GetHash();
if (pfrom->setKnown.count(alertHash) == 0)
{
if (alert.ProcessAlert())
{
// Relay
pfrom->setKnown.insert(alertHash);
{
LOCK(cs_vNodes);
BOOST_FOREACH(CNode* pnode, vNodes)
alert.RelayTo(pnode);
}
}
else {
// Small DoS penalty so peers that send us lots of
// duplicate/expired/invalid-signature/whatever alerts
// eventually get banned.
// This isn't a Misbehaving(100) (immediate ban) because the
// peer might be an older or different implementation with
// a different signature key, etc.
pfrom->Misbehaving(10);
}
}
}
else
{
// Ignore unknown commands for extensibility
}
// Update the last seen time for this node's address
if (pfrom->fNetworkNode)
if (strCommand == "version" || strCommand == "addr" || strCommand == "inv" || strCommand == "getdata" || strCommand == "ping")
AddressCurrentlyConnected(pfrom->addr);
return true;
}
bool ProcessMessages(CNode* pfrom)
{
CDataStream& vRecv = pfrom->vRecv;
if (vRecv.empty())
return true;
//if (fDebug)
// printf("ProcessMessages(%u bytes)\n", vRecv.size());
//
// Message format
// (4) message start
// (12) command
// (4) size
// (4) checksum
// (x) data
//
while (true)
{
// Don't bother if send buffer is too full to respond anyway
if (pfrom->vSend.size() >= SendBufferSize())
break;
// Scan for message start
CDataStream::iterator pstart = search(vRecv.begin(), vRecv.end(), BEGIN(pchMessageStart), END(pchMessageStart));
int nHeaderSize = vRecv.GetSerializeSize(CMessageHeader());
if (vRecv.end() - pstart < nHeaderSize)
{
if ((int)vRecv.size() > nHeaderSize)
{
printf("\n\nPROCESSMESSAGE MESSAGESTART NOT FOUND\n\n");
vRecv.erase(vRecv.begin(), vRecv.end() - nHeaderSize);
}
break;
}
if (pstart - vRecv.begin() > 0)
printf("\n\nPROCESSMESSAGE SKIPPED %" PRIpdd " BYTES\n\n", pstart - vRecv.begin());
vRecv.erase(vRecv.begin(), pstart);
// Read header
vector<char> vHeaderSave(vRecv.begin(), vRecv.begin() + nHeaderSize);
CMessageHeader hdr;
vRecv >> hdr;
if (!hdr.IsValid())
{
printf("\n\nPROCESSMESSAGE: ERRORS IN HEADER %s\n\n\n", hdr.GetCommand().c_str());
continue;
}
string strCommand = hdr.GetCommand();
// Message size
unsigned int nMessageSize = hdr.nMessageSize;
if (nMessageSize > MAX_SIZE)
{
printf("ProcessMessages(%s, %u bytes) : nMessageSize > MAX_SIZE\n", strCommand.c_str(), nMessageSize);
continue;
}
if (nMessageSize > vRecv.size())
{
// Rewind and wait for rest of message
vRecv.insert(vRecv.begin(), vHeaderSave.begin(), vHeaderSave.end());
break;
}
// Checksum
uint256 hash = Hash(vRecv.begin(), vRecv.begin() + nMessageSize);
unsigned int nChecksum = 0;
memcpy(&nChecksum, &hash, sizeof(nChecksum));
if (nChecksum != hdr.nChecksum)
{
printf("ProcessMessages(%s, %u bytes) : CHECKSUM ERROR nChecksum=%08x hdr.nChecksum=%08x\n",
strCommand.c_str(), nMessageSize, nChecksum, hdr.nChecksum);
continue;
}
// Copy message to its own buffer
CDataStream vMsg(vRecv.begin(), vRecv.begin() + nMessageSize, vRecv.nType, vRecv.nVersion);
vRecv.ignore(nMessageSize);
// Process message
bool fRet = false;
try
{
{
LOCK(cs_main);
fRet = ProcessMessage(pfrom, strCommand, vMsg);
}
if (fShutdown)
return true;
}
catch (std::ios_base::failure& e)
{
if (strstr(e.what(), "end of data"))
{
// Allow exceptions from under-length message on vRecv
printf("ProcessMessages(%s, %u bytes) : Exception '%s' caught, normally caused by a message being shorter than its stated length\n", strCommand.c_str(), nMessageSize, e.what());
}
else if (strstr(e.what(), "size too large"))
{
// Allow exceptions from over-long size
printf("ProcessMessages(%s, %u bytes) : Exception '%s' caught\n", strCommand.c_str(), nMessageSize, e.what());
}
else
{
PrintExceptionContinue(&e, "ProcessMessages()");
}
}
catch (std::exception& e) {
PrintExceptionContinue(&e, "ProcessMessages()");
} catch (...) {
PrintExceptionContinue(NULL, "ProcessMessages()");
}
if (!fRet)
printf("ProcessMessage(%s, %u bytes) FAILED\n", strCommand.c_str(), nMessageSize);
}
vRecv.Compact();
return true;
}
bool SendMessages(CNode* pto, bool fSendTrickle)
{
TRY_LOCK(cs_main, lockMain);
if (lockMain) {
// Don't send anything until we get their version message
if (pto->nVersion == 0)
return true;
// Keep-alive ping. We send a nonce of zero because we don't use it anywhere
// right now.
if (pto->nLastSend && GetTime() - pto->nLastSend > nPingInterval && pto->vSend.empty()) {
uint64_t nonce = 0;
if (pto->nVersion > BIP0031_VERSION)
pto->PushMessage("ping", nonce);
else
pto->PushMessage("ping");
}
// Start block sync
if (pto->fStartSync) {
pto->fStartSync = false;
pto->PushGetBlocks(pindexBest, uint256(0));
}
// Resend wallet transactions that haven't gotten in a block yet
ResendWalletTransactions();
// Address refresh broadcast
static int64_t nLastRebroadcast;
if (!IsInitialBlockDownload() && (GetTime() - nLastRebroadcast > nBroadcastInterval))
{
{
LOCK(cs_vNodes);
BOOST_FOREACH(CNode* pnode, vNodes)
{
// Periodically clear setAddrKnown to allow refresh broadcasts
if (nLastRebroadcast)
pnode->setAddrKnown.clear();
// Rebroadcast our address
if (!fNoListen)
{
CAddress addr = GetLocalAddress(&pnode->addr);
if (addr.IsRoutable())
pnode->PushAddress(addr);
}
}
}
nLastRebroadcast = GetTime();
}
//
// Message: addr
//
if (fSendTrickle)
{
vector<CAddress> vAddr;
vAddr.reserve(pto->vAddrToSend.size());
BOOST_FOREACH(const CAddress& addr, pto->vAddrToSend)
{
// returns true if wasn't already contained in the set
if (pto->setAddrKnown.insert(addr).second)
{
vAddr.push_back(addr);
// receiver rejects addr messages larger than 1000
if (vAddr.size() >= 1000)
{
pto->PushMessage("addr", vAddr);
vAddr.clear();
}
}
}
pto->vAddrToSend.clear();
if (!vAddr.empty())
pto->PushMessage("addr", vAddr);
}
//
// Message: inventory
//
vector<CInv> vInv;
vector<CInv> vInvWait;
{
LOCK(pto->cs_inventory);
vInv.reserve(pto->vInventoryToSend.size());
vInvWait.reserve(pto->vInventoryToSend.size());
BOOST_FOREACH(const CInv& inv, pto->vInventoryToSend)
{
if (pto->setInventoryKnown.count(inv))
continue;
// trickle out tx inv to protect privacy
if (inv.type == MSG_TX && !fSendTrickle)
{
// 1/4 of tx invs blast to all immediately
static uint256 hashSalt;
if (hashSalt == 0)
hashSalt = GetRandHash();
uint256 hashRand = inv.hash ^ hashSalt;
hashRand = Hash(BEGIN(hashRand), END(hashRand));
bool fTrickleWait = ((hashRand & 3) != 0);
// always trickle our own transactions
if (!fTrickleWait)
{
CWalletTx wtx;
if (GetTransaction(inv.hash, wtx))
if (wtx.fFromMe)
fTrickleWait = true;
}
if (fTrickleWait)
{
vInvWait.push_back(inv);
continue;
}
}
// returns true if wasn't already contained in the set
if (pto->setInventoryKnown.insert(inv).second)
{
vInv.push_back(inv);
if (vInv.size() >= 1000)
{
pto->PushMessage("inv", vInv);
vInv.clear();
}
}
}
pto->vInventoryToSend = vInvWait;
}
if (!vInv.empty())
pto->PushMessage("inv", vInv);
//
// Message: getdata
//
vector<CInv> vGetData;
int64_t nNow = GetTime() * 1000000;
CTxDB txdb("r");
while (!pto->mapAskFor.empty() && (*pto->mapAskFor.begin()).first <= nNow)
{
const CInv& inv = (*pto->mapAskFor.begin()).second;
if (!AlreadyHave(txdb, inv))
{
if (fDebugNet)
printf("sending getdata: %s\n", inv.ToString().c_str());
vGetData.push_back(inv);
if (vGetData.size() >= 1000)
{
pto->PushMessage("getdata", vGetData);
vGetData.clear();
}
mapAlreadyAskedFor[inv] = nNow;
}
pto->mapAskFor.erase(pto->mapAskFor.begin());
}
if (!vGetData.empty())
pto->PushMessage("getdata", vGetData);
}
return true;
}
| nuggetbram/nova | src/main.cpp | C++ | mit | 146,572 |
package com.vsked.timer;
import java.util.Date;
import java.util.TimerTask;
public class MyJobTi extends TimerTask {
private String jobName="defaultJob";
private int jobCount=0;
public int getJobCount() {
return jobCount;
}
public MyJobTi(String jobName) {
super();
this.jobName = jobName;
jobCount=0;
}
@Override
public void run() {
jobCount++;
System.out.println(new Date()+ "this is my job:"+jobName+"|current count is:"+jobCount);
}
}
| brucevsked/vskeddemolist | vskeddemos/projects/taskdemo/src/com/vsked/timer/MyJobTi.java | Java | mit | 498 |
import React, { Component, PropTypes } from 'react'
import cx from 'classnames'
import { Icon } from '../icon'
import { capitalize } from 'utils/string'
import './button.view.styl'
export class Button extends Component {
static propTypes = {
className: PropTypes.string,
children: PropTypes.oneOfType([
PropTypes.element,
PropTypes.string
]),
icon: PropTypes.string,
type: PropTypes.oneOf(['primary', 'text', 'danger', 'normal']),
htmlType: PropTypes.oneOf(['submit', 'button', 'reset']),
size: PropTypes.oneOf(['small', 'normal', 'large']),
block: PropTypes.bool,
loading: PropTypes.bool,
disabled: PropTypes.bool,
ghost: PropTypes.bool,
onClick: PropTypes.func
}
static defaultProps = {
type: 'primary',
size: 'normal',
onClick: () => {}
}
getRootClassNames () {
const {
className,
type,
size,
block,
loading,
disabled,
ghost
} = this.props
return cx(
'button',
`button${capitalize(type)}`,
`size${capitalize(size)}`,
{ isBlock: block },
{ isGhost: ghost },
{ isLoading: loading },
{ isDisabled: disabled },
className
)
}
handleClick = (e) => {
const {
loading,
disabled,
onClick
} = this.props
if (loading || disabled) {
e.preventDefault()
return null
}
if (onClick) {
onClick(e)
}
}
render () {
const {
icon,
htmlType,
// loading,
children
} = this.props
const iconName = icon // @OLD: loading ? 'loading' : icon
const iconNode = iconName ? <Icon name={iconName} /> : null
return (
<button
className={this.getRootClassNames()}
onClick={this.handleClick}
type={htmlType || 'button'}
>
{iconNode}{children}
</button>
)
}
}
| seccom/kpass | web/src/uis/generics/button/button.view.js | JavaScript | mit | 1,895 |
var mySteal = require('@steal');
if (typeof window !== "undefined" && window.assert) {
assert.ok(mySteal.loader == steal.loader, "The steal's loader is the loader");
done();
} else {
console.log("Systems", mySteal.loader == steal.loader);
}
| stealjs/steal | test/current-steal/main.js | JavaScript | mit | 245 |
def template(from, to)
tmpl = File.read(File.expand_path("../templates/#{from}", __FILE__))
erb = ERB.new(tmpl).result(binding)
execute :touch, "#{to}"
upload! StringIO.new(erb), to
end
| parasquid/capistrano-devops | lib/capistrano/devops/base.rb | Ruby | mit | 194 |
<?php
declare (strict_types=1);
namespace Jacoby\Intervention\PhpParser\Node;
use Jacoby\Intervention\PhpParser\NodeAbstract;
class Arg extends NodeAbstract
{
/** @var Expr Value to pass */
public $value;
/** @var bool Whether to pass by ref */
public $byRef;
/** @var bool Whether to unpack the argument */
public $unpack;
/**
* Constructs a function call argument node.
*
* @param Expr $value Value to pass
* @param bool $byRef Whether to pass by ref
* @param bool $unpack Whether to unpack the argument
* @param array $attributes Additional attributes
*/
public function __construct(Expr $value, bool $byRef = \false, bool $unpack = \false, array $attributes = [])
{
parent::__construct($attributes);
$this->value = $value;
$this->byRef = $byRef;
$this->unpack = $unpack;
}
public function getSubNodeNames() : array
{
return ['value', 'byRef', 'unpack'];
}
public function getType() : string
{
return 'Arg';
}
}
| soberwp/intervention | vendor/nikic/php-parser/lib/PhpParser/Node/Arg.php | PHP | mit | 1,081 |
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Kelolapendaftar extends CI_Controller {
public function _construct()
{
parent::_construct();
$this->load->helper('url');
$this->load->helper('form');
$this->load->library('input');
$this->load->library('form_validation');
$this->load->library('session');
}
public function index()
{
if($this->session->userdata('admin_logged_in')){
$this->load->model('pendaftar_models/PendaftarModels');
$data['listEventGratis'] = $this->PendaftarModels->get_data_event_gratis();
$data['listEventBayar'] = $this->PendaftarModels->get_data_event_bayar();
$this->load->view('skin/admin/header_admin');
$this->load->view('skin/admin/nav_kiri');
$this->load->view('content_admin/kelola_pendaftar', $data);
$this->load->view('skin/admin/footer_admin');
} else {
redirect(site_url('Account'));
}
}
//List pendaftar
public function list_pendaftar($id_event)
{ if($this->session->userdata('admin_logged_in')){
$this->load->model('pendaftar_models/PendaftarModels');
$data['idEvent'] = $id_event;
$event = $this->PendaftarModels->get_event($id_event);
$data['jenis_event'] = $event['jenis_event'];
$data['nama_event'] = $event['nama_coming'];
$data['listPendaftar'] = $this->PendaftarModels->get_data_pendaftar($id_event);
$this->load->view('skin/admin/header_admin');
$this->load->view('skin/admin/nav_kiri');
$this->load->view('content_admin/list_pendaftar', $data);
$this->load->view('skin/admin/footer_admin');
} else {
redirect(site_url('Account'));
}
}
//Delete Data detail produk
public function delete_detail_pendaftar($id_pendaftar)//
{
$this->load->model('pendaftar_models/PendaftarModels');
$this->PendaftarModels->delete_pendaftar($id_pendaftar);
$this->index();
}
//Verifikasi Pembayaran
function verifikasi_bayar($id_pendaftar){
header('Access-Control-Allow-Origin: *');
header('Content-type: text/xml');
//var_dump($search_term); exit();
$get_pendaftar=$this->db->where("id_pendaftar",$id_pendaftar)->get('pendaftar');
$this->load->helper('xml');
$xml_out = '<pendaftars>';
if ($get_pendaftar->num_rows()>0) {
foreach ($get_pendaftar->result() as $row_pendaftar) {
$xml_out .= '<pendaftar ';
$xml_out .= 'id_pendaftar="' . xml_convert($row_pendaftar->id_pendaftar) . '" ';
$xml_out .= 'id_event="' . xml_convert($row_pendaftar->id_event) . '" ';
$xml_out .= 'nama_pendaftar="' . xml_convert($row_pendaftar->nama_pendaftar) . '" ';
$xml_out .= 'email="' . xml_convert($row_pendaftar->email) . '" ';
$xml_out .= 'telepon="' . xml_convert($row_pendaftar->telepon) . '" ';
$xml_out .= 'alamat="' . xml_convert($row_pendaftar->alamat) . '" ';
$xml_out .= 'no_pendaftar="' . xml_convert($row_pendaftar->no_pendaftar) . '" ';
$xml_out .= '/>';
}
}
$xml_out .= '</pendaftars>';
echo $xml_out;
}
//Get Pembayaran
function get_pembayaran($no_pendaftar){
header('Access-Control-Allow-Origin: *');
header('Content-type: text/xml');
//var_dump($search_term); exit();
$data_pembayaran=$this->db->where("no_peserta",$no_pendaftar)->get('pembayaran');
$this->load->helper('xml');
$xml_out = '<pembayarans>';
if ($data_pembayaran->num_rows()>0) {
foreach ($data_pembayaran->result() as $row_pembayaran) {
$xml_out .= '<pembayaran ';
$xml_out .= 'bukti_pembayaran="' . xml_convert($row_pembayaran->path_gambar) . '" ';
$xml_out .= '/>';
}
}
$xml_out .= '</pembayarans>';
echo $xml_out;
}
function verifikasi_bayar_check($id_pendaftar){
$id_pendaftar = $_POST['id_pendaftar'];
$this->load->model('pendaftar_models/PendaftarModels');
$this->PendaftarModels->verifikasi_bayar_check($id_pendaftar);
}
//Lihat detail produk
public function lihat_detail_pendaftar($id_pendaftar)
{
if($this->session->userdata('admin_logged_in')){
$this->load->model('pendaftar_models/PendaftarModels');
//Ambil id_agenda yang akan diedit
$data['id_pendaftar'] = $this->PendaftarModels->select_by_id_pendaftar($id_pendaftar)->row();
$this->load->view('skin/admin/header_admin');
$this->load->view('skin/admin/nav_kiri');
$this->load->view('content_admin/detail_pendaftar', $data);
$this->load->view('skin/admin/footer_admin');
} else {
redirect(site_url('Account'));
}
}
//Validasi pendaftar
public function validasi_pendaftar()
{
$this->load->model('pendaftar_models/PendaftarModels');
$data['listpendaftar'] = $this->PendaftarModels->get_data_pendaftar_pend();
$this->load->view('skin/admin/header_admin');
$this->load->view('skin/admin/nav_kiri');
$this->load->view('content_admin/validasi_pendaftar', $data);
$this->load->view('skin/admin/footer_admin');
}
//Setujui pendaftar
public function setuju_pendaftar()
{
$id_pendaftar = $_POST['id_pendaftar'];
$this->load->model('pendaftar_models/PendaftarModels');
$this->PendaftarModels->setuju_pendaftar($id_pendaftar);
$sub_setuju = "Youth pendaftar";
$msg_setuju = "Posting yang anda masukan di Youth pendaftar telah disetujui";
$this->kirim_email($sub_setuju,$msg_setuju);
$this->validasi_pendaftar();
}
//Setujui pendaftar
public function setuju_detail_pendaftar($id_pendaftar)
{
$this->load->model('pendaftar_models/PendaftarModels');
$this->PendaftarModels->setuju_pendaftar($id_pendaftar);
$sub_setuju = "Youth pendaftar";
$msg_setuju = "Posting yang anda masukan di Youth pendaftar Soon telah disetujui";
$this->kirim_email($sub_setuju,$msg_setuju);
$this->validasi_pendaftar();
}
//Tolak Data
public function tolak_pendaftar()
{
$id_pendaftar = $_POST['id_pendaftar'];
$this->load->model('pendaftar_models/PendaftarModels');
$this->PendaftarModels->delete_pendaftar($id_pendaftar);
$sub_tolak = "Youth pendaftar";
$msg_tolak = "Posting yang anda masukan di Youth pendaftar Soon telah ditolak";
$this->kirim_email($sub_tolak,$msg_tolak);
$this->validasi_pendaftar();
}
//Tolak Data
public function tolak_detail_pendaftar($id_pendaftar)
{
$this->load->model('pendaftar_models/PendaftarModels');
$this->PendaftarModels->delete_pendaftar($id_pendaftar);
$sub_tolak = "Youth pendaftar";
$msg_tolak = "Posting yang anda masukan di Youth pendaftar Soon telah ditolak";
$this->kirim_email($sub_tolak,$msg_tolak);
$this->validasi_pendaftar();
}
//kirim email
function kirim_email($sub, $msg, $email) {
$config['protocol'] = 'smtp';
$config['smtp_host'] = 'mail.boloku.id'; //change this
$config['smtp_port'] = '465';
$config['smtp_user'] = 'info@boloku.id'; //change this
$config['smtp_pass'] = 'cz431081994'; //change this
$config['mailtype'] = 'html';
$config['charset'] = 'iso-8859-1';
$config['smtp_crypto'] = 'ssl';
$config['wordwrap'] = TRUE;
$config['newline'] = "\r\n"; //use double quotes to comply with RFC 822 standard
$this->load->library('email'); // load email library
$this->email->initialize($config);
$this->email->from('info@boloku.id', 'boloku.id');
$this->email->to($email);
$this->email->subject($sub);
$this->email->message($msg);
if ($this->email->send()){
$this->session->set_flashdata('msg_berhasil', 'Pesan balasan telah terkirim.');
//redirect('FrontControl_ContactUs/kelola_message');
}
else{
show_error($this->email->print_debugger());}
}
//tambah pendaftar soon
public function tambah_pendaftar()
{
if($this->session->userdata('admin_logged_in')){
$this->load->model('pendaftar_models/PendaftarModels');
$this->load->view('skin/admin/header_admin');
$this->load->view('skin/admin/nav_kiri');
$this->load->view('content_admin/tambah_pendaftar');
$this->load->view('skin/admin/footer_admin');
} else {
redirect(site_url('Account'));
}
}
function tambah_pendaftar_check() {
if($this->session->userdata('admin_logged_in')){
$this->load->model('pendaftar_models/pendaftarModels');
$this->load->library('form_validation');
$tambah = $this->input->post('submit');
if ($tambah == 1)
{
$this->form_validation->set_rules('nama_pendaftar', 'Nama', 'required');
$this->form_validation->set_rules('email', 'Email', 'required');
$this->form_validation->set_rules('telepon', 'Telepon', 'required');
$this->form_validation->set_rules('alamat', 'Alamat', 'required');
//value id_koridor berisi beberapa data, sehingga dilakukan split dengan explode
if (($this->form_validation->run() == TRUE))
{
$data_pendaftar=array(
'id_event'=>$id_event,
'nama_pendaftar'=>$this->input->post('nama_pendaftar'),
'email'=>$this->input->post('email'),
'telepon'=>$this->input->post('telepon'),
'alamat'=>$this->input->post('alamat'),
'no_pendaftar'=>12312
);
$data['dataPendaftar'] = $data_pendaftar;
$this->db->insert('pendaftar', $data_pendaftar);
redirect('KelolaPendaftar');
}
else
{
$this->session->set_flashdata('msg_gagal', 'Data pendaftar gagal ditambahkan');
$this->tambah_pendaftar_check();
}
}
else
{
$this->load->view('skin/admin/header_admin');
$this->load->view('skin/admin/nav_kiri');
$this->load->view('content_admin/tambah_pendaftar');
$this->load->view('skin/admin/footer_admin');
}
} else {
redirect(site_url('Account'));
}
}
function tambah_pendaftar_check_front($id_event)
{
$data['active']=2;
$this->load->model('pendaftar_models/PendaftarModels');
$this->load->model('coming_models/ComingModels');
$this->load->library('form_validation');
$tambah = $this->input->post('submit');
$seat = $this->input->post('seat');
$event = $this->ComingModels->select_by_id_coming($id_event)->row();
$nama_event=$event->nama_coming;
if ($tambah == 1)
{
$this->form_validation->set_rules('nama_pendaftar', 'Nama', 'required');
$this->form_validation->set_rules('email', 'Email', 'required');
$this->form_validation->set_rules('telepon', 'Telepon', 'required');
$this->form_validation->set_rules('alamat', 'Alamat', 'required');
$this->form_validation->set_rules('tipe_tiket', 'Tipe Tiket', 'required');
//value id_koridor berisi beberapa data, sehingga dilakukan split dengan explode
if (($this->form_validation->run() == TRUE))
<<<<<<< HEAD
{
if($this->input->post('tipe_tiket')=="0"){
=======
{
if($this->input->post('tipe_tiket')=="0"){
>>>>>>> origin/master
$nama_tiket = "Gratis";
$harga = 0;
} else {
$tipe_tiket = explode(":",$this->input->post('tipe_tiket'));
$nama_tiket = $tipe_tiket[0];
$harga = $tipe_tiket[1];
<<<<<<< HEAD
=======
$id_jenis_tiket = $tipe_tiket[2];
>>>>>>> origin/master
}
$seat=$this->input->post('seat');
$no_pendaftar = $this->PendaftarModels->get_jumlah_pendaftar($id_event) + 1;
if($no_pendaftar<10){
$no_pendaftar = '00000'.$no_pendaftar;
} elseif($no_pendaftar<100){
$no_pendaftar = '0000'.$no_pendaftar;
} elseif($no_pendaftar<1000){
$no_pendaftar = '000'.$no_pendaftar;
} elseif($no_pendaftar<10000){
$no_pendaftar = '00'.$no_pendaftar;
} else{
$no_pendaftar = '0'.$no_pendaftar;
}
$kode = substr(md5($this->input->post('nama_pendaftar')), 0, 4);
$nama_pendaftar = $this->input->post('nama_pendaftar');
$data_pendaftar=array(
'id_event'=>$id_event,
'nama_pendaftar'=>$this->input->post('nama_pendaftar'),
'email'=>$this->input->post('email'),
'telepon'=>$this->input->post('telepon'),
'alamat'=>$this->input->post('alamat'),
'nama_tiket'=>$nama_tiket,
'harga'=>$harga,
'status_bayar'=>0,
'no_pendaftar'=>$id_event.'-'.$no_pendaftar.'-'.strtoupper($kode)
);
$data['dataPendaftar'] = $data_pendaftar;
$this->db->insert('pendaftar', $data_pendaftar);
if ($tipe_tiket == 0)
{
$seat = $seat-1;
$this->db->update('coming', array('jumlah_seat'=>$seat), array('id_coming'=>$id_event));
$sub = 'Pendaftaran Peserta '.$nama_event;
$msg = 'Terimakasih telah melalukan pendaftaran pada event '.$nama_event;
$msg .= '<br/> Nomor peserta Anda adalah '.$id_event.'-'.$no_pendaftar.'-'.strtoupper($kode).'. Harap simpan dengan baik nomor peserta Anda';
$email = $this->input->post('email');
$this->kirim_email($sub,$msg,$email);
$this->session->set_flashdata('msg_berhasil', 'Terima kasih telah mendaftar pada event ini, silahkan cek email anda.');
redirect('FrontControl_Event/event_click/'.$id_event);
}
else
{
$tiket = $this->ComingModels->select_tiket_by_id_tiket($id_jenis_tiket)->row();
$seat = $tiket->seat;
if ($seat == NULL)
{
$sub = 'Pendaftaran Peserta '.$nama_event;
$msg = 'Terimakasih telah melalukan pendaftaran pada event '.$nama_event;
$msg .= '<br/> Nomor peserta Anda adalah '.$id_event.'-'.$no_pendaftar.'-'.strtoupper($kode).'.';
$msg .= '<br/> Jenis Tiket : '.$nama_tiket.'';
$msg .= '<br/> Harga Tiket : '.$harga.'';
$msg .= '<br/> Harap simpan dengan baik data pendaftaran Kamu';
$email = $this->input->post('email');
$this->kirim_email($sub,$msg,$email);
$this->session->set_flashdata('msg_berhasil', 'Terima kasih telah mendaftar pada event ini, silahkan cek email anda.');
redirect('FrontControl_Event/event_click/'.$id_event);
}
else
{
$seat = $seat-1;
$this->db->update('tiket', array('seat'=>$seat), array('id_jenis_tiket'=>$id_jenis_tiket));
$sub = 'Pendaftaran Peserta '.$nama_event;
$msg = 'Terimakasih telah melalukan pendaftaran pada event '.$nama_event;
$msg .= '<br/> Nomor peserta Anda adalah '.$id_event.'-'.$no_pendaftar.'-'.strtoupper($kode).'.';
$msg .= '<br/> Jenis Tiket : '.$nama_tiket.'';
$msg .= '<br/> Harga Tiket : '.$harga.'';
$msg .= '<br/> Harap simpan dengan baik data pendaftaran Kamu';
$email = $this->input->post('email');
$this->kirim_email($sub,$msg,$email);
$this->session->set_flashdata('msg_berhasil', 'Terima kasih telah mendaftar pada event ini, silahkan cek email anda.');
redirect('FrontControl_Event/event_click/'.$id_event);
}
}
}
else
{
$this->session->set_flashdata('msg_gagal', 'Data pendaftar gagal ditambahkan');
$this->tambah_pendaftar_check_front();
}
}
else
{
$this->load->view('skin/front_end/header_front_end',$data);
$this->load->view('content_front_end/mendaftar_ikut_event_page');
$this->load->view('skin/front_end/footer_front_end');
}
}
function cari_kata($kata) {
$kata=str_replace('%20',' ',$kata);
header('Access-Control-Allow-Origin: *');
header('Content-type: text/xml');
//var_dump($search_term); exit();
$get_kata=$this->db->like('jawa',$this->db->escape_like_str($kata))->get('pendaftar');
$this->load->helper('xml');
$xml_out = '<kosakata>';
if ($get_kata->num_rows()>0) {
foreach ($get_kata->result() as $row_kata) {
$xml_out .= '<kata ';
$xml_out .= 'id="' . xml_convert($row_kata->id_pendaftar) . '" ';
$xml_out .= 'jawa="' . xml_convert($row_kata->jawa) . '" ';
$xml_out .= 'indonesia="' . xml_convert(($row_kata->indonesia)) . '" ';
$xml_out .= 'deskripsi_jawa="' . xml_convert(($row_kata->deskripsi_jawa)) . '" ';
$xml_out .= '/>';
}
}
$xml_out .= '</kata>';
echo $xml_out;
}
//Fungsi melakukan update pada database
public function edit_pendaftar($id_pendaftar)
{
$this->load->model('pendaftar_models/PendaftarModels');
$this->load->library('form_validation');
$edit = $this->input->post('save');
if (isset($_POST['save']))
{
if($this->input->post('passwordbaru')==NULL){
$password=$this->input->post('passwordlama');
} else{
$password=md5($this->input->post('passwordbaru'));
}
$id_pendaftar = $this->input->post('id_pendaftar');
$this->form_validation->set_rules('username', 'Username', 'required');
$this->form_validation->set_rules('nama_pendaftar', 'Nama_pendaftar', 'required');
$this->form_validation->set_rules('email', 'email', 'required');
//Mengambil filename gambar untuk disimpan
$nmfile = "file_".time();
$config['upload_path'] = './asset/upload_img_pendaftar/';
$config['allowed_types'] = 'jpg|png|jpeg';
$config['max_size'] = '4000'; //kb
$config['file_name'] = $nmfile;
$data_pendaftar=array(
'username'=>$this->input->post('username'),
'nama_pendaftar'=>$this->input->post('nama_pendaftar'),
'email'=>$this->input->post('email'),
'password'=>$password
);
$data['datapendaftar'] = $data_pendaftar;
//value id_koridor berisi beberapa data, sehingga dilakukan split dengan explode
if (($this->form_validation->run() == TRUE))
{
$gbr = NULL;
$iserror = false;
if ((!empty($_FILES['filefoto']['name']))) {
$this->load->library('upload', $config);
if($this->upload->do_upload('filefoto'))
{
//echo "Masuk";
$gbr = $this->upload->data();
$data_pendaftar['path_foto'] = $gbr['file_name'];
}
else
{
$this->session->set_flashdata('msg_gagal', 'Data pendaftar gagal diperbaharui');
$iserror = true;
}
}
if (!$iserror) {
$this->db->update('pendaftar', $data_pendaftar, array('id_pendaftar'=>$id_pendaftar));
$this->session->set_flashdata('msg_berhasil', 'Data pendaftar berhasil diperbaharui');
redirect('Kelolapendaftar');
}
}
else
{
$this->session->set_flashdata('msg_gagal', 'Data pendaftar gagal diperbaharui');
//$this->edit_pendaftar();
}
}
else
{
$data['pendaftar'] = $this->PendaftarModels->select_by_id_pendaftar($id_pendaftar)->row();
$data_pendaftar=array(
'username'=>$data['pendaftar']->username,
'nama_pendaftar'=>$data['pendaftar']->nama_pendaftar,
'email'=>$data['pendaftar']->email,
'password'=>$data['pendaftar']->password,
'path_foto'=> $data['pendaftar']->path_foto
);
$data['datapendaftar'] = $data_pendaftar;
}
$data['idPendaaftar'] = $id_pendaftar;
$this->load->view('skin/admin/header_admin');
$this->load->view('skin/admin/nav_kiri');
$this->load->view('content_admin/edit_pendaftar', $data);
$this->load->view('skin/admin/footer_admin');
}
//tambah pendaftar soon
public function mendaftar_event($id_event)
{
$data['active']=2;
$this->load->model('pendaftar_models/PendaftarModels');
$this->load->model('home_models/HomeModels');
$this->load->model('coming_models/ComingModels');
$ikutEvent = $this->HomeModels->get_event_byid($id_event);
if ($ikutEvent['pendaftaran']==0)
{
show_404();
return;
}
$data['id_event'] = $ikutEvent['id_coming'];
$data['nama_event'] = $ikutEvent['nama_coming'];
$data['tgl_mulai'] = $ikutEvent['tgl_mulai'];
$data['jam_mulai'] = $ikutEvent['jam_mulai'];
$data['tgl_selesai'] = $ikutEvent['tgl_selesai'];
$data['jam_selesai'] = $ikutEvent['jam_selesai'];
$data['kota_lokasi'] = $ikutEvent['id_lokasi'];
$data['alamat'] = $ikutEvent['alamat'];
$data['jenis_event'] = $ikutEvent['jenis_event'];
$data['harga'] = $ikutEvent['harga'];
$data['seat'] = $ikutEvent['seat'];
$data['jumlah_seat'] = $ikutEvent['jumlah_seat'];
$data['namaKota'] = $this->ComingModels->select_by_id_kota($data['kota_lokasi']);
<<<<<<< HEAD
$data['tiket'] = $this->HomeModels->get_tiket_byid($id_event);
=======
$data['tiket'] = $this->HomeModels->get_tiket_byid($id_event);
>>>>>>> origin/master
$this->load->view('skin/front_end/header_front_end', $data);
$this->load->view('content_front_end/mendaftar_ikut_event_page', $data);
$this->load->view('skin/front_end/footer_front_end');
}
function upload_bukti_bayar()
{
$data['active']=6;
$this->load->model('pendaftar_models/PendaftarModels');
$this->load->view('skin/front_end/header_front_end', $data);
$this->load->view('content_front_end/upload_bukti_bayar');
$this->load->view('skin/front_end/footer_front_end');
}
function validate_no_peserta(){
$data = array();
if(isset($_POST['no_peserta'])){
$no_pendaftar = $_POST['no_peserta'];
$query = $this->db->where('no_pendaftar',$no_pendaftar)->get('pendaftar');
foreach ($query->result() as $row){
$data += array('id_pendaftar' => $row->id_pendaftar,
'nama_pendaftar' => $row->nama_pendaftar,
'email' => $row->email,
'telepon' => $row->telepon,
'nama_tiket' => $row->nama_tiket,
'harga' => $row->harga,
'alamat' => $row->alamat
);
}
$query2 = $this->db->select('id_event')->where('no_pendaftar',$no_pendaftar)->get('pendaftar');
foreach ($query2->result() as $row2){
$query3 = $this->db->select('nama_coming, harga, tgl_mulai, tgl_selesai')->where('id_coming',$row2->id_event)->get('coming');
foreach ($query3->result() as $row3){
$tgl_mulai=date('d-F-Y', strtotime($row3->tgl_mulai));
$tgl_selesai=date('d-F-Y', strtotime($row3->tgl_selesai));
$data += array('nama_event' => $row3->nama_coming,
'harga' => $row3->harga,
'tgl_mulai' => $tgl_mulai,
'tgl_selesai' => $tgl_selesai
);
}
}
$data += array('check' => sizeof($query->row_array())
);
echo json_encode($data);
}
}
function upload_bukti() {
$this->load->library('form_validation');
$this->form_validation->set_rules('no_peserta', 'No Peserta', 'required');
//Mengambil filename gambar untuk disimpan
$nmfile = "file_".time();
$config['upload_path'] = './asset/upload_img_pembayaran/';
$config['allowed_types'] = 'jpg|png|jpeg';
$config['max_size'] = '4000'; //kb
$config['file_name'] = $nmfile;
//value id_koridor berisi beberapa data, sehingga dilakukan split dengan explode
if (($this->form_validation->run() == TRUE) AND (!empty($_FILES['filefoto']['name'])))
{
$gbr = NULL;
$data_bukti=array(
'no_peserta'=>$this->input->post('no_peserta'),
'tanggal_upload'=>date("Y-m-d h:i:sa"),
'path_gambar'=> NULL
);
$data['dataBukti'] = $data_bukti;
$this->load->library('upload', $config);
if($this->upload->do_upload('filefoto'))
{
//echo "Masuk";
$gbr = $this->upload->data();
$data_bukti['path_gambar'] = $gbr['file_name'];
$this->db->insert('pembayaran', $data_bukti);
$data = array(
'status_bayar' => 1
);
$this->db->where('no_pendaftar',$this->input->post('no_peserta'));
$this->db->update('pendaftar',$data);
$this->session->set_flashdata('msg_berhasil', 'Bukti pembayaran kamu berhasil diupload, Admin kami akan melakukan verifikasi terhadap bukti pembayaran dalam kurun waktu 1 x 24 jam.');
redirect(site_url());
}
else
{
$this->session->set_flashdata('msg_gagal', 'Data Event baru gagal ditambahkan, cek type file dan ukuran file yang anda upload');
$this->load->view('skin/front_end/header_front_end');
$this->load->view('content_front_end/upload_bukti_bayar');
$this->load->view('skin/front_end/footer_front_end');
}
}
else
{
$error = validation_errors('<div class="error">','</div>');
$this->session->set_flashdata('msg_gagal', $error);
redirect('KelolaMember/dashboard_member');
}
}
public function export_excel_respon($id_event)
{
$this->load->helper('export_xlsx_helper');
$this->load->model('pendaftar_models/PendaftarModels');
$event = $this->PendaftarModels->get_event($id_event);
$nama_event = $event['nama_coming'];
$jenis_event = $event['jenis_event'];
$data['listPendaftar'] = $this->PendaftarModels->get_data_pendaftar($id_event);
do_export_xlsx($data['listPendaftar'], $nama_event, $jenis_event);
}
}
| abdulazieskurniawan/pii_diy | application/controllers/KelolaPendaftar.php | PHP | mit | 24,509 |
define(function(require, exports, module) {
require('jquery.cycle2');
exports.run = function() {
$('.homepage-feature').cycle({
fx:"scrollHorz",
slides: "> a, > img",
log: "false",
pauseOnHover: "true"
});
$('.live-rating-course').find('.media-body').hover(function() {
$( this ).find( ".rating" ).show();
}, function() {
$( this ).find( ".rating" ).hide();
});
};
}); | smeagonline-developers/OnlineEducationPlatform---SMEAGonline | src/Topxia/WebBundle/Resources/public/js/controller/live-course/index.js | JavaScript | mit | 467 |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System.Threading.Tasks;
using Azure.Core.TestFramework;
using Azure.ResourceManager.Resources;
using Azure.ResourceManager.Resources.Models;
using NUnit.Framework;
namespace Azure.ResourceManager.Tests
{
public class ManagementLockObjectOperationsTests : ResourceManagerTestBase
{
public ManagementLockObjectOperationsTests(bool isAsync)
: base(isAsync)//, RecordedTestMode.Record)
{
}
[TestCase]
[RecordedTest]
public async Task Delete()
{
Subscription subscription = await Client.GetDefaultSubscriptionAsync();
string mgmtLockObjectName = Recording.GenerateAssetName("mgmtLock-");
ManagementLock mgmtLockObject = await CreateManagementLockObject(subscription, mgmtLockObjectName);
await mgmtLockObject.DeleteAsync(true);
var ex = Assert.ThrowsAsync<RequestFailedException>(async () => await mgmtLockObject.GetAsync());
Assert.AreEqual(404, ex.Status);
}
}
}
| Azure/azure-sdk-for-net | sdk/resourcemanager/Azure.ResourceManager/tests/Scenario/ManagementLockObjectOperationsTests.cs | C# | mit | 1,128 |
/*===========================================================================
* Licensed Materials - Property of IBM
* "Restricted Materials of IBM"
*
* IBM SDK, Java(tm) Technology Edition, v8
* (C) Copyright IBM Corp. 1999, 2009. All Rights Reserved
*
* US Government Users Restricted Rights - Use, duplication or disclosure
* restricted by GSA ADP Schedule Contract with IBM Corp.
*===========================================================================
*/
/*
* Copyright (c) 1999, 2009, Oracle and/or its affiliates. All rights reserved.
* ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*/
package javax.naming.directory;
import java.util.Hashtable;
import javax.naming.spi.NamingManager;
import javax.naming.*;
/**
* This class is the starting context for performing
* directory operations. The documentation in the class description
* of InitialContext (including those for synchronization) apply here.
*
*
* @author Rosanna Lee
* @author Scott Seligman
*
* @see javax.naming.InitialContext
* @since 1.3
*/
public class InitialDirContext extends InitialContext implements DirContext {
/**
* Constructs an initial DirContext with the option of not
* initializing it. This may be used by a constructor in
* a subclass when the value of the environment parameter
* is not yet known at the time the <tt>InitialDirContext</tt>
* constructor is called. The subclass's constructor will
* call this constructor, compute the value of the environment,
* and then call <tt>init()</tt> before returning.
*
* @param lazy
* true means do not initialize the initial DirContext; false
* is equivalent to calling <tt>new InitialDirContext()</tt>
* @throws NamingException if a naming exception is encountered
*
* @see InitialContext#init(Hashtable)
* @since 1.3
*/
protected InitialDirContext(boolean lazy) throws NamingException {
super(lazy);
}
/**
* Constructs an initial DirContext.
* No environment properties are supplied.
* Equivalent to <tt>new InitialDirContext(null)</tt>.
*
* @throws NamingException if a naming exception is encountered
*
* @see #InitialDirContext(Hashtable)
*/
public InitialDirContext() throws NamingException {
super();
}
/**
* Constructs an initial DirContext using the supplied environment.
* Environment properties are discussed in the
* <tt>javax.naming.InitialContext</tt> class description.
*
* <p> This constructor will not modify <tt>environment</tt>
* or save a reference to it, but may save a clone.
* Caller should not modify mutable keys and values in
* <tt>environment</tt> after it has been passed to the constructor.
*
* @param environment
* environment used to create the initial DirContext.
* Null indicates an empty environment.
*
* @throws NamingException if a naming exception is encountered
*/
public InitialDirContext(Hashtable<?,?> environment)
throws NamingException
{
super(environment);
}
private DirContext getURLOrDefaultInitDirCtx(String name)
throws NamingException {
Context answer = getURLOrDefaultInitCtx(name);
if (!(answer instanceof DirContext)) {
if (answer == null) {
throw new NoInitialContextException();
} else {
throw new NotContextException(
"Not an instance of DirContext");
}
}
return (DirContext)answer;
}
private DirContext getURLOrDefaultInitDirCtx(Name name)
throws NamingException {
Context answer = getURLOrDefaultInitCtx(name);
if (!(answer instanceof DirContext)) {
if (answer == null) {
throw new NoInitialContextException();
} else {
throw new NotContextException(
"Not an instance of DirContext");
}
}
return (DirContext)answer;
}
// DirContext methods
// Most Javadoc is deferred to the DirContext interface.
public Attributes getAttributes(String name)
throws NamingException {
return getAttributes(name, null);
}
public Attributes getAttributes(String name, String[] attrIds)
throws NamingException {
return getURLOrDefaultInitDirCtx(name).getAttributes(name, attrIds);
}
public Attributes getAttributes(Name name)
throws NamingException {
return getAttributes(name, null);
}
public Attributes getAttributes(Name name, String[] attrIds)
throws NamingException {
return getURLOrDefaultInitDirCtx(name).getAttributes(name, attrIds);
}
public void modifyAttributes(String name, int mod_op, Attributes attrs)
throws NamingException {
getURLOrDefaultInitDirCtx(name).modifyAttributes(name, mod_op, attrs);
}
public void modifyAttributes(Name name, int mod_op, Attributes attrs)
throws NamingException {
getURLOrDefaultInitDirCtx(name).modifyAttributes(name, mod_op, attrs);
}
public void modifyAttributes(String name, ModificationItem[] mods)
throws NamingException {
getURLOrDefaultInitDirCtx(name).modifyAttributes(name, mods);
}
public void modifyAttributes(Name name, ModificationItem[] mods)
throws NamingException {
getURLOrDefaultInitDirCtx(name).modifyAttributes(name, mods);
}
public void bind(String name, Object obj, Attributes attrs)
throws NamingException {
getURLOrDefaultInitDirCtx(name).bind(name, obj, attrs);
}
public void bind(Name name, Object obj, Attributes attrs)
throws NamingException {
getURLOrDefaultInitDirCtx(name).bind(name, obj, attrs);
}
public void rebind(String name, Object obj, Attributes attrs)
throws NamingException {
getURLOrDefaultInitDirCtx(name).rebind(name, obj, attrs);
}
public void rebind(Name name, Object obj, Attributes attrs)
throws NamingException {
getURLOrDefaultInitDirCtx(name).rebind(name, obj, attrs);
}
public DirContext createSubcontext(String name, Attributes attrs)
throws NamingException {
return getURLOrDefaultInitDirCtx(name).createSubcontext(name, attrs);
}
public DirContext createSubcontext(Name name, Attributes attrs)
throws NamingException {
return getURLOrDefaultInitDirCtx(name).createSubcontext(name, attrs);
}
public DirContext getSchema(String name) throws NamingException {
return getURLOrDefaultInitDirCtx(name).getSchema(name);
}
public DirContext getSchema(Name name) throws NamingException {
return getURLOrDefaultInitDirCtx(name).getSchema(name);
}
public DirContext getSchemaClassDefinition(String name)
throws NamingException {
return getURLOrDefaultInitDirCtx(name).getSchemaClassDefinition(name);
}
public DirContext getSchemaClassDefinition(Name name)
throws NamingException {
return getURLOrDefaultInitDirCtx(name).getSchemaClassDefinition(name);
}
// -------------------- search operations
public NamingEnumeration<SearchResult>
search(String name, Attributes matchingAttributes)
throws NamingException
{
return getURLOrDefaultInitDirCtx(name).search(name, matchingAttributes);
}
public NamingEnumeration<SearchResult>
search(Name name, Attributes matchingAttributes)
throws NamingException
{
return getURLOrDefaultInitDirCtx(name).search(name, matchingAttributes);
}
public NamingEnumeration<SearchResult>
search(String name,
Attributes matchingAttributes,
String[] attributesToReturn)
throws NamingException
{
return getURLOrDefaultInitDirCtx(name).search(name,
matchingAttributes,
attributesToReturn);
}
public NamingEnumeration<SearchResult>
search(Name name,
Attributes matchingAttributes,
String[] attributesToReturn)
throws NamingException
{
return getURLOrDefaultInitDirCtx(name).search(name,
matchingAttributes,
attributesToReturn);
}
public NamingEnumeration<SearchResult>
search(String name,
String filter,
SearchControls cons)
throws NamingException
{
return getURLOrDefaultInitDirCtx(name).search(name, filter, cons);
}
public NamingEnumeration<SearchResult>
search(Name name,
String filter,
SearchControls cons)
throws NamingException
{
return getURLOrDefaultInitDirCtx(name).search(name, filter, cons);
}
public NamingEnumeration<SearchResult>
search(String name,
String filterExpr,
Object[] filterArgs,
SearchControls cons)
throws NamingException
{
return getURLOrDefaultInitDirCtx(name).search(name, filterExpr,
filterArgs, cons);
}
public NamingEnumeration<SearchResult>
search(Name name,
String filterExpr,
Object[] filterArgs,
SearchControls cons)
throws NamingException
{
return getURLOrDefaultInitDirCtx(name).search(name, filterExpr,
filterArgs, cons);
}
}
| flyzsd/java-code-snippets | ibm.jdk8/src/javax/naming/directory/InitialDirContext.java | Java | mit | 9,969 |
package msvcdojo;
import static org.springframework.hateoas.mvc.ControllerLinkBuilder.linkTo;
import org.springframework.hateoas.Resource;
import org.springframework.hateoas.mvc.ResourceAssemblerSupport;
import org.springframework.stereotype.Component;
// tag::ResourceAssembler[]
@Component
public class ContactResourceAssembler
extends ResourceAssemblerSupport<Contact, ContactResourceAssembler.ContactResource> {
public ContactResourceAssembler() {
super(ContactController.class, ContactResource.class);
}
@Override
public ContactResource toResource(Contact entity) {
ContactResource resource = createResourceWithId(entity.getId(), entity);
resource.add(linkTo(ContactController.class).slash(entity.getId()).slash("accounts").withRel("contact-accounts"));
return resource;
}
@Override
protected ContactResource instantiateResource(Contact entity) {
return new ContactResource(entity);
}
static class ContactResource extends Resource<Contact> {
public ContactResource(Contact contact) {
super(contact);
}
}
}
// end::ResourceAssembler[] | Accordance/microservice-dojo | kata-spring-restdocs/solution/mysvc/src/main/java/msvcdojo/ContactResourceAssembler.java | Java | mit | 1,105 |
package org.innovateuk.ifs.assessment.invite.controller;
import org.innovateuk.ifs.BaseControllerMockMVCTest;
import org.innovateuk.ifs.assessment.invite.form.ReviewInviteForm;
import org.innovateuk.ifs.assessment.invite.populator.ReviewInviteModelPopulator;
import org.innovateuk.ifs.assessment.invite.viewmodel.ReviewInviteViewModel;
import org.innovateuk.ifs.invite.resource.RejectionReasonResource;
import org.innovateuk.ifs.invite.resource.ReviewInviteResource;
import org.innovateuk.ifs.invite.service.RejectionReasonRestService;
import org.innovateuk.ifs.review.service.ReviewInviteRestService;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InOrder;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Spy;
import org.mockito.junit.MockitoJUnitRunner;
import org.springframework.http.MediaType;
import org.springframework.test.context.TestPropertySource;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.validation.BindingResult;
import java.time.ZonedDateTime;
import java.util.List;
import static java.lang.Boolean.TRUE;
import static java.util.Collections.nCopies;
import static org.innovateuk.ifs.commons.error.CommonErrors.notFoundError;
import static org.innovateuk.ifs.commons.error.CommonFailureKeys.GENERAL_NOT_FOUND;
import static org.innovateuk.ifs.commons.rest.RestResult.restFailure;
import static org.innovateuk.ifs.commons.rest.RestResult.restSuccess;
import static org.innovateuk.ifs.invite.builder.RejectionReasonResourceBuilder.newRejectionReasonResource;
import static org.innovateuk.ifs.review.builder.ReviewInviteResourceBuilder.newReviewInviteResource;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.*;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
@RunWith(MockitoJUnitRunner.Silent.class)
@TestPropertySource(locations = { "classpath:application.properties", "classpath:/application-web-core.properties"} )
public class ReviewInviteControllerTest extends BaseControllerMockMVCTest<ReviewInviteController> {
@Spy
@InjectMocks
private ReviewInviteModelPopulator reviewInviteModelPopulator;
@Mock
private RejectionReasonRestService rejectionReasonRestService;
@Mock
private ReviewInviteRestService reviewInviteRestService;
private List<RejectionReasonResource> rejectionReasons = newRejectionReasonResource()
.withReason("Reason 1", "Reason 2")
.build(2);
private static final String restUrl = "/invite/panel/";
@Override
protected ReviewInviteController supplyControllerUnderTest() {
return new ReviewInviteController();
}
@Before
public void setUp() {
when(rejectionReasonRestService.findAllActive()).thenReturn(restSuccess(rejectionReasons));
}
@Test
public void acceptInvite_loggedIn() throws Exception {
Boolean accept = true;
mockMvc.perform(post(restUrl + "{inviteHash}/decision", "hash")
.contentType(MediaType.APPLICATION_FORM_URLENCODED)
.param("acceptInvitation", accept.toString()))
.andExpect(status().is3xxRedirection())
.andExpect(redirectedUrl("/invite-accept/panel/hash/accept"));
verifyZeroInteractions(reviewInviteRestService);
}
@Test
public void acceptInvite_notLoggedInAndExistingUser() throws Exception {
setLoggedInUser(null);
ZonedDateTime panelDate = ZonedDateTime.now();
Boolean accept = true;
ReviewInviteResource inviteResource = newReviewInviteResource()
.withCompetitionName("my competition")
.withPanelDate(panelDate)
.build();
ReviewInviteViewModel expectedViewModel = new ReviewInviteViewModel("hash", inviteResource, false);
when(reviewInviteRestService.checkExistingUser("hash")).thenReturn(restSuccess(TRUE));
when(reviewInviteRestService.openInvite("hash")).thenReturn(restSuccess(inviteResource));
mockMvc.perform(post(restUrl + "{inviteHash}/decision", "hash")
.contentType(MediaType.APPLICATION_FORM_URLENCODED)
.param("acceptInvitation", accept.toString()))
.andExpect(status().isOk())
.andExpect(model().attribute("model", expectedViewModel))
.andExpect(view().name("assessor-panel-accept-user-exists-but-not-logged-in"));
InOrder inOrder = inOrder(reviewInviteRestService);
inOrder.verify(reviewInviteRestService).checkExistingUser("hash");
inOrder.verify(reviewInviteRestService).openInvite("hash");
inOrder.verifyNoMoreInteractions();
}
@Test
public void confirmAcceptInvite() throws Exception {
when(reviewInviteRestService.acceptInvite("hash")).thenReturn(restSuccess());
mockMvc.perform(get("/invite-accept/panel/{inviteHash}/accept", "hash"))
.andExpect(status().is3xxRedirection())
.andExpect(redirectedUrl("/assessor/dashboard"));
verify(reviewInviteRestService).acceptInvite("hash");
}
@Test
public void confirmAcceptInvite_hashNotExists() throws Exception {
when(reviewInviteRestService.acceptInvite("notExistHash")).thenReturn(restFailure(GENERAL_NOT_FOUND));
mockMvc.perform(get("/invite-accept/panel/{inviteHash}/accept", "notExistHash"))
.andExpect(status().isNotFound());
verify(reviewInviteRestService).acceptInvite("notExistHash");
}
@Test
public void openInvite() throws Exception {
ZonedDateTime panelDate = ZonedDateTime.now();
ReviewInviteResource inviteResource = newReviewInviteResource().withCompetitionName("my competition")
.withPanelDate(panelDate)
.build();
ReviewInviteViewModel expectedViewModel = new ReviewInviteViewModel("hash", inviteResource, true);
when(reviewInviteRestService.openInvite("hash")).thenReturn(restSuccess(inviteResource));
mockMvc.perform(get(restUrl + "{inviteHash}", "hash"))
.andExpect(status().isOk())
.andExpect(view().name("assessor-panel-invite"))
.andExpect(model().attribute("model", expectedViewModel));
verify(reviewInviteRestService).openInvite("hash");
}
@Test
public void openInvite_hashNotExists() throws Exception {
when(reviewInviteRestService.openInvite("notExistHash")).thenReturn(restFailure(notFoundError(ReviewInviteResource.class, "notExistHash")));
mockMvc.perform(get(restUrl + "{inviteHash}", "notExistHash"))
.andExpect(model().attributeDoesNotExist("model"))
.andExpect(status().isNotFound());
verify(reviewInviteRestService).openInvite("notExistHash");
}
@Test
public void noDecisionMade() throws Exception {
ReviewInviteResource inviteResource = newReviewInviteResource().withCompetitionName("my competition").build();
when(reviewInviteRestService.openInvite("hash")).thenReturn(restSuccess(inviteResource));
ReviewInviteForm expectedForm = new ReviewInviteForm();
MvcResult result = mockMvc.perform(post(restUrl + "{inviteHash}/decision", "hash"))
.andExpect(status().isOk())
.andExpect(model().hasErrors())
.andExpect(model().attributeHasFieldErrors("form", "acceptInvitation"))
.andExpect(model().attribute("form", expectedForm))
.andExpect(model().attribute("rejectionReasons", rejectionReasons))
.andExpect(model().attributeExists("model"))
.andExpect(view().name("assessor-panel-invite")).andReturn();
ReviewInviteViewModel model = (ReviewInviteViewModel) result.getModelAndView().getModel().get("model");
assertEquals("hash", model.getPanelInviteHash());
assertEquals("my competition", model.getCompetitionName());
ReviewInviteForm form = (ReviewInviteForm) result.getModelAndView().getModel().get("form");
BindingResult bindingResult = form.getBindingResult();
assertTrue(bindingResult.hasErrors());
assertEquals(0, bindingResult.getGlobalErrorCount());
assertEquals(1, bindingResult.getFieldErrorCount());
assertTrue(bindingResult.hasFieldErrors("acceptInvitation"));
assertEquals("Please indicate your decision.", bindingResult.getFieldError("acceptInvitation").getDefaultMessage());
verify(reviewInviteRestService).openInvite("hash");
verifyNoMoreInteractions(reviewInviteRestService);
}
@Test
public void rejectInvite() throws Exception {
Boolean accept = false;
when(reviewInviteRestService.rejectInvite("hash")).thenReturn(restSuccess());
mockMvc.perform(post(restUrl + "{inviteHash}/decision", "hash")
.contentType(MediaType.APPLICATION_FORM_URLENCODED)
.param("acceptInvitation", accept.toString()))
.andExpect(status().is3xxRedirection())
.andExpect(redirectedUrl("/invite/panel/hash/reject/thank-you"));
verify(reviewInviteRestService).rejectInvite("hash");
verifyNoMoreInteractions(reviewInviteRestService);
}
@Test
public void rejectInvite_hashNotExists() throws Exception {
String comment = String.join(" ", nCopies(100, "comment"));
Boolean accept = false;
when(reviewInviteRestService.rejectInvite("notExistHash")).thenReturn(restFailure(notFoundError(ReviewInviteResource.class, "notExistHash")));
when(reviewInviteRestService.openInvite("notExistHash")).thenReturn(restFailure(notFoundError(ReviewInviteResource.class, "notExistHash")));
mockMvc.perform(post(restUrl + "{inviteHash}/decision", "notExistHash")
.contentType(MediaType.APPLICATION_FORM_URLENCODED)
.param("acceptInvitation", accept.toString()))
.andExpect(status().isNotFound());
InOrder inOrder = inOrder(reviewInviteRestService);
inOrder.verify(reviewInviteRestService).rejectInvite("notExistHash");
inOrder.verify(reviewInviteRestService).openInvite("notExistHash");
inOrder.verifyNoMoreInteractions();
}
@Test
public void rejectThankYou() throws Exception {
mockMvc.perform(get(restUrl + "{inviteHash}/reject/thank-you", "hash"))
.andExpect(status().isOk())
.andExpect(view().name("assessor-panel-reject"))
.andReturn();
}
}
| InnovateUKGitHub/innovation-funding-service | ifs-web-service/ifs-assessment-service/src/test/java/org/innovateuk/ifs/assessment/invite/controller/ReviewInviteControllerTest.java | Java | mit | 10,855 |
package org.innovateuk.ifs.registration.service;
import org.springframework.web.context.request.RequestAttributes;
import java.util.HashMap;
import java.util.Map;
/**
* This solves the java.lang.IllegalStateException: Cannot ask for request attribute - request is not active anymore!
* Error, Request attributes are reset before the organisation is updates and removed afterwards.
* @see https://stackoverflow.com/questions/44121654/inherited-servletrquestattributes-is-marked-completed-before-child-thread-finish
* @see https://medium.com/@pranav_maniar/spring-accessing-request-scope-beans-outside-of-web-request-faad27b5ed57
*
*/
public class CustomRequestScopeAttr implements RequestAttributes {
private Map<String, Object> requestAttributeMap = new HashMap<>();
@Override
public Object getAttribute(String name, int scope) {
if (scope == RequestAttributes.SCOPE_REQUEST) {
return this.requestAttributeMap.get(name);
}
return null;
}
@Override
public void setAttribute(String name, Object value, int scope) {
if (scope == RequestAttributes.SCOPE_REQUEST) {
this.requestAttributeMap.put(name, value);
}
}
@Override
public void removeAttribute(String name, int scope) {
if (scope == RequestAttributes.SCOPE_REQUEST) {
this.requestAttributeMap.remove(name);
}
}
@Override
public String[] getAttributeNames(int scope) {
if (scope == RequestAttributes.SCOPE_REQUEST) {
return this.requestAttributeMap.keySet().toArray(new String[0]);
}
return new String[0];
}
@Override
public void registerDestructionCallback(String name, Runnable callback, int scope) {
// Not Supported
}
@Override
public Object resolveReference(String key) {
// Not supported
return null;
}
@Override
public String getSessionId() {
return null;
}
@Override
public Object getSessionMutex() {
return null;
}
} | InnovateUKGitHub/innovation-funding-service | ifs-web-service/ifs-web-core/src/main/java/org/innovateuk/ifs/registration/service/CustomRequestScopeAttr.java | Java | mit | 2,061 |
<?php
/*
* This file is part of the EP-Manager website
*
* (c) 2013 Julien Brochet <julien.brochet@orange.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace EPManager\MainBundle\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\ParamConverter;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\JsonResponse;
use EPManager\MainBundle\Entity\Group;
/**
* Group controller
*
* @author Julien Brochet <julien.brochet@orange.com>
*
* @Route("/group")
*/
class GroupController extends BaseController
{
/**
* @Route("/list", name="group_list")
* @Template
*/
public function listAction()
{
$this->checkCredentials('ROLE_USER');
$em = $this->getDoctrine()->getManager();
$groups = $em->getRepository('MainBundle:Group')->childrenHierarchy(null, false, [
'childSort' => [
'field' => 'name',
'dir' => 'asc'
]
]);
return [
'groups' => $groups
];
}
/**
* @Route("/show/{id}", name="group_show")
* @ParamConverter("group", class="MainBundle:Group")
* @Template
*/
public function showAction(Group $group)
{
$em = $this->getDoctrine()->getManager();
$gRepo = $em->getRepository('MainBundle:Group');
$sRepo = $em->getRepository('MainBundle:Server');
$groups = $gRepo->children($group);
$ids = [];
foreach ($groups as $g) {
$ids[] = $g->getId();
}
return [
'group' => $group,
'path' => $gRepo->getPath($group),
'children_servers' => $sRepo->findAllByGroups($ids),
];
}
/**
* @Route("/create", name="group_create")
* @Method("POST")
*/
public function createAction(Request $request)
{
$this->checkCredentials('ROLE_USER');
$parentId = $request->request->get('parent_id', null);
$name = $request->request->get('name');
$group = new Group($name);
$em = $this->getDoctrine()->getManager();
if ($parentId) {
// Add the parent if it exists
$repo = $em->getRepository('MainBundle:Group');
$parent = $repo->findOneById($parentId);
if (!$parent) {
throw $this->createNotFoundException('Unable to find the parent group');
}
$group->setParent($parent);
}
$validator = $this->get('validator');
$errorList = $validator->validate($group);
// We need to do the validation ourself because
// the form is not used this time
if (count($errorList) > 0) {
$errors = [];
foreach ($errorList as $error) {
$errors[] = $error->getMessage();
}
$this->get('session')->getFlashBag()->add('error',
'Impossible de créer le groupe du nom "'.$name.'". ('.
implode(', ', $errors).
')'
);
return new JsonResponse(['status' => 'nok']);
}
$em->persist($group);
$em->flush();
return new JsonResponse(['status' => 'ok']);
}
/**
* @Route("/delete", name="group_delete_async")
* @Method("POST")
*/
public function deleteAsyncAction(Request $request)
{
$this->checkCredentials('ROLE_USER');
$ids = $request->request->get('ids', null);
if (null === $ids) {
return new JsonResponse(['status' => 'nok']);
}
$em = $this->getDoctrine()->getManager();
$repo = $em->getRepository('MainBundle:Group');
$groups = $repo->findArrayNodes($ids);
foreach ($groups as $group) {
if (true === $group->hasTasks()) {
$this->get('session')->getFlashBag()->add('error',
'Impossible de supprimer le groupe "'.$group->getName().'" car'.
' celui-ci est toujours associé à une tâche.'.
' Vous devez préalablement supprimer cette tâche'.
' avant de pouvoir continuer.'
);
return new JsonResponse(['status' => 'nok']);
}
$em->remove($group);
}
$em->flush();
return new JsonResponse(['status' => 'ok']);
}
}
| aerialls/EPManager | src/EPManager/MainBundle/Controller/GroupController.php | PHP | mit | 4,681 |
<?php
namespace Pharam\Generator;
use Doctrine\DBAL\Connection;
use Doctrine\DBAL\Schema\Table;
/**
* Class Database
* @package Pharam\Generator
*/
class Database
{
/**
* @var Connection
*/
private $connection;
/**
* Initailize connection.
* @param Connection $connection
*/
public function __construct(Connection $connection)
{
$this->setConnection($connection);
}
/**
* Get Connection object
* @return Connection
*/
public function getConnection()
{
return $this->connection;
}
/**
* Sets Connection object
* @param Connection $connection
*/
public function setConnection(Connection $connection)
{
$this->connection = $connection;
}
/**
* Gets all details related to a particular DB table
* @param $tableName
* @return obj Table
* @throws \Exception
*/
public function getTable($tableName)
{
$exists = $this->getConnection()->getSchemaManager()->tablesExist([$tableName]);
if (!$exists) {
throw new \Exception(sprintf('Table %s does not exist', $tableName));
}
$table = $this->getConnection()->getSchemaManager()->listTableDetails($tableName);
return $table;
}
/**
* Get details from all the table present in a DB Table.
* @return \Doctrine\DBAL\Schema\Table[]
*/
public function getAllTables()
{
$tables = $this->getConnection()->getSchemaManager()->listTables();
return $tables;
}
/**
* Gets table details from specified table name.
* @param array $tableNames
* @return array
* @throws \Exception
*/
public function getTables(array $tableNames)
{
$tables = [];
foreach ($tableNames as $tableName) {
$tables[] = $this->getTable($tableName);
}
return $tables;
}
}
| kabirbaidhya/pharam | src/Generator/Database.php | PHP | mit | 1,944 |
from nose.tools import with_setup
import os
import hk_glazer as js2deg
import subprocess
import json
class TestClass:
@classmethod
def setup_class(cls):
cls.here = os.path.dirname(__file__)
cls.data = cls.here + '/data'
def test_1(self):
'''Test 1: Check that json_to_degree works when imported'''
with open(self.data + "/json_test_in.json") as config_file:
config_dict = json.load(config_file)
gen_str = js2deg.dict_to_dat(config_dict)
with open(self.data + "/json_test_out.txt") as verif_file:
test_str = verif_file.read()
assert(test_str == gen_str)
pass
def test_2(self):
'''Test 2: Check command line execution when saving to file'''
cmd = os.path.abspath(self.here + '/../../bin/hk_glazer')
print(cmd)
subprocess.check_call([cmd, "js2degree", self.data + "/json_test_in.json", "-o=test2.txt", "-s"])
with open("test2.txt") as file:
gen_str = file.read()
with open(self.data + "/json_test_out.txt") as file:
test_str = file.read()
assert(test_str == gen_str)
os.remove("test2.txt")
pass
def test_3(self):
'''Test 3: Command line execution when outfile already exists'''
cmd = os.path.abspath(self.here + '/../../bin/hk_glazer')
subprocess.check_call([cmd, "js2degree", self.data + "/json_test_in.json", "-o=test3.txt", "-s"])
try:
subprocess.check_call([cmd,"js2degree", self.data + "/json_test_in.json", "-o=test3.txt"])
except Exception as e:
#print(type(e))
assert(type(e) == subprocess.CalledProcessError)
pass
else:
assert(False)
finally:
os.remove("test3.txt")
| fmuzf/python_hk_glazer | hk_glazer/test/test.py | Python | mit | 1,705 |
import React from 'react';
import Slider from 'material-ui/Slider';
/**
* The `defaultValue` property sets the initial position of the slider.
* The slider appearance changes when not at the starting position.
*/
const SliderTransparency = (props) => (
<Slider defaultValue={props.transparency} onChange={props.update} sliderStyle={{margin:'auto',pointerEvents:'all'}} axis='y' style={{height:'400px', paddingTop:"30px"}}
data-tip={`Opacity`}
data-offset="{'top': -30}"
/>
);
export default SliderTransparency;
| ekatzenstein/three.js-live | src/components/SliderTransparency.js | JavaScript | mit | 543 |
/*
Qt5xHb - Bindings libraries for Harbour/xHarbour and Qt Framework 5
Copyright (C) 2020 Marcos Antonio Gambeta <marcosgambeta AT outlook DOT com>
*/
/*
DO NOT EDIT THIS FILE - the content was created using a source code generator
*/
#include "QBoxSetSlots.h"
QBoxSetSlots::QBoxSetSlots( QObject *parent ) : QObject( parent )
{
}
QBoxSetSlots::~QBoxSetSlots()
{
}
#if (QT_VERSION >= QT_VERSION_CHECK(5,7,0))
void QBoxSetSlots::brushChanged()
{
QObject *object = qobject_cast<QObject *>(sender());
PHB_ITEM cb = Qt5xHb::Signals_return_codeblock( object, "brushChanged()" );
if( cb )
{
PHB_ITEM psender = Qt5xHb::Signals_return_qobject( (QObject *) object, "QBOXSET" );
hb_vmEvalBlockV( cb, 1, psender );
hb_itemRelease( psender );
}
}
#endif
#if (QT_VERSION >= QT_VERSION_CHECK(5,7,0))
void QBoxSetSlots::cleared()
{
QObject *object = qobject_cast<QObject *>(sender());
PHB_ITEM cb = Qt5xHb::Signals_return_codeblock( object, "cleared()" );
if( cb )
{
PHB_ITEM psender = Qt5xHb::Signals_return_qobject( (QObject *) object, "QBOXSET" );
hb_vmEvalBlockV( cb, 1, psender );
hb_itemRelease( psender );
}
}
#endif
#if (QT_VERSION >= QT_VERSION_CHECK(5,7,0))
void QBoxSetSlots::clicked()
{
QObject *object = qobject_cast<QObject *>(sender());
PHB_ITEM cb = Qt5xHb::Signals_return_codeblock( object, "clicked()" );
if( cb )
{
PHB_ITEM psender = Qt5xHb::Signals_return_qobject( (QObject *) object, "QBOXSET" );
hb_vmEvalBlockV( cb, 1, psender );
hb_itemRelease( psender );
}
}
#endif
#if (QT_VERSION >= QT_VERSION_CHECK(5,7,0))
void QBoxSetSlots::doubleClicked()
{
QObject *object = qobject_cast<QObject *>(sender());
PHB_ITEM cb = Qt5xHb::Signals_return_codeblock( object, "doubleClicked()" );
if( cb )
{
PHB_ITEM psender = Qt5xHb::Signals_return_qobject( (QObject *) object, "QBOXSET" );
hb_vmEvalBlockV( cb, 1, psender );
hb_itemRelease( psender );
}
}
#endif
#if (QT_VERSION >= QT_VERSION_CHECK(5,7,0))
void QBoxSetSlots::hovered( bool status )
{
QObject *object = qobject_cast<QObject *>(sender());
PHB_ITEM cb = Qt5xHb::Signals_return_codeblock( object, "hovered(bool)" );
if( cb )
{
PHB_ITEM psender = Qt5xHb::Signals_return_qobject( (QObject *) object, "QBOXSET" );
PHB_ITEM pstatus = hb_itemPutL( NULL, status );
hb_vmEvalBlockV( cb, 2, psender, pstatus );
hb_itemRelease( psender );
hb_itemRelease( pstatus );
}
}
#endif
#if (QT_VERSION >= QT_VERSION_CHECK(5,7,0))
void QBoxSetSlots::penChanged()
{
QObject *object = qobject_cast<QObject *>(sender());
PHB_ITEM cb = Qt5xHb::Signals_return_codeblock( object, "penChanged()" );
if( cb )
{
PHB_ITEM psender = Qt5xHb::Signals_return_qobject( (QObject *) object, "QBOXSET" );
hb_vmEvalBlockV( cb, 1, psender );
hb_itemRelease( psender );
}
}
#endif
#if (QT_VERSION >= QT_VERSION_CHECK(5,7,0))
void QBoxSetSlots::pressed()
{
QObject *object = qobject_cast<QObject *>(sender());
PHB_ITEM cb = Qt5xHb::Signals_return_codeblock( object, "pressed()" );
if( cb )
{
PHB_ITEM psender = Qt5xHb::Signals_return_qobject( (QObject *) object, "QBOXSET" );
hb_vmEvalBlockV( cb, 1, psender );
hb_itemRelease( psender );
}
}
#endif
#if (QT_VERSION >= QT_VERSION_CHECK(5,7,0))
void QBoxSetSlots::released()
{
QObject *object = qobject_cast<QObject *>(sender());
PHB_ITEM cb = Qt5xHb::Signals_return_codeblock( object, "released()" );
if( cb )
{
PHB_ITEM psender = Qt5xHb::Signals_return_qobject( (QObject *) object, "QBOXSET" );
hb_vmEvalBlockV( cb, 1, psender );
hb_itemRelease( psender );
}
}
#endif
#if (QT_VERSION >= QT_VERSION_CHECK(5,7,0))
void QBoxSetSlots::valueChanged( int index )
{
QObject *object = qobject_cast<QObject *>(sender());
PHB_ITEM cb = Qt5xHb::Signals_return_codeblock( object, "valueChanged(int)" );
if( cb )
{
PHB_ITEM psender = Qt5xHb::Signals_return_qobject( (QObject *) object, "QBOXSET" );
PHB_ITEM pindex = hb_itemPutNI( NULL, index );
hb_vmEvalBlockV( cb, 2, psender, pindex );
hb_itemRelease( psender );
hb_itemRelease( pindex );
}
}
#endif
#if (QT_VERSION >= QT_VERSION_CHECK(5,7,0))
void QBoxSetSlots::valuesChanged()
{
QObject *object = qobject_cast<QObject *>(sender());
PHB_ITEM cb = Qt5xHb::Signals_return_codeblock( object, "valuesChanged()" );
if( cb )
{
PHB_ITEM psender = Qt5xHb::Signals_return_qobject( (QObject *) object, "QBOXSET" );
hb_vmEvalBlockV( cb, 1, psender );
hb_itemRelease( psender );
}
}
#endif
void QBoxSetSlots_connect_signal( const QString & signal, const QString & slot )
{
#if (QT_VERSION >= QT_VERSION_CHECK(5,7,0))
QBoxSet * obj = (QBoxSet *) Qt5xHb::itemGetPtrStackSelfItem();
if( obj )
{
QBoxSetSlots * s = QCoreApplication::instance()->findChild<QBoxSetSlots *>();
if( s == NULL )
{
s = new QBoxSetSlots();
s->moveToThread( QCoreApplication::instance()->thread() );
s->setParent( QCoreApplication::instance() );
}
hb_retl( Qt5xHb::Signals_connection_disconnection( s, signal, slot ) );
}
else
{
hb_retl( false );
}
#else
hb_retl( false );
#endif
}
| marcosgambeta/Qt5xHb | source/QtCharts/QBoxSetSlots.cpp | C++ | mit | 5,439 |