text stringlengths 2 1.04M | meta dict |
|---|---|
layout: post
title: "Giant Lightning Eel"
date: 2017-09-10
tags: [large, beast, cr3, tales-from-the-yawning-portal]
---
**Large beast, unaligned**
**Armor Class** 13
**Hit Points** 42 (5d10+15)
**Speed** 5 ft., swim 30 ft.
| STR | DEX | CON | INT | WIS | CHA |
|:-----:|:-----:|:-----:|:-----:|:-----:|:-----:|
| 11 (0) | 17 (+3) | 16 (+3) | 2 (-4) | 12 (+1) | 3 (-4) |
**Damage Resistances** lightning
**Senses** blindsight 60 ft.
**Challenge** 3 (700 XP)
***Source.*** tales from the yawning portal, page 236
***Water Breathing.*** The eel can breathe only underwater.
**Actions**
***Multiattack.*** The eel makes two bite attacks.
***Bite.*** Melee Weapon Attack: +5 to hit, reach 5 ft., one target. Hit: 10 (2d6 + 3) piercing damage plus 4 (1d8) lightning damage.
***Lightning jolt (Recharge 5-6).*** One creature the eel touches within 5 feet of it outside water, or each creature within l 5 feet ofit in a body of water, must make a DC 12 Constitution saving throw. On failed save, a target takes 13 (3d8) lightning damage. If the target takes any of this damage, the target is stunned until the end of the eel's next turn. On a successful save, a target takes half as much damage and isn't stunned.
| {
"content_hash": "6ed4cd5c5f0ac0ab123605e1fb1ed73a",
"timestamp": "",
"source": "github",
"line_count": 36,
"max_line_length": 437,
"avg_line_length": 34.611111111111114,
"alnum_prop": 0.637239165329053,
"repo_name": "whiplashomega/elthelas2",
"id": "163bf27f05a247d2e37c3795985ed5892b2caba3",
"size": "1250",
"binary": false,
"copies": "1",
"ref": "refs/heads/3.x-dev",
"path": "data/creaturebackup/giant-lightning-eel.markdown",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "2037"
},
{
"name": "HTML",
"bytes": "354"
},
{
"name": "JavaScript",
"bytes": "761819"
},
{
"name": "PHP",
"bytes": "6911"
},
{
"name": "Procfile",
"bytes": "19"
},
{
"name": "SCSS",
"bytes": "29752"
},
{
"name": "Vue",
"bytes": "727797"
}
],
"symlink_target": ""
} |
<?php
// Do not add namespace
use BlockCypher\Common\BlockCypherUserAgent;
class UserAgentTest extends \PHPUnit\Framework\TestCase
{
public function testGetValue()
{
$ua = BlockCypherUserAgent::getValue("name", "version");
list($id, $version, $features) = sscanf($ua, "BlockCypherSDK/%s %s (%s)");
// Check that we pass the user agent in the expected format
$this->assertNotNull($id);
$this->assertNotNull($version);
$this->assertNotNull($features);
$this->assertEquals("name", $id);
$this->assertEquals("version", $version);
// Check that we pass in these minimal features
$this->assertThat($features, $this->stringContains("OS="));
$this->assertThat($features, $this->stringContains("Bit="));
$this->assertThat($features, $this->stringContains("Lang="));
$this->assertThat($features, $this->stringContains("V="));
$this->assertGreaterThan(5, count(explode(';', $features)));
}
}
| {
"content_hash": "5f45a390dd7432c9e52c35fe04e7c6e6",
"timestamp": "",
"source": "github",
"line_count": 30,
"max_line_length": 82,
"avg_line_length": 33.733333333333334,
"alnum_prop": 0.6294466403162056,
"repo_name": "blockcypher/php-client",
"id": "65f64d2e97874d2ec085e196c7891749d81fabc3",
"size": "1012",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "tests/BlockCypher/Test/Common/UserAgentTest.php",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "33"
},
{
"name": "Makefile",
"bytes": "305"
},
{
"name": "PHP",
"bytes": "1020533"
},
{
"name": "Shell",
"bytes": "797"
}
],
"symlink_target": ""
} |
package com.iluwatar;
public class InvisibilitySpell extends Command {
private Target target;
@Override
public void execute(Target target) {
target.setVisibility(Visibility.INVISIBLE);
this.target = target;
}
@Override
public void undo() {
if (target != null) {
target.setVisibility(Visibility.VISIBLE);
}
}
@Override
public void redo() {
if (target != null) {
target.setVisibility(Visibility.INVISIBLE);
}
}
@Override
public String toString() {
return "Invisibility spell";
}
}
| {
"content_hash": "a490b5e8dba196ab804053c3fdb67b2a",
"timestamp": "",
"source": "github",
"line_count": 31,
"max_line_length": 48,
"avg_line_length": 17.70967741935484,
"alnum_prop": 0.6612021857923497,
"repo_name": "lightSky/java-design-patterns",
"id": "175aef4fcd8c3bd4d217522eb459ad9c33871180",
"size": "549",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "command/src/main/java/com/iluwatar/InvisibilitySpell.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "226256"
}
],
"symlink_target": ""
} |
/////////////////////////////////////////////////////////////////////////////
// Name: resource.cpp
// Purpose: Resource system
// Author: Julian Smart
// Modified by:
// Created: 04/01/98
// RCS-ID: $Id: resource.cpp,v 1.17 2005/03/03 19:17:45 ABX Exp $
// Copyright: (c) Julian Smart
// Licence: wxWindows licence
/////////////////////////////////////////////////////////////////////////////
#ifdef __GNUG__
#pragma implementation "resource.h"
#endif
// For compilers that support precompilation, includes "wx.h".
#include "wx/wxprec.h"
#ifdef __BORLANDC__
#pragma hdrstop
#endif
#include "wx/deprecated/setup.h"
#if wxUSE_WX_RESOURCES
#ifdef __VISUALC__
#pragma warning(disable:4706) // assignment within conditional expression
#endif // VC++
#ifndef WX_PRECOMP
#include "wx/defs.h"
#include "wx/setup.h"
#include "wx/list.h"
#include "wx/hash.h"
#include "wx/gdicmn.h"
#include "wx/utils.h"
#include "wx/types.h"
#include "wx/menu.h"
#include "wx/stattext.h"
#include "wx/button.h"
#include "wx/bmpbuttn.h"
#include "wx/radiobox.h"
#include "wx/listbox.h"
#include "wx/choice.h"
#include "wx/checkbox.h"
#include "wx/settings.h"
#include "wx/slider.h"
#include "wx/icon.h"
#include "wx/statbox.h"
#include "wx/statbmp.h"
#include "wx/gauge.h"
#include "wx/textctrl.h"
#include "wx/msgdlg.h"
#include "wx/intl.h"
#endif
#include "wx/treebase.h"
#include "wx/listctrl.h"
#if wxUSE_RADIOBTN
#include "wx/radiobut.h"
#endif
#if wxUSE_SCROLLBAR
#include "wx/scrolbar.h"
#endif
#if wxUSE_COMBOBOX
#include "wx/combobox.h"
#endif
#include "wx/splitter.h"
#include "wx/toolbar.h"
#include "wx/validate.h"
#include "wx/log.h"
#include "wx/module.h"
#include <ctype.h>
#include <math.h>
#include <stdlib.h>
#include <string.h>
#include "wx/string.h"
#include "wx/settings.h"
#include "wx/stream.h"
#include "wx/deprecated/resource.h"
#include "wx/deprecated/wxexpr.h"
#if !WXWIN_COMPATIBILITY_2_4
static inline wxChar* copystring(const wxChar* s)
{ return wxStrcpy(new wxChar[wxStrlen(s) + 1], s); }
#endif
// Forward (private) declarations
bool wxResourceInterpretResources(wxResourceTable& table, wxExprDatabase& db);
wxItemResource *wxResourceInterpretDialog(wxResourceTable& table, wxExpr *expr, bool isPanel = false);
wxItemResource *wxResourceInterpretControl(wxResourceTable& table, wxExpr *expr);
wxItemResource *wxResourceInterpretMenu(wxResourceTable& table, wxExpr *expr);
wxItemResource *wxResourceInterpretMenuBar(wxResourceTable& table, wxExpr *expr);
wxItemResource *wxResourceInterpretString(wxResourceTable& table, wxExpr *expr);
wxItemResource *wxResourceInterpretBitmap(wxResourceTable& table, wxExpr *expr);
wxItemResource *wxResourceInterpretIcon(wxResourceTable& table, wxExpr *expr);
// Interpret list expression
wxFont wxResourceInterpretFontSpec(wxExpr *expr);
bool wxResourceReadOneResource(FILE *fd, wxExprDatabase& db, bool *eof, wxResourceTable *table = (wxResourceTable *) NULL);
bool wxResourceReadOneResource(wxInputStream *fd, wxExprDatabase& db, bool *eof, wxResourceTable *table) ;
bool wxResourceParseIncludeFile(const wxString& f, wxResourceTable *table = (wxResourceTable *) NULL);
wxResourceTable *wxDefaultResourceTable = (wxResourceTable *) NULL;
char *wxResourceBuffer = (char *) NULL;
long wxResourceBufferSize = 0;
long wxResourceBufferCount = 0;
int wxResourceStringPtr = 0;
void wxInitializeResourceSystem()
{
if (!wxDefaultResourceTable)
wxDefaultResourceTable = new wxResourceTable;
}
void wxCleanUpResourceSystem()
{
delete wxDefaultResourceTable;
if (wxResourceBuffer)
delete[] wxResourceBuffer;
}
// Module to ensure the resource system data gets initialized
// and cleaned up.
class wxResourceModule: public wxModule
{
public:
wxResourceModule() : wxModule() {}
virtual bool OnInit() { wxInitializeResourceSystem(); return true; }
virtual void OnExit() { wxCleanUpResourceSystem(); }
DECLARE_DYNAMIC_CLASS(wxResourceModule)
};
IMPLEMENT_DYNAMIC_CLASS(wxResourceModule, wxModule)
IMPLEMENT_DYNAMIC_CLASS(wxItemResource, wxObject)
IMPLEMENT_DYNAMIC_CLASS(wxResourceTable, wxHashTable)
wxItemResource::wxItemResource()
{
m_itemType = wxEmptyString;
m_title = wxEmptyString;
m_name = wxEmptyString;
m_windowStyle = 0;
m_x = m_y = m_width = m_height = 0;
m_value1 = m_value2 = m_value3 = m_value5 = 0;
m_value4 = wxEmptyString;
m_windowId = 0;
m_exStyle = 0;
}
wxItemResource::~wxItemResource()
{
wxNode *node = m_children.GetFirst();
while (node)
{
wxItemResource *item = (wxItemResource *)node->GetData();
delete item;
delete node;
node = m_children.GetFirst();
}
}
/*
* Resource table
*/
wxResourceTable::wxResourceTable():wxHashTable(wxKEY_STRING), identifiers(wxKEY_STRING)
{
}
wxResourceTable::~wxResourceTable()
{
ClearTable();
}
wxItemResource *wxResourceTable::FindResource(const wxString& name) const
{
wxItemResource *item = (wxItemResource *)Get(WXSTRINGCAST name);
return item;
}
void wxResourceTable::AddResource(wxItemResource *item)
{
wxString name = item->GetName();
if (name.empty())
name = item->GetTitle();
if (name.empty())
name = wxT("no name");
// Delete existing resource, if any.
Delete(name);
Put(name, item);
}
bool wxResourceTable::DeleteResource(const wxString& name)
{
wxItemResource *item = (wxItemResource *)Delete(WXSTRINGCAST name);
if (item)
{
// See if any resource has this as its child; if so, delete from
// parent's child list.
BeginFind();
wxHashTable::Node *node = Next();
while (node != NULL)
{
wxItemResource *parent = (wxItemResource *)node->GetData();
if (parent->GetChildren().Member(item))
{
parent->GetChildren().DeleteObject(item);
break;
}
node = Next();
}
delete item;
return true;
}
else
return false;
}
bool wxResourceTable::ParseResourceFile( wxInputStream *is )
{
wxExprDatabase db;
int len = is->GetSize() ;
bool eof = false;
while ( is->TellI() + 10 < len) // it's a hack because the streams dont support EOF
{
wxResourceReadOneResource(is, db, &eof, this) ;
}
return wxResourceInterpretResources(*this, db);
}
bool wxResourceTable::ParseResourceFile(const wxString& filename)
{
wxExprDatabase db;
FILE *fd = wxFopen(filename, wxT("r"));
if (!fd)
return false;
bool eof = false;
while (wxResourceReadOneResource(fd, db, &eof, this) && !eof)
{
// Loop
}
fclose(fd);
return wxResourceInterpretResources(*this, db);
}
bool wxResourceTable::ParseResourceData(const wxString& data)
{
wxExprDatabase db;
if (!db.ReadFromString(data))
{
wxLogWarning(_("Ill-formed resource file syntax."));
return false;
}
return wxResourceInterpretResources(*this, db);
}
bool wxResourceTable::RegisterResourceBitmapData(const wxString& name, char bits[], int width, int height)
{
// Register pre-loaded bitmap data
wxItemResource *item = new wxItemResource;
// item->SetType(wxRESOURCE_TYPE_XBM_DATA);
item->SetType(wxT("wxXBMData"));
item->SetName(name);
item->SetValue1((long)bits);
item->SetValue2((long)width);
item->SetValue3((long)height);
AddResource(item);
return true;
}
bool wxResourceTable::RegisterResourceBitmapData(const wxString& name, char **data)
{
// Register pre-loaded bitmap data
wxItemResource *item = new wxItemResource;
// item->SetType(wxRESOURCE_TYPE_XPM_DATA);
item->SetType(wxT("wxXPMData"));
item->SetName(name);
item->SetValue1((long)data);
AddResource(item);
return true;
}
bool wxResourceTable::SaveResource(const wxString& WXUNUSED(filename))
{
return false;
}
void wxResourceTable::ClearTable()
{
BeginFind();
wxHashTable::Node *node = Next();
while (node)
{
wxHashTable::Node *next = Next();
wxItemResource *item = (wxItemResource *)node->GetData();
delete item;
delete node;
node = next;
}
}
wxControl *wxResourceTable::CreateItem(wxWindow *parent, const wxItemResource* childResource, const wxItemResource* parentResource) const
{
int id = childResource->GetId();
if ( id == 0 )
id = wxID_ANY;
bool dlgUnits = ((parentResource->GetResourceStyle() & wxRESOURCE_DIALOG_UNITS) != 0);
wxControl *control = (wxControl *) NULL;
wxString itemType(childResource->GetType());
wxPoint pos;
wxSize size;
if (dlgUnits)
{
pos = parent->ConvertDialogToPixels(wxPoint(childResource->GetX(), childResource->GetY()));
size = parent->ConvertDialogToPixels(wxSize(childResource->GetWidth(), childResource->GetHeight()));
}
else
{
pos = wxPoint(childResource->GetX(), childResource->GetY());
size = wxSize(childResource->GetWidth(), childResource->GetHeight());
}
if (itemType == wxString(wxT("wxButton")) || itemType == wxString(wxT("wxBitmapButton")))
{
if (!childResource->GetValue4().empty())
{
// Bitmap button
wxBitmap bitmap = childResource->GetBitmap();
if (!bitmap.Ok())
{
bitmap = wxResourceCreateBitmap(childResource->GetValue4(), (wxResourceTable *)this);
((wxItemResource*) childResource)->SetBitmap(bitmap);
}
if (!bitmap.Ok())
#if defined(__WXPM__)
//
// OS/2 uses integer id's to access resources, not file name strings
//
bitmap.LoadFile(wxCROSS_BITMAP, wxBITMAP_TYPE_BMP_RESOURCE);
#else
bitmap.LoadFile(wxT("cross_bmp"), wxBITMAP_TYPE_BMP_RESOURCE);
#endif
control = new wxBitmapButton(parent, id, bitmap, pos, size,
childResource->GetStyle() | wxBU_AUTODRAW, wxDefaultValidator, childResource->GetName());
}
else
// Normal, text button
control = new wxButton(parent, id, childResource->GetTitle(), pos, size,
childResource->GetStyle(), wxDefaultValidator, childResource->GetName());
}
else if (itemType == wxString(wxT("wxMessage")) || itemType == wxString(wxT("wxStaticText")) ||
itemType == wxString(wxT("wxStaticBitmap")))
{
if (!childResource->GetValue4().empty() || itemType == wxString(wxT("wxStaticBitmap")) )
{
// Bitmap message
wxBitmap bitmap = childResource->GetBitmap();
if (!bitmap.Ok())
{
bitmap = wxResourceCreateBitmap(childResource->GetValue4(), (wxResourceTable *)this);
((wxItemResource*) childResource)->SetBitmap(bitmap);
}
#if wxUSE_BITMAP_MESSAGE
#ifdef __WXMSW__
// Use a default bitmap
if (!bitmap.Ok())
bitmap.LoadFile(wxT("cross_bmp"), wxBITMAP_TYPE_BMP_RESOURCE);
#endif
if (bitmap.Ok())
control = new wxStaticBitmap(parent, id, bitmap, pos, size,
childResource->GetStyle(), childResource->GetName());
#endif
}
else
{
control = new wxStaticText(parent, id, childResource->GetTitle(), pos, size,
childResource->GetStyle(), childResource->GetName());
}
}
else if (itemType == wxString(wxT("wxText")) || itemType == wxString(wxT("wxTextCtrl")) || itemType == wxString(wxT("wxMultiText")))
{
control = new wxTextCtrl(parent, id, childResource->GetValue4(), pos, size,
childResource->GetStyle(), wxDefaultValidator, childResource->GetName());
}
else if (itemType == wxString(wxT("wxCheckBox")))
{
control = new wxCheckBox(parent, id, childResource->GetTitle(), pos, size,
childResource->GetStyle(), wxDefaultValidator, childResource->GetName());
((wxCheckBox *)control)->SetValue((childResource->GetValue1() != 0));
}
#if wxUSE_GAUGE
else if (itemType == wxString(wxT("wxGauge")))
{
control = new wxGauge(parent, id, (int)childResource->GetValue2(), pos, size,
childResource->GetStyle(), wxDefaultValidator, childResource->GetName());
((wxGauge *)control)->SetValue((int)childResource->GetValue1());
}
#endif
#if wxUSE_RADIOBTN
else if (itemType == wxString(wxT("wxRadioButton")))
{
control = new wxRadioButton(parent, id, childResource->GetTitle(), // (int)childResource->GetValue1(),
pos, size,
childResource->GetStyle(), wxDefaultValidator, childResource->GetName());
}
#endif
#if wxUSE_SCROLLBAR
else if (itemType == wxString(wxT("wxScrollBar")))
{
control = new wxScrollBar(parent, id, pos, size,
childResource->GetStyle(), wxDefaultValidator, childResource->GetName());
/*
((wxScrollBar *)control)->SetValue((int)childResource->GetValue1());
((wxScrollBar *)control)->SetPageSize((int)childResource->GetValue2());
((wxScrollBar *)control)->SetObjectLength((int)childResource->GetValue3());
((wxScrollBar *)control)->SetViewLength((int)(long)childResource->GetValue5());
*/
((wxScrollBar *)control)->SetScrollbar((int)childResource->GetValue1(),(int)childResource->GetValue2(),
(int)childResource->GetValue3(),(int)(long)childResource->GetValue5(),false);
}
#endif
else if (itemType == wxString(wxT("wxSlider")))
{
control = new wxSlider(parent, id, (int)childResource->GetValue1(),
(int)childResource->GetValue2(), (int)childResource->GetValue3(), pos, size,
childResource->GetStyle(), wxDefaultValidator, childResource->GetName());
}
else if (itemType == wxString(wxT("wxGroupBox")) || itemType == wxString(wxT("wxStaticBox")))
{
control = new wxStaticBox(parent, id, childResource->GetTitle(), pos, size,
childResource->GetStyle(), childResource->GetName());
}
else if (itemType == wxString(wxT("wxListBox")))
{
wxStringList& stringList = childResource->GetStringValues();
wxString *strings = (wxString *) NULL;
int noStrings = 0;
if (stringList.GetCount() > 0)
{
noStrings = stringList.GetCount();
strings = new wxString[noStrings];
wxStringListNode *node = stringList.GetFirst();
int i = 0;
while (node)
{
strings[i] = (wxChar *)node->GetData();
i ++;
node = node->GetNext();
}
}
control = new wxListBox(parent, id, pos, size,
noStrings, strings, childResource->GetStyle(), wxDefaultValidator, childResource->GetName());
if (strings)
delete[] strings;
}
else if (itemType == wxString(wxT("wxChoice")))
{
wxStringList& stringList = childResource->GetStringValues();
wxString *strings = (wxString *) NULL;
int noStrings = 0;
if (stringList.GetCount() > 0)
{
noStrings = stringList.GetCount();
strings = new wxString[noStrings];
wxStringListNode *node = stringList.GetFirst();
int i = 0;
while (node)
{
strings[i] = (wxChar *)node->GetData();
i ++;
node = node->GetNext();
}
}
control = new wxChoice(parent, id, pos, size,
noStrings, strings, childResource->GetStyle(), wxDefaultValidator, childResource->GetName());
if (strings)
delete[] strings;
}
#if wxUSE_COMBOBOX
else if (itemType == wxString(wxT("wxComboBox")))
{
wxStringList& stringList = childResource->GetStringValues();
wxString *strings = (wxString *) NULL;
int noStrings = 0;
if (stringList.GetCount() > 0)
{
noStrings = stringList.GetCount();
strings = new wxString[noStrings];
wxStringListNode *node = stringList.GetFirst();
int i = 0;
while (node)
{
strings[i] = (wxChar *)node->GetData();
i ++;
node = node->GetNext();
}
}
control = new wxComboBox(parent, id, childResource->GetValue4(), pos, size,
noStrings, strings, childResource->GetStyle(), wxDefaultValidator, childResource->GetName());
if (strings)
delete[] strings;
}
#endif
else if (itemType == wxString(wxT("wxRadioBox")))
{
wxStringList& stringList = childResource->GetStringValues();
wxString *strings = (wxString *) NULL;
int noStrings = 0;
if (stringList.GetCount() > 0)
{
noStrings = stringList.GetCount();
strings = new wxString[noStrings];
wxStringListNode *node = stringList.GetFirst();
int i = 0;
while (node)
{
strings[i] = (wxChar *)node->GetData();
i ++;
node = node->GetNext();
}
}
control = new wxRadioBox(parent, (wxWindowID) id, wxString(childResource->GetTitle()), pos, size,
noStrings, strings, (int)childResource->GetValue1(), childResource->GetStyle(), wxDefaultValidator,
childResource->GetName());
if (strings)
delete[] strings;
}
if ((parentResource->GetResourceStyle() & wxRESOURCE_USE_DEFAULTS) != 0)
{
// Don't set font; will be inherited from parent.
}
else
{
if (control && childResource->GetFont().Ok())
{
control->SetFont(childResource->GetFont());
#ifdef __WXMSW__
// Force the layout algorithm since the size changes the layout
if (control->IsKindOf(CLASSINFO(wxRadioBox)))
{
control->SetSize(wxDefaultCoord, wxDefaultCoord, wxDefaultCoord, wxDefaultCoord, wxSIZE_AUTO_WIDTH|wxSIZE_AUTO_HEIGHT);
}
#endif
}
}
return control;
}
/*
* Interpret database as a series of resources
*/
bool wxResourceInterpretResources(wxResourceTable& table, wxExprDatabase& db)
{
wxNode *node = db.GetFirst();
while (node)
{
wxExpr *clause = (wxExpr *)node->GetData();
wxString functor(clause->Functor());
wxItemResource *item = (wxItemResource *) NULL;
if (functor == wxT("dialog"))
item = wxResourceInterpretDialog(table, clause);
else if (functor == wxT("panel"))
item = wxResourceInterpretDialog(table, clause, true);
else if (functor == wxT("menubar"))
item = wxResourceInterpretMenuBar(table, clause);
else if (functor == wxT("menu"))
item = wxResourceInterpretMenu(table, clause);
else if (functor == wxT("string"))
item = wxResourceInterpretString(table, clause);
else if (functor == wxT("bitmap"))
item = wxResourceInterpretBitmap(table, clause);
else if (functor == wxT("icon"))
item = wxResourceInterpretIcon(table, clause);
if (item)
{
// Remove any existing resource of same name
if (!item->GetName().empty())
table.DeleteResource(item->GetName());
table.AddResource(item);
}
node = node->GetNext();
}
return true;
}
static const wxChar *g_ValidControlClasses[] =
{
wxT("wxButton"),
wxT("wxBitmapButton"),
wxT("wxMessage"),
wxT("wxStaticText"),
wxT("wxStaticBitmap"),
wxT("wxText"),
wxT("wxTextCtrl"),
wxT("wxMultiText"),
wxT("wxListBox"),
wxT("wxRadioBox"),
wxT("wxRadioButton"),
wxT("wxCheckBox"),
wxT("wxBitmapCheckBox"),
wxT("wxGroupBox"),
wxT("wxStaticBox"),
wxT("wxSlider"),
wxT("wxGauge"),
wxT("wxScrollBar"),
wxT("wxChoice"),
wxT("wxComboBox")
};
static bool wxIsValidControlClass(const wxString& c)
{
for ( size_t i = 0; i < WXSIZEOF(g_ValidControlClasses); i++ )
{
if ( c == g_ValidControlClasses[i] )
return true;
}
return false;
}
wxItemResource *wxResourceInterpretDialog(wxResourceTable& table, wxExpr *expr, bool isPanel)
{
wxItemResource *dialogItem = new wxItemResource;
if (isPanel)
dialogItem->SetType(wxT("wxPanel"));
else
dialogItem->SetType(wxT("wxDialog"));
wxString style = wxEmptyString;
wxString title = wxEmptyString;
wxString name = wxEmptyString;
wxString backColourHex = wxEmptyString;
wxString labelColourHex = wxEmptyString;
wxString buttonColourHex = wxEmptyString;
long windowStyle = wxDEFAULT_DIALOG_STYLE;
if (isPanel)
windowStyle = 0;
int x = 0; int y = 0; int width = wxDefaultCoord; int height = wxDefaultCoord;
int isModal = 0;
wxExpr *labelFontExpr = (wxExpr *) NULL;
wxExpr *buttonFontExpr = (wxExpr *) NULL;
wxExpr *fontExpr = (wxExpr *) NULL;
expr->GetAttributeValue(wxT("style"), style);
expr->GetAttributeValue(wxT("name"), name);
expr->GetAttributeValue(wxT("title"), title);
expr->GetAttributeValue(wxT("x"), x);
expr->GetAttributeValue(wxT("y"), y);
expr->GetAttributeValue(wxT("width"), width);
expr->GetAttributeValue(wxT("height"), height);
expr->GetAttributeValue(wxT("modal"), isModal);
expr->GetAttributeValue(wxT("label_font"), &labelFontExpr);
expr->GetAttributeValue(wxT("button_font"), &buttonFontExpr);
expr->GetAttributeValue(wxT("font"), &fontExpr);
expr->GetAttributeValue(wxT("background_colour"), backColourHex);
expr->GetAttributeValue(wxT("label_colour"), labelColourHex);
expr->GetAttributeValue(wxT("button_colour"), buttonColourHex);
int useDialogUnits = 0;
expr->GetAttributeValue(wxT("use_dialog_units"), useDialogUnits);
if (useDialogUnits != 0)
dialogItem->SetResourceStyle(dialogItem->GetResourceStyle() | wxRESOURCE_DIALOG_UNITS);
int useDefaults = 0;
expr->GetAttributeValue(wxT("use_system_defaults"), useDefaults);
if (useDefaults != 0)
dialogItem->SetResourceStyle(dialogItem->GetResourceStyle() | wxRESOURCE_USE_DEFAULTS);
int id = 0;
expr->GetAttributeValue(wxT("id"), id);
dialogItem->SetId(id);
if (!style.empty())
{
windowStyle = wxParseWindowStyle(style);
}
dialogItem->SetStyle(windowStyle);
dialogItem->SetValue1(isModal);
#ifdef __VMS
#pragma message disable CODCAUUNR
#endif
if (windowStyle & wxDIALOG_MODAL) // Uses style in wxWin 2
dialogItem->SetValue1(true);
#ifdef __VMS
#pragma message enable CODCAUUNR
#endif
dialogItem->SetName(name);
dialogItem->SetTitle(title);
dialogItem->SetSize(x, y, width, height);
// Check for wxWin 1.68-style specifications
if (style.Find(wxT("VERTICAL_LABEL")) != wxNOT_FOUND)
dialogItem->SetResourceStyle(dialogItem->GetResourceStyle() | wxRESOURCE_VERTICAL_LABEL);
else if (style.Find(wxT("HORIZONTAL_LABEL")) != wxNOT_FOUND)
dialogItem->SetResourceStyle(dialogItem->GetResourceStyle() | wxRESOURCE_HORIZONTAL_LABEL);
if (!backColourHex.empty())
{
int r = 0;
int g = 0;
int b = 0;
r = wxHexToDec(backColourHex.Mid(0, 2));
g = wxHexToDec(backColourHex.Mid(2, 2));
b = wxHexToDec(backColourHex.Mid(4, 2));
dialogItem->SetBackgroundColour(wxColour((unsigned char)r,(unsigned char)g,(unsigned char)b));
}
if (!labelColourHex.empty())
{
int r = 0;
int g = 0;
int b = 0;
r = wxHexToDec(labelColourHex.Mid(0, 2));
g = wxHexToDec(labelColourHex.Mid(2, 2));
b = wxHexToDec(labelColourHex.Mid(4, 2));
dialogItem->SetLabelColour(wxColour((unsigned char)r,(unsigned char)g,(unsigned char)b));
}
if (!buttonColourHex.empty())
{
int r = 0;
int g = 0;
int b = 0;
r = wxHexToDec(buttonColourHex.Mid(0, 2));
g = wxHexToDec(buttonColourHex.Mid(2, 2));
b = wxHexToDec(buttonColourHex.Mid(4, 2));
dialogItem->SetButtonColour(wxColour((unsigned char)r,(unsigned char)g,(unsigned char)b));
}
if (fontExpr)
dialogItem->SetFont(wxResourceInterpretFontSpec(fontExpr));
else if (buttonFontExpr)
dialogItem->SetFont(wxResourceInterpretFontSpec(buttonFontExpr));
else if (labelFontExpr)
dialogItem->SetFont(wxResourceInterpretFontSpec(labelFontExpr));
// Now parse all controls
wxExpr *controlExpr = expr->GetFirst();
while (controlExpr)
{
if (controlExpr->Number() == 3)
{
wxString controlKeyword(controlExpr->Nth(1)->StringValue());
if (!controlKeyword.empty() && controlKeyword == wxT("control"))
{
// The value part: always a list.
wxExpr *listExpr = controlExpr->Nth(2);
if (listExpr->Type() == PrologList)
{
wxItemResource *controlItem = wxResourceInterpretControl(table, listExpr);
if (controlItem)
{
dialogItem->GetChildren().Append(controlItem);
}
}
}
}
controlExpr = controlExpr->GetNext();
}
return dialogItem;
}
wxItemResource *wxResourceInterpretControl(wxResourceTable& table, wxExpr *expr)
{
wxItemResource *controlItem = new wxItemResource;
// First, find the standard features of a control definition:
// [optional integer/string id], control name, title, style, name, x, y, width, height
wxString controlType;
wxString style;
wxString title;
wxString name;
int id = 0;
long windowStyle = 0;
int x = 0; int y = 0; int width = wxDefaultCoord; int height = wxDefaultCoord;
int count = 0;
wxExpr *expr1 = expr->Nth(0);
if ( expr1->Type() == PrologString || expr1->Type() == PrologWord )
{
if ( wxIsValidControlClass(expr1->StringValue()) )
{
count = 1;
controlType = expr1->StringValue();
}
else
{
wxString str(expr1->StringValue());
id = wxResourceGetIdentifier(str, &table);
if (id == 0)
{
wxLogWarning(_("Could not resolve control class or id '%s'. Use (non-zero) integer instead\n or provide #define (see manual for caveats)"),
(const wxChar*) expr1->StringValue());
delete controlItem;
return (wxItemResource *) NULL;
}
else
{
// Success - we have an id, so the 2nd element must be the control class.
controlType = expr->Nth(1)->StringValue();
count = 2;
}
}
}
else if (expr1->Type() == PrologInteger)
{
id = (int)expr1->IntegerValue();
// Success - we have an id, so the 2nd element must be the control class.
controlType = expr->Nth(1)->StringValue();
count = 2;
}
expr1 = expr->Nth(count);
count ++;
if ( expr1 )
title = expr1->StringValue();
expr1 = expr->Nth(count);
count ++;
if (expr1)
{
style = expr1->StringValue();
windowStyle = wxParseWindowStyle(style);
}
expr1 = expr->Nth(count);
count ++;
if (expr1)
name = expr1->StringValue();
expr1 = expr->Nth(count);
count ++;
if (expr1)
x = (int)expr1->IntegerValue();
expr1 = expr->Nth(count);
count ++;
if (expr1)
y = (int)expr1->IntegerValue();
expr1 = expr->Nth(count);
count ++;
if (expr1)
width = (int)expr1->IntegerValue();
expr1 = expr->Nth(count);
count ++;
if (expr1)
height = (int)expr1->IntegerValue();
controlItem->SetStyle(windowStyle);
controlItem->SetName(name);
controlItem->SetTitle(title);
controlItem->SetSize(x, y, width, height);
controlItem->SetType(controlType);
controlItem->SetId(id);
// Check for wxWin 1.68-style specifications
if (style.Find(wxT("VERTICAL_LABEL")) != wxNOT_FOUND)
controlItem->SetResourceStyle(controlItem->GetResourceStyle() | wxRESOURCE_VERTICAL_LABEL);
else if (style.Find(wxT("HORIZONTAL_LABEL")) != wxNOT_FOUND)
controlItem->SetResourceStyle(controlItem->GetResourceStyle() | wxRESOURCE_HORIZONTAL_LABEL);
if (controlType == wxT("wxButton"))
{
// Check for bitmap resource name (in case loading old-style resource file)
if (expr->Nth(count) && ((expr->Nth(count)->Type() == PrologString) || (expr->Nth(count)->Type() == PrologWord)))
{
wxString str(expr->Nth(count)->StringValue());
count ++;
if (!str.empty())
{
controlItem->SetValue4(str);
controlItem->SetType(wxT("wxBitmapButton"));
}
}
if (expr->Nth(count) && expr->Nth(count)->Type() == PrologList)
controlItem->SetFont(wxResourceInterpretFontSpec(expr->Nth(count)));
}
else if (controlType == wxT("wxBitmapButton"))
{
// Check for bitmap resource name
if (expr->Nth(count) && ((expr->Nth(count)->Type() == PrologString) || (expr->Nth(count)->Type() == PrologWord)))
{
wxString str(expr->Nth(count)->StringValue());
controlItem->SetValue4(str);
count ++;
if (expr->Nth(count) && expr->Nth(count)->Type() == PrologList)
controlItem->SetFont(wxResourceInterpretFontSpec(expr->Nth(count)));
}
}
else if (controlType == wxT("wxCheckBox"))
{
// Check for default value
if (expr->Nth(count) && (expr->Nth(count)->Type() == PrologInteger))
{
controlItem->SetValue1(expr->Nth(count)->IntegerValue());
count ++;
if (expr->Nth(count) && expr->Nth(count)->Type() == PrologList)
controlItem->SetFont(wxResourceInterpretFontSpec(expr->Nth(count)));
}
}
#if wxUSE_RADIOBTN
else if (controlType == wxT("wxRadioButton"))
{
// Check for default value
if (expr->Nth(count) && (expr->Nth(count)->Type() == PrologInteger))
{
controlItem->SetValue1(expr->Nth(count)->IntegerValue());
count ++;
if (expr->Nth(count) && expr->Nth(count)->Type() == PrologList)
controlItem->SetFont(wxResourceInterpretFontSpec(expr->Nth(count)));
}
}
#endif
else if (controlType == wxT("wxText") || controlType == wxT("wxTextCtrl") || controlType == wxT("wxMultiText"))
{
// Check for default value
if (expr->Nth(count) && ((expr->Nth(count)->Type() == PrologString) || (expr->Nth(count)->Type() == PrologWord)))
{
wxString str(expr->Nth(count)->StringValue());
controlItem->SetValue4(str);
count ++;
if (expr->Nth(count) && expr->Nth(count)->Type() == PrologList)
{
// controlItem->SetLabelFont(wxResourceInterpretFontSpec(expr->Nth(count)));
// Skip past the obsolete label font spec if there are two consecutive specs
if (expr->Nth(count+1) && expr->Nth(count+1)->Type() == PrologList)
count ++;
controlItem->SetFont(wxResourceInterpretFontSpec(expr->Nth(count)));
}
}
}
else if (controlType == wxT("wxMessage") || controlType == wxT("wxStaticText"))
{
// Check for bitmap resource name (in case it's an old-style .wxr file)
if (expr->Nth(count) && ((expr->Nth(count)->Type() == PrologString) || (expr->Nth(count)->Type() == PrologWord)))
{
wxString str(expr->Nth(count)->StringValue());
controlItem->SetValue4(str);
count ++;
controlItem->SetType(wxT("wxStaticText"));
}
if (expr->Nth(count) && expr->Nth(count)->Type() == PrologList)
controlItem->SetFont(wxResourceInterpretFontSpec(expr->Nth(count)));
}
else if (controlType == wxT("wxStaticBitmap"))
{
// Check for bitmap resource name
if (expr->Nth(count) && ((expr->Nth(count)->Type() == PrologString) || (expr->Nth(count)->Type() == PrologWord)))
{
wxString str(expr->Nth(count)->StringValue());
controlItem->SetValue4(str);
count ++;
}
if (expr->Nth(count) && expr->Nth(count)->Type() == PrologList)
controlItem->SetFont(wxResourceInterpretFontSpec(expr->Nth(count)));
}
else if (controlType == wxT("wxGroupBox") || controlType == wxT("wxStaticBox"))
{
if (expr->Nth(count) && expr->Nth(count)->Type() == PrologList)
controlItem->SetFont(wxResourceInterpretFontSpec(expr->Nth(count)));
}
else if (controlType == wxT("wxGauge"))
{
// Check for default value
if (expr->Nth(count) && (expr->Nth(count)->Type() == PrologInteger))
{
controlItem->SetValue1(expr->Nth(count)->IntegerValue());
count ++;
// Check for range
if (expr->Nth(count) && (expr->Nth(count)->Type() == PrologInteger))
{
controlItem->SetValue2(expr->Nth(count)->IntegerValue());
count ++;
if (expr->Nth(count) && expr->Nth(count)->Type() == PrologList)
{
// Skip past the obsolete label font spec if there are two consecutive specs
if (expr->Nth(count+1) && expr->Nth(count+1)->Type() == PrologList)
count ++;
controlItem->SetFont(wxResourceInterpretFontSpec(expr->Nth(count)));
}
}
}
}
else if (controlType == wxT("wxSlider"))
{
// Check for default value
if (expr->Nth(count) && (expr->Nth(count)->Type() == PrologInteger))
{
controlItem->SetValue1(expr->Nth(count)->IntegerValue());
count ++;
// Check for min
if (expr->Nth(count) && (expr->Nth(count)->Type() == PrologInteger))
{
controlItem->SetValue2(expr->Nth(count)->IntegerValue());
count ++;
// Check for max
if (expr->Nth(count) && (expr->Nth(count)->Type() == PrologInteger))
{
controlItem->SetValue3(expr->Nth(count)->IntegerValue());
count ++;
if (expr->Nth(count) && expr->Nth(count)->Type() == PrologList)
{
// controlItem->SetLabelFont(wxResourceInterpretFontSpec(expr->Nth(count)));
// do nothing
count ++;
if (expr->Nth(count) && expr->Nth(count)->Type() == PrologList)
controlItem->SetFont(wxResourceInterpretFontSpec(expr->Nth(count)));
}
}
}
}
}
else if (controlType == wxT("wxScrollBar"))
{
// DEFAULT VALUE
if (expr->Nth(count) && (expr->Nth(count)->Type() == PrologInteger))
{
controlItem->SetValue1(expr->Nth(count)->IntegerValue());
count ++;
// PAGE LENGTH
if (expr->Nth(count) && (expr->Nth(count)->Type() == PrologInteger))
{
controlItem->SetValue2(expr->Nth(count)->IntegerValue());
count ++;
// OBJECT LENGTH
if (expr->Nth(count) && (expr->Nth(count)->Type() == PrologInteger))
{
controlItem->SetValue3(expr->Nth(count)->IntegerValue());
count ++;
// VIEW LENGTH
if (expr->Nth(count) && (expr->Nth(count)->Type() == PrologInteger))
controlItem->SetValue5(expr->Nth(count)->IntegerValue());
}
}
}
}
else if (controlType == wxT("wxListBox"))
{
wxExpr *valueList = (wxExpr *) NULL;
if (((valueList = expr->Nth(count)) != 0) && (valueList->Type() == PrologList))
{
wxStringList stringList;
wxExpr *stringExpr = valueList->GetFirst();
while (stringExpr)
{
stringList.Add(stringExpr->StringValue());
stringExpr = stringExpr->GetNext();
}
controlItem->SetStringValues(stringList);
count ++;
// This is now obsolete: it's in the window style.
// Check for wxSINGLE/wxMULTIPLE
wxExpr *mult = (wxExpr *) NULL;
/*
controlItem->SetValue1(wxLB_SINGLE);
*/
if (((mult = expr->Nth(count)) != 0) && ((mult->Type() == PrologString)||(mult->Type() == PrologWord)))
{
/*
wxString m(mult->StringValue());
if (m == "wxLB_MULTIPLE")
controlItem->SetValue1(wxLB_MULTIPLE);
else if (m == "wxLB_EXTENDED")
controlItem->SetValue1(wxLB_EXTENDED);
*/
// Ignore the value
count ++;
}
if (expr->Nth(count) && expr->Nth(count)->Type() == PrologList)
{
// Skip past the obsolete label font spec if there are two consecutive specs
if (expr->Nth(count+1) && expr->Nth(count+1)->Type() == PrologList)
count ++;
controlItem->SetFont(wxResourceInterpretFontSpec(expr->Nth(count)));
}
}
}
else if (controlType == wxT("wxChoice"))
{
wxExpr *valueList = (wxExpr *) NULL;
// Check for default value list
if (((valueList = expr->Nth(count)) != 0) && (valueList->Type() == PrologList))
{
wxStringList stringList;
wxExpr *stringExpr = valueList->GetFirst();
while (stringExpr)
{
stringList.Add(stringExpr->StringValue());
stringExpr = stringExpr->GetNext();
}
controlItem->SetStringValues(stringList);
count ++;
if (expr->Nth(count) && expr->Nth(count)->Type() == PrologList)
{
// Skip past the obsolete label font spec if there are two consecutive specs
if (expr->Nth(count+1) && expr->Nth(count+1)->Type() == PrologList)
count ++;
controlItem->SetFont(wxResourceInterpretFontSpec(expr->Nth(count)));
}
}
}
#if wxUSE_COMBOBOX
else if (controlType == wxT("wxComboBox"))
{
wxExpr *textValue = expr->Nth(count);
if (textValue && (textValue->Type() == PrologString || textValue->Type() == PrologWord))
{
wxString str(textValue->StringValue());
controlItem->SetValue4(str);
count ++;
wxExpr *valueList = (wxExpr *) NULL;
// Check for default value list
if (((valueList = expr->Nth(count)) != 0) && (valueList->Type() == PrologList))
{
wxStringList stringList;
wxExpr *stringExpr = valueList->GetFirst();
while (stringExpr)
{
stringList.Add(stringExpr->StringValue());
stringExpr = stringExpr->GetNext();
}
controlItem->SetStringValues(stringList);
count ++;
if (expr->Nth(count) && expr->Nth(count)->Type() == PrologList)
{
// Skip past the obsolete label font spec if there are two consecutive specs
if (expr->Nth(count+1) && expr->Nth(count+1)->Type() == PrologList)
count ++;
controlItem->SetFont(wxResourceInterpretFontSpec(expr->Nth(count)));
}
}
}
}
#endif
#if 1
else if (controlType == wxT("wxRadioBox"))
{
wxExpr *valueList = (wxExpr *) NULL;
// Check for default value list
if (((valueList = expr->Nth(count)) != 0) && (valueList->Type() == PrologList))
{
wxStringList stringList;
wxExpr *stringExpr = valueList->GetFirst();
while (stringExpr)
{
stringList.Add(stringExpr->StringValue());
stringExpr = stringExpr->GetNext();
}
controlItem->SetStringValues(stringList);
count ++;
// majorDim (number of rows or cols)
if (expr->Nth(count) && (expr->Nth(count)->Type() == PrologInteger))
{
controlItem->SetValue1(expr->Nth(count)->IntegerValue());
count ++;
}
else
controlItem->SetValue1(0);
if (expr->Nth(count) && expr->Nth(count)->Type() == PrologList)
{
// Skip past the obsolete label font spec if there are two consecutive specs
if (expr->Nth(count+1) && expr->Nth(count+1)->Type() == PrologList)
count ++;
controlItem->SetFont(wxResourceInterpretFontSpec(expr->Nth(count)));
}
}
}
#endif
else
{
delete controlItem;
return (wxItemResource *) NULL;
}
return controlItem;
}
// Forward declaration
wxItemResource *wxResourceInterpretMenu1(wxResourceTable& table, wxExpr *expr);
/*
* Interpet a menu item
*/
wxItemResource *wxResourceInterpretMenuItem(wxResourceTable& table, wxExpr *expr)
{
wxItemResource *item = new wxItemResource;
wxExpr *labelExpr = expr->Nth(0);
wxExpr *idExpr = expr->Nth(1);
wxExpr *helpExpr = expr->Nth(2);
wxExpr *checkableExpr = expr->Nth(3);
// Further keywords/attributes to follow sometime...
if (expr->Number() == 0)
{
// item->SetType(wxRESOURCE_TYPE_SEPARATOR);
item->SetType(wxT("wxMenuSeparator"));
return item;
}
else
{
// item->SetType(wxTYPE_MENU); // Well, menu item, but doesn't matter.
item->SetType(wxT("wxMenu")); // Well, menu item, but doesn't matter.
if (labelExpr)
{
wxString str(labelExpr->StringValue());
item->SetTitle(str);
}
if (idExpr)
{
int id = 0;
// If a string or word, must look up in identifier table.
if ((idExpr->Type() == PrologString) || (idExpr->Type() == PrologWord))
{
wxString str(idExpr->StringValue());
id = wxResourceGetIdentifier(str, &table);
if (id == 0)
{
wxLogWarning(_("Could not resolve menu id '%s'. Use (non-zero) integer instead\nor provide #define (see manual for caveats)"),
(const wxChar*) idExpr->StringValue());
}
}
else if (idExpr->Type() == PrologInteger)
id = (int)idExpr->IntegerValue();
item->SetValue1(id);
}
if (helpExpr)
{
wxString str(helpExpr->StringValue());
item->SetValue4(str);
}
if (checkableExpr)
item->SetValue2(checkableExpr->IntegerValue());
// Find the first expression that's a list, for submenu
wxExpr *subMenuExpr = expr->GetFirst();
while (subMenuExpr && (subMenuExpr->Type() != PrologList))
subMenuExpr = subMenuExpr->GetNext();
while (subMenuExpr)
{
wxItemResource *child = wxResourceInterpretMenuItem(table, subMenuExpr);
item->GetChildren().Append(child);
subMenuExpr = subMenuExpr->GetNext();
}
}
return item;
}
/*
* Interpret a nested list as a menu
*/
/*
wxItemResource *wxResourceInterpretMenu1(wxResourceTable& table, wxExpr *expr)
{
wxItemResource *menu = new wxItemResource;
// menu->SetType(wxTYPE_MENU);
menu->SetType("wxMenu");
wxExpr *element = expr->GetFirst();
while (element)
{
wxItemResource *item = wxResourceInterpretMenuItem(table, element);
if (item)
menu->GetChildren().Append(item);
element = element->GetNext();
}
return menu;
}
*/
wxItemResource *wxResourceInterpretMenu(wxResourceTable& table, wxExpr *expr)
{
wxExpr *listExpr = (wxExpr *) NULL;
expr->GetAttributeValue(wxT("menu"), &listExpr);
if (!listExpr)
return (wxItemResource *) NULL;
wxItemResource *menuResource = wxResourceInterpretMenuItem(table, listExpr);
if (!menuResource)
return (wxItemResource *) NULL;
wxString name;
if (expr->GetAttributeValue(wxT("name"), name))
{
menuResource->SetName(name);
}
return menuResource;
}
wxItemResource *wxResourceInterpretMenuBar(wxResourceTable& table, wxExpr *expr)
{
wxExpr *listExpr = (wxExpr *) NULL;
expr->GetAttributeValue(wxT("menu"), &listExpr);
if (!listExpr)
return (wxItemResource *) NULL;
wxItemResource *resource = new wxItemResource;
resource->SetType(wxT("wxMenu"));
// resource->SetType(wxTYPE_MENU);
wxExpr *element = listExpr->GetFirst();
while (element)
{
wxItemResource *menuResource = wxResourceInterpretMenuItem(table, listExpr);
resource->GetChildren().Append(menuResource);
element = element->GetNext();
}
wxString name;
if (expr->GetAttributeValue(wxT("name"), name))
{
resource->SetName(name);
}
return resource;
}
wxItemResource *wxResourceInterpretString(wxResourceTable& WXUNUSED(table), wxExpr *WXUNUSED(expr))
{
return (wxItemResource *) NULL;
}
wxItemResource *wxResourceInterpretBitmap(wxResourceTable& WXUNUSED(table), wxExpr *expr)
{
wxItemResource *bitmapItem = new wxItemResource;
// bitmapItem->SetType(wxTYPE_BITMAP);
bitmapItem->SetType(wxT("wxBitmap"));
wxString name;
if (expr->GetAttributeValue(wxT("name"), name))
{
bitmapItem->SetName(name);
}
// Now parse all bitmap specifications
wxExpr *bitmapExpr = expr->GetFirst();
while (bitmapExpr)
{
if (bitmapExpr->Number() == 3)
{
wxString bitmapKeyword(bitmapExpr->Nth(1)->StringValue());
if (bitmapKeyword == wxT("bitmap") || bitmapKeyword == wxT("icon"))
{
// The value part: always a list.
wxExpr *listExpr = bitmapExpr->Nth(2);
if (listExpr->Type() == PrologList)
{
wxItemResource *bitmapSpec = new wxItemResource;
// bitmapSpec->SetType(wxTYPE_BITMAP);
bitmapSpec->SetType(wxT("wxBitmap"));
// List is of form: [filename, bitmaptype, platform, colours, xresolution, yresolution]
// where everything after 'filename' is optional.
wxExpr *nameExpr = listExpr->Nth(0);
wxExpr *typeExpr = listExpr->Nth(1);
wxExpr *platformExpr = listExpr->Nth(2);
wxExpr *coloursExpr = listExpr->Nth(3);
wxExpr *xresExpr = listExpr->Nth(4);
wxExpr *yresExpr = listExpr->Nth(5);
if (nameExpr && !nameExpr->StringValue().empty())
{
bitmapSpec->SetName(nameExpr->StringValue());
}
if (typeExpr && !typeExpr->StringValue().empty())
{
bitmapSpec->SetValue1(wxParseWindowStyle(typeExpr->StringValue()));
}
else
bitmapSpec->SetValue1(0);
if (platformExpr && !platformExpr->StringValue().empty())
{
wxString plat(platformExpr->StringValue());
if (plat == wxT("windows") || plat == wxT("WINDOWS"))
bitmapSpec->SetValue2(RESOURCE_PLATFORM_WINDOWS);
else if (plat == wxT("x") || plat == wxT("X"))
bitmapSpec->SetValue2(RESOURCE_PLATFORM_X);
else if (plat == wxT("mac") || plat == wxT("MAC"))
bitmapSpec->SetValue2(RESOURCE_PLATFORM_MAC);
else
bitmapSpec->SetValue2(RESOURCE_PLATFORM_ANY);
}
else
bitmapSpec->SetValue2(RESOURCE_PLATFORM_ANY);
if (coloursExpr)
bitmapSpec->SetValue3(coloursExpr->IntegerValue());
int xres = 0;
int yres = 0;
if (xresExpr)
xres = (int)xresExpr->IntegerValue();
if (yresExpr)
yres = (int)yresExpr->IntegerValue();
bitmapSpec->SetSize(0, 0, xres, yres);
bitmapItem->GetChildren().Append(bitmapSpec);
}
}
}
bitmapExpr = bitmapExpr->GetNext();
}
return bitmapItem;
}
wxItemResource *wxResourceInterpretIcon(wxResourceTable& table, wxExpr *expr)
{
wxItemResource *item = wxResourceInterpretBitmap(table, expr);
if (item)
{
// item->SetType(wxTYPE_ICON);
item->SetType(wxT("wxIcon"));
return item;
}
else
return (wxItemResource *) NULL;
}
// Interpret list expression as a font
wxFont wxResourceInterpretFontSpec(wxExpr *expr)
{
if (expr->Type() != PrologList)
return wxNullFont;
int point = 10;
int family = wxSWISS;
int style = wxNORMAL;
int weight = wxNORMAL;
int underline = 0;
wxString faceName;
wxExpr *pointExpr = expr->Nth(0);
wxExpr *familyExpr = expr->Nth(1);
wxExpr *styleExpr = expr->Nth(2);
wxExpr *weightExpr = expr->Nth(3);
wxExpr *underlineExpr = expr->Nth(4);
wxExpr *faceNameExpr = expr->Nth(5);
if (pointExpr)
point = (int)pointExpr->IntegerValue();
wxString str;
if (familyExpr)
{
str = familyExpr->StringValue();
family = (int)wxParseWindowStyle(str);
}
if (styleExpr)
{
str = styleExpr->StringValue();
style = (int)wxParseWindowStyle(str);
}
if (weightExpr)
{
str = weightExpr->StringValue();
weight = (int)wxParseWindowStyle(str);
}
if (underlineExpr)
underline = (int)underlineExpr->IntegerValue();
if (faceNameExpr)
faceName = faceNameExpr->StringValue();
return *wxTheFontList->FindOrCreateFont(point, family, style, weight,
(underline != 0), faceName);
}
/*
* (Re)allocate buffer for reading in from resource file
*/
bool wxReallocateResourceBuffer()
{
if (!wxResourceBuffer)
{
wxResourceBufferSize = 1000;
wxResourceBuffer = new char[wxResourceBufferSize];
return true;
}
if (wxResourceBuffer)
{
long newSize = wxResourceBufferSize + 1000;
char *tmp = new char[(int)newSize];
strncpy(tmp, wxResourceBuffer, (int)wxResourceBufferCount);
delete[] wxResourceBuffer;
wxResourceBuffer = tmp;
wxResourceBufferSize = newSize;
}
return true;
}
static bool wxEatWhiteSpace(FILE *fd)
{
int ch;
while ((ch = getc(fd)) != EOF)
{
switch (ch)
{
case ' ':
case 0x0a:
case 0x0d:
case 0x09:
break;
case '/':
{
int prev_ch = ch;
ch = getc(fd);
if (ch == EOF)
{
ungetc(prev_ch, fd);
return true;
}
if (ch == '*')
{
// Eat C comment
prev_ch = 0;
while ((ch = getc(fd)) != EOF)
{
if (ch == '/' && prev_ch == '*')
break;
prev_ch = ch;
}
}
else if (ch == '/')
{
// Eat C++ comment
static char buffer[255];
fgets(buffer, 255, fd);
}
else
{
ungetc(prev_ch, fd);
ungetc(ch, fd);
return true;
}
}
break;
default:
ungetc(ch, fd);
return true;
}
}
return false;
}
static bool wxEatWhiteSpace(wxInputStream *is)
{
char ch = is->GetC() ;
if ((ch != ' ') && (ch != '/') && (ch != ' ') && (ch != 10) && (ch != 13) && (ch != 9))
{
is->Ungetch(ch);
return true;
}
// Eat whitespace
while (ch == ' ' || ch == 10 || ch == 13 || ch == 9)
ch = is->GetC();
// Check for comment
if (ch == '/')
{
ch = is->GetC();
if (ch == '*')
{
bool finished = false;
while (!finished)
{
ch = is->GetC();
if (is->LastRead() == 0)
return false;
if (ch == '*')
{
int newCh = is->GetC();
if (newCh == '/')
finished = true;
else
{
is->Ungetch(ch);
}
}
}
}
else // False alarm
return false;
}
else
is->Ungetch(ch);
return wxEatWhiteSpace(is);
}
bool wxGetResourceToken(FILE *fd)
{
if (!wxResourceBuffer)
wxReallocateResourceBuffer();
wxResourceBuffer[0] = 0;
wxEatWhiteSpace(fd);
int ch = getc(fd);
if (ch == '"')
{
// Get string
wxResourceBufferCount = 0;
ch = getc(fd);
while (ch != '"')
{
int actualCh = ch;
if (ch == EOF)
{
wxResourceBuffer[wxResourceBufferCount] = 0;
return false;
}
// Escaped characters
else if (ch == '\\')
{
int newCh = getc(fd);
if (newCh == '"')
actualCh = '"';
else if (newCh == 10)
actualCh = 10;
else
{
ungetc(newCh, fd);
}
}
if (wxResourceBufferCount >= wxResourceBufferSize-1)
wxReallocateResourceBuffer();
wxResourceBuffer[wxResourceBufferCount] = (char)actualCh;
wxResourceBufferCount ++;
ch = getc(fd);
}
wxResourceBuffer[wxResourceBufferCount] = 0;
}
else
{
wxResourceBufferCount = 0;
// Any other token
while (ch != ' ' && ch != EOF && ch != ' ' && ch != 13 && ch != 9 && ch != 10)
{
if (wxResourceBufferCount >= wxResourceBufferSize-1)
wxReallocateResourceBuffer();
wxResourceBuffer[wxResourceBufferCount] = (char)ch;
wxResourceBufferCount ++;
ch = getc(fd);
}
wxResourceBuffer[wxResourceBufferCount] = 0;
if (ch == EOF)
return false;
}
return true;
}
bool wxGetResourceToken(wxInputStream *is)
{
if (!wxResourceBuffer)
wxReallocateResourceBuffer();
wxResourceBuffer[0] = 0;
wxEatWhiteSpace(is);
int ch = is->GetC() ;
if (ch == '"')
{
// Get string
wxResourceBufferCount = 0;
ch = is->GetC();
while (ch != '"')
{
int actualCh = ch;
if (ch == EOF)
{
wxResourceBuffer[wxResourceBufferCount] = 0;
return false;
}
// Escaped characters
else if (ch == '\\')
{
char newCh = is->GetC();
if (newCh == '"')
actualCh = '"';
else if (newCh == 10)
actualCh = 10;
else if (newCh == 13) // mac
actualCh = 10;
else
{
is->Ungetch(newCh);
}
}
if (wxResourceBufferCount >= wxResourceBufferSize-1)
wxReallocateResourceBuffer();
wxResourceBuffer[wxResourceBufferCount] = (char)actualCh;
wxResourceBufferCount ++;
ch = is->GetC();
}
wxResourceBuffer[wxResourceBufferCount] = 0;
}
else
{
wxResourceBufferCount = 0;
// Any other token
while (ch != ' ' && ch != EOF && ch != ' ' && ch != 13 && ch != 9 && ch != 10)
{
if (wxResourceBufferCount >= wxResourceBufferSize-1)
wxReallocateResourceBuffer();
wxResourceBuffer[wxResourceBufferCount] = (char)ch;
wxResourceBufferCount ++;
ch = is->GetC();
}
wxResourceBuffer[wxResourceBufferCount] = 0;
if (ch == EOF)
return false;
}
return true;
}
/*
* Files are in form:
static char *name = "....";
with possible comments.
*/
bool wxResourceReadOneResource(FILE *fd, wxExprDatabase& db, bool *eof, wxResourceTable *table)
{
if (!table)
table = wxDefaultResourceTable;
// static or #define
if (!wxGetResourceToken(fd))
{
*eof = true;
return false;
}
if (strcmp(wxResourceBuffer, "#define") == 0)
{
wxGetResourceToken(fd);
wxChar *name = copystring(wxConvCurrent->cMB2WX(wxResourceBuffer));
wxGetResourceToken(fd);
wxChar *value = copystring(wxConvCurrent->cMB2WX(wxResourceBuffer));
if (wxIsdigit(value[0]))
{
int val = (int)wxAtol(value);
wxResourceAddIdentifier(name, val, table);
}
else
{
wxLogWarning(_("#define %s must be an integer."), name);
delete[] name;
delete[] value;
return false;
}
delete[] name;
delete[] value;
return true;
}
else if (strcmp(wxResourceBuffer, "#include") == 0)
{
wxGetResourceToken(fd);
wxChar *name = copystring(wxConvCurrent->cMB2WX(wxResourceBuffer));
wxChar *actualName = name;
if (name[0] == wxT('"'))
actualName = name + 1;
int len = wxStrlen(name);
if ((len > 0) && (name[len-1] == wxT('"')))
name[len-1] = 0;
if (!wxResourceParseIncludeFile(actualName, table))
{
wxLogWarning(_("Could not find resource include file %s."), actualName);
}
delete[] name;
return true;
}
else if (strcmp(wxResourceBuffer, "static") != 0)
{
wxChar buf[300];
wxStrcpy(buf, _("Found "));
wxStrncat(buf, wxConvCurrent->cMB2WX(wxResourceBuffer), 30);
wxStrcat(buf, _(", expected static, #include or #define\nwhile parsing resource."));
wxLogWarning(buf);
return false;
}
// char
if (!wxGetResourceToken(fd))
{
wxLogWarning(_("Unexpected end of file while parsing resource."));
*eof = true;
return false;
}
if (strcmp(wxResourceBuffer, "char") != 0)
{
wxLogWarning(_("Expected 'char' while parsing resource."));
return false;
}
// *name
if (!wxGetResourceToken(fd))
{
wxLogWarning(_("Unexpected end of file while parsing resource."));
*eof = true;
return false;
}
if (wxResourceBuffer[0] != '*')
{
wxLogWarning(_("Expected '*' while parsing resource."));
return false;
}
wxChar nameBuf[100];
wxMB2WX(nameBuf, wxResourceBuffer+1, 99);
nameBuf[99] = 0;
// =
if (!wxGetResourceToken(fd))
{
wxLogWarning(_("Unexpected end of file while parsing resource."));
*eof = true;
return false;
}
if (strcmp(wxResourceBuffer, "=") != 0)
{
wxLogWarning(_("Expected '=' while parsing resource."));
return false;
}
// String
if (!wxGetResourceToken(fd))
{
wxLogWarning(_("Unexpected end of file while parsing resource."));
*eof = true;
return false;
}
else
{
if (!db.ReadPrologFromString(wxResourceBuffer))
{
wxLogWarning(_("%s: ill-formed resource file syntax."), nameBuf);
return false;
}
}
// Semicolon
if (!wxGetResourceToken(fd))
{
*eof = true;
}
return true;
}
bool wxResourceReadOneResource(wxInputStream *fd, wxExprDatabase& db, bool *eof, wxResourceTable *table)
{
if (!table)
table = wxDefaultResourceTable;
// static or #define
if (!wxGetResourceToken(fd))
{
*eof = true;
return false;
}
if (strcmp(wxResourceBuffer, "#define") == 0)
{
wxGetResourceToken(fd);
wxChar *name = copystring(wxConvLibc.cMB2WX(wxResourceBuffer));
wxGetResourceToken(fd);
wxChar *value = copystring(wxConvLibc.cMB2WX(wxResourceBuffer));
if (wxIsalpha(value[0]))
{
int val = (int)wxAtol(value);
wxResourceAddIdentifier(name, val, table);
}
else
{
wxLogWarning(_("#define %s must be an integer."), name);
delete[] name;
delete[] value;
return false;
}
delete[] name;
delete[] value;
return true;
}
else if (strcmp(wxResourceBuffer, "#include") == 0)
{
wxGetResourceToken(fd);
wxChar *name = copystring(wxConvLibc.cMB2WX(wxResourceBuffer));
wxChar *actualName = name;
if (name[0] == wxT('"'))
actualName = name + 1;
int len = wxStrlen(name);
if ((len > 0) && (name[len-1] == wxT('"')))
name[len-1] = 0;
if (!wxResourceParseIncludeFile(actualName, table))
{
wxLogWarning(_("Could not find resource include file %s."), actualName);
}
delete[] name;
return true;
}
else if (strcmp(wxResourceBuffer, "static") != 0)
{
wxChar buf[300];
wxStrcpy(buf, _("Found "));
wxStrncat(buf, wxConvLibc.cMB2WX(wxResourceBuffer), 30);
wxStrcat(buf, _(", expected static, #include or #define\nwhile parsing resource."));
wxLogWarning(buf);
return false;
}
// char
if (!wxGetResourceToken(fd))
{
wxLogWarning(_("Unexpected end of file while parsing resource."));
*eof = true;
return false;
}
if (strcmp(wxResourceBuffer, "char") != 0)
{
wxLogWarning(_("Expected 'char' while parsing resource."));
return false;
}
// *name
if (!wxGetResourceToken(fd))
{
wxLogWarning(_("Unexpected end of file while parsing resource."));
*eof = true;
return false;
}
if (wxResourceBuffer[0] != '*')
{
wxLogWarning(_("Expected '*' while parsing resource."));
return false;
}
char nameBuf[100];
strncpy(nameBuf, wxResourceBuffer+1, 99);
// =
if (!wxGetResourceToken(fd))
{
wxLogWarning(_("Unexpected end of file while parsing resource."));
*eof = true;
return false;
}
if (strcmp(wxResourceBuffer, "=") != 0)
{
wxLogWarning(_("Expected '=' while parsing resource."));
return false;
}
// String
if (!wxGetResourceToken(fd))
{
wxLogWarning(_("Unexpected end of file while parsing resource."));
*eof = true;
return false;
}
else
{
if (!db.ReadPrologFromString(wxResourceBuffer))
{
wxLogWarning(_("%s: ill-formed resource file syntax."), nameBuf);
return false;
}
}
// Semicolon
if (!wxGetResourceToken(fd))
{
*eof = true;
}
return true;
}
/*
* Parses string window style into integer window style
*/
/*
* Style flag parsing, e.g.
* "wxSYSTEM_MENU | wxBORDER" -> integer
*/
wxChar* wxResourceParseWord(wxChar*s, int *i)
{
if (!s)
return (wxChar*) NULL;
static wxChar buf[150];
int len = wxStrlen(s);
int j = 0;
int ii = *i;
while ((ii < len) && (wxIsalpha(s[ii]) || (s[ii] == wxT('_'))))
{
buf[j] = s[ii];
j ++;
ii ++;
}
buf[j] = 0;
// Eat whitespace and conjunction characters
while ((ii < len) &&
((s[ii] == wxT(' ')) || (s[ii] == wxT('|')) || (s[ii] == wxT(','))))
{
ii ++;
}
*i = ii;
if (j == 0)
return (wxChar*) NULL;
else
return buf;
}
struct wxResourceBitListStruct
{
const wxChar *word;
long bits;
};
static wxResourceBitListStruct wxResourceBitListTable[] =
{
/* wxListBox */
{ wxT("wxSINGLE"), wxLB_SINGLE },
{ wxT("wxMULTIPLE"), wxLB_MULTIPLE },
{ wxT("wxEXTENDED"), wxLB_EXTENDED },
{ wxT("wxLB_SINGLE"), wxLB_SINGLE },
{ wxT("wxLB_MULTIPLE"), wxLB_MULTIPLE },
{ wxT("wxLB_EXTENDED"), wxLB_EXTENDED },
{ wxT("wxLB_NEEDED_SB"), wxLB_NEEDED_SB },
{ wxT("wxLB_ALWAYS_SB"), wxLB_ALWAYS_SB },
{ wxT("wxLB_SORT"), wxLB_SORT },
{ wxT("wxLB_OWNERDRAW"), wxLB_OWNERDRAW },
{ wxT("wxLB_HSCROLL"), wxLB_HSCROLL },
/* wxComboxBox */
{ wxT("wxCB_SIMPLE"), wxCB_SIMPLE },
{ wxT("wxCB_DROPDOWN"), wxCB_DROPDOWN },
{ wxT("wxCB_READONLY"), wxCB_READONLY },
{ wxT("wxCB_SORT"), wxCB_SORT },
/* wxGauge */
{ wxT("wxGA_PROGRESSBAR"), wxGA_PROGRESSBAR },
{ wxT("wxGA_HORIZONTAL"), wxGA_HORIZONTAL },
{ wxT("wxGA_VERTICAL"), wxGA_VERTICAL },
/* wxTextCtrl */
{ wxT("wxPASSWORD"), wxPASSWORD},
{ wxT("wxPROCESS_ENTER"), wxPROCESS_ENTER},
{ wxT("wxTE_PASSWORD"), wxTE_PASSWORD},
{ wxT("wxTE_READONLY"), wxTE_READONLY},
{ wxT("wxTE_PROCESS_ENTER"), wxTE_PROCESS_ENTER},
{ wxT("wxTE_MULTILINE"), wxTE_MULTILINE},
{ wxT("wxTE_NO_VSCROLL"), wxTE_NO_VSCROLL},
/* wxRadioBox/wxRadioButton */
{ wxT("wxRB_GROUP"), wxRB_GROUP },
{ wxT("wxRA_SPECIFY_COLS"), wxRA_SPECIFY_COLS },
{ wxT("wxRA_SPECIFY_ROWS"), wxRA_SPECIFY_ROWS },
{ wxT("wxRA_HORIZONTAL"), wxRA_HORIZONTAL },
{ wxT("wxRA_VERTICAL"), wxRA_VERTICAL },
/* wxSlider */
{ wxT("wxSL_HORIZONTAL"), wxSL_HORIZONTAL },
{ wxT("wxSL_VERTICAL"), wxSL_VERTICAL },
{ wxT("wxSL_AUTOTICKS"), wxSL_AUTOTICKS },
{ wxT("wxSL_LABELS"), wxSL_LABELS },
{ wxT("wxSL_LEFT"), wxSL_LEFT },
{ wxT("wxSL_TOP"), wxSL_TOP },
{ wxT("wxSL_RIGHT"), wxSL_RIGHT },
{ wxT("wxSL_BOTTOM"), wxSL_BOTTOM },
{ wxT("wxSL_BOTH"), wxSL_BOTH },
{ wxT("wxSL_SELRANGE"), wxSL_SELRANGE },
/* wxScrollBar */
{ wxT("wxSB_HORIZONTAL"), wxSB_HORIZONTAL },
{ wxT("wxSB_VERTICAL"), wxSB_VERTICAL },
/* wxButton */
{ wxT("wxBU_AUTODRAW"), wxBU_AUTODRAW },
{ wxT("wxBU_NOAUTODRAW"), wxBU_NOAUTODRAW },
/* wxTreeCtrl */
{ wxT("wxTR_HAS_BUTTONS"), wxTR_HAS_BUTTONS },
{ wxT("wxTR_EDIT_LABELS"), wxTR_EDIT_LABELS },
{ wxT("wxTR_LINES_AT_ROOT"), wxTR_LINES_AT_ROOT },
/* wxListCtrl */
{ wxT("wxLC_ICON"), wxLC_ICON },
{ wxT("wxLC_SMALL_ICON"), wxLC_SMALL_ICON },
{ wxT("wxLC_LIST"), wxLC_LIST },
{ wxT("wxLC_REPORT"), wxLC_REPORT },
{ wxT("wxLC_ALIGN_TOP"), wxLC_ALIGN_TOP },
{ wxT("wxLC_ALIGN_LEFT"), wxLC_ALIGN_LEFT },
{ wxT("wxLC_AUTOARRANGE"), wxLC_AUTOARRANGE },
{ wxT("wxLC_USER_TEXT"), wxLC_USER_TEXT },
{ wxT("wxLC_EDIT_LABELS"), wxLC_EDIT_LABELS },
{ wxT("wxLC_NO_HEADER"), wxLC_NO_HEADER },
{ wxT("wxLC_NO_SORT_HEADER"), wxLC_NO_SORT_HEADER },
{ wxT("wxLC_SINGLE_SEL"), wxLC_SINGLE_SEL },
{ wxT("wxLC_SORT_ASCENDING"), wxLC_SORT_ASCENDING },
{ wxT("wxLC_SORT_DESCENDING"), wxLC_SORT_DESCENDING },
/* wxSpinButton */
{ wxT("wxSP_VERTICAL"), wxSP_VERTICAL},
{ wxT("wxSP_HORIZONTAL"), wxSP_HORIZONTAL},
{ wxT("wxSP_ARROW_KEYS"), wxSP_ARROW_KEYS},
{ wxT("wxSP_WRAP"), wxSP_WRAP},
/* wxSplitterWnd */
{ wxT("wxSP_NOBORDER"), wxSP_NOBORDER},
{ wxT("wxSP_3D"), wxSP_3D},
{ wxT("wxSP_BORDER"), wxSP_BORDER},
/* wxTabCtrl */
{ wxT("wxTC_MULTILINE"), wxTC_MULTILINE},
{ wxT("wxTC_RIGHTJUSTIFY"), wxTC_RIGHTJUSTIFY},
{ wxT("wxTC_FIXEDWIDTH"), wxTC_FIXEDWIDTH},
{ wxT("wxTC_OWNERDRAW"), wxTC_OWNERDRAW},
/* wxStatusBar95 */
{ wxT("wxST_SIZEGRIP"), wxST_SIZEGRIP},
/* wxControl */
{ wxT("wxFIXED_LENGTH"), wxFIXED_LENGTH},
{ wxT("wxALIGN_LEFT"), wxALIGN_LEFT},
{ wxT("wxALIGN_CENTER"), wxALIGN_CENTER},
{ wxT("wxALIGN_CENTRE"), wxALIGN_CENTRE},
{ wxT("wxALIGN_RIGHT"), wxALIGN_RIGHT},
{ wxT("wxCOLOURED"), wxCOLOURED},
/* wxToolBar */
{ wxT("wxTB_3DBUTTONS"), wxTB_3DBUTTONS},
{ wxT("wxTB_HORIZONTAL"), wxTB_HORIZONTAL},
{ wxT("wxTB_VERTICAL"), wxTB_VERTICAL},
{ wxT("wxTB_FLAT"), wxTB_FLAT},
/* wxDialog */
{ wxT("wxDIALOG_MODAL"), wxDIALOG_MODAL },
/* Generic */
{ wxT("wxVSCROLL"), wxVSCROLL },
{ wxT("wxHSCROLL"), wxHSCROLL },
{ wxT("wxCAPTION"), wxCAPTION },
{ wxT("wxSTAY_ON_TOP"), wxSTAY_ON_TOP},
{ wxT("wxICONIZE"), wxICONIZE},
{ wxT("wxMINIMIZE"), wxICONIZE},
{ wxT("wxMAXIMIZE"), wxMAXIMIZE},
{ wxT("wxSDI"), 0},
{ wxT("wxMDI_PARENT"), 0},
{ wxT("wxMDI_CHILD"), 0},
{ wxT("wxTHICK_FRAME"), wxTHICK_FRAME},
{ wxT("wxRESIZE_BORDER"), wxRESIZE_BORDER},
{ wxT("wxSYSTEM_MENU"), wxSYSTEM_MENU},
{ wxT("wxMINIMIZE_BOX"), wxMINIMIZE_BOX},
{ wxT("wxMAXIMIZE_BOX"), wxMAXIMIZE_BOX},
{ wxT("wxRESIZE_BOX"), wxRESIZE_BOX},
{ wxT("wxDEFAULT_FRAME_STYLE"), wxDEFAULT_FRAME_STYLE},
{ wxT("wxDEFAULT_FRAME"), wxDEFAULT_FRAME_STYLE},
{ wxT("wxDEFAULT_DIALOG_STYLE"), wxDEFAULT_DIALOG_STYLE},
{ wxT("wxBORDER"), wxBORDER},
{ wxT("wxRETAINED"), wxRETAINED},
{ wxT("wxNATIVE_IMPL"), 0},
{ wxT("wxEXTENDED_IMPL"), 0},
{ wxT("wxBACKINGSTORE"), wxBACKINGSTORE},
// { wxT("wxFLAT"), wxFLAT},
// { wxT("wxMOTIF_RESIZE"), wxMOTIF_RESIZE},
{ wxT("wxFIXED_LENGTH"), 0},
{ wxT("wxDOUBLE_BORDER"), wxDOUBLE_BORDER},
{ wxT("wxSUNKEN_BORDER"), wxSUNKEN_BORDER},
{ wxT("wxRAISED_BORDER"), wxRAISED_BORDER},
{ wxT("wxSIMPLE_BORDER"), wxSIMPLE_BORDER},
{ wxT("wxSTATIC_BORDER"), wxSTATIC_BORDER},
{ wxT("wxTRANSPARENT_WINDOW"), wxTRANSPARENT_WINDOW},
{ wxT("wxNO_BORDER"), wxNO_BORDER},
{ wxT("wxCLIP_CHILDREN"), wxCLIP_CHILDREN},
{ wxT("wxCLIP_SIBLINGS"), wxCLIP_SIBLINGS},
{ wxT("wxTAB_TRAVERSAL"), 0}, // Compatibility only
{ wxT("wxTINY_CAPTION_HORIZ"), wxTINY_CAPTION_HORIZ},
{ wxT("wxTINY_CAPTION_VERT"), wxTINY_CAPTION_VERT},
// Text font families
{ wxT("wxDEFAULT"), wxDEFAULT},
{ wxT("wxDECORATIVE"), wxDECORATIVE},
{ wxT("wxROMAN"), wxROMAN},
{ wxT("wxSCRIPT"), wxSCRIPT},
{ wxT("wxSWISS"), wxSWISS},
{ wxT("wxMODERN"), wxMODERN},
{ wxT("wxTELETYPE"), wxTELETYPE},
{ wxT("wxVARIABLE"), wxVARIABLE},
{ wxT("wxFIXED"), wxFIXED},
{ wxT("wxNORMAL"), wxNORMAL},
{ wxT("wxLIGHT"), wxLIGHT},
{ wxT("wxBOLD"), wxBOLD},
{ wxT("wxITALIC"), wxITALIC},
{ wxT("wxSLANT"), wxSLANT},
{ wxT("wxSOLID"), wxSOLID},
{ wxT("wxDOT"), wxDOT},
{ wxT("wxLONG_DASH"), wxLONG_DASH},
{ wxT("wxSHORT_DASH"), wxSHORT_DASH},
{ wxT("wxDOT_DASH"), wxDOT_DASH},
{ wxT("wxUSER_DASH"), wxUSER_DASH},
{ wxT("wxTRANSPARENT"), wxTRANSPARENT},
{ wxT("wxSTIPPLE"), wxSTIPPLE},
{ wxT("wxBDIAGONAL_HATCH"), wxBDIAGONAL_HATCH},
{ wxT("wxCROSSDIAG_HATCH"), wxCROSSDIAG_HATCH},
{ wxT("wxFDIAGONAL_HATCH"), wxFDIAGONAL_HATCH},
{ wxT("wxCROSS_HATCH"), wxCROSS_HATCH},
{ wxT("wxHORIZONTAL_HATCH"), wxHORIZONTAL_HATCH},
{ wxT("wxVERTICAL_HATCH"), wxVERTICAL_HATCH},
{ wxT("wxJOIN_BEVEL"), wxJOIN_BEVEL},
{ wxT("wxJOIN_MITER"), wxJOIN_MITER},
{ wxT("wxJOIN_ROUND"), wxJOIN_ROUND},
{ wxT("wxCAP_ROUND"), wxCAP_ROUND},
{ wxT("wxCAP_PROJECTING"), wxCAP_PROJECTING},
{ wxT("wxCAP_BUTT"), wxCAP_BUTT},
// Logical ops
{ wxT("wxCLEAR"), wxCLEAR},
{ wxT("wxXOR"), wxXOR},
{ wxT("wxINVERT"), wxINVERT},
{ wxT("wxOR_REVERSE"), wxOR_REVERSE},
{ wxT("wxAND_REVERSE"), wxAND_REVERSE},
{ wxT("wxCOPY"), wxCOPY},
{ wxT("wxAND"), wxAND},
{ wxT("wxAND_INVERT"), wxAND_INVERT},
{ wxT("wxNO_OP"), wxNO_OP},
{ wxT("wxNOR"), wxNOR},
{ wxT("wxEQUIV"), wxEQUIV},
{ wxT("wxSRC_INVERT"), wxSRC_INVERT},
{ wxT("wxOR_INVERT"), wxOR_INVERT},
{ wxT("wxNAND"), wxNAND},
{ wxT("wxOR"), wxOR},
{ wxT("wxSET"), wxSET},
{ wxT("wxFLOOD_SURFACE"), wxFLOOD_SURFACE},
{ wxT("wxFLOOD_BORDER"), wxFLOOD_BORDER},
{ wxT("wxODDEVEN_RULE"), wxODDEVEN_RULE},
{ wxT("wxWINDING_RULE"), wxWINDING_RULE},
{ wxT("wxHORIZONTAL"), wxHORIZONTAL},
{ wxT("wxVERTICAL"), wxVERTICAL},
{ wxT("wxBOTH"), wxBOTH},
{ wxT("wxCENTER_FRAME"), wxCENTER_FRAME},
{ wxT("wxOK"), wxOK},
{ wxT("wxYES_NO"), wxYES_NO},
{ wxT("wxCANCEL"), wxCANCEL},
{ wxT("wxYES"), wxYES},
{ wxT("wxNO"), wxNO},
{ wxT("wxICON_EXCLAMATION"), wxICON_EXCLAMATION},
{ wxT("wxICON_HAND"), wxICON_HAND},
{ wxT("wxICON_QUESTION"), wxICON_QUESTION},
{ wxT("wxICON_INFORMATION"), wxICON_INFORMATION},
{ wxT("wxICON_STOP"), wxICON_STOP},
{ wxT("wxICON_ASTERISK"), wxICON_ASTERISK},
{ wxT("wxICON_MASK"), wxICON_MASK},
{ wxT("wxCENTRE"), wxCENTRE},
{ wxT("wxCENTER"), wxCENTRE},
{ wxT("wxUSER_COLOURS"), wxUSER_COLOURS},
{ wxT("wxVERTICAL_LABEL"), 0},
{ wxT("wxHORIZONTAL_LABEL"), 0},
// Bitmap types (not strictly styles)
{ wxT("wxBITMAP_TYPE_XPM"), wxBITMAP_TYPE_XPM},
{ wxT("wxBITMAP_TYPE_XBM"), wxBITMAP_TYPE_XBM},
{ wxT("wxBITMAP_TYPE_BMP"), wxBITMAP_TYPE_BMP},
{ wxT("wxBITMAP_TYPE_RESOURCE"), wxBITMAP_TYPE_BMP_RESOURCE},
{ wxT("wxBITMAP_TYPE_BMP_RESOURCE"), wxBITMAP_TYPE_BMP_RESOURCE},
{ wxT("wxBITMAP_TYPE_GIF"), wxBITMAP_TYPE_GIF},
{ wxT("wxBITMAP_TYPE_TIF"), wxBITMAP_TYPE_TIF},
{ wxT("wxBITMAP_TYPE_ICO"), wxBITMAP_TYPE_ICO},
{ wxT("wxBITMAP_TYPE_ICO_RESOURCE"), wxBITMAP_TYPE_ICO_RESOURCE},
{ wxT("wxBITMAP_TYPE_CUR"), wxBITMAP_TYPE_CUR},
{ wxT("wxBITMAP_TYPE_CUR_RESOURCE"), wxBITMAP_TYPE_CUR_RESOURCE},
{ wxT("wxBITMAP_TYPE_XBM_DATA"), wxBITMAP_TYPE_XBM_DATA},
{ wxT("wxBITMAP_TYPE_XPM_DATA"), wxBITMAP_TYPE_XPM_DATA},
{ wxT("wxBITMAP_TYPE_ANY"), wxBITMAP_TYPE_ANY}
};
static int wxResourceBitListCount = (sizeof(wxResourceBitListTable)/sizeof(wxResourceBitListStruct));
long wxParseWindowStyle(const wxString& bitListString)
{
int i = 0;
wxChar *word;
long bitList = 0;
word = wxResourceParseWord(WXSTRINGCAST bitListString, &i);
while (word != NULL)
{
bool found = false;
int j;
for (j = 0; j < wxResourceBitListCount; j++)
if (wxStrcmp(wxResourceBitListTable[j].word, word) == 0)
{
bitList |= wxResourceBitListTable[j].bits;
found = true;
break;
}
if (!found)
{
wxLogWarning(_("Unrecognized style %s while parsing resource."), word);
return 0;
}
word = wxResourceParseWord(WXSTRINGCAST bitListString, &i);
}
return bitList;
}
/*
* Load a bitmap from a wxWidgets resource, choosing an optimum
* depth and appropriate type.
*/
wxBitmap wxResourceCreateBitmap(const wxString& resource, wxResourceTable *table)
{
if (!table)
table = wxDefaultResourceTable;
wxItemResource *item = table->FindResource(resource);
if (item)
{
if ((item->GetType().empty()) || (item->GetType() != wxT("wxBitmap")))
{
wxLogWarning(_("%s not a bitmap resource specification."), (const wxChar*) resource);
return wxNullBitmap;
}
int thisDepth = wxDisplayDepth();
long thisNoColours = (long)pow(2.0, (double)thisDepth);
wxItemResource *optResource = (wxItemResource *) NULL;
// Try to find optimum bitmap for this platform/colour depth
wxNode *node = item->GetChildren().GetFirst();
while (node)
{
wxItemResource *child = (wxItemResource *)node->GetData();
int platform = (int)child->GetValue2();
int noColours = (int)child->GetValue3();
/*
char *name = child->GetName();
int bitmapType = (int)child->GetValue1();
int xRes = child->GetWidth();
int yRes = child->GetHeight();
*/
switch (platform)
{
case RESOURCE_PLATFORM_ANY:
{
if (!optResource && ((noColours == 0) || (noColours <= thisNoColours)))
optResource = child;
else
{
// Maximise the number of colours.
// If noColours is zero (unspecified), then assume this
// is the right one.
if ((noColours == 0) || ((noColours <= thisNoColours) && (noColours > optResource->GetValue3())))
optResource = child;
}
break;
}
#ifdef __WXMSW__
case RESOURCE_PLATFORM_WINDOWS:
{
if (!optResource && ((noColours == 0) || (noColours <= thisNoColours)))
optResource = child;
else
{
// Maximise the number of colours
if ((noColours > 0) || ((noColours <= thisNoColours) && (noColours > optResource->GetValue3())))
optResource = child;
}
break;
}
#endif
#ifdef __WXGTK__
case RESOURCE_PLATFORM_X:
{
if (!optResource && ((noColours == 0) || (noColours <= thisNoColours)))
optResource = child;
else
{
// Maximise the number of colours
if ((noColours == 0) || ((noColours <= thisNoColours) && (noColours > optResource->GetValue3())))
optResource = child;
}
break;
}
#endif
#ifdef wx_max
case RESOURCE_PLATFORM_MAC:
{
if (!optResource && ((noColours == 0) || (noColours <= thisNoColours)))
optResource = child;
else
{
// Maximise the number of colours
if ((noColours == 0) || ((noColours <= thisNoColours) && (noColours > optResource->GetValue3())))
optResource = child;
}
break;
}
#endif
default:
break;
}
node = node->GetNext();
}
// If no matching resource, fail.
if (!optResource)
return wxNullBitmap;
wxString name = optResource->GetName();
int bitmapType = (int)optResource->GetValue1();
switch (bitmapType)
{
case wxBITMAP_TYPE_XBM_DATA:
{
#ifdef __WXGTK__
wxItemResource *item = table->FindResource(name);
if (!item)
{
wxLogWarning(_("Failed to find XBM resource %s.\n"
"Forgot to use wxResourceLoadBitmapData?"), (const wxChar*) name);
return wxNullBitmap;
}
return wxBitmap(item->GetValue1(), (int)item->GetValue2(), (int)item->GetValue3()) ;
#else
wxLogWarning(_("No XBM facility available!"));
break;
#endif
}
case wxBITMAP_TYPE_XPM_DATA:
{
wxItemResource *item = table->FindResource(name);
if (!item)
{
wxLogWarning(_("Failed to find XPM resource %s.\nForgot to use wxResourceLoadBitmapData?"), (const wxChar*) name);
return wxNullBitmap;
}
return wxBitmap((char **)item->GetValue1());
}
default:
{
#if defined(__WXPM__)
return wxNullBitmap;
#else
return wxBitmap(name, (wxBitmapType)bitmapType);
#endif
}
}
#ifndef __WXGTK__
return wxNullBitmap;
#endif
}
else
{
wxLogWarning(_("Bitmap resource specification %s not found."), (const wxChar*) resource);
return wxNullBitmap;
}
}
/*
* Load an icon from a wxWidgets resource, choosing an optimum
* depth and appropriate type.
*/
wxIcon wxResourceCreateIcon(const wxString& resource, wxResourceTable *table)
{
if (!table)
table = wxDefaultResourceTable;
wxItemResource *item = table->FindResource(resource);
if (item)
{
if ((item->GetType().empty()) || wxStrcmp(item->GetType(), wxT("wxIcon")) != 0)
{
wxLogWarning(_("%s not an icon resource specification."), (const wxChar*) resource);
return wxNullIcon;
}
int thisDepth = wxDisplayDepth();
long thisNoColours = (long)pow(2.0, (double)thisDepth);
wxItemResource *optResource = (wxItemResource *) NULL;
// Try to find optimum icon for this platform/colour depth
wxNode *node = item->GetChildren().GetFirst();
while (node)
{
wxItemResource *child = (wxItemResource *)node->GetData();
int platform = (int)child->GetValue2();
int noColours = (int)child->GetValue3();
/*
char *name = child->GetName();
int bitmapType = (int)child->GetValue1();
int xRes = child->GetWidth();
int yRes = child->GetHeight();
*/
switch (platform)
{
case RESOURCE_PLATFORM_ANY:
{
if (!optResource && ((noColours == 0) || (noColours <= thisNoColours)))
optResource = child;
else
{
// Maximise the number of colours.
// If noColours is zero (unspecified), then assume this
// is the right one.
if ((noColours == 0) || ((noColours <= thisNoColours) && (noColours > optResource->GetValue3())))
optResource = child;
}
break;
}
#ifdef __WXMSW__
case RESOURCE_PLATFORM_WINDOWS:
{
if (!optResource && ((noColours == 0) || (noColours <= thisNoColours)))
optResource = child;
else
{
// Maximise the number of colours
if ((noColours > 0) || ((noColours <= thisNoColours) && (noColours > optResource->GetValue3())))
optResource = child;
}
break;
}
#endif
#ifdef __WXGTK__
case RESOURCE_PLATFORM_X:
{
if (!optResource && ((noColours == 0) || (noColours <= thisNoColours)))
optResource = child;
else
{
// Maximise the number of colours
if ((noColours == 0) || ((noColours <= thisNoColours) && (noColours > optResource->GetValue3())))
optResource = child;
}
break;
}
#endif
#ifdef wx_max
case RESOURCE_PLATFORM_MAC:
{
if (!optResource && ((noColours == 0) || (noColours <= thisNoColours)))
optResource = child;
else
{
// Maximise the number of colours
if ((noColours == 0) || ((noColours <= thisNoColours) && (noColours > optResource->GetValue3())))
optResource = child;
}
break;
}
#endif
default:
break;
}
node = node->GetNext();
}
// If no matching resource, fail.
if (!optResource)
return wxNullIcon;
wxString name = optResource->GetName();
int bitmapType = (int)optResource->GetValue1();
switch (bitmapType)
{
case wxBITMAP_TYPE_XBM_DATA:
{
#ifdef __WXGTK__
wxItemResource *item = table->FindResource(name);
if (!item)
{
wxLogWarning(_("Failed to find XBM resource %s.\n"
"Forgot to use wxResourceLoadIconData?"), (const wxChar*) name);
return wxNullIcon;
}
return wxIcon((const char **)item->GetValue1(), (int)item->GetValue2(), (int)item->GetValue3());
#else
wxLogWarning(_("No XBM facility available!"));
break;
#endif
}
case wxBITMAP_TYPE_XPM_DATA:
{
// *** XPM ICON NOT YET IMPLEMENTED IN wxWidgets ***
/*
wxItemResource *item = table->FindResource(name);
if (!item)
{
char buf[400];
sprintf(buf, _("Failed to find XPM resource %s.\nForgot to use wxResourceLoadIconData?"), name);
wxLogWarning(buf);
return NULL;
}
return wxIcon((char **)item->GetValue1());
*/
wxLogWarning(_("No XPM icon facility available!"));
break;
}
default:
{
#if defined( __WXGTK__ ) || defined( __WXMOTIF__ )
wxLogWarning(_("Icon resource specification %s not found."), (const wxChar*) resource);
break;
#else
return wxIcon(name, (wxBitmapType) bitmapType);
#endif
}
}
return wxNullIcon;
}
else
{
wxLogWarning(_("Icon resource specification %s not found."), (const wxChar*) resource);
return wxNullIcon;
}
}
#if wxUSE_MENUS
wxMenu *wxResourceCreateMenu(wxItemResource *item)
{
wxMenu *menu = new wxMenu;
wxNode *node = item->GetChildren().GetFirst();
while (node)
{
wxItemResource *child = (wxItemResource *)node->GetData();
if ((!child->GetType().empty()) && (child->GetType() == wxT("wxMenuSeparator")))
menu->AppendSeparator();
else if (child->GetChildren().GetCount() > 0)
{
wxMenu *subMenu = wxResourceCreateMenu(child);
if (subMenu)
menu->Append((int)child->GetValue1(), child->GetTitle(), subMenu, child->GetValue4());
}
else
{
menu->Append((int)child->GetValue1(), child->GetTitle(), child->GetValue4(), (child->GetValue2() != 0));
}
node = node->GetNext();
}
return menu;
}
wxMenuBar *wxResourceCreateMenuBar(const wxString& resource, wxResourceTable *table, wxMenuBar *menuBar)
{
if (!table)
table = wxDefaultResourceTable;
wxItemResource *menuResource = table->FindResource(resource);
if (menuResource && (!menuResource->GetType().empty()) && (menuResource->GetType() == wxT("wxMenu")))
{
if (!menuBar)
menuBar = new wxMenuBar;
wxNode *node = menuResource->GetChildren().GetFirst();
while (node)
{
wxItemResource *child = (wxItemResource *)node->GetData();
wxMenu *menu = wxResourceCreateMenu(child);
if (menu)
menuBar->Append(menu, child->GetTitle());
node = node->GetNext();
}
return menuBar;
}
return (wxMenuBar *) NULL;
}
wxMenu *wxResourceCreateMenu(const wxString& resource, wxResourceTable *table)
{
if (!table)
table = wxDefaultResourceTable;
wxItemResource *menuResource = table->FindResource(resource);
if (menuResource && (!menuResource->GetType().empty()) && (menuResource->GetType() == wxT("wxMenu")))
// if (menuResource && (menuResource->GetType() == wxTYPE_MENU))
return wxResourceCreateMenu(menuResource);
return (wxMenu *) NULL;
}
#endif // wxUSE_MENUS
// Global equivalents (so don't have to refer to default table explicitly)
bool wxResourceParseData(const wxString& resource, wxResourceTable *table)
{
if (!table)
table = wxDefaultResourceTable;
return table->ParseResourceData(resource);
}
bool wxResourceParseData(const char* resource, wxResourceTable *table)
{
wxString str(resource, wxConvLibc);
if (!table)
table = wxDefaultResourceTable;
return table->ParseResourceData(str);
}
bool wxResourceParseFile(const wxString& filename, wxResourceTable *table)
{
if (!table)
table = wxDefaultResourceTable;
return table->ParseResourceFile(filename);
}
// Register XBM/XPM data
bool wxResourceRegisterBitmapData(const wxString& name, char bits[], int width, int height, wxResourceTable *table)
{
if (!table)
table = wxDefaultResourceTable;
return table->RegisterResourceBitmapData(name, bits, width, height);
}
bool wxResourceRegisterBitmapData(const wxString& name, char **data, wxResourceTable *table)
{
if (!table)
table = wxDefaultResourceTable;
return table->RegisterResourceBitmapData(name, data);
}
void wxResourceClear(wxResourceTable *table)
{
if (!table)
table = wxDefaultResourceTable;
table->ClearTable();
}
/*
* Identifiers
*/
bool wxResourceAddIdentifier(const wxString& name, int value, wxResourceTable *table)
{
if (!table)
table = wxDefaultResourceTable;
table->identifiers.Put(name, (wxObject *)(long)value);
return true;
}
int wxResourceGetIdentifier(const wxString& name, wxResourceTable *table)
{
if (!table)
table = wxDefaultResourceTable;
return (int)(long)table->identifiers.Get(name);
}
/*
* Parse #include file for #defines (only)
*/
bool wxResourceParseIncludeFile(const wxString& f, wxResourceTable *table)
{
if (!table)
table = wxDefaultResourceTable;
FILE *fd = wxFopen(f, wxT("r"));
if (!fd)
{
return false;
}
while (wxGetResourceToken(fd))
{
if (strcmp(wxResourceBuffer, "#define") == 0)
{
wxGetResourceToken(fd);
wxChar *name = copystring(wxConvCurrent->cMB2WX(wxResourceBuffer));
wxGetResourceToken(fd);
wxChar *value = copystring(wxConvCurrent->cMB2WX(wxResourceBuffer));
if (wxIsdigit(value[0]))
{
int val = (int)wxAtol(value);
wxResourceAddIdentifier(name, val, table);
}
delete[] name;
delete[] value;
}
}
fclose(fd);
return true;
}
/*
* Reading strings as if they were .wxr files
*/
static int getc_string(char *s)
{
int ch = s[wxResourceStringPtr];
if (ch == 0)
return EOF;
else
{
wxResourceStringPtr ++;
return ch;
}
}
static int ungetc_string()
{
wxResourceStringPtr --;
return 0;
}
bool wxEatWhiteSpaceString(char *s)
{
int ch;
while ((ch = getc_string(s)) != EOF)
{
switch (ch)
{
case ' ':
case 0x0a:
case 0x0d:
case 0x09:
break;
case '/':
{
ch = getc_string(s);
if (ch == EOF)
{
ungetc_string();
return true;
}
if (ch == '*')
{
// Eat C comment
int prev_ch = 0;
while ((ch = getc_string(s)) != EOF)
{
if (ch == '/' && prev_ch == '*')
break;
prev_ch = ch;
}
}
else
{
ungetc_string();
ungetc_string();
return true;
}
}
break;
default:
ungetc_string();
return true;
}
}
return false;
}
bool wxGetResourceTokenString(char *s)
{
if (!wxResourceBuffer)
wxReallocateResourceBuffer();
wxResourceBuffer[0] = 0;
wxEatWhiteSpaceString(s);
int ch = getc_string(s);
if (ch == '"')
{
// Get string
wxResourceBufferCount = 0;
ch = getc_string(s);
while (ch != '"')
{
int actualCh = ch;
if (ch == EOF)
{
wxResourceBuffer[wxResourceBufferCount] = 0;
return false;
}
// Escaped characters
else if (ch == '\\')
{
int newCh = getc_string(s);
if (newCh == '"')
actualCh = '"';
else if (newCh == 10)
actualCh = 10;
else
{
ungetc_string();
}
}
if (wxResourceBufferCount >= wxResourceBufferSize-1)
wxReallocateResourceBuffer();
wxResourceBuffer[wxResourceBufferCount] = (char)actualCh;
wxResourceBufferCount ++;
ch = getc_string(s);
}
wxResourceBuffer[wxResourceBufferCount] = 0;
}
else
{
wxResourceBufferCount = 0;
// Any other token
while (ch != ' ' && ch != EOF && ch != ' ' && ch != 13 && ch != 9 && ch != 10)
{
if (wxResourceBufferCount >= wxResourceBufferSize-1)
wxReallocateResourceBuffer();
wxResourceBuffer[wxResourceBufferCount] = (char)ch;
wxResourceBufferCount ++;
ch = getc_string(s);
}
wxResourceBuffer[wxResourceBufferCount] = 0;
if (ch == EOF)
return false;
}
return true;
}
/*
* Files are in form:
static char *name = "....";
with possible comments.
*/
bool wxResourceReadOneResourceString(char *s, wxExprDatabase& db, bool *eof, wxResourceTable *table)
{
if (!table)
table = wxDefaultResourceTable;
// static or #define
if (!wxGetResourceTokenString(s))
{
*eof = true;
return false;
}
if (strcmp(wxResourceBuffer, "#define") == 0)
{
wxGetResourceTokenString(s);
wxChar *name = copystring(wxConvCurrent->cMB2WX(wxResourceBuffer));
wxGetResourceTokenString(s);
wxChar *value = copystring(wxConvCurrent->cMB2WX(wxResourceBuffer));
if (wxIsdigit(value[0]))
{
int val = (int)wxAtol(value);
wxResourceAddIdentifier(name, val, table);
}
else
{
wxLogWarning(_("#define %s must be an integer."), name);
delete[] name;
delete[] value;
return false;
}
delete[] name;
delete[] value;
return true;
}
/*
else if (strcmp(wxResourceBuffer, "#include") == 0)
{
wxGetResourceTokenString(s);
char *name = copystring(wxResourceBuffer);
char *actualName = name;
if (name[0] == '"')
actualName = name + 1;
int len = strlen(name);
if ((len > 0) && (name[len-1] == '"'))
name[len-1] = 0;
if (!wxResourceParseIncludeFile(actualName, table))
{
char buf[400];
sprintf(buf, _("Could not find resource include file %s."), actualName);
wxLogWarning(buf);
}
delete[] name;
return true;
}
*/
else if (strcmp(wxResourceBuffer, "static") != 0)
{
wxChar buf[300];
wxStrcpy(buf, _("Found "));
wxStrncat(buf, wxConvCurrent->cMB2WX(wxResourceBuffer), 30);
wxStrcat(buf, _(", expected static, #include or #define\nwhile parsing resource."));
wxLogWarning(buf);
return false;
}
// char
if (!wxGetResourceTokenString(s))
{
wxLogWarning(_("Unexpected end of file while parsing resource."));
*eof = true;
return false;
}
if (strcmp(wxResourceBuffer, "char") != 0)
{
wxLogWarning(_("Expected 'char' while parsing resource."));
return false;
}
// *name
if (!wxGetResourceTokenString(s))
{
wxLogWarning(_("Unexpected end of file while parsing resource."));
*eof = true;
return false;
}
if (wxResourceBuffer[0] != '*')
{
wxLogWarning(_("Expected '*' while parsing resource."));
return false;
}
wxChar nameBuf[100];
wxMB2WX(nameBuf, wxResourceBuffer+1, 99);
nameBuf[99] = 0;
// =
if (!wxGetResourceTokenString(s))
{
wxLogWarning(_("Unexpected end of file while parsing resource."));
*eof = true;
return false;
}
if (strcmp(wxResourceBuffer, "=") != 0)
{
wxLogWarning(_("Expected '=' while parsing resource."));
return false;
}
// String
if (!wxGetResourceTokenString(s))
{
wxLogWarning(_("Unexpected end of file while parsing resource."));
*eof = true;
return false;
}
else
{
if (!db.ReadPrologFromString(wxResourceBuffer))
{
wxLogWarning(_("%s: ill-formed resource file syntax."), nameBuf);
return false;
}
}
// Semicolon
if (!wxGetResourceTokenString(s))
{
*eof = true;
}
return true;
}
bool wxResourceParseString(const wxString& s, wxResourceTable *WXUNUSED(table))
{
#if wxUSE_UNICODE
return wxResourceParseString( (char*)s.mb_str().data() );
#else
return wxResourceParseString( (char*)s.c_str() );
#endif
}
bool wxResourceParseString(char *s, wxResourceTable *table)
{
if (!table)
table = wxDefaultResourceTable;
if (!s)
return false;
// Turn backslashes into spaces
if (s)
{
int len = strlen(s);
int i;
for (i = 0; i < len; i++)
if (s[i] == 92 && s[i+1] == 13)
{
s[i] = ' ';
s[i+1] = ' ';
}
}
wxExprDatabase db;
wxResourceStringPtr = 0;
bool eof = false;
while (wxResourceReadOneResourceString(s, db, &eof, table) && !eof)
{
// Loop
}
return wxResourceInterpretResources(*table, db);
}
/*
* resource loading facility
*/
bool wxLoadFromResource(wxWindow* thisWindow, wxWindow *parent, const wxString& resourceName, const wxResourceTable *table)
{
if (!table)
table = wxDefaultResourceTable;
wxItemResource *resource = table->FindResource((const wxChar *)resourceName);
// if (!resource || (resource->GetType() != wxTYPE_DIALOG_BOX))
if (!resource || (resource->GetType().empty()) ||
! ((resource->GetType() == wxT("wxDialog")) || (resource->GetType() == wxT("wxPanel"))))
return false;
wxString title(resource->GetTitle());
long theWindowStyle = resource->GetStyle();
bool isModal = (resource->GetValue1() != 0) ;
int x = resource->GetX();
int y = resource->GetY();
int width = resource->GetWidth();
int height = resource->GetHeight();
wxString name = resource->GetName();
// this is used for loading wxWizard pages from WXR
if ( parent != thisWindow )
{
if (thisWindow->IsKindOf(CLASSINFO(wxDialog)))
{
wxDialog *dialogBox = (wxDialog *)thisWindow;
long modalStyle = isModal ? wxDIALOG_MODAL : 0;
if (!dialogBox->Create(parent, wxID_ANY, title, wxPoint(x, y), wxSize(width, height), theWindowStyle|modalStyle, name))
return false;
// Only reset the client size if we know we're not going to do it again below.
if ((resource->GetResourceStyle() & wxRESOURCE_DIALOG_UNITS) == 0)
dialogBox->SetClientSize(width, height);
}
else if (thisWindow->IsKindOf(CLASSINFO(wxPanel)))
{
wxPanel* panel = (wxPanel *)thisWindow;
if (!panel->Create(parent, wxID_ANY, wxPoint(x, y), wxSize(width, height), theWindowStyle | wxTAB_TRAVERSAL, name))
return false;
}
else
{
if (!((wxWindow *)thisWindow)->Create(parent, wxID_ANY, wxPoint(x, y), wxSize(width, height), theWindowStyle, name))
return false;
}
}
if ((resource->GetResourceStyle() & wxRESOURCE_USE_DEFAULTS) != 0)
{
// No need to do this since it's done in wxPanel or wxDialog constructor.
// SetFont(wxSystemSettings::GetFont(wxSYS_DEFAULT_GUI_FONT));
}
else
{
if (resource->GetFont().Ok())
thisWindow->SetFont(resource->GetFont());
if (resource->GetBackgroundColour().Ok())
thisWindow->SetBackgroundColour(resource->GetBackgroundColour());
}
// Should have some kind of font at this point
if (!thisWindow->GetFont().Ok())
thisWindow->SetFont(wxSystemSettings::GetFont(wxSYS_DEFAULT_GUI_FONT));
if (!thisWindow->GetBackgroundColour().Ok())
thisWindow->SetBackgroundColour(wxSystemSettings::GetColour(wxSYS_COLOUR_3DFACE));
// Only when we've created the window and set the font can we set the correct size,
// if based on dialog units.
if ((resource->GetResourceStyle() & wxRESOURCE_DIALOG_UNITS) != 0)
{
wxSize sz = thisWindow->ConvertDialogToPixels(wxSize(width, height));
thisWindow->SetClientSize(sz.x, sz.y);
wxPoint pt = thisWindow->ConvertDialogToPixels(wxPoint(x, y));
thisWindow->Move(pt.x, pt.y);
}
// Now create children
wxNode *node = resource->GetChildren().GetFirst();
while (node)
{
wxItemResource *childResource = (wxItemResource *)node->GetData();
(void) wxCreateItem(thisWindow, childResource, resource, table);
node = node->GetNext();
}
return true;
}
wxControl *wxCreateItem(wxWindow* thisWindow, const wxItemResource *resource, const wxItemResource* parentResource, const wxResourceTable *table)
{
if (!table)
table = wxDefaultResourceTable;
return table->CreateItem(thisWindow, resource, parentResource);
}
#ifdef __VISUALC__
#pragma warning(default:4706) // assignment within conditional expression
#endif // VC++
#endif // wxUSE_WX_RESOURCES
| {
"content_hash": "2a25855b71fe0690dfcfc0b78104bbaf",
"timestamp": "",
"source": "github",
"line_count": 3282,
"max_line_length": 155,
"avg_line_length": 31.57556368068251,
"alnum_prop": 0.5490731537860293,
"repo_name": "SickheadGames/Torsion",
"id": "96fd6e92835f5231b3cec25c2236ce8f1a1adc0b",
"size": "103631",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "code/wxWidgets/contrib/src/deprecated/resource.cpp",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "74209"
},
{
"name": "C",
"bytes": "6906504"
},
{
"name": "C#",
"bytes": "1624"
},
{
"name": "C++",
"bytes": "30405718"
},
{
"name": "CSS",
"bytes": "591"
},
{
"name": "DIGITAL Command Language",
"bytes": "4055"
},
{
"name": "Groff",
"bytes": "280584"
},
{
"name": "HTML",
"bytes": "148434"
},
{
"name": "Inno Setup",
"bytes": "9684"
},
{
"name": "Lex",
"bytes": "4201"
},
{
"name": "Makefile",
"bytes": "147895"
},
{
"name": "Module Management System",
"bytes": "48825"
},
{
"name": "Objective-C",
"bytes": "143389"
},
{
"name": "Objective-C++",
"bytes": "430038"
},
{
"name": "PHP",
"bytes": "35873"
},
{
"name": "Perl",
"bytes": "105033"
},
{
"name": "Perl6",
"bytes": "107551"
},
{
"name": "Prolog",
"bytes": "421"
},
{
"name": "Python",
"bytes": "5849"
},
{
"name": "R",
"bytes": "7779"
},
{
"name": "Rebol",
"bytes": "732"
},
{
"name": "Scala",
"bytes": "4674"
},
{
"name": "Scheme",
"bytes": "154"
},
{
"name": "Shell",
"bytes": "269793"
},
{
"name": "SourcePawn",
"bytes": "8637"
},
{
"name": "TeX",
"bytes": "194986"
}
],
"symlink_target": ""
} |
var blah = {
frenchies : "French Bulldog Time!",
howMuchILoveFrenchies : Infinity,
frenchieGifs : [
"http://www.allstarfrenchbulldogs.com/LilDebConeGif.gif",
"http://25.media.tumblr.com/tumblr_lu6bewBpPb1qb9pa3o1_500.gif",
"http://www.gifbin.com/bin/122013/1386790251_frenchie_vs_stick.gif",
// //Uncomment for more frenchie
// "http://cdn.gifbay.com/2014/01/french_bulldog_appreciates_a_carrot-112424.gif"
],
showDemFrenchies : function showDemFrenchies(){
blah._h1 = document.getElementById("title");
// //Uncomment to passs tests (Uncomment failing test in test/spec/ first)
// blah._h1.innerHTML = blah.frenchies;
var imgCollection = document.getElementsByTagName("img"),
imgs = Array.prototype.slice.call(imgCollection);
imgs.forEach(function eachImg(img, index) {
img.setAttribute("src", blah.frenchieGifs[index]);
});
}
};
| {
"content_hash": "6cfe1fc783bffc17e44de339e5119772",
"timestamp": "",
"source": "github",
"line_count": 24,
"max_line_length": 85,
"avg_line_length": 37.625,
"alnum_prop": 0.6954595791805094,
"repo_name": "topherbullock/gruntfile-starter-templates",
"id": "c5d671b73e5fe5c3beb1a3faf84bb449cd742295",
"size": "903",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "serve-test-livereload/src/js/module.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "432"
},
{
"name": "HTML",
"bytes": "498"
},
{
"name": "JavaScript",
"bytes": "2974"
}
],
"symlink_target": ""
} |
// XLA-specific reshape Op.
#include "tensorflow/compiler/tf2xla/type_util.h"
#include "tensorflow/compiler/tf2xla/xla_helpers.h"
#include "tensorflow/compiler/tf2xla/xla_op_kernel.h"
#include "tensorflow/compiler/tf2xla/xla_op_registry.h"
#include "tensorflow/compiler/xla/client/lib/constants.h"
#include "tensorflow/compiler/xla/client/xla_builder.h"
#include "tensorflow/compiler/xla/literal.h"
#include "tensorflow/compiler/xla/util.h"
#include "tensorflow/core/framework/op_kernel.h"
#include "tensorflow/core/framework/register_types.h"
#include "tensorflow/core/framework/tensor.h"
#include "tensorflow/core/framework/tensor_shape.h"
namespace tensorflow {
namespace {
class ReshapeOp : public XlaOpKernel {
public:
explicit ReshapeOp(OpKernelConstruction* ctx) : XlaOpKernel(ctx) {}
void Compile(XlaOpKernelContext* ctx) override {
const TensorShape input_shape = ctx->InputShape(0);
const TensorShape sizes_shape = ctx->InputShape(1);
// Preliminary validation of sizes.
OP_REQUIRES(ctx, TensorShapeUtils::IsVector(sizes_shape),
errors::InvalidArgument("sizes input must be 1-D, not shape ",
sizes_shape.DebugString()));
const int64 num_dims = sizes_shape.num_elements();
std::vector<int64> shape_input;
OP_REQUIRES_OK(ctx, ctx->ConstantInputAsIntVector(1, &shape_input));
// Compute the output shape. Determine product of specified
// dimensions, and find the index of the unspecified one if there
// is one.
TensorShape shape;
int64 product = 1;
int unknown_index = -1;
bool shape_has_zero_dim = false;
for (int d = 0; d < num_dims; ++d) {
const int32 size = shape_input[d];
if (size == -1) {
OP_REQUIRES(
ctx, unknown_index == -1,
errors::InvalidArgument("only one input size may be -1, not both ",
unknown_index, " and ", d));
unknown_index = d;
shape.AddDim(1);
} else if (size == 0) {
// We don't include zero-sized dimension in product, so that we can
// still calculate number of elements for non-zero-sized dimensions and
// therefore infer their shapes.
shape.AddDim(size);
shape_has_zero_dim = true;
} else {
OP_REQUIRES(ctx, size >= 0,
errors::InvalidArgument(
"size ", d, " must be non-negative, not ", size));
shape.AddDim(size);
product *= size;
}
}
if (unknown_index != -1) {
int64 input_num_elements = 1;
bool input_has_zero_dim = false;
for (int dim = 0; dim < input_shape.dims(); dim++) {
// For zero dimension, we don't count it into `input_num_elements`
// unless `sizes` has no zero dimension, so we are still able to
// infer shapes for other dimensions.
if (input_shape.dim_size(dim) > 0 || !shape_has_zero_dim) {
input_num_elements *= input_shape.dim_size(dim);
} else {
input_has_zero_dim = true;
}
}
const int64 missing = input_num_elements / product;
if (!input_has_zero_dim) {
OP_REQUIRES(
ctx, product * missing == input_num_elements,
errors::InvalidArgument(
"Input to reshape is a tensor with ", input_num_elements,
" values, but the requested shape requires a multiple of ",
product));
}
shape.set_dim(unknown_index, missing);
}
OP_REQUIRES(ctx, shape.num_elements() == input_shape.num_elements(),
errors::InvalidArgument("Input to reshape is a tensor with ",
input_shape.num_elements(),
" values, but the requested shape has ",
shape.num_elements()));
VLOG(2) << "Reshape from " << input_shape.DebugString() << " to "
<< shape.DebugString() << ", unknown_index=" << unknown_index;
auto input_xla_shape = ctx->InputXlaShape(0);
if (input_xla_shape->is_static()) {
ctx->SetOutput(0, xla::Reshape(ctx->Input(0), shape.dim_sizes()));
return;
}
// Handing dynamic reshapes if input contains a dynamic dimension.
std::vector<xla::XlaOp> output_dim_sizes;
std::vector<bool> dims_are_dynamic;
for (int64 i = 0; i < shape.dims(); ++i) {
output_dim_sizes.push_back(
xla::Reshape(xla::Slice(ctx->Input(1), {i}, {i + 1}, {1}), {}));
}
OP_REQUIRES_OK(
ctx, ctx->ResolveInputDynamismIntoPredVector(1, &dims_are_dynamic));
if (unknown_index == -1) {
// No unknown index.
ctx->SetOutput(0,
xla::DynamicReshape(ctx->Input(0), output_dim_sizes,
shape.dim_sizes(), dims_are_dynamic));
return;
}
auto common_factors =
xla::CommonFactors(input_shape.dim_sizes(), shape.dim_sizes());
// Find common_factors that the input belongs to.
for (int64 i = 0; i < common_factors.size() - 1; ++i) {
auto start = common_factors[i];
auto end = common_factors[i + 1];
bool input_is_dynamic = false;
// product of all input dims in this group. E.g., in
// reshape(Tensor([2, 3, 3]), [3, -1, 3]) product of the group
// containing -1 will be 6.
xla::XlaOp product = xla::One(ctx->builder(), xla::S32);
for (int64 dim = start.first; dim < end.first; ++dim) {
if (input_xla_shape->is_dynamic_dimension(dim)) {
input_is_dynamic = true;
}
product = xla::Mul(product, xla::GetDimensionSize(ctx->Input(0), dim));
}
bool unknown_dim_in_group = false;
// The real size for the -1 dimension in a reshape. E.g., in
// reshape(Tensor([2, 3, 3]), [3, -1, 3]) this will be 2.
xla::XlaOp unknown_dim_size = product;
for (int64 dim = start.second; dim < end.second; ++dim) {
if (dim == unknown_index) {
unknown_dim_in_group = true;
} else {
unknown_dim_size = xla::Div(unknown_dim_size, output_dim_sizes[dim]);
}
}
if (unknown_dim_in_group) {
// If input dim is dynamic, output dim at the -1 position must be
// dynamic. Similarly, if input dim is static, output dim has to be
// static at the -1 dimension.
dims_are_dynamic[unknown_index] = input_is_dynamic;
output_dim_sizes[unknown_index] = unknown_dim_size;
ctx->SetOutput(
0, xla::DynamicReshape(ctx->Input(0), output_dim_sizes,
shape.dim_sizes(), dims_are_dynamic));
VLOG(2) << "Reshape from " << ctx->InputXlaShape(0)->ToString()
<< " to " << xla::VectorString(shape.dim_sizes())
<< ", dynamic_dims=" << xla::VectorString(dims_are_dynamic);
return;
}
}
}
};
REGISTER_XLA_OP(Name("Reshape").CompileTimeConstantInput("shape"), ReshapeOp);
} // namespace
} // namespace tensorflow
| {
"content_hash": "42732f523c7659813bad7512f777fb8a",
"timestamp": "",
"source": "github",
"line_count": 173,
"max_line_length": 80,
"avg_line_length": 40.820809248554916,
"alnum_prop": 0.5851033701500992,
"repo_name": "annarev/tensorflow",
"id": "213045e428afb1a6838f620e09be4b0fe4745528",
"size": "7730",
"binary": false,
"copies": "7",
"ref": "refs/heads/master",
"path": "tensorflow/compiler/tf2xla/kernels/reshape_op.cc",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Assembly",
"bytes": "1286"
},
{
"name": "Batchfile",
"bytes": "9258"
},
{
"name": "C",
"bytes": "341894"
},
{
"name": "C#",
"bytes": "8446"
},
{
"name": "C++",
"bytes": "49343974"
},
{
"name": "CMake",
"bytes": "195286"
},
{
"name": "Dockerfile",
"bytes": "36386"
},
{
"name": "Go",
"bytes": "1253646"
},
{
"name": "HTML",
"bytes": "4681865"
},
{
"name": "Java",
"bytes": "863222"
},
{
"name": "Jupyter Notebook",
"bytes": "2604741"
},
{
"name": "LLVM",
"bytes": "6536"
},
{
"name": "Makefile",
"bytes": "52734"
},
{
"name": "Objective-C",
"bytes": "15650"
},
{
"name": "Objective-C++",
"bytes": "99243"
},
{
"name": "PHP",
"bytes": "1357"
},
{
"name": "Perl",
"bytes": "7536"
},
{
"name": "PureBasic",
"bytes": "25356"
},
{
"name": "Python",
"bytes": "41289329"
},
{
"name": "Ruby",
"bytes": "553"
},
{
"name": "Shell",
"bytes": "469612"
},
{
"name": "Smarty",
"bytes": "6976"
}
],
"symlink_target": ""
} |
using System.Collections.Generic;
using System.Globalization;
using Xunit;
namespace System.Tests
{
public partial class UInt16Tests
{
public static IEnumerable<object[]> Parse_ValidWithOffsetCount_TestData()
{
foreach (object[] inputs in Parse_Valid_TestData())
{
yield return new object[] { inputs[0], 0, ((string)inputs[0]).Length, inputs[1], inputs[2], inputs[3] };
}
yield return new object[] { "123", 0, 2, NumberStyles.Integer, null, (ushort)12 };
yield return new object[] { "123", 1, 2, NumberStyles.Integer, null, (ushort)23 };
yield return new object[] { "+123", 0, 2, NumberStyles.Integer, null, (ushort)1 };
yield return new object[] { "+123", 1, 3, NumberStyles.Integer, null, (ushort)123 };
yield return new object[] { "AJK", 0, 1, NumberStyles.HexNumber, new NumberFormatInfo(), (ushort)0XA };
yield return new object[] { "$1,000", 0, 2, NumberStyles.Currency, new NumberFormatInfo() { CurrencySymbol = "$" }, (ushort)1 };
yield return new object[] { "$1,000", 1, 3, NumberStyles.Currency, new NumberFormatInfo() { CurrencySymbol = "$" }, (ushort)10 };
}
[Theory]
[MemberData(nameof(Parse_ValidWithOffsetCount_TestData))]
public static void Parse_Span_Valid(string value, int offset, int count, NumberStyles style, IFormatProvider provider, ushort expected)
{
ushort result;
// Default style and provider
if (style == NumberStyles.Integer && provider == null)
{
Assert.True(ushort.TryParse(value.AsSpan(offset, count), out result));
Assert.Equal(expected, result);
}
Assert.Equal(expected, ushort.Parse(value.AsSpan(offset, count), style, provider));
Assert.True(ushort.TryParse(value.AsSpan(offset, count), style, provider, out result));
Assert.Equal(expected, result);
}
[Theory]
[MemberData(nameof(Parse_Invalid_TestData))]
public static void Parse_Span_Invalid(string value, NumberStyles style, IFormatProvider provider, Type exceptionType)
{
if (value != null)
{
ushort result;
// Default style and provider
if (style == NumberStyles.Integer && provider == null)
{
Assert.False(ushort.TryParse(value.AsSpan(), out result));
Assert.Equal(0u, result);
}
Assert.Throws(exceptionType, () => ushort.Parse(value.AsSpan(), style, provider));
Assert.False(ushort.TryParse(value.AsSpan(), style, provider, out result));
Assert.Equal(0u, result);
}
}
[Theory]
[MemberData(nameof(ToString_TestData))]
public static void TryFormat(ushort i, string format, IFormatProvider provider, string expected)
{
char[] actual;
int charsWritten;
// Just right
actual = new char[expected.Length];
Assert.True(i.TryFormat(actual.AsSpan(), out charsWritten, format, provider));
Assert.Equal(expected.Length, charsWritten);
Assert.Equal(expected, new string(actual));
// Longer than needed
actual = new char[expected.Length + 1];
Assert.True(i.TryFormat(actual.AsSpan(), out charsWritten, format, provider));
Assert.Equal(expected.Length, charsWritten);
Assert.Equal(expected, new string(actual, 0, charsWritten));
// Too short
if (expected.Length > 0)
{
actual = new char[expected.Length - 1];
Assert.False(i.TryFormat(actual.AsSpan(), out charsWritten, format, provider));
Assert.Equal(0, charsWritten);
}
if (format != null)
{
// Upper format
actual = new char[expected.Length];
Assert.True(i.TryFormat(actual.AsSpan(), out charsWritten, format.ToUpperInvariant(), provider));
Assert.Equal(expected.Length, charsWritten);
Assert.Equal(expected.ToUpperInvariant(), new string(actual));
// Lower format
actual = new char[expected.Length];
Assert.True(i.TryFormat(actual.AsSpan(), out charsWritten, format.ToLowerInvariant(), provider));
Assert.Equal(expected.Length, charsWritten);
Assert.Equal(expected.ToLowerInvariant(), new string(actual));
}
}
}
}
| {
"content_hash": "9a3a0a5d817b6f3797c3a7a2a92c9763",
"timestamp": "",
"source": "github",
"line_count": 109,
"max_line_length": 143,
"avg_line_length": 43.330275229357795,
"alnum_prop": 0.5744230362058014,
"repo_name": "wtgodbe/corefx",
"id": "a6e830167910025828db8474f24844bf411bfdea",
"size": "4927",
"binary": false,
"copies": "48",
"ref": "refs/heads/master",
"path": "src/System.Runtime/tests/System/UInt16Tests.netcoreapp.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "1C Enterprise",
"bytes": "280724"
},
{
"name": "ASP",
"bytes": "1687"
},
{
"name": "Batchfile",
"bytes": "11027"
},
{
"name": "C",
"bytes": "3803475"
},
{
"name": "C#",
"bytes": "181225579"
},
{
"name": "C++",
"bytes": "1521"
},
{
"name": "CMake",
"bytes": "79434"
},
{
"name": "DIGITAL Command Language",
"bytes": "26402"
},
{
"name": "HTML",
"bytes": "653"
},
{
"name": "Makefile",
"bytes": "13780"
},
{
"name": "OpenEdge ABL",
"bytes": "137969"
},
{
"name": "Perl",
"bytes": "3895"
},
{
"name": "PowerShell",
"bytes": "192527"
},
{
"name": "Python",
"bytes": "1535"
},
{
"name": "Roff",
"bytes": "9422"
},
{
"name": "Shell",
"bytes": "131260"
},
{
"name": "TSQL",
"bytes": "96941"
},
{
"name": "Visual Basic",
"bytes": "2135715"
},
{
"name": "XSLT",
"bytes": "514720"
}
],
"symlink_target": ""
} |
INDEX PAGE
recent stuff
- bagel owner
- bagel owning team
- bagelling team
- teams on the "rise"
- teams getting "cold"
- players on the "rise"
- players getting "cold"
all-time stuff
- best teams
- worst teams
- best player
- worst player
statistics
- total bagels
- most bagels in one day
- most bagels in one week
- most bagels in one month
- number of bagels this week
- number of bagels this month
| {
"content_hash": "e8f7b4895e726c5607396f2200d8ed35",
"timestamp": "",
"source": "github",
"line_count": 25,
"max_line_length": 29,
"avg_line_length": 16.28,
"alnum_prop": 0.7297297297297297,
"repo_name": "winterchord/foosball-bagels",
"id": "d593f2b6e185f77f2079191f755ec98602991d2f",
"size": "407",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "TODO.md",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "134453"
},
{
"name": "Cucumber",
"bytes": "2543"
},
{
"name": "HTML",
"bytes": "14195"
},
{
"name": "JavaScript",
"bytes": "67831"
},
{
"name": "Ruby",
"bytes": "62495"
},
{
"name": "Shell",
"bytes": "312"
}
],
"symlink_target": ""
} |
require File.dirname(__FILE__) + '/../../../spec_helper'
require File.dirname(__FILE__) + '/shared/constants'
describe "Digest::MD5#==" do
it 'should be equal to itself' do
cur_digest = Digest::MD5.new
cur_digest.should == cur_digest
end
it 'should be equal to string representing its hexdigest' do
cur_digest = Digest::MD5.new
cur_digest.should == MD5Constants::BlankHexdigest
end
it 'should be equal to appropriate object that responds to to_str' do
# blank digest
cur_digest = Digest::MD5.new
(obj = mock(MD5Constants::BlankHexdigest)).should_receive(:to_str).and_return(MD5Constants::BlankHexdigest)
cur_digest.should == obj
# non-blank digest
cur_digest = Digest::MD5.new
cur_digest << "test"
d_value = cur_digest.hexdigest
(obj = mock(d_value)).should_receive(:to_str).and_return(d_value)
cur_digest.should == obj
end
it 'should be equal for same digest different object' do
cur_digest = Digest::MD5.new
cur_digest2 = Digest::MD5.new
cur_digest.should == cur_digest2
end
end
| {
"content_hash": "68189c5ebeb43b905bca7e08e35001ae",
"timestamp": "",
"source": "github",
"line_count": 37,
"max_line_length": 111,
"avg_line_length": 29,
"alnum_prop": 0.6747437092264679,
"repo_name": "yugui/rubyspec",
"id": "ee6f7789c0800e4893713d48a16562d9f4f3fcb1",
"size": "1073",
"binary": false,
"copies": "5",
"ref": "refs/heads/master",
"path": "1.8/library/digest/md5/equal_spec.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Ruby",
"bytes": "2772477"
}
],
"symlink_target": ""
} |
<?php
return array(
'system' => array(
'System' => 'Sistema',
'Published a new version of the :monstra' => 'Išleista nauja :monstra versija',
'Sitemap created' => 'Sitemap sukurtas',
'Create Sitemap' => 'Sukurti sitemap',
'on' => 'įjungti',
'off'=> 'išjungti',
'Site Url' => 'Tinklapio adresas (url)',
'Maintenance Mode' => 'Remonto režimas',
'Maintenance Mode On' => 'Įjungti remonto režimą',
'Maintenance Mode Off' => 'Išjungti remonto režimą',
'Site Settings' => 'Tinklapio nustatymai',
'System Settings' => 'Sistemos nustatymai',
'Site Name' => 'Tinklapio pavadinimas',
'Site Description' => 'Tinklapio aprašymas',
'Site Keywords' => 'Tinklapio raktažodžiai',
'Site Slogan' => 'Tinklapio šūkis',
'Default Page' => 'Pagrindinis puslapis',
'Time zone' => 'Laiko zona',
'Language' => 'Kalba',
'Email' => 'El. paštas',
'Save' => 'Išsaugoti',
'Site' => 'Tinklapis',
'System version' => 'Sistemos versija',
'System version ID' => 'Sistemos versijos ID',
'GZIP' => 'GZIP',
'Debugging' => 'Derinimas',
'Plugin API' => 'Įskiepių API',
'Plugins active' => 'Aktyvūs įskiepiai',
'Actions registered' => 'Veiksmai užregistruoti',
'Filters registered' => 'Filtrai užregistruoti',
'Delete Temporary Files' => 'Trinti laikinas bylas',
'Download the latest version' => 'Atsisiųsti naujausią versiją',
'Powered by' => 'Veikia su',
'Administration' => 'Administravimas',
'Settings' => 'Nustatymai',
'Temporary files deleted' => 'Laikinos bylos ištrintos',
'Extends' => 'Išplėtimas',
'View Site' => 'Peržiūrėti tinklapį',
'Welcome, :username' => 'Sveiki, :username',
'Reset Password' => 'Gauti naują slaptažodį',
'Back to Website' => 'Grįžti į tinklapį',
'Forgot your password ?' => 'Pamišote slaptažodį ?',
'Administration' => 'Administravimas',
'Send New Password' => 'Siųsti naują slaptažodį',
'This user does not exist' => 'Tokio naudotojo nėra',
'Version' => 'Versija',
'Plugin does not exist' => 'Papildinio nėra',
'Install script writable' => 'Galima rašyti į diegimo scenarijų',
'Install script not writable' => 'Negalima rašyti į diegimo scenarijų',
'Directory: <b> :dir </b> writable' => 'Aplankas: galima rašyti į <b> :dir </b>',
'Directory: <b> :dir </b> not writable' => 'Aplankas: negalima rašyti į <b> :dir </b>',
'PHP Version' => 'PHP versija',
'Module DOM is installed' => 'DOM modulis yra įdiegtas',
'Module DOM is required' => 'Reikalingas DOM modulis',
'Module Mod Rewrite is installed' => 'Apache Mod Rewrite yra įdiegtas',
'Module SimpleXML is installed' => 'SimpleXML modulis yra įdiegtas',
'PHP 5.2 or greater is required' => 'Reikalingas PHP 5.2 ar naujesnis',
'Apache Mod Rewrite is required' => 'Reikalingas Apache Mod Rewrite',
'SimpleXML module is required' => 'Reikalingas SimpleXML modulis',
'Field "Site name" is empty' => 'Laukas „Tinklapio pavadimas“ yra tuščias',
'Field "Email" is empty' => 'Laukas „El. paštas“ yra tuščias',
'Field "Username" is empty' => 'Laukas „Prisijungimo vardas“ yra tuščias',
'Field "Password" is empty' => 'Laukas „Slaptažodis“ yra tuščias',
'Field "Site url" is empty' => 'Laukas „Tinklapio adresas (url)“ yra tuščias',
'Email not valid' => 'Neteisingas el. pašto adresas',
'Install' => 'Įdiegti',
'...Monstra says...' => '...Monstra sako...',
'Sitemap file writable' => 'Galima rašyti į sitemap bylą',
'Sitemap file not writable' => 'Negalima rašyti į sitemap bylą',
'Main .htaccess file writable' => 'Galima rašyti į pagrindinę .htaccess bylą',
'Main .htaccess file not writable' => 'Negalima rašyti į pagrindinę .htaccess bylą',
'Official Support Forum' => 'Pagalbos forumas',
'Documentation' => 'Dokumentacija',
)
);
| {
"content_hash": "aa5b6737c1df333ae0457f8228c403fb",
"timestamp": "",
"source": "github",
"line_count": 80,
"max_line_length": 99,
"avg_line_length": 55.875,
"alnum_prop": 0.5543624161073826,
"repo_name": "ravilrrr/Monstra.R-CMS",
"id": "a847380f10e6c4cece3e41936422e5305e131c68",
"size": "4580",
"binary": false,
"copies": "11",
"ref": "refs/heads/master",
"path": "plugins/box/system/languages/lt.lang.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ApacheConf",
"bytes": "2795"
},
{
"name": "CSS",
"bytes": "229951"
},
{
"name": "JavaScript",
"bytes": "161374"
},
{
"name": "PHP",
"bytes": "1926354"
}
],
"symlink_target": ""
} |
from typing import List, Union
from azure.ai.ml._restclient.v2022_10_01_preview.models import (
AutoForecastHorizon,
AutoSeasonality,
AutoTargetLags,
AutoTargetRollingWindowSize,
CustomForecastHorizon,
CustomSeasonality,
CustomTargetLags,
CustomTargetRollingWindowSize,
ForecastHorizonMode,
)
from azure.ai.ml._restclient.v2022_10_01_preview.models import ForecastingSettings as RestForecastingSettings
from azure.ai.ml._restclient.v2022_10_01_preview.models import (
SeasonalityMode,
TargetLagsMode,
TargetRollingWindowSizeMode,
)
from azure.ai.ml.entities._mixins import RestTranslatableMixin
class ForecastingSettings(RestTranslatableMixin):
"""Forecasting settings for an AutoML Job.
:param country_or_region_for_holidays: The country/region used to generate holiday features. These should be ISO
3166 two-letter country/region code, for example 'US' or 'GB'.
:type country_or_region_for_holidays: str
:param forecast_horizon: The desired maximum forecast horizon in units of time-series frequency.
:type forecast_horizon: int
:param target_lags: The number of past periods to lag from the target column. Use 'auto' to use the automatic
heuristic based lag.
:type target_lags: Union[str, int, List[int]]
:param target_rolling_window_size: The number of past periods used to create a rolling window average of the
target column.
:type target_rolling_window_size: int
:param frequency: Forecast frequency. When forecasting, this parameter represents the period with which the
forecast is desired, for example daily, weekly, yearly, etc.
:type frequency: str
:param feature_lags: Flag for generating lags for the numeric features with 'auto'
:type feature_lags: str
:param seasonality: Set time series seasonality as an integer multiple of the series frequency. Use 'auto' for
automatic settings.
:type seasonality: Union[str, int]
:param use_stl: Configure STL Decomposition of the time-series target column. use_stl can take two values:
'season' - only generate season component and 'season_trend' - generate both season and trend components.
:type use_stl: str
:param short_series_handling_config: The parameter defining how if AutoML should handle short time series.
:type short_series_handling_config: str
:param target_aggregate_function: The function to be used to aggregate the time series target column to conform
to a user specified frequency. If the target_aggregation_function is set, but the freq parameter is not set,
the error is raised. The possible target aggregation functions are: "sum", "max", "min" and "mean".
:type target_aggregate_function: str
:param time_column_name: The name of the time column.
:type time_column_name: str
:param time_series_id_column_names: The names of columns used to group a timeseries.
:type time_series_id_column_names: Union[str, List[str]]
"""
def __init__(
self,
*,
country_or_region_for_holidays: str = None,
cv_step_size: int = None,
forecast_horizon: Union[str, int] = None,
target_lags: Union[str, int, List[int]] = None,
target_rolling_window_size: Union[str, int] = None,
frequency: str = None,
feature_lags: str = None,
seasonality: Union[str, int] = None,
use_stl: str = None,
short_series_handling_config: str = None,
target_aggregate_function: str = None,
time_column_name: str = None,
time_series_id_column_names: Union[str, List[str]] = None,
):
self.country_or_region_for_holidays = country_or_region_for_holidays
self.cv_step_size = cv_step_size
self.forecast_horizon = forecast_horizon
self.target_lags = target_lags
self.target_rolling_window_size = target_rolling_window_size
self.frequency = frequency
self.feature_lags = feature_lags
self.seasonality = seasonality
self.use_stl = use_stl
self.short_series_handling_config = short_series_handling_config
self.target_aggregate_function = target_aggregate_function
self.time_column_name = time_column_name
self.time_series_id_column_names = time_series_id_column_names
def _to_rest_object(self) -> RestForecastingSettings:
forecast_horizon = None
if isinstance(self.forecast_horizon, str):
forecast_horizon = AutoForecastHorizon()
elif self.forecast_horizon:
forecast_horizon = CustomForecastHorizon(value=self.forecast_horizon)
target_lags = None
if isinstance(self.target_lags, str):
target_lags = AutoTargetLags()
elif self.target_lags:
lags = [self.target_lags] if not isinstance(self.target_lags, list) else self.target_lags
target_lags = CustomTargetLags(values=lags)
target_rolling_window_size = None
if isinstance(self.target_rolling_window_size, str):
target_rolling_window_size = AutoTargetRollingWindowSize()
elif self.target_rolling_window_size:
target_rolling_window_size = CustomTargetRollingWindowSize(value=self.target_rolling_window_size)
seasonality = None
if isinstance(self.seasonality, str):
seasonality = AutoSeasonality()
elif self.seasonality:
seasonality = CustomSeasonality(value=self.seasonality)
time_series_id_column_names = self.time_series_id_column_names
if isinstance(self.time_series_id_column_names, str) and self.time_series_id_column_names:
time_series_id_column_names = [self.time_series_id_column_names]
return RestForecastingSettings(
country_or_region_for_holidays=self.country_or_region_for_holidays,
cv_step_size=self.cv_step_size,
forecast_horizon=forecast_horizon,
time_column_name=self.time_column_name,
target_lags=target_lags,
target_rolling_window_size=target_rolling_window_size,
seasonality=seasonality,
frequency=self.frequency,
feature_lags=self.feature_lags,
use_stl=self.use_stl,
short_series_handling_config=self.short_series_handling_config,
target_aggregate_function=self.target_aggregate_function,
time_series_id_column_names=time_series_id_column_names,
)
@classmethod
def _from_rest_object(cls, obj: RestForecastingSettings) -> "ForecastingSettings":
forecast_horizon = None
if obj.forecast_horizon and obj.forecast_horizon.mode == ForecastHorizonMode.AUTO:
forecast_horizon = obj.forecast_horizon.mode.lower()
elif obj.forecast_horizon:
forecast_horizon = obj.forecast_horizon.value
rest_target_lags = obj.target_lags
target_lags = None
if rest_target_lags and rest_target_lags.mode == TargetLagsMode.AUTO:
target_lags = rest_target_lags.mode.lower()
elif rest_target_lags:
target_lags = rest_target_lags.values
target_rolling_window_size = None
if obj.target_rolling_window_size and obj.target_rolling_window_size.mode == TargetRollingWindowSizeMode.AUTO:
target_rolling_window_size = obj.target_rolling_window_size.mode.lower()
elif obj.target_rolling_window_size:
target_rolling_window_size = obj.target_rolling_window_size.value
seasonality = None
if obj.seasonality and obj.seasonality.mode == SeasonalityMode.AUTO:
seasonality = obj.seasonality.mode.lower()
elif obj.seasonality:
seasonality = obj.seasonality.value
return cls(
country_or_region_for_holidays=obj.country_or_region_for_holidays,
cv_step_size=obj.cv_step_size,
forecast_horizon=forecast_horizon,
target_lags=target_lags,
target_rolling_window_size=target_rolling_window_size,
frequency=obj.frequency,
feature_lags=obj.feature_lags,
seasonality=seasonality,
use_stl=obj.use_stl,
short_series_handling_config=obj.short_series_handling_config,
target_aggregate_function=obj.target_aggregate_function,
time_column_name=obj.time_column_name,
time_series_id_column_names=obj.time_series_id_column_names,
)
def __eq__(self, other: object) -> bool:
if not isinstance(other, ForecastingSettings):
return NotImplemented
return (
self.country_or_region_for_holidays == other.country_or_region_for_holidays
and self.cv_step_size == other.cv_step_size
and self.forecast_horizon == other.forecast_horizon
and self.target_lags == other.target_lags
and self.target_rolling_window_size == other.target_rolling_window_size
and self.frequency == other.frequency
and self.feature_lags == other.feature_lags
and self.seasonality == other.seasonality
and self.use_stl == other.use_stl
and self.short_series_handling_config == other.short_series_handling_config
and self.target_aggregate_function == other.target_aggregate_function
and self.time_column_name == other.time_column_name
and self.time_series_id_column_names == other.time_series_id_column_names
)
def __ne__(self, other: object) -> bool:
return not self.__eq__(other)
| {
"content_hash": "ebddfecf28c9b38f23ac17a2b74e1772",
"timestamp": "",
"source": "github",
"line_count": 200,
"max_line_length": 118,
"avg_line_length": 48.125,
"alnum_prop": 0.6742857142857143,
"repo_name": "Azure/azure-sdk-for-python",
"id": "24303737461dc9e580c6f37af96b3b2f1bb5819d",
"size": "9871",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "sdk/ml/azure-ai-ml/azure/ai/ml/entities/_job/automl/tabular/forecasting_settings.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "1224"
},
{
"name": "Bicep",
"bytes": "24196"
},
{
"name": "CSS",
"bytes": "6089"
},
{
"name": "Dockerfile",
"bytes": "4892"
},
{
"name": "HTML",
"bytes": "12058"
},
{
"name": "JavaScript",
"bytes": "8137"
},
{
"name": "Jinja",
"bytes": "10377"
},
{
"name": "Jupyter Notebook",
"bytes": "272022"
},
{
"name": "PowerShell",
"bytes": "518535"
},
{
"name": "Python",
"bytes": "715484989"
},
{
"name": "Shell",
"bytes": "3631"
}
],
"symlink_target": ""
} |
var zrUtil = require("zrender/lib/core/util");
var eventTool = require("zrender/lib/core/event");
var graphic = require("../../util/graphic");
var throttle = require("../../util/throttle");
var DataZoomView = require("./DataZoomView");
var numberUtil = require("../../util/number");
var layout = require("../../util/layout");
var sliderMove = require("../helper/sliderMove");
var Rect = graphic.Rect;
var linearMap = numberUtil.linearMap;
var asc = numberUtil.asc;
var bind = zrUtil.bind;
var each = zrUtil.each; // Constants
var DEFAULT_LOCATION_EDGE_GAP = 7;
var DEFAULT_FRAME_BORDER_WIDTH = 1;
var DEFAULT_FILLER_SIZE = 30;
var HORIZONTAL = 'horizontal';
var VERTICAL = 'vertical';
var LABEL_GAP = 5;
var SHOW_DATA_SHADOW_SERIES_TYPE = ['line', 'bar', 'candlestick', 'scatter'];
var SliderZoomView = DataZoomView.extend({
type: 'dataZoom.slider',
init: function (ecModel, api) {
/**
* @private
* @type {Object}
*/
this._displayables = {};
/**
* @private
* @type {string}
*/
this._orient;
/**
* [0, 100]
* @private
*/
this._range;
/**
* [coord of the first handle, coord of the second handle]
* @private
*/
this._handleEnds;
/**
* [length, thick]
* @private
* @type {Array.<number>}
*/
this._size;
/**
* @private
* @type {number}
*/
this._handleWidth;
/**
* @private
* @type {number}
*/
this._handleHeight;
/**
* @private
*/
this._location;
/**
* @private
*/
this._dragging;
/**
* @private
*/
this._dataShadowInfo;
this.api = api;
},
/**
* @override
*/
render: function (dataZoomModel, ecModel, api, payload) {
SliderZoomView.superApply(this, 'render', arguments);
throttle.createOrUpdate(this, '_dispatchZoomAction', this.dataZoomModel.get('throttle'), 'fixRate');
this._orient = dataZoomModel.get('orient');
if (this.dataZoomModel.get('show') === false) {
this.group.removeAll();
return;
} // Notice: this._resetInterval() should not be executed when payload.type
// is 'dataZoom', origin this._range should be maintained, otherwise 'pan'
// or 'zoom' info will be missed because of 'throttle' of this.dispatchAction,
if (!payload || payload.type !== 'dataZoom' || payload.from !== this.uid) {
this._buildView();
}
this._updateView();
},
/**
* @override
*/
remove: function () {
SliderZoomView.superApply(this, 'remove', arguments);
throttle.clear(this, '_dispatchZoomAction');
},
/**
* @override
*/
dispose: function () {
SliderZoomView.superApply(this, 'dispose', arguments);
throttle.clear(this, '_dispatchZoomAction');
},
_buildView: function () {
var thisGroup = this.group;
thisGroup.removeAll();
this._resetLocation();
this._resetInterval();
var barGroup = this._displayables.barGroup = new graphic.Group();
this._renderBackground();
this._renderHandle();
this._renderDataShadow();
thisGroup.add(barGroup);
this._positionGroup();
},
/**
* @private
*/
_resetLocation: function () {
var dataZoomModel = this.dataZoomModel;
var api = this.api; // If some of x/y/width/height are not specified,
// auto-adapt according to target grid.
var coordRect = this._findCoordRect();
var ecSize = {
width: api.getWidth(),
height: api.getHeight()
}; // Default align by coordinate system rect.
var positionInfo = this._orient === HORIZONTAL ? {
// Why using 'right', because right should be used in vertical,
// and it is better to be consistent for dealing with position param merge.
right: ecSize.width - coordRect.x - coordRect.width,
top: ecSize.height - DEFAULT_FILLER_SIZE - DEFAULT_LOCATION_EDGE_GAP,
width: coordRect.width,
height: DEFAULT_FILLER_SIZE
} : {
// vertical
right: DEFAULT_LOCATION_EDGE_GAP,
top: coordRect.y,
width: DEFAULT_FILLER_SIZE,
height: coordRect.height
}; // Do not write back to option and replace value 'ph', because
// the 'ph' value should be recalculated when resize.
var layoutParams = layout.getLayoutParams(dataZoomModel.option); // Replace the placeholder value.
zrUtil.each(['right', 'top', 'width', 'height'], function (name) {
if (layoutParams[name] === 'ph') {
layoutParams[name] = positionInfo[name];
}
});
var layoutRect = layout.getLayoutRect(layoutParams, ecSize, dataZoomModel.padding);
this._location = {
x: layoutRect.x,
y: layoutRect.y
};
this._size = [layoutRect.width, layoutRect.height];
this._orient === VERTICAL && this._size.reverse();
},
/**
* @private
*/
_positionGroup: function () {
var thisGroup = this.group;
var location = this._location;
var orient = this._orient; // Just use the first axis to determine mapping.
var targetAxisModel = this.dataZoomModel.getFirstTargetAxisModel();
var inverse = targetAxisModel && targetAxisModel.get('inverse');
var barGroup = this._displayables.barGroup;
var otherAxisInverse = (this._dataShadowInfo || {}).otherAxisInverse; // Transform barGroup.
barGroup.attr(orient === HORIZONTAL && !inverse ? {
scale: otherAxisInverse ? [1, 1] : [1, -1]
} : orient === HORIZONTAL && inverse ? {
scale: otherAxisInverse ? [-1, 1] : [-1, -1]
} : orient === VERTICAL && !inverse ? {
scale: otherAxisInverse ? [1, -1] : [1, 1],
rotation: Math.PI / 2 // Dont use Math.PI, considering shadow direction.
} : {
scale: otherAxisInverse ? [-1, -1] : [-1, 1],
rotation: Math.PI / 2
}); // Position barGroup
var rect = thisGroup.getBoundingRect([barGroup]);
thisGroup.attr('position', [location.x - rect.x, location.y - rect.y]);
},
/**
* @private
*/
_getViewExtent: function () {
return [0, this._size[0]];
},
_renderBackground: function () {
var dataZoomModel = this.dataZoomModel;
var size = this._size;
var barGroup = this._displayables.barGroup;
barGroup.add(new Rect({
silent: true,
shape: {
x: 0,
y: 0,
width: size[0],
height: size[1]
},
style: {
fill: dataZoomModel.get('backgroundColor')
},
z2: -40
})); // Click panel, over shadow, below handles.
barGroup.add(new Rect({
shape: {
x: 0,
y: 0,
width: size[0],
height: size[1]
},
style: {
fill: 'transparent'
},
z2: 0,
onclick: zrUtil.bind(this._onClickPanelClick, this)
}));
},
_renderDataShadow: function () {
var info = this._dataShadowInfo = this._prepareDataShadowInfo();
if (!info) {
return;
}
var size = this._size;
var seriesModel = info.series;
var data = seriesModel.getRawData();
var otherDim = seriesModel.getShadowDim ? seriesModel.getShadowDim() // @see candlestick
: info.otherDim;
if (otherDim == null) {
return;
}
var otherDataExtent = data.getDataExtent(otherDim); // Nice extent.
var otherOffset = (otherDataExtent[1] - otherDataExtent[0]) * 0.3;
otherDataExtent = [otherDataExtent[0] - otherOffset, otherDataExtent[1] + otherOffset];
var otherShadowExtent = [0, size[1]];
var thisShadowExtent = [0, size[0]];
var areaPoints = [[size[0], 0], [0, 0]];
var linePoints = [];
var step = thisShadowExtent[1] / (data.count() - 1);
var thisCoord = 0; // Optimize for large data shadow
var stride = Math.round(data.count() / size[0]);
var lastIsEmpty;
data.each([otherDim], function (value, index) {
if (stride > 0 && index % stride) {
thisCoord += step;
return;
} // FIXME
// Should consider axis.min/axis.max when drawing dataShadow.
// FIXME
// 应该使用统一的空判断?还是在list里进行空判断?
var isEmpty = value == null || isNaN(value) || value === ''; // See #4235.
var otherCoord = isEmpty ? 0 : linearMap(value, otherDataExtent, otherShadowExtent, true); // Attempt to draw data shadow precisely when there are empty value.
if (isEmpty && !lastIsEmpty && index) {
areaPoints.push([areaPoints[areaPoints.length - 1][0], 0]);
linePoints.push([linePoints[linePoints.length - 1][0], 0]);
} else if (!isEmpty && lastIsEmpty) {
areaPoints.push([thisCoord, 0]);
linePoints.push([thisCoord, 0]);
}
areaPoints.push([thisCoord, otherCoord]);
linePoints.push([thisCoord, otherCoord]);
thisCoord += step;
lastIsEmpty = isEmpty;
});
var dataZoomModel = this.dataZoomModel; // var dataBackgroundModel = dataZoomModel.getModel('dataBackground');
this._displayables.barGroup.add(new graphic.Polygon({
shape: {
points: areaPoints
},
style: zrUtil.defaults({
fill: dataZoomModel.get('dataBackgroundColor')
}, dataZoomModel.getModel('dataBackground.areaStyle').getAreaStyle()),
silent: true,
z2: -20
}));
this._displayables.barGroup.add(new graphic.Polyline({
shape: {
points: linePoints
},
style: dataZoomModel.getModel('dataBackground.lineStyle').getLineStyle(),
silent: true,
z2: -19
}));
},
_prepareDataShadowInfo: function () {
var dataZoomModel = this.dataZoomModel;
var showDataShadow = dataZoomModel.get('showDataShadow');
if (showDataShadow === false) {
return;
} // Find a representative series.
var result;
var ecModel = this.ecModel;
dataZoomModel.eachTargetAxis(function (dimNames, axisIndex) {
var seriesModels = dataZoomModel.getAxisProxy(dimNames.name, axisIndex).getTargetSeriesModels();
zrUtil.each(seriesModels, function (seriesModel) {
if (result) {
return;
}
if (showDataShadow !== true && zrUtil.indexOf(SHOW_DATA_SHADOW_SERIES_TYPE, seriesModel.get('type')) < 0) {
return;
}
var thisAxis = ecModel.getComponent(dimNames.axis, axisIndex).axis;
var otherDim = getOtherDim(dimNames.name);
var otherAxisInverse;
var coordSys = seriesModel.coordinateSystem;
if (otherDim != null && coordSys.getOtherAxis) {
otherAxisInverse = coordSys.getOtherAxis(thisAxis).inverse;
}
result = {
thisAxis: thisAxis,
series: seriesModel,
thisDim: dimNames.name,
otherDim: otherDim,
otherAxisInverse: otherAxisInverse
};
}, this);
}, this);
return result;
},
_renderHandle: function () {
var displaybles = this._displayables;
var handles = displaybles.handles = [];
var handleLabels = displaybles.handleLabels = [];
var barGroup = this._displayables.barGroup;
var size = this._size;
var dataZoomModel = this.dataZoomModel;
barGroup.add(displaybles.filler = new Rect({
draggable: true,
cursor: getCursor(this._orient),
drift: bind(this._onDragMove, this, 'all'),
onmousemove: function (e) {
// Fot mobile devicem, prevent screen slider on the button.
eventTool.stop(e.event);
},
ondragstart: bind(this._showDataInfo, this, true),
ondragend: bind(this._onDragEnd, this),
onmouseover: bind(this._showDataInfo, this, true),
onmouseout: bind(this._showDataInfo, this, false),
style: {
fill: dataZoomModel.get('fillerColor'),
textPosition: 'inside'
}
})); // Frame border.
barGroup.add(new Rect(graphic.subPixelOptimizeRect({
silent: true,
shape: {
x: 0,
y: 0,
width: size[0],
height: size[1]
},
style: {
stroke: dataZoomModel.get('dataBackgroundColor') || dataZoomModel.get('borderColor'),
lineWidth: DEFAULT_FRAME_BORDER_WIDTH,
fill: 'rgba(0,0,0,0)'
}
})));
each([0, 1], function (handleIndex) {
var path = graphic.createIcon(dataZoomModel.get('handleIcon'), {
cursor: getCursor(this._orient),
draggable: true,
drift: bind(this._onDragMove, this, handleIndex),
onmousemove: function (e) {
// Fot mobile devicem, prevent screen slider on the button.
eventTool.stop(e.event);
},
ondragend: bind(this._onDragEnd, this),
onmouseover: bind(this._showDataInfo, this, true),
onmouseout: bind(this._showDataInfo, this, false)
}, {
x: -1,
y: 0,
width: 2,
height: 2
});
var bRect = path.getBoundingRect();
this._handleHeight = numberUtil.parsePercent(dataZoomModel.get('handleSize'), this._size[1]);
this._handleWidth = bRect.width / bRect.height * this._handleHeight;
path.setStyle(dataZoomModel.getModel('handleStyle').getItemStyle());
var handleColor = dataZoomModel.get('handleColor'); // Compatitable with previous version
if (handleColor != null) {
path.style.fill = handleColor;
}
barGroup.add(handles[handleIndex] = path);
var textStyleModel = dataZoomModel.textStyleModel;
this.group.add(handleLabels[handleIndex] = new graphic.Text({
silent: true,
invisible: true,
style: {
x: 0,
y: 0,
text: '',
textVerticalAlign: 'middle',
textAlign: 'center',
textFill: textStyleModel.getTextColor(),
textFont: textStyleModel.getFont()
},
z2: 10
}));
}, this);
},
/**
* @private
*/
_resetInterval: function () {
var range = this._range = this.dataZoomModel.getPercentRange();
var viewExtent = this._getViewExtent();
this._handleEnds = [linearMap(range[0], [0, 100], viewExtent, true), linearMap(range[1], [0, 100], viewExtent, true)];
},
/**
* @private
* @param {(number|string)} handleIndex 0 or 1 or 'all'
* @param {number} delta
*/
_updateInterval: function (handleIndex, delta) {
var dataZoomModel = this.dataZoomModel;
var handleEnds = this._handleEnds;
var viewExtend = this._getViewExtent();
var minMaxSpan = dataZoomModel.findRepresentativeAxisProxy().getMinMaxSpan();
var percentExtent = [0, 100];
sliderMove(delta, handleEnds, viewExtend, dataZoomModel.get('zoomLock') ? 'all' : handleIndex, minMaxSpan.minSpan != null ? linearMap(minMaxSpan.minSpan, percentExtent, viewExtend, true) : null, minMaxSpan.maxSpan != null ? linearMap(minMaxSpan.maxSpan, percentExtent, viewExtend, true) : null);
this._range = asc([linearMap(handleEnds[0], viewExtend, percentExtent, true), linearMap(handleEnds[1], viewExtend, percentExtent, true)]);
},
/**
* @private
*/
_updateView: function (nonRealtime) {
var displaybles = this._displayables;
var handleEnds = this._handleEnds;
var handleInterval = asc(handleEnds.slice());
var size = this._size;
each([0, 1], function (handleIndex) {
// Handles
var handle = displaybles.handles[handleIndex];
var handleHeight = this._handleHeight;
handle.attr({
scale: [handleHeight / 2, handleHeight / 2],
position: [handleEnds[handleIndex], size[1] / 2 - handleHeight / 2]
});
}, this); // Filler
displaybles.filler.setShape({
x: handleInterval[0],
y: 0,
width: handleInterval[1] - handleInterval[0],
height: size[1]
});
this._updateDataInfo(nonRealtime);
},
/**
* @private
*/
_updateDataInfo: function (nonRealtime) {
var dataZoomModel = this.dataZoomModel;
var displaybles = this._displayables;
var handleLabels = displaybles.handleLabels;
var orient = this._orient;
var labelTexts = ['', '']; // FIXME
// date型,支持formatter,autoformatter(ec2 date.getAutoFormatter)
if (dataZoomModel.get('showDetail')) {
var axisProxy = dataZoomModel.findRepresentativeAxisProxy();
if (axisProxy) {
var axis = axisProxy.getAxisModel().axis;
var range = this._range;
var dataInterval = nonRealtime // See #4434, data and axis are not processed and reset yet in non-realtime mode.
? axisProxy.calculateDataWindow({
start: range[0],
end: range[1]
}).valueWindow : axisProxy.getDataValueWindow();
labelTexts = [this._formatLabel(dataInterval[0], axis), this._formatLabel(dataInterval[1], axis)];
}
}
var orderedHandleEnds = asc(this._handleEnds.slice());
setLabel.call(this, 0);
setLabel.call(this, 1);
function setLabel(handleIndex) {
// Label
// Text should not transform by barGroup.
// Ignore handlers transform
var barTransform = graphic.getTransform(displaybles.handles[handleIndex].parent, this.group);
var direction = graphic.transformDirection(handleIndex === 0 ? 'right' : 'left', barTransform);
var offset = this._handleWidth / 2 + LABEL_GAP;
var textPoint = graphic.applyTransform([orderedHandleEnds[handleIndex] + (handleIndex === 0 ? -offset : offset), this._size[1] / 2], barTransform);
handleLabels[handleIndex].setStyle({
x: textPoint[0],
y: textPoint[1],
textVerticalAlign: orient === HORIZONTAL ? 'middle' : direction,
textAlign: orient === HORIZONTAL ? direction : 'center',
text: labelTexts[handleIndex]
});
}
},
/**
* @private
*/
_formatLabel: function (value, axis) {
var dataZoomModel = this.dataZoomModel;
var labelFormatter = dataZoomModel.get('labelFormatter');
var labelPrecision = dataZoomModel.get('labelPrecision');
if (labelPrecision == null || labelPrecision === 'auto') {
labelPrecision = axis.getPixelPrecision();
}
var valueStr = value == null || isNaN(value) ? '' // FIXME Glue code
: axis.type === 'category' || axis.type === 'time' ? axis.scale.getLabel(Math.round(value)) // param of toFixed should less then 20.
: value.toFixed(Math.min(labelPrecision, 20));
return zrUtil.isFunction(labelFormatter) ? labelFormatter(value, valueStr) : zrUtil.isString(labelFormatter) ? labelFormatter.replace('{value}', valueStr) : valueStr;
},
/**
* @private
* @param {boolean} showOrHide true: show, false: hide
*/
_showDataInfo: function (showOrHide) {
// Always show when drgging.
showOrHide = this._dragging || showOrHide;
var handleLabels = this._displayables.handleLabels;
handleLabels[0].attr('invisible', !showOrHide);
handleLabels[1].attr('invisible', !showOrHide);
},
_onDragMove: function (handleIndex, dx, dy) {
this._dragging = true; // Transform dx, dy to bar coordination.
var barTransform = this._displayables.barGroup.getLocalTransform();
var vertex = graphic.applyTransform([dx, dy], barTransform, true);
this._updateInterval(handleIndex, vertex[0]);
var realtime = this.dataZoomModel.get('realtime');
this._updateView(!realtime);
if (realtime) {
realtime && this._dispatchZoomAction();
}
},
_onDragEnd: function () {
this._dragging = false;
this._showDataInfo(false);
this._dispatchZoomAction();
},
_onClickPanelClick: function (e) {
var size = this._size;
var localPoint = this._displayables.barGroup.transformCoordToLocal(e.offsetX, e.offsetY);
if (localPoint[0] < 0 || localPoint[0] > size[0] || localPoint[1] < 0 || localPoint[1] > size[1]) {
return;
}
var handleEnds = this._handleEnds;
var center = (handleEnds[0] + handleEnds[1]) / 2;
this._updateInterval('all', localPoint[0] - center);
this._updateView();
this._dispatchZoomAction();
},
/**
* This action will be throttled.
* @private
*/
_dispatchZoomAction: function () {
var range = this._range;
this.api.dispatchAction({
type: 'dataZoom',
from: this.uid,
dataZoomId: this.dataZoomModel.id,
start: range[0],
end: range[1]
});
},
/**
* @private
*/
_findCoordRect: function () {
// Find the grid coresponding to the first axis referred by dataZoom.
var rect;
each(this.getTargetCoordInfo(), function (coordInfoList) {
if (!rect && coordInfoList.length) {
var coordSys = coordInfoList[0].model.coordinateSystem;
rect = coordSys.getRect && coordSys.getRect();
}
});
if (!rect) {
var width = this.api.getWidth();
var height = this.api.getHeight();
rect = {
x: width * 0.2,
y: height * 0.2,
width: width * 0.6,
height: height * 0.6
};
}
return rect;
}
});
function getOtherDim(thisDim) {
// FIXME
// 这个逻辑和getOtherAxis里一致,但是写在这里是否不好
var map = {
x: 'y',
y: 'x',
radius: 'angle',
angle: 'radius'
};
return map[thisDim];
}
function getCursor(orient) {
return orient === 'vertical' ? 'ns-resize' : 'ew-resize';
}
var _default = SliderZoomView;
module.exports = _default; | {
"content_hash": "ff40e698801e2215f07a87f73dbef099",
"timestamp": "",
"source": "github",
"line_count": 710,
"max_line_length": 299,
"avg_line_length": 29.628169014084506,
"alnum_prop": 0.6166096216010648,
"repo_name": "falost/falost.github.io",
"id": "14cb5618f8a81aa7eb56f38c75d76f53626448a8",
"size": "21130",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "static/libs/echarts/lib/component/dataZoom/SliderZoomView.js",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "303039"
},
{
"name": "HTML",
"bytes": "11691"
},
{
"name": "JavaScript",
"bytes": "4351373"
}
],
"symlink_target": ""
} |
The MIT License (MIT)
Copyright (c) 2014 Ondřej Plšek (http://www.ondraplsek.cz)
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.
| {
"content_hash": "267c426b364e2d635a1470f58fb159e7",
"timestamp": "",
"source": "github",
"line_count": 20,
"max_line_length": 80,
"avg_line_length": 55.3,
"alnum_prop": 0.8010849909584087,
"repo_name": "ondrs/WebLoaderFilters",
"id": "38c9f95bc9656323e99c9e70047eac999297a4ac",
"size": "1108",
"binary": false,
"copies": "10",
"ref": "refs/heads/master",
"path": "LICENSE.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "PHP",
"bytes": "509"
}
],
"symlink_target": ""
} |
<?php
namespace Zephir\Builder\Statements;
/**
* ThrowStatementBuilder
*
* Allows to manually build a 'throw' statement AST node
*/
class ThrowStatementBuilder extends AbstractStatementBuilder
{
private $expr;
/**
* ThrowStatementBuilder constructor
*
* @param mixed $expr
*/
public function __construct($expr)
{
$this->expr = $expr;
}
/**
* {@inheritdoc}
*/
public function get()
{
return array(
'type' => 'throw',
'expr' => $this->expr->get()
);
}
}
| {
"content_hash": "376b92086f592222a77febf0ce88fa9c",
"timestamp": "",
"source": "github",
"line_count": 36,
"max_line_length": 60,
"avg_line_length": 16,
"alnum_prop": 0.5451388888888888,
"repo_name": "sergeyklay/zephir",
"id": "de8ddc748f9128dab7d68e9e921d718971b271e9",
"size": "1205",
"binary": false,
"copies": "3",
"ref": "refs/heads/development",
"path": "Library/Builder/Statements/ThrowStatementBuilder.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "41"
},
{
"name": "C",
"bytes": "1503466"
},
{
"name": "C++",
"bytes": "57746"
},
{
"name": "CSS",
"bytes": "7247"
},
{
"name": "HTML",
"bytes": "14994"
},
{
"name": "JavaScript",
"bytes": "4041"
},
{
"name": "M4",
"bytes": "7155"
},
{
"name": "PHP",
"bytes": "2238333"
},
{
"name": "Shell",
"bytes": "6659"
},
{
"name": "Zephir",
"bytes": "209730"
}
],
"symlink_target": ""
} |
package nl.tudelft.lifetiles.graph.model;
import java.io.File;
import java.io.IOException;
import java.util.Map;
import nl.tudelft.lifetiles.sequence.model.Sequence;
import nl.tudelft.lifetiles.sequence.model.SequenceSegment;
/**
* Interface for Graph Parser.
*
* @author Rutger van den Berg
*/
public interface GraphParser {
/**
* @param vertexfile
* The file to retrieve vertices from.
* @param edgefile
* The file to retrieve edges from.
* @param gfact
* The graph factory to use to produce the graph.
* @return A new graph containing the parsed vertices and edges.
* @throws IOException
* When there is an error reading one of the specified files.
*/
Graph<SequenceSegment> parseGraph(final File vertexfile,
final File edgefile, GraphFactory<SequenceSegment> gfact)
throws IOException;
/**
* @return A mapping of sequencenames to sequences.
*/
Map<String, Sequence> getSequences();
}
| {
"content_hash": "a353b711e04d2ed10da521a7d092331a",
"timestamp": "",
"source": "github",
"line_count": 35,
"max_line_length": 77,
"avg_line_length": 29.742857142857144,
"alnum_prop": 0.659942363112392,
"repo_name": "jorenham/LifeTiles",
"id": "fa8bab1d6719e2dc1a554ec050dfd6e76410f2a6",
"size": "1041",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "lifetiles-graph/src/main/java/nl/tudelft/lifetiles/graph/model/GraphParser.java",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "CSS",
"bytes": "4497"
},
{
"name": "Java",
"bytes": "424384"
}
],
"symlink_target": ""
} |
Ti={Company.Name.Full} Outside Counsel Guidelines
#Notes=------------:
Overview
After incorporating sample contributions from many companies across multiple industries, CLOC is proud to author and publish a common set of Outside Counsel Guidelines. These sample guidelines are provided as a tool to assist CLOC members interested in creating a set of terms to use in retaining outside counsel. We encourage CLOC members to customize these sample guidelines to fit the needs of your organization and usage of outside counsel. We hope this guide saves you time by providing a solid starting point because as we say at CLOC, “Never start with a blank page.”
#:___________
Intro.=[G/CLOC/OutsideCounselGuidelines/Sec/Intro/0.md]
Invoice.=[G/CLOC/OutsideCounselGuidelines/Sec/Invoice/0.md]
Budget.=[G/CLOC/OutsideCounselGuidelines/Sec/Budget/0.md]
Staff.=[G/CLOC/OutsideCounselGuidelines/Sec/Staff/0.md]
Appendix.=[G/CLOC/OutsideCounselGuidelines/Sec/Appendix/0.md]
sec=<ol type=I><li>{Intro.Sec}<li>{Invoice.Sec}<li>{Budget.Sec}<li>{Staff.Sec}<li>{Appendix.Sec}</ol>
=[G/Z/Base]
#Note=Supporting Widgets
Def.Guidelines.sec={_Guidelines}
Def.Legal_Contact.sec={_Legal_Contact}
Def.ISR.sec={_ISR}
Def.RO.sec={_RO}
Def.Dispute.sec={_Dispute}
Def.Engagement_Terms.sec={_Engagement_Terms}
Def.Engagement_Letter.sec={_Engagement_Letter}
Def.Due_Date.sec={_Due_Date}
_Engagement_Letter=<a href='#Guidelines.Def.Engagement_Letter.sec' class='definedterm'>Engagement Letter</a>
_Guidelines=<a href='#Guidelines.Def.Guidelines.sec' class='definedterm'>Guidelines</a>
_Legal_Contact=<a href='#Guidelines.Def.Legal_Contact.sec' class='definedterm'>Legal Contact</a>
_ISR=<a href='#Guidelines.Def.ISR.sec' class='definedterm'>ISR</a>
_RO=<a href='#Guidelines.Def.RO.sec' class='definedterm'>RO</a>
_Dispute=<a href='#Guidelines.Def.Dispute.sec' class='definedterm'>Dispute</a>
_Engagement_Terms=<a href='#Guidelines.Def.Engagement_Terms.sec' class='definedterm'>Engagement Terms</a>
_Due_Date=<a href='#Guidelines.Def.Due_Date.sec' class='definedterm'>Due Date</a>
| {
"content_hash": "75af9c3eac5c042922be65e692866452",
"timestamp": "",
"source": "github",
"line_count": 60,
"max_line_length": 576,
"avg_line_length": 34.7,
"alnum_prop": 0.7540826128722382,
"repo_name": "CommonAccord/Cmacc-Org",
"id": "1d22cb78e87bff8301f9498053b5993dfdb0acce",
"size": "2089",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Doc/G/CLOC/OutsideCounselGuidelines/Form/0.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "4996"
},
{
"name": "HTML",
"bytes": "130299"
},
{
"name": "PHP",
"bytes": "1463"
}
],
"symlink_target": ""
} |
class Week < ActiveRecord::Base
has_many :submissions
validates :name, presence: true
validates :max_points, presence: true
end
| {
"content_hash": "42b45a0d061ed6f976ddc38dbf228661",
"timestamp": "",
"source": "github",
"line_count": 7,
"max_line_length": 39,
"avg_line_length": 19.428571428571427,
"alnum_prop": 0.7426470588235294,
"repo_name": "josalmi/lapio-stats",
"id": "1de79e7b364d3045a24a60073212f294a7dd6fe9",
"size": "136",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/models/week.rb",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "2107"
},
{
"name": "CoffeeScript",
"bytes": "422"
},
{
"name": "HTML",
"bytes": "12759"
},
{
"name": "JavaScript",
"bytes": "1014"
},
{
"name": "Ruby",
"bytes": "49924"
}
],
"symlink_target": ""
} |
using System;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.Reflection;
namespace Ssemi.Common.Core
{
public static class BinarySerialize
{
#region Binary Serialize
#region MemoryStream SerializeData(Object obj)
private static MemoryStream SerializeData(this object obj)
{
MemoryStream stream = new MemoryStream();
IFormatter formatter = new BinaryFormatter();
formatter.Serialize(stream, obj);
stream.Position = 0;
return stream;
}
#endregion
#region object DeserializeData(MemoryStream stream)
private static object DeserializeData(MemoryStream stream)
{
IFormatter formatter = new BinaryFormatter();
formatter.Binder = new BinarySerializationTypeConvertor(); // 이거 엄청 중요함. -_- WTF -_-;;
return formatter.Deserialize(stream);
}
#endregion
#region string SerializeObject(Object obj)
public static string SerializeObject(this object obj)
{
var stream = SerializeData(obj);
string s = Convert.ToBase64String(stream.ToArray());
byte[] data = TripleDES.EncryptTextToMemory(s);
return Convert.ToBase64String(data);
}
#endregion
#region T DeserializeObject<T>(string objString)
public static T DeserializeObject<T>(this string objString)
{
byte[] data = Convert.FromBase64String(objString);
string s = TripleDES.DecryptTextFromMemory(data);
byte[] buffer = Convert.FromBase64String(s);
var stream = new MemoryStream(buffer);
return (T)DeserializeData(stream);
}
#endregion
#endregion
}
#region Binary Serialize Type Converter
sealed class BinarySerializationTypeConvertor : SerializationBinder
{
public override Type BindToType(string assemblyName, string typeName)
{
Type returntype = null;
// 여기 RV5 License 만들 때
if (assemblyName == "RV5License, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" || assemblyName.Contains("R.Data"))
{
assemblyName = Assembly.GetExecutingAssembly().FullName;
//returntype = Type.GetType(String.Format("{0}, {1}", "R.Data.Entity.ServerLicense", assemblyName));
returntype = Type.GetType(String.Format("{0}, {1}", "R.Data.Entity.Enterprise.ServerLicense", "R.Data"));
return returntype;
}
//if (typeName == "System.Collections.Generic.List`1[[Mousemove.Curve,draw on desktop, Version=1.0.0.0, Culture=neutral,PublicKeyToken=null]]")
//{
// typeName = typeName.Replace("draw on desktop,Version=1.0.0.0, Culture=neutral, PublicKeyToken=null",Assembly.GetExecutingAssembly().FullName);
// returntype = Type.GetType(String.Format("{0}, {1}",typeName, assemblyName));
// return returntype;
//}
return returntype;
}
}
#endregion
}
| {
"content_hash": "b252d476a340bede0a47cfedf6723332",
"timestamp": "",
"source": "github",
"line_count": 78,
"max_line_length": 160,
"avg_line_length": 40.94871794871795,
"alnum_prop": 0.6183469004383219,
"repo_name": "ssemi/csharp-lib",
"id": "a1bea6669ab9994b3b9d8ee56fb976ccfcd535b4",
"size": "3220",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Core/File/BinarySerialize.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "542795"
}
],
"symlink_target": ""
} |
* The default config now match the Symfony's and API Platform's Best Practices (namespaces)
* The API Platform's annotation generator is enabled by default
* Use HTTPS to retrieve vocabularies by default
* Properties are generated in the order of the config file
* Properties and constants are separated by an empty line
## 1.1.2
* Fix a bug when generating enumerations
## 1.1.1
* Use the new PHP CS Fixer package
## 1.1.0
* MongoDB support
* API Platform Core v2 support
* Schema Generator is now available as PHAR
* Support any RDF vocabulary (was previously limited to Schema.org)
* Support for custom classes
* Support for [Doctrine Embeddables](http://doctrine-orm.readthedocs.io/projects/doctrine-orm/en/latest/tutorials/embeddables.html)
* Support for serialization groups
* Support for the `nullable` option
* Support for the `unique` option
* Support for custom Doctine `@Column` annotations
* Symfony 3.0 compatibility
* Various bug fixes and improved tests
## 1.0.0
* Rename the package API Platform Schema Generator (formerly PHP Schema)
* Support for external and custom RDFa schemas
* Support custom name for relation tables
* Allow to use properties from parent classes
* Allow to create custom fields
* Improve code quality and tests
## 0.4.3
* Fix compatibility with [API Platform Core](https://github.com/api-platform/core) v1 (formerly DunglasJsonLdApiBundle)
## 0.4.2
* Fix compatibility with [API Platform Core](https://github.com/api-platform/core) v1 (formerly DunglasJsonLdApiBundle)
## 0.4.1
* Make CS fixer working again
## 0.4.0
* [API Platform Core](https://github.com/api-platform/core) v1 (formerly DunglasJsonLdApiBundle) support
## 0.3.2
* Fixed Doctrine relations handling
* Better `null` value handling
## 0.3.1
* Fix a bug when using Doctrine `ArrayCollection`
* Don't call `parent::__construct()`` when the parent constructor doesn't exist
## 0.3.0
* Symfony / Doctrine's ResolveTragetEntityListener config mapping generation
* Refactored Doctrine config
* Removed deprecated call to `YAML::parse()``
## 0.2.0
* Better generated PHPDoc
* Removed `@type` support
| {
"content_hash": "50fb05bdc5b1e8edd167aed2250bc9ff",
"timestamp": "",
"source": "github",
"line_count": 74,
"max_line_length": 131,
"avg_line_length": 28.68918918918919,
"alnum_prop": 0.7597739048516251,
"repo_name": "yoan-durand/test-api-platform",
"id": "b1d4c98961444affbec8a90eac18e0b34033aa54",
"size": "2146",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "apps/platform/vendor/api-platform/schema-generator/CHANGELOG.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "102118"
},
{
"name": "HTML",
"bytes": "729"
},
{
"name": "JavaScript",
"bytes": "335574"
},
{
"name": "PHP",
"bytes": "68732"
},
{
"name": "Shell",
"bytes": "893"
},
{
"name": "TypeScript",
"bytes": "1933"
}
],
"symlink_target": ""
} |
// Copyright 2020 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <stddef.h>
#include <stdint.h>
namespace my_namespace {
class SomeClass {
public:
void Method(char) {}
int data_member;
};
// The class below deletes the |operator new| - this simulate's Blink's
// STACK_ALLOCATED macro and/or OilPan / GarbageCollected<T> classes.
class NoNewOperator {
void* operator new(size_t) = delete;
};
struct MyStruct {
// No rewrite expected for classes with no |operator new|.
NoNewOperator* no_new_ptr;
// Expected rewrite: CheckedPtr<CheckedPtr<SomeClass>> double_ptr;
// TODO(lukasza): Handle recursion/nesting.
SomeClass** double_ptr;
// Expected rewrite: CheckedPtr<void> void_ptr;
void* void_ptr;
// |bool*| used to be rewritten as |CheckedPtr<_Bool>| which doesn't compile:
// use of undeclared identifier '_Bool'.
//
// Expected rewrite: CheckedPtr<bool> bool_ptr;
bool* bool_ptr;
// Expected rewrite: CheckedPtr<const bool> bool_ptr;
const bool* const_bool_ptr;
// Some types may be spelled in various, alternative ways. If possible, the
// rewriter should preserve the original spelling.
//
// Spelling of integer types.
//
// Expected rewrite: CheckedPtr<int> ...
int* int_spelling1;
// Expected rewrite: CheckedPtr<signed int> ...
// TODO(lukasza): Fix? Today this is rewritten into: CheckedPtr<int> ...
signed int* int_spelling2;
// Expected rewrite: CheckedPtr<long int> ...
// TODO(lukasza): Fix? Today this is rewritten into: CheckedPtr<long> ...
long int* int_spelling3;
// Expected rewrite: CheckedPtr<unsigned> ...
// TODO(lukasza): Fix? Today this is rewritten into: CheckedPtr<unsigned int>
unsigned* int_spelling4;
// Expected rewrite: CheckedPtr<int32_t> ...
int32_t* int_spelling5;
// Expected rewrite: CheckedPtr<int64_t> ...
int64_t* int_spelling6;
// Expected rewrite: CheckedPtr<int_fast32_t> ...
int_fast32_t* int_spelling7;
//
// Spelling of structs and classes.
//
// Expected rewrite: CheckedPtr<SomeClass> ...
SomeClass* class_spelling1;
// Expected rewrite: CheckedPtr<class SomeClass> ...
class SomeClass* class_spelling2;
// Expected rewrite: CheckedPtr<my_namespace::SomeClass> ...
my_namespace::SomeClass* class_spelling3;
// No rewrite of function pointers expected, because they won't ever be either
// A) allocated by PartitionAlloc or B) derived from CheckedPtrSupport. In
// theory |member_data_ptr| below can be A or B, but it can't be expressed as
// non-pointer T used as a template argument of CheckedPtr.
int (*func_ptr)();
void (SomeClass::*member_func_ptr)(char); // ~ pointer to SomeClass::Method
int SomeClass::*member_data_ptr; // ~ pointer to SomeClass::data_member
typedef void (*func_ptr_typedef)(char);
func_ptr_typedef func_ptr_typedef_field;
// Typedef-ed or type-aliased pointees should participate in the rewriting. No
// desugaring of the aliases is expected.
typedef SomeClass SomeClassTypedef;
using SomeClassAlias = SomeClass;
typedef void (*func_ptr_typedef2)(char);
// Expected rewrite: CheckedPtr<SomeClassTypedef> ...
SomeClassTypedef* typedef_ptr;
// Expected rewrite: CheckedPtr<SomeClassAlias> ...
SomeClassAlias* alias_ptr;
// Expected rewrite: CheckedPtr<func_ptr_typedef2> ...
func_ptr_typedef2* ptr_to_function_ptr;
// Typedefs and type alias definitions should not be rewritten.
//
// No rewrite expected (for now - in V1 we only rewrite field decls).
typedef SomeClass* SomeClassPtrTypedef;
// No rewrite expected (for now - in V1 we only rewrite field decls).
using SomeClassPtrAlias = SomeClass*;
// Chromium is built with a warning/error that there are no user-defined
// constructors invoked when initializing global-scoped values.
// CheckedPtr<char> conversion might trigger a global constructor for string
// literals:
// struct MyStruct {
// int foo;
// CheckedPtr<const char> bar;
// }
// MyStruct g_foo = {123, "string literal" /* global constr! */};
// Because of the above, no rewrite is expected below.
char* char_ptr;
const char* const_char_ptr;
wchar_t* wide_char_ptr;
const wchar_t* const_wide_char_ptr;
// |array_of_ptrs| is an array 123 of pointer to SomeClass.
// No rewrite expected (this is not a pointer - this is an array).
SomeClass* ptr_array[123];
// |ptr_to_array| is a pointer to array 123 of const SomeClass.
//
// This test is based on EqualsFramesMatcher from
// //net/websockets/websocket_channel_test.cc
//
// No rewrite expected (this *is* a pointer, but generating a correct
// replacement is tricky, because the |replacement_range| needs to cover
// "[123]" that comes *after* the field name).
const SomeClass (*ptr_to_array)[123];
};
} // namespace my_namespace
| {
"content_hash": "60cf2e0247272a6c72ebcd9831f781f8",
"timestamp": "",
"source": "github",
"line_count": 132,
"max_line_length": 80,
"avg_line_length": 37.32575757575758,
"alnum_prop": 0.7026588187538055,
"repo_name": "endlessm/chromium-browser",
"id": "ed231b983cc10c0114a72bbb6cb7c45be467da0c",
"size": "4927",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "tools/clang/rewrite_raw_ptr_fields/tests/various-types-original.cc",
"mode": "33188",
"license": "bsd-3-clause",
"language": [],
"symlink_target": ""
} |
package edu.umuc.cmis141.homework1;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* Homework1 Assignment.
*
* The Homework1 program is built to display the area of a circle.
*
* Javadoc Generated Documentation is available:
* http://benbunk.github.io/CMIS141/Homework1/project-reports.html
*
* Homework 1
* CMIS 141 6980 Introductory Programming (2142)
* Feb. 7, 2014
*
* @author Benjamin Bunk
* @version 1.0-DEV
*/
public class BenjaminBunkhw1Test {
/**
* Test cases 1-4 from BenjaminBunkhw1.docx
*/
//@Test
/*public void testGetArea() {
// Test 1
assertEquals(BenjaminBunkhw1.getArea(10.0), 314.0, 10.0);
// Test 2
assertEquals(BenjaminBunkhw1.getArea(0.0), 0.0, 10.0);
// Test 3
assertEquals(BenjaminBunkhw1.getArea(.01), 0.000314, 10.0);
// Test 4
assertEquals(BenjaminBunkhw1.getArea(10000000.), 314000000000000.0, 10.0);
}*/
/**
* Test case 5 from BenjaminBunkhw1.docx
*/
//@Test(expected = IllegalArgumentException.class)
/*public void testGetAreaIllegal() {
BenjaminBunkhw1.getArea(-1);
}*/
/**
* Test output method is working as expected.
*/
//@Test
/*public void testGetMessage() {
double radius = 10.0;
double area = BenjaminBunkhw1.getArea(radius);
assertEquals(BenjaminBunkhw1.getMessage(radius, area),
"The area of a circle with a given radius 10.0 is 314.0");
}*/
}
| {
"content_hash": "65972a2100724dae3467b38dcf3e8ea6",
"timestamp": "",
"source": "github",
"line_count": 56,
"max_line_length": 82,
"avg_line_length": 26.821428571428573,
"alnum_prop": 0.6331557922769641,
"repo_name": "benbunk/CMIS141",
"id": "458feabdaa95406ee1bdfa65009f7f95773062c0",
"size": "1502",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Homework1/src/test/java/edu/umuc/cmis141/homework1/BenjaminBunkhw1Test.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "65916"
}
],
"symlink_target": ""
} |
* Added ``binDir`` option to specify where the build output should be placed
(Thank you [@minciue](https://github.com/minciue)).
* Fixed deprecated code (Thank you [@lou15b](https://github.com/lou15b)).
* Fixes to old ``.babel`` folder handling
(Thank you [@ClementJnc](https://github.com/ClementJnc)).
* Added ability to list only the installed packages via
``nimble list --installed`` (Thank you
[@hiteshjasani](https://github.com/hiteshjasani).
* Fixes compilation with Nim v0.11.2 (Thank you
[@JCavallo](https://github.com/JCavallo)).
* Implements the ``--nimbleDir`` option (Thank you
[@ClementJnc](https://github.com/ClementJnc)).
* [Fixes](https://github.com/nim-lang/nimble/issues/128) ``nimble uninstall``
not giving an error when no package name is
specified (Thank you [@dom96](https://github.com/dom96)).
* [When](https://github.com/nim-lang/nimble/issues/139) installing and building
a tagged version of a package fails, Nimble will
now attempt to install and build the ``#head`` of the repo
(Thank you [@dom96](https://github.com/dom96)).
* [Fixed](https://github.com/nim-lang/nimble/commit/1234cdce13c1f1b25da7980099cffd7f39b54326)
cloning of git repositories with non-standard default branches
(Thank you [@dom96](https://github.com/dom96)).
----
Full changelog: https://github.com/nim-lang/nimble/compare/v0.6...v0.6.2
## 0.6.0 - 26/12/2014
* Renamed from Babel to Nimble
* Introduces compatibility with Nim v0.10.0+
* Implemented the ``init`` command which generates a .nimble file for new
projects. (Thank you
[@singularperturbation](https://github.com/singularperturbation))
* Improved cloning of git repositories.
(Thank you [@gradha](https://github.com/gradha))
* Fixes ``path`` command issues (Thank you [@gradha](https://github.com/gradha))
* Fixes problems with symlinking when there is a space in the path.
(Thank you [@philip-wernersbach](https://github.com/philip-wernersbach))
* The code page will now be changed when executing Nimble binary packages.
This adds support for Unicode in cmd.exe (#54).
* ``.cmd`` files are now used in place of ``.bat`` files. Shell files for
Cygwin/Git bash are also now created.
## 0.4.0 - 24/06/2014
* Introduced the ability to delete packages.
* When installing packages, a list of files which have been copied is stored
in the babelmeta.json file.
* When overwriting an already installed package babel will no longer delete
the whole directory but only the files which it installed.
* Versions are now specified on the command line after the '@' character when
installing and uninstalling packages. For example: ``babel install foobar@0.1``
and ``babel install foobar@#head``.
* The babel package installation directory can now be changed in the new
config.
* Fixes a number of issues.
| {
"content_hash": "c8c5274736c9cf02312361e620de7d79",
"timestamp": "",
"source": "github",
"line_count": 57,
"max_line_length": 93,
"avg_line_length": 49.21052631578947,
"alnum_prop": 0.7358288770053476,
"repo_name": "Araq/nimble",
"id": "f4262b11d803f48eb07e82143cbac77d11730eda",
"size": "2847",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "changelog.markdown",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Nimrod",
"bytes": "88122"
}
],
"symlink_target": ""
} |
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1.0"/>
<title>Portal Educação</title>
<script src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
<script src="../../template/js/materialize.js"></script>
<script src="../../template/js/init.js"></script>
<script src="script.js"></script>
<!-- CSS -->
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<link href="../../styles/css/materialize.css" type="text/css" rel="stylesheet" media="screen,projection"/>
<link href="../../styles/css/style.css" type="text/css" rel="stylesheet" media="screen,projection"/>
<link rel="icon" href="../../imgs/logo.png" >
<link rel="stylesheet" type="text/css" href="estilo.css">
<style type="text/css">
body {
display: flex;
min-height: 100vh;
flex-direction: column;
}
main {
flex: 1 0 auto;
}
</style>
<link rel="icon" href="../../imgs/logo.png" >
</head>
<body>
<nav class="light-blue darken-4" role="navigation">
<div class="nav-wrapper container">
<!-- MENU SLIDE OUT STRUCTURE-->
<ul id="slide-out" class="side-nav">
<br>
<li>
<div class="logo">
<img class="background center-block responsive" src="../../imgs/logo.png">
</div>
</li>
<br>
<li><a class="waves-effect" href="../../index.html">Página Inicial</a></li>
<li><a class="waves-effect" href="pagInicial.html">Modelo de Provas/Trabalhos</a></li>
<li><a class="waves-effect" href="../../Forum/Web/Fórum.html">Fórum</a></li>
<li><a class="waves-effect" href="../../Upload/index.html">Download/Upload Aplicativos</a></li>
<li><a class="waves-effect" href="../../Correcao/LayoutCorrecaoProvas.html">Correção Provas e Trabalhos</a></li>
<li><a class="waves-effect" href="../../Mural/web/index.html">Mural</a></li>
<li><a class="waves-effect" href="#!">Chat</a></li>
<li><a class="waves-effect" href="#!">Repositório de Fotos</a></li>
<li><a class="waves-effect" href="#!">Banco de Questões</a></li>
<li><a class="waves-effect" href="#!">Calendário</a></li>
<!--<li><div class="divider"></div></li>-->
<!--<li><a class="subheader">Subheader</a></li>-->
</ul>
<ul class="left ">
<li>
<button data-activates="slide-out" class="waves-effect waves-light btn-flat button-collapse white-text light-blue darken-4">Menu</button>
</li>
</ul>
<ul class="right ">
<!-- <li><button class="waves-effect waves-light btn-flat white-text light-blue darken-4">Entrar</button></li> -->
<li><a class="waves-effect waves-light btn modal-trigger white-text light-blue darken-3" href="#modal1">Entrar</a></li>
</ul>
</div>
</nav>
<!-- Modal de login -->
<div id="modal1" class="modal modal-fixed-footer">
<div class="modal-content">
<h4>Login</h4>
<div class="row">
<p>Insira dados</p>
<form>
<label for="username">Nome de usuario</label>
<input type="text" name="username">
<label for="senha">Senha</label>
<input type="password" name="senha">
<label for="tipoUsuario">Tipo de usuário</label>
<select name="tipoUsuario">
<option value="" disabled selected>Tipo de Usuario</option>
<option value="1">Aluno</option>
<option value="2">Professor</option>
<option value="3">Coordenador</option>
<option value="4">Diretor</option>
</select>
<button class="col s12 btn-flat waves-effect waves-light green white-text" type="submit" name="action">Entrar
<i class="material-icons right">input</i>
</button>
</form>
</div>
</div>
<div class="modal-footer">
<a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat red white-text">Sair</a>
</div>
</div>
<!-- ESPAÇO PARA MARQUEE -->
<div>
</div>
<main>
<div class="section no-pad-bot" id="index-banner">
<div class="container">
<br><br>
<h1 class="header center blue-text text-darken-4">Modelos de Provas e Trabalhos</h1>
<div class="row center">
<h5 class="header col s12 light">Faça Seu Cabeçalho</h5>
<br><br><br><br>
<a href="formulario.html" class="waves-effect waves-light blue darken-4 btn"><i class="material-icons left">cloud</i>Novo Arquivo</a> 
<a href="formEdicao.php" class="waves-effect waves-light blue darken-4 btn"><i class="material-icons left">cloud</i>Editar</a>
</div>
<br><br><br><br>
</div>
</div>
</main>
</div>
</div>
</div>
</div>
</main>
<footer class="page-footer blue">
<div class="container">
<div class="row">
<div class="col l6 s12">
<h5 class="white-text">Desenvolvedores</h5>
<p class="grey-text text-lighten-4">
Somos a turma de Informática 2A do ano de 2016 do CEFET-MG (Centro Federal de Educação Tecnológica de Minas Gerais) desenvolvendo o trabalho final multidisciplinar de Linguagem de Programação 1 e Aplicações para WEB.
<br><a class="white-text link" href="../../colaboradores.html">Clique aqui</a> para saber mais
</p>
</div>
<div class="col l3 s12">
<h5 class="white-text">Sobre a Instituição</h5>
<p class="grey-text text-lighten-4">
Centro Federal de Educação Tecnológica de Minas Gerais
<br>Av. Amazonas 5253 - Nova Suiça - Belo Horizonte - MG - Brasil
<br>Telefone: +55 (31) 3319-7000 - Fax: +55 (31) 3319-7001
</p>
</div>
<div class="col l3 s12">
<h5 class="white-text">Recursos</h5>
<ul>
<li><a class="white-text link" href="https://github.com/cefet-inf-2015/portal-educacao/" target="_blank">Github</a></li>
<li><a class="white-text link" href="http://cefetmg.br/" target="_blank">CEFET-MG</a></li>
</ul>
</div>
</div>
</div>
<div class="footer-copyright">
<div class="container">
Made by <a class="blue-text text-lighten-3" href="http://materializecss.com">Materialize</a>
</div>
</div>
</footer>
<!-- Scripts-->
<script src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
<script src="../../template/js/materialize.js"></script>
<script src="../../template/js/init.js"></script>
<script src="../../index.js"></script>
</body>
</html>
| {
"content_hash": "1471350d07843deed8b1565ccc533966",
"timestamp": "",
"source": "github",
"line_count": 172,
"max_line_length": 228,
"avg_line_length": 39.26744186046512,
"alnum_prop": 0.5817293455729938,
"repo_name": "Haddadson/portal-educacao",
"id": "62856837da821b6e09eb7ce8351d7b75d5688d7e",
"size": "6782",
"binary": false,
"copies": "8",
"ref": "refs/heads/master",
"path": "Modelo de Provas e Trabalhos/web/pagInicial.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "2291"
},
{
"name": "CSS",
"bytes": "783474"
},
{
"name": "HTML",
"bytes": "7343216"
},
{
"name": "Java",
"bytes": "1812510"
},
{
"name": "JavaScript",
"bytes": "1015535"
},
{
"name": "PHP",
"bytes": "1020927"
},
{
"name": "Shell",
"bytes": "2101"
}
],
"symlink_target": ""
} |
/*global QUnit*/
/**
* General consistency checks on designtime metadata of controls in the sap.ui.layout library
*/
sap.ui.require(["sap/ui/dt/test/LibraryTest"], function (LibraryTest) {
"use strict";
LibraryTest("sap.ui.layout", QUnit);
});
| {
"content_hash": "17a3cecb4e8111d0cd526672ad64e739",
"timestamp": "",
"source": "github",
"line_count": 9,
"max_line_length": 93,
"avg_line_length": 27.666666666666668,
"alnum_prop": 0.7108433734939759,
"repo_name": "nzamani/openui5",
"id": "f537af636f072f4e240e924a57aad2eae7c9c014",
"size": "249",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "src/sap.ui.layout/test/sap/ui/layout/qunit/designtime/Library.qunit.js",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "2853775"
},
{
"name": "Gherkin",
"bytes": "17351"
},
{
"name": "HTML",
"bytes": "17332110"
},
{
"name": "Java",
"bytes": "83480"
},
{
"name": "JavaScript",
"bytes": "44924427"
}
],
"symlink_target": ""
} |
package scheme
import (
admissionv1alpha1 "k8s.io/api/admission/v1beta1"
admissionregistrationv1beta1 "k8s.io/api/admissionregistration/v1beta1"
appsv1 "k8s.io/api/apps/v1"
appsv1beta1 "k8s.io/api/apps/v1beta1"
appsv1beta2 "k8s.io/api/apps/v1beta2"
authenticationv1 "k8s.io/api/authentication/v1"
authenticationv1beta1 "k8s.io/api/authentication/v1beta1"
authorizationv1 "k8s.io/api/authorization/v1"
authorizationv1beta1 "k8s.io/api/authorization/v1beta1"
autoscalingv1 "k8s.io/api/autoscaling/v1"
autoscalingv2beta1 "k8s.io/api/autoscaling/v2beta1"
batchv1 "k8s.io/api/batch/v1"
batchv1beta1 "k8s.io/api/batch/v1beta1"
batchv2alpha1 "k8s.io/api/batch/v2alpha1"
certificatesv1beta1 "k8s.io/api/certificates/v1beta1"
corev1 "k8s.io/api/core/v1"
extensionsv1beta1 "k8s.io/api/extensions/v1beta1"
imagepolicyv1alpha1 "k8s.io/api/imagepolicy/v1alpha1"
networkingv1 "k8s.io/api/networking/v1"
policyv1beta1 "k8s.io/api/policy/v1beta1"
rbacv1 "k8s.io/api/rbac/v1"
rbacv1alpha1 "k8s.io/api/rbac/v1alpha1"
rbacv1beta1 "k8s.io/api/rbac/v1beta1"
schedulingv1alpha1 "k8s.io/api/scheduling/v1alpha1"
settingsv1alpha1 "k8s.io/api/settings/v1alpha1"
storagev1 "k8s.io/api/storage/v1"
storagev1beta1 "k8s.io/api/storage/v1beta1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
metav1beta1 "k8s.io/apimachinery/pkg/apis/meta/v1beta1"
"k8s.io/apimachinery/pkg/runtime/schema"
utilruntime "k8s.io/apimachinery/pkg/util/runtime"
"k8s.io/client-go/kubernetes/scheme"
)
// Register all groups in the kubectl's registry, but no componentconfig group since it's not in k8s.io/api
// The code in this file mostly duplicate the install under k8s.io/kubernetes/pkg/api and k8s.io/kubernetes/pkg/apis,
// but does NOT register the internal types.
func init() {
// Register external types for Scheme
metav1.AddToGroupVersion(Scheme, schema.GroupVersion{Version: "v1"})
utilruntime.Must(metav1beta1.AddMetaToScheme(Scheme))
utilruntime.Must(metav1.AddMetaToScheme(Scheme))
utilruntime.Must(scheme.AddToScheme(Scheme))
utilruntime.Must(Scheme.SetVersionPriority(corev1.SchemeGroupVersion))
utilruntime.Must(Scheme.SetVersionPriority(admissionv1alpha1.SchemeGroupVersion))
utilruntime.Must(Scheme.SetVersionPriority(admissionregistrationv1beta1.SchemeGroupVersion))
utilruntime.Must(Scheme.SetVersionPriority(appsv1beta1.SchemeGroupVersion, appsv1beta2.SchemeGroupVersion, appsv1.SchemeGroupVersion))
utilruntime.Must(Scheme.SetVersionPriority(authenticationv1.SchemeGroupVersion, authenticationv1beta1.SchemeGroupVersion))
utilruntime.Must(Scheme.SetVersionPriority(authorizationv1.SchemeGroupVersion, authorizationv1beta1.SchemeGroupVersion))
utilruntime.Must(Scheme.SetVersionPriority(autoscalingv1.SchemeGroupVersion, autoscalingv2beta1.SchemeGroupVersion))
utilruntime.Must(Scheme.SetVersionPriority(batchv1.SchemeGroupVersion, batchv1beta1.SchemeGroupVersion, batchv2alpha1.SchemeGroupVersion))
utilruntime.Must(Scheme.SetVersionPriority(certificatesv1beta1.SchemeGroupVersion))
utilruntime.Must(Scheme.SetVersionPriority(extensionsv1beta1.SchemeGroupVersion))
utilruntime.Must(Scheme.SetVersionPriority(imagepolicyv1alpha1.SchemeGroupVersion))
utilruntime.Must(Scheme.SetVersionPriority(networkingv1.SchemeGroupVersion))
utilruntime.Must(Scheme.SetVersionPriority(policyv1beta1.SchemeGroupVersion))
utilruntime.Must(Scheme.SetVersionPriority(rbacv1.SchemeGroupVersion, rbacv1beta1.SchemeGroupVersion, rbacv1alpha1.SchemeGroupVersion))
utilruntime.Must(Scheme.SetVersionPriority(schedulingv1alpha1.SchemeGroupVersion))
utilruntime.Must(Scheme.SetVersionPriority(settingsv1alpha1.SchemeGroupVersion))
utilruntime.Must(Scheme.SetVersionPriority(storagev1.SchemeGroupVersion, storagev1beta1.SchemeGroupVersion))
}
| {
"content_hash": "5ea6790afb613329043b9c9a68b571e8",
"timestamp": "",
"source": "github",
"line_count": 67,
"max_line_length": 139,
"avg_line_length": 55.88059701492537,
"alnum_prop": 0.8389423076923077,
"repo_name": "NickrenREN/kubernetes",
"id": "76a0578dc1937f44283e359fc8af69343aa487e3",
"size": "4313",
"binary": false,
"copies": "5",
"ref": "refs/heads/master",
"path": "pkg/kubectl/scheme/install.go",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "2840"
},
{
"name": "Dockerfile",
"bytes": "63039"
},
{
"name": "Go",
"bytes": "47186472"
},
{
"name": "HTML",
"bytes": "38"
},
{
"name": "Lua",
"bytes": "17200"
},
{
"name": "Makefile",
"bytes": "77502"
},
{
"name": "PowerShell",
"bytes": "99342"
},
{
"name": "Python",
"bytes": "3234296"
},
{
"name": "Ruby",
"bytes": "431"
},
{
"name": "Shell",
"bytes": "1570893"
},
{
"name": "sed",
"bytes": "12323"
}
],
"symlink_target": ""
} |
<!doctype html public "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">
<html>
<head>
<title>PHPXRef 0.7.1 : Unnamed Project : Variable Reference: $ignore</title>
<link rel="stylesheet" href="../sample.css" type="text/css">
<link rel="stylesheet" href="../sample-print.css" type="text/css" media="print">
<style id="hilight" type="text/css"></style>
<meta http-equiv="content-type" content="text/html;charset=iso-8859-1">
</head>
<body bgcolor="#ffffff" text="#000000" link="#801800" vlink="#300540" alink="#ffffff">
<table class="pagetitle" width="100%">
<tr>
<td valign="top" class="pagetitle">
[ <a href="../index.html">Index</a> ]
</td>
<td align="right" class="pagetitle">
<h2 style="margin-bottom: 0px">PHP Cross Reference of Unnamed Project</h2>
</td>
</tr>
</table>
<!-- Generated by PHPXref 0.7.1 at Thu Oct 23 19:31:09 2014 -->
<!-- PHPXref (c) 2000-2010 Gareth Watts - gareth@omnipotent.net -->
<!-- http://phpxref.sourceforge.net/ -->
<script src="../phpxref.js" type="text/javascript"></script>
<script language="JavaScript" type="text/javascript">
<!--
ext='.html';
relbase='../';
subdir='_variables';
filename='index.html';
cookiekey='phpxref';
handleNavFrame(relbase, subdir, filename);
logVariable('ignore');
// -->
</script>
<script language="JavaScript" type="text/javascript">
if (gwGetCookie('xrefnav')=='off')
document.write('<p class="navlinks">[ <a href="javascript:navOn()">Show Explorer<\/a> ]<\/p>');
else
document.write('<p class="navlinks">[ <a href="javascript:navOff()">Hide Explorer<\/a> ]<\/p>');
</script>
<noscript>
<p class="navlinks">
[ <a href="../nav.html" target="_top">Show Explorer</a> ]
[ <a href="index.html" target="_top">Hide Navbar</a> ]
</p>
</noscript>
[<a href="../index.html">Top level directory</a>]<br>
<script language="JavaScript" type="text/javascript">
<!--
document.writeln('<table align="right" class="searchbox-link"><tr><td><a class="searchbox-link" href="javascript:void(0)" onMouseOver="showSearchBox()">Search</a><br>');
document.writeln('<table border="0" cellspacing="0" cellpadding="0" class="searchbox" id="searchbox">');
document.writeln('<tr><td class="searchbox-title">');
document.writeln('<a class="searchbox-title" href="javascript:showSearchPopup()">Search History +</a>');
document.writeln('<\/td><\/tr>');
document.writeln('<tr><td class="searchbox-body" id="searchbox-body">');
document.writeln('<form name="search" style="margin:0px; padding:0px" onSubmit=\'return jump()\'>');
document.writeln('<a class="searchbox-body" href="../_classes/index.html">Class<\/a>: ');
document.writeln('<input type="text" size=10 value="" name="classname"><br>');
document.writeln('<a id="funcsearchlink" class="searchbox-body" href="../_functions/index.html">Function<\/a>: ');
document.writeln('<input type="text" size=10 value="" name="funcname"><br>');
document.writeln('<a class="searchbox-body" href="../_variables/index.html">Variable<\/a>: ');
document.writeln('<input type="text" size=10 value="" name="varname"><br>');
document.writeln('<a class="searchbox-body" href="../_constants/index.html">Constant<\/a>: ');
document.writeln('<input type="text" size=10 value="" name="constname"><br>');
document.writeln('<a class="searchbox-body" href="../_tables/index.html">Table<\/a>: ');
document.writeln('<input type="text" size=10 value="" name="tablename"><br>');
document.writeln('<input type="submit" class="searchbox-button" value="Search">');
document.writeln('<\/form>');
document.writeln('<\/td><\/tr><\/table>');
document.writeln('<\/td><\/tr><\/table>');
// -->
</script>
<div id="search-popup" class="searchpopup"><p id="searchpopup-title" class="searchpopup-title">title</p><div id="searchpopup-body" class="searchpopup-body">Body</div><p class="searchpopup-close"><a href="javascript:gwCloseActive()">[close]</a></p></div>
<h3>Variable Cross Reference</h3>
<h2><a href="index.html#ignore">$ignore</a></h2>
<br><b>Referenced 1 times:</b><ul>
<li><a href="../system/database/drivers/mysql/mysql_utility.php.html">/system/database/drivers/mysql/mysql_utility.php</a> -> <a href="../system/database/drivers/mysql/mysql_utility.php.source.html#l93"> line 93</a></li>
</ul>
<!-- A link to the phpxref site in your customized footer file is appreciated ;-) -->
<br><hr>
<table width="100%">
<tr><td>Generated: Thu Oct 23 19:31:09 2014</td>
<td align="right"><i>Cross-referenced by <a href="http://phpxref.sourceforge.net/">PHPXref 0.7.1</a></i></td>
</tr>
</table>
</body></html>
| {
"content_hash": "af5ee88c1a1763ec3bcd31da0b2e5baf",
"timestamp": "",
"source": "github",
"line_count": 93,
"max_line_length": 253,
"avg_line_length": 49.18279569892473,
"alnum_prop": 0.6679055531263665,
"repo_name": "inputx/code-ref-doc",
"id": "9f53a651a94bf1ec75e3ac47a8fbe1e932a416a7",
"size": "4574",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "codeigniter/_variables/ignore.html",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "17952"
},
{
"name": "JavaScript",
"bytes": "255489"
}
],
"symlink_target": ""
} |
package org.spongepowered.api.event.message;
import org.spongepowered.api.event.GameEvent;
import org.spongepowered.api.text.Text;
import org.spongepowered.api.text.sink.MessageSink;
import org.spongepowered.api.util.command.CommandSource;
/**
* Describes events when a {@link CommandSource} sends a {@link Text} message.
*/
public interface MessageEvent extends GameEvent {
/**
* Gets the {@link CommandSource} of the event which may
* or may not be a target of the {@link Text}.
*
* @return The source
*/
CommandSource getSource();
/**
* Gets the {@link Text} message created by the {@link CommandSource} before
* the calling of this event.
*
* @return The message
*/
Text getMessage();
/**
* Gets the currently set {@link Text} message.
*
* @return The message
*/
Text getNewMessage();
/**
* Sets the {@link Text} message.
*
* @param message The new message
*/
void setNewMessage(Text message);
/**
* Gets the current sink that this message will be sent to.
*
* @return The message sink the message in this event will be sent to
*/
MessageSink getSink();
/**
* Set the target for this message to go to.
*
* @param sink The sink to set
*/
void setSink(MessageSink sink);
}
| {
"content_hash": "1fee68bc1fecb76f06b67ca4d03ad887",
"timestamp": "",
"source": "github",
"line_count": 58,
"max_line_length": 80,
"avg_line_length": 23.53448275862069,
"alnum_prop": 0.6285714285714286,
"repo_name": "caseif/SpongeAPI",
"id": "8c0cfa73e7adb654eed112a0b1f2e7ee72885dd9",
"size": "2615",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "src/main/java/org/spongepowered/api/event/message/MessageEvent.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "3364181"
},
{
"name": "Shell",
"bytes": "77"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="utf-8"?>
<!--
~ Copyright (c) 2010-2011, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
~
~ Licensed under the Apache License, Version 2.0 (the "License");
~ you may not use this file except in compliance with the License.
~ You may obtain a copy of the License at
~
~ http://www.apache.org/licenses/LICENSE-2.0
~
~ Unless required by applicable law or agreed to in writing, software
~ distributed under the License is distributed on an "AS IS" BASIS,
~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
~ See the License for the specific language governing permissions and
~ limitations under the License.
-->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<parent>
<groupId>org.wso2.carbon.mobile.appmgt</groupId>
<artifactId>carbon-mobile-appmgt</artifactId>
<version>2.0.0-SNAPSHOT</version>
<relativePath>../../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>org.wso2.carbon.appmgt.core.feature</artifactId>
<packaging>pom</packaging>
<name>WSO2 Carbon - App management Core Feature</name>
<url>http://wso2.org</url>
<description>This feature contains the core bundles required for getting light weight App Management functionalities.</description>
<dependencies>
<dependency>
<groupId>org.wso2.carbon</groupId>
<artifactId>org.wso2.carbon.registry.core</artifactId>
</dependency>
<dependency>
<groupId>org.wso2.carbon.registry</groupId>
<artifactId>org.wso2.carbon.registry.ws.client</artifactId>
</dependency>
<dependency>
<groupId>org.wso2.carbon.governance</groupId>
<artifactId>org.wso2.carbon.governance.api</artifactId>
</dependency>
<dependency>
<groupId>org.wso2.carbon.mobile.appmgt</groupId>
<artifactId>org.wso2.carbon.appmgt.api</artifactId>
</dependency>
<dependency>
<groupId>org.wso2.carbon.mobile.appmgt</groupId>
<artifactId>org.wso2.carbon.appmgt.impl</artifactId>
</dependency>
<dependency>
<groupId>org.wso2.carbon.mobile.appmgt</groupId>
<artifactId>org.wso2.carbon.appmgt.hostobjects</artifactId>
</dependency>
<dependency>
<groupId>org.wso2.carbon.mobile.appmgt</groupId>
<artifactId>org.wso2.carbon.appmgt.core</artifactId>
</dependency>
<dependency>
<groupId>org.wso2.carbon.identity.framework</groupId>
<artifactId>org.wso2.carbon.identity.core</artifactId>
</dependency>
<dependency>
<groupId>org.wso2.carbon</groupId>
<artifactId>org.wso2.carbon.bam.presentation.stub</artifactId>
</dependency>
<dependency>
<groupId>org.wso2.carbon.mediation</groupId>
<artifactId>org.wso2.carbon.mediation.security.stub</artifactId>
</dependency>
<dependency>
<groupId>org.wso2.carbon.mobile.appmgt</groupId>
<artifactId>org.wso2.carbon.appmgt.oauth.endpoint</artifactId>
<type>war</type>
</dependency>
<!-- Entitlement Dependencies -->
<dependency>
<groupId>org.wso2.carbon.identity.framework</groupId>
<artifactId>org.wso2.carbon.identity.entitlement.stub</artifactId>
</dependency>
<dependency>
<groupId>org.wso2.carbon.identity.agent.entitlement.mediator</groupId>
<artifactId>org.wso2.carbon.identity.entitlement.proxy</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-antrun-plugin</artifactId>
<version>1.1</version>
<executions>
<execution>
<id>clean-APIM-h2-database</id>
<phase>prepare-package</phase>
<goals>
<goal>run</goal>
</goals>
<configuration>
<tasks>
<delete file="src/main/resources/repository/database/WSO2AM_DB.h2.db" />
</tasks>
</configuration>
</execution>
<execution>
<id>create-APP-manager-database</id>
<phase>package</phase>
<goals>
<goal>run</goal>
</goals>
<configuration>
<tasks>
<path id="h2.classpath">
<path refid="maven.compile.classpath" />
</path>
<echo message="########### Creating APP Manager Database ##############" />
<sql driver="org.h2.Driver" url="jdbc:h2:${basedir}/src/main/resources/repository/database/WSO2AM_DB;create=true" userid="wso2carbon" password="wso2carbon" autocommit="true" onerror="continue">
<classpath>
<path refid="h2.classpath" />
</classpath>
<fileset file="${basedir}/src/main/resources/sql/h2.sql" />
</sql>
<echo message="##################### END ########################" />
</tasks>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<artifactId>maven-resources-plugin</artifactId>
<executions>
<execution>
<id>copy-resources</id>
<!--phase>generate-resources</phase-->
<phase>package</phase>
<goals>
<goal>copy-resources</goal>
</goals>
<configuration>
<outputDirectory>src/main/resources</outputDirectory>
<resources>
<resource>
<directory>resources</directory>
<includes>
<include>conf/app-manager.xml</include>
<include>conf/master-datasources.xml</include>
<include>conf/WSO2AM_DB.h2.db</include>
<include>**/*.sql</include>
<include>p2.inf</include>
<include>build.properties</include>
</includes>
</resource>
</resources>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.wso2.maven</groupId>
<artifactId>carbon-p2-plugin</artifactId>
<version>${carbon.p2.plugin.version}</version>
<executions>
<execution>
<id>4-p2-feature-generation</id>
<phase>package</phase>
<goals>
<goal>p2-feature-gen</goal>
</goals>
<configuration>
<id>org.wso2.carbon.appmgt.core</id>
<propertiesFile>../etc/feature.properties</propertiesFile>
<adviceFile>
<properties>
<propertyDef>org.wso2.carbon.p2.category.type:server
</propertyDef>
<propertyDef>org.eclipse.equinox.p2.type.group:false
</propertyDef>
</properties>
</adviceFile>
<bundles>
<bundleDef>org.wso2.carbon.mobile.appmgt:org.wso2.carbon.appmgt.api:${carbon.mobile.appmgt.version}</bundleDef>
<bundleDef>org.wso2.carbon.mobile.appmgt:org.wso2.carbon.appmgt.impl:${carbon.mobile.appmgt.version}</bundleDef>
<bundleDef>org.wso2.carbon.mobile.appmgt:org.wso2.carbon.appmgt.hostobjects:${carbon.mobile.appmgt.version}</bundleDef>
<bundleDef>org.wso2.carbon.mobile.appmgt:org.wso2.carbon.appmgt.core:${carbon.mobile.appmgt.version}</bundleDef>
<bundleDef>org.wso2.carbon.mediation:org.wso2.carbon.sequences.stub:${carbon.sequences.stub.version}</bundleDef>
<bundleDef>org.wso2.carbon.identity.framework:org.wso2.carbon.identity.user.registration.stub:compatible:${carbon-identity-framework.version}</bundleDef>
<bundleDef>org.wso2.carbon:org.wso2.carbon.bam.presentation.stub:compatible:${bam.presentation.stub.version}</bundleDef>
<bundleDef>org.wso2.carbon.mediation:org.wso2.carbon.mediation.security.stub:compatible:${carbon.mediation.security.stub}</bundleDef>
<bundleDef>org.wso2.carbon.identity.framework:org.wso2.carbon.identity.entitlement.stub:compatible:${carbon-identity-framework.version}</bundleDef>
<bundleDef>org.wso2.carbon.identity.framework:org.wso2.carbon.identity.base:compatible:${carbon-identity-framework.version}</bundleDef>
<bundleDef>org.wso2.carbon.identity.agent.entitlement.mediator:org.wso2.carbon.identity.entitlement.proxy:compatible:${identity-agent-entitlement-proxy.version}</bundleDef>
<bundleDef>org.wso2.carbon.identity.metadata.saml2:org.wso2.carbon.identity.sp.metadata.saml2:compatible:0.1.6</bundleDef>
<bundleDef>org.wso2.carbon:org.wso2.carbon.webapp.mgt.stub:${carbon.webapp.mgt.stub}</bundleDef>
<bundleDef>org.apache.velocity:velocity:${apache.velocity.version}</bundleDef>
</bundles>
<importBundles>
<!--<importBundleDef>org.wso2.carbon.identity:org.wso2.carbon.identity.authentication:compatible:${carbon.identity.auth.version}</importBundleDef>-->
<!--<importBundleDef>org.wso2.carbon.identity:org.wso2.carbon.identity.authenticator.thrift:compatible:${carbon.identity.thrift.auth.version}</importBundleDef>-->
<!--<importBundleDef>libthrift.wso2:libthrift:0.8.0.wso2v1</importBundleDef>-->
<importBundleDef>org.wso2.carbon.store:jaggery-scxml-executors:${carbon.store.version}</importBundleDef>
</importBundles>
<importFeatures>
<importFeatureDef>org.wso2.carbon.core.server:compatible:${carbon.kernel.base.version}</importFeatureDef>
<importFeatureDef>org.wso2.carbon.identity.oauth.server:compatible:${identity-inbound-auth-oauth.version}</importFeatureDef>
<importFeatureDef>org.wso2.carbon.um.ws.service.server:compatible:${identity-user-ws.version}</importFeatureDef>
</importFeatures>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
| {
"content_hash": "e46d2920dbc936bab8c5a02c4d01435a",
"timestamp": "",
"source": "github",
"line_count": 222,
"max_line_length": 225,
"avg_line_length": 55.067567567567565,
"alnum_prop": 0.5267893660531697,
"repo_name": "lakshani/carbon-mobile-appmgt",
"id": "f532137521a75979a8307493262cae09918e414e",
"size": "12225",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "features/org.wso2.carbon.appmgt.core.feature/pom.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "7078"
},
{
"name": "CSS",
"bytes": "383652"
},
{
"name": "HTML",
"bytes": "1528933"
},
{
"name": "Java",
"bytes": "2506096"
},
{
"name": "JavaScript",
"bytes": "1947233"
},
{
"name": "PLSQL",
"bytes": "27755"
},
{
"name": "PLpgSQL",
"bytes": "9882"
},
{
"name": "Shell",
"bytes": "9863"
}
],
"symlink_target": ""
} |
package consulo.javascript.lang;
/**
* @author VISTALL
* @since 15.02.2016
*/
public interface JavaScriptConstants
{
String USE_STRICT = "use strict";
}
| {
"content_hash": "83d286d41813d9217dc1f16595e492e8",
"timestamp": "",
"source": "github",
"line_count": 10,
"max_line_length": 36,
"avg_line_length": 15.8,
"alnum_prop": 0.7088607594936709,
"repo_name": "consulo/consulo-javascript",
"id": "02eef68c966878f3ef49b0a5813ff031e28625bb",
"size": "158",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "base-api/src/main/java/consulo/javascript/lang/JavaScriptConstants.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "HTML",
"bytes": "82933"
},
{
"name": "Java",
"bytes": "2939705"
},
{
"name": "JavaScript",
"bytes": "436"
},
{
"name": "Lex",
"bytes": "78754"
}
],
"symlink_target": ""
} |
package com.google.cloud.dataflow.sdk.runners.inprocess;
import static com.google.common.base.Preconditions.checkState;
import com.google.cloud.dataflow.sdk.coders.VoidCoder;
import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.CommittedBundle;
import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.UncommittedBundle;
import com.google.cloud.dataflow.sdk.util.WindowedValue;
import com.google.cloud.dataflow.sdk.values.PCollection;
import com.google.common.base.MoreObjects;
import com.google.common.collect.ImmutableList;
import org.joda.time.Instant;
/**
* A factory that produces bundles that perform no additional validation.
*/
class InProcessBundleFactory implements BundleFactory {
public static InProcessBundleFactory create() {
return new InProcessBundleFactory();
}
private InProcessBundleFactory() {}
@Override
public <T> UncommittedBundle<T> createRootBundle(PCollection<T> output) {
return InProcessBundle.create(output, StructuralKey.of(null, VoidCoder.of()));
}
@Override
public <T> UncommittedBundle<T> createBundle(CommittedBundle<?> input, PCollection<T> output) {
return InProcessBundle.create(output, input.getKey());
}
@Override
public <K, T> UncommittedBundle<T> createKeyedBundle(
CommittedBundle<?> input, StructuralKey<K> key, PCollection<T> output) {
return InProcessBundle.create(output, key);
}
/**
* A {@link UncommittedBundle} that buffers elements in memory.
*/
private static final class InProcessBundle<T> implements UncommittedBundle<T> {
private final PCollection<T> pcollection;
private final StructuralKey<?> key;
private boolean committed = false;
private ImmutableList.Builder<WindowedValue<T>> elements;
/**
* Create a new {@link InProcessBundle} for the specified {@link PCollection}.
*/
public static <T> InProcessBundle<T> create(PCollection<T> pcollection, StructuralKey<?> key) {
return new InProcessBundle<>(pcollection, key);
}
private InProcessBundle(PCollection<T> pcollection, StructuralKey<?> key) {
this.pcollection = pcollection;
this.key = key;
this.elements = ImmutableList.builder();
}
@Override
public PCollection<T> getPCollection() {
return pcollection;
}
@Override
public InProcessBundle<T> add(WindowedValue<T> element) {
checkState(
!committed,
"Can't add element %s to committed bundle in PCollection %s",
element,
pcollection);
elements.add(element);
return this;
}
@Override
public CommittedBundle<T> commit(final Instant synchronizedCompletionTime) {
checkState(!committed, "Can't commit already committed bundle %s", this);
committed = true;
final Iterable<WindowedValue<T>> committedElements = elements.build();
return new CommittedInProcessBundle<>(
pcollection, key, committedElements, synchronizedCompletionTime);
}
}
private static class CommittedInProcessBundle<T> implements CommittedBundle<T> {
public CommittedInProcessBundle(
PCollection<T> pcollection,
StructuralKey<?> key,
Iterable<WindowedValue<T>> committedElements,
Instant synchronizedCompletionTime) {
this.pcollection = pcollection;
this.key = key;
this.committedElements = committedElements;
this.synchronizedCompletionTime = synchronizedCompletionTime;
}
private final PCollection<T> pcollection;
/** The structural value key of the Bundle, as specified by the coder that created it. */
private final StructuralKey<?> key;
private final Iterable<WindowedValue<T>> committedElements;
private final Instant synchronizedCompletionTime;
@Override
public StructuralKey<?> getKey() {
return key;
}
@Override
public Iterable<WindowedValue<T>> getElements() {
return committedElements;
}
@Override
public PCollection<T> getPCollection() {
return pcollection;
}
@Override
public Instant getSynchronizedProcessingOutputWatermark() {
return synchronizedCompletionTime;
}
@Override
public String toString() {
return MoreObjects.toStringHelper(this)
.omitNullValues()
.add("pcollection", pcollection)
.add("key", key)
.add("elements", committedElements)
.toString();
}
@Override
public CommittedBundle<T> withElements(Iterable<WindowedValue<T>> elements) {
return new CommittedInProcessBundle<>(
pcollection, key, ImmutableList.copyOf(elements), synchronizedCompletionTime);
}
}
}
| {
"content_hash": "75950e7660a759e726d872cab07e7124",
"timestamp": "",
"source": "github",
"line_count": 145,
"max_line_length": 99,
"avg_line_length": 32.42068965517242,
"alnum_prop": 0.7104871303977877,
"repo_name": "joshualitt/DataflowJavaSDK",
"id": "d6f7cb4f61a9841e65302540996b40ebfcb4e652",
"size": "5295",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/InProcessBundleFactory.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "6959136"
},
{
"name": "Protocol Buffer",
"bytes": "1206"
},
{
"name": "Shell",
"bytes": "3353"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.m60732.poupanca">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest> | {
"content_hash": "9451688f79f51c729cf3613b84daaead",
"timestamp": "",
"source": "github",
"line_count": 21,
"max_line_length": 76,
"avg_line_length": 35.285714285714285,
"alnum_prop": 0.6045883940620783,
"repo_name": "vpithan/android",
"id": "4693209b7bb94077cdb7cde1d12e3d824490969a",
"size": "741",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Poupanca/app/src/main/AndroidManifest.xml",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "13941"
}
],
"symlink_target": ""
} |
<?php
class Services_Upgrade_Settings {
private $_settings;
function __construct(Dao_Factory $daoFactory, Services_Settings_Container $settings) {
$this->_settings = $settings;
} # ctor
function update() {
/*
* Make sure some versionnumbers are always in the db, so
* comparisons always work
*/
$this->setIfNot("settingsversion", "0.00");
$this->setIfNot("securityversion", "0.00");
if ($this->_settings->get('settingsversion') < 0.15) {
$this->remove('system_languages');
} # if
$this->createServerKeys($this->_settings->get('openssl_cnf_path'));
$this->createPasswordSalt();
$this->setupNewsgroups();
$this->createRsaKeys();
$this->createXsrfSecret();
$this->remove('sabnzbdurltpl');
$this->remove('sabnzbdurl');
$this->remove('recompress_nzb');
$this->remove('available_languages');
$this->remove('featureversion');
$this->remove('max_newcount');
$this->remove('action');
$this->remove('submitedit');
$this->setIfNot('cookie_expires', 30);
$this->setIfNot('sendwelcomemail', true);
$this->setIfNot('twitter_consumer_key', 'LRJCpeHASigYtWEmxoNPA');
$this->setIfNot('twitter_consumer_secret', 'QvwZglJNpzAnoVDt40uUyu5dRDlVFVs4ddxfEkYp7A'); // This secret can be shared
$this->setIfNot('boxcar_api_key', 'pOQM9O2AnEWL0RjSoHln');
$this->setIfNot('boxcar_api_secret', '7CwTFfX7KeAKfjM1DJjg5s9qcHm4cwmLkxQgW9fe'); // This secret can be shared
$this->setIfNot('auditlevel', 0); // No auditing
$this->setIfNot('system_languages', array('nl_NL' => 'Nederlands', 'en_US' => 'English'));
$this->setIfNot('retention', 0);
$this->setIfNot('retentiontype', 'fullonly');
$this->setIfNot('deny_robots', true);
$this->setIfNot('nntp_nzb', array('host' => '', 'user' => '', 'pass' => '', 'enc' => false, 'port' => 119, 'buggy' => false));
$this->setIfNot('nntp_hdr', array('host' => '', 'user' => '', 'pass' => '', 'enc' => false, 'port' => 119, 'buggy' => false));
$this->setIfNot('nntp_post', array('host' => '', 'user' => '', 'pass' => '', 'enc' => false, 'port' => 119, 'buggy' => false));
$this->setIfNot('retrieve_newer_than', 0);
$this->setIfNot('retrieve_full', false);
$this->setIfNot('prefetch_image', false);
$this->setIfNot('prefetch_nzb', false);
$this->setIfNot('retrieve_comments', true);
$this->setIfNot('retrieve_full_comments', false);
$this->setIfNot('retrieve_reports', true);
$this->setIfNot('retrieve_increment', 5000);
$this->setIfNot('spot_moderation', 'act');
$this->setIfNot('prepare_statistics', true);
$this->setIfNot('external_blacklist', true);
$this->setIfNot('blacklist_url', 'http://jijhaatmij.hopto.me/blacklist.txt');
$this->setIfNot('external_whitelist', true);
$this->setIfNot('whitelist_url', 'http://jijhaatmij.hopto.me/whitelist.txt');
$this->setIfNot('enable_timing', false);
$this->setIfNot('cache_path', './cache');
$this->setIfNot('enable_stacktrace', true);
$this->setIfNot('systemfrommail', 'spotweb@example.com');
$this->setIfNot('customcss', '');
$this->setIfNot('systemtype', 'public');
$this->setIfNot('imageover_subcats', true);
$this->setIfNot('newuser_grouplist',
array(
Array('groupid' => 2, 'prio' => 1), // Group ID 2 == Anonymous users, open system
Array('groupid' => 3, 'prio' => 2) // Group ID 3 == Authenticated users
));
$this->setIfNot('nonauthenticated_userid', 1);
$this->setIfNot('custom_admin_userid', 2);
$this->setIfNot('valid_templates',
array(
'we1rdo' => 'we1rdo'
));;
$this->setIfNot('ms_translator_clientid', '');
$this->setIfNot('ms_translator_clientsecret', '');
$this->updateSettingsVersion();
} # update()
/*
* Create a setting only if no other value is set
*/
function setIfNot($name, $value) {
if ($this->_settings->exists($name)) {
return ;
} # if
$this->_settings->set($name,$value);
} # setIfNot
/*
* Remove a setting, silently fails if not set
*/
function remove($name) {
$this->_settings->remove($name);
} # remove
/*
* Update the current settingsversion number
*/
function updateSettingsVersion() {
$this->_settings->set('settingsversion', SPOTWEB_SETTINGS_VERSION);
} # updateSettingsVersion
/*
* Create the server private and public keys
*/
function createServerKeys($openSslCnfPath) {
$spotSigning = Services_Signing_Base::factory();
$x = $spotSigning->createPrivateKey($openSslCnfPath);
$this->setIfNot('publickey', $x['public']);
$this->setIfNot('privatekey', $x['private']);
} # createServerKeys
/*
* Create the RSA keys
*/
function createRsaKeys() {
/*
* RSA Keys
*
* These are used to validate spots and moderator messages
*/
$rsaKeys = array();
$rsaKeys[2] = array('modulo' => 'ys8WSlqonQMWT8ubG0tAA2Q07P36E+CJmb875wSR1XH7IFhEi0CCwlUzNqBFhC+P',
'exponent' => 'AQAB');
$rsaKeys[3] = array('modulo' => 'uiyChPV23eguLAJNttC/o0nAsxXgdjtvUvidV2JL+hjNzc4Tc/PPo2JdYvsqUsat',
'exponent' => 'AQAB');
$rsaKeys[4] = array('modulo' => '1k6RNDVD6yBYWR6kHmwzmSud7JkNV4SMigBrs+jFgOK5Ldzwl17mKXJhl+su/GR9',
'exponent' => 'AQAB');
$this->setIfNot('rsa_keys', $rsaKeys);
} # createRsaKeys
/*
* Create an xsrf secret
*/
function createXsrfSecret() {
$secret = substr(Services_User_Util::generateUniqueId(), 0, 8);
$this->setIfNot('xsrfsecret', $secret);
} # createXsrfSecret
/*
* Create the servers' password salt
*/
function createPasswordSalt() {
$salt = Services_User_Util::generateUniqueId() . Services_User_Util::generateUniqueId();
$this->setIfNot('pass_salt', $salt);
} # createPasswordSalt
/*
* Define the standard Spotnet groups
*/
function setupNewsgroups() {
$this->setIfNot('hdr_group', 'free.pt');
$this->setIfNot('nzb_group', 'alt.binaries.ftd');
$this->setIfNot('comment_group', 'free.usenet');
$this->setIfNot('report_group', 'free.willey');
} # setupNewsgroups()
/*
* Change a systems' systemtype
*/
function setSystemType($systemType) {
/*
* Depending on the system type, we will have to make some additional
* adjustments.
*/
switch($systemType) {
case 'public' : {
# Public sites should be indexable by a search engine
$this->_settings->set('deny_robots', false);
# Public systems should not show a public visible stack trace either
$this->setIfNot('enable_stacktrace', true);
# Reset the new users' group membership, id 2 is anonymous, 3 = authenticated
$this->_settings->set('newuser_grouplist', array( Array('groupid' => 2, 'prio' => 1), Array('groupid' => 3, 'prio' => 2) ));
/*
* The default anonymous user should be set to 1
*/
$this->_settings->set('nonauthenticated_userid', 1);
break;
} # public
case 'shared' : {
# Shared sites might be indexable by a search engine
$this->_settings->set('deny_robots', false);
# Reset the new users' group membership, id 2 is anonymous, 3 = authenticated, 4 = trusted
$this->_settings->set('newuser_grouplist', array(
Array('groupid' => 2, 'prio' => 1),
Array('groupid' => 3, 'prio' => 2),
Array('groupid' => 4, 'prio' => 3)
));
/*
* The default anonymous user should be set to 1, and this user is only placed
* into the closed system group
*/
$this->_settings->set('nonauthenticated_userid', 1);
break;
} # shared
case 'single' : {
# Private/single owner sites should not be indexable by a search engine
$this->_settings->set('deny_robots', true);
# Reset the new users' group membership, id 2 is anonymous, 3 = authenticated, 4 = trusted, 5 = admin
$this->_settings->set('newuser_grouplist', array(
Array('groupid' => 2, 'prio' => 1),
Array('groupid' => 3, 'prio' => 2),
Array('groupid' => 4, 'prio' => 3),
Array('groupid' => 5, 'prio' => 4)
));
# The default anonymous user should be set to the custom admin use
$this->_settings->set('nonauthenticated_userid', $this->_settings->get('custom_admin_userid'));
break;
} # single
default : throw new Exception("Unknown system type defined: '" . $systemType . "'");
} # switch
# Update the systems' type to our given setting
$this->_settings->set('systemtype', $systemType);
} # setSystemType
} # Services_Upgrade_Settings
| {
"content_hash": "849e97e86da362e61a2b6e10578cc449",
"timestamp": "",
"source": "github",
"line_count": 243,
"max_line_length": 129,
"avg_line_length": 34.19753086419753,
"alnum_prop": 0.641756919374248,
"repo_name": "the-darkvoid/spotweb",
"id": "bec38cc7e983840ab8e78b2be40764785f6e687e",
"size": "8310",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "lib/services/Upgrade/Services_Upgrade_Settings.php",
"mode": "33261",
"license": "bsd-3-clause",
"language": [
{
"name": "ApacheConf",
"bytes": "752"
},
{
"name": "CSS",
"bytes": "114515"
},
{
"name": "JavaScript",
"bytes": "299242"
},
{
"name": "PHP",
"bytes": "1353886"
}
],
"symlink_target": ""
} |
$KCODE = 'u' if RUBY_VERSION < '1.9'
module Localize
autoload :YAMLadapter, File.join(File.dirname(__FILE__), 'localize/adapters/yaml')
autoload :XMLadapter, File.join(File.dirname(__FILE__), 'localize/adapters/xml')
autoload :Formats, File.join(File.dirname(__FILE__), 'localize/formats')
@@default_locale = :en
@@locale = @@default_locale
@@store = :yaml
@@location = ''
class << self
def load(locale=nil, location=nil)
@@locale = locale if locale
@@location = location if location
ret = case @@store
when :yaml
YAMLadapter.get_trans
when :xml
XMLadapter.get_trans
when :plain
@@location
else
raise "Adapter not avalaible: #{adapter}"
end
@@trans = {
:text => Translation.new(ret['text']),
:formats => ret['formats']
}
end
def translate
load unless @@trans
@@trans[:text]
end
def localize(source, format = :full)
load unless @@trans
if source.is_a?(Integer)
Formats.number(source)
elsif source.is_a?(Float)
Formats.number(source)
elsif source.is_a?(Time) or source.is_a?(Date)
Formats.date(source, format)
else
raise "Format not recognize"
end
end
alias :l :localize
def phone(source, format = :full)
load unless @@trans
fone = if source.is_a?(Integer)
source
elsif source.is_a?(String)
source.gsub(/[\+., -]/, '').trim.to_i
elsif source.is_a?(Float)
source.to_s.gsub('.', '').to_i
else
raise "Format not recognize"
end
Formats.phone(fone, format)
end
alias :f :phone
def reset!
@@trans = nil
end
def store=(str)
reset!
@@store = str.to_sym
end
def store
@@store
end
def locale=(loc)
reset!
@@locale = loc
end
def locale
@@locale
end
def default_locale=(loc)
reset!
@@locale = loc.to_sym
end
def default_locale
@@locale
end
def location=(locat)
reset!
@@location = locat
end
def location
@@location
end
def trans
@@trans
end
end
class Translation
def initialize(hash)
hash.each_pair do |key, value|
value = Translation.new(value) if value.is_a?(Hash)
key = key.to_s
instance_variable_set("@#{key}", value)
self.class.class_eval do
define_method("#{key}") do |*args|
str = instance_variable_get("@#{key}")
if args.length > 0
_interpolate(str, args)
else
str
end
end
end
end
end
def method_missing(name, *params)
MissString.new('Translation missing: '+name.to_s)
end
private
def _interpolate(string, args)
args.length.times do |i|
string.gsub!(/\$\{#{i+1}\}/, args[i])
end
string
end
end
class MissString < String
def method_missing(name, *params)
self << '.' + name.to_s
end
end
end | {
"content_hash": "f27e0e3a0029e5cf85a15549d1a460fe",
"timestamp": "",
"source": "github",
"line_count": 155,
"max_line_length": 84,
"avg_line_length": 20.329032258064515,
"alnum_prop": 0.5385591875595049,
"repo_name": "berowar/XML-adapter",
"id": "b73f1179e5a4e84759bbfeb498cdd46a8b2a4823",
"size": "3169",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "lib/localize.rb",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Ruby",
"bytes": "8724"
}
],
"symlink_target": ""
} |
import os
from setuptools import find_packages
from setuptools import setup
PACKAGE_ROOT = os.path.abspath(os.path.dirname(__file__))
with open(os.path.join(PACKAGE_ROOT, 'README.rst')) as file_obj:
README = file_obj.read()
# NOTE: This is duplicated throughout and we should try to
# consolidate.
SETUP_BASE = {
'author': 'Google Cloud Platform',
'author_email': 'jjg+google-cloud-python@google.com',
'scripts': [],
'url': 'https://github.com/GoogleCloudPlatform/google-cloud-python',
'license': 'Apache 2.0',
'platforms': 'Posix; MacOS X; Windows',
'include_package_data': True,
'zip_safe': False,
'classifiers': [
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'License :: OSI Approved :: Apache Software License',
'Operating System :: OS Independent',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Topic :: Internet',
],
}
REQUIREMENTS = [
'google-cloud-core >= 0.22.1, < 0.23dev',
'grpcio >= 1.0.2, < 2.0dev',
]
setup(
name='google-cloud-bigtable',
version='0.22.0',
description='Python Client for Google Cloud Bigtable',
long_description=README,
namespace_packages=[
'google',
'google.cloud',
],
packages=find_packages(),
install_requires=REQUIREMENTS,
**SETUP_BASE
)
| {
"content_hash": "5d59984a84982fe58e440b4f7c6ebc85",
"timestamp": "",
"source": "github",
"line_count": 55,
"max_line_length": 72,
"avg_line_length": 28.181818181818183,
"alnum_prop": 0.6161290322580645,
"repo_name": "quom/google-cloud-python",
"id": "08cd2eb7d6b46754e8e9c16d05fd43e061b47980",
"size": "2126",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "bigtable/setup.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "3366"
},
{
"name": "PowerShell",
"bytes": "7195"
},
{
"name": "Protocol Buffer",
"bytes": "62009"
},
{
"name": "Python",
"bytes": "3388266"
},
{
"name": "Shell",
"bytes": "7548"
}
],
"symlink_target": ""
} |
// +build !ignore_autogenerated
// This file was autogenerated by deepcopy-gen. Do not edit it manually!
package v1alpha1
import (
conversion "k8s.io/apimachinery/pkg/conversion"
runtime "k8s.io/apimachinery/pkg/runtime"
v1 "k8s.io/kubernetes/pkg/api/v1"
reflect "reflect"
)
func init() {
SchemeBuilder.Register(RegisterDeepCopies)
}
// RegisterDeepCopies adds deep-copy functions to the given scheme. Public
// to allow building arbitrary schemes.
func RegisterDeepCopies(scheme *runtime.Scheme) error {
return scheme.AddGeneratedDeepCopyFuncs(
conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1alpha1_CertificateSigningRequest, InType: reflect.TypeOf(&CertificateSigningRequest{})},
conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1alpha1_CertificateSigningRequestCondition, InType: reflect.TypeOf(&CertificateSigningRequestCondition{})},
conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1alpha1_CertificateSigningRequestList, InType: reflect.TypeOf(&CertificateSigningRequestList{})},
conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1alpha1_CertificateSigningRequestSpec, InType: reflect.TypeOf(&CertificateSigningRequestSpec{})},
conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1alpha1_CertificateSigningRequestStatus, InType: reflect.TypeOf(&CertificateSigningRequestStatus{})},
)
}
func DeepCopy_v1alpha1_CertificateSigningRequest(in interface{}, out interface{}, c *conversion.Cloner) error {
{
in := in.(*CertificateSigningRequest)
out := out.(*CertificateSigningRequest)
*out = *in
if err := v1.DeepCopy_v1_ObjectMeta(&in.ObjectMeta, &out.ObjectMeta, c); err != nil {
return err
}
if err := DeepCopy_v1alpha1_CertificateSigningRequestSpec(&in.Spec, &out.Spec, c); err != nil {
return err
}
if err := DeepCopy_v1alpha1_CertificateSigningRequestStatus(&in.Status, &out.Status, c); err != nil {
return err
}
return nil
}
}
func DeepCopy_v1alpha1_CertificateSigningRequestCondition(in interface{}, out interface{}, c *conversion.Cloner) error {
{
in := in.(*CertificateSigningRequestCondition)
out := out.(*CertificateSigningRequestCondition)
*out = *in
out.LastUpdateTime = in.LastUpdateTime.DeepCopy()
return nil
}
}
func DeepCopy_v1alpha1_CertificateSigningRequestList(in interface{}, out interface{}, c *conversion.Cloner) error {
{
in := in.(*CertificateSigningRequestList)
out := out.(*CertificateSigningRequestList)
*out = *in
if in.Items != nil {
in, out := &in.Items, &out.Items
*out = make([]CertificateSigningRequest, len(*in))
for i := range *in {
if err := DeepCopy_v1alpha1_CertificateSigningRequest(&(*in)[i], &(*out)[i], c); err != nil {
return err
}
}
}
return nil
}
}
func DeepCopy_v1alpha1_CertificateSigningRequestSpec(in interface{}, out interface{}, c *conversion.Cloner) error {
{
in := in.(*CertificateSigningRequestSpec)
out := out.(*CertificateSigningRequestSpec)
*out = *in
if in.Request != nil {
in, out := &in.Request, &out.Request
*out = make([]byte, len(*in))
copy(*out, *in)
}
if in.Usages != nil {
in, out := &in.Usages, &out.Usages
*out = make([]KeyUsage, len(*in))
for i := range *in {
(*out)[i] = (*in)[i]
}
}
if in.Groups != nil {
in, out := &in.Groups, &out.Groups
*out = make([]string, len(*in))
copy(*out, *in)
}
return nil
}
}
func DeepCopy_v1alpha1_CertificateSigningRequestStatus(in interface{}, out interface{}, c *conversion.Cloner) error {
{
in := in.(*CertificateSigningRequestStatus)
out := out.(*CertificateSigningRequestStatus)
*out = *in
if in.Conditions != nil {
in, out := &in.Conditions, &out.Conditions
*out = make([]CertificateSigningRequestCondition, len(*in))
for i := range *in {
if err := DeepCopy_v1alpha1_CertificateSigningRequestCondition(&(*in)[i], &(*out)[i], c); err != nil {
return err
}
}
}
if in.Certificate != nil {
in, out := &in.Certificate, &out.Certificate
*out = make([]byte, len(*in))
copy(*out, *in)
}
return nil
}
}
| {
"content_hash": "d4ce27dac8c197e3a7a5630718ce6ae3",
"timestamp": "",
"source": "github",
"line_count": 125,
"max_line_length": 156,
"avg_line_length": 32.088,
"alnum_prop": 0.7075542258788332,
"repo_name": "huang195/kubernetes",
"id": "9bacf3501fd374b1c53b4b1868aab70220c0eb23",
"size": "4580",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "pkg/apis/certificates/v1alpha1/zz_generated.deepcopy.go",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "978"
},
{
"name": "Go",
"bytes": "44520032"
},
{
"name": "HTML",
"bytes": "2249497"
},
{
"name": "Makefile",
"bytes": "67522"
},
{
"name": "Nginx",
"bytes": "1013"
},
{
"name": "Protocol Buffer",
"bytes": "553789"
},
{
"name": "Python",
"bytes": "47393"
},
{
"name": "SaltStack",
"bytes": "56179"
},
{
"name": "Shell",
"bytes": "1477139"
}
],
"symlink_target": ""
} |
require_relative '../../models/map/presenter'
class Admin::TablesController < ApplicationController
ssl_required :index, :show
skip_before_filter :browser_is_html5_compliant?, :only => [:embed_map]
before_filter :login_required, :only => [:index]
after_filter :update_user_last_activity, :only => [:index, :show]
def index
@tables_count = current_user.tables.count
end
# We only require login for index, so we must manage the security at this level.
# we present different actions depending on if there is a user logged in or not.
# if the user is not logged in, we redirect them to the public page
def show
if current_user.present?
@table = ::Table.get_by_id(params[:id], current_user)
respond_to do |format|
format.html
download_formats @table, format
end
else
redirect_to CartoDB.path(self, 'public_table', { id: params[:id], :format => params[:format] })
end
end
def public
@table = nil
@subdomain = CartoDB.extract_subdomain(request)
@table = ::Table.get_by_id(params[:id], User.find(:username => @subdomain))
# Has quite strange checks to see if a user can access a public table
if @table.blank? || @table.private? || ((current_user && current_user.id != @table.user_id) && @table.private?)
render_403
else
@vizzjson = CartoDB::Map::Presenter.new(
@table.map,
{ full: true },
Cartodb.config
)
respond_to do |format|
format.html { render 'public', layout: 'application_table_public' }
download_formats @table, format
end
end
end
private
def download_formats table, format
format.sql { send_data table.to_sql, send_data_conf(table, 'zip', 'zip') }
format.kml { send_data table.to_kml, send_data_conf(table, 'zip', 'kmz') }
format.csv { send_data table.to_csv, send_data_conf(table, 'zip', 'zip') }
format.shp { send_data table.to_shp, send_data_conf(table, 'octet-stream', 'zip') }
end
def send_data_conf table, type, ext
{ :type => "application/#{type}; charset=binary; header=present",
:disposition => "attachment; filename=#{table.name}.#{ext}" }
end
def update_user_last_activity
return true unless current_user.present?
current_user.set_last_active_time
current_user.set_last_ip_address request.remote_ip
end
end
| {
"content_hash": "5e190a64db785abfc5e9a85567efbc01",
"timestamp": "",
"source": "github",
"line_count": 69,
"max_line_length": 115,
"avg_line_length": 34.768115942028984,
"alnum_prop": 0.6448520216756982,
"repo_name": "raquel-ucl/cartodb",
"id": "ed92f43f947fcc507fbe04a06228d2d5c05ae9d3",
"size": "2415",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/controllers/admin/tables_controller.rb",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "CSS",
"bytes": "683077"
},
{
"name": "Game Maker Language",
"bytes": "182471"
},
{
"name": "HTML",
"bytes": "2982014"
},
{
"name": "JavaScript",
"bytes": "3286910"
},
{
"name": "Makefile",
"bytes": "8033"
},
{
"name": "PLpgSQL",
"bytes": "1233"
},
{
"name": "Python",
"bytes": "11060"
},
{
"name": "Ruby",
"bytes": "2599971"
},
{
"name": "Shell",
"bytes": "5658"
}
],
"symlink_target": ""
} |
ACCEPTED
#### According to
Index Fungorum
#### Published in
Kew Bull. , Addit. Ser. 9: 367 (1983)
#### Original name
Eccilia martinica Pegler
### Remarks
null | {
"content_hash": "d3fd21c39367047665e85e06d29f8d18",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 37,
"avg_line_length": 12.461538461538462,
"alnum_prop": 0.6851851851851852,
"repo_name": "mdoering/backbone",
"id": "1506ce9e4696d710700ad49b23e6212c272da2d0",
"size": "210",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Fungi/Basidiomycota/Agaricomycetes/Agaricales/Entolomataceae/Eccilia/Eccilia martinica/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
package ssl
type Sslcertkeysslocspresponderbinding struct {
Ca bool `json:"ca,omitempty"`
Certkey string `json:"certkey,omitempty"`
Ocspresponder string `json:"ocspresponder,omitempty"`
Priority int `json:"priority,omitempty"`
}
| {
"content_hash": "b260445a2d90658b91e2533886edd827",
"timestamp": "",
"source": "github",
"line_count": 8,
"max_line_length": 54,
"avg_line_length": 32.625,
"alnum_prop": 0.7049808429118773,
"repo_name": "chiradeep/go-nitro",
"id": "e6c18c780139ccb13dfbf3f2911b09d6c4cd83c1",
"size": "261",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "config/ssl/sslcertkey_sslocspresponder_binding.go",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Go",
"bytes": "870653"
},
{
"name": "Makefile",
"bytes": "975"
},
{
"name": "Shell",
"bytes": "865"
}
],
"symlink_target": ""
} |
import Phaser from 'phaser';
import Text from './base/Text';
import Sprite from './base/Sprite';
import { store } from '../store/';
export default class extends Sprite {
constructor(game, options) {
super(game, options);
this.init(game, options);
}
init(game, options) {
this.game = game;
this.store = store;
this.initData()
.initSignals(options);
this.game.add.existing(this);
this.initText();
}
initData() {
this.data = {
text: null,
};
return this;
}
initText() {
const options = {
x: this.game.world.centerX,
y: this.game.world.centerY,
text: 'PAUSED',
style: {
font: 'bold 30px Quicksand',
fill: 'white',
},
anchor: {
x: 0.5,
y: 0.5,
},
exists: false,
};
this.data.text = new Text(this.game, options);
this.game.add.existing(this.data.text);
this.data.text.exists = false;
return this;
}
initSignals({ uiSignals }) {
const { onPauseClick } = uiSignals;
onPauseClick.add(this.toggle, this);
return this;
}
toggle() {
if (this.store.isGameOver) return;
if (this.exists) {
this.data.text.exists = false;
this.hide();
} else {
this.data.text.exists = true;
this.reveal();
}
}
}
| {
"content_hash": "85fe6264961fbe1424721051caaff1a5",
"timestamp": "",
"source": "github",
"line_count": 74,
"max_line_length": 48,
"avg_line_length": 16.364864864864863,
"alnum_prop": 0.6135425268373246,
"repo_name": "pavermakov/phaser-synth",
"id": "47ebfbe25993d629762bcdfc7125eba225159c96",
"size": "1211",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/prefabs/PauseScreen.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "723"
},
{
"name": "HTML",
"bytes": "2067"
},
{
"name": "JavaScript",
"bytes": "39832"
}
],
"symlink_target": ""
} |
<?php
namespace Geocoder\Tests\Provider;
use Geocoder\Provider\Nominatim;
use Geocoder\Tests\TestCase;
class NominatimTest extends TestCase
{
public function testGeocodeWithRealAddress()
{
$provider = Nominatim::withOpenStreetMapServer($this->getAdapter());
$results = $provider->geocode('Paris');
$this->assertInstanceOf('Geocoder\Model\AddressCollection', $results);
$this->assertCount(5, $results);
/** @var \Geocoder\Model\Address $result */
$result = $results->first();
$this->assertInstanceOf('\Geocoder\Model\Address', $result);
$this->assertEquals(48.8565056, $result->getLatitude(), '', 0.01);
$this->assertEquals(2.3521334, $result->getLongitude(), '', 0.01);
$this->assertTrue($result->getBounds()->isDefined());
$this->assertEquals(48.8155250549316, $result->getBounds()->getSouth(), '', 0.01);
$this->assertEquals(2.22412180900574, $result->getBounds()->getWest(), '', 0.01);
$this->assertEquals(48.902156829834, $result->getBounds()->getNorth(), '', 0.01);
$this->assertEquals(2.46976041793823, $result->getBounds()->getEast(), '', 0.01);
$this->assertNull($result->getStreetNumber());
$this->assertNull($result->getStreetName());
$this->assertNull($result->getPostalCode());
$this->assertNull($result->getSubLocality());
$this->assertEquals('Paris', $result->getLocality());
$this->assertCount(2, $result->getAdminLevels());
$this->assertEquals('Paris', $result->getAdminLevels()->get(2)->getName());
$this->assertEquals('Île-de-France', $result->getAdminLevels()->get(1)->getName());
$this->assertNull($result->getAdminLevels()->get(1)->getCode());
$this->assertEquals('France', $result->getCountry()->getName());
$this->assertEquals('FR', $result->getCountry()->getCode());
/** @var \Geocoder\Model\Address $result */
$result = $results->get(1);
$this->assertInstanceOf('\Geocoder\Model\Address', $result);
$this->assertEquals(48.8588408, $result->getLatitude(), '', 0.01);
$this->assertEquals(2.32003465529896, $result->getLongitude(), '', 0.01);
$this->assertTrue($result->getBounds()->isDefined());
$this->assertEquals(48.8155250549316, $result->getBounds()->getSouth(), '', 0.01);
$this->assertEquals(2.22412180900574, $result->getBounds()->getWest(), '', 0.01);
$this->assertEquals(48.902156829834, $result->getBounds()->getNorth(), '', 0.01);
$this->assertEquals(2.46976041793823, $result->getBounds()->getEast(), '', 0.01);
$this->assertNull($result->getStreetNumber());
$this->assertNull($result->getStreetName());
$this->assertNull($result->getPostalCode());
$this->assertNull($result->getSubLocality());
$this->assertNull($result->getLocality());
$this->assertCount(2, $result->getAdminLevels());
$this->assertEquals('Paris', $result->getAdminLevels()->get(2)->getName());
$this->assertEquals('Île-de-France', $result->getAdminLevels()->get(1)->getName());
$this->assertNull($result->getAdminLevels()->get(1)->getCode());
$this->assertEquals('France', $result->getCountry()->getName());
$this->assertEquals('FR', $result->getCountry()->getCode());
/** @var \Geocoder\Model\Address $result */
$result = $results->get(2);
$this->assertInstanceOf('\Geocoder\Model\Address', $result);
$this->assertEquals(35.28687645, $result->getLatitude(), '', 0.01);
$this->assertEquals(-93.7354879210082, $result->getLongitude(), '', 0.01);
$this->assertTrue($result->getBounds()->isDefined());
$this->assertEquals(35.2672462463379, $result->getBounds()->getSouth(), '', 0.01);
$this->assertEquals(-93.7618103027344, $result->getBounds()->getWest(), '', 0.01);
$this->assertEquals(35.3065032958984, $result->getBounds()->getNorth(), '', 0.01);
$this->assertEquals(-93.6750793457031, $result->getBounds()->getEast(), '', 0.01);
$this->assertNull($result->getStreetNumber());
$this->assertNull($result->getStreetName());
$this->assertNull($result->getPostalCode());
$this->assertNull($result->getSubLocality());
$this->assertEquals('Paris', $result->getLocality());
$this->assertCount(2, $result->getAdminLevels());
$this->assertEquals('Logan County', $result->getAdminLevels()->get(2)->getName());
$this->assertEquals('Arkansas', $result->getAdminLevels()->get(1)->getName());
$this->assertNull($result->getAdminLevels()->get(1)->getCode());
$this->assertEquals('United States of America', $result->getCountry()->getName());
$this->assertEquals('US', $result->getCountry()->getCode());
/** @var \Geocoder\Model\Address $result */
$result = $results->get(3);
$this->assertInstanceOf('\Geocoder\Model\Address', $result);
$this->assertEquals(33.6751155, $result->getLatitude(), '', 0.01);
$this->assertEquals(-95.5502662477703, $result->getLongitude(), '', 0.01);
$this->assertTrue($result->getBounds()->isDefined());
$this->assertEquals(33.6118507385254, $result->getBounds()->getSouth(), '', 0.01);
$this->assertEquals(-95.6279296875, $result->getBounds()->getWest(), '', 0.01);
$this->assertEquals(33.7383804321289, $result->getBounds()->getNorth(), '', 0.01);
$this->assertEquals(-95.4354476928711, $result->getBounds()->getEast(), '', 0.01);
$this->assertNull($result->getStreetNumber());
$this->assertNull($result->getStreetName());
$this->assertNull($result->getPostalCode());
$this->assertNull($result->getSubLocality());
$this->assertEquals('Paris', $result->getLocality());
$this->assertCount(2, $result->getAdminLevels());
$this->assertEquals('Lamar County', $result->getAdminLevels()->get(2)->getName());
$this->assertEquals('Texas', $result->getAdminLevels()->get(1)->getName());
$this->assertNull($result->getAdminLevels()->get(1)->getCode());
$this->assertEquals('United States of America', $result->getCountry()->getName());
$this->assertEquals('US', $result->getCountry()->getCode());
/** @var \Geocoder\Model\Address $result */
$result = $results->get(4);
$this->assertInstanceOf('\Geocoder\Model\Address', $result);
$this->assertEquals(38.2097987, $result->getLatitude(), '', 0.01);
$this->assertEquals(-84.2529869, $result->getLongitude(), '', 0.01);
$this->assertTrue($result->getBounds()->isDefined());
$this->assertEquals(38.1649208068848, $result->getBounds()->getSouth(), '', 0.01);
$this->assertEquals(-84.3073272705078, $result->getBounds()->getWest(), '', 0.01);
$this->assertEquals(38.2382736206055, $result->getBounds()->getNorth(), '', 0.01);
$this->assertEquals(-84.2320861816406, $result->getBounds()->getEast(), '', 0.01);
$this->assertNull($result->getStreetNumber());
$this->assertNull($result->getStreetName());
$this->assertNull($result->getPostalCode());
$this->assertNull($result->getSubLocality());
$this->assertEquals('Paris', $result->getLocality());
$this->assertCount(2, $result->getAdminLevels());
$this->assertEquals('Bourbon County', $result->getAdminLevels()->get(2)->getName());
$this->assertEquals('Kentucky', $result->getAdminLevels()->get(1)->getName());
$this->assertNull($result->getAdminLevels()->get(1)->getCode());
$this->assertEquals('United States of America', $result->getCountry()->getName());
$this->assertEquals('US', $result->getCountry()->getCode());
}
public function testGeocodeWithRealAddressWithLocale()
{
$provider = Nominatim::withOpenStreetMapServer($this->getAdapter(), 'fr_FR');
$results = $provider->geocode('10 allée Evariste Galois, Clermont ferrand');
$this->assertInstanceOf('Geocoder\Model\AddressCollection', $results);
$this->assertCount(2, $results);
/** @var \Geocoder\Model\Address $result */
$result = $results->first();
$this->assertInstanceOf('\Geocoder\Model\Address', $result);
$this->assertEquals(45.7586841, $result->getLatitude(), '', 0.01);
$this->assertEquals(3.1354075, $result->getLongitude(), '', 0.01);
$this->assertTrue($result->getBounds()->isDefined());
$this->assertEquals(45.7576484680176, $result->getBounds()->getSouth(), '', 0.01);
$this->assertEquals(3.13258004188538, $result->getBounds()->getWest(), '', 0.01);
$this->assertEquals(45.7595367431641, $result->getBounds()->getNorth(), '', 0.01);
$this->assertEquals(3.13707232475281, $result->getBounds()->getEast(), '', 0.01);
$this->assertNull($result->getStreetNumber());
$this->assertEquals('Allée Évariste Galois', $result->getStreetName());
$this->assertEquals('63000', $result->getPostalCode());
$this->assertEquals('La Pardieu', $result->getSubLocality());
$this->assertEquals('Clermont-Ferrand', $result->getLocality());
$this->assertCount(2, $result->getAdminLevels());
$this->assertEquals('Clermont-Ferrand', $result->getAdminLevels()->get(2)->getName());
$this->assertEquals('Auvergne', $result->getAdminLevels()->get(1)->getName());
$this->assertNull($result->getAdminLevels()->get(1)->getCode());
$this->assertEquals('France', $result->getCountry()->getName());
$this->assertEquals('FR', $result->getCountry()->getCode());
/** @var \Geocoder\Model\Address $result */
$result = $results->get(1);
$this->assertInstanceOf('\Geocoder\Model\Address', $result);
$this->assertEquals(45.7586841, $result->getLatitude(), '', 0.01);
$this->assertEquals(3.1354075, $result->getLongitude(), '', 0.01);
$this->assertTrue($result->getBounds()->isDefined());
$this->assertEquals(45.7576484680176, $result->getBounds()->getSouth(), '', 0.01);
$this->assertEquals(3.13258004188538, $result->getBounds()->getWest(), '', 0.01);
$this->assertEquals(45.7595367431641, $result->getBounds()->getNorth(), '', 0.01);
$this->assertEquals(3.13707232475281, $result->getBounds()->getEast(), '', 0.01);
$this->assertNull($result->getStreetNumber());
$this->assertEquals('Allée Évariste Galois', $result->getStreetName());
$this->assertEquals('63170', $result->getPostalCode());
$this->assertEquals('Cap Sud', $result->getSubLocality());
$this->assertNull($result->getLocality());
$this->assertCount(2, $result->getAdminLevels());
$this->assertEquals('Clermont-Ferrand', $result->getAdminLevels()->get(2)->getName());
$this->assertEquals('Auvergne', $result->getAdminLevels()->get(1)->getName());
$this->assertNull($result->getAdminLevels()->get(1)->getCode());
$this->assertEquals('France', $result->getCountry()->getName());
$this->assertEquals('FR', $result->getCountry()->getCode());
}
public function testReverseWithRealCoordinates()
{
$provider = Nominatim::withOpenStreetMapServer($this->getAdapter());
$results = $provider->reverse(60.4539471728726, 22.2567841926781);
$this->assertInstanceOf('Geocoder\Model\AddressCollection', $results);
$this->assertCount(1, $results);
/** @var \Geocoder\Model\Address $result */
$result = $results->first();
$this->assertInstanceOf('\Geocoder\Model\Address', $result);
$this->assertEquals(60.4539, $result->getLatitude(), '', 0.001);
$this->assertEquals(22.2568, $result->getLongitude(), '', 0.001);
$this->assertFalse($result->getBounds()->isDefined());
$this->assertEquals(35, $result->getStreetNumber());
$this->assertEquals('Läntinen Pitkäkatu', $result->getStreetName());
$this->assertEquals(20100, $result->getPostalCode());
$this->assertEquals('VII', $result->getSubLocality());
$this->assertEquals('Turku', $result->getLocality());
$this->assertCount(2, $result->getAdminLevels());
$this->assertEquals('Varsinais-Suomi', $result->getAdminLevels()->get(2)->getName());
$this->assertEquals('Etelä-Suomi', $result->getAdminLevels()->get(1)->getName());
$this->assertNull( $result->getAdminLevels()->get(1)->getCode());
$this->assertEquals('Suomi', $result->getCountry()->getName());
$this->assertEquals('FI', $result->getCountry()->getCode());
}
/**
* @expectedException \Geocoder\Exception\NoResult
* @expectedExceptionMessage Could not execute query "http://nominatim.openstreetmap.org/search?q=Hammm&format=xml&addressdetails=1&limit=5".
*/
public function testGeocodeWithUnknownCity()
{
$provider = Nominatim::withOpenStreetMapServer($this->getAdapter());
$provider->geocode('Hammm');
}
public function testReverseWithRealCoordinatesWithLocale()
{
$provider = Nominatim::withOpenStreetMapServer($this->getAdapter(), 'de_DE');
$results = $provider->geocode('Kalbacher Hauptstraße, 60437 Frankfurt, Germany');
$this->assertInstanceOf('Geocoder\Model\AddressCollection', $results);
$this->assertCount(5, $results);
/** @var \Geocoder\Model\Address $result */
$result = $results->first();
$this->assertInstanceOf('\Geocoder\Model\Address', $result);
$this->assertEquals(50.1856803, $result->getLatitude(), '', 0.01);
$this->assertEquals(8.6506285, $result->getLongitude(), '', 0.01);
$this->assertTrue($result->getBounds()->isDefined());
$this->assertEquals(50.1851196289062, $result->getBounds()->getSouth(), '', 0.01);
$this->assertEquals(8.64984607696533, $result->getBounds()->getWest(), '', 0.01);
$this->assertEquals(50.1860122680664, $result->getBounds()->getNorth(), '', 0.01);
$this->assertEquals(8.65207576751709, $result->getBounds()->getEast(), '', 0.01);
$this->assertNull($result->getStreetNumber());
$this->assertEquals('Kalbacher Hauptstraße', $result->getStreetName());
$this->assertEquals(60437, $result->getPostalCode());
$this->assertEquals('Kalbach', $result->getSubLocality());
$this->assertEquals('Frankfurt am Main', $result->getLocality());
$this->assertCount(1, $result->getAdminLevels());
$this->assertEquals('Hessen', $result->getAdminLevels()->get(1)->getName());
$this->assertNull($result->getAdminLevels()->get(1)->getCode());
$this->assertEquals('Deutschland', $result->getCountry()->getName());
$this->assertEquals('DE', $result->getCountry()->getCode());
/** @var \Geocoder\Model\Address $result */
$result = $results->get(1);
$this->assertInstanceOf('\Geocoder\Model\Address', $result);
$this->assertEquals(50.1845911, $result->getLatitude(), '', 0.01);
$this->assertEquals(8.6540194, $result->getLongitude(), '', 0.01);
$this->assertTrue($result->getBounds()->isDefined());
$this->assertEquals(50.1840019226074, $result->getBounds()->getSouth(), '', 0.01);
$this->assertEquals(8.65207481384277, $result->getBounds()->getWest(), '', 0.01);
$this->assertEquals(50.1851234436035, $result->getBounds()->getNorth(), '', 0.01);
$this->assertEquals(8.65643787384033, $result->getBounds()->getEast(), '', 0.01);
$this->assertNull($result->getStreetNumber());
$this->assertEquals('Kalbacher Hauptstraße', $result->getStreetName());
$this->assertEquals(60437, $result->getPostalCode());
$this->assertEquals('Kalbach', $result->getSubLocality());
$this->assertEquals('Frankfurt am Main', $result->getLocality());
$this->assertCount(1, $result->getAdminLevels());
$this->assertEquals('Hessen', $result->getAdminLevels()->get(1)->getName());
$this->assertNull($result->getAdminLevels()->get(1)->getCode());
$this->assertEquals('Deutschland', $result->getCountry()->getName());
$this->assertEquals('DE', $result->getCountry()->getCode());
/** @var \Geocoder\Model\Address $result */
$result = $results->get(2);
$this->assertInstanceOf('\Geocoder\Model\Address', $result);
$this->assertEquals(50.1862884, $result->getLatitude(), '', 0.01);
$this->assertEquals(8.6493167, $result->getLongitude(), '', 0.01);
$this->assertTrue($result->getBounds()->isDefined());
$this->assertEquals(50.1862106323242, $result->getBounds()->getSouth(), '', 0.01);
$this->assertEquals(8.64931583404541, $result->getBounds()->getWest(), '', 0.01);
$this->assertEquals(50.1862907409668, $result->getBounds()->getNorth(), '', 0.01);
$this->assertEquals(8.64943981170654, $result->getBounds()->getEast(), '', 0.01);
$this->assertNull($result->getStreetNumber());
$this->assertEquals('Kalbacher Hauptstraße', $result->getStreetName());
$this->assertEquals(60437, $result->getPostalCode());
$this->assertEquals('Kalbach', $result->getSubLocality());
$this->assertEquals('Frankfurt am Main', $result->getLocality());
$this->assertCount(1, $result->getAdminLevels());
$this->assertEquals('Hessen', $result->getAdminLevels()->get(1)->getName());
$this->assertNull($result->getAdminLevels()->get(1)->getCode());
$this->assertEquals('Deutschland', $result->getCountry()->getName());
$this->assertEquals('DE', $result->getCountry()->getCode());
/** @var \Geocoder\Model\Address $result */
$result = $results->get(3);
$this->assertInstanceOf('\Geocoder\Model\Address', $result);
$this->assertEquals(50.1861344, $result->getLatitude(), '', 0.01);
$this->assertEquals(8.649578, $result->getLongitude(), '', 0.01);
$this->assertTrue($result->getBounds()->isDefined());
$this->assertEquals(50.1860084533691, $result->getBounds()->getSouth(), '', 0.01);
$this->assertEquals(8.64943885803223, $result->getBounds()->getWest(), '', 0.01);
$this->assertEquals(50.1862144470215, $result->getBounds()->getNorth(), '', 0.01);
$this->assertEquals(8.64984703063965, $result->getBounds()->getEast(), '', 0.01);
$this->assertNull($result->getStreetNumber());
$this->assertEquals('Kalbacher Hauptstraße', $result->getStreetName());
$this->assertEquals(60437, $result->getPostalCode());
$this->assertNull($result->getSubLocality());
$this->assertEquals('Frankfurt am Main', $result->getLocality());
$this->assertCount(1, $result->getAdminLevels());
$this->assertEquals('Hessen', $result->getAdminLevels()->get(1)->getName());
$this->assertNull($result->getAdminLevels()->get(1)->getCode());
$this->assertEquals('Deutschland', $result->getCountry()->getName());
$this->assertEquals('DE', $result->getCountry()->getCode());
}
public function testGeocodeWithLocalhostIPv4()
{
$provider = Nominatim::withOpenStreetMapServer($this->getMockAdapter($this->never()));
$results = $provider->geocode('127.0.0.1');
$this->assertInstanceOf('Geocoder\Model\AddressCollection', $results);
$this->assertCount(1, $results);
/** @var \Geocoder\Model\Address $result */
$result = $results->first();
$this->assertInstanceOf('\Geocoder\Model\Address', $result);
$this->assertEquals('localhost', $result->getLocality());
$this->assertEmpty($result->getAdminLevels());
$this->assertEquals('localhost', $result->getCountry()->getName());
}
/**
* @expectedException \Geocoder\Exception\UnsupportedOperation
* @expectedExceptionMessage The Geocoder\Provider\Nominatim provider does not support IPv6 addresses.
*/
public function testGeocodeWithLocalhostIPv6()
{
$provider = Nominatim::withOpenStreetMapServer($this->getMockAdapter($this->never()));
$provider->geocode('::1');
}
public function testGeocodeWithRealIPv4()
{
$provider = Nominatim::withOpenStreetMapServer($this->getAdapter());
$results = $provider->geocode('88.188.221.14');
$this->assertInstanceOf('Geocoder\Model\AddressCollection', $results);
$this->assertCount(5, $results);
/** @var \Geocoder\Model\Address $result */
$result = $results->first();
$this->assertInstanceOf('\Geocoder\Model\Address', $result);
$this->assertEquals(43.6189768, $result->getLatitude(), '', 0.01);
$this->assertEquals(1.4564493, $result->getLongitude(), '', 0.01);
$this->assertTrue($result->getBounds()->isDefined());
$this->assertEquals(43.6159553527832, $result->getBounds()->getSouth(), '', 0.01);
$this->assertEquals(1.45302963256836, $result->getBounds()->getWest(), '', 0.01);
$this->assertEquals(43.623119354248, $result->getBounds()->getNorth(), '', 0.01);
$this->assertEquals(1.45882403850555, $result->getBounds()->getEast(), '', 0.01);
$this->assertNull($result->getStreetNumber());
$this->assertEquals('Avenue de Lyon', $result->getStreetName());
$this->assertEquals(31506, $result->getPostalCode());
$this->assertEquals(4, $result->getSubLocality());
$this->assertEquals('Toulouse', $result->getLocality());
$this->assertCount(2, $result->getAdminLevels());
$this->assertEquals('Toulouse', $result->getAdminLevels()->get(2)->getName());
$this->assertEquals('Midi-Pyrénées', $result->getAdminLevels()->get(1)->getName());
$this->assertNull($result->getAdminLevels()->get(1)->getCode());
$this->assertEquals('France métropolitaine', $result->getCountry()->getName());
$this->assertEquals('FR', $result->getCountry()->getCode());
}
public function testGeocodeWithRealIPv4WithLocale()
{
$provider = Nominatim::withOpenStreetMapServer($this->getAdapter(), 'da_DK');
$results = $provider->geocode('88.188.221.14');
$this->assertInstanceOf('Geocoder\Model\AddressCollection', $results);
$this->assertCount(5, $results);
/** @var \Geocoder\Model\Address $result */
$result = $results->first();
$this->assertInstanceOf('\Geocoder\Model\Address', $result);
$this->assertEquals(43.6155351, $result->getLatitude(), '', 0.01);
$this->assertEquals(1.4525647, $result->getLongitude(), '', 0.01);
$this->assertTrue($result->getBounds()->isDefined());
$this->assertEquals(43.6154556274414, $result->getBounds()->getSouth(), '', 0.01);
$this->assertEquals(1.4524964094162, $result->getBounds()->getWest(), '', 0.01);
$this->assertEquals(43.6156005859375, $result->getBounds()->getNorth(), '', 0.01);
$this->assertEquals(1.45262920856476, $result->getBounds()->getEast(), '', 0.01);
$this->assertNull($result->getStreetNumber());
$this->assertEquals('Rue du Faubourg Bonnefoy', $result->getStreetName());
$this->assertEquals(31506, $result->getPostalCode());
$this->assertEquals(4, $result->getSubLocality());
$this->assertEquals('Toulouse', $result->getLocality());
$this->assertCount(2, $result->getAdminLevels());
$this->assertEquals('Toulouse', $result->getAdminLevels()->get(2)->getName());
$this->assertEquals('Midi-Pyrénées', $result->getAdminLevels()->get(1)->getName());
$this->assertNull($result->getAdminLevels()->get(1)->getCode());
$this->assertEquals('Frankrig', $result->getCountry()->getName());
$this->assertEquals('FR', $result->getCountry()->getCode());
}
/**
* @expectedException \Geocoder\Exception\UnsupportedOperation
* @expectedExceptionMessage The Geocoder\Provider\Nominatim provider does not support IPv6 addresses.
*/
public function testGeocodeWithRealIPv6()
{
$provider = Nominatim::withOpenStreetMapServer($this->getAdapter());
$provider->geocode('::ffff:88.188.221.14');
}
/**
* @expectedException \Geocoder\Exception\NoResult
* @expectedExceptionMessage Could not execute query "http://nominatim.openstreetmap.org/search?q=L%C3%A4ntinen+Pitk%C3%A4katu+35%2C+Turku&format=xml&addressdetails=1&limit=5".
*/
public function testGeocodeWithAddressGetsNullContent()
{
$provider = Nominatim::withOpenStreetMapServer($this->getMockAdapterReturns(null));
$provider->geocode('Läntinen Pitkäkatu 35, Turku');
}
/**
* @expectedException \Geocoder\Exception\NoResult
* @expectedExceptionMessage Could not execute query "http://nominatim.openstreetmap.org/search?q=L%C3%A4ntinen+Pitk%C3%A4katu+35%2C+Turku&format=xml&addressdetails=1&limit=5".
*/
public function testGeocodeWithAddressGetsEmptyContent()
{
$provider = Nominatim::withOpenStreetMapServer($this->getMockAdapterReturns('<foo></foo>'));
$provider->geocode('Läntinen Pitkäkatu 35, Turku');
}
/**
* @expectedException \Geocoder\Exception\NoResult
* @expectedExceptionMessage Could not execute query "http://nominatim.openstreetmap.org/search?q=L%C3%A4ntinen+Pitk%C3%A4katu+35%2C+Turku&format=xml&addressdetails=1&limit=5".
*/
public function testGeocodeWithAddressGetsEmptyXML()
{
$emptyXML = <<<XML
<?xml version="1.0" encoding="utf-8"?><searchresults_empty></searchresults_empty>
XML;
$provider = Nominatim::withOpenStreetMapServer($this->getMockAdapterReturns($emptyXML));
$provider->geocode('Läntinen Pitkäkatu 35, Turku');
}
/**
* @expectedException \Geocoder\Exception\NoResult
* @expectedExceptionMessage Unable to find results for coordinates [ 60.453947, 22.256784 ].
*/
public function testReverseWithCoordinatesGetsNullContent()
{
$provider = Nominatim::withOpenStreetMapServer($this->getMockAdapterReturns(null));
$provider->reverse(60.4539471728726, 22.2567841926781);
}
/**
* @expectedException \Geocoder\Exception\NoResult
* @expectedExceptionMessage Unable to find results for coordinates [ 60.453947, 22.256784 ].
*/
public function testReverseWithCoordinatesGetsEmptyContent()
{
$provider = Nominatim::withOpenStreetMapServer($this->getMockAdapterReturns('<error></error>'));
$provider->reverse(60.4539471728726, 22.2567841926781);
}
/**
* @expectedException \Geocoder\Exception\NoResult
* @expectedExceptionMessage Unable to find results for coordinates [ -80.000000, -170.000000 ].
*/
public function testReverseWithCoordinatesGetsError()
{
$errorXml = <<<XML
<?xml version="1.0" encoding="UTF-8" ?>
<reversegeocode querystring='format=xml&lat=-80.000000&lon=-170.000000&addressdetails=1'>
<error>Unable to geocode</error>
</reversegeocode>
XML;
$provider = Nominatim::withOpenStreetMapServer($this->getMockAdapterReturns($errorXml));
$provider->reverse(-80.000000, -170.000000);
}
public function testGetNodeStreetName()
{
$provider = Nominatim::withOpenStreetMapServer($this->getAdapter(), 'fr_FR');
$results = $provider->reverse(48.86, 2.35);
$this->assertInstanceOf('Geocoder\Model\AddressCollection', $results);
$this->assertCount(1, $results);
/** @var \Geocoder\Model\Address $result */
$result = $results->first();
$this->assertInstanceOf('\Geocoder\Model\Address', $result);
$this->assertEquals('Rue Quincampoix', $result->getStreetName());
}
}
| {
"content_hash": "53a12f69cb2efeac6b0db7eada55da0c",
"timestamp": "",
"source": "github",
"line_count": 492,
"max_line_length": 180,
"avg_line_length": 56.636178861788615,
"alnum_prop": 0.636497398169747,
"repo_name": "arunlodhi/Geocoder",
"id": "7fb931548ee656206b1273822728bdccda48319d",
"size": "27891",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "tests/Geocoder/Tests/Provider/NominatimTest.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "PHP",
"bytes": "450447"
}
],
"symlink_target": ""
} |
<!DOCTYPE html>
<!--
Copyright (c) 2013 The Chromium Authors. All rights reserved.
Use of this source code is governed by a BSD-style license that can be
found in the LICENSE file.
-->
<link rel="import" href="/tracing/base/math/bbox2.html">
<link rel="import" href="/tracing/base/math/math.html">
<link rel="import" href="/tracing/base/math/quad.html">
<link rel="import" href="/tracing/base/math/rect.html">
<link rel="import" href="/tracing/base/raf.html">
<link rel="import" href="/tracing/base/settings.html">
<link rel="import" href="/tracing/ui/base/camera.html">
<link rel="import" href="/tracing/ui/base/mouse_mode_selector.html">
<link rel="import" href="/tracing/ui/base/mouse_tracker.html">
<link rel="import" href="/tracing/ui/base/utils.html">
<style>
* /deep/ quad-stack-view {
display: block;
float: left;
height: 100%;
overflow: hidden;
position: relative; /* For the absolute positioned mouse-mode-selector */
width: 100%;
}
* /deep/ quad-stack-view > #header {
position: absolute;
font-size: 70%;
top: 10px;
left: 10px;
width: 800px;
}
* /deep/ quad-stack-view > #stacking-distance-slider {
position: absolute;
font-size: 70%;
top: 10px;
right: 10px;
}
* /deep/ quad-stack-view > #chrome-left {
background-image: url('../images/chrome-left.png');
display: none;
}
* /deep/ quad-stack-view > #chrome-mid {
background-image: url('../images/chrome-mid.png');
display: none;
}
* /deep/ quad-stack-view > #chrome-right {
background-image: url('../images/chrome-right.png');
display: none;
}
</style>
<template id='quad-stack-view-template'>
<div id="header"></div>
<input id="stacking-distance-slider" type="range" min=1 max=400 step=1>
</input>
<canvas id='canvas'></canvas>
<img id='chrome-left'/>
<img id='chrome-mid'/>
<img id='chrome-right'/>
</template>
<script>
'use strict';
/**
* @fileoverview QuadStackView controls the content and viewing angle a
* QuadStack.
*/
tr.exportTo('tr.ui.b', function() {
const THIS_DOC = document.currentScript.ownerDocument;
const constants = {};
constants.IMAGE_LOAD_RETRY_TIME_MS = 500;
constants.SUBDIVISION_MINIMUM = 1;
constants.SUBDIVISION_RECURSION_DEPTH = 3;
constants.SUBDIVISION_DEPTH_THRESHOLD = 100;
constants.FAR_PLANE_DISTANCE = 10000;
// Care of bckenney@ via
// http://extremelysatisfactorytotalitarianism.com/blog/?p=2120
function drawTexturedTriangle(ctx, img, p0, p1, p2, t0, t1, t2) {
const tmpP0 = [p0[0], p0[1]];
const tmpP1 = [p1[0], p1[1]];
const tmpP2 = [p2[0], p2[1]];
const tmpT0 = [t0[0], t0[1]];
const tmpT1 = [t1[0], t1[1]];
const tmpT2 = [t2[0], t2[1]];
ctx.beginPath();
ctx.moveTo(tmpP0[0], tmpP0[1]);
ctx.lineTo(tmpP1[0], tmpP1[1]);
ctx.lineTo(tmpP2[0], tmpP2[1]);
ctx.closePath();
tmpP1[0] -= tmpP0[0];
tmpP1[1] -= tmpP0[1];
tmpP2[0] -= tmpP0[0];
tmpP2[1] -= tmpP0[1];
tmpT1[0] -= tmpT0[0];
tmpT1[1] -= tmpT0[1];
tmpT2[0] -= tmpT0[0];
tmpT2[1] -= tmpT0[1];
const det = 1 / (tmpT1[0] * tmpT2[1] - tmpT2[0] * tmpT1[1]);
// linear transformation
const a = (tmpT2[1] * tmpP1[0] - tmpT1[1] * tmpP2[0]) * det;
const b = (tmpT2[1] * tmpP1[1] - tmpT1[1] * tmpP2[1]) * det;
const c = (tmpT1[0] * tmpP2[0] - tmpT2[0] * tmpP1[0]) * det;
const d = (tmpT1[0] * tmpP2[1] - tmpT2[0] * tmpP1[1]) * det;
// translation
const e = tmpP0[0] - a * tmpT0[0] - c * tmpT0[1];
const f = tmpP0[1] - b * tmpT0[0] - d * tmpT0[1];
ctx.save();
ctx.transform(a, b, c, d, e, f);
ctx.clip();
ctx.drawImage(img, 0, 0);
ctx.restore();
}
function drawTriangleSub(
ctx, img, p0, p1, p2, t0, t1, t2, opt_recursionDepth) {
const depth = opt_recursionDepth || 0;
// We may subdivide if we are not at the limit of recursion.
let subdivisionIndex = 0;
if (depth < constants.SUBDIVISION_MINIMUM) {
subdivisionIndex = 7;
} else if (depth < constants.SUBDIVISION_RECURSION_DEPTH) {
if (Math.abs(p0[2] - p1[2]) > constants.SUBDIVISION_DEPTH_THRESHOLD) {
subdivisionIndex += 1;
}
if (Math.abs(p0[2] - p2[2]) > constants.SUBDIVISION_DEPTH_THRESHOLD) {
subdivisionIndex += 2;
}
if (Math.abs(p1[2] - p2[2]) > constants.SUBDIVISION_DEPTH_THRESHOLD) {
subdivisionIndex += 4;
}
}
// These need to be created every time, since temporaries
// outside of the scope will be rewritten in recursion.
const p01 = vec4.create();
const p02 = vec4.create();
const p12 = vec4.create();
const t01 = vec2.create();
const t02 = vec2.create();
const t12 = vec2.create();
// Calculate the position before w-divide.
for (let i = 0; i < 2; ++i) {
p0[i] *= p0[2];
p1[i] *= p1[2];
p2[i] *= p2[2];
}
// Interpolate the 3d position.
for (let i = 0; i < 4; ++i) {
p01[i] = (p0[i] + p1[i]) / 2;
p02[i] = (p0[i] + p2[i]) / 2;
p12[i] = (p1[i] + p2[i]) / 2;
}
// Re-apply w-divide to the original points and the interpolated ones.
for (let i = 0; i < 2; ++i) {
p0[i] /= p0[2];
p1[i] /= p1[2];
p2[i] /= p2[2];
p01[i] /= p01[2];
p02[i] /= p02[2];
p12[i] /= p12[2];
}
// Interpolate the texture coordinates.
for (let i = 0; i < 2; ++i) {
t01[i] = (t0[i] + t1[i]) / 2;
t02[i] = (t0[i] + t2[i]) / 2;
t12[i] = (t1[i] + t2[i]) / 2;
}
// Based on the index, we subdivide the triangle differently.
// Assuming the triangle is p0, p1, p2 and points between i j
// are represented as pij (that is, a point between p2 and p0
// is p02, etc), then the new triangles are defined by
// the 3rd 4th and 5th arguments into the function.
switch (subdivisionIndex) {
case 1:
drawTriangleSub(ctx, img, p0, p01, p2, t0, t01, t2, depth + 1);
drawTriangleSub(ctx, img, p01, p1, p2, t01, t1, t2, depth + 1);
break;
case 2:
drawTriangleSub(ctx, img, p0, p1, p02, t0, t1, t02, depth + 1);
drawTriangleSub(ctx, img, p1, p02, p2, t1, t02, t2, depth + 1);
break;
case 3:
drawTriangleSub(ctx, img, p0, p01, p02, t0, t01, t02, depth + 1);
drawTriangleSub(ctx, img, p02, p01, p2, t02, t01, t2, depth + 1);
drawTriangleSub(ctx, img, p01, p1, p2, t01, t1, t2, depth + 1);
break;
case 4:
drawTriangleSub(ctx, img, p0, p12, p2, t0, t12, t2, depth + 1);
drawTriangleSub(ctx, img, p0, p1, p12, t0, t1, t12, depth + 1);
break;
case 5:
drawTriangleSub(ctx, img, p0, p01, p2, t0, t01, t2, depth + 1);
drawTriangleSub(ctx, img, p2, p01, p12, t2, t01, t12, depth + 1);
drawTriangleSub(ctx, img, p01, p1, p12, t01, t1, t12, depth + 1);
break;
case 6:
drawTriangleSub(ctx, img, p0, p12, p02, t0, t12, t02, depth + 1);
drawTriangleSub(ctx, img, p0, p1, p12, t0, t1, t12, depth + 1);
drawTriangleSub(ctx, img, p02, p12, p2, t02, t12, t2, depth + 1);
break;
case 7:
drawTriangleSub(ctx, img, p0, p01, p02, t0, t01, t02, depth + 1);
drawTriangleSub(ctx, img, p01, p12, p02, t01, t12, t02, depth + 1);
drawTriangleSub(ctx, img, p01, p1, p12, t01, t1, t12, depth + 1);
drawTriangleSub(ctx, img, p02, p12, p2, t02, t12, t2, depth + 1);
break;
default:
// In the 0 case and all other cases, we simply draw the triangle.
drawTexturedTriangle(ctx, img, p0, p1, p2, t0, t1, t2);
break;
}
}
// Created to avoid creating garbage when doing bulk transforms.
const tmpVec4 = vec4.create();
function transform(transformed, point, matrix, viewport) {
vec4.set(tmpVec4, point[0], point[1], 0, 1);
vec4.transformMat4(tmpVec4, tmpVec4, matrix);
let w = tmpVec4[3];
if (w < 1e-6) w = 1e-6;
transformed[0] = ((tmpVec4[0] / w) + 1) * viewport.width / 2;
transformed[1] = ((tmpVec4[1] / w) + 1) * viewport.height / 2;
transformed[2] = w;
}
function drawProjectedQuadBackgroundToContext(
quad, p1, p2, p3, p4, ctx, quadCanvas) {
if (quad.imageData) {
quadCanvas.width = quad.imageData.width;
quadCanvas.height = quad.imageData.height;
quadCanvas.getContext('2d').putImageData(quad.imageData, 0, 0);
const quadBBox = new tr.b.math.BBox2();
quadBBox.addQuad(quad);
const iw = quadCanvas.width;
const ih = quadCanvas.height;
drawTriangleSub(
ctx, quadCanvas,
p1, p2, p4,
[0, 0], [iw, 0], [0, ih]);
drawTriangleSub(
ctx, quadCanvas,
p2, p3, p4,
[iw, 0], [iw, ih], [0, ih]);
}
if (quad.backgroundColor) {
ctx.fillStyle = quad.backgroundColor;
ctx.beginPath();
ctx.moveTo(p1[0], p1[1]);
ctx.lineTo(p2[0], p2[1]);
ctx.lineTo(p3[0], p3[1]);
ctx.lineTo(p4[0], p4[1]);
ctx.closePath();
ctx.fill();
}
}
function drawProjectedQuadOutlineToContext(
quad, p1, p2, p3, p4, ctx, quadCanvas) {
ctx.beginPath();
ctx.moveTo(p1[0], p1[1]);
ctx.lineTo(p2[0], p2[1]);
ctx.lineTo(p3[0], p3[1]);
ctx.lineTo(p4[0], p4[1]);
ctx.closePath();
ctx.save();
if (quad.borderColor) {
ctx.strokeStyle = quad.borderColor;
} else {
ctx.strokeStyle = 'rgb(128,128,128)';
}
if (quad.shadowOffset) {
ctx.shadowColor = 'rgb(0, 0, 0)';
ctx.shadowOffsetX = quad.shadowOffset[0];
ctx.shadowOffsetY = quad.shadowOffset[1];
if (quad.shadowBlur) {
ctx.shadowBlur = quad.shadowBlur;
}
}
if (quad.borderWidth) {
ctx.lineWidth = quad.borderWidth;
} else {
ctx.lineWidth = 1;
}
ctx.stroke();
ctx.restore();
}
function drawProjectedQuadSelectionOutlineToContext(
quad, p1, p2, p3, p4, ctx, quadCanvas) {
if (!quad.upperBorderColor) return;
ctx.lineWidth = 8;
ctx.strokeStyle = quad.upperBorderColor;
ctx.beginPath();
ctx.moveTo(p1[0], p1[1]);
ctx.lineTo(p2[0], p2[1]);
ctx.lineTo(p3[0], p3[1]);
ctx.lineTo(p4[0], p4[1]);
ctx.closePath();
ctx.stroke();
}
function drawProjectedQuadToContext(
passNumber, quad, p1, p2, p3, p4, ctx, quadCanvas) {
if (passNumber === 0) {
drawProjectedQuadBackgroundToContext(
quad, p1, p2, p3, p4, ctx, quadCanvas);
} else if (passNumber === 1) {
drawProjectedQuadOutlineToContext(
quad, p1, p2, p3, p4, ctx, quadCanvas);
} else if (passNumber === 2) {
drawProjectedQuadSelectionOutlineToContext(
quad, p1, p2, p3, p4, ctx, quadCanvas);
} else {
throw new Error('Invalid pass number');
}
}
const tmpP1 = vec3.create();
const tmpP2 = vec3.create();
const tmpP3 = vec3.create();
const tmpP4 = vec3.create();
function transformAndProcessQuads(
matrix, viewport, quads, numPasses, handleQuadFunc, opt_arg1, opt_arg2) {
for (let passNumber = 0; passNumber < numPasses; passNumber++) {
for (let i = 0; i < quads.length; i++) {
const quad = quads[i];
transform(tmpP1, quad.p1, matrix, viewport);
transform(tmpP2, quad.p2, matrix, viewport);
transform(tmpP3, quad.p3, matrix, viewport);
transform(tmpP4, quad.p4, matrix, viewport);
handleQuadFunc(passNumber, quad,
tmpP1, tmpP2, tmpP3, tmpP4,
opt_arg1, opt_arg2);
}
}
}
/**
* @constructor
*/
const QuadStackView = tr.ui.b.define('quad-stack-view');
QuadStackView.prototype = {
__proto__: HTMLDivElement.prototype,
decorate() {
this.className = 'quad-stack-view';
const node = tr.ui.b.instantiateTemplate('#quad-stack-view-template',
THIS_DOC);
Polymer.dom(this).appendChild(node);
this.updateHeaderVisibility_();
this.canvas_ = Polymer.dom(this).querySelector('#canvas');
this.chromeImages_ = {
left: Polymer.dom(this).querySelector('#chrome-left'),
mid: Polymer.dom(this).querySelector('#chrome-mid'),
right: Polymer.dom(this).querySelector('#chrome-right')
};
const stackingDistanceSlider = Polymer.dom(this).querySelector(
'#stacking-distance-slider');
stackingDistanceSlider.value = tr.b.Settings.get(
'quadStackView.stackingDistance', 45);
stackingDistanceSlider.addEventListener(
'change', this.onStackingDistanceChange_.bind(this));
stackingDistanceSlider.addEventListener(
'input', this.onStackingDistanceChange_.bind(this));
this.trackMouse_();
this.camera_ = new tr.ui.b.Camera(this.mouseModeSelector_);
this.camera_.addEventListener('renderrequired',
this.onRenderRequired_.bind(this));
this.cameraWasReset_ = false;
this.camera_.canvas = this.canvas_;
this.viewportRect_ = tr.b.math.Rect.fromXYWH(0, 0, 0, 0);
this.pixelRatio_ = window.devicePixelRatio || 1;
},
updateHeaderVisibility_() {
if (this.headerText) {
Polymer.dom(this).querySelector('#header').style.display = '';
} else {
Polymer.dom(this).querySelector('#header').style.display = 'none';
}
},
get headerText() {
return Polymer.dom(this).querySelector('#header').textContent;
},
set headerText(headerText) {
Polymer.dom(this).querySelector('#header').textContent = headerText;
this.updateHeaderVisibility_();
},
onStackingDistanceChange_(e) {
tr.b.Settings.set('quadStackView.stackingDistance',
this.stackingDistance);
this.scheduleRender();
e.stopPropagation();
},
get stackingDistance() {
return Polymer.dom(this).querySelector('#stacking-distance-slider').value;
},
get mouseModeSelector() {
return this.mouseModeSelector_;
},
get camera() {
return this.camera_;
},
set quads(q) {
this.quads_ = q;
this.scheduleRender();
},
set deviceRect(rect) {
if (!rect || rect.equalTo(this.deviceRect_)) return;
this.deviceRect_ = rect;
this.camera_.deviceRect = rect;
this.chromeQuad_ = undefined;
},
resize() {
if (!this.offsetParent) return true;
const width = parseInt(window.getComputedStyle(this.offsetParent).width);
const height = parseInt(window.getComputedStyle(
this.offsetParent).height);
const rect = tr.b.math.Rect.fromXYWH(0, 0, width, height);
if (rect.equalTo(this.viewportRect_)) return false;
this.viewportRect_ = rect;
this.style.width = width + 'px';
this.style.height = height + 'px';
this.canvas_.style.width = width + 'px';
this.canvas_.style.height = height + 'px';
this.canvas_.width = this.pixelRatio_ * width;
this.canvas_.height = this.pixelRatio_ * height;
if (!this.cameraWasReset_) {
this.camera_.resetCamera();
this.cameraWasReset_ = true;
}
return true;
},
readyToDraw() {
// If src isn't set yet, set it to ensure we can use
// the image to draw onto a canvas.
if (!this.chromeImages_.left.src) {
let leftContent =
window.getComputedStyle(this.chromeImages_.left).backgroundImage;
leftContent = tr.ui.b.extractUrlString(leftContent);
let midContent =
window.getComputedStyle(this.chromeImages_.mid).backgroundImage;
midContent = tr.ui.b.extractUrlString(midContent);
let rightContent =
window.getComputedStyle(this.chromeImages_.right).backgroundImage;
rightContent = tr.ui.b.extractUrlString(rightContent);
this.chromeImages_.left.src = leftContent;
this.chromeImages_.mid.src = midContent;
this.chromeImages_.right.src = rightContent;
}
// If all of the images are loaded (height > 0), then
// we are ready to draw.
return (this.chromeImages_.left.height > 0) &&
(this.chromeImages_.mid.height > 0) &&
(this.chromeImages_.right.height > 0);
},
get chromeQuad() {
if (this.chromeQuad_) return this.chromeQuad_;
// Draw the chrome border into a separate canvas.
const chromeCanvas = document.createElement('canvas');
const offsetY = this.chromeImages_.left.height;
chromeCanvas.width = this.deviceRect_.width;
chromeCanvas.height = this.deviceRect_.height + offsetY;
const leftWidth = this.chromeImages_.left.width;
const midWidth = this.chromeImages_.mid.width;
const rightWidth = this.chromeImages_.right.width;
const chromeCtx = chromeCanvas.getContext('2d');
chromeCtx.drawImage(this.chromeImages_.left, 0, 0);
chromeCtx.save();
chromeCtx.translate(leftWidth, 0);
// Calculate the scale of the mid image.
const s = (this.deviceRect_.width - leftWidth - rightWidth) / midWidth;
chromeCtx.scale(s, 1);
chromeCtx.drawImage(this.chromeImages_.mid, 0, 0);
chromeCtx.restore();
chromeCtx.drawImage(
this.chromeImages_.right, leftWidth + s * midWidth, 0);
// Construct the quad.
const chromeRect = tr.b.math.Rect.fromXYWH(
this.deviceRect_.x,
this.deviceRect_.y - offsetY,
this.deviceRect_.width,
this.deviceRect_.height + offsetY);
const chromeQuad = tr.b.math.Quad.fromRect(chromeRect);
chromeQuad.stackingGroupId = this.maxStackingGroupId_ + 1;
chromeQuad.imageData = chromeCtx.getImageData(
0, 0, chromeCanvas.width, chromeCanvas.height);
chromeQuad.shadowOffset = [0, 0];
chromeQuad.shadowBlur = 5;
chromeQuad.borderWidth = 3;
this.chromeQuad_ = chromeQuad;
return this.chromeQuad_;
},
scheduleRender() {
if (this.redrawScheduled_) return false;
this.redrawScheduled_ = true;
tr.b.requestAnimationFrame(this.render, this);
},
onRenderRequired_(e) {
this.scheduleRender();
},
stackTransformAndProcessQuads_(
numPasses, handleQuadFunc, includeChromeQuad, opt_arg1, opt_arg2) {
const mv = this.camera_.modelViewMatrix;
const p = this.camera_.projectionMatrix;
const viewport = tr.b.math.Rect.fromXYWH(
0, 0, this.canvas_.width, this.canvas_.height);
// Calculate the quad stacks.
const quadStacks = [];
for (let i = 0; i < this.quads_.length; ++i) {
const quad = this.quads_[i];
const stackingId = quad.stackingGroupId || 0;
while (stackingId >= quadStacks.length) {
quadStacks.push([]);
}
quadStacks[stackingId].push(quad);
}
const mvp = mat4.create();
this.maxStackingGroupId_ = quadStacks.length;
const effectiveStackingDistance =
this.stackingDistance * this.camera_.stackingDistanceDampening;
// Draw the quad stacks, raising each subsequent level.
mat4.multiply(mvp, p, mv);
for (let i = 0; i < quadStacks.length; ++i) {
transformAndProcessQuads(mvp, viewport, quadStacks[i],
numPasses, handleQuadFunc,
opt_arg1, opt_arg2);
mat4.translate(mv, mv, [0, 0, effectiveStackingDistance]);
mat4.multiply(mvp, p, mv);
}
if (includeChromeQuad && this.deviceRect_) {
transformAndProcessQuads(mvp, viewport, [this.chromeQuad],
numPasses, drawProjectedQuadToContext,
opt_arg1, opt_arg2);
}
},
render() {
this.redrawScheduled_ = false;
if (!this.readyToDraw()) {
setTimeout(this.scheduleRender.bind(this),
constants.IMAGE_LOAD_RETRY_TIME_MS);
return;
}
if (!this.quads_) return;
const canvasCtx = this.canvas_.getContext('2d');
if (!this.resize()) {
canvasCtx.clearRect(0, 0, this.canvas_.width, this.canvas_.height);
}
const quadCanvas = document.createElement('canvas');
this.stackTransformAndProcessQuads_(
3, drawProjectedQuadToContext, true,
canvasCtx, quadCanvas);
quadCanvas.width = 0; // Hack: Frees the quadCanvas' resources.
},
trackMouse_() {
this.mouseModeSelector_ = document.createElement(
'tr-ui-b-mouse-mode-selector');
this.mouseModeSelector_.targetElement = this.canvas_;
this.mouseModeSelector_.supportedModeMask =
tr.ui.b.MOUSE_SELECTOR_MODE.SELECTION |
tr.ui.b.MOUSE_SELECTOR_MODE.PANSCAN |
tr.ui.b.MOUSE_SELECTOR_MODE.ZOOM |
tr.ui.b.MOUSE_SELECTOR_MODE.ROTATE;
this.mouseModeSelector_.mode = tr.ui.b.MOUSE_SELECTOR_MODE.PANSCAN;
this.mouseModeSelector_.pos = {x: 0, y: 100};
Polymer.dom(this).appendChild(this.mouseModeSelector_);
this.mouseModeSelector_.settingsKey =
'quadStackView.mouseModeSelector';
this.mouseModeSelector_.setModifierForAlternateMode(
tr.ui.b.MOUSE_SELECTOR_MODE.ROTATE, tr.ui.b.MODIFIER.SHIFT);
this.mouseModeSelector_.setModifierForAlternateMode(
tr.ui.b.MOUSE_SELECTOR_MODE.PANSCAN, tr.ui.b.MODIFIER.SPACE);
this.mouseModeSelector_.setModifierForAlternateMode(
tr.ui.b.MOUSE_SELECTOR_MODE.ZOOM, tr.ui.b.MODIFIER.CMD_OR_CTRL);
this.mouseModeSelector_.addEventListener('updateselection',
this.onSelectionUpdate_.bind(this));
this.mouseModeSelector_.addEventListener('endselection',
this.onSelectionUpdate_.bind(this));
},
extractRelativeMousePosition_(e) {
const br = this.canvas_.getBoundingClientRect();
return [
this.pixelRatio_ * (e.clientX - this.canvas_.offsetLeft - br.left),
this.pixelRatio_ * (e.clientY - this.canvas_.offsetTop - br.top)
];
},
onSelectionUpdate_(e) {
const mousePos = this.extractRelativeMousePosition_(e);
const res = [];
function handleQuad(passNumber, quad, p1, p2, p3, p4) {
if (tr.b.math.pointInImplicitQuad(mousePos, p1, p2, p3, p4)) {
res.push(quad);
}
}
this.stackTransformAndProcessQuads_(1, handleQuad, false);
e = new tr.b.Event('selectionchange');
e.quads = res;
this.dispatchEvent(e);
}
};
return {
QuadStackView,
};
});
</script>
| {
"content_hash": "ac104a68c4e35fbd71d868e505c77cc5",
"timestamp": "",
"source": "github",
"line_count": 692,
"max_line_length": 80,
"avg_line_length": 32.20809248554913,
"alnum_prop": 0.6090272792534099,
"repo_name": "catapult-project/catapult-csm",
"id": "63b0c5e7df541de5784de2416cc38e17cb8b7d06",
"size": "22288",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "tracing/tracing/ui/base/quad_stack_view.html",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "C",
"bytes": "4902"
},
{
"name": "C++",
"bytes": "43728"
},
{
"name": "CSS",
"bytes": "24873"
},
{
"name": "Go",
"bytes": "80325"
},
{
"name": "HTML",
"bytes": "11817766"
},
{
"name": "JavaScript",
"bytes": "518002"
},
{
"name": "Makefile",
"bytes": "1588"
},
{
"name": "Python",
"bytes": "6207634"
},
{
"name": "Shell",
"bytes": "2558"
}
],
"symlink_target": ""
} |
/**
* Base room configuration
*/
function BaseRoomConfig(room)
{
this.room = room;
this.maxScore = null;
this.variables = {
bonusRate: 0
};
this.bonuses = {
BonusSelfSmall: true,
BonusSelfSlow: true,
BonusSelfFast: true,
BonusSelfMaster: true,
BonusEnemySlow: true,
BonusEnemyFast: true,
BonusEnemyBig: true,
BonusEnemyInverse: true,
BonusEnemyStraightAngle: true,
BonusAllBorderless: true,
BonusAllColor: false,
BonusGameClear: false
};
}
BaseRoomConfig.prototype.setMaxScore = function(maxScore)
{
maxScore = parseInt(maxScore, 10);
this.maxScore = maxScore ? maxScore : null;
return true;
};
/**
* Variable exists
*
* @param {String} variable
*
* @return {Boolean}
*/
BaseRoomConfig.prototype.variableExists = function(variable)
{
return typeof(this.variables[variable]) !== 'undefined';
};
/**
* Set variable
*
* @param {String} variable
* @param {Float} value
*/
BaseRoomConfig.prototype.setVariable = function(variable, value)
{
if (!this.variableExists(variable)) { return false; }
value = parseFloat(value);
if (-1 > value || value > 1 ) { return false; }
this.variables[variable] = value;
return true;
};
/**
* Get variable
*
* @param {String} variable
*
* @return {Float}
*/
BaseRoomConfig.prototype.getVariable = function(variable)
{
if (!this.variableExists(variable)) { return; }
return this.variables[variable];
};
/**
* Bonus exists
*
* @param {String} bonus
*
* @return {Boolean}
*/
BaseRoomConfig.prototype.bonusExists = function(bonus)
{
return typeof(this.bonuses[bonus]) !== 'undefined';
};
/**
* Toggle bonus
*
* @param {String} bonus
*
* @return {Boolean}
*/
BaseRoomConfig.prototype.toggleBonus = function(bonus)
{
if (!this.bonusExists(bonus)) { return false; }
this.bonuses[bonus] = !this.bonuses[bonus];
return true;
};
/**
* Get bonus value
*
* @param {String} bonus
*
* @return {Boolean}
*/
BaseRoomConfig.prototype.getBonus = function(bonus)
{
if (!this.bonusExists(bonus)) { return; }
return this.bonuses[bonus];
};
/**
* Set bonus value
*
* @param {String} bonus
* @param {Boolean} value
*
* @return {Boolean}
*/
BaseRoomConfig.prototype.setBonus = function(bonus, value)
{
if (!this.bonusExists(bonus)) { return; }
this.bonuses[bonus] = value ? true : false;
};
/**
* Get max score
*
* @return {Number}
*/
BaseRoomConfig.prototype.getMaxScore = function()
{
return this.maxScore ? this.maxScore : this.getDefaultMaxScore();
};
/**
* Get max score
*
* @param {Number} players
*
* @return {Number}
*/
BaseRoomConfig.prototype.getDefaultMaxScore = function()
{
return Math.max(1, (this.room.players.count() - 1) * 5);
};
/**
* Serialize
*
* @return {Object}
*/
BaseRoomConfig.prototype.serialize = function()
{
return {
maxScore: this.maxScore,
variables: this.variables,
bonuses: this.bonuses
};
};
| {
"content_hash": "118a7e5ec96eaa436f2e8a35a0d5032e",
"timestamp": "",
"source": "github",
"line_count": 174,
"max_line_length": 69,
"avg_line_length": 17.586206896551722,
"alnum_prop": 0.6303921568627451,
"repo_name": "Elao/curvytron-arcade",
"id": "565aaaee50bdc9c7207f3f3ac12bcb5588068d37",
"size": "3060",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "src/shared/model/BaseRoomConfig.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "146787"
},
{
"name": "HTML",
"bytes": "10413"
},
{
"name": "JavaScript",
"bytes": "210304"
}
],
"symlink_target": ""
} |
package org.blackbananacoin.incubator.extsupernode;
import static com.google.common.base.Preconditions.checkNotNull;
import java.math.BigDecimal;
import java.math.BigInteger;
import com.google.bitcoin.core.Utils;
public class BkbcUtils {
public static final long BTC = 100000000L;
public static final int mBTC = 100000;
public static final int uBTC = 100;
public static final BigInteger COIN = new BigInteger("100000000", 10);
public static final BigInteger mCOIN = new BigInteger("100000", 10);
public static final BigInteger uCOIN = new BigInteger("100", 10);
public static String toBtcStr(BigInteger value) {
checkNotNull(value);
String r = "";
BigDecimal v = new BigDecimal(value);
if (value.compareTo(Utils.COIN) > 0) {
BigDecimal valueInBTC = v.divide(new BigDecimal(Utils.COIN));
r = valueInBTC.toPlainString() + "BTC";
} else if (value.compareTo(mCOIN) > 0) {
BigDecimal valueInmBTC = v.divide(new BigDecimal(mCOIN));
r = valueInmBTC.toPlainString() + "mBTC";
} else {
BigDecimal valueInuBTC = v.divide(new BigDecimal(uCOIN));
r = valueInuBTC.toPlainString() + "uBTC";
}
return r;
}
public static String toBtcStr(long value) {
return toBtcStr(BigInteger.valueOf(value));
}
}
| {
"content_hash": "c177fa94b5b18c75b3c4ef72b6dc928d",
"timestamp": "",
"source": "github",
"line_count": 41,
"max_line_length": 71,
"avg_line_length": 30.21951219512195,
"alnum_prop": 0.7296206618240516,
"repo_name": "y12studio/BlackBananaCoin",
"id": "8a76221c3f686b659c6d6c9c98a249470695fae0",
"size": "1830",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "incubator/extsupernode/src/org/blackbananacoin/incubator/extsupernode/BkbcUtils.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "1411"
},
{
"name": "HTML",
"bytes": "5057"
},
{
"name": "Java",
"bytes": "66327"
}
],
"symlink_target": ""
} |
package org.sleuthkit.autopsy.timeline;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.logging.Level;
import javafx.collections.FXCollections;
import javafx.scene.Node;
import javafx.scene.control.Alert;
import javafx.scene.control.ButtonBar;
import javafx.scene.control.ButtonType;
import javafx.scene.control.Dialog;
import javafx.scene.control.DialogPane;
import javafx.scene.control.ListView;
import javafx.scene.image.Image;
import javafx.stage.Modality;
import javafx.stage.Stage;
import org.controlsfx.dialog.ProgressDialog;
import org.controlsfx.tools.Borders;
import org.openide.util.NbBundle;
import org.sleuthkit.autopsy.coreutils.Logger;
import org.sleuthkit.autopsy.coreutils.ThreadConfined;
/**
* Manager for the various prompts Timeline shows the user related to rebuilding
* the database.
*/
public class PromptDialogManager {
private static final Logger LOGGER = Logger.getLogger(PromptDialogManager.class.getName());
@NbBundle.Messages("PrompDialogManager.buttonType.showTimeline=Show Timeline")
private static final ButtonType SHOW_TIMELINE = new ButtonType(Bundle.PrompDialogManager_buttonType_showTimeline(), ButtonBar.ButtonData.OK_DONE);
@NbBundle.Messages("PrompDialogManager.buttonType.continueNoUpdate=Continue Without Updating")
private static final ButtonType CONTINUE_NO_UPDATE = new ButtonType(Bundle.PrompDialogManager_buttonType_continueNoUpdate(), ButtonBar.ButtonData.CANCEL_CLOSE);
@NbBundle.Messages("PrompDialogManager.buttonType.update=Update")
private static final ButtonType UPDATE = new ButtonType(Bundle.PrompDialogManager_buttonType_update(), ButtonBar.ButtonData.OK_DONE);
private static final Image LOGO;
static {
Image x = null;
try {
x = new Image(new URL("nbresloc:/org/netbeans/core/startup/frame.gif").openStream()); //NOI18N
} catch (IOException ex) {
LOGGER.log(Level.WARNING, "Failed to load branded icon for progress dialog.", ex); //NOI18N
}
LOGO = x;
}
private Dialog<?> currentDialog;
private final TimeLineController controller;
PromptDialogManager(TimeLineController controller) {
this.controller = controller;
}
@ThreadConfined(type = ThreadConfined.ThreadType.JFX)
boolean bringCurrentDialogToFront() {
if (currentDialog != null && currentDialog.isShowing()) {
((Stage) currentDialog.getDialogPane().getScene().getWindow()).toFront();
return true;
}
return false;
}
@NbBundle.Messages({"PromptDialogManager.progressDialog.title=Populating Timeline Data"})
@ThreadConfined(type = ThreadConfined.ThreadType.JFX)
public void showProgressDialog(CancellationProgressTask<?> task) {
currentDialog = new ProgressDialog(task);
currentDialog.headerTextProperty().bind(task.titleProperty());
setDialogIcons(currentDialog);
currentDialog.setTitle(Bundle.PromptDialogManager_progressDialog_title());
DialogPane dialogPane = currentDialog.getDialogPane();
dialogPane.setPrefSize(400, 200); //override autosizing which fails for some reason
//co-ordinate task cancelation and dialog hiding.
task.setOnCancelled(cancelled -> currentDialog.close());
task.setOnSucceeded(succeeded -> currentDialog.close());
dialogPane.getButtonTypes().setAll(ButtonType.CANCEL);
final Node cancelButton = dialogPane.lookupButton(ButtonType.CANCEL);
cancelButton.disableProperty().bind(task.cancellableProperty().not());
currentDialog.setOnCloseRequest(closeRequest -> {
if (task.isRunning()) {
closeRequest.consume();
}
if (task.isCancellable() && task.isCancelRequested() == false) {
task.requestCancel();
}
});
currentDialog.show();
}
@ThreadConfined(type = ThreadConfined.ThreadType.JFX)
static private void setDialogIcons(Dialog<?> dialog) {
Stage stage = (Stage) dialog.getDialogPane().getScene().getWindow();
stage.getIcons().setAll(LOGO);
}
@ThreadConfined(type = ThreadConfined.ThreadType.JFX)
static private void setDialogTitle(Dialog<?> dialog) {
Stage stage = (Stage) dialog.getDialogPane().getScene().getWindow();
stage.setTitle(Bundle.Timeline_confirmation_dialogs_title());
}
/**
* prompt the user that ingest is running and the db may not end up
* complete.
*
* @return true if they want to continue anyways
*/
@NbBundle.Messages({"PromptDialogManager.confirmDuringIngest.headerText=You are trying to show a timeline before ingest has been completed.\nThe timeline may be incomplete.",
"PromptDialogManager.confirmDuringIngest.contentText=Do you want to continue?"})
@ThreadConfined(type = ThreadConfined.ThreadType.JFX)
boolean confirmDuringIngest() {
currentDialog = new Alert(Alert.AlertType.CONFIRMATION, Bundle.PromptDialogManager_confirmDuringIngest_contentText(), SHOW_TIMELINE, ButtonType.CANCEL);
currentDialog.initModality(Modality.APPLICATION_MODAL);
currentDialog.setHeaderText(Bundle.PromptDialogManager_confirmDuringIngest_headerText());
setDialogIcons(currentDialog);
setDialogTitle(currentDialog);
return currentDialog.showAndWait().map(SHOW_TIMELINE::equals).orElse(false);
}
@NbBundle.Messages({"PromptDialogManager.rebuildPrompt.headerText=The Timeline database is incomplete and/or out of date.\nSome events may be missing or inaccurate and some features may be unavailable.",
"PromptDialogManager.rebuildPrompt.details=Details:"})
@ThreadConfined(type = ThreadConfined.ThreadType.JFX)
boolean confirmRebuild(ArrayList<String> rebuildReasons) {
currentDialog = new Alert(Alert.AlertType.CONFIRMATION, Bundle.TimeLinecontroller_updateNowQuestion(), UPDATE, CONTINUE_NO_UPDATE);
currentDialog.initModality(Modality.APPLICATION_MODAL);
currentDialog.setHeaderText(Bundle.PromptDialogManager_rebuildPrompt_headerText());
setDialogIcons(currentDialog);
setDialogTitle(currentDialog);
DialogPane dialogPane = currentDialog.getDialogPane();
ListView<String> listView = new ListView<>(FXCollections.observableArrayList(rebuildReasons));
listView.setCellFactory(lstView -> new WrappingListCell());
listView.setMaxHeight(75);
Node wrappedListView = Borders.wrap(listView).lineBorder().title(Bundle.PromptDialogManager_rebuildPrompt_details()).buildAll();
dialogPane.setExpandableContent(wrappedListView);
return currentDialog.showAndWait().map(UPDATE::equals).orElse(false);
}
}
| {
"content_hash": "9a6add5975eae0e33b3593c23e72c49a",
"timestamp": "",
"source": "github",
"line_count": 149,
"max_line_length": 207,
"avg_line_length": 45.54362416107382,
"alnum_prop": 0.7301797819039199,
"repo_name": "mhmdfy/autopsy",
"id": "ef249ff1e87fcc126d0f37324a0cafbea028f4ab",
"size": "7467",
"binary": false,
"copies": "2",
"ref": "refs/heads/develop",
"path": "Core/src/org/sleuthkit/autopsy/timeline/PromptDialogManager.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "5199"
},
{
"name": "CSS",
"bytes": "2953"
},
{
"name": "HTML",
"bytes": "8763"
},
{
"name": "Java",
"bytes": "6099326"
},
{
"name": "Perl",
"bytes": "1145199"
},
{
"name": "Python",
"bytes": "199334"
}
],
"symlink_target": ""
} |
package render
import (
"encoding/xml"
"net/http"
"net/http/httptest"
"testing"
)
type GreetingXML struct {
XMLName xml.Name `xml:"greeting"`
One string `xml:"one,attr"`
Two string `xml:"two,attr"`
}
func TestXMLBasic(t *testing.T) {
render := New(Options{
// nothing here to configure
})
var err error
h := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
err = render.XML(w, 299, GreetingXML{One: "hello", Two: "world"})
})
res := httptest.NewRecorder()
req, _ := http.NewRequest("GET", "/foo", nil)
h.ServeHTTP(res, req)
expectNil(t, err)
expect(t, res.Code, 299)
expect(t, res.Header().Get(ContentType), ContentXML+"; charset=UTF-8")
expect(t, res.Body.String(), "<greeting one=\"hello\" two=\"world\"></greeting>")
}
func TestXMLPrefix(t *testing.T) {
prefix := "<?xml version='1.0' encoding='UTF-8'?>\n"
render := New(Options{
PrefixXML: []byte(prefix),
})
var err error
h := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
err = render.XML(w, 300, GreetingXML{One: "hello", Two: "world"})
})
res := httptest.NewRecorder()
req, _ := http.NewRequest("GET", "/foo", nil)
h.ServeHTTP(res, req)
expectNil(t, err)
expect(t, res.Code, 300)
expect(t, res.Header().Get(ContentType), ContentXML+"; charset=UTF-8")
expect(t, res.Body.String(), prefix+"<greeting one=\"hello\" two=\"world\"></greeting>")
}
func TestXMLIndented(t *testing.T) {
render := New(Options{
IndentXML: true,
})
var err error
h := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
err = render.XML(w, http.StatusOK, GreetingXML{One: "hello", Two: "world"})
})
res := httptest.NewRecorder()
req, _ := http.NewRequest("GET", "/foo", nil)
h.ServeHTTP(res, req)
expectNil(t, err)
expect(t, res.Code, http.StatusOK)
expect(t, res.Header().Get(ContentType), ContentXML+"; charset=UTF-8")
expect(t, res.Body.String(), "<greeting one=\"hello\" two=\"world\"></greeting>\n")
}
func TestXMLWithError(t *testing.T) {
render := New(Options{
// nothing here to configure
})
var err error
h := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
err = render.XML(w, 299, map[string]string{"foo": "bar"})
})
res := httptest.NewRecorder()
req, _ := http.NewRequest("GET", "/foo", nil)
h.ServeHTTP(res, req)
expectNotNil(t, err)
expect(t, res.Code, 500)
}
func TestXMLCustomContentType(t *testing.T) {
render := New(Options{
XMLContentType: "application/customxml",
})
var err error
h := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
err = render.XML(w, http.StatusOK, GreetingXML{One: "hello", Two: "world"})
})
res := httptest.NewRecorder()
req, _ := http.NewRequest("GET", "/foo", nil)
h.ServeHTTP(res, req)
expectNil(t, err)
expect(t, res.Code, http.StatusOK)
expect(t, res.Header().Get(ContentType), "application/customxml; charset=UTF-8")
expect(t, res.Body.String(), "<greeting one=\"hello\" two=\"world\"></greeting>")
}
func TestXMLDisabledCharset(t *testing.T) {
render := New(Options{
DisableCharset: true,
})
var err error
h := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
err = render.XML(w, http.StatusOK, GreetingXML{One: "hello", Two: "world"})
})
res := httptest.NewRecorder()
req, _ := http.NewRequest("GET", "/foo", nil)
h.ServeHTTP(res, req)
expectNil(t, err)
expect(t, res.Code, http.StatusOK)
expect(t, res.Header().Get(ContentType), ContentXML)
expect(t, res.Body.String(), "<greeting one=\"hello\" two=\"world\"></greeting>")
}
| {
"content_hash": "32f2a1690f5bb67e3349d200731a5904",
"timestamp": "",
"source": "github",
"line_count": 133,
"max_line_length": 89,
"avg_line_length": 26.593984962406015,
"alnum_prop": 0.6627085100367544,
"repo_name": "paulnguyen/cloud",
"id": "284ff79b62217da1be9eb7f626023cf4c01647f0",
"size": "3537",
"binary": false,
"copies": "27",
"ref": "refs/heads/master",
"path": "google/kubernetes-engine/gumball-pod/src/github.com/unrolled/render/render_xml_test.go",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "25533"
},
{
"name": "C",
"bytes": "126040"
},
{
"name": "CSS",
"bytes": "245036"
},
{
"name": "CoffeeScript",
"bytes": "2743"
},
{
"name": "Dockerfile",
"bytes": "14608"
},
{
"name": "Go",
"bytes": "20481511"
},
{
"name": "Groovy",
"bytes": "188941"
},
{
"name": "HTML",
"bytes": "954443"
},
{
"name": "Java",
"bytes": "564731"
},
{
"name": "JavaScript",
"bytes": "1135459"
},
{
"name": "Makefile",
"bytes": "114425"
},
{
"name": "Objective-C",
"bytes": "194"
},
{
"name": "PHP",
"bytes": "2694"
},
{
"name": "PLpgSQL",
"bytes": "24418"
},
{
"name": "Processing",
"bytes": "18508"
},
{
"name": "Ruby",
"bytes": "4183900"
},
{
"name": "Shell",
"bytes": "492733"
},
{
"name": "Swift",
"bytes": "12437"
},
{
"name": "TSQL",
"bytes": "346528"
},
{
"name": "Vim script",
"bytes": "837"
}
],
"symlink_target": ""
} |
import socket
import threading
import Queue
import collections
import SocketServer
import struct
import os
import sys
import time
import traceback
import uuid
import subprocess
import StringIO
import imp
import hashlib
import base64
import logging
import re
import ssl
import tempfile
import string
import datetime
import random
import shutil
import platform
import errno, stat
import zlib
import tempfile
import code
import Queue
import glob
import multiprocessing
import math
import binascii
import inspect
import shlex
import json
import ctypes
import ctypes.wintypes
import threading
import time
import urllib
import urllib2
import socks
| {
"content_hash": "c83cac0a4283e1300ac580fe6d99d6cc",
"timestamp": "",
"source": "github",
"line_count": 44,
"max_line_length": 22,
"avg_line_length": 14.590909090909092,
"alnum_prop": 0.8582554517133957,
"repo_name": "xeddmc/pupy",
"id": "6cbd4d3d628f110e8944ff000e44e9a6822ed37f",
"size": "642",
"binary": false,
"copies": "10",
"ref": "refs/heads/master",
"path": "client/additional_imports.py",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Batchfile",
"bytes": "4914"
},
{
"name": "C",
"bytes": "205080"
},
{
"name": "Python",
"bytes": "530306"
},
{
"name": "Shell",
"bytes": "85"
}
],
"symlink_target": ""
} |
package org.apache.camel.component.elsql;
import java.util.Collections;
import java.util.Map;
import org.apache.camel.Exchange;
import org.springframework.jdbc.core.namedparam.AbstractSqlParameterSource;
/**
* A {@link org.springframework.jdbc.core.namedparam.SqlParameterSource} that is used by {@link com.opengamma.elsql.ElSql}
* to lookup parameter values. This source will lookup in the Camel {@link Exchange} and {@link org.apache.camel.Message}
* assuming they are Map based.
*/
public class ElsqlSqlMapSource extends AbstractSqlParameterSource {
// use the maps from the Camel Message as they are case insensitive which makes it easier for end users to work with
private final Exchange exchange;
private final Map<?, ?> bodyMap;
private final Map<?, ?> headersMap;
public ElsqlSqlMapSource(Exchange exchange, Object body) {
this.exchange = exchange;
this.bodyMap = safeMap(exchange.getContext().getTypeConverter().tryConvertTo(Map.class, body));
this.headersMap = safeMap(exchange.getIn().getHeaders());
}
private static Map<?, ?> safeMap(Map<?, ?> map) {
return (map == null || map.isEmpty()) ? Collections.emptyMap() : map;
}
@Override
public boolean hasValue(String paramName) {
if ("body".equals(paramName)) {
return true;
} else if ((paramName.startsWith("$simple{") || paramName.startsWith("${")) && paramName.endsWith("}")) {
return true;
} else {
return bodyMap.containsKey(paramName) || headersMap.containsKey(paramName);
}
}
@Override
public Object getValue(String paramName) throws IllegalArgumentException {
Object answer;
if ("body".equals(paramName)) {
answer = exchange.getIn().getBody();
} else if ((paramName.startsWith("$simple{") || paramName.startsWith("${")) && paramName.endsWith("}")) {
// its a simple language expression
// spring org.springframework.jdbc.core.namedparam.NamedParameterUtils.PARAMETER_SEPARATORS
// uses : as parameter separator and we may use colon in simple languages as well such as bean:foo
// so we have to use # instead and replace them back
paramName = paramName.replace('#', ':');
answer = exchange.getContext().resolveLanguage("simple").createExpression(paramName).evaluate(exchange, Object.class);
} else {
answer = bodyMap.get(paramName);
if (answer == null) {
answer = headersMap.get(paramName);
}
}
return answer;
}
}
| {
"content_hash": "19456cb538c63f8fe20442bf99cde74b",
"timestamp": "",
"source": "github",
"line_count": 65,
"max_line_length": 130,
"avg_line_length": 40.53846153846154,
"alnum_prop": 0.6527514231499051,
"repo_name": "zregvart/camel",
"id": "6ea5760891e63af57da7ede1807963fa7b95d9cf",
"size": "3437",
"binary": false,
"copies": "7",
"ref": "refs/heads/master",
"path": "components/camel-elsql/src/main/java/org/apache/camel/component/elsql/ElsqlSqlMapSource.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Apex",
"bytes": "6521"
},
{
"name": "Batchfile",
"bytes": "2353"
},
{
"name": "CSS",
"bytes": "5472"
},
{
"name": "Elm",
"bytes": "10852"
},
{
"name": "FreeMarker",
"bytes": "8015"
},
{
"name": "Groovy",
"bytes": "20938"
},
{
"name": "HTML",
"bytes": "914791"
},
{
"name": "Java",
"bytes": "90321137"
},
{
"name": "JavaScript",
"bytes": "101298"
},
{
"name": "RobotFramework",
"bytes": "8461"
},
{
"name": "Shell",
"bytes": "11165"
},
{
"name": "TSQL",
"bytes": "28835"
},
{
"name": "Tcl",
"bytes": "4974"
},
{
"name": "Thrift",
"bytes": "6979"
},
{
"name": "XQuery",
"bytes": "546"
},
{
"name": "XSLT",
"bytes": "280849"
}
],
"symlink_target": ""
} |
<html lang="en">
<head>
<title>TIC54X-Locals - Using as</title>
<meta http-equiv="Content-Type" content="text/html">
<meta name="description" content="Using as">
<meta name="generator" content="makeinfo 4.13">
<link title="Top" rel="start" href="index.html#Top">
<link rel="up" href="TIC54X_002dDependent.html#TIC54X_002dDependent" title="TIC54X-Dependent">
<link rel="prev" href="TIC54X_002dSubsyms.html#TIC54X_002dSubsyms" title="TIC54X-Subsyms">
<link rel="next" href="TIC54X_002dBuiltins.html#TIC54X_002dBuiltins" title="TIC54X-Builtins">
<link href="http://www.gnu.org/software/texinfo/" rel="generator-home" title="Texinfo Homepage">
<!--
This file documents the GNU Assembler "as".
Copyright (C) 1991-2019 Free Software Foundation, Inc.
Permission is granted to copy, distribute and/or modify this document
under the terms of the GNU Free Documentation License, Version 1.3
or any later version published by the Free Software Foundation;
with no Invariant Sections, with no Front-Cover Texts, and with no
Back-Cover Texts. A copy of the license is included in the
section entitled ``GNU Free Documentation License''.
-->
<meta http-equiv="Content-Style-Type" content="text/css">
<style type="text/css"><!--
pre.display { font-family:inherit }
pre.format { font-family:inherit }
pre.smalldisplay { font-family:inherit; font-size:smaller }
pre.smallformat { font-family:inherit; font-size:smaller }
pre.smallexample { font-size:smaller }
pre.smalllisp { font-size:smaller }
span.sc { font-variant:small-caps }
span.roman { font-family:serif; font-weight:normal; }
span.sansserif { font-family:sans-serif; font-weight:normal; }
--></style>
</head>
<body>
<div class="node">
<a name="TIC54X-Locals"></a>
<a name="TIC54X_002dLocals"></a>
<p>
Next: <a rel="next" accesskey="n" href="TIC54X_002dBuiltins.html#TIC54X_002dBuiltins">TIC54X-Builtins</a>,
Previous: <a rel="previous" accesskey="p" href="TIC54X_002dSubsyms.html#TIC54X_002dSubsyms">TIC54X-Subsyms</a>,
Up: <a rel="up" accesskey="u" href="TIC54X_002dDependent.html#TIC54X_002dDependent">TIC54X-Dependent</a>
<hr>
</div>
<h4 class="subsection">9.44.6 Local Labels</h4>
<p>Local labels may be defined in two ways:
<ul>
<li>$N, where N is a decimal number between 0 and 9
<li>LABEL?, where LABEL is any legal symbol name.
</ul>
<p>Local labels thus defined may be redefined or automatically generated.
The scope of a local label is based on when it may be undefined or reset.
This happens when one of the following situations is encountered:
<ul>
<li>.newblock directive see <a href="TIC54X_002dDirectives.html#TIC54X_002dDirectives"><code>.newblock</code></a>
<li>The current section is changed (.sect, .text, or .data)
<li>Entering or leaving an included file
<li>The macro scope where the label was defined is exited
</ul>
</body></html>
| {
"content_hash": "b9f48b4099e9035d40e69093150301cb",
"timestamp": "",
"source": "github",
"line_count": 70,
"max_line_length": 116,
"avg_line_length": 41.01428571428571,
"alnum_prop": 0.7335423197492164,
"repo_name": "bouffalolab/bl_iot_sdk_matter",
"id": "1b064a59e2ba0e8e8dbf4334f0a47a25d3da8c09",
"size": "2871",
"binary": false,
"copies": "1",
"ref": "refs/heads/release_spiwifi_bl602",
"path": "toolchain/riscv/Linux/share/doc/as.html/TIC54X_002dLocals.html",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Assembly",
"bytes": "46671"
},
{
"name": "Batchfile",
"bytes": "1603"
},
{
"name": "C",
"bytes": "24837905"
},
{
"name": "C++",
"bytes": "14471862"
},
{
"name": "CMake",
"bytes": "124252"
},
{
"name": "HTML",
"bytes": "24826"
},
{
"name": "Makefile",
"bytes": "114632"
},
{
"name": "Perl",
"bytes": "2589"
},
{
"name": "Python",
"bytes": "273291"
},
{
"name": "Roff",
"bytes": "3255873"
},
{
"name": "Shell",
"bytes": "27722"
},
{
"name": "XC",
"bytes": "18410"
}
],
"symlink_target": ""
} |
import * as Supertest from "supertest"
import * as Chai from "chai"
import { RequestAdapter } from "../src/request-adapter"
import * as Express from "express"
import * as Kamboja from "kamboja"
import * as Sinon from "sinon"
describe("RequestAdapter", () => {
it("Should return cookie with case insensitive", async () => {
let test = new RequestAdapter(<any>{
cookies: { otherKey: "OtherValue", TheKey: "TheValue" },
header: () => { }
})
Chai.expect(test.getCookie("thekey")).eq("TheValue")
})
it("Should return header with case insensitive", async () => {
let test = new RequestAdapter(<any>{
headers: { TheKey: "TheValue" },
header: () => { }
})
Chai.expect(test.getHeader("thekey")).eq("TheValue")
})
it("Should return params with case insensitive", async () => {
let test = new RequestAdapter(<any>{
params: { TheKey: "TheValue" },
header: () => { }
})
Chai.expect(test.getParam("thekey")).eq("TheValue")
})
it("Should check Accept header", async () => {
let accept = Sinon.stub()
accept.withArgs("xml").returns("xml")
accept.withArgs(["xml", "html"]).returns("xml")
let test = new RequestAdapter(<any>{
accepts: accept,
header: () => { }
})
Chai.expect(test.getAccepts("xml")).eq("xml")
Chai.expect(test.getAccepts(["xml", "html"])).eq("xml")
})
it("Should return isAuthenticated properly", async () => {
let test = new RequestAdapter(<any>{
isAuthenticated: function () { return true },
header: () => { }
})
Chai.expect(test.isAuthenticated()).true
})
it("Should return user properly", async () => {
let test = new RequestAdapter(<any>{
user: {
role: "admin",
displayName: "Ketut Sandiarsa",
id: "8083535"
},
header: () => { }
})
Chai.expect(test.user).deep.eq({
role: "admin",
displayName: "Ketut Sandiarsa",
id: "8083535"
})
})
it("Should return user role properly", async () => {
let test = new RequestAdapter(<any>{
user: {
role: "admin",
displayName: "Ketut Sandiarsa",
id: "8083535"
},
header: () => { }
})
Chai.expect(test.getUserRole()).eq("admin")
})
it("getUserRole should not error when user is undefined", async () => {
let test = new RequestAdapter(<any>{
header: () => { }
})
Chai.expect(test.getUserRole()).undefined
})
}) | {
"content_hash": "f311e289d8e81bbbde37d715778c28b7",
"timestamp": "",
"source": "github",
"line_count": 88,
"max_line_length": 75,
"avg_line_length": 31.636363636363637,
"alnum_prop": 0.5093390804597702,
"repo_name": "kambojajs/kamboja-express",
"id": "c5082a4eda1d1b715343f0b465d6773125f19cf2",
"size": "2784",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "test/request-adapter.spec.ts",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "166"
},
{
"name": "JavaScript",
"bytes": "3116"
},
{
"name": "Shell",
"bytes": "157"
},
{
"name": "TypeScript",
"bytes": "52780"
}
],
"symlink_target": ""
} |
FROM balenalib/vab820-quad-ubuntu:bionic-build
ENV NODE_VERSION 10.23.1
ENV YARN_VERSION 1.22.4
RUN for key in \
6A010C5166006599AA17F08146C2130DFD2497F5 \
; do \
gpg --keyserver pgp.mit.edu --recv-keys "$key" || \
gpg --keyserver keyserver.pgp.com --recv-keys "$key" || \
gpg --keyserver ha.pool.sks-keyservers.net --recv-keys "$key" ; \
done \
&& curl -SLO "http://nodejs.org/dist/v$NODE_VERSION/node-v$NODE_VERSION-linux-armv7l.tar.gz" \
&& echo "8f965f2757efcf3077d655bfcea36f7a29c58958355e0eb23cfb725740c3ccbe node-v$NODE_VERSION-linux-armv7l.tar.gz" | sha256sum -c - \
&& tar -xzf "node-v$NODE_VERSION-linux-armv7l.tar.gz" -C /usr/local --strip-components=1 \
&& rm "node-v$NODE_VERSION-linux-armv7l.tar.gz" \
&& curl -fSLO --compressed "https://yarnpkg.com/downloads/$YARN_VERSION/yarn-v$YARN_VERSION.tar.gz" \
&& curl -fSLO --compressed "https://yarnpkg.com/downloads/$YARN_VERSION/yarn-v$YARN_VERSION.tar.gz.asc" \
&& gpg --batch --verify yarn-v$YARN_VERSION.tar.gz.asc yarn-v$YARN_VERSION.tar.gz \
&& mkdir -p /opt/yarn \
&& tar -xzf yarn-v$YARN_VERSION.tar.gz -C /opt/yarn --strip-components=1 \
&& ln -s /opt/yarn/bin/yarn /usr/local/bin/yarn \
&& ln -s /opt/yarn/bin/yarn /usr/local/bin/yarnpkg \
&& rm yarn-v$YARN_VERSION.tar.gz.asc yarn-v$YARN_VERSION.tar.gz \
&& npm config set unsafe-perm true -g --unsafe-perm \
&& rm -rf /tmp/*
CMD ["echo","'No CMD command was set in Dockerfile! Details about CMD command could be found in Dockerfile Guide section in our Docs. Here's the link: https://balena.io/docs"]
RUN curl -SLO "https://raw.githubusercontent.com/balena-io-library/base-images/8accad6af708fca7271c5c65f18a86782e19f877/scripts/assets/tests/test-stack@node.sh" \
&& echo "Running test-stack@node" \
&& chmod +x test-stack@node.sh \
&& bash test-stack@node.sh \
&& rm -rf test-stack@node.sh
RUN [ ! -d /.balena/messages ] && mkdir -p /.balena/messages; echo 'Here are a few details about this Docker image (For more information please visit https://www.balena.io/docs/reference/base-images/base-images/): \nArchitecture: ARM v7 \nOS: Ubuntu bionic \nVariant: build variant \nDefault variable(s): UDEV=off \nThe following software stack is preinstalled: \nNode.js v10.23.1, Yarn v1.22.4 \nExtra features: \n- Easy way to install packages with `install_packages <package-name>` command \n- Run anywhere with cross-build feature (for ARM only) \n- Keep the container idling with `balena-idle` command \n- Show base image details with `balena-info` command' > /.balena/messages/image-info
RUN echo '#!/bin/sh.real\nbalena-info\nrm -f /bin/sh\ncp /bin/sh.real /bin/sh\n/bin/sh "$@"' > /bin/sh-shim \
&& chmod +x /bin/sh-shim \
&& cp /bin/sh /bin/sh.real \
&& mv /bin/sh-shim /bin/sh | {
"content_hash": "b2a3df456b965dbecb6e892f153ac596",
"timestamp": "",
"source": "github",
"line_count": 41,
"max_line_length": 694,
"avg_line_length": 66.90243902439025,
"alnum_prop": 0.7101713452424353,
"repo_name": "nghiant2710/base-images",
"id": "fef72bb60afe8d56b5d632d2e452e1ec29de9c58",
"size": "2764",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "balena-base-images/node/vab820-quad/ubuntu/bionic/10.23.1/build/Dockerfile",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Dockerfile",
"bytes": "144558581"
},
{
"name": "JavaScript",
"bytes": "16316"
},
{
"name": "Shell",
"bytes": "368690"
}
],
"symlink_target": ""
} |
#ifndef ContainerNodeAlgorithms_h
#define ContainerNodeAlgorithms_h
#include "Document.h"
#include "ElementIterator.h"
#include "Frame.h"
#include "HTMLFrameOwnerElement.h"
#include "InspectorInstrumentation.h"
#include "NodeTraversal.h"
#include "ShadowRoot.h"
#include <wtf/Assertions.h>
#include <wtf/Ref.h>
namespace WebCore {
class ChildNodeInsertionNotifier {
public:
explicit ChildNodeInsertionNotifier(ContainerNode& insertionPoint)
: m_insertionPoint(insertionPoint)
{
}
void notify(Node&);
private:
void notifyDescendantInsertedIntoDocument(ContainerNode&);
void notifyDescendantInsertedIntoTree(ContainerNode&);
void notifyNodeInsertedIntoDocument(Node&);
void notifyNodeInsertedIntoTree(ContainerNode&);
ContainerNode& m_insertionPoint;
Vector<Ref<Node>> m_postInsertionNotificationTargets;
};
class ChildNodeRemovalNotifier {
public:
explicit ChildNodeRemovalNotifier(ContainerNode& insertionPoint)
: m_insertionPoint(insertionPoint)
{
}
void notify(Node&);
private:
void notifyDescendantRemovedFromDocument(ContainerNode&);
void notifyDescendantRemovedFromTree(ContainerNode&);
void notifyNodeRemovedFromDocument(Node&);
void notifyNodeRemovedFromTree(ContainerNode&);
ContainerNode& m_insertionPoint;
};
namespace Private {
template<class GenericNode, class GenericNodeContainer>
void addChildNodesToDeletionQueue(GenericNode*& head, GenericNode*& tail, GenericNodeContainer&);
}
// Helper functions for TreeShared-derived classes, which have a 'Node' style interface
// This applies to 'ContainerNode' and 'SVGElementInstance'
template<class GenericNode, class GenericNodeContainer>
inline void removeDetachedChildrenInContainer(GenericNodeContainer& container)
{
// List of nodes to be deleted.
GenericNode* head = 0;
GenericNode* tail = 0;
Private::addChildNodesToDeletionQueue<GenericNode, GenericNodeContainer>(head, tail, container);
GenericNode* n;
GenericNode* next;
while ((n = head) != 0) {
ASSERT(n->m_deletionHasBegun);
next = n->nextSibling();
n->setNextSibling(0);
head = next;
if (next == 0)
tail = 0;
if (n->hasChildNodes())
Private::addChildNodesToDeletionQueue<GenericNode, GenericNodeContainer>(head, tail, *static_cast<GenericNodeContainer*>(n));
delete n;
}
}
template<class GenericNode, class GenericNodeContainer>
inline void appendChildToContainer(GenericNode* child, GenericNodeContainer& container)
{
child->setParentNode(&container);
GenericNode* lastChild = container.lastChild();
if (lastChild) {
child->setPreviousSibling(lastChild);
lastChild->setNextSibling(child);
} else
container.setFirstChild(child);
container.setLastChild(child);
}
// Helper methods for removeDetachedChildrenInContainer, hidden from WebCore namespace
namespace Private {
template<class GenericNode, class GenericNodeContainer, bool dispatchRemovalNotification>
struct NodeRemovalDispatcher {
static void dispatch(GenericNode&, GenericNodeContainer&)
{
// no-op, by default
}
};
template<class GenericNode, class GenericNodeContainer>
struct NodeRemovalDispatcher<GenericNode, GenericNodeContainer, true> {
static void dispatch(GenericNode& node, GenericNodeContainer& container)
{
// Clean up any TreeScope to a removed tree.
if (Document* containerDocument = container.ownerDocument())
containerDocument->adoptIfNeeded(&node);
if (node.inDocument())
ChildNodeRemovalNotifier(container).notify(node);
}
};
template<class GenericNode>
struct ShouldDispatchRemovalNotification {
static const bool value = false;
};
template<>
struct ShouldDispatchRemovalNotification<Node> {
static const bool value = true;
};
template<class GenericNode, class GenericNodeContainer>
void addChildNodesToDeletionQueue(GenericNode*& head, GenericNode*& tail, GenericNodeContainer& container)
{
// We have to tell all children that their parent has died.
GenericNode* next = 0;
for (GenericNode* n = container.firstChild(); n != 0; n = next) {
ASSERT(!n->m_deletionHasBegun);
next = n->nextSibling();
n->setNextSibling(0);
n->setParentNode(0);
container.setFirstChild(next);
if (next)
next->setPreviousSibling(0);
if (!n->refCount()) {
#ifndef NDEBUG
n->m_deletionHasBegun = true;
#endif
// Add the node to the list of nodes to be deleted.
// Reuse the nextSibling pointer for this purpose.
if (tail)
tail->setNextSibling(n);
else
head = n;
tail = n;
} else {
Ref<GenericNode> protect(*n); // removedFromDocument may remove remove all references to this node.
NodeRemovalDispatcher<GenericNode, GenericNodeContainer, ShouldDispatchRemovalNotification<GenericNode>::value>::dispatch(*n, container);
}
}
container.setLastChild(0);
}
} // namespace Private
inline void ChildNodeInsertionNotifier::notifyNodeInsertedIntoDocument(Node& node)
{
ASSERT(m_insertionPoint.inDocument());
if (Node::InsertionShouldCallDidNotifySubtreeInsertions == node.insertedInto(m_insertionPoint))
m_postInsertionNotificationTargets.append(node);
if (node.isContainerNode())
notifyDescendantInsertedIntoDocument(toContainerNode(node));
}
inline void ChildNodeInsertionNotifier::notifyNodeInsertedIntoTree(ContainerNode& node)
{
NoEventDispatchAssertion assertNoEventDispatch;
ASSERT(!m_insertionPoint.inDocument());
if (Node::InsertionShouldCallDidNotifySubtreeInsertions == node.insertedInto(m_insertionPoint))
m_postInsertionNotificationTargets.append(node);
notifyDescendantInsertedIntoTree(node);
}
inline void ChildNodeInsertionNotifier::notify(Node& node)
{
ASSERT(!NoEventDispatchAssertion::isEventDispatchForbidden());
#if ENABLE(INSPECTOR)
InspectorInstrumentation::didInsertDOMNode(&node.document(), &node);
#endif
Ref<Document> protectDocument(node.document());
Ref<Node> protectNode(node);
if (m_insertionPoint.inDocument())
notifyNodeInsertedIntoDocument(node);
else if (node.isContainerNode())
notifyNodeInsertedIntoTree(toContainerNode(node));
for (size_t i = 0; i < m_postInsertionNotificationTargets.size(); ++i)
m_postInsertionNotificationTargets[i]->didNotifySubtreeInsertions(&m_insertionPoint);
}
inline void ChildNodeRemovalNotifier::notifyNodeRemovedFromDocument(Node& node)
{
ASSERT(m_insertionPoint.inDocument());
node.removedFrom(m_insertionPoint);
if (node.isContainerNode())
notifyDescendantRemovedFromDocument(toContainerNode(node));
}
inline void ChildNodeRemovalNotifier::notifyNodeRemovedFromTree(ContainerNode& node)
{
NoEventDispatchAssertion assertNoEventDispatch;
ASSERT(!m_insertionPoint.inDocument());
node.removedFrom(m_insertionPoint);
notifyDescendantRemovedFromTree(node);
}
inline void ChildNodeRemovalNotifier::notify(Node& node)
{
if (node.inDocument()) {
notifyNodeRemovedFromDocument(node);
node.document().notifyRemovePendingSheetIfNeeded();
} else if (node.isContainerNode())
notifyNodeRemovedFromTree(toContainerNode(node));
}
enum SubframeDisconnectPolicy {
RootAndDescendants,
DescendantsOnly
};
void disconnectSubframes(ContainerNode& root, SubframeDisconnectPolicy);
inline void disconnectSubframesIfNeeded(ContainerNode& root, SubframeDisconnectPolicy policy)
{
if (!root.connectedSubframeCount())
return;
disconnectSubframes(root, policy);
}
} // namespace WebCore
#endif // ContainerNodeAlgorithms_h
| {
"content_hash": "2dbdd91eb1b708b9320609470435098e",
"timestamp": "",
"source": "github",
"line_count": 260,
"max_line_length": 153,
"avg_line_length": 31.06923076923077,
"alnum_prop": 0.7077246843278039,
"repo_name": "unofficial-opensource-apple/WebCore",
"id": "b4299b01a91fe13f053cfdf4c8ee068edb4388d3",
"size": "8978",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "dom/ContainerNodeAlgorithms.h",
"mode": "33188",
"license": "bsd-2-clause",
"language": [
{
"name": "Assembly",
"bytes": "3242"
},
{
"name": "Bison",
"bytes": "11790"
},
{
"name": "C",
"bytes": "3445018"
},
{
"name": "C++",
"bytes": "37881487"
},
{
"name": "CSS",
"bytes": "121894"
},
{
"name": "JavaScript",
"bytes": "131375"
},
{
"name": "Makefile",
"bytes": "27"
},
{
"name": "Objective-C",
"bytes": "392661"
},
{
"name": "Objective-C++",
"bytes": "2868092"
},
{
"name": "Perl",
"bytes": "638219"
},
{
"name": "Python",
"bytes": "24585"
},
{
"name": "Shell",
"bytes": "12541"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="UTF-8"?>
<!--
Copyright 2015-2016 Red Hat, Inc. and/or its affiliates
and other contributors as indicated by the @author tags.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.hawkular.inventory</groupId>
<artifactId>hawkular-inventory-impl-tinkerpop-parent</artifactId>
<version>1.1.4.Final-SNAPSHOT</version>
</parent>
<artifactId>hawkular-inventory-impl-tinkerpop</artifactId>
<packaging>jar</packaging>
<name>Hawkular Inventory Tinkerpop Implementation</name>
<dependencies>
<dependency>
<groupId>org.hawkular.inventory</groupId>
<artifactId>hawkular-inventory-api</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>org.hawkular.inventory</groupId>
<artifactId>hawkular-inventory-impl-tinkerpop-spi</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>org.jboss.logging</groupId>
<artifactId>jboss-logging</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.jboss.logging</groupId>
<artifactId>jboss-logging-annotations</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.jboss.logging</groupId>
<artifactId>jboss-logging-processor</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.apache.tinkerpop</groupId>
<artifactId>gremlin-core</artifactId>
<version>${version.org.apache.tinkerpop}</version>
</dependency>
<!-- test deps -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.hawkular.inventory</groupId>
<artifactId>hawkular-inventory-api</artifactId>
<version>${project.version}</version>
<scope>test</scope>
<type>test-jar</type>
</dependency>
<dependency>
<groupId>javax.mail</groupId>
<artifactId>javax.mail-api</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<finalName>hawkular-${project.artifactId}-${project.version}</finalName>
</build>
</project>
| {
"content_hash": "d5c62fa824b0640bb47930f68351f5cc",
"timestamp": "",
"source": "github",
"line_count": 104,
"max_line_length": 204,
"avg_line_length": 30.528846153846153,
"alnum_prop": 0.6818897637795276,
"repo_name": "hawkular/hawkular-inventory",
"id": "405653046068f5dd2e8de739fc934179cb428ebe",
"size": "3175",
"binary": false,
"copies": "1",
"ref": "refs/heads/1.0.x",
"path": "hawkular-inventory-impl-tinkerpop-parent/hawkular-inventory-impl-tinkerpop/pom.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ANTLR",
"bytes": "4851"
},
{
"name": "Batchfile",
"bytes": "5271"
},
{
"name": "Java",
"bytes": "2357226"
},
{
"name": "Scala",
"bytes": "15376"
},
{
"name": "Shell",
"bytes": "11074"
},
{
"name": "XSLT",
"bytes": "9792"
}
],
"symlink_target": ""
} |
class Timer {
public:
Timer() = default;
void Tic() {
start_ = std::chrono::system_clock::now();
}
double Toc() {
std::chrono::time_point<std::chrono::system_clock> end =
std::chrono::system_clock::now();
std::chrono::duration<double> elapsed = end - start_;
return elapsed.count();
}
private:
std::chrono::time_point<std::chrono::system_clock> start_;
};
#endif // _MONSTER_AVENGERS_TIMER_
| {
"content_hash": "e6ae515753f2a7539b899d98a1536cbc",
"timestamp": "",
"source": "github",
"line_count": 21,
"max_line_length": 61,
"avg_line_length": 20.761904761904763,
"alnum_prop": 0.6123853211009175,
"repo_name": "breakds/monster-avengers",
"id": "7124f7193b0a2ec56e40832335cd238885c73652",
"size": "522",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "cpp/supp/timer.h",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "709"
},
{
"name": "C#",
"bytes": "16508"
},
{
"name": "C++",
"bytes": "189199"
},
{
"name": "CMake",
"bytes": "7485"
},
{
"name": "CSS",
"bytes": "207527"
},
{
"name": "Common Lisp",
"bytes": "225172"
},
{
"name": "HTML",
"bytes": "187192"
},
{
"name": "JavaScript",
"bytes": "549985"
},
{
"name": "Shell",
"bytes": "454"
}
],
"symlink_target": ""
} |
import {isLayoutSizeDefined} from '../../../src/layout';
import {loadPromise} from '../../../src/event-helper';
import {addParamsToUrl} from '../../../src/url';
import {getDataParamsFromAttributes} from '../../../src/dom';
import {setStyles} from '../../../src/style';
import {user} from '../../../src/log';
class AmpKaltura extends AMP.BaseElement {
/** @override */
createdCallback() {
this.preconnect.url('https://cdnapisec.kaltura.com');
}
/** @override */
isLayoutSupported(layout) {
return isLayoutSizeDefined(layout);
}
/** @override */
buildCallback() {
if (!this.getPlaceholder()) {
this.buildImagePlaceholder_();
}
}
/** @override */
layoutCallback() {
const width = this.element.getAttribute('width');
const height = this.element.getAttribute('height');
const partnerid = user.assert(
this.element.getAttribute('data-partner'),
'The data-partner attribute is required for <amp-kaltura-player> %s',
this.element);
const uiconfid = this.element.getAttribute('data-uiconf') ||
this.element.getAttribute('data-uiconf-id') ||
'default';
const entryid = this.element.getAttribute('data-entryid') || 'default';
const iframe = this.element.ownerDocument.createElement('iframe');
let src = `https://cdnapisec.kaltura.com/p/${encodeURIComponent(partnerid)}/sp/${encodeURIComponent(partnerid)}00/embedIframeJs/uiconf_id/${encodeURIComponent(uiconfid)}/partner_id/${encodeURIComponent(partnerid)}?iframeembed=true&playerId=kaltura_player_amp&entry_id=${encodeURIComponent(entryid)}`;
const params = getDataParamsFromAttributes(
this.element, key => `flashvars[${key}]`);
src = addParamsToUrl(src, params);
iframe.setAttribute('frameborder', '0');
iframe.setAttribute('allowfullscreen', 'true');
iframe.src = src;
this.applyFillContent(iframe);
iframe.width = width;
iframe.height = height;
this.element.appendChild(iframe);
/** @private {?Element} */
this.iframe_ = iframe;
return loadPromise(iframe);
}
/** @private */
buildImagePlaceholder_() {
const imgPlaceholder = new Image();
setStyles(imgPlaceholder, {
'object-fit': 'cover',
'visibility': 'hidden',
});
const width = this.element.getAttribute('width');
const height = this.element.getAttribute('height');
const partnerid = user.assert(
this.element.getAttribute('data-partner'),
'The data-partner attribute is required for <amp-kaltura-player> %s',
this.element);
const entryid = this.element.getAttribute('data-entryid') || 'default';
let src = `https://cdnapisec.kaltura.com/p/${encodeURIComponent(partnerid)}/thumbnail/entry_id/${encodeURIComponent(entryid)}`;
if (width) {
src += `/width/${width}`;
}
if (height) {
src += `/height/${height}`;
}
imgPlaceholder.src = src;
imgPlaceholder.setAttribute('placeholder', '');
imgPlaceholder.width = this.width_;
imgPlaceholder.height = this.height_;
this.element.appendChild(imgPlaceholder);
this.applyFillContent(imgPlaceholder);
loadPromise(imgPlaceholder).then(() => {
setStyles(imgPlaceholder, {
'visibility': '',
});
});
}
/** @override */
pauseCallback() {
if (this.iframe_ && this.iframe_.contentWindow) {
this.iframe_.contentWindow./*OK*/postMessage(JSON.stringify({
'method': 'pause' ,
'value': '' ,
}) , '*');
}
}
};
AMP.registerElement('amp-kaltura-player', AmpKaltura);
| {
"content_hash": "083c5682e270475852c3d45f730deb61",
"timestamp": "",
"source": "github",
"line_count": 108,
"max_line_length": 304,
"avg_line_length": 32.94444444444444,
"alnum_prop": 0.6481169196177627,
"repo_name": "BenDz/amphtml-atinternet",
"id": "db264b80dce32b86181cd5ffd35fcfcd91b07a08",
"size": "4185",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "extensions/amp-kaltura-player/0.1/amp-kaltura-player.js",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "23020"
},
{
"name": "HTML",
"bytes": "151956"
},
{
"name": "JavaScript",
"bytes": "2050654"
},
{
"name": "Protocol Buffer",
"bytes": "14116"
},
{
"name": "Python",
"bytes": "25322"
}
],
"symlink_target": ""
} |
<?php
namespace Dark\DissectBundle\Builder;
/**
* Storage languages
*
* @todo Add caching feature
* @author Evgeniy Guseletov <d46k16@gmail.com>
*/
class LanguageRepository
{
private $lb;
private $languageHolder;
private $pathHolder;
public function __construct(LanguageBuilder $lb)
{
$this->lb = $lb;
$this->languageHolder = array();
$this->pathHolder = array();
}
/**
* Adds path to languages YAML configs
*/
public function addPath($name, $path)
{
$this->pathHolder[$name] = $path;
}
/**
* Builds language if not built yet.
*/
public function get($name)
{
if (isset($this->languageHolder[$name])) {
return $this->languageHolder[$name];
} else {
if (isset($this->pathHolder[$name])) {
return $this->languageHolder[$name] = $this->lb->build($this->pathHolder[$name]);
} else {
throw new \RuntimeException(sprintf('Language "%s" not found', $name));
}
}
}
}
| {
"content_hash": "e2200c08e424170e6cfd50915525dc8e",
"timestamp": "",
"source": "github",
"line_count": 47,
"max_line_length": 97,
"avg_line_length": 22.97872340425532,
"alnum_prop": 0.5527777777777778,
"repo_name": "cursedcoder/DarkDissectBundle",
"id": "2b5d2823b1b2bff0c5c20b7ce5f2d6ef99764374",
"size": "1080",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Builder/LanguageRepository.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "PHP",
"bytes": "15113"
}
],
"symlink_target": ""
} |
Simple and easy licensing framework for your .NET projects.
Nothing clever, it just keeps honest people honest.
If you need an easy way to license a .NET Windows Forms application,
but don't want to pay the large fees expected from the .NET licensing
companies, LicenseLib.NET might be for you.
Here is a brief explanation:
----------------------------
LicenseLib: Contains the core methods to create and verify a registry key
is installed, verify if the key has expired, and remove a key.
LicenseUtilityLib: Does the actual registry editing.
LicenseApp: Windows Forms application to create and verify a key can be used.
CodeGenLib: License code hashing and salting.
TestLicense: Small Windows Forms application to test method calls.
NUnitTestLicense: NUnit project to Unit Test core license method calls.
How to use LicenseLib.NET
-------------------------
STEP 1: Download all files and create your Visual Studio solution.
Download each project folder. Create a blank Visual Studio solution,
and add each project to this solution. Look in LicenseApp --> files
for an xlsx spreadsheet containing diagrams of the project heirarchy.
STEP 2: Compile. Grab the LicenseLib.dll and LicenseUtilityLib.dll
from the LicenseLib\bin folder. Add references to these in your project.
STEP 3: From there, you will see access to the various methods to create
and verify license key creation.
| {
"content_hash": "eecf826bbf8cd22f17a21527b4cbc6b5",
"timestamp": "",
"source": "github",
"line_count": 39,
"max_line_length": 77,
"avg_line_length": 36.05128205128205,
"alnum_prop": 0.7610241820768137,
"repo_name": "dalehenning/LicenseLib.NET",
"id": "f440a60a9222a49cff1476438a509a3ef5d99396",
"size": "1423",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "README.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "72535"
}
],
"symlink_target": ""
} |
class AddApiIds < ActiveRecord::Migration
def self.up
add_column :surveys, :api_id, :string
add_column :questions, :api_id, :string
add_column :answers, :api_id, :string
end
def self.down
remove_column :surveys, :api_id
remove_column :questions, :api_id
remove_column :answers, :api_id
end
end
| {
"content_hash": "5f64421e5bfdefb6a6dc80f05df6af95",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 43,
"avg_line_length": 25.153846153846153,
"alnum_prop": 0.6758409785932722,
"repo_name": "tcw48/surveyor_FriendCompare",
"id": "e63712bc9addab757d76a9c7a2444ff347d47fad",
"size": "327",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "lib/generators/surveyor/templates/db/migrate/add_api_ids.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "21952"
},
{
"name": "Ruby",
"bytes": "257526"
},
{
"name": "Shell",
"bytes": "882"
}
],
"symlink_target": ""
} |
<?php
namespace Ker\MVCP;
abstract class View
{
protected static $charset;
protected static $cssFile;
protected static $description;
protected static $favicon;
protected static $IeForce9;
protected static $imgPreloader;
protected static $jsCode;
protected static $jsFile;
protected static $jsReadyCode;
protected static $meta;
protected static $minJsCode;
protected static $obState;
protected static $obWanted;
protected static $staticContentPath;
protected static $subtitle;
protected static $title;
protected static $titlePattern;
protected static $xHtml;
protected static $clearWhitespace;
protected static $replaceEndingSpaceWithNbsp;
protected static $removeNewLines;
protected static $bodyHeader;
/**
* @see \Ker\Config::get (view_charset, view_cssFile, view_description, view_favicon, view_IeForce9, view_imgPreloader, view_jsCode, view_jsFile, view_jsReadyCode, view_meta, view_obWanted,
* view_staticContentPath, view_subtitle, view_title, view_titlePattern, view_xHtml, view_clearWhitespace, view_replaceEndingSpaceWithNbsp)
*/
public static function __init($_action = null)
{
static::$charset = \Ker\Config::getOne("view_charset", null);
static::$cssFile = \Ker\Config::getOne("view_cssFile", array());
static::$description = \Ker\Config::getOne("view_description", null);
static::$favicon = \Ker\Config::getOne("view_favicon", null);
static::$IeForce9 = \Ker\Config::getOne("view_IeForce9", null);
static::$imgPreloader = \Ker\Config::getOne("view_imgPreloader", null);
static::$jsCode = \Ker\Config::getOne("view_jsCode", null);
static::$jsFile = \Ker\Config::getOne("view_jsFile", array());
static::$jsReadyCode = \Ker\Config::getOne("view_jsReadyCode", null);
static::$meta = \Ker\Config::getOne("view_meta", array());
static::$obWanted = \Ker\Config::getOne("view_obWanted", false);
static::$staticContentPath = \Ker\Config::getOne("view_staticContentPath", "/static/");
static::$subtitle = \Ker\Config::getOne("view_subtitle", null);
static::$title = \Ker\Config::getOne("view_title", "");
static::$titlePattern = \Ker\Config::getOne("view_titlePattern", null);
static::$xHtml = \Ker\Config::getOne("view_xHtml", null);
static::$clearWhitespace = \Ker\Config::getOne("view_clearWhitespace", null);
static::$replaceEndingSpaceWithNbsp = \Ker\Config::getOne("view_replaceEndingSpaceWithNbsp", null);
static::$removeNewLines = \Ker\Config::getOne("view_removeNewLines", null);
static::$minJsCode = \Ker\Config::getOne("view_minJsCode", null);
static::$bodyHeader = null;
//wymuszenie zawartosci, jesli byl BOOL to mamy STRING, jesli bylo co innego - wymuszamy stringa
static::$xHtml = static::$xHtml ? " /" : "";
}
protected static function addMeta(/* argument list */)
{
if (!func_num_args()) {
throw new \BadMethodCallException();
}
foreach (func_get_args() as $arg) {
static::$meta[] = $arg;
}
}
protected static function getStaticContent($_file)
{
if (in_array(substr($_file, 0, 7), array("http://", "https:/"))) {
return $_file;
}
$path = static::$staticContentPath . $_file;
// uzywamy Config::path gdyz Ker moze byc w innej lokalizacji niz aplikacja!
return $path . "?" . \Ker\Utils\File::getModifyTimestamp(\Ker\Config::getOne("path") . $path);
}
protected static function getTitle()
{
if (static::$titlePattern === NULL or static::$subtitle === NULL or static::$subtitle === "") {
return static::$title;
}
return str_replace(array("%title%", "%subtitle%"), array(static::$title, static::$subtitle), static::$titlePattern);
}
public static function getViewFile($_lang, $_module, $_action)
{
// jesli istnieje plik przewidziany dla danego jezyka
$file = \Ker\Config::getOne("view", "./view") . "/$_module/$_action.$_lang.php";
if (file_exists($file)) {
return $file;
}
// w przeciwnym wypadku zwroc plik ogolny (bez uszczegolowionego jezyka)
// funckja zaklada, ze jesli nie ma pliku dla jezyka to _musi_ byc plik ogolny
return \Ker\Config::getOne("view", "./view") . "/$_module/$_action.php";
}
public static function obStart()
{
if (static::$obWanted) {
static::$obState = \Ker\Utils\Misc::obStart();
}
}
public static function obFlush()
{
\Ker\Utils\Misc::obFlush(static::$obState);
}
public static function obFinish()
{
\Ker\Utils\Misc::obFinish(static::$obState);
}
public static function preprocessHtml($_)
{
if (static::$removeNewLines) {
$_ = \Ker\Utils\Text::removeNewLines($_, array("safeJsInline" => true));
}
if (static::$clearWhitespace) {
// eksperymentalne, na rosyjskim '/\s+/' => ' ' sie wykladal, zamienial niektore litery na krzaki (np 'Русский')
// zmieniono \s na \h - by nie laczyl wersow gdy koniec pierwszego i poczatek drugiego to spacje - jest to niewlasciwe np w textarea, gdzie stracilibysmy przejscie do nowego wersu
$_ = preg_replace('/(\h)\h+/', '\\1', $_);
}
if (static::$replaceEndingSpaceWithNbsp) {
$_ = \Ker\Utils\Text::replaceEndingSpaceWithNbsp($_);
}
return $_;
}
public static function printBody($_headerContent, $_bodyContent)
{
$bodyHeader = (static::$bodyHeader ? \Ker\Res::call("tpl_bodyHeader", static::$bodyHeader) : "");
$messages = \Ker\Res::call("tpl_messages", \Ker\Messages::getAll());
echo static::preprocessHtml(\Ker\Res::call("tpl_body", $_headerContent, $bodyHeader . $messages . $_bodyContent));
}
public static function printHead($_extraContent = "")
{
if (static::$imgPreloader) {
echo "<script src='" . static::getStaticContent(static::$imgPreloader) . "' type='text/javascript'></script>";
static::obFlush();
}
$ret = "<title>" . static::getTitle() . "</title>
<meta http-equiv='content-type' content='text/html; charset=" . static::$charset . "'" . static::$xHtml . ">";
if (static::$IeForce9) {
$ret .= "<meta http-equiv='X-UA-Compatible' content='IE=9'" . static::$xHtml . ">";
}
if (static::$favicon) {
$ret .= "<link rel='shortcut icon' type='image/x-icon' href='" . static::$favicon . "'" . static::$xHtml . ">";
}
if (static::$cssFile) {
foreach (static::$cssFile as & $item) {
$tmp = ( is_array($item) ? "href='" . static::getStaticContent($item[0]) . "' media='{$item[1]}'" : "href='" . static::getStaticContent($item) . "'" );
$ret .= "<link rel='stylesheet' type='text/css' $tmp" . static::$xHtml . ">";
}
}
if (static::$jsFile) {
foreach (static::$jsFile as & $item) {
$ret .= "<script src='" . static::getStaticContent($item) . "' type='text/javascript'></script>";
}
}
if (static::$jsCode or static::$jsReadyCode) {
$jsCode = "";
if (static::$jsCode) {
foreach (static::$jsCode as & $item) {
$jsCode .= $item;
}
}
if (static::$jsReadyCode) {
$jsCode .= "$(document).ready(function () {";
foreach (static::$jsReadyCode as & $item)
$jsCode .= $item;
$jsCode .= "});";
}
if (static::$minJsCode) {
$jsCode = \Ker\External\JSMin::minify($jsCode);
}
$jsCode = "<script type='text/javascript'>
//<![CDATA[
$jsCode
//]]>
</script>";
$ret .= $jsCode;
}
if (static::$meta) {
foreach (static::$meta as & $item) {
$ret .= "<meta name='{$item[0]}' content='{$item[1]}'" . static::$xHtml . ">";
}
}
if (static::$description) {
$ret .= "<meta name='description' content='" . static::$description . "'" . static::$xHtml . ">";
}
$ret .= $_extraContent;
echo static::preprocessHtml("<head>$ret</head>");
static::obFlush();
}
public static function printSite(array $_ = [])
{
$info = (isset($_["info"]) ? $_["info"] : []);
$htmlParams = [];
foreach (["lang", "action", "module", ] as $v) {
if (isset($info[$v])) {
$htmlParams[$v] = $info[$v];
}
}
echo \Ker\Res::call("tpl_doctype");
echo \Ker\Res::call("tpl_html", $htmlParams);
static::printHead((isset($_["head"]) ? $_["head"] : ""));
static::printBody($_["bodyHeader"], $_["body"]);
echo "</html>";
}
}
| {
"content_hash": "f53fabb92add19eeb5e9233a657bf6ee",
"timestamp": "",
"source": "github",
"line_count": 248,
"max_line_length": 193,
"avg_line_length": 36.778225806451616,
"alnum_prop": 0.5626576033329679,
"repo_name": "keradus/Ker",
"id": "3f73ca8e9561bc720f9da16fc85a178e4bdf18be",
"size": "9342",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/Ker/MVCP/View.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "PHP",
"bytes": "199994"
}
],
"symlink_target": ""
} |
var testBase = require('tape');
var mobx = require('..');
var m = mobx;
var observable = mobx.observable;
var computed = mobx.computed;
var voidObserver = function(){};
function test(name, func) {
testBase(name, function(t) {
try {
func(t);
} finally {
mobx._.resetGlobalState();
}
});
}
function buffer() {
var b = [];
var res = function(newValue) {
b.push(newValue);
};
res.toArray = function() {
return b;
};
return res;
}
test('exception1', function(t) {
var a = computed(function() {
throw "hoi";
});
t.throws(() => a(), "hoi");
t.end();
})
test('deny state changes in views', function(t) {
var x = observable(3);
var z = observable(5);
var y = observable(function() {
z(6);
return x() * x();
});
t.throws(() => {
y()
}, 'It is not allowed to change the state during the computation of a reactive view');
t.end();
})
test('allow state changes in autorun', function(t) {
var x = observable(3);
var z = observable(3);
m.autorun(function() {
if (x.get() !== 3)
z.set(x.get());
});
t.equal(x.get(), 3);
t.equal(z.get(), 3);
x.set(5); // autorunneres are allowed to change state
t.equal(x.get(), 5);
t.equal(z.get(), 5);
t.equal(mobx.extras.isComputingDerivation(), false);
t.end();
})
test('deny array change in view', function(t) {
try {
var x = observable(3);
var z = observable([]);
var y = observable(function() {
z.push(3);
return x() * x();
});
t.throws(function() {
t.equal(9, y());
}, 'It is not allowed to change the state during the computation of a reactive derivation');
t.deepEqual(z.slice(), []);
t.equal(mobx.extras.isComputingDerivation(), false);
t.end();
}
catch(e) {
console.log(e.stack);
}
})
test('allow array change in autorun', function(t) {
var x = observable(3);
var z = observable([]);
var y = m.autorun(function() {
if (x.get() > 4)
z.push(x.get());
});
x.set(5);
x.set(6);
t.deepEqual(z.slice(), [5, 6])
x.set(2);
t.deepEqual(z.slice(), [5, 6])
t.equal(mobx.extras.isComputingDerivation(), false);
t.end();
})
test('throw error if modification loop', function(t) {
var x = observable(3);
var dis = m.autorun(function() {
x.set(x.get() + 1); // is allowed to throw, but doesn't as the observables aren't bound yet during first execution
});
t.throws(() => {
x.set(5);
}, "Reaction doesn't converge to a stable state")
t.end();
})
test('cycle1', function(t) {
t.throws(() => {
var p = observable(function() { return p() * 2; }); // thats a cycle!
p.observe(voidObserver, true);
}, "Found cyclic dependency");
t.end();
})
test('cycle2', function(t) {
var a = observable(function() { return b.get() * 2; });
var b = observable(function() { return a.get() * 2; });
t.throws(() => {
b.get()
}, "Found cyclic dependency");
t.end();
})
test('cycle3', function(t) {
var p = observable(function() { return p.get() * 2; });
t.throws(() => {
p.get();
}, "Found cyclic dependency");
t.end();
})
test('cycle3', function(t) {
var z = observable(true);
var a = observable(function() { return z.get() ? 1 : b.get() * 2; });
var b = observable(function() { return a.get() * 2; });
m.observe(b, voidObserver);
t.equal(1, a.get());
t.throws(() => {
z.set(false); // introduces a cycle!
}, "Found cyclic dependency");
t.end();
});
test('issue 86, converging cycles', function(t) {
function findIndex(arr, predicate) {
for (var i = 0, l = arr.length; i < l; i++)
if (predicate(arr[i]) === true)
return i;
return -1;
}
const deleteThisId = mobx.observable(1);
const state = mobx.observable({ someArray: [] });
var calcs = 0;
state.someArray.push({ id: 1, text: 'I am 1' });
state.someArray.push({ id: 2, text: 'I am 2' });
// should delete item 1 in first run, which works fine
mobx.autorun(() => {
calcs++;
const i = findIndex(state.someArray, item => item.id === deleteThisId.get());
state.someArray.remove(state.someArray[i]);
});
t.equal(state.someArray.length, 1); // should be 1, which prints fine
t.equal(calcs, 1);
deleteThisId.set(2); // should delete item 2, but it errors on cycle
t.equal(console.log(state.someArray.length, 0)); // should be 0, which never prints
t.equal(calcs, 3);
t.end();
});
test('slow converging cycle', function(t) {
var x = mobx.observable(1);
var res = -1;
mobx.autorun(() => {
if (x.get() === 100)
res = x.get();
else
x.set(x.get() + 1);
});
// ideally the outcome should be 100 / 100.
// autorun is only an observer of x *after* the first run, hence the initial outcome is not as expected..
// is there a practical use case where such a pattern would be expected?
// maybe we need to immediately register observers on the observable? but that would be slow....
// or detect cycles and re-run the autorun in that case once?
t.equal(x.get(), 2)
t.equal(res, -1);
x.set(7);
t.equal(x.get(), 100)
t.equal(res, 100);
t.end();
});
test('error handling assistence ', function(t) {
var baseError = console.error;
var baseWarn = console.warn;
var errors = []; // logged errors
var warns = []; // logged warns
var values = []; // produced errors
var thrown = []; // list of actually thrown exceptons
console.error = function(msg) {
baseError.apply(console, arguments);
errors.push(msg);
}
console.warn = function(msg) {
baseWarn.apply(console, arguments);
warns.push(msg);
}
var a = observable(3);
var b = computed(function() {
if (a.get() === 42)
throw 'should not be 42';
return a.get() * 2;
});
var c = m.autorun(function() {
values.push(b.get());
});
a.set(2);
try{
a.set(42);
} catch (e) {
thrown.push(e);
}
a.set(7);
// Test recovery
setTimeout(function() {
a.set(4);
try {
a.set(42);
} catch (e) {
thrown.push(e);
}
t.deepEqual(values, [6, 4, 14, 8]);
t.equal(errors.length, 0);
t.equal(warns.length, 2);
t.equal(thrown.length, 2);
console.error = baseError;
console.warn = baseWarn;
t.end();
}, 10);
})
test('236 - cycles', t => {
var Parent = function() {
m.extendObservable(this, {
children: [],
total0: function() {
// Sum "value" of children of kind "0"
return this.children.filter(c => c.kind === 0).map(c => c.value).reduce((a, b) => a+b, 0);
},
total1: function() {
// Sum "value" of children of kind "1"
return this.children.filter(c => c.kind === 1).map(c => c.value).reduce((a, b) => a+b, 0);
}
});
};
var Child = function(parent, kind) {
this.parent = parent;
m.extendObservable(this, {
kind: kind,
value: function() {
if (this.kind === 0) {
return 3;
} else {
// Value of child of kind "1" depends on the total value for all children of kind "0"
return this.parent.total0 * 2;
}
}
});
};
const parent = new Parent();
parent.children.push(new Child(parent, 0));
parent.children.push(new Child(parent, 0));
parent.children.push(new Child(parent, 0));
var msg = [];
var d = m.autorun(() => {
msg.push('total0:', parent.total0, 'total1:', parent.total1);
});
// So far, so good: total0: 9 total1: 0
t.deepEqual(msg, ["total0:", 9, "total1:", 0])
parent.children[0].kind = 1;
t.deepEqual(msg, [
"total0:", 9, "total1:", 0,
"total0:", 6, "total1:", 12
])
t.end();
}) | {
"content_hash": "02211a25c6d48f9bb2eb18957ee8c9d4",
"timestamp": "",
"source": "github",
"line_count": 328,
"max_line_length": 122,
"avg_line_length": 24.58231707317073,
"alnum_prop": 0.5411137293811237,
"repo_name": "tomaash/mobx-input",
"id": "4c2d19c33bf15964c8f20f1549c1c0fce6abce62",
"size": "8063",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "test/errorhandling.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "183027"
},
{
"name": "TypeScript",
"bytes": "25546"
}
],
"symlink_target": ""
} |
// This file was automatically generated by informer-gen
package v1beta2
import (
apps_v1beta2 "k8s.io/api/apps/v1beta2"
v1 "k8s.io/apimachinery/pkg/apis/meta/v1"
runtime "k8s.io/apimachinery/pkg/runtime"
watch "k8s.io/apimachinery/pkg/watch"
internalinterfaces "github.com/hyperhq/client-go/informers/internalinterfaces"
kubernetes "github.com/hyperhq/client-go/kubernetes"
v1beta2 "github.com/hyperhq/client-go/listers/apps/v1beta2"
cache "github.com/hyperhq/client-go/tools/cache"
time "time"
)
// DeploymentInformer provides access to a shared informer and lister for
// Deployments.
type DeploymentInformer interface {
Informer() cache.SharedIndexInformer
Lister() v1beta2.DeploymentLister
}
type deploymentInformer struct {
factory internalinterfaces.SharedInformerFactory
tweakListOptions internalinterfaces.TweakListOptionsFunc
namespace string
}
// NewDeploymentInformer constructs a new informer for Deployment type.
// Always prefer using an informer factory to get a shared informer instead of getting an independent
// one. This reduces memory footprint and number of connections to the server.
func NewDeploymentInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer {
return NewFilteredDeploymentInformer(client, namespace, resyncPeriod, indexers, nil)
}
// NewFilteredDeploymentInformer constructs a new informer for Deployment type.
// Always prefer using an informer factory to get a shared informer instead of getting an independent
// one. This reduces memory footprint and number of connections to the server.
func NewFilteredDeploymentInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer {
return cache.NewSharedIndexInformer(
&cache.ListWatch{
ListFunc: func(options v1.ListOptions) (runtime.Object, error) {
if tweakListOptions != nil {
tweakListOptions(&options)
}
return client.AppsV1beta2().Deployments(namespace).List(options)
},
WatchFunc: func(options v1.ListOptions) (watch.Interface, error) {
if tweakListOptions != nil {
tweakListOptions(&options)
}
return client.AppsV1beta2().Deployments(namespace).Watch(options)
},
},
&apps_v1beta2.Deployment{},
resyncPeriod,
indexers,
)
}
func (f *deploymentInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer {
return NewFilteredDeploymentInformer(client, f.namespace, resyncPeriod, cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, f.tweakListOptions)
}
func (f *deploymentInformer) Informer() cache.SharedIndexInformer {
return f.factory.InformerFor(&apps_v1beta2.Deployment{}, f.defaultInformer)
}
func (f *deploymentInformer) Lister() v1beta2.DeploymentLister {
return v1beta2.NewDeploymentLister(f.Informer().GetIndexer())
}
| {
"content_hash": "dd82f3f6b8e1f0f5ccf518f71dde392c",
"timestamp": "",
"source": "github",
"line_count": 74,
"max_line_length": 220,
"avg_line_length": 40.554054054054056,
"alnum_prop": 0.7950683105631456,
"repo_name": "hyperhq/kubernetes",
"id": "305a0a515039c1ed73b4274e5b8434f3285f42b8",
"size": "3570",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "vendor/github.com/hyperhq/client-go/informers/apps/v1beta2/deployment.go",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
package com.og.util;
import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.provider.Settings;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.util.Log;
/**
* Android 6.0 上权限分为<b>正常</b>和<b>危险</b>级别
* <ul>
* <li>正常级别权限:开发者仅仅需要在AndroidManifext.xml上声明,那么应用就会被允许拥有该权限,如:android.permission.INTERNET</li>
* <li>危险级别权限:开发者需要在AndroidManifext.xml上声明,并且在运行时进行申请,而且用户允许了,应用才会被允许拥有该权限,如:android.permission.WRITE_EXTERNAL_STORAGE</li>
* </ul>
* 有米的以下权限需要在Android6.0上被允许,有米广告sdk才能正常工作,开发者需要在调用有米的任何代码之前,提前让用户允许权限
* <ul>
* <li>必须申请的权限
* <ul>
* <li>android.permission.READ_PHONE_STATE</li>
* <li>android.permission.WRITE_EXTERNAL_STORAGE</li>
* </ul>
* </li>
* <li>可选申请的权限
* <ul>
* <li>android.permission.ACCESS_FINE_LOCATION</li>
* </ul>
* </li>
* </ul>
* <p>Android 6.0 权限申请助手</p>
* Created by Alian on 16-1-12.
*/
public class PermissionHelper {
private static final String TAG = "PermissionHelper";
/**
* 小tips:这里的int数值不能太大,否则不会弹出请求权限提示,测试的时候,改到1000就不会弹出请求了
*/
private final static int READ_PHONE_STATE_CODE = 101;
private final static int WRITE_EXTERNAL_STORAGE_CODE = 102;
private final static int REQUEST_OPEN_APPLICATION_SETTINGS_CODE = 12345;
/**
* 有米 Android SDK 所需要向用户申请的权限列表
*/
private PermissionModel[] mPermissionModels = new PermissionModel[] {
new PermissionModel("电话", Manifest.permission.READ_PHONE_STATE, "我们需要读取手机信息的权限来标识您的身份", READ_PHONE_STATE_CODE),
new PermissionModel("存储空间", Manifest.permission.WRITE_EXTERNAL_STORAGE, "我们需要您允许我们读写你的存储卡,以方便我们临时保存一些数据",
WRITE_EXTERNAL_STORAGE_CODE)
};
private Activity mActivity;
private OnApplyPermissionListener mOnApplyPermissionListener;
public PermissionHelper(Activity activity) {
mActivity = activity;
}
public void setOnApplyPermissionListener(OnApplyPermissionListener onApplyPermissionListener) {
mOnApplyPermissionListener = onApplyPermissionListener;
}
/**
* 这里我们演示如何在Android 6.0+上运行时申请权限
*/
public void applyPermissions() {
try {
for (final PermissionModel model : mPermissionModels) {
if (PackageManager.PERMISSION_GRANTED != ContextCompat.checkSelfPermission(mActivity, model.permission)) {
ActivityCompat.requestPermissions(mActivity, new String[] { model.permission }, model.requestCode);
return;
}
}
if (mOnApplyPermissionListener != null) {
mOnApplyPermissionListener.onAfterApplyAllPermission();
}
} catch (Throwable e) {
Log.e(TAG, "", e);
}
}
/**
* 对应Activity的 {@code onRequestPermissionsResult(...)} 方法
*
* @param requestCode
* @param permissions
* @param grantResults
*/
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
switch (requestCode) {
case READ_PHONE_STATE_CODE:
case WRITE_EXTERNAL_STORAGE_CODE:
// 如果用户不允许,我们视情况发起二次请求或者引导用户到应用页面手动打开
if (PackageManager.PERMISSION_GRANTED != grantResults[0]) {
// 二次请求,表现为:以前请求过这个权限,但是用户拒接了
// 在二次请求的时候,会有一个“不再提示的”checkbox
// 因此这里需要给用户解释一下我们为什么需要这个权限,否则用户可能会永久不在激活这个申请
// 方便用户理解我们为什么需要这个权限
if (ActivityCompat.shouldShowRequestPermissionRationale(mActivity, permissions[0])) {
AlertDialog.Builder builder =
new AlertDialog.Builder(mActivity).setTitle("权限申请").setMessage(findPermissionExplain(permissions[0]))
.setPositiveButton("确定", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
applyPermissions();
}
});
builder.setCancelable(false);
builder.show();
}
// 到这里就表示已经是第3+次请求,而且此时用户已经永久拒绝了,这个时候,我们引导用户到应用权限页面,让用户自己手动打开
else {
AlertDialog.Builder builder = new AlertDialog.Builder(mActivity).setTitle("权限申请")
.setMessage("请在打开的窗口的权限中开启" + findPermissionName(permissions[0]) + "权限,以正常使用本应用")
.setPositiveButton("去设置", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
openApplicationSettings(REQUEST_OPEN_APPLICATION_SETTINGS_CODE);
}
}).setNegativeButton("取消", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
mActivity.finish();
}
});
builder.setCancelable(false);
builder.show();
}
return;
}
// 到这里就表示用户允许了本次请求,我们继续检查是否还有待申请的权限没有申请
if (isAllRequestedPermissionGranted()) {
if (mOnApplyPermissionListener != null) {
mOnApplyPermissionListener.onAfterApplyAllPermission();
}
} else {
applyPermissions();
}
break;
}
}
/**
* 对应Activity的 {@code onActivityResult(...)} 方法
*
* @param requestCode
* @param resultCode
* @param data
*/
public void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case REQUEST_OPEN_APPLICATION_SETTINGS_CODE:
if (isAllRequestedPermissionGranted()) {
if (mOnApplyPermissionListener != null) {
mOnApplyPermissionListener.onAfterApplyAllPermission();
}
} else {
mActivity.finish();
}
break;
}
}
/**
* 判断是否所有的权限都被授权了
*
* @return
*/
public boolean isAllRequestedPermissionGranted() {
for (PermissionModel model : mPermissionModels) {
if (PackageManager.PERMISSION_GRANTED != ContextCompat.checkSelfPermission(mActivity, model.permission)) {
return false;
}
}
return true;
}
/**
* 打开应用设置界面
*
* @param requestCode 请求码
*
* @return
*/
private boolean openApplicationSettings(int requestCode) {
try {
Intent intent =
new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS, Uri.parse("package:" + mActivity.getPackageName()));
intent.addCategory(Intent.CATEGORY_DEFAULT);
// Android L 之后Activity的启动模式发生了一些变化
// 如果用了下面的 Intent.FLAG_ACTIVITY_NEW_TASK ,并且是 startActivityForResult
// 那么会在打开新的activity的时候就会立即回调 onActivityResult
// intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
mActivity.startActivityForResult(intent, requestCode);
return true;
} catch (Throwable e) {
Log.e(TAG, "", e);
}
return false;
}
/**
* 查找申请权限的解释短语
*
* @param permission 权限
*
* @return
*/
private String findPermissionExplain(String permission) {
if (mPermissionModels != null) {
for (PermissionModel model : mPermissionModels) {
if (model != null && model.permission != null && model.permission.equals(permission)) {
return model.explain;
}
}
}
return null;
}
/**
* 查找申请权限的名称
*
* @param permission 权限
*
* @return
*/
private String findPermissionName(String permission) {
if (mPermissionModels != null) {
for (PermissionModel model : mPermissionModels) {
if (model != null && model.permission != null && model.permission.equals(permission)) {
return model.name;
}
}
}
return null;
}
private static class PermissionModel {
/**
* 权限名称
*/
public String name;
/**
* 请求的权限
*/
public String permission;
/**
* 解析为什么请求这个权限
*/
public String explain;
/**
* 请求代码
*/
public int requestCode;
public PermissionModel(String name, String permission, String explain, int requestCode) {
this.name = name;
this.permission = permission;
this.explain = explain;
this.requestCode = requestCode;
}
}
/**
* 权限申请事件监听
*/
public interface OnApplyPermissionListener {
/**
* 申请所有权限之后的逻辑
*/
void onAfterApplyAllPermission();
}
}
| {
"content_hash": "d04d15ee456c5e879fba8b32ce6bde87",
"timestamp": "",
"source": "github",
"line_count": 293,
"max_line_length": 123,
"avg_line_length": 26.017064846416382,
"alnum_prop": 0.6993309720582448,
"repo_name": "blitzfeng/IceMFi",
"id": "1fe230ff9e4a028b87593e0613cef6059853ba91",
"size": "9049",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "FileManager/src/com/og/util/PermissionHelper.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "576346"
}
],
"symlink_target": ""
} |
/**
* Automatically generated file. Please do not edit.
* @author Highcharts Config Generator by Karasiq
* @see [[http://api.highcharts.com/highmaps]]
*/
package com.highmaps.config
import scalajs.js, js.`|`
import com.highcharts.CleanJsObject
import com.highcharts.HighchartsUtils._
/**
* @note JavaScript name: <code>series<flags>-pathfinder-endMarker</code>
*/
@js.annotation.ScalaJSDefined
class SeriesFlagsPathfinderEndMarker extends com.highcharts.HighchartsGenericObject {
/**
* <p>Set the symbol of the pathfinder end markers.</p>
* @since 6.2.0
*/
val symbol: js.UndefOr[String] = js.undefined
/**
* <p>Enable markers for the connectors.</p>
* @since 6.2.0
*/
val enabled: js.UndefOr[Boolean] = js.undefined
/**
* <p>Horizontal alignment of the markers relative to the points.</p>
* @since 6.2.0
*/
val align: js.UndefOr[String] = js.undefined
/**
* <p>Vertical alignment of the markers relative to the points.</p>
* @since 6.2.0
*/
val verticalAlign: js.UndefOr[String] = js.undefined
/**
* <p>Whether or not to draw the markers inside the points.</p>
* @since 6.2.0
*/
val inside: js.UndefOr[Boolean] = js.undefined
/**
* <p>Set the line/border width of the pathfinder markers.</p>
* @since 6.2.0
*/
val lineWidth: js.UndefOr[Double] = js.undefined
/**
* <p>Set the radius of the pathfinder markers. The default is
* automatically computed based on the algorithmMargin setting.</p>
* <p>Setting marker.width and marker.height will override this
* setting.</p>
* @since 6.2.0
*/
val radius: js.UndefOr[Double] = js.undefined
/**
* <p>Set the width of the pathfinder markers. If not supplied, this
* is inferred from the marker radius.</p>
* @since 6.2.0
*/
val width: js.UndefOr[Double] = js.undefined
/**
* <p>Set the height of the pathfinder markers. If not supplied, this
* is inferred from the marker radius.</p>
* @since 6.2.0
*/
val height: js.UndefOr[Double] = js.undefined
/**
* <p>Set the color of the pathfinder markers. By default this is the
* same as the connector color.</p>
* @since 6.2.0
*/
val color: js.UndefOr[String | js.Object] = js.undefined
/**
* <p>Set the line/border color of the pathfinder markers. By default
* this is the same as the marker color.</p>
* @since 6.2.0
*/
val lineColor: js.UndefOr[String | js.Object] = js.undefined
}
object SeriesFlagsPathfinderEndMarker {
/**
* @param symbol <p>Set the symbol of the pathfinder end markers.</p>
* @param enabled <p>Enable markers for the connectors.</p>
* @param align <p>Horizontal alignment of the markers relative to the points.</p>
* @param verticalAlign <p>Vertical alignment of the markers relative to the points.</p>
* @param inside <p>Whether or not to draw the markers inside the points.</p>
* @param lineWidth <p>Set the line/border width of the pathfinder markers.</p>
* @param radius <p>Set the radius of the pathfinder markers. The default is. automatically computed based on the algorithmMargin setting.</p>. <p>Setting marker.width and marker.height will override this. setting.</p>
* @param width <p>Set the width of the pathfinder markers. If not supplied, this. is inferred from the marker radius.</p>
* @param height <p>Set the height of the pathfinder markers. If not supplied, this. is inferred from the marker radius.</p>
* @param color <p>Set the color of the pathfinder markers. By default this is the. same as the connector color.</p>
* @param lineColor <p>Set the line/border color of the pathfinder markers. By default. this is the same as the marker color.</p>
*/
def apply(symbol: js.UndefOr[String] = js.undefined, enabled: js.UndefOr[Boolean] = js.undefined, align: js.UndefOr[String] = js.undefined, verticalAlign: js.UndefOr[String] = js.undefined, inside: js.UndefOr[Boolean] = js.undefined, lineWidth: js.UndefOr[Double] = js.undefined, radius: js.UndefOr[Double] = js.undefined, width: js.UndefOr[Double] = js.undefined, height: js.UndefOr[Double] = js.undefined, color: js.UndefOr[String | js.Object] = js.undefined, lineColor: js.UndefOr[String | js.Object] = js.undefined): SeriesFlagsPathfinderEndMarker = {
val symbolOuter: js.UndefOr[String] = symbol
val enabledOuter: js.UndefOr[Boolean] = enabled
val alignOuter: js.UndefOr[String] = align
val verticalAlignOuter: js.UndefOr[String] = verticalAlign
val insideOuter: js.UndefOr[Boolean] = inside
val lineWidthOuter: js.UndefOr[Double] = lineWidth
val radiusOuter: js.UndefOr[Double] = radius
val widthOuter: js.UndefOr[Double] = width
val heightOuter: js.UndefOr[Double] = height
val colorOuter: js.UndefOr[String | js.Object] = color
val lineColorOuter: js.UndefOr[String | js.Object] = lineColor
com.highcharts.HighchartsGenericObject.toCleanObject(new SeriesFlagsPathfinderEndMarker {
override val symbol: js.UndefOr[String] = symbolOuter
override val enabled: js.UndefOr[Boolean] = enabledOuter
override val align: js.UndefOr[String] = alignOuter
override val verticalAlign: js.UndefOr[String] = verticalAlignOuter
override val inside: js.UndefOr[Boolean] = insideOuter
override val lineWidth: js.UndefOr[Double] = lineWidthOuter
override val radius: js.UndefOr[Double] = radiusOuter
override val width: js.UndefOr[Double] = widthOuter
override val height: js.UndefOr[Double] = heightOuter
override val color: js.UndefOr[String | js.Object] = colorOuter
override val lineColor: js.UndefOr[String | js.Object] = lineColorOuter
})
}
}
| {
"content_hash": "d9ad5f9aa0158ef55be96c34f464204b",
"timestamp": "",
"source": "github",
"line_count": 132,
"max_line_length": 557,
"avg_line_length": 43.39393939393939,
"alnum_prop": 0.6944832402234636,
"repo_name": "Karasiq/scalajs-highcharts",
"id": "47b55764f203c4d77efecc898836712911a3a685",
"size": "5728",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/main/scala/com/highmaps/config/SeriesFlagsPathfinderEndMarker.scala",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Scala",
"bytes": "131509301"
}
],
"symlink_target": ""
} |
import spur
__all__ = ["run", "RunProcessError"]
local_shell = spur.LocalShell()
run = local_shell.run
RunProcessError = spur.RunProcessError
| {
"content_hash": "df6a01410590071b99fda18ec875e001",
"timestamp": "",
"source": "github",
"line_count": 11,
"max_line_length": 38,
"avg_line_length": 13.454545454545455,
"alnum_prop": 0.7094594594594594,
"repo_name": "mwilliamson/whack",
"id": "98205c3aff7ca04b804436fbde5222f9023b8101",
"size": "148",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "whack/local.py",
"mode": "33188",
"license": "bsd-2-clause",
"language": [
{
"name": "Makefile",
"bytes": "530"
},
{
"name": "Python",
"bytes": "106682"
}
],
"symlink_target": ""
} |
FROM node:onbuild
# make sure apt is up to date
RUN apt-get update
# add source files
ADD . /srv
# set the working directory to run commands from
WORKDIR /srv
CMD ["ls"]
RUN rm -rf ./node_modules
# install express
RUN npm install -g express
# install the dependencies
RUN npm install
# expose the port so host can have access
EXPOSE 3000
# run this after the container has been instantiated
CMD ["npm", "start"] | {
"content_hash": "4d0583fa2b983b697679520d2201a9ad",
"timestamp": "",
"source": "github",
"line_count": 24,
"max_line_length": 52,
"avg_line_length": 17.416666666666668,
"alnum_prop": 0.7392344497607656,
"repo_name": "BaobabCoder/nle",
"id": "b1b781fd8907347565502bccbc7cc19c1cbd8713",
"size": "418",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "Dockerfile",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "9023"
},
{
"name": "HTML",
"bytes": "4921"
},
{
"name": "JavaScript",
"bytes": "18671"
}
],
"symlink_target": ""
} |
require "compass/app_integration/stand_alone"
module Compass
module AppIntegration
module Helpers
#attr_accessor :project_types
DEAFULT_PROJECT_TYPES = {
:stand_alone => "Compass::AppIntegration::StandAlone"
}
def init
@project_types ||= DEAFULT_PROJECT_TYPES.dup
end
def project_types
@project_types
end
def default?
@project_types.keys === DEAFULT_PROJECT_TYPES.keys
end
def lookup(type)
unless @project_types[type].nil?
eval @project_types[type]
else
raise Compass::Error, "No application integration exists for #{type}"
end
end
def register(type, klass)
@project_types[type] = klass
end
end
extend Helpers
init
end
end
| {
"content_hash": "c352b9dd382e6d0cb21c9a3a74b38c28",
"timestamp": "",
"source": "github",
"line_count": 39,
"max_line_length": 79,
"avg_line_length": 20.82051282051282,
"alnum_prop": 0.5985221674876847,
"repo_name": "natewscott/rb-co",
"id": "2439984d904887f02d5dbcd87c0d36501372718a",
"size": "812",
"binary": false,
"copies": "41",
"ref": "refs/heads/master",
"path": "lib/ruby/2.0.0/gems/compass-1.0.1/lib/compass/app_integration.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Assembly",
"bytes": "455326"
},
{
"name": "C",
"bytes": "1460970"
},
{
"name": "C++",
"bytes": "9149"
},
{
"name": "CSS",
"bytes": "586376"
},
{
"name": "Gherkin",
"bytes": "9648"
},
{
"name": "HTML",
"bytes": "194476"
},
{
"name": "JavaScript",
"bytes": "3786"
},
{
"name": "M4",
"bytes": "67848"
},
{
"name": "Makefile",
"bytes": "154392"
},
{
"name": "Objective-C",
"bytes": "2911"
},
{
"name": "Perl",
"bytes": "72"
},
{
"name": "Roff",
"bytes": "4034"
},
{
"name": "Ruby",
"bytes": "3028854"
},
{
"name": "Shell",
"bytes": "346996"
},
{
"name": "TeX",
"bytes": "230259"
}
],
"symlink_target": ""
} |
@interface IDEWelcomeWindowHighlightButtonCell : NSButtonCell
{
}
- (struct CGRect)imageRectForBounds:(struct CGRect)arg1;
- (void)drawBezelWithFrame:(struct CGRect)arg1 inView:(id)arg2;
- (void)drawImage:(id)arg1 withFrame:(struct CGRect)arg2 inView:(id)arg3;
- (void)drawWithFrame:(struct CGRect)arg1 inView:(id)arg2;
@end
| {
"content_hash": "28ab2342628a1e2077ab12c73d659348",
"timestamp": "",
"source": "github",
"line_count": 11,
"max_line_length": 73,
"avg_line_length": 29.818181818181817,
"alnum_prop": 0.7804878048780488,
"repo_name": "wczekalski/Distraction-Free-Xcode-plugin",
"id": "374197c2ed1b976abd1df96e72f1bc7e52d9691d",
"size": "493",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Archived/v1/WCDistractionFreeXcodePlugin/Headers/Frameworks/IDEKit/IDEWelcomeWindowHighlightButtonCell.h",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "81011"
},
{
"name": "C++",
"bytes": "588495"
},
{
"name": "DTrace",
"bytes": "1835"
},
{
"name": "Objective-C",
"bytes": "10151940"
},
{
"name": "Ruby",
"bytes": "1105"
}
],
"symlink_target": ""
} |
var MapManager = (function() {
var map;
var cedGeoJson;
var pollingPlaces;
var markerGroup;
// ui elements
var toggleCedGeoJson;
var infoTable;
var infoTableBody;
var votesTable;
var votesTableBody;
// public methods
// init
var init = function() {
bindUIActions();
createMap();
};
var getMap = function() {
return map;
}
// private methods
var bindUIActions = function() {
toggleCedGeoJson = $('#checkDisplayCED');
toggleCedGeoJson.on('change', showHideCedGeoJson);
infoTable = $('#placeTable');
infoTableBody = $('#placeTableBody');
votesTable = $('#voteResultsTable');
votesTableBody = $('#voteResultsTableBody');
};
// event handler for togging cedGeoJson layer
var showHideCedGeoJson = function() {
if (toggleCedGeoJson.is(":checked")) {
map.addLayer(cedGeoJson);
} else {
map.removeLayer(cedGeoJson);
}
};
// create map and features
var createMap = function() {
// instantiate leaflet map
map = L.map('map', {
// surry hills = [-33.8899, 151.2151], zoom = 13
// au national = [-27.371767300523032, 133.94531250000003], zoom = 4
center: [-27.371767300523032, 133.94531250000003],
minZoom: 2,
zoom: 4
});
// add tiles to map
L.tileLayer('http://{s}.tiles.wmflabs.org/bw-mapnik/{z}/{x}/{y}.png', {
maxZoom: 18,
attribution: '© <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
}).addTo(map);
// add geo search plugin to map
new L.Control.GeoSearch({
provider: new L.GeoSearch.Provider.OpenStreetMap()
}).addTo(map);
// add geo location button to map
lc = L.control.locate().addTo(map);
// add CED geojson layer
$.getJSON("./geodata/ABS_CED_2016.geo.json",
function(json) {
cedGeoJson = L.geoJson(json, {
style: function (feature) {
return {
color: '#0000ff',
fillColor: '#0000aa',
weight: 1,
opacity: 0.7,
fillOpacity: 0.05
};
},
onEachFeature: function (feature, layer) {
layer.bindPopup('CED: ' + feature.properties.Elect_div);
}
}).addTo(map);
}
);
// add polling place markers in a marker group to map
markerGroup = L.markerClusterGroup();
$.ajax({
url: './api/v1/pollingplaces',
type: 'get',
success: function(json) {
pollingPlaces = json.data;
for (var i=0; i<json.data.length; i++) {
var place = json.data[i];
if (place.lat == null) {
console.log(place);
} else {
var placeId = place.polling_place_id;
var placeName = place.polling_place_name;
var markerTitle = JSON.stringify({id: placeId, name: placeName});
var marker = L.marker([place.lat, place.long], {title: markerTitle});
marker.bindPopup('Polling place: ' + placeName);
marker.on('click', function(e) {
var markerData = JSON.parse(this.options.title);
var id = markerData.id;
renderPollingPlaceData(id);
});
markerGroup.addLayer(marker);
}
}
}
});
map.addLayer(markerGroup);
};
// get data on marker click
var renderPollingPlaceData = function(id) {
var pp = pollingPlaces.filter(function(k) {return k.polling_place_id == id;});
renderPollingPlaceInfoTable(pp[0]);
$.ajax({
url: './api/v1/votes2016/' + id,
type: 'get',
success: function(json) {
renderVotingDataTable(json.data);
}
});
};
// table builder functions
var renderPollingPlaceInfoTable = function(info) {
// get correct address html
var addressHtml = '';
var addressItems = [info.address1, info.address2, info.address3, info.locality, info.postcode];
addressHtml = addressItems.filter(function(k) {return k !== null;}).join('<br>');
// place info array
var latLong = info.lat + ' ' + info.long
var placeInfo = [info.polling_place_id, info.polling_place_name, info.division_name, addressHtml, latLong];
// render table
$.each(placeInfo, function(index, item) {
infoTableBody.children().eq(index).children().eq(1).html(placeInfo[index]);
});
};
var renderVotingDataTable = function(info) {
var html, rgb;
// clear existing rows
votesTableBody.empty();
// add rows from data
$.each(info, function(index, item) {
html = '<tr>';
html += '<td>' + item.candidate_name + '</td>';
html += '<td>' + item.party_name + '</td>';
html += '<td>' + item.party_group_code + '</td>';
if (item.party_group_rgb == null) {
rgb = '#ffffff';
} else {
rgb = item.party_group_rgb;
}
html += '<td><span class="glyphicon glyphicon-stop" style="color:' + rgb + '"></span></td>';
if (item.elected == 1) {
html += '<td><span class="glyphicon glyphicon-ok"></span></td>';
} else {
html += '<td></td>';
}
html += '<td>' + item.votes + '</td>';
html += '<td>' + item.swing + '</td>';
html += '<td>' + (item.two_pp_votes == null ? '' : item.two_pp_votes) + '</td>';
html += '<td>' + item.ced_votes + '</td>';
html += '<td>' + (item.ced_two_pp_votes == null ? '' : item.ced_two_pp_votes) + '</td>';
html += '<td>' + (item.pp_ced_ratio * 100).toFixed(3)+'%' + '</td>';
html += '</tr>';
votesTableBody.append(html);
});
};
// return public methods from module
return {
init: init,
map: getMap
};
})();
| {
"content_hash": "9305110ff63a5399d523c0212436a998",
"timestamp": "",
"source": "github",
"line_count": 194,
"max_line_length": 114,
"avg_line_length": 29.762886597938145,
"alnum_prop": 0.5547280914444059,
"repo_name": "robinmackenzie/polling-au",
"id": "c07f9d6e57f800b18f34d0a899acc3d166b84843",
"size": "5774",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "assets/js/MapManager.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ApacheConf",
"bytes": "114"
},
{
"name": "HTML",
"bytes": "3269"
},
{
"name": "JavaScript",
"bytes": "5542"
},
{
"name": "PHP",
"bytes": "6218"
}
],
"symlink_target": ""
} |
@component('sts-consumer')
class StsConsumer extends polymer.Base {
}
StsConsumer.register();
| {
"content_hash": "cfedbda9962fb06210d4349537985210",
"timestamp": "",
"source": "github",
"line_count": 5,
"max_line_length": 40,
"avg_line_length": 19,
"alnum_prop": 0.7684210526315789,
"repo_name": "fluffynuts/polymer-ts-scratch",
"id": "c0ba898b83f5b9dc8c59bcb821dfcd83ed157c95",
"size": "95",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/app/sts-consumer/element.ts",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "HTML",
"bytes": "3282"
},
{
"name": "JavaScript",
"bytes": "19184"
},
{
"name": "TypeScript",
"bytes": "20327"
}
],
"symlink_target": ""
} |
package org.jbpm.workbench.ks.utils;
import java.util.Arrays;
import org.jbpm.workbench.ks.security.KeyCloakTokenCredentialsProvider;
import org.kie.server.api.KieServerConstants;
import org.kie.server.api.marshalling.MarshallingFormat;
import org.kie.server.client.CredentialsProvider;
import org.kie.server.client.KieServicesClient;
import org.kie.server.client.KieServicesConfiguration;
import org.kie.server.client.KieServicesFactory;
import org.kie.server.client.balancer.LoadBalancer;
import org.kie.server.client.credentials.EnteredCredentialsProvider;
import org.kie.server.client.credentials.EnteredTokenCredentialsProvider;
import org.kie.server.client.credentials.SubjectCredentialsProvider;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Strings.isNullOrEmpty;
public class KieServerUtils {
private static final Logger LOGGER = LoggerFactory.getLogger(KieServerUtils.class);
public static KieServicesClient createKieServicesClient(final String... capabilities) {
final String kieServerEndpoint = System.getProperty(KieServerConstants.KIE_SERVER_LOCATION);
checkNotNull(kieServerEndpoint, "Missing Kie Server system property " + KieServerConstants.KIE_SERVER_LOCATION);
final String userName = System.getProperty(KieServerConstants.CFG_KIE_USER);
final String password = System.getProperty(KieServerConstants.CFG_KIE_PASSWORD);
if (isNullOrEmpty(userName)) {
return createKieServicesClient(kieServerEndpoint, null, getCredentialsProvider(), capabilities);
} else {
return createKieServicesClient(kieServerEndpoint, null, userName, password, capabilities);
}
}
public static KieServicesClient createAdminKieServicesClient(final String... capabilities) {
final String kieServerEndpoint = System.getProperty(KieServerConstants.KIE_SERVER_LOCATION);
checkNotNull(kieServerEndpoint, "Missing Kie Server system property " + KieServerConstants.KIE_SERVER_LOCATION);
return createKieServicesClient(kieServerEndpoint, null, getAdminCredentialsProvider(), capabilities);
}
public static KieServicesClient createKieServicesClient(final String endpoint, final ClassLoader classLoader, final String login, final String password, final String... capabilities) {
final KieServicesConfiguration configuration = KieServicesFactory.newRestConfiguration(endpoint, login, password);
return createKieServicesClient(endpoint, classLoader, configuration, capabilities);
}
public static KieServicesClient createKieServicesClient(final String endpoint, final ClassLoader classLoader, final CredentialsProvider credentialsProvider, final String... capabilities) {
final KieServicesConfiguration configuration = KieServicesFactory.newRestConfiguration(endpoint, credentialsProvider);
return createKieServicesClient(endpoint, classLoader, configuration, capabilities);
}
public static KieServicesClient createKieServicesClient(final String endpoint, final ClassLoader classLoader, final KieServicesConfiguration configuration, final String... capabilities) {
LOGGER.debug("Creating client that will use following endpoint {}", endpoint);
configuration.setTimeout(60000);
configuration.setCapabilities(Arrays.asList(capabilities));
configuration.setMarshallingFormat(MarshallingFormat.XSTREAM);
configuration.setLoadBalancer(LoadBalancer.getDefault(endpoint));
KieServicesClient kieServicesClient;
if (classLoader == null) {
kieServicesClient = KieServicesFactory.newKieServicesClient(configuration);
} else {
kieServicesClient = KieServicesFactory.newKieServicesClient(configuration, classLoader);
}
LOGGER.debug("KieServerClient created successfully for endpoint {}", endpoint);
return kieServicesClient;
}
public static CredentialsProvider getCredentialsProvider() {
CredentialsProvider credentialsProvider;
try {
credentialsProvider = new KeyCloakTokenCredentialsProvider();
} catch (UnsupportedOperationException e) {
credentialsProvider = new SubjectCredentialsProvider();
}
LOGGER.debug("{} initialized for the client.", credentialsProvider.getClass().getName());
return credentialsProvider;
}
public static CredentialsProvider getAdminCredentialsProvider() {
if (System.getProperty(KieServerConstants.CFG_KIE_TOKEN) != null) {
return new EnteredTokenCredentialsProvider(System.getProperty(KieServerConstants.CFG_KIE_TOKEN));
} else {
return new EnteredCredentialsProvider(System.getProperty(KieServerConstants.CFG_KIE_USER, "kieserver"), System.getProperty(KieServerConstants.CFG_KIE_PASSWORD, "kieserver1!"));
}
}
}
| {
"content_hash": "abc92b863abb4cc736ec84f5f5a46c33",
"timestamp": "",
"source": "github",
"line_count": 94,
"max_line_length": 192,
"avg_line_length": 52.819148936170215,
"alnum_prop": 0.770392749244713,
"repo_name": "pefernan/jbpm-console-ng",
"id": "050cd319fe24fdaea57717ea1391de1124c782a2",
"size": "5586",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "jbpm-wb-kie-server/jbpm-wb-kie-server-api/src/main/java/org/jbpm/workbench/ks/utils/KieServerUtils.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "28454"
},
{
"name": "FreeMarker",
"bytes": "2262"
},
{
"name": "HTML",
"bytes": "61877"
},
{
"name": "Java",
"bytes": "2298838"
},
{
"name": "Visual Basic",
"bytes": "18019"
}
],
"symlink_target": ""
} |
"""Initialize and launch the onramp REST server."""
import logging
import os
import signal
import socket
import sys
import cherrypy
from cherrypy.process.plugins import Daemonizer, PIDFile
from configobj import ConfigObj
from validate import Validator
from PCE.dispatchers import APIMap, ClusterInfo, ClusterPing, Files, Jobs, \
Modules
from PCEHelper import pce_root
def _CORS():
"""Set HTTP Access Control Header to allow cross-site HTTP requests from
any origin.
"""
cherrypy.response.headers['Access-Control-Allow-Origin'] = '*'
def _term_handler(signal, frame):
"""Gracefully shutdown the server and exit.
This function is intended to be registered as a SIGTERM handler.
"""
logger = logging.getLogger('onramp')
logger.info('Shutting down server')
cherrypy.engine.exit()
logger.info('Exiting')
sys.exit(0)
def _restart_handler(signal, frame):
"""Restart the server.
This function is intended to be registered as a SIGHUP handler.
"""
logger = logging.getLogger('onramp')
logger.info('Restarting server')
# FIXME: This needs to reload the config, including attrs in
# onramp_pce_config.cfg.
cherrypy.engine.restart()
logger.debug('Blocking cherrypy engine')
cherrypy.engine.block()
if __name__ == '__main__':
# Default conf. Some of these can/will be overrided by attrs in
# onramp_pce_config.cfg.
conf = {
'global': {
'server.socket_host': socket.gethostbyname(socket.gethostname()),
'log.access_file': 'log/access.log',
'log.error_file': 'log/cherrypy_error.log',
'log.screen': False,
# Don't run CherryPy Checker on custom conf sections:
# FIXME: This setting doesn't seem to be working...
'checker.check_internal_config': False,
},
'/': {
'request.dispatch': cherrypy.dispatch.MethodDispatcher(),
'tools.CORS.on': True
},
'internal': {
'PIDfile': os.path.join(os.getcwd(), 'src/.onrampRESTservice.pid'),
'log_level': 'INFO',
'onramp_log_file': 'log/onramp.log'
}
}
# Load onramp_pce_config.cfg and integrate appropriate attrs into cherrpy
# conf.
cfg = ConfigObj(os.path.join(pce_root, 'bin', 'onramp_pce_config.cfg'),
configspec=os.path.join(pce_root, 'src', 'configspecs',
'onramp_pce_config.cfgspec'))
cfg.validate(Validator())
if 'server' in cfg.keys():
for k in cfg['server']:
conf['global']['server.' + k] = cfg['server'][k]
if 'cluster' in cfg.keys():
if 'log_level' in cfg['cluster'].keys():
conf['internal']['log_level'] = cfg['cluster']['log_level']
if 'log_file' in cfg['cluster'].keys():
log_file = cfg['cluster']['log_file']
if not log_file.startswith('/'):
# Path is relative to onramp_pce_config.cfg location
log_file = cfg['cluster']['log_file']
conf['internal']['onramp_log_file'] = log_file
cherrypy.config.update(conf)
# Set up logging.
log_levels = {
'DEBUG': logging.DEBUG,
'INFO': logging.INFO,
'WARNING': logging.WARNING,
'ERROR': logging.ERROR,
'CRITICAL': logging.CRITICAL
}
log_name = 'onramp'
logger = logging.getLogger(log_name)
logger.setLevel(log_levels[conf['internal']['log_level']])
handler = logging.FileHandler(conf['internal']['onramp_log_file'])
handler.setFormatter(
logging.Formatter('[%(asctime)s] %(levelname)s %(message)s'))
logger.addHandler(handler)
logger.info('Logging at %s to %s' % (conf['internal']['log_level'],
conf['internal']['onramp_log_file']))
# Log the PID
PIDFile(cherrypy.engine, conf['internal']['PIDfile']).subscribe()
Daemonizer(cherrypy.engine).subscribe()
cherrypy.tools.CORS = cherrypy.Tool('before_finalize', _CORS)
cherrypy.tree.mount(Modules(cfg, log_name), '/modules', conf)
cherrypy.tree.mount(Jobs(cfg, log_name), '/jobs', conf)
cherrypy.tree.mount(ClusterInfo(cfg, log_name), '/cluster/info', conf)
cherrypy.tree.mount(ClusterPing(cfg, log_name), '/cluster/ping', conf)
cherrypy.tree.mount(Files(cfg, log_name), '/files', conf)
cherrypy.tree.mount(APIMap(cfg, log_name), '/api', conf)
logger.info('Starting cherrypy engine')
cherrypy.engine.start()
logger.debug('Registering signal handlers')
signal.signal(signal.SIGTERM, _term_handler)
signal.signal(signal.SIGHUP, _restart_handler)
logger.debug('Blocking cherrypy engine')
cherrypy.engine.block()
| {
"content_hash": "3d2c4c2f09c7c28741cf59ed5485745c",
"timestamp": "",
"source": "github",
"line_count": 134,
"max_line_length": 79,
"avg_line_length": 35.66417910447761,
"alnum_prop": 0.6179116970077422,
"repo_name": "koepked/onramp",
"id": "b38d36dc17cf71900d09b272d29a14604fdc008b",
"size": "4805",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "pce/src/RESTservice.py",
"mode": "33261",
"license": "bsd-3-clause",
"language": [
{
"name": "C",
"bytes": "1436045"
},
{
"name": "Gnuplot",
"bytes": "701"
},
{
"name": "Groff",
"bytes": "253441"
},
{
"name": "HTML",
"bytes": "584449"
},
{
"name": "JavaScript",
"bytes": "144082"
},
{
"name": "Makefile",
"bytes": "88349"
},
{
"name": "Perl",
"bytes": "5501"
},
{
"name": "Python",
"bytes": "406605"
},
{
"name": "Shell",
"bytes": "8072"
},
{
"name": "SourcePawn",
"bytes": "120276"
},
{
"name": "TeX",
"bytes": "82592"
}
],
"symlink_target": ""
} |
package com.jcommerce.core.util;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.logging.Logger;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.BeanUtilsBean;
import org.apache.commons.beanutils.PropertyUtils;
import org.apache.commons.lang.StringUtils;
import com.jcommerce.core.model.ModelObject;
public class MyPropertyUtil {
private static final Logger log = Logger.getLogger(MyPropertyUtil.class.getName());
// by default only copy simple fields and associated Object's Id, unless requested with wantedFields
public static Map<String, Object> to2Form(ModelObject obj, List<String> wantedFields) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {
Map<String, Object> props = new HashMap<String, Object>();
try {
if(wantedFields==null) {
Map<String, Object> res = new HashMap<String, Object>();
PropertyDescriptor srcDescriptors[] = BeanUtilsBean.getInstance().getPropertyUtils()
.getPropertyDescriptors(obj);
for(PropertyDescriptor pd:srcDescriptors) {
String name = pd.getName();
if ("class".equals(name)) {
continue;
}
Class type = pd.getPropertyType();
// debug("to2Form-- name="+name+", type="+type+", value="+PropertyUtils.getProperty(obj, name));
if(ModelObject.class.isAssignableFrom(type)) {
// continue;
// return associated object's id
// OpenPersistenceManagerInViewFilter and lazy-loading works here
ModelObject assoc = (ModelObject)PropertyUtils.getProperty(obj, name);
if(assoc!=null) {
res.put(name, assoc.getModelId());
}
}
else if(Set.class.isAssignableFrom(type)) {
Field field = obj.getClass().getDeclaredField(name);
if(MyPropertyUtil.isFieldCollectionOfModel(field)) {
// ingore collection of Model
} else {
// TODO leon convert from org.datanucleus.sco.backed.HashSet to a normal HashSet
// just to make it work, need refine
Set t = (Set)PropertyUtils.getProperty(obj, name);
Set t2 = new HashSet();
if(t!=null) {
t2.addAll(t);
}
res.put(name, t2);
}
}
else if(PropertyUtils.isReadable(obj, name)) {
res.put(name, PropertyUtils.getProperty(obj, name));
}
}
return res;
}
else {
// not tested yet
for(String wantedField : wantedFields) {
String[] chainedNames = StringUtils.split(wantedField, "_");
int i=1, noOfNames = chainedNames.length;
ModelObject curObj = obj;
for(String name: chainedNames) {
Object value = PropertyUtils.getProperty(curObj, name);
if(i == noOfNames) {
if(value instanceof ModelObject || value instanceof Collection) {
throw new RuntimeException("reached the end of chainedNames but found no simple value");
}
if(value!=null) {
props.put(wantedField, value);
break;
}
}
else {
if(value instanceof ModelObject) {
curObj = (ModelObject)value;
}
else {
throw new RuntimeException("not reached the end of chainedNames but found a simple value");
}
}
i++;
}
}
}
return props;
} catch (Exception ex) {
throw new RuntimeException(ex);
}
}
public static boolean isFieldCollectionOfModel(Field field) {
boolean res = true;
try {
String type = field.getGenericType().toString();
String paraType = type.substring(type.indexOf('<')+1, type.indexOf('>'));
debug("paraType="+paraType);
if(ModelObject.class.isAssignableFrom(Class.forName(paraType))) {
res = true;
} else {
res = false;
}
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return res;
}
// to be used in DAOImpl.update only
public static void copySimpleProperties(ModelObject dest, ModelObject orig) {
try {
PropertyDescriptor srcDescriptors[] = BeanUtilsBean.getInstance()
.getPropertyUtils().getPropertyDescriptors(dest);
for (PropertyDescriptor pd : srcDescriptors) {
String name = pd.getName();
if("class".equals(name)) {
continue;
}
if("id".equals(name)) {
// TODO hardcoded. for update, never change Id field
continue;
}
Class type = pd.getPropertyType();
debug("copySimpleProperties-- name=" + name + ", type=" + type);
if (Collection.class.isAssignableFrom(type)) {
Field field = dest.getClass().getDeclaredField(name);
if(MyPropertyUtil.isFieldCollectionOfModel(field)) {
// ingore collection of Model
continue;
} else {
PropertyUtils.setProperty(dest, name, PropertyUtils.getProperty(orig, name));
}
}
else if (ModelObject.class.isAssignableFrom(type)) {
// we do not support editing of associated object at this point
// nor pointing to another associated object
continue;
}
else {
PropertyUtils.setProperty(dest, name, PropertyUtils.getProperty(orig, name));
}
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public static void form2To(ModelObject dest, Map<String, Object> orig) {
debug("form2To-- props:"+orig);
try {
HashMap<String, Object> _props = new HashMap<String, Object>();
PropertyDescriptor srcDescriptors[] = BeanUtilsBean.getInstance()
.getPropertyUtils().getPropertyDescriptors(dest);
for (PropertyDescriptor pd : srcDescriptors) {
String fn = pd.getName();
if("class".equals(fn)) {
continue;
}
Class type = pd.getPropertyType();
debug("fn:"+fn+" type:"+type);
if (!orig.containsKey(fn)) {
continue;
}
Object value = orig.get(fn);
if (value == null) {
_props.put(fn, value);
continue;
}
if (ModelObject.class.isAssignableFrom(type)) {
String bean = type.getSimpleName();
if (value instanceof String) {
// the value is ID
debug("form2To-- type="+type);
ModelObject mo = (ModelObject)type.newInstance();
mo.setModelId((String)value);
// ModelObject mo = getModelObject(bean, (String)value);
_props.put(fn, mo);
} else if (value instanceof Map) {
Map<String, Object> cprops = (Map<String, Object>)value;
ModelObject mo = (ModelObject)type.newInstance();
form2To(mo, cprops);
_props.put(fn, mo);
} else {
throw new RuntimeException("Unknown value type: " + value+","+value.getClass()+" bean:"+bean);
}
} else if (Collection.class.isAssignableFrom(type)) {
Collection col = null;
if (value != null) {
if(MyPropertyUtil.isFieldCollectionOfModel(dest.getClass().getDeclaredField(fn))) {
// NOTE: this means always Add/Update child ModelObject separately
continue;
}
else {
// String bean = config.getItemType(obj.getModelName(), fn);
if (value instanceof String) {
col = (Collection)PropertyUtils.getProperty(dest, fn);
String val = (String)value;
if(((String)val).indexOf(",")>0) {
// for properties like Goods.categoryIds which is internally list of String,
// and submitted in the format of comma-separated string
// TODO escape ","
String[] values = ConvertUtil.split(val, ",");
col.addAll(Arrays.asList(values));
} else {
col.add(value);
}
} else if (value instanceof Collection) {
Collection c = (Collection)value;
col = (Collection)PropertyUtils.getProperty(dest, fn);
debug("size: "+c.size());
col.addAll(c);
// _props.put(fn, c);
}
}
// else {
//// throw new RuntimeException("Unknown value type: " + value+","+value.getClass()+" bean:"+bean);
// throw new RuntimeException("Unknown value type: " + value+","+value.getClass());
// }
} else {
// keep the old value
col = (Collection)PropertyUtils.getProperty(dest, fn);
}
// _props.put(fn, col);
} else {
_props.put(fn, value);
}
}
debug("form2To-- _props:"+_props);
BeanUtils.populate(dest, _props);
} catch (Exception e) {
e.printStackTrace();
}
}
public static void debug(String s) {
log.info("in [MyPropertyUtil]: "+s);
}
}
| {
"content_hash": "af4aee34f77ffbd38863534677f3b4ca",
"timestamp": "",
"source": "github",
"line_count": 281,
"max_line_length": 171,
"avg_line_length": 37.67259786476868,
"alnum_prop": 0.5187984129982997,
"repo_name": "jbosschina/jcommerce",
"id": "06db66e3451361a355d4a0ad422780001974c4c0",
"size": "10586",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "spring/core/src/main/java/com/jcommerce/core/util/MyPropertyUtil.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "200608"
},
{
"name": "GAP",
"bytes": "2286"
},
{
"name": "Java",
"bytes": "4485563"
}
],
"symlink_target": ""
} |
function Command(command, target, value) {
this.command = command != null ? command : '';
if (target != null && target instanceof Array) {
if (target[0]) {
this.target = target[0][0];
this.targetCandidates = target;
} else {
this.target = "LOCATOR_DETECTION_FAILED";
}
} else {
this.target = target != null ? target : '';
}
this.value = value != null ? value : '';
}
Command.prototype.createCopy = function() {
var copy = new Command();
for (prop in this) {
copy[prop] = this[prop];
}
return copy;
};
Command.prototype.getRealValue = function() {
if (this.value) {
return this.value;
} else {
return this.target;
}
}
Command.prototype.getRealTarget = function() {
if (this.value) {
return this.target;
} else {
return null;
}
}
Command.innerHTML = function(element) {
var html = "";
var nodes = element.childNodes;
for (var i = 0; i < nodes.length; i++) {
var node = nodes.item(i);
switch (node.nodeType) {
case 1: // ELEMENT_NODE
html += "<" + node.nodeName + ">";
html += this.innerHTML(node);
html += "</" + node.nodeName + ">";
break;
case 3: // TEXT_NODE
html += node.data;
break;
}
}
return html;
}
Command.loadAPI = function() {
if (!this.functions) {
var document;
var documents = this.apiDocuments;
var functions = {};
// document.length will be 1 by default, but will grow with plugins
for (var d = 0; d < documents.length; d++) {
// set the current document. again, by default this is the iedoc-core.xml
document = documents[d];
// <function name="someName">
// <param name="targetName">description</param>
// <param name="valueName">description</param> -- optional
// <return type="string">description</return> -- optional
// <comment>description for ide here</comment>
// </function>
var functionElements = document.documentElement.getElementsByTagName("function");
for (var i = 0; i < functionElements.length; i++) {
var element = functionElements.item(i);
var def = new CommandDefinition(String(element.attributes.getNamedItem('name').value));
var returns = element.getElementsByTagName("return");
if (returns.length > 0) {
var returnType = new String(returns.item(0).attributes.getNamedItem("type").value);
returnType = returnType.replace(/string/, "String");
def.returnType = returnType;
def.returnDescription = this.innerHTML(returns.item(0));
}
var comments = element.getElementsByTagName("comment");
if (comments.length > 0) {
def.comment = this.innerHTML(comments.item(0));
}
var params = element.getElementsByTagName("param");
for (var j = 0; j < params.length; j++) {
var paramElement = params.item(j);
var param = {};
param.name = String(paramElement.attributes.getNamedItem('name').value);
param.description = this.innerHTML(paramElement);
def.params.push(param);
}
functions[def.name] = def;
// generate negative accessors
if (def.name.match(/^(is|get)/)) {
def.isAccessor = true;
functions["!" + def.name] = def.negativeAccessor();
}
if (def.name.match(/^assert/)) { // only assertSelected should match
var verifyDef = new CommandDefinition(def.name);
verifyDef.params = def.params;
functions["verify" + def.name.substring(6)] = verifyDef;
}
}
}
functions['assertFailureOnNext'] = new CommandDefinition('assertFailureOnNext');
functions['verifyFailureOnNext'] = new CommandDefinition('verifyFailureOnNext');
functions['assertErrorOnNext'] = new CommandDefinition('assertErrorOnNext');
functions['verifyErrorOnNext'] = new CommandDefinition('verifyErrorOnNext');
this.functions = functions;
}
return this.functions;
}
function CommandDefinition(name) {
this.name = name;
this.params = [];
}
CommandDefinition.prototype.getReferenceFor = function(command) {
var paramNames = [];
for (var i = 0; i < this.params.length; i++) {
paramNames.push(this.params[i].name);
}
var originalParamNames = paramNames.join(", ");
if (this.name.match(/^is|get/)) { // accessor
if (command.command) {
if (command.command.match(/^store/)) {
paramNames.push("variableName");
} else if (command.command.match(/^(assert|verify|waitFor)/)) {
if (this.name.match(/^get/)) {
paramNames.push("pattern");
}
}
}
}
var note = "";
if (command.command && command.command != this.name) {
note = "<dt>Generated from <strong>" + this.name + "(" +
originalParamNames + ")</strong></dt>";
}
var params = "";
if (this.params.length > 0) {
params += "<div>Arguments:</div><ul>";
for (var i = 0; i < this.params.length; i++) {
params += "<li>" + this.params[i].name + " - " + this.params[i].description + "</li>";
}
params += "</ul>";
}
var returns = "";
if (this.returnDescription) {
returns += "<dl><dt>Returns:</dt><dd>" + this.returnDescription + "</dd></dl>";
}
return "<dl><dt><strong>" + (command.command || this.name) + "(" +
paramNames.join(", ") + ")</strong></dt>" +
note +
'<dd style="margin:5px;">' +
params + returns +
this.comment + "</dd></dl>";
}
CommandDefinition.prototype.negativeAccessor = function() {
var def = new CommandDefinition(this.name);
for (var name in this) {
def[name] = this[name];
}
def.isAccessor = true;
def.negative = true;
return def;
}
Command.prototype.getDefinition = function() {
if (this.command == null) return null;
var commandName = this.command.replace(/AndWait$/, '');
var api = Command.loadAPI();
var r = /^(assert|verify|store|waitFor)(.*)$/.exec(commandName);
if (r) {
var suffix = r[2];
var prefix = "";
if ((r = /^(.*)NotPresent$/.exec(suffix)) != null) {
suffix = r[1] + "Present";
prefix = "!";
} else if ((r = /^Not(.*)$/.exec(suffix)) != null) {
suffix = r[1];
prefix = "!";
}
var booleanAccessor = api[prefix + "is" + suffix];
if (booleanAccessor) {
return booleanAccessor;
}
var accessor = api[prefix + "get" + suffix];
if (accessor) {
return accessor;
}
}
return api[commandName];
}
Command.prototype.getParameterAt = function(index) {
switch (index) {
case 0:
return this.target;
case 1:
return this.value;
default:
return null;
}
}
Command.prototype.getAPI = function() {
return window.editor.seleniumAPI;
}
Command.prototype.type = 'command';
/**
* The string representation of a command is the command, target, and value
* delimited by padded pipes.
*/
Command.prototype.toString = function()
{
var s = this.command
if (this.target) {
s += ' | ' + this.target;
if (this.value) {
s += ' | ' + this.value;
}
}
return s;
}
Command.prototype.isRollup = function()
{
return /^rollup(?:AndWait)?$/.test(this.command);
}
function Comment(comment) {
this.comment = comment != null ? comment : '';
}
Comment.prototype.type = 'comment';
function Line(line) {
this.line = line;
}
Line.prototype.type = 'line';
Comment.prototype.createCopy = function() {
var copy = new Comment();
for (prop in this) {
copy[prop] = this[prop];
}
return copy;
};
function TestCase(tempTitle) {
if (!tempTitle) tempTitle = "Untitled";
this.log = new Log("TestCase");
this.tempTitle = tempTitle;
this.formatLocalMap = {};
this.commands = [];
this.recordModifiedInCommands();
this.baseURL = "";
var testCase = this;
this.debugContext = {
reset: function() {
this.failed = false;
this.started = false;
this.debugIndex = -1;
},
nextCommand: function() {
if (!this.started) {
this.started = true;
this.debugIndex = testCase.startPoint ? testCase.commands.indexOf(testCase.startPoint) : 0
} else {
this.debugIndex++;
}
for (; this.debugIndex < testCase.commands.length; this.debugIndex++) {
var command = testCase.commands[this.debugIndex];
if (command.type == 'command') {
return command;
}
}
return null;
},
currentCommand: function() {
var command = testCase.commands[this.debugIndex];
if (!command) {
testCase.log.warn("currentCommand() not found: commands.length=" + testCase.commands.length + ", debugIndex=" + this.debugIndex);
}
return command;
}
}
}
// Create a shallow copy of testcase
TestCase.prototype.createCopy = function() {
var copy = new TestCase();
for (prop in this) {
copy[prop] = this[prop];
}
return copy;
};
// Store variables specific to each format in this hash.
TestCase.prototype.formatLocal = function(formatName) {
var scope = this.formatLocalMap[formatName];
if (!scope) {
scope = {};
this.formatLocalMap[formatName] = scope;
}
return scope;
}
// For backwards compatibility
TestCase.prototype.setCommands = function(commands) {
this.commands = commands;
this.recordModifiedInCommands();
}
TestCase.prototype.recordModifiedInCommands = function() {
if (this.commands.recordModified) {
return;
}
this.commands.recordModified = true;
var self = this;
var commands = this.commands;
var _push = commands.push;
commands.push = function(command) {
_push.call(commands, command);
self.setModified();
}
var _splice = commands.splice;
commands.splice = function(index, removeCount, command) {
var removed = null;
if (command !== undefined && command != null) {
removed = _splice.call(commands, index, removeCount, command);
} else {
removed = _splice.call(commands, index, removeCount);
}
self.setModified();
return removed;
}
var _pop = commands.pop;
commands.pop = function() {
var command = commands[commands.length - 1];
commands.splice(commands.length - 1, 1);
self.setModified();
return command;
}
}
TestCase.prototype.clear = function() {
var length = this.commands.length;
this.commands.splice(0, this.commands.length);
this.setModified();
};
TestCase.prototype.setModified = function() {
this.modified = true;
this.notify("modifiedStateUpdated");
}
TestCase.prototype.clearModified = function() {
this.modified = false;
this.notify("modifiedStateUpdated");
}
TestCase.prototype.checkTimestamp = function() {
if (this.file) {
if (this.lastModifiedTime < this.file.lastModifiedTime) {
this.lastModifiedTime = this.file.lastModifiedTime;
return true;
}
}
return false;
}
TestCase.prototype.getCommandIndexByTextIndex = function(text, index, formatter) {
this.log.debug("getCommandIndexByTextIndex: index=" + index);
var lineno = text.substring(0, index).split(/\n/).length - 1;
var header = this.formatLocal(formatter.name).header;
this.log.debug("lineno=" + lineno + ", header=" + header);
if (header) {
lineno -= header.split(/\n/).length - 1;
}
this.log.debug("this.commands.length=" + this.commands.length);
for (var i = 0; i < this.commands.length; i++) {
this.log.debug("lineno=" + lineno + ", i=" + i);
if (lineno <= 0) {
return i;
}
var command = this.commands[i];
if (command.line != null) {
lineno -= command.line.split(/\n/).length;
}
}
return this.commands.length;
}
TestCase.prototype.getTitle = function() {
if (this.title) {
return this.title;
} else if (this.file && this.file.leafName) {
return this.file.leafName.replace(/\.\w+$/,'');
} else if (this.tempTitle) {
return this.tempTitle;
} else {
return null;
}
}
TestCase.prototype.setBaseURL = function(baseURL) {
this.baseURL = baseURL;
}
observable(TestCase);
| {
"content_hash": "1fca59d514c8fdb5d996017909f2f637",
"timestamp": "",
"source": "github",
"line_count": 440,
"max_line_length": 145,
"avg_line_length": 27.279545454545456,
"alnum_prop": 0.6157627259851703,
"repo_name": "hugs/selenium",
"id": "640b8114cb40e1559fb44cda52e957d4bf080550",
"size": "12602",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "ide/src/extension/content/testCase.js",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ASP",
"bytes": "853"
},
{
"name": "C",
"bytes": "9165596"
},
{
"name": "C#",
"bytes": "1276218"
},
{
"name": "C++",
"bytes": "245706"
},
{
"name": "Java",
"bytes": "5070618"
},
{
"name": "JavaScript",
"bytes": "11186985"
},
{
"name": "Objective-C",
"bytes": "430464"
},
{
"name": "Python",
"bytes": "2146977"
},
{
"name": "Ruby",
"bytes": "249671"
},
{
"name": "Shell",
"bytes": "13541"
}
],
"symlink_target": ""
} |
/******************************************************************************
*
*
* Notepad2
*
* version.h
* Notepad2 version information
*
* See Readme.txt for more information about this source code.
* Please send me your comments to this work.
*
* See License.txt for details about distribution and modification.
*
* (c) Florian Balmer 1996-2011
* florian.balmer@gmail.com
* http://www.flos-freeware.ch
*
*
******************************************************************************/
#define VERSION_FILEVERSION_NUM 4,2,25,0
#define VERSION_FILEVERSION_SHORT L"4.2.25"
#define VERSION_FILEVERSION_LONG L"Notepad2 4.2.25"
#define VERSION_LEGALCOPYRIGHT_SHORT L"Copyright © 2004-2011"
#define VERSION_LEGALCOPYRIGHT_LONG L"© Florian Balmer 2004-2011"
#ifdef _M_AMD64
#define VERSION_FILEDESCRIPTION L"Notepad2 x64"
#else
#define VERSION_FILEDESCRIPTION L"Notepad2"
#endif
#define VERSION_INTERNALNAME L"Notepad2"
#define VERSION_ORIGINALFILENAME L"Notepad2.exe"
#define VERSION_AUTHORNAME L"Florian Balmer"
#define VERSION_WEBPAGEDISPLAY L"flo's freeware - http://www.flos-freeware.ch"
#define VERSION_EMAILDISPLAY L"florian.balmer@gmail.com"
| {
"content_hash": "ac0ab4da6fd074c833824269cf28c18d",
"timestamp": "",
"source": "github",
"line_count": 36,
"max_line_length": 84,
"avg_line_length": 37.55555555555556,
"alnum_prop": 0.5702662721893491,
"repo_name": "zergtmn/notepad2",
"id": "e0c722da79a3d81ba24bbbe44198eb57d335367a",
"size": "1352",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "src/version.h",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "ASP",
"bytes": "121"
},
{
"name": "C",
"bytes": "884486"
},
{
"name": "C++",
"bytes": "2579023"
},
{
"name": "D",
"bytes": "506"
},
{
"name": "JavaScript",
"bytes": "885"
},
{
"name": "Objective-C",
"bytes": "218122"
},
{
"name": "PHP",
"bytes": "99"
},
{
"name": "Python",
"bytes": "85770"
},
{
"name": "Shell",
"bytes": "1345"
},
{
"name": "Visual Basic",
"bytes": "250"
}
],
"symlink_target": ""
} |
class CircularQueue
{
friend class CircularQueueTest;
public:
// Can be seen outside as CircularQueue::QueueItem
typedef int QueueItem;
// Used as an indicator of empty queue.
static const QueueItem EMPTY_QUEUE;
// Default constructor used to initialise the circular queue class.
CircularQueue();
// Destructor.
~CircularQueue();
// Takes as an argument a QueueItem value. If the queue is not full, it
// inserts the value at the rear of the queue (after the last item), and
// returns true. It returns false if the process fails.
bool enqueue(QueueItem value);
// Returns the value at the front of the queue. If the queue is not empty,
// the front item is removed from it. If the queue was empty before the
// dequeue, the EMPTY_QUEUE constant is returned.
QueueItem dequeue();
// Returns the value at the front of the queue without removing it from the
// queue. If the queue was empty before the peek, the EMPTY_QUEUE constant is
// returned.
QueueItem peek() const;
// Returns true if the queue is empty and false otherwise.
bool empty() const;
// Returns true if the queue is full and false otherwise.
bool full() const;
// Returns the number of items in the queue.
int size() const;
// Rrints the queue items sequentially ordered from the front to the rear of
// the queue.
void print() const;
private:
// Override copy constructor and assignment operator in private so we can't
// use them.
CircularQueue(const CircularQueue& other) {}
CircularQueue operator=(const CircularQueue& other) {}
private:
// As the size is fixed, you may as well use an array here (not a dynamic
// array; a normal array). But to keep it flexible, we use a dynamic array
// and initialise it with size 16 in the constructor.
QueueItem *items_;
// Indices for keeping track of the circular array
int head_, tail_;
int capacity_;
int size_;
};
#endif
| {
"content_hash": "28928790e2d3ee8aa76842d79fc57168",
"timestamp": "",
"source": "github",
"line_count": 63,
"max_line_length": 81,
"avg_line_length": 32.6031746031746,
"alnum_prop": 0.6733203505355404,
"repo_name": "chrisjluc/Datastructures",
"id": "0e4f11507628171ab1295c7f09544e9a0e60c5af",
"size": "2197",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "CircularQueue.hpp",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "C++",
"bytes": "29189"
}
],
"symlink_target": ""
} |
var exercise = require('../../exercise');
module.exports = exercise
.push('/', function (data, res, stream) {
stream.write('responds ' + data.toString() + ' when requset /\n');
stream.write('response status is ' + res.statusCode + ' when request /\n');
})
.push('/error', function (data, res, stream) {
stream.write('responds ' + data.toString() + ' when requset /error\n');
stream.write('response status is ' + res.statusCode + ' when request /error\n');
})
.generate();
| {
"content_hash": "132508e990696c7ad4179f52ae6d1e74",
"timestamp": "",
"source": "github",
"line_count": 12,
"max_line_length": 82,
"avg_line_length": 40.083333333333336,
"alnum_prop": 0.6444906444906445,
"repo_name": "qwo/kick-off-koa",
"id": "9997762a9076db801be661f95235f901ef729140",
"size": "482",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "exercises/error_handling/exercise.js",
"mode": "33188",
"license": "mit",
"language": [],
"symlink_target": ""
} |
'use strict';
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
var mongoose = require('mongoose');
var User = require('../models/user');
passport.use(new LocalStrategy({
usernameField: 'email'
}, function (username, password, done) {
User.findOne({ email: username }, function (err, user) {
if (err) return done(err);
// User not found in the database
if (!user) return done(null, false, { message: 'User not found' });
// Wrong password provided
if (!user.validPassword(password))
return done(null, false, { message: 'Password is wrong' });
// Credentials arre correct, returns the User object
return done(null, user);
});
}
));
| {
"content_hash": "bb330f2bc679ee95dc62db8800894d92",
"timestamp": "",
"source": "github",
"line_count": 27,
"max_line_length": 73,
"avg_line_length": 27.62962962962963,
"alnum_prop": 0.6394101876675603,
"repo_name": "dalonsog/nodeTwitter",
"id": "de52a11e7fcbdc51e927b4824ff52a355e1e964e",
"size": "746",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/config/passport.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "9082"
},
{
"name": "HTML",
"bytes": "7808"
},
{
"name": "JavaScript",
"bytes": "20968"
}
],
"symlink_target": ""
} |
#ifndef BOOST_SERIALIZATION_SHARED_PTR_HPP
#define BOOST_SERIALIZATION_SHARED_PTR_HPP
// MS compatible compilers support #pragma once
#if defined(_MSC_VER) && (_MSC_VER >= 1020)
# pragma once
#endif
/////////1/////////2/////////3/////////4/////////5/////////6/////////7/////////8
// shared_ptr.hpp: serialization for boost shared pointer
// (C) Copyright 2004 Robert Ramey and Martin Ecker
// Use, modification and distribution is subject to the Boost Software
// License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
// See http://www.boost.org for updates, documentation, and revision history.
#include <map>
#include <cstddef> // NULL
#include <boost/config.hpp>
#include <boost/mpl/integral_c.hpp>
#include <boost/mpl/integral_c_tag.hpp>
#include <boost/detail/workaround.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/serialization/split_free.hpp>
#include <boost/serialization/nvp.hpp>
#include <boost/serialization/version.hpp>
#include <boost/serialization/tracking.hpp>
/////////1/////////2/////////3/////////4/////////5/////////6/////////7/////////8
// shared_ptr serialization traits
// version 1 to distinguish from boost 1.32 version. Note: we can only do this
// for a template when the compiler supports partial template specialization
#ifndef BOOST_NO_TEMPLATE_PARTIAL_SPECIALIZATION
namespace boost {
namespace serialization{
template<class T>
struct version< ::boost::shared_ptr<T> > {
typedef mpl::integral_c_tag tag;
#if BOOST_WORKAROUND(__MWERKS__, BOOST_TESTED_AT(0x3206))
typedef BOOST_DEDUCED_TYPENAME mpl::int_<1> type;
#else
typedef mpl::int_<1> type;
#endif
#if BOOST_WORKAROUND(__BORLANDC__, BOOST_TESTED_AT(0x570))
BOOST_STATIC_CONSTANT(unsigned int, value = 1);
#else
BOOST_STATIC_CONSTANT(unsigned int, value = type::value);
#endif
};
// don't track shared pointers
template<class T>
struct tracking_level< ::boost::shared_ptr<T> > {
typedef mpl::integral_c_tag tag;
#if BOOST_WORKAROUND(__MWERKS__, BOOST_TESTED_AT(0x3206))
typedef BOOST_DEDUCED_TYPENAME mpl::int_< ::boost::serialization::track_never> type;
#else
typedef mpl::int_< ::boost::serialization::track_never> type;
#endif
#if BOOST_WORKAROUND(__BORLANDC__, BOOST_TESTED_AT(0x570))
BOOST_STATIC_CONSTANT(int, value = ::boost::serialization::track_never);
#else
BOOST_STATIC_CONSTANT(int, value = type::value);
#endif
};
}}
#define BOOST_SERIALIZATION_SHARED_PTR(T)
#else
// define macro to let users of these compilers do this
#define BOOST_SERIALIZATION_SHARED_PTR(T) \
BOOST_CLASS_VERSION( \
::boost::shared_ptr< T >, \
1 \
) \
BOOST_CLASS_TRACKING( \
::boost::shared_ptr< T >, \
::boost::serialization::track_never \
) \
/**/
#endif
namespace boost {
namespace serialization{
/////////1/////////2/////////3/////////4/////////5/////////6/////////7/////////8
// serialization for shared_ptr
template<class Archive, class T>
inline void save(
Archive & ar,
const boost::shared_ptr<T> &t,
const unsigned int /* file_version */
){
// The most common cause of trapping here would be serializing
// something like shared_ptr<int>. This occurs because int
// is never tracked by default. Wrap int in a trackable type
BOOST_STATIC_ASSERT((tracking_level<T>::value != track_never));
const T * t_ptr = t.get();
ar << boost::serialization::make_nvp("px", t_ptr);
}
template<class Archive, class T>
inline void load(
Archive & ar,
boost::shared_ptr<T> &t,
const unsigned int file_version
){
// The most common cause of trapping here would be serializing
// something like shared_ptr<int>. This occurs because int
// is never tracked by default. Wrap int in a trackable type
BOOST_STATIC_ASSERT((tracking_level<T>::value != track_never));
T* r;
#ifdef BOOST_SERIALIZATION_SHARED_PTR_132_HPP
if(file_version < 1){
//ar.register_type(static_cast<
// boost_132::detail::sp_counted_base_impl<T *, boost::checked_deleter<T> > *
//>(NULL));
ar.register_type(static_cast<
boost_132::detail::sp_counted_base_impl<T *, boost::archive::detail::null_deleter > *
>(NULL));
boost_132::shared_ptr<T> sp;
ar >> boost::serialization::make_nvp("px", sp.px);
ar >> boost::serialization::make_nvp("pn", sp.pn);
// got to keep the sps around so the sp.pns don't disappear
ar.append(sp);
r = sp.get();
}
else
#endif
{
ar >> boost::serialization::make_nvp("px", r);
}
ar.reset(t,r);
}
template<class Archive, class T>
inline void serialize(
Archive & ar,
boost::shared_ptr<T> &t,
const unsigned int file_version
){
// correct shared_ptr serialization depends upon object tracking
// being used.
BOOST_STATIC_ASSERT(
boost::serialization::tracking_level<T>::value
!= boost::serialization::track_never
);
boost::serialization::split_free(ar, t, file_version);
}
} // namespace serialization
} // namespace boost
#endif // BOOST_SERIALIZATION_SHARED_PTR_HPP
| {
"content_hash": "dee4e1238db1e779eb76c422c0edab8e",
"timestamp": "",
"source": "github",
"line_count": 159,
"max_line_length": 97,
"avg_line_length": 37.861635220125784,
"alnum_prop": 0.5561461794019934,
"repo_name": "jaredhoberock/gotham",
"id": "f22d052ce84709d4282c2655883567291cd0abc6",
"size": "6020",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "windows/include/boost/serialization/shared_ptr.hpp",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "3000328"
},
{
"name": "C++",
"bytes": "43171616"
},
{
"name": "Perl",
"bytes": "6275"
},
{
"name": "Python",
"bytes": "2200222"
},
{
"name": "Shell",
"bytes": "2497"
}
],
"symlink_target": ""
} |
package net.brainage.example.mapper;
import net.brainage.example.model.Department;
import net.brainage.example.model.Employee;
import org.apache.ibatis.annotations.*;
import java.util.List;
/**
* @author <a href="mailto:ms29.seo+ara@gmail.com">ms29.seo</a>
*/
public interface EmployeeMapper extends CrudMapper<Employee, Integer> {
@Select("SELECT EMPNO, DEPTNO, ENAME, JOB, MGR, HIREDATE, SAL, COMM FROM EMP WHERE EMPNO = #{id}")
@Results({
@Result(property = "id", column = "EMPNO"),
@Result(property = "departmentId", column = "DEPTNO"),
@Result(property = "department", column = "DEPTNO", javaType = Department.class,
one = @One(select = "net.brainage.example.mapper.DepartmentMapper.findOne")),
@Result(property = "name", column = "ENAME"),
@Result(property = "job", column = "JOB"),
@Result(property = "managerId", column = "MGR"),
@Result(property = "manager", column = "MGR", javaType = Employee.class,
one = @One(select = "net.brainage.example.mapper.EmployeeMapper.findOne")),
@Result(property = "hireDate", column = "HIREDATE"),
@Result(property = "salary", column = "SAL"),
@Result(property = "commissionPercent", column = "COMM")
})
@Override
Employee findOne(Integer key);
@Select("SELECT EMPNO, DEPTNO, ENAME, JOB, MGR, HIREDATE, SAL, COMM FROM EMP")
@Results({
@Result(property = "id", column = "EMPNO"),
@Result(property = "departmentId", column = "DEPTNO"),
@Result(property = "name", column = "ENAME"),
@Result(property = "job", column = "JOB"),
@Result(property = "managerId", column = "MGR"),
@Result(property = "hireDate", column = "HIREDATE"),
@Result(property = "salary", column = "SAL"),
@Result(property = "commissionPercent", column = "COMM")
})
@Override
List<Employee> findAll();
@Insert("INSERT INTO EMP (EMPNO, DEPTNO, ENAME, JOB, MGR, HIREDATE, SAL, COMM) " +
"VALUES (#{id}, #{departmentId}, #{name}, #{job}, #{managerId}, #{hireDate}, #{salary}, #{commissionPercent})")
@Override
void insert(Employee emp);
@Update("UPDATE EMP " +
"SET DEPTNO = #{departmentId}, " +
"ENAME = #{name}, " +
"JOB = #{job}, MGR = #{managerId}, " +
"HIREDATE = #{hireDate}, SAL = #{salary}, " +
"COMM = #{commissionPercent} " +
"WHERE EMPNO = #{id}")
@Override
void update(Employee emp);
@Delete("DELETE FROM EMP WHERE EMPNO = #{id}")
@Override
int delete(@Param("id") Integer id);
}
| {
"content_hash": "64a30d0dc154a2150f2c89881afd9b81",
"timestamp": "",
"source": "github",
"line_count": 66,
"max_line_length": 123,
"avg_line_length": 41.27272727272727,
"alnum_prop": 0.5752569750367107,
"repo_name": "brainagenet/spring-mybatis-manual-transaction",
"id": "031956bc67eb1b64f7db11d21aeb40ec8c876556",
"size": "3404",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/main/java/net/brainage/example/mapper/EmployeeMapper.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "5006"
},
{
"name": "Java",
"bytes": "18980"
},
{
"name": "Shell",
"bytes": "7058"
}
],
"symlink_target": ""
} |
var NAVTREE =
[
[ "Lua-API++", "index.html", [
[ "Lua API++ library", "index.html", null ],
[ "License", "main_license.html", null ],
[ "Basic concepts", "basic_concepts.html", [
[ "Global state", "basic_concepts.html#basic_global_state", null ],
[ "Lua functions and context", "basic_concepts.html#basic_state", [
[ "Multiple return values", "basic_concepts.html#basic_state_multiret", [
[ "Returning multiple values", "basic_concepts.html#basic_state_multiret_return", null ],
[ "Accepting multiple return values of a call", "basic_concepts.html#basic_state_multiret_call", null ]
] ]
] ],
[ "Lua values", "basic_concepts.html#basic_values", [
[ "Native values", "basic_concepts.html#basic_values_native", null ],
[ "User values", "basic_concepts.html#basic_values_user", null ],
[ "Temporary value handling", "basic_concepts.html#basic_values_temporary", null ],
[ "Valref", "basic_concepts.html#basic_values_valref", null ],
[ "Anchor value types", "basic_concepts.html#basic_values_anchors", [
[ "Value", "basic_concepts.html#basic_values_anchors_value", null ],
[ "Table", "basic_concepts.html#basic_values_anchors_table", null ],
[ "Valset", "basic_concepts.html#basic_values_anchors_valset", null ]
] ]
] ]
] ],
[ "Motivational example", "motivational_example.html", null ],
[ "Automatic stack management", "stack_management.html", [
[ "Passing values to and returning from functions", "stack_management.html#stack_management_function", [
[ "References", "stack_management.html#stack_management_function_valref", null ],
[ "Anchors", "stack_management.html#stack_management_function_anchor", null ]
] ]
] ],
[ "Using the library", "usage.html", [
[ "Using the library with your project", "usage.html#usage_basic", null ],
[ "Building the tests (for library development)", "usage.html#usage_tests", null ],
[ "Documentation", "usage.html#Documentation", null ]
] ],
[ "Configuring the library", "configuring.html", [
[ "Compatibility", "configuring.html#configuring_compatibility", [
[ "Lua language version", "configuring.html#configuring_compatibility_langver", null ],
[ "NRVO support", "configuring.html#configuring_compatibility_nrvo", null ]
] ],
[ "Discardability", "configuring.html#configuring_discardability", null ],
[ "Performance", "configuring.html#configuring_performance", null ],
[ "Debugging: stack integrity checking", "configuring.html#configuring_stack_watch", null ]
] ],
[ "Performance", "performace.html", null ],
[ "Compatibility", "compatibility.html", [
[ "Lua 5.1", "compatibility.html#compatibility_5_1", null ],
[ "Lua 5.2", "compatibility.html#compatibility_5_2", null ],
[ "Lua 5.3", "compatibility.html#compatibility_5_3", null ],
[ "NRVO compiler capability", "compatibility.html#compatibility_nrvo", null ]
] ],
[ "External links", "external_links.html", null ],
[ "FAQ", "faq.html", [
[ "Compatibility", "faq.html#faq_compat", [
[ "Which versions of Lua does this library support?", "faq.html#faq_compat_versions", null ],
[ "Is this library compatible with LuaJIT?", "faq.html#faq_compat_luajit", null ]
] ],
[ "Programming", "faq.html#faq_programming", [
[ "Is it possible to use inherited classes with virtual functions as userdata?", "faq.html#faq_programming_polymorphic_userdata", null ]
] ],
[ "Technical issues", "faq.html#faq_known_problems", [
[ "I compiled the motivational example and it crashes on out-of-bound array access.", "faq.html#faq_known_problems_sjlj", null ]
] ]
] ],
[ "Changelog", "changelog.html", [
[ "2015-02-12-0", "changelog.html#changes_2015_02_12_0", [
[ "2015-02-12-1", "changelog.html#changes_2015_02_12_1", null ],
[ "2015-02-12-2", "changelog.html#changes_2015_02_12_2", null ],
[ "2015-02-12-3", "changelog.html#changes_2015_02_12_3", null ]
] ],
[ "2015-01-21-0", "changelog.html#changes_2015_01_21_0", null ],
[ "2014-11-24-0", "changelog.html#changes_2014_11_24_0", null ],
[ "2014-10-29-0", "changelog.html#changes_2014_10_29_0", null ],
[ "2014-09-22-0", "changelog.html#changes_2014_09_22_0", null ],
[ "2014-09-18-0", "changelog.html#changes_2014_09_18_0", null ],
[ "2014-09-09-0", "changelog.html#changes_2014_09_09_0", null ],
[ "2014-09-01-0", "changelog.html#changes_2014_09_01_0", null ],
[ "2014-08-29-0", "changelog.html#changes_2014_08_29_0", null ],
[ "2014-08-28-0", "changelog.html#changes_2014_08_28_0", null ],
[ "2014-08-18-0", "changelog.html#changes_2014_08_18_0", null ]
] ],
[ "Deprecated List", "deprecated.html", null ],
[ "Namespace Members", "namespacemembers.html", [
[ "All", "namespacemembers.html", null ],
[ "Functions", "namespacemembers_func.html", null ],
[ "Variables", "namespacemembers_vars.html", null ],
[ "Typedefs", "namespacemembers_type.html", null ],
[ "Enumerations", "namespacemembers_enum.html", null ]
] ],
[ "Classes", "annotated.html", [
[ "Class List", "annotated.html", "annotated_dup" ],
[ "Class Index", "classes.html", null ],
[ "Class Hierarchy", "hierarchy.html", "hierarchy" ],
[ "Class Members", "functions.html", [
[ "All", "functions.html", null ],
[ "Functions", "functions_func.html", null ],
[ "Variables", "functions_vars.html", null ],
[ "Typedefs", "functions_type.html", null ],
[ "Enumerations", "functions_enum.html", null ]
] ]
] ],
[ "Files", null, [
[ "File List", "files.html", "files" ],
[ "File Members", "globals.html", [
[ "All", "globals.html", null ],
[ "Macros", "globals_defs.html", null ]
] ]
] ]
] ]
];
var NAVTREEINDEX =
[
"annotated.html",
"namespacemembers_enum.html"
];
var SYNCONMSG = 'click to disable panel synchronisation';
var SYNCOFFMSG = 'click to enable panel synchronisation'; | {
"content_hash": "26c4c0243c658918ea4bb32c2f884a1e",
"timestamp": "",
"source": "github",
"line_count": 121,
"max_line_length": 144,
"avg_line_length": 51.45454545454545,
"alnum_prop": 0.6100224863475747,
"repo_name": "OldFisher/lua-api-pp",
"id": "76cf40a45ce4fa3d97a744a5cba0d52d92d06aa8",
"size": "6226",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "doc/html/navtreedata.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "910"
},
{
"name": "C++",
"bytes": "316320"
},
{
"name": "Objective-C",
"bytes": "511"
}
],
"symlink_target": ""
} |
using System;
using System.ComponentModel;
using System.Configuration;
namespace System.Runtime.Caching.Configuration
{
internal sealed class MemoryCacheElement : ConfigurationElement
{
private static ConfigurationPropertyCollection s_properties;
private static readonly ConfigurationProperty s_propName;
private static readonly ConfigurationProperty s_propPhysicalMemoryLimitPercentage;
private static readonly ConfigurationProperty s_propCacheMemoryLimitMegabytes;
private static readonly ConfigurationProperty s_propPollingInterval;
static MemoryCacheElement()
{
// Property initialization
s_properties = new ConfigurationPropertyCollection();
s_propName =
new ConfigurationProperty("name",
typeof(string),
null,
new WhiteSpaceTrimStringConverter(),
new StringValidator(1),
ConfigurationPropertyOptions.IsRequired |
ConfigurationPropertyOptions.IsKey);
s_propPhysicalMemoryLimitPercentage =
new ConfigurationProperty("physicalMemoryLimitPercentage",
typeof(int),
(int)0,
null,
new IntegerValidator(0, 100),
ConfigurationPropertyOptions.None);
s_propCacheMemoryLimitMegabytes =
new ConfigurationProperty("cacheMemoryLimitMegabytes",
typeof(int),
(int)0,
null,
new IntegerValidator(0, int.MaxValue),
ConfigurationPropertyOptions.None);
s_propPollingInterval =
new ConfigurationProperty("pollingInterval",
typeof(TimeSpan),
TimeSpan.FromMilliseconds(ConfigUtil.DefaultPollingTimeMilliseconds),
new InfiniteTimeSpanConverter(),
new PositiveTimeSpanValidator(),
ConfigurationPropertyOptions.None);
s_properties.Add(s_propName);
s_properties.Add(s_propPhysicalMemoryLimitPercentage);
s_properties.Add(s_propCacheMemoryLimitMegabytes);
s_properties.Add(s_propPollingInterval);
}
internal MemoryCacheElement()
{
}
public MemoryCacheElement(string name)
{
Name = name;
}
protected override ConfigurationPropertyCollection Properties
{
get
{
return s_properties;
}
}
[ConfigurationProperty("name", DefaultValue = "", IsRequired = true, IsKey = true)]
[TypeConverter(typeof(WhiteSpaceTrimStringConverter))]
[StringValidator(MinLength = 1)]
public string Name
{
get
{
return (string)base["name"];
}
set
{
base["name"] = value;
}
}
[ConfigurationProperty("physicalMemoryLimitPercentage", DefaultValue = (int)0)]
[IntegerValidator(MinValue = 0, MaxValue = 100)]
public int PhysicalMemoryLimitPercentage
{
get
{
return (int)base["physicalMemoryLimitPercentage"];
}
set
{
base["physicalMemoryLimitPercentage"] = value;
}
}
[ConfigurationProperty("cacheMemoryLimitMegabytes", DefaultValue = (int)0)]
[IntegerValidator(MinValue = 0)]
public int CacheMemoryLimitMegabytes
{
get
{
return (int)base["cacheMemoryLimitMegabytes"];
}
set
{
base["cacheMemoryLimitMegabytes"] = value;
}
}
[ConfigurationProperty("pollingInterval", DefaultValue = "00:02:00")]
[TypeConverter(typeof(InfiniteTimeSpanConverter))]
public TimeSpan PollingInterval
{
get
{
return (TimeSpan)base["pollingInterval"];
}
set
{
base["pollingInterval"] = value;
}
}
}
}
| {
"content_hash": "46621570e0ba94a1a7482416b9a42747",
"timestamp": "",
"source": "github",
"line_count": 133,
"max_line_length": 111,
"avg_line_length": 36.045112781954884,
"alnum_prop": 0.49687108886107634,
"repo_name": "mmitche/corefx",
"id": "07ed012da7e56338039f69016019f6a3ef3eeb5e",
"size": "4998",
"binary": false,
"copies": "43",
"ref": "refs/heads/master",
"path": "src/System.Runtime.Caching/src/System/Runtime/Caching/Configuration/MemoryCacheElement.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "1C Enterprise",
"bytes": "280724"
},
{
"name": "ASP",
"bytes": "1687"
},
{
"name": "Batchfile",
"bytes": "20096"
},
{
"name": "C",
"bytes": "3730054"
},
{
"name": "C#",
"bytes": "166928159"
},
{
"name": "C++",
"bytes": "117360"
},
{
"name": "CMake",
"bytes": "77718"
},
{
"name": "DIGITAL Command Language",
"bytes": "26402"
},
{
"name": "Groovy",
"bytes": "50984"
},
{
"name": "HTML",
"bytes": "653"
},
{
"name": "Makefile",
"bytes": "13780"
},
{
"name": "OpenEdge ABL",
"bytes": "137969"
},
{
"name": "Perl",
"bytes": "3895"
},
{
"name": "PowerShell",
"bytes": "95072"
},
{
"name": "Python",
"bytes": "1535"
},
{
"name": "Roff",
"bytes": "9387"
},
{
"name": "Shell",
"bytes": "119395"
},
{
"name": "Visual Basic",
"bytes": "1001421"
},
{
"name": "XSLT",
"bytes": "513537"
}
],
"symlink_target": ""
} |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("Miles.MassTransit.UnitTests")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Miles.MassTransit.UnitTests")]
[assembly: AssemblyCopyright("Copyright © 2019")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
[assembly: Guid("1fa53bc6-4e11-4c3d-bfba-a0cdac06dec1")]
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| {
"content_hash": "5eab1d12353e9cd69c3a3056991c6bae",
"timestamp": "",
"source": "github",
"line_count": 20,
"max_line_length": 58,
"avg_line_length": 32.7,
"alnum_prop": 0.7599388379204893,
"repo_name": "adz21c/miles",
"id": "9dad991cab8e9a3a9a76f168b86e6be64e1a2336",
"size": "655",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Miles.MassTransit.UnitTests/Properties/AssemblyInfo.cs",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C#",
"bytes": "81183"
}
],
"symlink_target": ""
} |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (1.8.0_45) on Sat Apr 09 10:11:08 EDT 2016 -->
<title>Uses of Class org.apache.cassandra.thrift.Cassandra.Processor.get_indexed_slices (apache-cassandra API)</title>
<meta name="date" content="2016-04-09">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">
<script type="text/javascript" src="../../../../../script.js"></script>
</head>
<body>
<script type="text/javascript"><!--
try {
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Uses of Class org.apache.cassandra.thrift.Cassandra.Processor.get_indexed_slices (apache-cassandra API)";
}
}
catch(err) {
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar.top">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.top.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../../org/apache/cassandra/thrift/Cassandra.Processor.get_indexed_slices.html" title="class in org.apache.cassandra.thrift">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../../../../../overview-tree.html">Tree</a></li>
<li><a href="../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../index.html?org/apache/cassandra/thrift/class-use/Cassandra.Processor.get_indexed_slices.html" target="_top">Frames</a></li>
<li><a href="Cassandra.Processor.get_indexed_slices.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip.navbar.top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<div class="header">
<h2 title="Uses of Class org.apache.cassandra.thrift.Cassandra.Processor.get_indexed_slices" class="title">Uses of Class<br>org.apache.cassandra.thrift.Cassandra.Processor.get_indexed_slices</h2>
</div>
<div class="classUseContainer">No usage of org.apache.cassandra.thrift.Cassandra.Processor.get_indexed_slices</div>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar.bottom">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.bottom.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../../org/apache/cassandra/thrift/Cassandra.Processor.get_indexed_slices.html" title="class in org.apache.cassandra.thrift">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../../../../../overview-tree.html">Tree</a></li>
<li><a href="../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../index.html?org/apache/cassandra/thrift/class-use/Cassandra.Processor.get_indexed_slices.html" target="_top">Frames</a></li>
<li><a href="Cassandra.Processor.get_indexed_slices.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip.navbar.bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<p class="legalCopy"><small>Copyright © 2016 The Apache Software Foundation</small></p>
</body>
</html>
| {
"content_hash": "5d09cbce23a25e83abe82624faf3d2f2",
"timestamp": "",
"source": "github",
"line_count": 125,
"max_line_length": 195,
"avg_line_length": 38.808,
"alnum_prop": 0.6279117707689136,
"repo_name": "jasonwee/videoOnCloud",
"id": "22bdc8904eb9bdcb4e1a3477d4e551df55f7d850",
"size": "4851",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "ahkl/apache-cassandra-3.5/javadoc/org/apache/cassandra/thrift/class-use/Cassandra.Processor.get_indexed_slices.html",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "116270"
},
{
"name": "C",
"bytes": "2209717"
},
{
"name": "C++",
"bytes": "375267"
},
{
"name": "CSS",
"bytes": "1134648"
},
{
"name": "Dockerfile",
"bytes": "1656"
},
{
"name": "HTML",
"bytes": "306558398"
},
{
"name": "Java",
"bytes": "1465506"
},
{
"name": "JavaScript",
"bytes": "9028509"
},
{
"name": "Jupyter Notebook",
"bytes": "30907"
},
{
"name": "Less",
"bytes": "107003"
},
{
"name": "PHP",
"bytes": "856"
},
{
"name": "PowerShell",
"bytes": "77807"
},
{
"name": "Pug",
"bytes": "2968"
},
{
"name": "Python",
"bytes": "1001861"
},
{
"name": "R",
"bytes": "7390"
},
{
"name": "Roff",
"bytes": "3553"
},
{
"name": "Shell",
"bytes": "206191"
},
{
"name": "Thrift",
"bytes": "80564"
},
{
"name": "XSLT",
"bytes": "4740"
}
],
"symlink_target": ""
} |
from zipfile import ZipFile, ZIP_DEFLATED
from optparse import OptionParser
parser = OptionParser()
## Make options for commandline available through -h
## -f/--files takes a commaseparated list of filenames _without_ paths
parser.add_option("-f", "--files", dest="filename",
help="List of files to compress", metavar="FILE")
## -p/--path takes the path for the supplied files
parser.add_option("-p", "--path", dest="path",
help="Path containing files", metavar="PATH")
## -o/--outpath takes the path where the zip is to be created
parser.add_option("-o", "--outpath", dest="outpath",
help="Outpath", metavar="OUTPATH")
## -z/--zipname takes the filename for the zip file
parser.add_option("-z", "--zipname", dest="zipname",
help="Name for zipfile", metavar="ZIPNAME")
(options, args) = parser.parse_args()
with ZipFile(options.outpath+options.zipname,'w',ZIP_DEFLATED) as z:
for item in options.filename.split(','):
print('Crunching '+item)
z.write(options.path+item,item)
z.close()
print(options.outpath+options.zipname)
| {
"content_hash": "85224165bf46f2f5ee4587968bab3b6e",
"timestamp": "",
"source": "github",
"line_count": 29,
"max_line_length": 71,
"avg_line_length": 38.89655172413793,
"alnum_prop": 0.6578014184397163,
"repo_name": "foag/pyzippr",
"id": "9db8c54505abd1c90b95cb4ba6c9d53c65ef57d0",
"size": "1261",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "PyZippr.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Python",
"bytes": "1261"
}
],
"symlink_target": ""
} |
package com.vmware.vim25;
/**
* @author Steve Jin (http://www.doublecloud.org)
* @version 5.1
*/
public class ArrayOfVirtualMachineCdromInfo {
public VirtualMachineCdromInfo[] VirtualMachineCdromInfo;
public VirtualMachineCdromInfo[] getVirtualMachineCdromInfo() {
return this.VirtualMachineCdromInfo;
}
public VirtualMachineCdromInfo getVirtualMachineCdromInfo(int i) {
return this.VirtualMachineCdromInfo[i];
}
public void setVirtualMachineCdromInfo(VirtualMachineCdromInfo[] VirtualMachineCdromInfo) {
this.VirtualMachineCdromInfo=VirtualMachineCdromInfo;
}
} | {
"content_hash": "646891eb9b4f2e8dcc5f7038ef61fdb0",
"timestamp": "",
"source": "github",
"line_count": 24,
"max_line_length": 93,
"avg_line_length": 24.791666666666668,
"alnum_prop": 0.7915966386554621,
"repo_name": "paksv/vijava",
"id": "1f984e874caad5a8223b13b88dcc6e0cc7359f1f",
"size": "2235",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/com/vmware/vim25/ArrayOfVirtualMachineCdromInfo.java",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Java",
"bytes": "7900718"
}
],
"symlink_target": ""
} |
function request(url, method, body) {
return fetch(`${BASE_URL}/${url}`, {
headers: {
'Content-Type': 'application/json',
},
method,
body: body ? JSON.stringify(body) : undefined,
}).then((res) => {
if (res.json) {
return res.json()
}
return res
})
}
export default request
| {
"content_hash": "4dd9829c7a07682857dea3988e7c764d",
"timestamp": "",
"source": "github",
"line_count": 16,
"max_line_length": 50,
"avg_line_length": 20.0625,
"alnum_prop": 0.5607476635514018,
"repo_name": "thomasthiebaud/lundalogik",
"id": "d0d6177c45934e3476b379cf32e5a4d4aa2fefbc",
"size": "321",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/network/request.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "1061"
},
{
"name": "HTML",
"bytes": "305"
},
{
"name": "JavaScript",
"bytes": "39563"
}
],
"symlink_target": ""
} |
<?php
defined('_JEXEC') or die;
?>
<!DOCTYPE html>
<html lang="<?php echo $this->language; ?>" dir="<?php echo $this->direction; ?>" class='<jdoc:include type="pageclass" />'>
<head>
<jdoc:include type="head" />
<?php $this->loadBlock ('head') ?>
</head>
<body>
<?php $this->loadBlock ('header') ?>
<?php $this->loadBlock ('mainnav') ?>
<?php $this->loadBlock ('spotlight-1') ?>
<?php $this->loadBlock ('mainbody-content-left') ?>
<?php $this->loadBlock ('spotlight-2') ?>
<?php $this->loadBlock ('navhelper') ?>
<?php $this->loadBlock ('footer') ?>
</body>
</html> | {
"content_hash": "e1fdcb62695a01381228511821a58c46",
"timestamp": "",
"source": "github",
"line_count": 34,
"max_line_length": 124,
"avg_line_length": 18.941176470588236,
"alnum_prop": 0.5403726708074534,
"repo_name": "vifprogram/vifprogram.github.io",
"id": "9e6f7457fe8b0bdf83a5ea445aeb46086f446ad3",
"size": "1337",
"binary": false,
"copies": "43",
"ref": "refs/heads/gh-pages",
"path": "blog/templates/t3_blank/tpls/default-content-left.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "11308845"
},
{
"name": "JavaScript",
"bytes": "10978474"
},
{
"name": "PHP",
"bytes": "31179244"
},
{
"name": "Ruby",
"bytes": "25316"
}
],
"symlink_target": ""
} |
namespace GraphQLParser.AST;
/// <summary>
/// AST node for <see cref="ASTNodeKind.Directives"/>.
/// </summary>
public class GraphQLDirectives : ASTListNode<GraphQLDirective>
{
/// <inheritdoc/>
public override ASTNodeKind Kind => ASTNodeKind.Directives;
}
internal sealed class GraphQLDirectivesWithLocation : GraphQLDirectives
{
private GraphQLLocation _location;
public override GraphQLLocation Location
{
get => _location;
set => _location = value;
}
}
| {
"content_hash": "f6db4e2515f00ba59bcec19e0b46588c",
"timestamp": "",
"source": "github",
"line_count": 21,
"max_line_length": 71,
"avg_line_length": 23.857142857142858,
"alnum_prop": 0.7005988023952096,
"repo_name": "graphql-dotnet/parser",
"id": "51a001ecf8f5bfa7ce07d7790f64df04fd9770b2",
"size": "501",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/GraphQLParser/AST/GraphQLDirectives.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "610323"
}
],
"symlink_target": ""
} |
<?php
namespace Brasa\GeneralBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* @ORM\Table(name="gen_cobertura")
* @ORM\Entity(repositoryClass="Brasa\GeneralBundle\Repository\GenCoberturaRepository")
*/
class GenCobertura
{
/**
* @ORM\Id
* @ORM\Column(name="codigo_cobertura_pk", type="integer")
* @ORM\GeneratedValue(strategy="AUTO")
*/
private $codigoCoberturaPk;
/**
* @ORM\Column(name="nombre", type="string", length=80, nullable=true)
*/
private $nombre;
/**
* @ORM\OneToMany(targetEntity="Brasa\TurnoBundle\Entity\TurCliente", mappedBy="coberturaRel")
*/
protected $turClientesCoberturaRel;
/**
* Constructor
*/
public function __construct()
{
$this->turClientesCoberturaRel = new \Doctrine\Common\Collections\ArrayCollection();
}
/**
* Get codigoCoberturaPk
*
* @return integer
*/
public function getCodigoCoberturaPk()
{
return $this->codigoCoberturaPk;
}
/**
* Set nombre
*
* @param string $nombre
*
* @return GenCobertura
*/
public function setNombre($nombre)
{
$this->nombre = $nombre;
return $this;
}
/**
* Get nombre
*
* @return string
*/
public function getNombre()
{
return $this->nombre;
}
/**
* Add turClientesCoberturaRel
*
* @param \Brasa\TurnoBundle\Entity\TurCliente $turClientesCoberturaRel
*
* @return GenCobertura
*/
public function addTurClientesCoberturaRel(\Brasa\TurnoBundle\Entity\TurCliente $turClientesCoberturaRel)
{
$this->turClientesCoberturaRel[] = $turClientesCoberturaRel;
return $this;
}
/**
* Remove turClientesCoberturaRel
*
* @param \Brasa\TurnoBundle\Entity\TurCliente $turClientesCoberturaRel
*/
public function removeTurClientesCoberturaRel(\Brasa\TurnoBundle\Entity\TurCliente $turClientesCoberturaRel)
{
$this->turClientesCoberturaRel->removeElement($turClientesCoberturaRel);
}
/**
* Get turClientesCoberturaRel
*
* @return \Doctrine\Common\Collections\Collection
*/
public function getTurClientesCoberturaRel()
{
return $this->turClientesCoberturaRel;
}
}
| {
"content_hash": "22eb3574a9fb434fbbb751f60a7f3221",
"timestamp": "",
"source": "github",
"line_count": 106,
"max_line_length": 112,
"avg_line_length": 22.141509433962263,
"alnum_prop": 0.6186621218576907,
"repo_name": "wariox3/brasa",
"id": "79aba7f301d5754ad2db103ddda2dda8dac570ee",
"size": "2347",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/Brasa/GeneralBundle/Entity/GenCobertura.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "122817"
},
{
"name": "HTML",
"bytes": "3724591"
},
{
"name": "JavaScript",
"bytes": "382852"
},
{
"name": "PHP",
"bytes": "12584043"
},
{
"name": "Shell",
"bytes": "4440"
},
{
"name": "TSQL",
"bytes": "1403931"
}
],
"symlink_target": ""
} |
shadow
======
| {
"content_hash": "689288b2b58a13b7255b534b661c50e8",
"timestamp": "",
"source": "github",
"line_count": 2,
"max_line_length": 6,
"avg_line_length": 7,
"alnum_prop": 0.42857142857142855,
"repo_name": "queba/shadow",
"id": "e2dd38fdcde5859cdc675f7421a698e7c85e4de4",
"size": "14",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "README.md",
"mode": "33188",
"license": "bsd-3-clause",
"language": [],
"symlink_target": ""
} |
namespace pdalboost {} namespace boost = pdalboost; namespace pdalboost {
namespace asio {
/// Typedef for the typical usage of a signal set.
typedef basic_signal_set<> signal_set;
} // namespace asio
} // namespace pdalboost
#endif // BOOST_ASIO_SIGNAL_SET_HPP
| {
"content_hash": "a65dd16cf8dc1391bcf769257550e5f7",
"timestamp": "",
"source": "github",
"line_count": 10,
"max_line_length": 73,
"avg_line_length": 26.5,
"alnum_prop": 0.7396226415094339,
"repo_name": "verma/PDAL",
"id": "ce57d9d2f477346e02d2ebce2547bd40a6a3e1e9",
"size": "808",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "boost/boost/asio/signal_set.hpp",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "C",
"bytes": "755744"
},
{
"name": "C#",
"bytes": "51165"
},
{
"name": "C++",
"bytes": "58234219"
},
{
"name": "CSS",
"bytes": "65128"
},
{
"name": "JavaScript",
"bytes": "81726"
},
{
"name": "Lasso",
"bytes": "1053782"
},
{
"name": "Perl",
"bytes": "4925"
},
{
"name": "Python",
"bytes": "12600"
},
{
"name": "Shell",
"bytes": "40033"
},
{
"name": "XSLT",
"bytes": "7284"
}
],
"symlink_target": ""
} |
module TopFiveHelper
def first_non_empty value
text = value.select{|r,e| !e.blank?}
return "" if text.empty?
text = text.first[1]
return text
end
end | {
"content_hash": "41bd980bd2603ac2b809a44dcb763eb6",
"timestamp": "",
"source": "github",
"line_count": 11,
"max_line_length": 44,
"avg_line_length": 17.636363636363637,
"alnum_prop": 0.5670103092783505,
"repo_name": "ptolts/dishgo_backend_and_frontend",
"id": "acc543fc02ae98d0e2bdd9d668fa46c74118ef71",
"size": "194",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/helpers/top_five_helper.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "321441"
},
{
"name": "CoffeeScript",
"bytes": "229"
},
{
"name": "JavaScript",
"bytes": "781789"
},
{
"name": "Ruby",
"bytes": "284903"
},
{
"name": "Shell",
"bytes": "877"
}
],
"symlink_target": ""
} |
interface TSBaseType {
name: string;
type?: string;
raw?: string;
required?: boolean;
}
type TSArgType = TSType;
type TSCombinationType = TSBaseType & {
name: 'union' | 'intersection';
elements: TSType[];
};
type TSFuncSigType = TSBaseType & {
name: 'signature';
type: 'function';
signature: {
arguments: TSArgType[];
return: TSType;
};
};
type TSObjectSigType = TSBaseType & {
name: 'signature';
type: 'object';
signature: {
properties: {
key: string;
value: TSType;
}[];
};
};
type TSScalarType = TSBaseType & {
name: 'any' | 'boolean' | 'number' | 'void' | 'string' | 'symbol';
};
type TSArrayType = TSBaseType & {
name: 'Array';
elements: TSType[];
};
export type TSSigType = TSObjectSigType | TSFuncSigType;
export type TSType = TSScalarType | TSCombinationType | TSSigType | TSArrayType;
| {
"content_hash": "9672cc1d9c7fd4442625b4b3a85010d6",
"timestamp": "",
"source": "github",
"line_count": 46,
"max_line_length": 80,
"avg_line_length": 18.782608695652176,
"alnum_prop": 0.6388888888888888,
"repo_name": "storybooks/react-storybook",
"id": "dee016d767348398c6af1ce65e481abd14083edd",
"size": "864",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "addons/docs/src/lib/convert/typescript/types.ts",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "9157"
},
{
"name": "HTML",
"bytes": "5560"
},
{
"name": "JavaScript",
"bytes": "325573"
},
{
"name": "Shell",
"bytes": "7563"
},
{
"name": "TypeScript",
"bytes": "2617"
}
],
"symlink_target": ""
} |
<!DOCTYPE html>
<html>
<head>
<!-- HTML meta refresh URL redirection -->
<meta http-equiv="refresh"
content="0; url=/intranet/login.jsf">
</head>
<body>
</body>
</html> | {
"content_hash": "bdd5169edfe4a6ccb64743496e3a5e8d",
"timestamp": "",
"source": "github",
"line_count": 11,
"max_line_length": 47,
"avg_line_length": 17.90909090909091,
"alnum_prop": 0.5634517766497462,
"repo_name": "regianemsms/pib",
"id": "943146678617210d9036cb0ac924be17a736ef8c",
"size": "197",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/main/resources/META-INF/resources/index.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "3202"
},
{
"name": "HTML",
"bytes": "78132"
},
{
"name": "Java",
"bytes": "132213"
},
{
"name": "JavaScript",
"bytes": "12321"
},
{
"name": "Shell",
"bytes": "140"
}
],
"symlink_target": ""
} |
/* ###
* IP: GHIDRA
* REVIEWED: YES
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package ghidra.app.merge.util;
import ghidra.program.model.address.AddressSet;
import ghidra.program.model.address.AddressSetView;
/**
* <code>MergeUtilities</code> provides generic static methods for use by the
* multi-user program merge managers.
*/
public class MergeUtilities {
/**
* Adds addresses to autoChanges where there are changes in the myDiffs set,
* but none in the latestDiffs set.
* Adds addresses to conflictChanges where there are changes in the myDiffs
* set and also some changes in the latestDiffs set.
* @param latestDiffs the address set of the changes in LATEST.
* @param myDiffs the address set of the changes in MY.
* @param autoChanges address set for the myDiffs non-conflicting changes.
* @param conflictChanges address set for the myDiffs conflicting changes
*/
public static void adjustSets(AddressSetView latestDiffs, AddressSetView myDiffs,
AddressSet autoChanges, AddressSet conflictChanges) {
AddressSet diffAutoChanges = new AddressSet(myDiffs);
diffAutoChanges.delete(latestDiffs);
AddressSet diffConflictChanges = new AddressSet(myDiffs);
diffConflictChanges = diffConflictChanges.intersect(latestDiffs);
autoChanges.add(diffAutoChanges);
conflictChanges.add(diffConflictChanges);
}
// /** Creates an address set that contains the entire code units within the
// * listing that are part of the address set that is passed in.
// * <br>Note: This method will not remove any addresses from the address set even
// * if they are not part of code units in the listing.
// * @param addrSet The original address set that may contain portions of
// * code units.
// * @param listing the program listing which has the code units.
// * @return the address set that contains addresses for whole code units.
// */
// public static AddressSet getCodeUnitSet(AddressSetView addrSet, Listing listing) {
// AddressSet addrs = new AddressSet(addrSet);
// AddressRangeIterator iter = addrSet.getAddressRanges();
// while (iter.hasNext()) {
// AddressRange range = iter.next();
// Address rangeMin = range.getMinAddress();
// Address rangeMax = range.getMaxAddress();
// CodeUnit minCu = listing.getCodeUnitContaining(rangeMin);
// if (minCu != null) {
// Address minCuMinAddr = minCu.getMinAddress();
// if (minCuMinAddr.compareTo(rangeMin) != 0) {
// addrs.addRange(minCuMinAddr, minCu.getMaxAddress());
// }
// }
// CodeUnit maxCu = listing.getCodeUnitContaining(rangeMax);
// if (maxCu != null) {
// Address maxCuMaxAddr = maxCu.getMaxAddress();
// if (maxCuMaxAddr.compareTo(rangeMax) != 0) {
// addrs.addRange(maxCu.getMinAddress(), maxCuMaxAddr);
// }
// }
// }
// return addrs;
// }
//
// /**
// * Returns whether or not the two indicated objects are equal. It allows
// * either or both of the specified objects to be null.
// * @param o1 the first object or null
// * @param o2 the second object or null
// * @return true if the objects are equal.
// */
// public static boolean same(Object o1, Object o2) {
// if (o1 == null) {
// return (o2 == null);
// }
// else {
// return o1.equals(o2);
// }
// }
//
// /**
// * Returns the signed hex string representing the int value.
// * Positive values are represented beginning with 0x. (i.e. value of 12 would be 0xc)
// * Negative values are represented beginning with -0x. (i.e. value of -12 would be -0xc)
// * @param value the value
// * @return the signed hex string
// */
// public static String toSignedHexString(int value) {
// return (value >= 0 ? "0x"+Integer.toHexString(value) :
// "-0x"+Integer.toHexString(-value) );
// }
//
// /**
// * Returns the signed hex string representing the long value.
// * Positive values are represented beginning with 0x. (i.e. value of 12 would be 0xc)
// * Negative values are represented beginning with -0x. (i.e. value of -12 would be -0xc)
// * @param value the value
// * @return the signed hex string
// */
// public static String toSignedHexString(long value) {
// return (value >= 0 ? "0x"+Long.toHexString(value) :
// "-0x"+Long.toHexString(-value) );
// }
}
| {
"content_hash": "68360616cd359a1eced527cf1da0a3d7",
"timestamp": "",
"source": "github",
"line_count": 121,
"max_line_length": 94,
"avg_line_length": 39.77685950413223,
"alnum_prop": 0.6910450862248078,
"repo_name": "NationalSecurityAgency/ghidra",
"id": "ae76a839865bf930447cf54ef717c3a5527793d8",
"size": "4813",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Ghidra/Features/Base/src/main/java/ghidra/app/merge/util/MergeUtilities.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Assembly",
"bytes": "77536"
},
{
"name": "Batchfile",
"bytes": "21610"
},
{
"name": "C",
"bytes": "1132868"
},
{
"name": "C++",
"bytes": "7334484"
},
{
"name": "CSS",
"bytes": "75788"
},
{
"name": "GAP",
"bytes": "102771"
},
{
"name": "GDB",
"bytes": "3094"
},
{
"name": "HTML",
"bytes": "4121163"
},
{
"name": "Hack",
"bytes": "31483"
},
{
"name": "Haskell",
"bytes": "453"
},
{
"name": "Java",
"bytes": "88669329"
},
{
"name": "JavaScript",
"bytes": "1109"
},
{
"name": "Lex",
"bytes": "22193"
},
{
"name": "Makefile",
"bytes": "15883"
},
{
"name": "Objective-C",
"bytes": "23937"
},
{
"name": "Pawn",
"bytes": "82"
},
{
"name": "Python",
"bytes": "587415"
},
{
"name": "Shell",
"bytes": "234945"
},
{
"name": "TeX",
"bytes": "54049"
},
{
"name": "XSLT",
"bytes": "15056"
},
{
"name": "Xtend",
"bytes": "115955"
},
{
"name": "Yacc",
"bytes": "127754"
}
],
"symlink_target": ""
} |
/**
* @file parent.h
* @author Simone Girardi
* @date 27 jun 2016.
* @version 1.0
*/
#ifndef parent_h
#define parent_h
#include "mylib.h"
#include "utils.h"
/**
* @brief This function is called from the parent process after it created the childs with fork()
*
* Initially the parent wait (on semaphore: sem_parent 1) that all his childs are ready. So when all chids are ready, for each operations,
* it read the id number of the child to which to perform the operation. If the is id number is "-1" the parent search for the first child
* that is ready to perform the next operation. (1) Now if the slected child is ready to read the operation, the parent write the next operation
* to do for the current selected child into the struct current_operation (see current_operation in utils), unclok the selected child which is
* waiting on sem_wait_data and wait that the selected child has read the data to perform the operation. Finally the parent can pass to
* the next operation to perform. If, at point (1), the selected child isn't ready to read the operation, then the parent calls the
* busy_child_routine, and it continue as point (1)
* When the parent finishes to send all operation to his childs, it wait that all operations are performed and then kill the current selected
* child
*
* @param my_semaphores array of semaphores
* @param n_operations number of operations to perform
* @param NPROC the number of processes
* @param my_semaphores the array of semaphores
* @param operations a strcut that contains all operations to perform
* @param current_operation a struct pointer for get the current operation
* @param current_result a struct pointer for save the result of current operation
* @param child_isFree array for check which child process is free
* @see busy_child_routine
* @see child
* @return results the array of results of operations performed
*/
float *my_parent(int n_operations, int NPROC, struct operation *operations, int my_semaphores[], int msqid);
/**
* @brief Called if the id number read from parent is "-1".
*
* The parent doesn't return from this function until it has not found a free child
*
* @param NPROC the number of processes
* @param child_isFree array for check which child process is free
* @see my_parent
* @return child_id id of the first free child
*/
int get_first_free_child(int NPROC, bool child_isFree[]);
/**
* @brief This function is a routing that is called from the parent when it wants receive the result of an operation from a specific child, or it
* wants terminate a specific child.
*
* If the selected child isn't ready to read the data for the new operation, then the parent wait the
* selected child complete to compute the operation and then it request for the result. When the result is ready, the parent read it and save the
* result in current_result struct.
*
* @param child_id
* @param current_result
* @see my_parent
* @return current_result->val
*/
float busy_child_routine(int child_id, struct result *current_result);
/**
* @brief This function is a routing that is called from the parent when it wants receive the result of an operation from a specific child, or it
* wants terminate a specific child.
*
* If the selected child isn't ready to read the data for the new operation, then the parent wait the
* selected child complete to compute the operation and then it request for the result. When the result is ready, the parent read it and save the
* result in current_result struct.
*
* @param child_id
* @see my_parent
* @return void
*/
void busy_child_routine_2(int child_id);
/**
* @ This function is used to print on STDOUT the current status of parent
*
* This function allows us to see how the parent manage his childs
*
* @param info the information to print on STDOUT
* @param child_id the id of current managed child process
* @see print
* @return void
*/
void print_parent_info(const char *info, int child_id);
/**
* @brief This function is used to print the results of operations on STDOUT
*
* When all operations have been completed and all childs have been terminated, the parent will print the results on STDOUT
*
* @param resutls the array of results
* @param n_operations the length of array results
* @see print
* @return void
*/
void print_results(float resutls[], int n_operations);
#endif /* parent_h */
| {
"content_hash": "e3bf4f0b8b1982fc469ecdfa5a463f8e",
"timestamp": "",
"source": "github",
"line_count": 108,
"max_line_length": 146,
"avg_line_length": 40.7037037037037,
"alnum_prop": 0.7397634212920837,
"repo_name": "SimoGira/ipc",
"id": "908eef5e18f26056cd139d95754c30b57680f2f9",
"size": "4396",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "varie verisioni elaborato ipc/elaborato ipc con code e semafori/headers/parent.h",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "C",
"bytes": "293500"
},
{
"name": "Makefile",
"bytes": "5058"
},
{
"name": "Shell",
"bytes": "4614"
}
],
"symlink_target": ""
} |
<?php
namespace Magento\Framework\Search\Adapter\Mysql\Aggregation\Builder;
use Magento\Framework\DB\Ddl\Table;
use Magento\Framework\DB\Select;
use Magento\Framework\Search\Adapter\Mysql\Aggregation\DataProviderInterface;
use Magento\Framework\Search\Request\BucketInterface as RequestBucketInterface;
class Term implements BucketInterface
{
/**
* @var Metrics
*/
private $metricsBuilder;
/**
* @param Metrics $metricsBuilder
*/
public function __construct(Metrics $metricsBuilder)
{
$this->metricsBuilder = $metricsBuilder;
}
/**
* {@inheritdoc}
*/
public function build(
DataProviderInterface $dataProvider,
array $dimensions,
RequestBucketInterface $bucket,
Table $entityIdsTable
) {
$metrics = $this->metricsBuilder->build($bucket);
$select = $dataProvider->getDataSet($bucket, $dimensions, $entityIdsTable);
$select->columns($metrics);
$select->group(RequestBucketInterface::FIELD_VALUE);
return $dataProvider->execute($select);
}
}
| {
"content_hash": "f26cb315df757a86403fd5d182ea3921",
"timestamp": "",
"source": "github",
"line_count": 42,
"max_line_length": 83,
"avg_line_length": 26.095238095238095,
"alnum_prop": 0.6742700729927007,
"repo_name": "enettolima/magento-training",
"id": "521393b7bb0d465578cf395669cd8a7e0887edd6",
"size": "1194",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "magento2ce/lib/internal/Magento/Framework/Search/Adapter/Mysql/Aggregation/Builder/Term.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ApacheConf",
"bytes": "22648"
},
{
"name": "CSS",
"bytes": "3382928"
},
{
"name": "HTML",
"bytes": "8749335"
},
{
"name": "JavaScript",
"bytes": "7355635"
},
{
"name": "PHP",
"bytes": "58607662"
},
{
"name": "Perl",
"bytes": "10258"
},
{
"name": "Shell",
"bytes": "41887"
},
{
"name": "XSLT",
"bytes": "19889"
}
],
"symlink_target": ""
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
//first
//second
//third
//fourth
//fifth
//tenth
//thirteenth
namespace NaturalLanguageDateTime.NLDT
{
class OrdinalNumbers
{
public static string[] m_OrdinalNumbers = new string[] { "first", "second", "third", "fourth", "fifth", "sixth", "seventh", "eight", "ninenth", "tenth"};
public static bool IsA(string ordinalNumber)
{
return m_OrdinalNumbers.Contains(ordinalNumber);
}
}
}
| {
"content_hash": "2545224f82a5f4851a579d24c996dd13",
"timestamp": "",
"source": "github",
"line_count": 24,
"max_line_length": 161,
"avg_line_length": 22.041666666666668,
"alnum_prop": 0.6521739130434783,
"repo_name": "spookiecookie/NaturalLanguageDateTime",
"id": "9aa42aacb89dfe32ba8813269e0bbaaf0d165093",
"size": "531",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "NaturalLanguageDateTime/OrdinalNumbers.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "26412"
}
],
"symlink_target": ""
} |
```bash
if [[ $getstatus == "Pending" ]]; then
echo "pending... please wait"
elif [[ $getstatus == "Success" ]]; then
echo "deployed"
elif [[ $getstatus == "Failed" ]]; then
echo "deployment failed, please check SSM logs"
exit 1
fi;
```
# FOR LOOP CLAUSE
* with timer and breaks
```bash
for i in {1..90}; do
if [[ $getstatus == "Pending" ]]; then
echo "pending... please wait"
sleep 10
elif [[ $getstatus == "Success" ]]; then
echo "deployed"
break
elif [[ $getstatus == "Failed" ]]; then
echo "deployment failed, please check SSM logs"
exit 1
fi;
done;
```
Sometimes the above doesnt work. Below might be an alternative.
```bash
count=10
for i in $(seq $count); do
echo test
done
```
# Print Contents of File
* `cat <filename>`: prints whole file contents
* `head -10 <filename>`: prints first 10 lines of file
* `tail -10 <filename>`: prints last 10 lines of file
* `grep -R "<string>" "<filename>"`: prints contents in file that contains <string>
# Delete
* `rm -rf /path/dir`: delete directory and contents
# File Manipulation
* `touch Dockerfile`: create new file if not exist
* `echo FROM python:3.7 > Dockerfile`: add echoed line to new file, replace if exist
* `echo FROM python:3.7 >> Dockerfile`: add echoed line to existing file as new line
## Zip Files
* `zip --encrypt secure.zip file1 file2`: enter & it will prompt u for password
* `zip --encrypt file.zip -r folder`: for zipping folders
## DATETIME
* `$(date)`: display datetime
## DU
**Disk Usage**
* `du -sh .git`: check total file size
* `du -h`: file sizes of all top level directories
* `du -csh`: show file size in MB
* ncdu: NCurses Disk Usage, a very easy to use terminal storage query. After scan, can enter within folders and out to see breakdown
* apt install ncdu
* ncdu /foldername
## MEMORY
**Memory Usage**
* `free`: show free & used memory
* `free -t -g`: show total & also in gigabytes
* `watch -n 1 free -m`: check memory every 1 sec, in Mb
* `free -m | grep "Mem" | awk '{ print $3 }'`: output only used memory
* `free -m | grep "Mem" | awk '{ print $4 }'`: output only free memory
* `top`: check cpu & memory for each process [link](https://linuxaria.com/howto/understanding-the-top-command-on-linux)
* `top -p PID`: check for specific PID
* `top -o %MEM`: sort by memory usage
* `top | grep python`: check by process name
* in Live View
* `SHIFT + e`: change size from Kb to Mb to Gb etc...
* `SHIFT + l`: search & highlight process name
## SCP
**Secure Copy**
* `scp /path/to/file username@ipaddress`: copy paste files to remote server. need enter pw.
* `scp -r directory username@ipaddress`: copy paste directory to server
## SSHPASS
**Sending Shell Commands Through SSH**
* `sshpass -p $password ssh ubuntu@ipaddress`: ssh to server
* `sshpass -p $password scp -r scene-understanding ubuntu@ipaddress`: copy
* multiple commands
```bash
sshpass -p $password ssh ubuntu@$ip <<EOF
docker rm -f $module
wait
docker build -t $module $module
wait
yes | docker image prune
wait
docker run -d -p 80:$port --log-opt max-size=5m --log-opt max-file=5 --restart always --name $module $module
docker ps
EOF
```
## JQ
**JSON Parser**
* `jq -r`: return value w/o double quotes
* `cat /tmp/curl_body | jq '.'`: prints entire json file from curl_body
* `id=$(echo $result | jq -r .Command.CommandId)`: query from a json variable, and save output as variable
* `mask=$(cat /tmp/curl_body | jq '.FACEMASK_DETECTION[0]')`: get 1st array within the value of `FACEMASK_DETECTION`
* `mask=$(cat /tmp/curl_body | jq '.FACEMASK_DETECTION[0] .boundingPoly .normalizedVertices | length')`: get length of array
* `cat bandit.json | jq '[.results [] | select(.issue_severity=="MEDIUM")]'`: filter
* `cat bandit.json | jq '[.results [] | select(.issue_severity=="MEDIUM")]' | jq '. | length'`: filter and get length of array
## SED
**Stream Editor (Find/Replace)**
* `-i` = in-place (i.e. save back to the original file)
* `s` = the substitute/replace command
* `g` = global (i.e. replace all and not just the first occurrence)
* `sed -i -e 's/original_string/replacement_string/g' file/path/location`
* `sed -i "/CMD/d" $DOCKERFILE`: remove line if contain substring
## REGEX
Save matched regex as a variable
```bash
# FROM python:3.8-slim
first_line=$(head -n 1 $DOCKERFILE)
subtext=$(egrep -o "python.+[0-9]" <<<$first_line)
# python:3.8
```
## CURL
**Client URL**
Sends POST request from JSON file
```bash
curl --header "Content-Type:application/json"
--data @./facedetection/sample_json_request.json
--request POST http://docker:5003/api
```
Gets only HTTP status code and dump output to `/tml/curl_body`
```bash
statuscode=$(curl -s -o /tmp/curl_body -w "%{http_code}" http://localhost:5001)
echo $statuscode
```
Get HTTP status code without saving a hardcopy
```bash
content=$(curl -s -w "%{http_code}" http://localhost:$port)
statuscode="${content:(-3)}"
```
Sends Post request from JSON file, and exit if not status 200
```bash
content=$(curl -s -w "%{http_code}" \
--header "Content-Type:application/json" \
--data @./facedetection/sample_json_request.json \
--request POST http://docker:5003/api)
statuscode="${content:(-3)}" # or {$content: -3}
response="${content%???}"
echo $response
echo "statuscode is $statuscode"
if [[ $statuscode != "200" ]]
then exit 1
fi
```
## Code Snippets
### Login SSH
```bash
#!/bin/bash
echo
"
server-1 = 1
server-2 = 2
server-3 = 3
server-4 = 4
"
read -p 'select server code:' selection
password='yourpassword'
if [[ $selection == '1' ]]
then sshpass -p $password ssh ubuntu@18.1.70.9
elif [[ $selection == '2' ]]
then sshpass -p $password ssh ubuntu@18.1.20.75
elif [[ $selection == '3' ]]
then sshpass -p $password ssh ubuntu@52.2.19.40
elif [[ $selection == '4' ]]
then sshpass -p $password ssh ubuntu@18.1.07.14
fi
```
### Update Docker
```bash
#!/bin/bash
$module=facedetection
# remove existing container if any
docker rm -f $module
wait
# rebuild image
docker build -t $module $module
wait
# remove dangling image
docker image prune
wait
# run container
docker run -d -p 80:5003 --log-opt max-size=5m --log-opt max-file=5 --restart always --name $module $module
```
| {
"content_hash": "6b35fa7700d3bbe88595525cfd1ab2e8",
"timestamp": "",
"source": "github",
"line_count": 250,
"max_line_length": 133,
"avg_line_length": 25.464,
"alnum_prop": 0.6545711592836946,
"repo_name": "mapattacker/cheatsheets",
"id": "46c3092763fb191ca0a36151b9af36fab900d498",
"size": "6392",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "bash.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "2620"
},
{
"name": "HTML",
"bytes": "5243"
},
{
"name": "JavaScript",
"bytes": "52428"
},
{
"name": "Jupyter Notebook",
"bytes": "4327532"
},
{
"name": "PHP",
"bytes": "9881"
},
{
"name": "Python",
"bytes": "175058"
},
{
"name": "R",
"bytes": "1348"
},
{
"name": "Shell",
"bytes": "956"
}
],
"symlink_target": ""
} |
package org.apache.camel.processor.onexception;
import java.io.IOException;
import java.net.ConnectException;
import org.apache.camel.ContextTestSupport;
import org.apache.camel.builder.RouteBuilder;
import org.junit.Test;
/**
* @version
*/
public class OnExceptionsPerRouteTest extends ContextTestSupport {
@Test
public void testOnExceptionsPerRouteDamn() throws Exception {
getMockEndpoint("mock:error").expectedBodiesReceived("Damn");
template.sendBody("direct:start", "Damn");
assertMockEndpointsSatisfied();
}
@Test
public void testOnExceptionsPerRouteConnect() throws Exception {
getMockEndpoint("mock:error").expectedBodiesReceived("Connect");
template.sendBody("direct:start", "Connect");
assertMockEndpointsSatisfied();
}
@Override
protected RouteBuilder createRouteBuilder() throws Exception {
return new RouteBuilder() {
@Override
@SuppressWarnings("unchecked")
public void configure() throws Exception {
from("direct:start")
.onException(IllegalArgumentException.class, IOException.class)
.handled(true)
.to("mock:error")
.end()
.choice()
.when(body().contains("Damn")).throwException(new IllegalArgumentException("Damn"))
.when(body().contains("Connect")).throwException(new ConnectException("Cannot connect"))
.end();
}
};
}
}
| {
"content_hash": "7f472eba4f47e6fcc1d4f70a5107b76b",
"timestamp": "",
"source": "github",
"line_count": 52,
"max_line_length": 112,
"avg_line_length": 30.673076923076923,
"alnum_prop": 0.6175548589341693,
"repo_name": "sverkera/camel",
"id": "aba5ca3f3e5c21b514ba3a5bcd620649cbdecf2f",
"size": "2398",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "camel-core/src/test/java/org/apache/camel/processor/onexception/OnExceptionsPerRouteTest.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Apex",
"bytes": "6519"
},
{
"name": "Batchfile",
"bytes": "1518"
},
{
"name": "CSS",
"bytes": "30373"
},
{
"name": "Elm",
"bytes": "10852"
},
{
"name": "FreeMarker",
"bytes": "11410"
},
{
"name": "Groovy",
"bytes": "44835"
},
{
"name": "HTML",
"bytes": "903016"
},
{
"name": "Java",
"bytes": "74372940"
},
{
"name": "JavaScript",
"bytes": "90399"
},
{
"name": "Makefile",
"bytes": "513"
},
{
"name": "Python",
"bytes": "36"
},
{
"name": "Ruby",
"bytes": "4802"
},
{
"name": "Scala",
"bytes": "323982"
},
{
"name": "Shell",
"bytes": "17120"
},
{
"name": "Tcl",
"bytes": "4974"
},
{
"name": "Thrift",
"bytes": "6979"
},
{
"name": "XQuery",
"bytes": "546"
},
{
"name": "XSLT",
"bytes": "288715"
}
],
"symlink_target": ""
} |
<?php
namespace Google\Service\CloudKMS\Resource;
use Google\Service\CloudKMS\AsymmetricDecryptRequest;
use Google\Service\CloudKMS\AsymmetricDecryptResponse;
use Google\Service\CloudKMS\AsymmetricSignRequest;
use Google\Service\CloudKMS\AsymmetricSignResponse;
use Google\Service\CloudKMS\CryptoKeyVersion;
use Google\Service\CloudKMS\DestroyCryptoKeyVersionRequest;
use Google\Service\CloudKMS\ImportCryptoKeyVersionRequest;
use Google\Service\CloudKMS\ListCryptoKeyVersionsResponse;
use Google\Service\CloudKMS\MacSignRequest;
use Google\Service\CloudKMS\MacSignResponse;
use Google\Service\CloudKMS\MacVerifyRequest;
use Google\Service\CloudKMS\MacVerifyResponse;
use Google\Service\CloudKMS\PublicKey;
use Google\Service\CloudKMS\RestoreCryptoKeyVersionRequest;
/**
* The "cryptoKeyVersions" collection of methods.
* Typical usage is:
* <code>
* $cloudkmsService = new Google\Service\CloudKMS(...);
* $cryptoKeyVersions = $cloudkmsService->cryptoKeyVersions;
* </code>
*/
class ProjectsLocationsKeyRingsCryptoKeysCryptoKeyVersions extends \Google\Service\Resource
{
/**
* Decrypts data that was encrypted with a public key retrieved from
* GetPublicKey corresponding to a CryptoKeyVersion with CryptoKey.purpose
* ASYMMETRIC_DECRYPT. (cryptoKeyVersions.asymmetricDecrypt)
*
* @param string $name Required. The resource name of the CryptoKeyVersion to
* use for decryption.
* @param AsymmetricDecryptRequest $postBody
* @param array $optParams Optional parameters.
* @return AsymmetricDecryptResponse
*/
public function asymmetricDecrypt($name, AsymmetricDecryptRequest $postBody, $optParams = [])
{
$params = ['name' => $name, 'postBody' => $postBody];
$params = array_merge($params, $optParams);
return $this->call('asymmetricDecrypt', [$params], AsymmetricDecryptResponse::class);
}
/**
* Signs data using a CryptoKeyVersion with CryptoKey.purpose ASYMMETRIC_SIGN,
* producing a signature that can be verified with the public key retrieved from
* GetPublicKey. (cryptoKeyVersions.asymmetricSign)
*
* @param string $name Required. The resource name of the CryptoKeyVersion to
* use for signing.
* @param AsymmetricSignRequest $postBody
* @param array $optParams Optional parameters.
* @return AsymmetricSignResponse
*/
public function asymmetricSign($name, AsymmetricSignRequest $postBody, $optParams = [])
{
$params = ['name' => $name, 'postBody' => $postBody];
$params = array_merge($params, $optParams);
return $this->call('asymmetricSign', [$params], AsymmetricSignResponse::class);
}
/**
* Create a new CryptoKeyVersion in a CryptoKey. The server will assign the next
* sequential id. If unset, state will be set to ENABLED.
* (cryptoKeyVersions.create)
*
* @param string $parent Required. The name of the CryptoKey associated with the
* CryptoKeyVersions.
* @param CryptoKeyVersion $postBody
* @param array $optParams Optional parameters.
* @return CryptoKeyVersion
*/
public function create($parent, CryptoKeyVersion $postBody, $optParams = [])
{
$params = ['parent' => $parent, 'postBody' => $postBody];
$params = array_merge($params, $optParams);
return $this->call('create', [$params], CryptoKeyVersion::class);
}
/**
* Schedule a CryptoKeyVersion for destruction. Upon calling this method,
* CryptoKeyVersion.state will be set to DESTROY_SCHEDULED, and destroy_time
* will be set to the time destroy_scheduled_duration in the future. At that
* time, the state will automatically change to DESTROYED, and the key material
* will be irrevocably destroyed. Before the destroy_time is reached,
* RestoreCryptoKeyVersion may be called to reverse the process.
* (cryptoKeyVersions.destroy)
*
* @param string $name Required. The resource name of the CryptoKeyVersion to
* destroy.
* @param DestroyCryptoKeyVersionRequest $postBody
* @param array $optParams Optional parameters.
* @return CryptoKeyVersion
*/
public function destroy($name, DestroyCryptoKeyVersionRequest $postBody, $optParams = [])
{
$params = ['name' => $name, 'postBody' => $postBody];
$params = array_merge($params, $optParams);
return $this->call('destroy', [$params], CryptoKeyVersion::class);
}
/**
* Returns metadata for a given CryptoKeyVersion. (cryptoKeyVersions.get)
*
* @param string $name Required. The name of the CryptoKeyVersion to get.
* @param array $optParams Optional parameters.
* @return CryptoKeyVersion
*/
public function get($name, $optParams = [])
{
$params = ['name' => $name];
$params = array_merge($params, $optParams);
return $this->call('get', [$params], CryptoKeyVersion::class);
}
/**
* Returns the public key for the given CryptoKeyVersion. The CryptoKey.purpose
* must be ASYMMETRIC_SIGN or ASYMMETRIC_DECRYPT.
* (cryptoKeyVersions.getPublicKey)
*
* @param string $name Required. The name of the CryptoKeyVersion public key to
* get.
* @param array $optParams Optional parameters.
* @return PublicKey
*/
public function getPublicKey($name, $optParams = [])
{
$params = ['name' => $name];
$params = array_merge($params, $optParams);
return $this->call('getPublicKey', [$params], PublicKey::class);
}
/**
* Import wrapped key material into a CryptoKeyVersion. All requests must
* specify a CryptoKey. If a CryptoKeyVersion is additionally specified in the
* request, key material will be reimported into that version. Otherwise, a new
* version will be created, and will be assigned the next sequential id within
* the CryptoKey. (cryptoKeyVersions.import)
*
* @param string $parent Required. The name of the CryptoKey to be imported
* into. The create permission is only required on this key when creating a new
* CryptoKeyVersion.
* @param ImportCryptoKeyVersionRequest $postBody
* @param array $optParams Optional parameters.
* @return CryptoKeyVersion
*/
public function import($parent, ImportCryptoKeyVersionRequest $postBody, $optParams = [])
{
$params = ['parent' => $parent, 'postBody' => $postBody];
$params = array_merge($params, $optParams);
return $this->call('import', [$params], CryptoKeyVersion::class);
}
/**
* Lists CryptoKeyVersions.
* (cryptoKeyVersions.listProjectsLocationsKeyRingsCryptoKeysCryptoKeyVersions)
*
* @param string $parent Required. The resource name of the CryptoKey to list,
* in the format `projects/locations/keyRings/cryptoKeys`.
* @param array $optParams Optional parameters.
*
* @opt_param string filter Optional. Only include resources that match the
* filter in the response. For more information, see [Sorting and filtering list
* results](https://cloud.google.com/kms/docs/sorting-and-filtering).
* @opt_param string orderBy Optional. Specify how the results should be sorted.
* If not specified, the results will be sorted in the default order. For more
* information, see [Sorting and filtering list
* results](https://cloud.google.com/kms/docs/sorting-and-filtering).
* @opt_param int pageSize Optional. Optional limit on the number of
* CryptoKeyVersions to include in the response. Further CryptoKeyVersions can
* subsequently be obtained by including the
* ListCryptoKeyVersionsResponse.next_page_token in a subsequent request. If
* unspecified, the server will pick an appropriate default.
* @opt_param string pageToken Optional. Optional pagination token, returned
* earlier via ListCryptoKeyVersionsResponse.next_page_token.
* @opt_param string view The fields to include in the response.
* @return ListCryptoKeyVersionsResponse
*/
public function listProjectsLocationsKeyRingsCryptoKeysCryptoKeyVersions($parent, $optParams = [])
{
$params = ['parent' => $parent];
$params = array_merge($params, $optParams);
return $this->call('list', [$params], ListCryptoKeyVersionsResponse::class);
}
/**
* Signs data using a CryptoKeyVersion with CryptoKey.purpose MAC, producing a
* tag that can be verified by another source with the same key.
* (cryptoKeyVersions.macSign)
*
* @param string $name Required. The resource name of the CryptoKeyVersion to
* use for signing.
* @param MacSignRequest $postBody
* @param array $optParams Optional parameters.
* @return MacSignResponse
*/
public function macSign($name, MacSignRequest $postBody, $optParams = [])
{
$params = ['name' => $name, 'postBody' => $postBody];
$params = array_merge($params, $optParams);
return $this->call('macSign', [$params], MacSignResponse::class);
}
/**
* Verifies MAC tag using a CryptoKeyVersion with CryptoKey.purpose MAC, and
* returns a response that indicates whether or not the verification was
* successful. (cryptoKeyVersions.macVerify)
*
* @param string $name Required. The resource name of the CryptoKeyVersion to
* use for verification.
* @param MacVerifyRequest $postBody
* @param array $optParams Optional parameters.
* @return MacVerifyResponse
*/
public function macVerify($name, MacVerifyRequest $postBody, $optParams = [])
{
$params = ['name' => $name, 'postBody' => $postBody];
$params = array_merge($params, $optParams);
return $this->call('macVerify', [$params], MacVerifyResponse::class);
}
/**
* Update a CryptoKeyVersion's metadata. state may be changed between ENABLED
* and DISABLED using this method. See DestroyCryptoKeyVersion and
* RestoreCryptoKeyVersion to move between other states.
* (cryptoKeyVersions.patch)
*
* @param string $name Output only. The resource name for this CryptoKeyVersion
* in the format `projects/locations/keyRings/cryptoKeys/cryptoKeyVersions`.
* @param CryptoKeyVersion $postBody
* @param array $optParams Optional parameters.
*
* @opt_param string updateMask Required. List of fields to be updated in this
* request.
* @return CryptoKeyVersion
*/
public function patch($name, CryptoKeyVersion $postBody, $optParams = [])
{
$params = ['name' => $name, 'postBody' => $postBody];
$params = array_merge($params, $optParams);
return $this->call('patch', [$params], CryptoKeyVersion::class);
}
/**
* Restore a CryptoKeyVersion in the DESTROY_SCHEDULED state. Upon restoration
* of the CryptoKeyVersion, state will be set to DISABLED, and destroy_time will
* be cleared. (cryptoKeyVersions.restore)
*
* @param string $name Required. The resource name of the CryptoKeyVersion to
* restore.
* @param RestoreCryptoKeyVersionRequest $postBody
* @param array $optParams Optional parameters.
* @return CryptoKeyVersion
*/
public function restore($name, RestoreCryptoKeyVersionRequest $postBody, $optParams = [])
{
$params = ['name' => $name, 'postBody' => $postBody];
$params = array_merge($params, $optParams);
return $this->call('restore', [$params], CryptoKeyVersion::class);
}
}
// Adding a class alias for backwards compatibility with the previous class name.
class_alias(ProjectsLocationsKeyRingsCryptoKeysCryptoKeyVersions::class, 'Google_Service_CloudKMS_Resource_ProjectsLocationsKeyRingsCryptoKeysCryptoKeyVersions');
| {
"content_hash": "d5d06d9fc62aaab07650b3a990aee58a",
"timestamp": "",
"source": "github",
"line_count": 258,
"max_line_length": 162,
"avg_line_length": 43.71705426356589,
"alnum_prop": 0.7245323166947425,
"repo_name": "googleapis/google-api-php-client-services",
"id": "6051fe5c54f4dcf89107cc6c5000e96f8d98e0bd",
"size": "11869",
"binary": false,
"copies": "6",
"ref": "refs/heads/main",
"path": "src/CloudKMS/Resource/ProjectsLocationsKeyRingsCryptoKeysCryptoKeyVersions.php",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "PHP",
"bytes": "55414116"
},
{
"name": "Python",
"bytes": "427325"
},
{
"name": "Shell",
"bytes": "787"
}
],
"symlink_target": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.